@plexui/react-native 0.2.10 → 0.2.12

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,246 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useMemo, useRef, useState } from "react";
3
+ import { Animated, ScrollView, StyleSheet, View, useWindowDimensions, } from "react-native";
4
+ import { useSafeAreaInsets } from "react-native-safe-area-context";
5
+ import CheckMd from "../../icons/plex/CheckMd";
6
+ import Search from "../../icons/plex/Search";
7
+ import { Pressable } from "../../internal/Pressable";
8
+ import { ANDROID_DIM, iosDim, Overlay } from "../../internal/Overlay";
9
+ import { useKeyboardHeight } from "../../internal/keyboard";
10
+ import { useTheme } from "../../theme/ThemeProvider";
11
+ import { Field } from "../Field/Field";
12
+ import { FloatingLabelInput } from "../FloatingLabelInput/FloatingLabelInput";
13
+ import { MaterialArrowDropDown } from "../Icon/material";
14
+ import { Input } from "../Input/Input";
15
+ import { List, ListItem } from "../List/List";
16
+ import { NavigationButton } from "../NavigationButton/NavigationButton";
17
+ import { Text } from "../Text/Text";
18
+ import { ALL_COUNTRIES, countryFlag, countryName, deviceCountry, dialCode, digitsOf, fold, isCountry, matchesCountry, readInput, readNational, readValue, tooLongValue, } from "./phone";
19
+ /** A region's calling code, kept left to right in a right-to-left line. */
20
+ const ltr = (text) => `⁦${text}⁩`;
21
+ /**
22
+ * A phone number field: the region and the number, as iOS's Add Phone Number (Settings): one group of two rows, the
23
+ * region's code and name with a chevron, which opens the list of regions, then the number alone; on Android Material's
24
+ * region dropdown field over the number's outlined field. The value is E.164; a pasted or autofilled international
25
+ * number picks its region, a national trunk prefix (the UK's 0) is dropped from the value, and the field takes no more
26
+ * digits than the region's longest number (libphonenumber's metadata).
27
+ */
28
+ export function PhoneInput({ value: valueProp, defaultValue, onChange, country: countryProp, defaultCountry, onCountryChange, countries = ALL_COUNTRIES, locale, formatting, flags = false, label = "Phone number", countryLabel = "Country or Region", searchPlaceholder = "Search", header, description, errorMessage, invalid, disabled = false, autoFocus, onBlur, onSubmitEditing, returnKeyType, testID, style, }) {
29
+ const theme = useTheme();
30
+ const android = theme.isAndroid;
31
+ const format = formatting ?? android;
32
+ // The first value is read in the first region; an international one names its own (+44… under a US default)
33
+ const [initial] = useState(() => {
34
+ const start = countryProp ?? defaultCountry ?? deviceCountry();
35
+ return readValue(valueProp ?? defaultValue, start && isCountry(start) ? start : "US", format);
36
+ });
37
+ const [ownCountry, setOwnCountry] = useState(initial.country);
38
+ const country = countryProp ?? ownCountry;
39
+ const [text, setText] = useState(initial.text);
40
+ // The value last sent (or read in): a new value from outside that differs from it is read into the field. Only a
41
+ // new one: a parent's value may come a render after the edit, so an unchanged value is not read as a rejected edit
42
+ const sent = useRef(valueProp ?? defaultValue ?? "");
43
+ useEffect(() => {
44
+ if (valueProp === undefined || valueProp === sent.current)
45
+ return;
46
+ sent.current = valueProp;
47
+ const details = readValue(valueProp, country, format);
48
+ setText(details.text);
49
+ if (details.country !== country)
50
+ pickCountry(details.country);
51
+ // Only a new value from outside is read in
52
+ // eslint-disable-next-line react-hooks/exhaustive-deps
53
+ }, [valueProp]);
54
+ // A controlled region that the first value names otherwise is told once
55
+ useEffect(() => {
56
+ if (countryProp !== undefined && initial.country !== countryProp)
57
+ onCountryChange?.(initial.country);
58
+ // eslint-disable-next-line react-hooks/exhaustive-deps
59
+ }, []);
60
+ // Where the caret is: grouping applies to what is typed at the end only
61
+ const selection = useRef(null);
62
+ const [open, setOpen] = useState(false);
63
+ const pickCountry = (next) => {
64
+ if (countryProp === undefined)
65
+ setOwnCountry(next);
66
+ if (next !== country)
67
+ onCountryChange?.(next);
68
+ };
69
+ const emit = (details) => {
70
+ sent.current = details.value;
71
+ onChange?.(details.value, details);
72
+ };
73
+ const change = (next) => {
74
+ const before = text;
75
+ let input = next;
76
+ // A separator deleted (a space, a dash): the digit before it goes, as the caret would be stuck behind it
77
+ if (input.length < before.length && digitsOf(input) === digitsOf(before)) {
78
+ let at = 0;
79
+ while (at < input.length && input[at] === before[at])
80
+ at++;
81
+ const digit = before.slice(0, at).search(/\d(?=\D*$)/);
82
+ input = digit < 0 ? input : before.slice(0, digit) + before.slice(digit + 1);
83
+ }
84
+ const typing = !/^\s*(\+|00)/.test(input);
85
+ // Typed at the end the digits take their groups; an edit inside keeps the text as it is, grouped again on blur.
86
+ // At the end: the caret was there (where the platform tells it) and one text starts the other
87
+ const caret = selection.current;
88
+ const atEnd = (caret == null || caret.end >= before.length) && (input.startsWith(before) || before.startsWith(input));
89
+ const details = readInput(input, country, format && atEnd);
90
+ // No more digits than the region's longest number, typed or pasted
91
+ if (digitsOf(input).length > digitsOf(before).length && tooLongValue(details.value))
92
+ return;
93
+ setText(format && !atEnd && typing ? input : details.text);
94
+ if (details.country !== country)
95
+ pickCountry(details.country);
96
+ emit(details);
97
+ };
98
+ const blur = () => {
99
+ if (format && text && !/^\s*\+/.test(text))
100
+ setText(readNational(digitsOf(text), country, true).text);
101
+ onBlur?.();
102
+ };
103
+ const choose = (next) => {
104
+ setOpen(false);
105
+ if (next === country)
106
+ return;
107
+ pickCountry(next);
108
+ // The digits stay; the value follows the new region's code
109
+ const details = readNational(digitsOf(text), next, format);
110
+ setText(details.text);
111
+ emit(details);
112
+ };
113
+ const name = countryName(country, locale);
114
+ const code = dialCode(country);
115
+ const regionName = `${countryLabel}, ${name}, ${code.replace("+", "plus ")}`;
116
+ const fieldProps = {
117
+ value: text,
118
+ onChangeText: change,
119
+ onSelectionChange: (event) => {
120
+ selection.current = event.nativeEvent.selection;
121
+ },
122
+ onBlur: blur,
123
+ onSubmitEditing,
124
+ returnKeyType,
125
+ autoFocus,
126
+ keyboardType: "phone-pad",
127
+ inputMode: "tel",
128
+ textContentType: "telephoneNumber",
129
+ autoComplete: "tel",
130
+ importantForAutofill: "yes",
131
+ accessibilityLabel: label,
132
+ };
133
+ const picker = (_jsx(CountryPicker, { open: open, onClose: () => setOpen(false), value: country, onSelect: choose, countries: countries, locale: locale, flags: flags, title: countryLabel, searchPlaceholder: searchPlaceholder }));
134
+ const error = errorMessage || undefined;
135
+ const marked = invalid ?? error != null;
136
+ if (android) {
137
+ // Material: the region's dropdown field (its arrow turned while the list is open), the number's field under it
138
+ return (_jsxs(View, { style: [styles.androidStack, style], testID: testID, children: [_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: regionName, accessibilityState: { disabled, expanded: open }, disabled: disabled, onPress: () => setOpen(true), children: _jsx(View, { pointerEvents: "none", children: _jsx(FloatingLabelInput, { label: countryLabel, value: `${ltr(code)} ${name}`, readOnly: true, disabled: disabled, endAdornment: _jsx(View, { style: open ? styles.turned : null, children: _jsx(MaterialArrowDropDown, { size: 24, color: theme.material.onSurfaceVariant }) }), importantForAccessibility: "no-hide-descendants" }) }) }), _jsx(FloatingLabelInput, { label: label, type: "tel", errorMessage: error, invalid: marked, description: description, disabled: disabled, ...fieldProps }), picker] }));
139
+ }
140
+ // iOS: one group, the region's row (its code and name in the label color, a chevron) over the number's row
141
+ return (_jsxs(View, { style: style, testID: testID, children: [_jsxs(List, { header: header, footer: description, error: error, children: [_jsx(ListItem, { label: `${ltr(code)} (${name})`, onPress: disabled ? undefined : () => setOpen(true), disabled: disabled, accessibilityLabel: regionName }), _jsx(Field, { row: true, label: label, hideLabel: true, children: _jsx(Input, { placeholder: label, invalid: marked, disabled: disabled, ...fieldProps }) })] }), picker] }));
142
+ }
143
+ /** The section index's step and its letters' size (UIKit's section index, measured on iOS 27.2: 13.787 a letter, 11pt). */
144
+ const INDEX_STEP = 13.787;
145
+ /**
146
+ * The list of regions: on iOS a sheet as large as the screen allows (the sheet bar's Close and title, a search field
147
+ * under it, the picked and the device's regions first, then A to Z with the section index at the trailing edge, a
148
+ * checkmark on the picked one); on Android Material's full-screen dialog (Close, the title, a search field, the list).
149
+ */
150
+ function CountryPicker({ open, onClose, value, onSelect, countries, locale, flags, title, searchPlaceholder }) {
151
+ const theme = useTheme();
152
+ const android = theme.isAndroid;
153
+ const insets = useSafeAreaInsets();
154
+ const { height: screen } = useWindowDimensions();
155
+ const keyboard = useKeyboardHeight(open);
156
+ const [query, setQuery] = useState("");
157
+ // A list that opens again starts from its top, with no search
158
+ const [wasOpen, setWasOpen] = useState(open);
159
+ if (wasOpen !== open) {
160
+ setWasOpen(open);
161
+ if (open)
162
+ setQuery("");
163
+ }
164
+ const named = useMemo(() => {
165
+ const collator = new Intl.Collator(locale, { sensitivity: "base" });
166
+ return countries.map((country) => ({ country, name: countryName(country, locale) })).sort((a, b) => collator.compare(a.name, b.name));
167
+ }, [countries, locale]);
168
+ const sections = useMemo(() => {
169
+ const found = named.filter((item) => matchesCountry(item.country, item.name, query));
170
+ if (query.trim())
171
+ return [{ key: "results", items: found }];
172
+ const here = deviceCountry();
173
+ const top = [value, ...(here && here !== value && countries.includes(here) ? [here] : [])];
174
+ const first = { key: "top", items: top.map((country) => ({ country, name: countryName(country, locale) })) };
175
+ const letters = new Map();
176
+ for (const item of found) {
177
+ const letter = fold(item.name).charAt(0).toUpperCase();
178
+ const key = /[A-Z]/.test(letter) ? letter : "#";
179
+ if (!letters.has(key))
180
+ letters.set(key, { key, title: key, items: [] });
181
+ letters.get(key).items.push(item);
182
+ }
183
+ return [first, ...letters.values()];
184
+ }, [named, query, value, countries, locale]);
185
+ const scroller = useRef(null);
186
+ const offsets = useRef({});
187
+ const index = sections.filter((section) => section.title);
188
+ const [indexHeight, setIndexHeight] = useState(0);
189
+ const jump = (event) => {
190
+ // The letters' step as laid out (they grow with the text size)
191
+ const step = indexHeight > 0 && index.length ? indexHeight / index.length : INDEX_STEP;
192
+ const at = Math.floor(event.nativeEvent.locationY / step);
193
+ const section = index[Math.max(0, Math.min(index.length - 1, at))];
194
+ const y = section ? offsets.current[section.key] : undefined;
195
+ if (y != null)
196
+ scroller.current?.scrollTo({ y, animated: false });
197
+ };
198
+ const m = theme.material;
199
+ // iOS: the grouped canvas of a picker sheet, the regions in inset groups on it (the section index stands in the
200
+ // margin beside them); Android: the full-screen dialog's surface, the regions in a plain list across it
201
+ const background = android ? m.surface : theme.colors.groupedBackground;
202
+ const radius = theme.length("--dialog-sheet-radius", 38);
203
+ const margin = theme.length("--mobile-layout-margin", 16);
204
+ const closeSize = theme.length("--dialog-sheet-close-size", 44);
205
+ const height = android ? screen : screen - insets.top - 16;
206
+ const row = (item) => {
207
+ const code = dialCode(item.country);
208
+ const picked = item.country === value;
209
+ return (_jsx(ListItem, { label: flags ? `${countryFlag(item.country)} ${item.name}` : item.name,
210
+ // The code in the secondary label (an Android row's value would take the accent)
211
+ value: android ? undefined : ltr(code), trailing: android ? (_jsxs(View, { style: styles.androidEnd, children: [_jsx(Text, { color: m.onSurfaceVariant, style: styles.androidCode, children: ltr(code) }), picked ? _jsx(CheckMd, { color: m.primary }) : null] })) : picked ? (_jsx(CheckMd, { color: theme.colors.accent })) : undefined, disclosure: false, onPress: () => onSelect(item.country), accessibilityLabel: `${item.name}, ${code.replace("+", "plus ")}${picked ? ", selected" : ""}` }, item.country));
212
+ };
213
+ return (_jsx(Overlay, { open: open, onDismiss: onClose, scrim: android ? ANDROID_DIM.dialog : iosDim(theme), motion: android ? "dialog" : "sheet", children: (progress) => (_jsx(View, { pointerEvents: "box-none", style: styles.bottom, children: _jsxs(Animated.View, { accessibilityViewIsModal: true, "aria-label": title, style: [
214
+ styles.sheet,
215
+ {
216
+ height,
217
+ backgroundColor: background,
218
+ paddingTop: android ? insets.top : 0,
219
+ paddingBottom: keyboard,
220
+ borderTopLeftRadius: android ? 0 : radius,
221
+ borderTopRightRadius: android ? 0 : radius,
222
+ opacity: android || theme.reducedMotion ? progress : undefined,
223
+ transform: android || theme.reducedMotion ? undefined : [{ translateY: progress.interpolate({ inputRange: [0, 1], outputRange: [height, 0] }) }],
224
+ },
225
+ ], children: [android ? (
226
+ // Material's full-screen dialog: Close at the start of a 64dp bar, the title 22sp after it
227
+ _jsxs(View, { style: styles.androidBar, children: [_jsx(NavigationButton, { action: "close", onPress: onClose }), _jsx(Text, { accessibilityRole: "header", numberOfLines: 1, color: m.onSurface, style: styles.androidTitle, children: title })] })) : (
228
+ // The sheet bar: Close at the leading edge, the title centered, 16 under the sheet's top
229
+ _jsxs(View, { style: [styles.iosBar, { paddingTop: theme.length("--dialog-sheet-action-inset-block", 16), paddingBottom: theme.length("--toolbar-padding-bottom", 10), paddingHorizontal: margin }], children: [_jsx(View, { style: { width: closeSize, height: closeSize }, children: _jsx(NavigationButton, { action: "close", onPress: onClose }) }), _jsx(View, { style: [styles.iosHeading, { minHeight: closeSize }], children: _jsx(Text, { accessibilityRole: "header", weight: "semibold", align: "center", numberOfLines: 1, style: { fontSize: theme.length("--toolbar-title-font-size", 17), lineHeight: theme.length("--toolbar-title-line-height", 22) }, children: title }) }), _jsx(View, { style: { width: closeSize } })] })), _jsx(View, { style: { paddingHorizontal: android ? 16 : margin, paddingBottom: 8 }, children: _jsx(Input, { variant: "soft", pill: !android, value: query, onChangeText: setQuery, onClear: () => setQuery(""), placeholder: searchPlaceholder, inputMode: "search", autoCorrect: false, autoCapitalize: "none", returnKeyType: "search", accessibilityLabel: searchPlaceholder, startAdornment: _jsx(Search, {}) }) }), _jsxs(View, { style: styles.grow, children: [_jsxs(ScrollView, { ref: scroller, keyboardShouldPersistTaps: "handled", keyboardDismissMode: "on-drag", contentContainerStyle: { paddingHorizontal: android ? 0 : margin, gap: android ? 0 : 8, paddingBottom: keyboard ? 16 : insets.bottom + 16 }, children: [sections.map((section) => section.items.length ? (_jsx(View, { onLayout: (event) => (offsets.current[section.key] = event.nativeEvent.layout.y), children: _jsx(List, { surface: android ? "plain" : "grouped", header: section.title, children: section.items.map(row) }) }, section.key)) : null), sections.every((section) => !section.items.length) ? (_jsx(Text, { color: "secondary", align: "center", style: styles.none, children: "No results" })) : null] }), !android && !query.trim() ? (_jsx(View, { style: [styles.index, { marginTop: -indexHeight / 2 }], onLayout: (event) => setIndexHeight(event.nativeEvent.layout.height), onStartShouldSetResponder: () => true, onMoveShouldSetResponder: () => true, onResponderGrant: jump, onResponderMove: jump, accessible: false, importantForAccessibility: "no-hide-descendants", children: index.map((section) => (_jsx(Text, { pointerEvents: "none", weight: "semibold", color: theme.colors.accent, align: "center", style: styles.indexLetter, children: section.title }, section.key))) })) : null] })] }) })) }));
230
+ }
231
+ const styles = StyleSheet.create({
232
+ androidStack: { gap: 16 },
233
+ turned: { transform: [{ rotate: "180deg" }] },
234
+ bottom: { flex: 1, justifyContent: "flex-end" },
235
+ sheet: { overflow: "hidden" },
236
+ iosBar: { flexDirection: "row", alignItems: "center" },
237
+ iosHeading: { flex: 1, justifyContent: "center", paddingHorizontal: 8 },
238
+ androidBar: { height: 64, flexDirection: "row", alignItems: "center", paddingHorizontal: 4, gap: 4 },
239
+ androidTitle: { flex: 1, fontSize: 22, lineHeight: 28 },
240
+ grow: { flex: 1 },
241
+ androidEnd: { flexDirection: "row", alignItems: "center", gap: 12 },
242
+ androidCode: { fontSize: 16, lineHeight: 24 },
243
+ none: { marginTop: 32 },
244
+ index: { position: "absolute", end: 0, top: "50%", width: 15, alignItems: "center" },
245
+ indexLetter: { fontSize: 11, lineHeight: INDEX_STEP, width: 15 },
246
+ });
@@ -0,0 +1,249 @@
1
+ // Generated from Intl.DisplayNames("en", { type: "region" }) for every region libphonenumber-js knows: the names where the
2
+ // engine has no Intl.DisplayNames (Hermes). Keep in sync with packages/ui/src/components/PhoneInput/countryNames.ts.
3
+ export const COUNTRY_NAMES = {
4
+ AC: "Ascension Island",
5
+ AD: "Andorra",
6
+ AE: "United Arab Emirates",
7
+ AF: "Afghanistan",
8
+ AG: "Antigua & Barbuda",
9
+ AI: "Anguilla",
10
+ AL: "Albania",
11
+ AM: "Armenia",
12
+ AO: "Angola",
13
+ AR: "Argentina",
14
+ AS: "American Samoa",
15
+ AT: "Austria",
16
+ AU: "Australia",
17
+ AW: "Aruba",
18
+ AX: "Åland Islands",
19
+ AZ: "Azerbaijan",
20
+ BA: "Bosnia & Herzegovina",
21
+ BB: "Barbados",
22
+ BD: "Bangladesh",
23
+ BE: "Belgium",
24
+ BF: "Burkina Faso",
25
+ BG: "Bulgaria",
26
+ BH: "Bahrain",
27
+ BI: "Burundi",
28
+ BJ: "Benin",
29
+ BL: "St. Barthélemy",
30
+ BM: "Bermuda",
31
+ BN: "Brunei",
32
+ BO: "Bolivia",
33
+ BQ: "Caribbean Netherlands",
34
+ BR: "Brazil",
35
+ BS: "Bahamas",
36
+ BT: "Bhutan",
37
+ BW: "Botswana",
38
+ BY: "Belarus",
39
+ BZ: "Belize",
40
+ CA: "Canada",
41
+ CC: "Cocos (Keeling) Islands",
42
+ CD: "Congo - Kinshasa",
43
+ CF: "Central African Republic",
44
+ CG: "Congo - Brazzaville",
45
+ CH: "Switzerland",
46
+ CI: "Côte d’Ivoire",
47
+ CK: "Cook Islands",
48
+ CL: "Chile",
49
+ CM: "Cameroon",
50
+ CN: "China",
51
+ CO: "Colombia",
52
+ CR: "Costa Rica",
53
+ CU: "Cuba",
54
+ CV: "Cape Verde",
55
+ CW: "Curaçao",
56
+ CX: "Christmas Island",
57
+ CY: "Cyprus",
58
+ CZ: "Czechia",
59
+ DE: "Germany",
60
+ DJ: "Djibouti",
61
+ DK: "Denmark",
62
+ DM: "Dominica",
63
+ DO: "Dominican Republic",
64
+ DZ: "Algeria",
65
+ EC: "Ecuador",
66
+ EE: "Estonia",
67
+ EG: "Egypt",
68
+ EH: "Western Sahara",
69
+ ER: "Eritrea",
70
+ ES: "Spain",
71
+ ET: "Ethiopia",
72
+ FI: "Finland",
73
+ FJ: "Fiji",
74
+ FK: "Falkland Islands",
75
+ FM: "Micronesia",
76
+ FO: "Faroe Islands",
77
+ FR: "France",
78
+ GA: "Gabon",
79
+ GB: "United Kingdom",
80
+ GD: "Grenada",
81
+ GE: "Georgia",
82
+ GF: "French Guiana",
83
+ GG: "Guernsey",
84
+ GH: "Ghana",
85
+ GI: "Gibraltar",
86
+ GL: "Greenland",
87
+ GM: "Gambia",
88
+ GN: "Guinea",
89
+ GP: "Guadeloupe",
90
+ GQ: "Equatorial Guinea",
91
+ GR: "Greece",
92
+ GT: "Guatemala",
93
+ GU: "Guam",
94
+ GW: "Guinea-Bissau",
95
+ GY: "Guyana",
96
+ HK: "Hong Kong SAR China",
97
+ HN: "Honduras",
98
+ HR: "Croatia",
99
+ HT: "Haiti",
100
+ HU: "Hungary",
101
+ ID: "Indonesia",
102
+ IE: "Ireland",
103
+ IL: "Israel",
104
+ IM: "Isle of Man",
105
+ IN: "India",
106
+ IO: "British Indian Ocean Territory",
107
+ IQ: "Iraq",
108
+ IR: "Iran",
109
+ IS: "Iceland",
110
+ IT: "Italy",
111
+ JE: "Jersey",
112
+ JM: "Jamaica",
113
+ JO: "Jordan",
114
+ JP: "Japan",
115
+ KE: "Kenya",
116
+ KG: "Kyrgyzstan",
117
+ KH: "Cambodia",
118
+ KI: "Kiribati",
119
+ KM: "Comoros",
120
+ KN: "St. Kitts & Nevis",
121
+ KP: "North Korea",
122
+ KR: "South Korea",
123
+ KW: "Kuwait",
124
+ KY: "Cayman Islands",
125
+ KZ: "Kazakhstan",
126
+ LA: "Laos",
127
+ LB: "Lebanon",
128
+ LC: "St. Lucia",
129
+ LI: "Liechtenstein",
130
+ LK: "Sri Lanka",
131
+ LR: "Liberia",
132
+ LS: "Lesotho",
133
+ LT: "Lithuania",
134
+ LU: "Luxembourg",
135
+ LV: "Latvia",
136
+ LY: "Libya",
137
+ MA: "Morocco",
138
+ MC: "Monaco",
139
+ MD: "Moldova",
140
+ ME: "Montenegro",
141
+ MF: "St. Martin",
142
+ MG: "Madagascar",
143
+ MH: "Marshall Islands",
144
+ MK: "North Macedonia",
145
+ ML: "Mali",
146
+ MM: "Myanmar (Burma)",
147
+ MN: "Mongolia",
148
+ MO: "Macao SAR China",
149
+ MP: "Northern Mariana Islands",
150
+ MQ: "Martinique",
151
+ MR: "Mauritania",
152
+ MS: "Montserrat",
153
+ MT: "Malta",
154
+ MU: "Mauritius",
155
+ MV: "Maldives",
156
+ MW: "Malawi",
157
+ MX: "Mexico",
158
+ MY: "Malaysia",
159
+ MZ: "Mozambique",
160
+ NA: "Namibia",
161
+ NC: "New Caledonia",
162
+ NE: "Niger",
163
+ NF: "Norfolk Island",
164
+ NG: "Nigeria",
165
+ NI: "Nicaragua",
166
+ NL: "Netherlands",
167
+ NO: "Norway",
168
+ NP: "Nepal",
169
+ NR: "Nauru",
170
+ NU: "Niue",
171
+ NZ: "New Zealand",
172
+ OM: "Oman",
173
+ PA: "Panama",
174
+ PE: "Peru",
175
+ PF: "French Polynesia",
176
+ PG: "Papua New Guinea",
177
+ PH: "Philippines",
178
+ PK: "Pakistan",
179
+ PL: "Poland",
180
+ PM: "St. Pierre & Miquelon",
181
+ PR: "Puerto Rico",
182
+ PS: "Palestinian Territories",
183
+ PT: "Portugal",
184
+ PW: "Palau",
185
+ PY: "Paraguay",
186
+ QA: "Qatar",
187
+ RE: "Réunion",
188
+ RO: "Romania",
189
+ RS: "Serbia",
190
+ RU: "Russia",
191
+ RW: "Rwanda",
192
+ SA: "Saudi Arabia",
193
+ SB: "Solomon Islands",
194
+ SC: "Seychelles",
195
+ SD: "Sudan",
196
+ SE: "Sweden",
197
+ SG: "Singapore",
198
+ SH: "St. Helena",
199
+ SI: "Slovenia",
200
+ SJ: "Svalbard & Jan Mayen",
201
+ SK: "Slovakia",
202
+ SL: "Sierra Leone",
203
+ SM: "San Marino",
204
+ SN: "Senegal",
205
+ SO: "Somalia",
206
+ SR: "Suriname",
207
+ SS: "South Sudan",
208
+ ST: "São Tomé & Príncipe",
209
+ SV: "El Salvador",
210
+ SX: "Sint Maarten",
211
+ SY: "Syria",
212
+ SZ: "Eswatini",
213
+ TA: "Tristan da Cunha",
214
+ TC: "Turks & Caicos Islands",
215
+ TD: "Chad",
216
+ TG: "Togo",
217
+ TH: "Thailand",
218
+ TJ: "Tajikistan",
219
+ TK: "Tokelau",
220
+ TL: "Timor-Leste",
221
+ TM: "Turkmenistan",
222
+ TN: "Tunisia",
223
+ TO: "Tonga",
224
+ TR: "Türkiye",
225
+ TT: "Trinidad & Tobago",
226
+ TV: "Tuvalu",
227
+ TW: "Taiwan",
228
+ TZ: "Tanzania",
229
+ UA: "Ukraine",
230
+ UG: "Uganda",
231
+ US: "United States",
232
+ UY: "Uruguay",
233
+ UZ: "Uzbekistan",
234
+ VA: "Vatican City",
235
+ VC: "St. Vincent & Grenadines",
236
+ VE: "Venezuela",
237
+ VG: "British Virgin Islands",
238
+ VI: "U.S. Virgin Islands",
239
+ VN: "Vietnam",
240
+ VU: "Vanuatu",
241
+ WF: "Wallis & Futuna",
242
+ WS: "Samoa",
243
+ XK: "Kosovo",
244
+ YE: "Yemen",
245
+ YT: "Mayotte",
246
+ ZA: "South Africa",
247
+ ZM: "Zambia",
248
+ ZW: "Zimbabwe",
249
+ };
@@ -0,0 +1,181 @@
1
+ // The logic of a phone number field, the same in @plexui/ui and @plexui/react-native (keep the two copies identical:
2
+ // packages/ui/src/components/PhoneInput/phone.ts). libphonenumber-js's `min` metadata (Google's libphonenumber, the
3
+ // lengths and leading digits of every region; ~37 kB gzipped) formats as you type, reads a pasted or autofilled
4
+ // international number, drops the national trunk prefix (the UK's 0) and checks the length of each region's numbers.
5
+ import { AsYouType, getCountries, getCountryCallingCode, parsePhoneNumberFromString, validatePhoneNumberLength, } from "libphonenumber-js/min";
6
+ import metadata from "libphonenumber-js/min/metadata";
7
+ import { COUNTRY_NAMES } from "./countryNames";
8
+ /** Every region with a calling code, as ISO 3166-1 alpha-2. */
9
+ export const ALL_COUNTRIES = getCountries();
10
+ /** The calling code of a region, with its plus: `+44`. */
11
+ export function dialCode(country) {
12
+ return `+${getCountryCallingCode(country)}`;
13
+ }
14
+ /** The regions that share a calling code, its main region first (+1: the US, then Canada and the Caribbean). */
15
+ export function countriesForCode(code) {
16
+ const list = metadata.country_calling_codes[code];
17
+ return (list ?? []);
18
+ }
19
+ /** Whether a string is a region the metadata knows. */
20
+ export function isCountry(value) {
21
+ return typeof value === "string" && ALL_COUNTRIES.includes(value);
22
+ }
23
+ let displayNames = null;
24
+ /** A region's name in the locale (Intl.DisplayNames), in English where the engine has no Intl.DisplayNames. */
25
+ export function countryName(country, locale) {
26
+ const key = locale ?? "";
27
+ if (!displayNames || displayNames.locale !== key) {
28
+ let names = null;
29
+ try {
30
+ const DisplayNames = Intl.DisplayNames;
31
+ names = DisplayNames ? new DisplayNames(locale, { type: "region" }) : null;
32
+ }
33
+ catch {
34
+ names = null;
35
+ }
36
+ displayNames = { locale: key, names };
37
+ }
38
+ const name = displayNames.names?.of(country);
39
+ return name && name !== country ? name : (COUNTRY_NAMES[country] ?? country);
40
+ }
41
+ /** The flag of a region, as its two regional indicator symbols. */
42
+ export function countryFlag(country) {
43
+ return String.fromCodePoint(...[...country.toUpperCase()].map((letter) => 0x1f1e6 + letter.charCodeAt(0) - 65));
44
+ }
45
+ /** The device's region, from the locale the engine runs in (`en-GB` → GB); undefined when the locale names none. */
46
+ export function deviceCountry() {
47
+ try {
48
+ const locale = new Intl.DateTimeFormat().resolvedOptions().locale;
49
+ const region = Intl.Locale
50
+ ? new Intl.Locale(locale).region
51
+ : locale.split(/[-_]/).find((part, index) => index > 0 && /^[A-Z]{2}$/.test(part));
52
+ return isCountry(region) ? region : undefined;
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ /** Folds a name for search: lower case, no accents (`Côte d’Ivoire` → `cote d’ivoire`). */
59
+ export function fold(text) {
60
+ return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
61
+ }
62
+ /** Whether a region answers a search: by its name (any word's start), its ISO code or its calling code (`44`, `+44`). */
63
+ export function matchesCountry(country, name, query) {
64
+ const q = fold(query.trim());
65
+ if (!q)
66
+ return true;
67
+ const digits = q.replace(/^\+/, "");
68
+ if (/^\d+$/.test(digits))
69
+ return String(getCountryCallingCode(country)).startsWith(digits);
70
+ if (q.length === 2 && country.toLowerCase() === q)
71
+ return true;
72
+ const folded = fold(name);
73
+ return folded.startsWith(q) || folded.includes(` ${q}`) || folded.includes(`(${q}`) || folded.includes(`-${q}`);
74
+ }
75
+ /** The characters a phone number may be typed with. */
76
+ const ALLOWED = /[^\d+\s().-]/g;
77
+ /** Whether the text is an international number: a plus, or 00 (the international prefix most regions dial). */
78
+ function international(text) {
79
+ const trimmed = text.replace(/[\s().-]/g, "");
80
+ return trimmed.startsWith("+") || trimmed.startsWith("00");
81
+ }
82
+ /** The digits of a text, in order. */
83
+ export function digitsOf(text) {
84
+ return text.replace(/\D/g, "");
85
+ }
86
+ /** The number's details for its national digits in a region; `format` groups the digits as the region writes them. */
87
+ export function readNational(digits, country, format) {
88
+ if (!digits)
89
+ return { value: "", country, text: "", possible: false, valid: false };
90
+ const typer = new AsYouType(country);
91
+ const formatted = typer.input(digits);
92
+ const number = typer.getNumber();
93
+ const value = typer.getNumberValue() ?? `${dialCode(country)}${digits}`;
94
+ return {
95
+ value,
96
+ country,
97
+ text: format ? formatted : digits,
98
+ possible: number?.isPossible() ?? false,
99
+ valid: number?.isValid() ?? false,
100
+ };
101
+ }
102
+ /** Whether national digits are longer than any number of the region (the field takes no more). */
103
+ export function tooLong(digits, country) {
104
+ if (!digits)
105
+ return false;
106
+ const value = new AsYouType(country);
107
+ value.input(digits);
108
+ return tooLongValue(value.getNumberValue() ?? "");
109
+ }
110
+ /** Whether a value in E.164 is longer than any number of its region. */
111
+ export function tooLongValue(value) {
112
+ return value.length > 2 && validatePhoneNumberLength(value) === "TOO_LONG";
113
+ }
114
+ /** The calling code a `+digits` text starts with (calling codes are prefix-free), and the digits after it. */
115
+ function splitCode(digits) {
116
+ for (let length = 1; length <= 3 && length <= digits.length; length++) {
117
+ const code = digits.slice(0, length);
118
+ if (countriesForCode(code).length)
119
+ return { code, rest: digits.slice(length) };
120
+ }
121
+ return null;
122
+ }
123
+ /** The region of a calling code: the picked one when it shares the code, else the code's main region. */
124
+ function regionFor(code, country, named) {
125
+ const shared = countriesForCode(code);
126
+ return shared.includes(country) ? country : (named ?? shared[0] ?? country);
127
+ }
128
+ /**
129
+ * What the number field holds after a change: a typed national number in the picked region, or a pasted or autofilled
130
+ * international one (`+44 7700 900123`, `0044…`), whose code picks the region (the picked region stays when it shares
131
+ * the code and the number fits it: +1 in Canada) and is dropped from the field.
132
+ */
133
+ export function readInput(text, country, format) {
134
+ const clean = text.replace(ALLOWED, "");
135
+ if (international(clean)) {
136
+ const plus = clean.replace(/[\s().-]/g, "").replace(/^00/, "+");
137
+ const parsed = parsePhoneNumberFromString(plus);
138
+ if (parsed) {
139
+ const code = String(parsed.countryCallingCode);
140
+ const national = String(parsed.nationalNumber);
141
+ const fits = countriesForCode(code).includes(country) && parsePhoneNumberFromString(national, country)?.isPossible();
142
+ // The picked region stays where it shares the code and the number fits it (+1 in Canada); else the number's own
143
+ const region = fits ? country : (parsed.country ?? countriesForCode(code)[0] ?? country);
144
+ // The field holds the number as the region dials it, with its trunk prefix (07400 123456, 8 812 123-45-67): read
145
+ // again it gives the same number (Russia's 812 alone would lose its 8 as a trunk prefix)
146
+ const dialled = parsed.formatNational();
147
+ return { value: parsed.number, country: region, text: format ? dialled : digitsOf(dialled), possible: parsed.isPossible(), valid: parsed.isValid() };
148
+ }
149
+ // Too short to parse: a known code with digits after it (+447) is that code's region and those digits; a code
150
+ // still being typed (+4) stays as it is
151
+ const split = splitCode(digitsOf(plus));
152
+ if (split && split.rest) {
153
+ const region = regionFor(split.code, country);
154
+ return { value: `+${split.code}${split.rest}`, country: region, text: split.rest, possible: false, valid: false };
155
+ }
156
+ return { value: "", country, text: clean, possible: false, valid: false };
157
+ }
158
+ return readNational(digitsOf(clean), country, format);
159
+ }
160
+ /** The field's details for a value in E.164 (or the digits so far after a code), read in a region. */
161
+ export function readValue(value, country, format) {
162
+ if (!value)
163
+ return { value: "", country, text: "", possible: false, valid: false };
164
+ return readInput(value.startsWith("+") ? value : `+${value}`, country, format);
165
+ }
166
+ /** The caret's place after `count` digits in a formatted text (just after the count-th digit). */
167
+ export function caretAfterDigits(text, count) {
168
+ if (count <= 0) {
169
+ const first = text.search(/\d/);
170
+ return first < 0 ? text.length : first;
171
+ }
172
+ let seen = 0;
173
+ for (let index = 0; index < text.length; index++) {
174
+ if (/\d/.test(text[index])) {
175
+ seen++;
176
+ if (seen === count)
177
+ return index + 1;
178
+ }
179
+ }
180
+ return text.length;
181
+ }