Phone Number
Build an international phone number field with a flag button inside it, where the typed dial code or a pick from a searchable list sets the country and its format. A button in the before slot opens an sv-flyout through trigger-element, and the modify function of the sv-masked-input picks the mask from the dial code.
The country starts from the browser language, with the United States as the fallback. Typing a dial code, like +90, or pasting a full number switches the flag, and a pick from the list swaps the dial code and keeps the rest of the number. The search ignores accents and also matches the dial code.
The flag button is named after the picked country and its dial code, like "Country: Germany +49". It opens a dialog named "Choose a country" whose search field takes the focus through autofocus, and a pick closes the dialog and moves the focus to the number.
A build-time script builds the country data with the libphonenumber-js package and writes it into a JSON <script>, with a mask that fits the mobile numbers of each country. Without build-time, the same script runs in the browser and needs to import the package from a CDN.
No country matches your search
Code
The following example assumes that you have imported the components and set up the theme.
<div class="phone-number">40 collapsed lines
<label for="phone-number-field">Phone number</label>
<sv-masked-input id="phone-number-field" autocomplete="tel" name="phone" rejected-label="Only digits are allowed" > <button id="phone-country-button" type="button" class="country-button" slot="before"> <img alt="" /> </button> </sv-masked-input>
<sv-flyout id="phone-country-flyout" aria-label="Choose a country" popup-role="dialog" trigger-element="#phone-country-button" > <input id="phone-country-search" type="text" class="country-search" aria-label="Search countries" autocomplete="off" autofocus placeholder="Search by name or code" spellcheck="false" />
<sv-listbox id="phone-country-list" class="country-list" aria-label="Countries" input-element="#phone-country-search" name="country" > <p class="no-match" data-sv-listbox-empty>No country matches your search</p> </sv-listbox> </sv-flyout></div>
<template id="phone-country-option">5 collapsed lines
<button type="button" class="country-option"> <img alt="" loading="lazy" /> <span class="country-name"></span> <span class="dial-code"></span> </button></template>
<script id="phone-countries-data" type="application/json"></script>
<script type="application/x-typescript" build-time>51 collapsed lines
import { getCountries, getCountryCallingCode, getExampleNumber, parsePhoneNumberFromString, } from "libphonenumber-js/max"; import metadata from "libphonenumber-js/metadata.max.json"; import mobileExamples from "libphonenumber-js/mobile/examples";
import type { CountryCode, PhoneNumber } from "libphonenumber-js/max";
const regionNames = new Intl.DisplayNames(["en"], { type: "region" });
function getLongestMobileNumber(phoneNumber: PhoneNumber): PhoneNumber { const longerNumber = parsePhoneNumberFromString(`${phoneNumber.number}0`);
if (longerNumber?.getType() === "MOBILE") { return getLongestMobileNumber(longerNumber); }
return phoneNumber; }
// A partial number fits, because the digits after the dial code are optional function createMask(country: CountryCode, dialCode: string) { const exampleNumber = getExampleNumber(country, mobileExamples)!; const numberMask = getLongestMobileNumber(exampleNumber) .formatInternational() .replace(/\d/g, "9");
return `${numberMask.slice(0, dialCode.length)}?${numberMask.slice(dialCode.length)}`; }
const phoneCountries = getCountries().map(country => { const code = country.toLowerCase(); const callingCode = getCountryCallingCode(country); const dialCode = `+${callingCode}`;
return { code, name: regionNames.of(country)!, flagUrl: `https://hatscripts.github.io/circle-flags/flags/${code}.svg`, dialCode, mask: createMask(country, dialCode), isMainForDialCode: metadata.country_calling_codes[callingCode][0] === country, }; });
phoneCountries.sort((first, second) => first.name.localeCompare(second.name, "en"));
document.querySelector("#phone-countries-data")!.textContent = JSON.stringify(phoneCountries);</script>
<script type="application/x-typescript" module>126 collapsed lines
import type { Flyout } from "@staticview/ui/flyout"; import type { Listbox } from "@staticview/ui/listbox"; import type { MaskedInput } from "@staticview/ui/masked-input";
interface PhoneCountry { code: string; name: string; flagUrl: string; dialCode: string; mask: string; isMainForDialCode: boolean; }
const phoneCountriesJson = document.querySelector("#phone-countries-data")!.textContent!; const phoneCountries: PhoneCountry[] = JSON.parse(phoneCountriesJson);
const countryFlyout = document.querySelector<Flyout>("#phone-country-flyout")!; const countryButton = document.querySelector<HTMLButtonElement>("#phone-country-button")!; const countrySearch = document.querySelector<HTMLInputElement>("#phone-country-search")!; const countryList = document.querySelector<Listbox>("#phone-country-list")!; const phoneField = document.querySelector<MaskedInput>("#phone-number-field")!; const optionTemplate = document.querySelector<HTMLTemplateElement>("#phone-country-option")!;
const countriesByCode = new Map(phoneCountries.map(country => [country.code, country]));
// Match without accents, like "turk" for "Türkiye" function getSearchText(text: string) { return text .normalize("NFD") .replace(/\p{Diacritic}/gu, "") .toLowerCase(); }
function getPickedCountry(): PhoneCountry { return countriesByCode.get(countryList.value as string)!; }
function getDialDigits(country: PhoneCountry) { return country.dialCode.slice(1); // + }
// Some countries share a dial code, like the United States and Canada function findCountryOfNumber(numberDigits: string): PhoneCountry | undefined { const matchingCountries = phoneCountries.filter(country => { return numberDigits.startsWith(getDialDigits(country)); });
const pickedCountry = getPickedCountry(); if (matchingCountries.includes(pickedCountry)) { return pickedCountry; }
return matchingCountries.find(country => country.isMainForDialCode) ?? matchingCountries[0]; }
function getNationalDigits(numberDigits: string): string { const country = findCountryOfNumber(numberDigits); return country ? numberDigits.slice(getDialDigits(country).length) : ""; }
// Render listbox options for (const country of phoneCountries) { const optionFragment = document.importNode(optionTemplate.content, true); const option = optionFragment.querySelector("button")!;
option.value = country.code; option.ariaLabel = `${country.name} ${country.dialCode}`; option.querySelector("img")!.src = country.flagUrl; option.querySelector(".country-name")!.textContent = country.name; option.querySelector(".dial-code")!.textContent = country.dialCode;
countryList.append(option); }
countryList.filter = (option, query) => { return getSearchText(option.ariaLabel!).includes(getSearchText(query)); };
// Show the picked country and its format countryList.addEventListener("valuechange", () => { const country = getPickedCountry();
countryButton.querySelector("img")!.src = country.flagUrl; countryButton.ariaLabel = `Country: ${country.name} ${country.dialCode}`; phoneField.mask = country.mask; });
// Close the flyout and swap the dial code in the number countryList.addEventListener("optionclicked", event => { const country = countriesByCode.get(event.detail.value as string)!;
countryFlyout.close(); phoneField.focus(); phoneField.value = country.dialCode + getNationalDigits(phoneField.rawValue); });
// Reset the search on open countryFlyout.addEventListener("openedchange", () => { if (countryFlyout.opened) { countrySearch.value = ""; countryList.query = ""; } });
// Pick the mask from the dial code. A dial code of no country takes up to 15 digits. phoneField.modify = rawValue => { if (rawValue) { return findCountryOfNumber(rawValue)?.mask ?? "+999 9?99999999999"; } };
// Pick the country of the dial code in the number phoneField.addEventListener("valuechange", () => { const country = findCountryOfNumber(phoneField.rawValue); if (country) { countryList.value = country.code; } });
// Anchor the flyout to the field, and keep the button as its trigger countryFlyout.anchorElement = phoneField;
// Start from the country of the browser language const browserRegion = new Intl.Locale(navigator.language).maximize().region?.toLowerCase() ?? ""; countryList.value = countriesByCode.has(browserRegion) ? browserRegion : "us"; phoneField.value = getPickedCountry().dialCode;</script>
<style>116 collapsed lines
.phone-number { display: grid; gap: 0.5em; inline-size: min(100%, 22rem); margin-inline: auto; color: var(--sv-gray-2);
label { justify-self: start; font-weight: 600; cursor: pointer; }
sv-masked-input { inline-size: 100%; } }
.country-button { display: flex; padding: 0.25em; margin-inline: 0.125em; font: inherit; cursor: pointer; background: none; border: none; border-radius: var(--sv-bdr-rad-sm);
&:hover { background-color: var(--sv-gray-5); }
&:focus-visible { outline: auto; outline-color: var(--sv-accent); outline-offset: -2px; } }
:is(.country-button, .country-option) img { flex: none; inline-size: 1.5em; block-size: 1.5em; }
.country-button img { inline-size: 1.25em; block-size: 1.25em; }
#phone-number-field::part(input), #phone-number-field::part(mask) { padding-inline-start: 0.5em; }
#phone-country-flyout { &::part(content) { inline-size: max(var(--sv-flyout-anchor-width), 16rem); padding: 0; }
.country-search { flex: none; padding: 0.5em 0.75em; font: inherit; line-height: 1.25; color: inherit; background: none; border: none; border-block-end: solid var(--sv-bdr-sz-sm) var(--sv-gray-5);
&:focus-visible { outline: none; border-block-end-color: var(--sv-accent); } }
.country-list { gap: 0.4em; min-block-size: 0; max-block-size: 18rem; padding: 0.25em; background: none; border: none; border-radius: 0; }
.country-option { display: flex; gap: 0.75em; align-items: center; padding: 0.4em;
.dial-code { color: var(--sv-gray-3); }
&[aria-selected="true"] .dial-code { color: inherit; } }
.country-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.no-match { padding: 1em 0.5em; margin: 0; color: var(--sv-gray-3); text-align: center; } }</style>