country-select-pro 6.1.4 → 6.2.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/README.md +162 -101
- package/dist/country-select.js +853 -402
- package/dist/country-select.min.js +2 -1
- package/package.json +13 -7
- package/dist/flags/1x1/null +0 -1
- package/dist/flags/4x3/null +0 -1
|
@@ -1 +1,2 @@
|
|
|
1
|
-
class CountrySelect{constructor(e,t={}){if(this.input=e,!this.input)return;if("1"===this.input.dataset.csInitialized)return;this.input.dataset.csInitialized="1",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";const i=this.input.dataset.preferred||"";this.preferredCodes=i?i.split(",").map(e=>e.trim().toUpperCase()):[],this.config={placeholder:this.input.dataset.placeholder||"Select",...t},this.countries=[],this.filteredCountries=[],this.isOpen=!1,this.activeIndex=-1,this.rowHeight=44,this.baseUrl="https://cdn.jsdelivr.net/gh/nikmauro/country-select-pro@6.1.3/",this._init()}async _init(){this._applyStyles(),this._setupDOM(),this._bindEvents(),await this._loadData()}_applyStyles(){const e="cs-v57-styles";if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent="\n.cs-no-results {\n padding: 10px;\n text-align: center;\n color: #999;\n cursor: default;\n font-style: italic;\n}\n\n.cs-flag-img {\n width: 22px !important; \n height: 16px !important; \n object-fit: cover; /* Ή contain, ανάλογα πώς φαίνεται καλύτερα */\n vertical-align: middle;\n margin-right: 8px;\n border-radius: 2px;\n display: inline-block;\n}\n \n .cs-wrapper { position: relative; font-family: inherit; width: 100%; outline: none; }\n .cs-trigger { \n /* Bootstrap 5 Exact Specs */\n padding: 0.375rem 2.25rem 0.375rem 0.75rem; \n font-size: 1rem;\n font-weight: 400;\n line-height: 1.5;\n color: #212529;\n background-color: #fff;\n background-clip: padding-box;\n border: 1px solid #ced4da;\n border-radius: 0.375rem;\n transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;\n display: flex; align-items: center; gap: 8px; cursor: pointer; \n min-height: calc(1.5em + 0.75rem + 2px); \n box-sizing: border-box; position: relative;\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3E%3C/svg%3E\");\n background-repeat: no-repeat; background-position: right 0.75rem center; background-size: 16px 12px;\n }\n \n .input-group > .cs-wrapper { flex: 1 1 auto; width: 1%; }\n .cs-wrapper.is-invalid .cs-trigger { border-color: #dc3545 !important; }\n .cs-error-msg { display: none; color: #dc3545; font-size: 0.825em; margin-top: 4px; position: absolute; left: 0; top: 100%; width: 100%; z-index: 10; }\n .cs-wrapper.is-invalid .cs-error-msg { display: block; }\n\n /* Focus state Bootstrap 5 */\n .cs-wrapper:focus-within .cs-trigger {\n border-color: #86b7fe;\n outline: 0;\n box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);\n }\n\n .flag-emoji {\n font-size: 1.2em; /* Για να φαίνεται πιο καθαρό το emoji */\n margin-right: 8px;\n }\n\n .cs-dropdown { \n position: absolute; left: 0; right: 0; background: #fff; \n border: 1px solid rgba(0,0,0,.15); border-radius: 0.375rem;\n z-index: 2050; display: none; margin-top: 0.125rem;\n box-shadow: 0 0.5rem 1rem rgba(0,0,0,.175);\n overflow: hidden; max-width: 95vw;\n }\n \n .cs-wrapper.drop-up .cs-dropdown { \n bottom: calc(100% + 0.25rem); top: auto;\n box-shadow: 0 -0.5rem 1rem rgba(0,0,0,.175);\n }\n .cs-wrapper.open .cs-dropdown { display: block; }\n \n .cs-search-box { padding: 8px; border-bottom: 1px solid #dee2e6; background: #f8f9fa; }\n .cs-search-input { \n width: 100%; padding: 0.375rem 0.75rem; border: 1px solid #ced4da; \n border-radius: 0.25rem; outline: none; font-size: 0.875rem;\n }\n .cs-list { overflow-y: auto; scrollbar-width: thin; scroll-behavior: auto; min-height: 50px; padding: 0.375rem 0; }\n .cs-option { \n padding: 0.5rem 0.75rem; display: flex; align-items: center; gap: 10px; \n cursor: pointer; font-size: 0.9rem; transition: background 0.1s;\n }\n .cs-option:hover { background-color: #f8f9fa; }\n .cs-option.active { background-color: #0d6efd; color: #fff; }\n \n .cs-wrapper img { width: 20px !important; height: 14px !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; line-height: 1; }\n .cs-divider { height: 1px; background: #dee2e6; margin: 0.375rem 0; pointer-events: none; }\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)}_updateActiveElement(){this.wrapper.querySelectorAll(".cs-option").forEach((e,t)=>{t===this.activeIndex?(e.classList.add("active"),e.scrollIntoView({block:"nearest"})):e.classList.remove("active")})}_updatePosition(){const e=this.wrapper.getBoundingClientRect(),t=this.rowLimit*this.rowHeight+(this.hasSearch?60:0),i=window.innerHeight-e.bottom,n=e.top;i<t&&n>t?this.wrapper.classList.add("drop-up"):this.wrapper.classList.remove("drop-up")}async _loadData(){try{const e=`${this.baseUrl}dist/data.json`,t=await fetch(e),i=await t.json(),n=i?.data?.objects||[];this.countries=n.map(e=>{const t=e.codes?.alpha_2?e.codes.alpha_2.toUpperCase():"";return{name:e.names?.common||"",code:t,flag:t?`${this.baseUrl}dist/flags/4x3/${t.toLowerCase()}.svg`:"",phone:e.calling_codes&&e.calling_codes.length>0?`+${e.calling_codes[0]}`:"",isPreferred:!!t&&this.preferredCodes.includes(t)}}).filter(e=>""!==e.code).sort((e,t)=>e.name.localeCompare(t.name)),this.filteredCountries=[...this.countries],this._renderOptions(),this._syncInitialValue()}catch(e){console.error("CountrySelect Load Fail:",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)}_parseTemplate(e,t){return e.replace("{img}",`<img src="${t.flag}" class="cs-flag-img" loading="lazy" alt="${t.name}">`).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");if(!e)return;if(e.innerHTML="",0===this.filteredCountries.length){const t=document.createElement("div");return t.className="cs-no-results",t.innerHTML='<span class="cs-no-results-text">Not found</span>',void e.appendChild(t)}const t=this.wrapper.querySelector(".cs-search-input")?.value||"",i=this.filteredCountries.filter(e=>e.isPreferred),n=this.filteredCountries.filter(e=>!e.isPreferred),s=(e,t)=>{const i=document.createElement("div");return i.className="cs-option "+(t===this.activeIndex?"active":""),i.innerHTML=this._parseTemplate(this.schema,e),i.onclick=t=>{t.stopPropagation(),this._select(e)},i};if(i.forEach((t,i)=>e.appendChild(s(t,i))),i.length>0&&n.length>0&&!t){const t=document.createElement("div");t.className="cs-divider",e.appendChild(t)}n.forEach((t,n)=>e.appendChild(s(t,i.length+n)))}_select(e){this._updateUI(e),this.input.value="phone"===this.valueType?e.phone:"name"===this.valueType?e.name:e.code,this.input.setCustomValidity(""),this.wrapper.classList.remove("is-invalid"),this.input.dispatchEvent(new Event("change",{bubbles:!0})),this.input.dispatchEvent(new Event("input",{bubbles:!0})),this.input.dispatchEvent(new Event("country-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))}_toggle(e){if(0!==this.countries.length){if(this.isOpen=void 0!==e?e:!this.isOpen,this.isOpen){this._updatePosition(),document.dispatchEvent(new CustomEvent("cs-close-others",{detail:{opener:this.wrapper}}));const e=this.wrapper.querySelector(".cs-list");0===e.children.length&&this._renderOptions(),e.style.maxHeight=this.rowLimit*this.rowHeight+"px";const t=[...this.filteredCountries.filter(e=>e.isPreferred),...this.filteredCountries.filter(e=>!e.isPreferred)];this.activeIndex=t.findIndex(e=>this.input.value.includes(e.code)||this.input.value.includes(e.phone)),this._updateActiveElement(),this.activeIndex>-1&&setTimeout(()=>this._scrollToActive(!0),0),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.wrapper.addEventListener("keydown",e=>{if(!this.isOpen&&"ArrowDown"===e.key)return e.preventDefault(),void this._toggle(!0);this.isOpen&&("ArrowDown"===e.key?(e.preventDefault(),this.activeIndex<this.filteredCountries.length-1&&(this.activeIndex++,this._updateActiveElement(),this._scrollToActive())):"ArrowUp"===e.key?(e.preventDefault(),this.activeIndex>0&&(this.activeIndex--,this._updateActiveElement(),this._scrollToActive())):"Escape"===e.key?this._toggle(!1):"Enter"===e.key&&(e.preventDefault(),this.activeIndex>=0&&this.activeIndex<this.filteredCountries.length&&this._select(this.filteredCountries[this.activeIndex])))}),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(e=!1){const t=this.wrapper.querySelector(".cs-list"),i=t.querySelectorAll(".cs-option")[this.activeIndex];if(!i)return;const n=i.getBoundingClientRect().top-t.getBoundingClientRect().top+t.scrollTop;e&&n+i.offsetHeight<=t.clientHeight?t.scrollTop=0:t.scrollTop=n-t.clientHeight/2+i.offsetHeight/2}}const initCS=e=>{const t=e&&e.querySelectorAll?e:document;t.matches?.(".country-select")&&"1"!==t.dataset.csInitialized&&new CountrySelect(t),t.querySelectorAll?.(".country-select").forEach(e=>{"1"!==e.dataset.csInitialized&&new CountrySelect(e)})},setupListeners=()=>{initCS(document),document.body.addEventListener("htmx:afterSettle",e=>{initCS(e.detail.target||e.target)}),new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{1===e.nodeType&&initCS(e)})})}).observe(document.body,{childList:!0,subtree:!0})};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",setupListeners):setupListeners();
|
|
1
|
+
/*! CountrySelect Pro v6.2.0 | MIT | https://github.com/nikmauro/country-select-pro */
|
|
2
|
+
!function(e){"use strict";if("undefined"==typeof document)return;if(e.CountrySelect&&e.CountrySelect.version)return;const t={en:{placeholder:"Select",searchPlaceholder:"Search...",noResults:"Not found",loading:"Loading...",loadError:"Could not load the list",results:"{n} results",listLabel:"Countries"},el:{placeholder:"Επιλέξτε",searchPlaceholder:"Αναζήτηση...",noResults:"Δεν βρέθηκε",loading:"Φόρτωση...",loadError:"Η λίστα δεν φορτώθηκε",results:"{n} αποτελέσματα",listLabel:"Χώρες"}},s={"+1":"US","+7":"RU","+44":"GB","+47":"NO","+61":"AU","+64":"NZ","+212":"MA","+262":"RE","+358":"FI","+500":"FK","+590":"GP","+599":"CW","+672":"NF"},i={GB:"uk britain england",US:"usa america",GR:"hellas ellada ελλαδα",CY:"kypros κυπρος",AE:"uae emirates",NL:"holland",CZ:"czech",KR:"south korea",KP:"north korea",DE:"deutschland",ES:"espana",CH:"schweiz suisse",VA:"vatican",CI:"cote d'ivoire",MK:"macedonia",TR:"turkey turkiye"},r="url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3E%3C/svg%3E\")",o=e=>null==e?"":String(e),a=e=>o(e).normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().trim(),n=e=>o(e).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[e])),l=e=>(Array.isArray(e)?e:o(e).split(",")).map(e=>o(e).trim().toUpperCase()).filter(Boolean),c=(e,t)=>null==e||""===e?t:!(!1===e||"false"===e||"0"===e||"no"===e),d=e=>{const t=o(e).replace(/\D/g,"").replace(/^00/,"");return t?"+"+t:""},h={};function p(e,t){return h[e]||(h[e]=fetch(e,t).then(t=>{if(!t.ok)throw new Error("HTTP "+t.status+" "+e);return t.json()}).catch(t=>{throw delete h[e],t})),h[e]}function u(e){if(!e)return[];if(Array.isArray(e))return e;if(e.data&&Array.isArray(e.data.objects))return e.data.objects;for(const t of["countries","items","data","results"])if(Array.isArray(e[t]))return e[t];return"object"==typeof e?Object.keys(e).map(t=>e[t]&&"object"==typeof e[t]?Object.assign({code:t},e[t]):{code:t,name:e[t]}):[]}function m(e){if(null==e||""===e)return null;"object"!=typeof e&&(e={code:e});const t=e.calling_codes||e.callingCodes,s=o(null!=e.name?e.name:null!=e.label?e.label:null!=e.text?e.text:e.names&&e.names.common).trim(),i={code:o(e.code||e.iso2||e.iso||e.alpha2||e.codes&&e.codes.alpha_2).trim().toUpperCase(),nameEn:s,fixedName:!(!s||e.names&&e.names.common),phone:d(e.phone||e.dial_code||e.dialCode||(Array.isArray(t)?t[0]:t))};null!=e.value&&""!==e.value&&(i.value=o(e.value)),"string"!=typeof e.flag&&!1!==e.flag||(i.flag=e.flag);const r=e.keywords||e.aliases;return r&&(i.keywords=Array.isArray(r)?r.join(" "):o(r)),i.code||i.value?i:null}const f=`.cs-wrapper{position:relative;display:block;width:100%;font-family:inherit;text-align:start;outline:none;color:var(--cs-color,var(--bs-body-color,#212529))}.cs-wrapper,.cs-wrapper *,.cs-wrapper *::before,.cs-wrapper *::after{box-sizing:border-box}.cs-trigger{position:relative;display:flex;align-items:center;gap:8px;cursor:pointer;min-height:calc(1.5em + .75rem + 2px);padding-block:.375rem;padding-inline:.75rem 2.25rem;font-size:var(--cs-font-size,1rem);font-weight:400;line-height:1.5;color:var(--cs-color,var(--bs-body-color,#212529));background-color:var(--cs-bg,var(--bs-body-bg,#fff));background-clip:padding-box;border:1px solid var(--cs-border-color,var(--bs-border-color,#ced4da));border-radius:var(--cs-radius,var(--bs-border-radius,.375rem));transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}.cs-trigger::after{content:"";position:absolute;inset-inline-end:.75rem;top:50%;width:16px;height:12px;margin-top:-6px;pointer-events:none;background-color:currentColor;-webkit-mask:${r}no-repeat center / 16px 12px;mask:${r}no-repeat center / 16px 12px;transition:transform .15s ease-in-out}.cs-wrapper.open .cs-trigger::after{transform:rotate(180deg)}.cs-wrapper:focus-within .cs-trigger{border-color:var(--cs-focus-border,#86b7fe);outline:0;box-shadow:0 0 0 .25rem var(--cs-focus-ring,var(--bs-focus-ring-color,rgba(13,110,253,.25)))}.cs-selected-content{display:flex;align-items:center;gap:8px;min-width:0;overflow:hidden;white-space:nowrap;line-height:1}.cs-selected-content.cs-placeholder{color:var(--cs-muted,var(--bs-secondary-color,#6c757d))}.input-group>.cs-wrapper{flex:1 1 auto;width:1%;min-width:0}.input-group>.cs-wrapper:not(:last-child) .cs-trigger{border-start-end-radius:0;border-end-end-radius:0}.input-group>* + .country-select + .cs-wrapper .cs-trigger{border-start-start-radius:0;border-end-start-radius:0}.cs-wrapper.is-invalid .cs-trigger,.is-invalid + .cs-wrapper .cs-trigger,.was-validated :invalid + .cs-wrapper .cs-trigger{border-color:var(--cs-invalid,var(--bs-form-invalid-border-color,#dc3545)) !important}.cs-error-msg{display:none;position:absolute;left:0;top:100%;width:100%;z-index:10;margin-top:4px;font-size:.825em;color:var(--cs-invalid,var(--bs-form-invalid-color,#dc3545))}.cs-wrapper.is-invalid .cs-error-msg:not(:empty){display:block}.cs-wrapper.cs-disabled .cs-trigger,:disabled + .cs-wrapper .cs-trigger{cursor:default;opacity:1;background-color:var(--cs-disabled-bg,var(--bs-secondary-bg,#e9ecef))}.cs-dropdown{position:absolute;left:0;right:0;z-index:var(--cs-z-index,2050);display:none;max-width:95vw;margin-top:.125rem;overflow:hidden;color:var(--cs-color,var(--bs-body-color,#212529));background:var(--cs-dropdown-bg,var(--cs-bg,var(--bs-body-bg,#fff)));border:1px solid var(--cs-dropdown-border-color,var(--bs-border-color-translucent,rgba(0,0,0,.15)));border-radius:var(--cs-radius,var(--bs-border-radius,.375rem));box-shadow:var(--cs-shadow,0 .5rem 1rem rgba(0,0,0,.175))}.cs-wrapper.drop-up .cs-dropdown{bottom:calc(100% + .25rem);top:auto;box-shadow:var(--cs-shadow-up,0 -.5rem 1rem rgba(0,0,0,.175))}.cs-wrapper.open .cs-dropdown{display:block}.cs-search-box{padding:8px;background:var(--cs-search-bg,var(--bs-tertiary-bg,#f8f9fa));border-bottom:1px solid var(--cs-divider-color,var(--bs-border-color,#dee2e6))}.cs-search-input{font-size:.875rem}.cs-wrapper input.cs-search-input{display:block;width:100%;height:auto;margin:0;padding:.375rem .75rem;font-family:inherit;line-height:1.5;outline:none;color:inherit;background:var(--cs-bg,var(--bs-body-bg,#fff));box-shadow:none;border:1px solid var(--cs-border-color,var(--bs-border-color,#ced4da));border-radius:.25rem}.cs-wrapper input.cs-search-input:focus{border-color:var(--cs-focus-border,#86b7fe);box-shadow:0 0 0 .2rem var(--cs-focus-ring,var(--bs-focus-ring-color,rgba(13,110,253,.25)))}@media (pointer:coarse){.cs-search-input{font-size:16px}}.cs-list{overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin;scroll-behavior:auto;min-height:50px;padding:.375rem 0}.cs-option{display:flex;align-items:center;gap:10px;padding:.5rem .75rem;font-size:.9rem;cursor:pointer;transition:background-color .1s}.cs-option:hover{background-color:var(--cs-hover-bg,var(--bs-tertiary-bg,#f8f9fa))}.cs-option[aria-selected="true"]{font-weight:600}.cs-option.active{background-color:var(--cs-active-bg,var(--bs-primary,#0d6efd));color:var(--cs-active-color,#fff)}.cs-divider{height:1px;margin:.375rem 0;pointer-events:none;background:var(--cs-divider-color,var(--bs-border-color,#dee2e6))}.cs-no-results,.cs-loading,.cs-load-error{padding:10px;text-align:center;font-style:italic;cursor:default;color:var(--cs-muted,var(--bs-secondary-color,#6c757d))}.cs-load-error{color:var(--cs-invalid,var(--bs-form-invalid-color,#dc3545))}.cs-flag-img{display:inline-block;width:22px !important;height:16px !important;object-fit:cover;vertical-align:middle;margin-inline-end:8px;border-radius:2px}.cs-wrapper img{width:20px !important;height:14px !important;object-fit:cover;border-radius:2px;flex-shrink:0}.cs-hidden{display:none !important}.cs-sr-only{position:absolute !important;width:1px !important;height:1px !important;padding:0 !important;margin:-1px !important;overflow:hidden !important;clip:rect(0,0,0,0) !important;white-space:nowrap !important;border:0 !important}@media (prefers-reduced-motion:reduce){.cs-trigger,.cs-trigger::after,.cs-option{transition:none}}@media (forced-colors:active){.cs-trigger::after{forced-color-adjust:none;background-color:CanvasText}.cs-option.active{forced-color-adjust:none;background-color:Highlight;color:HighlightText}}`;const g=new Set;let v=0,b=!1;class y{constructor(e,s){const i=s||{},r="string"==typeof e?document.querySelector(e):e;if(this.input=r,!r||!r.parentNode)return void("string"!=typeof e||r||console.warn("CountrySelect: element not found:",e));if(y._isLive(r)){if(!Object.keys(i).length)return r._countrySelect;r._countrySelect.destroy()}r._countrySelect&&r._countrySelect.destroy();const a=r.nextElementSibling;a&&a.classList.contains("cs-wrapper")&&a.remove(),r._countrySelect=this,r.dataset.csInitialized="1",g.add(this);const n=r.dataset,d=y.defaults,h=(e,t)=>void 0!==i[e]?i[e]:void 0!==n[t||e]?n[t||e]:d[e];this.options=i,this._id="cs"+ ++v,this._off=[],this.isSelect="SELECT"===r.tagName,this.schema=h("schema")||"{img} {name}",this.schemaReturn=h("schemaReturn")||this.schema,this.valueType=h("valueType")||"code",this.rowLimit=parseInt(h("rows","countryRowValues"),10)||5,this.hasSearch=c(h("search","countrySearch"),!0),this.dropdownWidth=h("dropdownWidth")||"auto",this.preferredCodes=l(h("preferredCountries","preferred")),this.onlyCodes=l(h("onlyCountries")),this.excludeCodes=l(h("excludeCountries")),this.defaultCountry=o(h("defaultCountry")).trim(),this.sort=c(h("sort"),!0),this.showFlags=c(h("flags"),!0);let p=o(h("lang"));var u;"auto"===p&&(p=document.documentElement.lang||navigator.language||""),this.lang=p,this.baseUrl=(u=h("baseUrl")||y.baseUrl)&&!/\/$/.test(u)?u+"/":u,this.flagPath=h("flagPath")||this.baseUrl+"dist/flags/4x3/{code}.svg",this.source=null!=h("countries")?h("countries"):h("dataUrl","src");const m=t[p.slice(0,2).toLowerCase()]||t.en,f=this.isSelect?Array.from(r.options).find(e=>""===e.value):null;this.config=Object.assign({},m,{placeholder:n.placeholder||d.placeholder||f&&f.text.trim()||m.placeholder,searchPlaceholder:n.searchPlaceholder||d.searchPlaceholder||m.searchPlaceholder,noResults:n.noResults||d.noResults||m.noResults},i),this.countries=[],this.filteredCountries=[],this.ordered=[],this._els=[],this.selected=null,this.isOpen=!1,this.activeIndex=-1,this.rowHeight=44,this.ready=this._init()}static _isLive(e){const t=e&&e._countrySelect;return!(!t||t._destroyed||"1"!==e.dataset.csInitialized||!t.wrapper||!t.wrapper.isConnected)}async _init(){return function(){if(!1===y.defaults.css||document.getElementById("cs-styles"))return;const e=document.createElement("style");e.id="cs-styles",e.textContent=f,document.head.appendChild(e)}(),this._setupDOM(),this._bindEvents(),await this._loadData(),this}_setupDOM(){const e=this.input,t=this._id,s=this.config;this._orig={style:e.getAttribute("style"),tabindex:e.getAttribute("tabindex")},Object.assign(e.style,{position:"absolute",opacity:"0",width:"1px",height:"1px",pointerEvents:"none"}),e.tabIndex=-1;const i=this.wrapper=document.createElement("div");i.className="cs-wrapper",i.tabIndex=0,i.setAttribute("role","combobox"),i.setAttribute("aria-haspopup","listbox"),i.setAttribute("aria-expanded","false"),i.setAttribute("aria-controls",t+"-list");const r=e.getAttribute("aria-labelledby"),o=e.getAttribute("aria-label")||(e.labels&&e.labels[0]?e.labels[0].textContent.trim():"");r?i.setAttribute("aria-labelledby",r):o&&i.setAttribute("aria-label",o),e.getAttribute("aria-describedby")&&i.setAttribute("aria-describedby",e.getAttribute("aria-describedby")),e.required&&i.setAttribute("aria-required","true"),i.innerHTML='<div class="cs-trigger"><span class="cs-selected-content"></span></div><div class="cs-error-msg"></div><div class="cs-dropdown"><div class="cs-search-box'+(this.hasSearch?"":" cs-hidden")+'"><input type="text" class="cs-search-input" autocomplete="off" autocapitalize="off" spellcheck="false" tabindex="-1" aria-autocomplete="list"></div><div class="cs-list" role="listbox" id="'+t+'-list"><div class="cs-loading">'+n(s.loading)+'</div></div></div><div class="cs-sr-only" aria-live="polite"></div>',this.contentEl=i.querySelector(".cs-selected-content"),this.dropdownEl=i.querySelector(".cs-dropdown"),this.searchEl=i.querySelector(".cs-search-input"),this.listEl=i.querySelector(".cs-list"),this.liveEl=i.querySelector(".cs-sr-only"),this.searchEl.placeholder=s.searchPlaceholder,this.searchEl.setAttribute("aria-label",s.searchPlaceholder),this.searchEl.setAttribute("aria-controls",t+"-list"),this.listEl.setAttribute("aria-label",o||s.listLabel),this.dropdownEl.style.width="auto"===this.dropdownWidth?"100%":this.dropdownWidth,e.value||this._showPlaceholder(),e.parentNode.insertBefore(i,e.nextSibling),document.activeElement===e&&i.focus({preventScroll:!0}),this._syncDisabled()}_bindEvents(){const e=this.wrapper,t=this.input,s=(e,t,s)=>{e.addEventListener(t,s),this._off.push(()=>e.removeEventListener(t,s))};s(e.querySelector(".cs-trigger"),"click",e=>{e.stopPropagation(),this.toggle()}),s(e,"keydown",e=>this._onKey(e)),s(this.searchEl,"input",()=>this._onSearch()),s(this.listEl,"click",e=>{const t=e.target.closest(".cs-option");if(!t)return;e.stopPropagation();const s=this.ordered[+t.dataset.index];s&&this._choose(s)});const i=()=>{this._emitting||this._syncFromInput()};s(t,"change",i),s(t,"input",i),s(t,"invalid",()=>{e.classList.add("is-invalid"),e.setAttribute("aria-invalid","true")}),t.form&&s(t.form,"reset",()=>setTimeout(()=>{e.classList.remove("is-invalid"),e.removeAttribute("aria-invalid"),this._syncFromInput()},0)),Array.from(t.labels||[]).forEach(t=>s(t,"click",t=>{e.contains(t.target)||(t.preventDefault(),this._isDisabled()||e.focus())})),this._mo=new MutationObserver(e=>{this._syncDisabled(),this.isSelect&&e.some(e=>"childList"===e.type)&&this._loadData()}),this._mo.observe(t,{attributes:!0,attributeFilter:["disabled","readonly"],childList:this.isSelect}),b||(b=!0,document.addEventListener("click",e=>{g.forEach(t=>{if(!t.input.isConnected)return t.destroy();t.isOpen&&!t.wrapper.contains(e.target)&&t.close()})}))}async _loadData(){const e=this._loadToken=(this._loadToken||0)+1;try{const t=await this._getItems();if(e!==this._loadToken||this._destroyed)return;if(this.close(),this._build(t),!this.input.value&&this.defaultCountry){const e=this.defaultCountry,t=this.countries.find(t=>t.code===e.toUpperCase())||this._find(e);t&&(this.input.value=this._valueOf(t))}this._renderOptions(),this._syncFromInput()}catch(e){console.error("CountrySelect Load Fail:",e),this._destroyed||(this.listEl.innerHTML='<div class="cs-load-error">'+n(this.config.loadError)+"</div>")}}_base(){return p(this.baseUrl+"dist/data.json").then(e=>u(e).map(m).filter(e=>e&&e.code))}async _getItems(){let e=null,t=this.source;if(this.isSelect)e=Array.from(this.input.options).filter(e=>""!==e.value).map(e=>({value:e.value,code:e.dataset.code||("code"===this.valueType?e.value:""),phone:e.dataset.phone||("phone"===this.valueType?e.value:""),name:e.text.trim(),flag:e.dataset.flag}));else if(null!=t&&""!==t){if("function"==typeof t&&(t=await t()),"string"==typeof t){const e=t.trim();t="["===e[0]||"{"===e[0]?JSON.parse(e):await p(e,this.options.fetchOptions)}e=u(await t)}if(!e)return(await this._base()).map(e=>Object.assign({},e));const s=e.map(m).filter(Boolean),i="phone"===this.valueType||/\{phone\}/.test(this.schema+this.schemaReturn);if(c(this.options.merge,!0)&&s.some(e=>e.code&&(!e.nameEn||i&&!e.phone))){const e=await this._base().catch(()=>[]),t={};e.forEach(e=>{t[e.code]=e}),s.forEach(e=>{const s=t[e.code];s&&(e.nameEn||(e.nameEn=s.nameEn),e.phone||(e.phone=s.phone))})}return s.forEach(e=>{e.nameEn||(e.nameEn=e.code||e.value)}),s}_build(e){let t=null,s=null;if(this.lang){try{t=new Intl.DisplayNames([this.lang],{type:"region",fallback:"none"})}catch(e){}try{s=new Intl.Collator(this.lang)}catch(e){}}const r=this.onlyCodes,o=this.excludeCodes,n=this.preferredCodes;let l=e.filter(e=>(!r.length||r.includes(e.code))&&!o.includes(e.code)).map(e=>{let s=e.nameEn;if(t&&e.code&&!e.fixedName)try{s=t.of(e.code)||s}catch(e){}let r="";var o;return this.showFlags&&!1!==e.flag&&(r="string"==typeof e.flag?e.flag:(o=e.code,/^[a-z]{2}(-[a-z]{2,4})?$/i.test(o)?this.flagPath.split("{code}").join(e.code.toLowerCase()).split("{CODE}").join(e.code):"")),{code:e.code,name:s,nameEn:e.nameEn,phone:e.phone||"",flag:r,value:e.value,isPreferred:!!e.code&&n.includes(e.code),_search:a([s,e.nameEn,e.code,i[e.code],e.keywords].join(" "))}});this.sort&&l.sort((e,t)=>s?s.compare(e.name,t.name):e.name.localeCompare(t.name)),this.countries=l,this.filteredCountries=l.slice(),this._filtered=!1}_valueOf(e){return null!=e.value?e.value:"phone"===this.valueType?e.phone:"name"===this.valueType?e.nameEn:e.code}_find(e){const t=o(e).trim();if(!t)return null;const i=this.countries,r=this.selected;if(r&&this._valueOf(r)===t)return r;const n=i.find(e=>null!=e.value&&e.value===t);if(n)return n;if("phone"===this.valueType){const e=d(t),r=i.filter(t=>t.phone===e);if(r.length<2)return r[0]||null;for(const e of this.preferredCodes){const t=r.find(t=>t.code===e);if(t)return t}return r.find(t=>t.code===s[e])||r[0]}if("name"===this.valueType){const e=a(t);return i.find(t=>a(t.nameEn)===e||a(t.name)===e)||null}const l=t.toUpperCase();return i.find(e=>e.code===l)||i.find(e=>null!=e.value&&e.value.toUpperCase()===l)||null}_parseTemplate(e,t){const s=t.flag?'<img src="'+n(t.flag)+'" class="cs-flag-img" width="20" height="14" loading="lazy" decoding="async" alt="'+(e.indexOf("{name}")>-1?"":n(t.name))+'">':"";return e.split("{img}").join(s).split("{name}").join("<span>"+n(t.name)+"</span>").split("{code}").join("<span>"+n(t.code)+"</span>").split("{phone}").join("<span>"+n(t.phone)+"</span>")}_showPlaceholder(){this.contentEl.classList.add("cs-placeholder"),this.contentEl.innerHTML=this.config.placeholder}_setSelected(e){this.selected=e||null,e?(this.contentEl.classList.remove("cs-placeholder"),this.contentEl.innerHTML=this._parseTemplate(this.schemaReturn,e)):this._showPlaceholder(),this._els.forEach((e,t)=>e.setAttribute("aria-selected",this.ordered[t]===this.selected?"true":"false"))}_syncFromInput(){this.countries.length&&this._setSelected(this._find(this.input.value))}_renderOptions(){const e=this.listEl,t=[],s=[];if(this.filteredCountries.forEach(e=>(e.isPreferred?t:s).push(e)),this.ordered=t.concat(s),this._els=[],e.textContent="",!this.ordered.length)return void(e.innerHTML='<div class="cs-no-results"><span class="cs-no-results-text">'+n(this.config.noResults)+"</span></div>");const i=document.createDocumentFragment(),r=!!this.searchEl.value.trim();this.ordered.forEach((e,s)=>{if(s===t.length&&s>0&&!r){const e=document.createElement("div");e.className="cs-divider",e.setAttribute("aria-hidden","true"),i.appendChild(e)}const o=document.createElement("div");o.className="cs-option"+(s===this.activeIndex?" active":""),o.id=this._id+"-o"+s,o.setAttribute("role","option"),o.setAttribute("aria-selected",e===this.selected?"true":"false"),o.dataset.index=s,o.innerHTML=this._parseTemplate(this.schema,e),i.appendChild(o),this._els.push(o)}),e.appendChild(i)}_updateActive(){this._els.forEach((e,t)=>e.classList.toggle("active",t===this.activeIndex));const e=this.isOpen?this._els[this.activeIndex]:null;[this.wrapper,this.searchEl].forEach(t=>e?t.setAttribute("aria-activedescendant",e.id):t.removeAttribute("aria-activedescendant"))}_updatePosition(){const e=this.wrapper.getBoundingClientRect(),t=this.rowLimit*this.rowHeight+(this.hasSearch?60:0),s=window.innerHeight-e.bottom;this.wrapper.classList.toggle("drop-up",s<t&&e.top>t)}_itemTop(e){return e.getBoundingClientRect().top-this.listEl.getBoundingClientRect().top+this.listEl.scrollTop}_scrollToActive(){const e=this.listEl,t=this._els[this.activeIndex];if(!t)return void(e.scrollTop=0);const s=this._itemTop(t);e.scrollTop=s+t.offsetHeight<=e.clientHeight?0:s-e.clientHeight/2+t.offsetHeight/2}_scrollNearest(){const e=this.listEl,t=this._els[this.activeIndex];if(!t)return;if(0===this.activeIndex)return void(e.scrollTop=0);if(this.activeIndex===this._els.length-1)return void(e.scrollTop=e.scrollHeight);const s=this._itemTop(t),i=s+t.offsetHeight;s<e.scrollTop?e.scrollTop=s:i>e.scrollTop+e.clientHeight&&(e.scrollTop=i-e.clientHeight)}_announce(e){clearTimeout(this._liveTimer),this._liveTimer=setTimeout(()=>{this.liveEl.textContent=e},400)}_isDisabled(){return this.input.disabled||this.input.matches(":disabled")}_syncDisabled(){const e=this._isDisabled(),t=this.wrapper;t&&(t.classList.toggle("cs-disabled",e),t.tabIndex=e?-1:0,e?t.setAttribute("aria-disabled","true"):t.removeAttribute("aria-disabled"),this.input.readOnly?t.setAttribute("aria-readonly","true"):t.removeAttribute("aria-readonly"),e&&this.close())}_onSearch(){const e=this.searchEl.value.trim(),t=a(e);let i=this.countries;if(t){const r=/^\+?[\d\s().-]*$/.test(e),o=e.replace(/\D/g,""),a=s["+"+o],n=r?e=>!e.phone||e.phone.indexOf(o)<0?-1:e.phone==="+"+o?e.code===a?0:1:0===e.phone.indexOf("+"+o)?2:3:e=>{const s=" "+e._search+" ";return s.indexOf(t)<0?-1:s.indexOf(" "+t+" ")>-1?0:s.indexOf(" "+t)>-1?1:2};i=i.map((e,t)=>[n(e),t,e]).filter(e=>e[0]>-1).sort((e,t)=>e[0]-t[0]||e[1]-t[1]).map(e=>e[2])}this.filteredCountries=i===this.countries?i.slice():i,this._filtered=!!t,this.activeIndex=i.length?0:-1,this._renderOptions(),this.listEl.scrollTop=0,this._updateActive(),this._announce(t?this.config.results.replace("{n}",i.length):"")}_move(e){e<0||e>=this.ordered.length||(this.activeIndex=e,this._updateActive(),this._scrollNearest())}_onKey(e){if(e.isComposing||229===e.keyCode)return;if(this._isDisabled()||this.input.readOnly)return;const t=e.key,s=e.target===this.searchEl,i=1===t.length&&" "!==t&&!e.ctrlKey&&!e.metaKey&&!e.altKey;if(!this.isOpen){if(e.target!==this.wrapper)return;return void(["ArrowDown","ArrowUp","Enter"," ","Home","End"].indexOf(t)>-1?(e.preventDefault(),this.open(),"Home"===t?this._move(0):"End"===t&&this._move(this.ordered.length-1)):i&&this.hasSearch&&this.open())}const r=this.ordered.length-1;switch(t){case"ArrowDown":e.preventDefault(),this._move(Math.min(this.activeIndex+1,r));break;case"ArrowUp":e.preventDefault(),this._move(Math.max(this.activeIndex-1,0));break;case"PageDown":e.preventDefault(),this._move(Math.min(this.activeIndex+this.rowLimit,r));break;case"PageUp":e.preventDefault(),this._move(Math.max(this.activeIndex-this.rowLimit,0));break;case"Home":case"End":if(s)break;e.preventDefault(),this._move("Home"===t?0:r);break;case" ":if(s)break;case"Enter":e.preventDefault(),this.ordered[this.activeIndex]&&this._choose(this.ordered[this.activeIndex]);break;case"Escape":e.preventDefault(),e.stopPropagation(),this.close(!0);break;case"Tab":this.close();break;default:i&&this.hasSearch&&!s&&this.searchEl.focus()}}_apply(e,t){this.input.value=e?this._valueOf(e):"",this._setSelected(e),this.input.setCustomValidity(""),this.wrapper.classList.remove("is-invalid"),this.wrapper.removeAttribute("aria-invalid"),t||this._emit()}_choose(e){this._apply(e),this.close(!0)}_emit(){const e=this.input;this._emitting=!0;try{e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new CustomEvent("country-change",{bubbles:!0,detail:{value:e.value,country:this.getCountry()}}))}finally{this._emitting=!1}}open(){this.isOpen||this._destroyed||!this.countries.length||this._isDisabled()||this.input.readOnly||(g.forEach(e=>{e!==this&&e.isOpen&&e.close()}),document.dispatchEvent(new CustomEvent("cs-close-others",{detail:{opener:this.wrapper}})),(this._filtered||this.searchEl.value)&&(this.searchEl.value="",this.filteredCountries=this.countries.slice(),this._filtered=!1,this._renderOptions()),this._updatePosition(),this.listEl.style.maxHeight=this.rowLimit*this.rowHeight+"px",this.isOpen=!0,this.wrapper.classList.add("open"),this.wrapper.setAttribute("aria-expanded","true"),this.activeIndex=this.selected?this.ordered.indexOf(this.selected):-1,this._updateActive(),this._scrollToActive(),this.hasSearch&&this.searchEl.focus({preventScroll:!0}))}close(e){this.isOpen&&(this.isOpen=!1,this.wrapper.classList.remove("open"),this.wrapper.setAttribute("aria-expanded","false"),this._updateActive(),e&&this.wrapper.focus({preventScroll:!0}))}toggle(){this.isOpen?this.close(!0):this.open()}_toggle(e){void 0===e?this.toggle():e?this.open():this.close()}setValue(e,t){return this.countries.length?(this._apply(this._find(e),!(!t||!t.silent)),this):(this.input.value=o(e),this)}getValue(){return this.input.value}getCountry(){const e=this.selected;return e?{code:e.code,name:e.nameEn,localName:e.name,phone:e.phone,value:this._valueOf(e)}:null}setCountries(e){return this.source=e,this._loadData()}refresh(){return this._syncFromInput(),this}destroy(){if(this._destroyed)return;this.close(),this._destroyed=!0,this._off.forEach(e=>e()),this._off=[],this._mo&&this._mo.disconnect(),clearTimeout(this._liveTimer),g.delete(this),this.wrapper&&this.wrapper.parentNode&&this.wrapper.remove();const e=this.input;e._countrySelect===this&&delete e._countrySelect,delete e.dataset.csInitialized,this._orig&&(null==this._orig.style?e.removeAttribute("style"):e.setAttribute("style",this._orig.style),null==this._orig.tabindex?e.removeAttribute("tabindex"):e.setAttribute("tabindex",this._orig.tabindex))}}y.version="6.2.0",y.baseUrl="https://cdn.jsdelivr.net/gh/nikmauro/country-select-pro@6.1.3/",y.defaults=Object.assign({},e.CountrySelectConfig),y.defaults.baseUrl&&(y.baseUrl=y.defaults.baseUrl);const w=e=>{const t=e&&e.querySelectorAll?e:document,s=[];t.matches&&t.matches(".country-select")&&s.push(t),t.querySelectorAll(".country-select").forEach(e=>s.push(e)),s.forEach(e=>{"INPUT"!==e.tagName&&"SELECT"!==e.tagName||y._isLive(e)||new y(e)})};function _(){w(document),document.addEventListener("htmx:afterSettle",e=>w(e.detail&&e.detail.target||e.target)),new MutationObserver(e=>{e.forEach(e=>e.addedNodes.forEach(e=>{1!==e.nodeType||e.closest(".cs-wrapper")||w(e)}))}).observe(document.documentElement,{childList:!0,subtree:!0})}y.init=w,y.getInstance=e=>{const t="string"==typeof e?document.querySelector(e):e;return t&&y._isLive(t)?t._countrySelect:null},e.CountrySelect=y,e.initCS||(e.initCS=w),"object"==typeof module&&module.exports&&(module.exports=y),!1!==y.defaults.autoInit&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",_):_())}("undefined"!=typeof window?window:this);
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "country-select-pro",
|
|
3
|
-
"version": "6.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "6.2.0",
|
|
4
|
+
"description": "Lightweight, zero-dependency vanilla JS country selector: flags, phone codes, search, custom lists, ARIA, Bootstrap 5 or plain CSS.",
|
|
5
5
|
"main": "dist/country-select.js",
|
|
6
|
-
"jsdelivr": "dist/country-select.js",
|
|
7
|
-
"unpkg": "dist/country-select.js",
|
|
6
|
+
"jsdelivr": "dist/country-select.min.js",
|
|
7
|
+
"unpkg": "dist/country-select.min.js",
|
|
8
8
|
"browser": "dist/country-select.js",
|
|
9
9
|
"exports": {
|
|
10
10
|
".": "./dist/country-select.js"
|
|
@@ -14,18 +14,24 @@
|
|
|
14
14
|
],
|
|
15
15
|
"repository": {
|
|
16
16
|
"type": "git",
|
|
17
|
-
"url": "https://github.com/nikmauro/country-select-pro.git"
|
|
17
|
+
"url": "git+https://github.com/nikmauro/country-select-pro.git"
|
|
18
18
|
},
|
|
19
19
|
"keywords": [
|
|
20
20
|
"country",
|
|
21
|
+
"country-select",
|
|
22
|
+
"country-picker",
|
|
21
23
|
"dropdown",
|
|
22
24
|
"flags",
|
|
25
|
+
"phone-code",
|
|
23
26
|
"select",
|
|
24
|
-
"
|
|
27
|
+
"bootstrap",
|
|
28
|
+
"htmx",
|
|
29
|
+
"accessible",
|
|
25
30
|
"vanilla-js"
|
|
26
31
|
],
|
|
27
32
|
"scripts": {
|
|
28
|
-
"build": "gulp build"
|
|
33
|
+
"build": "gulp build",
|
|
34
|
+
"prepublishOnly": "npm run build"
|
|
29
35
|
},
|
|
30
36
|
"author": "Nikolaos Mavroidis",
|
|
31
37
|
"license": "MIT",
|
package/dist/flags/1x1/null
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
|
package/dist/flags/4x3/null
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
|