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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use crate::prelude::*;
use std::{marker::PhantomData, rc::Rc};
use uuid::Uuid;
use yew::{
    prelude::*,
    virtual_dom::{VChild, VNode},
};

// form group

/// Properties for [`FormGroup`]
#[derive(Clone, PartialEq, Properties)]
pub struct FormGroupProperties {
    pub children: Html,
    #[prop_or_default]
    pub label: String,
    #[prop_or_default]
    pub required: bool,
    #[prop_or_default]
    pub label_icon: LabelIcon,
    #[prop_or_default]
    pub helper_text: Option<FormHelperText>,
}

#[derive(Clone, Default, PartialEq)]
pub enum LabelIcon {
    /// No label icon
    #[default]
    None,
    /// Help
    Help(VChild<PopoverBody>),
    /// Any children
    Children(Html),
}

/// Helper text information for a [`FormGroup`]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FormHelperText {
    pub input_state: InputState,
    pub custom_icon: Option<Icon>,
    pub no_icon: bool,
    pub is_dynamic: bool,
    pub message: String,
}

impl From<&FormHelperText> for VNode {
    fn from(text: &FormHelperText) -> Self {
        let mut classes = Classes::from("pf-v5-c-helper-text__item");

        classes.extend(text.input_state.as_classes());

        if text.is_dynamic {
            classes.push("pf-m-dynamic");
        }

        html!(
            <div class={classes}>
                if !text.no_icon {
                    <span class="pf-v5-c-helper-text__item-icon">
                        { text.custom_icon.unwrap_or_else(|| text.input_state.icon() )}
                    </span>
                }
                <span class="pf-v5-c-helper-text__item-text"> { &text.message } </span>
            </div>
        )
    }
}

impl From<&str> for FormHelperText {
    fn from(text: &str) -> Self {
        FormHelperText {
            input_state: Default::default(),
            custom_icon: None,
            no_icon: true,
            is_dynamic: false,
            message: text.into(),
        }
    }
}

impl From<(String, InputState)> for FormHelperText {
    fn from((message, input_state): (String, InputState)) -> Self {
        Self {
            input_state,
            custom_icon: None,
            no_icon: false,
            is_dynamic: false,
            message,
        }
    }
}

impl From<(&str, InputState)> for FormHelperText {
    fn from((message, input_state): (&str, InputState)) -> Self {
        Self {
            input_state,
            custom_icon: None,
            no_icon: false,
            is_dynamic: false,
            message: message.to_string(),
        }
    }
}

/// A group of components building a field in a [`Form`](crate::prelude::Form)
///
/// ## Properties
///
/// Defined by [`FormGroupProperties`].
pub struct FormGroup {}

impl Component for FormGroup {
    type Message = ();
    type Properties = FormGroupProperties;

    fn create(_: &Context<Self>) -> Self {
        Self {}
    }

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

        html! (
            <div class={classes}>

                if !ctx.props().label.is_empty() {
                    <div class="pf-v5-c-form__group-label">
                        <label class="pf-v5-c-form__label">

                            <span class="pf-v5-c-form__label-text">{&ctx.props().label}</span>

                            if ctx.props().required {
                                {" "}
                                <span class="pf-v5-c-form__label-required" aria-hidden="true">{"*"}</span>
                            }
                        </label>
                        {
                            match &ctx.props().label_icon  {
                                LabelIcon::None => html!(),
                                LabelIcon::Help(popover) => html!(
                                    <span
                                        class="pf-v5-c-form__group-label-help"
                                        role="button"
                                        type="button"
                                        tabindex=0
                                    >
                                        {" "}
                                        <Popover target={html!(Icon::QuestionCircle)} body={popover.clone()} />
                                    </span>
                                ),
                                LabelIcon::Children(children) => children.clone(),
                            }
                        }
                    </div>
                }

                <div class="pf-v5-c-form__group-control">
                    { ctx.props().children.clone() }
                    if let Some(text) = &ctx.props().helper_text {
                        { FormGroupHelpText(text) }
                    }
                </div>
            </div>
        )
    }
}

pub struct FormGroupHelpText<'a>(pub &'a FormHelperText);

impl<'a> FormGroupHelpText<'a> {}

impl<'a> From<FormGroupHelpText<'a>> for VNode {
    fn from(text: FormGroupHelpText<'a>) -> Self {
        let mut classes = classes!("pf-v5-c-helper-text__item");

        classes.extend(text.0.input_state.as_classes());

        let icon = match text.0.no_icon {
            true => None,
            false => Some(
                text.0
                    .custom_icon
                    .unwrap_or_else(|| text.0.input_state.icon()),
            ),
        };

        html!(
            <div
                class="pf-v5-c-form__helper-text"
                aria-live="polite"
            >
                <div class="pf-v5-c-helper-text">
                    <div
                        class={classes}
                        id="form-help-text-info-helper"
                    >
                        if let Some(icon) = icon {
                            <span class="pf-v5-c-helper-text__item-icon">
                                { icon }
                            </span>
                        }
                        <span class="pf-v5-c-helper-text__item-text">
                            { &text.0.message }
                        </span>
                    </div>
                </div>
            </div>
        )
    }
}

// with validation

/// Properties for [`FormGroupValidated`]
#[derive(Clone, Properties)]
pub struct FormGroupValidatedProperties<C>
where
    C: BaseComponent + ValidatingComponent,
{
    #[prop_or_default]
    pub children: ChildrenWithProps<C>,
    #[prop_or_default]
    pub label: String,
    #[prop_or_default]
    pub label_icon: LabelIcon,
    #[prop_or_default]
    pub required: bool,
    pub validator: Validator<C::Value, ValidationResult>,

    #[prop_or_default]
    pub onvalidated: Callback<ValidationResult>,
}

#[doc(hidden)]
pub enum FormGroupValidatedMsg<C>
where
    C: ValidatingComponent,
{
    Validate(ValidationContext<C::Value>),
}

impl<C> PartialEq for FormGroupValidatedProperties<C>
where
    C: BaseComponent + ValidatingComponent,
{
    fn eq(&self, other: &Self) -> bool {
        self.required == other.required
            && self.label == other.label
            && self.children == other.children
    }
}

pub struct FormGroupValidated<C>
where
    C: BaseComponent,
{
    _marker: PhantomData<C>,

    id: String,
    state: Option<ValidationResult>,
}

impl<C> Component for FormGroupValidated<C>
where
    C: BaseComponent + ValidatingComponent,
    <C as BaseComponent>::Properties: ValidatingComponentProperties<C::Value> + Clone,
{
    type Message = FormGroupValidatedMsg<C>;
    type Properties = FormGroupValidatedProperties<C>;

    fn create(_: &Context<Self>) -> Self {
        Self {
            _marker: Default::default(),
            id: Uuid::new_v4().to_string(),
            state: None,
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Self::Message::Validate(value) => {
                let state = ctx.props().validator.run(value);
                if self.state != state {
                    self.state = state;
                    ctx.props()
                        .onvalidated
                        .emit(self.state.clone().unwrap_or_default());
                    if let Some((validation_ctx, _)) = ctx
                        .link()
                        .context::<ValidationFormContext>(Callback::noop())
                    {
                        validation_ctx
                            .push_state(GroupValidationResult(self.id.clone(), self.state.clone()));
                    }
                }
            }
        }
        true
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let onvalidate = ctx.link().callback(|v| FormGroupValidatedMsg::Validate(v));

        html!(
            <FormGroup
                label={ctx.props().label.clone()}
                label_icon={ctx.props().label_icon.clone()}
                required={ctx.props().required}
                helper_text={self.state.clone().and_then(|s|s.into())}
            >
                { for ctx.props().children.iter().map(|mut c|{
                    let props = Rc::make_mut(&mut c.props);
                    props.set_onvalidate(onvalidate.clone());
                    props.set_input_state(self.state.as_ref().map(|s|s.state).unwrap_or_default());
                    c
                })}
            </FormGroup>
        )
    }

    fn destroy(&mut self, ctx: &Context<Self>) {
        if let Some((ctx, _)) = ctx
            .link()
            .context::<ValidationFormContext>(Callback::noop())
        {
            ctx.clear_state(self.id.clone());
        }
    }
}