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
//! Form controls
mod area;
mod checkbox;
mod group;
mod input;
mod radio;
mod section;
mod select;
mod validation;

pub use area::*;
pub use checkbox::*;
pub use group::*;
pub use input::*;
pub use radio::*;
pub use section::*;
pub use select::*;
use std::collections::BTreeMap;
pub use validation::*;

use crate::prelude::{Alert, AlertType, AsClasses, Button, ExtendClasses, WithBreakpoints};
use yew::prelude::*;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FormHorizontal;

impl AsClasses for FormHorizontal {
    fn extend_classes(&self, classes: &mut Classes) {
        classes.push("pf-m-horizontal")
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct FormAlert {
    pub r#type: AlertType,
    pub title: String,
    pub children: Html,
}

//
// Form
//

/// Properties for [`Form`]
#[derive(Clone, PartialEq, Properties)]
pub struct FormProperties {
    #[prop_or_default]
    pub id: Option<String>,

    #[prop_or_default]
    pub horizontal: WithBreakpoints<FormHorizontal>,

    #[prop_or_default]
    pub action: Option<String>,
    #[prop_or_default]
    pub method: Option<String>,

    #[prop_or_default]
    pub limit_width: bool,

    #[prop_or_default]
    pub children: Html,

    #[prop_or_default]
    pub alert: Option<FormAlert>,

    /// Reports the overall validation state
    #[prop_or_default]
    pub onvalidated: Callback<InputState>,

    #[prop_or_default]
    pub validation_warning_title: Option<String>,
    #[prop_or_default]
    pub validation_error_title: Option<String>,

    #[prop_or_default]
    pub onsubmit: Callback<SubmitEvent>,
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct ValidationState {
    results: BTreeMap<String, ValidationResult>,
    state: InputState,
}

impl ValidationState {
    fn to_state(&self) -> InputState {
        let mut current = InputState::Default;
        for r in self.results.values() {
            if r.state > current {
                current = r.state;
            }
            if current == InputState::Error {
                break;
            }
        }
        current
    }

    fn push_state(&mut self, state: GroupValidationResult) -> bool {
        match state.1 {
            Some(result) => {
                self.results.insert(state.0, result);
            }
            None => {
                self.results.remove(&state.0);
            }
        }

        // update with diff

        let state = self.to_state();
        if self.state != state {
            self.state = state;
            true
        } else {
            false
        }
    }
}

#[derive(Clone, Default, PartialEq)]
pub struct ValidationFormContext {
    callback: Callback<GroupValidationResult>,
    state: InputState,
}

impl ValidationFormContext {
    pub fn new(callback: Callback<GroupValidationResult>, state: InputState) -> Self {
        Self { callback, state }
    }

    pub fn is_error(&self) -> bool {
        matches!(self.state, InputState::Error)
    }

    pub fn push_state(&self, state: GroupValidationResult) {
        self.callback.emit(state);
    }

    pub fn clear_state(&self, id: String) {
        self.callback.emit(GroupValidationResult(id, None));
    }
}

pub struct GroupValidationResult(pub String, pub Option<ValidationResult>);

/// The Form component.
///
/// > A **form** is a group of elements used to collect information from a user in a variety of contexts including in a modal, in a wizard, or on a page. Use cases for forms include tasks reliant on user-inputted information for completion like logging in, registering, configuring settings, or completing surveys.
///
/// See: <https://www.patternfly.org/components/form>
///
/// ## Properties
///
/// Defined by [`FormProperties`].
pub struct Form {
    validation: ValidationState,
}

#[doc(hidden)]
pub enum FormMsg {
    GroupValidationChanged(GroupValidationResult),
}

impl Component for Form {
    type Message = FormMsg;
    type Properties = FormProperties;

    fn create(_ctx: &Context<Self>) -> Self {
        Self {
            validation: Default::default(),
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            FormMsg::GroupValidationChanged(state) => {
                let changed = self.validation.push_state(state);
                if changed {
                    ctx.props().onvalidated.emit(self.validation.state);
                }
                changed
            }
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let mut classes = Classes::from("pf-v5-c-form");

        classes.extend_from(&ctx.props().horizontal);

        if ctx.props().limit_width {
            classes.push("pf-m-limit-width");
        }

        let alert = &ctx.props().alert;
        let validation_alert = Self::make_alert(
            self.validation.state,
            (
                ctx.props()
                    .validation_warning_title
                    .as_deref()
                    .unwrap_or("The form contains fields with warnings."),
                &html!(),
            ),
            (
                ctx.props()
                    .validation_error_title
                    .as_deref()
                    .unwrap_or("The form contains fields with errors."),
                &html!(),
            ),
        );

        // reduce by severity

        let alert = match (alert, &validation_alert) {
            (None, None) => None,
            (Some(alert), None) | (None, Some(alert)) => Some(alert),
            (Some(props), Some(validation)) if validation.r#type > props.r#type => Some(validation),
            (Some(props), Some(_)) => Some(props),
        };

        let validation_context = ValidationFormContext::new(
            ctx.link().callback(FormMsg::GroupValidationChanged),
            self.validation.state,
        );

        html! (
            <ContextProvider<ValidationFormContext> context={validation_context} >
                <form
                    novalidate=true
                    class={classes}
                    id={ctx.props().id.clone()}
                    action={ctx.props().action.clone()}
                    method={ctx.props().method.clone()}
                    onsubmit={ctx.props().onsubmit.clone()}
                >

                    if let Some(alert) = alert {
                        <div class="pf-v5-c-form__alert">
                            <Alert
                                inline=true
                                r#type={alert.r#type}
                                title={alert.title.clone()}
                                >
                                { alert.children.clone() }
                            </Alert>
                        </div>
                    }

                    { ctx.props().children.clone() }

                </form>
            </ContextProvider<ValidationFormContext>>
        )
    }
}

impl Form {
    fn make_alert(
        state: InputState,
        warning: (&str, &Html),
        error: (&str, &Html),
    ) -> Option<FormAlert> {
        match state {
            InputState::Default | InputState::Success => None,
            InputState::Warning => Some(FormAlert {
                r#type: AlertType::Warning,
                title: warning.0.to_string(),
                children: warning.1.clone(),
            }),
            InputState::Error => Some(FormAlert {
                r#type: AlertType::Danger,
                title: error.0.to_string(),
                children: error.1.clone(),
            }),
        }
    }
}

//
// Action group
//

/// Properties for [`ActionGroup`]
#[derive(Clone, PartialEq, Properties)]
pub struct ActionGroupProperties {
    pub children: ChildrenWithProps<Button>,
}

#[function_component(ActionGroup)]
pub fn action_group(props: &ActionGroupProperties) -> Html {
    html! {
        <div class="pf-v5-c-form__group pf-m-action">
            <div class="pf-v5-c-form__actions">
                { for props.children.iter() }
            </div>
        </div>
    }
}