nuxt-phone-number 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adama Sambe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # nuxt-phone-number
2
+
3
+ `nuxt-phone-number` is a Nuxt-first phone input module.
4
+
5
+ It provides:
6
+
7
+ - auto-registered `<UPhoneInput />`
8
+ - `usePhone()` composable
9
+ - global config via `nuxt.config.ts`
10
+ - live formatting and validation with `libphonenumber-js`
11
+ - configurable UI props like `variant`, `rounded` and `size`
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install nuxt-phone-number libphonenumber-js
17
+ ```
18
+
19
+ ```ts
20
+ export default defineNuxtConfig({
21
+ modules: ["nuxt-phone-number"],
22
+
23
+ phoneInput: {
24
+ defaultCountry: "SN",
25
+ preferredCountries: ["SN", "FR"],
26
+ format: "international",
27
+ },
28
+ });
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ```vue
34
+ <script setup lang="ts">
35
+ const phone = ref("");
36
+ </script>
37
+
38
+ <template>
39
+ <UPhoneInput
40
+ v-model="phone"
41
+ variant="outline"
42
+ rounded="lg"
43
+ />
44
+ </template>
45
+ ```
46
+
47
+ ## usePhone
48
+
49
+ ```vue
50
+ <script setup lang="ts">
51
+ const { formatPhone, validatePhone } = usePhone();
52
+
53
+ const formatted = formatPhone("+221771234567");
54
+ const isValid = validatePhone("+221771234567");
55
+ </script>
56
+ ```
@@ -0,0 +1,5 @@
1
+ module.exports = function(...args) {
2
+ return import('./module.mjs').then(m => m.default.call(this, ...args))
3
+ }
4
+ const _meta = module.exports.meta = require('./module.json')
5
+ module.exports.getMeta = () => Promise.resolve(_meta)
@@ -0,0 +1,7 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+ import { ModuleOptions } from '../dist/runtime/types/index.js';
3
+ export { ModuleOptions, PhoneFormat, PhoneInputData, PhoneInputUiOptions } from '../dist/runtime/types/index.js';
4
+
5
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
6
+
7
+ export { _default as default };
@@ -0,0 +1,7 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+ import { ModuleOptions } from '../dist/runtime/types/index.js';
3
+ export { ModuleOptions, PhoneFormat, PhoneInputData, PhoneInputUiOptions } from '../dist/runtime/types/index.js';
4
+
5
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
6
+
7
+ export { _default as default };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "nuxt-phone-number",
3
+ "configKey": "phoneInput",
4
+ "compatibility": {
5
+ "nuxt": "^3.0.0 || ^4.0.0"
6
+ },
7
+ "version": "0.1.0",
8
+ "builder": {
9
+ "@nuxt/module-builder": "0.8.4",
10
+ "unbuild": "2.0.0"
11
+ }
12
+ }
@@ -0,0 +1,50 @@
1
+ import { defineNuxtModule, createResolver, addPlugin, addImports, addComponent } from '@nuxt/kit';
2
+
3
+ const module = defineNuxtModule({
4
+ meta: {
5
+ name: "nuxt-phone-number",
6
+ configKey: "phoneInput",
7
+ compatibility: {
8
+ nuxt: "^3.0.0 || ^4.0.0"
9
+ }
10
+ },
11
+ defaults: {
12
+ defaultCountry: "SN",
13
+ preferredCountries: ["SN", "FR"],
14
+ onlyCountries: [],
15
+ ignoredCountries: [],
16
+ useBrowserLocale: true,
17
+ format: "international",
18
+ ui: {
19
+ variant: "outline",
20
+ size: "md",
21
+ rounded: "lg"
22
+ }
23
+ },
24
+ setup(options, nuxt) {
25
+ const resolver = createResolver(import.meta.url);
26
+ nuxt.options.runtimeConfig.public.phoneInput = {
27
+ defaultCountry: options.defaultCountry,
28
+ preferredCountries: options.preferredCountries,
29
+ onlyCountries: options.onlyCountries,
30
+ ignoredCountries: options.ignoredCountries,
31
+ useBrowserLocale: options.useBrowserLocale,
32
+ format: options.format,
33
+ ui: options.ui
34
+ };
35
+ addPlugin(resolver.resolve("./runtime/plugins/phone"));
36
+ addImports([
37
+ {
38
+ name: "usePhone",
39
+ as: "usePhone",
40
+ from: resolver.resolve("./runtime/composables/usePhone")
41
+ }
42
+ ]);
43
+ addComponent({
44
+ name: "UPhoneInput",
45
+ filePath: resolver.resolve("./runtime/components/UPhoneInput.vue")
46
+ });
47
+ }
48
+ });
49
+
50
+ export { module as default };
@@ -0,0 +1,514 @@
1
+ <template>
2
+ <div class="npi-root" ref="triggerRef" :style="cssVars">
3
+ <div
4
+ class="npi-control"
5
+ :class="[
6
+ roundedClass,
7
+ sizeClass,
8
+ variantClass,
9
+ hasError ? 'npi-control-error' : isFocused || isOpen ? 'npi-control-active' : 'npi-control-idle',
10
+ props.disabled ? 'npi-control-disabled' : '',
11
+ ]"
12
+ >
13
+ <button
14
+ type="button"
15
+ class="npi-country-button"
16
+ :class="props.disabled ? 'npi-country-button-disabled' : ''"
17
+ :disabled="props.disabled"
18
+ @click="toggleDropdown"
19
+ @keydown.escape="closeDropdown"
20
+ @keydown.enter.prevent="toggleDropdown"
21
+ @keydown.space.prevent="toggleDropdown"
22
+ >
23
+ <span class="npi-flag" role="img" :aria-label="selectedCountry?.name">
24
+ {{ selectedCountry ? countryFlag(selectedCountry.code) : "🌍" }}
25
+ </span>
26
+ <span class="npi-dial-code">+{{ selectedCountry?.dial }}</span>
27
+ <svg
28
+ width="14"
29
+ height="14"
30
+ class="npi-chevron"
31
+ :class="isOpen ? 'npi-chevron-open' : ''"
32
+ viewBox="0 0 20 20"
33
+ fill="currentColor"
34
+ >
35
+ <path
36
+ fill-rule="evenodd"
37
+ d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
38
+ clip-rule="evenodd"
39
+ />
40
+ </svg>
41
+ </button>
42
+
43
+ <div class="npi-input-wrap">
44
+ <input
45
+ ref="inputRef"
46
+ v-model="displayValue"
47
+ type="tel"
48
+ inputmode="tel"
49
+ class="npi-input"
50
+ :placeholder="currentPlaceholder"
51
+ :disabled="props.disabled"
52
+ :aria-invalid="hasError"
53
+ autocomplete="tel"
54
+ @input="onInput"
55
+ @focus="isFocused = true"
56
+ @blur="onBlur"
57
+ @keydown.escape="closeDropdown"
58
+ />
59
+ <span
60
+ v-if="displayValue.replace(/\D/g, '').length >= 7 && isValid"
61
+ class="npi-check"
62
+ >
63
+ <svg width="16" height="16" viewBox="0 0 20 20" fill="currentColor">
64
+ <path
65
+ fill-rule="evenodd"
66
+ d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
67
+ clip-rule="evenodd"
68
+ />
69
+ </svg>
70
+ </span>
71
+ </div>
72
+ </div>
73
+
74
+ <p v-if="hasError && errorMessage" class="npi-error">
75
+ {{ errorMessage }}
76
+ </p>
77
+
78
+ <Transition
79
+ enter-active-class="npi-transition-enter-active"
80
+ enter-from-class="npi-transition-enter-from"
81
+ enter-to-class="npi-transition-enter-to"
82
+ leave-active-class="npi-transition-leave-active"
83
+ leave-from-class="npi-transition-leave-from"
84
+ leave-to-class="npi-transition-leave-to"
85
+ >
86
+ <div v-if="isOpen" ref="dropdownRef" class="npi-dropdown">
87
+ <div class="npi-search-wrap">
88
+ <div class="npi-search-box">
89
+ <svg
90
+ width="14"
91
+ height="14"
92
+ class="npi-search-icon"
93
+ fill="none"
94
+ viewBox="0 0 24 24"
95
+ stroke="currentColor"
96
+ stroke-width="2"
97
+ >
98
+ <path
99
+ stroke-linecap="round"
100
+ stroke-linejoin="round"
101
+ d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
102
+ />
103
+ </svg>
104
+ <input
105
+ ref="searchRef"
106
+ v-model="searchQuery"
107
+ type="text"
108
+ class="npi-search-input"
109
+ :placeholder="searchPlaceholder"
110
+ @keydown.escape="closeDropdown"
111
+ @keydown.enter.prevent="selectFirstResult"
112
+ />
113
+ </div>
114
+ </div>
115
+
116
+ <ul class="npi-list" role="listbox">
117
+ <template v-if="!searchQuery && preferredCountriesList.length">
118
+ <li
119
+ v-for="country in preferredCountriesList"
120
+ :key="`pref-${country.code}`"
121
+ class="npi-item"
122
+ :class="selectedCountry?.code === country.code ? 'npi-item-selected' : 'npi-item-idle'"
123
+ role="option"
124
+ :aria-selected="selectedCountry?.code === country.code"
125
+ @click="selectCountry(country)"
126
+ >
127
+ <span class="npi-item-flag">{{ countryFlag(country.code) }}</span>
128
+ <span class="npi-item-name">{{ country.name }}</span>
129
+ <span class="npi-item-dial">+{{ country.dial }}</span>
130
+ </li>
131
+ <li class="npi-divider" aria-hidden="true" />
132
+ </template>
133
+
134
+ <li
135
+ v-for="country in filteredCountries"
136
+ :key="country.code"
137
+ class="npi-item"
138
+ :class="selectedCountry?.code === country.code ? 'npi-item-selected' : 'npi-item-idle'"
139
+ role="option"
140
+ :aria-selected="selectedCountry?.code === country.code"
141
+ @click="selectCountry(country)"
142
+ >
143
+ <span class="npi-item-flag">{{ countryFlag(country.code) }}</span>
144
+ <span class="npi-item-name">{{ country.name }}</span>
145
+ <span class="npi-item-dial">+{{ country.dial }}</span>
146
+ </li>
147
+
148
+ <li v-if="filteredCountries.length === 0" class="npi-empty">
149
+ {{ noResultsText }}
150
+ </li>
151
+ </ul>
152
+ </div>
153
+ </Transition>
154
+ </div>
155
+ </template>
156
+
157
+ <script setup lang="ts">
158
+ import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
159
+ import { useRuntimeConfig } from "#imports";
160
+ import {
161
+ AsYouType,
162
+ getCountries,
163
+ getCountryCallingCode,
164
+ type CountryCode,
165
+ } from "libphonenumber-js";
166
+ import { parsePhoneNumberFromString } from "libphonenumber-js/max";
167
+ import type { ModuleOptions, PhoneFormat, PhoneInputData, PhoneInputUiOptions } from "../types";
168
+
169
+ interface Country {
170
+ code: CountryCode;
171
+ name: string;
172
+ dial: string;
173
+ }
174
+
175
+ const defaults = useRuntimeConfig().public.phoneInput as Required<ModuleOptions>;
176
+
177
+ const props = withDefaults(
178
+ defineProps<{
179
+ modelValue?: string;
180
+ countryCode?: CountryCode | string;
181
+ defaultCountry?: string;
182
+ preferredCountries?: string[];
183
+ onlyCountries?: string[];
184
+ ignoredCountries?: string[];
185
+ useBrowserLocale?: boolean;
186
+ placeholder?: string;
187
+ disabled?: boolean;
188
+ error?: string | boolean;
189
+ locale?: string;
190
+ searchPlaceholder?: string;
191
+ noResultsText?: string;
192
+ invalidMessage?: string;
193
+ format?: PhoneFormat;
194
+ variant?: PhoneInputUiOptions["variant"];
195
+ size?: PhoneInputUiOptions["size"];
196
+ rounded?: PhoneInputUiOptions["rounded"];
197
+ }>(),
198
+ {
199
+ modelValue: "",
200
+ preferredCountries: () => [],
201
+ onlyCountries: () => [],
202
+ ignoredCountries: () => [],
203
+ disabled: false,
204
+ locale: "fr",
205
+ },
206
+ );
207
+
208
+ const emit = defineEmits<{
209
+ "update:modelValue": [value: string];
210
+ "update:countryCode": [code: CountryCode];
211
+ data: [data: PhoneInputData];
212
+ }>();
213
+
214
+ const resolvedVariant = computed(() => props.variant ?? defaults.ui.variant ?? "outline");
215
+ const resolvedSize = computed(() => props.size ?? defaults.ui.size ?? "md");
216
+ const resolvedRounded = computed(() => props.rounded ?? defaults.ui.rounded ?? "lg");
217
+ const resolvedFormat = computed(() => props.format ?? defaults.format ?? "international");
218
+ const resolvedPreferredCountries = computed(
219
+ () => (props.preferredCountries.length ? props.preferredCountries : defaults.preferredCountries) ?? [],
220
+ );
221
+ const resolvedOnlyCountries = computed(
222
+ () => (props.onlyCountries.length ? props.onlyCountries : defaults.onlyCountries) ?? [],
223
+ );
224
+ const resolvedIgnoredCountries = computed(
225
+ () => (props.ignoredCountries.length ? props.ignoredCountries : defaults.ignoredCountries) ?? [],
226
+ );
227
+ const resolvedDefaultCountry = computed(
228
+ () => props.defaultCountry ?? defaults.defaultCountry ?? "SN",
229
+ );
230
+ const resolvedUseBrowserLocale = computed(
231
+ () => props.useBrowserLocale ?? defaults.useBrowserLocale ?? true,
232
+ );
233
+ const searchPlaceholder = computed(() => props.searchPlaceholder ?? "Search country...");
234
+ const noResultsText = computed(() => props.noResultsText ?? "No country found");
235
+ const invalidMessage = computed(() => props.invalidMessage ?? "Invalid phone number");
236
+
237
+ const roundedClass = computed(() => `npi-rounded-${resolvedRounded.value}`);
238
+ const sizeClass = computed(() => `npi-size-${resolvedSize.value}`);
239
+ const variantClass = computed(() => `npi-variant-${resolvedVariant.value}`);
240
+ const cssVars = computed(() => ({}));
241
+ const displayNames = computed(
242
+ () => new Intl.DisplayNames([props.locale || "fr"], { type: "region" }),
243
+ );
244
+
245
+ const allCountries = computed<Country[]>(() => {
246
+ let codes = getCountries() as CountryCode[];
247
+
248
+ if (resolvedOnlyCountries.value.length) {
249
+ codes = codes.filter((code) => resolvedOnlyCountries.value.includes(code));
250
+ }
251
+ if (resolvedIgnoredCountries.value.length) {
252
+ codes = codes.filter((code) => !resolvedIgnoredCountries.value.includes(code));
253
+ }
254
+
255
+ return codes
256
+ .map((code) => ({
257
+ code,
258
+ name: displayNames.value.of(code) ?? code,
259
+ dial: getCountryCallingCode(code),
260
+ }))
261
+ .sort((a, b) => a.name.localeCompare(b.name, props.locale || "fr"));
262
+ });
263
+
264
+ const preferredCountriesList = computed<Country[]>(
265
+ () =>
266
+ resolvedPreferredCountries.value
267
+ .map((code) => allCountries.value.find((country) => country.code === code))
268
+ .filter(Boolean) as Country[],
269
+ );
270
+
271
+ const selectedCountry = ref<Country | null>(null);
272
+ const displayValue = ref("");
273
+ const isOpen = ref(false);
274
+ const isFocused = ref(false);
275
+ const searchQuery = ref("");
276
+ const isValid = ref(false);
277
+
278
+ const searchRef = ref<HTMLInputElement | null>(null);
279
+ const inputRef = ref<HTMLInputElement | null>(null);
280
+ const triggerRef = ref<HTMLElement | null>(null);
281
+ const dropdownRef = ref<HTMLElement | null>(null);
282
+
283
+ const filteredCountries = computed<Country[]>(() => {
284
+ if (!searchQuery.value) return allCountries.value;
285
+ const q = searchQuery.value.toLowerCase();
286
+ return allCountries.value.filter(
287
+ (country) =>
288
+ country.name.toLowerCase().includes(q) ||
289
+ country.dial.includes(q) ||
290
+ country.code.toLowerCase().includes(q),
291
+ );
292
+ });
293
+
294
+ const currentPlaceholder = computed(() => props.placeholder || "Phone number");
295
+ const hasError = computed(
296
+ () =>
297
+ !!props.error ||
298
+ (displayValue.value.length > 3 && !isValid.value && !isFocused.value),
299
+ );
300
+ const errorMessage = computed(() => {
301
+ if (typeof props.error === "string") return props.error;
302
+ if (displayValue.value.length > 3 && !isValid.value) return invalidMessage.value;
303
+ return "";
304
+ });
305
+
306
+ function countryFlag(code: string): string {
307
+ return code
308
+ .toUpperCase()
309
+ .split("")
310
+ .map((char) => String.fromCodePoint(0x1f1e6 - 65 + char.charCodeAt(0)))
311
+ .join("");
312
+ }
313
+
314
+ function formatOutput(e164: string | null, nationalFallback: string): string {
315
+ if (!e164) return nationalFallback;
316
+ try {
317
+ const parsed = parsePhoneNumberFromString(e164);
318
+ if (!parsed) return nationalFallback;
319
+ if (resolvedFormat.value === "e164") return parsed.number;
320
+ if (resolvedFormat.value === "national") return parsed.formatNational();
321
+ return parsed.formatInternational();
322
+ } catch {
323
+ return nationalFallback;
324
+ }
325
+ }
326
+
327
+ function selectCountry(country: Country) {
328
+ selectedCountry.value = country;
329
+ closeDropdown();
330
+ if (displayValue.value) {
331
+ const formatter = new AsYouType(country.code);
332
+ displayValue.value = formatter.input(displayValue.value.replace(/\D/g, ""));
333
+ }
334
+ emit("update:countryCode", country.code);
335
+ nextTick(() => inputRef.value?.focus());
336
+ emitData();
337
+ }
338
+
339
+ function onInput() {
340
+ if (!selectedCountry.value) return;
341
+
342
+ if (displayValue.value.startsWith("+")) {
343
+ const parsed = parsePhoneNumberFromString(displayValue.value);
344
+ if (parsed?.country && parsed.isValid()) {
345
+ const found = allCountries.value.find((country) => country.code === parsed.country);
346
+ if (found) selectedCountry.value = found;
347
+ displayValue.value = parsed.formatNational();
348
+ isValid.value = true;
349
+ emitData();
350
+ return;
351
+ }
352
+ displayValue.value = displayValue.value.replace(/^\+/, "");
353
+ }
354
+
355
+ let raw = displayValue.value.replace(/[^\d]/g, "");
356
+ const dial = selectedCountry.value.dial;
357
+ if (raw.startsWith(dial) && raw.length > dial.length) {
358
+ raw = raw.slice(dial.length);
359
+ }
360
+
361
+ const formatter = new AsYouType(selectedCountry.value.code);
362
+ displayValue.value = formatter.input(raw) || raw;
363
+
364
+ try {
365
+ const parsed = parsePhoneNumberFromString(
366
+ `+${dial}${raw}`,
367
+ selectedCountry.value.code,
368
+ );
369
+ isValid.value = parsed?.isValid() ?? false;
370
+ } catch {
371
+ isValid.value = false;
372
+ }
373
+
374
+ emitData();
375
+ }
376
+
377
+ function onBlur() {
378
+ isFocused.value = false;
379
+ emitData();
380
+ }
381
+
382
+ function emitData() {
383
+ if (!selectedCountry.value) return;
384
+
385
+ const raw = displayValue.value.replace(/[^\d]/g, "");
386
+ const e164 = raw ? `+${selectedCountry.value.dial}${raw}` : null;
387
+ let valid = false;
388
+
389
+ if (e164) {
390
+ try {
391
+ const parsed = parsePhoneNumberFromString(e164, selectedCountry.value.code);
392
+ valid = parsed?.isValid() ?? false;
393
+ } catch {
394
+ valid = false;
395
+ }
396
+ }
397
+
398
+ isValid.value = valid;
399
+ emit("update:modelValue", formatOutput(e164, displayValue.value));
400
+ emit("data", {
401
+ e164,
402
+ countryCode: selectedCountry.value.code,
403
+ formatted: formatOutput(e164, displayValue.value),
404
+ isValid: valid,
405
+ });
406
+ }
407
+
408
+ function toggleDropdown() {
409
+ if (isOpen.value) {
410
+ closeDropdown();
411
+ return;
412
+ }
413
+ isOpen.value = true;
414
+ searchQuery.value = "";
415
+ nextTick(() => searchRef.value?.focus());
416
+ }
417
+
418
+ function closeDropdown() {
419
+ isOpen.value = false;
420
+ searchQuery.value = "";
421
+ }
422
+
423
+ function selectFirstResult() {
424
+ const firstCountry = filteredCountries.value[0];
425
+ if (firstCountry) selectCountry(firstCountry);
426
+ }
427
+
428
+ function onClickOutside(event: MouseEvent) {
429
+ if (
430
+ !triggerRef.value?.contains(event.target as Node) &&
431
+ !dropdownRef.value?.contains(event.target as Node)
432
+ ) {
433
+ closeDropdown();
434
+ }
435
+ }
436
+
437
+ onMounted(() => {
438
+ document.addEventListener("click", onClickOutside);
439
+
440
+ if (props.countryCode) {
441
+ const found = allCountries.value.find((country) => country.code === props.countryCode);
442
+ if (found) {
443
+ selectedCountry.value = found;
444
+ return;
445
+ }
446
+ }
447
+
448
+ const initialCountry = String(resolvedDefaultCountry.value).toUpperCase();
449
+ const foundDefault = allCountries.value.find((country) => country.code === initialCountry);
450
+ if (foundDefault) {
451
+ selectedCountry.value = foundDefault;
452
+ return;
453
+ }
454
+
455
+ if (resolvedUseBrowserLocale.value && typeof navigator !== "undefined") {
456
+ const region = (navigator.language || navigator.languages?.[0] || "")
457
+ .split("-")[1]
458
+ ?.toUpperCase();
459
+ if (region) {
460
+ const found = allCountries.value.find((country) => country.code === region);
461
+ if (found) {
462
+ selectedCountry.value = found;
463
+ return;
464
+ }
465
+ }
466
+ }
467
+
468
+ if (resolvedPreferredCountries.value.length) {
469
+ const found = allCountries.value.find(
470
+ (country) => country.code === resolvedPreferredCountries.value[0],
471
+ );
472
+ if (found) {
473
+ selectedCountry.value = found;
474
+ return;
475
+ }
476
+ }
477
+
478
+ selectedCountry.value =
479
+ allCountries.value.find((country) => country.code === "SN") ||
480
+ allCountries.value[0] ||
481
+ null;
482
+ });
483
+
484
+ onUnmounted(() => {
485
+ document.removeEventListener("click", onClickOutside);
486
+ });
487
+
488
+ watch(
489
+ () => props.modelValue,
490
+ (value) => {
491
+ if (!value || value === displayValue.value) return;
492
+ if (value.startsWith("+")) {
493
+ const parsed = parsePhoneNumberFromString(value);
494
+ if (parsed?.country) {
495
+ const found = allCountries.value.find((country) => country.code === parsed.country);
496
+ if (found) selectedCountry.value = found;
497
+ }
498
+ displayValue.value =
499
+ resolvedFormat.value === "national"
500
+ ? (parsed?.formatNational() ?? value)
501
+ : resolvedFormat.value === "international"
502
+ ? (parsed?.formatInternational() ?? value)
503
+ : value;
504
+ return;
505
+ }
506
+ displayValue.value = value;
507
+ },
508
+ { immediate: true },
509
+ );
510
+ </script>
511
+
512
+ <style scoped>
513
+ .npi-root{position:relative;width:100%;--npi-border:#d1d5db;--npi-border-hover:#9ca3af;--npi-border-active:#0f172a;--npi-border-error:#ef4444;--npi-ring:rgba(148,163,184,.2);--npi-ring-error:rgba(239,68,68,.2);--npi-bg:#fff;--npi-bg-soft:#f8fafc;--npi-bg-hover:#f1f5f9;--npi-bg-selected:#e2e8f0;--npi-text:#0f172a;--npi-muted:#64748b;--npi-placeholder:#94a3b8;--npi-success:#16a34a;--npi-error:#dc2626;font-family:Inter,ui-sans-serif,system-ui,sans-serif}.npi-control{background:var(--npi-bg);border:1px solid var(--npi-border);display:flex;overflow:hidden;transition:border-color .15s ease,box-shadow .15s ease,background-color .15s ease;width:100%}.npi-control-idle:hover{border-color:var(--npi-border-hover)}.npi-control-active{border-color:var(--npi-border-active);box-shadow:0 0 0 4px var(--npi-ring)}.npi-control-error{border-color:var(--npi-border-error);box-shadow:0 0 0 4px var(--npi-ring-error)}.npi-control-disabled{background:var(--npi-bg-soft);opacity:.55}.npi-variant-outline{background:var(--npi-bg)}.npi-variant-soft{background:var(--npi-bg-soft)}.npi-variant-ghost{background:transparent}.npi-rounded-sm{border-radius:.375rem}.npi-rounded-md{border-radius:.5rem}.npi-rounded-lg{border-radius:.75rem}.npi-rounded-xl{border-radius:1rem}.npi-rounded-full{border-radius:9999px}.npi-size-sm .npi-country-button,.npi-size-sm .npi-input{font-size:.875rem;padding:.55rem .75rem}.npi-size-md .npi-country-button,.npi-size-md .npi-input{font-size:.95rem;padding:.75rem .9rem}.npi-size-lg .npi-country-button,.npi-size-lg .npi-input{font-size:1rem;padding:.95rem 1rem}.npi-country-button{align-items:center;background:transparent;border:0;border-right:1px solid var(--npi-border);cursor:pointer;display:flex;flex-shrink:0;gap:.45rem}.npi-country-button:hover{background:var(--npi-bg-hover)}.npi-country-button-disabled{cursor:not-allowed}.npi-flag{font-size:1.1rem;line-height:1}.npi-chevron,.npi-dial-code,.npi-item-dial,.npi-search-icon{color:var(--npi-muted)}.npi-chevron{transition:transform .2s ease}.npi-chevron-open{transform:rotate(180deg)}.npi-input-wrap{align-items:center;display:flex;flex:1 1 0%;position:relative}.npi-input,.npi-search-input{background:transparent;border:0;color:var(--npi-text);outline:none;width:100%}.npi-input::-moz-placeholder,.npi-search-input::-moz-placeholder{color:var(--npi-placeholder)}.npi-input::placeholder,.npi-search-input::placeholder{color:var(--npi-placeholder)}.npi-check{color:var(--npi-success);padding-right:.9rem}.npi-error{color:var(--npi-error);font-size:.875rem;margin-top:.5rem}.npi-dropdown{background:var(--npi-bg);border:1px solid var(--npi-border);border-radius:1rem;box-shadow:0 18px 40px rgba(15,23,42,.12);left:0;overflow:hidden;position:absolute;top:calc(100% + .4rem);width:18rem;z-index:50}.npi-search-wrap{border-bottom:1px solid #e5e7eb;padding:.625rem}.npi-search-box{align-items:center;background:var(--npi-bg-soft);border:1px solid var(--npi-border);border-radius:.75rem;display:flex;gap:.5rem;padding:.5rem .75rem}.npi-list{max-height:15rem;overflow-y:auto;padding:.375rem}.npi-item{align-items:center;border-radius:.75rem;cursor:pointer;display:flex;font-size:.875rem;gap:.625rem;padding:.625rem}.npi-item-idle{color:var(--npi-text)}.npi-item-idle:hover{background:var(--npi-bg-hover)}.npi-item-selected{background:var(--npi-bg-selected);color:var(--npi-text);font-weight:600}.npi-item-flag{flex-shrink:0;font-size:1.125rem}.npi-item-name{flex:1 1 0%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.npi-divider{background:#e5e7eb;height:1px;margin:.25rem .5rem}.npi-empty{color:var(--npi-muted);font-size:.875rem;padding:1rem;text-align:center}.npi-transition-enter-active{transition:all .15s ease-out}.npi-transition-enter-from{opacity:0;transform:translateY(-.25rem) scale(.96)}.npi-transition-enter-to{opacity:1;transform:translateY(0) scale(1)}.npi-transition-leave-active{transition:all .1s ease-in}.npi-transition-leave-from{opacity:1}.npi-transition-leave-to{opacity:0;transform:translateY(-.25rem) scale(.96)}
514
+ </style>
@@ -0,0 +1,2 @@
1
+ import type { PhoneHelpers } from "../types/index.js";
2
+ export declare function usePhone(): PhoneHelpers;
@@ -0,0 +1,5 @@
1
+ import { useNuxtApp } from "#imports";
2
+ export function usePhone() {
3
+ const nuxtApp = useNuxtApp();
4
+ return nuxtApp.$phone;
5
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,76 @@
1
+ import { parsePhoneNumberFromString } from "libphonenumber-js/max";
2
+ import { defineNuxtPlugin, useRuntimeConfig } from "#imports";
3
+ function normalizeCountryCode(code) {
4
+ if (!code) return void 0;
5
+ return String(code).toUpperCase();
6
+ }
7
+ function parsePhone(phone, countryCode) {
8
+ const normalizedCountry = normalizeCountryCode(countryCode);
9
+ try {
10
+ const parsed = parsePhoneNumberFromString(phone, normalizedCountry);
11
+ if (!parsed) {
12
+ return {
13
+ e164: null,
14
+ countryCode: normalizedCountry ?? null,
15
+ formatted: phone,
16
+ isValid: false
17
+ };
18
+ }
19
+ return {
20
+ e164: parsed.number ?? null,
21
+ countryCode: parsed.country ?? normalizedCountry ?? null,
22
+ formatted: parsed.formatInternational(),
23
+ isValid: parsed.isValid()
24
+ };
25
+ } catch {
26
+ return {
27
+ e164: null,
28
+ countryCode: normalizedCountry ?? null,
29
+ formatted: phone,
30
+ isValid: false
31
+ };
32
+ }
33
+ }
34
+ export default defineNuxtPlugin(() => {
35
+ const config = useRuntimeConfig();
36
+ const defaults = {
37
+ defaultCountry: config.public.phoneInput?.defaultCountry ?? "SN",
38
+ preferredCountries: config.public.phoneInput?.preferredCountries ?? ["SN", "FR"],
39
+ onlyCountries: config.public.phoneInput?.onlyCountries ?? [],
40
+ ignoredCountries: config.public.phoneInput?.ignoredCountries ?? [],
41
+ useBrowserLocale: config.public.phoneInput?.useBrowserLocale ?? true,
42
+ format: config.public.phoneInput?.format ?? "international",
43
+ ui: {
44
+ variant: config.public.phoneInput?.ui?.variant ?? "outline",
45
+ size: config.public.phoneInput?.ui?.size ?? "md",
46
+ rounded: config.public.phoneInput?.ui?.rounded ?? "lg"
47
+ }
48
+ };
49
+ const phoneHelpers = {
50
+ formatPhone(phone, countryCode, format = defaults.format) {
51
+ const parsed = parsePhone(phone, countryCode);
52
+ if (!parsed.e164) return phone;
53
+ if (format === "e164") return parsed.e164;
54
+ try {
55
+ const phoneNumber = parsePhoneNumberFromString(
56
+ parsed.e164,
57
+ normalizeCountryCode(countryCode)
58
+ );
59
+ if (!phoneNumber) return parsed.formatted;
60
+ return format === "national" ? phoneNumber.formatNational() : phoneNumber.formatInternational();
61
+ } catch {
62
+ return parsed.formatted;
63
+ }
64
+ },
65
+ validatePhone(phone, countryCode) {
66
+ return parsePhone(phone, countryCode).isValid;
67
+ },
68
+ parsePhone,
69
+ defaults
70
+ };
71
+ return {
72
+ provide: {
73
+ phone: phoneHelpers
74
+ }
75
+ };
76
+ });
@@ -0,0 +1,28 @@
1
+ import type { CountryCode } from "libphonenumber-js";
2
+ export type PhoneFormat = "national" | "international" | "e164";
3
+ export interface PhoneInputUiOptions {
4
+ variant?: "outline" | "soft" | "ghost";
5
+ size?: "sm" | "md" | "lg";
6
+ rounded?: "sm" | "md" | "lg" | "xl" | "full";
7
+ }
8
+ export interface ModuleOptions {
9
+ defaultCountry?: CountryCode | string;
10
+ preferredCountries?: string[];
11
+ onlyCountries?: string[];
12
+ ignoredCountries?: string[];
13
+ useBrowserLocale?: boolean;
14
+ format?: PhoneFormat;
15
+ ui?: PhoneInputUiOptions;
16
+ }
17
+ export interface PhoneInputData {
18
+ e164: string | null;
19
+ countryCode: CountryCode | null;
20
+ formatted: string;
21
+ isValid: boolean;
22
+ }
23
+ export interface PhoneHelpers {
24
+ formatPhone: (phone: string, countryCode?: CountryCode | string, format?: PhoneFormat) => string;
25
+ validatePhone: (phone: string, countryCode?: CountryCode | string) => boolean;
26
+ parsePhone: (phone: string, countryCode?: CountryCode | string) => PhoneInputData;
27
+ defaults: Required<ModuleOptions>;
28
+ }
File without changes
@@ -0,0 +1,15 @@
1
+ import type { PhoneHelpers } from "./index";
2
+
3
+ declare module "#app" {
4
+ interface NuxtApp {
5
+ $phone: PhoneHelpers;
6
+ }
7
+ }
8
+
9
+ declare module "vue" {
10
+ interface ComponentCustomProperties {
11
+ $phone: PhoneHelpers;
12
+ }
13
+ }
14
+
15
+ export {};
@@ -0,0 +1 @@
1
+ export { type ModuleOptions, type PhoneFormat, type PhoneInputData, type PhoneInputUiOptions } from './module.js'
@@ -0,0 +1 @@
1
+ export { type ModuleOptions, type PhoneFormat, type PhoneInputData, type PhoneInputUiOptions } from './module'
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "nuxt-phone-number",
3
+ "version": "0.1.0",
4
+ "description": "Nuxt-first phone input module with UPhoneInput, usePhone and global phoneInput config",
5
+ "keywords": [
6
+ "nuxt",
7
+ "nuxt-module",
8
+ "phone-input",
9
+ "telephone",
10
+ "libphonenumber",
11
+ "nuxt-ui"
12
+ ],
13
+ "author": "Adama Sambe",
14
+ "homepage": "https://thecodemaker12.github.io/nuxt-phone-input",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/thecodemaker12/nuxt-phone-input.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/thecodemaker12/nuxt-phone-input/issues"
21
+ },
22
+ "license": "MIT",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "import": "./dist/module.mjs",
27
+ "require": "./dist/module.cjs"
28
+ }
29
+ },
30
+ "main": "./dist/module.cjs",
31
+ "types": "./dist/types.d.ts",
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "scripts": {
36
+ "preinstall": "npx only-allow npm",
37
+ "build": "npx nuxt-module-build build",
38
+ "dev": "npx nuxt-module-build build --stub && npx nuxt-module-build prepare",
39
+ "dev:prepare": "npx nuxt-module-build build --stub && npx nuxt-module-build prepare",
40
+ "typecheck": "npx vue-tsc --noEmit -p tsconfig.json",
41
+ "release": "npm run build && npm publish --access public"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "peerDependencies": {
47
+ "nuxt": "^3.0.0 || ^4.0.0"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@nuxt/ui": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "dependencies": {
55
+ "libphonenumber-js": "^1.12.41"
56
+ },
57
+ "devDependencies": {
58
+ "@nuxt/module-builder": "^0.8.4",
59
+ "@nuxt/schema": "^3.13.0",
60
+ "@types/node": "^22.15.3",
61
+ "nuxt": "^3.13.0",
62
+ "typescript": "^5.5.0",
63
+ "vue-tsc": "^2.1.0"
64
+ }
65
+ }