Skip to main content

lumen_dioxus/pickers/
phone_input.rs

1//! `PhoneInput`, `CountryFlag`, and `PhoneNumber`, backed by the dependency-free phone engine.
2
3use dioxus::prelude::*;
4
5use super::phone_engine::{PhoneInputCountry, PhoneInputNumber};
6use crate::class::compose;
7use crate::form::ControlSize;
8use crate::hooks::{use_controllable, use_unique_id};
9
10fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
11    attributes
12        .iter()
13        .rev()
14        .find(|attribute| attribute.name == name)
15        .and_then(|attribute| match &attribute.value {
16            dioxus::core::AttributeValue::Text(text) => Some(text.clone()),
17            _ => None,
18        })
19}
20
21/// Mirrors the `value` attribute of the number input, a private copy of the numeric inputs'
22/// `ValueMirror`.
23///
24/// Dioxus only writes an attribute that differs from the previous render, so when sanitizing
25/// leaves the number unchanged (a rejected letter) the control would keep showing, and submit, the
26/// raw text. After such an edit the mirror first renders the raw text the control already shows,
27/// then the corrected value on the next pass, which always produces a write.
28#[derive(Clone, Copy)]
29struct ValueMirror {
30    pending: Signal<Option<String>>,
31}
32
33fn use_value_mirror() -> ValueMirror {
34    ValueMirror {
35        pending: use_signal(|| None),
36    }
37}
38
39impl ValueMirror {
40    /// The `value` attribute to render this pass, given the corrected value.
41    fn attribute(&self, corrected: &str) -> String {
42        self.pending
43            .read()
44            .clone()
45            .unwrap_or_else(|| corrected.to_string())
46    }
47
48    /// Records the text the control shows after a user edit and schedules the correction.
49    fn record(&self, raw: String) {
50        let mut pending = self.pending;
51
52        pending.set(Some(raw));
53        spawn(async move {
54            pending.set(None);
55        });
56    }
57}
58
59/// The first two characters of a region code, uppercased: the text a flag shows without artwork.
60fn region_text(region_code: &str) -> String {
61    region_code
62        .chars()
63        .take(2)
64        .collect::<String>()
65        .to_uppercase()
66}
67
68/// Props for [`CountryFlag`].
69#[derive(Props, Clone, PartialEq)]
70pub struct CountryFlagProps {
71    /// ISO 3166-1 alpha-2 region code, such as `US`.
72    #[props(into)]
73    pub region_code: String,
74    /// Hides the flag from assistive technology when nearby text already names the country.
75    #[props(default)]
76    pub decorative: bool,
77    /// Flag artwork URL. Without one the flag shows the region code, like lumen-react does for a
78    /// region without bundled artwork.
79    #[props(into)]
80    pub source: Option<String>,
81    /// Extra classes appended after the Lumen class.
82    #[props(into)]
83    pub class: Option<String>,
84    /// Any other `<span>` or global attribute. `aria_label` replaces the region-code name.
85    #[props(extends = GlobalAttributes, extends = span)]
86    pub attributes: Vec<Attribute>,
87}
88
89/// A country flag: an image when `source` is set, otherwise the region code.
90///
91/// lumen-dioxus does not bundle flag artwork (about 300 KB for every region); pass `source`
92/// with your own artwork, such as the MIT-licensed `flag-icons` set lumen-react embeds.
93#[component]
94pub fn CountryFlag(props: CountryFlagProps) -> Element {
95    let label = attribute_text(&props.attributes, "aria-label")
96        .unwrap_or_else(|| props.region_code.to_uppercase());
97    let attributes: Vec<Attribute> = props
98        .attributes
99        .into_iter()
100        .filter(|attribute| attribute.name != "aria-label")
101        .collect();
102    let class = compose([Some("ui-country-flag"), props.class.as_deref()]);
103    let decorative = props.decorative;
104
105    rsx! {
106        span {
107            aria_hidden: decorative.then_some("true"),
108            aria_label: (!decorative).then_some(label),
109            class,
110            "data-slot": "country-flag",
111            role: (!decorative).then_some("img"),
112            ..attributes,
113            if let Some(source) = props.source {
114                img { alt: "", height: "18", src: source, width: "24" }
115            } else {
116                "{region_text(&props.region_code)}"
117            }
118        }
119    }
120}
121
122/// Props for [`PhoneNumber`].
123#[derive(Props, Clone, PartialEq)]
124pub struct PhoneNumberProps {
125    /// The number to show.
126    pub value: PhoneInputNumber,
127    /// Renders a `tel:` link when the number is valid.
128    #[props(default)]
129    pub link: bool,
130    /// Flag artwork URL for the number's country.
131    #[props(into)]
132    pub flag_source: Option<String>,
133    /// Extra classes appended after the Lumen class.
134    #[props(into)]
135    pub class: Option<String>,
136    /// Any other global attribute.
137    #[props(extends = GlobalAttributes)]
138    pub attributes: Vec<Attribute>,
139}
140
141/// A read-only phone number with its country flag: the E.164 value when valid, otherwise the
142/// typed text, or an em dash when empty.
143#[component]
144pub fn PhoneNumber(props: PhoneNumberProps) -> Element {
145    let class = compose([Some("ui-phone-number"), props.class.as_deref()]);
146    let text = props.value.display();
147    let text = if text.is_empty() {
148        "—".to_string()
149    } else {
150        text
151    };
152    let title = props.value.country.display_name;
153    let region = props.value.country.region_code;
154    let href = props
155        .value
156        .e164
157        .as_ref()
158        .filter(|_| props.link && props.value.is_valid)
159        .map(|e164| format!("tel:{e164}"));
160
161    rsx! {
162        if let Some(href) = href {
163            a { class, href, title, ..props.attributes,
164                CountryFlag { decorative: true, region_code: region, source: props.flag_source }
165                span { "{text}" }
166            }
167        } else {
168            span { class, title, ..props.attributes,
169                CountryFlag { decorative: true, region_code: region, source: props.flag_source }
170                span { "{text}" }
171            }
172        }
173    }
174}
175
176/// The country `PhoneInput` starts with, like `resolveReactPhoneInputCountry`.
177pub(crate) fn resolve_phone_country(
178    countries: &[PhoneInputCountry],
179    default_country: &str,
180    value: Option<&PhoneInputNumber>,
181) -> PhoneInputCountry {
182    let requested = value.map(|number| number.country);
183
184    countries
185        .iter()
186        .find(|country| {
187            requested.is_some_and(|requested| requested.region_code == country.region_code)
188        })
189        .or_else(|| {
190            countries.iter().find(|country| {
191                requested.is_some_and(|requested| requested.calling_code == country.calling_code)
192            })
193        })
194        .or_else(|| {
195            countries
196                .iter()
197                .find(|country| country.region_code == default_country)
198        })
199        .or_else(|| {
200            countries
201                .iter()
202                .find(|country| country.calling_code == default_country)
203        })
204        .or_else(|| countries.first())
205        .copied()
206        .or_else(|| PhoneInputCountry::find("US"))
207        .unwrap_or(PhoneInputCountry {
208            region_code: "US",
209            calling_code: "+1",
210            display_name: "United States",
211        })
212}
213
214/// Resolves input against the offered countries, like `resolveReactPhoneInputValue`: an
215/// international number for a country that is not offered is read as national input instead.
216pub(crate) fn resolve_offered_phone_value(
217    countries: &[PhoneInputCountry],
218    country: PhoneInputCountry,
219    input: &str,
220) -> PhoneInputNumber {
221    let detected = PhoneInputNumber::resolve(country, input);
222
223    if countries
224        .iter()
225        .any(|candidate| candidate.region_code == detected.country.region_code)
226    {
227        return detected;
228    }
229
230    let national = detected
231        .national_number
232        .strip_prefix('+')
233        .unwrap_or(&detected.national_number)
234        .to_string();
235
236    PhoneInputNumber::resolve(country, &national)
237}
238
239/// The value the picker shows when the selected country is no longer offered, like
240/// `resolveOfferedPhoneValue`.
241fn offered_phone_value(
242    countries: &[PhoneInputCountry],
243    default_country: &str,
244    initial: PhoneInputCountry,
245    source: &PhoneInputNumber,
246    controlled: bool,
247) -> PhoneInputNumber {
248    if controlled {
249        return if source.country.region_code == initial.region_code {
250            source.clone()
251        } else {
252            resolve_offered_phone_value(countries, initial, &source.national_number)
253        };
254    }
255
256    let offered = countries
257        .iter()
258        .any(|country| country.region_code == source.country.region_code);
259
260    if offered || countries.is_empty() {
261        return source.clone();
262    }
263
264    let fallback = resolve_phone_country(countries, default_country, None);
265
266    resolve_offered_phone_value(countries, fallback, &source.national_number)
267}
268
269/// Props for [`PhoneInput`].
270#[derive(Props, Clone, PartialEq)]
271pub struct PhoneInputProps {
272    /// Controlled value.
273    pub value: Option<PhoneInputNumber>,
274    /// Initial number text when uncontrolled; `+` numbers pick their country.
275    #[props(into)]
276    pub default_value: Option<String>,
277    /// Called with every parsed value.
278    pub on_value_change: Option<EventHandler<PhoneInputNumber>>,
279    /// Countries to offer, in order. Defaults to every supported country in English order.
280    pub country_options: Option<Vec<PhoneInputCountry>>,
281    /// Initial country: a region code such as `CO`, or a calling code such as `+57`.
282    #[props(default = "US".to_string(), into)]
283    pub default_country_value: String,
284    /// Accessible name of the country select.
285    #[props(default = "Country code".to_string(), into)]
286    pub country_label: String,
287    /// Form field name of the country select.
288    #[props(default = "country".to_string(), into)]
289    pub country_name: String,
290    /// Form field name of the number input.
291    #[props(default = "phone".to_string(), into)]
292    pub name: String,
293    /// Placeholder, and the input's accessible name when it has no `id` or `input_aria_label`.
294    #[props(default = "Phone number".to_string(), into)]
295    pub placeholder: String,
296    /// Message shown for an incomplete or invalid number.
297    #[props(default = "Enter a complete phone number.".to_string(), into)]
298    pub invalid_number_message: String,
299    /// An app-provided error that replaces built-in validation.
300    #[props(into)]
301    pub error_message: Option<String>,
302    /// Shows `invalid_number_message` while the typed number is invalid.
303    #[props(default = true)]
304    pub show_validation_error: bool,
305    /// Control height.
306    #[props(default)]
307    pub visual_size: ControlSize,
308    /// Disables both controls.
309    #[props(default)]
310    pub disabled: bool,
311    /// Shows the value without letting the user change it; the country is still submitted.
312    #[props(default)]
313    pub read_only: bool,
314    /// Marks the number input as required.
315    pub required: Option<bool>,
316    /// Id of the number input; generated when unset.
317    #[props(into)]
318    pub id: Option<String>,
319    /// Id of a form outside the component that the controls belong to.
320    #[props(into)]
321    pub form: Option<String>,
322    /// Extra classes for the number input.
323    #[props(into)]
324    pub input_class: Option<String>,
325    /// Accessible name of the number input.
326    #[props(into)]
327    pub input_aria_label: Option<String>,
328    /// Ids of descriptions of the number input; the error id is appended while invalid.
329    #[props(into)]
330    pub input_aria_describedby: Option<String>,
331    /// `autocomplete` of the number input.
332    #[props(default = "tel-national".to_string(), into)]
333    pub autocomplete: String,
334    /// Returns flag artwork for a region code. Without it the flag shows the region code.
335    pub flag_source: Option<Callback<String, Option<String>>>,
336    /// Extra classes appended after the Lumen classes.
337    #[props(into)]
338    pub class: Option<String>,
339    /// Any other `<div>` or global attribute.
340    #[props(extends = GlobalAttributes, extends = div)]
341    pub attributes: Vec<Attribute>,
342}
343
344/// A phone field: a country select with calling codes and flags, and a number input that formats
345/// as you type, validates against libphonenumber metadata, and reports an E.164 value.
346#[component]
347pub fn PhoneInput(props: PhoneInputProps) -> Element {
348    let countries = props
349        .country_options
350        .clone()
351        .unwrap_or_else(|| PhoneInputCountry::all().to_vec());
352    let initial_country = resolve_phone_country(
353        &countries,
354        &props.default_country_value,
355        props.value.as_ref(),
356    );
357    let controlled = props.value.is_some();
358    let value = use_controllable(
359        props.value.clone(),
360        || {
361            props.default_value.as_deref().map_or_else(
362                || PhoneInputNumber::empty(initial_country),
363                |input| resolve_offered_phone_value(&countries, initial_country, input),
364            )
365        },
366        props.on_value_change,
367    );
368    let source = value.get();
369    let phone_value = offered_phone_value(
370        &countries,
371        &props.default_country_value,
372        initial_country,
373        &source,
374        controlled,
375    );
376
377    // When the selected country leaves `country_options`, adopt the fallback once per change.
378    let mut notified = use_signal(|| None::<String>);
379    let fallback_key = (phone_value.country.region_code != source.country.region_code).then(|| {
380        format!(
381            "{}>{}",
382            source.country.region_code, phone_value.country.region_code
383        )
384    });
385    let fallback_value = phone_value.clone();
386    let on_value_change = props.on_value_change;
387
388    use_effect(use_reactive((&fallback_key,), move |(fallback_key,)| {
389        let Some(key) = fallback_key else {
390            notified.set(None);
391            return;
392        };
393
394        if notified.peek().as_deref() == Some(key.as_str()) {
395            return;
396        }
397
398        notified.set(Some(key));
399
400        if value.is_controlled() {
401            if let Some(handler) = on_value_change {
402                handler.call(fallback_value.clone());
403            }
404        } else {
405            value.set(fallback_value.clone());
406        }
407    }));
408
409    let generated = use_unique_id();
410    let mirror = use_value_mirror();
411    let has_explicit_id = props.id.is_some();
412    let control_id = props.id.clone().unwrap_or_else(|| generated.clone());
413    let error_id = format!("{generated}-error");
414    let is_disabled = props.disabled;
415    let is_read_only = props.read_only;
416    let effective_error = props.error_message.clone().or_else(|| {
417        (props.show_validation_error
418            && !phone_value.national_number.is_empty()
419            && !phone_value.is_valid)
420            .then(|| props.invalid_number_message.clone())
421    });
422    let invalid = effective_error.is_some();
423    let (size, select_size, input_size) = match props.visual_size {
424        ControlSize::Default => ("default", None, None),
425        ControlSize::Sm => ("sm", Some("ui-select--sm"), Some("ui-input--sm")),
426        ControlSize::Lg => ("lg", Some("ui-select--lg"), Some("ui-input--lg")),
427    };
428    let class = compose([
429        Some("ui-phone-input ui-input-group"),
430        props.class.as_deref(),
431    ]);
432    let select_class = compose([Some("ui-select ui-phone-input__country"), select_size]);
433    let input_class = compose([
434        Some("ui-input ui-phone-input__number"),
435        input_size,
436        props.input_class.as_deref(),
437    ]);
438    let described_by = Some(compose([
439        props.input_aria_describedby.as_deref(),
440        invalid.then_some(error_id.as_str()),
441    ]))
442    .filter(|ids| !ids.is_empty());
443    let aria_label = props
444        .input_aria_label
445        .clone()
446        .or_else(|| (!has_explicit_id).then(|| props.placeholder.clone()));
447    let current = phone_value.country;
448    let flag = props
449        .flag_source
450        .and_then(|source| source.call(current.region_code.to_string()));
451    let country_value = (is_read_only && !is_disabled).then(|| current.region_code.to_string());
452
453    let error_message_id = invalid.then(|| error_id.clone());
454    let countries_for_select = countries.clone();
455    let number_for_select = phone_value.national_number.clone();
456    let countries_for_number = countries.clone();
457    let rendered_number = mirror.attribute(&phone_value.national_number);
458
459    rsx! {
460        div {
461            class,
462            "data-disabled": is_disabled.then_some("true"),
463            "data-invalid": invalid.then_some("true"),
464            "data-phone-enhanced": "true",
465            "data-readonly": is_read_only.then_some("true"),
466            "data-size": size,
467            "data-slot": "phone-input",
468            ..props.attributes,
469            span { class: "ui-phone-input__picker", "data-slot": "phone-country",
470                span { aria_hidden: "true", class: "ui-phone-input__selection",
471                    CountryFlag { decorative: true, region_code: current.region_code, source: flag }
472                    span { "{current.calling_code}" }
473                    span { class: "ui-phone-input__chevron" }
474                }
475                select {
476                    aria_label: props.country_label.clone(),
477                    class: select_class,
478                    disabled: is_disabled || is_read_only || countries.is_empty(),
479                    form: props.form.clone(),
480                    name: props.country_name.clone(),
481                    onchange: move |event: FormEvent| {
482                        let picked = event.value();
483
484                        if let Some(country) = countries_for_select.iter().find(|country| {
485                            country.region_code == picked || country.calling_code == picked
486                        }) {
487                            value.set(PhoneInputNumber::resolve(*country, &number_for_select));
488                        }
489                    },
490                    for country in countries.iter() {
491                        option {
492                            key: "{country.region_code}",
493                            selected: country.region_code == current.region_code,
494                            value: country.region_code,
495                            "{country.display_name} ({country.calling_code})"
496                        }
497                    }
498                }
499            }
500            input {
501                aria_describedby: described_by,
502                aria_errormessage: error_message_id,
503                aria_invalid: invalid.then_some("true"),
504                autocomplete: props.autocomplete.clone(),
505                aria_label,
506                class: input_class,
507                disabled: is_disabled,
508                id: control_id,
509                inputmode: "tel",
510                name: props.name.clone(),
511                placeholder: props.placeholder.clone(),
512                readonly: is_read_only,
513                required: props.required.unwrap_or(false),
514                r#type: "tel",
515                value: rendered_number,
516                oninput: move |event: FormEvent| {
517                    let raw = event.value();
518                    let next = resolve_offered_phone_value(&countries_for_number, current, &raw);
519
520                    // Rewrite the control when sanitizing or formatting changed the text, or when
521                    // a controlled value may stay the same while the control shows the edit.
522                    if value.is_controlled() || raw != next.national_number {
523                        mirror.record(raw);
524                    }
525
526                    value.set(next);
527                },
528            }
529            if let Some(region) = country_value {
530                input {
531                    form: props.form.clone(),
532                    name: props.country_name.clone(),
533                    r#type: "hidden",
534                    value: region,
535                }
536            }
537        }
538        if let Some(error) = effective_error {
539            span { class: "ui-phone-input__error", id: error_id, role: "alert", "{error}" }
540        }
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use super::{resolve_offered_phone_value, resolve_phone_country};
547    use crate::pickers::phone_engine::{PhoneInputCountry, PhoneInputNumber};
548
549    fn country(region: &str) -> PhoneInputCountry {
550        PhoneInputCountry::find(region).expect("supported test region")
551    }
552
553    #[test]
554    fn initial_country_prefers_value_then_default() {
555        let offered = [country("CO"), country("US"), country("GB")];
556        assert_eq!(
557            resolve_phone_country(&offered, "GB", None).region_code,
558            "GB"
559        );
560        assert_eq!(
561            resolve_phone_country(&offered, "+57", None).region_code,
562            "CO"
563        );
564        assert_eq!(
565            resolve_phone_country(&offered, "FR", None).region_code,
566            "CO"
567        );
568
569        let canada = PhoneInputNumber::empty(country("CA"));
570        // Canada is not offered, so the shared +1 calling code picks the United States.
571        assert_eq!(
572            resolve_phone_country(&offered, "GB", Some(&canada)).region_code,
573            "US"
574        );
575        assert_eq!(resolve_phone_country(&[], "GB", None).region_code, "US");
576    }
577
578    #[test]
579    fn international_numbers_for_other_countries_stay_national() {
580        let offered = [country("US")];
581        let value = resolve_offered_phone_value(&offered, country("US"), "+44 20 7946 0018");
582        assert_eq!(value.country.region_code, "US");
583        assert!(!value.national_number.starts_with('+'));
584
585        let value = resolve_offered_phone_value(&offered, country("US"), "2015550123");
586        assert!(value.is_valid);
587        assert_eq!(value.e164.as_deref(), Some("+12015550123"));
588    }
589}