use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
MouseButton, MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
SharedString, Styled, TestSupportExt as _, Window,
assets::IconName,
base::{Button as BaseButton, StyledExt as _},
canvas,
component::{
Icon,
input::{Input as KitInput, InputState},
},
deferred, div, point,
prelude::*,
px,
};
use super::field_message::render_field_message;
type PhoneValueChangeHandler = Rc<dyn Fn(&PhoneValueEvent, &mut Window, &mut App)>;
type PhoneCountryChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
pub const PHONE_CLOSED_RADIUS: f32 = 8.0;
pub const PHONE_OPEN_RADIUS: f32 = 10.0;
pub const PHONE_PANEL_MAX: f32 = 310.0;
pub const PHONE_PAGE: usize = 8;
pub const PHONE_LIST_MAX_H: f32 = 240.0;
pub const fn phone_grow_spring() -> SpringSpec {
SpringSpec::visual(0.4, 0.0)
}
pub const fn phone_shrink_spring() -> SpringSpec {
SpringSpec::visual(0.32, 0.0)
}
pub const fn phone_glide_spring() -> SpringSpec {
SpringSpec::visual(0.28, 0.0)
}
pub const fn phone_width_spring() -> SpringSpec {
SpringSpec::visual(0.42, 0.0)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PhoneCountry {
pub iso: &'static str,
pub name: &'static str,
pub dial: &'static str,
pub patterns: &'static [&'static str],
pub trunk: &'static str,
pub example: &'static str,
pub area_codes: &'static [&'static str],
}
const fn country(
iso: &'static str,
name: &'static str,
dial: &'static str,
patterns: &'static [&'static str],
example: &'static str,
) -> PhoneCountry {
PhoneCountry {
iso,
name,
dial,
patterns,
trunk: "0",
example,
area_codes: &[],
}
}
const fn country_flat(
iso: &'static str,
name: &'static str,
dial: &'static str,
patterns: &'static [&'static str],
example: &'static str,
) -> PhoneCountry {
PhoneCountry {
iso,
name,
dial,
patterns,
trunk: "",
example,
area_codes: &[],
}
}
const fn country_trunk(
iso: &'static str,
name: &'static str,
dial: &'static str,
patterns: &'static [&'static str],
example: &'static str,
trunk: &'static str,
) -> PhoneCountry {
PhoneCountry {
iso,
name,
dial,
patterns,
trunk,
example,
area_codes: &[],
}
}
const CA_AREA_CODES: &[&str] = &[
"204", "226", "236", "249", "250", "263", "289", "306", "343", "354", "365", "367", "368",
"382", "387", "403", "416", "418", "428", "431", "437", "438", "450", "468", "474", "506",
"514", "519", "548", "579", "581", "584", "587", "604", "613", "639", "647", "672", "683",
"705", "709", "742", "753", "778", "780", "782", "807", "819", "825", "867", "873", "879",
"902", "905",
];
pub static PHONE_COUNTRIES: &[PhoneCountry] = &[
country_trunk(
"US",
"United States",
"1",
&["(###) ###-####"],
"2015550123",
"1",
),
PhoneCountry {
iso: "CA",
name: "Canada",
dial: "1",
patterns: &["(###) ###-####"],
trunk: "1",
example: "5065550123",
area_codes: CA_AREA_CODES,
},
country_flat("MX", "Mexico", "52", &["## #### ####"], "2221234567"),
country(
"BR",
"Brazil",
"55",
&["(##) ####-####", "(##) #####-####"],
"11961234567",
),
country("AR", "Argentina", "54", &["## ####-####"], "1123456789"),
country_flat("CO", "Colombia", "57", &["### ### ####"], "3211234567"),
country_flat("CL", "Chile", "56", &["# #### ####"], "221234567"),
country_flat("PE", "Peru", "51", &["### ### ###"], "912345678"),
country("GB", "United Kingdom", "44", &["#### ######"], "7400123456"),
country("IE", "Ireland", "353", &["## ### ####"], "850123456"),
country("FR", "France", "33", &["# ## ## ## ##"], "612345678"),
country(
"DE",
"Germany",
"49",
&["### #######", "### ########"],
"15123456789",
),
country_flat("ES", "Spain", "34", &["### ## ## ##"], "612345678"),
country_flat(
"IT",
"Italy",
"39",
&["### ### ###", "### ### ####"],
"3123456789",
),
country_flat("PT", "Portugal", "351", &["### ### ###"], "912345678"),
country_flat("NL", "Netherlands", "31", &["# ########"], "612345678"),
country_flat("BE", "Belgium", "32", &["### ## ## ##"], "470123456"),
country_flat("CH", "Switzerland", "41", &["## ### ## ##"], "781234567"),
country(
"AT",
"Austria",
"43",
&["### #######", "### ########"],
"6641234567",
),
country("SE", "Sweden", "46", &["## ### ## ##"], "701234567"),
country_flat("NO", "Norway", "47", &["### ## ###"], "40612345"),
country_flat("DK", "Denmark", "45", &["## ## ## ##"], "32123456"),
country(
"FI",
"Finland",
"358",
&["## ### ####", "## ### #####"],
"412345678",
),
country_flat("PL", "Poland", "48", &["### ### ###"], "512345678"),
country_flat("CZ", "Czechia", "420", &["### ### ###"], "601123456"),
country_flat("GR", "Greece", "30", &["### ### ####"], "6912345678"),
country("UA", "Ukraine", "380", &["## ### ## ##"], "501234567"),
country("TR", "Turkey", "90", &["### ### ## ##"], "5012345678"),
country("IL", "Israel", "972", &["##-###-####"], "502345678"),
country(
"AE",
"United Arab Emirates",
"971",
&["## ### ####"],
"501234567",
),
country("SA", "Saudi Arabia", "966", &["## ### ####"], "512345678"),
country("EG", "Egypt", "20", &["### ### ####"], "1001234567"),
country("NG", "Nigeria", "234", &["### ### ####"], "8021234567"),
country("KE", "Kenya", "254", &["### ######"], "712123456"),
country("ZA", "South Africa", "27", &["## ### ####"], "711234567"),
country("IN", "India", "91", &["#####-#####"], "8123456789"),
country("PK", "Pakistan", "92", &["### #######"], "3012345678"),
country("CN", "China", "86", &["### #### ####"], "13123456789"),
country("JP", "Japan", "81", &["##-####-####"], "9012345678"),
country(
"KR",
"South Korea",
"82",
&["##-###-####", "##-####-####"],
"1020000000",
),
country("TW", "Taiwan", "886", &["### ### ###"], "912345678"),
country_flat("HK", "Hong Kong", "852", &["#### ####"], "51234567"),
country_flat("SG", "Singapore", "65", &["#### ####"], "81234567"),
country("PH", "Philippines", "63", &["### ### ####"], "9051234567"),
country(
"ID",
"Indonesia",
"62",
&["###-###-####", "###-####-####", "###-####-#####"],
"81234567890",
),
country("TH", "Thailand", "66", &["## ### ####"], "812345678"),
country("VN", "Vietnam", "84", &["## ### ## ##"], "912345678"),
country("AU", "Australia", "61", &["### ### ###"], "412345678"),
country(
"NZ",
"New Zealand",
"64",
&["# ### ####", "## ### ####", "## #### ####"],
"211234567",
),
];
pub fn phone_country_by_iso(iso: &str) -> Option<&'static PhoneCountry> {
PHONE_COUNTRIES.iter().find(|entry| entry.iso == iso)
}
pub fn phone_only_digits(text: &str) -> String {
text.chars().filter(|c| c.is_ascii_digit()).collect()
}
pub fn phone_flag_of(iso: &str) -> String {
iso.to_uppercase()
.chars()
.map(|c| char::from_u32(0x1f1e6 + (u32::from(c) - 65)).unwrap_or(c))
.collect()
}
pub fn phone_split_trunk<'a>(entry: &PhoneCountry, digits: &'a str) -> (&'a str, &'a str) {
if !entry.trunk.is_empty() && digits.starts_with(entry.trunk) {
(entry.trunk, &digits[entry.trunk.len()..])
} else {
("", digits)
}
}
pub fn phone_capacity(pattern: &str) -> usize {
pattern.matches('#').count()
}
pub fn phone_lengths(entry: &PhoneCountry) -> Vec<usize> {
entry.patterns.iter().map(|p| phone_capacity(p)).collect()
}
pub fn phone_cap_digits(entry: &PhoneCountry, digits: &str) -> String {
let trunk_len = phone_split_trunk(entry, digits).0.len();
let max_len = phone_lengths(entry).into_iter().max().unwrap_or(0);
digits.chars().take(trunk_len + max_len).collect()
}
pub fn phone_apply_pattern(digits: &str, pattern: &str) -> String {
let mut out = String::new();
let mut chars = digits.chars().peekable();
for ch in pattern.chars() {
if chars.peek().is_none() {
break;
}
if ch == '#' {
if let Some(d) = chars.next() {
out.push(d);
}
} else {
out.push(ch);
}
}
let rest: String = chars.collect();
out + &rest
}
pub fn phone_pattern_for(entry: &PhoneCountry, length: usize) -> &str {
entry
.patterns
.iter()
.find(|p| phone_capacity(p) >= length)
.copied()
.unwrap_or_else(|| entry.patterns.last().expect("patterns is non-empty"))
}
pub fn phone_format_national(entry: &PhoneCountry, digits: &str) -> String {
let (trunk, rest) = phone_split_trunk(entry, digits);
let pattern = phone_pattern_for(entry, rest.len());
let body = phone_apply_pattern(rest, pattern);
if trunk.is_empty() {
return body;
}
if rest.is_empty() {
return trunk.to_string();
}
let gap = if pattern.starts_with('#') { "" } else { " " };
format!("{trunk}{gap}{body}")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PhoneStatus {
Empty,
Incomplete,
Valid,
TooLong,
}
pub fn phone_status_of(entry: &PhoneCountry, digits: &str) -> PhoneStatus {
let length = phone_split_trunk(entry, digits).1.len();
let lengths = phone_lengths(entry);
if length == 0 {
return PhoneStatus::Empty;
}
if lengths.contains(&length) {
return PhoneStatus::Valid;
}
if length > lengths.iter().max().copied().unwrap_or(0) {
PhoneStatus::TooLong
} else {
PhoneStatus::Incomplete
}
}
pub fn phone_to_e164(entry: &PhoneCountry, digits: &str) -> String {
let rest = phone_split_trunk(entry, digits).1;
if rest.is_empty() {
String::new()
} else {
format!("+{}{}", entry.dial, rest)
}
}
pub fn phone_parse_number(input: &str) -> Option<(&'static PhoneCountry, String)> {
let trimmed = input.trim();
let all_digits = phone_only_digits(trimmed);
let digits = if trimmed.starts_with('+') {
all_digits
} else if trimmed.starts_with("00") && all_digits.len() > 2 {
all_digits[2..].to_string()
} else {
return None;
};
for size in [3usize, 2, 1] {
if digits.len() < size {
continue;
}
let dial = &digits[..size];
let matches: Vec<&PhoneCountry> =
PHONE_COUNTRIES.iter().filter(|e| e.dial == dial).collect();
if matches.is_empty() {
continue;
}
let mut rest = digits[size..].to_string();
let entry = matches
.iter()
.find(|item| item.area_codes.iter().any(|code| rest.starts_with(code)))
.or_else(|| matches.iter().find(|item| item.area_codes.is_empty()))
.or_else(|| matches.first())
.copied()
.expect("matches is non-empty");
let min_len = phone_lengths(entry).into_iter().min().unwrap_or(0);
if !entry.trunk.is_empty()
&& rest.starts_with(entry.trunk)
&& rest.len() - entry.trunk.len() >= min_len
{
rest = rest[entry.trunk.len()..].to_string();
}
return Some((entry, phone_cap_digits(entry, &rest)));
}
None
}
pub fn phone_format_e164(e164: &str) -> String {
match phone_parse_number(e164) {
Some((entry, national)) => {
format!(
"+{} {}",
entry.dial,
phone_format_national(entry, &national)
)
}
None => e164.to_string(),
}
}
pub fn phone_matches_query(entry: &PhoneCountry, needle: &str) -> bool {
if needle.is_empty() {
return true;
}
let digits = phone_only_digits(needle);
let is_dial_query = !digits.is_empty()
&& needle.chars().all(|c| {
c.is_ascii_digit() || c == '+' || c == ' ' || c == '(' || c == ')' || c == '-'
});
if is_dial_query {
return entry.dial.starts_with(&digits) || digits.starts_with(entry.dial);
}
if needle.chars().all(|c| c == '+') {
return true;
}
entry.name.to_lowercase().contains(needle) || entry.iso.to_lowercase() == needle
}
fn phone_order_of(iso: &str) -> usize {
let mut sorted: Vec<&PhoneCountry> = PHONE_COUNTRIES.iter().collect();
sorted.sort_by_key(|entry| entry.name);
sorted
.iter()
.position(|entry| entry.iso == iso)
.unwrap_or(0)
}
#[derive(Clone, Debug, PartialEq)]
pub struct PhoneInputDetails {
pub country: &'static PhoneCountry,
pub formatted: String,
pub status: PhoneStatus,
pub valid: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PhoneValueEvent {
pub value: String,
pub details: PhoneInputDetails,
}
#[derive(Clone)]
struct PhoneInternal {
uncontrolled_iso: SharedString,
digits: String,
seen_value: Option<String>,
source_changed_at_secs: f64,
roll_dir: i8,
menu_open: bool,
active_iso: Option<SharedString>,
highlight_seeded: bool,
control_hovered: bool,
trigger_hovered: bool,
trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
query_input: Entity<InputState>,
focus_handle: FocusHandle,
}
impl PhoneInternal {
fn new(now: f64, window: &mut Window, cx: &mut App) -> Self {
let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Country or code"));
Self {
uncontrolled_iso: "US".into(),
digits: String::new(),
seen_value: None,
source_changed_at_secs: now - 10.0,
roll_dir: 1,
menu_open: false,
active_iso: None,
highlight_seeded: false,
control_hovered: false,
trigger_hovered: false,
trigger_bounds: Rc::new(RefCell::new(None)),
panel_bounds: Rc::new(RefCell::new(None)),
control_bounds: Rc::new(RefCell::new(None)),
query_input,
focus_handle: cx.focus_handle(),
}
}
}
fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let cos_a = rad.cos();
let sin_a = rad.sin();
let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let rx = cx + lx * cos_a - ly * sin_a;
let ry = cy + lx * sin_a + ly * cos_a;
let p = point(px(rx), px(ry));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
fn paint_scaled_check(
cx: f32,
cy: f32,
scale: f32,
opacity: f32,
color: Hsla,
window: &mut Window,
) {
if opacity <= 0.01 {
return;
}
let pts = [(-4.0_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
let mut builder = PathBuilder::stroke(px(2.0));
for (i, (lx, ly)) in pts.iter().enumerate() {
let p = point(px(cx + lx * scale), px(cy + ly * scale));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
let c = Hsla {
a: color.a * opacity.clamp(0.0, 1.0),
..color
};
if let Ok(path) = builder.build() {
window.paint_path(path, c);
}
}
#[derive(IntoElement)]
pub struct PhoneInput {
id: ElementId,
label: SharedString,
hide_label: bool,
value: Option<String>,
default_value: Option<String>,
country: Option<SharedString>,
default_country: SharedString,
countries: Vec<SharedString>,
preferred_countries: Vec<SharedString>,
description: Option<SharedString>,
error: Option<SharedString>,
validate: bool,
disabled: bool,
width: Option<Pixels>,
on_value_change: Option<PhoneValueChangeHandler>,
on_country_change: Option<PhoneCountryChangeHandler>,
}
impl PhoneInput {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
hide_label: false,
value: None,
default_value: None,
country: None,
default_country: "US".into(),
countries: Vec::new(),
preferred_countries: vec!["US".into(), "CA".into(), "GB".into()],
description: None,
error: None,
validate: true,
disabled: false,
width: None,
on_value_change: None,
on_country_change: None,
}
}
pub fn hide_label(mut self, hide: bool) -> Self {
self.hide_label = hide;
self
}
pub fn value(mut self, e164: impl Into<String>) -> Self {
self.value = Some(e164.into());
self
}
pub fn default_value(mut self, e164: impl Into<String>) -> Self {
self.default_value = Some(e164.into());
self
}
pub fn country(mut self, iso: impl Into<SharedString>) -> Self {
self.country = Some(iso.into());
self
}
pub fn default_country(mut self, iso: impl Into<SharedString>) -> Self {
self.default_country = iso.into();
self
}
pub fn countries<I, S>(mut self, codes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.countries = codes.into_iter().map(Into::into).collect();
self
}
pub fn preferred_countries<I, S>(mut self, codes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.preferred_countries = codes.into_iter().map(Into::into).collect();
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn error(mut self, error: impl Into<SharedString>) -> Self {
self.error = Some(error.into());
self
}
pub fn validate(mut self, validate: bool) -> Self {
self.validate = validate;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&PhoneValueEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
pub fn on_country_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_country_change = Some(Rc::new(handler));
self
}
}
fn build_phone_details(entry: &'static PhoneCountry, digits: &str) -> PhoneInputDetails {
let status = phone_status_of(entry, digits);
PhoneInputDetails {
country: entry,
formatted: phone_format_national(entry, digits),
status,
valid: status == PhoneStatus::Valid,
}
}
fn phone_pool(countries: &[SharedString]) -> Vec<&'static PhoneCountry> {
if countries.is_empty() {
PHONE_COUNTRIES.iter().collect()
} else {
PHONE_COUNTRIES
.iter()
.filter(|entry| countries.iter().any(|c| c.as_ref() == entry.iso))
.collect()
}
}
impl RenderOnce for PhoneInput {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let pool = phone_pool(&self.countries);
let default_entry = phone_country_by_iso(&self.default_country)
.or_else(|| pool.first().copied())
.unwrap_or(&PHONE_COUNTRIES[0]);
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-phone-state".into());
let internal = window.use_keyed_state(state_id, cx, |window, cx| {
let seed = self
.value
.clone()
.or_else(|| self.default_value.clone())
.unwrap_or_default();
let (iso, digits) = if seed.is_empty() {
(default_entry.iso.to_string(), String::new())
} else {
match phone_parse_number(&seed) {
Some((entry, national)) => (entry.iso.to_string(), national),
None => (default_entry.iso.to_string(), String::new()),
}
};
PhoneInternal {
uncontrolled_iso: iso.into(),
digits,
seen_value: self.value.clone(),
..PhoneInternal::new(now, window, cx)
}
});
if self.value != internal.read(cx).seen_value {
let seen = self.value.clone();
internal.update(cx, |s, _| {
s.seen_value = seen.clone();
if let Some(ext) = seen {
let cur_e164 = {
let iso = s.uncontrolled_iso.clone();
let entry = phone_country_by_iso(&iso).unwrap_or(default_entry);
phone_to_e164(entry, &s.digits)
};
if ext != cur_e164 {
if let Some((entry, national)) = phone_parse_number(&ext) {
s.uncontrolled_iso = entry.iso.into();
s.digits = national;
} else {
s.digits = String::new();
}
s.source_changed_at_secs = now;
}
}
});
}
let iso = self
.country
.clone()
.unwrap_or_else(|| internal.read(cx).uncontrolled_iso.clone());
let current = phone_country_by_iso(&iso).unwrap_or(default_entry);
let snap = internal.read(cx).clone();
let digits = snap.digits.clone();
let formatted = phone_format_national(current, &digits);
let status = phone_status_of(current, &digits);
let guide = {
let (trunk, rest) = phone_split_trunk(current, &digits);
if rest.len() >= current.example.len() {
String::new()
} else {
let filled = format!("{trunk}{}{}", rest, ¤t.example[rest.len()..]);
let full = phone_format_national(current, &filled);
if full.starts_with(&formatted) {
full[formatted.len()..].to_string()
} else {
String::new()
}
}
};
let is_focused = snap.focus_handle.is_focused(window);
let lengths = phone_lengths(current);
let length_copy = if lengths.len() == 1 {
format!("{}", lengths[0])
} else {
let heads: Vec<String> = lengths[..lengths.len() - 1]
.iter()
.map(|l| l.to_string())
.collect();
format!("{} or {}", heads.join(", "), lengths[lengths.len() - 1])
};
let built_in_error: Option<SharedString> = if self.validate
&& !is_focused
&& !digits.is_empty()
&& matches!(status, PhoneStatus::Incomplete | PhoneStatus::TooLong)
{
Some(SharedString::from(format!(
"Numbers in {} have {} digits",
current.name, length_copy
)))
} else {
None
};
let effective_error = self.error.clone().or(built_in_error);
let is_invalid = effective_error.is_some();
let control_border = if is_invalid {
colors.danger
} else if !self.disabled && is_focused {
colors.foreground
} else {
colors.border_strong
};
let needle = snap.query_input.read(cx).value().trim().to_lowercase();
let mut sorted: Vec<&PhoneCountry> = pool.clone();
sorted.sort_by_key(|entry| entry.name);
let sections: Vec<(&'static str, Option<&'static str>, Vec<&PhoneCountry>)> =
if !needle.is_empty() && needle != "+" {
let mut hits: Vec<&PhoneCountry> = sorted
.iter()
.copied()
.filter(|entry| phone_matches_query(entry, &needle))
.collect();
let digits_only = phone_only_digits(&needle);
if !digits_only.is_empty() {
hits.sort_by_key(|entry| {
(
std::cmp::Reverse(entry.dial == digits_only),
entry.dial.len(),
)
});
}
vec![("results", None, hits)]
} else {
let preferred: Vec<&PhoneCountry> = self
.preferred_countries
.iter()
.filter_map(|code| {
pool.iter()
.find(|entry| entry.iso == code.as_ref())
.copied()
})
.collect();
if preferred.is_empty() {
vec![("all", None, sorted.clone())]
} else {
vec![
("preferred", Some("Suggested"), preferred),
("all", Some("All countries"), sorted.clone()),
]
}
};
let rows: Vec<&PhoneCountry> = sections
.iter()
.flat_map(|(_, _, r)| r.iter().copied())
.collect();
let active_iso = snap
.active_iso
.clone()
.filter(|a| rows.iter().any(|r| r.iso == a.as_ref()))
.or_else(|| rows.first().map(|r| SharedString::from(r.iso)));
let menu_open = snap.menu_open && !self.disabled;
let src_elapsed = (now - snap.source_changed_at_secs).max(0.0);
let (flag_op, flag_y) = if src_elapsed >= 0.22 {
(1.0_f32, 0.0_f32)
} else {
window.request_animation_frame();
let t = (src_elapsed / 0.20).clamp(0.0, 1.0) as f32;
let e = if reduced {
t
} else {
CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
};
let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
let y = if reduced {
0.0
} else {
(snap.roll_dir as f32) * 0.6 * 17.0 * (1.0 - e)
};
(op, y)
};
let glide_spec = phone_glide_spring();
let chevron_deg = if reduced {
if menu_open { 180.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "chevron-deg"),
if menu_open { 180.0 } else { 0.0 },
glide_spec,
window,
cx,
)
};
let panel_presence = ArcPresence::new((self.id.clone(), "panel-presence"), menu_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
exit_duration: motion.duration.instant,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let panel_p = panel_presence.progress.clamp(0.0, 1.0);
let trigger_w = snap
.trigger_bounds
.borrow()
.map(|b| f32::from(b.size.width))
.unwrap_or(72.0);
let panel_target_w = trigger_w.max(PHONE_PANEL_MAX);
let grow_spec = phone_grow_spring();
let width_spec = phone_width_spring();
let panel_rendering = panel_presence.should_render();
let (panel_w, panel_r) = if reduced || !panel_rendering {
(
if panel_rendering {
panel_target_w
} else {
trigger_w
},
if panel_rendering {
PHONE_OPEN_RADIUS
} else {
PHONE_CLOSED_RADIUS
},
)
} else {
let w = arc_spring_with_options(
(self.id.clone(), "panel-w"),
panel_target_w,
SpringOptions::new(width_spec).with_initial_value(trigger_w),
window,
cx,
)
.value;
let r = arc_spring(
(self.id.clone(), "panel-r"),
PHONE_OPEN_RADIUS,
grow_spec,
window,
cx,
);
(w, r)
};
let show_check = status == PhoneStatus::Valid;
let check_scale = if reduced {
if show_check { 1.0 } else { 0.6 }
} else {
arc_spring(
(self.id.clone(), "check-sc"),
if show_check { 1.0 } else { 0.6 },
motion.spring.snappy,
window,
cx,
)
};
let check_op = arc_transition(
(self.id.clone(), "check-op"),
if show_check { 1.0 } else { 0.0 },
if reduced {
std::time::Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let highlight_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
let guide_color = oklab_mix(colors.text_muted, colors.surface, 0.72);
let mut section_els: Vec<AnyElement> = Vec::new();
for (section_key, label, rows_in_section) in §ions {
let mut rows_el: Vec<AnyElement> = Vec::new();
for entry in rows_in_section {
let row_key = format!("{section_key}-{}", entry.iso);
let is_selected = entry.iso == current.iso;
let is_active = active_iso.as_ref().is_some_and(|a| a.as_ref() == entry.iso);
let check_op_row = arc_transition(
(self.id.clone(), format!("ph-chk-op-{}", entry.iso)),
if is_selected { 1.0 } else { 0.0 },
if reduced {
std::time::Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let check_scale_row = if reduced {
if is_selected { 1.0 } else { 0.6 }
} else {
arc_spring(
(self.id.clone(), format!("ph-chk-sc-{}", entry.iso)),
if is_selected { 1.0 } else { 0.6 },
glide_spec,
window,
cx,
)
};
let row_fg = if is_active || is_selected {
colors.foreground
} else {
colors.text_secondary
};
let entry_clone = *entry;
let int_hover = internal.clone();
let iso_hover = SharedString::from(entry.iso);
let int_pick = internal.clone();
let on_v_pick = self.on_value_change.clone();
let on_c_pick = self.on_country_change.clone();
rows_el.push(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("country-{row_key}")),
))
.test_support()
.role(Role::ListBoxOption)
.aria_label(SharedString::from(format!(
"{} +{}",
entry.name, entry.dial
)))
.w_full()
.flex_none()
.h(px(36.0))
.min_h(px(36.0))
.px(px(10.0))
.flex()
.flex_row()
.items_center()
.gap(px(10.0))
.rounded(px(6.0))
.text_size(Typography::TEXT_SM)
.text_color(row_fg)
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
if *hovered {
int_hover.update(cx, |s, _| {
s.active_iso = Some(iso_hover.clone());
});
window.refresh();
}
})
.on_click(move |_, window, cx| {
let entry = entry_clone;
let t_now = motion_now(cx);
let (cur_digits, cur_iso, q_in) = {
let s = int_pick.read(cx);
(
s.digits.clone(),
s.uncontrolled_iso.clone(),
s.query_input.clone(),
)
};
let changed = entry.iso != cur_iso.as_ref();
let next_digits = phone_cap_digits(entry, &cur_digits);
let ev = PhoneValueEvent {
value: phone_to_e164(entry, &next_digits),
details: build_phone_details(entry, &next_digits),
};
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_pick.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
s.active_iso = None;
if changed {
s.roll_dir = (phone_order_of(entry.iso) as i64
- phone_order_of(cur_iso.as_ref()) as i64)
.signum()
as i8;
s.source_changed_at_secs = t_now;
s.uncontrolled_iso = entry.iso.into();
}
s.digits = next_digits;
});
if changed && let Some(cb) = &on_c_pick {
cb(&SharedString::from(entry.iso), window, cx);
}
if let Some(cb) = &on_v_pick {
cb(&ev, window, cx);
}
window.refresh();
})
.child(
div()
.w(px(20.0))
.flex_none()
.text_size(px(15.0))
.child(SharedString::from(phone_flag_of(entry.iso))),
)
.child(
div()
.flex_1()
.min_w_0()
.font_medium()
.truncate()
.child(SharedString::from(entry.name)),
)
.child(
div()
.flex_none()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(SharedString::from(format!("+{}", entry.dial))),
)
.child(
div().size(px(16.0)).flex_none().child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt =
f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt =
f32::from(rect.origin.y + rect.size.height * 0.5);
paint_scaled_check(
cx_pt,
cy_pt,
check_scale_row,
check_op_row,
colors.foreground,
window,
);
},
)
.size_full(),
),
)
.into_any_element(),
);
}
let group_el = if let Some(label_text) = label {
div()
.flex_none()
.w_full()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.flex_none()
.pt(px(8.0))
.px(px(10.0))
.pb(px(4.0))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(SharedString::from(*label_text)),
)
.children(rows_el)
.into_any_element()
} else {
div()
.flex_none()
.w_full()
.flex()
.flex_col()
.gap(px(2.0))
.children(rows_el)
.into_any_element()
};
section_els.push(group_el);
}
let empty_el = if rows.is_empty() {
Some(
div()
.px(px(10.0))
.pt(px(12.0))
.pb(px(14.0))
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(SharedString::from(format!(
"No countries match \u{201c}{}\u{201d}",
needle.trim()
))),
)
} else {
None
};
let target_hy = {
let mut cur_y = 6.0_f32;
let mut found_y = 6.0_f32;
let mut found = false;
for (sec_idx, (_, label, rows_in_section)) in sections.iter().enumerate() {
if sec_idx > 0 {
cur_y += 2.0;
}
if label.is_some() {
cur_y += 24.0 + 2.0;
}
for (row_idx, entry) in rows_in_section.iter().enumerate() {
if row_idx > 0 {
cur_y += 2.0;
}
if !found && active_iso.as_ref().is_some_and(|a| a.as_ref() == entry.iso) {
found_y = cur_y;
found = true;
}
cur_y += 36.0;
}
}
found_y
};
let pill_y = if reduced || !snap.highlight_seeded {
let _ = arc_spring_with_options(
(self.id.clone(), "hi-y"),
target_hy,
SpringOptions::new(glide_spec).with_initial_value(target_hy),
window,
cx,
);
if menu_open && !snap.highlight_seeded {
internal.update(cx, |s, _| s.highlight_seeded = true);
}
target_hy
} else {
arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx)
};
let int_close = internal.clone();
let control_bounds_ref = snap.control_bounds.clone();
let panel_bounds_ref_out = snap.panel_bounds.clone();
let panel_el = if panel_rendering {
let search_input = KitInput::new(&snap.query_input)
.appearance(false)
.w_full()
.text_size(Typography::TEXT_SM);
let int_clear = internal.clone();
Some(
deferred(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"country-panel".into(),
))
.test_support()
.role(Role::ListBox)
.absolute()
.left_0()
.top_full()
.overflow_hidden()
.w(px(panel_w))
.rounded(px(panel_r))
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.opacity(panel_p)
.on_key_down({
let int_key = internal.clone();
let rows_for_key = rows.clone();
let on_v_key = self.on_value_change.clone();
let on_c_key = self.on_country_change.clone();
move |event: &KeyDownEvent, window, cx| {
if !int_key.read(cx).menu_open {
return;
}
let cur_active = int_key.read(cx).active_iso.clone();
let at = cur_active
.as_ref()
.and_then(|a| {
rows_for_key.iter().position(|r| r.iso == a.as_ref())
})
.unwrap_or(0);
match event.keystroke.key.as_str() {
"escape" => {
let q_in = int_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_key.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
s.active_iso = None;
});
window.refresh();
}
"down" | "arrowdown" => {
let idx = (at + 1).min(rows_for_key.len() - 1);
if let Some(next) = rows_for_key.get(idx) {
int_key.update(cx, |s, _| {
s.active_iso = Some(SharedString::from(next.iso));
});
window.refresh();
}
}
"up" | "arrowup" => {
if let Some(prev) = rows_for_key.get(at.saturating_sub(1)) {
int_key.update(cx, |s, _| {
s.active_iso = Some(SharedString::from(prev.iso));
});
window.refresh();
}
}
"pageup" => {
if let Some(prev) =
rows_for_key.get(at.saturating_sub(PHONE_PAGE))
{
int_key.update(cx, |s, _| {
s.active_iso = Some(SharedString::from(prev.iso));
});
window.refresh();
}
}
"pagedown" => {
let idx = (at + PHONE_PAGE).min(rows_for_key.len() - 1);
if let Some(next) = rows_for_key.get(idx) {
int_key.update(cx, |s, _| {
s.active_iso = Some(SharedString::from(next.iso));
});
window.refresh();
}
}
"enter" => {
if let Some(entry) = rows_for_key.get(at).copied() {
let t_now = motion_now(cx);
let (cur_digits, cur_iso, q_in) = {
let s = int_key.read(cx);
(
s.digits.clone(),
s.uncontrolled_iso.clone(),
s.query_input.clone(),
)
};
let changed = entry.iso != cur_iso.as_ref();
let next_digits = phone_cap_digits(entry, &cur_digits);
let ev = PhoneValueEvent {
value: phone_to_e164(entry, &next_digits),
details: build_phone_details(entry, &next_digits),
};
q_in.update(cx, |s, cx| s.set_value("", window, cx));
int_key.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
s.active_iso = None;
if changed {
s.roll_dir = (phone_order_of(entry.iso) as i64
- phone_order_of(cur_iso.as_ref()) as i64)
.signum()
as i8;
s.source_changed_at_secs = t_now;
s.uncontrolled_iso = entry.iso.into();
}
s.digits = next_digits;
});
if changed && let Some(cb) = &on_c_key {
cb(&SharedString::from(entry.iso), window, cx);
}
if let Some(cb) = &on_v_key {
cb(&ev, window, cx);
}
window.refresh();
}
}
_ => {}
}
}
})
.child(
div()
.relative()
.h(ControlHeights::MD)
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.pl(px(13.0))
.pr(px(2.0))
.child(
Icon::new(IconName::Search)
.text_size(px(16.0))
.text_color(colors.text_muted),
)
.child(
div()
.flex_1()
.min_w_0()
.text_color(colors.foreground)
.child(search_input),
)
.when(!needle.is_empty(), |this| {
this.child(
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"clear-search".into(),
))
.accessibility_label("Clear search")
.on_click(move |_, window, cx| {
let q_in = int_clear.read(cx).query_input.clone();
q_in.update(cx, |s, cx| {
s.set_value("", window, cx);
s.focus(window, cx);
});
window.refresh();
})
.size(px(24.0))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.bg(highlight_bg)
.text_color(colors.text_secondary)
.cursor_pointer()
.child(Icon::new(IconName::Close).text_size(px(14.0))),
)
}),
)
.child(div().mx(px(14.0)).h(px(1.0)).bg(colors.border))
.child(
div()
.flex_none()
.flex()
.flex_col()
.px(px(6.0))
.pb(px(6.0))
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"country-scroll".into(),
))
.test_support()
.relative()
.w_full()
.pt(px(6.0))
.h(px(PHONE_LIST_MAX_H))
.max_h(px(PHONE_LIST_MAX_H))
.overflow_y_scroll()
.on_scroll(|_, _, cx| cx.stop_propagation())
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.absolute()
.left_0()
.right_0()
.top(px(pill_y))
.h(px(36.0))
.rounded(px(6.0))
.bg(highlight_bg),
)
.children(section_els)
.children(empty_el),
),
)
.child(
canvas(
{
let probe = panel_bounds_ref_out.clone();
move |rect, _, _| {
*probe.borrow_mut() = Some(rect);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(canvas(
|_, _, _| {},
move |_, _, window, _| {
let c_ref = control_bounds_ref.clone();
let p_ref = panel_bounds_ref_out.clone();
let st = int_close.clone();
window.on_mouse_event(
move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let in_ctrl = c_ref
.borrow()
.is_some_and(|b| b.contains(&event.position));
let in_panel = p_ref
.borrow()
.is_some_and(|b| b.contains(&event.position));
if !in_ctrl && !in_panel {
st.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
s.active_iso = None;
});
window.refresh();
}
},
);
},
)),
)
.with_priority(25),
)
} else {
None
};
let int_key = internal.clone();
let on_v_change_key = self.on_value_change.clone();
let on_c_change_key = self.on_country_change.clone();
let disabled_key = self.disabled;
let focus_handle_key = snap.focus_handle.clone();
let focus_for_wrap = snap.focus_handle.clone();
let control = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"control".into(),
))
.test_support()
.role(Role::Group)
.track_focus(&focus_handle_key)
.on_hover({
let int_h = internal.clone();
move |hovered, window, cx| {
int_h.update(cx, |s, _| s.control_hovered = *hovered);
window.refresh();
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if disabled_key || int_key.read(cx).menu_open {
return;
}
let key = event.keystroke.key.as_str();
let ctrl_or_platform =
event.keystroke.modifiers.control || event.keystroke.modifiers.platform;
let t_now = motion_now(cx);
if key == "+" && !ctrl_or_platform {
int_key.update(cx, |s, _| {
s.menu_open = true;
s.highlight_seeded = false;
});
let q_in = int_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| {
s.set_value("+", window, cx);
s.focus(window, cx);
});
window.refresh();
return;
}
if ctrl_or_platform && key == "v" {
let pasted = cx
.read_from_clipboard()
.and_then(|item| item.text())
.unwrap_or_default();
let entry = current;
let parsed = if pasted.trim_start().starts_with('+')
|| pasted.trim_start().starts_with("00")
{
phone_parse_number(&pasted)
} else {
None
};
let (entry, next_digits) = match parsed {
Some((entry, national)) if !national.is_empty() => (entry, national),
_ => {
let mut fragment = phone_only_digits(&pasted);
let cap_len = phone_cap_digits(entry, &fragment).len();
if fragment.starts_with(entry.dial) && fragment.len() > cap_len {
fragment = fragment[entry.dial.len()..].to_string();
}
(entry, phone_cap_digits(entry, &fragment))
}
};
let changed_iso = entry.iso != current.iso;
let ev = PhoneValueEvent {
value: phone_to_e164(entry, &next_digits),
details: build_phone_details(entry, &next_digits),
};
int_key.update(cx, |s, _| {
if changed_iso {
s.roll_dir = (phone_order_of(entry.iso) as i64
- phone_order_of(current.iso) as i64)
.signum() as i8;
s.source_changed_at_secs = t_now;
s.uncontrolled_iso = entry.iso.into();
}
s.digits = next_digits;
});
if changed_iso && let Some(cb) = &on_c_change_key {
cb(&SharedString::from(entry.iso), window, cx);
}
if let Some(cb) = &on_v_change_key {
cb(&ev, window, cx);
}
window.refresh();
return;
}
let digit_char = event
.keystroke
.key_char
.as_deref()
.and_then(|kc| (kc.len() == 1).then(|| kc.chars().next()).flatten())
.filter(|c| c.is_ascii_digit())
.or_else(|| {
(key.len() == 1)
.then(|| key.chars().next())
.flatten()
.filter(|c| c.is_ascii_digit())
});
if let Some(digit) = digit_char
&& !ctrl_or_platform
{
let entry = current;
let next = {
let s = int_key.read(cx);
let candidate = format!("{}{digit}", s.digits);
phone_cap_digits(entry, &candidate)
};
let ev = PhoneValueEvent {
value: phone_to_e164(entry, &next),
details: build_phone_details(entry, &next),
};
int_key.update(cx, |s, _| {
s.digits = next;
s.seen_value = Some(ev.value.clone());
});
if let Some(cb) = &on_v_change_key {
cb(&ev, window, cx);
}
window.refresh();
return;
}
if key == "backspace" {
let entry = current;
let next: String = {
let s = int_key.read(cx);
s.digits
.chars()
.take(s.digits.len().saturating_sub(1))
.collect()
};
let ev = PhoneValueEvent {
value: phone_to_e164(entry, &next),
details: build_phone_details(entry, &next),
};
int_key.update(cx, |s, _| {
s.digits = next;
s.seen_value = Some(ev.value.clone());
});
if let Some(cb) = &on_v_change_key {
cb(&ev, window, cx);
}
window.refresh();
}
})
.relative()
.w_full()
.h(ControlHeights::MD)
.px(px(1.0))
.flex()
.flex_row()
.items_center()
.rounded(Radii::CONTROL)
.border_1()
.border_color(control_border)
.bg(if self.disabled {
colors.surface_muted
} else {
colors.surface
})
.opacity(if self.disabled { 0.5 } else { 1.0 })
.child(
canvas(
{
let probe = snap.control_bounds.clone();
move |rect, _, _| {
*probe.borrow_mut() = Some(rect);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(
div()
.relative()
.h_full()
.flex_none()
.when_some(panel_el, |this, panel| this.child(panel))
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"trigger".into(),
))
.test_support()
.role(Role::Button)
.aria_label(SharedString::from(format!(
"Country, {} +{}",
current.name, current.dial
)))
.relative()
.h_full()
.pl(px(11.0))
.pr(px(33.0))
.flex()
.flex_row()
.items_center()
.gap(px(6.0))
.rounded(px(PHONE_CLOSED_RADIUS - 4.0))
.when(
!self.disabled && (snap.trigger_hovered || menu_open),
|this| this.bg(colors.surface_muted),
)
.when(!self.disabled, |this| {
this.cursor_pointer().on_hover({
let int_t = internal.clone();
move |hovered, window, cx| {
int_t.update(cx, |s, _| s.trigger_hovered = *hovered);
window.refresh();
}
})
})
.on_click({
let int_t = internal.clone();
let disabled_t = self.disabled;
let focus_t = snap.focus_handle.clone();
move |_, window, cx| {
if disabled_t {
return;
}
window.focus(&focus_t, cx);
let will_open = !int_t.read(cx).menu_open;
int_t.update(cx, |s, _| {
s.menu_open = !s.menu_open;
s.highlight_seeded = false;
});
if will_open {
let q_in = int_t.read(cx).query_input.clone();
q_in.update(cx, |s, cx| {
s.set_value("", window, cx);
s.focus(window, cx);
});
}
window.refresh();
}
})
.child(
div()
.mt(px(flag_y))
.opacity(flag_op)
.flex()
.flex_row()
.items_center()
.gap(px(6.0))
.child(
div()
.w(px(20.0))
.flex_none()
.text_size(px(17.0))
.child(SharedString::from(phone_flag_of(current.iso))),
)
.child(
div()
.flex_none()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(SharedString::from(format!(
"+{}",
current.dial
))),
),
)
.child(
div()
.absolute()
.right(px(12.0))
.top(px(14.0))
.size(px(16.0))
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt = f32::from(
rect.origin.x + rect.size.width * 0.5,
);
let cy_pt = f32::from(
rect.origin.y + rect.size.height * 0.5,
);
paint_rotated_chevron(
cx_pt,
cy_pt,
chevron_deg,
colors.text_muted,
window,
);
},
)
.size_full(),
),
)
.child(
canvas(
{
let probe = snap.trigger_bounds.clone();
move |rect, _, _| {
*probe.borrow_mut() = Some(rect);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
),
),
)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"number-wrap".into(),
))
.test_support()
.flex_1()
.min_w_0()
.h_full()
.flex()
.items_center()
.pl(px(11.0))
.pr(px(36.0))
.when(!self.disabled, |this| {
let focus_down = focus_for_wrap.clone();
this.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
window.focus(&focus_down, cx);
window.refresh();
})
.on_click({
let int_n = internal.clone();
move |_, window, cx| {
window.focus(&focus_for_wrap, cx);
let _ = &int_n;
window.refresh();
}
})
})
.child(
div()
.flex()
.flex_row()
.items_center()
.min_w_0()
.whitespace_nowrap()
.text_size(Typography::TEXT_SM)
.child(
div()
.flex_none()
.text_color(colors.foreground)
.child(SharedString::from(formatted.clone())),
)
.when(is_focused && !menu_open && !self.disabled, |this| {
this.child(
div()
.mx(px(1.0))
.w(px(1.5))
.h(px(16.0))
.bg(colors.foreground),
)
})
.when(!guide.is_empty(), |this| {
this.child(
div()
.flex_none()
.text_color(guide_color)
.child(SharedString::from(guide.clone())),
)
}),
)
.child(
div()
.absolute()
.right(px(12.0))
.top(px(13.0))
.size(px(18.0))
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt =
f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt =
f32::from(rect.origin.y + rect.size.height * 0.5);
paint_scaled_check(
cx_pt,
cy_pt,
check_scale,
check_op,
colors.success,
window,
);
},
)
.size_full(),
),
),
);
let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
let msg_text = effective_error.clone().or(self.description);
div()
.id(self.id)
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.when(!self.hide_label, |this| {
this.child(
div()
.mb(Spacing::S2)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label),
)
})
.child(control)
.child(render_field_message(
msg_id, msg_text, is_invalid, window, cx,
))
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{ClipboardItem, Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
#[test]
fn phone_patterns_format_national_numbers_with_trunk_prefix() {
let us = phone_country_by_iso("US").unwrap();
assert_eq!(phone_format_national(us, "2015550123"), "(201) 555-0123");
assert_eq!(phone_to_e164(us, "2015550123"), "+12015550123");
let gb = phone_country_by_iso("GB").unwrap();
assert_eq!(phone_format_national(gb, "07911123456"), "07911 123456");
assert_eq!(phone_status_of(gb, "07911123456"), PhoneStatus::Valid);
assert_eq!(phone_status_of(gb, ""), PhoneStatus::Empty);
assert_eq!(phone_status_of(gb, "07911"), PhoneStatus::Incomplete);
assert_eq!(phone_status_of(gb, "079111234567"), PhoneStatus::TooLong);
}
#[test]
fn phone_parse_number_resolves_longest_dial_and_area_codes() {
let (entry, national) = phone_parse_number("+353850123456").unwrap();
assert_eq!(entry.iso, "IE");
assert_eq!(national, "850123456");
let (entry, national) = phone_parse_number("+14165550123").unwrap();
assert_eq!(entry.iso, "CA");
assert_eq!(national, "4165550123");
let (entry, national) = phone_parse_number("+44 (0)7400 123456").unwrap();
assert_eq!(entry.iso, "GB");
assert_eq!(national, "7400123456");
let (entry, _) = phone_parse_number("0041 78 123 45 67").unwrap();
assert_eq!(entry.iso, "CH");
assert!(phone_parse_number("not a phone").is_none());
}
#[test]
fn phone_cap_digits_earn_trunk_room_and_format_e164_round_trips() {
let gb = phone_country_by_iso("GB").unwrap();
assert_eq!(phone_cap_digits(gb, "0791112345678"), "07911123456");
let e164 = phone_to_e164(gb, "07911123456");
assert_eq!(e164, "+447911123456");
assert_eq!(phone_format_e164(&e164), "+44 7911 123456");
}
#[test]
fn phone_matches_query_matches_dials_names_and_iso() {
let us = phone_country_by_iso("US").unwrap();
let de = phone_country_by_iso("DE").unwrap();
assert!(phone_matches_query(us, "1"));
assert!(phone_matches_query(us, "+1"));
assert!(phone_matches_query(de, "49"));
assert!(phone_matches_query(de, "germ"));
assert!(phone_matches_query(de, "de"));
assert!(!phone_matches_query(de, "44"));
assert!(phone_matches_query(us, "+"));
}
struct PhoneHost {
value: String,
iso: SharedString,
disabled: bool,
events: Rc<RefCell<Vec<String>>>,
countries_seen: Rc<RefCell<Vec<SharedString>>>,
}
impl Render for PhoneHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
let countries_seen = self.countries_seen.clone();
div().w(px(560.0)).p(px(16.0)).child(
PhoneInput::new("phone-test", "Phone")
.value(self.value.clone())
.country(self.iso.clone())
.disabled(self.disabled)
.on_value_change(cx.listener({
let events = events.clone();
move |this, event: &PhoneValueEvent, _, cx| {
events.borrow_mut().push(event.value.clone());
this.value = event.value.clone();
cx.notify();
}
}))
.on_country_change(cx.listener({
let countries_seen = countries_seen.clone();
move |this, iso: &SharedString, _, cx| {
countries_seen.borrow_mut().push(iso.clone());
this.iso = iso.clone();
cx.notify();
}
})),
)
}
}
fn phone_element(name: &str) -> ElementId {
ElementId::NamedChild(ElementId::Name("phone-test".into()).into(), name.into())
}
#[gpui_kit::test]
fn phone_input_types_backspaces_picks_country_and_parses_paste(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let host = PhoneHost {
value: String::new(),
iso: "US".into(),
disabled: false,
events: Rc::new(RefCell::new(Vec::new())),
countries_seen: Rc::new(RefCell::new(Vec::new())),
};
let events = host.events.clone();
let countries_seen = host.countries_seen.clone();
let (view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
let trigger = window.find(phone_element("trigger"));
assert_eq!(trigger.role(), Some(Role::Button));
window.click(phone_element("number-wrap"), cx);
window.input("201555", cx);
});
assert_eq!(events.borrow().last(), Some(&"+1201555".to_string()));
cx.update(|window, cx| {
window.press("backspace", cx);
});
assert_eq!(events.borrow().last(), Some(&"+120155".to_string()));
cx.update(|window, cx| {
window.click(phone_element("trigger"), cx);
window.render_frame(cx);
let panel = window.find(phone_element("country-panel"));
assert_eq!(panel.role(), Some(Role::ListBox));
let row = window.find(phone_element("country-preferred-CA"));
assert_eq!(row.role(), Some(Role::ListBoxOption));
window.click(phone_element("country-preferred-CA"), cx);
});
assert_eq!(
countries_seen.borrow().last().map(|c| c.to_string()),
Some("CA".to_string())
);
cx.update(|window, cx| {
window.click(phone_element("number-wrap"), cx);
});
cx.update(|_window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string("+447911123456".to_string()));
});
cx.update(|window, cx| {
window.press("ctrl-v", cx);
});
assert_eq!(
countries_seen.borrow().last().map(|c| c.to_string()),
Some("GB".to_string())
);
assert_eq!(events.borrow().last(), Some(&"+447911123456".to_string()));
cx.update(|window, cx| {
window.click(phone_element("number-wrap"), cx);
window.press("+", cx);
window.render_frame(cx);
assert!(window.try_find(phone_element("country-panel")).is_some());
});
view.update(cx, |host, cx| {
host.disabled = true;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
window.click(phone_element("number-wrap"), cx);
window.input("7", cx);
});
assert_eq!(events.borrow().last(), Some(&"+447911123456".to_string()));
}
#[gpui_kit::test]
fn phone_input_reduced_motion_keeps_interactions_instant(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let host = PhoneHost {
value: String::new(),
iso: "US".into(),
disabled: false,
events: Rc::new(RefCell::new(Vec::new())),
countries_seen: Rc::new(RefCell::new(Vec::new())),
};
let events = host.events.clone();
let (_view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
window.click(phone_element("number-wrap"), cx);
window.input("20", cx);
});
assert_eq!(
events.borrow().as_slice(),
["+12".to_string(), "+120".to_string()]
);
}
}