@countriesdb/widget 0.1.34 → 0.1.35
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/dist/index.esm.js +50 -2
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/initialization.js +51 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).CountriesWidget=t()}(this,function(){"use strict";class e{static async fetchCountries(e){const{apiKey:t,backendUrl:a,shouldUseGeoIP:i=!0,isoCountryNames:n=!1,languageHeaders:o={}}=e,s=`${a}/api/countries`,r=[];i||r.push("no_geoip=1"),n&&r.push("country_name_source=iso");const l=r.length?`${s}?${r.join("&")}`:s;return this.fetchFromApi(l,t,o)}static async fetchSubdivisions(e){const{apiKey:t,backendUrl:a,countryCode:i,shouldUseGeoIP:n=!0,preferOfficial:o=!1,subdivisionRomanizationPreference:s,preferLocalVariant:r=!1,languageHeaders:l={}}=e;if(!i)return{data:[],language:null};const d=`${a}/api/countries/${i}/subdivisions`,u=[];n||u.push("no_geoip=1"),s&&u.push(`subdivision_romanization_preference=${encodeURIComponent(s)}`),r&&u.push("prefer_local_variant=1"),o&&u.push("prefer_official=1");const c=u.length?`${d}?${u.join("&")}`:d;return this.fetchFromApi(c,t,l)}static async fetchFromApi(e,t,a){try{const i=await fetch(e,{headers:{...a,"X-API-KEY":t,"Content-Type":"application/json"}});if(!i.ok){let e=`HTTP Error: ${i.status}`;try{const t=await i.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const n=await i.json();return{data:n,language:i.headers.get("X-Selected-Language")||null}}catch(t){throw console.error(`Failed to fetch data from ${e}:`,t),t}}static getLanguageHeaders(e,t){const a={};return e&&(a["X-Forced-Language"]=e),t&&(a["X-Default-Language"]=t),"undefined"!=typeof navigator&&navigator.language?a["Accept-Language"]=navigator.language:a["Accept-Language"]="en",a}}function t(e,a,i,n,o,s,r){let l="";const d=e.map(e=>{let t=e[n]||e.name;const a=e.code?e.code.split("-")[0]:null;if(r&&"function"==typeof r){const i=r(e.code,t,o,a,e);if(!1===i)return null;null!=i&&(t=i)}return{...e,_displayName:t}}).filter(e=>null!==e),u=r&&"function"==typeof r&&o?o:void 0;d.sort((e,t)=>u?e._displayName.localeCompare(t._displayName,u,{sensitivity:"accent",ignorePunctuation:!1}):e._displayName.localeCompare(t._displayName));const c=a>0?i[a]??" ".repeat(2*a):"",f=`subdivision-level-${a}`;for(const e of d){const d=e.children&&e.children.length>0,u=`${c}${e._displayName}`;d?(l+=s?`<option value="${e.code}" class="${f}">${u}</option>`:`<option disabled value="${e.code}" class="${f}">${u}</option>`,l+=t(e.children,a+1,i,n,o,s,r)):l+=`<option value="${e.code}" class="${f}">${u}</option>`}return l}function a(e,t="Not Applicable",a=!1){if(e.hasAttribute("multiple"))e.innerHTML="",void 0!==e.dataset.label&&delete e.dataset.label,void 0!==e.dataset.defaultValue&&delete e.dataset.defaultValue;else{const a=e.dataset.label,i=e.dataset.defaultValue,n=a||t,o=i??"";e.innerHTML=`<option value="${o}">${n}</option>`,void 0!==a&&(e.dataset.label=a),void 0!==i&&(e.dataset.defaultValue=i)}a&&(e.disabled=!0)}function i(e,t,a,i){let n=function(e,t,a){return t&&"function"==typeof t?e.map(e=>{const i=t(e.iso_alpha_2,e.name,a,e);if(!1===i)return null;const n=null!=i?i:e.name;return{...e,_displayName:n}}).filter(e=>null!==e):e.map(e=>({...e,_displayName:e.name}))}(t,i,a);i&&(n=function(e,t){const a=t;return[...e].sort((e,t)=>e._displayName.localeCompare(t._displayName,a,{sensitivity:"accent",ignorePunctuation:!1}))}(n,a));if(e.hasAttribute("multiple")||e.multiple)e.innerHTML="";else{const t=e.querySelector('option[value=""]')||(e.dataset.defaultValue?e.querySelector(`option[value="${e.dataset.defaultValue}"]`):null),a=e.dataset.defaultValue??"";e.innerHTML=t?t.outerHTML:`<option value="${a}">${e.dataset.label||"—"}</option>`}n.forEach(t=>{const a=document.createElement("option");a.value=t.iso_alpha_2,a.textContent=t._displayName,e.appendChild(a)})}function n(e,a,i,n,o,s){const r=function(e){const t={},a=[];return e.forEach(e=>{t[e.id]={...e,children:[]}}),e.forEach(e=>{const i=t[e.id];e.parent_id&&t[e.parent_id]?t[e.parent_id].children.push(i):a.push(i)}),a}(e),l={};for(let e=1;e<=10;e++){const t=`nested${e}Prefix`,i=a.dataset[t];if(void 0===i)break;l[`nested${e}Prefix`]=i}const d=function(e){const t={};for(let a=1;a<=10;a++){const i=e[`nested${a}Prefix`];if(void 0===i)break;t[a]=i}return t}(l),u=n?"full_name":"name";let c="";if(!a.hasAttribute("multiple")){const e=a.dataset.label||"—";c=`<option value="${a.dataset.defaultValue??""}">${e}</option>`}return c+=t(r,0,d,u,i,o,s),c}function o(e,t){const a=e.dataset._widgetTempPreselect,i=e.getAttribute("data-preselected")||e.dataset.preselected,n=null!=a&&""!==String(a).trim()?a:i;if(!n||"string"==typeof n&&""===n.trim())return;const o=String(n);if(e.hasAttribute("multiple")){const t=o.split(",").map(e=>e.trim()).filter(e=>""!==e);Array.from(e.options).forEach(e=>{e.selected=t.includes(e.value)})}else e.value=o;void 0!==e.dataset._widgetTempPreselect&&delete e.dataset._widgetTempPreselect,null!=i&&""!==String(i).trim()&&(e.dataset._widgetPreselectedConsumed="1")}function s(e,t,a=!1){const i=t instanceof Error?t.message:t,n=e.dataset.defaultValue??"",o=i.startsWith("Error: ")?i:`Error: ${i}`;a?e.innerHTML=`<option value="${n}" disabled>${o}</option>`:e.innerHTML+=`<option value="${n}" disabled>${o}</option>`}function r(e,t={}){let a=[];a=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[];const i=new CustomEvent("countriesWidget:update",{bubbles:!0,detail:{value:e.value||"",selectedValues:a,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),...t}});e.dispatchEvent(i)}function l(e,t={}){const a=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[],i=new CustomEvent("countriesWidget:ready",{bubbles:!0,detail:{value:e.value||"",selectedValues:a,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),type:e.classList.contains("subdivision-selection")?"subdivision":"country",phase:"initial",...t}});e.dispatchEvent(i)}function d(e){return!0===e.isWidgetInitiated}async function u(e,t,a,i,n,o,s,l){if(!n&&!o)return;const d=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!d||d.multiple)return;const u=i.subdivisionsMap.get(e);if(!u)return;if(o&&e.multiple)return;const c=e.value;if(!c)return;const f=u.find(e=>e.code===c);if(f){if(n&&f.related_country_code){const e=f.related_country_code,a=f.related_subdivision_code,i=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);i&&a&&(i.dataset._widgetTempPreselect=a),d.value!==e?(d.value=e,r(d,{type:"country",reason:"regular"}),l?await l(d,t):i&&await s(i,t,e)):i&&a&&await s(i,t,e)}if(o&&f.is_subdivision_of){const e=f.is_subdivision_of.parent_country_code,a=f.is_subdivision_of.subdivision_code;if(a){const e=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);e&&!e.multiple&&(e.dataset._widgetTempPreselect=a)}if(d.value!==e)if(d.value=e,r(d,{type:"country",reason:"regular"}),l)await l(d,t);else{const a=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);a&&await s(a,t,e)}else if(a){const a=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);a&&!a.multiple&&await s(a,t,e)}}}}async function c(e,t,a,i,n,o){if(!n)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const l=i.subdivisionsMap.get(e);if(!l)return;const d=e.multiple?e.selectedOptions[0]?.value||null:e.value;if(!d)return;const u=l.find(e=>e.code===d);if(!u||!u.related_country_code)return;const c=u.related_country_code,f=u.related_subdivision_code,p=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);p&&f&&(p.dataset.preselected=f),s.value!==c?(s.value=c,r(s,{type:"country",reason:"regular"}),p&&await o(p,t,c)):p&&f&&await o(p,t,c)}async function f(e,t,a,i,n,o){if(!n)return;if(e.multiple)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const l=i.subdivisionsMap.get(e);if(!l)return;const d=e.value;if(!d)return;const u=l.find(e=>e.code===d);if(!u||!u.is_subdivision_of)return;const c=u.is_subdivision_of.parent_country_code,f=u.is_subdivision_of.subdivision_code;if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&(e.dataset.preselected=f)}if(s.value!==c){s.value=c,r(s,{type:"country",reason:"follow"});const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}else if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}}async function p(e,t,a,i,n,o){if(!n||e.multiple)return;const s=i.countriesMap.get(e);if(!s)return;const l=e.value;if(!l)return;const d=s.find(e=>e.iso_alpha_2===l);if(!d||!d.is_subdivision_of)return;const u=d.is_subdivision_of.parent_country_code,c=d.is_subdivision_of.subdivision_code;if(e.value!==u){if(c){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of t)e.multiple||(e.dataset.preselected=c)}e.value=u,r(e,{type:"country",reason:"regular"});const a=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of a)await o(e,t,u)}else if(c){const a=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of a)e.multiple||await o(e,t,u)}}async function m(t,i,d,c,f,p){const v=t.getAttribute("data-preselected")||t.dataset.preselected,g=c.subdivisionsMap.has(t);a(t,"—",!0),c.isInitializing.add(t);let w=p;if(w||(w=t.dataset.countryCode||""),w){let a=!1;try{const s=null==v,l=!!t.hasAttribute("data-prefer-official")||f.preferOfficialSubdivisions,p=e.getLanguageHeaders(f.forcedLanguage,f.defaultLanguage),b=await e.fetchSubdivisions({apiKey:i,backendUrl:d,countryCode:w,shouldUseGeoIP:s,preferOfficial:l,subdivisionRomanizationPreference:f.subdivisionRomanizationPreference,preferLocalVariant:f.preferLocalVariant,languageHeaders:p}),h=b.data,_=b.language||"en";if(c.subdivisionsMap.set(t,h),c.subdivisionsLanguageMap.set(t,_),h.length>0){t.disabled=!1;const e=t.hasAttribute("multiple"),l=e?void 0:t.dataset.label,p=e?void 0:t.dataset.defaultValue,v=t.value,w=t.dataset.defaultValue||"",b=v&&v!==w&&""!==v.trim();t.innerHTML=n(h,t,_,f.showSubdivisionType,f.allowParentSelection,f.subdivisionNameFilter),e||(void 0!==l&&(t.dataset.label=l),void 0!==p&&(t.dataset.defaultValue=p));let S=!1;if(b&&!e){Array.from(t.options).some(e=>e.value===v)&&(t.value=v,S=!0)}if(!S){const e=void 0!==(t.getAttribute("data-preselected")||t.dataset.preselected||t.dataset._widgetTempPreselect),n="1"===t.dataset._widgetPreselectedConsumed;if(!e||n&&g){if(s){const e=h.find(e=>e.preselected);if(e){if(t.hasAttribute("multiple")){const a=Array.from(t.options).find(t=>t.value===e.code);a&&(a.selected=!0)}else t.value=e.code;r(t,{type:"subdivision",reason:"geoip"}),a=!0,await u(t,i,0,c,f.followRelated,f.followUpward,(e,t,a)=>m(e,t,d,c,f,a),(e,t)=>y(e,t,d,c,f))}}}else o(t),r(t,{type:"subdivision",reason:"preselected"}),a=!0,await u(t,i,0,c,f.followRelated,f.followUpward,(e,t,a)=>m(e,t,d,c,f,a),(e,t)=>y(e,t,d,c,f))}}else t.disabled=!0}catch(e){console.error("Failed to fetch subdivisions:",e),s(t,e)}finally{c.isInitializing.delete(t),l(t,{type:"subdivision",phase:g?"reload":"initial"}),g&&!a&&r(t,{type:"subdivision",reason:"reload"})}}else if(!t.dataset.country||!document.querySelector(`.country-selection[data-name="${t.dataset.country}"]`)){const e=t.dataset.defaultValue??"";t.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}}function v(e,t){const a="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let i=null;try{const e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null;e&&e.src&&(i=new URL(e.src))}catch{}const n=e=>{if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)};return{followRelated:void 0!==a?.followRelated?a.followRelated:n(i?.searchParams.get("follow_related")??"false"),followUpward:void 0!==a?.followUpward?a.followUpward:n(i?.searchParams.get("follow_upward")??"false"),showSubdivisionType:void 0!==a?.showSubdivisionType?a.showSubdivisionType:n(i?.searchParams.get("show_subdivision_type")??"1"),allowParentSelection:void 0!==a?.allowParentSelection?a.allowParentSelection:n(i?.searchParams.get("allow_parent_selection")??"false"),preferOfficialSubdivisions:void 0!==a?.preferOfficialSubdivisions?a.preferOfficialSubdivisions:n(i?.searchParams.get("prefer_official")??"false"),subdivisionRomanizationPreference:a?.subdivisionRomanizationPreference||i?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==a?.preferLocalVariant?a.preferLocalVariant:n(i?.searchParams.get("prefer_local_variant")??"false"),forcedLanguage:a?.forcedLanguage||i?.searchParams.get("forced_language")||void 0,defaultLanguage:a?.defaultLanguage||i?.searchParams.get("default_language")||void 0,subdivisionNameFilter:a?.subdivisionNameFilter}}async function y(e,t,a,i,n){if(e.hasAttribute("multiple"))return;const o=e.value,s=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of s)await m(e,t,a,i,n,o)}const g="__CountriesWidgetNS__";async function w(t={}){window[g]||(window[g]={initialized:!1,initPromise:null,version:0,eventHandlers:new WeakMap});const n=window[g];n.eventHandlers||(n.eventHandlers=new WeakMap);if(!0===t.reload&&(n.initialized=!1,n.initPromise=null,"undefined"!=typeof document)){document.querySelectorAll(".subdivision-selection").forEach(e=>{e.dataset._widgetPreselectedConsumed&&delete e.dataset._widgetPreselectedConsumed})}return n.initPromise=(async()=>{"loading"===document.readyState&&await new Promise(e=>{document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})});const u=function(e){const t="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let a=null;try{let e=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const t=document.currentScript.src;t&&(t.includes("@countriesdb/widget")||t.includes("widget/dist/index.js"))&&(e=document.currentScript)}if(!e){e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}e&&e.src&&(a=new URL(e.src))}catch{}const i={publicKey:e.publicKey??t?.publicKey??a?.searchParams.get("public_key")??"",backendUrl:e.backendUrl??t?.backendUrl??a?.searchParams.get("backend_url")??"https://api.countriesdb.com",defaultLanguage:e.defaultLanguage??t?.defaultLanguage??a?.searchParams.get("default_language")??void 0,forcedLanguage:e.forcedLanguage??t?.forcedLanguage??a?.searchParams.get("forced_language")??void 0,showSubdivisionType:void 0!==e.showSubdivisionType?e.showSubdivisionType:void 0!==t?.showSubdivisionType?t.showSubdivisionType:b(a?.searchParams.get("show_subdivision_type")??"1"),followRelated:void 0!==e.followRelated?e.followRelated:void 0!==t?.followRelated?t.followRelated:b(a?.searchParams.get("follow_related")??"false"),followUpward:void 0!==e.followUpward?e.followUpward:void 0!==t?.followUpward?t.followUpward:b(a?.searchParams.get("follow_upward")??"false"),allowParentSelection:void 0!==e.allowParentSelection?e.allowParentSelection:void 0!==t?.allowParentSelection?t.allowParentSelection:b(a?.searchParams.get("allow_parent_selection")??"false"),isoCountryNames:void 0!==e.isoCountryNames?e.isoCountryNames:void 0!==t?.isoCountryNames?t.isoCountryNames:b(a?.searchParams.get("iso_country_names")??"false"),subdivisionRomanizationPreference:e.subdivisionRomanizationPreference||t?.subdivisionRomanizationPreference||a?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==e.preferLocalVariant?e.preferLocalVariant:void 0!==t?.preferLocalVariant?t.preferLocalVariant:b(a?.searchParams.get("prefer_local_variant")??"false"),preferOfficialSubdivisions:void 0!==e.preferOfficialSubdivisions?e.preferOfficialSubdivisions:void 0!==t?.preferOfficialSubdivisions?t.preferOfficialSubdivisions:b(a?.searchParams.get("prefer_official")??"false"),countryNameFilter:e.countryNameFilter??t?.countryNameFilter,subdivisionNameFilter:e.subdivisionNameFilter??t?.subdivisionNameFilter,autoInit:void 0!==e.autoInit?e.autoInit:void 0!==t?.autoInit?t.autoInit:b(a?.searchParams.get("auto_init")??"true")};if(a){const e=a.searchParams.get("countryNameFilter");if(e&&"undefined"!=typeof window){const t=window[e];"function"==typeof t&&(i.countryNameFilter=t)}const t=a.searchParams.get("subdivisionNameFilter");if(t&&"undefined"!=typeof window){const e=window[t];"function"==typeof e&&(i.subdivisionNameFilter=e)}}return i}(t);if(function(){const e=Array.from(document.querySelectorAll(".country-selection"));for(const t of e)t.classList.contains("subdivision-selection")&&(t.classList.remove("subdivision-selection"),t.classList.add("subdivision-selection-removed"))}(),u.followRelated&&u.followUpward)return function(){const e="Error: Cannot enable both follow_related and follow_upward",t=Array.from(document.querySelectorAll(".country-selection"));for(const a of t)a.innerHTML=`<option value="${a.dataset.defaultValue??""}" disabled>${e}</option>`;const a=Array.from(document.querySelectorAll(".subdivision-selection"));for(const t of a)t.innerHTML=`<option value="${t.dataset.defaultValue??""}" disabled>${e}</option>`}(),!1;const g={countriesMap:new WeakMap,subdivisionsMap:new WeakMap,subdivisionsLanguageMap:new WeakMap,isInitializing:new Set,eventHandlers:n.eventHandlers},w=u.publicKey||"";await async function(e,t,i,n){const o=Array.from(document.querySelectorAll(".subdivision-selection"));for(const s of o){a(s,"—",!0);const o=s.dataset.country,l=o?document.querySelector(`.country-selection[data-name="${o}"]`):null;if(l&&l.hasAttribute("multiple")){const e=s.dataset.defaultValue??"";s.innerHTML=`<option value="${e}" disabled>Error: Cannot link to multi-select country. Use data-country-code instead.</option>`;continue}if(!o||!l)if(s.hasAttribute("data-country-code")&&s.dataset.countryCode)await m(s,e,t,i,n,s.dataset.countryCode);else{const e=s.dataset.defaultValue??"";s.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}const u=i.eventHandlers.get(s);u&&(u.update&&s.removeEventListener("change",u.update),u.followRelated&&s.removeEventListener("change",u.followRelated),u.followUpward&&s.removeEventListener("change",u.followUpward));const p={update:e=>{d(e)||r(s,{type:"subdivision",reason:"regular"})}};s.addEventListener("change",p.update),p.followRelated=async a=>{d(a)||await c(s,e,0,i,n.followRelated,(e,a,o)=>m(e,a,t,i,n,o))},s.addEventListener("change",p.followRelated),p.followUpward=async a=>{d(a)||await f(s,e,0,i,n.followUpward,(e,a,o)=>m(e,a,t,i,n,o))},s.addEventListener("change",p.followUpward),i.eventHandlers.set(s,p)}}(w,u.backendUrl,g,{followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,showSubdivisionType:!1!==u.showSubdivisionType,allowParentSelection:u.allowParentSelection||!1,preferOfficialSubdivisions:u.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:u.subdivisionRomanizationPreference,preferLocalVariant:u.preferLocalVariant||!1,subdivisionNameFilter:u.subdivisionNameFilter});const h={followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,showSubdivisionType:!1!==u.showSubdivisionType,allowParentSelection:u.allowParentSelection||!1,preferOfficialSubdivisions:u.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:u.subdivisionRomanizationPreference,preferLocalVariant:u.preferLocalVariant||!1,forcedLanguage:u.forcedLanguage,defaultLanguage:u.defaultLanguage,subdivisionNameFilter:u.subdivisionNameFilter};await async function(t,n,u,c){const f=Array.from(document.querySelectorAll(".country-selection")),g={};for(const w of f){const f=w.dataset.name;if(f&&g[f]){w.removeAttribute("data-name"),a(w,"—");const e=w.dataset.defaultValue??"";w.innerHTML+=`<option value="${e}" disabled>Error: Duplicate field</option>`;continue}f&&(g[f]=!0),a(w,"—"),u.isInitializing.add(w);let b=!1,h=!1;try{const a=null==(w.getAttribute("data-preselected")||w.dataset.preselected),s=e.getLanguageHeaders(c.forcedLanguage,c.defaultLanguage),l=await e.fetchCountries({apiKey:t,backendUrl:n,shouldUseGeoIP:a,isoCountryNames:c.isoCountryNames,languageHeaders:s}),f=l.data,g=l.language||"en";if(u.countriesMap.set(w,f),i(w,f,g,c.countryNameFilter),void 0!==(w.getAttribute("data-preselected")||w.dataset.preselected||w.dataset._widgetTempPreselect)&&(o(w),r(w,{type:"country",reason:"preselected"}),b=!0,w.value&&(w.value,w.dataset.defaultValue)),a){const e=f.find(e=>e.preselected);e&&(w.value=e.iso_alpha_2,r(w,{type:"country",reason:"geoip"}),b=!0)}!h&&w.value&&w.value!==(w.dataset.defaultValue||"")&&(h=!0);const _=u.eventHandlers.get(w);_?.countryChange&&w.removeEventListener("change",_.countryChange);const S=async e=>{if(d(e))return;r(w,{type:"country",reason:"regular"});const a=v(),i="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:c;await y(w,t,n,u,a);const o=w.value;if(!o)return;const s=(u.countriesMap.get(w)||[]).find(e=>e.iso_alpha_2===o);if(!s)return;const l=i?.followUpward||!1;l&&!w.multiple&&s.is_subdivision_of&&await p(w,t,0,u,l,(e,t,i)=>m(e,t,n,u,a,i))},L=u.eventHandlers.get(w)||{};L.countryChange=S,u.eventHandlers.set(w,L),w.addEventListener("change",S)}catch(e){if(console.error("Failed to fetch countries:",e),s(w,e),w.dataset.name){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${w.dataset.name}"]`));for(const i of t)a(i,"—"),s(i,e)}}finally{u.isInitializing.delete(w),l(w,{type:"country",phase:"initial"}),b||r(w,{type:"country",reason:"regular"})}}}(w,u.backendUrl,g,{defaultLanguage:u.defaultLanguage,forcedLanguage:u.forcedLanguage,isoCountryNames:u.isoCountryNames||!1,followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,countryNameFilter:u.countryNameFilter});const _=Array.from(document.querySelectorAll(".country-selection"));for(const e of _)e.value&&e.value!==(e.dataset.defaultValue||"")&&await y(e,w,u.backendUrl,g,h);return n.initialized=!0,!0})(),n.initPromise}function b(e){if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)}return"undefined"!=typeof window&&(window.CountriesWidgetLoad=w,function e(){if("loading"===document.readyState)return void document.addEventListener("DOMContentLoaded",e,{once:!0});let t=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const e=document.currentScript.src;e&&(e.includes("@countriesdb/widget")||e.includes("widget/dist/index.js"))&&(t=document.currentScript)}if(!t){t=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}let a=!0;const i="undefined"!=typeof window&&window.CountriesDBConfig||null;if(i&&void 0!==i.autoInit)a=!!i.autoInit;else if(t&&t.src)try{const e=new URL(t.src).searchParams.get("auto_init");a=null===e||"true"===e||"1"===e}catch{a=!0}a&&setTimeout(()=>{w().catch(console.error)},0)}()),w});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).CountriesWidget=t()}(this,function(){"use strict";class e{static async fetchCountries(e){const{apiKey:t,backendUrl:n,shouldUseGeoIP:a=!0,isoCountryNames:i=!1,languageHeaders:o={}}=e,s=`${n}/api/countries`,r=[];a||r.push("no_geoip=1"),i&&r.push("country_name_source=iso");const l=r.length?`${s}?${r.join("&")}`:s;return this.fetchFromApi(l,t,o)}static async fetchSubdivisions(e){const{apiKey:t,backendUrl:n,countryCode:a,shouldUseGeoIP:i=!0,preferOfficial:o=!1,subdivisionRomanizationPreference:s,preferLocalVariant:r=!1,languageHeaders:l={}}=e;if(!a)return{data:[],language:null};const d=`${n}/api/countries/${a}/subdivisions`,u=[];i||u.push("no_geoip=1"),s&&u.push(`subdivision_romanization_preference=${encodeURIComponent(s)}`),r&&u.push("prefer_local_variant=1"),o&&u.push("prefer_official=1");const c=u.length?`${d}?${u.join("&")}`:d;return this.fetchFromApi(c,t,l)}static async fetchFromApi(e,t,n){try{const a=await fetch(e,{headers:{...n,"X-API-KEY":t,"Content-Type":"application/json"}});if(!a.ok){let e=`HTTP Error: ${a.status}`;try{const t=await a.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const i=await a.json();return{data:i,language:a.headers.get("X-Selected-Language")||null}}catch(t){throw console.error(`Failed to fetch data from ${e}:`,t),t}}static getLanguageHeaders(e,t){const n={};return e&&(n["X-Forced-Language"]=e),t&&(n["X-Default-Language"]=t),"undefined"!=typeof navigator&&navigator.language?n["Accept-Language"]=navigator.language:n["Accept-Language"]="en",n}}function t(e){const t={},n=[];return e.forEach(e=>{t[e.id]={...e,children:[]}}),e.forEach(e=>{const a=t[e.id];e.parent_id&&t[e.parent_id]?t[e.parent_id].children.push(a):n.push(a)}),n}function n(e,t,a,i,o,s,r){let l="";const d=e.map(e=>{let t=e[i]||e.name;const n=e.code?e.code.split("-")[0]:null;if(r&&"function"==typeof r){const a=r(e.code,t,o,n,e);if(!1===a)return null;null!=a&&(t=a)}return{...e,_displayName:t}}).filter(e=>null!==e),u=r&&"function"==typeof r&&o?o:void 0;d.sort((e,t)=>u?e._displayName.localeCompare(t._displayName,u,{sensitivity:"accent",ignorePunctuation:!1}):e._displayName.localeCompare(t._displayName));const c=t>0?a[t]??" ".repeat(2*t):"",f=`subdivision-level-${t}`;for(const e of d){const d=e.children&&e.children.length>0,u=`${c}${e._displayName}`;d?(l+=s?`<option value="${e.code}" class="${f}">${u}</option>`:`<option disabled value="${e.code}" class="${f}">${u}</option>`,l+=n(e.children,t+1,a,i,o,s,r)):l+=`<option value="${e.code}" class="${f}">${u}</option>`}return l}function a(e,t="Not Applicable",n=!1){if(e.hasAttribute("multiple"))e.innerHTML="",void 0!==e.dataset.label&&delete e.dataset.label,void 0!==e.dataset.defaultValue&&delete e.dataset.defaultValue;else{const n=e.dataset.label,a=e.dataset.defaultValue,i=n||t,o=a??"";e.innerHTML=`<option value="${o}">${i}</option>`,void 0!==n&&(e.dataset.label=n),void 0!==a&&(e.dataset.defaultValue=a)}n&&(e.disabled=!0)}function i(e,t,n,a){let i=function(e,t,n){return t&&"function"==typeof t?e.map(e=>{const a=t(e.iso_alpha_2,e.name,n,e);if(!1===a)return null;const i=null!=a?a:e.name;return{...e,_displayName:i}}).filter(e=>null!==e):e.map(e=>({...e,_displayName:e.name}))}(t,a,n);a&&(i=function(e,t){const n=t;return[...e].sort((e,t)=>e._displayName.localeCompare(t._displayName,n,{sensitivity:"accent",ignorePunctuation:!1}))}(i,n));if(e.hasAttribute("multiple")||e.multiple)e.innerHTML="";else{const t=e.querySelector('option[value=""]')||(e.dataset.defaultValue?e.querySelector(`option[value="${e.dataset.defaultValue}"]`):null),n=e.dataset.defaultValue??"";e.innerHTML=t?t.outerHTML:`<option value="${n}">${e.dataset.label||"—"}</option>`}i.forEach(t=>{const n=document.createElement("option");n.value=t.iso_alpha_2,n.textContent=t._displayName,e.appendChild(n)})}function o(e,a,i,o,s,r){const l=t(e),d={};for(let e=1;e<=10;e++){const t=`nested${e}Prefix`,n=a.dataset[t];if(void 0===n)break;d[`nested${e}Prefix`]=n}const u=function(e){const t={};for(let n=1;n<=10;n++){const a=e[`nested${n}Prefix`];if(void 0===a)break;t[n]=a}return t}(d),c=o?"full_name":"name";let f="";if(!a.hasAttribute("multiple")){const e=a.dataset.label||"—";f=`<option value="${a.dataset.defaultValue??""}">${e}</option>`}return f+=n(l,0,u,c,i,s,r),f}function s(e,t){const n=e.dataset._widgetTempPreselect,a=e.getAttribute("data-preselected")||e.dataset.preselected,i=null!=n&&""!==String(n).trim()?n:a;if(!i||"string"==typeof i&&""===i.trim())return;const o=String(i);if(e.hasAttribute("multiple")){const t=o.split(",").map(e=>e.trim()).filter(e=>""!==e);Array.from(e.options).forEach(e=>{e.selected=t.includes(e.value)})}else e.value=o;void 0!==e.dataset._widgetTempPreselect&&delete e.dataset._widgetTempPreselect,null!=a&&""!==String(a).trim()&&(e.dataset._widgetPreselectedConsumed="1")}function r(e,t,n=!1){const a=t instanceof Error?t.message:t,i=e.dataset.defaultValue??"",o=a.startsWith("Error: ")?a:`Error: ${a}`;n?e.innerHTML=`<option value="${i}" disabled>${o}</option>`:e.innerHTML+=`<option value="${i}" disabled>${o}</option>`}function l(e,t={}){let n=[];n=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[];const a=new CustomEvent("countriesWidget:update",{bubbles:!0,detail:{value:e.value||"",selectedValues:n,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),...t}});e.dispatchEvent(a)}function d(e,t={}){const n=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[],a=new CustomEvent("countriesWidget:ready",{bubbles:!0,detail:{value:e.value||"",selectedValues:n,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),type:e.classList.contains("subdivision-selection")?"subdivision":"country",phase:"initial",...t}});e.dispatchEvent(a)}function u(e){return!0===e.isWidgetInitiated}async function c(e,t,n,a,i,o,s,r){if(!i&&!o)return;const d=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!d||d.multiple)return;const u=a.subdivisionsMap.get(e);if(!u)return;if(o&&e.multiple)return;const c=e.value;if(!c)return;const f=u.find(e=>e.code===c);if(f){if(i&&f.related_country_code){const e=f.related_country_code,n=f.related_subdivision_code,a=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);a&&n&&(a.dataset._widgetTempPreselect=n),d.value!==e?(d.value=e,l(d,{type:"country",reason:"regular"}),r?await r(d,t):a&&await s(a,t,e)):a&&n&&await s(a,t,e)}if(o&&f.is_subdivision_of){const e=f.is_subdivision_of.parent_country_code,n=f.is_subdivision_of.subdivision_code;if(n){const e=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);e&&!e.multiple&&(e.dataset._widgetTempPreselect=n)}if(d.value!==e)if(d.value=e,l(d,{type:"country",reason:"regular"}),r)await r(d,t);else{const n=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);n&&await s(n,t,e)}else if(n){const n=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);n&&!n.multiple&&await s(n,t,e)}}}}async function f(e,t,n,a,i,o){if(!i)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const r=a.subdivisionsMap.get(e);if(!r)return;const d=e.multiple?e.selectedOptions[0]?.value||null:e.value;if(!d)return;const u=r.find(e=>e.code===d);if(!u||!u.related_country_code)return;const c=u.related_country_code,f=u.related_subdivision_code,p=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);p&&f&&(p.dataset.preselected=f),s.value!==c?(s.value=c,l(s,{type:"country",reason:"regular"}),p&&await o(p,t,c)):p&&f&&await o(p,t,c)}async function p(e,t,n,a,i,o){if(!i)return;if(e.multiple)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const r=a.subdivisionsMap.get(e);if(!r)return;const d=e.value;if(!d)return;const u=r.find(e=>e.code===d);if(!u||!u.is_subdivision_of)return;const c=u.is_subdivision_of.parent_country_code,f=u.is_subdivision_of.subdivision_code;if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&(e.dataset.preselected=f)}if(s.value!==c){s.value=c,l(s,{type:"country",reason:"follow"});const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}else if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}}async function m(e,t,n,a,i,o){if(!i||e.multiple)return;const s=a.countriesMap.get(e);if(!s)return;const r=e.value;if(!r)return;const d=s.find(e=>e.iso_alpha_2===r);if(!d||!d.is_subdivision_of)return;const u=d.is_subdivision_of.parent_country_code,c=d.is_subdivision_of.subdivision_code;if(e.value!==u){if(c){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of t)e.multiple||(e.dataset.preselected=c)}e.value=u,l(e,{type:"country",reason:"regular"});const n=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of n)await o(e,t,u)}else if(c){const n=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of n)e.multiple||await o(e,t,u)}}async function v(n,i,u,f,p,m){const y=n.getAttribute("data-preselected")||n.dataset.preselected,w=f.subdivisionsMap.has(n);a(n,"—",!0),f.isInitializing.add(n);let b=m;if(b||(b=n.dataset.countryCode||""),b){let h=!1;try{const _=null==y,S=!!n.hasAttribute("data-prefer-official")||p.preferOfficialSubdivisions,L=e.getLanguageHeaders(p.forcedLanguage,p.defaultLanguage),P=await e.fetchSubdivisions({apiKey:i,backendUrl:u,countryCode:b,shouldUseGeoIP:_,preferOfficial:S,subdivisionRomanizationPreference:p.subdivisionRomanizationPreference,preferLocalVariant:p.preferLocalVariant,languageHeaders:L}),$=P.data,C=P.language||"en";if(f.subdivisionsMap.set(n,$),f.subdivisionsLanguageMap.set(n,C),$.length>0){n.disabled=!1;const A=n.hasAttribute("multiple"),N=A?void 0:n.dataset.label,T=A?void 0:n.dataset.defaultValue,U=n.value,R=n.dataset.defaultValue||"",V=U&&U!==R&&""!==U.trim();n.innerHTML=o($,n,C,p.showSubdivisionType,p.allowParentSelection,p.subdivisionNameFilter),A||(void 0!==N&&(n.dataset.label=N),void 0!==T&&(n.dataset.defaultValue=T));let E=!1;if(V&&!A){Array.from(n.options).some(e=>e.value===U)&&(n.value=U,E=!0)}if(!E){const M=void 0!==(n.getAttribute("data-preselected")||n.dataset.preselected||n.dataset._widgetTempPreselect),H="1"===n.dataset._widgetPreselectedConsumed;if(!M||H&&w){if(_){const q=$.find(e=>e.preselected);if(q){const F=n.hasAttribute("multiple");let z=q;if(!p.allowParentSelection&&!F){const k=Array.from(n.options).find(e=>e.value===q.code);if(k&&k.disabled){function O(e,t){for(const n of e){if(n.code===t)return n;if(n.children&&n.children.length>0){const e=O(n.children,t);if(e)return e}}return null}const I=O(t($),q.code);function W(e){if(!e||!e.children||0===e.children.length)return null;const t=[...e.children].sort((e,t)=>{const n=e.name||"",a=t.name||"";return n.localeCompare(a)})[0];if(t.children&&t.children.length>0){return W(t)||t}return t}const j=I?W(I):null;j&&(z=$.find(e=>e.code===j.code)||q)}}if(F){const x=Array.from(n.options).find(e=>e.value===z.code);x&&(x.selected=!0)}else n.value=z.code;l(n,{type:"subdivision",reason:"geoip"}),h=!0,await c(n,i,0,f,p.followRelated,p.followUpward,(e,t,n)=>v(e,t,u,f,p,n),(e,t)=>g(e,t,u,f,p))}}}else s(n),l(n,{type:"subdivision",reason:"preselected"}),h=!0,await c(n,i,0,f,p.followRelated,p.followUpward,(e,t,n)=>v(e,t,u,f,p,n),(e,t)=>g(e,t,u,f,p))}}else n.disabled=!0}catch(D){console.error("Failed to fetch subdivisions:",D),r(n,D)}finally{f.isInitializing.delete(n),d(n,{type:"subdivision",phase:w?"reload":"initial"}),w&&!h&&l(n,{type:"subdivision",reason:"reload"})}}else if(!n.dataset.country||!document.querySelector(`.country-selection[data-name="${n.dataset.country}"]`)){const B=n.dataset.defaultValue??"";n.innerHTML+=`<option value="${B}" disabled>Error: No country select present</option>`}}function y(e,t){const n="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let a=null;try{const e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null;e&&e.src&&(a=new URL(e.src))}catch{}const i=e=>{if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)};return{followRelated:void 0!==n?.followRelated?n.followRelated:i(a?.searchParams.get("follow_related")??"false"),followUpward:void 0!==n?.followUpward?n.followUpward:i(a?.searchParams.get("follow_upward")??"false"),showSubdivisionType:void 0!==n?.showSubdivisionType?n.showSubdivisionType:i(a?.searchParams.get("show_subdivision_type")??"1"),allowParentSelection:void 0!==n?.allowParentSelection?n.allowParentSelection:i(a?.searchParams.get("allow_parent_selection")??"false"),preferOfficialSubdivisions:void 0!==n?.preferOfficialSubdivisions?n.preferOfficialSubdivisions:i(a?.searchParams.get("prefer_official")??"false"),subdivisionRomanizationPreference:n?.subdivisionRomanizationPreference||a?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==n?.preferLocalVariant?n.preferLocalVariant:i(a?.searchParams.get("prefer_local_variant")??"false"),forcedLanguage:n?.forcedLanguage||a?.searchParams.get("forced_language")||void 0,defaultLanguage:n?.defaultLanguage||a?.searchParams.get("default_language")||void 0,subdivisionNameFilter:n?.subdivisionNameFilter}}async function g(e,t,n,a,i){if(e.hasAttribute("multiple"))return;const o=e.value,s=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of s)await v(e,t,n,a,i,o)}const w="__CountriesWidgetNS__";async function b(t={}){window[w]||(window[w]={initialized:!1,initPromise:null,version:0,eventHandlers:new WeakMap});const n=window[w];n.eventHandlers||(n.eventHandlers=new WeakMap);if(!0===t.reload&&(n.initialized=!1,n.initPromise=null,"undefined"!=typeof document)){document.querySelectorAll(".subdivision-selection").forEach(e=>{e.dataset._widgetPreselectedConsumed&&delete e.dataset._widgetPreselectedConsumed})}return n.initPromise=(async()=>{"loading"===document.readyState&&await new Promise(e=>{document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})});const o=function(e){const t="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let n=null;try{let e=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const t=document.currentScript.src;t&&(t.includes("@countriesdb/widget")||t.includes("widget/dist/index.js"))&&(e=document.currentScript)}if(!e){e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}e&&e.src&&(n=new URL(e.src))}catch{}const a={publicKey:e.publicKey??t?.publicKey??n?.searchParams.get("public_key")??"",backendUrl:e.backendUrl??t?.backendUrl??n?.searchParams.get("backend_url")??"https://api.countriesdb.com",defaultLanguage:e.defaultLanguage??t?.defaultLanguage??n?.searchParams.get("default_language")??void 0,forcedLanguage:e.forcedLanguage??t?.forcedLanguage??n?.searchParams.get("forced_language")??void 0,showSubdivisionType:void 0!==e.showSubdivisionType?e.showSubdivisionType:void 0!==t?.showSubdivisionType?t.showSubdivisionType:h(n?.searchParams.get("show_subdivision_type")??"1"),followRelated:void 0!==e.followRelated?e.followRelated:void 0!==t?.followRelated?t.followRelated:h(n?.searchParams.get("follow_related")??"false"),followUpward:void 0!==e.followUpward?e.followUpward:void 0!==t?.followUpward?t.followUpward:h(n?.searchParams.get("follow_upward")??"false"),allowParentSelection:void 0!==e.allowParentSelection?e.allowParentSelection:void 0!==t?.allowParentSelection?t.allowParentSelection:h(n?.searchParams.get("allow_parent_selection")??"false"),isoCountryNames:void 0!==e.isoCountryNames?e.isoCountryNames:void 0!==t?.isoCountryNames?t.isoCountryNames:h(n?.searchParams.get("iso_country_names")??"false"),subdivisionRomanizationPreference:e.subdivisionRomanizationPreference||t?.subdivisionRomanizationPreference||n?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==e.preferLocalVariant?e.preferLocalVariant:void 0!==t?.preferLocalVariant?t.preferLocalVariant:h(n?.searchParams.get("prefer_local_variant")??"false"),preferOfficialSubdivisions:void 0!==e.preferOfficialSubdivisions?e.preferOfficialSubdivisions:void 0!==t?.preferOfficialSubdivisions?t.preferOfficialSubdivisions:h(n?.searchParams.get("prefer_official")??"false"),countryNameFilter:e.countryNameFilter??t?.countryNameFilter,subdivisionNameFilter:e.subdivisionNameFilter??t?.subdivisionNameFilter,autoInit:void 0!==e.autoInit?e.autoInit:void 0!==t?.autoInit?t.autoInit:h(n?.searchParams.get("auto_init")??"true")};if(n){const e=n.searchParams.get("countryNameFilter");if(e&&"undefined"!=typeof window){const t=window[e];"function"==typeof t&&(a.countryNameFilter=t)}const t=n.searchParams.get("subdivisionNameFilter");if(t&&"undefined"!=typeof window){const e=window[t];"function"==typeof e&&(a.subdivisionNameFilter=e)}}return a}(t);if(function(){const e=Array.from(document.querySelectorAll(".country-selection"));for(const t of e)t.classList.contains("subdivision-selection")&&(t.classList.remove("subdivision-selection"),t.classList.add("subdivision-selection-removed"))}(),o.followRelated&&o.followUpward)return function(){const e="Error: Cannot enable both follow_related and follow_upward",t=Array.from(document.querySelectorAll(".country-selection"));for(const n of t)n.innerHTML=`<option value="${n.dataset.defaultValue??""}" disabled>${e}</option>`;const n=Array.from(document.querySelectorAll(".subdivision-selection"));for(const t of n)t.innerHTML=`<option value="${t.dataset.defaultValue??""}" disabled>${e}</option>`}(),!1;const c={countriesMap:new WeakMap,subdivisionsMap:new WeakMap,subdivisionsLanguageMap:new WeakMap,isInitializing:new Set,eventHandlers:n.eventHandlers},w=o.publicKey||"";await async function(e,t,n,i){const o=Array.from(document.querySelectorAll(".subdivision-selection"));for(const s of o){a(s,"—",!0);const o=s.dataset.country,r=o?document.querySelector(`.country-selection[data-name="${o}"]`):null;if(r&&r.hasAttribute("multiple")){const e=s.dataset.defaultValue??"";s.innerHTML=`<option value="${e}" disabled>Error: Cannot link to multi-select country. Use data-country-code instead.</option>`;continue}if(!o||!r)if(s.hasAttribute("data-country-code")&&s.dataset.countryCode)await v(s,e,t,n,i,s.dataset.countryCode);else{const e=s.dataset.defaultValue??"";s.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}const d=n.eventHandlers.get(s);d&&(d.update&&s.removeEventListener("change",d.update),d.followRelated&&s.removeEventListener("change",d.followRelated),d.followUpward&&s.removeEventListener("change",d.followUpward));const c={update:e=>{u(e)||l(s,{type:"subdivision",reason:"regular"})}};s.addEventListener("change",c.update),c.followRelated=async a=>{u(a)||await f(s,e,0,n,i.followRelated,(e,a,o)=>v(e,a,t,n,i,o))},s.addEventListener("change",c.followRelated),c.followUpward=async a=>{u(a)||await p(s,e,0,n,i.followUpward,(e,a,o)=>v(e,a,t,n,i,o))},s.addEventListener("change",c.followUpward),n.eventHandlers.set(s,c)}}(w,o.backendUrl,c,{followRelated:o.followRelated||!1,followUpward:o.followUpward||!1,showSubdivisionType:!1!==o.showSubdivisionType,allowParentSelection:o.allowParentSelection||!1,preferOfficialSubdivisions:o.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:o.subdivisionRomanizationPreference,preferLocalVariant:o.preferLocalVariant||!1,subdivisionNameFilter:o.subdivisionNameFilter});const b={followRelated:o.followRelated||!1,followUpward:o.followUpward||!1,showSubdivisionType:!1!==o.showSubdivisionType,allowParentSelection:o.allowParentSelection||!1,preferOfficialSubdivisions:o.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:o.subdivisionRomanizationPreference,preferLocalVariant:o.preferLocalVariant||!1,forcedLanguage:o.forcedLanguage,defaultLanguage:o.defaultLanguage,subdivisionNameFilter:o.subdivisionNameFilter};await async function(t,n,o,c){const f=Array.from(document.querySelectorAll(".country-selection")),p={};for(const w of f){const f=w.dataset.name;if(f&&p[f]){w.removeAttribute("data-name"),a(w,"—");const e=w.dataset.defaultValue??"";w.innerHTML+=`<option value="${e}" disabled>Error: Duplicate field</option>`;continue}f&&(p[f]=!0),a(w,"—"),o.isInitializing.add(w);let b=!1,h=!1;try{const a=null==(w.getAttribute("data-preselected")||w.dataset.preselected),r=e.getLanguageHeaders(c.forcedLanguage,c.defaultLanguage),d=await e.fetchCountries({apiKey:t,backendUrl:n,shouldUseGeoIP:a,isoCountryNames:c.isoCountryNames,languageHeaders:r}),f=d.data,p=d.language||"en";if(o.countriesMap.set(w,f),i(w,f,p,c.countryNameFilter),void 0!==(w.getAttribute("data-preselected")||w.dataset.preselected||w.dataset._widgetTempPreselect)&&(s(w),l(w,{type:"country",reason:"preselected"}),b=!0,w.value&&(w.value,w.dataset.defaultValue)),a){const e=f.find(e=>e.preselected);e&&(w.value=e.iso_alpha_2,l(w,{type:"country",reason:"geoip"}),b=!0)}!h&&w.value&&w.value!==(w.dataset.defaultValue||"")&&(h=!0);const _=o.eventHandlers.get(w);_?.countryChange&&w.removeEventListener("change",_.countryChange);const S=async e=>{if(u(e))return;l(w,{type:"country",reason:"regular"});const a=y(),i="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:c;await g(w,t,n,o,a);const s=w.value;if(!s)return;const r=(o.countriesMap.get(w)||[]).find(e=>e.iso_alpha_2===s);if(!r)return;const d=i?.followUpward||!1;d&&!w.multiple&&r.is_subdivision_of&&await m(w,t,0,o,d,(e,t,i)=>v(e,t,n,o,a,i))},L=o.eventHandlers.get(w)||{};L.countryChange=S,o.eventHandlers.set(w,L),w.addEventListener("change",S)}catch(e){if(console.error("Failed to fetch countries:",e),r(w,e),w.dataset.name){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${w.dataset.name}"]`));for(const n of t)a(n,"—"),r(n,e)}}finally{o.isInitializing.delete(w),d(w,{type:"country",phase:"initial"}),b||l(w,{type:"country",reason:"regular"})}}}(w,o.backendUrl,c,{defaultLanguage:o.defaultLanguage,forcedLanguage:o.forcedLanguage,isoCountryNames:o.isoCountryNames||!1,followRelated:o.followRelated||!1,followUpward:o.followUpward||!1,countryNameFilter:o.countryNameFilter});const _=Array.from(document.querySelectorAll(".country-selection"));for(const e of _)e.value&&e.value!==(e.dataset.defaultValue||"")&&await g(e,w,o.backendUrl,c,b);return n.initialized=!0,!0})(),n.initPromise}function h(e){if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)}return"undefined"!=typeof window&&(window.CountriesWidgetLoad=b,function e(){if("loading"===document.readyState)return void document.addEventListener("DOMContentLoaded",e,{once:!0});let t=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const e=document.currentScript.src;e&&(e.includes("@countriesdb/widget")||e.includes("widget/dist/index.js"))&&(t=document.currentScript)}if(!t){t=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}let n=!0;const a="undefined"!=typeof window&&window.CountriesDBConfig||null;if(a&&void 0!==a.autoInit)n=!!a.autoInit;else if(t&&t.src)try{const e=new URL(t.src).searchParams.get("auto_init");n=null===e||"true"===e||"1"===e}catch{n=!0}n&&setTimeout(()=>{b().catch(console.error)},0)}()),b});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|