UNPKG

@salla.sa/twilight-components

Version:
4 lines 15.1 kB
/*! * Crafted with ❤ by Salla */ import{r as t,c as s,h as i,H as e,a as n}from"./p-Dbv0I4re.js";import{A as o,a as l}from"./p-Vqpj4CWE.js";const d=class{constructor(i){t(this,i),this.optionsSaved=s(this,"optionsSaved"),this.productSelected=s(this,"productSelected"),this.product=null,this.sectionId=null,this.sectionIndex=0,this.productIndex=0,this.selectedOptions={},this.optionsResetTokens={},this.isLoading=!1,this.hasUnsavedChanges=!1,this.validationErrors=[]}generateCacheKey(t,s,i){return`${t||"unknown"}-${s||0}-${i||"unknown"}`}handleProductChange(t){setTimeout((()=>{this.modal&&t&&this.modal.setTitle(t.name||"")}),100),this.validationErrors=[],this.hasUnsavedChanges=!1}async open(){this.modal?(this.isLoading=!0,this.product?.name&&this.modal.setTitle(this.product.name),this.modal.open(),setTimeout((async()=>{this.product?.id&&await this.initializeSelectedOptions(),this.product?.name&&this.modal.setTitle(this.product.name),this.modal.stopLoading(),this.isLoading=!1}),300)):requestAnimationFrame((()=>this.open()))}async close(){this.modal&&this.modal.close()}async refreshOptionsState(){this.selectedOptions={...this.selectedOptions}}componentDidLoad(){this.modalOpenListener=t=>{this.product=t.product,this.sectionId=t.sectionId||null,this.sectionIndex=t.sectionIndex||0,this.productIndex=t.productIndex||0,this.open()},salla.event.on("multiple-bundle-product-modal::open",this.modalOpenListener),this.clearOptionsListener=t=>{t&&t.productId&&this.clearProductOptions(t.productId,t.sectionId,t.productIndex)},salla.event.on("multiple-bundle-product-modal::clear-options",this.clearOptionsListener),this.optionChangeListener=t=>{const s=t.detail||t,{option:i,detail:e}=s,n=i||s.option_id&&this.product?.options?.find((t=>t.id===s.option_id||String(t.id)===String(s.option_id))),o=e||(s.id?s:null);this.product?.id&&n&&this.handleOptionChange(Number(this.product.id),n,o)},salla.event.on("product-options::change",this.optionChangeListener),this.checkboxChangeListener=t=>{const s=t.target;if(s&&"checkbox"===s.type&&s.name&&s.name.includes("bundle[")&&s.name.includes("][id]")){const t=s.name.match(/^bundle\[([^\]]+)\]\[([^\]]+)\]\[id\]$/);if(t&&!s.checked){const[,i,e]=t,n=s.value,o=this.host.closest("form");this.cleanupProductDeselection({sectionId:i,productIndex:parseInt(e,10),productId:n,form:o,uncheckedInput:s})}}},document.addEventListener("change",this.checkboxChangeListener)}disconnectedCallback(){this.checkboxChangeListener&&document.removeEventListener("change",this.checkboxChangeListener),this.optionChangeListener&&salla.event.off("product-options::change",this.optionChangeListener),this.modalOpenListener&&salla.event.off("multiple-bundle-product-modal::open",this.modalOpenListener),this.clearOptionsListener&&salla.event.off("multiple-bundle-product-modal::clear-options",this.clearOptionsListener)}cleanupProductDeselection(t){const{sectionId:s,productIndex:i,productId:e,form:n,uncheckedInput:o}=t;if(this.clearProductOptions(e,s,i),n){const t=`bundle[${s}][${i}]`;Array.from(n.querySelectorAll(`input[name^="${t}"]`)).forEach((s=>{if(s===o)return;const i="hidden"===s.type,n=s.getAttribute("data-product-id")===String(e)&&s.name?.startsWith(t);(i||n)&&s.remove()})),requestAnimationFrame((()=>{const t=new window.Event("change",{bubbles:!0});n.dispatchEvent(t)}))}}generateFormInputName(t,s,i){return`bundle[${t}][${s}][options][${i}]`}async initializeSelectedOptions(){if(!this.product?.id)return;const t=this.product.id,s=this.generateCacheKey(this.sectionId,this.productIndex,t),i=document.querySelector(`salla-product-options[product-id="${t}"]`);if(i)try{const t=await i.getSelectedOptions();t&&t.length>0&&(this.selectedOptions={...this.selectedOptions,[s]:t})}catch(t){console.warn("Could not initialize selected options:",t)}}clearProductOptions(t,s,i){const e={...this.selectedOptions};if(null==s||null==i||Number.isNaN(i)){const s=`-${String(t)}`,i=[];Object.keys(e).forEach((t=>{t.endsWith(s)&&(delete e[t],i.push(t))})),i.forEach((t=>this.bumpOptionsResetToken(t)))}else{const n=this.generateCacheKey(s,i,t);delete e[n],this.bumpOptionsResetToken(n)}this.selectedOptions=e,this.validationErrors=[],this.hasUnsavedChanges=!1}bumpOptionsResetToken(t){t&&(this.optionsResetTokens={...this.optionsResetTokens,[t]:(this.optionsResetTokens[t]||0)+1})}async handleOptionChange(t,s,i){const e=this.generateCacheKey(this.sectionId,this.productIndex,t),n=document.querySelector(`salla-product-options[product-id="${t}"]`);let o=[];if(n)try{o=await n.getSelectedOptions()||[]}catch(t){console.warn("Could not get current selections from component:",t)}if(o.length>0)this.selectedOptions={...this.selectedOptions,[e]:o};else if(this.selectedOptions[e]&&this.selectedOptions[e].length>0){const t=[...this.selectedOptions[e]||[]],n=t.findIndex((t=>t.option_id===s.id));n>-1?i&&null!=i.id?t[n]={...i,option_id:s.id}:t.splice(n,1):i&&null!=i.id&&t.push({...i,option_id:s.id}),this.selectedOptions={...this.selectedOptions,[e]:t}}else i&&null!=i.id&&(this.selectedOptions={...this.selectedOptions,[e]:[{...i,option_id:s.id}]});this.hasUnsavedChanges=!0,this.validationErrors=[]}async validateOptions(){if(!this.product?.options)return!0;const t=[],s=this.product.id,i=this.generateCacheKey(this.sectionId,this.productIndex,s),e=document.querySelector(`salla-product-options[product-id="${s}"]`);let n=[];if(e)try{n=await e.getSelectedOptions()||[];const t=this.selectedOptions[i]||[];(t.length>n.length||0===n.length&&t.length>0)&&(n=t)}catch(t){n=this.selectedOptions[i]||[]}else n=this.selectedOptions[i]||[];return 0===n.length&&t.push(salla.lang.get("pages.products.no_options_selected")),this.product.options.forEach((s=>{s.required&&(n.some((t=>t.option_id==s.id))||t.push(salla.lang.get("pages.products.required_option_missing",{option:s.name})))})),this.validationErrors=t,0===t.length}async onSave(t){t.preventDefault();const s=this.product?.id;if(!s)return;const i=this.generateCacheKey(this.sectionId,this.productIndex,s);if(await new Promise((t=>setTimeout(t,100))),await this.validateOptions()){this.isLoading=!0;try{const t=document.querySelector(`salla-product-options[product-id="${s}"]`);let e=await(t?.getSelectedOptions());if((!e||0===e.length)&&this.selectedOptions[i]?.length>0&&(e=this.selectedOptions[i]),!e||0===e.length)return void(this.isLoading=!1);this.selectedOptions={...this.selectedOptions,[i]:e};const n=this.host.closest("form");if(!n)return void(this.isLoading=!1);const o=`bundle[${this.sectionId}][${this.productIndex}]`;Array.from(n.querySelectorAll(`input[name^="${o}"][type="hidden"]`)).forEach((t=>t.remove())),Array.from(n.querySelectorAll(`[data-product-id="${s}"][name^="${o}"]`)).forEach((t=>t.remove()));const l=`bundle[${this.sectionId}][${this.productIndex}][id]`,d=document.getElementById(l);if(d)d.checked=!0;else{const t=document.createElement("input");t.type="hidden",t.name=`bundle[${this.sectionId}][${this.productIndex}][id]`,t.value=String(s),t.dataset.productId=String(s),n.appendChild(t)}e.forEach((t=>{const i=t.option_id,e=document.createElement("input");e.type="hidden",e.name=this.generateFormInputName(this.sectionId,this.productIndex??0,i),e.value=String(t.id),e.dataset.productId=String(s),n.appendChild(e)}));const a=new window.Event("change",{bubbles:!0});n.dispatchEvent(a),this.optionsSaved.emit({productId:Number(s),selectedOptions:e,sectionId:this.sectionId,productIndex:this.productIndex}),this.sectionId&&this.productSelected.emit({productId:Number(s),sectionId:this.sectionId,product:this.product,fromModal:!0}),salla.notify.success(salla.lang.get("pages.products.options_saved")),this.hasUnsavedChanges=!1,this.validationErrors=[],this.modal.close()}catch(t){salla.notify.error(salla.lang.get("pages.products.options_save_error"))}finally{this.isLoading=!1}}else salla.notify.error(this.validationErrors.join(", "))}getOptionsWithSelectedState(){if(!this.product?.options)return[];const t=this.generateCacheKey(this.sectionId,this.productIndex,this.product.id),s=this.selectedOptions[t]||[];return this.product.options.map((t=>({...t,details:t.details.map((t=>{const i=s.some((s=>s.id===t.id));return{...t,is_selected:i}}))})))}render(){const t=this.product?.id,s=this.getOptionsWithSelectedState(),n=this.generateCacheKey(this.sectionId,this.productIndex,t),o=this.optionsResetTokens[n]||0,l=this.isLoading||s.some((t=>t.details.some((t=>t.is_selected&&!0===t.is_out))));return i(e,{key:"2daff50a76067220f79c498bf756db36aec2996f"},i("salla-modal",{key:"3ed6ec8860016d10cec0ee5d4bf55125fc3e44f0",isLoading:this.isLoading,ref:t=>this.modal=t,width:"md",centered:!1,id:`s-multiple-bundle-product-options-modal-options-${t}`,class:"s-multiple-bundle-product-options-modal-wrapper"},i("div",{key:"9896b07b43cf0e8191d3c7e1ba6d0613d31f08f3",slot:"loading"},i("salla-skeleton",{key:"cdf032bdbaebc1e54136b5380a10f9077a781ab0",height:"100%",width:"100%"})),this.product?.images&&this.product?.images.length>0&&i("salla-slider",{key:"5df7c6e1868f3b3ca8983ff1baa43ad3351aeca2",id:`details-slider-${this.product?.id}`,type:"thumbs",loop:!1,"auto-height":!0,"listen-to-thumbnails-option":!0,showThumbsControls:!1,controlsOuter:!1,showControls:!1,class:"s-multiple-bundle-product-options-modal-slider",verticalThumbs:!0,thumbsConfig:{centeredSlides:!0,centeredSlidesBounds:!0,slidesPerView:Math.min(5,Math.max(1,this.product?.images.length)),watchOverflow:!0,watchSlidesProgress:!0,direction:"vertical",spaceBetween:10}},i("div",{key:"190198c7256c9669c25d0cd587cf5193bd75c57e",slot:"items"},this.product?.images&&this.product?.images.map(((t,s)=>i("div",{key:s,class:"swiper-slide"},i("img",{src:t.url,alt:t.alt||`${this.product?.name} - Image ${s+1}`,loading:"lazy",onError:t=>{t.target.style.display="none"}}))))),this.product?.images&&this.product?.images.length>1&&i("div",{key:"1c8d14ffc416800d19ac3cc87b463da2acede83e",slot:"thumbs"},this.product?.images&&this.product?.images.map(((t,s)=>i("div",{key:s,"data-caption":`${this.product?.name} - Image ${s+1}`},i("img",{src:t.url,loading:"eager",class:"s-multiple-bundle-product-options-modal-slider-thumb",title:`${this.product?.name} - ${s+1}`,alt:t.alt||`${this.product?.name} - ${s+1}`,onError:t=>{t.target.style.display="none"}})))))),i("salla-product-options",{options:JSON.stringify(s),key:`${n}-reset-${o}`,"product-id":t,"unique-key":`${n}-reset-${o}`}),i("div",{key:"52dd62ee4b96b11a10981cccd301ad199adfa61e",slot:"footer"},i("div",{key:"c846f4d9099936f41872fe99f3d0b8a789f90c01",class:"s-multiple-bundle-product-options-modal-footer"},i("salla-button",{key:"40d0742d67f6ab45deace262dbd085feba3d8980",onClick:t=>this.onSave(t),loading:this.isLoading,disabled:l},this.isLoading?salla.lang.get("common.elements.saving"):salla.lang.get("common.elements.save"))))))}get host(){return n(this)}static get watchers(){return{product:["handleProductChange"]}}};d.style=":host{display:block}";const a=class{constructor(i){t(this,i),this.productSelected=s(this,"productSelected"),this.productOptionsSelected=s(this,"productOptionsSelected"),this.selectedProducts={},this.savedOptionsByInstance={},this.handleProductClick=(t,s)=>{const i=this.generateEventName(this.section.id,s),e=document.getElementById(i);if(e){if(e){const i=!e.checked;i||(this.dispatchClearOptionsEvent(t,s),this.clearSavedOptionsState(this.section.id,s)),e.checked=i,requestAnimationFrame((()=>{const t=new window.Event("change",{bubbles:!0});e.dispatchEvent(t)}))}this.productSelected.emit({product:t,sectionId:this.section.id})}},this.handleOptionsClick=t=>{this.productOptionsSelected.emit({product:t,sectionId:this.section.id})}}getProductInstanceKey(t,s){return`${t}::${s}`}dispatchClearOptionsEvent(t,s){salla.event.dispatch("multiple-bundle-product-modal::clear-options",{productId:t.id,sectionId:this.section.id,sectionIndex:this.sectionIndex,productIndex:s})}handleOptionsSaved(t){const s=t.detail;if(!s)return;const{sectionId:i,productIndex:e,selectedOptions:n}=s;if(null==i||i!==this.section?.id)return;if(null==e||Number.isNaN(e))return;const o=this.getProductInstanceKey(i,e);if(n?.length)this.savedOptionsByInstance={...this.savedOptionsByInstance,[o]:!0};else if(this.savedOptionsByInstance[o]){const t={...this.savedOptionsByInstance};delete t[o],this.savedOptionsByInstance=t}}clearSavedOptionsState(t,s){const i=this.getProductInstanceKey(t,s);if(!this.savedOptionsByInstance[i])return;const e={...this.savedOptionsByInstance};delete e[i],this.savedOptionsByInstance=e}generateEventName(t,s){return`bundle[${t}][${s}][id]`}render(){return i(e,{key:"df82c8c561e6ef9718a179be2815ed01789700a0"},i("salla-slider",{key:"b7b96681ce045a2dad72edf9cdbda7ea1b3f3c2e",type:"carousel",controlsOuter:!1,showControls:!1,id:`accordion-multiple-bundle-product-${this.section.id}`,pagination:!0,class:"s-multiple-bundle-product-wrapper-slider",sliderConfig:{spaceBetween:0}},i("div",{key:"9762b78a8c67586f2455632632a1e97eefcddbaf",slot:"items"},this?.section?.products?.map(((t,s)=>{const e=this.selectedProducts[this.section.id]?.has(t.id)||!1,n=this.savedOptionsByInstance[this.getProductInstanceKey(this.section.id,s)]?salla.lang.getWithDefault("pages.products.edit_selected_options","تعديل الخيارات"):salla.lang.get("pages.products.choose_from_options");let d=salla.config.get("theme.is_rtl",!0)?o:l;return i("div",{class:"s-multiple-bundle-product-slide-one-third "+(0==t.quantity?"s-multiple-bundle-product-slide-one-third-disabled":""),key:t.id},i("div",{class:"s-multiple-bundle-product-card"},i("div",{class:"s-multiple-bundle-product-image-wrapper",onClick:()=>this.handleProductClick(t,s)},i("input",{id:this.generateEventName(this.section.id,s),type:"checkbox",class:"s-multiple-bundle-product-checkbox",checked:e,name:this.generateEventName(this.section.id,s),value:t.id}),i("img",{src:t.image.url||salla.url.cdn("images/s-empty.png"),loading:"lazy",alt:t.image.alt||t.name,class:"s-multiple-bundle-product-image"})),i("div",{class:"s-multiple-bundle-product-content-wrapper"},i("div",{class:"s-multiple-bundle-product-content"},i("div",{class:"s-multiple-bundle-product-details"},i("div",{class:"s-multiple-bundle-product-title-wrapper"},i("h2",{class:"s-multiple-bundle-product-title"},i("a",{href:t?.url||"#",target:"_blank",rel:"noopener noreferrer"},t.name))),i("div",{class:"s-multiple-bundle-product-price-wrapper"},i("span",{class:"s-multiple-bundle-product-price"},i("span",{innerHTML:salla.money(t.price)})),t.sale_price>0&&i("span",{class:"s-multiple-bundle-product-price-discount"},i("span",{innerHTML:salla.money(t.regular_price)})))),t.quantity_in_group>0&&0!==t.quantity&&i("span",{class:"s-multiple-bundle-product-badge"},salla.lang.get("pages.products.pieces"),i("span",null,t.quantity_in_group)),0===t.quantity&&i("span",{class:"s-multiple-bundle-product-badge"},salla.lang.get("pages.products.quantity_in_group_finished"))),t.options?.length>0&&i("button",{class:"s-multiple-bundle-product-button",onClick:()=>this.handleOptionsClick(t),type:"button"},n,i("span",{class:"s-multiple-bundle-product-button-icon",innerHTML:d})))))})))))}get host(){return n(this)}};a.style="";export{d as salla_multiple_bundle_product_options_modal,a as salla_multiple_bundle_product_slider}