Skip to main content

arc_ui/inputs/
phone_input.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/phone-input/phone-input.tsx` & `.module.css`
3//!
4//! P4 Component #10: `phone-input`
5//!
6//! - Phone number field with a country picker, value emitted as E.164:
7//!   - Compact country table (46 countries) carrying dial codes, national format patterns
8//!     (`#` is a digit), typed trunk prefixes, example numbers, and shared-dial area codes
9//!     (Canada inside `+1`). No metadata dependency; formatting is pattern-driven.
10//!   - The number formats as it is typed (`(###) ###-####`), with a faint guide painting the
11//!     rest of the country's example shape after the typed digits, and a `success` check that
12//!     pops on `motion.spring.snappy` once the national digit count matches the pattern.
13//!   - The country button morphs into a searchable list: one surface whose width, height, and
14//!     corners spring between the closed trigger (`17px` radius) and the open panel
15//!     (`22px` radius, `340px` max) on `physical(0.4, 0)` grow / `physical(0.32, 0)` shrink
16//!     springs, with a gliding highlight pill and `Suggested` / `All countries` sections.
17//!   - Typing `+` in the number opens the picker seeded with a calling-code search; pasting an
18//!     international number (`+44 (0)7911 123456`, `0044 …`) picks its own country; the flag
19//!     and dial roll in the direction of the list move.
20//!   - Validation reads the national digit count against the pattern capacities (`empty`,
21//!     `incomplete`, `valid`, `too-long`) and reports `Numbers in <country> have N digits`.
22//!
23//! Known deviations from upstream:
24//! - No caret editing in the number field: the number is self-painted text (no system text
25//!   input), so editing appends digits at the end and `Backspace` deletes the last digit;
26//!   paste replaces the draft with a whole number or appends a fragment.
27//! - The built-in validation message shows while the field is not focused (upstream latches it
28//!   after the first blur); there is no `aria-live` announcement region.
29//! - The web-only `name` hidden form field is omitted; the flag renders as regional-indicator
30//!   letters when the platform lacks color-emoji glyphs (same fallback as upstream).
31//! - Keyboard moves in the country list do not scroll an out-of-viewport active row into view
32//!   yet (the list scrolls by wheel); selection itself works for any row.
33
34use std::{cell::RefCell, rc::Rc};
35
36use arc_motion::{
37    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
38    arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
39};
40use arc_tokens::{
41    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
42};
43use gpui_kit::{
44    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
45    MouseButton, MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
46    SharedString, Styled, TestSupportExt as _, Window,
47    assets::IconName,
48    base::{Button as BaseButton, StyledExt as _},
49    canvas,
50    component::{
51        Icon,
52        input::{Input as KitInput, InputState},
53    },
54    deferred, div, point,
55    prelude::*,
56    px,
57};
58
59use super::field_message::render_field_message;
60
61type PhoneValueChangeHandler = Rc<dyn Fn(&PhoneValueEvent, &mut Window, &mut App)>;
62type PhoneCountryChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
63
64/// One surface for both picker states: closed trigger radius (`8px`), open panel radius (`10px`).
65pub const PHONE_CLOSED_RADIUS: f32 = 8.0;
66pub const PHONE_OPEN_RADIUS: f32 = 10.0;
67/// Max width (`310px`) of the open country panel.
68pub const PHONE_PANEL_MAX: f32 = 310.0;
69/// Page size (`8` rows) for `PageUp` / `PageDown` in the country list.
70pub const PHONE_PAGE: usize = 8;
71/// Max height (`240px`) of the country list viewport.
72pub const PHONE_LIST_MAX_H: f32 = 240.0;
73
74/// The panel springs open on `physical(0.4, 0)` and closed on `physical(0.32, 0)`.
75pub const fn phone_grow_spring() -> SpringSpec {
76    SpringSpec::visual(0.4, 0.0)
77}
78pub const fn phone_shrink_spring() -> SpringSpec {
79    SpringSpec::visual(0.32, 0.0)
80}
81/// Gliding highlights, chevron rotation, and flag rolls run on `physical(0.28, 0)`.
82pub const fn phone_glide_spring() -> SpringSpec {
83    SpringSpec::visual(0.28, 0.0)
84}
85/// The panel width morphs on `physical(0.42, 0)` (`WIDTH`).
86pub const fn phone_width_spring() -> SpringSpec {
87    SpringSpec::visual(0.42, 0.0)
88}
89
90/// One country entry: ISO code, name, calling code, national format patterns, typed trunk
91/// prefix, a realistic example number, and optional shared-dial area codes.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub struct PhoneCountry {
94    pub iso: &'static str,
95    pub name: &'static str,
96    pub dial: &'static str,
97    pub patterns: &'static [&'static str],
98    pub trunk: &'static str,
99    pub example: &'static str,
100    pub area_codes: &'static [&'static str],
101}
102
103/// Most countries type a `0` trunk prefix before the national number
104/// (upstream `country(..., trunk = "0")` default).
105const fn country(
106    iso: &'static str,
107    name: &'static str,
108    dial: &'static str,
109    patterns: &'static [&'static str],
110    example: &'static str,
111) -> PhoneCountry {
112    PhoneCountry {
113        iso,
114        name,
115        dial,
116        patterns,
117        trunk: "0",
118        example,
119        area_codes: &[],
120    }
121}
122
123/// Countries whose numbers carry no trunk prefix.
124const fn country_flat(
125    iso: &'static str,
126    name: &'static str,
127    dial: &'static str,
128    patterns: &'static [&'static str],
129    example: &'static str,
130) -> PhoneCountry {
131    PhoneCountry {
132        iso,
133        name,
134        dial,
135        patterns,
136        trunk: "",
137        example,
138        area_codes: &[],
139    }
140}
141
142/// Countries with a typed trunk prefix that is not `0` (NANP members type `1`).
143const fn country_trunk(
144    iso: &'static str,
145    name: &'static str,
146    dial: &'static str,
147    patterns: &'static [&'static str],
148    example: &'static str,
149    trunk: &'static str,
150) -> PhoneCountry {
151    PhoneCountry {
152        iso,
153        name,
154        dial,
155        patterns,
156        trunk,
157        example,
158        area_codes: &[],
159    }
160}
161
162/// Canada shares the `+1` dial; area codes pick it inside `phone_parse_number`.
163const CA_AREA_CODES: &[&str] = &[
164    "204", "226", "236", "249", "250", "263", "289", "306", "343", "354", "365", "367", "368",
165    "382", "387", "403", "416", "418", "428", "431", "437", "438", "450", "468", "474", "506",
166    "514", "519", "548", "579", "581", "584", "587", "604", "613", "639", "647", "672", "683",
167    "705", "709", "742", "753", "778", "780", "782", "807", "819", "825", "867", "873", "879",
168    "902", "905",
169];
170
171/// The compact country table (upstream `PHONE_COUNTRIES`, 46 entries).
172pub static PHONE_COUNTRIES: &[PhoneCountry] = &[
173    country_trunk(
174        "US",
175        "United States",
176        "1",
177        &["(###) ###-####"],
178        "2015550123",
179        "1",
180    ),
181    PhoneCountry {
182        iso: "CA",
183        name: "Canada",
184        dial: "1",
185        patterns: &["(###) ###-####"],
186        trunk: "1",
187        example: "5065550123",
188        area_codes: CA_AREA_CODES,
189    },
190    country_flat("MX", "Mexico", "52", &["## #### ####"], "2221234567"),
191    country(
192        "BR",
193        "Brazil",
194        "55",
195        &["(##) ####-####", "(##) #####-####"],
196        "11961234567",
197    ),
198    country("AR", "Argentina", "54", &["## ####-####"], "1123456789"),
199    country_flat("CO", "Colombia", "57", &["### ### ####"], "3211234567"),
200    country_flat("CL", "Chile", "56", &["# #### ####"], "221234567"),
201    country_flat("PE", "Peru", "51", &["### ### ###"], "912345678"),
202    country("GB", "United Kingdom", "44", &["#### ######"], "7400123456"),
203    country("IE", "Ireland", "353", &["## ### ####"], "850123456"),
204    country("FR", "France", "33", &["# ## ## ## ##"], "612345678"),
205    country(
206        "DE",
207        "Germany",
208        "49",
209        &["### #######", "### ########"],
210        "15123456789",
211    ),
212    country_flat("ES", "Spain", "34", &["### ## ## ##"], "612345678"),
213    country_flat(
214        "IT",
215        "Italy",
216        "39",
217        &["### ### ###", "### ### ####"],
218        "3123456789",
219    ),
220    country_flat("PT", "Portugal", "351", &["### ### ###"], "912345678"),
221    country_flat("NL", "Netherlands", "31", &["# ########"], "612345678"),
222    country_flat("BE", "Belgium", "32", &["### ## ## ##"], "470123456"),
223    country_flat("CH", "Switzerland", "41", &["## ### ## ##"], "781234567"),
224    country(
225        "AT",
226        "Austria",
227        "43",
228        &["### #######", "### ########"],
229        "6641234567",
230    ),
231    country("SE", "Sweden", "46", &["## ### ## ##"], "701234567"),
232    country_flat("NO", "Norway", "47", &["### ## ###"], "40612345"),
233    country_flat("DK", "Denmark", "45", &["## ## ## ##"], "32123456"),
234    country(
235        "FI",
236        "Finland",
237        "358",
238        &["## ### ####", "## ### #####"],
239        "412345678",
240    ),
241    country_flat("PL", "Poland", "48", &["### ### ###"], "512345678"),
242    country_flat("CZ", "Czechia", "420", &["### ### ###"], "601123456"),
243    country_flat("GR", "Greece", "30", &["### ### ####"], "6912345678"),
244    country("UA", "Ukraine", "380", &["## ### ## ##"], "501234567"),
245    country("TR", "Turkey", "90", &["### ### ## ##"], "5012345678"),
246    country("IL", "Israel", "972", &["##-###-####"], "502345678"),
247    country(
248        "AE",
249        "United Arab Emirates",
250        "971",
251        &["## ### ####"],
252        "501234567",
253    ),
254    country("SA", "Saudi Arabia", "966", &["## ### ####"], "512345678"),
255    country("EG", "Egypt", "20", &["### ### ####"], "1001234567"),
256    country("NG", "Nigeria", "234", &["### ### ####"], "8021234567"),
257    country("KE", "Kenya", "254", &["### ######"], "712123456"),
258    country("ZA", "South Africa", "27", &["## ### ####"], "711234567"),
259    country("IN", "India", "91", &["#####-#####"], "8123456789"),
260    country("PK", "Pakistan", "92", &["### #######"], "3012345678"),
261    country("CN", "China", "86", &["### #### ####"], "13123456789"),
262    country("JP", "Japan", "81", &["##-####-####"], "9012345678"),
263    country(
264        "KR",
265        "South Korea",
266        "82",
267        &["##-###-####", "##-####-####"],
268        "1020000000",
269    ),
270    country("TW", "Taiwan", "886", &["### ### ###"], "912345678"),
271    country_flat("HK", "Hong Kong", "852", &["#### ####"], "51234567"),
272    country_flat("SG", "Singapore", "65", &["#### ####"], "81234567"),
273    country("PH", "Philippines", "63", &["### ### ####"], "9051234567"),
274    country(
275        "ID",
276        "Indonesia",
277        "62",
278        &["###-###-####", "###-####-####", "###-####-#####"],
279        "81234567890",
280    ),
281    country("TH", "Thailand", "66", &["## ### ####"], "812345678"),
282    country("VN", "Vietnam", "84", &["## ### ## ##"], "912345678"),
283    country("AU", "Australia", "61", &["### ### ###"], "412345678"),
284    country(
285        "NZ",
286        "New Zealand",
287        "64",
288        &["# ### ####", "## ### ####", "## #### ####"],
289        "211234567",
290    ),
291];
292
293/// Resolves a country by ISO code.
294pub fn phone_country_by_iso(iso: &str) -> Option<&'static PhoneCountry> {
295    PHONE_COUNTRIES.iter().find(|entry| entry.iso == iso)
296}
297
298pub fn phone_only_digits(text: &str) -> String {
299    text.chars().filter(|c| c.is_ascii_digit()).collect()
300}
301
302/// Regional indicator letters; platforms without flag glyphs show the two letters.
303pub fn phone_flag_of(iso: &str) -> String {
304    iso.to_uppercase()
305        .chars()
306        .map(|c| char::from_u32(0x1f1e6 + (u32::from(c) - 65)).unwrap_or(c))
307        .collect()
308}
309
310/// `(typed trunk, national rest)` — a typed trunk prefix earns its own room.
311pub fn phone_split_trunk<'a>(entry: &PhoneCountry, digits: &'a str) -> (&'a str, &'a str) {
312    if !entry.trunk.is_empty() && digits.starts_with(entry.trunk) {
313        (entry.trunk, &digits[entry.trunk.len()..])
314    } else {
315        ("", digits)
316    }
317}
318
319/// Digit capacity of one pattern (`#` count).
320pub fn phone_capacity(pattern: &str) -> usize {
321    pattern.matches('#').count()
322}
323
324/// Valid national lengths, i.e. the digit capacities of the patterns.
325pub fn phone_lengths(entry: &PhoneCountry) -> Vec<usize> {
326    entry.patterns.iter().map(|p| phone_capacity(p)).collect()
327}
328
329/// Caps digits so a typed trunk prefix plus the longest pattern still fit.
330pub fn phone_cap_digits(entry: &PhoneCountry, digits: &str) -> String {
331    let trunk_len = phone_split_trunk(entry, digits).0.len();
332    let max_len = phone_lengths(entry).into_iter().max().unwrap_or(0);
333    digits.chars().take(trunk_len + max_len).collect()
334}
335
336/// Applies a format pattern: separators only print while digits follow and consume no digit,
337/// and digits beyond the pattern are appended as-is.
338pub fn phone_apply_pattern(digits: &str, pattern: &str) -> String {
339    let mut out = String::new();
340    let mut chars = digits.chars().peekable();
341    for ch in pattern.chars() {
342        if chars.peek().is_none() {
343            break;
344        }
345        if ch == '#' {
346            if let Some(d) = chars.next() {
347                out.push(d);
348            }
349        } else {
350            out.push(ch);
351        }
352    }
353    let rest: String = chars.collect();
354    out + &rest
355}
356
357/// Picks the pattern whose capacity first covers `length`, else the longest pattern.
358pub fn phone_pattern_for(entry: &PhoneCountry, length: usize) -> &str {
359    entry
360        .patterns
361        .iter()
362        .find(|p| phone_capacity(p) >= length)
363        .copied()
364        .unwrap_or_else(|| entry.patterns.last().expect("patterns is non-empty"))
365}
366
367/// Formats national digits as typed, keeping a typed trunk prefix:
368/// `"07911123456"` in the UK reads `"07911 123456"`.
369pub fn phone_format_national(entry: &PhoneCountry, digits: &str) -> String {
370    let (trunk, rest) = phone_split_trunk(entry, digits);
371    let pattern = phone_pattern_for(entry, rest.len());
372    let body = phone_apply_pattern(rest, pattern);
373    if trunk.is_empty() {
374        return body;
375    }
376    if rest.is_empty() {
377        return trunk.to_string();
378    }
379    let gap = if pattern.starts_with('#') { "" } else { " " };
380    format!("{trunk}{gap}{body}")
381}
382
383/// Validation status read from the national digit count against the pattern capacities.
384#[derive(Clone, Copy, Debug, PartialEq, Eq)]
385pub enum PhoneStatus {
386    Empty,
387    Incomplete,
388    Valid,
389    TooLong,
390}
391
392pub fn phone_status_of(entry: &PhoneCountry, digits: &str) -> PhoneStatus {
393    let length = phone_split_trunk(entry, digits).1.len();
394    let lengths = phone_lengths(entry);
395    if length == 0 {
396        return PhoneStatus::Empty;
397    }
398    if lengths.contains(&length) {
399        return PhoneStatus::Valid;
400    }
401    if length > lengths.iter().max().copied().unwrap_or(0) {
402        PhoneStatus::TooLong
403    } else {
404        PhoneStatus::Incomplete
405    }
406}
407
408/// E.164 encoding: `+<dial><national>` (empty when there are no national digits).
409pub fn phone_to_e164(entry: &PhoneCountry, digits: &str) -> String {
410    let rest = phone_split_trunk(entry, digits).1;
411    if rest.is_empty() {
412        String::new()
413    } else {
414        format!("+{}{}", entry.dial, rest)
415    }
416}
417
418/// Reads `"+44 (0)7911 123456"`, `"0044 7911…"`, or `"+14165550123"` into a country and
419/// national digits. Longest calling code wins; shared dials resolve through area codes.
420pub fn phone_parse_number(input: &str) -> Option<(&'static PhoneCountry, String)> {
421    let trimmed = input.trim();
422    let all_digits = phone_only_digits(trimmed);
423    let digits = if trimmed.starts_with('+') {
424        all_digits
425    } else if trimmed.starts_with("00") && all_digits.len() > 2 {
426        all_digits[2..].to_string()
427    } else {
428        return None;
429    };
430    for size in [3usize, 2, 1] {
431        if digits.len() < size {
432            continue;
433        }
434        let dial = &digits[..size];
435        let matches: Vec<&PhoneCountry> =
436            PHONE_COUNTRIES.iter().filter(|e| e.dial == dial).collect();
437        if matches.is_empty() {
438            continue;
439        }
440        let mut rest = digits[size..].to_string();
441        let entry = matches
442            .iter()
443            .find(|item| item.area_codes.iter().any(|code| rest.starts_with(code)))
444            .or_else(|| matches.iter().find(|item| item.area_codes.is_empty()))
445            .or_else(|| matches.first())
446            .copied()
447            .expect("matches is non-empty");
448        // "+44 (0)7911…" carries a trunk zero it should not; drop it when the rest is still a
449        // full number without it.
450        let min_len = phone_lengths(entry).into_iter().min().unwrap_or(0);
451        if !entry.trunk.is_empty()
452            && rest.starts_with(entry.trunk)
453            && rest.len() - entry.trunk.len() >= min_len
454        {
455            rest = rest[entry.trunk.len()..].to_string();
456        }
457        return Some((entry, phone_cap_digits(entry, &rest)));
458    }
459    None
460}
461
462/// Formats an E.164 number for display (`"+44 7911 123456"`); returns the input unreadable.
463pub fn phone_format_e164(e164: &str) -> String {
464    match phone_parse_number(e164) {
465        Some((entry, national)) => {
466            format!(
467                "+{} {}",
468                entry.dial,
469                phone_format_national(entry, &national)
470            )
471        }
472        None => e164.to_string(),
473    }
474}
475
476/// Picker search: digits match calling codes (either direction), letters match names/ISO codes.
477pub fn phone_matches_query(entry: &PhoneCountry, needle: &str) -> bool {
478    if needle.is_empty() {
479        return true;
480    }
481    let digits = phone_only_digits(needle);
482    let is_dial_query = !digits.is_empty()
483        && needle.chars().all(|c| {
484            c.is_ascii_digit() || c == '+' || c == ' ' || c == '(' || c == ')' || c == '-'
485        });
486    if is_dial_query {
487        return entry.dial.starts_with(&digits) || digits.starts_with(entry.dial);
488    }
489    if needle.chars().all(|c| c == '+') {
490        return true;
491    }
492    entry.name.to_lowercase().contains(needle) || entry.iso.to_lowercase() == needle
493}
494
495/// Country position in the name-sorted order, used to roll the flag toward the list move.
496fn phone_order_of(iso: &str) -> usize {
497    let mut sorted: Vec<&PhoneCountry> = PHONE_COUNTRIES.iter().collect();
498    sorted.sort_by_key(|entry| entry.name);
499    sorted
500        .iter()
501        .position(|entry| entry.iso == iso)
502        .unwrap_or(0)
503}
504
505/// Details snapshot passed alongside the E.164 value in [`PhoneValueEvent`].
506#[derive(Clone, Debug, PartialEq)]
507pub struct PhoneInputDetails {
508    pub country: &'static PhoneCountry,
509    pub formatted: String,
510    pub status: PhoneStatus,
511    pub valid: bool,
512}
513
514/// Single event for [`PhoneInput::on_value_change`]: the E.164 number (empty when there are no
515/// digits) plus its parsed details.
516#[derive(Clone, Debug, PartialEq)]
517pub struct PhoneValueEvent {
518    pub value: String,
519    pub details: PhoneInputDetails,
520}
521
522#[derive(Clone)]
523struct PhoneInternal {
524    uncontrolled_iso: SharedString,
525    digits: String,
526    seen_value: Option<String>,
527    source_changed_at_secs: f64,
528    roll_dir: i8,
529    menu_open: bool,
530    active_iso: Option<SharedString>,
531    highlight_seeded: bool,
532    control_hovered: bool,
533    trigger_hovered: bool,
534    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
535    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
536    control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
537    query_input: Entity<InputState>,
538    focus_handle: FocusHandle,
539}
540
541impl PhoneInternal {
542    fn new(now: f64, window: &mut Window, cx: &mut App) -> Self {
543        let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Country or code"));
544        Self {
545            uncontrolled_iso: "US".into(),
546            digits: String::new(),
547            seen_value: None,
548            source_changed_at_secs: now - 10.0,
549            roll_dir: 1,
550            menu_open: false,
551            active_iso: None,
552            highlight_seeded: false,
553            control_hovered: false,
554            trigger_hovered: false,
555            trigger_bounds: Rc::new(RefCell::new(None)),
556            panel_bounds: Rc::new(RefCell::new(None)),
557            control_bounds: Rc::new(RefCell::new(None)),
558            query_input,
559            focus_handle: cx.focus_handle(),
560        }
561    }
562}
563
564fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
565    let rad = angle_deg.to_radians();
566    let cos_a = rad.cos();
567    let sin_a = rad.sin();
568    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
569    let mut builder = PathBuilder::stroke(px(1.75));
570    for (i, (lx, ly)) in pts.iter().enumerate() {
571        let rx = cx + lx * cos_a - ly * sin_a;
572        let ry = cy + lx * sin_a + ly * cos_a;
573        let p = point(px(rx), px(ry));
574        if i == 0 {
575            builder.move_to(p);
576        } else {
577            builder.line_to(p);
578        }
579    }
580    if let Ok(path) = builder.build() {
581        window.paint_path(path, color);
582    }
583}
584
585fn paint_scaled_check(
586    cx: f32,
587    cy: f32,
588    scale: f32,
589    opacity: f32,
590    color: Hsla,
591    window: &mut Window,
592) {
593    if opacity <= 0.01 {
594        return;
595    }
596    let pts = [(-4.0_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
597    let mut builder = PathBuilder::stroke(px(2.0));
598    for (i, (lx, ly)) in pts.iter().enumerate() {
599        let p = point(px(cx + lx * scale), px(cy + ly * scale));
600        if i == 0 {
601            builder.move_to(p);
602        } else {
603            builder.line_to(p);
604        }
605    }
606    let c = Hsla {
607        a: color.a * opacity.clamp(0.0, 1.0),
608        ..color
609    };
610    if let Ok(path) = builder.build() {
611        window.paint_path(path, c);
612    }
613}
614
615/// Arc `PhoneInput` — phone field with a morphing country picker, live formatting with a faint
616/// shape guide, and E.164 output.
617#[derive(IntoElement)]
618pub struct PhoneInput {
619    id: ElementId,
620    label: SharedString,
621    hide_label: bool,
622    value: Option<String>,
623    default_value: Option<String>,
624    country: Option<SharedString>,
625    default_country: SharedString,
626    countries: Vec<SharedString>,
627    preferred_countries: Vec<SharedString>,
628    description: Option<SharedString>,
629    error: Option<SharedString>,
630    validate: bool,
631    disabled: bool,
632    width: Option<Pixels>,
633    on_value_change: Option<PhoneValueChangeHandler>,
634    on_country_change: Option<PhoneCountryChangeHandler>,
635}
636
637impl PhoneInput {
638    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
639        Self {
640            id: id.into(),
641            label: label.into(),
642            hide_label: false,
643            value: None,
644            default_value: None,
645            country: None,
646            default_country: "US".into(),
647            countries: Vec::new(),
648            preferred_countries: vec!["US".into(), "CA".into(), "GB".into()],
649            description: None,
650            error: None,
651            validate: true,
652            disabled: false,
653            width: None,
654            on_value_change: None,
655            on_country_change: None,
656        }
657    }
658
659    pub fn hide_label(mut self, hide: bool) -> Self {
660        self.hide_label = hide;
661        self
662    }
663
664    /// The number in E.164 (`"+14155550132"`); an empty string clears the field.
665    pub fn value(mut self, e164: impl Into<String>) -> Self {
666        self.value = Some(e164.into());
667        self
668    }
669
670    pub fn default_value(mut self, e164: impl Into<String>) -> Self {
671        self.default_value = Some(e164.into());
672        self
673    }
674
675    pub fn country(mut self, iso: impl Into<SharedString>) -> Self {
676        self.country = Some(iso.into());
677        self
678    }
679
680    pub fn default_country(mut self, iso: impl Into<SharedString>) -> Self {
681        self.default_country = iso.into();
682        self
683    }
684
685    /// Limits the picker to these ISO codes (empty keeps the full table).
686    pub fn countries<I, S>(mut self, codes: I) -> Self
687    where
688        I: IntoIterator<Item = S>,
689        S: Into<SharedString>,
690    {
691        self.countries = codes.into_iter().map(Into::into).collect();
692        self
693    }
694
695    /// Pinned at the top of the picker under "Suggested".
696    pub fn preferred_countries<I, S>(mut self, codes: I) -> Self
697    where
698        I: IntoIterator<Item = S>,
699        S: Into<SharedString>,
700    {
701        self.preferred_countries = codes.into_iter().map(Into::into).collect();
702        self
703    }
704
705    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
706        self.description = Some(description.into());
707        self
708    }
709
710    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
711        self.error = Some(error.into());
712        self
713    }
714
715    pub fn validate(mut self, validate: bool) -> Self {
716        self.validate = validate;
717        self
718    }
719
720    pub fn disabled(mut self, disabled: bool) -> Self {
721        self.disabled = disabled;
722        self
723    }
724
725    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
726        self.width = Some(width.into());
727        self
728    }
729
730    pub fn on_value_change(
731        mut self,
732        handler: impl Fn(&PhoneValueEvent, &mut Window, &mut App) + 'static,
733    ) -> Self {
734        self.on_value_change = Some(Rc::new(handler));
735        self
736    }
737
738    pub fn on_country_change(
739        mut self,
740        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
741    ) -> Self {
742        self.on_country_change = Some(Rc::new(handler));
743        self
744    }
745}
746
747fn build_phone_details(entry: &'static PhoneCountry, digits: &str) -> PhoneInputDetails {
748    let status = phone_status_of(entry, digits);
749    PhoneInputDetails {
750        country: entry,
751        formatted: phone_format_national(entry, digits),
752        status,
753        valid: status == PhoneStatus::Valid,
754    }
755}
756
757fn phone_pool(countries: &[SharedString]) -> Vec<&'static PhoneCountry> {
758    if countries.is_empty() {
759        PHONE_COUNTRIES.iter().collect()
760    } else {
761        PHONE_COUNTRIES
762            .iter()
763            .filter(|entry| countries.iter().any(|c| c.as_ref() == entry.iso))
764            .collect()
765    }
766}
767
768impl RenderOnce for PhoneInput {
769    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
770        let theme = cx.arc_theme().clone();
771        let colors = theme.colors;
772        let motion = theme.motion;
773        let reduced = is_reduced_motion(cx);
774        let now = motion_now(cx);
775
776        let pool = phone_pool(&self.countries);
777        let default_entry = phone_country_by_iso(&self.default_country)
778            .or_else(|| pool.first().copied())
779            .unwrap_or(&PHONE_COUNTRIES[0]);
780
781        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-phone-state".into());
782        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
783            // Seed from a controlled or default international value when it parses.
784            let seed = self
785                .value
786                .clone()
787                .or_else(|| self.default_value.clone())
788                .unwrap_or_default();
789            let (iso, digits) = if seed.is_empty() {
790                (default_entry.iso.to_string(), String::new())
791            } else {
792                match phone_parse_number(&seed) {
793                    Some((entry, national)) => (entry.iso.to_string(), national),
794                    None => (default_entry.iso.to_string(), String::new()),
795                }
796            };
797            PhoneInternal {
798                uncontrolled_iso: iso.into(),
799                digits,
800                seen_value: self.value.clone(),
801                ..PhoneInternal::new(now, window, cx)
802            }
803        });
804
805        // Sync a controlled external value that differs from what the field last produced.
806        if self.value != internal.read(cx).seen_value {
807            let seen = self.value.clone();
808            internal.update(cx, |s, _| {
809                s.seen_value = seen.clone();
810                if let Some(ext) = seen {
811                    let cur_e164 = {
812                        let iso = s.uncontrolled_iso.clone();
813                        let entry = phone_country_by_iso(&iso).unwrap_or(default_entry);
814                        phone_to_e164(entry, &s.digits)
815                    };
816                    if ext != cur_e164 {
817                        if let Some((entry, national)) = phone_parse_number(&ext) {
818                            s.uncontrolled_iso = entry.iso.into();
819                            s.digits = national;
820                        } else {
821                            s.digits = String::new();
822                        }
823                        s.source_changed_at_secs = now;
824                    }
825                }
826            });
827        }
828
829        let iso = self
830            .country
831            .clone()
832            .unwrap_or_else(|| internal.read(cx).uncontrolled_iso.clone());
833        let current = phone_country_by_iso(&iso).unwrap_or(default_entry);
834        let snap = internal.read(cx).clone();
835        let digits = snap.digits.clone();
836        let formatted = phone_format_national(current, &digits);
837        let status = phone_status_of(current, &digits);
838
839        // The guide: the rest of the example number, in this country's shape, drawn faintly
840        // after what was typed.
841        let guide = {
842            let (trunk, rest) = phone_split_trunk(current, &digits);
843            if rest.len() >= current.example.len() {
844                String::new()
845            } else {
846                let filled = format!("{trunk}{}{}", rest, &current.example[rest.len()..]);
847                let full = phone_format_national(current, &filled);
848                if full.starts_with(&formatted) {
849                    full[formatted.len()..].to_string()
850                } else {
851                    String::new()
852                }
853            }
854        };
855
856        // Built-in validation message while unfocused (see deviation note).
857        let is_focused = snap.focus_handle.is_focused(window);
858        let lengths = phone_lengths(current);
859        let length_copy = if lengths.len() == 1 {
860            format!("{}", lengths[0])
861        } else {
862            let heads: Vec<String> = lengths[..lengths.len() - 1]
863                .iter()
864                .map(|l| l.to_string())
865                .collect();
866            format!("{} or {}", heads.join(", "), lengths[lengths.len() - 1])
867        };
868        let built_in_error: Option<SharedString> = if self.validate
869            && !is_focused
870            && !digits.is_empty()
871            && matches!(status, PhoneStatus::Incomplete | PhoneStatus::TooLong)
872        {
873            Some(SharedString::from(format!(
874                "Numbers in {} have {} digits",
875                current.name, length_copy
876            )))
877        } else {
878            None
879        };
880        let effective_error = self.error.clone().or(built_in_error);
881        let is_invalid = effective_error.is_some();
882
883        let control_border = if is_invalid {
884            colors.danger
885        } else if !self.disabled && is_focused {
886            colors.foreground
887        } else {
888            colors.border_strong
889        };
890
891        // Country picker search sections.
892        let needle = snap.query_input.read(cx).value().trim().to_lowercase();
893        let mut sorted: Vec<&PhoneCountry> = pool.clone();
894        sorted.sort_by_key(|entry| entry.name);
895        let sections: Vec<(&'static str, Option<&'static str>, Vec<&PhoneCountry>)> =
896            if !needle.is_empty() && needle != "+" {
897                let mut hits: Vec<&PhoneCountry> = sorted
898                    .iter()
899                    .copied()
900                    .filter(|entry| phone_matches_query(entry, &needle))
901                    .collect();
902                let digits_only = phone_only_digits(&needle);
903                if !digits_only.is_empty() {
904                    hits.sort_by_key(|entry| {
905                        (
906                            std::cmp::Reverse(entry.dial == digits_only),
907                            entry.dial.len(),
908                        )
909                    });
910                }
911                vec![("results", None, hits)]
912            } else {
913                let preferred: Vec<&PhoneCountry> = self
914                    .preferred_countries
915                    .iter()
916                    .filter_map(|code| {
917                        pool.iter()
918                            .find(|entry| entry.iso == code.as_ref())
919                            .copied()
920                    })
921                    .collect();
922                if preferred.is_empty() {
923                    vec![("all", None, sorted.clone())]
924                } else {
925                    vec![
926                        ("preferred", Some("Suggested"), preferred),
927                        ("all", Some("All countries"), sorted.clone()),
928                    ]
929                }
930            };
931        let rows: Vec<&PhoneCountry> = sections
932            .iter()
933            .flat_map(|(_, _, r)| r.iter().copied())
934            .collect();
935        let active_iso = snap
936            .active_iso
937            .clone()
938            .filter(|a| rows.iter().any(|r| r.iso == a.as_ref()))
939            .or_else(|| rows.first().map(|r| SharedString::from(r.iso)));
940
941        let menu_open = snap.menu_open && !self.disabled;
942
943        // Flag-and-dial roll when the country changed (upstream layerVariants: ±0.6em roll with
944        // a soft blur sharpen).
945        let src_elapsed = (now - snap.source_changed_at_secs).max(0.0);
946        let (flag_op, flag_y) = if src_elapsed >= 0.22 {
947            (1.0_f32, 0.0_f32)
948        } else {
949            window.request_animation_frame();
950            let t = (src_elapsed / 0.20).clamp(0.0, 1.0) as f32;
951            let e = if reduced {
952                t
953            } else {
954                CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
955            };
956            let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
957            let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
958            let y = if reduced {
959                0.0
960            } else {
961                (snap.roll_dir as f32) * 0.6 * 17.0 * (1.0 - e)
962            };
963            (op, y)
964        };
965
966        // Chevron rotation (`GLIDE = physical(0.28, 0)`).
967        let glide_spec = phone_glide_spring();
968        let chevron_deg = if reduced {
969            if menu_open { 180.0 } else { 0.0 }
970        } else {
971            arc_spring(
972                (self.id.clone(), "chevron-deg"),
973                if menu_open { 180.0 } else { 0.0 },
974                glide_spec,
975                window,
976                cx,
977            )
978        };
979
980        // Panel presence (`fast` 160ms enter / `instant` 120ms exit) + width/height/radius morph.
981        let panel_presence = ArcPresence::new((self.id.clone(), "panel-presence"), menu_open)
982            .animate_initial(false)
983            .config(ArcPresenceConfig {
984                enter_duration: motion.duration.fast,
985                exit_duration: motion.duration.instant,
986                enter_ease: motion.ease.enter,
987                exit_ease: motion.ease.standard,
988                fade_on_reduced_motion: true,
989            })
990            .sample(window, cx);
991        let panel_p = panel_presence.progress.clamp(0.0, 1.0);
992
993        let trigger_w = snap
994            .trigger_bounds
995            .borrow()
996            .map(|b| f32::from(b.size.width))
997            .unwrap_or(72.0);
998        let panel_target_w = trigger_w.max(PHONE_PANEL_MAX);
999        let grow_spec = phone_grow_spring();
1000        let width_spec = phone_width_spring();
1001        let panel_rendering = panel_presence.should_render();
1002        let (panel_w, panel_r) = if reduced || !panel_rendering {
1003            (
1004                if panel_rendering {
1005                    panel_target_w
1006                } else {
1007                    trigger_w
1008                },
1009                if panel_rendering {
1010                    PHONE_OPEN_RADIUS
1011                } else {
1012                    PHONE_CLOSED_RADIUS
1013                },
1014            )
1015        } else {
1016            let w = arc_spring_with_options(
1017                (self.id.clone(), "panel-w"),
1018                panel_target_w,
1019                SpringOptions::new(width_spec).with_initial_value(trigger_w),
1020                window,
1021                cx,
1022            )
1023            .value;
1024            let r = arc_spring(
1025                (self.id.clone(), "panel-r"),
1026                PHONE_OPEN_RADIUS,
1027                grow_spec,
1028                window,
1029                cx,
1030            );
1031            (w, r)
1032        };
1033
1034        let show_check = status == PhoneStatus::Valid;
1035        let check_scale = if reduced {
1036            if show_check { 1.0 } else { 0.6 }
1037        } else {
1038            arc_spring(
1039                (self.id.clone(), "check-sc"),
1040                if show_check { 1.0 } else { 0.6 },
1041                motion.spring.snappy,
1042                window,
1043                cx,
1044            )
1045        };
1046        let check_op = arc_transition(
1047            (self.id.clone(), "check-op"),
1048            if show_check { 1.0 } else { 0.0 },
1049            if reduced {
1050                std::time::Duration::ZERO
1051            } else {
1052                motion.duration.fast
1053            },
1054            motion.ease.standard,
1055            window,
1056            cx,
1057        );
1058
1059        let highlight_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
1060        let guide_color = oklab_mix(colors.text_muted, colors.surface, 0.72);
1061
1062        // ── Panel content ─────────────────────────────────────────────────────────────────────
1063        let mut section_els: Vec<AnyElement> = Vec::new();
1064        for (section_key, label, rows_in_section) in &sections {
1065            let mut rows_el: Vec<AnyElement> = Vec::new();
1066            for entry in rows_in_section {
1067                let row_key = format!("{section_key}-{}", entry.iso);
1068                let is_selected = entry.iso == current.iso;
1069                let is_active = active_iso.as_ref().is_some_and(|a| a.as_ref() == entry.iso);
1070                let check_op_row = arc_transition(
1071                    (self.id.clone(), format!("ph-chk-op-{}", entry.iso)),
1072                    if is_selected { 1.0 } else { 0.0 },
1073                    if reduced {
1074                        std::time::Duration::ZERO
1075                    } else {
1076                        motion.duration.fast
1077                    },
1078                    motion.ease.standard,
1079                    window,
1080                    cx,
1081                );
1082                let check_scale_row = if reduced {
1083                    if is_selected { 1.0 } else { 0.6 }
1084                } else {
1085                    arc_spring(
1086                        (self.id.clone(), format!("ph-chk-sc-{}", entry.iso)),
1087                        if is_selected { 1.0 } else { 0.6 },
1088                        glide_spec,
1089                        window,
1090                        cx,
1091                    )
1092                };
1093                let row_fg = if is_active || is_selected {
1094                    colors.foreground
1095                } else {
1096                    colors.text_secondary
1097                };
1098                let entry_clone = *entry;
1099                let int_hover = internal.clone();
1100                let iso_hover = SharedString::from(entry.iso);
1101                let int_pick = internal.clone();
1102                let on_v_pick = self.on_value_change.clone();
1103                let on_c_pick = self.on_country_change.clone();
1104                rows_el.push(
1105                    div()
1106                        .id(ElementId::NamedChild(
1107                            self.id.clone().into(),
1108                            SharedString::from(format!("country-{row_key}")),
1109                        ))
1110                        .test_support()
1111                        .role(Role::ListBoxOption)
1112                        .aria_label(SharedString::from(format!(
1113                            "{} +{}",
1114                            entry.name, entry.dial
1115                        )))
1116                        .w_full()
1117                        .flex_none()
1118                        .h(px(36.0))
1119                        .min_h(px(36.0))
1120                        .px(px(10.0))
1121                        .flex()
1122                        .flex_row()
1123                        .items_center()
1124                        .gap(px(10.0))
1125                        .rounded(px(6.0))
1126                        .text_size(Typography::TEXT_SM)
1127                        .text_color(row_fg)
1128                        .cursor_pointer()
1129                        .on_hover(move |hovered, window, cx| {
1130                            if *hovered {
1131                                int_hover.update(cx, |s, _| {
1132                                    s.active_iso = Some(iso_hover.clone());
1133                                });
1134                                window.refresh();
1135                            }
1136                        })
1137                        .on_click(move |_, window, cx| {
1138                            let entry = entry_clone;
1139                            let t_now = motion_now(cx);
1140                            let (cur_digits, cur_iso, q_in) = {
1141                                let s = int_pick.read(cx);
1142                                (
1143                                    s.digits.clone(),
1144                                    s.uncontrolled_iso.clone(),
1145                                    s.query_input.clone(),
1146                                )
1147                            };
1148                            let changed = entry.iso != cur_iso.as_ref();
1149                            let next_digits = phone_cap_digits(entry, &cur_digits);
1150                            let ev = PhoneValueEvent {
1151                                value: phone_to_e164(entry, &next_digits),
1152                                details: build_phone_details(entry, &next_digits),
1153                            };
1154                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
1155                            int_pick.update(cx, |s, _| {
1156                                s.menu_open = false;
1157                                s.highlight_seeded = false;
1158                                s.active_iso = None;
1159                                if changed {
1160                                    s.roll_dir = (phone_order_of(entry.iso) as i64
1161                                        - phone_order_of(cur_iso.as_ref()) as i64)
1162                                        .signum()
1163                                        as i8;
1164                                    s.source_changed_at_secs = t_now;
1165                                    s.uncontrolled_iso = entry.iso.into();
1166                                }
1167                                s.digits = next_digits;
1168                            });
1169                            if changed && let Some(cb) = &on_c_pick {
1170                                cb(&SharedString::from(entry.iso), window, cx);
1171                            }
1172                            if let Some(cb) = &on_v_pick {
1173                                cb(&ev, window, cx);
1174                            }
1175                            window.refresh();
1176                        })
1177                        .child(
1178                            div()
1179                                .w(px(20.0))
1180                                .flex_none()
1181                                .text_size(px(15.0))
1182                                .child(SharedString::from(phone_flag_of(entry.iso))),
1183                        )
1184                        .child(
1185                            div()
1186                                .flex_1()
1187                                .min_w_0()
1188                                .font_medium()
1189                                .truncate()
1190                                .child(SharedString::from(entry.name)),
1191                        )
1192                        .child(
1193                            div()
1194                                .flex_none()
1195                                .text_size(Typography::TEXT_XS)
1196                                .text_color(colors.text_muted)
1197                                .child(SharedString::from(format!("+{}", entry.dial))),
1198                        )
1199                        .child(
1200                            div().size(px(16.0)).flex_none().child(
1201                                canvas(
1202                                    |_, _, _| {},
1203                                    move |rect, _, window, _| {
1204                                        let cx_pt =
1205                                            f32::from(rect.origin.x + rect.size.width * 0.5);
1206                                        let cy_pt =
1207                                            f32::from(rect.origin.y + rect.size.height * 0.5);
1208                                        paint_scaled_check(
1209                                            cx_pt,
1210                                            cy_pt,
1211                                            check_scale_row,
1212                                            check_op_row,
1213                                            colors.foreground,
1214                                            window,
1215                                        );
1216                                    },
1217                                )
1218                                .size_full(),
1219                            ),
1220                        )
1221                        .into_any_element(),
1222                );
1223            }
1224            let group_el = if let Some(label_text) = label {
1225                div()
1226                    .flex_none()
1227                    .w_full()
1228                    .flex()
1229                    .flex_col()
1230                    .gap(px(2.0))
1231                    .child(
1232                        div()
1233                            .flex_none()
1234                            .pt(px(8.0))
1235                            .px(px(10.0))
1236                            .pb(px(4.0))
1237                            .text_size(Typography::TEXT_XS)
1238                            .text_color(colors.text_muted)
1239                            .child(SharedString::from(*label_text)),
1240                    )
1241                    .children(rows_el)
1242                    .into_any_element()
1243            } else {
1244                div()
1245                    .flex_none()
1246                    .w_full()
1247                    .flex()
1248                    .flex_col()
1249                    .gap(px(2.0))
1250                    .children(rows_el)
1251                    .into_any_element()
1252            };
1253            section_els.push(group_el);
1254        }
1255
1256        let empty_el = if rows.is_empty() {
1257            Some(
1258                div()
1259                    .px(px(10.0))
1260                    .pt(px(12.0))
1261                    .pb(px(14.0))
1262                    .text_size(Typography::TEXT_SM)
1263                    .text_color(colors.text_muted)
1264                    .child(SharedString::from(format!(
1265                        "No countries match \u{201c}{}\u{201d}",
1266                        needle.trim()
1267                    ))),
1268            )
1269        } else {
1270            None
1271        };
1272
1273        // Highlight pill position (glide spring; seeded on first render). Rows stride 38px
1274        // (36px row + 2px gap); group labels shift the stride by 26px each (24px header + 2px gap).
1275        let target_hy = {
1276            let mut cur_y = 6.0_f32;
1277            let mut found_y = 6.0_f32;
1278            let mut found = false;
1279            for (sec_idx, (_, label, rows_in_section)) in sections.iter().enumerate() {
1280                if sec_idx > 0 {
1281                    cur_y += 2.0;
1282                }
1283                if label.is_some() {
1284                    cur_y += 24.0 + 2.0;
1285                }
1286                for (row_idx, entry) in rows_in_section.iter().enumerate() {
1287                    if row_idx > 0 {
1288                        cur_y += 2.0;
1289                    }
1290                    if !found && active_iso.as_ref().is_some_and(|a| a.as_ref() == entry.iso) {
1291                        found_y = cur_y;
1292                        found = true;
1293                    }
1294                    cur_y += 36.0;
1295                }
1296            }
1297            found_y
1298        };
1299        let pill_y = if reduced || !snap.highlight_seeded {
1300            let _ = arc_spring_with_options(
1301                (self.id.clone(), "hi-y"),
1302                target_hy,
1303                SpringOptions::new(glide_spec).with_initial_value(target_hy),
1304                window,
1305                cx,
1306            );
1307            if menu_open && !snap.highlight_seeded {
1308                internal.update(cx, |s, _| s.highlight_seeded = true);
1309            }
1310            target_hy
1311        } else {
1312            arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx)
1313        };
1314
1315        // ── Overlay panel ─────────────────────────────────────────────────────────────────────
1316        let int_close = internal.clone();
1317        let control_bounds_ref = snap.control_bounds.clone();
1318        let panel_bounds_ref_out = snap.panel_bounds.clone();
1319        let panel_el = if panel_rendering {
1320            let search_input = KitInput::new(&snap.query_input)
1321                .appearance(false)
1322                .w_full()
1323                .text_size(Typography::TEXT_SM);
1324            let int_clear = internal.clone();
1325            Some(
1326                deferred(
1327                    div()
1328                        .id(ElementId::NamedChild(
1329                            self.id.clone().into(),
1330                            "country-panel".into(),
1331                        ))
1332                        .test_support()
1333                        .role(Role::ListBox)
1334                        .absolute()
1335                        .left_0()
1336                        .top_full()
1337                        .overflow_hidden()
1338                        .w(px(panel_w))
1339                        .rounded(px(panel_r))
1340                        .border_1()
1341                        .border_color(colors.border)
1342                        .bg(colors.surface_raised)
1343                        .shadow(Shadows::floating(theme.mode))
1344                        .opacity(panel_p)
1345                        .on_key_down({
1346                            let int_key = internal.clone();
1347                            let rows_for_key = rows.clone();
1348                            let on_v_key = self.on_value_change.clone();
1349                            let on_c_key = self.on_country_change.clone();
1350                            move |event: &KeyDownEvent, window, cx| {
1351                                if !int_key.read(cx).menu_open {
1352                                    return;
1353                                }
1354                                let cur_active = int_key.read(cx).active_iso.clone();
1355                                let at = cur_active
1356                                    .as_ref()
1357                                    .and_then(|a| {
1358                                        rows_for_key.iter().position(|r| r.iso == a.as_ref())
1359                                    })
1360                                    .unwrap_or(0);
1361                                match event.keystroke.key.as_str() {
1362                                    "escape" => {
1363                                        let q_in = int_key.read(cx).query_input.clone();
1364                                        q_in.update(cx, |s, cx| s.set_value("", window, cx));
1365                                        int_key.update(cx, |s, _| {
1366                                            s.menu_open = false;
1367                                            s.highlight_seeded = false;
1368                                            s.active_iso = None;
1369                                        });
1370                                        window.refresh();
1371                                    }
1372                                    "down" | "arrowdown" => {
1373                                        let idx = (at + 1).min(rows_for_key.len() - 1);
1374                                        if let Some(next) = rows_for_key.get(idx) {
1375                                            int_key.update(cx, |s, _| {
1376                                                s.active_iso = Some(SharedString::from(next.iso));
1377                                            });
1378                                            window.refresh();
1379                                        }
1380                                    }
1381                                    "up" | "arrowup" => {
1382                                        if let Some(prev) = rows_for_key.get(at.saturating_sub(1)) {
1383                                            int_key.update(cx, |s, _| {
1384                                                s.active_iso = Some(SharedString::from(prev.iso));
1385                                            });
1386                                            window.refresh();
1387                                        }
1388                                    }
1389                                    "pageup" => {
1390                                        if let Some(prev) =
1391                                            rows_for_key.get(at.saturating_sub(PHONE_PAGE))
1392                                        {
1393                                            int_key.update(cx, |s, _| {
1394                                                s.active_iso = Some(SharedString::from(prev.iso));
1395                                            });
1396                                            window.refresh();
1397                                        }
1398                                    }
1399                                    "pagedown" => {
1400                                        let idx = (at + PHONE_PAGE).min(rows_for_key.len() - 1);
1401                                        if let Some(next) = rows_for_key.get(idx) {
1402                                            int_key.update(cx, |s, _| {
1403                                                s.active_iso = Some(SharedString::from(next.iso));
1404                                            });
1405                                            window.refresh();
1406                                        }
1407                                    }
1408                                    "enter" => {
1409                                        if let Some(entry) = rows_for_key.get(at).copied() {
1410                                            let t_now = motion_now(cx);
1411                                            let (cur_digits, cur_iso, q_in) = {
1412                                                let s = int_key.read(cx);
1413                                                (
1414                                                    s.digits.clone(),
1415                                                    s.uncontrolled_iso.clone(),
1416                                                    s.query_input.clone(),
1417                                                )
1418                                            };
1419                                            let changed = entry.iso != cur_iso.as_ref();
1420                                            let next_digits = phone_cap_digits(entry, &cur_digits);
1421                                            let ev = PhoneValueEvent {
1422                                                value: phone_to_e164(entry, &next_digits),
1423                                                details: build_phone_details(entry, &next_digits),
1424                                            };
1425                                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
1426                                            int_key.update(cx, |s, _| {
1427                                                s.menu_open = false;
1428                                                s.highlight_seeded = false;
1429                                                s.active_iso = None;
1430                                                if changed {
1431                                                    s.roll_dir = (phone_order_of(entry.iso) as i64
1432                                                        - phone_order_of(cur_iso.as_ref()) as i64)
1433                                                        .signum()
1434                                                        as i8;
1435                                                    s.source_changed_at_secs = t_now;
1436                                                    s.uncontrolled_iso = entry.iso.into();
1437                                                }
1438                                                s.digits = next_digits;
1439                                            });
1440                                            if changed && let Some(cb) = &on_c_key {
1441                                                cb(&SharedString::from(entry.iso), window, cx);
1442                                            }
1443                                            if let Some(cb) = &on_v_key {
1444                                                cb(&ev, window, cx);
1445                                            }
1446                                            window.refresh();
1447                                        }
1448                                    }
1449                                    _ => {}
1450                                }
1451                            }
1452                        })
1453                        .child(
1454                            div()
1455                                .relative()
1456                                .h(ControlHeights::MD)
1457                                .flex()
1458                                .flex_row()
1459                                .items_center()
1460                                .gap(Spacing::S2)
1461                                .pl(px(13.0))
1462                                .pr(px(2.0))
1463                                .child(
1464                                    Icon::new(IconName::Search)
1465                                        .text_size(px(16.0))
1466                                        .text_color(colors.text_muted),
1467                                )
1468                                .child(
1469                                    div()
1470                                        .flex_1()
1471                                        .min_w_0()
1472                                        .text_color(colors.foreground)
1473                                        .child(search_input),
1474                                )
1475                                .when(!needle.is_empty(), |this| {
1476                                    this.child(
1477                                        BaseButton::new(ElementId::NamedChild(
1478                                            self.id.clone().into(),
1479                                            "clear-search".into(),
1480                                        ))
1481                                        .accessibility_label("Clear search")
1482                                        .on_click(move |_, window, cx| {
1483                                            let q_in = int_clear.read(cx).query_input.clone();
1484                                            q_in.update(cx, |s, cx| {
1485                                                s.set_value("", window, cx);
1486                                                s.focus(window, cx);
1487                                            });
1488                                            window.refresh();
1489                                        })
1490                                        .size(px(24.0))
1491                                        .flex()
1492                                        .items_center()
1493                                        .justify_center()
1494                                        .rounded(Radii::PILL)
1495                                        .bg(highlight_bg)
1496                                        .text_color(colors.text_secondary)
1497                                        .cursor_pointer()
1498                                        .child(Icon::new(IconName::Close).text_size(px(14.0))),
1499                                    )
1500                                }),
1501                        )
1502                        .child(div().mx(px(14.0)).h(px(1.0)).bg(colors.border))
1503                        .child(
1504                            div()
1505                                .flex_none()
1506                                .flex()
1507                                .flex_col()
1508                                .px(px(6.0))
1509                                .pb(px(6.0))
1510                                .child(
1511                                    div()
1512                                        .id(ElementId::NamedChild(
1513                                            self.id.clone().into(),
1514                                            "country-scroll".into(),
1515                                        ))
1516                                        .test_support()
1517                                        .relative()
1518                                        .w_full()
1519                                        .pt(px(6.0))
1520                                        .h(px(PHONE_LIST_MAX_H))
1521                                        .max_h(px(PHONE_LIST_MAX_H))
1522                                        .overflow_y_scroll()
1523                                        .on_scroll(|_, _, cx| cx.stop_propagation())
1524                                        .flex()
1525                                        .flex_col()
1526                                        .gap(px(2.0))
1527                                        .child(
1528                                            div()
1529                                                .absolute()
1530                                                .left_0()
1531                                                .right_0()
1532                                                .top(px(pill_y))
1533                                                .h(px(36.0))
1534                                                .rounded(px(6.0))
1535                                                .bg(highlight_bg),
1536                                        )
1537                                        .children(section_els)
1538                                        .children(empty_el),
1539                                ),
1540                        )
1541                        .child(
1542                            canvas(
1543                                {
1544                                    let probe = panel_bounds_ref_out.clone();
1545                                    move |rect, _, _| {
1546                                        *probe.borrow_mut() = Some(rect);
1547                                    }
1548                                },
1549                                |_, _, _, _| {},
1550                            )
1551                            .absolute()
1552                            .inset_0(),
1553                        )
1554                        .child(canvas(
1555                            |_, _, _| {},
1556                            move |_, _, window, _| {
1557                                // Dismiss on outside pointer down (window-level, like money-input).
1558                                let c_ref = control_bounds_ref.clone();
1559                                let p_ref = panel_bounds_ref_out.clone();
1560                                let st = int_close.clone();
1561                                window.on_mouse_event(
1562                                    move |event: &MouseDownEvent, phase, window, cx| {
1563                                        if !phase.bubble() {
1564                                            return;
1565                                        }
1566                                        let in_ctrl = c_ref
1567                                            .borrow()
1568                                            .is_some_and(|b| b.contains(&event.position));
1569                                        let in_panel = p_ref
1570                                            .borrow()
1571                                            .is_some_and(|b| b.contains(&event.position));
1572                                        if !in_ctrl && !in_panel {
1573                                            st.update(cx, |s, _| {
1574                                                s.menu_open = false;
1575                                                s.highlight_seeded = false;
1576                                                s.active_iso = None;
1577                                            });
1578                                            window.refresh();
1579                                        }
1580                                    },
1581                                );
1582                            },
1583                        )),
1584                )
1585                .with_priority(25),
1586            )
1587        } else {
1588            None
1589        };
1590
1591        // ── Number key handling (append model, see deviation note) ────────────────────────────
1592        let int_key = internal.clone();
1593        let on_v_change_key = self.on_value_change.clone();
1594        let on_c_change_key = self.on_country_change.clone();
1595        let disabled_key = self.disabled;
1596        let focus_handle_key = snap.focus_handle.clone();
1597        let focus_for_wrap = snap.focus_handle.clone();
1598
1599        let control = div()
1600            .id(ElementId::NamedChild(
1601                self.id.clone().into(),
1602                "control".into(),
1603            ))
1604            .test_support()
1605            .role(Role::Group)
1606            .track_focus(&focus_handle_key)
1607            .on_hover({
1608                let int_h = internal.clone();
1609                move |hovered, window, cx| {
1610                    int_h.update(cx, |s, _| s.control_hovered = *hovered);
1611                    window.refresh();
1612                }
1613            })
1614            .on_key_down(move |event: &KeyDownEvent, window, cx| {
1615                if disabled_key || int_key.read(cx).menu_open {
1616                    return;
1617                }
1618                let key = event.keystroke.key.as_str();
1619                let ctrl_or_platform =
1620                    event.keystroke.modifiers.control || event.keystroke.modifiers.platform;
1621                let t_now = motion_now(cx);
1622                if key == "+" && !ctrl_or_platform {
1623                    int_key.update(cx, |s, _| {
1624                        s.menu_open = true;
1625                        s.highlight_seeded = false;
1626                    });
1627                    let q_in = int_key.read(cx).query_input.clone();
1628                    q_in.update(cx, |s, cx| {
1629                        s.set_value("+", window, cx);
1630                        s.focus(window, cx);
1631                    });
1632                    window.refresh();
1633                    return;
1634                }
1635                if ctrl_or_platform && key == "v" {
1636                    let pasted = cx
1637                        .read_from_clipboard()
1638                        .and_then(|item| item.text())
1639                        .unwrap_or_default();
1640                    let entry = current;
1641                    let parsed = if pasted.trim_start().starts_with('+')
1642                        || pasted.trim_start().starts_with("00")
1643                    {
1644                        phone_parse_number(&pasted)
1645                    } else {
1646                        None
1647                    };
1648                    let (entry, next_digits) = match parsed {
1649                        Some((entry, national)) if !national.is_empty() => (entry, national),
1650                        _ => {
1651                            let mut fragment = phone_only_digits(&pasted);
1652                            let cap_len = phone_cap_digits(entry, &fragment).len();
1653                            // "1 415 555 0132" into a US field: the leading calling code is
1654                            // dropped when the number would not fit otherwise.
1655                            if fragment.starts_with(entry.dial) && fragment.len() > cap_len {
1656                                fragment = fragment[entry.dial.len()..].to_string();
1657                            }
1658                            (entry, phone_cap_digits(entry, &fragment))
1659                        }
1660                    };
1661                    let changed_iso = entry.iso != current.iso;
1662                    let ev = PhoneValueEvent {
1663                        value: phone_to_e164(entry, &next_digits),
1664                        details: build_phone_details(entry, &next_digits),
1665                    };
1666                    int_key.update(cx, |s, _| {
1667                        if changed_iso {
1668                            s.roll_dir = (phone_order_of(entry.iso) as i64
1669                                - phone_order_of(current.iso) as i64)
1670                                .signum() as i8;
1671                            s.source_changed_at_secs = t_now;
1672                            s.uncontrolled_iso = entry.iso.into();
1673                        }
1674                        s.digits = next_digits;
1675                    });
1676                    if changed_iso && let Some(cb) = &on_c_change_key {
1677                        cb(&SharedString::from(entry.iso), window, cx);
1678                    }
1679                    if let Some(cb) = &on_v_change_key {
1680                        cb(&ev, window, cx);
1681                    }
1682                    window.refresh();
1683                    return;
1684                }
1685                let digit_char = event
1686                    .keystroke
1687                    .key_char
1688                    .as_deref()
1689                    .and_then(|kc| (kc.len() == 1).then(|| kc.chars().next()).flatten())
1690                    .filter(|c| c.is_ascii_digit())
1691                    .or_else(|| {
1692                        (key.len() == 1)
1693                            .then(|| key.chars().next())
1694                            .flatten()
1695                            .filter(|c| c.is_ascii_digit())
1696                    });
1697                if let Some(digit) = digit_char
1698                    && !ctrl_or_platform
1699                {
1700                    let entry = current;
1701                    let next = {
1702                        let s = int_key.read(cx);
1703                        let candidate = format!("{}{digit}", s.digits);
1704                        phone_cap_digits(entry, &candidate)
1705                    };
1706                    let ev = PhoneValueEvent {
1707                        value: phone_to_e164(entry, &next),
1708                        details: build_phone_details(entry, &next),
1709                    };
1710                    int_key.update(cx, |s, _| {
1711                        s.digits = next;
1712                        s.seen_value = Some(ev.value.clone());
1713                    });
1714                    if let Some(cb) = &on_v_change_key {
1715                        cb(&ev, window, cx);
1716                    }
1717                    window.refresh();
1718                    return;
1719                }
1720                if key == "backspace" {
1721                    let entry = current;
1722                    let next: String = {
1723                        let s = int_key.read(cx);
1724                        s.digits
1725                            .chars()
1726                            .take(s.digits.len().saturating_sub(1))
1727                            .collect()
1728                    };
1729                    let ev = PhoneValueEvent {
1730                        value: phone_to_e164(entry, &next),
1731                        details: build_phone_details(entry, &next),
1732                    };
1733                    int_key.update(cx, |s, _| {
1734                        s.digits = next;
1735                        s.seen_value = Some(ev.value.clone());
1736                    });
1737                    if let Some(cb) = &on_v_change_key {
1738                        cb(&ev, window, cx);
1739                    }
1740                    window.refresh();
1741                }
1742            })
1743            .relative()
1744            .w_full()
1745            .h(ControlHeights::MD)
1746            .px(px(1.0))
1747            .flex()
1748            .flex_row()
1749            .items_center()
1750            .rounded(Radii::CONTROL)
1751            .border_1()
1752            .border_color(control_border)
1753            .bg(if self.disabled {
1754                colors.surface_muted
1755            } else {
1756                colors.surface
1757            })
1758            .opacity(if self.disabled { 0.5 } else { 1.0 })
1759            .child(
1760                canvas(
1761                    {
1762                        let probe = snap.control_bounds.clone();
1763                        move |rect, _, _| {
1764                            *probe.borrow_mut() = Some(rect);
1765                        }
1766                    },
1767                    |_, _, _, _| {},
1768                )
1769                .absolute()
1770                .inset_0(),
1771            )
1772            // ── Country trigger + morphing panel ──────────────────────────────────────────────
1773            .child(
1774                div()
1775                    .relative()
1776                    .h_full()
1777                    .flex_none()
1778                    .when_some(panel_el, |this, panel| this.child(panel))
1779                    .child(
1780                        div()
1781                            .id(ElementId::NamedChild(
1782                                self.id.clone().into(),
1783                                "trigger".into(),
1784                            ))
1785                            .test_support()
1786                            .role(Role::Button)
1787                            .aria_label(SharedString::from(format!(
1788                                "Country, {} +{}",
1789                                current.name, current.dial
1790                            )))
1791                            .relative()
1792                            .h_full()
1793                            .pl(px(11.0))
1794                            .pr(px(33.0))
1795                            .flex()
1796                            .flex_row()
1797                            .items_center()
1798                            .gap(px(6.0))
1799                            .rounded(px(PHONE_CLOSED_RADIUS - 4.0))
1800                            .when(
1801                                !self.disabled && (snap.trigger_hovered || menu_open),
1802                                |this| this.bg(colors.surface_muted),
1803                            )
1804                            .when(!self.disabled, |this| {
1805                                this.cursor_pointer().on_hover({
1806                                    let int_t = internal.clone();
1807                                    move |hovered, window, cx| {
1808                                        int_t.update(cx, |s, _| s.trigger_hovered = *hovered);
1809                                        window.refresh();
1810                                    }
1811                                })
1812                            })
1813                            .on_click({
1814                                let int_t = internal.clone();
1815                                let disabled_t = self.disabled;
1816                                let focus_t = snap.focus_handle.clone();
1817                                move |_, window, cx| {
1818                                    if disabled_t {
1819                                        return;
1820                                    }
1821                                    window.focus(&focus_t, cx);
1822                                    let will_open = !int_t.read(cx).menu_open;
1823                                    int_t.update(cx, |s, _| {
1824                                        s.menu_open = !s.menu_open;
1825                                        s.highlight_seeded = false;
1826                                    });
1827                                    if will_open {
1828                                        let q_in = int_t.read(cx).query_input.clone();
1829                                        q_in.update(cx, |s, cx| {
1830                                            s.set_value("", window, cx);
1831                                            s.focus(window, cx);
1832                                        });
1833                                    }
1834                                    window.refresh();
1835                                }
1836                            })
1837                            .child(
1838                                div()
1839                                    .mt(px(flag_y))
1840                                    .opacity(flag_op)
1841                                    .flex()
1842                                    .flex_row()
1843                                    .items_center()
1844                                    .gap(px(6.0))
1845                                    .child(
1846                                        div()
1847                                            .w(px(20.0))
1848                                            .flex_none()
1849                                            .text_size(px(17.0))
1850                                            .child(SharedString::from(phone_flag_of(current.iso))),
1851                                    )
1852                                    .child(
1853                                        div()
1854                                            .flex_none()
1855                                            .text_size(Typography::TEXT_SM)
1856                                            .font_medium()
1857                                            .text_color(colors.foreground)
1858                                            .child(SharedString::from(format!(
1859                                                "+{}",
1860                                                current.dial
1861                                            ))),
1862                                    ),
1863                            )
1864                            .child(
1865                                div()
1866                                    .absolute()
1867                                    .right(px(12.0))
1868                                    .top(px(14.0))
1869                                    .size(px(16.0))
1870                                    .child(
1871                                        canvas(
1872                                            |_, _, _| {},
1873                                            move |rect, _, window, _| {
1874                                                let cx_pt = f32::from(
1875                                                    rect.origin.x + rect.size.width * 0.5,
1876                                                );
1877                                                let cy_pt = f32::from(
1878                                                    rect.origin.y + rect.size.height * 0.5,
1879                                                );
1880                                                paint_rotated_chevron(
1881                                                    cx_pt,
1882                                                    cy_pt,
1883                                                    chevron_deg,
1884                                                    colors.text_muted,
1885                                                    window,
1886                                                );
1887                                            },
1888                                        )
1889                                        .size_full(),
1890                                    ),
1891                            )
1892                            .child(
1893                                canvas(
1894                                    {
1895                                        let probe = snap.trigger_bounds.clone();
1896                                        move |rect, _, _| {
1897                                            *probe.borrow_mut() = Some(rect);
1898                                        }
1899                                    },
1900                                    |_, _, _, _| {},
1901                                )
1902                                .absolute()
1903                                .inset_0(),
1904                            ),
1905                    ),
1906            )
1907            // ── Number + guide + valid check ───────────────────────────────────────────────────
1908            .child(
1909                div()
1910                    .id(ElementId::NamedChild(
1911                        self.id.clone().into(),
1912                        "number-wrap".into(),
1913                    ))
1914                    .test_support()
1915                    .flex_1()
1916                    .min_w_0()
1917                    .h_full()
1918                    .flex()
1919                    .items_center()
1920                    .pl(px(11.0))
1921                    .pr(px(36.0))
1922                    .when(!self.disabled, |this| {
1923                        let focus_down = focus_for_wrap.clone();
1924                        this.cursor_pointer()
1925                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1926                                window.focus(&focus_down, cx);
1927                                window.refresh();
1928                            })
1929                            .on_click({
1930                                let int_n = internal.clone();
1931                                move |_, window, cx| {
1932                                    window.focus(&focus_for_wrap, cx);
1933                                    let _ = &int_n;
1934                                    window.refresh();
1935                                }
1936                            })
1937                    })
1938                    .child(
1939                        div()
1940                            .flex()
1941                            .flex_row()
1942                            .items_center()
1943                            .min_w_0()
1944                            .whitespace_nowrap()
1945                            .text_size(Typography::TEXT_SM)
1946                            .child(
1947                                div()
1948                                    .flex_none()
1949                                    .text_color(colors.foreground)
1950                                    .child(SharedString::from(formatted.clone())),
1951                            )
1952                            .when(is_focused && !menu_open && !self.disabled, |this| {
1953                                this.child(
1954                                    div()
1955                                        .mx(px(1.0))
1956                                        .w(px(1.5))
1957                                        .h(px(16.0))
1958                                        .bg(colors.foreground),
1959                                )
1960                            })
1961                            .when(!guide.is_empty(), |this| {
1962                                this.child(
1963                                    div()
1964                                        .flex_none()
1965                                        .text_color(guide_color)
1966                                        .child(SharedString::from(guide.clone())),
1967                                )
1968                            }),
1969                    )
1970                    .child(
1971                        div()
1972                            .absolute()
1973                            .right(px(12.0))
1974                            .top(px(13.0))
1975                            .size(px(18.0))
1976                            .child(
1977                                canvas(
1978                                    |_, _, _| {},
1979                                    move |rect, _, window, _| {
1980                                        let cx_pt =
1981                                            f32::from(rect.origin.x + rect.size.width * 0.5);
1982                                        let cy_pt =
1983                                            f32::from(rect.origin.y + rect.size.height * 0.5);
1984                                        paint_scaled_check(
1985                                            cx_pt,
1986                                            cy_pt,
1987                                            check_scale,
1988                                            check_op,
1989                                            colors.success,
1990                                            window,
1991                                        );
1992                                    },
1993                                )
1994                                .size_full(),
1995                            ),
1996                    ),
1997            );
1998
1999        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
2000        let msg_text = effective_error.clone().or(self.description);
2001
2002        div()
2003            .id(self.id)
2004            .test_support()
2005            .when_some(self.width, |this, w| this.w(w))
2006            .when(self.width.is_none(), |this| this.w_full())
2007            .flex()
2008            .flex_col()
2009            .when(!self.hide_label, |this| {
2010                this.child(
2011                    div()
2012                        .mb(Spacing::S2)
2013                        .text_size(Typography::TEXT_SM)
2014                        .font_medium()
2015                        .text_color(colors.foreground)
2016                        .child(self.label),
2017                )
2018            })
2019            .child(control)
2020            .child(render_field_message(
2021                msg_id, msg_text, is_invalid, window, cx,
2022            ))
2023    }
2024}
2025
2026#[cfg(test)]
2027mod tests {
2028    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
2029    use gpui_kit::{ClipboardItem, Context, Render, TestAppContext, test::TestWindowExt as _};
2030
2031    use super::*;
2032
2033    #[test]
2034    fn phone_patterns_format_national_numbers_with_trunk_prefix() {
2035        let us = phone_country_by_iso("US").unwrap();
2036        assert_eq!(phone_format_national(us, "2015550123"), "(201) 555-0123");
2037        assert_eq!(phone_to_e164(us, "2015550123"), "+12015550123");
2038        // A typed UK trunk prefix keeps its own room: "07911123456" -> "07911 123456".
2039        let gb = phone_country_by_iso("GB").unwrap();
2040        assert_eq!(phone_format_national(gb, "07911123456"), "07911 123456");
2041        assert_eq!(phone_status_of(gb, "07911123456"), PhoneStatus::Valid);
2042        assert_eq!(phone_status_of(gb, ""), PhoneStatus::Empty);
2043        assert_eq!(phone_status_of(gb, "07911"), PhoneStatus::Incomplete);
2044        assert_eq!(phone_status_of(gb, "079111234567"), PhoneStatus::TooLong);
2045    }
2046
2047    #[test]
2048    fn phone_parse_number_resolves_longest_dial_and_area_codes() {
2049        // Longest calling code wins: +353 is Ireland, not +3 with junk.
2050        let (entry, national) = phone_parse_number("+353850123456").unwrap();
2051        assert_eq!(entry.iso, "IE");
2052        assert_eq!(national, "850123456");
2053        // Canada resolves inside the shared +1 dial through its area codes.
2054        let (entry, national) = phone_parse_number("+14165550123").unwrap();
2055        assert_eq!(entry.iso, "CA");
2056        assert_eq!(national, "4165550123");
2057        // "+44 (0)…" carries a trunk zero that is dropped.
2058        let (entry, national) = phone_parse_number("+44 (0)7400 123456").unwrap();
2059        assert_eq!(entry.iso, "GB");
2060        assert_eq!(national, "7400123456");
2061        // 00 international prefix.
2062        let (entry, _) = phone_parse_number("0041 78 123 45 67").unwrap();
2063        assert_eq!(entry.iso, "CH");
2064        assert!(phone_parse_number("not a phone").is_none());
2065    }
2066
2067    #[test]
2068    fn phone_cap_digits_earn_trunk_room_and_format_e164_round_trips() {
2069        let gb = phone_country_by_iso("GB").unwrap();
2070        // The typed trunk "0" earns its own room: 1 + 10 digits fit.
2071        assert_eq!(phone_cap_digits(gb, "0791112345678"), "07911123456");
2072        let e164 = phone_to_e164(gb, "07911123456");
2073        assert_eq!(e164, "+447911123456");
2074        assert_eq!(phone_format_e164(&e164), "+44 7911 123456");
2075    }
2076
2077    #[test]
2078    fn phone_matches_query_matches_dials_names_and_iso() {
2079        let us = phone_country_by_iso("US").unwrap();
2080        let de = phone_country_by_iso("DE").unwrap();
2081        assert!(phone_matches_query(us, "1"));
2082        assert!(phone_matches_query(us, "+1"));
2083        assert!(phone_matches_query(de, "49"));
2084        assert!(phone_matches_query(de, "germ"));
2085        assert!(phone_matches_query(de, "de"));
2086        assert!(!phone_matches_query(de, "44"));
2087        assert!(phone_matches_query(us, "+"));
2088    }
2089
2090    struct PhoneHost {
2091        value: String,
2092        iso: SharedString,
2093        disabled: bool,
2094        events: Rc<RefCell<Vec<String>>>,
2095        countries_seen: Rc<RefCell<Vec<SharedString>>>,
2096    }
2097
2098    impl Render for PhoneHost {
2099        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2100            let events = self.events.clone();
2101            let countries_seen = self.countries_seen.clone();
2102            div().w(px(560.0)).p(px(16.0)).child(
2103                PhoneInput::new("phone-test", "Phone")
2104                    .value(self.value.clone())
2105                    .country(self.iso.clone())
2106                    .disabled(self.disabled)
2107                    .on_value_change(cx.listener({
2108                        let events = events.clone();
2109                        move |this, event: &PhoneValueEvent, _, cx| {
2110                            events.borrow_mut().push(event.value.clone());
2111                            this.value = event.value.clone();
2112                            cx.notify();
2113                        }
2114                    }))
2115                    .on_country_change(cx.listener({
2116                        let countries_seen = countries_seen.clone();
2117                        move |this, iso: &SharedString, _, cx| {
2118                            countries_seen.borrow_mut().push(iso.clone());
2119                            this.iso = iso.clone();
2120                            cx.notify();
2121                        }
2122                    })),
2123            )
2124        }
2125    }
2126
2127    fn phone_element(name: &str) -> ElementId {
2128        ElementId::NamedChild(ElementId::Name("phone-test".into()).into(), name.into())
2129    }
2130
2131    #[gpui_kit::test]
2132    fn phone_input_types_backspaces_picks_country_and_parses_paste(cx: &mut TestAppContext) {
2133        cx.update(|cx| {
2134            gpui_kit::init(cx);
2135            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
2136        });
2137
2138        let host = PhoneHost {
2139            value: String::new(),
2140            iso: "US".into(),
2141            disabled: false,
2142            events: Rc::new(RefCell::new(Vec::new())),
2143            countries_seen: Rc::new(RefCell::new(Vec::new())),
2144        };
2145        let events = host.events.clone();
2146        let countries_seen = host.countries_seen.clone();
2147        let (view, cx) = cx.add_window_view(|_, _| host);
2148
2149        cx.update(|window, cx| {
2150            window.render_frame(cx);
2151            let trigger = window.find(phone_element("trigger"));
2152            assert_eq!(trigger.role(), Some(Role::Button));
2153
2154            // Typing digits emits the running draft as E.164 per keystroke.
2155            window.click(phone_element("number-wrap"), cx);
2156            window.input("201555", cx);
2157        });
2158        assert_eq!(events.borrow().last(), Some(&"+1201555".to_string()));
2159
2160        cx.update(|window, cx| {
2161            window.press("backspace", cx);
2162        });
2163        assert_eq!(events.borrow().last(), Some(&"+120155".to_string()));
2164
2165        // The country picker opens as a listbox; picking Canada keeps the digits.
2166        cx.update(|window, cx| {
2167            window.click(phone_element("trigger"), cx);
2168            window.render_frame(cx);
2169            let panel = window.find(phone_element("country-panel"));
2170            assert_eq!(panel.role(), Some(Role::ListBox));
2171            let row = window.find(phone_element("country-preferred-CA"));
2172            assert_eq!(row.role(), Some(Role::ListBoxOption));
2173            window.click(phone_element("country-preferred-CA"), cx);
2174        });
2175        assert_eq!(
2176            countries_seen.borrow().last().map(|c| c.to_string()),
2177            Some("CA".to_string())
2178        );
2179
2180        // Pasting an international number picks its own country.
2181        cx.update(|window, cx| {
2182            window.click(phone_element("number-wrap"), cx);
2183        });
2184        cx.update(|_window, cx| {
2185            cx.write_to_clipboard(ClipboardItem::new_string("+447911123456".to_string()));
2186        });
2187        cx.update(|window, cx| {
2188            window.press("ctrl-v", cx);
2189        });
2190        assert_eq!(
2191            countries_seen.borrow().last().map(|c| c.to_string()),
2192            Some("GB".to_string())
2193        );
2194        assert_eq!(events.borrow().last(), Some(&"+447911123456".to_string()));
2195
2196        // "+" opens the picker seeded with a calling-code search.
2197        cx.update(|window, cx| {
2198            window.click(phone_element("number-wrap"), cx);
2199            window.press("+", cx);
2200            window.render_frame(cx);
2201            assert!(window.try_find(phone_element("country-panel")).is_some());
2202        });
2203
2204        // Disabled swallows typing.
2205        view.update(cx, |host, cx| {
2206            host.disabled = true;
2207            cx.notify();
2208        });
2209        cx.update(|window, cx| {
2210            window.render_frame(cx);
2211            window.click(phone_element("number-wrap"), cx);
2212            window.input("7", cx);
2213        });
2214        assert_eq!(events.borrow().last(), Some(&"+447911123456".to_string()));
2215    }
2216
2217    #[gpui_kit::test]
2218    fn phone_input_reduced_motion_keeps_interactions_instant(cx: &mut TestAppContext) {
2219        cx.update(|cx| {
2220            gpui_kit::init(cx);
2221            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
2222            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
2223        });
2224
2225        let host = PhoneHost {
2226            value: String::new(),
2227            iso: "US".into(),
2228            disabled: false,
2229            events: Rc::new(RefCell::new(Vec::new())),
2230            countries_seen: Rc::new(RefCell::new(Vec::new())),
2231        };
2232        let events = host.events.clone();
2233        let (_view, cx) = cx.add_window_view(|_, _| host);
2234
2235        cx.update(|window, cx| {
2236            window.render_frame(cx);
2237            window.click(phone_element("number-wrap"), cx);
2238            window.input("20", cx);
2239        });
2240        assert_eq!(
2241            events.borrow().as_slice(),
2242            ["+12".to_string(), "+120".to_string()]
2243        );
2244    }
2245}