periplo-ui 4.11.4 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ import { ComboboxSingleProps } from '../Combobox';
2
+ import { Country, CountrySelectAccessors } from './types';
3
+ import type * as React from 'react';
4
+ type CountrySelectComboboxProps = Pick<ComboboxSingleProps<object>, 'id' | 'className' | 'disabled' | 'error' | 'value' | 'placeholder' | 'searchPlaceholder' | 'emptyMessage' | 'aria-invalid' | 'aria-describedby'>;
5
+ type CountrySelectBaseProps<T> = CountrySelectComboboxProps & {
6
+ /** ISO codes pinned above the list, in order. */
7
+ priorityCountries?: Array<string>;
8
+ onChange?: (value: string, country: T) => void;
9
+ };
10
+ type ResolvedCountrySelectProps<T extends object> = CountrySelectBaseProps<T> & Partial<CountrySelectAccessors<T>> & {
11
+ /** Defaults to the generated list. */
12
+ countries?: Array<T>;
13
+ /** Ignored when `countries` is passed. */
14
+ locale?: string;
15
+ };
16
+ export type CountrySelectDefaultProps = ResolvedCountrySelectProps<Country>;
17
+ export type CountrySelectCustomProps<T extends object> = CountrySelectBaseProps<T> & CountrySelectAccessors<T> & {
18
+ countries: Array<T>;
19
+ };
20
+ export type CountrySelectProps<T extends object = Country> = CountrySelectDefaultProps | CountrySelectCustomProps<T>;
21
+ export declare function CountrySelect(props: CountrySelectDefaultProps): React.ReactElement;
22
+ export declare function CountrySelect<T extends object>(props: CountrySelectCustomProps<T>): React.ReactElement;
23
+ export declare namespace CountrySelect {
24
+ var displayName: string;
25
+ }
26
+ export {};
@@ -0,0 +1,78 @@
1
+ import { cn, createSearchMatcher } from "../../../lib/utils.js";
2
+ import { Combobox } from "../Combobox/Combobox.js";
3
+ import { buildCountries, isoToFlag, regionName, resolveIso, splitByPriority } from "../../../lib/countries.js";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { CheckIcon } from "@phosphor-icons/react/dist/ssr/Check";
6
+ import { GlobeIcon } from "@phosphor-icons/react/dist/ssr/Globe";
7
+ //#region src/components/inputs/CountrySelect/CountrySelect.tsx
8
+ function CountrySelect(props) {
9
+ const { countries, locale = "en", priorityCountries, onChange, getCountryValue, getCountryIsoCode, getCountryName, getCountrySearchTerms, className, disabled = false, placeholder = "Select country", ...comboboxProps } = props;
10
+ const options = countries ?? buildCountries(locale);
11
+ const valueOf = getCountryValue ?? ((option) => option.isoCode);
12
+ const nameOf = getCountryName ?? ((option) => option.name);
13
+ const isoOf = (option) => resolveIso(valueOf(option), getCountryIsoCode?.(option));
14
+ const { priority, rest } = splitByPriority(options, priorityCountries, isoOf);
15
+ const filterOptions = (list, search) => {
16
+ const matches = createSearchMatcher(search);
17
+ return list.filter((option) => {
18
+ const iso = isoOf(option);
19
+ const terms = [
20
+ nameOf(option),
21
+ iso ?? "",
22
+ ...getCountrySearchTerms?.(option) ?? []
23
+ ];
24
+ if (!countries && iso && locale !== "en") terms.push(regionName(iso));
25
+ return matches(terms);
26
+ });
27
+ };
28
+ const renderCountry = (option) => {
29
+ const iso = isoOf(option);
30
+ return /* @__PURE__ */ jsxs("span", {
31
+ className: "flex min-w-0 items-center gap-2",
32
+ children: [iso && /* @__PURE__ */ jsx("span", {
33
+ className: "text-lg leading-none",
34
+ children: isoToFlag(iso)
35
+ }), /* @__PURE__ */ jsx("span", {
36
+ className: "truncate",
37
+ children: nameOf(option)
38
+ })]
39
+ });
40
+ };
41
+ return /* @__PURE__ */ jsx(Combobox, {
42
+ ...comboboxProps,
43
+ className: cn("w-full", className),
44
+ disabled: disabled || options.length <= 1 && !!comboboxProps.value,
45
+ placeholder: /* @__PURE__ */ jsxs("span", {
46
+ className: "flex items-center gap-2",
47
+ children: [/* @__PURE__ */ jsx(GlobeIcon, {
48
+ className: "h-5 w-5 shrink-0",
49
+ "aria-hidden": true
50
+ }), /* @__PURE__ */ jsx("span", {
51
+ className: "truncate",
52
+ children: placeholder
53
+ })]
54
+ }),
55
+ options: rest,
56
+ specialOptions: priority,
57
+ getOptionValue: valueOf,
58
+ getOptionLabel: nameOf,
59
+ filterOptions,
60
+ clearable: false,
61
+ onOpenAutoFocus: true,
62
+ onChange: (value) => {
63
+ const country = options.find((option) => valueOf(option) === value);
64
+ if (country) onChange?.(value, country);
65
+ },
66
+ renderLabel: renderCountry,
67
+ renderOption: (option, isSelected) => /* @__PURE__ */ jsxs(Fragment, { children: [renderCountry(option), isSelected && /* @__PURE__ */ jsx(CheckIcon, {
68
+ "data-testid": "selected-check",
69
+ weight: "bold",
70
+ className: "ml-auto h-4 w-4 shrink-0 text-neutral-950"
71
+ })] })
72
+ });
73
+ }
74
+ CountrySelect.displayName = "CountrySelect";
75
+ //#endregion
76
+ export { CountrySelect };
77
+
78
+ //# sourceMappingURL=CountrySelect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CountrySelect.js","names":["_Fragment"],"sources":["../../../../src/components/inputs/CountrySelect/CountrySelect.tsx"],"sourcesContent":["import { CheckIcon } from '@phosphor-icons/react/dist/ssr/Check'\nimport { GlobeIcon } from '@phosphor-icons/react/dist/ssr/Globe'\nimport type * as React from 'react'\n\nimport { Combobox, type ComboboxSingleProps } from '../Combobox'\n\nimport type { Country, CountrySelectAccessors } from './types'\n\nimport { buildCountries, isoToFlag, regionName, resolveIso, splitByPriority } from '@/lib/countries'\nimport { cn, createSearchMatcher } from '@/lib/utils'\n\ntype CountrySelectComboboxProps = Pick<\n ComboboxSingleProps<object>,\n | 'id'\n | 'className'\n | 'disabled'\n | 'error'\n | 'value'\n | 'placeholder'\n | 'searchPlaceholder'\n | 'emptyMessage'\n | 'aria-invalid'\n | 'aria-describedby'\n>\n\ntype CountrySelectBaseProps<T> = CountrySelectComboboxProps & {\n /** ISO codes pinned above the list, in order. */\n priorityCountries?: Array<string>\n onChange?: (value: string, country: T) => void\n}\n\ntype ResolvedCountrySelectProps<T extends object> = CountrySelectBaseProps<T> &\n Partial<CountrySelectAccessors<T>> & {\n /** Defaults to the generated list. */\n countries?: Array<T>\n /** Ignored when `countries` is passed. */\n locale?: string\n }\n\nexport type CountrySelectDefaultProps = ResolvedCountrySelectProps<Country>\n\nexport type CountrySelectCustomProps<T extends object> = CountrySelectBaseProps<T> &\n CountrySelectAccessors<T> & {\n countries: Array<T>\n }\n\nexport type CountrySelectProps<T extends object = Country> = CountrySelectDefaultProps | CountrySelectCustomProps<T>\n\nexport function CountrySelect(props: CountrySelectDefaultProps): React.ReactElement\nexport function CountrySelect<T extends object>(props: CountrySelectCustomProps<T>): React.ReactElement\nexport function CountrySelect<T extends object>(props: ResolvedCountrySelectProps<T>): React.ReactElement {\n const {\n countries,\n locale = 'en',\n priorityCountries,\n onChange,\n getCountryValue,\n getCountryIsoCode,\n getCountryName,\n getCountrySearchTerms,\n className,\n disabled = false,\n placeholder = 'Select country',\n ...comboboxProps\n } = props\n\n const options = countries ?? (buildCountries(locale) as unknown as Array<T>)\n const valueOf = getCountryValue ?? ((option: T) => (option as unknown as Country).isoCode)\n const nameOf = getCountryName ?? ((option: T) => (option as unknown as Country).name)\n const isoOf = (option: T) => resolveIso(valueOf(option), getCountryIsoCode?.(option))\n\n const { priority, rest } = splitByPriority(options, priorityCountries, isoOf)\n\n const filterOptions = (list: Array<T>, search: string) => {\n const matches = createSearchMatcher(search)\n return list.filter((option) => {\n const iso = isoOf(option)\n const terms = [nameOf(option), iso ?? '', ...(getCountrySearchTerms?.(option) ?? [])]\n if (!countries && iso && locale !== 'en') terms.push(regionName(iso))\n return matches(terms)\n })\n }\n\n const renderCountry = (option: T) => {\n const iso = isoOf(option)\n return (\n <span className=\"flex min-w-0 items-center gap-2\">\n {iso && <span className=\"text-lg leading-none\">{isoToFlag(iso)}</span>}\n <span className=\"truncate\">{nameOf(option)}</span>\n </span>\n )\n }\n\n return (\n <Combobox<T>\n {...comboboxProps}\n className={cn('w-full', className)}\n disabled={disabled || (options.length <= 1 && !!comboboxProps.value)}\n placeholder={\n <span className=\"flex items-center gap-2\">\n <GlobeIcon className=\"h-5 w-5 shrink-0\" aria-hidden />\n <span className=\"truncate\">{placeholder}</span>\n </span>\n }\n options={rest}\n specialOptions={priority}\n getOptionValue={valueOf}\n getOptionLabel={nameOf}\n filterOptions={filterOptions}\n clearable={false}\n onOpenAutoFocus\n onChange={(value) => {\n const country = options.find((option) => valueOf(option) === value)\n if (country) onChange?.(value, country)\n }}\n renderLabel={renderCountry}\n renderOption={(option, isSelected) => (\n <>\n {renderCountry(option)}\n {isSelected && (\n <CheckIcon\n data-testid=\"selected-check\"\n weight=\"bold\"\n className=\"ml-auto h-4 w-4 shrink-0 text-neutral-950\"\n />\n )}\n </>\n )}\n />\n )\n}\n\nCountrySelect.displayName = 'CountrySelect'\n"],"mappings":";;;;;;;AAkDA,SAAgB,cAAgC,OAA0D;CACxG,MAAM,EACJ,WACA,SAAS,MACT,mBACA,UACA,iBACA,mBACA,gBACA,uBACA,WACA,WAAW,OACX,cAAc,kBACd,GAAG,kBACD;CAEJ,MAAM,UAAU,aAAc,eAAe,MAAM;CACnD,MAAM,UAAU,qBAAqB,WAAe,OAA8B;CAClF,MAAM,SAAS,oBAAoB,WAAe,OAA8B;CAChF,MAAM,SAAS,WAAc,WAAW,QAAQ,MAAM,GAAG,oBAAoB,MAAM,CAAC;CAEpF,MAAM,EAAE,UAAU,SAAS,gBAAgB,SAAS,mBAAmB,KAAK;CAE5E,MAAM,iBAAiB,MAAgB,WAAmB;EACxD,MAAM,UAAU,oBAAoB,MAAM;EAC1C,OAAO,KAAK,QAAQ,WAAW;GAC7B,MAAM,MAAM,MAAM,MAAM;GACxB,MAAM,QAAQ;IAAC,OAAO,MAAM;IAAG,OAAO;IAAI,GAAI,wBAAwB,MAAM,KAAK,CAAC;GAAE;GACpF,IAAI,CAAC,aAAa,OAAO,WAAW,MAAM,MAAM,KAAK,WAAW,GAAG,CAAC;GACpE,OAAO,QAAQ,KAAK;EACtB,CAAC;CACH;CAEA,MAAM,iBAAiB,WAAc;EACnC,MAAM,MAAM,MAAM,MAAM;EACxB,OACE,qBAAC,QAAD;GAAM,WAAU;GAAhB,UAAA,CACG,OAAO,oBAAC,QAAD;IAAM,WAAU;IAAwB,UAAA,UAAU,GAAG;GAAQ,CAAA,GACrE,oBAAC,QAAD;IAAM,WAAU;IAAY,UAAA,OAAO,MAAM;GAAQ,CAAA,CAC7C;;CAEV;CAEA,OACE,oBAAC,UAAD;EACE,GAAI;EACJ,WAAW,GAAG,UAAU,SAAS;EACjC,UAAU,YAAa,QAAQ,UAAU,KAAK,CAAC,CAAC,cAAc;EAC9D,aACE,qBAAC,QAAD;GAAM,WAAU;GAAhB,UAAA,CACE,oBAAC,WAAD;IAAW,WAAU;IAAmB,eAAA;GAAa,CAAA,GACrD,oBAAC,QAAD;IAAM,WAAU;IAAY,UAAA;GAAkB,CAAA,CAC1C;;EAER,SAAS;EACT,gBAAgB;EAChB,gBAAgB;EAChB,gBAAgB;EACD;EACf,WAAW;EACX,iBAAA;EACA,WAAW,UAAU;GACnB,MAAM,UAAU,QAAQ,MAAM,WAAW,QAAQ,MAAM,MAAM,KAAK;GAClE,IAAI,SAAS,WAAW,OAAO,OAAO;EACxC;EACA,aAAa;EACb,eAAe,QAAQ,eACrB,qBAAAA,UAAA,EAAA,UAAA,CACG,cAAc,MAAM,GACpB,cACC,oBAAC,WAAD;GACE,eAAY;GACZ,QAAO;GACP,WAAU;EACX,CAAA,CAEH,EAAA,CAAA;CAEL,CAAA;AAEL;AAEA,cAAc,cAAc"}
@@ -0,0 +1,2 @@
1
+ export * from './CountrySelect';
2
+ export * from './types';
@@ -0,0 +1,2 @@
1
+ import { CountrySelect } from "./CountrySelect.js";
2
+ export { CountrySelect };
@@ -0,0 +1,9 @@
1
+ export type { Country } from '../../../lib/countries';
2
+ export type CountrySelectAccessors<T> = {
3
+ getCountryValue: (country: T) => string;
4
+ getCountryName: (country: T) => string;
5
+ /** Optional when `getCountryValue` already returns an ISO code. */
6
+ getCountryIsoCode?: (country: T) => string | undefined;
7
+ /** Extra search terms, e.g. aliases. */
8
+ getCountrySearchTerms?: (country: T) => Array<string>;
9
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,14 +1,16 @@
1
- import { cn, normalizeForSearch } from "../../../lib/utils.js";
1
+ import { cn, createSearchMatcher } from "../../../lib/utils.js";
2
+ import { useListScroll } from "../../../lib/useListScroll.js";
2
3
  import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from "../../utils/Command/Command.js";
3
4
  import { PopoverContent, PopoverRoot, PopoverTrigger } from "../../utils/Popover/Popover.js";
4
- import { buildCountries, exampleNational } from "./phone.js";
5
+ import { buildCountries, splitByPriority } from "../../../lib/countries.js";
6
+ import { exampleNational } from "./phone.js";
5
7
  import { usePhoneField } from "./hooks/usePhoneField.js";
6
8
  import * as React$1 from "react";
7
9
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
10
  import { CheckIcon } from "@phosphor-icons/react/dist/ssr/Check";
9
11
  import { CaretDownIcon } from "@phosphor-icons/react/dist/ssr/CaretDown";
10
- import { WarningCircleIcon } from "@phosphor-icons/react/dist/ssr/WarningCircle";
11
12
  import { GlobeIcon } from "@phosphor-icons/react/dist/ssr/Globe";
13
+ import { WarningCircleIcon } from "@phosphor-icons/react/dist/ssr/WarningCircle";
12
14
  //#region src/components/inputs/PhoneInput/PhoneInput.tsx
13
15
  var defaultAccessors = {
14
16
  getCountryValue: (country) => country.isoCode,
@@ -39,15 +41,19 @@ function PhoneInput(props) {
39
41
  });
40
42
  const [open, setOpen] = React$1.useState(false);
41
43
  const [search, setSearch] = React$1.useState("");
42
- const prefixDisabled = disabled || options.length <= 1;
43
- const normalizedSearch = normalizeForSearch(search.trim());
44
- const filteredOptions = !normalizedSearch ? options : options.filter((option) => {
45
- const iso = isoOf(option);
46
- return normalizeForSearch(resolveName(option)).includes(normalizedSearch) || normalizeForSearch(resolveDialCode(option)).includes(normalizedSearch) || (iso ? normalizeForSearch(iso).includes(normalizedSearch) : false);
44
+ const listRef = useListScroll({
45
+ open,
46
+ searchTerm: search,
47
+ selectedValue
47
48
  });
48
- const priorityOptions = (priorityCountries ?? []).map((iso) => filteredOptions.find((option) => isoOf(option) === iso.toUpperCase())).filter((option) => Boolean(option));
49
- const priorityValues = new Set(priorityOptions.map((option) => resolveValue(option)));
50
- const restOptions = filteredOptions.filter((option) => !priorityValues.has(resolveValue(option)));
49
+ const prefixDisabled = disabled || options.length <= 1;
50
+ const matches = createSearchMatcher(search);
51
+ const filteredOptions = search.trim() ? options.filter((option) => matches([
52
+ resolveName(option),
53
+ resolveDialCode(option),
54
+ isoOf(option) ?? ""
55
+ ])) : options;
56
+ const { priority: priorityOptions, rest: restOptions } = splitByPriority(filteredOptions, priorityCountries, isoOf);
51
57
  const handleOpenChange = (next) => {
52
58
  setOpen(next);
53
59
  if (!next) setSearch("");
@@ -85,12 +91,7 @@ function PhoneInput(props) {
85
91
  };
86
92
  const renderOptionList = () => {
87
93
  if (filteredOptions.length === 0) return /* @__PURE__ */ jsx(CommandEmpty, { children: emptyMessage });
88
- if (priorityOptions.length === 0) return restOptions.map(renderOption);
89
- return /* @__PURE__ */ jsxs(Fragment, { children: [
90
- /* @__PURE__ */ jsx(CommandGroup, { children: priorityOptions.map(renderOption) }),
91
- /* @__PURE__ */ jsx(CommandSeparator, {}),
92
- /* @__PURE__ */ jsx(CommandGroup, { children: restOptions.map(renderOption) })
93
- ] });
94
+ return /* @__PURE__ */ jsxs(Fragment, { children: [priorityOptions.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(CommandGroup, { children: priorityOptions.map(renderOption) }), restOptions.length > 0 && /* @__PURE__ */ jsx(CommandSeparator, { className: "mx-1" })] }), restOptions.length > 0 && /* @__PURE__ */ jsx(CommandGroup, { children: restOptions.map(renderOption) })] });
94
95
  };
95
96
  return /* @__PURE__ */ jsx("div", {
96
97
  className: cn("flex w-full flex-col gap-1", className),
@@ -108,7 +109,7 @@ function PhoneInput(props) {
108
109
  id: id ? `${id}-country` : void 0,
109
110
  disabled: prefixDisabled,
110
111
  "aria-label": selectedOption ? resolveName(selectedOption) : countryAriaLabel,
111
- className: cn("flex w-28 shrink-0 items-center gap-1.5 border-r border-neutral-200 px-3 text-base text-neutral-950 transition-colors outline-none", !prefixDisabled && "cursor-pointer hover:bg-neutral-50", prefixDisabled && "cursor-not-allowed", disabled && "opacity-50"),
112
+ className: cn("flex shrink-0 items-center gap-1.5 border-r border-neutral-200 px-3 text-base text-neutral-950 transition-colors outline-none", options.length > 1 && "w-28", !prefixDisabled && "cursor-pointer hover:bg-neutral-50", prefixDisabled && "cursor-not-allowed", disabled && "opacity-50"),
112
113
  children: [selectedOption ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
113
114
  className: "text-lg leading-none",
114
115
  children: resolveFlag(selectedOption)
@@ -125,12 +126,14 @@ function PhoneInput(props) {
125
126
  className: "w-72 overflow-hidden p-0",
126
127
  children: /* @__PURE__ */ jsxs(Command, {
127
128
  shouldFilter: false,
129
+ defaultValue: selectedValue,
128
130
  children: [/* @__PURE__ */ jsx(CommandInput, {
129
131
  placeholder: searchPlaceholder,
130
132
  value: search,
131
133
  onValueChange: setSearch
132
134
  }), /* @__PURE__ */ jsx(CommandList, {
133
- className: "px-2.5 pb-2",
135
+ ref: listRef,
136
+ className: "px-1.5 pb-1.5",
134
137
  children: renderOptionList()
135
138
  })]
136
139
  })
@@ -1 +1 @@
1
- {"version":3,"file":"PhoneInput.js","names":["React","_Fragment"],"sources":["../../../../src/components/inputs/PhoneInput/PhoneInput.tsx"],"sourcesContent":["import { CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown'\nimport { CheckIcon } from '@phosphor-icons/react/dist/ssr/Check'\nimport { GlobeIcon } from '@phosphor-icons/react/dist/ssr/Globe'\nimport { WarningCircleIcon } from '@phosphor-icons/react/dist/ssr/WarningCircle'\nimport * as React from 'react'\n\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n CommandSeparator,\n} from '../../utils/Command'\nimport { PopoverContent, PopoverRoot, PopoverTrigger } from '../../utils/Popover'\n\nimport { usePhoneField } from './hooks'\nimport { buildCountries, exampleNational } from './phone'\nimport type { PhoneCountry, PhoneInputCountryAccessors, PhoneValue } from './types'\n\nimport { cn, normalizeForSearch } from '@/lib/utils'\n\ntype PhoneInputBaseProps = {\n /** Lands on the number input, so `<label htmlFor>` targets it. */\n id?: string\n name?: string\n className?: string\n disabled?: boolean\n error?: boolean\n inputRef?: React.Ref<HTMLInputElement>\n /** Controlled when set, otherwise seeded by `defaultCountry`. */\n country?: string\n /** National digits, no country code or separators. */\n number?: string\n onChange?: (value: PhoneValue) => void\n /** ISO code, used when `country` is uncontrolled. */\n defaultCountry?: string\n /** ISO codes pinned above the list, in order. */\n priorityCountries?: Array<string>\n numberInputProps?: Omit<\n React.InputHTMLAttributes<HTMLInputElement>,\n 'id' | 'name' | 'disabled' | 'value' | 'onChange' | 'onKeyDown' | 'className'\n >\n /** Defaults to the country's example number. */\n placeholder?: string\n countryAriaLabel?: string\n searchPlaceholder?: string\n emptyMessage?: string\n 'aria-describedby'?: string\n 'aria-invalid'?: boolean\n}\n\ntype ResolvedPhoneInputProps<T extends object> = PhoneInputBaseProps &\n Partial<PhoneInputCountryAccessors<T>> & {\n /** Defaults to the generated list. */\n countries?: Array<T>\n /** Names the generated list. Ignored when `countries` is passed. */\n locale?: string\n onChange?: (value: PhoneValue<T>) => void\n }\n\nexport type PhoneInputDefaultProps = ResolvedPhoneInputProps<PhoneCountry>\n\nexport type PhoneInputCustomProps<T extends object> = PhoneInputBaseProps &\n PhoneInputCountryAccessors<T> & {\n countries: Array<T>\n onChange?: (value: PhoneValue<T>) => void\n }\n\nexport type PhoneInputProps<T extends object = PhoneCountry> = PhoneInputDefaultProps | PhoneInputCustomProps<T>\n\nconst defaultAccessors: PhoneInputCountryAccessors<PhoneCountry> = {\n getCountryValue: (country) => country.isoCode,\n getCountryIsoCode: (country) => country.isoCode,\n getCountryDialCode: (country) => country.dialCode,\n getCountryFlag: (country) => country.flag,\n getCountryName: (country) => country.name,\n}\n\nexport function PhoneInput(props: PhoneInputDefaultProps): React.ReactElement\nexport function PhoneInput<T extends object>(props: PhoneInputCustomProps<T>): React.ReactElement\nexport function PhoneInput<T extends object>(props: ResolvedPhoneInputProps<T>): React.ReactElement {\n const {\n id,\n name,\n className,\n disabled = false,\n error = false,\n inputRef: externalInputRef,\n countries,\n country,\n onChange,\n number,\n defaultCountry,\n priorityCountries,\n locale = 'en',\n numberInputProps,\n placeholder,\n countryAriaLabel = 'Select country',\n searchPlaceholder = 'Search...',\n emptyMessage = 'No results found.',\n getCountryValue,\n getCountryIsoCode,\n getCountryDialCode,\n getCountryFlag,\n getCountryName,\n 'aria-describedby': ariaDescribedBy,\n 'aria-invalid': ariaInvalid,\n } = props\n\n const defaults = defaultAccessors as unknown as PhoneInputCountryAccessors<T>\n const options = countries ?? (buildCountries(locale) as unknown as Array<T>)\n const resolveValue = getCountryValue ?? defaults.getCountryValue\n const resolveIsoCode = getCountryIsoCode ?? defaults.getCountryIsoCode\n const resolveDialCode = getCountryDialCode ?? defaults.getCountryDialCode\n const resolveFlag = getCountryFlag ?? defaults.getCountryFlag\n const resolveName = getCountryName ?? defaults.getCountryName\n\n const {\n isoOf,\n selectedValue,\n selectedOption,\n selectedIso,\n displayValue,\n inputElRef,\n selectCountry,\n onInputChange,\n onInputKeyDown,\n } = usePhoneField({\n options,\n getCountryValue: resolveValue,\n getCountryDialCode: resolveDialCode,\n getCountryIsoCode: resolveIsoCode,\n country,\n number,\n onChange,\n defaultCountry,\n priorityCountries,\n })\n\n const [open, setOpen] = React.useState(false)\n const [search, setSearch] = React.useState('')\n\n const prefixDisabled = disabled || options.length <= 1\n\n const normalizedSearch = normalizeForSearch(search.trim())\n const filteredOptions = !normalizedSearch\n ? options\n : options.filter((option) => {\n const iso = isoOf(option)\n return (\n normalizeForSearch(resolveName(option)).includes(normalizedSearch) ||\n normalizeForSearch(resolveDialCode(option)).includes(normalizedSearch) ||\n (iso ? normalizeForSearch(iso).includes(normalizedSearch) : false)\n )\n })\n\n const priorityOptions = (priorityCountries ?? [])\n .map((iso) => filteredOptions.find((option) => isoOf(option) === iso.toUpperCase()))\n .filter((option): option is T => Boolean(option))\n\n const priorityValues = new Set(priorityOptions.map((option) => resolveValue(option)))\n const restOptions = filteredOptions.filter((option) => !priorityValues.has(resolveValue(option)))\n\n const handleOpenChange = (next: boolean) => {\n setOpen(next)\n if (!next) setSearch('')\n }\n\n const renderOption = (option: T) => {\n const value = resolveValue(option)\n const isSelected = value === selectedValue\n return (\n <CommandItem\n key={value}\n value={value}\n onSelect={() => {\n selectCountry(option)\n handleOpenChange(false)\n }}\n className=\"gap-2 rounded-lg px-3\"\n >\n <span className=\"text-lg leading-none\">{resolveFlag(option)}</span>\n <span className=\"shrink-0 text-neutral-500\">{resolveDialCode(option)}</span>\n <span className=\"truncate\">{resolveName(option)}</span>\n {isSelected && (\n <CheckIcon data-testid=\"selected-check\" weight=\"bold\" className=\"ml-auto h-4 w-4 shrink-0 text-neutral-950\" />\n )}\n </CommandItem>\n )\n }\n\n const renderOptionList = () => {\n if (filteredOptions.length === 0) return <CommandEmpty>{emptyMessage}</CommandEmpty>\n if (priorityOptions.length === 0) return restOptions.map(renderOption)\n\n return (\n <>\n <CommandGroup>{priorityOptions.map(renderOption)}</CommandGroup>\n <CommandSeparator />\n <CommandGroup>{restOptions.map(renderOption)}</CommandGroup>\n </>\n )\n }\n\n return (\n <div className={cn('flex w-full flex-col gap-1', className)}>\n <div\n data-testid=\"phone-input-shell\"\n className={cn(\n 'flex h-12 w-full items-stretch overflow-hidden rounded-lg border border-neutral-200 bg-white transition-colors has-[input:focus]:border-neutral-950',\n disabled && 'bg-neutral-50',\n error && 'border-error-400 has-[input:focus]:border-error-700',\n )}\n >\n <PopoverRoot open={open} onOpenChange={handleOpenChange}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n id={id ? `${id}-country` : undefined}\n disabled={prefixDisabled}\n aria-label={selectedOption ? resolveName(selectedOption) : countryAriaLabel}\n className={cn(\n 'flex w-28 shrink-0 items-center gap-1.5 border-r border-neutral-200 px-3 text-base text-neutral-950 transition-colors outline-none',\n !prefixDisabled && 'cursor-pointer hover:bg-neutral-50',\n prefixDisabled && 'cursor-not-allowed',\n disabled && 'opacity-50',\n )}\n >\n {selectedOption ? (\n <>\n <span className=\"text-lg leading-none\">{resolveFlag(selectedOption)}</span>\n <span className=\"tabular-nums\">{resolveDialCode(selectedOption)}</span>\n </>\n ) : (\n <GlobeIcon className=\"h-5 w-5 text-neutral-300\" aria-hidden />\n )}\n {!prefixDisabled && <CaretDownIcon className=\"ml-auto h-4 w-4 shrink-0 opacity-50\" />}\n </button>\n </PopoverTrigger>\n <PopoverContent align=\"start\" className=\"w-72 overflow-hidden p-0\">\n <Command shouldFilter={false}>\n <CommandInput placeholder={searchPlaceholder} value={search} onValueChange={setSearch} />\n <CommandList className=\"px-2.5 pb-2\">{renderOptionList()}</CommandList>\n </Command>\n </PopoverContent>\n </PopoverRoot>\n\n <input\n /* eslint-disable react-hooks/immutability -- merging the internal ref with the caller-supplied `inputRef` is the standard ref-forwarding idiom */\n ref={(el) => {\n inputElRef.current = el\n if (typeof externalInputRef === 'function') externalInputRef(el)\n else if (externalInputRef) externalInputRef.current = el\n }}\n /* eslint-enable react-hooks/immutability */\n id={id}\n name={name}\n type=\"tel\"\n inputMode=\"tel\"\n autoComplete=\"tel-national\"\n disabled={disabled}\n value={displayValue}\n onChange={onInputChange}\n onKeyDown={onInputKeyDown}\n placeholder={placeholder ?? exampleNational(selectedIso)}\n aria-invalid={ariaInvalid ?? (error || undefined)}\n aria-describedby={ariaDescribedBy}\n className=\"min-w-0 flex-1 bg-transparent px-3 text-base text-neutral-950 outline-none placeholder:text-neutral-300 disabled:cursor-not-allowed disabled:opacity-50\"\n {...numberInputProps}\n />\n\n {error && (\n <div className=\"flex items-center pr-3\">\n <WarningCircleIcon data-testid=\"exclaim-icon\" className=\"text-error-500\" size={18} />\n </div>\n )}\n </div>\n </div>\n )\n}\n\nPhoneInput.displayName = 'PhoneInput'\n"],"mappings":";;;;;;;;;;;;AAwEA,IAAM,mBAA6D;CACjE,kBAAkB,YAAY,QAAQ;CACtC,oBAAoB,YAAY,QAAQ;CACxC,qBAAqB,YAAY,QAAQ;CACzC,iBAAiB,YAAY,QAAQ;CACrC,iBAAiB,YAAY,QAAQ;AACvC;AAIA,SAAgB,WAA6B,OAAuD;CAClG,MAAM,EACJ,IACA,MACA,WACA,WAAW,OACX,QAAQ,OACR,UAAU,kBACV,WACA,SACA,UACA,QACA,gBACA,mBACA,SAAS,MACT,kBACA,aACA,mBAAmB,kBACnB,oBAAoB,aACpB,eAAe,qBACf,iBACA,mBACA,oBACA,gBACA,gBACA,oBAAoB,iBACpB,gBAAgB,gBACd;CAEJ,MAAM,WAAW;CACjB,MAAM,UAAU,aAAc,eAAe,MAAM;CACnD,MAAM,eAAe,mBAAmB,SAAS;CACjD,MAAM,iBAAiB,qBAAqB,SAAS;CACrD,MAAM,kBAAkB,sBAAsB,SAAS;CACvD,MAAM,cAAc,kBAAkB,SAAS;CAC/C,MAAM,cAAc,kBAAkB,SAAS;CAE/C,MAAM,EACJ,OACA,eACA,gBACA,aACA,cACA,YACA,eACA,eACA,mBACE,cAAc;EAChB;EACA,iBAAiB;EACjB,oBAAoB;EACpB,mBAAmB;EACnB;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,MAAM,CAAC,MAAM,WAAWA,QAAM,SAAS,KAAK;CAC5C,MAAM,CAAC,QAAQ,aAAaA,QAAM,SAAS,EAAE;CAE7C,MAAM,iBAAiB,YAAY,QAAQ,UAAU;CAErD,MAAM,mBAAmB,mBAAmB,OAAO,KAAK,CAAC;CACzD,MAAM,kBAAkB,CAAC,mBACrB,UACA,QAAQ,QAAQ,WAAW;EACzB,MAAM,MAAM,MAAM,MAAM;EACxB,OACE,mBAAmB,YAAY,MAAM,CAAC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AAiB;OAAe,CAAA,CAC/D;;KACK,CAAA,CACL;;IAEb,oBAAC,SAAD;KAEE,MAAM,OAAO;MACX,WAAW,UAAU;MACrB,IAAI,OAAO,qBAAqB,YAAY,iBAAiB,EAAE;WAC1D,IAAI,kBAAkB,iBAAiB,UAAU;KACxD;KAEI;KACE;KACN,MAAK;KACL,WAAU;KACV,cAAa;KACH;KACV,OAAO;KACP,UAAU;KACV,WAAW;KACX,aAAa,eAAe,gBAAgB,WAAW;KACvD,gBAAc,gBAAgB,SAAS,KAAA;KACvC,oBAAkB;KAClB,WAAU;KACV,GAAI;IACL,CAAA;IAEA,SACC,oBAAC,OAAD;KAAK,WAAU;KACb,UAAA,oBAAC,mBAAD;MAAmB,eAAY;MAAe,WAAU;MAAiB,MAAM;KAAK,CAAA;IACjF,CAAA;GAEJ;;CACF,CAAA;AAET;AAEA,WAAW,cAAc"}
1
+ {"version":3,"file":"PhoneInput.js","names":["React","_Fragment"],"sources":["../../../../src/components/inputs/PhoneInput/PhoneInput.tsx"],"sourcesContent":["import { CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown'\nimport { CheckIcon } from '@phosphor-icons/react/dist/ssr/Check'\nimport { GlobeIcon } from '@phosphor-icons/react/dist/ssr/Globe'\nimport { WarningCircleIcon } from '@phosphor-icons/react/dist/ssr/WarningCircle'\nimport * as React from 'react'\n\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n CommandSeparator,\n} from '../../utils/Command'\nimport { PopoverContent, PopoverRoot, PopoverTrigger } from '../../utils/Popover'\n\nimport { usePhoneField } from './hooks'\nimport { exampleNational } from './phone'\nimport type { PhoneCountry, PhoneInputCountryAccessors, PhoneValue } from './types'\n\nimport { buildCountries, splitByPriority } from '@/lib/countries'\nimport { useListScroll } from '@/lib/useListScroll'\nimport { cn, createSearchMatcher } from '@/lib/utils'\n\ntype PhoneInputBaseProps = {\n /** Lands on the number input, so `<label htmlFor>` targets it. */\n id?: string\n name?: string\n className?: string\n disabled?: boolean\n error?: boolean\n inputRef?: React.Ref<HTMLInputElement>\n /** Controlled when set, otherwise seeded by `defaultCountry`. */\n country?: string\n /** National digits, no country code or separators. */\n number?: string\n onChange?: (value: PhoneValue) => void\n /** ISO code, used when `country` is uncontrolled. */\n defaultCountry?: string\n /** ISO codes pinned above the list, in order. */\n priorityCountries?: Array<string>\n numberInputProps?: Omit<\n React.InputHTMLAttributes<HTMLInputElement>,\n 'id' | 'name' | 'disabled' | 'value' | 'onChange' | 'onKeyDown' | 'className'\n >\n /** Defaults to the country's example number. */\n placeholder?: string\n countryAriaLabel?: string\n searchPlaceholder?: string\n emptyMessage?: string\n 'aria-describedby'?: string\n 'aria-invalid'?: boolean\n}\n\ntype ResolvedPhoneInputProps<T extends object> = PhoneInputBaseProps &\n Partial<PhoneInputCountryAccessors<T>> & {\n /** Defaults to the generated list. */\n countries?: Array<T>\n /** Names the generated list. Ignored when `countries` is passed. */\n locale?: string\n onChange?: (value: PhoneValue<T>) => void\n }\n\nexport type PhoneInputDefaultProps = ResolvedPhoneInputProps<PhoneCountry>\n\nexport type PhoneInputCustomProps<T extends object> = PhoneInputBaseProps &\n PhoneInputCountryAccessors<T> & {\n countries: Array<T>\n onChange?: (value: PhoneValue<T>) => void\n }\n\nexport type PhoneInputProps<T extends object = PhoneCountry> = PhoneInputDefaultProps | PhoneInputCustomProps<T>\n\nconst defaultAccessors: PhoneInputCountryAccessors<PhoneCountry> = {\n getCountryValue: (country) => country.isoCode,\n getCountryIsoCode: (country) => country.isoCode,\n getCountryDialCode: (country) => country.dialCode,\n getCountryFlag: (country) => country.flag,\n getCountryName: (country) => country.name,\n}\n\nexport function PhoneInput(props: PhoneInputDefaultProps): React.ReactElement\nexport function PhoneInput<T extends object>(props: PhoneInputCustomProps<T>): React.ReactElement\nexport function PhoneInput<T extends object>(props: ResolvedPhoneInputProps<T>): React.ReactElement {\n const {\n id,\n name,\n className,\n disabled = false,\n error = false,\n inputRef: externalInputRef,\n countries,\n country,\n onChange,\n number,\n defaultCountry,\n priorityCountries,\n locale = 'en',\n numberInputProps,\n placeholder,\n countryAriaLabel = 'Select country',\n searchPlaceholder = 'Search...',\n emptyMessage = 'No results found.',\n getCountryValue,\n getCountryIsoCode,\n getCountryDialCode,\n getCountryFlag,\n getCountryName,\n 'aria-describedby': ariaDescribedBy,\n 'aria-invalid': ariaInvalid,\n } = props\n\n const defaults = defaultAccessors as unknown as PhoneInputCountryAccessors<T>\n const options = countries ?? (buildCountries(locale) as unknown as Array<T>)\n const resolveValue = getCountryValue ?? defaults.getCountryValue\n const resolveIsoCode = getCountryIsoCode ?? defaults.getCountryIsoCode\n const resolveDialCode = getCountryDialCode ?? defaults.getCountryDialCode\n const resolveFlag = getCountryFlag ?? defaults.getCountryFlag\n const resolveName = getCountryName ?? defaults.getCountryName\n\n const {\n isoOf,\n selectedValue,\n selectedOption,\n selectedIso,\n displayValue,\n inputElRef,\n selectCountry,\n onInputChange,\n onInputKeyDown,\n } = usePhoneField({\n options,\n getCountryValue: resolveValue,\n getCountryDialCode: resolveDialCode,\n getCountryIsoCode: resolveIsoCode,\n country,\n number,\n onChange,\n defaultCountry,\n priorityCountries,\n })\n\n const [open, setOpen] = React.useState(false)\n const [search, setSearch] = React.useState('')\n const listRef = useListScroll({ open, searchTerm: search, selectedValue })\n\n const prefixDisabled = disabled || options.length <= 1\n\n const matches = createSearchMatcher(search)\n const filteredOptions = search.trim()\n ? options.filter((option) => matches([resolveName(option), resolveDialCode(option), isoOf(option) ?? '']))\n : options\n const { priority: priorityOptions, rest: restOptions } = splitByPriority(filteredOptions, priorityCountries, isoOf)\n\n const handleOpenChange = (next: boolean) => {\n setOpen(next)\n if (!next) setSearch('')\n }\n\n const renderOption = (option: T) => {\n const value = resolveValue(option)\n const isSelected = value === selectedValue\n return (\n <CommandItem\n key={value}\n value={value}\n onSelect={() => {\n selectCountry(option)\n handleOpenChange(false)\n }}\n className=\"gap-2 rounded-lg px-3\"\n >\n <span className=\"text-lg leading-none\">{resolveFlag(option)}</span>\n <span className=\"shrink-0 text-neutral-500\">{resolveDialCode(option)}</span>\n <span className=\"truncate\">{resolveName(option)}</span>\n {isSelected && (\n <CheckIcon data-testid=\"selected-check\" weight=\"bold\" className=\"ml-auto h-4 w-4 shrink-0 text-neutral-950\" />\n )}\n </CommandItem>\n )\n }\n\n const renderOptionList = () => {\n if (filteredOptions.length === 0) return <CommandEmpty>{emptyMessage}</CommandEmpty>\n\n return (\n <>\n {priorityOptions.length > 0 && (\n <>\n <CommandGroup>{priorityOptions.map(renderOption)}</CommandGroup>\n {restOptions.length > 0 && <CommandSeparator className=\"mx-1\" />}\n </>\n )}\n {restOptions.length > 0 && <CommandGroup>{restOptions.map(renderOption)}</CommandGroup>}\n </>\n )\n }\n\n return (\n <div className={cn('flex w-full flex-col gap-1', className)}>\n <div\n data-testid=\"phone-input-shell\"\n className={cn(\n 'flex h-12 w-full items-stretch overflow-hidden rounded-lg border border-neutral-200 bg-white transition-colors has-[input:focus]:border-neutral-950',\n disabled && 'bg-neutral-50',\n error && 'border-error-400 has-[input:focus]:border-error-700',\n )}\n >\n <PopoverRoot open={open} onOpenChange={handleOpenChange}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n id={id ? `${id}-country` : undefined}\n disabled={prefixDisabled}\n aria-label={selectedOption ? resolveName(selectedOption) : countryAriaLabel}\n className={cn(\n 'flex shrink-0 items-center gap-1.5 border-r border-neutral-200 px-3 text-base text-neutral-950 transition-colors outline-none',\n options.length > 1 && 'w-28',\n !prefixDisabled && 'cursor-pointer hover:bg-neutral-50',\n prefixDisabled && 'cursor-not-allowed',\n disabled && 'opacity-50',\n )}\n >\n {selectedOption ? (\n <>\n <span className=\"text-lg leading-none\">{resolveFlag(selectedOption)}</span>\n <span className=\"tabular-nums\">{resolveDialCode(selectedOption)}</span>\n </>\n ) : (\n <GlobeIcon className=\"h-5 w-5 text-neutral-300\" aria-hidden />\n )}\n {!prefixDisabled && <CaretDownIcon className=\"ml-auto h-4 w-4 shrink-0 opacity-50\" />}\n </button>\n </PopoverTrigger>\n <PopoverContent align=\"start\" className=\"w-72 overflow-hidden p-0\">\n <Command shouldFilter={false} defaultValue={selectedValue}>\n <CommandInput placeholder={searchPlaceholder} value={search} onValueChange={setSearch} />\n <CommandList ref={listRef} className=\"px-1.5 pb-1.5\">\n {renderOptionList()}\n </CommandList>\n </Command>\n </PopoverContent>\n </PopoverRoot>\n\n <input\n /* eslint-disable react-hooks/immutability -- merging the internal ref with the caller-supplied `inputRef` is the standard ref-forwarding idiom */\n ref={(el) => {\n inputElRef.current = el\n if (typeof externalInputRef === 'function') externalInputRef(el)\n else if (externalInputRef) externalInputRef.current = el\n }}\n /* eslint-enable react-hooks/immutability */\n id={id}\n name={name}\n type=\"tel\"\n inputMode=\"tel\"\n autoComplete=\"tel-national\"\n disabled={disabled}\n value={displayValue}\n onChange={onInputChange}\n onKeyDown={onInputKeyDown}\n placeholder={placeholder ?? exampleNational(selectedIso)}\n aria-invalid={ariaInvalid ?? (error || undefined)}\n aria-describedby={ariaDescribedBy}\n className=\"min-w-0 flex-1 bg-transparent px-3 text-base text-neutral-950 outline-none placeholder:text-neutral-300 disabled:cursor-not-allowed disabled:opacity-50\"\n {...numberInputProps}\n />\n\n {error && (\n <div className=\"flex items-center pr-3\">\n <WarningCircleIcon data-testid=\"exclaim-icon\" className=\"text-error-500\" size={18} />\n </div>\n )}\n </div>\n </div>\n )\n}\n\nPhoneInput.displayName = 'PhoneInput'\n"],"mappings":";;;;;;;;;;;;;;AA0EA,IAAM,mBAA6D;CACjE,kBAAkB,YAAY,QAAQ;CACtC,oBAAoB,YAAY,QAAQ;CACxC,qBAAqB,YAAY,QAAQ;CACzC,iBAAiB,YAAY,QAAQ;CACrC,iBAAiB,YAAY,QAAQ;AACvC;AAIA,SAAgB,WAA6B,OAAuD;CAClG,MAAM,EACJ,IACA,MACA,WACA,WAAW,OACX,QAAQ,OACR,UAAU,kBACV,WACA,SACA,UACA,QACA,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lCandidate } from "../phone.js";
1
+ import { resolveIso } from "../../../../lib/countries.js";
2
+ import { describe, detectIntl, formatNational, isPartialCallingCode, parseDigits, pickCountryOption, toIntlCandidate } from "../phone.js";
2
3
  import * as React$1 from "react";
3
4
  //#region src/components/inputs/PhoneInput/hooks/usePhoneField.ts
4
5
  var CARET_END = Number.MAX_SAFE_INTEGER;
@@ -1 +1 @@
1
- {"version":3,"file":"usePhoneField.js","names":["React"],"sources":["../../../../../src/components/inputs/PhoneInput/hooks/usePhoneField.ts"],"sourcesContent":["import * as React from 'react'\n\nimport {\n describe,\n detectIntl,\n formatNational,\n isPartialCallingCode,\n parseDigits,\n pickCountryOption,\n resolveIso,\n toIntlCandidate,\n} from '../phone'\nimport type { PhoneInputCountryAccessors, PhoneValue } from '../types'\n\ntype UsePhoneFieldOptions<T> = Pick<\n PhoneInputCountryAccessors<T>,\n 'getCountryValue' | 'getCountryDialCode' | 'getCountryIsoCode'\n> & {\n options: Array<T>\n country?: string\n number?: string\n onChange?: (value: PhoneValue<T>) => void\n defaultCountry?: string\n priorityCountries?: Array<string>\n}\n\nconst CARET_END = Number.MAX_SAFE_INTEGER\n\nfunction trimTrailingNonDigits(text: string): string {\n let end = text.length\n while (end > 0 && !/\\d/.test(text[end - 1])) end -= 1\n return text.slice(0, end)\n}\n\nfunction caretAfterNthDigit(formatted: string, digitCount: number): number {\n if (digitCount <= 0) return 0\n let seen = 0\n for (let index = 0; index < formatted.length; index++) {\n if (/\\d/.test(formatted[index])) {\n seen += 1\n if (seen === digitCount) return index + 1\n }\n }\n return formatted.length\n}\n\nexport function usePhoneField<T extends object>({\n options,\n getCountryValue,\n getCountryDialCode,\n getCountryIsoCode,\n country,\n number,\n onChange,\n defaultCountry,\n priorityCountries,\n}: UsePhoneFieldOptions<T>) {\n const isoOf = (option: T) => resolveIso(getCountryValue(option), getCountryIsoCode?.(option))\n\n const [internalCountryValue, setInternalCountryValue] = React.useState<string | undefined>(() => {\n if (!defaultCountry) return undefined\n const iso = defaultCountry.toUpperCase()\n const initial = options.find((option) => isoOf(option) === iso)\n return initial ? getCountryValue(initial) : undefined\n })\n\n if (country !== undefined && country !== internalCountryValue) {\n setInternalCountryValue(country)\n }\n\n // Shown as typed until it resolves to a calling code (\"+3\" on the way to \"+34\").\n const [pendingIntl, setPendingIntl] = React.useState<string | undefined>(undefined)\n\n const selectedValue = country ?? internalCountryValue\n const selectedOption = options.find((option) => getCountryValue(option) === selectedValue)\n const selectedIso = selectedOption ? isoOf(selectedOption) : undefined\n const displayValue = pendingIntl ?? formatNational(number ?? '', selectedIso)\n\n const inputElRef = React.useRef<HTMLInputElement | null>(null)\n const caretTarget = React.useRef<number | null>(null)\n\n React.useLayoutEffect(() => {\n const el = inputElRef.current\n if (!el || caretTarget.current === null) return\n const pos = caretAfterNthDigit(el.value, caretTarget.current)\n el.setSelectionRange(pos, pos)\n caretTarget.current = null\n })\n\n function emit(digits: string, option: T | undefined) {\n const iso = option ? isoOf(option) : undefined\n const described = describe(digits, iso)\n onChange?.({\n country: option ? getCountryValue(option) : undefined,\n countryOption: option,\n isoCode: iso,\n dialCode: option ? getCountryDialCode(option) : undefined,\n national: digits,\n e164: described.e164,\n isPossible: described.isPossible,\n isValid: described.isValid,\n })\n }\n\n function commit(digits: string, option: T | undefined, digitsBefore: number) {\n caretTarget.current = digitsBefore\n emit(digits, option)\n }\n\n function handleIntl(text: string) {\n const { iso: detectedIso, callingCode, national } = detectIntl(text)\n\n if (!callingCode) {\n const digits = parseDigits(text)\n if (text === '+' || (digits !== '' && isPartialCallingCode(digits))) {\n setPendingIntl(text)\n return\n }\n setPendingIntl(undefined)\n commit(digits, selectedOption, CARET_END)\n return\n }\n\n setPendingIntl(undefined)\n const option =\n options.length <= 1\n ? selectedOption\n : pickCountryOption({\n detectedIso,\n callingCode,\n options,\n currentOption: selectedOption,\n priorityCountries,\n isoOf,\n dialOf: getCountryDialCode,\n })\n\n if (!option) {\n commit(parseDigits(text), selectedOption, CARET_END)\n return\n }\n\n setInternalCountryValue(getCountryValue(option))\n commit(national, option, CARET_END)\n }\n\n function onInputChange(event: React.ChangeEvent<HTMLInputElement>) {\n const raw = event.target.value\n const caret = event.target.selectionStart ?? raw.length\n const digitsBefore = parseDigits(raw.slice(0, caret)).length\n\n const intlCandidate = toIntlCandidate(raw)\n if (intlCandidate) {\n handleIntl(intlCandidate)\n return\n }\n setPendingIntl(undefined)\n\n const digits = parseDigits(raw)\n\n if (selectedIso && describe(digits, selectedIso).tooLong) {\n // No state update means React won't revert the DOM, so undo the keystroke by hand.\n event.target.value = displayValue\n const pos = caretAfterNthDigit(displayValue, digitsBefore - 1)\n event.target.setSelectionRange(pos, pos)\n return\n }\n\n commit(digits, selectedOption, digitsBefore)\n }\n\n function onInputKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {\n if (event.key !== 'Backspace') return\n if (pendingIntl !== undefined) return // no separators in pending text\n\n const el = event.currentTarget\n const { selectionStart: start, selectionEnd: end, value } = el\n if (start === null || start !== end || start === 0) return\n if (/\\d/.test(value[start - 1] ?? '')) return // deleting a digit: default is correct\n\n event.preventDefault()\n const head = trimTrailingNonDigits(value.slice(0, start))\n const digits = parseDigits(head.slice(0, -1) + value.slice(start))\n commit(digits, selectedOption, parseDigits(head).length - 1)\n }\n\n function selectCountry(option: T) {\n setPendingIntl(undefined)\n setInternalCountryValue(getCountryValue(option))\n emit(number ?? '', option)\n inputElRef.current?.focus()\n }\n\n return {\n isoOf,\n selectedValue,\n selectedOption,\n selectedIso,\n displayValue,\n inputElRef,\n selectCountry,\n onInputChange,\n onInputKeyDown,\n }\n}\n"],"mappings":";;;AA0BA,IAAM,YAAY,OAAO;AAEzB,SAAS,sBAAsB,MAAsB;CACnD,IAAI,MAAM,KAAK;CACf,OAAO,MAAM,KAAK,CAAC,KAAK,KAAK,KAAK,MAAM,EAAE,GAAG,OAAO;CACpD,OAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AAEA,SAAS,mBAAmB,WAAmB,YAA4B;CACzE,IA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AExB,MAAM,SAAS,YAAY,GAAG;EAE9B,IAAI,eAAe,SAAS,QAAQ,WAAW,CAAC,CAAC,SAAS;GAExD,MAAM,OAAO,QAAQ;GACrB,MAAM,MAAM,mBAAmB,cAAc,eAAe,CAAC;GAC7D,MAAM,OAAO,kBAAkB,KAAK,GAAG;GACvC;EACF;EAEA,OAAO,QAAQ,gBAAgB,YAAY;CAC7C;CAEA,SAAS,eAAe,OAA8C;EACpE,IAAI,MAAM,QAAQ,aAAa;EAC/B,IAAI,gBAAgB,KAAA,GAAW;EAG/B,MAAM,EAAE,gBAAgB,OAAO,cAAc,KAAK,UADvC,MAAM;EAEjB,IAAI,UAAU,QAAQ,UAAU,OAAO,UAAU,GAAG;EACpD,IAAI,KAAK,KAAK,MAAM,QAAQ,MAAM,EAAE,GAAG;EAEvC,MAAM,eAAe;EACrB,MAAM,OAAO,sBAAsB,MAAM,MAAM,GAAG,KAAK,CAAC;EAExD,OADe,YAAY,KAAK,MAAM,GAAG,EAAE,IAAI,MAAM,MAAM,KAAK,CACzD,GAAQ,gBAAgB,YAAY,IAAI,CAAC,CAAC,SAAS,CAAC;CAC7D;CAEA,SAAS,cAAc,QAAW;EAChC,eAAe,KAAA,CAAS;EACxB,wBAAwB,gBAAgB,MAAM,CAAC;EAC/C,KAAK,UAAU,IAAI,MAAM;EACzB,WAAW,SAAS,MAAM;CAC5B;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"usePhoneField.js","names":["React"],"sources":["../../../../../src/components/inputs/PhoneInput/hooks/usePhoneField.ts"],"sourcesContent":["import * as React from 'react'\n\nimport {\n describe,\n detectIntl,\n formatNational,\n isPartialCallingCode,\n parseDigits,\n pickCountryOption,\n toIntlCandidate,\n} from '../phone'\nimport type { PhoneInputCountryAccessors, PhoneValue } from '../types'\n\nimport { resolveIso } from '@/lib/countries'\n\ntype UsePhoneFieldOptions<T> = Pick<\n PhoneInputCountryAccessors<T>,\n 'getCountryValue' | 'getCountryDialCode' | 'getCountryIsoCode'\n> & {\n options: Array<T>\n country?: string\n number?: string\n onChange?: (value: PhoneValue<T>) => void\n defaultCountry?: string\n priorityCountries?: Array<string>\n}\n\nconst CARET_END = Number.MAX_SAFE_INTEGER\n\nfunction trimTrailingNonDigits(text: string): string {\n let end = text.length\n while (end > 0 && !/\\d/.test(text[end - 1])) end -= 1\n return text.slice(0, end)\n}\n\nfunction caretAfterNthDigit(formatted: string, digitCount: number): number {\n if (digitCount <= 0) return 0\n let seen = 0\n for (let index = 0; index < formatted.length; index++) {\n if (/\\d/.test(formatted[index])) {\n seen += 1\n if (seen === digitCount) return index + 1\n }\n }\n return formatted.length\n}\n\nexport function usePhoneField<T extends object>({\n options,\n getCountryValue,\n getCountryDialCode,\n getCountryIsoCode,\n country,\n number,\n onChange,\n defaultCountry,\n priorityCountries,\n}: UsePhoneFieldOptions<T>) {\n const isoOf = (option: T) => resolveIso(getCountryValue(option), getCountryIsoCode?.(option))\n\n const [internalCountryValue, setInternalCountryValue] = React.useState<string | undefined>(() => {\n if (!defaultCountry) return undefined\n const iso = defaultCountry.toUpperCase()\n const initial = options.find((option) => isoOf(option) === iso)\n return initial ? getCountryValue(initial) : undefined\n })\n\n if (country !== undefined && country !== internalCountryValue) {\n setInternalCountryValue(country)\n }\n\n // Shown as typed until it resolves to a calling code (\"+3\" on the way to \"+34\").\n const [pendingIntl, setPendingIntl] = React.useState<string | undefined>(undefined)\n\n const selectedValue = country ?? internalCountryValue\n const selectedOption = options.find((option) => getCountryValue(option) === selectedValue)\n const selectedIso = selectedOption ? isoOf(selectedOption) : undefined\n const displayValue = pendingIntl ?? formatNational(number ?? '', selectedIso)\n\n const inputElRef = React.useRef<HTMLInputElement | null>(null)\n const caretTarget = React.useRef<number | null>(null)\n\n React.useLayoutEffect(() => {\n const el = inputElRef.current\n if (!el || caretTarget.current === null) return\n const pos = caretAfterNthDigit(el.value, caretTarget.current)\n el.setSelectionRange(pos, pos)\n caretTarget.current = null\n })\n\n function emit(digits: string, option: T | undefined) {\n const iso = option ? isoOf(option) : undefined\n const described = describe(digits, iso)\n onChange?.({\n country: option ? getCountryValue(option) : undefined,\n countryOption: option,\n isoCode: iso,\n dialCode: option ? getCountryDialCode(option) : undefined,\n national: digits,\n e164: described.e164,\n isPossible: described.isPossible,\n isValid: described.isValid,\n })\n }\n\n function commit(digits: string, option: T | undefined, digitsBefore: number) {\n caretTarget.current = digitsBefore\n emit(digits, option)\n }\n\n function handleIntl(text: string) {\n const { iso: detectedIso, callingCode, national } = detectIntl(text)\n\n if (!callingCode) {\n const digits = parseDigits(text)\n if (text === '+' || (digits !== '' && isPartialCallingCode(digits))) {\n setPendingIntl(text)\n return\n }\n setPendingIntl(undefined)\n commit(digits, selectedOption, CARET_END)\n return\n }\n\n setPendingIntl(undefined)\n const option =\n options.length <= 1\n ? selectedOption\n : pickCountryOption({\n detectedIso,\n callingCode,\n options,\n currentOption: selectedOption,\n priorityCountries,\n isoOf,\n dialOf: getCountryDialCode,\n })\n\n if (!option) {\n commit(parseDigits(text), selectedOption, CARET_END)\n return\n }\n\n setInternalCountryValue(getCountryValue(option))\n commit(national, option, CARET_END)\n }\n\n function onInputChange(event: React.ChangeEvent<HTMLInputElement>) {\n const raw = event.target.value\n const caret = event.target.selectionStart ?? raw.length\n const digitsBefore = parseDigits(raw.slice(0, caret)).length\n\n const intlCandidate = toIntlCandidate(raw)\n if (intlCandidate) {\n handleIntl(intlCandidate)\n return\n }\n setPendingIntl(undefined)\n\n const digits = parseDigits(raw)\n\n if (selectedIso && describe(digits, selectedIso).tooLong) {\n // No state update means React won't revert the DOM, so undo the keystroke by hand.\n event.target.value = displayValue\n const pos = caretAfterNthDigit(displayValue, digitsBefore - 1)\n event.target.setSelectionRange(pos, pos)\n return\n }\n\n commit(digits, selectedOption, digitsBefore)\n }\n\n function onInputKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {\n if (event.key !== 'Backspace') return\n if (pendingIntl !== undefined) return // no separators in pending text\n\n const el = event.currentTarget\n const { selectionStart: start, selectionEnd: end, value } = el\n if (start === null || start !== end || start === 0) return\n if (/\\d/.test(value[start - 1] ?? '')) return // deleting a digit: default is correct\n\n event.preventDefault()\n const head = trimTrailingNonDigits(value.slice(0, start))\n const digits = parseDigits(head.slice(0, -1) + value.slice(start))\n commit(digits, selectedOption, parseDigits(head).length - 1)\n }\n\n function selectCountry(option: T) {\n setPendingIntl(undefined)\n setInternalCountryValue(getCountryValue(option))\n emit(number ?? '', option)\n inputElRef.current?.focus()\n }\n\n return {\n isoOf,\n selectedValue,\n selectedOption,\n selectedIso,\n displayValue,\n inputElRef,\n selectCountry,\n onInputChange,\n onInputKeyDown,\n }\n}\n"],"mappings":";;;;AA2BA,IAAM,YAAY,OAAO;AAEzB,SAAS,sBAAsB,MAAsB;CACnD,IAAI,MAAM,KAAK;CACf,OAAO,MAAM,KAAK,CAAC,KAAK,KAAK,KAAK,MAAM,EAAE,GAAG,OAAO;CACpD,OAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AAEA,SAAS,mBAAmB,WAAmB,YAA4B;CACzE,IAAI,cAAc,GAAG,OAAO;CAC5B,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAC5C,IAAI,KAAK,KAAK,UAAU,MAAM,GAAG;EAC/B,QAAQ;EACR,IAAI,SAAS,YAAY,OAAO,QAAQ;CAC1C;CAEF,OAAO,UAAU;AACnB;AAEA,SAAgB,cAAgC,EAC9C,SACA,iBACA,oBACA,mBACA,SACA,QACA,UACA,gBACA,qBAC0B;CAC1B,MAAM,SAAS,WAAc,WAAW,gBAAgB,MAAM,GAAG,oBAAoB,MAAM,CAAC;CAE5F,MAAM,CAAC,sBAAsB,2BAA2BA,QAAM,eAAmC;EAC/F,IAAI,CAAC,gBAAgB,OAAO,KAAA;EAC5B,MAAM,MAAM,eAAe,YAAY;EACvC,MAAM,UAAU,QAAQ,MAAM,WAAW,MAAM,M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AO,sBAAsB,MAAM,MAAM,GAAG,KAAK,CAAC;EAExD,OADe,YAAY,KAAK,MAAM,GAAG,EAAE,IAAI,MAAM,MAAM,KAAK,CACzD,GAAQ,gBAAgB,YAAY,IAAI,CAAC,CAAC,SAAS,CAAC;CAC7D;CAEA,SAAS,cAAc,QAAW;EAChC,eAAe,KAAA,CAAS;EACxB,wBAAwB,gBAAgB,MAAM,CAAC;EAC/C,KAAK,UAAU,IAAI,MAAM;EACzB,WAAW,SAAS,MAAM;CAC5B;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1,12 +1,8 @@
1
1
  import { parseDigits } from 'libphonenumber-js/min';
2
- import { PhoneCountry } from './types';
3
2
  export { parseDigits };
4
- export declare function isoToFlag(iso: string): string;
5
- export declare function buildCountries(locale?: string): Array<PhoneCountry>;
6
3
  /** Ambiguous for shared codes like "+1" — last resort, not exact. */
7
4
  export declare function isoFromDialCode(dialCode: string): string | undefined;
8
5
  export declare function isPartialCallingCode(digits: string): boolean;
9
- export declare function resolveIso(value: string, explicitIso?: string): string | undefined;
10
6
  export type PickCountryOptionArgs<T> = {
11
7
  detectedIso?: string;
12
8
  callingCode: string;
@@ -1,30 +1,6 @@
1
- import examples from "libphonenumber-js/examples.mobile.json";
2
1
  import { AsYouType, formatIncompletePhoneNumber, getCountries, getCountryCallingCode, getExampleNumber, isValidPhoneNumber, parseDigits, parsePhoneNumberFromString } from "libphonenumber-js/min";
2
+ import examples from "libphonenumber-js/examples.mobile.json";
3
3
  //#region src/components/inputs/PhoneInput/phone.ts
4
- function isoToFlag(iso) {
5
- return iso.toUpperCase().replace(/./gu, (char) => String.fromCodePoint(127397 + (char.codePointAt(0) ?? 0)));
6
- }
7
- function safeDisplayNames(locale) {
8
- try {
9
- return new Intl.DisplayNames([locale], { type: "region" });
10
- } catch {
11
- return;
12
- }
13
- }
14
- var countriesByLocale = /* @__PURE__ */ new Map();
15
- function buildCountries(locale = "en") {
16
- const cached = countriesByLocale.get(locale);
17
- if (cached) return cached;
18
- const displayNames = safeDisplayNames(locale);
19
- const built = getCountries().map((iso) => ({
20
- isoCode: iso,
21
- dialCode: `+${getCountryCallingCode(iso)}`,
22
- flag: isoToFlag(iso),
23
- name: displayNames?.of(iso) ?? iso
24
- })).sort((countryA, countryB) => countryA.name.localeCompare(countryB.name, locale));
25
- countriesByLocale.set(locale, built);
26
- return built;
27
- }
28
4
  var callingCodeIndex;
29
5
  function indexCallingCodes() {
30
6
  if (callingCodeIndex) return callingCodeIndex;
@@ -48,10 +24,6 @@ function isoFromDialCode(dialCode) {
48
24
  function isPartialCallingCode(digits) {
49
25
  return indexCallingCodes().prefixes.has(digits);
50
26
  }
51
- function resolveIso(value, explicitIso) {
52
- if (explicitIso) return explicitIso.toUpperCase();
53
- return /^[A-Za-z]{2}$/.test(value) ? value.toUpperCase() : void 0;
54
- }
55
27
  /** Keeps the current selection when its dial code already matches, e.g. "+44" staying GB instead of GG. */
56
28
  function pickCountryOption({ detectedIso, callingCode, options, currentOption, priorityCountries, isoOf, dialOf }) {
57
29
  const dial = `+${callingCode}`;
@@ -125,6 +97,6 @@ function isValidPhone(value, iso) {
125
97
  return isValidPhoneNumber(value, iso);
126
98
  }
127
99
  //#endregion
128
- export { buildCountries, describe, detectIntl, exampleNational, formatNational, isPartialCallingCode, isValidPhone, isoFromDialCode, isoToFlag, nationalDigitsFromE164, parseDigits, pickCountryOption, resolveIso, splitE164, toIntlCandidate };
100
+ export { describe, detectIntl, exampleNational, formatNational, isPartialCallingCode, isValidPhone, isoFromDialCode, nationalDigitsFromE164, parseDigits, pickCountryOption, splitE164, toIntlCandidate };
129
101
 
130
102
  //# sourceMappingURL=phone.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"phone.js","names":[],"sources":["../../../../src/components/inputs/PhoneInput/phone.ts"],"sourcesContent":["import examples from 'libphonenumber-js/examples.mobile.json'\nimport {\n AsYouType,\n formatIncompletePhoneNumber,\n getCountries,\n getCountryCallingCode,\n getExampleNumber,\n isValidPhoneNumber,\n parseDigits,\n parsePhoneNumberFromString,\n type CountryCode,\n} from 'libphonenumber-js/min'\n\nimport type { PhoneCountry } from './types'\n\nexport { parseDigits }\n\nexport function isoToFlag(iso: string): string {\n return iso.toUpperCase().replace(/./gu, (char) => String.fromCodePoint(127397 + (char.codePointAt(0) ?? 0)))\n}\n\nfunction safeDisplayNames(locale: string): Intl.DisplayNames | undefined {\n try {\n return new Intl.DisplayNames([locale], { type: 'region' })\n } catch {\n return undefined\n }\n}\n\nconst countriesByLocale = new Map<string, Array<PhoneCountry>>()\n\nexport function buildCountries(locale = 'en'): Array<PhoneCountry> {\n const cached = countriesByLocale.get(locale)\n if (cached) return cached\n\n const displayNames = safeDisplayNames(locale)\n const built = getCountries()\n .map((iso) => ({\n isoCode: iso,\n dialCode: `+${getCountryCallingCode(iso)}`,\n flag: isoToFlag(iso),\n name: displayNames?.of(iso) ?? iso,\n }))\n .sort((countryA, countryB) => countryA.name.localeCompare(countryB.name, locale))\n\n countriesByLocale.set(locale, built)\n return built\n}\n\ntype CallingCodeIndex = { isoByCode: Map<string, string>; prefixes: Set<string> }\n\nlet callingCodeIndex: CallingCodeIndex | undefined\n\nfunction indexCallingCodes(): CallingCodeIndex {\n if (callingCodeIndex) return callingCodeIndex\n\n const isoByCode = new Map<string, string>()\n const prefixes = new Set<string>()\n for (const iso of getCountries()) {\n const code = getCountryCallingCode(iso)\n if (!isoByCode.has(code)) isoByCode.set(code, iso)\n for (let end = 1; end <= code.length; end++) prefixes.add(code.slice(0, end))\n }\n\n callingCodeIndex = { isoByCode, prefixes }\n return callingCodeIndex\n}\n\n/** Ambiguous for shared codes like \"+1\" — last resort, not exact. */\nexport function isoFromDialCode(dialCode: string): string | undefined {\n return indexCallingCodes().isoByCode.get(parseDigits(dialCode))\n}\n\nexport function isPartialCallingCode(digits: string): boolean {\n return indexCallingCodes().prefixes.has(digits)\n}\n\nexport function resolveIso(value: string, explicitIso?: string): string | undefined {\n if (explicitIso) return explicitIso.toUpperCase()\n return /^[A-Za-z]{2}$/.test(value) ? value.toUpperCase() : undefined\n}\n\nexport type PickCountryOptionArgs<T> = {\n detectedIso?: string\n callingCode: string\n options: Array<T>\n currentOption?: T\n priorityCountries?: Array<string>\n isoOf: (option: T) => string | undefined\n dialOf: (option: T) => string\n}\n\n/** Keeps the current selection when its dial code already matches, e.g. \"+44\" staying GB instead of GG. */\nexport function pickCountryOption<T>({\n detectedIso,\n callingCode,\n options,\n currentOption,\n priorityCountries,\n isoOf,\n dialOf,\n}: PickCountryOptionArgs<T>): T | undefined {\n const dial = `+${callingCode}`\n const matchesDial = (option: T) => dialOf(option) === dial\n\n if (currentOption && matchesDial(currentOption)) return currentOption\n\n const priorityMatch = priorityCountries\n ?.map((iso) => options.find((option) => isoOf(option) === iso.toUpperCase()))\n .find((option) => option && matchesDial(option))\n if (priorityMatch) return priorityMatch\n\n const exactMatch = detectedIso && options.find((option) => isoOf(option) === detectedIso)\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- `exactMatch` can be an empty string (falsy but not nullish) when `detectedIso` is unset\n return exactMatch || options.find(matchesDial)\n}\n\nexport function formatNational(digits: string, iso?: string): string {\n return formatIncompletePhoneNumber(digits, iso as CountryCode | undefined)\n}\n\nexport type PhoneDescription = {\n formatted: string\n e164?: string\n isPossible: boolean\n isValid: boolean\n tooLong: boolean\n}\n\nexport function describe(digits: string, iso?: string): PhoneDescription {\n const ayt = new AsYouType(iso as CountryCode | undefined)\n const formatted = ayt.input(digits)\n return {\n formatted,\n e164: ayt.getNumberValue(),\n isPossible: ayt.isPossible(),\n isValid: ayt.isValid(),\n tooLong: ayt.validateLength() === 'TOO_LONG',\n }\n}\n\n/** Null when the text is not international. */\nexport function toIntlCandidate(raw: string): string | null {\n const trimmed = raw.trim()\n if (trimmed.startsWith('+')) return trimmed\n const bare = trimmed.replace(/[\\s().-]/g, '')\n if (/^00\\d/.test(bare)) return `+${bare.slice(2)}`\n return null\n}\n\nexport type IntlDetection = {\n iso?: string\n callingCode?: string\n national: string\n}\n\nexport function detectIntl(text: string): IntlDetection {\n const ayt = new AsYouType()\n ayt.input(text)\n const callingCode = ayt.getCallingCode()\n return {\n iso: ayt.getCountry(),\n callingCode,\n national: nationalDigitsFromE164(ayt.getNumberValue(), callingCode),\n }\n}\n\n/** Keeps trunk prefixes, e.g. GB \"+447911123456\" gives \"07911123456\". */\nexport function nationalDigitsFromE164(e164?: string, callingCode?: string): string {\n if (!e164) return ''\n const parsed = parsePhoneNumberFromString(e164)\n if (parsed) return parseDigits(parsed.formatNational())\n\n let code = callingCode\n if (code === undefined) {\n const ayt = new AsYouType()\n ayt.input(e164)\n code = ayt.getCallingCode()\n }\n const digits = parseDigits(e164)\n return code ? digits.slice(code.length) : digits\n}\n\nexport function exampleNational(iso?: string): string | undefined {\n if (!iso) return undefined\n return getExampleNumber(iso as CountryCode, examples)?.formatNational()\n}\n\nexport type SplitE164 = {\n isoCode?: string\n dialCode?: string\n national: string\n}\n\nexport function splitE164(value: string | undefined): SplitE164 {\n if (!value) return { national: '' }\n const intl = toIntlCandidate(value)\n if (!intl) return { national: parseDigits(value) }\n const { iso, callingCode, national } = detectIntl(intl)\n return { isoCode: iso, dialCode: callingCode ? `+${callingCode}` : undefined, national }\n}\n\nexport function isValidPhone(value: string, iso?: string): boolean {\n return isValidPhoneNumber(value, iso as CountryCode | undefined)\n}\n"],"mappings":";;;AAiBA,SAAgB,UAAU,KAAqB;CAC7C,OAAO,IAAI,YAAY,CAAC,CAAC,QAAQ,QAAQ,SAAS,OAAO,cAAc,UAAU,KAAK,YAAY,CAAC,KAAK,EAAE,CAAC;AAC7G;AAEA,SAAS,iBAAiB,QAA+C;CACvE,IAAI;EACF,OAAO,IAAI,KAAK,aAAa,CAAC,MAAM,GAAG,EAAE,MAAM,SAAS,CAAC;CAC3D,QAAQ;EACN;CACF;AACF;AAEA,IAAM,oCAAoB,IAAI,IAAiC;AAE/D,SAAgB,eAAe,S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AY,OAAO,eAAe,CAAC;CAEtD,IAAI,OAAO;CACX,IAAI,SAAS,KAAA,GAAW;EACtB,MAAM,MAAM,IAAI,UAAU;EAC1B,IAAI,MAAM,IAAI;EACd,OAAO,IAAI,eAAe;CAC5B;CACA,MAAM,SAAS,YAAY,IAAI;CAC/B,OAAO,OAAO,OAAO,MAAM,KAAK,MAAM,IAAI;AAC5C;AAEA,SAAgB,gBAAgB,KAAkC;CAChE,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,OAAO,iBAAiB,KAAoB,QAAQ,CAAC,EAAE,eAAe;AACxE;AAQA,SAAgB,UAAU,OAAsC;CAC9D,IAAI,CAAC,OAAO,OAAO,EAAE,UAAU,GAAG;CAClC,MAAM,OAAO,gBAAgB,KAAK;CAClC,IAAI,CAAC,MAAM,OAAO,EAAE,UAAU,YAAY,KAAK,EAAE;CACjD,MAAM,EAAE,KAAK,aAAa,aAAa,WAAW,IAAI;CACtD,OAAO;EAAE,SAAS;EAAK,UAAU,cAAc,IAAI,gBAAgB,KAAA;EAAW;CAAS;AACzF;AAEA,SAAgB,aAAa,OAAe,KAAuB;CACjE,OAAO,mBAAmB,OAAO,GAA8B;AACjE"}
1
+ {"version":3,"file":"phone.js","names":[],"sources":["../../../../src/components/inputs/PhoneInput/phone.ts"],"sourcesContent":["import examples from 'libphonenumber-js/examples.mobile.json'\nimport {\n AsYouType,\n formatIncompletePhoneNumber,\n getCountries,\n getCountryCallingCode,\n getExampleNumber,\n isValidPhoneNumber,\n parseDigits,\n parsePhoneNumberFromString,\n type CountryCode,\n} from 'libphonenumber-js/min'\n\nexport { parseDigits }\n\ntype CallingCodeIndex = { isoByCode: Map<string, string>; prefixes: Set<string> }\n\nlet callingCodeIndex: CallingCodeIndex | undefined\n\nfunction indexCallingCodes(): CallingCodeIndex {\n if (callingCodeIndex) return callingCodeIndex\n\n const isoByCode = new Map<string, string>()\n const prefixes = new Set<string>()\n for (const iso of getCountries()) {\n const code = getCountryCallingCode(iso)\n if (!isoByCode.has(code)) isoByCode.set(code, iso)\n for (let end = 1; end <= code.length; end++) prefixes.add(code.slice(0, end))\n }\n\n callingCodeIndex = { isoByCode, prefixes }\n return callingCodeIndex\n}\n\n/** Ambiguous for shared codes like \"+1\" — last resort, not exact. */\nexport function isoFromDialCode(dialCode: string): string | undefined {\n return indexCallingCodes().isoByCode.get(parseDigits(dialCode))\n}\n\nexport function isPartialCallingCode(digits: string): boolean {\n return indexCallingCodes().prefixes.has(digits)\n}\n\nexport type PickCountryOptionArgs<T> = {\n detectedIso?: string\n callingCode: string\n options: Array<T>\n currentOption?: T\n priorityCountries?: Array<string>\n isoOf: (option: T) => string | undefined\n dialOf: (option: T) => string\n}\n\n/** Keeps the current selection when its dial code already matches, e.g. \"+44\" staying GB instead of GG. */\nexport function pickCountryOption<T>({\n detectedIso,\n callingCode,\n options,\n currentOption,\n priorityCountries,\n isoOf,\n dialOf,\n}: PickCountryOptionArgs<T>): T | undefined {\n const dial = `+${callingCode}`\n const matchesDial = (option: T) => dialOf(option) === dial\n\n if (currentOption && matchesDial(currentOption)) return currentOption\n\n const priorityMatch = priorityCountries\n ?.map((iso) => options.find((option) => isoOf(option) === iso.toUpperCase()))\n .find((option) => option && matchesDial(option))\n if (priorityMatch) return priorityMatch\n\n const exactMatch = detectedIso && options.find((option) => isoOf(option) === detectedIso)\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- `exactMatch` can be an empty string (falsy but not nullish) when `detectedIso` is unset\n return exactMatch || options.find(matchesDial)\n}\n\nexport function formatNational(digits: string, iso?: string): string {\n return formatIncompletePhoneNumber(digits, iso as CountryCode | undefined)\n}\n\nexport type PhoneDescription = {\n formatted: string\n e164?: string\n isPossible: boolean\n isValid: boolean\n tooLong: boolean\n}\n\nexport function describe(digits: string, iso?: string): PhoneDescription {\n const ayt = new AsYouType(iso as CountryCode | undefined)\n const formatted = ayt.input(digits)\n return {\n formatted,\n e164: ayt.getNumberValue(),\n isPossible: ayt.isPossible(),\n isValid: ayt.isValid(),\n tooLong: ayt.validateLength() === 'TOO_LONG',\n }\n}\n\n/** Null when the text is not international. */\nexport function toIntlCandidate(raw: string): string | null {\n const trimmed = raw.trim()\n if (trimmed.startsWith('+')) return trimmed\n const bare = trimmed.replace(/[\\s().-]/g, '')\n if (/^00\\d/.test(bare)) return `+${bare.slice(2)}`\n return null\n}\n\nexport type IntlDetection = {\n iso?: string\n callingCode?: string\n national: string\n}\n\nexport function detectIntl(text: string): IntlDetection {\n const ayt = new AsYouType()\n ayt.input(text)\n const callingCode = ayt.getCallingCode()\n return {\n iso: ayt.getCountry(),\n callingCode,\n national: nationalDigitsFromE164(ayt.getNumberValue(), callingCode),\n }\n}\n\n/** Keeps trunk prefixes, e.g. GB \"+447911123456\" gives \"07911123456\". */\nexport function nationalDigitsFromE164(e164?: string, callingCode?: string): string {\n if (!e164) return ''\n const parsed = parsePhoneNumberFromString(e164)\n if (parsed) return parseDigits(parsed.formatNational())\n\n let code = callingCode\n if (code === undefined) {\n const ayt = new AsYouType()\n ayt.input(e164)\n code = ayt.getCallingCode()\n }\n const digits = parseDigits(e164)\n return code ? digits.slice(code.length) : digits\n}\n\nexport function exampleNational(iso?: string): string | undefined {\n if (!iso) return undefined\n return getExampleNumber(iso as CountryCode, examples)?.formatNational()\n}\n\nexport type SplitE164 = {\n isoCode?: string\n dialCode?: string\n national: string\n}\n\nexport function splitE164(value: string | undefined): SplitE164 {\n if (!value) return { national: '' }\n const intl = toIntlCandidate(value)\n if (!intl) return { national: parseDigits(value) }\n const { iso, callingCode, national } = detectIntl(intl)\n return { isoCode: iso, dialCode: callingCode ? `+${callingCode}` : undefined, national }\n}\n\nexport function isValidPhone(value: string, iso?: string): boolean {\n return isValidPhoneNumber(value, iso as CountryCode | undefined)\n}\n"],"mappings":";;;AAiBA,IAAI;AAEJ,SAAS,oBAAsC;CAC7C,IAAI,kBAAkB,OAAO;CAE7B,MAAM,4BAAY,IAAI,IAAoB;CAC1C,MAAM,2BAAW,IAAI,IA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F;AAEA,SAAgB,aAAa,OAAe,KAAuB;CACjE,OAAO,mBAAmB,OAAO,GAA8B;AACjE"}
@@ -1,9 +1,5 @@
1
- export type PhoneCountry = {
2
- isoCode: string;
3
- dialCode: string;
4
- flag: string;
5
- name: string;
6
- };
1
+ import { Country } from '../../../lib/countries';
2
+ export type PhoneCountry = Country;
7
3
  export type PhoneValue<T = PhoneCountry> = {
8
4
  country?: string;
9
5
  countryOption?: T;
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export * from './components/inputs/Button';
2
2
  export * from './components/inputs/Calendar';
3
3
  export * from './components/inputs/Checkbox';
4
4
  export * from './components/inputs/Combobox';
5
+ export * from './components/inputs/CountrySelect';
5
6
  export * from './components/inputs/DatePicker';
6
7
  export * from './components/inputs/Form';
7
8
  export * from './components/inputs/InlineMultiSelect';
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { StaticComboboxList } from "./components/inputs/Combobox/StaticComboboxL
11
11
  import { useCombobox } from "./components/inputs/Combobox/useCombobox.js";
12
12
  import { VirtualizedComboboxList } from "./components/inputs/Combobox/VirtualizedComboboxList.js";
13
13
  import { Combobox } from "./components/inputs/Combobox/Combobox.js";
14
+ import { CountrySelect } from "./components/inputs/CountrySelect/CountrySelect.js";
14
15
  import { DatePicker } from "./components/inputs/DatePicker/DatePicker.js";
15
16
  import { Label } from "./components/data-display/Label/Label.js";
16
17
  import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useFormField } from "./components/inputs/Form/Form.js";
@@ -49,4 +50,4 @@ import { BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, Bre
49
50
  import { Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetRoot, SheetTitle, SheetTrigger } from "./components/navigation/Sheet/Sheet.js";
50
51
  import { SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarRoot, SidebarSeparator, SidebarTrigger, sidebarGroupActionVariants, sidebarGroupLabelVariants, sidebarMenuActionVariants, sidebarMenuBadgeVariants, sidebarMenuButtonVariants, sidebarMenuSubButtonVariants, sidebarMenuSubVariants, useSidebar } from "./components/navigation/Sidebar/Sidebar.js";
51
52
  import { Tabs, TabsContent, TabsLink, TabsList, TabsTrigger } from "./components/navigation/Tabs/Tabs.js";
52
- export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Avatar, AvatarFallback, AvatarGroup, AvatarImage, Badge, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbRoot, BreadcrumbSeparator, Button, Calendar, Card, CardContent, CardMedia, Carousel, CarouselContent, CarouselContext, CarouselItem, CarouselNext, CarouselPrevious, Checkbox, Chip, CollapsibleContent, CollapsibleRoot, CollapsibleTrigger, Combobox, ComboboxOptionWithTooltip, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, DataTable, DatePicker, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, InlineMultiSelect, Input, InputDate, Label, LazyDatePicker, Marquee, MultiSelect, NavigationBreadcrumb, NotificationBadge, PagesBreadcrumb, Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, PaginationRoot, PhoneInput, Popover, PopoverAnchor, PopoverContent, PopoverRoot, PopoverTrigger, Progress, RadioGroup, RadioGroupItem, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectRoot, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetRoot, SheetTitle, SheetTrigger, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarRoot, SidebarSeparator, SidebarTrigger, Skeleton, StarRating, StaticComboboxList, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsLink, TabsList, TabsTrigger, Textarea, Toaster, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipPortal, TooltipProvider, TooltipRoot, TooltipTrigger, TruncatedTypographyWithTooltip, Typography, VirtualizedComboboxList, badgeVariants, buttonVariants, chipVariants, isValidPhone, isoFromDialCode, notificationBadgeVariants, sidebarGroupActionVariants, sidebarGroupLabelVariants, sidebarMenuActionVariants, sidebarMenuBadgeVariants, sidebarMenuButtonVariants, sidebarMenuSubButtonVariants, sidebarMenuSubVariants, splitE164, toast, toggleVariants, typographyVariants, useCombobox, useFormField, useSidebar };
53
+ export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Avatar, AvatarFallback, AvatarGroup, AvatarImage, Badge, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbRoot, BreadcrumbSeparator, Button, Calendar, Card, CardContent, CardMedia, Carousel, CarouselContent, CarouselContext, CarouselItem, CarouselNext, CarouselPrevious, Checkbox, Chip, CollapsibleContent, CollapsibleRoot, CollapsibleTrigger, Combobox, ComboboxOptionWithTooltip, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, CountrySelect, DataTable, DatePicker, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, InlineMultiSelect, Input, InputDate, Label, LazyDatePicker, Marquee, MultiSelect, NavigationBreadcrumb, NotificationBadge, PagesBreadcrumb, Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, PaginationRoot, PhoneInput, Popover, PopoverAnchor, PopoverContent, PopoverRoot, PopoverTrigger, Progress, RadioGroup, RadioGroupItem, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectRoot, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetRoot, SheetTitle, SheetTrigger, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarRoot, SidebarSeparator, SidebarTrigger, Skeleton, StarRating, StaticComboboxList, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsLink, TabsList, TabsTrigger, Textarea, Toaster, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipPortal, TooltipProvider, TooltipRoot, TooltipTrigger, TruncatedTypographyWithTooltip, Typography, VirtualizedComboboxList, badgeVariants, buttonVariants, chipVariants, isValidPhone, isoFromDialCode, notificationBadgeVariants, sidebarGroupActionVariants, sidebarGroupLabelVariants, sidebarMenuActionVariants, sidebarMenuBadgeVariants, sidebarMenuButtonVariants, sidebarMenuSubButtonVariants, sidebarMenuSubVariants, splitE164, toast, toggleVariants, typographyVariants, useCombobox, useFormField, useSidebar };
@@ -0,0 +1,16 @@
1
+ export type Country = {
2
+ isoCode: string;
3
+ dialCode: string;
4
+ flag: string;
5
+ name: string;
6
+ };
7
+ export declare function isoToFlag(iso: string): string;
8
+ export declare function regionName(iso: string, locale?: string): string;
9
+ /** libphonenumber countries, named in `locale`, sorted by name. */
10
+ export declare function buildCountries(locale?: string): Array<Country>;
11
+ export declare function resolveIso(value: string, explicitIso?: string): string | undefined;
12
+ /** Splits out `priorityIsos` options, in that order. */
13
+ export declare function splitByPriority<T>(options: Array<T>, priorityIsos: Array<string> | undefined, isoOf: (option: T) => string | undefined): {
14
+ priority: Array<T>;
15
+ rest: Array<T>;
16
+ };
@@ -0,0 +1,54 @@
1
+ import { getCountries, getCountryCallingCode } from "libphonenumber-js/min";
2
+ //#region src/lib/countries.ts
3
+ function isoToFlag(iso) {
4
+ return iso.toUpperCase().replace(/./gu, (char) => String.fromCodePoint(127397 + (char.codePointAt(0) ?? 0)));
5
+ }
6
+ var displayNamesByLocale = /* @__PURE__ */ new Map();
7
+ function createDisplayNames(locale) {
8
+ try {
9
+ return new Intl.DisplayNames([locale], { type: "region" });
10
+ } catch {
11
+ return;
12
+ }
13
+ }
14
+ function regionDisplayNames(locale) {
15
+ if (!displayNamesByLocale.has(locale)) displayNamesByLocale.set(locale, createDisplayNames(locale));
16
+ return displayNamesByLocale.get(locale);
17
+ }
18
+ function regionName(iso, locale = "en") {
19
+ return regionDisplayNames(locale)?.of(iso) ?? iso;
20
+ }
21
+ var countriesByLocale = /* @__PURE__ */ new Map();
22
+ /** libphonenumber countries, named in `locale`, sorted by name. */
23
+ function buildCountries(locale = "en") {
24
+ const cached = countriesByLocale.get(locale);
25
+ if (cached) return cached;
26
+ const built = getCountries().map((iso) => ({
27
+ isoCode: iso,
28
+ dialCode: `+${getCountryCallingCode(iso)}`,
29
+ flag: isoToFlag(iso),
30
+ name: regionName(iso, locale)
31
+ })).sort((countryA, countryB) => countryA.name.localeCompare(countryB.name, locale));
32
+ countriesByLocale.set(locale, built);
33
+ return built;
34
+ }
35
+ function resolveIso(value, explicitIso) {
36
+ if (explicitIso) return explicitIso.toUpperCase();
37
+ return /^[A-Za-z]{2}$/.test(value) ? value.toUpperCase() : void 0;
38
+ }
39
+ /** Splits out `priorityIsos` options, in that order. */
40
+ function splitByPriority(options, priorityIsos, isoOf) {
41
+ if (!priorityIsos?.length) return {
42
+ priority: [],
43
+ rest: options
44
+ };
45
+ const priority = priorityIsos.map((iso) => options.find((option) => isoOf(option) === iso.toUpperCase())).filter((option) => option !== void 0);
46
+ return {
47
+ priority,
48
+ rest: options.filter((option) => !priority.includes(option))
49
+ };
50
+ }
51
+ //#endregion
52
+ export { buildCountries, isoToFlag, regionName, resolveIso, splitByPriority };
53
+
54
+ //# sourceMappingURL=countries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"countries.js","names":[],"sources":["../../src/lib/countries.ts"],"sourcesContent":["import { getCountries, getCountryCallingCode } from 'libphonenumber-js/min'\n\nexport type Country = {\n isoCode: string\n dialCode: string\n flag: string\n name: string\n}\n\nexport function isoToFlag(iso: string): string {\n return iso.toUpperCase().replace(/./gu, (char) => String.fromCodePoint(127397 + (char.codePointAt(0) ?? 0)))\n}\n\nconst displayNamesByLocale = new Map<string, Intl.DisplayNames | undefined>()\n\nfunction createDisplayNames(locale: string): Intl.DisplayNames | undefined {\n try {\n return new Intl.DisplayNames([locale], { type: 'region' })\n } catch {\n return undefined\n }\n}\n\nfunction regionDisplayNames(locale: string): Intl.DisplayNames | undefined {\n if (!displayNamesByLocale.has(locale)) displayNamesByLocale.set(locale, createDisplayNames(locale))\n return displayNamesByLocale.get(locale)\n}\n\nexport function regionName(iso: string, locale = 'en'): string {\n return regionDisplayNames(locale)?.of(iso) ?? iso\n}\n\nconst countriesByLocale = new Map<string, Array<Country>>()\n\n/** libphonenumber countries, named in `locale`, sorted by name. */\nexport function buildCountries(locale = 'en'): Array<Country> {\n const cached = countriesByLocale.get(locale)\n if (cached) return cached\n\n const built = getCountries()\n .map((iso) => ({\n isoCode: iso,\n dialCode: `+${getCountryCallingCode(iso)}`,\n flag: isoToFlag(iso),\n name: regionName(iso, locale),\n }))\n .sort((countryA, countryB) => countryA.name.localeCompare(countryB.name, locale))\n\n countriesByLocale.set(locale, built)\n return built\n}\n\nexport function resolveIso(value: string, explicitIso?: string): string | undefined {\n if (explicitIso) return explicitIso.toUpperCase()\n return /^[A-Za-z]{2}$/.test(value) ? value.toUpperCase() : undefined\n}\n\n/** Splits out `priorityIsos` options, in that order. */\nexport function splitByPriority<T>(\n options: Array<T>,\n priorityIsos: Array<string> | undefined,\n isoOf: (option: T) => string | undefined,\n): { priority: Array<T>; rest: Array<T> } {\n if (!priorityIsos?.length) return { priority: [], rest: options }\n\n const priority = priorityIsos\n .map((iso) => options.find((option) => isoOf(option) === iso.toUpperCase()))\n .filter((option): option is T => option !== undefined)\n const rest = options.filter((option) => !priority.includes(option))\n return { priority, rest }\n}\n"],"mappings":";;AASA,SAAgB,UAAU,KAAqB;CAC7C,OAAO,IAAI,YAAY,CAAC,CAAC,QAAQ,QAAQ,SAAS,OAAO,cAAc,UAAU,KAAK,YAAY,CAAC,KAAK,EAAE,CAAC;AAC7G;AAEA,IAAM,uC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AAO;EAAE;EAAU,MADN,QAAQ,QAAQ,WAAW,CAAC,SAAS,SAAS,MAAM,CAC9C;CAAK;AAC1B"}
@@ -5,3 +5,5 @@ export type ColorToken = (typeof COLOR_TOKENS)[number];
5
5
  export declare function resolveColor(color: string | undefined, fallback?: string): string;
6
6
  /** Lowercases and strips diacritics so accent-insensitive comparisons can be made (e.g. "país" matches "pais"). */
7
7
  export declare function normalizeForSearch(value: string): string;
8
+ /** Every search word must appear in some term, ignoring accents, case and order. */
9
+ export declare function createSearchMatcher(search: string): (terms: Array<string>) => boolean;
package/dist/lib/utils.js CHANGED
@@ -21,7 +21,16 @@ function resolveColor(color, fallback = "primary") {
21
21
  function normalizeForSearch(value) {
22
22
  return value.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase();
23
23
  }
24
+ /** Every search word must appear in some term, ignoring accents, case and order. */
25
+ function createSearchMatcher(search) {
26
+ const tokens = normalizeForSearch(search).split(/\s+/).filter(Boolean);
27
+ if (tokens.length === 0) return () => true;
28
+ return (terms) => {
29
+ const normalizedTerms = terms.map(normalizeForSearch);
30
+ return tokens.every((token) => normalizedTerms.some((term) => term.includes(token)));
31
+ };
32
+ }
24
33
  //#endregion
25
- export { COLOR_TOKENS, cn, normalizeForSearch, resolveColor };
34
+ export { COLOR_TOKENS, cn, createSearchMatcher, normalizeForSearch, resolveColor };
26
35
 
27
36
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../src/lib/utils.ts"],"sourcesContent":["import { type ClassValue, clsx } from 'clsx'\nimport { twMerge } from 'tailwind-merge'\n\nexport function cn(...inputs: Array<ClassValue>) {\n return twMerge(clsx(inputs))\n}\n\nexport const COLOR_TOKENS = ['primary', 'accent', 'success', 'warning', 'error', 'information'] as const\nexport type ColorToken = (typeof COLOR_TOKENS)[number]\n\nexport function resolveColor(color: string | undefined, fallback = 'primary'): string {\n const value = color ?? fallback\n if (COLOR_TOKENS.includes(value as ColorToken)) return `var(--color-${value})`\n return value\n}\n\n/** Lowercases and strips diacritics so accent-insensitive comparisons can be made (e.g. \"país\" matches \"pais\"). */\nexport function normalizeForSearch(value: string): string {\n return value\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase()\n}\n"],"mappings":";;;AAGA,SAAgB,GAAG,GAAG,QAA2B;CAC/C,OAAO,QAAQ,KAAK,MAAM,CAAC;AAC7B;AAEA,IAAa,eAAe;CAAC;CAAW;CAAU;CAAW;CAAW;CAAS;AAAa;AAG9F,SAAgB,aAAa,OAA2B,WAAW,WAAmB;CACpF,MAAM,QAAQ,SAAS;CACvB,IAAI,aAAa,SAAS,KAAmB,GAAG,OAAO,eAAe,MAAM;CAC5E,OAAO;AACT;;AAGA,SAAgB,mBAAmB,OAAuB;CACxD,OAAO,MACJ,UAAU,KAAK,CAAC,CAChB,QAAQ,mBAAmB,EAAE,CAAC,CAC9B,YAAY;AACjB"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../src/lib/utils.ts"],"sourcesContent":["import { type ClassValue, clsx } from 'clsx'\nimport { twMerge } from 'tailwind-merge'\n\nexport function cn(...inputs: Array<ClassValue>) {\n return twMerge(clsx(inputs))\n}\n\nexport const COLOR_TOKENS = ['primary', 'accent', 'success', 'warning', 'error', 'information'] as const\nexport type ColorToken = (typeof COLOR_TOKENS)[number]\n\nexport function resolveColor(color: string | undefined, fallback = 'primary'): string {\n const value = color ?? fallback\n if (COLOR_TOKENS.includes(value as ColorToken)) return `var(--color-${value})`\n return value\n}\n\n/** Lowercases and strips diacritics so accent-insensitive comparisons can be made (e.g. \"país\" matches \"pais\"). */\nexport function normalizeForSearch(value: string): string {\n return value\n .normalize('NFD')\n .replace(/\\p{Diacritic}/gu, '')\n .toLowerCase()\n}\n\n/** Every search word must appear in some term, ignoring accents, case and order. */\nexport function createSearchMatcher(search: string): (terms: Array<string>) => boolean {\n const tokens = normalizeForSearch(search).split(/\\s+/).filter(Boolean)\n if (tokens.length === 0) return () => true\n return (terms) => {\n const normalizedTerms = terms.map(normalizeForSearch)\n return tokens.every((token) => normalizedTerms.some((term) => term.includes(token)))\n }\n}\n"],"mappings":";;;AAGA,SAAgB,GAAG,GAAG,QAA2B;CAC/C,OAAO,QAAQ,KAAK,MAAM,CAAC;AAC7B;AAEA,IAAa,eAAe;CAAC;CAAW;CAAU;CAAW;CAAW;CAAS;AAAa;AAG9F,SAAgB,aAAa,OAA2B,WAAW,WAAmB;CACpF,MAAM,QAAQ,SAAS;CACvB,IAAI,aAAa,SAAS,KAAmB,GAAG,OAAO,eAAe,MAAM;CAC5E,OAAO;AACT;;AAGA,SAAgB,mBAAmB,OAAuB;CACxD,OAAO,MACJ,UAAU,KAAK,CAAC,CAChB,QAAQ,mBAAmB,EAAE,CAAC,CAC9B,YAAY;AACjB;;AAGA,SAAgB,oBAAoB,QAAmD;CACrF,MAAM,SAAS,mBAAmB,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,OAAO,OAAO;CACrE,IAAI,OAAO,WAAW,GAAG,aAAa;CACtC,QAAQ,UAAU;EAChB,MAAM,kBAAkB,MAAM,IAAI,kBAAkB;EACpD,OAAO,OAAO,OAAO,UAAU,gBAAgB,MAAM,SAAS,KAAK,SAAS,KAAK,CAAC,CAAC;CACrF;AACF"}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "periplo-ui",
3
3
  "description": "IATI UI library",
4
4
  "private": false,
5
- "version": "4.11.4",
5
+ "version": "4.12.0",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
8
8
  "types": "dist/index.d.ts",