input-rs 0.2.6

🔤 A highly customizable input component for WASM frameworks like Yew, Dioxus, and Leptos.
Documentation
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use crate::countries::COUNTRY_CODES;
use dioxus::prelude::*;

/// Props for a custom input component.
/// This struct includes all possible attributes for an HTML `<input>` element.
/// See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) for more details.
#[derive(Props, Clone)]
pub struct InputProps {
    /// The type of the input, e.g., "text", "password", etc.
    #[props(default = "text")]
    pub r#type: &'static str,

    /// The label to be displayed for the input field.
    #[props(default = "")]
    pub label: &'static str,

    /// The name of the input field, used for form submission and accessibility.
    #[props(default = "")]
    pub name: &'static str,

    /// Indicates whether the input is required or not.
    #[props(default = false)]
    pub required: bool,

    /// The error message to display when there is a validation error.
    #[props(default = "")]
    pub error_message: &'static str,

    /// The CSS class to be applied to all inner elements.
    #[props(default = "")]
    pub input_class: &'static str,

    /// The CSS class to be applied to the inner input element and icon.
    #[props(default = "")]
    pub field_class: &'static str,

    /// The CSS class to be applied to the label for the input element.
    #[props(default = "")]
    pub label_class: &'static str,

    /// The CSS class to be applied to the input element.
    #[props(default = "")]
    pub class: &'static str,

    /// The CSS class to be applied to the error div element.
    #[props(default = "")]
    pub error_class: &'static str,

    /// The CSS class to be applied to the icon element.
    #[props(default = "")]
    pub icon_class: &'static str,

    /// The state handle for managing the value of the input.
    pub handle: Signal<String>,

    /// The state handle for managing the validity state of the input.
    pub valid_handle: Signal<bool>,

    /// A callback function to validate the input value. It takes a `String` as input and returns a `bool`.
    pub validate_function: fn(String) -> bool,

    /// The icon when the password is visible. Assuming fontawesome icons are used by default.
    #[props(
        default = "cursor-pointer right-4 top-1 text-2xl text-gray-600 toggle-button fa fa-eye"
    )]
    pub eye_active: &'static str,

    /// The icon when the password is not visible. Assuming fontawesome icons are used by default.
    #[props(
        default = "cursor-pointer right-4 top-1 text-2xl text-gray-600 toggle-button fa fa-eye-slash"
    )]
    pub eye_disabled: &'static str,

    // Accessibility and SEO-related attributes:
    /// The ID attribute of the input element.
    #[props(default = "")]
    pub id: &'static str,

    /// The placeholder text to be displayed in the input element.
    #[props(default = "")]
    pub placeholder: &'static str,

    /// The aria-label attribute for screen readers, providing a label for accessibility.
    #[props(default = "")]
    pub aria_label: &'static str,

    /// The aria-required attribute for screen readers, indicating whether the input is required.
    #[props(default = "true")]
    pub aria_required: &'static str,

    /// The aria-invalid attribute for screen readers, indicating whether the input value is invalid.
    #[props(default = "true")]
    pub aria_invalid: &'static str,

    /// The aria-describedby attribute for screen readers, describing the input element's error message.
    #[props(default = "")]
    pub aria_describedby: &'static str,

    // Newly added attributes from MDN:
    /// Hint for expected file type in file upload controls.
    #[props(default = "")]
    pub accept: &'static str,

    /// The alternative text for `<input type="image">`. Required for accessibility.
    #[props(default = "")]
    pub alt: &'static str,

    /// Controls automatic capitalization in inputted text.
    #[props(default = "")]
    pub autocapitalize: &'static str,

    /// Hint for the browser's autofill feature.
    #[props(default = "")]
    pub autocomplete: &'static str,

    /// Media capture input method in file upload controls.
    #[props(default = "")]
    pub capture: &'static str,

    /// Whether the control is checked (for checkboxes or radio buttons).
    #[props(default = false)]
    pub checked: bool,

    /// Name of the form field to use for sending the element's directionality in form submission.
    #[props(default = "")]
    pub dirname: &'static str,

    /// Whether the form control is disabled.
    #[props(default = false)]
    pub disabled: bool,

    /// Associates the input with a specific form element.
    #[props(default = "")]
    pub form: &'static str,

    /// URL to use for form submission (for `<input type="image" | "submit">`).
    #[props(default = "")]
    pub formaction: &'static str,

    /// Form data set encoding type for submission (for `<input type="image" | "submit">`).
    #[props(default = "")]
    pub formenctype: &'static str,

    /// HTTP method to use for form submission (for `<input type="image" | "submit">`).
    #[props(default = "")]
    pub formmethod: &'static str,

    /// Bypass form validation for submission (for `<input type="image" | "submit">`).
    #[props(default = false)]
    pub formnovalidate: bool,

    /// Browsing context for form submission (for `<input type="image" | "submit">`).
    #[props(default = "")]
    pub formtarget: &'static str,

    /// Same as the `height` attribute for `<img>` elements.
    #[props(default = None)]
    pub height: Option<u32>,

    /// ID of the `<datalist>` element to use for autocomplete suggestions.
    #[props(default = "")]
    pub list: &'static str,

    /// The maximum value for date, number, range, etc.
    #[props(default = "")]
    pub max: &'static str,

    /// Maximum length of the input value (in characters).
    #[props(default = None)]
    pub maxlength: Option<usize>,

    /// The minimum value for date, number, range, etc.
    #[props(default = "")]
    pub min: &'static str,

    /// Minimum length of the input value (in characters).
    #[props(default = None)]
    pub minlength: Option<usize>,

    /// Boolean indicating whether multiple values are allowed (for file inputs, emails, etc.).
    #[props(default = false)]
    pub multiple: bool,

    /// Regex pattern the value must match to be valid.
    #[props(default = ".*")]
    pub pattern: &'static str,

    /// Boolean indicating whether the input is read-only.
    #[props(default = false)]
    pub readonly: bool,

    /// Size of the input field (e.g., character width).
    #[props(default = None)]
    pub size: Option<u32>,

    /// Address of the image resource for `<input type="image">`.
    #[props(default = "")]
    pub src: &'static str,

    /// Incremental values that are valid for the input.
    #[props(default = "")]
    pub step: &'static str,

    /// The value of the control (used for two-way data binding).
    #[props(default = "")]
    pub value: &'static str,

    /// Same as the `width` attribute for `<img>` elements.
    #[props(default = None)]
    pub width: Option<u32>,
}

impl PartialEq for InputProps {
    fn eq(&self, other: &Self) -> bool {
        self.r#type == other.r#type
            && self.label == other.label
            && self.name == other.name
            && self.required == other.required
            && self.error_message == other.error_message
            && self.input_class == other.input_class
            && self.field_class == other.field_class
            && self.label_class == other.label_class
            && self.class == other.class
            && self.error_class == other.error_class
            && self.icon_class == other.icon_class
            && self.handle == other.handle
            && self.valid_handle == other.valid_handle
            && std::ptr::fn_addr_eq(self.validate_function, other.validate_function)
            && self.eye_active == other.eye_active
            && self.eye_disabled == other.eye_disabled
            && self.id == other.id
            && self.placeholder == other.placeholder
            && self.aria_label == other.aria_label
            && self.aria_required == other.aria_required
            && self.aria_invalid == other.aria_invalid
            && self.aria_describedby == other.aria_describedby
            && self.accept == other.accept
            && self.alt == other.alt
            && self.autocapitalize == other.autocapitalize
            && self.autocomplete == other.autocomplete
            && self.capture == other.capture
            && self.checked == other.checked
            && self.dirname == other.dirname
            && self.disabled == other.disabled
            && self.form == other.form
            && self.formaction == other.formaction
            && self.formenctype == other.formenctype
            && self.formmethod == other.formmethod
            && self.formnovalidate == other.formnovalidate
            && self.formtarget == other.formtarget
            && self.height == other.height
            && self.list == other.list
            && self.max == other.max
            && self.maxlength == other.maxlength
            && self.min == other.min
            && self.minlength == other.minlength
            && self.multiple == other.multiple
            && self.pattern == other.pattern
            && self.readonly == other.readonly
            && self.size == other.size
            && self.src == other.src
            && self.step == other.step
            && self.value == other.value
            && self.width == other.width
    }
}

/// A custom input component that handles user input and validation.
///
/// # Arguments
/// * `props` - The properties of the component.
///   - `valid_handle` - A state hook to track the validity of the input.
///   - `aria_invalid` - A string representing the 'aria-invalid' attribute value for accessibility. Defaults to "true".
///   - `aria_required` - A string representing the 'aria-required' attribute value for accessibility. Defaults to "true".
///   - `r#type` - The type of the input element. Defaults to "text".
///   - `handle` - A state hook to set the value of the input.
///   - `validate_function` - A function to validate the input value.
///
/// # Returns
/// (Element): A Dioxus element representation of the input component.
///
/// # Examples
/// ```rust
/// use regex::Regex;
/// use input_rs::dioxus::Input;
/// use dioxus::prelude::*;
///
/// #[derive(Debug, Default, Clone)]
/// struct LoginUserSchema {
///     email: String,
///     password: String,
/// }
///
/// fn LoginFormOne() -> Element {
///     let error_handle = use_signal(|| String::new());
///     let email_valid_handle = use_signal(|| true);
///     let password_valid_handle = use_signal(|| true);
///
///     let email_handle = use_signal(|| String::new());
///     let password_handle = use_signal(|| String::new());
///
///     let validate_email = |email: String| {
///         let pattern = Regex::new(r"^[^ ]+@[^ ]+\.[a-z]{2,3}$").unwrap();
///         pattern.is_match(&email)
///     };
///     
///     let validate_password = |password: String| {
///         !password.is_empty()
///     };
///
///     let onsubmit = {
///         move |e: FormEvent| {
///             e.stop_propagation();
///             // Custom logic for your endpoint goes here.
///         }
///     };
///
///     rsx! {
///         div {
///             class: "form-one-content",
///             role: "main",
///             aria_label: "Sign In Form",
///             div {
///                 class: "text",
///                 h2 { "Sign In" }
///                 if !error_handle().is_empty() {
///                     div { class: "error", "{error_handle}" }
///                 }
///             }
///             form {
///                 onsubmit: onsubmit,
///                 aria_label: "Sign In Form",
///                 Input {
///                     r#type: "text",
///                     handle: email_handle,
///                     name: "email",
///                     placeholder: "Email",
///                     icon_class: "fas fa-user",
///                     error_message: "Enter a valid email address",
///                     field_class: "form-one-field",
///                     error_class: "error-txt",
///                     required: true,
///                     valid_handle: email_valid_handle,
///                     validate_function: validate_email,
///                 }
///                 Input {
///                     r#type: "password",
///                     handle: password_handle,
///                     name: "password",
///                     placeholder: "Password",
///                     icon_class: "fas fa-lock",
///                     error_message: "Password can't be blank!",
///                     field_class: "form-one-field",
///                     error_class: "error-txt",
///                     required: true,
///                     valid_handle: password_valid_handle,
///                     validate_function: validate_password,
///                     eye_active: "fa fa-eye",
///                     eye_disabled: "fa fa-eye-slash",
///                 }
///                 div {
///                     class: "form-one-forgot-pass",
///                     a {
///                         href: "#",
///                         aria_label: "Forgot Password?",
///                         "Forgot Password?"
///                     }
///                 }
///                 button {
///                     r#type: "submit",
///                     "Sign in"
///                 }
///                 div {
///                     class: "sign-up",
///                     "Not a member? ",
///                     a {
///                         href: "#",
///                         aria_label: "Sign up now",
///                         "Sign up now"
///                     }
///                 }
///             }
///         }
///     }
/// }
/// ```
#[component]
pub fn Input(mut props: InputProps) -> Element {
    let mut is_eye_active = use_signal(|| false);
    let password_type = if is_eye_active() { "text" } else { "password" };
    let mut country = use_signal(String::default);

    let onchange = {
        move |e: Event<FormData>| {
            let value = e.value();
            props.handle.set(value.clone());
            props.valid_handle.set((props.validate_function)(value));
        }
    };

    let on_select_change = {
        move |e: Event<FormData>| {
            let value = e.value();
            country.set(value.clone());
            props.handle.set(value);
        }
    };

    let on_phone_number_input = {
        move |e: Event<FormData>| {
            let input_value = e.value();
            for (code, _, _, _, _, _) in &COUNTRY_CODES {
                if code.starts_with(&input_value) {
                    country.set(input_value);
                    break;
                }
            }
            // Filter out non-numeric characters
            let numeric_value: String = e.value().chars().filter(|c| c.is_numeric()).collect();
            props.handle.set('+'.to_string() + &numeric_value);
        }
    };

    let toggle_eye_icon = {
        move |_| {
            is_eye_active.set(!is_eye_active());
        }
    };

    let input_field = match props.r#type {
        "password" => rsx! {
            input {
                r#type: "{password_type}",
                class: "{props.input_class}",
                id: "{props.id}",
                name: "{props.name}",
                value: "{props.handle}",
                placeholder: "{props.placeholder}",
                aria_label: "{props.aria_label}",
                aria_required: "{props.aria_required}",
                aria_invalid: "{props.aria_invalid}",
                aria_describedby: "{props.aria_describedby}",
                oninput: onchange,
                required: props.required,
                autocomplete: props.autocomplete,
                autocapitalize: props.autocapitalize,
                readonly: "{props.readonly}",
                disabled: "{props.disabled}",
                minlength: props.minlength.map(|v| v.to_string()).unwrap_or_default(),
                maxlength: props.maxlength.map(|v| v.to_string()).unwrap_or_default(),
                pattern: "{props.pattern}",
                size: props.size.map(|v| v.to_string()).unwrap_or_default(),
            }
            span {
                class: if is_eye_active() { props.eye_active } else { props.eye_disabled },
                onclick: toggle_eye_icon
            }
        },
        "tel" => rsx! {
            select {
                style: "max-width: 55px; font-size: 14px; padding: 10px;",
                onchange: on_select_change,
                { COUNTRY_CODES.iter().map(|(code, emoji, _, name, _, _)| rsx! {
                    option { value: "{code}", selected: *code == country(), "{emoji} {name} ({code})" }
                })}
            }
            input {
                r#type: "tel",
                class: "{props.input_class}",
                id: "{props.id}",
                name: "{props.name}",
                value: "{props.handle}",
                placeholder: "{props.placeholder}",
                aria_label: "{props.aria_label}",
                aria_required: "{props.aria_required}",
                aria_invalid: "{props.aria_invalid}",
                aria_describedby: "{props.aria_describedby}",
                oninput: on_phone_number_input,
                required: props.required,
                autocomplete: props.autocomplete,
                autocapitalize: props.autocapitalize,
                readonly: "{props.readonly}",
                disabled: "{props.disabled}",
                minlength: props.minlength.map(|v| v.to_string()).unwrap_or_default(),
                maxlength: props.maxlength.map(|v| v.to_string()).unwrap_or_default(),
                pattern: "{props.pattern}",
                size: props.size.map(|v| v.to_string()).unwrap_or_default(),
            }
        },
        "textarea" => rsx! {
            textarea {
                class: "{props.input_class}",
                id: "{props.id}",
                name: "{props.name}",
                value: "{props.handle}",
                placeholder: "{props.placeholder}",
                aria_label: "{props.aria_label}",
                aria_required: "{props.aria_required}",
                aria_invalid: "{props.aria_invalid}",
                aria_describedby: "{props.aria_describedby}",
                oninput: onchange,
                required: props.required,
                readonly: "{props.readonly}",
                disabled: "{props.disabled}",
                minlength: props.minlength.map(|v| v.to_string()).unwrap_or_default(),
                maxlength: props.maxlength.map(|v| v.to_string()).unwrap_or_default(),
            }
        },
        _ => rsx! {
            input {
                r#type: "{props.r#type}",
                class: "{props.input_class}",
                id: "{props.id}",
                name: "{props.name}",
                value: "{props.handle}",
                placeholder: "{props.placeholder}",
                aria_label: "{props.aria_label}",
                aria_required: "{props.aria_required}",
                aria_invalid: "{props.aria_invalid}",
                aria_describedby: "{props.aria_describedby}",
                oninput: onchange,
                required: props.required,
                autocomplete: props.autocomplete,
                autocapitalize: props.autocapitalize,
                readonly: "{props.readonly}",
                disabled: "{props.disabled}",
                minlength: props.minlength.map(|v| v.to_string()).unwrap_or_default(),
                maxlength: props.maxlength.map(|v| v.to_string()).unwrap_or_default(),
                pattern: "{props.pattern}",
                size: props.size.map(|v| v.to_string()).unwrap_or_default(),
            }
        },
    };

    rsx! {
        div {
            class: "{props.class}",
            label {
                class: "{props.label_class}",
                r#for: "{props.id}",
                "{props.label}"
            }
            div {
                class: "{props.field_class}",
                {input_field}
                span {class: "{props.icon_class}" }
            }
            if !(props.valid_handle)() {
                div {
                    class: "{props.error_class}",
                    id: "{props.aria_describedby}",
                    "{props.error_message}"
                }
            }
        }
    }
}