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
use seed::{prelude::*, *};
use std::borrow::Cow;
use std::fmt;
use std::rc::Rc;

pub struct FormGroup<'a, Ms: 'static> {
    id: Cow<'a, str>,
    label: Option<Cow<'a, str>>,
    value: Option<Cow<'a, str>>,
    input_event: Option<Rc<dyn Fn(String) -> Ms>>,
    input_type: InputType,
    is_invalid: bool,
    invalid_feedback: Option<Cow<'a, str>>,
    is_warning: bool,
    warning_feedback: Option<Cow<'a, str>>,
    help_text: Vec<Node<Ms>>,
    group_attrs: Attrs,
    input_attrs: Attrs,
}

impl<'a, Ms> FormGroup<'a, Ms> {
    pub fn new(id: impl Into<Cow<'a, str>>) -> Self {
        Self {
            id: id.into(),
            label: None,
            value: None,
            input_event: None,
            input_type: InputType::Text,
            is_invalid: false,
            invalid_feedback: None,
            is_warning: false,
            warning_feedback: None,
            help_text: Vec::new(),
            group_attrs: Attrs::empty(),
            input_attrs: Attrs::empty(),
        }
    }

    pub fn label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn value(mut self, value: impl Into<Cow<'a, str>>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn on_input(mut self, input_event: impl Fn(String) -> Ms + Clone + 'static) -> Self {
        self.input_event = Some(Rc::new(input_event));
        self
    }

    pub fn text(mut self) -> Self {
        self.input_type = InputType::Text;
        self
    }
    pub fn number(mut self) -> Self {
        self.input_type = InputType::Number;
        self
    }
    pub fn password(mut self) -> Self {
        self.input_type = InputType::Password;
        self
    }
    pub fn textarea(mut self) -> Self {
        self.input_type = InputType::Textarea;
        self
    }
    pub fn checkbox(mut self) -> Self {
        self.input_type = InputType::Checkbox;
        self
    }

    pub fn select(mut self, options: Vec<(String, String)>, include_none_option: bool) -> Self {
        self.input_type = InputType::Select {
            options,
            include_none_option,
        };
        self
    }

    pub fn invalid(mut self, is_invalid: bool) -> Self {
        self.is_invalid = is_invalid;
        self
    }

    pub fn invalid_feedback(mut self, invalid_feedback: Option<impl Into<Cow<'a, str>>>) -> Self {
        self.invalid_feedback = invalid_feedback.map(|s| s.into());
        self
    }

    pub fn warning(mut self, is_warning: bool) -> Self {
        self.is_warning = is_warning;
        self
    }

    pub fn warning_feedback(mut self, warning_feedback: Option<impl Into<Cow<'a, str>>>) -> Self {
        self.warning_feedback = warning_feedback.map(|s| s.into());
        self
    }

    pub fn help_text(mut self, help_text: impl Into<Cow<'static, str>>) -> Self {
        self.help_text = Node::new_text(help_text).into_nodes();
        self
    }
    pub fn help_nodes(mut self, help_nodes: impl IntoNodes<Ms>) -> Self {
        self.help_text = help_nodes.into_nodes();
        self
    }

    pub fn group_attrs(mut self, attrs: Attrs) -> Self {
        self.group_attrs.merge(attrs);
        self
    }

    pub fn input_attrs(mut self, attrs: Attrs) -> Self {
        self.input_attrs.merge(attrs);
        self
    }

    pub fn view(self) -> Node<Ms> {
        if self.input_type == InputType::Checkbox {
            self.view_checkbox()
        } else {
            self.view_textfield()
        }
    }

    fn view_checkbox(self) -> Node<Ms> {
        let is_checked = self
            .value
            .as_ref()
            .map(|value| value == "true")
            .unwrap_or(false);
        let click_event_text = if is_checked {
            "false".to_string()
        } else {
            "true".to_string()
        };
        div![
            C!["form-group form-check"],
            &self.group_attrs,
            input![
                C!["form-check-input", IF!(self.is_invalid => "is-invalid")],
                &self.input_attrs,
                id![&self.id],
                attrs![
                    At::Type => "checkbox",
                    At::Value => "true",
                    At::Checked => is_checked.as_at_value()
                ],
                self.input_event.clone().map(|input_event| {
                    input_ev(Ev::Input, move |_event| input_event(click_event_text))
                })
            ],
            self.label.as_ref().map(|label| {
                label![
                    C!["form-check-label"],
                    attrs![
                        At::For => self.id
                    ],
                    label
                ]
            }),
            if !self.help_text.is_empty() {
                small![C!["form-text text-muted"], &self.help_text]
            } else {
                empty![]
            },
            self.invalid_feedback
                .as_ref()
                .filter(|_| self.is_invalid)
                .map(|err| div![C!["invalid-feedback"], err]),
            self.warning_feedback
                .as_ref()
                .filter(|_| self.is_warning)
                .map(|err| small![C!["form-text text-warning"], err])
        ]
    }

    fn view_textfield(self) -> Node<Ms> {
        div![
            C!["form-group"],
            &self.group_attrs,
            self.label.as_ref().map(|label| {
                label![
                    attrs![
                        At::For => self.id
                    ],
                    label
                ]
            }),
            match &self.input_type {
                InputType::Text | InputType::Number | InputType::Password => input![
                    C!["form-control", IF!(self.is_invalid => "is-invalid")],
                    &self.input_attrs,
                    id![&self.id],
                    attrs![
                        At::Type => &self.input_type,
                    ],
                    self.value.as_ref().map(|value| attrs![At::Value => value]),
                    self.input_event.clone().map(|input_event| {
                        input_ev(Ev::Input, move |event| input_event(event))
                    })
                ],
                InputType::Textarea => textarea![
                    C!["form-control", IF!(self.is_invalid => "is-invalid")],
                    &self.input_attrs,
                    id![&self.id],
                    self.value.as_ref().map(
                        |value| attrs![At::Value => value, At::Rows => value.split('\n').count(), At::Wrap => "off"]
                    ),
                    self.input_event.clone().map(|input_event| {
                        input_ev(Ev::Input, move |event| input_event(event))
                    })
                ],
                InputType::Select { options, include_none_option } => select![
                    C!["custom-select", IF!(self.is_invalid => "is-invalid")],
                    if *include_none_option { option![
                        attrs! {
                            At::Value => "",
                            At::Selected => self.value.is_none().as_at_value()
                        }
                    ] } else { empty![] },
                    options.iter().map(|(key, display)| {
                        option![
                            attrs! {
                                At::Value => &key,
                                At::Selected => self.value.as_ref().map(|value| value == key).unwrap_or(false).as_at_value()
                            },
                            &display
                        ]
                    }),
                    self.input_event.clone().map(|input_event| {
                        input_ev(Ev::Input, move |event| input_event(event))
                    })
                ],
                InputType::Checkbox => empty![],
            },
            if !self.help_text.is_empty() { small![C!["form-text text-muted"], &self.help_text] } else { empty![] },
            self.invalid_feedback
                .as_ref()
                .filter(|_| self.is_invalid)
                .map(|err| div![C!["invalid-feedback"], err]),
            self.warning_feedback
                .as_ref()
                .filter(|_| self.is_warning)
                .map(|err| small![C!["form-text text-warning"], err])
        ]
    }
}

impl<Ms> UpdateEl<Ms> for FormGroup<'_, Ms> {
    fn update_el(self, el: &mut El<Ms>) {
        self.view().update_el(el)
    }
}

#[derive(PartialEq)]
enum InputType {
    Text,
    Number,
    Password,
    Textarea,
    Checkbox,
    Select {
        options: Vec<(String, String)>,
        include_none_option: bool,
    },
}

impl fmt::Display for InputType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Self::Text => write!(f, "text"),
            Self::Number => write!(f, "number"),
            Self::Password => write!(f, "password"),
            Self::Textarea => write!(f, "textarea"),
            Self::Checkbox => write!(f, "checkbox"),
            Self::Select { .. } => write!(f, "select"),
        }
    }
}