@jacksonavila/phone-lib 2.0.9 → 2.0.11

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/README.md CHANGED
@@ -62,7 +62,7 @@ You can use PhoneLib directly from CDN without npm / Puedes usar PhoneLib direct
62
62
  <!DOCTYPE html>
63
63
  <html>
64
64
  <head>
65
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/phone-lib.css">
65
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/phone-lib.css">
66
66
  </head>
67
67
  <body>
68
68
  <div id="phone-container"></div>
@@ -70,7 +70,7 @@ You can use PhoneLib directly from CDN without npm / Puedes usar PhoneLib direct
70
70
  <script type="importmap">
71
71
  {
72
72
  "imports": {
73
- "@jacksonavila/phone-lib": "https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/phone-lib.js",
73
+ "@jacksonavila/phone-lib": "https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/phone-lib.js",
74
74
  "libphonenumber-js": "https://esm.sh/libphonenumber-js@1.11.0"
75
75
  }
76
76
  }
@@ -90,8 +90,8 @@ You can use PhoneLib directly from CDN without npm / Puedes usar PhoneLib direct
90
90
  ```
91
91
 
92
92
  **CDN URLs / URLs de CDN:**
93
- - **jsDelivr:** `https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/`
94
- - **unpkg:** `https://unpkg.com/@jacksonavila/phone-lib@2.0.9/`
93
+ - **jsDelivr:** `https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/`
94
+ - **unpkg:** `https://unpkg.com/@jacksonavila/phone-lib@2.0.10/`
95
95
 
96
96
  ### Method 2: Script Tag (All Browsers) / Método 2: Script Tag (Todos los Navegadores)
97
97
 
@@ -99,12 +99,12 @@ You can use PhoneLib directly from CDN without npm / Puedes usar PhoneLib direct
99
99
  <!DOCTYPE html>
100
100
  <html>
101
101
  <head>
102
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/phone-lib.css">
102
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/phone-lib.css">
103
103
  </head>
104
104
  <body>
105
105
  <div id="phone-container"></div>
106
106
 
107
- <script src="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/phone-lib.cdn.js"></script>
107
+ <script src="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/phone-lib.cdn.js"></script>
108
108
 
109
109
  <script>
110
110
  let phoneLib = null;
@@ -197,6 +197,7 @@ import '@jacksonavila/phone-lib/css';
197
197
 
198
198
  const phoneLib = new PhoneLib('#phone-container', {
199
199
  initialCountry: 'CO',
200
+ initialPhoneNumber: '+573001234567', // Optional: set initial phone number / Opcional: establecer número inicial
200
201
  preferredCountries: ['CO', 'US', 'ES'],
201
202
  showHint: true,
202
203
  layout: 'integrated',
@@ -454,6 +455,54 @@ function ContactForm() {
454
455
  }
455
456
  ```
456
457
 
458
+ #### With Initial Phone Number (React Forms) / Con Número Inicial (Formularios React)
459
+
460
+ **Important / Importante:** Use `initialPhoneNumber` to set an initial value and ensure the phone number persists when the parent component re-renders / Usa `initialPhoneNumber` para establecer un valor inicial y asegurar que el número persista cuando el componente padre se re-renderiza:
461
+
462
+ ```jsx
463
+ import React, { useState } from 'react';
464
+ import PhoneLibReact from '@jacksonavila/phone-lib/react';
465
+ import '@jacksonavila/phone-lib/css';
466
+
467
+ function EditContactForm({ contact }) {
468
+ const [name, setName] = useState(contact?.name || '');
469
+ const [email, setEmail] = useState(contact?.email || '');
470
+
471
+ return (
472
+ <form>
473
+ <input
474
+ value={name}
475
+ onChange={(e) => setName(e.target.value)}
476
+ placeholder="Name / Nombre"
477
+ />
478
+ <input
479
+ value={email}
480
+ onChange={(e) => setEmail(e.target.value)}
481
+ placeholder="Email"
482
+ />
483
+
484
+ {/* The phone number value persists even when name/email change /
485
+ El valor del teléfono persiste incluso cuando cambian name/email */}
486
+ <PhoneLibReact
487
+ initialCountry={contact?.country || 'US'}
488
+ initialPhoneNumber={contact?.phone || null}
489
+ onPhoneChange={(phone, isValid) => {
490
+ console.log('Phone / Teléfono:', phone);
491
+ }}
492
+ />
493
+
494
+ <button type="submit">Save / Guardar</button>
495
+ </form>
496
+ );
497
+ }
498
+ ```
499
+
500
+ **💡 Why `initialPhoneNumber` is important / Por qué `initialPhoneNumber` es importante:**
501
+
502
+ - **Prevents data loss / Previene pérdida de datos:** Without `initialPhoneNumber`, the phone value can be lost when the parent component re-renders (e.g., when other form fields change) / Sin `initialPhoneNumber`, el valor del teléfono puede perderse cuando el componente padre se re-renderiza (ej: cuando otros campos del formulario cambian)
503
+ - **Form editing / Edición de formularios:** Essential when editing existing data - the phone number is preserved during re-renders / Esencial al editar datos existentes - el número de teléfono se preserva durante re-renders
504
+ - **Controlled components / Componentes controlados:** Works seamlessly with React's controlled component pattern / Funciona perfectamente con el patrón de componentes controlados de React
505
+
457
506
  ---
458
507
 
459
508
  ## 🎨 Available Layouts / Layouts Disponibles
@@ -513,6 +562,7 @@ const phoneLib = new PhoneLib('#container', {
513
562
  ```javascript
514
563
  {
515
564
  initialCountry: 'CO', // Initial country / País inicial (ISO2)
565
+ initialPhoneNumber: '+573001234567', // Initial phone number (optional) / Número inicial (opcional)
516
566
  preferredCountries: ['CO', 'US'], // Countries that appear first / Países que aparecen primero
517
567
  showHint: true, // Show validation hint / Mostrar hint de validación
518
568
  layout: 'integrated', // 'integrated' or 'separated' / 'integrated' o 'separated'
@@ -520,10 +570,22 @@ const phoneLib = new PhoneLib('#container', {
520
570
  }
521
571
  ```
522
572
 
573
+ **📝 Note about `initialPhoneNumber` / Nota sobre `initialPhoneNumber`:**
574
+
575
+ - **Vanilla JS:** Use `initialPhoneNumber` in the constructor options to set an initial phone number value / Usa `initialPhoneNumber` en las opciones del constructor para establecer un valor inicial del teléfono
576
+ - **React:** Use the `initialPhoneNumber` prop to set an initial value. This prop also ensures the phone number value persists when the parent component re-renders / Usa la prop `initialPhoneNumber` para establecer un valor inicial. Esta prop también asegura que el valor del teléfono persista cuando el componente padre se re-renderiza
577
+ - The value is preserved during re-renders, preventing data loss in React forms / El valor se preserva durante re-renders, previniendo pérdida de datos en formularios React
578
+
523
579
  ### Advanced Options / Opciones Avanzadas
524
580
 
525
581
  ```javascript
526
582
  {
583
+ // Initial values / Valores iniciales
584
+ initialCountry: 'CO', // Initial country (ISO2) / País inicial (ISO2)
585
+ initialPhoneNumber: '+573001234567', // Initial phone number (optional) / Número inicial (opcional)
586
+ // In React: ensures value persists during re-renders /
587
+ // En React: asegura que el valor persista durante re-renders
588
+
527
589
  // Detection and validation / Detección y validación
528
590
  autoDetectCountry: true, // Auto-detect country / Detectar país automáticamente
529
591
  validateOnInput: false, // Validate while typing / Validar mientras se escribe
@@ -879,6 +941,7 @@ const phoneLib = new PhoneLib('#container', {
879
941
  | Prop | Type | Default | Description / Descripción |
880
942
  |------|------|---------|--------------------------|
881
943
  | `initialCountry` | string | `'US'` | Initial country (ISO2) / País inicial (ISO2) |
944
+ | `initialPhoneNumber` | string \| null | `null` | Initial phone number value. **Important:** This prop ensures the phone value persists during parent component re-renders in React / Valor inicial del teléfono. **Importante:** Esta prop asegura que el valor del teléfono persista durante re-renders del componente padre en React |
882
945
  | `preferredCountries` | array | `[]` | Preferred countries / Países preferidos |
883
946
  | `showHint` | boolean | `true` | Show validation hint / Mostrar hint de validación |
884
947
  | `layout` | string | `'integrated'` | `'integrated'` or `'separated'` / `'integrated'` o `'separated'` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacksonavila/phone-lib",
3
- "version": "2.0.9",
3
+ "version": "2.0.11",
4
4
  "description": "Librería JavaScript para input de teléfono con selector de país y banderas - Compatible con Vanilla JS y React",
5
5
  "main": "phone-lib.js",
6
6
  "module": "phone-lib.js",
@@ -42,12 +42,12 @@
42
42
  "license": "MIT",
43
43
  "repository": {
44
44
  "type": "git",
45
- "url": ""
45
+ "url": "git+https://github.com/jackAvilaP/phone-lib.git"
46
46
  },
47
47
  "bugs": {
48
- "url": ""
48
+ "url": "https://github.com/jackAvilaP/phone-lib/issues"
49
49
  },
50
- "homepage": "",
50
+ "homepage": "https://github.com/jackAvilaP/phone-lib#readme",
51
51
  "dependencies": {
52
52
  "libphonenumber-js": "^1.11.0"
53
53
  },
@@ -74,4 +74,4 @@
74
74
  "engines": {
75
75
  "node": ">=14.0.0"
76
76
  }
77
- }
77
+ }
@@ -28,6 +28,7 @@ const PhoneLibReact = forwardRef((props, ref) => {
28
28
  containerId,
29
29
  containerClassName,
30
30
  initialCountry = 'US',
31
+ initialPhoneNumber = null,
31
32
  preferredCountries = [],
32
33
  showHint = true,
33
34
  layout = 'integrated',
@@ -67,6 +68,7 @@ const PhoneLibReact = forwardRef((props, ref) => {
67
68
  // Inicializar PhoneLib
68
69
  phoneLibRef.current = new PhoneLib(containerRef.current, {
69
70
  initialCountry,
71
+ initialPhoneNumber,
70
72
  preferredCountries,
71
73
  showHint,
72
74
  layout,
@@ -93,6 +95,11 @@ const PhoneLibReact = forwardRef((props, ref) => {
93
95
  onBlur
94
96
  });
95
97
 
98
+ // Si hay un número inicial, establecerlo después de la inicialización
99
+ if (initialPhoneNumber) {
100
+ phoneLibRef.current.setPhoneNumber(initialPhoneNumber);
101
+ }
102
+
96
103
  // Cleanup al desmontar
97
104
  return () => {
98
105
  if (phoneLibRef.current) {
@@ -108,6 +115,7 @@ const PhoneLibReact = forwardRef((props, ref) => {
108
115
 
109
116
  phoneLibRef.current.updateOptions({
110
117
  initialCountry,
118
+ initialPhoneNumber,
111
119
  preferredCountries,
112
120
  showHint,
113
121
  layout,
@@ -130,6 +138,7 @@ const PhoneLibReact = forwardRef((props, ref) => {
130
138
  });
131
139
  }, [
132
140
  initialCountry,
141
+ initialPhoneNumber,
133
142
  preferredCountries,
134
143
  showHint,
135
144
  layout,
package/phone-lib.cdn.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * Carga libphonenumber-js dinámicamente y expone PhoneLib globalmente
5
5
  *
6
6
  * Uso:
7
- * <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/phone-lib.css">
8
- * <script src="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.9/phone-lib.cdn.js"></script>
7
+ * <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/phone-lib.css">
8
+ * <script src="https://cdn.jsdelivr.net/npm/@jacksonavila/phone-lib@2.0.10/phone-lib.cdn.js"></script>
9
9
  * <script>
10
10
  * document.addEventListener('phoneLibReady', () => {
11
11
  * const phoneLib = new PhoneLib('#container', {...});
@@ -17,7 +17,7 @@
17
17
  'use strict';
18
18
 
19
19
  // Versión del paquete (actualizar cuando se publique nueva versión)
20
- const PACKAGE_VERSION = '2.0.9';
20
+ const PACKAGE_VERSION = '2.0.10';
21
21
  const PACKAGE_NAME = '@jacksonavila/phone-lib';
22
22
 
23
23
  // URLs de CDN
package/phone-lib.js CHANGED
@@ -76,7 +76,7 @@ class PhoneLib {
76
76
 
77
77
  // Estado interno
78
78
  this.selectedCountry = this.options.initialCountry;
79
- this.phoneNumber = '';
79
+ this.phoneNumber = options.initialPhoneNumber || '';
80
80
  this.isValid = false;
81
81
  this.isDisabled = this.options.disabled;
82
82
  this.isReadonly = this.options.readonly;
@@ -543,7 +543,13 @@ class PhoneLib {
543
543
  init() {
544
544
  this.render();
545
545
  this.attachEventListeners();
546
- this.updatePhoneNumber();
546
+
547
+ // Si hay un número inicial, establecerlo después de renderizar
548
+ if (this.phoneNumber) {
549
+ this.setPhoneNumber(this.phoneNumber);
550
+ } else {
551
+ this.updatePhoneNumber();
552
+ }
547
553
 
548
554
  // Aplicar estados iniciales
549
555
  if (this.isDisabled) {
@@ -1685,6 +1691,10 @@ class PhoneLib {
1685
1691
  * Actualiza opciones dinámicamente
1686
1692
  */
1687
1693
  updateOptions(newOptions) {
1694
+ // Preservar el valor actual del teléfono y país antes de cualquier cambio
1695
+ const savedPhoneNumber = this.phoneNumber || '';
1696
+ const savedCountry = this.selectedCountry || this.options.initialCountry || 'US';
1697
+
1688
1698
  // Actualizar opciones
1689
1699
  this.options = { ...this.options, ...newOptions };
1690
1700
 
@@ -1707,10 +1717,28 @@ class PhoneLib {
1707
1717
  this.setCountry(newOptions.initialCountry);
1708
1718
  }
1709
1719
 
1720
+ // Si se proporciona un número inicial, usarlo
1721
+ if (newOptions.initialPhoneNumber !== undefined) {
1722
+ this.phoneNumber = newOptions.initialPhoneNumber;
1723
+ }
1724
+
1710
1725
  // Re-renderizar si cambió layout u opciones visuales importantes
1711
1726
  if (newOptions.layout || newOptions.showDialCode !== undefined || newOptions.customClasses || newOptions.customStyles || newOptions.arrowIcon !== undefined) {
1712
1727
  this.render();
1713
1728
  this.attachEventListeners();
1729
+
1730
+ // Restaurar el valor del teléfono después de re-renderizar
1731
+ // Si no se proporcionó un nuevo initialPhoneNumber, restaurar el valor guardado
1732
+ if (newOptions.initialPhoneNumber === undefined && savedPhoneNumber) {
1733
+ this.setPhoneNumber(savedPhoneNumber);
1734
+ } else if (newOptions.initialPhoneNumber !== undefined) {
1735
+ this.setPhoneNumber(newOptions.initialPhoneNumber);
1736
+ }
1737
+
1738
+ // Asegurar que el país también esté correcto
1739
+ if (this.selectedCountry !== savedCountry && newOptions.initialCountry === undefined) {
1740
+ this.setCountry(savedCountry);
1741
+ }
1714
1742
  }
1715
1743
  }
1716
1744
  }