lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! `PhoneInput`, `CountryFlag`, and `PhoneNumber`, backed by the dependency-free phone engine.

use dioxus::prelude::*;

use super::phone_engine::{PhoneInputCountry, PhoneInputNumber};
use crate::class::compose;
use crate::form::ControlSize;
use crate::hooks::{use_controllable, use_unique_id};

fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
    attributes
        .iter()
        .rev()
        .find(|attribute| attribute.name == name)
        .and_then(|attribute| match &attribute.value {
            dioxus::core::AttributeValue::Text(text) => Some(text.clone()),
            _ => None,
        })
}

/// Mirrors the `value` attribute of the number input, a private copy of the numeric inputs'
/// `ValueMirror`.
///
/// Dioxus only writes an attribute that differs from the previous render, so when sanitizing
/// leaves the number unchanged (a rejected letter) the control would keep showing, and submit, the
/// raw text. After such an edit the mirror first renders the raw text the control already shows,
/// then the corrected value on the next pass, which always produces a write.
#[derive(Clone, Copy)]
struct ValueMirror {
    pending: Signal<Option<String>>,
}

fn use_value_mirror() -> ValueMirror {
    ValueMirror {
        pending: use_signal(|| None),
    }
}

impl ValueMirror {
    /// The `value` attribute to render this pass, given the corrected value.
    fn attribute(&self, corrected: &str) -> String {
        self.pending
            .read()
            .clone()
            .unwrap_or_else(|| corrected.to_string())
    }

    /// Records the text the control shows after a user edit and schedules the correction.
    fn record(&self, raw: String) {
        let mut pending = self.pending;

        pending.set(Some(raw));
        spawn(async move {
            pending.set(None);
        });
    }
}

/// The first two characters of a region code, uppercased: the text a flag shows without artwork.
fn region_text(region_code: &str) -> String {
    region_code
        .chars()
        .take(2)
        .collect::<String>()
        .to_uppercase()
}

/// Props for [`CountryFlag`].
#[derive(Props, Clone, PartialEq)]
pub struct CountryFlagProps {
    /// ISO 3166-1 alpha-2 region code, such as `US`.
    #[props(into)]
    pub region_code: String,
    /// Hides the flag from assistive technology when nearby text already names the country.
    #[props(default)]
    pub decorative: bool,
    /// Flag artwork URL. Without one the flag shows the region code, like lumen-react does for a
    /// region without bundled artwork.
    #[props(into)]
    pub source: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute. `aria_label` replaces the region-code name.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
}

/// A country flag: an image when `source` is set, otherwise the region code.
///
/// lumen-dioxus does not bundle flag artwork (about 300 KB for every region); pass `source`
/// with your own artwork, such as the MIT-licensed `flag-icons` set lumen-react embeds.
#[component]
pub fn CountryFlag(props: CountryFlagProps) -> Element {
    let label = attribute_text(&props.attributes, "aria-label")
        .unwrap_or_else(|| props.region_code.to_uppercase());
    let attributes: Vec<Attribute> = props
        .attributes
        .into_iter()
        .filter(|attribute| attribute.name != "aria-label")
        .collect();
    let class = compose([Some("ui-country-flag"), props.class.as_deref()]);
    let decorative = props.decorative;

    rsx! {
        span {
            aria_hidden: decorative.then_some("true"),
            aria_label: (!decorative).then_some(label),
            class,
            "data-slot": "country-flag",
            role: (!decorative).then_some("img"),
            ..attributes,
            if let Some(source) = props.source {
                img { alt: "", height: "18", src: source, width: "24" }
            } else {
                "{region_text(&props.region_code)}"
            }
        }
    }
}

/// Props for [`PhoneNumber`].
#[derive(Props, Clone, PartialEq)]
pub struct PhoneNumberProps {
    /// The number to show.
    pub value: PhoneInputNumber,
    /// Renders a `tel:` link when the number is valid.
    #[props(default)]
    pub link: bool,
    /// Flag artwork URL for the number's country.
    #[props(into)]
    pub flag_source: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes)]
    pub attributes: Vec<Attribute>,
}

/// A read-only phone number with its country flag: the E.164 value when valid, otherwise the
/// typed text, or an em dash when empty.
#[component]
pub fn PhoneNumber(props: PhoneNumberProps) -> Element {
    let class = compose([Some("ui-phone-number"), props.class.as_deref()]);
    let text = props.value.display();
    let text = if text.is_empty() {
        "—".to_string()
    } else {
        text
    };
    let title = props.value.country.display_name;
    let region = props.value.country.region_code;
    let href = props
        .value
        .e164
        .as_ref()
        .filter(|_| props.link && props.value.is_valid)
        .map(|e164| format!("tel:{e164}"));

    rsx! {
        if let Some(href) = href {
            a { class, href, title, ..props.attributes,
                CountryFlag { decorative: true, region_code: region, source: props.flag_source }
                span { "{text}" }
            }
        } else {
            span { class, title, ..props.attributes,
                CountryFlag { decorative: true, region_code: region, source: props.flag_source }
                span { "{text}" }
            }
        }
    }
}

/// The country `PhoneInput` starts with, like `resolveReactPhoneInputCountry`.
pub(crate) fn resolve_phone_country(
    countries: &[PhoneInputCountry],
    default_country: &str,
    value: Option<&PhoneInputNumber>,
) -> PhoneInputCountry {
    let requested = value.map(|number| number.country);

    countries
        .iter()
        .find(|country| {
            requested.is_some_and(|requested| requested.region_code == country.region_code)
        })
        .or_else(|| {
            countries.iter().find(|country| {
                requested.is_some_and(|requested| requested.calling_code == country.calling_code)
            })
        })
        .or_else(|| {
            countries
                .iter()
                .find(|country| country.region_code == default_country)
        })
        .or_else(|| {
            countries
                .iter()
                .find(|country| country.calling_code == default_country)
        })
        .or_else(|| countries.first())
        .copied()
        .or_else(|| PhoneInputCountry::find("US"))
        .unwrap_or(PhoneInputCountry {
            region_code: "US",
            calling_code: "+1",
            display_name: "United States",
        })
}

/// Resolves input against the offered countries, like `resolveReactPhoneInputValue`: an
/// international number for a country that is not offered is read as national input instead.
pub(crate) fn resolve_offered_phone_value(
    countries: &[PhoneInputCountry],
    country: PhoneInputCountry,
    input: &str,
) -> PhoneInputNumber {
    let detected = PhoneInputNumber::resolve(country, input);

    if countries
        .iter()
        .any(|candidate| candidate.region_code == detected.country.region_code)
    {
        return detected;
    }

    let national = detected
        .national_number
        .strip_prefix('+')
        .unwrap_or(&detected.national_number)
        .to_string();

    PhoneInputNumber::resolve(country, &national)
}

/// The value the picker shows when the selected country is no longer offered, like
/// `resolveOfferedPhoneValue`.
fn offered_phone_value(
    countries: &[PhoneInputCountry],
    default_country: &str,
    initial: PhoneInputCountry,
    source: &PhoneInputNumber,
    controlled: bool,
) -> PhoneInputNumber {
    if controlled {
        return if source.country.region_code == initial.region_code {
            source.clone()
        } else {
            resolve_offered_phone_value(countries, initial, &source.national_number)
        };
    }

    let offered = countries
        .iter()
        .any(|country| country.region_code == source.country.region_code);

    if offered || countries.is_empty() {
        return source.clone();
    }

    let fallback = resolve_phone_country(countries, default_country, None);

    resolve_offered_phone_value(countries, fallback, &source.national_number)
}

/// Props for [`PhoneInput`].
#[derive(Props, Clone, PartialEq)]
pub struct PhoneInputProps {
    /// Controlled value.
    pub value: Option<PhoneInputNumber>,
    /// Initial number text when uncontrolled; `+` numbers pick their country.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with every parsed value.
    pub on_value_change: Option<EventHandler<PhoneInputNumber>>,
    /// Countries to offer, in order. Defaults to every supported country in English order.
    pub country_options: Option<Vec<PhoneInputCountry>>,
    /// Initial country: a region code such as `CO`, or a calling code such as `+57`.
    #[props(default = "US".to_string(), into)]
    pub default_country_value: String,
    /// Accessible name of the country select.
    #[props(default = "Country code".to_string(), into)]
    pub country_label: String,
    /// Form field name of the country select.
    #[props(default = "country".to_string(), into)]
    pub country_name: String,
    /// Form field name of the number input.
    #[props(default = "phone".to_string(), into)]
    pub name: String,
    /// Placeholder, and the input's accessible name when it has no `id` or `input_aria_label`.
    #[props(default = "Phone number".to_string(), into)]
    pub placeholder: String,
    /// Message shown for an incomplete or invalid number.
    #[props(default = "Enter a complete phone number.".to_string(), into)]
    pub invalid_number_message: String,
    /// An app-provided error that replaces built-in validation.
    #[props(into)]
    pub error_message: Option<String>,
    /// Shows `invalid_number_message` while the typed number is invalid.
    #[props(default = true)]
    pub show_validation_error: bool,
    /// Control height.
    #[props(default)]
    pub visual_size: ControlSize,
    /// Disables both controls.
    #[props(default)]
    pub disabled: bool,
    /// Shows the value without letting the user change it; the country is still submitted.
    #[props(default)]
    pub read_only: bool,
    /// Marks the number input as required.
    pub required: Option<bool>,
    /// Id of the number input; generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Id of a form outside the component that the controls belong to.
    #[props(into)]
    pub form: Option<String>,
    /// Extra classes for the number input.
    #[props(into)]
    pub input_class: Option<String>,
    /// Accessible name of the number input.
    #[props(into)]
    pub input_aria_label: Option<String>,
    /// Ids of descriptions of the number input; the error id is appended while invalid.
    #[props(into)]
    pub input_aria_describedby: Option<String>,
    /// `autocomplete` of the number input.
    #[props(default = "tel-national".to_string(), into)]
    pub autocomplete: String,
    /// Returns flag artwork for a region code. Without it the flag shows the region code.
    pub flag_source: Option<Callback<String, Option<String>>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// A phone field: a country select with calling codes and flags, and a number input that formats
/// as you type, validates against libphonenumber metadata, and reports an E.164 value.
#[component]
pub fn PhoneInput(props: PhoneInputProps) -> Element {
    let countries = props
        .country_options
        .clone()
        .unwrap_or_else(|| PhoneInputCountry::all().to_vec());
    let initial_country = resolve_phone_country(
        &countries,
        &props.default_country_value,
        props.value.as_ref(),
    );
    let controlled = props.value.is_some();
    let value = use_controllable(
        props.value.clone(),
        || {
            props.default_value.as_deref().map_or_else(
                || PhoneInputNumber::empty(initial_country),
                |input| resolve_offered_phone_value(&countries, initial_country, input),
            )
        },
        props.on_value_change,
    );
    let source = value.get();
    let phone_value = offered_phone_value(
        &countries,
        &props.default_country_value,
        initial_country,
        &source,
        controlled,
    );

    // When the selected country leaves `country_options`, adopt the fallback once per change.
    let mut notified = use_signal(|| None::<String>);
    let fallback_key = (phone_value.country.region_code != source.country.region_code).then(|| {
        format!(
            "{}>{}",
            source.country.region_code, phone_value.country.region_code
        )
    });
    let fallback_value = phone_value.clone();
    let on_value_change = props.on_value_change;

    use_effect(use_reactive((&fallback_key,), move |(fallback_key,)| {
        let Some(key) = fallback_key else {
            notified.set(None);
            return;
        };

        if notified.peek().as_deref() == Some(key.as_str()) {
            return;
        }

        notified.set(Some(key));

        if value.is_controlled() {
            if let Some(handler) = on_value_change {
                handler.call(fallback_value.clone());
            }
        } else {
            value.set(fallback_value.clone());
        }
    }));

    let generated = use_unique_id();
    let mirror = use_value_mirror();
    let has_explicit_id = props.id.is_some();
    let control_id = props.id.clone().unwrap_or_else(|| generated.clone());
    let error_id = format!("{generated}-error");
    let is_disabled = props.disabled;
    let is_read_only = props.read_only;
    let effective_error = props.error_message.clone().or_else(|| {
        (props.show_validation_error
            && !phone_value.national_number.is_empty()
            && !phone_value.is_valid)
            .then(|| props.invalid_number_message.clone())
    });
    let invalid = effective_error.is_some();
    let (size, select_size, input_size) = match props.visual_size {
        ControlSize::Default => ("default", None, None),
        ControlSize::Sm => ("sm", Some("ui-select--sm"), Some("ui-input--sm")),
        ControlSize::Lg => ("lg", Some("ui-select--lg"), Some("ui-input--lg")),
    };
    let class = compose([
        Some("ui-phone-input ui-input-group"),
        props.class.as_deref(),
    ]);
    let select_class = compose([Some("ui-select ui-phone-input__country"), select_size]);
    let input_class = compose([
        Some("ui-input ui-phone-input__number"),
        input_size,
        props.input_class.as_deref(),
    ]);
    let described_by = Some(compose([
        props.input_aria_describedby.as_deref(),
        invalid.then_some(error_id.as_str()),
    ]))
    .filter(|ids| !ids.is_empty());
    let aria_label = props
        .input_aria_label
        .clone()
        .or_else(|| (!has_explicit_id).then(|| props.placeholder.clone()));
    let current = phone_value.country;
    let flag = props
        .flag_source
        .and_then(|source| source.call(current.region_code.to_string()));
    let country_value = (is_read_only && !is_disabled).then(|| current.region_code.to_string());

    let error_message_id = invalid.then(|| error_id.clone());
    let countries_for_select = countries.clone();
    let number_for_select = phone_value.national_number.clone();
    let countries_for_number = countries.clone();
    let rendered_number = mirror.attribute(&phone_value.national_number);

    rsx! {
        div {
            class,
            "data-disabled": is_disabled.then_some("true"),
            "data-invalid": invalid.then_some("true"),
            "data-phone-enhanced": "true",
            "data-readonly": is_read_only.then_some("true"),
            "data-size": size,
            "data-slot": "phone-input",
            ..props.attributes,
            span { class: "ui-phone-input__picker", "data-slot": "phone-country",
                span { aria_hidden: "true", class: "ui-phone-input__selection",
                    CountryFlag { decorative: true, region_code: current.region_code, source: flag }
                    span { "{current.calling_code}" }
                    span { class: "ui-phone-input__chevron" }
                }
                select {
                    aria_label: props.country_label.clone(),
                    class: select_class,
                    disabled: is_disabled || is_read_only || countries.is_empty(),
                    form: props.form.clone(),
                    name: props.country_name.clone(),
                    onchange: move |event: FormEvent| {
                        let picked = event.value();

                        if let Some(country) = countries_for_select.iter().find(|country| {
                            country.region_code == picked || country.calling_code == picked
                        }) {
                            value.set(PhoneInputNumber::resolve(*country, &number_for_select));
                        }
                    },
                    for country in countries.iter() {
                        option {
                            key: "{country.region_code}",
                            selected: country.region_code == current.region_code,
                            value: country.region_code,
                            "{country.display_name} ({country.calling_code})"
                        }
                    }
                }
            }
            input {
                aria_describedby: described_by,
                aria_errormessage: error_message_id,
                aria_invalid: invalid.then_some("true"),
                autocomplete: props.autocomplete.clone(),
                aria_label,
                class: input_class,
                disabled: is_disabled,
                id: control_id,
                inputmode: "tel",
                name: props.name.clone(),
                placeholder: props.placeholder.clone(),
                readonly: is_read_only,
                required: props.required.unwrap_or(false),
                r#type: "tel",
                value: rendered_number,
                oninput: move |event: FormEvent| {
                    let raw = event.value();
                    let next = resolve_offered_phone_value(&countries_for_number, current, &raw);

                    // Rewrite the control when sanitizing or formatting changed the text, or when
                    // a controlled value may stay the same while the control shows the edit.
                    if value.is_controlled() || raw != next.national_number {
                        mirror.record(raw);
                    }

                    value.set(next);
                },
            }
            if let Some(region) = country_value {
                input {
                    form: props.form.clone(),
                    name: props.country_name.clone(),
                    r#type: "hidden",
                    value: region,
                }
            }
        }
        if let Some(error) = effective_error {
            span { class: "ui-phone-input__error", id: error_id, role: "alert", "{error}" }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{resolve_offered_phone_value, resolve_phone_country};
    use crate::pickers::phone_engine::{PhoneInputCountry, PhoneInputNumber};

    fn country(region: &str) -> PhoneInputCountry {
        PhoneInputCountry::find(region).expect("supported test region")
    }

    #[test]
    fn initial_country_prefers_value_then_default() {
        let offered = [country("CO"), country("US"), country("GB")];
        assert_eq!(
            resolve_phone_country(&offered, "GB", None).region_code,
            "GB"
        );
        assert_eq!(
            resolve_phone_country(&offered, "+57", None).region_code,
            "CO"
        );
        assert_eq!(
            resolve_phone_country(&offered, "FR", None).region_code,
            "CO"
        );

        let canada = PhoneInputNumber::empty(country("CA"));
        // Canada is not offered, so the shared +1 calling code picks the United States.
        assert_eq!(
            resolve_phone_country(&offered, "GB", Some(&canada)).region_code,
            "US"
        );
        assert_eq!(resolve_phone_country(&[], "GB", None).region_code, "US");
    }

    #[test]
    fn international_numbers_for_other_countries_stay_national() {
        let offered = [country("US")];
        let value = resolve_offered_phone_value(&offered, country("US"), "+44 20 7946 0018");
        assert_eq!(value.country.region_code, "US");
        assert!(!value.national_number.starts_with('+'));

        let value = resolve_offered_phone_value(&offered, country("US"), "2015550123");
        assert!(value.is_valid);
        assert_eq!(value.e164.as_deref(), Some("+12015550123"));
    }
}