window.jvbTaxCreator=class{constructor(e){this.selector=e,e.modal&&(this.createNew=e.modal.querySelector(".create-new-term"),this.toggle=e.modal.querySelector(".new-term-toggle"),this.form=this.createNew?.querySelector(".create-new-term-section")),this.initListeners(),this.form&&this.initTermCreation()}initListeners(){this.clickHandler=this.handleClick.bind(this),document.addEventListener("click",this.clickHandler)}handleClick(e){window.targetCheck(e,".create-new-term summary")&&(this.createNew.open&&this.createNew.querySelector('input[name="term_name"]').focus(),this.resetParentOptions()),window.targetCheck(e,".submit-term")&&this.handleTermCreation(e).then((()=>{})),window.targetCheck(e,".create-term")&&this.handleAutocompleteCreate(e).then((()=>{}))}async handleTermCreation(e){const t=this.selector.currentConfig?.taxonomy;if(!t)return;const r=this.form.querySelector('input[name="term_name"]').value.trim(),n=parseInt(this.form.querySelector("input#select_parent")?.value)||0;if(!r)return;const s=this.form.querySelector("button");try{s&&(s.disabled=!0);const e=await this.createTerm(r,n,t);e.success&&e.term&&(await this.handleSuccessfulCreation(e.term,t,n),this.clearForm())}catch(e){console.error("Error creating term:",e),this.selector.handleError(e,"handleTermCreation")}finally{s&&(s.disabled=!1)}}async handleSuccessfulCreation(e,t,r){const n=e.path||e.name;this.createNew.open=!1,await this.selector.store.clearCache(),this.selector.store.data.set(e.id,{id:e.id,name:e.name,path:n,taxonomy:t,parent:r,count:0,hasChildren:!1,slug:e.slug||termName.toLowerCase().replace(/\s+/g,"-")}),this.selector.addSelectedTermToModal(e.id,e.name,n),(this.selector.store.filters.parent||0)===r&&await this.selector.store.setFilters({taxonomy:t,parent:r,page:1,search:""})}async handleAutocompleteCreate(e){const t=e.target.closest(".create-term"),r=this.selector.getFieldId(t),n=this.selector.fields.get(r);if(!n)return;const s=n.container.querySelector("input[data-autocomplete]"),a=s?.value.trim()||t.dataset.query;if(!a)return;const o=t.innerHTML;try{t.disabled=!0,t.textContent="Creating...";const e=await this.createTerm(a,0,n.taxonomy);e.success&&e.term?await this.handleAutocompleteSuccess(e.term,n,s):"exists"===e.reason&&e.term&&this.handleExistingTerm(e.term,n,s)}catch(e){console.error("Error creating term:",e),this.selector.handleError(e,"handleAutocompleteCreate")}finally{t.innerHTML=o,t.disabled=!1}}async handleAutocompleteSuccess(e,t,r){const n=e.path||e.name;t.selectedTerms.add(parseInt(e.id)),this.selector.store.data.set(e.id,{id:e.id,name:e.name,path:n,taxonomy:t.taxonomy,parent:0,count:0,hasChildren:!1,slug:e.slug||e.name.toLowerCase().replace(/\s+/g,"-")}),this.selector.addTermDisplay(e.id,e.name,n,"field",t.id),t.input.value=Array.from(t.selectedTerms).join(","),t.input.dispatchEvent(new Event("change",{bubbles:!0})),t.autocompleteDropdown.hidden=!0,r&&(r.value=""),await this.selector.store.clearCache()}handleExistingTerm(e,t,r){t.selectedTerms.add(parseInt(e.id)),this.selector.addTermDisplay(e.id,e.name,e.path||e.name,"field",t.id),t.input.value=Array.from(t.selectedTerms).join(","),t.input.dispatchEvent(new Event("change",{bubbles:!0})),t.autocompleteDropdown.hidden=!0,r&&(r.value="")}initTermCreation(){this.form&&this.form.addEventListener("change",(e=>{e.preventDefault(),e.stopPropagation()}))}resetParentOptions(){const e=this.selector.currentConfig?.taxonomy;if(!e)return;let t=this.createNew.querySelector("#select_parent");if(!t)return;let r=t.querySelector("option");if(!r)return;window.removeChildren(t),t.append(r.cloneNode(!0));const n=this.selector.store.filters.parent||0;if(0!==n){const e=this.selector.store.data.get(n);if(e){let n=r.cloneNode(!0);n.value=e.id,n.textContent=e.name,t.append(n)}}const s=[];this.selector.store.data.forEach((t=>{t.taxonomy===e&&t.parent===n&&s.push(t)})),s.sort(((e,t)=>e.name.localeCompare(t.name))),s.forEach((e=>{let n=r.cloneNode(!0);n.id=`select-parent-${e.id}`,n.value=e.id,n.textContent=" — "+e.name,t.append(n)}))}async createTerm(e,t=0,r){try{await this.selector.store.setFilters({taxonomy:r,search:e,page:1,parent:0}),await new Promise((e=>setTimeout(e,100)));const n=Array.from(this.selector.store.data.values()).find((t=>t.taxonomy===r&&t.name.toLowerCase()===e.toLowerCase()));if(n)return this.createNew&&this.showTermSuggestions([n],!0),{success:!1,reason:"exists",term:n};const s=await fetch(`${jvbSettings.api}terms`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":window.auth.getNonce()},body:JSON.stringify({taxonomy:r,name:e,parent:t})});if(!s.ok)throw new Error(`Server error: ${s.status}`);return await s.json()}catch(e){throw console.error("Error creating term:",e),e}}showTermSuggestions(e,t=!1){const r=this.createNew.querySelector(".term-suggestions")||this.createSuggestionContainer();window.removeChildren(r);const n=document.createElement("h4");n.textContent=t?"This term already exists:":"Similar terms already exist:",r.appendChild(n);const s=document.createElement("ul");s.className="term-suggestion-list",e.forEach((e=>{const t=document.createElement("li"),r=this.createSuggestionButton(e);t.appendChild(r),s.appendChild(t)})),r.appendChild(s),r.hidden=!1}createSuggestionButton(e){const t=document.createElement("button");return t.type="button",t.className="use-existing-term",t.dataset.id=e.id,t.textContent=e.path||e.name,t.addEventListener("click",(()=>{this.selector.addSelectedTermToModal(e.id,e.name,e.path||e.name),this.createNew.open=!1;const t=this.createNew.querySelector(".term-suggestions");t&&(t.hidden=!0),this.clearForm()})),t}createSuggestionContainer(){const e=document.createElement("div");return e.className="term-suggestions",e.hidden=!0,this.createNew.querySelector("form").after(e),e}clearForm(){const e=this.form.querySelector('input[name="term_name"]');e&&(e.value="");const t=this.createNew.querySelector(".term-suggestions");t&&(t.hidden=!0)}destroy(){this.clickHandler&&document.removeEventListener("click",this.clickHandler);const e=this.createNew?.querySelector(".loading-message.create-term");e&&(e.hidden=!0);const t=this.createNew?.querySelector(".term-suggestions");t&&(t.hidden=!0)}};
|