country-select-pro 4.8.2

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 nikmauro
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,184 @@
1
+ # CountrySelect Pro 🌍
2
+
3
+ [![MIT License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
4
+ [![jsDelivr](https://data.jsdelivr.com/v1/package/gh/nikmauro/country-select-pro/badge)](https://www.jsdelivr.com/package/gh/nikmauro/country-select-pro)
5
+ ![Vanilla JS](https://img.shields.io/badge/Vanilla-JavaScript-yellow)
6
+ ![Size](https://img.shields.io/badge/size-%3C4KB-brightgreen)
7
+
8
+ A **lightweight, zero-dependency, vanilla JavaScript country selector** with localized browser validation and **Bootstrap 5 integration**.
9
+
10
+ CountrySelect Pro provides a clean and fast country dropdown with **search, phone codes, accessibility support and smart browser validation**, without requiring jQuery or any external framework.
11
+
12
+ ---
13
+
14
+ # ✨ Features
15
+
16
+ * 🚀 **Zero Dependencies** – No jQuery, no frameworks.
17
+ * ⚡ **Ultra Lightweight** – Less than **4KB minified**.
18
+ * 🎨 **Bootstrap 5 Ready** – Seamless integration with `input-group`.
19
+ * 🔍 **Built-in Search** – Quickly filter countries and phone codes.
20
+ * 🛡️ **Smart Validation** – Uses native browser localized validation messages.
21
+ * 📱 **Responsive UI** – Works perfectly on mobile and desktop.
22
+ * ⌨️ **Keyboard Accessible** – Fully navigable with keyboard.
23
+ * 🌐 **International Ready** – Supports ISO country codes.
24
+
25
+ ---
26
+
27
+ # 🎮 Live Demo
28
+
29
+ Try the interactive demo:
30
+
31
+ https://nikmauro.github.io/country-select-pro/
32
+
33
+ ---
34
+
35
+ # 📦 Installation
36
+
37
+ ## CDN (Recommended)
38
+
39
+ Include the script via **jsDelivr**:
40
+
41
+ ```html
42
+ <script src="https://cdn.jsdelivr.net/gh/nikmauro/country-select-pro@4.8.2/dist/country-select.min.js"></script>
43
+ ```
44
+
45
+ ---
46
+
47
+ ## Local Installation
48
+
49
+ Download the repository and include:
50
+
51
+ ```html
52
+ <script src="dist/country-select.min.js"></script>
53
+ ```
54
+
55
+ ---
56
+
57
+ # 🚀 Basic Usage
58
+
59
+ ```html
60
+ <input id="country" class="form-control">
61
+
62
+ <script>
63
+ const countrySelect = new CountrySelect("#country", {
64
+ defaultCountry: "gr"
65
+ });
66
+ </script>
67
+ ```
68
+
69
+ ---
70
+
71
+ # ⚙️ Options
72
+
73
+ | Option | Type | Description |
74
+ | -------------------- | ------- | ----------------------------------- |
75
+ | `defaultCountry` | string | Default selected country (ISO code) |
76
+ | `preferredCountries` | array | Countries displayed first |
77
+ | `onlyCountries` | array | Restrict selectable countries |
78
+ | `search` | boolean | Enable / disable search |
79
+ | `placeholder` | string | Custom placeholder text |
80
+
81
+ Example:
82
+
83
+ ```javascript
84
+ new CountrySelect("#country", {
85
+ defaultCountry: "gr",
86
+ preferredCountries: ["gr", "cy", "de"],
87
+ search: true
88
+ });
89
+ ```
90
+
91
+ ---
92
+
93
+ # 🧩 Bootstrap 5 Example
94
+
95
+ CountrySelect works perfectly with Bootstrap input groups.
96
+
97
+ ```html
98
+ <div class="input-group">
99
+ <span class="input-group-text">🌍</span>
100
+ <input id="country" class="form-control">
101
+ </div>
102
+ ```
103
+
104
+ ```javascript
105
+ new CountrySelect("#country");
106
+ ```
107
+
108
+ ---
109
+
110
+ # 🌐 Browser Support
111
+
112
+ Compatible with all modern browsers:
113
+
114
+ * Chrome
115
+ * Firefox
116
+ * Safari
117
+ * Edge
118
+ * Mobile browsers (iOS / Android)
119
+
120
+ No polyfills required.
121
+
122
+ ---
123
+
124
+ # 📂 Project Structure
125
+
126
+ ```
127
+ country-select-pro
128
+ │
129
+ ├─ dist
130
+ │ ├─ country-select.js
131
+ │ └─ country-select.min.js
132
+ │
133
+ ├─ demo
134
+ ├─ src
135
+ └─ README.md
136
+ ```
137
+
138
+ ---
139
+
140
+ # 🧠 Why CountrySelect Pro?
141
+
142
+ Many country dropdown libraries rely on **large frameworks like jQuery or heavy UI components**.
143
+
144
+ CountrySelect Pro was built to be:
145
+
146
+ * **Tiny**
147
+ * **Fast**
148
+ * **Dependency-free**
149
+ * **Easy to integrate**
150
+
151
+ Perfect for:
152
+
153
+ * checkout forms
154
+ * registration forms
155
+ * shipping address forms
156
+ * phone number inputs
157
+ * international forms
158
+
159
+ ---
160
+
161
+ # 🤝 Contributing
162
+
163
+ Contributions are welcome.
164
+
165
+ 1. Fork the repository
166
+ 2. Create a feature branch
167
+ 3. Submit a Pull Request
168
+
169
+ ---
170
+
171
+ # 👨‍💻 Author
172
+
173
+ Developed by **Nikolaos Mavroeidis**
174
+ GitHub: https://github.com/nikmauro
175
+
176
+ With collaborative assistance from **Gemini (Google AI)**.
177
+
178
+ ---
179
+
180
+ # 📄 License
181
+
182
+ MIT License
183
+
184
+ Feel free to use it in personal and commercial projects.
@@ -0,0 +1,277 @@
1
+ /**
2
+ * CountrySelect Pro v4.8
3
+ * (c) 2024 nikmauro
4
+ * Released under the MIT License.
5
+ * Repository: https://github.com/nikmauro/country-select-pro
6
+ */
7
+
8
+
9
+ /**
10
+ * CountrySelect Pro v4.8
11
+ * ---------------------------------------------------------------------------
12
+ * EXAMPLES & DATA ATTRIBUTES:
13
+ * * 1. Default (ISO Code):
14
+ * <input type="text" class="country-select" value="GR">
15
+ * * 2. Phone Mode (Returns +30):
16
+ * <input type="text" class="country-select" value="+30" data-value-type="phone">
17
+ * * 3. Custom Schemas (List vs Trigger):
18
+ * data-schema="{img} {name} (+{phone})" -> Πώς φαίνεται στη λίστα
19
+ * data-schema-return="{img} (+{phone})" -> Πώς φαίνεται αφού επιλεγεί
20
+ * * 4. UI Adjustments:
21
+ * data-dropdown-width="300px" -> Σταθερό πλάτος μενού (αντί για auto/100%)
22
+ * data-country-row-values="10" -> Πόσες γραμμές να φαίνονται πριν το scroll
23
+ * data-country-search="false" -> Απενεργοποίηση αναζήτησης
24
+ * * 5. Validation:
25
+ * Λειτουργεί αυτόματα με το 'required' attribute και το native validation του browser.
26
+ * ---------------------------------------------------------------------------
27
+ */
28
+
29
+ class CountrySelect {
30
+ constructor(element, options = {}) {
31
+ this.input = element;
32
+ if (!this.input) return;
33
+
34
+ // Configuration από data-attributes
35
+ this.schema = this.input.dataset.schema || "{img} {name}";
36
+ this.schemaReturn = this.input.dataset.schemaReturn || this.schema;
37
+ this.valueType = this.input.dataset.valueType || "code"; // code, phone, name
38
+ this.rowLimit = parseInt(this.input.dataset.countryRowValues) || 5;
39
+ this.hasSearch = this.input.dataset.countrySearch !== "false";
40
+ this.dropdownWidth = this.input.dataset.dropdownWidth || "auto";
41
+
42
+ this.config = {
43
+ placeholder: this.input.dataset.placeholder || "Select",
44
+ preferred: this.input.dataset.preferred ? this.input.dataset.preferred.split(',') : [],
45
+ ...options
46
+ };
47
+
48
+ this.countries = [];
49
+ this.filteredCountries = [];
50
+ this.isOpen = false;
51
+ this.activeIndex = -1;
52
+ this.rowHeight = 44;
53
+
54
+ this._init();
55
+ }
56
+
57
+ async _init() {
58
+ this._applyStyles();
59
+ this._setupDOM();
60
+ this._bindEvents();
61
+ await this._loadData();
62
+ }
63
+
64
+ _applyStyles() {
65
+ const styles = `
66
+ .cs-wrapper { position: relative; font-family: system-ui, sans-serif; outline: none; box-sizing: border-box; display: block; width: 100%; }
67
+ .cs-trigger {
68
+ padding: 10px 12px; border: 1px solid #ccc; border-radius: 6px;
69
+ display: flex; align-items: center; gap: 10px; cursor: pointer; background: #fff; min-height: 42px; box-sizing: border-box;
70
+ transition: border-color 0.15s ease-in-out;
71
+ }
72
+
73
+ /* Validation UI */
74
+ .cs-wrapper.is-invalid .cs-trigger { border-color: #dc3545 !important; }
75
+ .cs-error-msg {
76
+ display: none; color: #dc3545; font-size: 0.825em; margin-top: 4px; position: absolute; left: 0; top: 100%; width: 100%; z-index: 10;
77
+ }
78
+ .cs-wrapper.is-invalid .cs-error-msg { display: block; }
79
+
80
+ /* Bootstrap Input Group Support */
81
+ .input-group-text .cs-wrapper .cs-trigger { border: none; background: transparent; padding: 0; min-height: auto; width: auto; }
82
+ .input-group-text .cs-wrapper { width: auto; }
83
+ .input-group-text { padding: 0 12px !important; position: relative; }
84
+ .input-group-text:has(.cs-wrapper.is-invalid) { border-color: #dc3545; z-index: 5; }
85
+
86
+ .cs-wrapper:focus .cs-trigger { border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.15); }
87
+
88
+ /* Dropdown Menu */
89
+ .cs-dropdown {
90
+ position: absolute; top: calc(100% + 8px); left: 0; background: #fff;
91
+ border: 1px solid #ccc; z-index: 2050; display: none;
92
+ box-shadow: 0 10px 25px rgba(0,0,0,0.1); border-radius: 6px; overflow: hidden; max-width: 95vw;
93
+ }
94
+ .cs-wrapper.open .cs-dropdown { display: block; }
95
+ .cs-search-box { padding: 8px; border-bottom: 1px solid #eee; background: #f9f9f9; }
96
+ .cs-search-input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; outline: none; }
97
+ .cs-list { overflow-y: auto; scrollbar-width: thin; scroll-behavior: smooth; min-height: 50px; }
98
+ .cs-option { height: 44px; padding: 0 12px; display: flex; align-items: center; gap: 10px; cursor: pointer; font-size: 14px; box-sizing: border-box; color: #333; }
99
+ .cs-option:hover, .cs-option.active { background: #f0f7ff; color: #0056b3; }
100
+
101
+ /* Elements */
102
+ .cs-wrapper img { width: 22px !important; height: 15px !important; object-fit: cover; border-radius: 2px; flex-shrink: 0; }
103
+ .cs-selected-content { display: flex; align-items: center; gap: 8px; overflow: hidden; white-space: nowrap; min-width: 20px; font-size: 14px; }
104
+ .cs-hidden { display: none !important; }
105
+ `;
106
+ const styleId = 'cs-v48-final-styles';
107
+ if (!document.getElementById(styleId)) {
108
+ const style = document.createElement("style");
109
+ style.id = styleId;
110
+ style.textContent = styles;
111
+ document.head.appendChild(style);
112
+ }
113
+ }
114
+
115
+ _setupDOM() {
116
+ // Κάνουμε το input 'αόρατο' αλλά λειτουργικό για το validation
117
+ Object.assign(this.input.style, {
118
+ position: 'absolute', opacity: '0', width: '1px', height: '1px', pointerEvents: 'none'
119
+ });
120
+
121
+ this.wrapper = document.createElement('div');
122
+ this.wrapper.className = 'cs-wrapper';
123
+ this.wrapper.tabIndex = 0;
124
+
125
+ // Αν υπάρχει value, δείχνουμε κενό μέχρι να έρθει το API (αποφυγή flash "...")
126
+ const initialText = this.input.value ? "" : this.config.placeholder;
127
+
128
+ this.wrapper.innerHTML = `
129
+ <div class="cs-trigger"><span class="cs-selected-content">${initialText}</span></div>
130
+ <div class="cs-error-msg"></div>
131
+ <div class="cs-dropdown">
132
+ <div class="cs-search-box ${!this.hasSearch ? 'cs-hidden' : ''}">
133
+ <input type="text" class="cs-search-input" placeholder="Search..." autocomplete="off" tabindex="-1">
134
+ </div>
135
+ <div class="cs-list"><div class="cs-loading" style="padding:15px; text-align:center;">Loading...</div></div>
136
+ </div>
137
+ `;
138
+
139
+ const dropdown = this.wrapper.querySelector('.cs-dropdown');
140
+ dropdown.style.width = (this.dropdownWidth === 'auto') ? '100%' : this.dropdownWidth;
141
+
142
+ this.input.parentNode.insertBefore(this.wrapper, this.input.nextSibling);
143
+
144
+ // Server-side error check
145
+ if (this.input.classList.contains('is-invalid')) this._showError();
146
+ }
147
+
148
+ async _loadData() {
149
+ try {
150
+ const res = await fetch('https://restcountries.com/v3.1/all?fields=name,flags,cca2,idd');
151
+ const data = await res.json();
152
+ this.countries = data.map(c => ({
153
+ name: c.name.common,
154
+ code: c.cca2,
155
+ flag: c.flags.svg,
156
+ phone: c.idd.root + (c.idd.suffixes ? (c.idd.suffixes.length > 1 ? "" : c.idd.suffixes[0]) : "")
157
+ })).sort((a, b) => a.name.localeCompare(b.name));
158
+
159
+ this.filteredCountries = [...this.countries];
160
+ this._renderOptions();
161
+ this._syncInitialValue();
162
+ } catch (e) { console.error("CountrySelect: API Failed", e); }
163
+ }
164
+
165
+ _syncInitialValue() {
166
+ const val = this.input.value;
167
+ if (!val) {
168
+ this.wrapper.querySelector('.cs-selected-content').innerHTML = this.config.placeholder;
169
+ return;
170
+ }
171
+ const current = this.countries.find(c =>
172
+ this.valueType === "phone" ? c.phone === val :
173
+ this.valueType === "name" ? c.name === val : c.code === val
174
+ );
175
+ if (current) this._updateUI(current);
176
+ else this.wrapper.querySelector('.cs-selected-content').innerHTML = this.config.placeholder;
177
+ }
178
+
179
+ _parseTemplate(template, country) {
180
+ return template
181
+ .replace('{img}', `<img src="${country.flag}">`)
182
+ .replace('{name}', `<span>${country.name}</span>`)
183
+ .replace('{code}', `<span>${country.code}</span>`)
184
+ .replace('{phone}', `<span>${country.phone}</span>`);
185
+ }
186
+
187
+ _renderOptions() {
188
+ const listContainer = this.wrapper.querySelector('.cs-list');
189
+ if(!listContainer) return;
190
+ listContainer.innerHTML = '';
191
+ this.filteredCountries.forEach((country, index) => {
192
+ const div = document.createElement('div');
193
+ div.className = `cs-option ${index === this.activeIndex ? 'active' : ''}`;
194
+ div.innerHTML = this._parseTemplate(this.schema, country);
195
+ div.onclick = (e) => { e.stopPropagation(); this._select(country); };
196
+ listContainer.appendChild(div);
197
+ });
198
+ }
199
+
200
+ _select(country) {
201
+ this._updateUI(country);
202
+ const val = (this.valueType === "phone") ? country.phone : (this.valueType === "name" ? country.name : country.code);
203
+ this.input.value = val;
204
+ this.input.setCustomValidity("");
205
+ this.wrapper.classList.remove('is-invalid');
206
+ this.input.dispatchEvent(new Event('change', { bubbles: true }));
207
+ this._toggle(false);
208
+ this.wrapper.focus();
209
+ }
210
+
211
+ _updateUI(country) {
212
+ const content = this.wrapper.querySelector('.cs-selected-content');
213
+ if(content) content.innerHTML = this._parseTemplate(this.schemaReturn, country);
214
+ }
215
+
216
+ _showError() {
217
+ const errorDiv = this.wrapper.querySelector('.cs-error-msg');
218
+ errorDiv.textContent = this.input.validationMessage || "Invalid selection";
219
+ this.wrapper.classList.add('is-invalid');
220
+ }
221
+
222
+ _toggle(force) {
223
+ if (this.countries.length === 0) return;
224
+ this.isOpen = force !== undefined ? force : !this.isOpen;
225
+ if (this.isOpen) {
226
+ document.dispatchEvent(new CustomEvent('cs-close-others', { detail: { opener: this.wrapper } }));
227
+ this.activeIndex = this.filteredCountries.findIndex(c => this.input.value.includes(c.code) || this.input.value.includes(c.phone));
228
+ this._renderOptions();
229
+ const list = this.wrapper.querySelector('.cs-list');
230
+ list.style.maxHeight = `${this.rowLimit * this.rowHeight}px`;
231
+ if (this.activeIndex > -1) setTimeout(() => this._scrollToActive(), 50);
232
+ if (this.hasSearch) setTimeout(() => this.wrapper.querySelector('.cs-search-input').focus(), 50);
233
+ }
234
+ this.wrapper.classList.toggle('open', this.isOpen);
235
+ }
236
+
237
+ _bindEvents() {
238
+ this.wrapper.querySelector('.cs-trigger').onclick = (e) => { e.stopPropagation(); this._toggle(); };
239
+ this.input.addEventListener('invalid', (e) => { e.preventDefault(); this._showError(); });
240
+
241
+ this.wrapper.addEventListener('keydown', (e) => {
242
+ if (!this.isOpen && (e.key === 'Enter' || e.key === 'ArrowDown')) { e.preventDefault(); this._toggle(true); return; }
243
+ if (this.isOpen) {
244
+ if (e.key === 'ArrowDown') {
245
+ e.preventDefault();
246
+ this.activeIndex = Math.min(this.activeIndex + 1, this.filteredCountries.length - 1);
247
+ this._renderOptions(); this._scrollToActive();
248
+ } else if (e.key === 'ArrowUp') {
249
+ e.preventDefault();
250
+ this.activeIndex = Math.max(this.activeIndex - 1, 0);
251
+ this._renderOptions(); this._scrollToActive();
252
+ } else if (e.key === 'Enter' && this.activeIndex > -1) {
253
+ e.preventDefault(); this._select(this.filteredCountries[this.activeIndex]);
254
+ } else if (e.key === 'Escape') this._toggle(false);
255
+ }
256
+ });
257
+
258
+ if (this.hasSearch) {
259
+ this.wrapper.querySelector('.cs-search-input').oninput = (e) => {
260
+ const term = e.target.value.toLowerCase();
261
+ this.filteredCountries = this.countries.filter(c => c.name.toLowerCase().includes(term) || c.phone.includes(term));
262
+ this.activeIndex = 0; this._renderOptions();
263
+ };
264
+ }
265
+ document.addEventListener('click', (e) => { if (!this.wrapper.contains(e.target)) this._toggle(false); });
266
+ document.addEventListener('cs-close-others', (e) => { if (e.detail.opener !== this.wrapper) { this.isOpen = false; this.wrapper.classList.remove('open'); } });
267
+ }
268
+
269
+ _scrollToActive() {
270
+ const list = this.wrapper.querySelector('.cs-list');
271
+ const activeItem = list.querySelectorAll('.cs-option')[this.activeIndex];
272
+ if (activeItem) list.scrollTop = activeItem.offsetTop - (list.offsetHeight / 2) + (this.rowHeight / 2);
273
+ }
274
+ }
275
+
276
+ // Auto-run
277
+ document.querySelectorAll('.country-select').forEach(el => new CountrySelect(el));
@@ -0,0 +1 @@
1
+ class CountrySelect{constructor(e,t={}){this.input=e,this.input&&(this.schema=this.input.dataset.schema||"{img} {name}",this.schemaReturn=this.input.dataset.schemaReturn||this.schema,this.valueType=this.input.dataset.valueType||"code",this.rowLimit=parseInt(this.input.dataset.countryRowValues)||5,this.hasSearch="false"!==this.input.dataset.countrySearch,this.dropdownWidth=this.input.dataset.dropdownWidth||"auto",this.config={placeholder:this.input.dataset.placeholder||"Select",preferred:this.input.dataset.preferred?this.input.dataset.preferred.split(","):[],...t},this.countries=[],this.filteredCountries=[],this.isOpen=!1,this.activeIndex=-1,this.rowHeight=44,this._init())}async _init(){this._applyStyles(),this._setupDOM(),this._bindEvents(),await this._loadData()}_applyStyles(){const e="cs-v48-final-styles";if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent="\n .cs-wrapper { position: relative; font-family: system-ui, sans-serif; outline: none; box-sizing: border-box; display: block; width: 100%; }\n .cs-trigger { \n padding: 10px 12px; border: 1px solid #ccc; border-radius: 6px; \n display: flex; align-items: center; gap: 10px; cursor: pointer; background: #fff; min-height: 42px; box-sizing: border-box;\n transition: border-color 0.15s ease-in-out;\n }\n \n /* Validation UI */\n .cs-wrapper.is-invalid .cs-trigger { border-color: #dc3545 !important; }\n .cs-error-msg { \n display: none; color: #dc3545; font-size: 0.825em; margin-top: 4px; position: absolute; left: 0; top: 100%; width: 100%; z-index: 10;\n }\n .cs-wrapper.is-invalid .cs-error-msg { display: block; }\n\n /* Bootstrap Input Group Support */\n .input-group-text .cs-wrapper .cs-trigger { border: none; background: transparent; padding: 0; min-height: auto; width: auto; }\n .input-group-text .cs-wrapper { width: auto; }\n .input-group-text { padding: 0 12px !important; position: relative; }\n .input-group-text:has(.cs-wrapper.is-invalid) { border-color: #dc3545; z-index: 5; }\n\n .cs-wrapper:focus .cs-trigger { border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.15); }\n \n /* Dropdown Menu */\n .cs-dropdown { \n position: absolute; top: calc(100% + 8px); left: 0; background: #fff; \n border: 1px solid #ccc; z-index: 2050; display: none; \n box-shadow: 0 10px 25px rgba(0,0,0,0.1); border-radius: 6px; overflow: hidden; max-width: 95vw;\n }\n .cs-wrapper.open .cs-dropdown { display: block; }\n .cs-search-box { padding: 8px; border-bottom: 1px solid #eee; background: #f9f9f9; }\n .cs-search-input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; outline: none; }\n .cs-list { overflow-y: auto; scrollbar-width: thin; scroll-behavior: smooth; min-height: 50px; }\n .cs-option { height: 44px; padding: 0 12px; display: flex; align-items: center; gap: 10px; cursor: pointer; font-size: 14px; box-sizing: border-box; color: #333; }\n .cs-option:hover, .cs-option.active { background: #f0f7ff; color: #0056b3; }\n \n /* Elements */\n .cs-wrapper img { width: 22px !important; height: 15px !important; object-fit: cover; border-radius: 2px; flex-shrink: 0; }\n .cs-selected-content { display: flex; align-items: center; gap: 8px; overflow: hidden; white-space: nowrap; min-width: 20px; font-size: 14px; }\n .cs-hidden { display: none !important; }\n ",document.head.appendChild(t)}}_setupDOM(){Object.assign(this.input.style,{position:"absolute",opacity:"0",width:"1px",height:"1px",pointerEvents:"none"}),this.wrapper=document.createElement("div"),this.wrapper.className="cs-wrapper",this.wrapper.tabIndex=0;const e=this.input.value?"":this.config.placeholder;this.wrapper.innerHTML=`\n <div class="cs-trigger"><span class="cs-selected-content">${e}</span></div>\n <div class="cs-error-msg"></div>\n <div class="cs-dropdown">\n <div class="cs-search-box ${this.hasSearch?"":"cs-hidden"}">\n <input type="text" class="cs-search-input" placeholder="Search..." autocomplete="off" tabindex="-1">\n </div>\n <div class="cs-list"><div class="cs-loading" style="padding:15px; text-align:center;">Loading...</div></div>\n </div>\n `;this.wrapper.querySelector(".cs-dropdown").style.width="auto"===this.dropdownWidth?"100%":this.dropdownWidth,this.input.parentNode.insertBefore(this.wrapper,this.input.nextSibling),this.input.classList.contains("is-invalid")&&this._showError()}async _loadData(){try{const e=await fetch("https://restcountries.com/v3.1/all?fields=name,flags,cca2,idd"),t=await e.json();this.countries=t.map((e=>({name:e.name.common,code:e.cca2,flag:e.flags.svg,phone:e.idd.root+(e.idd.suffixes?e.idd.suffixes.length>1?"":e.idd.suffixes[0]:"")}))).sort(((e,t)=>e.name.localeCompare(t.name))),this.filteredCountries=[...this.countries],this._renderOptions(),this._syncInitialValue()}catch(e){console.error("CountrySelect: API Failed",e)}}_syncInitialValue(){const e=this.input.value;if(!e)return void(this.wrapper.querySelector(".cs-selected-content").innerHTML=this.config.placeholder);const t=this.countries.find((t=>"phone"===this.valueType?t.phone===e:"name"===this.valueType?t.name===e:t.code===e));t?this._updateUI(t):this.wrapper.querySelector(".cs-selected-content").innerHTML=this.config.placeholder}_parseTemplate(e,t){return e.replace("{img}",`<img src="${t.flag}">`).replace("{name}",`<span>${t.name}</span>`).replace("{code}",`<span>${t.code}</span>`).replace("{phone}",`<span>${t.phone}</span>`)}_renderOptions(){const e=this.wrapper.querySelector(".cs-list");e&&(e.innerHTML="",this.filteredCountries.forEach(((t,i)=>{const s=document.createElement("div");s.className="cs-option "+(i===this.activeIndex?"active":""),s.innerHTML=this._parseTemplate(this.schema,t),s.onclick=e=>{e.stopPropagation(),this._select(t)},e.appendChild(s)})))}_select(e){this._updateUI(e);const t="phone"===this.valueType?e.phone:"name"===this.valueType?e.name:e.code;this.input.value=t,this.input.setCustomValidity(""),this.wrapper.classList.remove("is-invalid"),this.input.dispatchEvent(new Event("change",{bubbles:!0})),this._toggle(!1),this.wrapper.focus()}_updateUI(e){const t=this.wrapper.querySelector(".cs-selected-content");t&&(t.innerHTML=this._parseTemplate(this.schemaReturn,e))}_showError(){this.wrapper.querySelector(".cs-error-msg").textContent=this.input.validationMessage||"Invalid selection",this.wrapper.classList.add("is-invalid")}_toggle(e){if(0!==this.countries.length){if(this.isOpen=void 0!==e?e:!this.isOpen,this.isOpen){document.dispatchEvent(new CustomEvent("cs-close-others",{detail:{opener:this.wrapper}})),this.activeIndex=this.filteredCountries.findIndex((e=>this.input.value.includes(e.code)||this.input.value.includes(e.phone))),this._renderOptions();this.wrapper.querySelector(".cs-list").style.maxHeight=this.rowLimit*this.rowHeight+"px",this.activeIndex>-1&&setTimeout((()=>this._scrollToActive()),50),this.hasSearch&&setTimeout((()=>this.wrapper.querySelector(".cs-search-input").focus()),50)}this.wrapper.classList.toggle("open",this.isOpen)}}_bindEvents(){this.wrapper.querySelector(".cs-trigger").onclick=e=>{e.stopPropagation(),this._toggle()},this.input.addEventListener("invalid",(e=>{e.preventDefault(),this._showError()})),this.wrapper.addEventListener("keydown",(e=>{if(!this.isOpen&&("Enter"===e.key||"ArrowDown"===e.key))return e.preventDefault(),void this._toggle(!0);this.isOpen&&("ArrowDown"===e.key?(e.preventDefault(),this.activeIndex=Math.min(this.activeIndex+1,this.filteredCountries.length-1),this._renderOptions(),this._scrollToActive()):"ArrowUp"===e.key?(e.preventDefault(),this.activeIndex=Math.max(this.activeIndex-1,0),this._renderOptions(),this._scrollToActive()):"Enter"===e.key&&this.activeIndex>-1?(e.preventDefault(),this._select(this.filteredCountries[this.activeIndex])):"Escape"===e.key&&this._toggle(!1))})),this.hasSearch&&(this.wrapper.querySelector(".cs-search-input").oninput=e=>{const t=e.target.value.toLowerCase();this.filteredCountries=this.countries.filter((e=>e.name.toLowerCase().includes(t)||e.phone.includes(t))),this.activeIndex=0,this._renderOptions()}),document.addEventListener("click",(e=>{this.wrapper.contains(e.target)||this._toggle(!1)})),document.addEventListener("cs-close-others",(e=>{e.detail.opener!==this.wrapper&&(this.isOpen=!1,this.wrapper.classList.remove("open"))}))}_scrollToActive(){const e=this.wrapper.querySelector(".cs-list"),t=e.querySelectorAll(".cs-option")[this.activeIndex];t&&(e.scrollTop=t.offsetTop-e.offsetHeight/2+this.rowHeight/2)}}document.querySelectorAll(".country-select").forEach((e=>new CountrySelect(e)));
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "country-select-pro",
3
+ "version": "4.8.2",
4
+ "description": "A lightweight, zero-dependency, vanilla JavaScript country selector with localized browser validation and Bootstrap 5 integration.",
5
+ "main": "dist/country-select.min.js",
6
+ "jsdelivr": "dist/country-select.min.js",
7
+ "unpkg": "dist/country-select.min.js",
8
+ "browser": "dist/country-select.min.js",
9
+ "exports": {
10
+ ".": "./dist/country-select.min.js"
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/nikmauro/country-select-pro.git"
18
+ },
19
+ "keywords": [
20
+ "country",
21
+ "dropdown",
22
+ "flags",
23
+ "select",
24
+ "international",
25
+ "vanilla-js"
26
+ ],
27
+ "scripts": {
28
+ "build": "gulp build"
29
+ },
30
+ "author": "Nikolaos Mavroidis",
31
+ "license": "MIT",
32
+ "bugs": {
33
+ "url": "https://github.com/nikmauro/country-select-pro/issues"
34
+ },
35
+ "homepage": "https://github.com/nikmauro/country-select-pro"
36
+ }