@aurigma/ui-framework
Version:
A platform which allows building print product personalization editors based on Aurigma's Customer's Canvas.
1 lines • 55.7 kB
JavaScript
(window.multistep_editor_jsonpFunction=window.multistep_editor_jsonpFunction||[]).push([[24],{539:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(404),a=s(603);class n{static get iframeApiPromise(){return this._iframeApiSubject.pipe(Object(a.a)(1)).toPromise()}static loadCCScript(e,t){if("undefined"!=typeof CustomersCanvas||document.body.querySelector("#CcIframeApiScript"))"undefined"!=typeof CustomersCanvas&&this._iframeApiSubject.next(CustomersCanvas);else{this._iframeApiSubject=new i.a(1);let s=document.createElement("script");s.type="text/javascript",s.id="CcIframeApiScript",s.onload=e=>{CustomersCanvas&&this._iframeApiSubject.next(CustomersCanvas)},s.onerror=e=>{this._iframeApiSubject.error(e)},s.src=e+t,document.body.appendChild(s)}return this.iframeApiPromise}}n._iframeApiSubject=new i.a(1)},540:function(e,t,s){"use strict";s.d(t,"a",(function(){return l}));var i=s(36),a=s(601),n=s(1),o=s(71),r=s(395),c=s(603),d=s(541);class l{constructor(e,t,s=()=>Promise.resolve(),i){this._executedActions=[],this._lastJobKey="init",this._lastExecutedJobSubject=new d.a("init"),this._commands=e,this._onJobFinish=s,this.logger=new o.Category("command-executer_"+t+"_"+n.a.guid()),this.widget=i}_showLockPreloader(e,t,s){if(e&&t&&e[t]&&e[t].lock&&this.widget){const i=Array.isArray(e[t].lock)?e[t].lock:[e[t].lock];for(const e of i){let t="main"===e?this.widget.auWizard:this.widget.auWizard.scope.$[e]||this.widget.jsonParamsFetcher.scope[e]||this.widget.jsonParamsFetcher.scope.$[e];t&&t.showPreloader(s)}}}executeActions(e,t,s){t=t.filter((t=>{const s=!(!0===e[t].executeOnce&&-1!==this._executedActions.indexOf(t));let i=!0;return Array.isArray(e[t].executeOnlyAfter)&&(i=e[t].executeOnlyAfter.reduce(((e,t)=>(-1===this._executedActions.indexOf(t)&&(e=!1),e)),!0)),s&&i}));const a=async o=>{this.logger.debug((()=>`Start Execute '${o}'`));const r=performance.now();let c=Promise.resolve();const d=this._commands[o],l=Array.isArray(e[o])?e[o][0].message:e[o].message,u=(Array.isArray(e[o])?e[o][0].timeout:e[o].timeout)||10;if(d&&void 0!==d.execute){l&&this.widget.showPreloader(!0,l,u),this._showLockPreloader(e,o,!0),c=d.execute(e[o],s[o]),-1===this._executedActions.indexOf(o)&&this._executedActions.push(o);let r=e[o].after;if(!r&&Array.isArray(e[o])){const t=e[o].find((e=>e.after));t&&(r=t.after)}if(void 0!==r){Object(i.a)(r)||(r=[r]);const e=(e,t,s)=>{const i=s.indexOf(e);return s.indexOf(t)>i};for(let s=0;s<r.length;s++){const i=r[s];e(o,i,t)||(await c,c=a(i))}}let h=e[o].onExecuted;if(!h&&Array.isArray(e[o])){const t=e[o].find((e=>e.onExecuted));t&&(h=t.onExecuted)}if(h){await c;const e=n.a.functionWrapperConstructor(h);await e()}}else console.warn(`Action ${o} is not supported! Double check the config.`);await c,l&&this.widget.showPreloader(!1),this._showLockPreloader(e,o,!1),this.logger.debug((()=>`Finish Execute '${o}'`));const h=performance.now();return this.widget.auWizard.telemetry.trackEvent("DE-"+o,h-r),c},o=this.getJobReady(this._lastJobKey),r=this._lastJobKey=n.a.guid();return o.then((()=>(this.logger.debug((()=>`Start actons: ${t}`)),n.a.recursiveJobPromise(t,a)))).then((()=>this._onJobFinish())).finally((()=>{this.logger.debug((()=>`End actons: ${t}`)),this._lastExecutedJobSubject.next(r)}))}getJobReady(e){return this._lastExecutedJobSubject.pipe(Object(r.a)((t=>t===e)),Object(c.a)(1)).toPromise()}getChangedActions(e,t){let s=Object.keys(e).filter((t=>n.a.isObjectNotEmpty(e[t]))).filter((s=>{return void 0===t[s]||(i=e[s],a=t[s],!(JSON.stringify(i)===JSON.stringify(a)));var i,a}));const i=s.indexOf("actionsErrorToast");return-1!==i&&s.splice(i,1),s=s.filter((t=>{const s=e[t];return Array.isArray(s)?s[0]&&!1!==s[0].autoCompile:!1!==s.autoCompile})),s.indexOf("initial")>-1?["initial"].concat(Object(a.a)(s,"initial")):s}}},865:function(e,t){e.exports="<style>\n :host {\n width: 100%;\n height: 100%;\n display: block;\n position: initial;\n }\n\n #design-editor {\n position: absolute;\n height: 1px;\n min-height: 100%;\n width: 1px;\n min-width: 100%;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n border: none;\n background-color: transparent;\n }\n</style>\n<iframe id='design-editor' allowfullscreen></iframe>\n"},924:function(e,t,s){"use strict";s.r(t),s.d(t,"AuWidgetDesignEditor",(function(){return ye})),s.d(t,"widget",(function(){return ye}));var i=s(0),a=s(888),n=s(887),o=s(445),r=s(464),c=s(410),d=s(540),l=s(1),u=s(537),h=s(598),g=s(202),m=s(928),f=s(2),p=s(17),w=s(539);class y{constructor(){this.promise=new Promise(function(e,t){this._resolve=e,this._reject=t}.bind(this))}then(e){return this.promise.then(e)}catch(e){return this.promise.catch(e)}resolve(e=""){this._resolve(e)}reject(e){this._reject(e)}}var I=s(413),C=s(408),P=s(559),v=s(435),b=s(560),_=s(562),x=s(478),O=s(512),S=s(567),D=s(458),A=s(440);class M{constructor(e){Object.assign(this,e)}}var E=s(404),k=s(603),j=s(160);class R extends j.c{constructor(){super(...arguments),this._customersCanvasSubject=new E.a(1)}customersCanvasPublish(e){this._customersCanvasSubject.next(e)}get customersCanvasObservable(){return this._customersCanvasSubject.asObservable()}get customersCanvasPromise(){return this.customersCanvasObservable.pipe(Object(k.a)(1)).toPromise()}async getProduct(){const e=await this.getEditor();return await e.getProduct()}async getEditor(){return await this._customersCanvasSubject.asObservable().pipe(Object(k.a)(1)).toPromise()}async getDesignEditorItemModel(e){const t=e.type===O.b.type,s=e.type===v.a.type||e.type===b.a.type||e.type===S.a.type||e.type===_.a.type||e.type===P.a.type,i=e.type===C.kb.type||e.type===C.gb.type||e.type===C.A.type||e.type===O.b.type;e.type,x.a.type;let a=!1,n=!1;if(!e)return;let o={name:e.name};switch(t&&(a=l.a.isNotNullOrUndefined(e.content)&&(e.content instanceof CustomersCanvas.DesignAtoms.ObjectModel.ImageItem||"ImageItem"===e.content.type),n=l.a.isNotNullOrUndefined(e.content)&&(e.content instanceof CustomersCanvas.DesignAtoms.ObjectModel.BarcodeItem||"BarcodeItem"===e.content.type)),!0){case t&&a&&!n&&null!==e.content.tags.sourceData&&void 0!==e.content.tags.sourceData:{const t=e.content,s=new A.a(e).getTransformedRectangle(),i=new D.b(t).getTransformedRectangle(),a=await this.getEditor();let n=300;try{n=await a.eval("var printArea = spEditor.productHandler.product.surfaces.elementAt(0).printAreas.elementAt(0);var config = spEditor.configuration.renderingConfig.getHiResRendering(printArea);config.dpi;")}catch(r){console.warn("Failed to get hires render config dpi")}o.tags=Object(u.a)(t.tags),o.value=t.tags.sourceData.name,o.placeholderContent={originalUrl:t.tags.sourceData.originalUrl,width:t.source.width,height:t.source.height,placeholderRectangle:s,contentRectangle:i,contentResizeMode:O.c[e.contentResizeMode].toLowerCase(),contentTransform:{angle:t.transform.angle,scaleX:t.transform.scaleX,scaleY:t.transform.scaleY,translateX:t.transform.translateX,translateY:t.transform.translateY},dpi:n};break}case t&&a:o={name:e.name,tags:Object(u.a)(e.tags)};break;case s&&!!e.text:{const t=e;let s="",i=e=>(e/255).toFixed(7);if(t.color)if(t.color.colorSpace===I.ColorSpace.Rgb){const e=t.color;s=`rgb(${e.r},${e.g},${e.b},${i(e.alpha)})`}else if(t.color.colorSpace===I.ColorSpace.Cmyk){const e=t.color;s=`cmyk(${i(e.c)},${i(e.m)},${i(e.y)},${i(e.k)},${i(e.alpha)})`}o={name:e.name,value:t.text,color:s,font:{postScriptName:t.font.postScriptName,size:t.font.size,fauxBold:t.font.fauxBold,fauxItalic:t.font.fauxItalic}};break}}if(t&&(e.contentPermissions&&e.contentPermissions.imagePermissions&&(o.contentPermissions={imagePermissions:{allowChangeImage:e.contentPermissions.imagePermissions.allowChangeImage,allowEditImage:e.contentPermissions.imagePermissions.allowEditImage}}),e.placeholderPermissions&&(o.placeholderPermissions={allowEditContent:e.placeholderPermissions.allowEditContent,showHandleButton:e.placeholderPermissions.showHandleButton,showSelectButton:e.placeholderPermissions.showSelectButton})),e.visualizationPermissions&&(o.visualizationPermissions={noPrint:e.visualizationPermissions.noPrint,noShow:e.visualizationPermissions.noShow}),null!==e.locked&&(o.locked=e.locked),i)if(e.type!==O.b.type){const t=window.CustomersCanvas.DesignAtoms.ObjectModel.ColorFactory.createColor(e.fillColor);o.fillColor=t,o.fillColorHex=await this.colorToHex(t)}else{const t=window.CustomersCanvas.DesignAtoms.ObjectModel.ColorFactory.createColor(e.contentFillColor);o.fillColor=t,o.fillColorHex=await this.colorToHex(t)}return new M(o)}async colorToHex(e){if(!e||l.a.isNullOrUndefined(e.colorSpace))return null;const t=e.getData(),s=await this.getEditor(),i=await s.eval((async function(e){return(await spEditor.model._viewer.colorPreviewService.getPreviewAsync(e)).getData()}),t),a=i.r.toString(16),n=i.g.toString(16),o=i.b.toString(16);return`#${1===a.length?"0"+a:a}${1===n.length?"0"+n:n}${1===o.length?"0"+o:o}`}}class N{constructor(e){this.widget=e}}class T extends N{async execute(e){var t;if(!(e.surfaceToDuplicateId||(null===(t=e.surfacesToChangeIds)||void 0===t?void 0:t.length)>0))return;const s=await this.widget.getProduct(),i=await s.getProductModel(),a=i.surfaces.get(e.surfaceToDuplicateId);if(a){for(let t of e.surfacesToChangeIds){if(t===e.surfaceToDuplicateId)continue;const s=i.surfaces.get(t);if(!s){console.warn(`There is no surface with index ${t}`);continue}const n=s.name,o=a.clone(!0);o.name=n,i.surfaces.replaceAt(o,t)}s.setProductModel(i)}else console.error(`There is no surface with index ${e.surfaceToDuplicateId}`)}}class z extends N{async execute(e){const t=(Array.isArray(e)?e:[e]).filter((e=>e));if(0!==t.length){this.widget.initDpApi();for(const e of t){const t=await this.widget.getProduct();if(!t.updateSurfaces)return void console.warn("Command unavailable for this version Customer's Canvas. Please, use version 6.2.0 or above.");if(1===t.updateSurfaces.length)if(e.definition&&e.definition.surfaces){const s=e.definition.surfaces,a=await Promise.all(s.map((async e=>{const{designVariant:t}=e,s=Object(i.c)(e,["designVariant"]),a=""!==(null==t?void 0:t.designResourceId)?await this.widget.createPrivateDesignFromResources(t.designResourceId):await this.widget.createPrivateDesignFromPublicDesign(t.designId);return Object.assign({stateId:a},s)}))),{definition:n}=e,o=Object(i.c)(e,["definition"]),r=Object.assign({definition:{surfaces:a},updateSurfaceSize:!0,preserveUserChanges:!0,updateBehavior:"changeSurfaceLength"},o);await t.updateSurfaces(r)}else{const{designVariant:s}=e,a=Object(i.c)(e,["designVariant"]);if(l.a.isNullOrUndefined(s))return;const n=""!==(null==s?void 0:s.designResourceId)?await this.widget.createPrivateDesignFromResources(s.designResourceId):await this.widget.createPrivateDesignFromPublicDesign(s.designId),o=Object.assign({definition:n,updateSurfaceSize:!0,preserveUserChanges:!0,updateBehavior:"changeSurfaceLength"},a);await t.updateSurfaces(o)}else await t.updateSurfaces(e.productDefinition||e.definition,e.options,e.sourceSurfaceIndexes,e.targetSurfaceIndexes)}}}}class U extends N{async execute(e){const t=await this.widget.getProduct(),s=e.data.map(((e,s)=>({mockup:e.mockup,previewMockups:e.previewMockups,surface:t.surfaces[s]})));return await t.setMockups(s,e.options)}}var F=s(407);class B extends N{async execute(e){const t=Array.isArray(e)?e:[e],s=await this.widget.getEditor(),i=await s.getProduct();for(const n of t){if(l.a.isEmptyString(n.url))continue;let e=n.surfaceIndex;(l.a.isNullOrUndefined(e)||e<0||e>i.surfaces.length)&&(e=1===t.length?i.currentSurfaceIndex:t.indexOf(n),(e<0||e>i.surfaces.length)&&(e=i.currentSurfaceIndex));let s=i.surfaces[e],a=s.width/2,o=s.height/2;n.size&&(n.size.width&&(a=n.size.width),n.size.height&&(o=n.size.height));let r=s.width/2-a/2,c=s.height/2-o/2;n.position&&(l.a.isNotNullOrUndefined(n.position.x)&&(r=n.position.x),l.a.isNotNullOrUndefined(n.position.y)&&(c=n.position.y));const d=new window.CustomersCanvas.DesignAtoms.ObjectModel.ImageItem(null,new F.PointF(r,c),a,o);d.name=n.name,await s.insertItem(d)}const a=t.reduce(((e,t)=>(e[t.name]=t.url,e)),{});await s.loadUserInfo(a)}}var L=s(891),W=s(37);class G extends N{async execute(e){var t,s,i,a;await this.widget.iframeApiPromise,e.editorConfig=e.editorConfig||{},e.onCustomButtonClicked&&(this.widget.customButtonCb=e.onCustomButtonClicked),"function"==typeof e.OnBoundsNotificationCb&&(this.widget._boundsNotificationCb=e.OnBoundsNotificationCb),"string"==typeof e.productDefinition&&(e.editorConfig.autoLoadUserInfo=!1,e.editorConfig.userInfo=null,this.widget._stateId=e.productDefinition,this.widget._userId=this.widget.driver.user.id);const n=this.widget.driver.user.data;n&&Object.keys(n).length>0&&(e.editorConfig.userInfo=l.a.DeepMerge(e.editorConfig.userInfo||{},n),e.editorConfig.autoLoadUserInfo=!0),e.editorConfig=e.editorConfig||{},e.editorConfig.themeConfiguration=e.editorConfig.themeConfiguration||{},this.widget.driver.themeSettings?(e.editorConfig.themeConfiguration.primaryColor=this.widget.driver.themeSettings.primaryColor,e.editorConfig.themeConfiguration.logo=this.widget.driver.themeSettings.logo):(this.widget.auWizard.config.icons&&this.widget.auWizard.config.icons.preloader&&(e.editorConfig.themeConfiguration.logo=this.widget.auWizard.config.icons.preloader),e.editorConfig.themeConfiguration.primaryColor=getComputedStyle(document.documentElement).getPropertyValue("--theme-primary-color"));const o=null===(s=null===(t=this.widget.driver)||void 0===t?void 0:t.localization)||void 0===s?void 0:s.find((e=>"design-editor"===e.app));let r={};const c=this.widget.language.slice(0,2);if(o){if(l.a.isNotNullOrUndefined(o.url)&&!l.a.isEmptyString(o.url)&&"string"==typeof o.url)try{r=await l.a.loadJson(o.url+"?ts="+Date.now())}catch(u){console.error(u)}else l.a.isNotNullOrUndefined(o.data)&&"object"==typeof o.data&&0!==Object.keys(o.data).length&&(r=-1!==Object.keys(o.data).indexOf(c)?l.a.DeepMerge(r,o.data):l.a.DeepMerge(r,{[c]:o.data}));e.editorConfig.translations=r}const d=e.maximizeAssetManager||e.galleryObserverEnable||this.widget.driver.config.displayInPopup;if((null===(a=null===(i=null==e?void 0:e.editorConfig)||void 0===i?void 0:i.preloader)||void 0===a?void 0:a.enabled)||(e.editorConfig.preloader={enabled:!1}),await this.load(e.productDefinition,e.editorConfig,d,e.initSurfaceIndex),await this.widget.getViolationData(),e.onInit){const t=l.a.functionWrapperConstructor(e.onInit);try{await t()}catch(h){}}return W.Maybe.maybe(e).map((e=>e.viewerSettings)).caseOf({just:e=>this.widget.applyViewerSettings(e),nothing:()=>this.widget.customersCanvasPromise})}async load(e,t,s,i){const a=this;e.surfaces&&Array.isArray(e.surfaces)&&e.surfaces.forEach((function(e){"object"==typeof e&&void 0!==e.width&&void 0!==e.height&&(e.width=Number(e.width),e.height=Number(e.height))})),a.widget.modifiedItem&&a.widget.updateModifiedItem({});const n=this.widget.shadowRoot.querySelector("#design-editor"),o=await CustomersCanvas.IframeApi.loadEditor(n,e,t);let r;try{r=await o.getProduct(),r=await r.switchTo(r.surfaces[0])}catch(u){return console.error("Load failed with exception: ",u),void a.widget.dispatchEvent(new CustomEvent("error",u))}if(l.a.isNotNullOrUndefined(i)){let e=Number(i);(Number.isNaN(e)||e<0||e>r.surfaces.length)&&(e=0),await r.switchTo(r.surfaces[e])}a.widget.customersCanvasPublish(o),a.widget.dispatchEvent(new CustomEvent("ready",{detail:{product:r,customersCanvas:o}})),await this.widget.replaceInterpolationPlaceholder();const c=[],d=(e,t,s=!1,i=!1)=>{c.push(e),o.subscribe(e,(async(...a)=>{var n,o;s&&await this.widget.getViolationData(),t&&await t(...a);const r=(null===(n=this.widget.params)||void 0===n?void 0:n.initial)&&(this.widget.params.initial["on"+e]||(null===(o=this.widget.params)||void 0===o?void 0:o.initial[e]));if(r){const e=l.a.functionWrapperConstructor(r);await e.apply(window,a)}i&&this.widget.emitChange()}))};s&&(d(L.a.ModalClose,(async(...e)=>this.widget.toggleMaximizeMainPanel(!1))),d(L.a.ModalOpen,(async(...e)=>this.widget.toggleMaximizeMainPanel(!0))),d(L.a.AssetManagerClosed,(async(...e)=>this.widget.toggleMaximizeMainPanel(!1))),d(L.a.AssetManagerOpened,(async(...e)=>this.widget.toggleMaximizeMainPanel(!0)))),d(L.a.OriginalSize,(async()=>this.widget.toggleMaximizeMainPanel(!1))),d(L.a.FullWindow,(async()=>this.widget.toggleMaximizeMainPanel(!0))),d(L.a.BoundsNotification,(e=>{this.widget.selectedGroupBoundsData=e,this.widget._boundsNotificationCb&&this.widget._boundsNotificationCb(e)})),d(L.a.OnImageDpiChanged,null,!0),d(L.a.OnSurfaceChanged,(async()=>await this.widget.updateCurrentSurfaceData())),d(L.a.ItemAdded,null,!0),d(L.a.ItemRemoved,null,!0),d(L.a.ItemChanged,(async(...e)=>{const t=e[0];if(!l.a.isNullOrUndefined(t))try{const e=await this.widget.getDesignEditorItemModel(t);this.widget.updateModifiedItem(e)}catch(s){console.warn("Failed to transform item model")}}),!0),d(L.a.RevertProduct,null,!0,!0),d(L.a.UndoProduct,null,!0),d(L.a.RedoProduct,null,!0),d(L.a.CustomButtonClicked,(async e=>this.widget.customButtonCb(e[0],e[1]))),Object.keys(L.a).forEach((e=>{-1===c.indexOf(e)&&d(e,null)}))}}class V extends N{async execute(e,t){if(l.a.isEmptyObject(e))return Promise.resolve();if(l.a.isEmptyObject(e.data))return Promise.resolve();const s=await this.widget.getEditor();try{await s.loadUserInfo(e.data,e.options)}catch(i){console.warn(i)}}}var $=s(471);class H extends N{async execute(e,t){if(l.a.isEmptyObject(e)||l.a.isEmptyObject(e.every)&&l.a.isEmptyObject(e.items))return Promise.resolve();e.items=e.items||{},l.a.isNotNullOrUndefined(t)&&(e=this._removeOldParams(e,t));const s=await this.widget.getEditor(),i=await s.getProduct();await this._modifyItems(e,i,s),await this._applyUserInfo(s,e)}async _modifyItems(e,t,s){if(l.a.isNullOrUndefined(e))return;l.a.isNotNullOrUndefined(e.items)&&await this._applyBackgroundColor(e,t);const i=await t.getProductModel(),a=i.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!1});for(const o of a){const t=Object.assign(Object.assign({},e.every),e.items[o.name]);0!==Object.keys(t).length&&this.needApplyOnce(t,o)&&(this._isTextItem(o.type)?this._updateTextItem(t,o):o.type===C.cb.type?await this._updatePlaceholderItem(t,o,s):this._isShapeItem(o)&&await this._updateShapeItem(t,o),this._updateVisualizationPermissions(t,o),this.setApplyOnce(t,o))}const n=t.currentSurfaceIndex>0?t.currentSurfaceIndex:0;await t.setProductModel(i),t=await s.getProduct(),await t.switchTo(t.surfaces[n])}needApplyOnce(e,t){return!(!0===e.once&&t&&t.tags.modifyItems&&!0===t.tags.modifyItems.once)}setApplyOnce(e,t){!0===e.once&&t&&(t.tags.modifyItems=t.tags.modifyItems||{},t.tags.modifyItems.once=!0)}_isTextItem(e){return e===C.o.type||e===C.q.type||e===C.eb.type||e===C.x.type||e===C.g.type}_removeOldParams(e,t){for(const s in e.items){const i=t.items[s],a=e.items[s];JSON.stringify(i)===JSON.stringify(a)&&!0!==a.force&&delete e.items[s]}return e}async _applyBackgroundColor(e,t){const s=e.items.background||e.items.Background;if(null!=s&&null!=s.color){const e=window.CustomersCanvas.DesignAtoms.ObjectModel.ColorFactory.createColor(s.color);if(null!==e)for(const s of t.surfaces)await s.changeBackground(e)}}_updateTextItem(e,t){const s=e.text||e.value;if(null!=s&&(t.text=s,t.placeholders&&t.placeholders.length>0&&(t.placeholders.forEach((e=>e.value=s)),t.value=s)),null!=e.font){let s=e.font.bold||e.font.fauxBold;s&&(t.font.fauxBold=s);let i=e.font.italic||e.font.fauxItalic;i&&(t.font.fauxItalic=i);let a=e.font.family||e.font.postScriptName;a&&(t.font.postScriptName=a),e.font.size&&(t.font.size=e.font.size),e.font.underline&&(t.underline=e.font.underline);let n=e.color||e.font.color;n&&(t.color=window.CustomersCanvas.DesignAtoms.ObjectModel.ColorFactory.createColor(n))}if(!0===e.locked&&(t.textPermissions.allowChangeText=!1,t.textPermissions.allowChangeTextBIU=!1),t.type===C.eb.type){let s=e.position||e.location;if(s){let e=0,i=0;const a=t;t.alignment=C.qb.Left,s||(s={x:0,y:0}),e=s.x||a.baselineLocation.x,i=s.y||a.baselineLocation.y,a.baselineLocation=new window.CustomersCanvas.DesignAtoms.ObjectModel.PointF(e,i)}}if(t.type===C.q.type||t.type===C.g.type){const s=t;let i=e.position||e.location;if(i||e.size){let t=0,a=0,n=0,o=0;i||(i={x:0,y:0}),t=i.x||s.textRectangle.left,a=i.y||s.textRectangle.top,e.size||(e.size={width:0,height:0}),n=e.size.width||s.textRectangle.width,o=e.size.height||s.textRectangle.height,s.textRectangle.width=n,s.textRectangle.height=o,s.textRectangle.left=t,s.textRectangle.top=a}}}_updateVisualizationPermissions(e,t){e.visualizationPermissions&&(l.a.isNotNullOrUndefined(e.visualizationPermissions.noPrint)&&(t.visualizationPermissions.noPrint=e.visualizationPermissions.noPrint),l.a.isNotNullOrUndefined(e.visualizationPermissions.noShow)&&(t.visualizationPermissions.noShow=e.visualizationPermissions.noShow)),l.a.isNotNullOrUndefined(e.locked)&&(t.locked=e.locked)}async _updatePlaceholderItem(e,t,s){if("ImagePlaceholder"===e.type){if((e=>e.placeholderContent&&e.tags&&e.tags.sourceData&&e.value===e.tags.sourceData.name)(e)){if(-1===e.placeholderContent.originalUrl.indexOf("?x-cctoken=")){const t=await this.widget.getToken();""!==t&&(e.placeholderContent.originalUrl+=`?x-cctoken=${t}`)}let a=e.placeholderContent.originalUrl;e.tags.sourceData.originalUrl=a;const n=await s.configuration.getImageMetadata(a),o=t.content;if(t.isStubContent=!1,o.setData)try{o.setData(n)}catch(i){$.a.setDataToImage(n,o)}else $.a.setDataToImage(n,o);o.tags=e.tags,o.parentPlaceholder=t;const r=new A.a(t),c=new D.b(o);c.updateRectangle(!1,t.contentResizeMode,r);const d=r.getTransformedRectangle(),l=e.placeholderContent;if(d.angle!==l.placeholderRectangle.angle||d.width!==l.placeholderRectangle.width||d.height!==l.placeholderRectangle.height||d.centerX!==l.placeholderRectangle.centerX||d.centerY!==l.placeholderRectangle.centerY){const e=new window.CustomersCanvas.DesignAtoms.ObjectModel.RotatedRectangleF(l.placeholderRectangle.centerX,l.placeholderRectangle.centerY,l.placeholderRectangle.width,l.placeholderRectangle.height,l.placeholderRectangle.angle);r.setTransformedRectangle(e)}const u=c.getTransformedRectangle();if(u.angle!==l.contentRectangle.angle||u.width!==l.contentRectangle.width||u.height!==l.contentRectangle.height||u.centerX!==l.contentRectangle.centerX||u.centerY!==l.contentRectangle.centerY){const e=new window.CustomersCanvas.DesignAtoms.ObjectModel.RotatedRectangleF(l.contentRectangle.centerX,l.contentRectangle.centerY,l.contentRectangle.width,l.contentRectangle.height,l.contentRectangle.angle);c.setTransformedRectangle(e)}}else if(!t.isStubContent){const e=t.content;if(e.parentPlaceholder=t,e.setData)try{e.setData(t.stubStorageMeta)}catch(i){$.a.setDataToImage(t.stubStorageMeta,e)}else $.a.setDataToImage(t.stubStorageMeta,e);const s=new A.a(t),a=new D.b(e);a.parentPlaceholder=s,a.updateRectangle(!1,t.contentResizeMode,s),t.isStubContent=!0}e.contentPermissions&&e.contentPermissions.imagePermissions&&(t.contentPermissions.imagePermissions.allowChangeImage=e.contentPermissions.imagePermissions.allowChangeImage,t.contentPermissions.imagePermissions.allowEditImage=e.contentPermissions.imagePermissions.allowEditImage),e.placeholderPermissions&&(t.placeholderPermissions.allowEditContent=e.placeholderPermissions.allowEditContent,t.placeholderPermissions.showHandleButton=e.placeholderPermissions.showHandleButton,t.placeholderPermissions.showSelectButton=e.placeholderPermissions.showSelectButton)}"BarcodePlaceholder"!==e.type||e.value||t.isStubContent||(t.content.applyBarcodeData(new window.CustomersCanvas.DesignAtoms.ObjectModel.BarcodeData("")),t.isStubContent=!0)}async _updateShapeItem(e,t){let s=e.color||e.fillColor;s&&(t.type!=C.cb.type?t.fillColor=window.CustomersCanvas.DesignAtoms.ObjectModel.ColorFactory.createColor(s):t.contentFillColor=window.CustomersCanvas.DesignAtoms.ObjectModel.ColorFactory.createColor(s));let i=e.position||e.location;if(i||e.size){let s=0,a=0,n=0,o=0;i||(i={x:0,y:0}),s=i.x||t.sourceRectangle.left,a=i.y||t.sourceRectangle.top,e.size||(e.size={width:0,height:0}),n=e.size.width||t.sourceRectangle.width,o=e.size.height||t.sourceRectangle.height,t.type!=C.A.type?t.sourcePath=window.CustomersCanvas.DesignAtoms.ObjectModel.Path.rectangle(s,a,n,o):t.sourcePath=window.CustomersCanvas.DesignAtoms.ObjectModel.Path.ellipse(s,a,n,o)}}async _applyUserInfo(e,t){const s=await e.getProduct(),i=(await s.getProductModel()).getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0}),a={};for(const r of Object.keys(t.items)){const e=t.items[r],s=i.find((e=>e.name===r));this.needApplyOnce(e,s)&&(e.value||"Text"===e.type||"InString"===e.type||e.image)&&("ImagePlaceholder"===e.type&&(n=e).placeholderContent&&n.tags&&n.tags.sourceData&&n.value===n.tags.sourceData.name||("BarcodePlaceholder"===e.type?e.barcodeSubType&&"None"!==e.barcodeSubType?"Url"===e.barcodeSubType?a[r]={BarcodeFormat:e.barcodeFormat,BarcodeSubType:e.barcodeSubType,Url:e.value}:"Phone"===e.barcodeSubType&&(a[r]={barcodeFormat:e.barcodeFormat,barcodeSubType:e.barcodeSubType,phone:e.value}):a[r]={barcodeFormat:e.barcodeFormat,barcodeValue:e.value}:a[r]=l.a.isNotNullOrUndefined(e.value)?e.value:e.image,this.setApplyOnce(e,s)))}var n;if(l.a.isEmptyObject(a))return Promise.resolve();try{await e.loadUserInfo(a)}catch(o){this.widget.showToast("Error: Invalid data"),console.log(o)}}_isShapeItem(e){return[C.gb.type,C.kb.type,C.A.type,C.cb.type].includes(e.type)}}var J=s(489);class X extends N{async execute(e){if(!e||!e.resizeParams||0===e.resizeParams.height||0===e.resizeParams.width)return;const t=await this.widget.getEditor(),s=e.resizeParams;if(s.targets&&s.targets.length>0&&"string"==typeof s.targets[0]){const i=await t.getProduct(),a=await i.getProductModel(),n=(await a.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0})).filter((e=>s.targets.includes(e.name))).map((e=>e.id)),o=e.resizeParams;o.targetIds=n,await t.commandManager.execute(J.b.resize,o)}else{if("product"!==e.resizeParams.targetType&&(e.resizeParams.targetIds||0===e.resizeParams.targetIds.length))return;if((null===e.resizeParams.target||void 0===e.resizeParams.target)&&"product"!==e.resizeParams.targetType)return;const s=e.resizeParams;await t.commandManager.execute(J.b.resize,s)}try{await t.eval("spEditor._canvasViewer._onResize()")}catch(i){}await this.widget.ready()}}class Y extends N{async execute(e){const t=Array.isArray(e)?e:[e],s=await this.widget.getEditor(),i=await s.getProduct();for(const n of t)if(n.url){const e=await i.getProductModel();let r=n.surfaceIndex;(null==r||r<0||r>i.surfaces.length)&&(r=1===t.length?i.currentSurfaceIndex:t.indexOf(n));const c=e.surfaces.get(r);if(l.a.isNullOrUndefined(c))continue;const d=c.printAreas.get(0),u=c.containers.first((e=>e.name===o.a.BG_CONTAINER_NAME));let h=u.items.get(0);l.a.isNullOrUndefined(h)&&(h=new window.CustomersCanvas.DesignAtoms.ObjectModel.PlaceholderItem,h.locked=!0,u.items.add(h)),l.a.isNullOrUndefined(h.content)&&(h.content=new window.CustomersCanvas.DesignAtoms.ObjectModel.ImageItem);const g=h.content,m=await s.configuration.getImageMetadata(n.url);if(m.isVector=this._isVector(n.url),!0===n.toTile){const t=h.content||h;if(t.sourceRectangle.width=m.size.width,t.sourceRectangle.height=m.size.height,t.setData)try{t.setData(m)}catch(a){$.a.setDataToImage(m,t)}else $.a.setDataToImage(m,t);t.source.isVector=m.isVector,u.items.setRange(this._getTiles(t,c)),await i.setProductModel(e)}else if(i.surfaces.length>r){const e=i.surfaces[r];await e.changeBackground(m)}if(!n.url.startsWith("public:")&&!n.url.startsWith("user:")&&n.autoResize){const t=new window.CustomersCanvas.DesignAtoms.ObjectModel.ImageItem.ImageSource;t.url=n.url,t.isVector=this._isVector(n.url),g.source=t,c.width=g.sourceRectangle.width,c.height=g.sourceRectangle.height,d.bounds.width=c.width,d.bounds.height=c.height,await i.setProductModel(e)}}await this.widget.ready()}_getTiles(e,t){let s=[],i=0,a=0;for(;a<t.height;){for(;i<t.width;){let t=e.clone();t.values=[],t.transform.setTranslateX(i),t.transform.setTranslateY(a),t.locked=!0,s.push(t),i+=e.source.width}i=0,a+=e.source.height}return s}_isVector(e){return e.endsWith(".pdf")||e.endsWith(".svg")}}class q extends N{async execute(e){let t=await this.widget.getProduct();Array.isArray(e)||(e=[e]);for(let s=0;s<e.length;s++){const i=e[s];if(!i.data)continue;let a=t.currentSurface;"number"==typeof i.surfaceIndex&&(a=t.surfaces[i.surfaceIndex]),t=await a.setPrintAreas([i.data],i.options),await this.widget.replaceInterpolationPlaceholder()}}}class K extends N{async execute(e){if(null==e)return Promise.resolve();const t=await this.widget.getEditor(),s=await t.getProduct(),i=await s.getProductModel();for(let n of e){if(l.a.isNullOrUndefined(n.url)||""===n.url)continue;const e="number"==typeof n.surfaceIndex?i.surfaces.get(n.surfaceIndex):i.surfaces.first((e=>e.name===s.currentSurface.name)),o="up"===n.mockup.toLowerCase()?e.mockup.overContainers:e.mockup.underContainers;if(o.empty){console.warn("Cannot set mockup because MockupContainer is empty");continue}const r=o.get(0);r.items.clear();const c=new window.CustomersCanvas.DesignAtoms.ObjectModel.ImageItem,d=await t.configuration.getImageMetadata(n.url);if(d.size={width:d.size.width||d.width,height:d.size.height||d.height},c.setData)try{c.setData(d)}catch(a){$.a.setDataToImage(d,c)}else $.a.setDataToImage(d,c);c.ratioWidthToHeight=r.size.width/r.size.height,c.SetWidth(r.size.width,!1),c.SetHeight(r.size.height,!1),r.items.add(c)}await s.setProductModel(i)}}var Z=s(890);class Q extends N{constructor(){super(...arguments),this._serializer=new Z.a}async execute(e){if(Object(c.l)(e.serializedProduct))throw"serializedProduct cannot be null or empty";const t=this._serializer.deserialize(e.serializedProduct),s=await this.widget.getProduct();await s.setProductModel(t)}}class ee extends N{async execute(e){if(!e||!e.surfaces||0===e.surfaces.length)return;if(e.surfaces.some((e=>0===Object.keys(e).length)))return;const t=await this.widget.getEditor();let s=await t.getProduct();await s.setSurfaces(e.surfaces),await this.widget.replaceInterpolationPlaceholder()}}class te extends N{async execute(e){("string"==typeof e||void 0===e.theme)&&(e={theme:e});const t=await this.widget.getProduct();return await t.applyProductTheme(e.theme)}}class se extends N{async execute(e){if(e){const t=await this.widget.getEditor(),s=Object.assign({},e);null!=e.scrollPosition&&(s.scrollingPosition={x:e.scrollPosition.X||e.scrollPosition.x,y:e.scrollPosition.Y||e.scrollPosition.y}),await t.setViewerSettings(s)}}}class ie extends N{async execute(e){const t=l.a.ensureArray(e).filter((e=>e));if(0!==t.length)for(const s of t){const e=await this.widget.getProduct();if(!e.swapSurfaces)return void console.warn("Command unavailable for this version Customer's Canvas.");const t=e.surfaces[s.lhsSurfaceIndex],i=e.surfaces[s.rhsSurfaceIndex];await e.swapSurfaces(t,i)}}}class ae extends N{async execute(e){if(!e||!e.translateParams)return;const t=e.translateParams,s=t.itemIds&&t.itemIds.length>0,i=e.translateParams,a=i.items&&0===i.items.length&&"string"!=typeof i.items[0],n=e.translateParams,o=n.items&&n.items.length>0&&"string"==typeof n.items[0];if(!s&&!a&&!o)return;const r=await this.widget.getEditor();if(o){const e=await r.getProduct(),t=await e.getProductModel(),s={itemIds:(await t.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0})).filter((e=>n.items.includes(e.name))).map((e=>e.id)),translateX:n.translateX,translateY:n.translateY};await r.commandManager.execute(J.a.translateItems,s)}else await r.commandManager.execute(J.a.translateItems,e.translateParams);await this.widget.ready()}}class ne extends N{async execute(e,t){if(null==e||!(e instanceof Array))return;const s=await this.widget.getProduct();for(let[i,a]of e.entries()){const e=s.surfaces[i];if(null!=e)for(let[t,s]of Object.entries(a)){const i=e.printAreas[0].getContainer(t);null!=i&&await i.update(s)}}}}var oe=s(25),re=s(14);class ce{static throw(e,...t){throw`${e}: ${t.join(", ")}`}}ce.InvalidProcessorExpression="Invalid expression",ce.CannotFoundType="Cannot found type",ce.CannotFoundTypeConstructor="Cannot found constructor of type",ce.CannotFoundStaticMethod="Cannot found static method",ce.CannotFoundEnum="Cannot found enumeration",ce.InvalidEnumValue="Enum does not contain value",ce.DublicateTypesFound="Dublicate types have been detected",ce.CommandNotFound="Command not found";var de=s(94),le=s(425),ue=s(444);class he{constructor(){this._types=new Map;const e=[ue,F,I];for(let t=0;t<e.length;t++)this._loadModuleTypes(e[t]);this._loadModuleTypes({Collection:le.a})}fromConstructor(e,...t){Object(c.l)(e)&&ce.throw("Invalid argument",e);const s=this._findFunction(e);this._isConstructor(s)||ce.throw(ce.CannotFoundTypeConstructor,e);const i=s;try{return new i(...t)}catch(a){throw console.error(a),a}}_findFunction(e){const t=e.split(".");this._types.has(t[0])||ce.throw(ce.CannotFoundType,e);let s=this._types.get(t[0]);for(let i=1;i<t.length;i++)null==s[t[i]]&&ce.throw(ce.CannotFoundTypeConstructor,e),s=s[t[i]];return s}_isConstructor(e){return e instanceof Function&&null!=e.prototype.constructor}fromStaticMethod(e,...t){const s=this._findFunction(e);null!=s&&s instanceof Function||ce.throw(ce.CannotFoundStaticMethod,e);try{return s(...t)}catch(i){throw console.error(i),i}}fromProperties(e,t){const s=this.fromConstructor(e);return Object(c.e)(s,[t],{deep:!1,ignoreNull:!1})}fromEnum(e,t){this._types.has(e)||ce.throw(ce.CannotFoundEnum,e);const s=this._types.get(e);return s instanceof Object||ce.throw(ce.CannotFoundEnum,e),null==s[t]&&ce.throw(ce.InvalidEnumValue,{type:e,value:t}),s[t]}_loadModuleTypes(e){if(void 0!==e)for(let[t,s]of Object.entries(e))(s instanceof Function||s instanceof Object)&&(this._types.has(t)&&ce.throw(ce.DublicateTypesFound,t),this._types.set(t,s))}}class ge extends re.a{subProcessorAllocatorFactory(){const e=new de.a;return e.register(new me(this,new he)),e}}class me extends oe.a{constructor(e,t){super(e),this._builder=t}apply(e,t,s=e=>e){switch(!0){case Array.isArray(e):return e.map((e=>s(e)));case this.isObject(e):const t={};for(let[i,a]of Object.entries(e)){if(this._isNewExpression(i)||this._isCallExpression(i))return this._buildObjectModel(i,a,s);t[i]=this._buildModelProperty(a,s)}return t;case this._isEnumExpression(e):return this._parseEnum(e);default:return e}}_buildModelProperty(e,t){switch(!0){case this.isObject(e):return t(e);case this._isEnumExpression(e):return this._parseEnum(e);default:return e}}_parseArguments(e,t){switch(!0){case Array.isArray(e):return e.map((e=>this._parseArguments(e,t)));case this.isObject(e)&&this.canApply(e):return t(e);case this._isEnumExpression(e):return this._parseEnum(e);default:return e}}_parseEnum(e){const t=this.splitOperandAndCondition(e);1===t.length&&null!=t[0].body||ce.throw(ce.InvalidProcessorExpression,e);const s=t[0].body.split(".");return 2==s.length?this._builder.fromEnum(s[0],s[1]):null}_buildObjectModel(e,t,s){const i=this.splitOperandAndCondition(e);1==i.length&&null!=i[0].body||ce.throw(ce.InvalidProcessorExpression,e);const a=i[0].body;return this._isCallExpression(e)?this._buildObjectByFactory(a,t,s):this._createObjectModel(a,t,s)}_buildObjectByFactory(e,t,s){let i=t;return Array.isArray(t)?i=t.map((e=>this._parseArguments(e,s))):this.isObject(t)&&(i=s(t)),this._builder.fromStaticMethod(e,i)}_createObjectModel(e,t,s){switch(!0){case this.isObject(t):return this._builder.fromProperties(e,s(t));case Array.isArray(t):const i=t.map((e=>this._parseArguments(e,s)));return this._builder.fromConstructor(e,...i);default:return this._builder.fromConstructor(e,t)}}canApply(e){return this.isObject(e)&&void 0!==Object.entries(e).find((([e,t])=>this._isNewExpression(e)||this._isCallExpression(e)||this._isEnumExpression(t)))}_isNewExpression(e){return/{{.*(#new).*/gi.test(e)}_isCallExpression(e){return/{{.*(#call).*/gi.test(e)}_isEnumExpression(e){return this.isString(e)&&/{{.*(#enum).*/gi.test(e)}}class fe extends N{constructor(){super(...arguments),this._configProcessor=new ge}async execute(e){const t=this._configProcessor.process(e,{}),s=await this.widget.getProduct(),i=await s.getProductModel(),a=await i.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0});for(let n of a){const e=t.items[n.name];l.a.isNullOrUndefined(e)||Object(c.f)(n,e)}await s.setProductModel(i)}}class pe extends N{async execute(e){const t=(Array.isArray(e)?e:[e]).filter((e=>e));if(0!==t.length)for(const s of t){const e=await this.widget.getProduct();if(!e.updateSurfaces)return void console.warn("Command unavailable for this version Customer's Canvas. Please, use version 6.2.0 or above.");1===e.updateSurfaces.length?await e.updateSurfaces(s):await e.updateSurfaces(s.productDefinition||s.definition,s.options,s.sourceSurfaceIndexes,s.targetSurfaceIndexes)}}}var we=s(865);let ye=class extends R{constructor(){super(...arguments),this._isRestoring=!1,this.isRestored=!1,this.modifiedItem=null,this._currentSurfaceName="",this._currentSurfaceIndex=0,this._surfaceCount=0,this.overallBounds={},this.itemsOnSurfacesCount=[],this._hiResUrls=[],this._proofImageUrls=[[]],this._proofPdfUrls=[],this._stateId="",this._userId="",this._privateDesignId="",this._userChanges={},this._variableData=[],this._allItems=[],this._depositPhotos=[],this._artLinkItems=[],this._tags={},this._identifyingString="",this._lastParams={},this._currentParams={},this._violationData=[],this.actionsFinished=!1,this.actionsFinishedPromise=new y,this.commands={initial:new G(this),changeMockup:new U(this),setPrintArea:new q(this),setTheme:new te(this),setBackground:new Y(this),updateContainerSettings:new ne(this),setRemoteMockup:new K(this),modifyItems:new H(this),setViewerSettings:new se(this),updateItems:new fe(this),setSerializedProduct:new Q(this),setSurfaces:new ee(this),swapSurfaces:new ie(this),resize:new X(this),translate:new ae(this),updateSurfaces:new pe(this),createImageItem:new B(this),loadUserInfo:new V(this),changeDesignVariant:new z(this),duplicateSurfaces:new T(this)},this.itemsData={},this._token=""}get violationWarningData(){return this._violationWarningData}get violationData(){return this._violationData}get boundsData(){return this._boundsData}get currentSurfaceName(){return this._currentSurfaceName}get currentSurfaceIndex(){return this._currentSurfaceIndex}get surfaceCount(){return this._surfaceCount}get proofImageUrls(){return this._proofImageUrls}get proofPdfUrls(){return this._proofPdfUrls}get hiResUrls(){return this._hiResUrls}get stateId(){return this._stateId}get userChanges(){return this._userChanges}get userId(){return this._userId}get allItems(){return this._allItems}get variableData(){return this._variableData}get depositPhotos(){return this._depositPhotos}get artLinkItems(){return this._artLinkItems}get sourcedItems(){return this._sourcedItems}get tags(){return this._tags}get identifyingString(){return this._identifyingString}get finishProductDesignResult(){return this._finishProductDesignResult}set stateId(e){this._stateId=e}async calculateIdentifyingString(e){const t=await this.getProduct(),s=await t.getProductModel(),i=await s.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0}),a=new n.a({titleTemplate:e}),o=i.reduce(((e,t)=>{const s=(e=>{var t,s;let i="";switch(!0){case e instanceof CustomersCanvas.DesignAtoms.ObjectModel.BaseTextItem:i=Object(c.k)(e.text);break;case e instanceof CustomersCanvas.DesignAtoms.ObjectModel.BarcodeItem:i=e.barcodeContent;break;case e instanceof CustomersCanvas.DesignAtoms.ObjectModel.ImageItem:i=null!==(t=e.displayName)&&void 0!==t?t:e.name;break;case e instanceof CustomersCanvas.DesignAtoms.ObjectModel.PlaceholderItem:e.imageContent&&(i=null!==(s=e.imageContent.displayName)&&void 0!==s?s:e.imageContent.name)}return{name:e.name,value:i}})(t);return e[s.name]=s.value,e}),{}),r=a.buildTitle(o);return this._identifyingString=r,this.emitChange(),r}isInstanceOf(e,t){const s=e=>{let t=[];return e.__proto__&&(t=t.concat(s(e.__proto__))),t.push((e=>e.constructor.type)(e)),t.filter((e=>e))};return i=t,-1!==s(e).indexOf(i.type);var i}updateParams(e){if(void 0!==e.initial&&(e.initial.editorConfig||(e.initial.editorConfig={}),e.initial.editorConfig.defaultLanguage=this.driver.config.language||"en",this.driver)){this._initialOrder=this._initialOrder||Object(u.a)(this.driver.orders[0]);const t=this.driver.user.id;t&&(e.initial.editorConfig.userId=t);const s=this.driver.user.tokenId;s&&(e.initial.editorConfig.tokenId=s);const i=this.auWizard.scopeInternal.widgetsData,a=i&&i[this.name]?i[this.name].stateId:this._initialOrder.data.stateId;a&&""!==a&&!0!==this.auWizard.clearState&&(e.initial.productDefinition=a),e.initial.editorConfig.preloader={enabled:!1}}}async exportWidgetData(e){return!0===e&&await this.finishProductDesign(),{stateId:this._stateId}}async restoreWidgetFromData(e,t=!1){var s,i,a,n;if(!0===t){const t=Object.assign({},(this.params||{}).initial||{});t.productDefinition=e.stateId;const o=null===(i=null===(s=this.driver)||void 0===s?void 0:s.user)||void 0===i?void 0:i.id,r=null===(n=null===(a=this.driver)||void 0===a?void 0:a.user)||void 0===n?void 0:n.tokenId;o&&r&&((null==t?void 0:t.initial)?(t.editorConfig.userId=o,t.editorConfig.tokenId=r):t.editorConfig={userId:o,tokenId:r}),"firefox"===l.a.getBrowser()?this.commands.initial.execute(t):await this.commands.initial.execute(t)}}async updateParamsAsync(e){await super.updateParamsAsync(e);let t=this._commandExecuter.getChangedActions(e,this._currentParams);if(0===t.length)return!1;if(-1!==t.indexOf("initial")){const s=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;let i=l.a.isNotNullOrUndefined(this._stateId)&&""!==this._stateId,a=l.a.isNotNullOrUndefined(e.initial.productDefinition)&&e.initial.productDefinition.toString().match(s);a&&(this._isRestoring=!0);const n=!0===e.initial.executeOnce;!i&&!a||n||(t=["initial"])}this.actionsFinishedPromise=new y,this.actionsFinished=!1,this._isRestoring||this.emitChange();const s=t.every((t=>{let s=e[t];return Array.isArray(e[t])&&(s=e[t][0]),!1===s.showPreloader}));let i=1===t.length&&-1!==t.indexOf("initial");s||this.showPreloader(!0,this.getPreloaderMessage(e,i)),this._currentParams=Object(u.a)(e);try{this._isRestoring&&!i||await this._commandExecuter.executeActions(e,t,this._lastParams)}catch(a){if(this.params.actionsErrorToast&&!0===this.params.actionsErrorToast.show){const e="widgets.canvas.actions.error";let t=this.localize(e);t===e&&(t="Something went wrong. Send the website support team information about your browser and steps to reproduce the problem."),this.showToast(t,this.params.actionsErrorToast.duration)}this.logger.error((()=>"Failed to perform an action on Design Editor. "),a)}finally{this.resetPreloaderState(),this._lastParams=e,this.actionsFinishedPromise.resolve(),this.actionsFinished=!0,this._isRestoring&&(this.getInitialParamsResolved(),this._isRestoring=!1,this.isRestored=!0),this.getSurfaceCount()}}connectedCallback(){super.connectedCallback(),this._commandExecuter=new d.a(this.commands,this.uniqWidgetName,(()=>Promise.resolve()),this),this.baseUrl=l.a.ensureEndsWith(this.driver.settings.customersCanvasBaseUrl,"/"),this.showPreloader(!0),this.iframeApiPromise=w.a.loadCCScript(this.baseUrl,l.a.CC_SCRIPT_RELATIVE_PATH),this.iframeApiPromise.then((()=>{this.showPreloader(!1),CustomersCanvas.IframeApi.editorUrl=this.baseUrl}))}async switchSurfaceTo(e){const t=await this.getProduct();return e<0||e>t.surfaces.length-1?(console.error(`Invalid surface index: ${e}`),t):await t.switchTo(t.surfaces[e])}async removeSurface(e){const t=await this.getProduct();if(e<0||e>t.surfaces.length-1)return void console.error(`Invalid surface index: ${e}`);const s=t.surfaces[e];return await t.removeSurface(s)}async addSurface(e,t){const s=await this.getProduct();return await s.addSurface(e,t)}async addSurfaces(e,t){const s=await this.getProduct();return await s.addSurfaces(e,t)}async updateSurfaces(e,t){let s=await this.getProduct();switch(e.toLowerCase()){case"remove":s=await this.removeSurface(t);break;case"add":s=await this.addSurface(t)}return s}async swapSurfaces(e,t){const s=await this.getProduct();if(!s.swapSurfaces)return void console.warn("Command unavailable for this version Customer's Canvas.");const i=s.surfaces[e],a=s.surfaces[t];return s.swapSurfaces(i,a)}updateModifiedItem(e){Object(h.a)(this.modifiedItem,e)||(this.modifiedItem=e,this.emitChange({modifiedItem:this.modifiedItem},!1))}updateOverallBounds(e){Object(h.a)(this.overallBounds,e)||(this.overallBounds=e,this.emitChange({overallBounds:this.overallBounds},!1))}async updateCurrentSurfaceData(){const e=await this.getProduct();this._currentSurfaceName=e.currentSurface.name,this._currentSurfaceIndex=e.surfaces.indexOf(e.currentSurface),this.emitChange()}async updateCurrentSurfaceName(){const e=await this.getProduct();this._currentSurfaceName=e.currentSurface.name,this.emitChange()}async updateCurrentSurfaceIndex(){const e=await this.getProduct();this._currentSurfaceIndex=e.surfaces.indexOf(e.currentSurface),this.emitChange()}async applyViewerSettings(e){return this.commands.setViewerSettings.execute(e)}async getProofImages(e=800,t=800,s=!0,i=!1,a=!1,n=1e3,o=1e3,r,c){const d=await this.getEditor();let l={};"object"==typeof s&&(r=s,s=!0);const u=null!=c?c:{};l="object"==typeof e?e:Object.assign({maxWidth:e,maxHeight:t,pregeneratePreviewImages:s,generateProductProof:i,generateLargePreviews:a,largePreviewMaxWidth:n,largePreviewMaxHeight:o},u);const h=await d.getProofImages(l,r);this._proofImageUrls=h.proofImageUrls;const g=await d.getProduct();return this._surfaceCount=g.surfaces.length,this.emitChange({urls:this.proofImageUrls},!1),h.proofImageUrls.map((e=>e[0]))}async getProofPdf(e,t={},s=!1){const i=Object.assign({},t,{generateProductProof:!0}),a=await this.getEditor(),n=(await a.getProofImages(i,e)).proofImageUrls.map((e=>e[0]));this._proofPdfUrls=n.filter((e=>e.endsWith(".pdf")));const o=await a.getProduct();return this._surfaceCount=o.surfaces.length,this.emitChange({proofPdfUrls:this.proofPdfUrls},s),this._proofPdfUrls}async getHiResImages(e=800,t=800,s,i=!1,a,n,o){const r=await this.getEditor();null!==s&&""!==s||(s=void 0),null!==a&&""!==a||(a=void 0),"object"==typeof s&&(n=s,s=void 0);const c=null!=o?o:{},d=await r.finishProductDesign(Object.assign({stateId:s,proofMaxWidth:e,proofMaxHeight:t,pregeneratePreviewImages:i,fileName:a},c),n);this._stateId=d.stateId,this._userId=d.userId,this._hiResUrls=d.hiResOutputUrls,this._proofImageUrls=d.proofImageUrls,this._userChanges=d.userChanges,this._violationWarningData=d.violationWarningData,this._boundsData=d.boundsData;const l=await r.getProduct();return this._surfaceCount=l.surfaces.length,this.emitChange({urls:this.hiResUrls,proofs:this.proofImageUrls,stateId:this.stateId,userId:this.userId,userChanges:this.userChanges,violationWarningData:this.violationWarningData,boundsData:this.boundsData},!0),d.hiResOutputUrls}async finishProductDesign(e,t){const s=await this.getEditor(),i=await s.finishProductDesign(e,t);this._finishProductDesignResult=i,this._stateId=i.stateId,this._userId=i.userId,this._hiResUrls=i.hiResOutputUrls,this._proofImageUrls=i.proofImageUrls,this._userChanges=i.userChanges,this._violationWarningData=i.violationWarningData,this._boundsData=i.boundsData;const a=await s.getProduct();return this._surfaceCount=a.surfaces.length,this.emitChange(),i}async getVariableData(){const e=await this.getProduct();return this._variableData=(await e.getVariableItems()).reverse(),this.emitChange({data:this.variableData}),this.variableData}async getAllItems(){const e=await this.getProduct(),t=await e.getProductModel();return this._allItems=t.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0}).reverse(),this.emitChange(),this.allItems}async getDepositPhotos(){const e=await this.getProduct(),t=await e.getProductModel(),s=await t.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0});return this.getDPItems(s),this._depositPhotos}getDPItems(e){const t=[];return e.forEach((e=>{const s=e.tags.dp_data;if(Object(g.a)(s)){const s=e=>e&&e.tags&&null!==e.tags.sourceData&&"DepositPhotosSource"===e.tags.sourceType,i=e=>e.tags.sourceData;if(s(e)){const s=i(e);t.push({imageId:e.id,depositPhotosId:s.id})}else if(e.content&&s(e.content)){const s=i(e.content);t.push({imageId:e.id,depositPhotosId:s.id,data:s})}}else t.push({imageId:e.id,depositPhotosId:JSON.parse(s).id})})),this._depositPhotos=t.map((e=>({imageId:e.imageId,depositPhotosId:e.depositPhotosId}))),this.emitChange({data:this.depositPhotos}),t}getArtLinkImages(e){const t=[];return e.forEach((e=>{var s=null!=e.content?e.content:e;if(null!=s.source&&null!=s.source.origin&&"ArtLinkSource"===s.source.origin.type){let i=s.source.origin.data;t.push({imageId:e.id,artLinkId:i.id,data:i})}})),this._artLinkItems=t.map((e=>({imageId:e.imageId,artLinkId:e.artLinkId}))),this.emitChange({data:this.artLinkItems}),t}async getArtLinkItems(){const e=await this.getProduct(),t=await e.getProductModel(),s=await t.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0});return this.getArtLinkImages(s),this._artLinkItems}async getItemsBySource(e){const t=[];if(!e)return{source:"unknown",items:t};const s=await this.getProduct(),i=await s.getProductModel(),a=await i.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0});return"dp"==e.toLowerCase()||"depositphotos"==e.toLowerCase()?(this.getDPItems(a).forEach((e=>{t.push({imageId:e.imageId,sourceId:e.depositPhotosId,data:e.data})})),this._sourcedItems={source:e.toLowerCase(),items:t},this.emitChange({data:this.sourcedItems}),this.sourcedItems):"artlink"==e.toLowerCase()?(this.getArtLinkImages(a).forEach((e=>{t.push({imageId:e.imageId,sourceId:e.artLinkId,data:e.data})})),this._sourcedItems={source:e.toLowerCase(),items:t},this.emitChange({data:this.sourcedItems}),this.sourcedItems):{source:"unknown",items:t}}async getTags(){const e=await this.getProduct();return this._tags=await e.getTags(),void 0===this._tags&&(this._tags={}),this.emitChange({tags:this.tags}),this.tags}async setTags(e){const t=await this.getProduct();await t.setTags(e),this._tags=e,this.emitChange({tags:this.tags})}async saveProduct(e,t){const s=await this.getEditor(),i=await s.saveProduct(e,t);this._stateId=i.stateId,this._userId=i.userId;const a=await s.getProduct();return this._surfaceCount=a.surfaces.length,await this.emitChange({stateId:this.stateId,userId:this.userId},!1),i}async replaceInterpolationPlaceholder(){if(!this._currentParams.replaceInterpolationPlaceholders)return Promise.resolve();(await this.getEditor()).replaceInterpolationPlaceholders()}toggleMaximizeMainPanel(e){this.publishData({main:e},p.a.TOGGLE_SIZE_MAIN)}async openAssetManagerFor(e){const t=await this.getEditor();await t.openGalleryForItem(e)}async openGalleryForBackground(){const e=await this.getEditor();await e.openGalleryForBackground()}async getItemText(e){const t=await this.getEditor(),s=await t.getProduct(),i=(await s.getProductModel()).getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0}).find((t=>t.name===e)),a=Object(c.k)(i&&i instanceof CustomersCanvas.DesignAtoms.ObjectModel.BaseTextItem?i.text:"");return this.itemsData[e]=this.itemsData[e]||{},this.itemsData[e].text=a,this.emitChange(),a}get token(){return this._token}async getToken(){const e=await this.getEditor();let t="";try{t=await e.eval("spEditor.configuration.tokenId;")}catch(s){console.error("Failed to get user token")}return this._token=t,this.emitChange(),t}async getSurfaceCount(){const e=(await this.getProduct()).surfaces.length;return this._surfaceCount=e,this.emitChange(),e}getPreloaderMessage(e,t){var s,i,a,n;return t?null!==(i=null===(s=null==e?void 0:e.preloader)||void 0===s?void 0:s.initialMessage)&&void 0!==i?i:this.localize("common.loading.preload"):null!==(n=null===(a=null==e?void 0:e.preloader)||void 0===a?void 0:a.actionsMessage)&&void 0!==n?n:this.localize("common.loading.preload")}async switchItemContent(e){if(l.a.isNullOrUndefined(e.to)||l.a.isNullOrUndefined(e.from))return;const t=await this.getProduct(),s=await t.getProductModel(),i=e=>{const t=s.surfaces.elementAt(e.surfaceIndex);return t?t.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!0}).firstOrDefault((t=>t.name===e.name)):null},a=i(e.from);let n=i(e.to);if(l.a.isNullOrUndefined(n)&&l.a.isNotNullOrUndefined(a)&&!0===e.to.force){n=a.clone(!0);const t=s.surfaces.elementAt(e.to.surfaceIndex);t&&t.containers[o.a.MAIN_CONTAINER_NAME].items.add(n)}if(!l.a.isNullOrUndefined(a)&&!l.a.isNullOrUndefined(n))if(a.type===n.type){switch(!0){case a instanceof window.CustomersCanvas.DesignAtoms.ObjectModel.BaseTextItem:const e=a,t=n,s=e.text,i=t.text;e.text=i,t.text=s;break;case a instanceof window.CustomersCanvas.DesignAtoms.ObjectModel.PlaceholderItem:const o=a,r=n,c=o.content.source,d=r.content.source;o.content.source=d,r.content.source=c;break;case a instanceof window.CustomersCanvas.DesignAtoms.ObjectModel.ImageItem:const l=a,u=n,h=l.source,g=u.source;l.source=g,u.source=h}await t.setProductModel(s)}else console.warn("Items have not matching types")}async countItemsOnSurfaces(e=!1){const t=[],s=await this.getProduct(),i=await s.getProductModel();for(const a of i.surfaces){const i=a.getAllItems({ignoreMockups:!0,flatGroupItems:!0,excludeGroupItems:!1,containerFilterFunc:e=>"Main"===e.name}).select((e=>e.id));if(e)if(s.getItemRectangles){const e=a.printAreas.select((e=>e.getBounds(r.a.Total)));let n=(await s.getItemRectangles(i.toArray())).map((e=>e.bounds)).filter((t=>e.any((e=>e.intersectsWith(t)))));t.push(n.length)}else t.push(i.count());else t.push(i.count())}this.itemsOnSurfacesCount=t,this.emitChange({itemsOnSurfacesCount:this.itemsOnSurfacesCount})}async getViolationData(){const e=await this.getEditor(),t=await e.getProduct();return this._violationData=t.getViolationData?await t.getViolationData():[],this.emitChange(),this._violationData}_createDAApiClientConfig(){const e=new a.a;return e.apiUrl=l.a.removeTrailingSlash(this.driver.backOffice.backOfficeUrl),e.setAuthorizationToken(this.driver.backOffice.token),e}initDpApi(){this._dpApiClientConfig=this._createDAApiClientConfig(),this.dpApi=new a.b(this._dpApiClientConfig,l.a.removeTrailingSlash(this.driver.backOffice.assetProcessorUrl))}_createDesignId(){return Object(m.a)()}async createPrivateDesignFromResources(e){try{if(l.a.isNullOrEmptyString(this._privateDesignId)){const t=await this.dpApi.copyDesignFromPublicResource(this.driver.backOffice.tenantId,this.driver.user.id,{publicResourceId:e,resultDesignId:this._createDesignId()}).then((e=>e.id));return this._privateDesignId=t,this.stateId=t,this._privateDesignId}return await this.dpApi.copyDesignFromPublicResource(this.driver.backOffice.tenantId,this.driver.user.id,{publicResourceId:e,resultDesignId:this._privateDesignId}),this._privateDesignId}catch(t){console.warn(`Can not create design from resource! Resource id - ${e}.`)}}async createPrivateDesignFromPublicDesign(e){try{if(l.a.isNullOrEmptyString(this._privateDesignId)){const t=await this.dpApi.copyDesignFromPublicDesign(this.driver.backOffice.tenantId,this.driver.user.id,{publicDesignId:e,resultDesignId:this._createDesignId()}).then((e=>e.id));return this._privateDesignId=t,this.stateId=t,this._privateDesignId}return await this.dpApi.copyDesignFromPublicDesign(this.driver.backOffice.tenantId,this.driver.user.id,{publicDesignId:e,resultDesignId:this._privateDesignId}),this._privateDesignId}catch(t){console.warn(`Can not create private design from public design! State id - ${e}.`)}}};ye=Object(i.a)([Object(f.a)("au-widget-design-editor",we)],ye)}}]);