Skip to content
Browse documentation

An international hairline phone input with searchable calling codes, caret-safe national formatting, automatic +E.164 country detection and structured output.

Used forAccount sign-up and SMS 2FACheckout and shipping formsCRM and contact drawersRegional SaaS onboarding

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/phone-input.json

Registered the namespace? Then it’s shadcn add @hairline/phone-input. Set it up

Templates

Need the whole page?

63 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

All 63 templates

Where it’s used

  • Account sign-up and SMS 2FA

    Collect clean E.164 strings (+14155550192) ready for Twilio, Clerk or Supabase Auth without pulling in libphonenumber.

  • Checkout and shipping forms

    Format national numbers cleanly as customers type without jumping the caret on mid-string edits.

  • CRM and contact drawers

    Paste international numbers from emails or Slack and let the picker switch countries automatically.

  • Regional SaaS onboarding

    Pass a filtered countries prop when your product operates in a specific set of markets.

What it handles for you

Good phone inputs should format cleanly without stealing the cursor, recognise pasted international codes automatically and hand clean E.164 strings to your backend.

Instead of wiring upreact-phone-number-inputlibphonenumber-js UI wrappercustom dial-code selectflag sprite sheets
  1. Caret-safe national grouping

    Tracks exact digit counts ahead of the cursor before formatting so inserting or deleting digits in the middle never jumps the caret.

  2. Automatic +E.164 country detection

    Pasting or typing a number starting with + or 00 matches the longest calling code, switches the country selector and strips optional trunk zeros.

  3. Zero emoji-flag glitches

    Uses crisp hairline monospace ISO badges (US, GB, IN) beside tabular dial codes so rendering stays sharp on Windows, Linux and macOS alike.

  4. Searchable keyboard country picker

    Filter all 36 built-in countries by name, ISO code or calling code with Arrow keys, Enter and Escape.

  5. Optical valid completion and blur guard

    Valid national lengths morph in an emerald check with a quiet 8×8 Bayer floor sweep; incomplete blurs trigger a gentle spring recoil and inline length hint.

  6. Structured output and parser helper

    Emits { e164, national, digits, country, dialCode, valid } on every change and exports parsePhoneNumber() and PHONE_COUNTRIES.

Overview

International phone inputs usually bring heavy dependencies, inconsistent emoji flags across operating systems and aggressive formatters that jump the cursor while editing. PhoneInput ships a built-in table of 36 major markets with crisp monospace ISO badges that render identically on every platform, caret-safe as-you-type national grouping and a searchable country popover with full keyboard navigation. Paste any full international number (+44 7700 900077, +91 98765 43210, +81 90-1234-5678) and it detects the country automatically, switches the dial code, strips trunk zeros where required and sweeps an optical 8×8 Bayer confirmation pulse across the lower rail. On completion it emits clean structured E.164 data and exports parsePhoneNumber() so server actions and forms share the exact same rules.

States

empty
Shows active country ISO badge, calling code and a realistic national placeholder example for that market.
typing
Formats national digits live into the country pattern while restoring the caret cleanly after the exact digit edited.
country detected
Pasting an international number switches the calling code automatically and sweeps a brief blue Bayer pulse across the lower edge.
valid
When digit length matches the country rules, an emerald check morphs into place alongside a quiet emerald Bayer floor confirmation.
incomplete on blur
A damped horizontal recoil nudges the field with a brief rose Bayer floor pulse and unfolds an exact digit-count message inline.
country popover open
Searchable hairline listbox filters by country name, ISO code or dial prefix with keyboard navigation.

Usage

usage.tsx
import { PhoneInput } from "@/components/phone-input";<PhoneInput  label="Mobile number"  defaultCountry="US"  onChange={(phone) => {    if (phone.valid) setE164(phone.e164);  }}/>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

SMS verification step wired to clean E.164 submission

Read phone.valid and phone.e164 straight from onChange so your SMS endpoint only receives verified international strings.

example.tsx
"use client";import { useState } from "react";import { PhoneInput, type PhoneValue } from "@/components/phone-input";export function SmsSignIn({ onSendCode }: { onSendCode: (e164: string) => Promise<void> }) {  const [phone, setPhone] = useState<PhoneValue | null>(null);  return (    <form      onSubmit={(e) => {        e.preventDefault();        if (phone?.valid) void onSendCode(phone.e164);      }}      className="space-y-3"    >      <PhoneInput label="Mobile number" defaultCountry="US" onChange={setPhone} />      <button        type="submit"        disabled={!phone?.valid}        className="h-10 w-full rounded-xl bg-foreground text-sm font-medium text-background disabled:opacity-40"      >        Send verification code      </button>    </form>  );}

Props

value / defaultValue / onChange
string / string / (v: PhoneValue) => void
Controlled or uncontrolled E.164 or national value plus callback emitting { e164, national, digits, country, dialCode, valid }.
country / defaultCountry / onCountryChange= "US"
string / string / (iso) => void
Controlled or initial ISO 3166-1 alpha-2 country code.
countries= PHONE_COUNTRIES (36)
PhoneCountry[]
Optional subset or custom calling-code list.
validateOnBlur / clearable / label / disabled / sound= true / true / "Phone number" / false / false
boolean / boolean / string / boolean / boolean
Incomplete-number blur validation, inline clear button, accessible label, disabled state and opt-in Web Audio cues.
parsePhoneNumber / PHONE_COUNTRIES
exported utility / array
Parse any E.164 or national string outside the input with identical country and length rules.

Accessibility and motion

  • Calling-code detection sorts longest prefixes first (+971 before +9, +353 before +35) and respects the active country on shared codes such as +1 (US and Canada).
  • Monospace ISO badges replace emoji flags so rendering stays crisp and uniform on Windows, Linux and macOS.
  • The 8×8 Bayer optical floor sleeps completely at 0% CPU except during the ~0.5s valid, auto-detect or error confirmation sweep.
  • Under prefers-reduced-motion: reduce, horizontal recoil and Bayer sweeps are skipped while all formatting, auto-detection and keyboard navigation remain active.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Text morph.

Source

"use client";import * as React from "react";import { Check, ChevronDown, Search, X } from "lucide-react";import {  EASE_OUT,  INTERACTION_FOCUS,  INTERACTION_PRESS,  MATERIAL_LIFT,  createSpring,  useInteractionActivity,  useInteractionReducedMotion,  type Spring,} from "./ui-interaction-motion";import { TextMorph } from "./text-morph";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * PHONE INPUT: international hairline phone field & E.164 parser * *   format    formats national digits as you type using each *             country's grouping template while locking the caret *             to the exact digit you edited (zero caret jumps) * *   paste     pasting any full international number (+44 7700..., *             +91 98765..., +81 90-1234...) automatically detects *             the country, switches the dial code, strips trunk 0s *             and sweeps an optical 8×8 Bayer lock-in confirmation * *   infra     zero external phone libraries or flag image assets; *             emits structured { e164, national, digits, country, *             dialCode, valid } and exports parsePhoneNumber() * ───────────────────────────────────────────────────────── */export interface PhoneCountry {  /** ISO 3166-1 alpha-2 code (e.g. "US", "GB", "IN"). */  iso: string;  /** English country name for search and screen readers. */  name: string;  /** Calling code without leading "+" (e.g. "1", "44", "91"). */  dial: string;  /** National grouping mask using "#" placeholders. */  pattern: string;  /** Minimum valid national digit count. */  minDigits: number;  /** Maximum valid national digit count. */  maxDigits: number;  /** Realistic placeholder example. */  example: string;  /** Strip a leading trunk "0" when pasted after the international dial code. */  stripTrunkZero?: boolean;}export interface PhoneValue {  /** Full E.164 string (e.g. "+14155550192"), or "" when empty. */  e164: string;  /** Formatted national representation (e.g. "(415) 555-0192"). */  national: string;  /** Raw national digits only (e.g. "4155550192"). */  digits: string;  /** Active ISO country code. */  country: string;  /** Calling code with leading "+" (e.g. "+1"). */  dialCode: string;  /** True when digits fall cleanly within the country's valid length range. */  valid: boolean;}export interface PhoneInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange"> {  /** Controlled E.164 value (e.g. "+14155550192") or raw phone string. */  value?: string;  /** Initial uncontrolled phone value. */  defaultValue?: string;  /** Default ISO country code when value has no dial prefix (default "US"). */  defaultCountry?: string;  /** Controlled ISO country code. */  country?: string;  onCountryChange?: (iso: string) => void;  /** Fires on every edit or country switch with full structured phone details. */  onChange?: (value: PhoneValue) => void;  /** Optional subset or custom list of countries (defaults to built-in 36-country table). */  countries?: PhoneCountry[];  /** Validate and surface inline error on blur when partially entered (default true). */  validateOnBlur?: boolean;  /** Show inline clear button when populated (default true). */  clearable?: boolean;  /** Accessible name for the phone input (default "Phone number"). */  label?: string;  /** Disabled state. */  disabled?: boolean;  /** Opt-in quiet Web Audio ticks on country switch and valid completion (from ui-sounds.ts). */  sound?: boolean;}export const PHONE_COUNTRIES: PhoneCountry[] = [  { iso: "US", name: "United States", dial: "1", pattern: "(###) ###-####", minDigits: 10, maxDigits: 10, example: "(415) 555-0192" },  { iso: "GB", name: "United Kingdom", dial: "44", pattern: "#### ######", minDigits: 10, maxDigits: 10, example: "7700 900077", stripTrunkZero: true },  { iso: "IN", name: "India", dial: "91", pattern: "##### #####", minDigits: 10, maxDigits: 10, example: "98765 43210", stripTrunkZero: true },  { iso: "CA", name: "Canada", dial: "1", pattern: "(###) ###-####", minDigits: 10, maxDigits: 10, example: "(416) 555-0148" },  { iso: "AU", name: "Australia", dial: "61", pattern: "### ### ###", minDigits: 9, maxDigits: 9, example: "412 345 678", stripTrunkZero: true },  { iso: "DE", name: "Germany", dial: "49", pattern: "### ########", minDigits: 10, maxDigits: 11, example: "151 23456789", stripTrunkZero: true },  { iso: "FR", name: "France", dial: "33", pattern: "# ## ## ## ##", minDigits: 9, maxDigits: 9, example: "6 12 34 56 78", stripTrunkZero: true },  { iso: "JP", name: "Japan", dial: "81", pattern: "##-####-####", minDigits: 10, maxDigits: 10, example: "90-1234-5678", stripTrunkZero: true },  { iso: "SG", name: "Singapore", dial: "65", pattern: "#### ####", minDigits: 8, maxDigits: 8, example: "8123 4567" },  { iso: "AE", name: "United Arab Emirates", dial: "971", pattern: "## ### ####", minDigits: 9, maxDigits: 9, example: "50 123 4567", stripTrunkZero: true },  { iso: "NL", name: "Netherlands", dial: "31", pattern: "# ########", minDigits: 9, maxDigits: 9, example: "6 12345678", stripTrunkZero: true },  { iso: "ES", name: "Spain", dial: "34", pattern: "### ### ###", minDigits: 9, maxDigits: 9, example: "612 345 678" },  { iso: "IT", name: "Italy", dial: "39", pattern: "### ### ####", minDigits: 9, maxDigits: 10, example: "312 345 6789" },  { iso: "CH", name: "Switzerland", dial: "41", pattern: "## ### ## ##", minDigits: 9, maxDigits: 9, example: "79 123 45 67", stripTrunkZero: true },  { iso: "SE", name: "Sweden", dial: "46", pattern: "##-### ## ##", minDigits: 9, maxDigits: 9, example: "70-123 45 67", stripTrunkZero: true },  { iso: "IE", name: "Ireland", dial: "353", pattern: "## ### ####", minDigits: 9, maxDigits: 9, example: "85 123 4567", stripTrunkZero: true },  { iso: "BR", name: "Brazil", dial: "55", pattern: "(##) #####-####", minDigits: 10, maxDigits: 11, example: "(11) 91234-5678" },  { iso: "MX", name: "Mexico", dial: "52", pattern: "## #### ####", minDigits: 10, maxDigits: 10, example: "55 1234 5678" },  { iso: "KR", name: "South Korea", dial: "82", pattern: "##-####-####", minDigits: 9, maxDigits: 10, example: "10-1234-5678", stripTrunkZero: true },  { iso: "CN", name: "China", dial: "86", pattern: "### #### ####", minDigits: 11, maxDigits: 11, example: "138 0013 8000" },  { iso: "HK", name: "Hong Kong", dial: "852", pattern: "#### ####", minDigits: 8, maxDigits: 8, example: "5123 4567" },  { iso: "NZ", name: "New Zealand", dial: "64", pattern: "## ### ####", minDigits: 8, maxDigits: 9, example: "21 123 4567", stripTrunkZero: true },  { iso: "ZA", name: "South Africa", dial: "27", pattern: "## ### ####", minDigits: 9, maxDigits: 9, example: "82 123 4567", stripTrunkZero: true },  { iso: "PL", name: "Poland", dial: "48", pattern: "### ### ###", minDigits: 9, maxDigits: 9, example: "512 345 678" },  { iso: "PT", name: "Portugal", dial: "351", pattern: "### ### ###", minDigits: 9, maxDigits: 9, example: "912 345 678" },  { iso: "NO", name: "Norway", dial: "47", pattern: "### ## ###", minDigits: 8, maxDigits: 8, example: "412 34 567" },  { iso: "DK", name: "Denmark", dial: "45", pattern: "## ## ## ##", minDigits: 8, maxDigits: 8, example: "20 12 34 56" },  { iso: "FI", name: "Finland", dial: "358", pattern: "## ### ####", minDigits: 9, maxDigits: 10, example: "40 123 4567", stripTrunkZero: true },  { iso: "BE", name: "Belgium", dial: "32", pattern: "### ## ## ##", minDigits: 9, maxDigits: 9, example: "470 12 34 56", stripTrunkZero: true },  { iso: "AT", name: "Austria", dial: "43", pattern: "### #######", minDigits: 10, maxDigits: 11, example: "664 1234567", stripTrunkZero: true },  { iso: "IL", name: "Israel", dial: "972", pattern: "##-###-####", minDigits: 9, maxDigits: 9, example: "50-123-4567", stripTrunkZero: true },  { iso: "TR", name: "Turkey", dial: "90", pattern: "### ### ## ##", minDigits: 10, maxDigits: 10, example: "532 123 45 67", stripTrunkZero: true },  { iso: "ID", name: "Indonesia", dial: "62", pattern: "###-####-####", minDigits: 9, maxDigits: 12, example: "812-3456-7890", stripTrunkZero: true },  { iso: "PH", name: "Philippines", dial: "63", pattern: "### ### ####", minDigits: 10, maxDigits: 10, example: "917 123 4567", stripTrunkZero: true },  { iso: "VN", name: "Vietnam", dial: "84", pattern: "## ### ####", minDigits: 9, maxDigits: 10, example: "91 234 5678", stripTrunkZero: true },  { iso: "NG", name: "Nigeria", dial: "234", pattern: "### ### ####", minDigits: 10, maxDigits: 10, example: "802 123 4567", stripTrunkZero: true },];const BAYER8: Float32Array = (() => {  const m = [    [0, 32, 8, 40, 2, 34, 10, 42],    [48, 16, 56, 24, 50, 18, 58, 26],    [12, 44, 4, 36, 14, 46, 6, 38],    [60, 28, 52, 20, 62, 30, 54, 22],    [3, 35, 11, 43, 1, 33, 9, 41],    [51, 19, 59, 27, 49, 17, 57, 25],    [15, 47, 7, 39, 13, 45, 5, 37],    [63, 31, 55, 23, 61, 29, 53, 21],  ];  const out = new Float32Array(64);  for (let y = 0; y < 8; y++) {    for (let x = 0; x < 8; x++) {      out[(y << 3) | x] = (m[y][x] + 0.5) / 64;    }  }  return out;})();const IS_LE = (() => {  const b = new ArrayBuffer(4);  new Uint32Array(b)[0] = 0x0a0b0c0d;  return new Uint8Array(b)[0] === 0x0d;})();function packRgba(r: number, g: number, b: number, a: number): number {  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;}const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);const clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);function onlyDigits(s: string): string {  return s.replace(/\D+/g, "");}/** Format national digits according to a country's "#" grouping template (never leaves dangling separators). */function formatNational(digits: string, pattern: string): string {  if (!digits) return "";  let out = "";  let dIdx = 0;  for (let i = 0; i < pattern.length && dIdx < digits.length; i++) {    const ch = pattern[i];    if (ch === "#") {      out += digits[dIdx++];    } else {      // Only append literal separator if another digit follows (or leading "(" before first digit)      if (dIdx < digits.length) out += ch;    }  }  if (dIdx < digits.length) out += digits.slice(dIdx);  return out;}/** Find the formatted string index sitting immediately after the Nth digit (caret-safe grouping). */function caretAfterDigitCount(formatted: string, digitCount: number): number {  if (digitCount <= 0) return 0;  let seen = 0;  for (let i = 0; i < formatted.length; i++) {    if (formatted[i] >= "0" && formatted[i] <= "9") {      seen++;      if (seen === digitCount) return i + 1;    }  }  return formatted.length;}/** Detect a country from a "+<dial>..." or "00<dial>..." international prefix (longest dial match first). */function detectCountryFromInternational(  raw: string,  countries: PhoneCountry[],  preferredIso?: string,): { country: PhoneCountry; nationalDigits: string } | null {  const trimmed = raw.trim();  const isIntl = trimmed.startsWith("+") || trimmed.startsWith("00");  if (!isIntl) return null;  let allDigits = onlyDigits(trimmed);  if (trimmed.startsWith("00")) allDigits = allDigits.slice(2);  if (!allDigits) return null;  // Sort longest dial code first so +971 matches before +9, +353 before +35, etc.  const sorted = [...countries].sort((a, b) => {    if (b.dial.length !== a.dial.length) return b.dial.length - a.dial.length;    if (a.iso === preferredIso) return -1;    if (b.iso === preferredIso) return 1;    return 0;  });  for (const c of sorted) {    if (allDigits.startsWith(c.dial)) {      let rest = allDigits.slice(c.dial.length);      if (c.stripTrunkZero && rest.startsWith("0") && rest.length > c.minDigits) {        rest = rest.slice(1);      }      return { country: c, nationalDigits: rest.slice(0, c.maxDigits) };    }  }  return null;}/** Parse any phone string (E.164 or national) into a structured PhoneValue using the built-in country table. */export function parsePhoneNumber(  raw: string,  fallbackIso = "US",  countries: PhoneCountry[] = PHONE_COUNTRIES,): PhoneValue {  const fallback = countries.find((c) => c.iso === fallbackIso.toUpperCase()) ?? countries[0];  const detected = detectCountryFromInternational(raw, countries, fallback.iso);  const country = detected?.country ?? fallback;  const digits = detected ? detected.nationalDigits : onlyDigits(raw).slice(0, country.maxDigits);  const national = formatNational(digits, country.pattern);  const valid = digits.length >= country.minDigits && digits.length <= country.maxDigits;  return {    e164: digits ? `+${country.dial}${digits}` : "",    national,    digits,    country: country.iso,    dialCode: `+${country.dial}`,    valid,  };}export function PhoneInput({  value: controlledValue,  defaultValue = "",  defaultCountry = "US",  country: controlledCountry,  onCountryChange,  onChange,  countries = PHONE_COUNTRIES,  validateOnBlur = true,  clearable = true,  label = "Phone number",  disabled = false,  sound = false,  className = "",  ...props}: PhoneInputProps) {  const reduced = useInteractionReducedMotion();  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();  const initialParsed = React.useMemo(    () => parsePhoneNumber(controlledValue ?? defaultValue, controlledCountry ?? defaultCountry, countries),    // eslint-disable-next-line react-hooks/exhaustive-deps    [],  );  const [ownCountryIso, setOwnCountryIso] = React.useState(initialParsed.country);  const [ownDigits, setOwnDigits] = React.useState(initialParsed.digits);  const [intlDraft, setIntlDraft] = React.useState<string | null>(null);  const [focused, setFocused] = React.useState(false);  const [touched, setTouched] = React.useState(false);  const [open, setOpen] = React.useState(false);  const [query, setQuery] = React.useState("");  const [activeIdx, setActiveIdx] = React.useState(0);  const [liveStatus, setLiveStatus] = React.useState("");  // Derive active country & digits cleanly for both controlled and uncontrolled usage  const activeCountryIso = controlledCountry ?? ownCountryIso;  const parsedControlled = React.useMemo(() => {    if (controlledValue === undefined) return null;    return parsePhoneNumber(controlledValue, activeCountryIso, countries);  }, [controlledValue, activeCountryIso, countries]);  const resolvedIso = controlledCountry ?? parsedControlled?.country ?? ownCountryIso;  const activeCountry = React.useMemo(    () => countries.find((c) => c.iso === resolvedIso) ?? countries[0],    [countries, resolvedIso],  );  const digits = parsedControlled ? parsedControlled.digits : ownDigits;  const national = React.useMemo(() => formatNational(digits, activeCountry.pattern), [digits, activeCountry.pattern]);  const isValid = digits.length >= activeCountry.minDigits && digits.length <= activeCountry.maxDigits;  const showError = validateOnBlur && touched && !focused && digits.length > 0 && !isValid;  const shellRef = React.useRef<HTMLDivElement>(null);  const inputRef = React.useRef<HTMLInputElement>(null);  const searchRef = React.useRef<HTMLInputElement>(null);  const floorCanvasRef = React.useRef<HTMLCanvasElement>(null);  const recoilRef = React.useRef<Spring | null>(null);  const flashRef = React.useRef<((kind: "valid" | "detect" | "error") => void) | null>(null);  const prevValidRef = React.useRef(isValid);  const filteredCountries = React.useMemo(() => {    const q = query.trim().toLowerCase();    if (!q) return countries;    const digitsQ = q.replace(/^\+/, "");    return countries.filter(      (c) =>        c.name.toLowerCase().includes(q) ||        c.iso.toLowerCase().includes(q) ||        c.dial.startsWith(digitsQ) ||        `+${c.dial}`.startsWith(q),    );  }, [countries, query]);  // Horizontal recoil spring on invalid blur  React.useEffect(() => {    const sp = createSpring(      0,      { stiffness: 450, damping: 17 },      () => {        const el = shellRef.current;        if (!el) return;        const x = sp.get();        el.style.transform = Math.abs(x) > 0.04 ? `translate3d(${x.toFixed(2)}px, 0, 0)` : "";      },      0.04,    );    recoilRef.current = sp;    return () => {      sp.stop();      recoilRef.current = null;    };  }, []);  // Optical 8×8 Bayer floor pulse (strictly wakes for ~0.48s on valid completion, E.164 auto-detect, or error -> 0% CPU at rest!)  React.useEffect(() => {    const canvas = floorCanvasRef.current;    const ctx = canvas?.getContext("2d");    if (!canvas || !ctx) return;    const gridCanvas = document.createElement("canvas");    const gridCtx = gridCanvas.getContext("2d");    if (!gridCtx) return;    let raf = 0;    let kind: "none" | "valid" | "detect" | "error" = "none";    let age = 0;    let last = 0;    let gCols = 0;    let gRows = 0;    let gridImg: ImageData | null = null;    let gridU32: Uint32Array | null = null;    const tick = (now: number) => {      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;      last = now;      age += dt;      const life = kind === "error" ? 0.44 : 0.54;      if (age >= life || !onScreen || reduced) {        kind = "none";        raf = 0;        ctx.clearRect(0, 0, canvas.width, canvas.height);        return;      }      const rect = canvas.getBoundingClientRect();      const w = Math.round(rect.width);      const h = Math.round(rect.height);      if (w > 0 && h > 0) {        const dpr = Math.min(2, window.devicePixelRatio || 1);        if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {          canvas.width = Math.round(w * dpr);          canvas.height = Math.round(h * dpr);        }        const pitch = 1.5;        const cols = Math.max(1, Math.ceil(w / pitch));        const rows = Math.max(1, Math.ceil(h / pitch));        if (cols !== gCols || rows !== gRows || !gridImg || !gridU32) {          gCols = cols;          gRows = rows;          gridCanvas.width = cols;          gridCanvas.height = rows;          gridImg = gridCtx.createImageData(cols, rows);          gridU32 = new Uint32Array(gridImg.data.buffer);        }        const u32 = gridU32;        u32.fill(0);        const k = age / life;        const fade = Math.sin(Math.PI * Math.pow(k, 0.72));        const front = (1 - Math.pow(1 - k, 2.2)) * 1.18 - 0.06;        const rgb: [number, number, number] =          kind === "error" ? [239, 68, 68] : kind === "detect" ? [96, 165, 250] : [52, 211, 153];        for (let r = 0; r < rows; r++) {          const v = (r + 0.5) / rows;          const floorV = Math.pow(v, 1.7);          const bRow = (r & 7) << 3;          const rowOff = r * cols;          for (let c = 0; c < cols; c++) {            const u = (c + 0.5) / cols;            let boost = 0;            if (kind === "error") {              boost = floorV * (0.45 + 0.55 * (1 - Math.abs(u - 0.5) * 1.6)) * fade;            } else {              const df = u - front;              const lead = Math.exp(-(df * df) / 0.02);              const tail = df < 0 ? Math.exp(df / 0.22) * 0.48 : 0;              boost = floorV * (lead + tail) * fade;            }            const bayer = BAYER8[bRow | (c & 7)];            const hit = clamp01((boost * 0.85 - bayer + 0.05) / 0.14);            if (hit > 0.02) {              u32[rowOff + c] = packRgba(rgb[0], rgb[1], rgb[2], hit * 0.72 * 255);            }          }        }        gridCtx.putImageData(gridImg, 0, 0);        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);        ctx.clearRect(0, 0, w, h);        ctx.imageSmoothingEnabled = false;        ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch);      }      raf = requestAnimationFrame(tick);    };    flashRef.current = (nextKind) => {      if (reduced || !onScreen) return;      kind = nextKind;      age = 0;      last = 0;      if (!raf) raf = requestAnimationFrame(tick);    };    return () => {      flashRef.current = null;      cancelAnimationFrame(raf);    };  }, [onScreen, reduced]);  // Fire emerald lock-in sweep strictly when transitioning into a valid phone number  React.useEffect(() => {    if (isValid && !prevValidRef.current) {      flashRef.current?.("valid");      if (sound) playSound("success", 0.34);    }    prevValidRef.current = isValid;  }, [isValid, sound]);  // Close country picker on click-outside or Escape  React.useEffect(() => {    if (!open) return;    const onPointerDown = (e: PointerEvent) => {      if (rootRef.current && !rootRef.current.contains(e.target as Node)) {        setOpen(false);        setQuery("");      }    };    window.addEventListener("pointerdown", onPointerDown, true);    return () => window.removeEventListener("pointerdown", onPointerDown, true);  }, [open, rootRef]);  const emitChange = React.useCallback(    (nextCountry: PhoneCountry, nextDigits: string) => {      const trimmed = nextDigits.slice(0, nextCountry.maxDigits);      if (controlledValue === undefined) setOwnDigits(trimmed);      if (controlledCountry === undefined) setOwnCountryIso(nextCountry.iso);      const nextNational = formatNational(trimmed, nextCountry.pattern);      const valid = trimmed.length >= nextCountry.minDigits && trimmed.length <= nextCountry.maxDigits;      onChange?.({        e164: trimmed ? `+${nextCountry.dial}${trimmed}` : "",        national: nextNational,        digits: trimmed,        country: nextCountry.iso,        dialCode: `+${nextCountry.dial}`,        valid,      });    },    [controlledValue, controlledCountry, onChange],  );  const selectCountry = React.useCallback(    (next: PhoneCountry, keepFocus = true) => {      if (controlledCountry === undefined) setOwnCountryIso(next.iso);      onCountryChange?.(next.iso);      emitChange(next, digits);      setOpen(false);      setQuery("");      flashRef.current?.("detect");      if (sound) playSound("tick", 0.3);      setLiveStatus(`Country set to ${next.name} +${next.dial}`);      if (keepFocus) {        window.requestAnimationFrame(() => inputRef.current?.focus());      }    },    [controlledCountry, onCountryChange, emitChange, digits, sound],  );  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {    const el = e.currentTarget;    const raw = el.value;    const selStart = el.selectionStart ?? raw.length;    const trimmed = raw.trimStart();    // 1) Auto-detect full international numbers when pasted OR typed starting with "+" / "00"    if (trimmed.startsWith("+") || trimmed.startsWith("00")) {      const codeDigits = trimmed.startsWith("00") ? onlyDigits(trimmed).slice(2) : onlyDigits(trimmed);      const hasSpaceAfterCode = /^[+0]\d+\s/.test(trimmed);      const hasLongerPrefix = codeDigits.length > 0 && countries.some((c) => c.dial.length > codeDigits.length && c.dial.startsWith(codeDigits));      const detected = detectCountryFromInternational(trimmed, countries, activeCountry.iso);      if (detected && (hasSpaceAfterCode || codeDigits.length > detected.country.dial.length || !hasLongerPrefix)) {        setIntlDraft(null);        const switched = detected.country.iso !== activeCountry.iso;        if (switched) {          onCountryChange?.(detected.country.iso);          flashRef.current?.("detect");          if (sound) playSound("pop", 0.34);          setLiveStatus(`Detected ${detected.country.name} +${detected.country.dial}`);        }        emitChange(detected.country, detected.nationalDigits);        const nextFormatted = formatNational(detected.nationalDigits, detected.country.pattern);        window.requestAnimationFrame(() => {          if (inputRef.current) inputRef.current.setSelectionRange(nextFormatted.length, nextFormatted.length);        });        return;      }      // Still typing an ambiguous calling-code prefix (e.g. "+", "+4", "+35") -> preserve verbatim until disambiguated      if (trimmed.startsWith("+") && codeDigits.length <= 3) {        setIntlDraft(trimmed);        return;      }    }    setIntlDraft(null);    // 2) Standard national typing with exact digit-count caret restoration    const digitsBeforeCaret = onlyDigits(raw.slice(0, selStart)).length;    const nextDigits = onlyDigits(raw).slice(0, activeCountry.maxDigits);    emitChange(activeCountry, nextDigits);    const nextFormatted = formatNational(nextDigits, activeCountry.pattern);    const nextCaret = caretAfterDigitCount(nextFormatted, Math.min(digitsBeforeCaret, nextDigits.length));    window.requestAnimationFrame(() => {      if (inputRef.current) inputRef.current.setSelectionRange(nextCaret, nextCaret);    });  };  const handleInputBlur = () => {    setIntlDraft(null);    setFocused(false);    setTouched(true);    if (validateOnBlur && digits.length > 0 && !isValid) {      if (!reduced) recoilRef.current?.push(140);      flashRef.current?.("error");      if (sound) playSound("error", 0.32);    }  };  const handlePickerKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {    if (e.key === "ArrowDown") {      e.preventDefault();      setActiveIdx((i) => Math.min(Math.max(0, filteredCountries.length - 1), i + 1));    } else if (e.key === "ArrowUp") {      e.preventDefault();      setActiveIdx((i) => Math.max(0, i - 1));    } else if (e.key === "Enter" && filteredCountries[activeIdx]) {      e.preventDefault();      selectCountry(filteredCountries[activeIdx]);    } else if (e.key === "Escape") {      e.preventDefault();      setOpen(false);      setQuery("");      inputRef.current?.focus();    }  };  const expectedLenLabel =    activeCountry.minDigits === activeCountry.maxDigits      ? `${activeCountry.minDigits}-digit`      : `${activeCountry.minDigits} to ${activeCountry.maxDigits}-digit`;  return (    <div ref={rootRef} className={`relative flex w-full flex-col ${className}`} {...props}>      <div        ref={shellRef}        data-valid={isValid ? "true" : "false"}        data-country={activeCountry.iso}        className={`relative flex h-11 w-full items-center rounded-[13px] border bg-card text-card-foreground transition-[border-color,box-shadow] duration-200 shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${          showError            ? "border-red-500/45 dark:border-red-400/45"            : focused || open              ? "border-foreground/25"              : "border-border hover:border-foreground/20"        } ${disabled ? "opacity-55" : ""}`}      >        {/* Optical 8×8 Bayer floor pulse (0% CPU at rest) */}        <canvas          ref={floorCanvasRef}          aria-hidden="true"          className="pointer-events-none absolute inset-x-1 bottom-1 z-0 h-5 w-[calc(100%_-_8px)] rounded-b-[9px]"        />        {/* Country dial selector button */}        <button          type="button"          disabled={disabled}          aria-haspopup="listbox"          aria-expanded={open}          aria-label={`Country code, ${activeCountry.name} +${activeCountry.dial}`}          onClick={() => {            if (disabled) return;            setOpen((prev) => {              const next = !prev;              if (next) {                setQuery("");                const idx = countries.findIndex((c) => c.iso === activeCountry.iso);                setActiveIdx(idx >= 0 ? idx : 0);                window.requestAnimationFrame(() => searchRef.current?.focus());              }              return next;            });          }}          className={`relative z-10 flex h-full shrink-0 cursor-pointer items-center gap-1.5 rounded-l-[12px] pl-2.5 pr-2 text-foreground hover:bg-accent/70 disabled:cursor-not-allowed ${INTERACTION_FOCUS}`}        >          <span className="inline-flex h-5 items-center rounded-[5px] border border-border bg-background px-1.5 font-mono text-[10.5px] font-semibold tracking-[0.04em] text-foreground">            <TextMorph>{activeCountry.iso}</TextMorph>          </span>          <span className="font-mono text-[13px] tabular-nums text-muted-foreground">            <TextMorph>{`+${activeCountry.dial}`}</TextMorph>          </span>          <ChevronDown            className={`size-3.5 text-muted-foreground transition-transform duration-200 ${open ? "rotate-180" : ""}`}            strokeWidth={2}            aria-hidden="true"          />        </button>        {/* Crisp 1px vertical instrument divider */}        <span aria-hidden="true" className="relative z-10 h-5 w-px shrink-0 bg-border" />        {/* Caret-safe formatted national number input */}        <input          ref={inputRef}          type="tel"          inputMode="tel"          autoComplete="tel-national"          disabled={disabled}          aria-label={label}          aria-invalid={showError || undefined}          placeholder={activeCountry.example}          value={intlDraft ?? national}          onChange={handleInputChange}          onFocus={() => setFocused(true)}          onBlur={handleInputBlur}          className="relative z-10 h-full min-w-0 flex-1 bg-transparent px-3 font-mono text-[14px] tracking-[-0.01em] tabular-nums text-foreground placeholder:text-muted-foreground/45 focus:outline-none disabled:cursor-not-allowed"        />        {/* Right slot: self-drawing valid check + optional clear */}        <div className="relative z-10 flex shrink-0 items-center gap-0.5 pr-2">          <span            aria-hidden="true"            className="flex size-6 items-center justify-center text-emerald-600 dark:text-emerald-400"          >            <svg viewBox="0 0 16 16" fill="none" className="size-4">              <path                d="M3.25 8.5 6.5 11.75 12.75 4.75"                stroke="currentColor"                strokeWidth="2.1"                strokeLinecap="round"                strokeLinejoin="round"                pathLength={1}                style={{                  strokeDasharray: 1,                  strokeDashoffset: isValid ? 0 : 1,                  opacity: isValid ? 1 : 0,                  transition: reduced ? "none" : `stroke-dashoffset 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,                }}              />            </svg>          </span>          {clearable && digits.length > 0 && !disabled && (            <button              type="button"              aria-label={`Clear ${label}`}              onMouseDown={(e) => e.preventDefault()}              onClick={() => {                setIntlDraft(null);                setTouched(false);                emitChange(activeCountry, "");                inputRef.current?.focus();              }}              className={`flex size-6 cursor-pointer items-center justify-center rounded-[7px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}            >              <X className="size-3.5" strokeWidth={2} />            </button>          )}        </div>      </div>      {/* Searchable hairline country popover */}      {open && (        <div          role="dialog"          aria-label="Choose country calling code"          className={`absolute left-0 top-[calc(100%_+_6px)] z-40 w-full overflow-hidden rounded-[14px] border border-border bg-card text-card-foreground ${MATERIAL_LIFT}`}        >          <div className="flex items-center gap-2 border-b border-border px-3 py-2">            <Search className="size-3.5 shrink-0 text-muted-foreground" strokeWidth={2} aria-hidden="true" />            <input              ref={searchRef}              type="text"              value={query}              placeholder="Search country or +code…"              aria-label="Search country or calling code"              onChange={(e) => {                setQuery(e.target.value);                setActiveIdx(0);              }}              onKeyDown={handlePickerKeyDown}              className="min-w-0 flex-1 bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"            />          </div>          <ul role="listbox" aria-label="Countries" className="max-h-[216px] overflow-y-auto p-1">            {filteredCountries.length === 0 ? (              <li className="px-3 py-4 text-center text-[12.5px] text-muted-foreground">No matching country</li>            ) : (              filteredCountries.map((c, idx) => {                const selected = c.iso === activeCountry.iso;                const highlighted = idx === activeIdx;                return (                  <li key={c.iso} role="option" aria-selected={selected}>                    <button                      type="button"                      onMouseEnter={() => setActiveIdx(idx)}                      onClick={() => selectCountry(c)}                      className={`flex w-full cursor-pointer items-center justify-between gap-2.5 rounded-[9px] px-2.5 py-2 text-left text-[13px] transition-colors duration-100 ${                        highlighted ? "bg-accent text-foreground" : "text-foreground/90"                      }`}                    >                      <span className="flex min-w-0 items-center gap-2">                        <span className="inline-flex h-5 w-8 shrink-0 items-center justify-center rounded-[5px] border border-border bg-background font-mono text-[10.5px] font-semibold tracking-[0.04em] text-foreground">                          {c.iso}                        </span>                        <span className="truncate font-medium">{c.name}</span>                      </span>                      <span className="flex shrink-0 items-center gap-2">                        <span className="font-mono text-[12px] tabular-nums text-muted-foreground">+{c.dial}</span>                        {selected && <Check className="size-3.5 text-emerald-600 dark:text-emerald-400" strokeWidth={2.4} aria-hidden="true" />}                      </span>                    </button>                  </li>                );              })            )}          </ul>        </div>      )}      {/* Inline error fold on incomplete blur */}      <div        aria-hidden={!showError || undefined}        className={`grid ${!showError ? "pointer-events-none" : ""}`}        style={{          gridTemplateRows: showError ? "1fr" : "0fr",          opacity: showError ? 1 : 0,          transition: reduced ? "none" : `grid-template-rows 240ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,        }}      >        <div className="min-h-0 overflow-hidden">          <p role="alert" className="px-1 pt-1.5 text-[12px] leading-5 text-red-600 dark:text-red-400">            Enter a {expectedLenLabel} {activeCountry.name} number.          </p>        </div>      </div>      <span className="sr-only" role="status" aria-live="polite">        {liveStatus}      </span>    </div>  );}export default PhoneInput;

Registry item: /r/phone-input.json