Plugin Directory

Changeset 3182931


Ignore:
Timestamp:
11/06/2024 07:53:29 AM (5 months ago)
Author:
printess
Message:

Fixed keyboard input issues in case the user did not click on editable frames / input elements before typing on the keyboard.

Location:
printess-editor/trunk
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • printess-editor/trunk/includes/js/printessEditor.js

    r3153712 r3182931  
    1 class PrintessEditor{constructor(e){if(this.calculateCurrentPrices=(e,t)=>{var i=this.getPriceCategories(t);let n=t.getPriceForFormFields(t.getCurrentFormFieldValues());return e.snippetPriceCategories&&e.snippetPriceCategories.forEach(e=>{e&&0<e.amount&&t.snippetPrices[e.priceCategory-1]&&(n+=t.snippetPrices[e.priceCategory-1].priceInCent)}),i.price=t.formatMoney(n),i},!e||!e.shopToken)throw"No shop token provided";this.Settings={...e};e={};void 0!==this.Settings.uiSettings&&null!==this.Settings.uiSettings&&(e.showAnimation=!0===this.Settings.uiSettings.showStartupAnimation||"true"==this.Settings.uiSettings.showStartupAnimation,this.Settings.uiSettings.startupLogoUrl&&(e.imageUrl=this.Settings.uiSettings.startupLogoUrl),this.Settings.uiSettings.startupBackgroundColor)&&(e.background=this.Settings.uiSettings.startupBackgroundColor),this.ClassicEditorUrl=this.getClassicEditorUrl(this.Settings.editorUrl,this.Settings.editorVersion,e)+"#"+encodeURIComponent(JSON.stringify(e))}stripEditorVersion(e){if(void 0!==(e=(e||"").trim())&&null!=e)if(e){for(;0==e.indexOf("/");)e=e.substring(1);for(;0<e.length&&"/"===e[e.length-1];)e=e.substring(0,e.length-1)}else e="";return e}sanitizeHost(e){return e?(e=e.trim()).endsWith("/")?e:e+"/":e||""}getClassicEditorUrl(e,t,i){var n=(e=e||"https://editor.printess.com/").indexOf("#");if(0<n){var s=e.substring(n+1);if(s)try{var o=JSON.parse(decodeURIComponent(s));if(o)for(var r in o)o.hasOwnProperty(r)&&(i[r]=o[r])}catch(e){}e=e.substring(0,n)}return e.toLowerCase().endsWith(".html")||(e=this.sanitizeHost(e),t&&(e+=(t=this.stripEditorVersion(t))+(t?"/":"")),e+="printess-editor/embed.html"),e=0!==e.toLowerCase().indexOf("https://")&&0!==e.toLowerCase().indexOf("http://")?"https://"+e:e}getLoaderUrl(e,t,i){var n=(e=e||"https://editor.printess.com/").indexOf("#");if(0<n){var s=e.substring(n+1);if(s)try{var o=JSON.parse(decodeURIComponent(s));if(o)for(var r in o)o.hasOwnProperty(r)&&(i[r]=o[r])}catch(e){}e=e.substring(0,n)}return(e=e.toLocaleLowerCase().endsWith("embed.html")?e.substring(0,e.length-"embed.html".length):e).toLowerCase().endsWith(".html")||(e=this.sanitizeHost(e),t&&(e+=(t=this.stripEditorVersion(t))+(t?"/":"")),e.toLowerCase().endsWith("printess-editor/")||(e+="printess-editor/"),e+="loader.js"),e=0!==e.toLowerCase().indexOf("https://")&&0!==e.toLowerCase().indexOf("http://")?"https://"+e:e}getPrintessComponent(){return document.querySelector("printess-component")||null}applyFormFieldMappings(t,i){var n=[];if(!i)for(const e in t)t.hasOwnProperty(e)&&n.push({name:e,value:t[e]});if(t)for(const r in t)if(t.hasOwnProperty(r)){var s=t[r],o=void 0!==i[r]&&void 0!==i[r].formField?i[r].formField:r;let e=s;void 0!==i[r]&&void 0!==i[r].values&&void 0!==i[r].values[e]&&(e=i[r].values[s]),n.push({name:o,value:e})}return n}reverseFormFieldMapping(e,t,i){let n=e||"",s=t||"";if(i)for(var o in i)if(i.hasOwnProperty(o)&&i[o].formField===e){if(i[n=o].values)for(var r in i[o].values)if(i[o].values.hasOwnProperty(r)&&i[o].values[r]===t){s=r;break}break}return{name:n,value:s}}setViewportMeta(){var i=document.getElementsByTagName("head");if(i&&0<i.length){let e=i[0].querySelector("meta[name=viewport]"),t=(e||((e=document.createElement("meta")).setAttribute("name","viewport"),i[0].appendChild(e)),e.getAttribute("content"));t?t.indexOf("interactive-widget")<0&&(t=t+(t?", ":"")+"interactive-widget=resizes-content",e.setAttribute("content",t)):e.setAttribute("content","interactive-widget=resizes-content")}}async initializeIFrame(t,e,i){const n=this;let s=document.getElementById("printess");const o=e=>{t&&"function"==typeof t.onCloseTab&&t.onCloseTab(e)},r=e=>{switch(e.data.cmd){case"back":window.removeEventListener("message",r),window.removeEventListener("beforeunload",o),window.removeEventListener("unload",o),s.setAttribute("printessHasListener","false"),t&&"function"==typeof t.onBack&&t.onBack();break;case"basket":window.removeEventListener("message",r),window.removeEventListener("beforeunload",o),window.removeEventListener("unload",o),s.setAttribute("printessHasListener","false"),t&&"function"==typeof t.onAddToBasket&&t.onAddToBasket(e.data.token,e.data.thumbnailUrl);break;case"formFieldChanged":t&&"function"==typeof t.onFormFieldChanged&&t.onFormFieldChanged(e.data.n||e.data.name,e.data.v||e.data.value,e.data.ffCaption||"",e.data.l||e.data.label);break;case"priceChanged":t&&"function"==typeof t.onPriceChanged&&t.onPriceChanged(e.data.priceInfo);break;case"renderFirstPageImage":t&&"function"==typeof t.onRenderedFirstPageImage&&t.onRenderedFirstPageImage(e.data.result);break;case"save":t&&"function"==typeof t.onSave&&t.onSave(e.data.token)}};return new Promise(e=>{var t;s?("true"!==s.getAttribute("printessHasListener")&&(window.addEventListener("message",r),!0===i.showAlertOnTabClose&&(window.addEventListener("beforeunload",o),window.addEventListener("unload",o)),s.setAttribute("printessHasListener","true")),e(s)):((t=document.createElement("div")).setAttribute("id","printess-container"),t.setAttribute("style","display: none; position: absolute; top: 0; bottom: 0; right: 0; left: 0; width: 100%; height: 100%; z-index: 100000;"),(s=document.createElement("iframe")).setAttribute("src",this.ClassicEditorUrl),s.setAttribute("id","printess"),s.setAttribute("style","width:100%; heigth:100%;"),s.setAttribute("data-attached","false"),s.setAttribute("allow","xr-spatial-tracking; clipboard-read; clipboard-write;"),s.setAttribute("allowfullscreen","true"),t.appendChild(s),s.onload=()=>{e(s)},window.addEventListener("message",r),!0===i.showAlertOnTabClose&&(window.addEventListener("beforeunload",o),window.addEventListener("unload",o)),s.setAttribute("printessHasListener","true"),window.visualViewport&&window.visualViewport.addEventListener("scroll",()=>{s.contentWindow?.postMessage({cmd:"viewportScroll",height:window.visualViewport?.height,offsetTop:window.visualViewport?.offsetTop},"*")},{passive:!0}),n.setViewportMeta(),document.body.append(t))})}getPriceCategories(e){return{snippetPrices:e.snippetPrices.map(e=>e?e.label:null),priceCategories:{},price:e.formatMoney(e.getPriceForFormFields(e.getCurrentFormFieldValues())),productName:e.getProductName(),legalNotice:e.legalText,infoUrl:e.legalTextUrl}}onPriceChanged(t,i){try{const n=document.getElementById("printess");let e=null;try{t.snippetPriceCategories&&0<t.snippetPriceCategories.length?i.stickers=t.snippetPriceCategories.filter(e=>i.snippetPrices&&i.snippetPrices.length>=e.priceCategory).map(e=>({productVariantId:i.snippetPrices[e.priceCategory-1].variantId,quantity:e.amount})):i.stickers=[],e=this.calculateCurrentPrices(t,i)}catch(e){console.error(e)}n&&!i.hidePricesInEditor&&setTimeout(()=>{n.contentWindow.postMessage({cmd:"refreshPriceDisplay",priceDisplay:e},"*")},0)}catch(e){}}hideBcUiVersion(e,t){var i=this.getPrintessComponent();i&&i.editor&&i.editor.ui.hide(),"function"==typeof e.editorClosed&&e.editorClosed(!0===t)}async showBcUiVersion(t,o){const i=this;var e=t.getPriceInfo();let n=null,s=null;n=i.applyFormFieldMappings(t.getCurrentFormFieldValues(),t.getFormFieldMappings()),s=t.getMergeTemplates();var r=i.getLoaderUrl(this.Settings.editorUrl,this.Settings.editorVersion,{}),r=await import(r);let a=i.getPrintessComponent();a&&a.editor?(a.style.display="block",await a.editor.api.loadTemplateAndFormFields(t.templateNameOrSaveToken,s,n,null),a.editor.ui.show()):(e={domain:i.Settings.apiDomain,mergeTemplates:s,formFields:n,token:i.Settings.shopToken,templateName:t.templateNameOrSaveToken,translationKey:"",basketId:"function"==typeof t.getBasketId&&t.getBasketId()||"Some-Unique-Basket-Or-Session-Id",shopUserId:"function"==typeof t.getUserId?t.getUserId()||"Some-Unique-Basket-Or-Session-Id":"Some-Unique-Shop-User-Id",snippetPriceCategoryLabels:e&&e.snippetPrices?e.snippetPrices:null,theme:i.Settings.uiSettings&&i.Settings.uiSettings.theme||"",addToBasketCallback:(e,t)=>{o&&"function"==typeof o.onAddToBasket&&o.onAddToBasket(e,t)},formFieldChangedCallback:(e,t,i,n,s)=>{o&&"function"==typeof o.onFormFieldChanged&&o.onFormFieldChanged(e,t,s,n)},priceChangeCallback:e=>{o&&"function"==typeof o.onPriceChanged&&o.onPriceChanged(e)},backButtonCallback:e=>{i.hideBcUiVersion(t,!0)},saveTemplateCallback:(e,t)=>{"function"==typeof o.onSave&&o.onSave(e)}},r=await r.load(e),(a=i.getPrintessComponent())&&(a.editor=r))}async show(s){const o=this;let i=!1;s&&s.templateNameOrSaveToken&&(i=0===s.templateNameOrSaveToken.indexOf("st:")&&90===s.templateNameOrSaveToken.length);var n={onBack:()=>{o.hide(s,!0)},onAddToBasket:(e,t)=>{const i=s.onAddToBasket(e,t);i&&i.waitUntilClosingMS?setTimeout(function(){"function"==typeof i.executeBeforeClosing&&i.executeBeforeClosing(),o.hide(s,!1)},i.waitUntilClosingMS):(i&&"function"==typeof i.executeBeforeClosing&&i.executeBeforeClosing(),o.hide(s,!1))},onFormFieldChanged:(e,t,i,n)=>{e=o.reverseFormFieldMapping(e,t,s.getFormFieldMappings());"function"==typeof s.onFormFieldChanged&&s.onFormFieldChanged(e.name,e.value,i,n)},onPriceChanged:e=>{o.onPriceChanged(e,s)},onRenderedFirstPageImage:e=>{"function"==typeof s.onRenderFirstPageImage&&s.onRenderFirstPageImage(e)},onSave:e=>{"function"==typeof s.onSave&&s.onSave(e,"")},onCloseTab:e=>{e.preventDefault(),e.returnValue=""}};if(this.Settings.uiSettings&&"bcui"===this.Settings.uiSettings.uiVersion)o.showBcUiVersion(s,n);else{var r=s.getPriceInfo();let e=null,t=null;i||(e=this.applyFormFieldMappings(s.getCurrentFormFieldValues(),s.getFormFieldMappings()),t=s.getMergeTemplates());n=await this.initializeIFrame(n,s,this.Settings);if("false"===n.getAttribute("data-attached"))try{var a={domain:o.Settings.apiDomain,token:this.Settings.shopToken||"",templateName:s.templateNameOrSaveToken,showBuyerSide:!0,templateUserId:"",basketId:"function"==typeof s.getBasketId&&s.getBasketId()||"Some-Unique-Basket-Or-Session-Id",shopUserId:"function"==typeof s.getUserId?s.getUserId()||"Some-Unique-Basket-Or-Session-Id":"Some-Unique-Shop-User-Id",formFields:e,snippetPriceCategoryLabels:r&&r.snippetPrices?r.snippetPrices:null,mergeTemplates:t};if(void 0!==s.showSplitterGridSizeButton&&null!==s.showSplitterGridSizeButton&&(a.showSplitterGridSizeButton=!0===s.showSplitterGridSizeButton||"true"===s.showSplitterGridSizeButton),this.Settings.uiSettings&&this.Settings.uiSettings.theme&&(a.theme=this.Settings.uiSettings.theme),this.Settings.attachParams)for(const d in this.Settings.attachParams)this.Settings.attachParams.hasOwnProperty(d)&&(a[d]=this.Settings.attachParams[d]);if(void 0!==s.additionalAttachParams||null!==s.additionalAttachParams)for(const l in s.additionalAttachParams)s.additionalAttachParams.hasOwnProperty(l)&&(a[l]=s.additionalAttachParams[l]);n.contentWindow.postMessage({cmd:"attach",properties:a},"*"),n.setAttribute("data-attached","true")}catch(e){console.error(e)}else n.contentWindow.postMessage({cmd:"loadTemplateAndFormFields",parameters:[s.templateNameOrSaveToken,t,e,void 0]},"*")}document.body.classList.add("hideAll");r=document.getElementsByTagName("html"),r&&0<r.length&&r[0].classList.add("printessEditorOpen"),n=document.getElementById("printess-container");n&&n.style.setProperty("display","block","important")}hide(e,t){this.Settings.uiSettings&&"bcui"===this.Settings.uiSettings.uiVersion?(i=this.getPrintessComponent())&&i.editor&&i.editor.ui.hide():(i=document.getElementById("printess-container"))&&(i.style.display="none"),document.body.classList.remove("hideAll");var i=document.getElementsByTagName("html");i&&0<i.length&&i[0].classList.remove("printessEditorOpen"),"function"==typeof e.editorClosed&&e.editorClosed(!0===t)}}function initPrintessEditor(e,t,i,n,s,o,r=""){let a;return a=e&&"string"!=typeof e?{apiDomain:e.apiDomain||null,shopToken:e.shopToken||"",editorUrl:e.editorUrl||"",editorVersion:e.editorVersion||"",attachParams:e.attachParams||"",showAlertOnTabClose:void 0!==e.showTabClosingAlert&&null!==e.showTabClosingAlert&&!0===e.showTabClosingAlert,uiSettings:{showStartupAnimation:void 0===e.showStartupAnimation||null===e.showStartupAnimation||!0===e.showStartupAnimation,startupBackgroundColor:e.startupBackgroundColor||"#ffffff",theme:e.theme||"",startupLogoUrl:e.startupLogoUrl||"",uiVersion:e.uiVersion||""},...e}:{apiDomain:null,shopToken:e||"",editorUrl:t,editorVersion:i,uiSettings:{showStartupAnimation:s,startupBackgroundColor:r,startupLogoUrl:n,theme:o}},new PrintessEditor(a)};
     1class PrintessEditor{constructor(e){if(this.calculateCurrentPrices=(e,t)=>{var i=this.getPriceCategories(t);let n=t.getPriceForFormFields(t.getCurrentFormFieldValues());return e.snippetPriceCategories&&e.snippetPriceCategories.forEach(e=>{e&&0<e.amount&&t.snippetPrices[e.priceCategory-1]&&(n+=t.snippetPrices[e.priceCategory-1].priceInCent)}),i.price=t.formatMoney(n),i},!e||!e.shopToken)throw"No shop token provided";this.Settings={...e};e={};null!=this.Settings.uiSettings&&(e.showAnimation=!0===this.Settings.uiSettings.showStartupAnimation||"true"==this.Settings.uiSettings.showStartupAnimation,this.Settings.uiSettings.startupLogoUrl&&(e.imageUrl=this.Settings.uiSettings.startupLogoUrl),this.Settings.uiSettings.startupBackgroundColor)&&(e.background=this.Settings.uiSettings.startupBackgroundColor),this.ClassicEditorUrl=this.getClassicEditorUrl(this.Settings.editorUrl,this.Settings.editorVersion,e)+"#"+encodeURIComponent(JSON.stringify(e))}stripEditorVersion(e){if(void 0!==(e=(e||"").trim())&&null!=e)if(e){for(;0==e.indexOf("/");)e=e.substring(1);for(;0<e.length&&"/"===e[e.length-1];)e=e.substring(0,e.length-1)}else e="";return e}sanitizeHost(e){return e?(e=e.trim()).endsWith("/")?e:e+"/":e||""}getClassicEditorUrl(e,t,i){var n=(e=e||"https://editor.printess.com/").indexOf("#");if(0<n){var s=e.substring(n+1);if(s)try{var r=JSON.parse(decodeURIComponent(s));if(r)for(var o in r)r.hasOwnProperty(o)&&(i[o]=r[o])}catch(e){}e=e.substring(0,n)}return e.toLowerCase().endsWith(".html")||(e=this.sanitizeHost(e),t&&(e+=(t=this.stripEditorVersion(t))+(t?"/":"")),e+="printess-editor/embed.html"),e=0!==e.toLowerCase().indexOf("https://")&&0!==e.toLowerCase().indexOf("http://")?"https://"+e:e}getLoaderUrl(e,t,i){var n=(e=e||"https://editor.printess.com/").indexOf("#");if(0<n){var s=e.substring(n+1);if(s)try{var r=JSON.parse(decodeURIComponent(s));if(r)for(var o in r)r.hasOwnProperty(o)&&(i[o]=r[o])}catch(e){}e=e.substring(0,n)}return(e=e.toLocaleLowerCase().endsWith("embed.html")?e.substring(0,e.length-"embed.html".length):e).toLowerCase().endsWith(".html")||(e=this.sanitizeHost(e),t&&(e+=(t=this.stripEditorVersion(t))+(t?"/":"")),e.toLowerCase().endsWith("printess-editor/")||(e+="printess-editor/"),e+="loader.js"),e=0!==e.toLowerCase().indexOf("https://")&&0!==e.toLowerCase().indexOf("http://")?"https://"+e:e}getPrintessComponent(){return document.querySelector("printess-component")||null}applyFormFieldMappings(t,i){var n=[];if(!i)for(var e in t)t.hasOwnProperty(e)&&n.push({name:e,value:t[e]});if(t)for(var s in t)if(t.hasOwnProperty(s)){var r=t[s],o=void 0!==i[s]&&void 0!==i[s].formField?i[s].formField:s;let e=r;void 0!==i[s]&&void 0!==i[s].values&&void 0!==i[s].values[e]&&(e=i[s].values[r]),n.push({name:o,value:e})}return n}reverseFormFieldMapping(e,t,i){let n=e||"",s=t||"";if(i)for(var r in i)if(i.hasOwnProperty(r)&&i[r].formField===e){if(i[n=r].values)for(var o in i[r].values)if(i[r].values.hasOwnProperty(o)&&i[r].values[o]===t){s=o;break}break}return{name:n,value:s}}setViewportMeta(){var i=document.getElementsByTagName("head");if(i&&0<i.length){let e=i[0].querySelector("meta[name=viewport]"),t=(e||((e=document.createElement("meta")).setAttribute("name","viewport"),i[0].appendChild(e)),e.getAttribute("content"));t?t.indexOf("interactive-widget")<0&&(t=t+(t?", ":"")+"interactive-widget=resizes-content",e.setAttribute("content",t)):e.setAttribute("content","interactive-widget=resizes-content")}}async initializeIFrame(t,e,i){let n=this,s=document.getElementById("printess"),r=e=>{t&&"function"==typeof t.onCloseTab&&t.onCloseTab(e)},o=e=>{switch(e.data.cmd){case"back":window.removeEventListener("message",o),window.removeEventListener("beforeunload",r),window.removeEventListener("unload",r),s.setAttribute("printessHasListener","false"),t&&"function"==typeof t.onBack&&t.onBack();break;case"basket":window.removeEventListener("message",o),window.removeEventListener("beforeunload",r),window.removeEventListener("unload",r),s.setAttribute("printessHasListener","false"),t&&"function"==typeof t.onAddToBasket&&t.onAddToBasket(e.data.token,e.data.thumbnailUrl);break;case"formFieldChanged":t&&"function"==typeof t.onFormFieldChanged&&t.onFormFieldChanged(e.data.n||e.data.name,e.data.v||e.data.value,e.data.ffCaption||"",e.data.l||e.data.label);break;case"priceChanged":t&&"function"==typeof t.onPriceChanged&&t.onPriceChanged(e.data.priceInfo);break;case"renderFirstPageImage":t&&"function"==typeof t.onRenderedFirstPageImage&&t.onRenderedFirstPageImage(e.data.result);break;case"save":t&&"function"==typeof t.onSave&&t.onSave(e.data.token)}};return new Promise(e=>{var t;s?("true"!==s.getAttribute("printessHasListener")&&(window.addEventListener("message",o),!0===i.showAlertOnTabClose&&(window.addEventListener("beforeunload",r),window.addEventListener("unload",r)),s.setAttribute("printessHasListener","true")),e(s)):((t=document.createElement("div")).setAttribute("id","printess-container"),t.setAttribute("style","display: none; position: absolute; top: 0; bottom: 0; right: 0; left: 0; width: 100%; height: 100%; z-index: 100000;"),(s=document.createElement("iframe")).setAttribute("src",this.ClassicEditorUrl),s.setAttribute("id","printess"),s.setAttribute("style","width:100%; heigth:100%;"),s.setAttribute("data-attached","false"),s.setAttribute("allow","xr-spatial-tracking; clipboard-read; clipboard-write;"),s.setAttribute("allowfullscreen","true"),t.appendChild(s),s.onload=()=>{e(s)},window.addEventListener("message",o),!0===i.showAlertOnTabClose&&(window.addEventListener("beforeunload",r),window.addEventListener("unload",r)),s.setAttribute("printessHasListener","true"),window.visualViewport&&window.visualViewport.addEventListener("scroll",()=>{s.contentWindow?.postMessage({cmd:"viewportScroll",height:window.visualViewport?.height,offsetTop:window.visualViewport?.offsetTop},"*")},{passive:!0}),n.setViewportMeta(),document.body.append(t))})}getPriceCategories(e){return{snippetPrices:e.snippetPrices.map(e=>e?e.label:null),priceCategories:{},price:e.formatMoney(e.getPriceForFormFields(e.getCurrentFormFieldValues())),productName:e.getProductName(),legalNotice:e.legalText,infoUrl:e.legalTextUrl}}onPriceChanged(i,n){try{let e=document.getElementById("printess"),t=null;try{i.snippetPriceCategories&&0<i.snippetPriceCategories.length?n.stickers=i.snippetPriceCategories.filter(e=>n.snippetPrices&&n.snippetPrices.length>=e.priceCategory).map(e=>({productVariantId:n.snippetPrices[e.priceCategory-1].variantId,quantity:e.amount})):n.stickers=[],t=this.calculateCurrentPrices(i,n)}catch(e){console.error(e)}e&&!n.hidePricesInEditor&&setTimeout(()=>{e.contentWindow.postMessage({cmd:"refreshPriceDisplay",priceDisplay:t},"*")},0)}catch(e){}}hideBcUiVersion(e,t){var i=this.getPrintessComponent();i&&i.editor&&i.editor.ui.hide(),"function"==typeof e.editorClosed&&e.editorClosed(!0===t)}async showBcUiVersion(t,r){let i=this;var e=t.getPriceInfo();let n=null,s=null;n=i.applyFormFieldMappings(t.getCurrentFormFieldValues(),t.getFormFieldMappings()),s=t.getMergeTemplates();var o=i.getLoaderUrl(this.Settings.editorUrl,this.Settings.editorVersion,{}),o=await import(o);let a=i.getPrintessComponent();a&&a.editor?(a.style.display="block",await a.editor.api.loadTemplateAndFormFields(t.templateNameOrSaveToken,s,n,null),a.editor.ui.show()):(e={domain:i.Settings.apiDomain,mergeTemplates:s,formFields:n,token:i.Settings.shopToken,templateName:t.templateNameOrSaveToken,translationKey:"",basketId:"function"==typeof t.getBasketId&&t.getBasketId()||"Some-Unique-Basket-Or-Session-Id",shopUserId:"function"==typeof t.getUserId?t.getUserId()||"Some-Unique-Basket-Or-Session-Id":"Some-Unique-Shop-User-Id",snippetPriceCategoryLabels:e&&e.snippetPrices?e.snippetPrices:null,theme:i.Settings.uiSettings&&i.Settings.uiSettings.theme||"",addToBasketCallback:(e,t)=>{r&&"function"==typeof r.onAddToBasket&&r.onAddToBasket(e,t)},formFieldChangedCallback:(e,t,i,n,s)=>{r&&"function"==typeof r.onFormFieldChanged&&r.onFormFieldChanged(e,t,s,n)},priceChangeCallback:e=>{r&&"function"==typeof r.onPriceChanged&&r.onPriceChanged(e)},backButtonCallback:e=>{i.hideBcUiVersion(t,!0)},saveTemplateCallback:(e,t)=>{"function"==typeof r.onSave&&r.onSave(e)}},o=await o.load(e),(a=i.getPrintessComponent())&&(a.editor=o))}async show(s){let r=this,i=!1;s&&s.templateNameOrSaveToken&&(i=0===s.templateNameOrSaveToken.indexOf("st:")&&90===s.templateNameOrSaveToken.length);var n={onBack:()=>{r.hide(s,!0)},onAddToBasket:(e,t)=>{let i=s.onAddToBasket(e,t);i&&i.waitUntilClosingMS?setTimeout(function(){"function"==typeof i.executeBeforeClosing&&i.executeBeforeClosing(),r.hide(s,!1)},i.waitUntilClosingMS):(i&&"function"==typeof i.executeBeforeClosing&&i.executeBeforeClosing(),r.hide(s,!1))},onFormFieldChanged:(e,t,i,n)=>{e=r.reverseFormFieldMapping(e,t,s.getFormFieldMappings());"function"==typeof s.onFormFieldChanged&&s.onFormFieldChanged(e.name,e.value,i,n)},onPriceChanged:e=>{r.onPriceChanged(e,s)},onRenderedFirstPageImage:e=>{"function"==typeof s.onRenderFirstPageImage&&s.onRenderFirstPageImage(e)},onSave:e=>{"function"==typeof s.onSave&&s.onSave(e,"")},onCloseTab:e=>{e.preventDefault(),e.returnValue=""}};if(this.Settings.uiSettings&&"bcui"===this.Settings.uiSettings.uiVersion)r.showBcUiVersion(s,n);else{var o=s.getPriceInfo();let e=null,t=null;i||(e=this.applyFormFieldMappings(s.getCurrentFormFieldValues(),s.getFormFieldMappings()),t=s.getMergeTemplates());n=await this.initializeIFrame(n,s,this.Settings);if("false"===n.getAttribute("data-attached"))try{var a={domain:r.Settings.apiDomain,token:this.Settings.shopToken||"",templateName:s.templateNameOrSaveToken,showBuyerSide:!0,templateUserId:"",basketId:"function"==typeof s.getBasketId&&s.getBasketId()||"Some-Unique-Basket-Or-Session-Id",shopUserId:"function"==typeof s.getUserId?s.getUserId()||"Some-Unique-Basket-Or-Session-Id":"Some-Unique-Shop-User-Id",formFields:e,snippetPriceCategoryLabels:o&&o.snippetPrices?o.snippetPrices:null,mergeTemplates:t};if(null!=s.showSplitterGridSizeButton&&(a.showSplitterGridSizeButton=!0===s.showSplitterGridSizeButton||"true"===s.showSplitterGridSizeButton),this.Settings.uiSettings&&this.Settings.uiSettings.theme&&(a.theme=this.Settings.uiSettings.theme),this.Settings.attachParams)for(var d in this.Settings.attachParams)this.Settings.attachParams.hasOwnProperty(d)&&(a[d]=this.Settings.attachParams[d]);if(void 0!==s.additionalAttachParams||null!==s.additionalAttachParams)for(var l in s.additionalAttachParams)s.additionalAttachParams.hasOwnProperty(l)&&(a[l]=s.additionalAttachParams[l]);n.contentWindow.postMessage({cmd:"attach",properties:a},"*"),n.setAttribute("data-attached","true"),n.contentWindow.focus()}catch(e){console.error(e)}else n.contentWindow.postMessage({cmd:"loadTemplateAndFormFields",parameters:[s.templateNameOrSaveToken,t,e,void 0]},"*"),n.contentWindow.focus()}document.body.classList.add("hideAll");o=document.getElementsByTagName("html"),o&&0<o.length&&o[0].classList.add("printessEditorOpen"),n=document.getElementById("printess-container");n&&n.style.setProperty("display","block","important")}hide(e,t){this.Settings.uiSettings&&"bcui"===this.Settings.uiSettings.uiVersion?(i=this.getPrintessComponent())&&i.editor&&i.editor.ui.hide():(i=document.getElementById("printess-container"))&&(i.style.display="none"),document.body.classList.remove("hideAll");var i=document.getElementsByTagName("html");i&&0<i.length&&i[0].classList.remove("printessEditorOpen"),"function"==typeof e.editorClosed&&e.editorClosed(!0===t)}}function initPrintessEditor(e,t,i,n,s,r,o=""){let a;return a=e&&"string"!=typeof e?{apiDomain:e.apiDomain||null,shopToken:e.shopToken||"",editorUrl:e.editorUrl||"",editorVersion:e.editorVersion||"",attachParams:e.attachParams||"",showAlertOnTabClose:null!=e.showTabClosingAlert&&!0===e.showTabClosingAlert,uiSettings:{showStartupAnimation:null==e.showStartupAnimation||!0===e.showStartupAnimation,startupBackgroundColor:e.startupBackgroundColor||"#ffffff",theme:e.theme||"",startupLogoUrl:e.startupLogoUrl||"",uiVersion:e.uiVersion||""},...e}:{apiDomain:null,shopToken:e||"",editorUrl:t,editorVersion:i,uiSettings:{showStartupAnimation:s,startupBackgroundColor:o,startupLogoUrl:n,theme:r}},new PrintessEditor(a)};
  • printess-editor/trunk/includes/js/printessWoocommerce.js

    r3170651 r3182931  
    1 const initPrintessWCEditor=function(f){const p="form.cart";if(void 0!==window.printessWooEditor)return window.printessWooEditor;function l(e,t,n,s){function r(e,t){(e=document.getElementById(e))&&(e.value=t)}r("printess-save-token",e),t&&r("printess-thumbnail-url",t),n&&r("printess-design-id",n),s&&r("printess-additional-settings",JSON.stringify(s))}function s(g){const v={templateNameOrSaveToken:g.templateNameOrSaveToken||g.product.templateName,stickers:[],legalText:g.legalText||"",legalTextUrl:g.legalUrl||"",snippetPrices:[],chargeEachStickerUsage:!1,hidePricesInEditor:void 0!==f.showPricesInEditor&&!1===f.showPricesInEditor,getProductName:()=>(void 0===f.showProductName||!1!==f.showProductName)&&(g.product&&g.product.name)||"",getPriceInfo:()=>null,getMergeTemplates:()=>{let e=[];if(g.mergeTemplates)if("string"==typeof g.mergeTemplates)try{var t=JSON.parse(g.mergeTemplates);if(!Array.isArray(t))return[];e=[...e,...t.map(e=>"string"==typeof e?{templateName:e}:e)]}catch(e){return[]}else e=[...e,...g.mergeTemplates.map(e=>"string"==typeof e?{templateName:e}:e)];return e=g.product.mergeTemplates?[...e,...g.product.mergeTemplates.map(e=>"string"==typeof e?{templateName:e}:e)]:e},formatMoney:e=>f.priceFormatOptions?(!0===f.priceFormatOptions.currencySymbolOnLeftSide?f.priceFormatOptions.currencySymbol:"")+((e,t,n,s)=>{e=(e+"").replace(/[^0-9+\-Ee.]/g,"");e=isFinite(+e)?+e:0,t=isFinite(+t)?Math.abs(t):0,s=void 0===s?",":s,n=void 0===n?".":n,e=(t?function(e,t){t=Math.pow(10,t);return""+Math.round(e*t)/t}(e,t):""+Math.round(e)).split(".");return 3<e[0].length&&(e[0]=e[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,s)),(e[1]||"").length<t&&(e[1]=e[1]||"",e[1]+=new Array(t-e[1].length+1).join("0")),e.join(n)})(""+e,2,f.priceFormatOptions.decimalSeperator,f.priceFormatOptions.thousandsSeperator)+(!0!==f.priceFormatOptions.currencySymbolOnLeftSide?f.priceFormatOptions.currencySymbol:""):parseFloat(""+e).toFixed(2),onFormFieldChanged:(e,s,t,r)=>{var n=o(g.product);let i=e;n[e]?i=n[e].key:n[t]&&(i=n[t].key);e=document.querySelectorAll('input[type="radio"][name="attribute_'+i+'"], input[type="radio"][name="'+i+'"],input[type="radio"][name="attribute_'+t+'"], input[type="radio"][name="'+t+'"]');if(e&&0<e.length)e.forEach(e=>{e.getAttribute("value")===s||e.getAttribute("value")===r?(e.setAttribute("checked",(!0).toString()),e.checked=!0):(e.removeAttribute("checked"),e.checked=!1)});else{n=document.querySelectorAll('select[name="attribute_'+i+'"],select[name="'+i+'"],select[name="attribute_'+t+'"],select[name="'+t+'"]');if(n&&0<n.length)n.forEach(t=>{if(t.options)for(let e=0;e<t.options.length;++e){var n=t.options[e].getAttribute("value");s==n||r===n?(t.options[e].setAttribute("selected",(!0).toString()),t.options[e].selected=!0,t.setAttribute("value",n),t.value=n):(t.options[e].removeAttribute("selected"),t.options[e].selected=!1)}});else{e=document.querySelectorAll('input[name="attribute_'+i+'"],input[name="'+i+'"],input[name="attribute_'+t+'"],input[name="'+t+'"]');const a=["color","date","datetime-local","email","month","number","tel","text","time","url","week"];e&&0<e.length&&e.forEach(e=>{-1<a.indexOf(e.getAttribute("type").toLowerCase())&&e.setAttribute("value",s)})}}},onAddToBasket:(t,n)=>{if("admin"===f.editorMode)w(t,n);else{let e=null;if(v.designId&&((e=e||{}).designId=v.designId),v.designName&&((e=e||{}).designName=v.designName),l(t,n,v.designId?.toString()??"",e),"buyer"===f.editorMode&&f.addToCartAfterCustomization){var s=document.querySelector(p),r=s.querySelector("[name=add-to-cart]"),i=h(g.product);const o=b(i,g.product),d=new URLSearchParams(window.location.search);o&&document.getElementsByName("variation_id").forEach(e=>e.setAttribute("value",o.id.toString())),r.hasAttribute("disabled")&&r.removeAttribute("disabled"),s&&f.cartUrl&&(void 0!==g.basketItemId&&g.basketItemId||(d.has("design_id")||d.has("design_name"))&&(d.get("design_id")||d.get("design_name")))?(s.setAttribute("action",f.cartUrl),(i=document.createElement("input")).setAttribute("id","printess_ignore_redirect"),i.setAttribute("name","printess_ignore_redirect"),i.value="true",s.appendChild(i)):(i=document.getElementById("printess_ignore_redirect"))&&i.remove();try{var a=y();a&&"function"==typeof a.onAddToBasket&&a.onAddToBasket(t,n)}catch(e){console.error(e)}"submit"===r.type?r.click():s.submit();return{executeBeforeClosing:()=>{if(!0===g.product.ajaxEnabled){let e="";g.product&&g.product.redirectUrl&&(e=g.product.redirectUrl),f.cartUrl&&void 0!==g.basketItemId&&g.basketItemId&&(e=f.cartUrl),(e=f.cartUrl&&(d.has("design_id")||d.has("design_name"))&&(d.get("design_id")||d.get("design_name"))?f.cartUrl:e)&&setTimeout(function(){window.location.href=e},200)}},waitUntilClosingMS:1e3}}}},getCurrentFormFieldValues:()=>h(g.product),getPriceForFormFields:e=>{e=b(e,g.product);return e?parseFloat(e.price):g.product.price},getFormFieldMappings:()=>{let e={};if(g.optionValueMappings&&"string"==typeof g.optionValueMappings)try{e=JSON.parse(g.optionValueMappings)}catch(e){console.error("Unable to parse form field mappings: "+e)}return e},onRenderFirstPageImage:e=>{if(v.cameFromSave&&v.lastSaveSaveToken){try{v.onSave(v.lastSaveSaveToken,e,!0)}catch(e){console.error(e)}v.cameFromSave=!1,v.lastSaveSaveToken=""}},onSave:(d,l,e=!1)=>{v.cameFromSave=!0,v.lastSaveSaveToken=d;const o=h(g.product),c=b(o,g.product);if(e){if("admin"===f.editorMode)return void w(d,l);const u=()=>{},m=e=>{var t,n,s,r,i,a,o;e&&e.trim()?(n=f.userMessages&&f.userMessages.savingDesign?f.userMessages.savingDesign:"Saving design to your list of saved designs",(s=document.getElementById("printess_information_overlay_background"))&&((t=document.getElementById("printess_information_overlay_text"))&&(t.innerHTML=n),s.classList.add("visible"),s.getAttribute("data-initialized")||(s.setAttribute("data-initialized","true"),document.body.appendChild(s))),t=d,n=l,s=g.product.id,r=e,e=v.designId,i=h(g.product,!1),a=(e,t)=>{E(),v.designName=e,v.designId=t;try{var n=y();n&&"function"==typeof n.onSave&&n.onSave(d,l)}catch(e){console.error(e)}},o=e=>{E(),alert(e),_(v.designName,f.userIsLoggedIn?m:p,u)},t={saveToken:t,thumbnailUrl:n,productId:s,displayName:r,options:JSON.stringify(i)},"string"==typeof e&&e?(n=parseInt(e),!isNaN(n)&&0<n&&(t.designId=n)):"number"==typeof e&&e&&!isNaN(e)&&0<e&&(t.designId=e),fetch("/index.php/wp-json/printess/v1/design/add",{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":f.nonce},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify(t)}).then(e=>(e.ok?e.json().then(e=>{"function"==typeof a&&a(r,e)}):(console.error(e.statusText),"function"==typeof o&&o(f.userMessages&&f.userMessages.saveError?f.userMessages.saveError:"There was an error while trying to save your design")),e)).catch(function(e){console.log(e),"function"==typeof o&&o(f.userMessages&&f.userMessages.saveError?f.userMessages.saveError:"There was an error while trying to save your design")})):(alert(f.userMessages&&f.userMessages.noDisplayName?f.userMessages.noDisplayName:"Please provide a display name."),_(v.designName,f.userIsLoggedIn?m:p,u))},p=e=>{var t,n,s,r,i,a;[t,n,s,r,i,a=null]=[e,g.product.id,c?c.id:null,d,l,o],t&&t.trim()&&f.accountPageUrl?(n=f.accountPageUrl.replace("__ProductId__",""+n.toString()).replace("__SaveToken__",""+r).replace("__ThumbnailUrl__",encodeURIComponent(i)).replace("__VariantId__",""+s).replace("__Options__",encodeURIComponent(JSON.stringify(a??{}))).replace("__Token__",encodeURIComponent(f.urlToken||"")).replace("__DisplayName__",""+t.trim()),window.location.href=n):(alert(f.userMessages&&f.userMessages.noDisplayName?f.userMessages.noDisplayName:"Please provide a display name."),_(e,f.userIsLoggedIn?m:p,u))};_(v.designName,f.userIsLoggedIn?m:p,u)}else{var t="renderFirstPageImage";var n=null;const s=document.getElementById("printess");s&&setTimeout(function(){s.contentWindow.postMessage({cmd:t,properties:n||{}},"*")},0)}},getBasketId:()=>g.basketId,getUserId:()=>g.userId,editorClosed:e=>{var t;r.hide(),v.designId=null,v.designName=null,e&&l("","","",null),"buyer"===f.editorMode?"undefined"!=typeof URLSearchParams&&(t=new URLSearchParams(window.location.search),e&&t.has("design_id")||t.has("design_name")||t.has("printess-save-token"))&&(t.delete("design_id"),t.delete("design_name"),t.delete("printess-save-token"),window.location.search=t.toString()):(e=f.userMessages&&f.userMessages.closeWindow?f.userMessages.closeWindow:"Please close this window or tab.",alert(e))}};var e=h(g.product);(e=b(e,g.product))&&e.templateName&&(v.templateNameOrSaveToken=e.templateName);var t=(e=new URLSearchParams(window.location.search)).get("printess-save-token")||e.get("printess_save_token"),n=e.get("design_name"),e=e.get("design_id");return t&&(v.templateNameOrSaveToken=t),n&&(v.designName=n),e&&(v.designId=parseInt(e)),v}function g(e){let t="";var n=b(h(e),e),s=!(!e.variants||void 0===e.variants.find(e=>e.templateName));(t=null!=n&&n.templateName?n.templateName:t)||s||(t=e.templateName),I(t&&0<t.length)}function v(n){window.jQuery?window.jQuery("form").on("found_variation",(e,t)=>{g(n)}):setTimeout(v,100)}const y=()=>window&&window.printessGlobalConfig?window.printessGlobalConfig:{},h=function(t,n=!0){var s={},e={"add-to-cart":!0,product_id:!0,quantity:!0,variation_id:!0},r=y();if(r&&r.formFields)for(const c in r.formFields)r.hasOwnProperty(c)&&(s[c]=r.formFields[c]);function i(e){return n&&0===e.indexOf("attribute_")&&(e=e.substring(10,e.length)),e=t.attributes&&t.attributes[e]?t.attributes[e].name:e}var a=document.querySelector(p);if(a){for(const u of new FormData(a).entries()){var o=i(u[0]);0<o.length&&"_"!==o[0]&&!e[o]&&0!==o.indexOf("printess-")&&(s[o]=u[1].toString())}var d,l=a.querySelectorAll('input[type="checkbox"]');if(l&&0<l.length)for(let e=0;e<l.length;++e)void 0!==l[e].checked&&!0===l[e].checked&&0<(d=i(l[e].name)).length&&"_"!==d[0]&&(s[d]="true")}return s},o=e=>{var t={};if(e&&e.attributes)for(const n in e.attributes)e.attributes.hasOwnProperty(n)&&(t[e.attributes[n].name]=e.attributes[n]);return t},b=function(e,t){let n=t.variants?t.variants[0]:null;var s=o(t),r=[];for(const i in e)e.hasOwnProperty(i)&&s[i]&&r.push({key:s[i].key,value:e[i]});if(t.variants){let e=t.variants;r.forEach(t=>{e=e.filter(e=>e.attributes[t.key]===t.value)}),0<e.length&&(n=e[0])}return n},c=()=>{var e=document.getElementById("printess_overlay_background");e&&e.classList.remove("visible")},_=(e,n,t)=>{var s=document.getElementById("printess_show_if_not_logged_in");const r=document.getElementById("printess_overlay_background");let i=()=>{};const a=e=>{e.srcElement&&("input"===e.srcElement.nodeName.toLowerCase()||null!=e.srcElement.closest("div.printess_overlay_background"))||(e.preventDefault(),e.stopPropagation())},o=()=>{if(c(),i(),"function"==typeof n){let e="";var t=document.getElementById("printess_designnameedit");t&&(e=t.value),n(e)}},d=()=>{c(),i(),"function"==typeof t&&t()};i=()=>{var e=document.getElementById("printess_save_design_button"),e=(e&&e.removeEventListener("click",o),document.getElementById("printess_cancel_button"));e&&e.removeEventListener("click",d),r&&(r.removeEventListener("mousedown",a),r.removeEventListener("mouseup",a),r.removeEventListener("mousemove",a))},s&&(f.userIsLoggedIn?s.classList.add("logged_in"):s.classList.remove("logged_in"));var s=document.getElementById("printess_show_if_no_design_name"),l=document.getElementById("printess_show_if_design_name"),s=(s&&l&&(e?(s.classList.remove("visible"),l.classList.add("visible")):(s.classList.add("visible"),l.classList.remove("visible"))),document.getElementById("printess_designnameedit")),l=(s&&(s.value=e||""),r&&(r.addEventListener("mousedown",a),r.addEventListener("mouseup",a),r.addEventListener("mousemove",a),r.getAttribute("data-initialized")||(document.body.appendChild(r),r.setAttribute("data-initialized","true")),r.classList.add("visible")),document.getElementById("printess_save_design_button")),s=(l&&l.addEventListener("click",o),document.getElementById("printess_cancel_button"));s&&s.addEventListener("click",d)},E=()=>{var e=document.getElementById("printess_information_overlay_background");e&&e.classList.remove("visible")},w=(e,t)=>{var n=document.getElementById("printess-admin-save"),s=document.getElementById("printess-loading-message"),r=document.getElementById("printess-saving-message");s?.style.setProperty("display","none"),r?.style.setProperty("display","block"),n?(n.href+="&pst="+e,n.href+="&ptu="+encodeURI(t),n.click()):alert("Error: Redirect link not found. Unable to save changes")},I=function(t){var e=document.getElementsByName("printess-customize-button"),n=document.querySelector(p+" button.single_add_to_cart_button");e&&0!==e.length&&(n&&(t?n.setAttribute("disabled","disabled"):n.removeAttribute("disabled"),n.style.display=t?"none":"inline-block"),e.forEach(e=>e.style.display=t?"inline-block":"none"))},r={show:function(e){if(!(e=>{var t=o(e),n=[],s=h(e);for(const r in s)s.hasOwnProperty(r)&&t[r]&&n.push({key:t[r].key,value:s[r]});for(const i in n)if(n.hasOwnProperty(i)&&!n[i].value)return!0;return!1})(e.product)){var e=s(e),t=(f.idsToHide&&f.idsToHide.forEach(e=>{e=document.getElementById(e);e&&e.classList.add("printess-hide")}),f.classesToHide&&f.classesToHide.forEach(e=>{e=document.getElementsByClassName(e);if(e&&e.length)for(const t of e)t.classList.add("printess-hide")}),y());if(t&&t.attachParams)for(const n in t.attachParams)t.attachParams.hasOwnProperty(n)&&(f.attachParams||(f.attachParams={}),f.attachParams[n]=t.attachParams[n]);"function"==typeof window.initPrintessEditor&&window.initPrintessEditor(f).show(e)}},hide:function(){f.idsToHide.forEach(e=>{e=document.getElementById(e);e&&e.classList.remove("printess-hide")}),f.classesToHide.forEach(e=>{e=document.getElementsByClassName(e);if(e&&e.length)for(const t of e)t.classList.remove("printess-hide")})},initProductPage:function(e,t,n,s="Customize",r,i=p){i=document.querySelector(i||p);if(i){{var a=t;var o=document.createElement("input"),d=document.createElement("input"),l=document.createElement("input"),c=document.createElement("input"),u=document.createElement("input");const m=document.createElement("button");o.setAttribute("id","printess-save-token"),o.setAttribute("name","printess-save-token"),o.setAttribute("type","hidden"),u.setAttribute("id","printess-additional-settings"),u.setAttribute("name","printess-additional-settings"),u.setAttribute("type","hidden"),d.setAttribute("id","printess-save-token-to-remove-from-cart"),d.setAttribute("name","printess-save-token-to-remove-from-cart"),d.setAttribute("type","hidden"),d.setAttribute("value",a||""),l.setAttribute("id","printess-thumbnail-url"),l.setAttribute("name","printess-thumbnail-url"),l.setAttribute("type","hidden"),c.setAttribute("id","printess-design-id"),c.setAttribute("name","printess-design-id"),c.setAttribute("type","hidden"),m.setAttribute("id","printess-customize-button"),m.setAttribute("name","printess-customize-button"),m.setAttribute("type","button"),m.setAttribute("onclick","showPrintessEditor();"),m.classList.add("wp-element-button","single_add_to_cart_button","button","alt"),f.customizeButtonClasses&&f.customizeButtonClasses.split(" ").forEach(e=>{(e=(e||"").trim())&&m.classList.add(e)}),m.appendChild(document.createTextNode(s||"Customize")),n&&m.classList.add(n);a=document.querySelector(p+" button.single_add_to_cart_button");(a&&a.parentElement?a.parentElement:i).appendChild(m),i.appendChild(o),i.appendChild(d),i.appendChild(l),i.appendChild(c),i.appendChild(u)}t&&I(!0)}v(e),g(e);s=new URLSearchParams(window.location.search).get("printess-save-token");s&&"function"==typeof r&&r(s)}};return window.printessWooEditor=r};
     1let initPrintessWCEditor=function(f){let m="form.cart",d=null;if(void 0!==window.printessWooEditor)return window.printessWooEditor;function l(e,t,r,i){function n(e,t){(e=document.getElementById(e))&&(e.value=t)}n("printess-save-token",e),t&&n("printess-thumbnail-url",t),r&&n("printess-design-id",r),i&&n("printess-design-name",i)}function i(g){let v={templateNameOrSaveToken:g.templateNameOrSaveToken||g.product.templateName,stickers:[],legalText:g.legalText||"",legalTextUrl:g.legalUrl||"",snippetPrices:[],chargeEachStickerUsage:!1,hidePricesInEditor:void 0!==f.showPricesInEditor&&!1===f.showPricesInEditor,getProductName:()=>(void 0===f.showProductName||!1!==f.showProductName)&&g.product&&g.product.name||"",getPriceInfo:()=>null,getMergeTemplates:()=>{let e=[];if(g.mergeTemplates)if("string"==typeof g.mergeTemplates)try{var t=JSON.parse(g.mergeTemplates);if(!Array.isArray(t))return[];e=[...e,...t.map(e=>"string"==typeof e?{templateName:e}:e)]}catch(e){return[]}else e=[...e,...g.mergeTemplates.map(e=>"string"==typeof e?{templateName:e}:e)];return e=g.product.mergeTemplates?[...e,...g.product.mergeTemplates.map(e=>"string"==typeof e?{templateName:e}:e)]:e},formatMoney:e=>f.priceFormatOptions?(!0===f.priceFormatOptions.currencySymbolOnLeftSide?f.priceFormatOptions.currencySymbol:"")+s(""+e,2,f.priceFormatOptions.decimalSeperator,f.priceFormatOptions.thousandsSeperator)+(!0!==f.priceFormatOptions.currencySymbolOnLeftSide?f.priceFormatOptions.currencySymbol:""):parseFloat(""+e).toFixed(2),onFormFieldChanged:(t,i,e,n)=>{var r=c(g.product);let s=t;r[t]?s=r[t].key:r[e]&&(s=r[e].key);var r=y(),a=(r&&r.pricePerUsageFields&&(Array.isArray(r.pricePerUsageFields)?(a=r.pricePerUsageFields.filter(e=>e.formFieldName===t))&&0<a.length&&(0<(o=parseInt(i))?(d=d||{})[a[0].formFieldName]=o:d[a[0].formFieldName]&&delete d[a[0].formFieldName]):r.pricePerUsageFields[t]&&(0<(o=parseInt(i))?(d=d||{})[t]=o:d[t]&&delete d[t])),document.querySelectorAll('input[type="radio"][name="attribute_'+s+'"], input[type="radio"][name="'+s+'"],input[type="radio"][name="attribute_'+e+'"], input[type="radio"][name="'+e+'"]'));if(a&&0<a.length)a.forEach(e=>{e.getAttribute("value")===i||e.getAttribute("value")===n?(e.setAttribute("checked",(!0).toString()),e.checked=!0):(e.removeAttribute("checked"),e.checked=!1)});else{r=document.querySelectorAll('select[name="attribute_'+s+'"],select[name="'+s+'"],select[name="attribute_'+e+'"],select[name="'+e+'"]');if(r&&0<r.length)r.forEach(t=>{if(t.options)for(let e=0;e<t.options.length;++e){var r=t.options[e].getAttribute("value");i==r||n===r?(t.options[e].setAttribute("selected",(!0).toString()),t.options[e].selected=!0,t.setAttribute("value",r),t.value=r):(t.options[e].removeAttribute("selected"),t.options[e].selected=!1)}});else{var o=document.querySelectorAll('input[name="attribute_'+s+'"],input[name="'+s+'"],input[name="attribute_'+e+'"],input[name="'+e+'"]');let t=["color","date","datetime-local","email","month","number","tel","text","time","url","week"];o&&0<o.length&&o.forEach(e=>{-1<t.indexOf(e.getAttribute("type").toLowerCase())&&e.setAttribute("value",i)})}}},onAddToBasket:(e,i)=>{if("admin"===f.editorMode)w(e,i);else if(l(e,i,v.designId?.toString()??"",v.designName?.toString()??""),"buyer"===f.editorMode&&f.addToCartAfterCustomization){var n=document.querySelector(m),s=n.querySelector("[name=add-to-cart]"),a=h(g.product);let t=b(a,g.product),r=new URLSearchParams(window.location.search);t&&document.getElementsByName("variation_id").forEach(e=>e.setAttribute("value",t.id.toString())),s.hasAttribute("disabled")&&s.removeAttribute("disabled"),n&&f.cartUrl&&(void 0!==g.basketItemId&&g.basketItemId||(r.has("design_id")||r.has("design_name"))&&(r.get("design_id")||r.get("design_name")))?(n.setAttribute("action",f.cartUrl),(a=document.createElement("input")).setAttribute("id","printess_ignore_redirect"),a.setAttribute("name","printess_ignore_redirect"),a.value="true",n.appendChild(a)):(a=document.getElementById("printess_ignore_redirect"))&&a.remove(),n&&d&&((a=document.createElement("input")).setAttribute("id","printess_item_usage"),a.setAttribute("name","printess_item_usage"),a.value=JSON.stringify(d),n.appendChild(a));try{var o=y();o&&"function"==typeof o.onAddToBasket&&o.onAddToBasket(e,i)}catch(e){console.error(e)}"submit"===s.type?s.click():n.submit();return{executeBeforeClosing:()=>{if(!0===g.product.ajaxEnabled){let e="";g.product&&g.product.redirectUrl&&(e=g.product.redirectUrl),f.cartUrl&&void 0!==g.basketItemId&&g.basketItemId&&(e=f.cartUrl),(e=f.cartUrl&&(r.has("design_id")||r.has("design_name"))&&(r.get("design_id")||r.get("design_name"))?f.cartUrl:e)&&setTimeout(function(){window.location.href=e},200)}},waitUntilClosingMS:1e3}}},getCurrentFormFieldValues:()=>h(g.product),getPriceForFormFields:e=>{e=b(e,g.product);let r=e?parseFloat(e.price):g.product.price;var i=y();if(d&&i&&i.pricePerUsageFields){let t={};if(Array.isArray(i.pricePerUsageFields))for(let e=0;e<i.pricePerUsageFields.length;++e)t[i.pricePerUsageFields[e].formFieldName]=i.pricePerUsageFields[e].pricePerUsage;else t=i.pricePerUsageFields;for(var n in d)d.hasOwnProperty(n)&&t[n]&&(r+=d[n]*t[n])}return r},getFormFieldMappings:()=>{let e={};if(g.optionValueMappings&&"string"==typeof g.optionValueMappings)try{e=JSON.parse(g.optionValueMappings)}catch(e){console.error("Unable to parse form field mappings: "+e)}return e},onRenderFirstPageImage:e=>{if(v.cameFromSave&&v.lastSaveSaveToken){try{v.onSave(v.lastSaveSaveToken,e,!0)}catch(e){console.error(e)}v.cameFromSave=!1,v.lastSaveSaveToken=""}},onSave:(c,u,e=!1)=>{v.cameFromSave=!0,v.lastSaveSaveToken=c;let m=h(g.product),p=b(m,g.product);if(e){if("admin"===f.editorMode)return void w(c,u);let o=()=>{},d=e=>{var t,r,i;e&&e.trim()?(t=f.userMessages&&f.userMessages.savingDesign?f.userMessages.savingDesign:"Saving design to your list of saved designs",(i=document.getElementById("printess_information_overlay_background"))&&((r=document.getElementById("printess_information_overlay_text"))&&(r.innerHTML=t),i.classList.add("visible"),i.getAttribute("data-initialized")||(i.setAttribute("data-initialized","true"),document.body.appendChild(i))),((e,t,r,i,n,s,a,o)=>{e={saveToken:e,thumbnailUrl:t,productId:r,displayName:i,options:JSON.stringify(s)};"string"==typeof n&&n?(t=parseInt(n),!isNaN(t)&&0<t&&(e.designId=t)):"number"==typeof n&&n&&!isNaN(n)&&0<n&&(e.designId=n),fetch("/index.php/wp-json/printess/v1/design/add",{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":f.nonce},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify(e)}).then(e=>(e.ok?e.json().then(e=>{"function"==typeof a&&a(i,e)}):(console.error(e.statusText),"function"==typeof o&&o(f.userMessages&&f.userMessages.saveError?f.userMessages.saveError:"There was an error while trying to save your design")),e)).catch(function(e){console.log(e),"function"==typeof o&&o(f.userMessages&&f.userMessages.saveError?f.userMessages.saveError:"There was an error while trying to save your design")})})(c,u,g.product.id,e,v.designId,h(g.product,!1),(e,t)=>{n(),v.designName=e,v.designId=t;try{var r=y();r&&"function"==typeof r.onSave&&r.onSave(c,u)}catch(e){console.error(e)}},e=>{n(),alert(e),_(v.designName,f.userIsLoggedIn?d:l,o)})):(alert(f.userMessages&&f.userMessages.noDisplayName?f.userMessages.noDisplayName:"Please provide a display name."),_(v.designName,f.userIsLoggedIn?d:l,o))},l=e=>{var t,r,i,n,s,a;[t,r,i,n,s,a=null]=[e,g.product.id,p?p.id:null,c,u,m],t&&t.trim()&&f.accountPageUrl?(r=f.accountPageUrl.replace("__ProductId__",""+r.toString()).replace("__SaveToken__",""+n).replace("__ThumbnailUrl__",encodeURIComponent(s)).replace("__VariantId__",""+i).replace("__Options__",encodeURIComponent(JSON.stringify(a??{}))).replace("__Token__",encodeURIComponent(f.urlToken||"")).replace("__DisplayName__",""+t.trim()),window.location.href=r):(alert(f.userMessages&&f.userMessages.noDisplayName?f.userMessages.noDisplayName:"Please provide a display name."),_(e,f.userIsLoggedIn?d:l,o))};_(v.designName,f.userIsLoggedIn?d:l,o)}else((e,t)=>{let r=document.getElementById("printess");r&&setTimeout(function(){r.contentWindow.postMessage({cmd:e,properties:t||{}},"*")},0)})("renderFirstPageImage",null)},getBasketId:()=>g.basketId,getUserId:()=>g.userId,editorClosed:e=>{var t;a.hide(),v.designId=null,v.designName=null,e&&l("","","",""),"buyer"===f.editorMode?"undefined"!=typeof URLSearchParams&&(t=new URLSearchParams(window.location.search),e&&t.has("design_id")||t.has("design_name")||t.has("printess-save-token"))&&(t.delete("design_id"),t.delete("design_name"),t.delete("printess-save-token"),window.location.search=t.toString()):(e=f.userMessages&&f.userMessages.closeWindow?f.userMessages.closeWindow:"Please close this window or tab.",alert(e))}};var e=h(g.product);(e=b(e,g.product))&&e.templateName&&(v.templateNameOrSaveToken=e.templateName);var t=(e=new URLSearchParams(window.location.search)).get("printess-save-token")||e.get("printess_save_token"),r=e.get("design_name"),e=e.get("design_id");return t&&(v.templateNameOrSaveToken=t),r&&(v.designName=r),e&&(v.designId=parseInt(e)),v}function p(e){let t="";var r=b(h(e),e),i=!(!e.variants||void 0===e.variants.find(e=>e.templateName));(t=null!=r&&r.templateName?r.templateName:t)||i||(t=e.templateName),v(t&&0<t.length)}function g(r){window.jQuery?window.jQuery("form").on("found_variation",(e,t)=>{p(r)}):setTimeout(g,100)}let y=()=>window&&window.printessGlobalConfig?window.printessGlobalConfig:{},h=function(t,r=!0){var i={},e={"add-to-cart":!0,product_id:!0,quantity:!0,variation_id:!0},n=y();if(n&&n.formFields)for(var s in n.formFields)n.hasOwnProperty(s)&&(i[s]=n.formFields[s]);function a(e){return r&&0===e.indexOf("attribute_")&&(e=e.substring(10,e.length)),e=t.attributes&&t.attributes[e]?t.attributes[e].name:e}var o,d=document.querySelector(m);if(d){for(o of new FormData(d).entries()){var l=a(o[0]);0<l.length&&"_"!==l[0]&&!e[l]&&0!==l.indexOf("printess-")&&(i[l]=o[1].toString())}var c,u=d.querySelectorAll('input[type="checkbox"]');if(u&&0<u.length)for(let e=0;e<u.length;++e)void 0!==u[e].checked&&!0===u[e].checked&&0<(c=a(u[e].name)).length&&"_"!==c[0]&&(i[c]="true")}return i},c=e=>{var t={};if(e&&e.attributes)for(var r in e.attributes)e.attributes.hasOwnProperty(r)&&(t[e.attributes[r].name]=e.attributes[r]);return t},b=function(e,t){let r=t.variants?t.variants[0]:null;var i,n=c(t),s=[];for(i in e)e.hasOwnProperty(i)&&n[i]&&s.push({key:n[i].key,value:e[i]});if(t.variants){let e=t.variants;s.forEach(t=>{e=e.filter(e=>e.attributes[t.key]===t.value)}),0<e.length&&(r=e[0])}return r},u=()=>{var e=document.getElementById("printess_overlay_background");e&&e.classList.remove("visible")},_=(e,r,t)=>{var i=document.getElementById("printess_show_if_not_logged_in");let n=document.getElementById("printess_overlay_background"),s=()=>{},a=e=>{e.srcElement&&("input"===e.srcElement.nodeName.toLowerCase()||null!=e.srcElement.closest("div.printess_overlay_background"))||(e.preventDefault(),e.stopPropagation())},o=()=>{if(u(),s(),"function"==typeof r){let e="";var t=document.getElementById("printess_designnameedit");t&&(e=t.value),r(e)}},d=()=>{u(),s(),"function"==typeof t&&t()};s=()=>{var e=document.getElementById("printess_save_design_button"),e=(e&&e.removeEventListener("click",o),document.getElementById("printess_cancel_button"));e&&e.removeEventListener("click",d),n&&(n.removeEventListener("mousedown",a),n.removeEventListener("mouseup",a),n.removeEventListener("mousemove",a))},i&&(f.userIsLoggedIn?i.classList.add("logged_in"):i.classList.remove("logged_in"));var i=document.getElementById("printess_show_if_no_design_name"),l=document.getElementById("printess_show_if_design_name"),i=(i&&l&&(e?(i.classList.remove("visible"),l.classList.add("visible")):(i.classList.add("visible"),l.classList.remove("visible"))),document.getElementById("printess_designnameedit")),l=(i&&(i.value=e||""),n&&(n.addEventListener("mousedown",a),n.addEventListener("mouseup",a),n.addEventListener("mousemove",a),n.getAttribute("data-initialized")||(document.body.appendChild(n),n.setAttribute("data-initialized","true")),n.classList.add("visible")),document.getElementById("printess_save_design_button")),i=(l&&l.addEventListener("click",o),document.getElementById("printess_cancel_button"));i&&i.addEventListener("click",d)},n=()=>{var e=document.getElementById("printess_information_overlay_background");e&&e.classList.remove("visible")},w=(e,t)=>{var r=document.getElementById("printess-admin-save"),i=document.getElementById("printess-loading-message"),n=document.getElementById("printess-saving-message");i?.style.setProperty("display","none"),n?.style.setProperty("display","block"),r?(r.href+="&pst="+e,r.href+="&ptu="+encodeURI(t),r.click()):alert("Error: Redirect link not found. Unable to save changes")},s=(e,t,r,i)=>{e=(e+"").replace(/[^0-9+\-Ee.]/g,"");e=isFinite(+e)?+e:0,t=isFinite(+t)?Math.abs(t):0,i=void 0===i?",":i,r=void 0===r?".":r,e=(t?((e,t)=>(t=Math.pow(10,t),""+Math.round(e*t)/t))(e,t):""+Math.round(e)).split(".");return 3<e[0].length&&(e[0]=e[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,i)),(e[1]||"").length<t&&(e[1]=e[1]||"",e[1]+=new Array(t-e[1].length+1).join("0")),e.join(r)},v=function(t){var e=document.getElementsByName("printess-customize-button"),r=document.querySelector(m+" button.single_add_to_cart_button");e&&0!==e.length&&(r&&(t?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled"),r.style.display=t?"none":"inline-block"),e.forEach(e=>e.style.display=t?"inline-block":"none"))},a={show:function(e){if(d=null,!(e=>{var t,r,i=c(e),n=[],s=h(e);for(t in s)s.hasOwnProperty(t)&&i[t]&&n.push({key:i[t].key,value:s[t]});for(r in n)if(n.hasOwnProperty(r)&&!n[r].value)return!0;return!1})(e.product)){var e=i(e),t=(f.idsToHide&&f.idsToHide.forEach(e=>{e=document.getElementById(e);e&&e.classList.add("printess-hide")}),f.classesToHide&&f.classesToHide.forEach(e=>{e=document.getElementsByClassName(e);if(e&&e.length)for(var t of e)t.classList.add("printess-hide")}),y());if(t&&t.attachParams)for(var r in t.attachParams)t.attachParams.hasOwnProperty(r)&&(f.attachParams||(f.attachParams={}),f.attachParams[r]=t.attachParams[r]);"function"==typeof window.initPrintessEditor&&window.initPrintessEditor(f).show(e)}},hide:function(){f.idsToHide.forEach(e=>{e=document.getElementById(e);e&&e.classList.remove("printess-hide")}),f.classesToHide.forEach(e=>{e=document.getElementsByClassName(e);if(e&&e.length)for(var t of e)t.classList.remove("printess-hide")})},initProductPage:function(e,r,i,n="Customize",t,s=m){s=document.querySelector(s||m);if(s){{var a=r;var o=document.createElement("input"),d=document.createElement("input"),l=document.createElement("input"),c=document.createElement("input"),u=document.createElement("input");let t=document.createElement("button");o.setAttribute("id","printess-save-token"),o.setAttribute("name","printess-save-token"),o.setAttribute("type","hidden"),d.setAttribute("id","printess-save-token-to-remove-from-cart"),d.setAttribute("name","printess-save-token-to-remove-from-cart"),d.setAttribute("type","hidden"),d.setAttribute("value",a||""),l.setAttribute("id","printess-thumbnail-url"),l.setAttribute("name","printess-thumbnail-url"),l.setAttribute("type","hidden"),c.setAttribute("id","printess-design-id"),c.setAttribute("name","printess-design-id"),c.setAttribute("type","hidden"),u.setAttribute("id","printess-design-name"),u.setAttribute("name","printess-design-name"),u.setAttribute("type","hidden"),t.setAttribute("id","printess-customize-button"),t.setAttribute("name","printess-customize-button"),t.setAttribute("type","button"),t.setAttribute("onclick","showPrintessEditor();"),t.classList.add("wp-element-button","single_add_to_cart_button","button","alt"),f.customizeButtonClasses&&f.customizeButtonClasses.split(" ").forEach(e=>{(e=(e||"").trim())&&t.classList.add(e)}),t.appendChild(document.createTextNode(n||"Customize")),i&&t.classList.add(i),((a=document.querySelector(m+" button.single_add_to_cart_button"))&&a.parentElement?a.parentElement:s).appendChild(t),s.appendChild(o),s.appendChild(d),s.appendChild(l),s.appendChild(c),s.appendChild(u)}r&&v(!0)}g(e),p(e);n=new URLSearchParams(window.location.search).get("printess-save-token");n&&"function"==typeof t&&t(n)}};return window.printessWooEditor=a};if(window.wc&&window.wc.blocksCheckout){let e=window.wc.blocksCheckout.registerCheckoutFilters,a=(e,t,r,i)=>{let n=(e||document).querySelector("."+t);return n||((n=document.createElement(r)).classList.add(t),i&&n.classList.add(i),e.appendChild(n)),n};e("printess-editor",{cartItemClass:(e,s,t)=>{let r=e||"";if(s&&s["printess-editor"]&&s["printess-editor"].saveToken&&t.cartItem){let e="printess_cart_item_"+t.cartItem.key;r+=" "+e+" ",setTimeout(function(){var t=document.querySelector("."+e);if(s["printess-editor"].designName){let e=t?t.querySelector("ul.wc-block-components-product-details"):null;e||(n=t.querySelector(".wc-block-cart-item__wrap"))&&(n=a(n,"wc-block-components-product-metadata","div"),e=a(n,"wc-block-components-product-details","ul")),e&&((n=e.querySelector(".printess-product-detail-name"))?(n.innerText="Design name: ",(n=e.querySelector("printess-product-detail-name"))&&(n.innerText=s["printess-editor"].designName)):((n=document.createElement("li")).classList.add("wc-block-components-product-details__designName"),n.classList.add("printess-product-details-item"),r=a(n,"wc-block-components-product-details__name","span","printess-product-detail-name"),i=a(n,"wc-block-components-product-details__value","span","printess-product-detail-value"),r.innerText="Design name: ",i.innerText=s["printess-editor"].designName,e.appendChild(n)))}var r=t?.querySelector(".wc-block-cart-item__image img");if(r&&(r.classList.add("printess-thumbnail-image"),r.setAttribute("src",s["printess-editor"].thumbnailUrl)),s["printess-editor"].thumbnailUrl){var i=t?.querySelector(".wc-block-cart-item__image a"),n=(i&&i.setAttribute("href",s["printess-editor"].editLink),t?.querySelector(".wc-block-cart-item__quantity"));if(n){let e=n.querySelector(".printess-edit-link");e||((e=document.createElement("a")).classList.add("wc-block-cart-item__remove-link"),e.classList.add("printess-edit-link"),e.innerText="Edit",(r=document.createElement("div")).appendChild(e),n.appendChild(r)),e.setAttribute("href",s["printess-editor"].editLink)}}},0)}return r}})}
  • printess-editor/trunk/printess.php

    r3173481 r3182931  
    55 * Plugin URI: https://printess.com/kb/integrations/woo-commerce/index.html
    66 * Developer: Bastian Kröger ([email protected]); Alexander Oser ([email protected])
    7  * Version: 1.6.27
     7 * Version: 1.6.29
    88 * Author: Printess
    99 * Author URI: https://printess.com
     
    1313 * Requires PHP: 8.1
    1414 *
    15  * Woo: 10000:923989dfsfhsf8429842384wdff234sfd
     15 * Woo: 10000:923991dfsfhsf8429842384wdff234sfd
    1616 * WC requires at least: 5.8
    1717 * WC tested up to: 9.3.3
     
    221221    }
    222222
     223    if ( ! empty( $values['printess-design-name'] ) ) {
     224        $item->add_meta_data( '_printess-design-name', $values['printess-design-name'], true );
     225    }
     226
    223227    if ( ! empty( $values['printess-additional-settings'] ) ) {
    224228        $item->add_meta_data( 'printess-additional-settings', $values['printess-additional-settings'], true );
     
    247251    $thumbnail_url                  = filter_input( INPUT_POST, 'printess-thumbnail-url', FILTER_VALIDATE_URL );
    248252    $design_id                      = filter_input( INPUT_POST, 'printess-design-id', FILTER_SANITIZE_SPECIAL_CHARS );
     253    $design_name                    = filter_input( INPUT_POST, 'printess-design-name', FILTER_SANITIZE_SPECIAL_CHARS );
    249254    $additionalSettings             = filter_input( INPUT_POST, 'printess-additional-settings', FILTER_SANITIZE_SPECIAL_CHARS );
     255    $item_usage                     = filter_input( INPUT_POST, 'printess_item_usage', FILTER_UNSAFE_RAW );
    250256
    251257    if ( empty( $save_token ) || strlen( $save_token ) !== 89 ) {
     
    269275    if ( ! empty( $design_id ) ) {
    270276        $cart_item_data['printess-design-id'] = $design_id;
     277    }
     278
     279    if ( ! empty( $design_name ) ) {
     280        $cart_item_data['printess-design-name'] = $design_name;
     281    }
     282
     283    if ( ! empty( $item_usage ) ) {
     284        $cart_item_data['printess-item-usage'] = $item_usage;
    271285    }
    272286
     
    457471            $printess_ui_version = "classical";
    458472        }
    459         ?>
     473
     474        $itemUsage = $product->get_meta( 'printess_item_usage', true );
     475
     476        if(null === $itemUsage) {
     477            $itemUsage = "";
     478        }
     479?>
    460480
    461481        <script id="printess-integration">
     482            var printessGlobalConfig = {};
     483            let itemUsage = <?php echo(!empty($itemUsage) ? wp_json_encode($itemUsage) : "\"\""); ?>;
     484
     485            try {
     486                printessGlobalConfig.pricePerUsageFields = JSON.parse(itemUsage);
     487            } catch(ex) {
     488
     489            }
     490
     491
    462492            let showPrintessEditor = function() {};
    463493            const userMessages = {
     
    14621492        $fields[] = '_printess-dropshipping';
    14631493        $fields[] = '_printess-design-id';
     1494        $fields[] = '_printess-design-name';
    14641495        $fields[] = '_printess-valid-until';
    14651496        $fields[] = '_printess-dropship-nonce';
     
    18571888    $printess_tracking_url    = $item->get_meta( '_printess-dropship-tracking-url' );
    18581889    $printess_shipping_status = $item->get_meta( '_printess_shipping-status' );
     1890    $printess_design_name = $item->get_meta( '_printess-design-name' );
     1891    $printess_design_id = $item->get_meta( '_printess-design-id' );
    18591892
    18601893    if ( ! empty( $printess_save_token ) ) {
     
    35883621        )
    35893622    );
     3623
     3624    woocommerce_wp_text_input(
     3625        array(
     3626            'id'                => 'printess_item_usage',
     3627            'value'             => get_post_meta( get_the_ID(), 'printess_item_usage', true ),
     3628            'label'             => __( 'Item Usage', 'printess-editor' ),
     3629            'description'       => __( 'Json configuration for item based usage pricing', 'printess-editor' ),
     3630            'custom_attributes' => array(
     3631                'min' => '0',
     3632                'max' => '100',
     3633            ),
     3634        )
     3635    );
    35903636    ?>
    35913637
     
    37253771 */
    37263772function printess_process_product_meta( $post_id ) {
    3727     $keys        = array( 'printess_template', 'printess_dropshipping', 'printess_merge_template_1', 'printess_merge_template_2', 'printess_merge_template_3', 'printess_output_type', 'printess_dpi', 'printess_cart_redirect_page', 'printess_custom_formfield_mappings', 'printess_jpg_compression', "printess_ui_version", "printess_output_files" );
     3773    $keys        = array( 'printess_template', 'printess_dropshipping', 'printess_merge_template_1', 'printess_merge_template_2', 'printess_merge_template_3', 'printess_output_type', 'printess_dpi', 'printess_cart_redirect_page', 'printess_custom_formfield_mappings', 'printess_jpg_compression', "printess_ui_version", "printess_output_files", "printess_item_usage" );
    37283774    $number_keys = array( 'printess_dpi' );
    37293775
     
    45454591
    45464592/**
     4593 * WooCommerce callback for price recalculations in case of itemUsage params
     4594 */
     4595function printess_recalculate_basketitem_price($cart_object) {
     4596    foreach ( $cart_object->get_cart() as $id => $basket_item ) {
     4597        if(array_key_exists("printess-item-usage", $basket_item) && !empty($basket_item["printess-item-usage"])) {
     4598            try {
     4599                $used_items = json_decode($basket_item["printess-item-usage"], true);
     4600
     4601                if(null === $used_items || !is_array($used_items)) {
     4602                    continue;
     4603                }
     4604                $product = wc_get_product($basket_item["product_id"] );
     4605                $variant = null;
     4606                $price = 0;
     4607
     4608                if(null === $product) {
     4609                    continue;
     4610                }
     4611
     4612                if(0 < $basket_item["variant_id"]) {
     4613                    $variant = wc_get_product($basket_item["variant_id"]);
     4614                    $price = $variant->get_price();
     4615                } else {
     4616                    $price = $product->get_price();
     4617                }
     4618
     4619                $configuration = $product->get_meta( 'printess_item_usage', true );
     4620
     4621                if(null !== $configuration && !empty($configuration)) {
     4622                    $configuration = json_decode($configuration, true);
     4623
     4624                    if(null === $used_items || !is_array($used_items)) {
     4625                        continue;
     4626                    }
     4627                }
     4628
     4629                $priceLookup = array();
     4630                foreach($configuration as $key => $value) {
     4631                    if(is_array($value) && array_key_exists("formFieldName", $value) && array_key_exists("pricePerUsage", $value)) {
     4632                        $priceLookup[$value["formFieldName"]] = $value["pricePerUsage"];
     4633                    } else if (is_numeric($value)) {
     4634                        $priceLookup[$key] = $value;
     4635                    }
     4636                }
     4637
     4638                foreach($used_items as $key => $value) {
     4639                    if(array_key_exists($key, $priceLookup)) {
     4640                        $price = $price + (intval($value) * $priceLookup[$key]);
     4641                    }
     4642                }
     4643
     4644                $basket_item["data"]->set_price($price);
     4645            }
     4646            catch(\Exception $ex) {
     4647
     4648            }
     4649        }
     4650    }
     4651}
     4652
     4653/**
    45474654 * Enqueues external javascripts
    45484655 */
     
    45514658    wp_enqueue_script( 'printess_editor_woo', plugins_url( 'includes/js/printessWoocommerce.js', __FILE__ ), array(), 1, array( 'in_footer' => true ) );
    45524659}
     4660
     4661// function printess_modify_template_code($template, $templateName) {
     4662//  if($template["blockName"] == "woocommerce/filled-mini-cart-contents-block") {
     4663//      $debug = 10;
     4664//  }
     4665
     4666//  return $template;
     4667// }
     4668
     4669// function printess_modify_template_code_1($content, $block) {
     4670//  if($$block["blockName"] == "woocommerce/filled-mini-cart-contents-block") {
     4671//      $debug = 10;
     4672//  }
     4673
     4674//  return $content;
     4675// }
    45534676
    45544677/**
     
    46084731    add_filter( 'woocommerce_widget_cart_item_quantity', 'printess_render_edit_button_before_mini_basket_buttons', 10, 2 );
    46094732    add_action( 'woocommerce_before_mini_cart_contents', 'printess_insert_helper_script_before_minibasket' );
     4733
     4734    //Recalculate basket item prices
     4735    add_action( 'woocommerce_before_calculate_totals', 'printess_recalculate_basketitem_price' );
     4736
     4737    //New theme block supports
     4738    include_once('includes/printessBlockIntegrations.php');
     4739    printess_register_block_hooks();
     4740
     4741    // //Loading of template parts (Required for mini cart template :( )
     4742    // add_filter("render_block_data", "printess_modify_template_code", 10, 2);
     4743    // add_filter("render_block", "printess_modify_template_code_1", 10, 2);
    46104744
    46114745    // CALLBACKS.
  • printess-editor/trunk/readme.txt

    r3173481 r3182931  
    210210= 1.6.27 =
    211211* Fixed: Fixed broken variant handling during saving of designs while not being logged in (variant settings got lost during the login process when saving a design)
     212
     213= 1.6.28 =
     214* Added: Added support for the new theme blocks inside the shopping basket
     215
     216= 1.6.29 =
     217* Fixed issues with keyboard inputs in case the keyboard input focus is required without having the user to click on input elements within the editor before.
     218* Added: Added support for item usage (Different pricing depending on numeric form field values)
Note: See TracChangeset for help on using the changeset viewer.