@spiffcommerce/core 0.10.227 → 0.10.228
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +2 -2
- package/dist/module.js +2 -2
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -374,7 +374,7 @@ var t=require("@apollo/client"),A=require("lodash.clonedeep"),e=require("react/j
|
|
|
374
374
|
workflowState
|
|
375
375
|
}
|
|
376
376
|
}
|
|
377
|
-
`,sa=t=>{const A=[];for(const e of t.steps)switch(e.type){case K.DigitalContent:e.data.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Frame:const t=e.data;t.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),t.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Illustration:const n=e.data;n.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),n.varyColors&&n.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Colors});break;case K.Material:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Model:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Picture:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Question:e.data.varySelections&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selections});break;case K.Shape:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Text:const i=e.data;i.varyText&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Text}),i.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),i.varyColor&&i.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Color})}return A},ca=[K.SilentIllustration,K.ProductOverlay],ga=async(t,A)=>{const e=[];t.introduction&&e.push({name:"Introduction",title:t.name,renderableSteps:[{type:K.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const n of t.steps){if(A.bulkScene){let t=!1;switch(n.type){case K.DigitalContent:n.data.varyUpload&&(t=!0);break;case K.Frame:{const A=n.data;!A.varyUpload||!A.varySelection&&n.option||(t=!0)}break;case K.Illustration:{const A=n.data;!A.varySelection&&n.option&&1!==n.option.variants.length||!A.varyColors&&A.colorPickerEnabled||(t=!0)}break;case K.Material:n.data.varySelection&&(t=!0);break;case K.Model:n.data.varySelection&&(t=!0);break;case K.Picture:n.data.varySelection&&(t=!0);break;case K.Question:n.data.varySelections&&(t=!0);break;case K.Shape:n.data.varySelection&&(t=!0);break;case K.Text:{const A=n.data;!A.varySelection&&n.option&&1!==n.option.variants.length||!A.varyColor&&A.colorPickerEnabled&&A.colorOption||!A.varyText||(t=!0)}}if(t)continue}const i=la(n.stepName,t.stepGroups);if(i){const t=e.find((t=>t.name===i.name));t?ca.includes(n.type)?t.silentSteps.push(n):t.renderableSteps.push(n):e.push({name:i.name,title:i.name,renderableSteps:ca.includes(n.type)?[]:[n],silentSteps:ca.includes(n.type)?[n]:[]})}else e.push({name:n.stepName,title:n.stepTitle,renderableSteps:ca.includes(n.type)?[]:[n],silentSteps:ca.includes(n.type)?[n]:[]})}return A.bulkScene&&e.push({name:"Bulk",title:A.bulkSceneTitle,renderableSteps:[{type:K.Bulk,stepName:"Bulk",stepTitle:A.bulkSceneTitle,helpText:"Add any variations of your base design here.",data:{aspects:sa(t)},conditions:[]}],silentSteps:[]}),A.finishScene&&e.push({name:"Finish",title:A.finishSceneTitle,renderableSteps:[{type:K.Finish,stepName:"Finish",stepTitle:A.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),e},la=(t,A)=>A.find((A=>A.stepNames.includes(t))),Ba=(t,A)=>(t.conditions||[]).every((t=>{const e=A[t.targetStepName];if(e&&e.selectedVariants){const A=e.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==A.find((A=>A.id===t))))}return!1})),wa=(t,A)=>t.map((t=>((t,A)=>{const e={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ba(t,A))),silentSteps:t.silentSteps.filter((t=>Ba(t,A)))};return 0===e.silentSteps.length&&0===e.renderableSteps.length?null:e})(t,A))).filter((t=>null!==t)),ha=async(t,A)=>{const e=wa(t,A),n=[];for(const t of e)for(const A of t.renderableSteps)if(A.type===K.Model||A.type===K.Material||A.type===K.Picture||A.type===K.Shape){const t=A.option?.variants.length;t&&t>1&&n.push(A.stepName)}else n.push(A.stepName);const i=e.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of i)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return i};function da(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}function Ea(t,A,e,n){const i=e.width*t.zoom,a=e.height*t.zoom;if(n){const n=t,i=Math.max(A.width/e.width,A.height/e.height);n.zoom=Math.max(i,t.zoom);const a=e.width*n.zoom,o=e.height*n.zoom;return n.x=ua(t.x,A.width-a,0),n.y=ua(t.y,A.height-o,0),n}const o=t;return o.x=ua(o.x,-i,A.width),o.y=ua(o.y,-a,A.height),o}function ua(t,A,e){return Math.min(Math.max(t,A),e)}class Qa{constructor(t){da(this,"offsets",void 0),da(this,"forceImageCover",void 0),da(this,"targetElements",void 0),da(this,"imageData",void 0),da(this,"frameData",void 0),da(this,"_debouncedUpdateFrameOffsets",void 0),da(this,"minZoomScale",.03),da(this,"maxZoomScale",20),da(this,"onFrameDataChangeListeners",void 0),da(this,"onZoomChangeListeners",void 0),da(this,"workflowManager",void 0),da(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=I(p)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,A){A&&t.addStepSpecificStorageCallback((async t=>{if(t){const A=t;if(A.currentFrameSource){const t=await Qe(A.currentFrameSource);I(u)(t,this.frameData)||(this.frameData=t,this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.offsets=Ce(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),A),this.workflowManager=t,this.stepName=A}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}async setFrameData(t){const A=he.get(t);this.frameData=A}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,A,e,n){if(this.imageData&&this.offsets&&this.frameData){const i=(A-this.offsets.x)/this.offsets.zoom,a=(e-this.offsets.y)/this.offsets.zoom,o={x:A-i*t,y:e-a*t,zoom:this.imageData.width*t/this.imageData.width};this.updateOffsets(Ea(o,this.frameData,this.imageData,this.forceImageCover),n),this.onZoomChangeListeners.forEach((A=>A(t)))}}setPatternData(t){(t&&this.frameData||t&&this.frameData&&!this.imageData)&&(this.offsets=Ce(t,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements),this.updateOffsets(Ea(this.offsets,this.frameData,t,this.forceImageCover))),this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,A){const e=this.imageData;e&&this.frameData&&(this.offsets&&t.x===this.offsets.x&&t.y===this.offsets.y&&t.zoom===this.offsets.zoom?A&&A():(this.offsets=Ea(t,this.frameData,e,this.forceImageCover),this._debouncedUpdateFrameOffsets(t,e,this.frameData,this.targetElements,A)))}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,A,e,n,i){if(!e)throw new ze("Frame data not set. This is a bug");if(!this.workflowManager)throw new ze("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach((e=>{a(new ZA(e,A,t))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:t}),i&&i()}recalculateZoomLimits(t,A){const e=Math.max(A.width/t.width,A.height/t.height);this.forceImageCover?(this.minZoomScale=e,this.maxZoomScale=2.5*e):(this.minZoomScale=e/10,this.maxZoomScale=2.5*e)}}function Ca(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class ma{constructor(t,A,e){Ca(this,"configuration",void 0),Ca(this,"layouts",void 0),Ca(this,"product",void 0),Ca(this,"processRegion",(async t=>{const A=this.layouts.find((A=>A.panelId===t.panelId));if(!A)throw new Ge(t);let e="";if(this.configuration.type===K.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),e=t,!t)throw new Je(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===N.Image){const e=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!e)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:e,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:t},command:new OA(i,A)}}{const i=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:e,a=async()=>new Promise(((t,A)=>{i?Nt(i).then((A=>{t(A)})).catch((t=>console.error(t))):A("Undefined vector silent step source")})),o=await IA(await a()),r={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await ve(o.svg),src:i,svg:o.svg,colors:o.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:r.id,region:t},command:new OA(r,A)}}})),this.configuration=t,this.layouts=A,this.product=e||void 0}async trigger(){if(!this.configuration.data.regions)throw new Je(this.configuration,"Missing regions.");if(this.configuration.type===K.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===K.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((A=>t.panelId===A.panelId)))throw new Ge(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===K.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?N.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),N.Illustration)}}const pa=async t=>{const A=`${Ze.getServicesApiUrl()}/shortener`;try{const e=await fetch(A,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await e.json()).shortUrl}catch(t){throw console.error(t),new je("Failed to shorten URL, see console.")}};function Da(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class fa{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,A,e,n=3e3,i=10){Da(this,"pollingId",void 0),Da(this,"attempts",void 0),Da(this,"interval",void 0),Da(this,"maxAttempts",void 0),Da(this,"predicate",void 0),Da(this,"onSuccess",void 0),Da(this,"onFailure",void 0),this.onSuccess=A,this.onFailure=e,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const Ia=new class{async init(t,A,e){return e&&await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{const e=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;A.updateStorage(t.stepName,{videoShortUrl:e,videoUrl:i})}))}async regenerateQRCode(t,A,e,n,i,a,o,r,s){if(A||""===e||""!==n)s(!1);else{const A=async()=>{const t=await ln.getLocalOrFromServer(e),A=t.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:A}},c=await new Promise(((t,e)=>{new fa((async()=>!!(await A()).link),(async()=>{const e=await A();if(!e.link||!e.link)throw new ke(e.asset);t({rel:"mpeg4",href:e.link})}),(()=>{e("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new TA(t.id))));const g="http"===a.data.baseUrl.slice(0,4)?"":"https://",l=new URL(g+a.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([c]))),l.pathname=l.pathname+("/"===l.pathname.slice(-1)?"":"/");const B=l.toString();if(B.length>=2e3)throw new je("Cannot create QR code, URL too long.");const w=await pa(B);if(o(w),!a.data||!a.data.regions)throw new Je(a,"Missing regions.");const h=await this.regionElements(a),d=await this.command(w,h,i,a.stepName);d&&(d.command&&i.getCommandDispatcher()(d.command),d.followup&&await d.followup()),await i.setSelectionsAndElements(a.stepName,[],h,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:w,videoUrl:n}),s(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,A,e,n){const i=e.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,C.toString)(t,{type:"svg"}))}`,o=A.map((t=>{const A=t.region,e=i.find((t=>t.panelId===A?.panelId));if(!e&&A)throw new Ge(A);if(e&&!A)throw new Error("Region not found");if(!e||!A)throw new Error("Neither a region or layout found!");return new OA({stepRegion:A,stepName:n,id:t.id,src:a,type:N.Image,y:A.top,x:A.left,width:A.width,height:A.height,rotation:0},e)}));return{command:new JA(o),followup:async()=>{}}}};function ya(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Ma=new class{constructor(){ya(this,"frameSourceSvg",(async(t,A)=>{if(!t)return Ee(A.data.regions[0]);const e=t.asset;if(!e)throw new be(t);const n=e.fileLink;if(n)return Nt(n);throw new ke(e)}))}async init(t,A,e){if(e)return await this.reload(t,A,e),null;if(A.setMandatoryFulfilled(t.stepName,!1),A.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants.length>0){const e=t.option,n=dn.getDefaultVariant(e);return n?this.selectVariantCommand(t,n,[],A,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],A,void 0,t.data.placeholderImageUrl)}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===t.option.variants.length){const e=Ee(t.data.regions[0]);A.updateStorage(t.stepName,{currentFrameSource:e})}if(n){const e=async()=>{const e=n.storage?.framePatternSrc,i=n.storage?.frameOffsets;if(A.updateMetadata(t.stepName,{frameOffsets:i,framePatternSrc:e}),e){const n=A.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(e,n),A.updateMetadata(t.stepName,{image:e}),A.updateStorage(t.stepName,{framePatternSrc:e})}if(i?.zoom){const e=A.getStepSpecificServices(t.stepName)?.frameService;e.updateOffsets(i)}A.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants.find((t=>t.id===a));n&&await A.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=await this.frameSourceSvg(n,t);A.updateStorage(t.stepName,{currentFrameSource:i}),await e()}))}}else await A.setSelectionsAndElements(t.stepName,[],i,e)}}selectImage(t,A,e){e.setEditedStatus(t.stepName,!0);(A.fileLink||"").endsWith("pdf")?e.addPoller(new fa((async()=>{const t=(await ln.getLocalOrFromServer(A.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{ln.getLocalOrFromServer(A.key||"").then((A=>{this.loadPatternFromAsset(A,t,e)}))}),(()=>{throw new je("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(A,t,e)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,A,e,n){return new OA({id:t,type:N.Frame,x:A.left,y:A.top,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,scaleX:A.width/n.frameData.width,scaleY:A.height/n.frameData.height,path:n.frameData.path,stepRegion:A,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:A.immutable},e)}async loadPatternFromString(t,A){if(t.endsWith("svg")){const e=await pe(t),n=e.width,i=e.height,a={src:t,width:n,height:i,aspect:n/i};we.set(t,a),A.setPatternData(a)}else{const e=await St(t),n=await le(e),i={src:t,width:n.width,height:n.height,aspect:n.width/n.height};we.set(t,i),A.setPatternData(i)}}async selectVariantCommand(t,A,e,n,i,a){const o=n.getStepSpecificServices(t.stepName)?.frameService,r=await this.frameSourceSvg(A,t),s=await Qe(r),c=o.getImageData(),g=e.map((t=>new TA(t.id))),l=c?Ce(c,s):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0;i&&i(!0);const w=t.data.regions.map((A=>{const e=F(),i=n.getLayouts().find((t=>t.panelId===A.panelId));if(!i)throw new Ge(A);return{command:this.getCreateElementCommand(e,A,i,{frameData:s,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:e,region:A}}})),h=w.map((t=>t.command));return{command:new JA([...h,...g]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,A?[A]:[],[...w.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSource:r}),a){const A=n.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(a,A)}}))}}}patternSource(t){const A=t.versions?.find((t=>"svg"===t.name));if(A)return A.link;const e=t.fileLink;if(e)return e;throw new ke(t)}async loadPatternFromAsset(t,A,e){const n=this.patternSource(t),i=e.markUpdatePending(),a=e.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(n,a),e.updateMetadata(A.stepName,{image:n}),e.updateStorage(A.stepName,{framePatternSrc:n}),e.markUpdateCompleted(i)}};const xa=new class{async getIllustrationBody(t){return new Promise((A=>{Nt(t).then((t=>{A(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,A,e,n){return new OA({stepRegion:A,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:N.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},e)}getColors(t,A){const e=A.getRegionElements(t.stepName)||[];if(0===e.length)return[];try{return SA(e[0].id,A.getAllLayoutData()).colors}catch(t){return[]}}async init(t,A,e){const n=t.option;if(!n)return null;if(e)return this.reload(t,A,e);{const e=dn.getDefaultVariant(n);if(e)return await this.selectVariantCommand(t,e,[],(()=>{}),A)}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(!a||!e)throw new Error("Required illustration variant no longer available");{const o=a.variants.find((t=>t.id===e));if(o){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[o],e,(async()=>{A.updateMetadata(t.stepName,{colors:n.storage?.colors}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,A){const e=t.data.colorOption;return e&&e?e.variants.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,A,e,n,i){const a={};for(const[t,A]of i.entries())a[t]={browserValue:A,spotColor:a[t]?.spotColor};const o=fA(t,A,e,a),r=await ve(o),s=[];for(const t of n){for(const[A,e]of i.entries())s.push(new _A(t,A,e));s.push(new te(t,o,r))}return new JA(s)}async changeColors(t,A,e,n,i){if(0===A.length)return;const a=SA(A[0].id,n().map((t=>t.layoutState))),o={...a.colors},r={};Object.entries(o).forEach((([t,A])=>{const e={browserValue:A.browserValue},n=A.spotColor;n&&(e.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=e}));for(const[t,A]of i.entries())o[t]={browserValue:A,spotColor:o[t]?.spotColor},r[t]={browserValue:A};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants.forEach((t=>{s=s.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),e.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,A])=>{g.set(t,A.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(a.svg,a.width,a.height,A.map((t=>t.id)),g);e.updateStorage(t.stepName,{colors:r}),e.getCommandDispatcher()(l)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,A,e,n,i){if(!t.data||!t.data.regions)throw new Je(t,"Missing regions.");n(!0);const a=e.map((t=>new TA(t.id)));i.setMandatoryFulfilled(t.stepName,!1);const o=A.asset;if(!o)throw new be(A);const r=o.fileLink;if(!r)throw new ke(o);const s=await IA(await this.getIllustrationBody(r)),c=await ve(s.svg),g=t.data.regions.map((A=>{const e=i.getLayouts().find((t=>t.panelId===A.panelId));if(!e)throw new Ge(A);const n=F();return{regionElement:{id:n,region:A},command:this.getCreateElementCommand(n,A,e,{stepName:t.stepName,src:r,objectURL:c,svg:s})}})),l=[...g.map((t=>t.command)),...a];let B=Array.from(Object.values(s.colors)).map((t=>t.browserValue));const w=t.data.colorOption;return w&&w.variants.forEach((t=>{B=B.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),i.updateMetadata(t.stepName,{colors:B}),{command:new JA(l),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[A],g.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Fa=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=dn.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(!a)throw new Ue(t);if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(e){const n=a.variants.find((t=>t.id===e));if(n){const e=n.material,o=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=A.getPreviewService();if(n){const i=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id,e)));Promise.all(i).then((()=>A.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){const i=e.getPreviewService();n(!0);const a=A.material;if(!a)throw n(!1),new be(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{i&&t.data.targetMaterials.forEach((A=>{t.option&&i.applyMaterialVariant(A,t.option.id,a)})),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ya=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=dn.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{const e=A.getPreviewService();if(e&&t.option){const i=n.asset?.fileLink;if(!i)throw new be(n);await e.applyModelVariant(t.option.id,{model:i,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){n(!0);const i=A.asset?.fileLink;if(!i)throw new be(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{const A=e.getPreviewService();A&&t.option&&A.applyModelVariant(t.option.id,{model:i,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const va=new class{async init(t,A,e){return e?(await this.reload(t,A,e),null):(A.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",A,"",(()=>{})))}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{A.updateStorage(t.stepName,{text:n?.storage?.text}),A.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,A,e,n,i){const a=await this.changeTextCommand(t,A,e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,A,e,n,i){const a=e.getRegionElements(t.stepName),o=e.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const r=e.getProfanities();if(!this.validateInput(t,A,r,i))return e.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(e.setMandatoryFulfilled(t.stepName,""!==A),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;e.updateStorage(t.stepName,{text:A});const s=(A,n,i)=>{const a=i||F(),o=e.getLayouts().find((t=>t.panelId===n.panelId));if(!o)return console.error(`Can not find layout for region: ${n.panelId}`),null;const r=[];return i&&r.push(new TA(a)),r.push(new OA({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:A,type:N.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},o)),{id:a,region:n,command:new JA(r)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const e=o.svgPrint(A,t.region);return s(e,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>s(o.svgPrint(A,t),t))),i=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(i),followup:async()=>{const A=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await e.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,A,e,n){if(t.data&&t.data.maxLength){const e=t.data.maxLength;if(A.length>e)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(A))return n("Unsupported characters."),!1;const i=A.toLowerCase();for(const t in e)if(i===e[t].toLowerCase().trim()&&""!==i)return n("Blocked profanity."),!1;return n(""),!0}};const Sa=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else if(n.defaultVariant)return A.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,A,(()=>{}));return A.markStepsAsInitialised([t.stepName]),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=A.asset;if(!i)throw new be(A);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),e.setMandatoryFulfilled(t.stepName,!1);const o=e.getRegionElements(t.stepName).map((t=>new TA(t.id))),r=t.data.regions.map((A=>{const n=e.getLayouts().find((t=>t.panelId===A.panelId));if(!n)throw new Ge(A);const i=F();return{regionElement:{id:i,region:A},command:new OA({stepName:t.stepName,stepRegion:A,id:i,src:a,type:N.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},n)}}));return{command:new JA([...o,...r.map((t=>t.command))]),followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],r.map((t=>t.regionElement)),(async()=>{e.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Na=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{const e=n.variants;if(dn.getDefaultVariant(n)){const i=e.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,i?.id||"",A)}}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(i&&e){const n=i.variants.find((t=>t.id===e));n&&await A.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,A,e){const n=await this.selectVariantLambda(t,A,e);n&&(n.command&&e.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,A,e){const n=t.option;if(!n)return null;const i=n.variants,a=i.length>1?i.find((t=>t.id===A)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[a],[],(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ra=new class{async availableColours(t){const A=t.option;return A?A.variants.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(!e){const e=dn.getDefaultVariant(n);if(!e)return null;const i={fill:e.color,stroke:e.color,variant:e};return this.selectVariantCommand(t,i,[],A)}return await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.updateStorage(t.stepName,{colour:n.color||""}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=n.getLayouts();if(e.length>0){const a=t=>{const e=t.region;if(!i.find((t=>t.panelId===e?.panelId)))throw new Ge(e);const n=A.variant?.color;return n?new _A(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=e.map(a).filter((t=>!!t));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],e),n.updateStorage(t.stepName,{colour:A.fill||""})}}}{const e=e=>{const n=i.find((t=>t.panelId===e.panelId));if(!n)throw new Ge(e);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${A.variant?.color}"\n />\n </svg>\n `,o={};o["spiff-fill-shape"]={browserValue:A.variant.color};const r=F();return{id:r,region:e,command:new OA({stepRegion:e,stepName:t.stepName,colors:o,id:r,svg:a,type:N.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},a=t.data.regions.map(e),o=a.filter((t=>!!t)).map((t=>t?.command)),r=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],r,(async()=>{n.updateStorage(t.stepName,{colour:A.fill||""})}))}}}}};function Ha(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Pa=new class{constructor(){Ha(this,"latestToast",void 0),Ha(this,"toastType",void 0),Ha(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}setLatestToast(t,A){this.latestToast=t,this.toastType=A,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((t=>t({toastMessage:this.latestToast,toastType:this.toastType})))}};function Ua(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class Ga extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ga.name}}class ba extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ba.name}}const ka=new class{constructor(){Ua(this,"cachedColors",new Map),Ua(this,"filterUnsupportedCharacters",((t,A)=>{let e=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=A?Vt(A):void 0;if(i){const t=e.split("").map((t=>i.getFont().charToGlyph(t)));for(let A=0;A<t.length;A++){const i=".notdef"===t[A].name;"\n"===e.charAt(A)||i&&n.push(String.fromCharCode(e.charCodeAt(A)))}}for(let t=0;t<n.length;t++)e=e.replaceAll(n[t],"");return e})),Ua(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Ua(this,"getErrorsForText",((t,A,e)=>{const n=[];A.data&&A.data.maxLength&&t.length>A.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=e.getProfanities(),a=t.toLowerCase();if(""!==a)for(const t in i){if(a===i[t].toLowerCase().trim()){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!A.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{A.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data)}),A.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data)});const e=dn.getDefaultVariant(n);if(e)return this.selectVariantCommand(t,e,{},[],A,(()=>{}),(()=>{}))}return null}findLayoutElements(t,A){return t.getRegionElements(A.stepName).map((A=>SA(A.id,t.getAllLayoutData())))}async availableColors(t,A){const e=this.cachedColors.get(t.stepName);if(e)return e;const n=t.data.colorOption;if(n){const A=n.variants.map((t=>({fill:t.color,stroke:t.color,variant:t})));return this.cachedColors.set(t.stepName,A),A}return[]}async changeFill(t,A,e,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher();A.variant?n.updateMetadata(t.stepName,{color:A.variant.name}):n.updateMetadata(t.stepName,{color:A.fill});const a=await this.getColorOption(t),o=a?this.createTextFillSpotColor(a,A.variant):void 0;a?n.updateStorage(t.stepName,{color:A.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:A.fill});for(const t of e){if(!A.fill)throw new Error("Fill not set on new color selection!");i(new KA(t.id,A.fill,o))}}getProcessedInput(t,A,e){const n=e?t:this.injectReplaceableText(t,A);return oA(n,{vertical:A.vertical,uppercase:A.uppercase})}updateInputText(t,A,e,n){const i=n.getStepStorage(e.stepName),a=this.getProcessedInput(t,e.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,e,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(e.data.maxLength-a.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&e.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of A){if(!t.fontData)throw new ze("Failed to resolve font data for text.");const[A,n]=ye(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});g.set(t.id,A),l.set(t.id,n);const i=e.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(A,e.data,t.id,i,s))}if(!e.data.curved&&A.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(e.stepName,{text:t}),n.updateMetadata(e.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(e.stepName,!0),o.command=new JA(c),o.command.varying=s,o}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e.getStepStorage(t.stepName)||{},e.getRegionElements(t.stepName),e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,A){const e=t.colorProfile;if(e){const t=(e.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),i=t.slice(n+1).slice(0,-4);if(!A.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:A.namedColor}}}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const o=a.variants.find((t=>t.id===e));if(o){const e=await this.fontDataFromVariant(o),a=i.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await A.setSelectionsAndElements(t.stepName,[o],a,(async()=>{A.updateMetadata(t.stepName,{color:r,text:s}),A.updateStorage(t.stepName,{text:s,inputText:s});const n=i.map((t=>new XA(t.id,e))),a=new JA(n);A.getCommandDispatcher()(a),A.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=ka.updateInputText(s||"",i,t,A);c&&A.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const A=t.colorOption;if(A)return dn.getDefaultVariant(A)}async getDefaultColor(t){const A=t.colorOption;if(!A)return;return dn.getDefaultVariant(A)?.color}async getColorOption(t){return t.data.colorOption}async fontDataFromVariant(t){const A=t.asset;if(!A)throw new be(t);const e=A.fileLink;if(!e)throw new ke(A);return{assetUrl:e,name:(await jt(e)).names.fullName.en}}async selectVariantCommand(t,A,e,n,i,a,o){const r=i.markUpdatePending(),s=await this.fontDataFromVariant(A);if(n.length>0){const c=n.map((t=>new XA(t.id,s))),g=await this.changeInputTextWithRegion(t,t.data.size||30,s,e.text||"",e,i,!!e.customiseAllText,a,o);g&&c.push(g);return{command:new JA(c),followup:async()=>{i.markUpdateCompleted(r),await i.setSelectionsAndElements(t.stepName,[A],n)}}}{const n=await this.createTextboxRegions(t.stepName,A,t.data,s,e,i),c=await this.changeInputTextWithRegion(t,t.data.size||30,s,n[0]?.newElement.input||e.text||t.data.defaultText||"",e,i,!!e.customiseAllText,a,o),g=n.flatMap((t=>t.commands));c&&g.push(c);return{command:new JA(g),followup:async()=>{i.markUpdateCompleted(r)}}}}injectReplaceableText(t,A){return A.replaceableText?A.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,A,e,n,i,a){if(!e||!e.regions)throw new Error("Step data not supplied");const o=a.getTransaction().bulk&&e.varyText||!1,r=o?"":i.text||e.defaultText||"",s=this.getProcessedInput(r,e,!1),c=await Promise.all(e.regions.map((async A=>{const c=a.getLayouts().find((t=>t.panelId===A.panelId)),g=F();try{if(!c)throw new ba("Failed to find layout for region: "+A.panelId);const l=e.colorOption;let B;if(l){const A=l.variants.find((t=>t.id===l.defaultVariant?.id))||l.variants[0];B=this.createTextFillSpotColor(l,A),a.updateStorage(t,{colorProfileAssetKey:l.colorProfile?.key})}const w=await this.getDefaultColor(e),h=w||"#000000",d={stepRegion:A,stepName:t,align:this.textAlign(e),fill:i.color?i.color:h,fontSize:e.size||30,fontData:n,id:g,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:s,input:r,type:N.Textbox,vertical:e.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:e.verticalAlign||"middle",curved:e.curved,paths:e.paths,fillSpotColorDefinition:B},E=[],u=new Map,Q=new Map;if(!d.fontData)throw new ze("Failed to resolve font data for text.");const[C,m]=ye(d.fontSize,d.fontData,{left:d.x,top:d.y,width:d.width,height:d.height,rotation:d.rotation,panelId:""},[s],{size:e.size,minSize:e.minSize,maxSize:e.maxSize});u.set(d.id,C),Q.set(d.id,m);const p=e.curved||e.vertical?s:(m||[]).join("\n");E.push(this.generateTextChangeCommandsForRegion(C,e,d.id,p,o));const D=new OA(d,c);return D.varying=o,{regionElement:{id:g,region:A},commands:[D,...E],newElement:d,fontData:n}}catch(t){throw console.log(t),new Ga("Error adding font to region")}}))).catch((t=>{throw t instanceof Ga?(Pa.setLatestToast("Failed to load font.",La.Error),t):t instanceof ba?t:new Error(t)}));return await a.setSelectionsAndElements(t,[A],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:r}),a.updateStorage(t,{text:r})})),c}generateTextChangeCommandsForRegion(t,A,e,n,i){const a=[],o=new $A(e,n);if(o.varying=i,a.push(o),!A.size){const A=new VA(e,t);A.varying=i,a.push(A)}const r=new JA(a);return r.varying=i,r}async changeInputTextWithRegion(t,A,e,n,i,a,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=a.getRegionElements(t.stepName),w=new Map,h=new Map;for(const n of B)if(n.region){const[i,a]=ye(A,e,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});w.set(n.id,i),h.set(n.id,a)}const d=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const A=l.toLowerCase(),e=a.getProfanities();for(const t in e)if(A===e[t].toLowerCase().trim()&&""!==A)return r(!0),{error:"Blocked profanity."};if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(d.error)return void s(d.error);if(s(`${d.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:g}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const E=a.getTransaction().bulk&&t.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const A of B){const e=t.data.curved?l:(h.get(A.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(w.get(A.id)||1,t.data,A.id,e,E))}const Q=new JA(u);return Q.varying=E,Q}};function Ja(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}let La;var za;(za=La||(La={})).Error="Error",za.Warning="Warning",za.Info="Info";class Oa extends li{constructor(t){super(),Ja(this,"update",void 0),Ja(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ta{constructor(t,A,e,n,i,a,o,r,s,c,g=!1){Ja(this,"reloadedState",void 0),Ja(this,"transaction",void 0),Ja(this,"updateTransaction",void 0),Ja(this,"confirmedDesign",void 0),Ja(this,"editedSteps",void 0),Ja(this,"informationResults",void 0),Ja(this,"layouts",void 0),Ja(this,"mandatorySteps",void 0),Ja(this,"pendingUpdates",void 0),Ja(this,"selectionCost",void 0),Ja(this,"workflow",void 0),Ja(this,"stepSpecificServices",void 0),Ja(this,"previewService",void 0),Ja(this,"profanityFilter",void 0),Ja(this,"pollers",void 0),Ja(this,"commandContext",void 0),Ja(this,"stepElements",void 0),Ja(this,"stepInitialised",void 0),Ja(this,"stepMetadata",void 0),Ja(this,"stepSelections",void 0),Ja(this,"storage",void 0),Ja(this,"confirmCallbacks",void 0),Ja(this,"editedCallbacks",void 0),Ja(this,"elementsCallbacks",void 0),Ja(this,"informationResultCallbacks",void 0),Ja(this,"initCallbacks",void 0),Ja(this,"makingAdjustmentsCallback",void 0),Ja(this,"mandatoryCallbacks",void 0),Ja(this,"metadataCallbacks",void 0),Ja(this,"selectionCallbacks",void 0),Ja(this,"stepSpecificStorageCallbacks",void 0),Ja(this,"storageCallbacks",void 0),Ja(this,"currentVariationRecordCallbacks",void 0),Ja(this,"variationRecordCallbacks",void 0),Ja(this,"allScenes",void 0),Ja(this,"product",void 0),Ja(this,"invalidModelVariants",void 0),Ja(this,"currentAdjustingStepId",void 0),Ja(this,"renderableContextService",void 0),Ja(this,"workflowStatePromiseQueue",new Bi(1)),Ja(this,"variationRecords",[]),Ja(this,"currentVariationRecord",void 0),Ja(this,"initializationPromise",void 0),Ja(this,"initialized",!1),Ja(this,"readOnly",!1),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=A,this.pollers=[],this.allScenes=[],this.layouts=e,this.product=o,this.previewService=r,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>this.updateStateWithServer()))))}async initializeDefaultWorkflowState(t,A){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await ga(t,{bulkScene:A.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"});const e=wa(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(e,!!this.reloadedState);this.commandContext.apply(new JA(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.readOnly&&await this.updateStateWithServerImmediate(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const A=t.lookAtAnimation,e=t.modelAnimation;A&&this.previewService?.executeCameraAnimation(A),e&&this.previewService?.executeModelAnimation(e)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const A={...t,recordNumber:this.variationRecords.reduce(((t,A)=>A.recordNumber>t?A.recordNumber:t),0)+1};return this.variationRecords.push(A),this.onVariationRecordsChange(),A}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((A=>A.recordNumber!==t)),this.variationRecords.forEach(((t,A)=>t.recordNumber=A+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,A=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(A||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const A=this.variationRecords.find((A=>A.recordNumber===t.recordNumber));A&&(A.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,A){Object.keys(this.storage).includes(A)||(this.storage[A]={}),t(this.storage[A]),Object.keys(this.stepSpecificStorageCallbacks).includes(A)||(this.stepSpecificStorageCallbacks[A]=[]),this.stepSpecificStorageCallbacks[A].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}setTransactionCustomerDetails(t){this.transaction.bulkEmailAddress=t.email}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((A=>{const e=this.stepSelections[A.stepName];e&&e.selectedVariants&&e.selectedVariants.length>0&&(t[A.stepName]={selections:e.selectedVariants})})),t}markStepsAsInitialised(t){const A={...this.stepInitialised};t.forEach((t=>{A[t]=!0})),this.stepInitialised=A,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((A=>A!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,A){this.editedSteps={...this.editedSteps,[t]:A},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,A){this.mandatorySteps[t]!==A&&(this.mandatorySteps={...this.mandatorySteps,[t]:A},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async updateStorage(t,A){const e={...this.storage,[t]:{...this.storage[t],...A}};if(!I(u)(e,this.storage)){this.storage=e;const A=new UA(this.constructSerializableWorkflow());this.commandContext.apply(A,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((A=>{A.renderableSteps.forEach((A=>{const e={stepName:A.stepName};e.storage=this.storage[A.stepName],e.selectedVariants=this.stepSelections[A.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(e)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Oa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Oa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ze("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(I(A)(t.transaction))),n=t.variation;if(!n)return{transaction:e};const i={layouts:{},serializableWorkflow:{steps:[]},...I(A)(n)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(i))}}dehydrateState(t){for(const A of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===A.type&&(delete A.cachedObjectURL,A.src&&delete A.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,A){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...A}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,A)=>Object.keys(t).reduce(((e,n)=>{const i=[...t[n]||[]];return A.forEach((t=>{const A=i.findIndex((A=>A.id===t.id));A>-1&&i.splice(A,1)})),e[n]=i,e}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,A)=>(Ba(A,this.stepSelections)||this.stepElements[A.stepName]&&this.stepElements[A.stepName].forEach((A=>t.push(A))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,A)=>("Model"!==A.type||Ba(A,this.stepSelections)||A.option&&t.push(A.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,A){const e=this.product;if(!e)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,A,e)=>{if(t.type===K.SilentIllustration){return{step:t,results:await new ma(t,A).trigger()}}if(t.type===K.ProductOverlay){return{step:t,results:await new ma(t,A,e).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},o=[];for(const t of i)this.markStepsAsInitialised([t.stepName]),A||o.push(n(t,this.layouts,e));const r=await Promise.all(o);for(const t of r)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,A){return A.find((A=>A.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new TA(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,A,e,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:A}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,A)=>t+A.selectedVariants.map((t=>t.priceModifier)).reduce(((t,A)=>t+A),0)),0),this.workflow.steps.forEach((t=>{Ba(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,o=wa(a,i),r=wa(a,this.stepSelections),s=o.map((t=>t.silentSteps)).flat(),c=r.map((t=>t.silentSteps)).flat().filter((t=>!s.some((A=>A.stepName===t.stepName))));s.forEach((t=>{Ba(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const g=this.getInvalidCanvasRegions(),{stepElements:l,commands:B}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...l,[t]:e},this.removeElements(g);if(this.workflow.steps.find((A=>A.stepName===t))?.type===K.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(e.map((t=>t.id)))}const w=[...B,...g.map((t=>new TA(t.id))),new UA(this.constructSerializableWorkflow())];w.length>0&&this.commandContext.apply(new JA(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],A=wa(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const e of A)if(!this.stepInitialised[e.stepName])switch(this.stepInitialised[e.stepName]=!0,e.type){case K.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case K.DigitalContent:t.push(Ia.init(e,this,this.reloadedState));break;case K.Frame:case K.Photo:{const A=new Qa(e.data.forceImageCover);A.connectWorkflowManager(this,e.stepName),this.stepSpecificServices[e.stepName]={frameService:A},t.push(Ma.init(e,this,this.reloadedState))}break;case K.Illustration:t.push(xa.init(e,this,this.reloadedState));break;case K.Material:t.push(Fa.init(e,this,this.reloadedState));break;case K.Model:t.push(Ya.init(e,this,this.reloadedState));break;case K.Module:this.stepSpecificServices[e.stepName]={module:await Ni(e.data.module)},t.push(va.init(e,this,this.reloadedState));break;case K.Picture:t.push(Sa.init(e,this,this.reloadedState));break;case K.Question:t.push(Na.init(e,this,this.reloadedState));break;case K.Shape:t.push(Ra.init(e,this,this.reloadedState));break;case K.Text:t.push(ka.init(e,this,this.reloadedState))}const e=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=e.filter((t=>!!t&&!!t.command)).map((t=>t.command)),i=e.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new JA(n),!0);for(const t of i)await t();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const A of this.selectionCallbacks)A({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((A=>A(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)}))}traversableScenes(){return ha(this.allScenes,this.stepSelections)}}function ja(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class Ka{constructor(t,A){ja(this,"manager",void 0),ja(this,"step",void 0),this.manager=t,this.step=A}setUpdateState(t){Ka.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Ka.updateState.get(this.step.stepName)}async getCurrentVariant(){return(await this.manager.getWorkflowSelections())[this.step.stepName]?.selections[0]}async getAvailableVariants(){return this.step.option?.variants||[]}getName(){return this.step.stepTitle}getId(){return this.step.stepName}getType(){return this.step.type}getHelpText(){return this.step.helpText}}function Va(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}ja(Ka,"updateState",new Map);const Wa=t.gql`
|
|
377
|
+
`,sa=t=>{const A=[];for(const e of t.steps)switch(e.type){case K.DigitalContent:e.data.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Frame:const t=e.data;t.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),t.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Illustration:const n=e.data;n.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),n.varyColors&&n.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Colors});break;case K.Material:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Model:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Picture:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Question:e.data.varySelections&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selections});break;case K.Shape:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Text:const i=e.data;i.varyText&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Text}),i.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),i.varyColor&&i.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Color})}return A},ca=[K.SilentIllustration,K.ProductOverlay],ga=async(t,A,e)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:K.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const e of t.steps){if(A.bulkScene){let t=!1;switch(e.type){case K.DigitalContent:e.data.varyUpload&&(t=!0);break;case K.Frame:{const A=e.data;!A.varyUpload||!A.varySelection&&e.option||(t=!0)}break;case K.Illustration:{const A=e.data;!A.varySelection&&e.option&&1!==e.option.variants.length||!A.varyColors&&A.colorPickerEnabled||(t=!0)}break;case K.Material:e.data.varySelection&&(t=!0);break;case K.Model:e.data.varySelection&&(t=!0);break;case K.Picture:e.data.varySelection&&(t=!0);break;case K.Question:e.data.varySelections&&(t=!0);break;case K.Shape:e.data.varySelection&&(t=!0);break;case K.Text:{const A=e.data;!A.varySelection&&e.option&&1!==e.option.variants.length||!A.varyColor&&A.colorPickerEnabled&&A.colorOption||!A.varyText||(t=!0)}}if(t)continue}const i=la(e.stepName,t.stepGroups);if(i){const t=n.find((t=>t.name===i.name));t?ca.includes(e.type)?t.silentSteps.push(e):t.renderableSteps.push(e):n.push({name:i.name,title:i.name,renderableSteps:ca.includes(e.type)?[]:[e],silentSteps:ca.includes(e.type)?[e]:[]})}else n.push({name:e.stepName,title:e.stepTitle,renderableSteps:ca.includes(e.type)?[]:[e],silentSteps:ca.includes(e.type)?[e]:[]})}if(A.bulkScene){const i=e?.product?.bulkConfiguration;n.push({name:"Bulk",title:i?.sceneTitle??A.bulkSceneTitle,renderableSteps:[{type:K.Bulk,stepName:"Bulk",stepTitle:i?.stepTitle??A.bulkSceneTitle,helpText:i?.helpText,data:{aspects:sa(t)},conditions:[]}],silentSteps:[]})}return A.finishScene&&n.push({name:"Finish",title:A.finishSceneTitle,renderableSteps:[{type:K.Finish,stepName:"Finish",stepTitle:A.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},la=(t,A)=>A.find((A=>A.stepNames.includes(t))),Ba=(t,A)=>(t.conditions||[]).every((t=>{const e=A[t.targetStepName];if(e&&e.selectedVariants){const A=e.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==A.find((A=>A.id===t))))}return!1})),wa=(t,A)=>t.map((t=>((t,A)=>{const e={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ba(t,A))),silentSteps:t.silentSteps.filter((t=>Ba(t,A)))};return 0===e.silentSteps.length&&0===e.renderableSteps.length?null:e})(t,A))).filter((t=>null!==t)),ha=async(t,A)=>{const e=wa(t,A),n=[];for(const t of e)for(const A of t.renderableSteps)if(A.type===K.Model||A.type===K.Material||A.type===K.Picture||A.type===K.Shape){const t=A.option?.variants.length;t&&t>1&&n.push(A.stepName)}else n.push(A.stepName);const i=e.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of i)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return i};function da(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}function Ea(t,A,e,n){const i=e.width*t.zoom,a=e.height*t.zoom;if(n){const n=t,i=Math.max(A.width/e.width,A.height/e.height);n.zoom=Math.max(i,t.zoom);const a=e.width*n.zoom,o=e.height*n.zoom;return n.x=ua(t.x,A.width-a,0),n.y=ua(t.y,A.height-o,0),n}const o=t;return o.x=ua(o.x,-i,A.width),o.y=ua(o.y,-a,A.height),o}function ua(t,A,e){return Math.min(Math.max(t,A),e)}class Qa{constructor(t){da(this,"offsets",void 0),da(this,"forceImageCover",void 0),da(this,"targetElements",void 0),da(this,"imageData",void 0),da(this,"frameData",void 0),da(this,"_debouncedUpdateFrameOffsets",void 0),da(this,"minZoomScale",.03),da(this,"maxZoomScale",20),da(this,"onFrameDataChangeListeners",void 0),da(this,"onZoomChangeListeners",void 0),da(this,"workflowManager",void 0),da(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=I(p)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,A){A&&t.addStepSpecificStorageCallback((async t=>{if(t){const A=t;if(A.currentFrameSource){const t=await Qe(A.currentFrameSource);I(u)(t,this.frameData)||(this.frameData=t,this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.offsets=Ce(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),A),this.workflowManager=t,this.stepName=A}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}async setFrameData(t){const A=he.get(t);this.frameData=A}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,A,e,n){if(this.imageData&&this.offsets&&this.frameData){const i=(A-this.offsets.x)/this.offsets.zoom,a=(e-this.offsets.y)/this.offsets.zoom,o={x:A-i*t,y:e-a*t,zoom:this.imageData.width*t/this.imageData.width};this.updateOffsets(Ea(o,this.frameData,this.imageData,this.forceImageCover),n),this.onZoomChangeListeners.forEach((A=>A(t)))}}setPatternData(t){(t&&this.frameData||t&&this.frameData&&!this.imageData)&&(this.offsets=Ce(t,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements),this.updateOffsets(Ea(this.offsets,this.frameData,t,this.forceImageCover))),this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,A){const e=this.imageData;e&&this.frameData&&(this.offsets&&t.x===this.offsets.x&&t.y===this.offsets.y&&t.zoom===this.offsets.zoom?A&&A():(this.offsets=Ea(t,this.frameData,e,this.forceImageCover),this._debouncedUpdateFrameOffsets(t,e,this.frameData,this.targetElements,A)))}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,A,e,n,i){if(!e)throw new ze("Frame data not set. This is a bug");if(!this.workflowManager)throw new ze("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach((e=>{a(new ZA(e,A,t))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:t}),i&&i()}recalculateZoomLimits(t,A){const e=Math.max(A.width/t.width,A.height/t.height);this.forceImageCover?(this.minZoomScale=e,this.maxZoomScale=2.5*e):(this.minZoomScale=e/10,this.maxZoomScale=2.5*e)}}function Ca(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class ma{constructor(t,A,e){Ca(this,"configuration",void 0),Ca(this,"layouts",void 0),Ca(this,"product",void 0),Ca(this,"processRegion",(async t=>{const A=this.layouts.find((A=>A.panelId===t.panelId));if(!A)throw new Ge(t);let e="";if(this.configuration.type===K.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),e=t,!t)throw new Je(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===N.Image){const e=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!e)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:e,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:t},command:new OA(i,A)}}{const i=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:e,a=async()=>new Promise(((t,A)=>{i?Nt(i).then((A=>{t(A)})).catch((t=>console.error(t))):A("Undefined vector silent step source")})),o=await IA(await a()),r={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await ve(o.svg),src:i,svg:o.svg,colors:o.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:r.id,region:t},command:new OA(r,A)}}})),this.configuration=t,this.layouts=A,this.product=e||void 0}async trigger(){if(!this.configuration.data.regions)throw new Je(this.configuration,"Missing regions.");if(this.configuration.type===K.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===K.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((A=>t.panelId===A.panelId)))throw new Ge(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===K.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?N.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),N.Illustration)}}const pa=async t=>{const A=`${Ze.getServicesApiUrl()}/shortener`;try{const e=await fetch(A,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await e.json()).shortUrl}catch(t){throw console.error(t),new je("Failed to shorten URL, see console.")}};function Da(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class fa{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,A,e,n=3e3,i=10){Da(this,"pollingId",void 0),Da(this,"attempts",void 0),Da(this,"interval",void 0),Da(this,"maxAttempts",void 0),Da(this,"predicate",void 0),Da(this,"onSuccess",void 0),Da(this,"onFailure",void 0),this.onSuccess=A,this.onFailure=e,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const Ia=new class{async init(t,A,e){return e&&await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{const e=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;A.updateStorage(t.stepName,{videoShortUrl:e,videoUrl:i})}))}async regenerateQRCode(t,A,e,n,i,a,o,r,s){if(A||""===e||""!==n)s(!1);else{const A=async()=>{const t=await ln.getLocalOrFromServer(e),A=t.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:A}},c=await new Promise(((t,e)=>{new fa((async()=>!!(await A()).link),(async()=>{const e=await A();if(!e.link||!e.link)throw new ke(e.asset);t({rel:"mpeg4",href:e.link})}),(()=>{e("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new TA(t.id))));const g="http"===a.data.baseUrl.slice(0,4)?"":"https://",l=new URL(g+a.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([c]))),l.pathname=l.pathname+("/"===l.pathname.slice(-1)?"":"/");const B=l.toString();if(B.length>=2e3)throw new je("Cannot create QR code, URL too long.");const w=await pa(B);if(o(w),!a.data||!a.data.regions)throw new Je(a,"Missing regions.");const h=await this.regionElements(a),d=await this.command(w,h,i,a.stepName);d&&(d.command&&i.getCommandDispatcher()(d.command),d.followup&&await d.followup()),await i.setSelectionsAndElements(a.stepName,[],h,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:w,videoUrl:n}),s(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,A,e,n){const i=e.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,C.toString)(t,{type:"svg"}))}`,o=A.map((t=>{const A=t.region,e=i.find((t=>t.panelId===A?.panelId));if(!e&&A)throw new Ge(A);if(e&&!A)throw new Error("Region not found");if(!e||!A)throw new Error("Neither a region or layout found!");return new OA({stepRegion:A,stepName:n,id:t.id,src:a,type:N.Image,y:A.top,x:A.left,width:A.width,height:A.height,rotation:0},e)}));return{command:new JA(o),followup:async()=>{}}}};function ya(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Ma=new class{constructor(){ya(this,"frameSourceSvg",(async(t,A)=>{if(!t)return Ee(A.data.regions[0]);const e=t.asset;if(!e)throw new be(t);const n=e.fileLink;if(n)return Nt(n);throw new ke(e)}))}async init(t,A,e){if(e)return await this.reload(t,A,e),null;if(A.setMandatoryFulfilled(t.stepName,!1),A.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants.length>0){const e=t.option,n=dn.getDefaultVariant(e);return n?this.selectVariantCommand(t,n,[],A,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],A,void 0,t.data.placeholderImageUrl)}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===t.option.variants.length){const e=Ee(t.data.regions[0]);A.updateStorage(t.stepName,{currentFrameSource:e})}if(n){const e=async()=>{const e=n.storage?.framePatternSrc,i=n.storage?.frameOffsets;if(A.updateMetadata(t.stepName,{frameOffsets:i,framePatternSrc:e}),e){const n=A.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(e,n),A.updateMetadata(t.stepName,{image:e}),A.updateStorage(t.stepName,{framePatternSrc:e})}if(i?.zoom){const e=A.getStepSpecificServices(t.stepName)?.frameService;e.updateOffsets(i)}A.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants.find((t=>t.id===a));n&&await A.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=await this.frameSourceSvg(n,t);A.updateStorage(t.stepName,{currentFrameSource:i}),await e()}))}}else await A.setSelectionsAndElements(t.stepName,[],i,e)}}selectImage(t,A,e){e.setEditedStatus(t.stepName,!0);(A.fileLink||"").endsWith("pdf")?e.addPoller(new fa((async()=>{const t=(await ln.getLocalOrFromServer(A.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{ln.getLocalOrFromServer(A.key||"").then((A=>{this.loadPatternFromAsset(A,t,e)}))}),(()=>{throw new je("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(A,t,e)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,A,e,n){return new OA({id:t,type:N.Frame,x:A.left,y:A.top,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,scaleX:A.width/n.frameData.width,scaleY:A.height/n.frameData.height,path:n.frameData.path,stepRegion:A,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:A.immutable},e)}async loadPatternFromString(t,A){if(t.endsWith("svg")){const e=await pe(t),n=e.width,i=e.height,a={src:t,width:n,height:i,aspect:n/i};we.set(t,a),A.setPatternData(a)}else{const e=await St(t),n=await le(e),i={src:t,width:n.width,height:n.height,aspect:n.width/n.height};we.set(t,i),A.setPatternData(i)}}async selectVariantCommand(t,A,e,n,i,a){const o=n.getStepSpecificServices(t.stepName)?.frameService,r=await this.frameSourceSvg(A,t),s=await Qe(r),c=o.getImageData(),g=e.map((t=>new TA(t.id))),l=c?Ce(c,s):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0;i&&i(!0);const w=t.data.regions.map((A=>{const e=F(),i=n.getLayouts().find((t=>t.panelId===A.panelId));if(!i)throw new Ge(A);return{command:this.getCreateElementCommand(e,A,i,{frameData:s,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:e,region:A}}})),h=w.map((t=>t.command));return{command:new JA([...h,...g]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,A?[A]:[],[...w.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSource:r}),a){const A=n.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(a,A)}}))}}}patternSource(t){const A=t.versions?.find((t=>"svg"===t.name));if(A)return A.link;const e=t.fileLink;if(e)return e;throw new ke(t)}async loadPatternFromAsset(t,A,e){const n=this.patternSource(t),i=e.markUpdatePending(),a=e.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(n,a),e.updateMetadata(A.stepName,{image:n}),e.updateStorage(A.stepName,{framePatternSrc:n}),e.markUpdateCompleted(i)}};const xa=new class{async getIllustrationBody(t){return new Promise((A=>{Nt(t).then((t=>{A(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,A,e,n){return new OA({stepRegion:A,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:N.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},e)}getColors(t,A){const e=A.getRegionElements(t.stepName)||[];if(0===e.length)return[];try{return SA(e[0].id,A.getAllLayoutData()).colors}catch(t){return[]}}async init(t,A,e){const n=t.option;if(!n)return null;if(e)return this.reload(t,A,e);{const e=dn.getDefaultVariant(n);if(e)return await this.selectVariantCommand(t,e,[],(()=>{}),A)}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(!a||!e)throw new Error("Required illustration variant no longer available");{const o=a.variants.find((t=>t.id===e));if(o){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[o],e,(async()=>{A.updateMetadata(t.stepName,{colors:n.storage?.colors}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,A){const e=t.data.colorOption;return e&&e?e.variants.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,A,e,n,i){const a={};for(const[t,A]of i.entries())a[t]={browserValue:A,spotColor:a[t]?.spotColor};const o=fA(t,A,e,a),r=await ve(o),s=[];for(const t of n){for(const[A,e]of i.entries())s.push(new _A(t,A,e));s.push(new te(t,o,r))}return new JA(s)}async changeColors(t,A,e,n,i){if(0===A.length)return;const a=SA(A[0].id,n().map((t=>t.layoutState))),o={...a.colors},r={};Object.entries(o).forEach((([t,A])=>{const e={browserValue:A.browserValue},n=A.spotColor;n&&(e.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=e}));for(const[t,A]of i.entries())o[t]={browserValue:A,spotColor:o[t]?.spotColor},r[t]={browserValue:A};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants.forEach((t=>{s=s.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),e.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,A])=>{g.set(t,A.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(a.svg,a.width,a.height,A.map((t=>t.id)),g);e.updateStorage(t.stepName,{colors:r}),e.getCommandDispatcher()(l)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,A,e,n,i){if(!t.data||!t.data.regions)throw new Je(t,"Missing regions.");n(!0);const a=e.map((t=>new TA(t.id)));i.setMandatoryFulfilled(t.stepName,!1);const o=A.asset;if(!o)throw new be(A);const r=o.fileLink;if(!r)throw new ke(o);const s=await IA(await this.getIllustrationBody(r)),c=await ve(s.svg),g=t.data.regions.map((A=>{const e=i.getLayouts().find((t=>t.panelId===A.panelId));if(!e)throw new Ge(A);const n=F();return{regionElement:{id:n,region:A},command:this.getCreateElementCommand(n,A,e,{stepName:t.stepName,src:r,objectURL:c,svg:s})}})),l=[...g.map((t=>t.command)),...a];let B=Array.from(Object.values(s.colors)).map((t=>t.browserValue));const w=t.data.colorOption;return w&&w.variants.forEach((t=>{B=B.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),i.updateMetadata(t.stepName,{colors:B}),{command:new JA(l),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[A],g.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Fa=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=dn.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(!a)throw new Ue(t);if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(e){const n=a.variants.find((t=>t.id===e));if(n){const e=n.material,o=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=A.getPreviewService();if(n){const i=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id,e)));Promise.all(i).then((()=>A.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){const i=e.getPreviewService();n(!0);const a=A.material;if(!a)throw n(!1),new be(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{i&&t.data.targetMaterials.forEach((A=>{t.option&&i.applyMaterialVariant(A,t.option.id,a)})),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ya=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=dn.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{const e=A.getPreviewService();if(e&&t.option){const i=n.asset?.fileLink;if(!i)throw new be(n);await e.applyModelVariant(t.option.id,{model:i,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){n(!0);const i=A.asset?.fileLink;if(!i)throw new be(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{const A=e.getPreviewService();A&&t.option&&A.applyModelVariant(t.option.id,{model:i,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const va=new class{async init(t,A,e){return e?(await this.reload(t,A,e),null):(A.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",A,"",(()=>{})))}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{A.updateStorage(t.stepName,{text:n?.storage?.text}),A.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,A,e,n,i){const a=await this.changeTextCommand(t,A,e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,A,e,n,i){const a=e.getRegionElements(t.stepName),o=e.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const r=e.getProfanities();if(!this.validateInput(t,A,r,i))return e.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(e.setMandatoryFulfilled(t.stepName,""!==A),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;e.updateStorage(t.stepName,{text:A});const s=(A,n,i)=>{const a=i||F(),o=e.getLayouts().find((t=>t.panelId===n.panelId));if(!o)return console.error(`Can not find layout for region: ${n.panelId}`),null;const r=[];return i&&r.push(new TA(a)),r.push(new OA({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:A,type:N.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},o)),{id:a,region:n,command:new JA(r)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const e=o.svgPrint(A,t.region);return s(e,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>s(o.svgPrint(A,t),t))),i=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(i),followup:async()=>{const A=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await e.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,A,e,n){if(t.data&&t.data.maxLength){const e=t.data.maxLength;if(A.length>e)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(A))return n("Unsupported characters."),!1;const i=A.toLowerCase();for(const t in e)if(i===e[t].toLowerCase().trim()&&""!==i)return n("Blocked profanity."),!1;return n(""),!0}};const Sa=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else if(n.defaultVariant)return A.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,A,(()=>{}));return A.markStepsAsInitialised([t.stepName]),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=A.asset;if(!i)throw new be(A);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),e.setMandatoryFulfilled(t.stepName,!1);const o=e.getRegionElements(t.stepName).map((t=>new TA(t.id))),r=t.data.regions.map((A=>{const n=e.getLayouts().find((t=>t.panelId===A.panelId));if(!n)throw new Ge(A);const i=F();return{regionElement:{id:i,region:A},command:new OA({stepName:t.stepName,stepRegion:A,id:i,src:a,type:N.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},n)}}));return{command:new JA([...o,...r.map((t=>t.command))]),followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],r.map((t=>t.regionElement)),(async()=>{e.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Na=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{const e=n.variants;if(dn.getDefaultVariant(n)){const i=e.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,i?.id||"",A)}}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(i&&e){const n=i.variants.find((t=>t.id===e));n&&await A.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,A,e){const n=await this.selectVariantLambda(t,A,e);n&&(n.command&&e.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,A,e){const n=t.option;if(!n)return null;const i=n.variants,a=i.length>1?i.find((t=>t.id===A)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[a],[],(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ra=new class{async availableColours(t){const A=t.option;return A?A.variants.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(!e){const e=dn.getDefaultVariant(n);if(!e)return null;const i={fill:e.color,stroke:e.color,variant:e};return this.selectVariantCommand(t,i,[],A)}return await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.updateStorage(t.stepName,{colour:n.color||""}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=n.getLayouts();if(e.length>0){const a=t=>{const e=t.region;if(!i.find((t=>t.panelId===e?.panelId)))throw new Ge(e);const n=A.variant?.color;return n?new _A(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=e.map(a).filter((t=>!!t));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],e),n.updateStorage(t.stepName,{colour:A.fill||""})}}}{const e=e=>{const n=i.find((t=>t.panelId===e.panelId));if(!n)throw new Ge(e);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${A.variant?.color}"\n />\n </svg>\n `,o={};o["spiff-fill-shape"]={browserValue:A.variant.color};const r=F();return{id:r,region:e,command:new OA({stepRegion:e,stepName:t.stepName,colors:o,id:r,svg:a,type:N.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},a=t.data.regions.map(e),o=a.filter((t=>!!t)).map((t=>t?.command)),r=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],r,(async()=>{n.updateStorage(t.stepName,{colour:A.fill||""})}))}}}}};function Ha(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Pa=new class{constructor(){Ha(this,"latestToast",void 0),Ha(this,"toastType",void 0),Ha(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}setLatestToast(t,A){this.latestToast=t,this.toastType=A,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((t=>t({toastMessage:this.latestToast,toastType:this.toastType})))}};function Ua(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class Ga extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ga.name}}class ba extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ba.name}}const ka=new class{constructor(){Ua(this,"cachedColors",new Map),Ua(this,"filterUnsupportedCharacters",((t,A)=>{let e=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=A?Vt(A):void 0;if(i){const t=e.split("").map((t=>i.getFont().charToGlyph(t)));for(let A=0;A<t.length;A++){const i=".notdef"===t[A].name;"\n"===e.charAt(A)||i&&n.push(String.fromCharCode(e.charCodeAt(A)))}}for(let t=0;t<n.length;t++)e=e.replaceAll(n[t],"");return e})),Ua(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Ua(this,"getErrorsForText",((t,A,e)=>{const n=[];A.data&&A.data.maxLength&&t.length>A.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=e.getProfanities(),a=t.toLowerCase();if(""!==a)for(const t in i){if(a===i[t].toLowerCase().trim()){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!A.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{A.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data)}),A.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data)});const e=dn.getDefaultVariant(n);if(e)return this.selectVariantCommand(t,e,{},[],A,(()=>{}),(()=>{}))}return null}findLayoutElements(t,A){return t.getRegionElements(A.stepName).map((A=>SA(A.id,t.getAllLayoutData())))}async availableColors(t,A){const e=this.cachedColors.get(t.stepName);if(e)return e;const n=t.data.colorOption;if(n){const A=n.variants.map((t=>({fill:t.color,stroke:t.color,variant:t})));return this.cachedColors.set(t.stepName,A),A}return[]}async changeFill(t,A,e,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher();A.variant?n.updateMetadata(t.stepName,{color:A.variant.name}):n.updateMetadata(t.stepName,{color:A.fill});const a=await this.getColorOption(t),o=a?this.createTextFillSpotColor(a,A.variant):void 0;a?n.updateStorage(t.stepName,{color:A.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:A.fill});for(const t of e){if(!A.fill)throw new Error("Fill not set on new color selection!");i(new KA(t.id,A.fill,o))}}getProcessedInput(t,A,e){const n=e?t:this.injectReplaceableText(t,A);return oA(n,{vertical:A.vertical,uppercase:A.uppercase})}updateInputText(t,A,e,n){const i=n.getStepStorage(e.stepName),a=this.getProcessedInput(t,e.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,e,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(e.data.maxLength-a.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&e.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of A){if(!t.fontData)throw new ze("Failed to resolve font data for text.");const[A,n]=ye(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});g.set(t.id,A),l.set(t.id,n);const i=e.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(A,e.data,t.id,i,s))}if(!e.data.curved&&A.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(e.stepName,{text:t}),n.updateMetadata(e.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(e.stepName,!0),o.command=new JA(c),o.command.varying=s,o}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e.getStepStorage(t.stepName)||{},e.getRegionElements(t.stepName),e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,A){const e=t.colorProfile;if(e){const t=(e.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),i=t.slice(n+1).slice(0,-4);if(!A.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:A.namedColor}}}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const o=a.variants.find((t=>t.id===e));if(o){const e=await this.fontDataFromVariant(o),a=i.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await A.setSelectionsAndElements(t.stepName,[o],a,(async()=>{A.updateMetadata(t.stepName,{color:r,text:s}),A.updateStorage(t.stepName,{text:s,inputText:s});const n=i.map((t=>new XA(t.id,e))),a=new JA(n);A.getCommandDispatcher()(a),A.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=ka.updateInputText(s||"",i,t,A);c&&A.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const A=t.colorOption;if(A)return dn.getDefaultVariant(A)}async getDefaultColor(t){const A=t.colorOption;if(!A)return;return dn.getDefaultVariant(A)?.color}async getColorOption(t){return t.data.colorOption}async fontDataFromVariant(t){const A=t.asset;if(!A)throw new be(t);const e=A.fileLink;if(!e)throw new ke(A);return{assetUrl:e,name:(await jt(e)).names.fullName.en}}async selectVariantCommand(t,A,e,n,i,a,o){const r=i.markUpdatePending(),s=await this.fontDataFromVariant(A);if(n.length>0){const c=n.map((t=>new XA(t.id,s))),g=await this.changeInputTextWithRegion(t,t.data.size||30,s,e.text||"",e,i,!!e.customiseAllText,a,o);g&&c.push(g);return{command:new JA(c),followup:async()=>{i.markUpdateCompleted(r),await i.setSelectionsAndElements(t.stepName,[A],n)}}}{const n=await this.createTextboxRegions(t.stepName,A,t.data,s,e,i),c=await this.changeInputTextWithRegion(t,t.data.size||30,s,n[0]?.newElement.input||e.text||t.data.defaultText||"",e,i,!!e.customiseAllText,a,o),g=n.flatMap((t=>t.commands));c&&g.push(c);return{command:new JA(g),followup:async()=>{i.markUpdateCompleted(r)}}}}injectReplaceableText(t,A){return A.replaceableText?A.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,A,e,n,i,a){if(!e||!e.regions)throw new Error("Step data not supplied");const o=a.getTransaction().bulk&&e.varyText||!1,r=o?"":i.text||e.defaultText||"",s=this.getProcessedInput(r,e,!1),c=await Promise.all(e.regions.map((async A=>{const c=a.getLayouts().find((t=>t.panelId===A.panelId)),g=F();try{if(!c)throw new ba("Failed to find layout for region: "+A.panelId);const l=e.colorOption;let B;if(l){const A=l.variants.find((t=>t.id===l.defaultVariant?.id))||l.variants[0];B=this.createTextFillSpotColor(l,A),a.updateStorage(t,{colorProfileAssetKey:l.colorProfile?.key})}const w=await this.getDefaultColor(e),h=w||"#000000",d={stepRegion:A,stepName:t,align:this.textAlign(e),fill:i.color?i.color:h,fontSize:e.size||30,fontData:n,id:g,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:s,input:r,type:N.Textbox,vertical:e.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:e.verticalAlign||"middle",curved:e.curved,paths:e.paths,fillSpotColorDefinition:B},E=[],u=new Map,Q=new Map;if(!d.fontData)throw new ze("Failed to resolve font data for text.");const[C,m]=ye(d.fontSize,d.fontData,{left:d.x,top:d.y,width:d.width,height:d.height,rotation:d.rotation,panelId:""},[s],{size:e.size,minSize:e.minSize,maxSize:e.maxSize});u.set(d.id,C),Q.set(d.id,m);const p=e.curved||e.vertical?s:(m||[]).join("\n");E.push(this.generateTextChangeCommandsForRegion(C,e,d.id,p,o));const D=new OA(d,c);return D.varying=o,{regionElement:{id:g,region:A},commands:[D,...E],newElement:d,fontData:n}}catch(t){throw console.log(t),new Ga("Error adding font to region")}}))).catch((t=>{throw t instanceof Ga?(Pa.setLatestToast("Failed to load font.",La.Error),t):t instanceof ba?t:new Error(t)}));return await a.setSelectionsAndElements(t,[A],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:r}),a.updateStorage(t,{text:r})})),c}generateTextChangeCommandsForRegion(t,A,e,n,i){const a=[],o=new $A(e,n);if(o.varying=i,a.push(o),!A.size){const A=new VA(e,t);A.varying=i,a.push(A)}const r=new JA(a);return r.varying=i,r}async changeInputTextWithRegion(t,A,e,n,i,a,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=a.getRegionElements(t.stepName),w=new Map,h=new Map;for(const n of B)if(n.region){const[i,a]=ye(A,e,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});w.set(n.id,i),h.set(n.id,a)}const d=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const A=l.toLowerCase(),e=a.getProfanities();for(const t in e)if(A===e[t].toLowerCase().trim()&&""!==A)return r(!0),{error:"Blocked profanity."};if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(d.error)return void s(d.error);if(s(`${d.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:g}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const E=a.getTransaction().bulk&&t.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const A of B){const e=t.data.curved?l:(h.get(A.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(w.get(A.id)||1,t.data,A.id,e,E))}const Q=new JA(u);return Q.varying=E,Q}};function Ja(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}let La;var za;(za=La||(La={})).Error="Error",za.Warning="Warning",za.Info="Info";class Oa extends li{constructor(t){super(),Ja(this,"update",void 0),Ja(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ta{constructor(t,A,e,n,i,a,o,r,s,c,g=!1){Ja(this,"reloadedState",void 0),Ja(this,"transaction",void 0),Ja(this,"updateTransaction",void 0),Ja(this,"confirmedDesign",void 0),Ja(this,"editedSteps",void 0),Ja(this,"informationResults",void 0),Ja(this,"layouts",void 0),Ja(this,"mandatorySteps",void 0),Ja(this,"pendingUpdates",void 0),Ja(this,"selectionCost",void 0),Ja(this,"workflow",void 0),Ja(this,"stepSpecificServices",void 0),Ja(this,"previewService",void 0),Ja(this,"profanityFilter",void 0),Ja(this,"pollers",void 0),Ja(this,"commandContext",void 0),Ja(this,"stepElements",void 0),Ja(this,"stepInitialised",void 0),Ja(this,"stepMetadata",void 0),Ja(this,"stepSelections",void 0),Ja(this,"storage",void 0),Ja(this,"confirmCallbacks",void 0),Ja(this,"editedCallbacks",void 0),Ja(this,"elementsCallbacks",void 0),Ja(this,"informationResultCallbacks",void 0),Ja(this,"initCallbacks",void 0),Ja(this,"makingAdjustmentsCallback",void 0),Ja(this,"mandatoryCallbacks",void 0),Ja(this,"metadataCallbacks",void 0),Ja(this,"selectionCallbacks",void 0),Ja(this,"stepSpecificStorageCallbacks",void 0),Ja(this,"storageCallbacks",void 0),Ja(this,"currentVariationRecordCallbacks",void 0),Ja(this,"variationRecordCallbacks",void 0),Ja(this,"allScenes",void 0),Ja(this,"product",void 0),Ja(this,"invalidModelVariants",void 0),Ja(this,"currentAdjustingStepId",void 0),Ja(this,"renderableContextService",void 0),Ja(this,"workflowStatePromiseQueue",new Bi(1)),Ja(this,"variationRecords",[]),Ja(this,"currentVariationRecord",void 0),Ja(this,"initializationPromise",void 0),Ja(this,"initialized",!1),Ja(this,"readOnly",!1),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=A,this.pollers=[],this.allScenes=[],this.layouts=e,this.product=o,this.previewService=r,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>this.updateStateWithServer()))))}async initializeDefaultWorkflowState(t,A){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await ga(t,{bulkScene:A.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},A);const e=wa(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(e,!!this.reloadedState);this.commandContext.apply(new JA(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.readOnly&&await this.updateStateWithServerImmediate(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const A=t.lookAtAnimation,e=t.modelAnimation;A&&this.previewService?.executeCameraAnimation(A),e&&this.previewService?.executeModelAnimation(e)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const A={...t,recordNumber:this.variationRecords.reduce(((t,A)=>A.recordNumber>t?A.recordNumber:t),0)+1};return this.variationRecords.push(A),this.onVariationRecordsChange(),A}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((A=>A.recordNumber!==t)),this.variationRecords.forEach(((t,A)=>t.recordNumber=A+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,A=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(A||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const A=this.variationRecords.find((A=>A.recordNumber===t.recordNumber));A&&(A.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,A){Object.keys(this.storage).includes(A)||(this.storage[A]={}),t(this.storage[A]),Object.keys(this.stepSpecificStorageCallbacks).includes(A)||(this.stepSpecificStorageCallbacks[A]=[]),this.stepSpecificStorageCallbacks[A].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}setTransactionCustomerDetails(t){this.transaction.bulkEmailAddress=t.email}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((A=>{const e=this.stepSelections[A.stepName];e&&e.selectedVariants&&e.selectedVariants.length>0&&(t[A.stepName]={selections:e.selectedVariants})})),t}markStepsAsInitialised(t){const A={...this.stepInitialised};t.forEach((t=>{A[t]=!0})),this.stepInitialised=A,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((A=>A!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,A){this.editedSteps={...this.editedSteps,[t]:A},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,A){this.mandatorySteps[t]!==A&&(this.mandatorySteps={...this.mandatorySteps,[t]:A},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async updateStorage(t,A){const e={...this.storage,[t]:{...this.storage[t],...A}};if(!I(u)(e,this.storage)){this.storage=e;const A=new UA(this.constructSerializableWorkflow());this.commandContext.apply(A,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((A=>{A.renderableSteps.forEach((A=>{const e={stepName:A.stepName};e.storage=this.storage[A.stepName],e.selectedVariants=this.stepSelections[A.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(e)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Oa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Oa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ze("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(I(A)(t.transaction))),n=t.variation;if(!n)return{transaction:e};const i={layouts:{},serializableWorkflow:{steps:[]},...I(A)(n)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(i))}}dehydrateState(t){for(const A of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===A.type&&(delete A.cachedObjectURL,A.src&&delete A.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,A){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...A}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,A)=>Object.keys(t).reduce(((e,n)=>{const i=[...t[n]||[]];return A.forEach((t=>{const A=i.findIndex((A=>A.id===t.id));A>-1&&i.splice(A,1)})),e[n]=i,e}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,A)=>(Ba(A,this.stepSelections)||this.stepElements[A.stepName]&&this.stepElements[A.stepName].forEach((A=>t.push(A))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,A)=>("Model"!==A.type||Ba(A,this.stepSelections)||A.option&&t.push(A.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,A){const e=this.product;if(!e)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,A,e)=>{if(t.type===K.SilentIllustration){return{step:t,results:await new ma(t,A).trigger()}}if(t.type===K.ProductOverlay){return{step:t,results:await new ma(t,A,e).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},o=[];for(const t of i)this.markStepsAsInitialised([t.stepName]),A||o.push(n(t,this.layouts,e));const r=await Promise.all(o);for(const t of r)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,A){return A.find((A=>A.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new TA(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,A,e,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:A}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,A)=>t+A.selectedVariants.map((t=>t.priceModifier)).reduce(((t,A)=>t+A),0)),0),this.workflow.steps.forEach((t=>{Ba(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,o=wa(a,i),r=wa(a,this.stepSelections),s=o.map((t=>t.silentSteps)).flat(),c=r.map((t=>t.silentSteps)).flat().filter((t=>!s.some((A=>A.stepName===t.stepName))));s.forEach((t=>{Ba(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const g=this.getInvalidCanvasRegions(),{stepElements:l,commands:B}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...l,[t]:e},this.removeElements(g);if(this.workflow.steps.find((A=>A.stepName===t))?.type===K.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(e.map((t=>t.id)))}const w=[...B,...g.map((t=>new TA(t.id))),new UA(this.constructSerializableWorkflow())];w.length>0&&this.commandContext.apply(new JA(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],A=wa(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const e of A)if(!this.stepInitialised[e.stepName])switch(this.stepInitialised[e.stepName]=!0,e.type){case K.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case K.DigitalContent:t.push(Ia.init(e,this,this.reloadedState));break;case K.Frame:case K.Photo:{const A=new Qa(e.data.forceImageCover);A.connectWorkflowManager(this,e.stepName),this.stepSpecificServices[e.stepName]={frameService:A},t.push(Ma.init(e,this,this.reloadedState))}break;case K.Illustration:t.push(xa.init(e,this,this.reloadedState));break;case K.Material:t.push(Fa.init(e,this,this.reloadedState));break;case K.Model:t.push(Ya.init(e,this,this.reloadedState));break;case K.Module:this.stepSpecificServices[e.stepName]={module:await Ni(e.data.module)},t.push(va.init(e,this,this.reloadedState));break;case K.Picture:t.push(Sa.init(e,this,this.reloadedState));break;case K.Question:t.push(Na.init(e,this,this.reloadedState));break;case K.Shape:t.push(Ra.init(e,this,this.reloadedState));break;case K.Text:t.push(ka.init(e,this,this.reloadedState))}const e=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=e.filter((t=>!!t&&!!t.command)).map((t=>t.command)),i=e.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new JA(n),!0);for(const t of i)await t();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const A of this.selectionCallbacks)A({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((A=>A(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)}))}traversableScenes(){return ha(this.allScenes,this.stepSelections)}}function ja(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class Ka{constructor(t,A){ja(this,"manager",void 0),ja(this,"step",void 0),this.manager=t,this.step=A}setUpdateState(t){Ka.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Ka.updateState.get(this.step.stepName)}async getCurrentVariant(){return(await this.manager.getWorkflowSelections())[this.step.stepName]?.selections[0]}async getAvailableVariants(){return this.step.option?.variants||[]}getName(){return this.step.stepTitle}getId(){return this.step.stepName}getType(){return this.step.type}getHelpText(){return this.step.helpText}}function Va(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}ja(Ka,"updateState",new Map);const Wa=t.gql`
|
|
378
378
|
mutation UpdateTransactionBulkEmailAddress($id: String!, $bulkEmailAddress: String!) {
|
|
379
379
|
transactionUpdate(id: $id, bulkEmailAddress: $bulkEmailAddress) {
|
|
380
380
|
id
|
|
@@ -437,7 +437,7 @@ var t=require("@apollo/client"),A=require("lodash.clonedeep"),e=require("react/j
|
|
|
437
437
|
}
|
|
438
438
|
}
|
|
439
439
|
}
|
|
440
|
-
`,ro=(t,A,e)=>{const n={};return A.steps.forEach((A=>{Object.assign(n,(A=>{const n={};if("Frame"===A.type){const i=t[A.stepName],a=A.data;if(!i||a.hideImageInCart&&e)return n;n[`${A.stepTitle} image`]=i.image}if("Illustration"===A.type){const i=t[A.stepName],a=A.data;if(!i||a.hideColorsInCart&&e||!i.colors)return n;if(i.colors.length>0){const t=i.colors.join(", ").toUpperCase();n[`${A.stepTitle} colors`]=t}}if("Module"===A.type){const i=t[A.stepName],a=A.data;if(!i||a.hideTextInCart&&e)return n;n[`${A.stepTitle} text`]=i.text}if("Text"===A.type){const i=t[A.stepName];if(!i)return n;const a=A.data;a.hideTextInCart&&e||(n[`${A.stepTitle} text`]=i.text),!i.color||a.hideColorInCart&&e||(n[`${A.stepTitle} color`]=i.color)}return n})(A))})),n},so=(t,A,e,n,i,a,o,r,s)=>{const c={event:"onComplete",lineItemImageUrl:o||"",transactionId:t.id,designProductVariantId:t.externalDesignProductVariantId,designProductId:t.externalDesignProductId,baseCost:e,weight:A.weight,optionsCost:n,exportedData:a,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return i&&(c.metadata=i),r&&(c.selectedVariants=r),s&&(c.sku=s),c},co=async(t,A,e,n,i,a,o)=>{const r=(t.product?.basePrice||0)*(t.variationsCount||0),s=t.priceModifierTotal||0,c=((t,A,e,n)=>{const i={};let a;if(e){a=ro(e,A,!1);for(const t of Object.keys(a))i[t]={value:a[t],priceModifier:0}}else if(n){a=n;for(const t of Object.keys(a))i[t]={value:a[t],priceModifier:0}}for(const e of Object.keys(t)){const n=t[e],a=A.steps.find((t=>t.stepTitle===e));if(1===n.length)i[`${a?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)i[`${a?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return i})(n,e,void 0,a);return so(t,A,r,s,a,c,o,n,i)},go=async(t,A,e,n,i,a,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=An.getShadowGraphqlClient();await w.resetStore();const h=await w.query({query:ra,variables:{id:a.id},errorPolicy:"all"}),d=h.data?.transactions[0].workflowState;!h.errors&&d||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),h.errors&&h.errors.forEach((t=>{h.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),u=A?.finalizeStepConfig?.lookAtAnimation,Q=E&&100===E.getSceneInitializationProgress()&&A.showModelOnFinishStep&&!!u,C=B&&ro(B,A,!0),m=B&&ro(B,A,!1),p=async t=>{const e={};let n=0;if(Object.keys(o).length>0)for(const i of Object.keys(o)){const a=o[i],r=A.steps.find((t=>t.stepName===i));for(let A=0;A<a.selections.length;++A){const i=a.selections[A];if(r&&(!t||r.option&&r.option.variants.length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;e[t]?e[t].push({id:i.id||"",name:i.name,priceModifier:i.priceModifier}):e[t]=[{id:i.id||"",name:i.name,priceModifier:i.priceModifier}]}n+=i.priceModifier}}return[e,n]},[D]=await p(!0),f=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[I]=await p(!1),y=Object.fromEntries(Object.keys(I).map((t=>[t,I[t].map((t=>t.id))]))),M=await l(Q);s("workflow.steps.finish.finalize.creatingDesign"),a.bulk&&await c(g);const x=await(async t=>(await An.getShadowGraphqlClient().mutate({mutation:oo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:e.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:A.id,transactionId:a.id,useThreeDimPreview:Q,previewImage:M};if(m){const A=[];for(const[t,e]of Object.entries(m))A.push({key:t,value:e});t.metadata=A}if(f){const A=[];for(const[t,e]of Object.entries(y))A.push({key:t,ids:e});t.selectedVariants=A}return t})()),F=x?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const Y=(await An.getShadowGraphqlClient().query({query:oa,variables:{id:a.id}})).data.transactions[0];return a.bulk?((t,A,e)=>{const n=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,a={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return so(t,A,n,i,void 0,a,e)})(Y,i,F):await co(Y,i,A,D,x?.sku,C,F)};let lo;var Bo;(Bo=lo||(lo={})).Local="Local",Bo.Remote="Remote";const wo=new class{constructor(){ao(this,"localPersistenceKey","designTransactions"),ao(this,"storageMethod",lo.Local),ao(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((A=>A!==t))}async getSavedDesigns(){return await this.getDesigns()}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((A=>A.transactionId===t))}async addDesign(t){const A=(await this.getSavedDesigns()).filter((A=>A.transactionId!==t.transactionId));A.unshift(t),await this.setDesigns(A),this.notifyDesignSaved(t)}async removeDesign(t){const A=await this.getSavedDesigns();await this.setDesigns(A.filter((A=>A.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==lo.Local)throw new ze("Unexpected storage method requested");Xe.set(this.localPersistenceKey,JSON.stringify(t))}async getDesigns(){if(this.storageMethod===lo.Local){const t=Xe.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new ze("Unexpected storage method requested")}notifyDesignSaved(t){this.designSavedListeners.forEach((A=>A(t)))}};function ho(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class Eo{constructor(t,A){if(ho(this,"client",void 0),ho(this,"commandContext",void 0),ho(this,"workflowManager",void 0),ho(this,"isReadOnly",void 0),ho(this,"renderableScenes",[]),ho(this,"renderableSceneCallbacks",[]),ho(this,"debouncedSavedDesignUpdate",I(p)((async()=>{await wo.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),!A.workflow)throw new Error("No Workflow ID provided.");this.client=t;const e=A.layouts;this.commandContext=new MA,this.commandContext.initialize(e,A.reloadedState),this.isReadOnly=!!A.transaction.lineItem?.id||!Xe.getMap("transactionOwnerIds")?.get(A.transaction.id)||!!A.readOnly,this.workflowManager=new Ta(A.workflow,A.product.profanities?.map((t=>t.word))||[],e,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly),this.workflowManager.addSelectionCallback((t=>{const A=t.traversableScenes.map((t=>{const A=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:A}}));this.renderableScenes=A,this.renderableSceneCallbacks.forEach((t=>t(A)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await An.getShadowGraphqlClient().mutate({mutation:aa,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,A){const e=this.workflowManager.getWorkflow()?.finalizeStepConfig?.lookAtAnimation;if(t){if(!e)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,e))||""}const n=document.createElement("canvas");let i=2048;A&&A<=2048&&(i=A),n.width=i,n.height=i;const a=this.commandContext.getAllLayouts()[this.workflowManager.getWorkflow().defaultPreviewPanelIndex||0],o=a.layoutState.layout.previewRegion?{x:a.layoutState.layout.previewRegion.left,y:a.layoutState.layout.previewRegion.top,width:a.layoutState.layout.previewRegion.width,height:a.layoutState.layout.previewRegion.height}:{x:0,y:0,width:a.layoutState.layout.width,height:a.layoutState.layout.height},r=this.commandContext.getLayoutById(a.layoutState.layout.id),s=n.getContext("2d");if(!s)throw new je("Failed to obtain 2D context for preview image creation");const c=FA(r.layoutState.layout,r.layoutState.elements,{renderingConfiguration:{purpose:H.Print,region:{left:o.x,top:o.y,width:o.width,height:o.height}}}),g=I(Q).renderToStaticMarkup(c),l=await B.Canvg.from(s,g,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await l.render();const w=await(async t=>new Promise(((A,e)=>{try{t.toBlob((t=>{if(t){const e=URL.createObjectURL(t);A(e)}}))}catch(t){e(t)}})))(n);return n.toDataURL(w)}getStepById(t){const A=this.getWorkflowManager().getWorkflow().steps.find((A=>A.stepName===t));if(A&&this.stepHasHandle(A))return io.get(this.getWorkflowManager(),A)}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t={type:K.Bulk,stepName:"Bulk",stepTitle:"workflow.steps.bulk.title",helpText:"Add any variations of your base design here.",data:{aspects:sa(this.getWorkflowManager().getWorkflow())},conditions:[]};return io.get(this.getWorkflowManager(),t)}}getStepByName(t){const A=this.getWorkflowManager().getWorkflow().steps.find((A=>A.stepTitle===t));if(A&&this.stepHasHandle(A))return io.get(this.getWorkflowManager(),A)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((A=>A.type===t)).map((t=>io.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((A=>A.name===t.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepNames.map((t=>this.getWorkflowManager().getWorkflow().steps.find((A=>A.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>io.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){await An.getShadowGraphqlClient().mutate({mutation:Wa,variables:{id:this.getWorkflowManager().getTransaction().id,bulkEmailAddress:t.email}}),this.getWorkflowManager().setTransactionCustomerDetails(t)}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((A=>A!==t))}async save(t){if(!this.getCommandContext().getState())throw new ze("State undefined!");const A={title:await(async()=>{if(t)return t;const A=this.getWorkflowManager().getTransaction().id,e=(await wo.getSavedDesigns()).find((t=>t.transactionId===A))?.title;return e||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await wo.addDesign(A),A}async copy(){const t=I(A)(this.getCommandContext().getState());if(!t)throw new ze("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),n=this.getWorkflowManager().getWorkflow(),i=new fo({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new ze("Integration product id is undefined!");await i.initFromIntegrationProduct(a);return await i.getWorkflowExperience(n.id,e,void 0)}async onDesignFinished(t,A,e,n){return go(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),t,this.workflowManager.getTransaction(),e,this.workflowManager.getWorkflow().name,A,(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),n)}stepHasHandle(t){return t.type!==K.SilentIllustration&&t.type!==K.ProductOverlay}}function uo(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Qo=t.gql`
|
|
440
|
+
`,ro=(t,A,e)=>{const n={};return A.steps.forEach((A=>{Object.assign(n,(A=>{const n={};if("Frame"===A.type){const i=t[A.stepName],a=A.data;if(!i||a.hideImageInCart&&e)return n;n[`${A.stepTitle} image`]=i.image}if("Illustration"===A.type){const i=t[A.stepName],a=A.data;if(!i||a.hideColorsInCart&&e||!i.colors)return n;if(i.colors.length>0){const t=i.colors.join(", ").toUpperCase();n[`${A.stepTitle} colors`]=t}}if("Module"===A.type){const i=t[A.stepName],a=A.data;if(!i||a.hideTextInCart&&e)return n;n[`${A.stepTitle} text`]=i.text}if("Text"===A.type){const i=t[A.stepName];if(!i)return n;const a=A.data;a.hideTextInCart&&e||(n[`${A.stepTitle} text`]=i.text),!i.color||a.hideColorInCart&&e||(n[`${A.stepTitle} color`]=i.color)}return n})(A))})),n},so=(t,A,e,n,i,a,o,r,s)=>{const c={event:"onComplete",lineItemImageUrl:o||"",transactionId:t.id,designProductVariantId:t.externalDesignProductVariantId,designProductId:t.externalDesignProductId,baseCost:e,weight:A.weight,optionsCost:n,exportedData:a,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return i&&(c.metadata=i),r&&(c.selectedVariants=r),s&&(c.sku=s),c},co=async(t,A,e,n,i,a,o)=>{const r=(t.product?.basePrice||0)*(t.variationsCount||0),s=t.priceModifierTotal||0,c=((t,A,e,n)=>{const i={};let a;if(e){a=ro(e,A,!1);for(const t of Object.keys(a))i[t]={value:a[t],priceModifier:0}}else if(n){a=n;for(const t of Object.keys(a))i[t]={value:a[t],priceModifier:0}}for(const e of Object.keys(t)){const n=t[e],a=A.steps.find((t=>t.stepTitle===e));if(1===n.length)i[`${a?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)i[`${a?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return i})(n,e,void 0,a);return so(t,A,r,s,a,c,o,n,i)},go=async(t,A,e,n,i,a,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=An.getShadowGraphqlClient();await w.resetStore();const h=await w.query({query:ra,variables:{id:a.id},errorPolicy:"all"}),d=h.data?.transactions[0].workflowState;!h.errors&&d||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),h.errors&&h.errors.forEach((t=>{h.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),u=A?.finalizeStepConfig?.lookAtAnimation,Q=E&&100===E.getSceneInitializationProgress()&&A.showModelOnFinishStep&&!!u,C=B&&ro(B,A,!0),m=B&&ro(B,A,!1),p=async t=>{const e={};let n=0;if(Object.keys(o).length>0)for(const i of Object.keys(o)){const a=o[i],r=A.steps.find((t=>t.stepName===i));for(let A=0;A<a.selections.length;++A){const i=a.selections[A];if(r&&(!t||r.option&&r.option.variants.length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;e[t]?e[t].push({id:i.id||"",name:i.name,priceModifier:i.priceModifier}):e[t]=[{id:i.id||"",name:i.name,priceModifier:i.priceModifier}]}n+=i.priceModifier}}return[e,n]},[D]=await p(!0),f=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[I]=await p(!1),y=Object.fromEntries(Object.keys(I).map((t=>[t,I[t].map((t=>t.id))]))),M=await l(Q);s("workflow.steps.finish.finalize.creatingDesign"),a.bulk&&await c(g);const x=await(async t=>(await An.getShadowGraphqlClient().mutate({mutation:oo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:e.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:A.id,transactionId:a.id,useThreeDimPreview:Q,previewImage:M};if(m){const A=[];for(const[t,e]of Object.entries(m))A.push({key:t,value:e});t.metadata=A}if(f){const A=[];for(const[t,e]of Object.entries(y))A.push({key:t,ids:e});t.selectedVariants=A}return t})()),F=x?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const Y=(await An.getShadowGraphqlClient().query({query:oa,variables:{id:a.id}})).data.transactions[0];return a.bulk?((t,A,e)=>{const n=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,a={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return so(t,A,n,i,void 0,a,e)})(Y,i,F):await co(Y,i,A,D,x?.sku,C,F)};let lo;var Bo;(Bo=lo||(lo={})).Local="Local",Bo.Remote="Remote";const wo=new class{constructor(){ao(this,"localPersistenceKey","designTransactions"),ao(this,"storageMethod",lo.Local),ao(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((A=>A!==t))}async getSavedDesigns(){return await this.getDesigns()}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((A=>A.transactionId===t))}async addDesign(t){const A=(await this.getSavedDesigns()).filter((A=>A.transactionId!==t.transactionId));A.unshift(t),await this.setDesigns(A),this.notifyDesignSaved(t)}async removeDesign(t){const A=await this.getSavedDesigns();await this.setDesigns(A.filter((A=>A.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==lo.Local)throw new ze("Unexpected storage method requested");Xe.set(this.localPersistenceKey,JSON.stringify(t))}async getDesigns(){if(this.storageMethod===lo.Local){const t=Xe.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new ze("Unexpected storage method requested")}notifyDesignSaved(t){this.designSavedListeners.forEach((A=>A(t)))}};function ho(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class Eo{constructor(t,A){if(ho(this,"client",void 0),ho(this,"commandContext",void 0),ho(this,"workflowManager",void 0),ho(this,"isReadOnly",void 0),ho(this,"renderableScenes",[]),ho(this,"renderableSceneCallbacks",[]),ho(this,"debouncedSavedDesignUpdate",I(p)((async()=>{await wo.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),!A.workflow)throw new Error("No Workflow ID provided.");this.client=t;const e=A.layouts;this.commandContext=new MA,this.commandContext.initialize(e,A.reloadedState),this.isReadOnly=!!A.transaction.lineItem?.id||!Xe.getMap("transactionOwnerIds")?.get(A.transaction.id)||!!A.readOnly,this.workflowManager=new Ta(A.workflow,A.product.profanities?.map((t=>t.word))||[],e,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly),this.workflowManager.addSelectionCallback((t=>{const A=t.traversableScenes.map((t=>{const A=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:A}}));this.renderableScenes=A,this.renderableSceneCallbacks.forEach((t=>t(A)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await An.getShadowGraphqlClient().mutate({mutation:aa,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,A){const e=this.workflowManager.getWorkflow()?.finalizeStepConfig?.lookAtAnimation;if(t){if(!e)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,e))||""}const n=document.createElement("canvas");let i=2048;A&&A<=2048&&(i=A),n.width=i,n.height=i;const a=this.commandContext.getAllLayouts()[this.workflowManager.getWorkflow().defaultPreviewPanelIndex||0],o=a.layoutState.layout.previewRegion?{x:a.layoutState.layout.previewRegion.left,y:a.layoutState.layout.previewRegion.top,width:a.layoutState.layout.previewRegion.width,height:a.layoutState.layout.previewRegion.height}:{x:0,y:0,width:a.layoutState.layout.width,height:a.layoutState.layout.height},r=this.commandContext.getLayoutById(a.layoutState.layout.id),s=n.getContext("2d");if(!s)throw new je("Failed to obtain 2D context for preview image creation");const c=FA(r.layoutState.layout,r.layoutState.elements,{renderingConfiguration:{purpose:H.Print,region:{left:o.x,top:o.y,width:o.width,height:o.height}}}),g=I(Q).renderToStaticMarkup(c),l=await B.Canvg.from(s,g,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await l.render();const w=await(async t=>new Promise(((A,e)=>{try{t.toBlob((t=>{if(t){const e=URL.createObjectURL(t);A(e)}}))}catch(t){e(t)}})))(n);return n.toDataURL(w)}getStepById(t){const A=this.getWorkflowManager().getWorkflow().steps.find((A=>A.stepName===t));if(A&&this.stepHasHandle(A))return io.get(this.getWorkflowManager(),A)}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,A={type:K.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:sa(this.getWorkflowManager().getWorkflow())},conditions:[]};return io.get(this.getWorkflowManager(),A)}}getStepByName(t){const A=this.getWorkflowManager().getWorkflow().steps.find((A=>A.stepTitle===t));if(A&&this.stepHasHandle(A))return io.get(this.getWorkflowManager(),A)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((A=>A.type===t)).map((t=>io.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((A=>A.name===t.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepNames.map((t=>this.getWorkflowManager().getWorkflow().steps.find((A=>A.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>io.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){await An.getShadowGraphqlClient().mutate({mutation:Wa,variables:{id:this.getWorkflowManager().getTransaction().id,bulkEmailAddress:t.email}}),this.getWorkflowManager().setTransactionCustomerDetails(t)}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((A=>A!==t))}async save(t){if(!this.getCommandContext().getState())throw new ze("State undefined!");const A={title:await(async()=>{if(t)return t;const A=this.getWorkflowManager().getTransaction().id,e=(await wo.getSavedDesigns()).find((t=>t.transactionId===A))?.title;return e||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await wo.addDesign(A),A}async copy(){const t=I(A)(this.getCommandContext().getState());if(!t)throw new ze("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),n=this.getWorkflowManager().getWorkflow(),i=new fo({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new ze("Integration product id is undefined!");await i.initFromIntegrationProduct(a);return await i.getWorkflowExperience(n.id,e,void 0)}async onDesignFinished(t,A,e,n){return go(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),t,this.workflowManager.getTransaction(),e,this.workflowManager.getWorkflow().name,A,(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),n)}stepHasHandle(t){return t.type!==K.SilentIllustration&&t.type!==K.ProductOverlay}}function uo(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Qo=t.gql`
|
|
441
441
|
fragment RegionFields on Region {
|
|
442
442
|
width
|
|
443
443
|
top
|
package/dist/module.js
CHANGED
|
@@ -374,7 +374,7 @@ import{CommandContext as A,AssetType as t,BringForwardCommand as e,BringToFrontC
|
|
|
374
374
|
workflowState
|
|
375
375
|
}
|
|
376
376
|
}
|
|
377
|
-
`,pn=A=>{const t=[];for(const e of A.steps)switch(e.type){case m.DigitalContent:e.data.varyUpload&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Upload});break;case m.Frame:const A=e.data;A.varySelection&&e.option&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection}),A.varyUpload&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Upload});break;case m.Illustration:const n=e.data;n.varySelection&&e.option&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection}),n.varyColors&&n.colorPickerEnabled&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Colors});break;case m.Material:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Model:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Picture:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Question:e.data.varySelections&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selections});break;case m.Shape:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Text:const i=e.data;i.varyText&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Text}),i.varySelection&&e.option&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection}),i.varyColor&&i.colorPickerEnabled&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Color})}return t},fn=[m.SilentIllustration,m.ProductOverlay],Mn=async(A,t)=>{const e=[];A.introduction&&e.push({name:"Introduction",title:A.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:A.name,helpText:A.introduction,data:{},conditions:[]}],silentSteps:[]});for(const n of A.steps){if(t.bulkScene){let A=!1;switch(n.type){case m.DigitalContent:n.data.varyUpload&&(A=!0);break;case m.Frame:{const t=n.data;!t.varyUpload||!t.varySelection&&n.option||(A=!0)}break;case m.Illustration:{const t=n.data;!t.varySelection&&n.option&&1!==n.option.variants.length||!t.varyColors&&t.colorPickerEnabled||(A=!0)}break;case m.Material:n.data.varySelection&&(A=!0);break;case m.Model:n.data.varySelection&&(A=!0);break;case m.Picture:n.data.varySelection&&(A=!0);break;case m.Question:n.data.varySelections&&(A=!0);break;case m.Shape:n.data.varySelection&&(A=!0);break;case m.Text:{const t=n.data;!t.varySelection&&n.option&&1!==n.option.variants.length||!t.varyColor&&t.colorPickerEnabled&&t.colorOption||!t.varyText||(A=!0)}}if(A)continue}const i=yn(n.stepName,A.stepGroups);if(i){const A=e.find((A=>A.name===i.name));A?fn.includes(n.type)?A.silentSteps.push(n):A.renderableSteps.push(n):e.push({name:i.name,title:i.name,renderableSteps:fn.includes(n.type)?[]:[n],silentSteps:fn.includes(n.type)?[n]:[]})}else e.push({name:n.stepName,title:n.stepTitle,renderableSteps:fn.includes(n.type)?[]:[n],silentSteps:fn.includes(n.type)?[n]:[]})}return t.bulkScene&&e.push({name:"Bulk",title:t.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:t.bulkSceneTitle,helpText:"Add any variations of your base design here.",data:{aspects:pn(A)},conditions:[]}],silentSteps:[]}),t.finishScene&&e.push({name:"Finish",title:t.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:t.finishSceneTitle,helpText:"",data:{modelAnimation:A.finalizeStepConfig?A.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:A.finalizeStepConfig?A.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),e},yn=(A,t)=>t.find((t=>t.stepNames.includes(A))),Fn=(A,t)=>(A.conditions||[]).every((A=>{const e=t[A.targetStepName];if(e&&e.selectedVariants){const t=e.selectedVariants;return A.requiredVariantSelections.some((A=>void 0!==t.find((t=>t.id===A))))}return!1})),Yn=(A,t)=>A.map((A=>((A,t)=>{const e={name:A.name,title:A.title,renderableSteps:A.renderableSteps.filter((A=>Fn(A,t))),silentSteps:A.silentSteps.filter((A=>Fn(A,t)))};return 0===e.silentSteps.length&&0===e.renderableSteps.length?null:e})(A,t))).filter((A=>null!==A)),xn=async(A,t)=>{const e=Yn(A,t),n=[];for(const A of e)for(const t of A.renderableSteps)if(t.type===m.Model||t.type===m.Material||t.type===m.Picture||t.type===m.Shape){const A=t.option?.variants.length;A&&A>1&&n.push(t.stepName)}else n.push(t.stepName);const i=e.filter((A=>A.renderableSteps.filter((A=>n.includes(A.stepName))).length>0));for(const A of i)A.renderableSteps=A.renderableSteps.filter((A=>n.includes(A.stepName)));return i};function Sn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}function Nn(A,t,e,n){const i=e.width*A.zoom,a=e.height*A.zoom;if(n){const n=A,i=Math.max(t.width/e.width,t.height/e.height);n.zoom=Math.max(i,A.zoom);const a=e.width*n.zoom,o=e.height*n.zoom;return n.x=vn(A.x,t.width-a,0),n.y=vn(A.y,t.height-o,0),n}const o=A;return o.x=vn(o.x,-i,t.width),o.y=vn(o.y,-a,t.height),o}function vn(A,t,e){return Math.min(Math.max(A,t),e)}class Hn{constructor(A){Sn(this,"offsets",void 0),Sn(this,"forceImageCover",void 0),Sn(this,"targetElements",void 0),Sn(this,"imageData",void 0),Sn(this,"frameData",void 0),Sn(this,"_debouncedUpdateFrameOffsets",void 0),Sn(this,"minZoomScale",.03),Sn(this,"maxZoomScale",20),Sn(this,"onFrameDataChangeListeners",void 0),Sn(this,"onZoomChangeListeners",void 0),Sn(this,"workflowManager",void 0),Sn(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=VA(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=A}connectWorkflowManager(A,t){t&&A.addStepSpecificStorageCallback((async A=>{if(A){const t=A;if(t.currentFrameSource){const A=await v(t.currentFrameSource);LA(A,this.frameData)||(this.frameData=A,this.onFrameDataChangeListeners.forEach((A=>A(this.frameData))),this.frameData&&this.imageData&&(this.offsets=AA(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),t),this.workflowManager=A,this.stepName=t}setTargetElements(A){this.targetElements=A}getFrameData(){return this.frameData}async setFrameData(A){const t=y.get(A);this.frameData=t}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(A){this.offsets=A}setZoom(A,t,e,n){if(this.imageData&&this.offsets&&this.frameData){const i=(t-this.offsets.x)/this.offsets.zoom,a=(e-this.offsets.y)/this.offsets.zoom,o={x:t-i*A,y:e-a*A,zoom:this.imageData.width*A/this.imageData.width};this.updateOffsets(Nn(o,this.frameData,this.imageData,this.forceImageCover),n),this.onZoomChangeListeners.forEach((t=>t(A)))}}setPatternData(A){(A&&this.frameData||A&&this.frameData&&!this.imageData)&&(this.offsets=AA(A,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements),this.updateOffsets(Nn(this.offsets,this.frameData,A,this.forceImageCover))),this.imageData=A,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(A,t){const e=this.imageData;e&&this.frameData&&(this.offsets&&A.x===this.offsets.x&&A.y===this.offsets.y&&A.zoom===this.offsets.zoom?t&&t():(this.offsets=Nn(A,this.frameData,e,this.forceImageCover),this._debouncedUpdateFrameOffsets(A,e,this.frameData,this.targetElements,t)))}onFrameDataChanged(A){A(this.frameData),this.onFrameDataChangeListeners.push(A)}onZoom(A){this.onZoomChangeListeners.push(A)}updateFrameOffsets(A,t,e,n,i){if(!e)throw new nt("Frame data not set. This is a bug");if(!this.workflowManager)throw new nt("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach((e=>{a(new tA(e,t,A))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:A}),i&&i()}recalculateZoomLimits(A,t){const e=Math.max(t.width/A.width,t.height/A.height);this.forceImageCover?(this.minZoomScale=e,this.maxZoomScale=2.5*e):(this.minZoomScale=e/10,this.maxZoomScale=2.5*e)}}function Rn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class Un{constructor(A,t,e){Rn(this,"configuration",void 0),Rn(this,"layouts",void 0),Rn(this,"product",void 0),Rn(this,"processRegion",(async A=>{const t=this.layouts.find((t=>t.panelId===A.panelId));if(!t)throw new $A(A);let e="";if(this.configuration.type===m.ProductOverlay){let A="";if(this.product?.overlayImageUrl&&(A=this.product.overlayImageUrl),e=A,!A)throw new tt(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===d.Image){const e=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!e)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:e,type:n,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,rotation:A.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:A},command:new o(i,t)}}{const i=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:e,a=async()=>new Promise(((A,t)=>{i?nA(i).then((t=>{A(t)})).catch((A=>console.error(A))):t("Undefined vector silent step source")})),s=await x(await a()),r={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await EA(s.svg),src:i,svg:s.svg,colors:s.colors,type:n,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,immutable:A.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:r.id,region:A},command:new o(r,t)}}})),this.configuration=A,this.layouts=t,this.product=e||void 0}async trigger(){if(!this.configuration.data.regions)throw new tt(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const A=this.configuration.data.regions.map(this.processRegion);return Promise.all(A)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((A=>{if(!this.layouts.find((t=>A.panelId===t.panelId)))throw new $A(A);return this.processRegion(A)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const A=this.configuration.type===m.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return A?.startsWith("data:image/png")||A?.endsWith(".jpeg")||A?.endsWith(".jpg")||A?.endsWith(".png")?d.Image:(A?.endsWith(".svg")||A?.startsWith("image/svg+xml"),d.Illustration)}}const Pn=async A=>{const t=`${lt.getServicesApiUrl()}/shortener`;try{const e=await fetch(t,{method:"POST",body:JSON.stringify({longUrl:A}),headers:{"Content-Type":"application/json"}});return(await e.json()).shortUrl}catch(A){throw console.error(A),new ot("Failed to shorten URL, see console.")}};function Gn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class kn{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(A){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(A,t,e,n=3e3,i=10){Gn(this,"pollingId",void 0),Gn(this,"attempts",void 0),Gn(this,"interval",void 0),Gn(this,"maxAttempts",void 0),Gn(this,"predicate",void 0),Gn(this,"onSuccess",void 0),Gn(this,"onFailure",void 0),this.onSuccess=t,this.onFailure=e,this.predicate=A,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const Jn=new class{async init(A,t,e){return e&&await this.reload(A,t,e),null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)).map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[],i,(async()=>{const e=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;t.updateStorage(A.stepName,{videoShortUrl:e,videoUrl:i})}))}async regenerateQRCode(A,t,e,n,i,a,o,s,c){if(t||""===e||""!==n)c(!1);else{const t=async()=>{const A=await Mt.getLocalOrFromServer(e),t=A.versions?.find((A=>"mpeg4"===A.name))?.link;return{asset:A,link:t}},g=await new Promise(((A,e)=>{new kn((async()=>!!(await t()).link),(async()=>{const e=await t();if(!e.link||!e.link)throw new At(e.asset);A({rel:"mpeg4",href:e.link})}),(()=>{e("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));A.forEach((A=>s(new r(A.id))));const B="http"===a.data.baseUrl.slice(0,4)?"":"https://",l=new URL(B+a.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([g]))),l.pathname=l.pathname+("/"===l.pathname.slice(-1)?"":"/");const w=l.toString();if(w.length>=2e3)throw new ot("Cannot create QR code, URL too long.");const E=await Pn(w);if(o(E),!a.data||!a.data.regions)throw new tt(a,"Missing regions.");const d=await this.regionElements(a),h=await this.command(E,d,i,a.stepName);h&&(h.command&&i.getCommandDispatcher()(h.command),h.followup&&await h.followup()),await i.setSelectionsAndElements(a.stepName,[],d,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:E,videoUrl:n}),c(!1)}))}}async regionElements(A){return A.data.regions.map((A=>({id:F(),region:A})))}async command(A,t,e,n){const i=e.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await jA(A,{type:"svg"}))}`,s=t.map((A=>{const t=A.region,e=i.find((A=>A.panelId===t?.panelId));if(!e&&t)throw new $A(t);if(e&&!t)throw new Error("Region not found");if(!e||!t)throw new Error("Neither a region or layout found!");return new o({stepRegion:t,stepName:n,id:A.id,src:a,type:d.Image,y:t.top,x:t.left,width:t.width,height:t.height,rotation:0},e)}));return{command:new w(s),followup:async()=>{}}}};function bn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}const Ln=new class{constructor(){bn(this,"frameSourceSvg",(async(A,t)=>{if(!A)return hA(t.data.regions[0]);const e=A.asset;if(!e)throw new _A(A);const n=e.fileLink;if(n)return nA(n);throw new At(e)}))}async init(A,t,e){if(e)return await this.reload(A,t,e),null;if(t.setMandatoryFulfilled(A.stepName,!1),t.markStepsAsInitialised([A.stepName]),A.option&&A.option.variants.length>0){const e=A.option,n=xt.getDefaultVariant(e);return n?this.selectVariantCommand(A,n,[],t,void 0,A.data.placeholderImageUrl):null}return this.selectVariantCommand(A,void 0,[],t,void 0,A.data.placeholderImageUrl)}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)).map((A=>({id:A.id,region:A.stepRegion})));if(!A.option||0===A.option.variants.length){const e=hA(A.data.regions[0]);t.updateStorage(A.stepName,{currentFrameSource:e})}if(n){const e=async()=>{const e=n.storage?.framePatternSrc,i=n.storage?.frameOffsets;if(t.updateMetadata(A.stepName,{frameOffsets:i,framePatternSrc:e}),e){const n=t.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(e,n),t.updateMetadata(A.stepName,{image:e}),t.updateStorage(A.stepName,{framePatternSrc:e})}if(i?.zoom){const e=t.getStepSpecificServices(A.stepName)?.frameService;e.updateOffsets(i)}t.setMandatoryFulfilled(A.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(A.option&&a){const n=A.option.variants.find((A=>A.id===a));n&&await t.setSelectionsAndElements(A.stepName,[n],i,(async()=>{const i=await this.frameSourceSvg(n,A);t.updateStorage(A.stepName,{currentFrameSource:i}),await e()}))}}else await t.setSelectionsAndElements(A.stepName,[],i,e)}}selectImage(A,t,e){e.setEditedStatus(A.stepName,!0);(t.fileLink||"").endsWith("pdf")?e.addPoller(new kn((async()=>{const A=(await Mt.getLocalOrFromServer(t.key||"")).versions?.find((A=>"svg"===A.name));if(!A)return!1;return 200===(await fetch(A.link)).status}),(()=>{Mt.getLocalOrFromServer(t.key||"").then((t=>{this.loadPatternFromAsset(t,A,e)}))}),(()=>{throw new ot("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(t,A,e)}async selectVariant(A,t,e,n,i){const a=await this.selectVariantCommand(A,t,e,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(A,t,e,n){return new o({id:A,type:d.Frame,x:t.left,y:t.top,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,scaleX:t.width/n.frameData.width,scaleY:t.height/n.frameData.height,path:n.frameData.path,stepRegion:t,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:t.immutable},e)}async loadPatternFromString(A,t){if(A.endsWith("svg")){const e=await QA(A),n=e.width,i=e.height,a={src:A,width:n,height:i,aspect:n/i};G.set(A,a),t.setPatternData(a)}else{const e=await rA(A),n=await S(e),i={src:A,width:n.width,height:n.height,aspect:n.width/n.height};G.set(A,i),t.setPatternData(i)}}async selectVariantCommand(A,t,e,n,i,a){const o=n.getStepSpecificServices(A.stepName)?.frameService,s=await this.frameSourceSvg(t,A),c=await v(s),g=o.getImageData(),B=e.map((A=>new r(A.id))),l=g?AA(g,c):void 0,E=g?{id:F(),src:g.src,x:l?.x||0,y:l?.y||0,width:g.width,height:g.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0;i&&i(!0);const d=A.data.regions.map((t=>{const e=F(),i=n.getLayouts().find((A=>A.panelId===t.panelId));if(!i)throw new $A(t);return{command:this.getCreateElementCommand(e,t,i,{frameData:c,pattern:E,disablePlaceholder:A.data.disablePlaceholder,focalBlur:A.data.focalBlur,focalBlurStrength:A.data.focalBlurStrength,focalBlurRadius:A.data.focalBlurRadius,stepName:A.stepName}),regionEl:{id:e,region:t}}})),h=d.map((A=>A.command));return{command:new w([...h,...B]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(A.stepName,t?[t]:[],[...d.map((A=>A.regionEl))],(async()=>{if(n.updateStorage(A.stepName,{currentFrameSource:s}),a){const t=n.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(a,t)}}))}}}patternSource(A){const t=A.versions?.find((A=>"svg"===A.name));if(t)return t.link;const e=A.fileLink;if(e)return e;throw new At(A)}async loadPatternFromAsset(A,t,e){const n=this.patternSource(A),i=e.markUpdatePending(),a=e.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(n,a),e.updateMetadata(t.stepName,{image:n}),e.updateStorage(t.stepName,{framePatternSrc:n}),e.markUpdateCompleted(i)}};const Tn=new class{async getIllustrationBody(A){return new Promise((t=>{nA(A).then((A=>{t(A)})).catch((A=>console.error(A)))}))}getCreateElementCommand(A,t,e,n){return new o({stepRegion:t,stepName:n.stepName,colors:n.svg.colors,id:A,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:d.Illustration,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable},e)}getColors(A,t){const e=t.getRegionElements(A.stepName)||[];if(0===e.length)return[];try{return M(e[0].id,t.getAllLayoutData()).colors}catch(A){return[]}}async init(A,t,e){const n=A.option;if(!n)return null;if(e)return this.reload(A,t,e);{const e=xt.getDefaultVariant(n);if(e)return await this.selectVariantCommand(A,e,[],(()=>{}),t)}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(!a||!e)throw new Error("Required illustration variant no longer available");{const o=a.variants.find((A=>A.id===e));if(o){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[o],e,(async()=>{t.updateMetadata(A.stepName,{colors:n.storage?.colors}),t.setMandatoryFulfilled(A.stepName,!0)}))}}}return null}async availableColors(A,t){const e=A.data.colorOption;return e&&e?e.variants.map((A=>({fill:A.color,stroke:A.color,variant:A}))):[]}async changeColorsCommand(A,t,e,n,i){const a={};for(const[A,t]of i.entries())a[A]={browserValue:t,spotColor:a[A]?.spotColor};const o=CA(A,t,e,a),s=await EA(o),r=[];for(const A of n){for(const[t,e]of i.entries())r.push(new uA(A,t,e));r.push(new DA(A,o,s))}return new w(r)}async changeColors(A,t,e,n,i){if(0===t.length)return;const a=M(t[0].id,n().map((A=>A.layoutState))),o={...a.colors},s={};Object.entries(o).forEach((([A,t])=>{const e={browserValue:t.browserValue},n=t.spotColor;n&&(e.spotColor={profileName:n.profileName,namedColor:n.namedColor}),s[A]=e}));for(const[A,t]of i.entries())o[A]={browserValue:t,spotColor:o[A]?.spotColor},s[A]={browserValue:t};let r=Array.from(Object.values(o)).map((A=>A.browserValue));const c=A.data.colorOption;c&&c.variants.forEach((A=>{r=r.map((t=>t.toLowerCase()===A.color?.toLowerCase()?A.name:t))})),e.updateMetadata(A.stepName,{colors:r});const g=new Map;if(Object.entries(o).forEach((([A,t])=>{g.set(A,t.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const B=await this.changeColorsCommand(a.svg,a.width,a.height,t.map((A=>A.id)),g);e.updateStorage(A.stepName,{colors:s}),e.getCommandDispatcher()(B)}async selectVariant(A,t,e,n,i){const a=await this.selectVariantCommand(A,t,e,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(A,t,e,n,i){if(!A.data||!A.data.regions)throw new tt(A,"Missing regions.");n(!0);const a=e.map((A=>new r(A.id)));i.setMandatoryFulfilled(A.stepName,!1);const o=t.asset;if(!o)throw new _A(t);const s=o.fileLink;if(!s)throw new At(o);const c=await x(await this.getIllustrationBody(s)),g=await EA(c.svg),B=A.data.regions.map((t=>{const e=i.getLayouts().find((A=>A.panelId===t.panelId));if(!e)throw new $A(t);const n=F();return{regionElement:{id:n,region:t},command:this.getCreateElementCommand(n,t,e,{stepName:A.stepName,src:s,objectURL:g,svg:c})}})),l=[...B.map((A=>A.command)),...a];let E=Array.from(Object.values(c.colors)).map((A=>A.browserValue));const d=A.data.colorOption;return d&&d.variants.forEach((A=>{E=E.map((t=>t.toLowerCase()===A.color?.toLowerCase()?A.name:t))})),i.updateMetadata(A.stepName,{colors:E}),{command:new w(l),followup:async()=>{await i.setSelectionsAndElements(A.stepName,[t],B.map((A=>A.regionElement)),(async()=>{i.setMandatoryFulfilled(A.stepName,!0),n(!1)}))}}}};const On=new class{async init(A,t,e){const n=A.option;if(!n)throw new ZA(A);if(e)await this.reload(A,t,e);else{const e=xt.getDefaultVariant(n);if(e)return await this.selectVariantLambda(A,e,t,(()=>{}))}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(!a)throw new ZA(A);if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(e){const n=a.variants.find((A=>A.id===e));if(n){const e=n.material,o=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],o,(async()=>{const n=t.getPreviewService();if(n){const i=A.data.targetMaterials.map((A=>n.applyMaterialVariant(A,a.id,e)));Promise.all(i).then((()=>t.setMandatoryFulfilled(A.stepName,!0)))}}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantLambda(A,t,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(A,t,e,n){const i=e.getPreviewService();n(!0);const a=t.material;if(!a)throw n(!1),new _A(t);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(A.stepName,[t],[],(async()=>{try{i&&A.data.targetMaterials.forEach((t=>{A.option&&i.applyMaterialVariant(t,A.option.id,a)})),e.setMandatoryFulfilled(A.stepName,!0)}finally{n(!1)}}))}}}};const zn=new class{async init(A,t,e){const n=A.option;if(!n)throw new ZA(A);if(e)await this.reload(A,t,e);else{const e=xt.getDefaultVariant(n);if(e)return await this.selectVariantLambda(A,e,t,(()=>{}))}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((A=>A.id===e));if(n){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],e,(async()=>{const e=t.getPreviewService();if(e&&A.option){const i=n.asset?.fileLink;if(!i)throw new _A(n);await e.applyModelVariant(A.option.id,{model:i,contextService:t.getLayoutPreviewService()},A.data.replaceProductModel||!1),t.setMandatoryFulfilled(A.stepName,!0)}}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantLambda(A,t,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(A,t,e,n){n(!0);const i=t.asset?.fileLink;if(!i)throw new _A(t);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(A.stepName,[t],[],(async()=>{try{const t=e.getPreviewService();t&&A.option&&t.applyModelVariant(A.option.id,{model:i,contextService:e.getLayoutPreviewService()},A.data.replaceProductModel||!1),e.setMandatoryFulfilled(A.stepName,!0)}finally{n(!1)}}))}}}};const jn=new class{async init(A,t,e){return e?(await this.reload(A,t,e),null):(t.updateMetadata(A.stepName,{text:""}),this.changeTextCommand(A,"",t,"",(()=>{})))}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)).map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[],i,(async()=>{t.updateStorage(A.stepName,{text:n?.storage?.text}),t.setMandatoryFulfilled(A.stepName,""!==n?.storage?.text)}))}async changeText(A,t,e,n,i){const a=await this.changeTextCommand(A,t,e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(A,t,e,n,i){const a=e.getRegionElements(A.stepName),s=e.getStepSpecificServices(A.stepName)?.module;if(!s)return console.error("Missing module."),null;const c=e.getProfanities();if(!this.validateInput(A,t,c,i))return e.setMandatoryFulfilled(A.stepName,!1),console.error(n),null;if(e.setMandatoryFulfilled(A.stepName,""!==t),!A.data||!A.data.regions||A.data.regions.length<=0)return console.error("Missing configuration."),null;e.updateStorage(A.stepName,{text:t});const g=(t,n,i)=>{const a=i||F(),s=e.getLayouts().find((A=>A.panelId===n.panelId));if(!s)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return i&&c.push(new r(a)),c.push(new o({stepRegion:n,stepName:A.stepName,colors:{},id:a,svg:t,type:d.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},s)),{id:a,region:n,command:new w(c)}};if(a.length>0){const A=a.map((A=>{if(!A.region)return null;const e=s.svgPrint(t,A.region);return g(e,A.region,A.id)})).filter((A=>!!A)).filter((A=>!!A)).map((A=>A&&A.command));return{command:new w(A),followup:async()=>{}}}{const n=A.data.regions.map((A=>g(s.svgPrint(t,A),A))),i=n.filter((A=>!!A)).map((A=>A&&A.command));return{command:new w(i),followup:async()=>{const t=n.filter((A=>A)).map((A=>A&&{id:A.id,region:A.region}));await e.setSelectionsAndElements(A.stepName,[],t)}}}}validateInput(A,t,e,n){if(A.data&&A.data.maxLength){const e=A.data.maxLength;if(t.length>e)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(t))return n("Unsupported characters."),!1;const i=t.toLowerCase();for(const A in e)if(i===e[A].toLowerCase().trim()&&""!==i)return n("Blocked profanity."),!1;return n(""),!0}};const Kn=new class{async init(A,t,e){const n=A.option;if(!n)return null;if(e)await this.reload(A,t,e);else if(n.defaultVariant)return t.markStepsAsInitialised([A.stepName]),this.selectVariantCommand(A,n.defaultVariant,t,(()=>{}));return t.markStepsAsInitialised([A.stepName]),null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((A=>A.id===e));if(n){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],e,(async()=>{t.setMandatoryFulfilled(A.stepName,!0)}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantCommand(A,t,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(A,t,e,n){const i=t.asset;if(!i)throw new _A(t);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),e.setMandatoryFulfilled(A.stepName,!1);const s=e.getRegionElements(A.stepName).map((A=>new r(A.id))),c=A.data.regions.map((t=>{const n=e.getLayouts().find((A=>A.panelId===t.panelId));if(!n)throw new $A(t);const i=F();return{regionElement:{id:i,region:t},command:new o({stepName:A.stepName,stepRegion:t,id:i,src:a,type:d.Image,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...s,...c.map((A=>A.command))]),followup:async()=>{await e.setSelectionsAndElements(A.stepName,[t],c.map((A=>A.regionElement)),(async()=>{e.setMandatoryFulfilled(A.stepName,!0),n(!1)}))}}}};const Vn=new class{async init(A,t,e){const n=A.option;if(!n)return null;if(e)await this.reload(A,t,e);else{const e=n.variants;if(xt.getDefaultVariant(n)){const i=e.find((A=>A.id===n.defaultVariant?.id));return this.selectVariantLambda(A,i?.id||"",t)}}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(i&&e){const n=i.variants.find((A=>A.id===e));n&&await t.setSelectionsAndElements(A.stepName,[n],[])}}}async selectVariant(A,t,e){const n=await this.selectVariantLambda(A,t,e);n&&(n.command&&e.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(A,t,e){const n=A.option;if(!n)return null;const i=n.variants,a=i.length>1?i.find((A=>A.id===t)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(A.stepName,[a],[],(async()=>{e.setMandatoryFulfilled(A.stepName,!0)}))}}}};const Wn=new class{async availableColours(A){const t=A.option;return t?t.variants.map((A=>({fill:A.color,stroke:A.color,variant:A}))):[]}async init(A,t,e){const n=A.option;if(!n)throw new ZA(A);if(!e){const e=xt.getDefaultVariant(n);if(!e)return null;const i={fill:e.color,stroke:e.color,variant:e};return this.selectVariantCommand(A,i,[],t)}return await this.reload(A,t,e),null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((A=>A.id===e));if(n){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],e,(async()=>{t.updateStorage(A.stepName,{colour:n.color||""}),t.setMandatoryFulfilled(A.stepName,!0)}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantCommand(A,t,e,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(A,t,e,n){const i=n.getLayouts();if(e.length>0){const a=A=>{const e=A.region;if(!i.find((A=>A.panelId===e?.panelId)))throw new $A(e);const n=t.variant?.color;return n?new uA(A.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=e.map(a).filter((A=>!!A));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(A.stepName,t.variant?[t.variant]:[],e),n.updateStorage(A.stepName,{colour:t.fill||""})}}}{const e=e=>{const n=i.find((A=>A.panelId===e.panelId));if(!n)throw new $A(e);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${t.variant?.color}"\n />\n </svg>\n `,s={};s["spiff-fill-shape"]={browserValue:t.variant.color};const r=F();return{id:r,region:e,command:new o({stepRegion:e,stepName:A.stepName,colors:s,id:r,svg:a,type:d.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:A.data.excludeFromPrint},n)}},a=A.data.regions.map(e),s=a.filter((A=>!!A)).map((A=>A?.command)),r=a.filter((A=>!!A)).map((A=>({id:A.id,region:A.region})));return{command:new w(s),followup:async()=>{await n.setSelectionsAndElements(A.stepName,t.variant?[t.variant]:[],r,(async()=>{n.updateStorage(A.stepName,{colour:t.fill||""})}))}}}}};function Xn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}const qn=new class{constructor(){Xn(this,"latestToast",void 0),Xn(this,"toastType",void 0),Xn(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(A){A({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(A)}setLatestToast(A,t){this.latestToast=A,this.toastType=t,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((A=>A({toastMessage:this.latestToast,toastType:this.toastType})))}};function Zn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class $n extends Error{constructor(A){super(A),Object.setPrototypeOf(this,new.target.prototype),this.name=$n.name}}class _n extends Error{constructor(A){super(A),Object.setPrototypeOf(this,new.target.prototype),this.name=_n.name}}const Ai=new class{constructor(){Zn(this,"cachedColors",new Map),Zn(this,"filterUnsupportedCharacters",((A,t)=>{let e=A.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=t?mA(t):void 0;if(i){const A=e.split("").map((A=>i.getFont().charToGlyph(A)));for(let t=0;t<A.length;t++){const i=".notdef"===A[t].name;"\n"===e.charAt(t)||i&&n.push(String.fromCharCode(e.charCodeAt(t)))}}for(let A=0;A<n.length;A++)e=e.replaceAll(n[A],"");return e})),Zn(this,"textAlign",(A=>A.vertical?"center":A.textAlign||"center")),Zn(this,"getErrorsForText",((A,t,e)=>{const n=[];t.data&&t.data.maxLength&&A.length>t.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=e.getProfanities(),a=A.toLowerCase();if(""!==a)for(const A in i){if(a===i[A].toLowerCase().trim()){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!t.data.allowNewlines&&(A.includes("\n")||A.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(A,t,e){const n=A.option;if(!n)return null;if(e)await this.reload(A,t,e);else{t.updateStorage(A.stepName,{inputText:A.data.defaultText||"",color:(await this.getDefaultColorVariant(A.data))?.color||await this.getDefaultColor(A.data)}),t.updateMetadata(A.stepName,{text:A.data.defaultText||"",color:(await this.getDefaultColorVariant(A.data))?.name||await this.getDefaultColor(A.data)});const e=xt.getDefaultVariant(n);if(e)return this.selectVariantCommand(A,e,{},[],t,(()=>{}),(()=>{}))}return null}findLayoutElements(A,t){return A.getRegionElements(t.stepName).map((t=>M(t.id,A.getAllLayoutData())))}async availableColors(A,t){const e=this.cachedColors.get(A.stepName);if(e)return e;const n=A.data.colorOption;if(n){const t=n.variants.map((A=>({fill:A.color,stroke:A.color,variant:A})));return this.cachedColors.set(A.stepName,t),t}return[]}async changeFill(A,t,e,n){if(!A.data||!A.data.regions)return;const i=n.getCommandDispatcher();t.variant?n.updateMetadata(A.stepName,{color:t.variant.name}):n.updateMetadata(A.stepName,{color:t.fill});const a=await this.getColorOption(A),o=a?this.createTextFillSpotColor(a,t.variant):void 0;a?n.updateStorage(A.stepName,{color:t.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(A.stepName,{color:t.fill});for(const A of e){if(!t.fill)throw new Error("Fill not set on new color selection!");i(new g(A.id,t.fill,o))}}getProcessedInput(A,t,e){const n=e?A:this.injectReplaceableText(A,t);return BA(n,{vertical:t.vertical,uppercase:t.uppercase})}updateInputText(A,t,e,n){const i=n.getStepStorage(e.stepName),a=this.getProcessedInput(A,e.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(A,e,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const s=(e.data.maxLength-a.length).toString();o.helperText=`${s} characters remaining`;const r=n.getTransaction().bulk&&e.data.varyText||!1,c=[],g=new Map,B=new Map;for(const A of t){if(!A.fontData)throw new nt("Failed to resolve font data for text.");const[t,n]=P(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation,panelId:""},[a],{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});g.set(A.id,t),B.set(A.id,n);const i=e.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(t,e.data,A.id,i,r))}if(!e.data.curved&&t.length>0){if(!Array.from(B.values()).every((A=>A)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(e.stepName,{text:A}),n.updateMetadata(e.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(e.stepName,!0),o.command=new w(c),o.command.varying=r,o}async selectVariant(A,t,e,n,i){const a=await this.selectVariantCommand(A,t,e.getStepStorage(A.stepName)||{},e.getRegionElements(A.stepName),e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(A,t){const e=A.colorProfile;if(e){const A=(e.name||"").replace(/\s/g,"-"),n=A.lastIndexOf("/"),i=A.slice(n+1).slice(0,-4);if(!t.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:t.namedColor}}}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const o=a.variants.find((A=>A.id===e));if(o){const e=await this.fontDataFromVariant(o),a=i.map((A=>({id:A.id,region:A.stepRegion}))),s=n.storage?.color,r=n.storage?.text;await t.setSelectionsAndElements(A.stepName,[o],a,(async()=>{t.updateMetadata(A.stepName,{color:s,text:r}),t.updateStorage(A.stepName,{text:r,inputText:r});const n=i.map((A=>new l(A.id,e))),a=new w(n);t.getCommandDispatcher()(a),t.setMandatoryFulfilled(A.stepName,!0)}));const{command:c}=Ai.updateInputText(r||"",i,A,t);c&&t.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(A){const t=A.colorOption;if(t)return xt.getDefaultVariant(t)}async getDefaultColor(A){const t=A.colorOption;if(!t)return;return xt.getDefaultVariant(t)?.color}async getColorOption(A){return A.data.colorOption}async fontDataFromVariant(A){const t=A.asset;if(!t)throw new _A(A);const e=t.fileLink;if(!e)throw new At(t);return{assetUrl:e,name:(await U(e)).names.fullName.en}}async selectVariantCommand(A,t,e,n,i,a,o){const s=i.markUpdatePending(),r=await this.fontDataFromVariant(t);if(n.length>0){const c=n.map((A=>new l(A.id,r))),g=await this.changeInputTextWithRegion(A,A.data.size||30,r,e.text||"",e,i,!!e.customiseAllText,a,o);g&&c.push(g);return{command:new w(c),followup:async()=>{i.markUpdateCompleted(s),await i.setSelectionsAndElements(A.stepName,[t],n)}}}{const n=await this.createTextboxRegions(A.stepName,t,A.data,r,e,i),c=await this.changeInputTextWithRegion(A,A.data.size||30,r,n[0]?.newElement.input||e.text||A.data.defaultText||"",e,i,!!e.customiseAllText,a,o),g=n.flatMap((A=>A.commands));c&&g.push(c);return{command:new w(g),followup:async()=>{i.markUpdateCompleted(s)}}}}injectReplaceableText(A,t){return t.replaceableText?t.replaceableText.replace("{{}}",A):A}async createTextboxRegions(A,t,e,n,i,a){if(!e||!e.regions)throw new Error("Step data not supplied");const s=a.getTransaction().bulk&&e.varyText||!1,r=s?"":i.text||e.defaultText||"",c=this.getProcessedInput(r,e,!1),g=await Promise.all(e.regions.map((async t=>{const g=a.getLayouts().find((A=>A.panelId===t.panelId)),B=F();try{if(!g)throw new _n("Failed to find layout for region: "+t.panelId);const l=e.colorOption;let w;if(l){const t=l.variants.find((A=>A.id===l.defaultVariant?.id))||l.variants[0];w=this.createTextFillSpotColor(l,t),a.updateStorage(A,{colorProfileAssetKey:l.colorProfile?.key})}const E=await this.getDefaultColor(e),h=E||"#000000",Q={stepRegion:t,stepName:A,align:this.textAlign(e),fill:i.color?i.color:h,fontSize:e.size||30,fontData:n,id:B,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,text:c,input:r,type:d.Textbox,vertical:e.vertical,x:t.left,y:t.top,height:t.height,width:t.width,immutable:t.immutable,verticalAlign:e.verticalAlign||"middle",curved:e.curved,paths:e.paths,fillSpotColorDefinition:w},C=[],u=new Map,D=new Map;if(!Q.fontData)throw new nt("Failed to resolve font data for text.");const[m,I]=P(Q.fontSize,Q.fontData,{left:Q.x,top:Q.y,width:Q.width,height:Q.height,rotation:Q.rotation,panelId:""},[c],{size:e.size,minSize:e.minSize,maxSize:e.maxSize});u.set(Q.id,m),D.set(Q.id,I);const p=e.curved||e.vertical?c:(I||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(m,e,Q.id,p,s));const f=new o(Q,g);return f.varying=s,{regionElement:{id:B,region:t},commands:[f,...C],newElement:Q,fontData:n}}catch(A){throw console.log(A),new $n("Error adding font to region")}}))).catch((A=>{throw A instanceof $n?(qn.setLatestToast("Failed to load font.",ei.Error),A):A instanceof _n?A:new Error(A)}));return await a.setSelectionsAndElements(A,[t],g.map((A=>A.regionElement)),(async()=>{a.updateMetadata(A,{text:r}),a.updateStorage(A,{text:r})})),g}generateTextChangeCommandsForRegion(A,t,e,n,i){const a=[],o=new I(e,n);if(o.varying=i,a.push(o),!t.size){const t=new B(e,A);t.varying=i,a.push(t)}const s=new w(a);return s.varying=i,s}async changeInputTextWithRegion(A,t,e,n,i,a,o,s,r,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),B=this.getProcessedInput(g,A.data,o),l=a.getRegionElements(A.stepName),E=new Map,d=new Map;for(const n of l)if(n.region){const[i,a]=P(t,e,n.region,[B],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});E.set(n.id,i),d.set(n.id,a)}const h=(()=>{if(A.data&&A.data.maxLength&&B.length>A.data.maxLength)return c&&c(!0),{info:"0"};const t=B.toLowerCase(),e=a.getProfanities();for(const A in e)if(t===e[A].toLowerCase().trim()&&""!==t)return s(!0),{error:"Blocked profanity."};if(!A.data.vertical&&!A.data.allowNewlines&&(B.includes("\n")||B.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!A.data.curved){if(!Array.from(d.values()).every((A=>A)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(A.data.maxLength-B.length).toString()}})();if(h.error)return void r(h.error);if(r(`${h.info} characters remaining`||""),c)return;a.updateStorage(A.stepName,{text:g}),a.updateMetadata(A.stepName,{text:this.injectReplaceableText(g,A.data)});const Q=a.getTransaction().bulk&&A.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(A.stepName,!0);const C=[];for(const t of l){const e=A.data.curved?B:(d.get(t.id)||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(E.get(t.id)||1,A.data,t.id,e,Q))}const u=new w(C);return u.varying=Q,u}};function ti(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}let ei;var ni;(ni=ei||(ei={})).Error="Error",ni.Warning="Warning",ni.Info="Info";class ii extends Me{constructor(A){super(),ti(this,"update",void 0),ti(this,"createdAt",new Date),this.update=A}async execute(){await this.update(),await new Promise((A=>{window.setTimeout((()=>{A()}),1e3)}))}}class ai{constructor(A,t,e,n,i,a,o,s,r,c,g=!1){ti(this,"reloadedState",void 0),ti(this,"transaction",void 0),ti(this,"updateTransaction",void 0),ti(this,"confirmedDesign",void 0),ti(this,"editedSteps",void 0),ti(this,"informationResults",void 0),ti(this,"layouts",void 0),ti(this,"mandatorySteps",void 0),ti(this,"pendingUpdates",void 0),ti(this,"selectionCost",void 0),ti(this,"workflow",void 0),ti(this,"stepSpecificServices",void 0),ti(this,"previewService",void 0),ti(this,"profanityFilter",void 0),ti(this,"pollers",void 0),ti(this,"commandContext",void 0),ti(this,"stepElements",void 0),ti(this,"stepInitialised",void 0),ti(this,"stepMetadata",void 0),ti(this,"stepSelections",void 0),ti(this,"storage",void 0),ti(this,"confirmCallbacks",void 0),ti(this,"editedCallbacks",void 0),ti(this,"elementsCallbacks",void 0),ti(this,"informationResultCallbacks",void 0),ti(this,"initCallbacks",void 0),ti(this,"makingAdjustmentsCallback",void 0),ti(this,"mandatoryCallbacks",void 0),ti(this,"metadataCallbacks",void 0),ti(this,"selectionCallbacks",void 0),ti(this,"stepSpecificStorageCallbacks",void 0),ti(this,"storageCallbacks",void 0),ti(this,"currentVariationRecordCallbacks",void 0),ti(this,"variationRecordCallbacks",void 0),ti(this,"allScenes",void 0),ti(this,"product",void 0),ti(this,"invalidModelVariants",void 0),ti(this,"currentAdjustingStepId",void 0),ti(this,"renderableContextService",void 0),ti(this,"workflowStatePromiseQueue",new ye(1)),ti(this,"variationRecords",[]),ti(this,"currentVariationRecord",void 0),ti(this,"initializationPromise",void 0),ti(this,"initialized",!1),ti(this,"readOnly",!1),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=A,this.stepSpecificServices={},this.profanityFilter=t,this.pollers=[],this.allScenes=[],this.layouts=e,this.product=o,this.previewService=s,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=r,this.currentVariationRecord=null,this.initializationPromise=this.initializeDefaultWorkflowState(A,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((A=>{throw console.error(A),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>this.updateStateWithServer()))))}async initializeDefaultWorkflowState(A,t){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((A=>{this.storage[A.stepName]=A.storage||{}})),this.allScenes=await Mn(A,{bulkScene:t.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"});const e=Yn(this.allScenes,this.stepSelections).map((A=>A.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(e,!!this.reloadedState);this.commandContext.apply(new w(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.readOnly&&await this.updateStateWithServerImmediate(),this.reloadedState&&(()=>{const A=this.workflow.finalizeStepConfig;if(!A)return;const t=A.lookAtAnimation,e=A.modelAnimation;t&&this.previewService?.executeCameraAnimation(t),e&&this.previewService?.executeModelAnimation(e)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(A){const t={...A,recordNumber:this.variationRecords.reduce(((A,t)=>t.recordNumber>A?t.recordNumber:A),0)+1};return this.variationRecords.push(t),this.onVariationRecordsChange(),t}removeVariationRecord(A){if(this.variationRecords=this.variationRecords.filter((t=>t.recordNumber!==A)),this.variationRecords.forEach(((A,t)=>A.recordNumber=t+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===A){const A=this.currentVariationRecord.recordNumber,t=A>1?this.variationRecords[A-2]:this.variationRecords[0];this.setCurrentVariationRecord(t||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(A){this.variationRecords=A,this.onVariationRecordsChange(),0===A.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(A[0])}setCurrentVariationRecord(A){if(this.currentVariationRecord=A,this.onCurrentVariationRecordChange(),A){const t=this.variationRecords.find((t=>t.recordNumber===A.recordNumber));t&&(t.values=A.values,this.onVariationRecordsChange())}}addConfirmCallback(A){A(this.confirmedDesign),this.confirmCallbacks.push(A)}addEditedCallback(A){A(this.editedSteps),this.editedCallbacks.push(A)}addElementsCallback(A){A(this.stepElements),this.elementsCallbacks.push(A)}addInformationResultCallback(A){A(this.informationResults),this.informationResultCallbacks.push(A)}addInitCallback(A){A(this.stepInitialised),this.initCallbacks.push(A)}addMandatoryCallback(A){A(this.mandatorySteps),this.mandatoryCallbacks.push(A)}addMetadataCallback(A){A(this.stepMetadata),this.metadataCallbacks.push(A)}async addSelectionCallback(A){A({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(A)}addStepSpecificStorageCallback(A,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),A(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(A)}addStorageCallback(A){A(this.storage),this.storageCallbacks.push(A)}addMakingAdjustmentsCallback(A){A(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(A)}addCurrentVariationCallback(A){A(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(A)}addVariationRecordsCallback(A){A(this.variationRecords),this.variationRecordCallbacks.push(A)}addPoller(A){this.pollers.push(A)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((A=>A.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(A){return this.stepElements[A]||[]}getStepSpecificServices(A){return this.stepSpecificServices[A]}getTransaction(){return this.transaction}setTransactionCustomerDetails(A){this.transaction.bulkEmailAddress=A.email}setTransaction(A){this.transaction=A}getWorkflow(){return this.workflow}getCommandDispatcher(){return A=>this.commandContext.apply(A,!this.initialized)}getWorkflowSelections(){const A={};return this.workflow.steps.forEach((t=>{const e=this.stepSelections[t.stepName];e&&e.selectedVariants&&e.selectedVariants.length>0&&(A[t.stepName]={selections:e.selectedVariants})})),A}markStepsAsInitialised(A){const t={...this.stepInitialised};A.forEach((A=>{t[A]=!0})),this.stepInitialised=t,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(A){this.pendingUpdates=this.pendingUpdates.filter((t=>t!==A))}markUpdatePending(){const A=F();return this.pendingUpdates=[...this.pendingUpdates,A],A}setEditedStatus(A,t){this.editedSteps={...this.editedSteps,[A]:t},this.onEditedChange()}setInformationResults(A){this.informationResults=[...A],this.onInformationResultChange()}setCurrentAdjustingStepId(A){this.currentAdjustingStepId=A,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(A,t){this.mandatorySteps[A]!==t&&(this.mandatorySteps={...this.mandatorySteps,[A]:t},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(A){A(this.mandatorySteps),this.mandatoryCallbacks.push(A)}async updateStorage(A,t){const e={...this.storage,[A]:{...this.storage[A],...t}};if(!LA(e,this.storage)){this.storage=e;const t=new dA(this.constructSerializableWorkflow());this.commandContext.apply(t,!0),this.onStepSpecificStorageChange(A),this.onStorageChange()}}constructSerializableWorkflow(){const A=[];return this.allScenes.forEach((t=>{t.renderableSteps.forEach((t=>{const e={stepName:t.stepName};e.storage=this.storage[t.stepName],e.selectedVariants=this.stepSelections[t.stepName]?.selectedVariants?.map((A=>({id:A.id,priceModifier:A.priceModifier}))),A.push(e)}))})),{steps:A}}updateStateWithServer(){if(this.readOnly)return;const A=this.serialize();this.workflowStatePromiseQueue.enqueue(new ii((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:A.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const A=this.serialize();return new ii((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:A.transaction}})})).execute()}serialize(){const A=this.getCommandContext().getState();if(!A)throw new nt("Attempted to serialize state before it was initialized.");const t=JSON.stringify(this.dehydrateState(TA(A.transaction))),e=A.variation;if(!e)return{transaction:t};const n={layouts:{},serializableWorkflow:{steps:[]},...TA(e)||{}};return{transaction:t,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(A){for(const t of Object.values(A.layouts).map((A=>A.elements)).flat())"illustration"===t.type&&(delete t.cachedObjectURL,t.src&&delete t.svg);return A}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(A,t){this.stepMetadata={...this.stepMetadata,[A]:{...this.stepMetadata[A],...t}},this.onMetadataChange()}removeElements(A){this.stepElements=((A,t)=>Object.keys(A).reduce(((e,n)=>{const i=[...A[n]||[]];return t.forEach((A=>{const t=i.findIndex((t=>t.id===A.id));t>-1&&i.splice(t,1)})),e[n]=i,e}),{}))(this.stepElements,A)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((A,t)=>(Fn(t,this.stepSelections)||this.stepElements[t.stepName]&&this.stepElements[t.stepName].forEach((t=>A.push(t))),A)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((A,t)=>("Model"!==t.type||Fn(t,this.stepSelections)||t.option&&A.push(t.option.id),A)),[])}async stepElementsForIntroducedSilentSteps(A,t){const e=this.product;if(!e)return Promise.resolve({stepElements:{},commands:[]});const n=async(A,t,e)=>{if(A.type===m.SilentIllustration){return{step:A,results:await new Un(A,t).trigger()}}if(A.type===m.ProductOverlay){return{step:A,results:await new Un(A,t,e).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=A.filter((A=>!this.stepInitialised[A.stepName])),a={stepElements:{},commands:[]},o=[];for(const A of i)this.markStepsAsInitialised([A.stepName]),t||o.push(n(A,this.layouts,e));const s=await Promise.all(o);for(const A of s)a.stepElements[A.step.stepName]=A.results.map((A=>A.regionElement)),a.commands=[...a.commands,...A.results.map((A=>A.command))];return a}getStepStorage(A){return this.storage[A]}getMetadata(A){return this.stepMetadata[A]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(A,t){return t.find((t=>t.stepName===A))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((A=>A.layoutState.elements.forEach((A=>{this.getCommandDispatcher()(new r(A.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(A,t,e,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[A]:{selectedVariants:t}},this.selectionCost=Object.values(this.stepSelections).reduce(((A,t)=>A+t.selectedVariants.map((A=>A.priceModifier)).reduce(((A,t)=>A+t),0)),0),this.workflow.steps.forEach((A=>{Fn(A,this.stepSelections)||(this.stepInitialised[A.stepName]=!1,delete this.stepMetadata[A.stepName],delete this.stepSelections[A.stepName],delete this.storage[A.stepName])}));const a=this.allScenes,o=Yn(a,i),s=Yn(a,this.stepSelections),c=o.map((A=>A.silentSteps)).flat(),g=s.map((A=>A.silentSteps)).flat().filter((A=>!c.some((t=>t.stepName===A.stepName))));c.forEach((A=>{Fn(A,this.stepSelections)||(this.stepInitialised[A.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const B=this.getInvalidCanvasRegions(),{stepElements:l,commands:E}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...l,[A]:e},this.removeElements(B);if(this.workflow.steps.find((t=>t.stepName===A))?.type===m.Frame){this.getStepSpecificServices(A)?.frameService?.setTargetElements(e.map((A=>A.id)))}const d=[...E,...B.map((A=>new r(A.id))),new dA(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new w(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const A=[],t=Yn(this.allScenes,this.stepSelections).map((A=>A.renderableSteps)).flat();for(const e of t)if(!this.stepInitialised[e.stepName])switch(this.stepInitialised[e.stepName]=!0,e.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((A=>"Bulk"===A.stepName))?.storage||{});break;case m.DigitalContent:A.push(Jn.init(e,this,this.reloadedState));break;case m.Frame:case m.Photo:{const t=new Hn(e.data.forceImageCover);t.connectWorkflowManager(this,e.stepName),this.stepSpecificServices[e.stepName]={frameService:t},A.push(Ln.init(e,this,this.reloadedState))}break;case m.Illustration:A.push(Tn.init(e,this,this.reloadedState));break;case m.Material:A.push(On.init(e,this,this.reloadedState));break;case m.Model:A.push(zn.init(e,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[e.stepName]={module:await Ke(e.data.module)},A.push(jn.init(e,this,this.reloadedState));break;case m.Picture:A.push(Kn.init(e,this,this.reloadedState));break;case m.Question:A.push(Vn.init(e,this,this.reloadedState));break;case m.Shape:A.push(Wn.init(e,this,this.reloadedState));break;case m.Text:A.push(Ai.init(e,this,this.reloadedState))}const e=(await Promise.allSettled(A)).map((A=>{if("rejected"===A.status)throw new Error(`Step initialization failed: ${A.reason}`);return A.value})),n=e.filter((A=>!!A&&!!A.command)).map((A=>A.command)),i=e.filter((A=>!!A&&!!A.followup)).map((A=>A.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const A of i)await A();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((A=>A(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((A=>A(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((A=>A(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((A=>A(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((A=>A(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((A=>{A(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((A=>A(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((A=>{A(this.stepMetadata)}))}async onSelectionChange(){const A=await this.traversableScenes();for(const t of this.selectionCallbacks)t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:A})}onStepSpecificStorageChange(A){Object.keys(this.stepSpecificStorageCallbacks).includes(A)||(this.stepSpecificStorageCallbacks[A]=[]),this.stepSpecificStorageCallbacks[A].forEach((t=>t(this.storage[A])))}onStorageChange(){this.storageCallbacks.forEach((A=>A(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((A=>{A(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((A=>{A(this.variationRecords)}))}traversableScenes(){return xn(this.allScenes,this.stepSelections)}}function oi(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class si{constructor(A,t){oi(this,"manager",void 0),oi(this,"step",void 0),this.manager=A,this.step=t}setUpdateState(A){si.updateState.set(this.step.stepName,A)}getUpdateState(){return!!si.updateState.get(this.step.stepName)}async getCurrentVariant(){return(await this.manager.getWorkflowSelections())[this.step.stepName]?.selections[0]}async getAvailableVariants(){return this.step.option?.variants||[]}getName(){return this.step.stepTitle}getId(){return this.step.stepName}getType(){return this.step.type}getHelpText(){return this.step.helpText}}function ri(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}oi(si,"updateState",new Map);const ci=IA`
|
|
377
|
+
`,pn=A=>{const t=[];for(const e of A.steps)switch(e.type){case m.DigitalContent:e.data.varyUpload&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Upload});break;case m.Frame:const A=e.data;A.varySelection&&e.option&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection}),A.varyUpload&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Upload});break;case m.Illustration:const n=e.data;n.varySelection&&e.option&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection}),n.varyColors&&n.colorPickerEnabled&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Colors});break;case m.Material:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Model:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Picture:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Question:e.data.varySelections&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selections});break;case m.Shape:e.data.varySelection&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection});break;case m.Text:const i=e.data;i.varyText&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Text}),i.varySelection&&e.option&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Selection}),i.varyColor&&i.colorPickerEnabled&&t.push({stepName:e.stepName,stepType:e.type,aspectType:D.Color})}return t},fn=[m.SilentIllustration,m.ProductOverlay],Mn=async(A,t,e)=>{const n=[];A.introduction&&n.push({name:"Introduction",title:A.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:A.name,helpText:A.introduction,data:{},conditions:[]}],silentSteps:[]});for(const e of A.steps){if(t.bulkScene){let A=!1;switch(e.type){case m.DigitalContent:e.data.varyUpload&&(A=!0);break;case m.Frame:{const t=e.data;!t.varyUpload||!t.varySelection&&e.option||(A=!0)}break;case m.Illustration:{const t=e.data;!t.varySelection&&e.option&&1!==e.option.variants.length||!t.varyColors&&t.colorPickerEnabled||(A=!0)}break;case m.Material:e.data.varySelection&&(A=!0);break;case m.Model:e.data.varySelection&&(A=!0);break;case m.Picture:e.data.varySelection&&(A=!0);break;case m.Question:e.data.varySelections&&(A=!0);break;case m.Shape:e.data.varySelection&&(A=!0);break;case m.Text:{const t=e.data;!t.varySelection&&e.option&&1!==e.option.variants.length||!t.varyColor&&t.colorPickerEnabled&&t.colorOption||!t.varyText||(A=!0)}}if(A)continue}const i=yn(e.stepName,A.stepGroups);if(i){const A=n.find((A=>A.name===i.name));A?fn.includes(e.type)?A.silentSteps.push(e):A.renderableSteps.push(e):n.push({name:i.name,title:i.name,renderableSteps:fn.includes(e.type)?[]:[e],silentSteps:fn.includes(e.type)?[e]:[]})}else n.push({name:e.stepName,title:e.stepTitle,renderableSteps:fn.includes(e.type)?[]:[e],silentSteps:fn.includes(e.type)?[e]:[]})}if(t.bulkScene){const i=e?.product?.bulkConfiguration;n.push({name:"Bulk",title:i?.sceneTitle??t.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:i?.stepTitle??t.bulkSceneTitle,helpText:i?.helpText,data:{aspects:pn(A)},conditions:[]}],silentSteps:[]})}return t.finishScene&&n.push({name:"Finish",title:t.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:t.finishSceneTitle,helpText:"",data:{modelAnimation:A.finalizeStepConfig?A.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:A.finalizeStepConfig?A.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},yn=(A,t)=>t.find((t=>t.stepNames.includes(A))),Fn=(A,t)=>(A.conditions||[]).every((A=>{const e=t[A.targetStepName];if(e&&e.selectedVariants){const t=e.selectedVariants;return A.requiredVariantSelections.some((A=>void 0!==t.find((t=>t.id===A))))}return!1})),Yn=(A,t)=>A.map((A=>((A,t)=>{const e={name:A.name,title:A.title,renderableSteps:A.renderableSteps.filter((A=>Fn(A,t))),silentSteps:A.silentSteps.filter((A=>Fn(A,t)))};return 0===e.silentSteps.length&&0===e.renderableSteps.length?null:e})(A,t))).filter((A=>null!==A)),xn=async(A,t)=>{const e=Yn(A,t),n=[];for(const A of e)for(const t of A.renderableSteps)if(t.type===m.Model||t.type===m.Material||t.type===m.Picture||t.type===m.Shape){const A=t.option?.variants.length;A&&A>1&&n.push(t.stepName)}else n.push(t.stepName);const i=e.filter((A=>A.renderableSteps.filter((A=>n.includes(A.stepName))).length>0));for(const A of i)A.renderableSteps=A.renderableSteps.filter((A=>n.includes(A.stepName)));return i};function Sn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}function Nn(A,t,e,n){const i=e.width*A.zoom,a=e.height*A.zoom;if(n){const n=A,i=Math.max(t.width/e.width,t.height/e.height);n.zoom=Math.max(i,A.zoom);const a=e.width*n.zoom,o=e.height*n.zoom;return n.x=vn(A.x,t.width-a,0),n.y=vn(A.y,t.height-o,0),n}const o=A;return o.x=vn(o.x,-i,t.width),o.y=vn(o.y,-a,t.height),o}function vn(A,t,e){return Math.min(Math.max(A,t),e)}class Hn{constructor(A){Sn(this,"offsets",void 0),Sn(this,"forceImageCover",void 0),Sn(this,"targetElements",void 0),Sn(this,"imageData",void 0),Sn(this,"frameData",void 0),Sn(this,"_debouncedUpdateFrameOffsets",void 0),Sn(this,"minZoomScale",.03),Sn(this,"maxZoomScale",20),Sn(this,"onFrameDataChangeListeners",void 0),Sn(this,"onZoomChangeListeners",void 0),Sn(this,"workflowManager",void 0),Sn(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=VA(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=A}connectWorkflowManager(A,t){t&&A.addStepSpecificStorageCallback((async A=>{if(A){const t=A;if(t.currentFrameSource){const A=await v(t.currentFrameSource);LA(A,this.frameData)||(this.frameData=A,this.onFrameDataChangeListeners.forEach((A=>A(this.frameData))),this.frameData&&this.imageData&&(this.offsets=AA(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),t),this.workflowManager=A,this.stepName=t}setTargetElements(A){this.targetElements=A}getFrameData(){return this.frameData}async setFrameData(A){const t=y.get(A);this.frameData=t}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(A){this.offsets=A}setZoom(A,t,e,n){if(this.imageData&&this.offsets&&this.frameData){const i=(t-this.offsets.x)/this.offsets.zoom,a=(e-this.offsets.y)/this.offsets.zoom,o={x:t-i*A,y:e-a*A,zoom:this.imageData.width*A/this.imageData.width};this.updateOffsets(Nn(o,this.frameData,this.imageData,this.forceImageCover),n),this.onZoomChangeListeners.forEach((t=>t(A)))}}setPatternData(A){(A&&this.frameData||A&&this.frameData&&!this.imageData)&&(this.offsets=AA(A,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements),this.updateOffsets(Nn(this.offsets,this.frameData,A,this.forceImageCover))),this.imageData=A,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(A,t){const e=this.imageData;e&&this.frameData&&(this.offsets&&A.x===this.offsets.x&&A.y===this.offsets.y&&A.zoom===this.offsets.zoom?t&&t():(this.offsets=Nn(A,this.frameData,e,this.forceImageCover),this._debouncedUpdateFrameOffsets(A,e,this.frameData,this.targetElements,t)))}onFrameDataChanged(A){A(this.frameData),this.onFrameDataChangeListeners.push(A)}onZoom(A){this.onZoomChangeListeners.push(A)}updateFrameOffsets(A,t,e,n,i){if(!e)throw new nt("Frame data not set. This is a bug");if(!this.workflowManager)throw new nt("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach((e=>{a(new tA(e,t,A))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:A}),i&&i()}recalculateZoomLimits(A,t){const e=Math.max(t.width/A.width,t.height/A.height);this.forceImageCover?(this.minZoomScale=e,this.maxZoomScale=2.5*e):(this.minZoomScale=e/10,this.maxZoomScale=2.5*e)}}function Rn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class Un{constructor(A,t,e){Rn(this,"configuration",void 0),Rn(this,"layouts",void 0),Rn(this,"product",void 0),Rn(this,"processRegion",(async A=>{const t=this.layouts.find((t=>t.panelId===A.panelId));if(!t)throw new $A(A);let e="";if(this.configuration.type===m.ProductOverlay){let A="";if(this.product?.overlayImageUrl&&(A=this.product.overlayImageUrl),e=A,!A)throw new tt(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===d.Image){const e=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!e)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:e,type:n,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,rotation:A.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:A},command:new o(i,t)}}{const i=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:e,a=async()=>new Promise(((A,t)=>{i?nA(i).then((t=>{A(t)})).catch((A=>console.error(A))):t("Undefined vector silent step source")})),s=await x(await a()),r={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await EA(s.svg),src:i,svg:s.svg,colors:s.colors,type:n,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,immutable:A.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:r.id,region:A},command:new o(r,t)}}})),this.configuration=A,this.layouts=t,this.product=e||void 0}async trigger(){if(!this.configuration.data.regions)throw new tt(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const A=this.configuration.data.regions.map(this.processRegion);return Promise.all(A)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((A=>{if(!this.layouts.find((t=>A.panelId===t.panelId)))throw new $A(A);return this.processRegion(A)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const A=this.configuration.type===m.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return A?.startsWith("data:image/png")||A?.endsWith(".jpeg")||A?.endsWith(".jpg")||A?.endsWith(".png")?d.Image:(A?.endsWith(".svg")||A?.startsWith("image/svg+xml"),d.Illustration)}}const Pn=async A=>{const t=`${lt.getServicesApiUrl()}/shortener`;try{const e=await fetch(t,{method:"POST",body:JSON.stringify({longUrl:A}),headers:{"Content-Type":"application/json"}});return(await e.json()).shortUrl}catch(A){throw console.error(A),new ot("Failed to shorten URL, see console.")}};function Gn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class kn{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(A){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(A,t,e,n=3e3,i=10){Gn(this,"pollingId",void 0),Gn(this,"attempts",void 0),Gn(this,"interval",void 0),Gn(this,"maxAttempts",void 0),Gn(this,"predicate",void 0),Gn(this,"onSuccess",void 0),Gn(this,"onFailure",void 0),this.onSuccess=t,this.onFailure=e,this.predicate=A,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const Jn=new class{async init(A,t,e){return e&&await this.reload(A,t,e),null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)).map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[],i,(async()=>{const e=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;t.updateStorage(A.stepName,{videoShortUrl:e,videoUrl:i})}))}async regenerateQRCode(A,t,e,n,i,a,o,s,c){if(t||""===e||""!==n)c(!1);else{const t=async()=>{const A=await Mt.getLocalOrFromServer(e),t=A.versions?.find((A=>"mpeg4"===A.name))?.link;return{asset:A,link:t}},g=await new Promise(((A,e)=>{new kn((async()=>!!(await t()).link),(async()=>{const e=await t();if(!e.link||!e.link)throw new At(e.asset);A({rel:"mpeg4",href:e.link})}),(()=>{e("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));A.forEach((A=>s(new r(A.id))));const B="http"===a.data.baseUrl.slice(0,4)?"":"https://",l=new URL(B+a.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([g]))),l.pathname=l.pathname+("/"===l.pathname.slice(-1)?"":"/");const w=l.toString();if(w.length>=2e3)throw new ot("Cannot create QR code, URL too long.");const E=await Pn(w);if(o(E),!a.data||!a.data.regions)throw new tt(a,"Missing regions.");const d=await this.regionElements(a),h=await this.command(E,d,i,a.stepName);h&&(h.command&&i.getCommandDispatcher()(h.command),h.followup&&await h.followup()),await i.setSelectionsAndElements(a.stepName,[],d,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:E,videoUrl:n}),c(!1)}))}}async regionElements(A){return A.data.regions.map((A=>({id:F(),region:A})))}async command(A,t,e,n){const i=e.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await jA(A,{type:"svg"}))}`,s=t.map((A=>{const t=A.region,e=i.find((A=>A.panelId===t?.panelId));if(!e&&t)throw new $A(t);if(e&&!t)throw new Error("Region not found");if(!e||!t)throw new Error("Neither a region or layout found!");return new o({stepRegion:t,stepName:n,id:A.id,src:a,type:d.Image,y:t.top,x:t.left,width:t.width,height:t.height,rotation:0},e)}));return{command:new w(s),followup:async()=>{}}}};function bn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}const Ln=new class{constructor(){bn(this,"frameSourceSvg",(async(A,t)=>{if(!A)return hA(t.data.regions[0]);const e=A.asset;if(!e)throw new _A(A);const n=e.fileLink;if(n)return nA(n);throw new At(e)}))}async init(A,t,e){if(e)return await this.reload(A,t,e),null;if(t.setMandatoryFulfilled(A.stepName,!1),t.markStepsAsInitialised([A.stepName]),A.option&&A.option.variants.length>0){const e=A.option,n=xt.getDefaultVariant(e);return n?this.selectVariantCommand(A,n,[],t,void 0,A.data.placeholderImageUrl):null}return this.selectVariantCommand(A,void 0,[],t,void 0,A.data.placeholderImageUrl)}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)).map((A=>({id:A.id,region:A.stepRegion})));if(!A.option||0===A.option.variants.length){const e=hA(A.data.regions[0]);t.updateStorage(A.stepName,{currentFrameSource:e})}if(n){const e=async()=>{const e=n.storage?.framePatternSrc,i=n.storage?.frameOffsets;if(t.updateMetadata(A.stepName,{frameOffsets:i,framePatternSrc:e}),e){const n=t.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(e,n),t.updateMetadata(A.stepName,{image:e}),t.updateStorage(A.stepName,{framePatternSrc:e})}if(i?.zoom){const e=t.getStepSpecificServices(A.stepName)?.frameService;e.updateOffsets(i)}t.setMandatoryFulfilled(A.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(A.option&&a){const n=A.option.variants.find((A=>A.id===a));n&&await t.setSelectionsAndElements(A.stepName,[n],i,(async()=>{const i=await this.frameSourceSvg(n,A);t.updateStorage(A.stepName,{currentFrameSource:i}),await e()}))}}else await t.setSelectionsAndElements(A.stepName,[],i,e)}}selectImage(A,t,e){e.setEditedStatus(A.stepName,!0);(t.fileLink||"").endsWith("pdf")?e.addPoller(new kn((async()=>{const A=(await Mt.getLocalOrFromServer(t.key||"")).versions?.find((A=>"svg"===A.name));if(!A)return!1;return 200===(await fetch(A.link)).status}),(()=>{Mt.getLocalOrFromServer(t.key||"").then((t=>{this.loadPatternFromAsset(t,A,e)}))}),(()=>{throw new ot("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(t,A,e)}async selectVariant(A,t,e,n,i){const a=await this.selectVariantCommand(A,t,e,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(A,t,e,n){return new o({id:A,type:d.Frame,x:t.left,y:t.top,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,scaleX:t.width/n.frameData.width,scaleY:t.height/n.frameData.height,path:n.frameData.path,stepRegion:t,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:t.immutable},e)}async loadPatternFromString(A,t){if(A.endsWith("svg")){const e=await QA(A),n=e.width,i=e.height,a={src:A,width:n,height:i,aspect:n/i};G.set(A,a),t.setPatternData(a)}else{const e=await rA(A),n=await S(e),i={src:A,width:n.width,height:n.height,aspect:n.width/n.height};G.set(A,i),t.setPatternData(i)}}async selectVariantCommand(A,t,e,n,i,a){const o=n.getStepSpecificServices(A.stepName)?.frameService,s=await this.frameSourceSvg(t,A),c=await v(s),g=o.getImageData(),B=e.map((A=>new r(A.id))),l=g?AA(g,c):void 0,E=g?{id:F(),src:g.src,x:l?.x||0,y:l?.y||0,width:g.width,height:g.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0;i&&i(!0);const d=A.data.regions.map((t=>{const e=F(),i=n.getLayouts().find((A=>A.panelId===t.panelId));if(!i)throw new $A(t);return{command:this.getCreateElementCommand(e,t,i,{frameData:c,pattern:E,disablePlaceholder:A.data.disablePlaceholder,focalBlur:A.data.focalBlur,focalBlurStrength:A.data.focalBlurStrength,focalBlurRadius:A.data.focalBlurRadius,stepName:A.stepName}),regionEl:{id:e,region:t}}})),h=d.map((A=>A.command));return{command:new w([...h,...B]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(A.stepName,t?[t]:[],[...d.map((A=>A.regionEl))],(async()=>{if(n.updateStorage(A.stepName,{currentFrameSource:s}),a){const t=n.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(a,t)}}))}}}patternSource(A){const t=A.versions?.find((A=>"svg"===A.name));if(t)return t.link;const e=A.fileLink;if(e)return e;throw new At(A)}async loadPatternFromAsset(A,t,e){const n=this.patternSource(A),i=e.markUpdatePending(),a=e.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(n,a),e.updateMetadata(t.stepName,{image:n}),e.updateStorage(t.stepName,{framePatternSrc:n}),e.markUpdateCompleted(i)}};const Tn=new class{async getIllustrationBody(A){return new Promise((t=>{nA(A).then((A=>{t(A)})).catch((A=>console.error(A)))}))}getCreateElementCommand(A,t,e,n){return new o({stepRegion:t,stepName:n.stepName,colors:n.svg.colors,id:A,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:d.Illustration,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable},e)}getColors(A,t){const e=t.getRegionElements(A.stepName)||[];if(0===e.length)return[];try{return M(e[0].id,t.getAllLayoutData()).colors}catch(A){return[]}}async init(A,t,e){const n=A.option;if(!n)return null;if(e)return this.reload(A,t,e);{const e=xt.getDefaultVariant(n);if(e)return await this.selectVariantCommand(A,e,[],(()=>{}),t)}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(!a||!e)throw new Error("Required illustration variant no longer available");{const o=a.variants.find((A=>A.id===e));if(o){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[o],e,(async()=>{t.updateMetadata(A.stepName,{colors:n.storage?.colors}),t.setMandatoryFulfilled(A.stepName,!0)}))}}}return null}async availableColors(A,t){const e=A.data.colorOption;return e&&e?e.variants.map((A=>({fill:A.color,stroke:A.color,variant:A}))):[]}async changeColorsCommand(A,t,e,n,i){const a={};for(const[A,t]of i.entries())a[A]={browserValue:t,spotColor:a[A]?.spotColor};const o=CA(A,t,e,a),s=await EA(o),r=[];for(const A of n){for(const[t,e]of i.entries())r.push(new uA(A,t,e));r.push(new DA(A,o,s))}return new w(r)}async changeColors(A,t,e,n,i){if(0===t.length)return;const a=M(t[0].id,n().map((A=>A.layoutState))),o={...a.colors},s={};Object.entries(o).forEach((([A,t])=>{const e={browserValue:t.browserValue},n=t.spotColor;n&&(e.spotColor={profileName:n.profileName,namedColor:n.namedColor}),s[A]=e}));for(const[A,t]of i.entries())o[A]={browserValue:t,spotColor:o[A]?.spotColor},s[A]={browserValue:t};let r=Array.from(Object.values(o)).map((A=>A.browserValue));const c=A.data.colorOption;c&&c.variants.forEach((A=>{r=r.map((t=>t.toLowerCase()===A.color?.toLowerCase()?A.name:t))})),e.updateMetadata(A.stepName,{colors:r});const g=new Map;if(Object.entries(o).forEach((([A,t])=>{g.set(A,t.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const B=await this.changeColorsCommand(a.svg,a.width,a.height,t.map((A=>A.id)),g);e.updateStorage(A.stepName,{colors:s}),e.getCommandDispatcher()(B)}async selectVariant(A,t,e,n,i){const a=await this.selectVariantCommand(A,t,e,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(A,t,e,n,i){if(!A.data||!A.data.regions)throw new tt(A,"Missing regions.");n(!0);const a=e.map((A=>new r(A.id)));i.setMandatoryFulfilled(A.stepName,!1);const o=t.asset;if(!o)throw new _A(t);const s=o.fileLink;if(!s)throw new At(o);const c=await x(await this.getIllustrationBody(s)),g=await EA(c.svg),B=A.data.regions.map((t=>{const e=i.getLayouts().find((A=>A.panelId===t.panelId));if(!e)throw new $A(t);const n=F();return{regionElement:{id:n,region:t},command:this.getCreateElementCommand(n,t,e,{stepName:A.stepName,src:s,objectURL:g,svg:c})}})),l=[...B.map((A=>A.command)),...a];let E=Array.from(Object.values(c.colors)).map((A=>A.browserValue));const d=A.data.colorOption;return d&&d.variants.forEach((A=>{E=E.map((t=>t.toLowerCase()===A.color?.toLowerCase()?A.name:t))})),i.updateMetadata(A.stepName,{colors:E}),{command:new w(l),followup:async()=>{await i.setSelectionsAndElements(A.stepName,[t],B.map((A=>A.regionElement)),(async()=>{i.setMandatoryFulfilled(A.stepName,!0),n(!1)}))}}}};const On=new class{async init(A,t,e){const n=A.option;if(!n)throw new ZA(A);if(e)await this.reload(A,t,e);else{const e=xt.getDefaultVariant(n);if(e)return await this.selectVariantLambda(A,e,t,(()=>{}))}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(!a)throw new ZA(A);if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(e){const n=a.variants.find((A=>A.id===e));if(n){const e=n.material,o=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],o,(async()=>{const n=t.getPreviewService();if(n){const i=A.data.targetMaterials.map((A=>n.applyMaterialVariant(A,a.id,e)));Promise.all(i).then((()=>t.setMandatoryFulfilled(A.stepName,!0)))}}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantLambda(A,t,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(A,t,e,n){const i=e.getPreviewService();n(!0);const a=t.material;if(!a)throw n(!1),new _A(t);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(A.stepName,[t],[],(async()=>{try{i&&A.data.targetMaterials.forEach((t=>{A.option&&i.applyMaterialVariant(t,A.option.id,a)})),e.setMandatoryFulfilled(A.stepName,!0)}finally{n(!1)}}))}}}};const zn=new class{async init(A,t,e){const n=A.option;if(!n)throw new ZA(A);if(e)await this.reload(A,t,e);else{const e=xt.getDefaultVariant(n);if(e)return await this.selectVariantLambda(A,e,t,(()=>{}))}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((A=>A.id===e));if(n){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],e,(async()=>{const e=t.getPreviewService();if(e&&A.option){const i=n.asset?.fileLink;if(!i)throw new _A(n);await e.applyModelVariant(A.option.id,{model:i,contextService:t.getLayoutPreviewService()},A.data.replaceProductModel||!1),t.setMandatoryFulfilled(A.stepName,!0)}}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantLambda(A,t,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(A,t,e,n){n(!0);const i=t.asset?.fileLink;if(!i)throw new _A(t);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(A.stepName,[t],[],(async()=>{try{const t=e.getPreviewService();t&&A.option&&t.applyModelVariant(A.option.id,{model:i,contextService:e.getLayoutPreviewService()},A.data.replaceProductModel||!1),e.setMandatoryFulfilled(A.stepName,!0)}finally{n(!1)}}))}}}};const jn=new class{async init(A,t,e){return e?(await this.reload(A,t,e),null):(t.updateMetadata(A.stepName,{text:""}),this.changeTextCommand(A,"",t,"",(()=>{})))}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)).map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[],i,(async()=>{t.updateStorage(A.stepName,{text:n?.storage?.text}),t.setMandatoryFulfilled(A.stepName,""!==n?.storage?.text)}))}async changeText(A,t,e,n,i){const a=await this.changeTextCommand(A,t,e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(A,t,e,n,i){const a=e.getRegionElements(A.stepName),s=e.getStepSpecificServices(A.stepName)?.module;if(!s)return console.error("Missing module."),null;const c=e.getProfanities();if(!this.validateInput(A,t,c,i))return e.setMandatoryFulfilled(A.stepName,!1),console.error(n),null;if(e.setMandatoryFulfilled(A.stepName,""!==t),!A.data||!A.data.regions||A.data.regions.length<=0)return console.error("Missing configuration."),null;e.updateStorage(A.stepName,{text:t});const g=(t,n,i)=>{const a=i||F(),s=e.getLayouts().find((A=>A.panelId===n.panelId));if(!s)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return i&&c.push(new r(a)),c.push(new o({stepRegion:n,stepName:A.stepName,colors:{},id:a,svg:t,type:d.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},s)),{id:a,region:n,command:new w(c)}};if(a.length>0){const A=a.map((A=>{if(!A.region)return null;const e=s.svgPrint(t,A.region);return g(e,A.region,A.id)})).filter((A=>!!A)).filter((A=>!!A)).map((A=>A&&A.command));return{command:new w(A),followup:async()=>{}}}{const n=A.data.regions.map((A=>g(s.svgPrint(t,A),A))),i=n.filter((A=>!!A)).map((A=>A&&A.command));return{command:new w(i),followup:async()=>{const t=n.filter((A=>A)).map((A=>A&&{id:A.id,region:A.region}));await e.setSelectionsAndElements(A.stepName,[],t)}}}}validateInput(A,t,e,n){if(A.data&&A.data.maxLength){const e=A.data.maxLength;if(t.length>e)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(t))return n("Unsupported characters."),!1;const i=t.toLowerCase();for(const A in e)if(i===e[A].toLowerCase().trim()&&""!==i)return n("Blocked profanity."),!1;return n(""),!0}};const Kn=new class{async init(A,t,e){const n=A.option;if(!n)return null;if(e)await this.reload(A,t,e);else if(n.defaultVariant)return t.markStepsAsInitialised([A.stepName]),this.selectVariantCommand(A,n.defaultVariant,t,(()=>{}));return t.markStepsAsInitialised([A.stepName]),null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((A=>A.id===e));if(n){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],e,(async()=>{t.setMandatoryFulfilled(A.stepName,!0)}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantCommand(A,t,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(A,t,e,n){const i=t.asset;if(!i)throw new _A(t);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),e.setMandatoryFulfilled(A.stepName,!1);const s=e.getRegionElements(A.stepName).map((A=>new r(A.id))),c=A.data.regions.map((t=>{const n=e.getLayouts().find((A=>A.panelId===t.panelId));if(!n)throw new $A(t);const i=F();return{regionElement:{id:i,region:t},command:new o({stepName:A.stepName,stepRegion:t,id:i,src:a,type:d.Image,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...s,...c.map((A=>A.command))]),followup:async()=>{await e.setSelectionsAndElements(A.stepName,[t],c.map((A=>A.regionElement)),(async()=>{e.setMandatoryFulfilled(A.stepName,!0),n(!1)}))}}}};const Vn=new class{async init(A,t,e){const n=A.option;if(!n)return null;if(e)await this.reload(A,t,e);else{const e=n.variants;if(xt.getDefaultVariant(n)){const i=e.find((A=>A.id===n.defaultVariant?.id));return this.selectVariantLambda(A,i?.id||"",t)}}return null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(i&&e){const n=i.variants.find((A=>A.id===e));n&&await t.setSelectionsAndElements(A.stepName,[n],[])}}}async selectVariant(A,t,e){const n=await this.selectVariantLambda(A,t,e);n&&(n.command&&e.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(A,t,e){const n=A.option;if(!n)return null;const i=n.variants,a=i.length>1?i.find((A=>A.id===t)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(A.stepName,[a],[],(async()=>{e.setMandatoryFulfilled(A.stepName,!0)}))}}}};const Wn=new class{async availableColours(A){const t=A.option;return t?t.variants.map((A=>({fill:A.color,stroke:A.color,variant:A}))):[]}async init(A,t,e){const n=A.option;if(!n)throw new ZA(A);if(!e){const e=xt.getDefaultVariant(n);if(!e)return null;const i={fill:e.color,stroke:e.color,variant:e};return this.selectVariantCommand(A,i,[],t)}return await this.reload(A,t,e),null}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants.find((A=>A.id===e));if(n){const e=i.map((A=>({id:A.id,region:A.stepRegion})));await t.setSelectionsAndElements(A.stepName,[n],e,(async()=>{t.updateStorage(A.stepName,{colour:n.color||""}),t.setMandatoryFulfilled(A.stepName,!0)}))}}}}async selectVariant(A,t,e,n){const i=await this.selectVariantCommand(A,t,e,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(A,t,e,n){const i=n.getLayouts();if(e.length>0){const a=A=>{const e=A.region;if(!i.find((A=>A.panelId===e?.panelId)))throw new $A(e);const n=t.variant?.color;return n?new uA(A.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=e.map(a).filter((A=>!!A));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(A.stepName,t.variant?[t.variant]:[],e),n.updateStorage(A.stepName,{colour:t.fill||""})}}}{const e=e=>{const n=i.find((A=>A.panelId===e.panelId));if(!n)throw new $A(e);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${t.variant?.color}"\n />\n </svg>\n `,s={};s["spiff-fill-shape"]={browserValue:t.variant.color};const r=F();return{id:r,region:e,command:new o({stepRegion:e,stepName:A.stepName,colors:s,id:r,svg:a,type:d.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:A.data.excludeFromPrint},n)}},a=A.data.regions.map(e),s=a.filter((A=>!!A)).map((A=>A?.command)),r=a.filter((A=>!!A)).map((A=>({id:A.id,region:A.region})));return{command:new w(s),followup:async()=>{await n.setSelectionsAndElements(A.stepName,t.variant?[t.variant]:[],r,(async()=>{n.updateStorage(A.stepName,{colour:t.fill||""})}))}}}}};function Xn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}const qn=new class{constructor(){Xn(this,"latestToast",void 0),Xn(this,"toastType",void 0),Xn(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(A){A({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(A)}setLatestToast(A,t){this.latestToast=A,this.toastType=t,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((A=>A({toastMessage:this.latestToast,toastType:this.toastType})))}};function Zn(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class $n extends Error{constructor(A){super(A),Object.setPrototypeOf(this,new.target.prototype),this.name=$n.name}}class _n extends Error{constructor(A){super(A),Object.setPrototypeOf(this,new.target.prototype),this.name=_n.name}}const Ai=new class{constructor(){Zn(this,"cachedColors",new Map),Zn(this,"filterUnsupportedCharacters",((A,t)=>{let e=A.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=t?mA(t):void 0;if(i){const A=e.split("").map((A=>i.getFont().charToGlyph(A)));for(let t=0;t<A.length;t++){const i=".notdef"===A[t].name;"\n"===e.charAt(t)||i&&n.push(String.fromCharCode(e.charCodeAt(t)))}}for(let A=0;A<n.length;A++)e=e.replaceAll(n[A],"");return e})),Zn(this,"textAlign",(A=>A.vertical?"center":A.textAlign||"center")),Zn(this,"getErrorsForText",((A,t,e)=>{const n=[];t.data&&t.data.maxLength&&A.length>t.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=e.getProfanities(),a=A.toLowerCase();if(""!==a)for(const A in i){if(a===i[A].toLowerCase().trim()){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!t.data.allowNewlines&&(A.includes("\n")||A.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(A,t,e){const n=A.option;if(!n)return null;if(e)await this.reload(A,t,e);else{t.updateStorage(A.stepName,{inputText:A.data.defaultText||"",color:(await this.getDefaultColorVariant(A.data))?.color||await this.getDefaultColor(A.data)}),t.updateMetadata(A.stepName,{text:A.data.defaultText||"",color:(await this.getDefaultColorVariant(A.data))?.name||await this.getDefaultColor(A.data)});const e=xt.getDefaultVariant(n);if(e)return this.selectVariantCommand(A,e,{},[],t,(()=>{}),(()=>{}))}return null}findLayoutElements(A,t){return A.getRegionElements(t.stepName).map((t=>M(t.id,A.getAllLayoutData())))}async availableColors(A,t){const e=this.cachedColors.get(A.stepName);if(e)return e;const n=A.data.colorOption;if(n){const t=n.variants.map((A=>({fill:A.color,stroke:A.color,variant:A})));return this.cachedColors.set(A.stepName,t),t}return[]}async changeFill(A,t,e,n){if(!A.data||!A.data.regions)return;const i=n.getCommandDispatcher();t.variant?n.updateMetadata(A.stepName,{color:t.variant.name}):n.updateMetadata(A.stepName,{color:t.fill});const a=await this.getColorOption(A),o=a?this.createTextFillSpotColor(a,t.variant):void 0;a?n.updateStorage(A.stepName,{color:t.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(A.stepName,{color:t.fill});for(const A of e){if(!t.fill)throw new Error("Fill not set on new color selection!");i(new g(A.id,t.fill,o))}}getProcessedInput(A,t,e){const n=e?A:this.injectReplaceableText(A,t);return BA(n,{vertical:t.vertical,uppercase:t.uppercase})}updateInputText(A,t,e,n){const i=n.getStepStorage(e.stepName),a=this.getProcessedInput(A,e.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(A,e,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const s=(e.data.maxLength-a.length).toString();o.helperText=`${s} characters remaining`;const r=n.getTransaction().bulk&&e.data.varyText||!1,c=[],g=new Map,B=new Map;for(const A of t){if(!A.fontData)throw new nt("Failed to resolve font data for text.");const[t,n]=P(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation,panelId:""},[a],{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});g.set(A.id,t),B.set(A.id,n);const i=e.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(t,e.data,A.id,i,r))}if(!e.data.curved&&t.length>0){if(!Array.from(B.values()).every((A=>A)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(e.stepName,{text:A}),n.updateMetadata(e.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(e.stepName,!0),o.command=new w(c),o.command.varying=r,o}async selectVariant(A,t,e,n,i){const a=await this.selectVariantCommand(A,t,e.getStepStorage(A.stepName)||{},e.getRegionElements(A.stepName),e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(A,t){const e=A.colorProfile;if(e){const A=(e.name||"").replace(/\s/g,"-"),n=A.lastIndexOf("/"),i=A.slice(n+1).slice(0,-4);if(!t.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:t.namedColor}}}async reload(A,t,e){const n=t.getSerializedStep(A.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((A=>A.elements)).flat().filter((t=>t.stepName===A.stepName)),a=A.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const o=a.variants.find((A=>A.id===e));if(o){const e=await this.fontDataFromVariant(o),a=i.map((A=>({id:A.id,region:A.stepRegion}))),s=n.storage?.color,r=n.storage?.text;await t.setSelectionsAndElements(A.stepName,[o],a,(async()=>{t.updateMetadata(A.stepName,{color:s,text:r}),t.updateStorage(A.stepName,{text:r,inputText:r});const n=i.map((A=>new l(A.id,e))),a=new w(n);t.getCommandDispatcher()(a),t.setMandatoryFulfilled(A.stepName,!0)}));const{command:c}=Ai.updateInputText(r||"",i,A,t);c&&t.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(A){const t=A.colorOption;if(t)return xt.getDefaultVariant(t)}async getDefaultColor(A){const t=A.colorOption;if(!t)return;return xt.getDefaultVariant(t)?.color}async getColorOption(A){return A.data.colorOption}async fontDataFromVariant(A){const t=A.asset;if(!t)throw new _A(A);const e=t.fileLink;if(!e)throw new At(t);return{assetUrl:e,name:(await U(e)).names.fullName.en}}async selectVariantCommand(A,t,e,n,i,a,o){const s=i.markUpdatePending(),r=await this.fontDataFromVariant(t);if(n.length>0){const c=n.map((A=>new l(A.id,r))),g=await this.changeInputTextWithRegion(A,A.data.size||30,r,e.text||"",e,i,!!e.customiseAllText,a,o);g&&c.push(g);return{command:new w(c),followup:async()=>{i.markUpdateCompleted(s),await i.setSelectionsAndElements(A.stepName,[t],n)}}}{const n=await this.createTextboxRegions(A.stepName,t,A.data,r,e,i),c=await this.changeInputTextWithRegion(A,A.data.size||30,r,n[0]?.newElement.input||e.text||A.data.defaultText||"",e,i,!!e.customiseAllText,a,o),g=n.flatMap((A=>A.commands));c&&g.push(c);return{command:new w(g),followup:async()=>{i.markUpdateCompleted(s)}}}}injectReplaceableText(A,t){return t.replaceableText?t.replaceableText.replace("{{}}",A):A}async createTextboxRegions(A,t,e,n,i,a){if(!e||!e.regions)throw new Error("Step data not supplied");const s=a.getTransaction().bulk&&e.varyText||!1,r=s?"":i.text||e.defaultText||"",c=this.getProcessedInput(r,e,!1),g=await Promise.all(e.regions.map((async t=>{const g=a.getLayouts().find((A=>A.panelId===t.panelId)),B=F();try{if(!g)throw new _n("Failed to find layout for region: "+t.panelId);const l=e.colorOption;let w;if(l){const t=l.variants.find((A=>A.id===l.defaultVariant?.id))||l.variants[0];w=this.createTextFillSpotColor(l,t),a.updateStorage(A,{colorProfileAssetKey:l.colorProfile?.key})}const E=await this.getDefaultColor(e),h=E||"#000000",Q={stepRegion:t,stepName:A,align:this.textAlign(e),fill:i.color?i.color:h,fontSize:e.size||30,fontData:n,id:B,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,text:c,input:r,type:d.Textbox,vertical:e.vertical,x:t.left,y:t.top,height:t.height,width:t.width,immutable:t.immutable,verticalAlign:e.verticalAlign||"middle",curved:e.curved,paths:e.paths,fillSpotColorDefinition:w},C=[],u=new Map,D=new Map;if(!Q.fontData)throw new nt("Failed to resolve font data for text.");const[m,I]=P(Q.fontSize,Q.fontData,{left:Q.x,top:Q.y,width:Q.width,height:Q.height,rotation:Q.rotation,panelId:""},[c],{size:e.size,minSize:e.minSize,maxSize:e.maxSize});u.set(Q.id,m),D.set(Q.id,I);const p=e.curved||e.vertical?c:(I||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(m,e,Q.id,p,s));const f=new o(Q,g);return f.varying=s,{regionElement:{id:B,region:t},commands:[f,...C],newElement:Q,fontData:n}}catch(A){throw console.log(A),new $n("Error adding font to region")}}))).catch((A=>{throw A instanceof $n?(qn.setLatestToast("Failed to load font.",ei.Error),A):A instanceof _n?A:new Error(A)}));return await a.setSelectionsAndElements(A,[t],g.map((A=>A.regionElement)),(async()=>{a.updateMetadata(A,{text:r}),a.updateStorage(A,{text:r})})),g}generateTextChangeCommandsForRegion(A,t,e,n,i){const a=[],o=new I(e,n);if(o.varying=i,a.push(o),!t.size){const t=new B(e,A);t.varying=i,a.push(t)}const s=new w(a);return s.varying=i,s}async changeInputTextWithRegion(A,t,e,n,i,a,o,s,r,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),B=this.getProcessedInput(g,A.data,o),l=a.getRegionElements(A.stepName),E=new Map,d=new Map;for(const n of l)if(n.region){const[i,a]=P(t,e,n.region,[B],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});E.set(n.id,i),d.set(n.id,a)}const h=(()=>{if(A.data&&A.data.maxLength&&B.length>A.data.maxLength)return c&&c(!0),{info:"0"};const t=B.toLowerCase(),e=a.getProfanities();for(const A in e)if(t===e[A].toLowerCase().trim()&&""!==t)return s(!0),{error:"Blocked profanity."};if(!A.data.vertical&&!A.data.allowNewlines&&(B.includes("\n")||B.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!A.data.curved){if(!Array.from(d.values()).every((A=>A)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(A.data.maxLength-B.length).toString()}})();if(h.error)return void r(h.error);if(r(`${h.info} characters remaining`||""),c)return;a.updateStorage(A.stepName,{text:g}),a.updateMetadata(A.stepName,{text:this.injectReplaceableText(g,A.data)});const Q=a.getTransaction().bulk&&A.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(A.stepName,!0);const C=[];for(const t of l){const e=A.data.curved?B:(d.get(t.id)||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(E.get(t.id)||1,A.data,t.id,e,Q))}const u=new w(C);return u.varying=Q,u}};function ti(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}let ei;var ni;(ni=ei||(ei={})).Error="Error",ni.Warning="Warning",ni.Info="Info";class ii extends Me{constructor(A){super(),ti(this,"update",void 0),ti(this,"createdAt",new Date),this.update=A}async execute(){await this.update(),await new Promise((A=>{window.setTimeout((()=>{A()}),1e3)}))}}class ai{constructor(A,t,e,n,i,a,o,s,r,c,g=!1){ti(this,"reloadedState",void 0),ti(this,"transaction",void 0),ti(this,"updateTransaction",void 0),ti(this,"confirmedDesign",void 0),ti(this,"editedSteps",void 0),ti(this,"informationResults",void 0),ti(this,"layouts",void 0),ti(this,"mandatorySteps",void 0),ti(this,"pendingUpdates",void 0),ti(this,"selectionCost",void 0),ti(this,"workflow",void 0),ti(this,"stepSpecificServices",void 0),ti(this,"previewService",void 0),ti(this,"profanityFilter",void 0),ti(this,"pollers",void 0),ti(this,"commandContext",void 0),ti(this,"stepElements",void 0),ti(this,"stepInitialised",void 0),ti(this,"stepMetadata",void 0),ti(this,"stepSelections",void 0),ti(this,"storage",void 0),ti(this,"confirmCallbacks",void 0),ti(this,"editedCallbacks",void 0),ti(this,"elementsCallbacks",void 0),ti(this,"informationResultCallbacks",void 0),ti(this,"initCallbacks",void 0),ti(this,"makingAdjustmentsCallback",void 0),ti(this,"mandatoryCallbacks",void 0),ti(this,"metadataCallbacks",void 0),ti(this,"selectionCallbacks",void 0),ti(this,"stepSpecificStorageCallbacks",void 0),ti(this,"storageCallbacks",void 0),ti(this,"currentVariationRecordCallbacks",void 0),ti(this,"variationRecordCallbacks",void 0),ti(this,"allScenes",void 0),ti(this,"product",void 0),ti(this,"invalidModelVariants",void 0),ti(this,"currentAdjustingStepId",void 0),ti(this,"renderableContextService",void 0),ti(this,"workflowStatePromiseQueue",new ye(1)),ti(this,"variationRecords",[]),ti(this,"currentVariationRecord",void 0),ti(this,"initializationPromise",void 0),ti(this,"initialized",!1),ti(this,"readOnly",!1),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=A,this.stepSpecificServices={},this.profanityFilter=t,this.pollers=[],this.allScenes=[],this.layouts=e,this.product=o,this.previewService=s,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=r,this.currentVariationRecord=null,this.initializationPromise=this.initializeDefaultWorkflowState(A,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((A=>{throw console.error(A),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>this.updateStateWithServer()))))}async initializeDefaultWorkflowState(A,t){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((A=>{this.storage[A.stepName]=A.storage||{}})),this.allScenes=await Mn(A,{bulkScene:t.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},t);const e=Yn(this.allScenes,this.stepSelections).map((A=>A.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(e,!!this.reloadedState);this.commandContext.apply(new w(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.readOnly&&await this.updateStateWithServerImmediate(),this.reloadedState&&(()=>{const A=this.workflow.finalizeStepConfig;if(!A)return;const t=A.lookAtAnimation,e=A.modelAnimation;t&&this.previewService?.executeCameraAnimation(t),e&&this.previewService?.executeModelAnimation(e)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(A){const t={...A,recordNumber:this.variationRecords.reduce(((A,t)=>t.recordNumber>A?t.recordNumber:A),0)+1};return this.variationRecords.push(t),this.onVariationRecordsChange(),t}removeVariationRecord(A){if(this.variationRecords=this.variationRecords.filter((t=>t.recordNumber!==A)),this.variationRecords.forEach(((A,t)=>A.recordNumber=t+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===A){const A=this.currentVariationRecord.recordNumber,t=A>1?this.variationRecords[A-2]:this.variationRecords[0];this.setCurrentVariationRecord(t||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(A){this.variationRecords=A,this.onVariationRecordsChange(),0===A.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(A[0])}setCurrentVariationRecord(A){if(this.currentVariationRecord=A,this.onCurrentVariationRecordChange(),A){const t=this.variationRecords.find((t=>t.recordNumber===A.recordNumber));t&&(t.values=A.values,this.onVariationRecordsChange())}}addConfirmCallback(A){A(this.confirmedDesign),this.confirmCallbacks.push(A)}addEditedCallback(A){A(this.editedSteps),this.editedCallbacks.push(A)}addElementsCallback(A){A(this.stepElements),this.elementsCallbacks.push(A)}addInformationResultCallback(A){A(this.informationResults),this.informationResultCallbacks.push(A)}addInitCallback(A){A(this.stepInitialised),this.initCallbacks.push(A)}addMandatoryCallback(A){A(this.mandatorySteps),this.mandatoryCallbacks.push(A)}addMetadataCallback(A){A(this.stepMetadata),this.metadataCallbacks.push(A)}async addSelectionCallback(A){A({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(A)}addStepSpecificStorageCallback(A,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),A(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(A)}addStorageCallback(A){A(this.storage),this.storageCallbacks.push(A)}addMakingAdjustmentsCallback(A){A(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(A)}addCurrentVariationCallback(A){A(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(A)}addVariationRecordsCallback(A){A(this.variationRecords),this.variationRecordCallbacks.push(A)}addPoller(A){this.pollers.push(A)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((A=>A.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(A){return this.stepElements[A]||[]}getStepSpecificServices(A){return this.stepSpecificServices[A]}getTransaction(){return this.transaction}setTransactionCustomerDetails(A){this.transaction.bulkEmailAddress=A.email}setTransaction(A){this.transaction=A}getWorkflow(){return this.workflow}getCommandDispatcher(){return A=>this.commandContext.apply(A,!this.initialized)}getWorkflowSelections(){const A={};return this.workflow.steps.forEach((t=>{const e=this.stepSelections[t.stepName];e&&e.selectedVariants&&e.selectedVariants.length>0&&(A[t.stepName]={selections:e.selectedVariants})})),A}markStepsAsInitialised(A){const t={...this.stepInitialised};A.forEach((A=>{t[A]=!0})),this.stepInitialised=t,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(A){this.pendingUpdates=this.pendingUpdates.filter((t=>t!==A))}markUpdatePending(){const A=F();return this.pendingUpdates=[...this.pendingUpdates,A],A}setEditedStatus(A,t){this.editedSteps={...this.editedSteps,[A]:t},this.onEditedChange()}setInformationResults(A){this.informationResults=[...A],this.onInformationResultChange()}setCurrentAdjustingStepId(A){this.currentAdjustingStepId=A,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(A,t){this.mandatorySteps[A]!==t&&(this.mandatorySteps={...this.mandatorySteps,[A]:t},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(A){A(this.mandatorySteps),this.mandatoryCallbacks.push(A)}async updateStorage(A,t){const e={...this.storage,[A]:{...this.storage[A],...t}};if(!LA(e,this.storage)){this.storage=e;const t=new dA(this.constructSerializableWorkflow());this.commandContext.apply(t,!0),this.onStepSpecificStorageChange(A),this.onStorageChange()}}constructSerializableWorkflow(){const A=[];return this.allScenes.forEach((t=>{t.renderableSteps.forEach((t=>{const e={stepName:t.stepName};e.storage=this.storage[t.stepName],e.selectedVariants=this.stepSelections[t.stepName]?.selectedVariants?.map((A=>({id:A.id,priceModifier:A.priceModifier}))),A.push(e)}))})),{steps:A}}updateStateWithServer(){if(this.readOnly)return;const A=this.serialize();this.workflowStatePromiseQueue.enqueue(new ii((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:A.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const A=this.serialize();return new ii((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:A.transaction}})})).execute()}serialize(){const A=this.getCommandContext().getState();if(!A)throw new nt("Attempted to serialize state before it was initialized.");const t=JSON.stringify(this.dehydrateState(TA(A.transaction))),e=A.variation;if(!e)return{transaction:t};const n={layouts:{},serializableWorkflow:{steps:[]},...TA(e)||{}};return{transaction:t,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(A){for(const t of Object.values(A.layouts).map((A=>A.elements)).flat())"illustration"===t.type&&(delete t.cachedObjectURL,t.src&&delete t.svg);return A}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(A,t){this.stepMetadata={...this.stepMetadata,[A]:{...this.stepMetadata[A],...t}},this.onMetadataChange()}removeElements(A){this.stepElements=((A,t)=>Object.keys(A).reduce(((e,n)=>{const i=[...A[n]||[]];return t.forEach((A=>{const t=i.findIndex((t=>t.id===A.id));t>-1&&i.splice(t,1)})),e[n]=i,e}),{}))(this.stepElements,A)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((A,t)=>(Fn(t,this.stepSelections)||this.stepElements[t.stepName]&&this.stepElements[t.stepName].forEach((t=>A.push(t))),A)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((A,t)=>("Model"!==t.type||Fn(t,this.stepSelections)||t.option&&A.push(t.option.id),A)),[])}async stepElementsForIntroducedSilentSteps(A,t){const e=this.product;if(!e)return Promise.resolve({stepElements:{},commands:[]});const n=async(A,t,e)=>{if(A.type===m.SilentIllustration){return{step:A,results:await new Un(A,t).trigger()}}if(A.type===m.ProductOverlay){return{step:A,results:await new Un(A,t,e).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=A.filter((A=>!this.stepInitialised[A.stepName])),a={stepElements:{},commands:[]},o=[];for(const A of i)this.markStepsAsInitialised([A.stepName]),t||o.push(n(A,this.layouts,e));const s=await Promise.all(o);for(const A of s)a.stepElements[A.step.stepName]=A.results.map((A=>A.regionElement)),a.commands=[...a.commands,...A.results.map((A=>A.command))];return a}getStepStorage(A){return this.storage[A]}getMetadata(A){return this.stepMetadata[A]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(A,t){return t.find((t=>t.stepName===A))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((A=>A.layoutState.elements.forEach((A=>{this.getCommandDispatcher()(new r(A.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(A,t,e,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[A]:{selectedVariants:t}},this.selectionCost=Object.values(this.stepSelections).reduce(((A,t)=>A+t.selectedVariants.map((A=>A.priceModifier)).reduce(((A,t)=>A+t),0)),0),this.workflow.steps.forEach((A=>{Fn(A,this.stepSelections)||(this.stepInitialised[A.stepName]=!1,delete this.stepMetadata[A.stepName],delete this.stepSelections[A.stepName],delete this.storage[A.stepName])}));const a=this.allScenes,o=Yn(a,i),s=Yn(a,this.stepSelections),c=o.map((A=>A.silentSteps)).flat(),g=s.map((A=>A.silentSteps)).flat().filter((A=>!c.some((t=>t.stepName===A.stepName))));c.forEach((A=>{Fn(A,this.stepSelections)||(this.stepInitialised[A.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const B=this.getInvalidCanvasRegions(),{stepElements:l,commands:E}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...l,[A]:e},this.removeElements(B);if(this.workflow.steps.find((t=>t.stepName===A))?.type===m.Frame){this.getStepSpecificServices(A)?.frameService?.setTargetElements(e.map((A=>A.id)))}const d=[...E,...B.map((A=>new r(A.id))),new dA(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new w(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const A=[],t=Yn(this.allScenes,this.stepSelections).map((A=>A.renderableSteps)).flat();for(const e of t)if(!this.stepInitialised[e.stepName])switch(this.stepInitialised[e.stepName]=!0,e.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((A=>"Bulk"===A.stepName))?.storage||{});break;case m.DigitalContent:A.push(Jn.init(e,this,this.reloadedState));break;case m.Frame:case m.Photo:{const t=new Hn(e.data.forceImageCover);t.connectWorkflowManager(this,e.stepName),this.stepSpecificServices[e.stepName]={frameService:t},A.push(Ln.init(e,this,this.reloadedState))}break;case m.Illustration:A.push(Tn.init(e,this,this.reloadedState));break;case m.Material:A.push(On.init(e,this,this.reloadedState));break;case m.Model:A.push(zn.init(e,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[e.stepName]={module:await Ke(e.data.module)},A.push(jn.init(e,this,this.reloadedState));break;case m.Picture:A.push(Kn.init(e,this,this.reloadedState));break;case m.Question:A.push(Vn.init(e,this,this.reloadedState));break;case m.Shape:A.push(Wn.init(e,this,this.reloadedState));break;case m.Text:A.push(Ai.init(e,this,this.reloadedState))}const e=(await Promise.allSettled(A)).map((A=>{if("rejected"===A.status)throw new Error(`Step initialization failed: ${A.reason}`);return A.value})),n=e.filter((A=>!!A&&!!A.command)).map((A=>A.command)),i=e.filter((A=>!!A&&!!A.followup)).map((A=>A.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const A of i)await A();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((A=>A(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((A=>A(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((A=>A(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((A=>A(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((A=>A(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((A=>{A(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((A=>A(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((A=>{A(this.stepMetadata)}))}async onSelectionChange(){const A=await this.traversableScenes();for(const t of this.selectionCallbacks)t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:A})}onStepSpecificStorageChange(A){Object.keys(this.stepSpecificStorageCallbacks).includes(A)||(this.stepSpecificStorageCallbacks[A]=[]),this.stepSpecificStorageCallbacks[A].forEach((t=>t(this.storage[A])))}onStorageChange(){this.storageCallbacks.forEach((A=>A(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((A=>{A(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((A=>{A(this.variationRecords)}))}traversableScenes(){return xn(this.allScenes,this.stepSelections)}}function oi(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class si{constructor(A,t){oi(this,"manager",void 0),oi(this,"step",void 0),this.manager=A,this.step=t}setUpdateState(A){si.updateState.set(this.step.stepName,A)}getUpdateState(){return!!si.updateState.get(this.step.stepName)}async getCurrentVariant(){return(await this.manager.getWorkflowSelections())[this.step.stepName]?.selections[0]}async getAvailableVariants(){return this.step.option?.variants||[]}getName(){return this.step.stepTitle}getId(){return this.step.stepName}getType(){return this.step.type}getHelpText(){return this.step.helpText}}function ri(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}oi(si,"updateState",new Map);const ci=IA`
|
|
378
378
|
mutation UpdateTransactionBulkEmailAddress($id: String!, $bulkEmailAddress: String!) {
|
|
379
379
|
transactionUpdate(id: $id, bulkEmailAddress: $bulkEmailAddress) {
|
|
380
380
|
id
|
|
@@ -437,7 +437,7 @@ import{CommandContext as A,AssetType as t,BringForwardCommand as e,BringToFrontC
|
|
|
437
437
|
}
|
|
438
438
|
}
|
|
439
439
|
}
|
|
440
|
-
`,Ii=(A,t,e)=>{const n={};return t.steps.forEach((t=>{Object.assign(n,(t=>{const n={};if("Frame"===t.type){const i=A[t.stepName],a=t.data;if(!i||a.hideImageInCart&&e)return n;n[`${t.stepTitle} image`]=i.image}if("Illustration"===t.type){const i=A[t.stepName],a=t.data;if(!i||a.hideColorsInCart&&e||!i.colors)return n;if(i.colors.length>0){const A=i.colors.join(", ").toUpperCase();n[`${t.stepTitle} colors`]=A}}if("Module"===t.type){const i=A[t.stepName],a=t.data;if(!i||a.hideTextInCart&&e)return n;n[`${t.stepTitle} text`]=i.text}if("Text"===t.type){const i=A[t.stepName];if(!i)return n;const a=t.data;a.hideTextInCart&&e||(n[`${t.stepTitle} text`]=i.text),!i.color||a.hideColorInCart&&e||(n[`${t.stepTitle} color`]=i.color)}return n})(t))})),n},pi=(A,t,e,n,i,a,o,s,r)=>{const c={event:"onComplete",lineItemImageUrl:o||"",transactionId:A.id,designProductVariantId:A.externalDesignProductVariantId,designProductId:A.externalDesignProductId,baseCost:e,weight:t.weight,optionsCost:n,exportedData:a,workflowViewerLink:A.workflowViewerLink||"",workflowViewerReadOnlyLink:A.workflowViewerReadOnlyLink||""};return i&&(c.metadata=i),s&&(c.selectedVariants=s),r&&(c.sku=r),c},fi=async(A,t,e,n,i,a,o)=>{const s=(A.product?.basePrice||0)*(A.variationsCount||0),r=A.priceModifierTotal||0,c=((A,t,e,n)=>{const i={};let a;if(e){a=Ii(e,t,!1);for(const A of Object.keys(a))i[A]={value:a[A],priceModifier:0}}else if(n){a=n;for(const A of Object.keys(a))i[A]={value:a[A],priceModifier:0}}for(const e of Object.keys(A)){const n=A[e],a=t.steps.find((A=>A.stepTitle===e));if(1===n.length)i[`${a?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let A=0;A<n.length;A++)i[`${a?.stepTitle} selection ${A+1}`]={value:n[A].name,priceModifier:n[A].priceModifier}}return i})(n,e,void 0,a);return pi(A,t,s,r,a,c,o,n,i)},Mi=async(A,t,e,n,i,a,o,s,r,c,g,B,l)=>{r("workflow.steps.finish.finalize.buildingLayouts"),await A.outstandingRequestsPromise();const w=ht.getShadowGraphqlClient();await w.resetStore();const E=await w.query({query:In,variables:{id:a.id},errorPolicy:"all"}),d=E.data?.transactions[0].workflowState;!E.errors&&d||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),E.errors&&E.errors.forEach((A=>{E.errors&&console.log("Server Error:",A.message)})),await A.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const h=A.getPreviewService(),Q=t?.finalizeStepConfig?.lookAtAnimation,C=h&&100===h.getSceneInitializationProgress()&&t.showModelOnFinishStep&&!!Q,u=l&&Ii(l,t,!0),D=l&&Ii(l,t,!1),m=async A=>{const e={};let n=0;if(Object.keys(o).length>0)for(const i of Object.keys(o)){const a=o[i],s=t.steps.find((A=>A.stepName===i));for(let t=0;t<a.selections.length;++t){const i=a.selections[t];if(s&&(!A||s.option&&s.option.variants.length>1&&!s.data.hideSelectionInCart&&!s.data.hideSelectionsInCart)){const A=s.stepTitle;e[A]?e[A].push({id:i.id||"",name:i.name,priceModifier:i.priceModifier}):e[A]=[{id:i.id||"",name:i.name,priceModifier:i.priceModifier}]}n+=i.priceModifier}}return[e,n]},[I]=await m(!0),p=Object.fromEntries(Object.keys(I).map((A=>[A,I[A].map((A=>A.id))]))),[f]=await m(!1),M=Object.fromEntries(Object.keys(f).map((A=>[A,f[A].map((A=>A.id))]))),y=await B(C);r("workflow.steps.finish.finalize.creatingDesign"),a.bulk&&await c(g);const F=await(async A=>(await ht.getShadowGraphqlClient().mutate({mutation:mi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:A.name,layouts:A.layouts,workflowId:A.workflowId,transactionId:A.transactionId,previewImage:A.previewImage,useThreeDimPreview:A.useThreeDimPreview,metadata:A.metadata,selectedVariants:A.selectedVariants}})).data?.designCreate)((()=>{const A={name:s,layouts:e.map((A=>({index:A.index,panelId:A.panelId}))),workflowId:t.id,transactionId:a.id,useThreeDimPreview:C,previewImage:y};if(D){const t=[];for(const[A,e]of Object.entries(D))t.push({key:A,value:e});A.metadata=t}if(p){const t=[];for(const[A,e]of Object.entries(M))t.push({key:A,ids:e});A.selectedVariants=t}return A})()),Y=F?.transaction?.previewImageLink;r("workflow.steps.finish.finalize.updatingTransaction");const x=(await ht.getShadowGraphqlClient().query({query:mn,variables:{id:a.id}})).data.transactions[0];return a.bulk?((A,t,e)=>{const n=(A.product?.basePrice||0)*(A.variationsCount||0),i=A.priceModifierTotal||0,a={items:{value:A.variationsCount?`${A.variationsCount}`:"0",priceModifier:0}};return pi(A,t,n,i,void 0,a,e)})(x,i,Y):await fi(x,i,t,I,F?.sku,u,Y)};let yi;var Fi;(Fi=yi||(yi={})).Local="Local",Fi.Remote="Remote";const Yi=new class{constructor(){Di(this,"localPersistenceKey","designTransactions"),Di(this,"storageMethod",yi.Local),Di(this,"designSavedListeners",[])}attachSaveListener(A){this.designSavedListeners.push(A)}detachSaveListener(A){this.designSavedListeners=this.designSavedListeners.filter((t=>t!==A))}async getSavedDesigns(){return await this.getDesigns()}async getSavedDesignByTransaction(A){return(await this.getSavedDesigns()).find((t=>t.transactionId===A))}async addDesign(A){const t=(await this.getSavedDesigns()).filter((t=>t.transactionId!==A.transactionId));t.unshift(A),await this.setDesigns(t),this.notifyDesignSaved(A)}async removeDesign(A){const t=await this.getSavedDesigns();await this.setDesigns(t.filter((t=>t.transactionId!==A)))}async setDesigns(A){if(this.storageMethod!==yi.Local)throw new nt("Unexpected storage method requested");gt.set(this.localPersistenceKey,JSON.stringify(A))}async getDesigns(){if(this.storageMethod===yi.Local){const A=gt.get(this.localPersistenceKey);return A?JSON.parse(A):[]}throw new nt("Unexpected storage method requested")}notifyDesignSaved(A){this.designSavedListeners.forEach((t=>t(A)))}};function xi(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class Si{constructor(t,e){if(xi(this,"client",void 0),xi(this,"commandContext",void 0),xi(this,"workflowManager",void 0),xi(this,"isReadOnly",void 0),xi(this,"renderableScenes",[]),xi(this,"renderableSceneCallbacks",[]),xi(this,"debouncedSavedDesignUpdate",VA((async()=>{await Yi.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const n=e.layouts;this.commandContext=new A,this.commandContext.initialize(n,e.reloadedState),this.isReadOnly=!!e.transaction.lineItem?.id||!gt.getMap("transactionOwnerIds")?.get(e.transaction.id)||!!e.readOnly,this.workflowManager=new ai(e.workflow,e.product.profanities?.map((A=>A.word))||[],n,this.commandContext,(A=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(A)}),e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly),this.workflowManager.addSelectionCallback((A=>{const t=A.traversableScenes.map((A=>{const t=A.renderableSteps.map((A=>A.stepName));return{id:A.name,title:A.title,renderableSteps:t}}));this.renderableScenes=t,this.renderableSceneCallbacks.forEach((A=>A(t)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(A){await ht.getShadowGraphqlClient().mutate({mutation:Dn,variables:{transactionId:this.workflowManager.getTransaction().id,updates:A.map((A=>({recordNumber:A.recordNumber,values:A.values.map((A=>({aspect:A.aspect,stepName:A.stepName,value:A.value})))})))}})}async createPreviewImage(A,t){const e=this.workflowManager.getWorkflow()?.finalizeStepConfig?.lookAtAnimation;if(A){if(!e)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,e))||""}const n=document.createElement("canvas");let i=2048;t&&t<=2048&&(i=t),n.width=i,n.height=i;const a=this.commandContext.getAllLayouts()[this.workflowManager.getWorkflow().defaultPreviewPanelIndex||0],o=a.layoutState.layout.previewRegion?{x:a.layoutState.layout.previewRegion.left,y:a.layoutState.layout.previewRegion.top,width:a.layoutState.layout.previewRegion.width,height:a.layoutState.layout.previewRegion.height}:{x:0,y:0,width:a.layoutState.layout.width,height:a.layoutState.layout.height},s=this.commandContext.getLayoutById(a.layoutState.layout.id),r=n.getContext("2d");if(!r)throw new ot("Failed to obtain 2D context for preview image creation");const c=H(s.layoutState.layout,s.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:o.x,top:o.y,width:o.width,height:o.height}}}),g=zA.renderToStaticMarkup(c),B=await OA.from(r,g,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await B.render();const l=await(async A=>new Promise(((t,e)=>{try{A.toBlob((A=>{if(A){const e=URL.createObjectURL(A);t(e)}}))}catch(A){e(A)}})))(n);return n.toDataURL(l)}getStepById(A){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepName===A));if(t&&this.stepHasHandle(t))return ui.get(this.getWorkflowManager(),t)}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const A={type:m.Bulk,stepName:"Bulk",stepTitle:"workflow.steps.bulk.title",helpText:"Add any variations of your base design here.",data:{aspects:pn(this.getWorkflowManager().getWorkflow())},conditions:[]};return ui.get(this.getWorkflowManager(),A)}}getStepByName(A){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepTitle===A));if(t&&this.stepHasHandle(t))return ui.get(this.getWorkflowManager(),t)}getStepsByType(A){return this.getWorkflowManager().getWorkflow().steps.filter((t=>t.type===A)).map((A=>ui.get(this.getWorkflowManager(),A)))}getStepsByScene(A){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((t=>t.name===A.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return A.stepNames.map((A=>this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepName===A)))).filter((A=>this.stepHasHandle(A))).map((A=>ui.get(this.getWorkflowManager(),A)))}async attachCustomerDetails(A){await ht.getShadowGraphqlClient().mutate({mutation:ci,variables:{id:this.getWorkflowManager().getTransaction().id,bulkEmailAddress:A.email}}),this.getWorkflowManager().setTransactionCustomerDetails(A)}attachRenderableSceneListener(A){this.renderableSceneCallbacks.push(A),A(this.renderableScenes)}detachRenderableSceneListener(A){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((t=>t!==A))}async save(A){if(!this.getCommandContext().getState())throw new nt("State undefined!");const t={title:await(async()=>{if(A)return A;const t=this.getWorkflowManager().getTransaction().id,e=(await Yi.getSavedDesigns()).find((A=>A.transactionId===t))?.title;return e||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Yi.addDesign(t),t}async copy(){const A=TA(this.getCommandContext().getState());if(!A)throw new nt("Internal state is undefined! Cannot copy experience!");const t=JSON.stringify(A.transaction),e=this.getWorkflowManager().getWorkflow(),n=new Ui({}),i=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!i)throw new nt("Integration product id is undefined!");await n.initFromIntegrationProduct(i);return await n.getWorkflowExperience(e.id,t,void 0)}async onDesignFinished(A,t,e,n){return Mi(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),A,this.workflowManager.getTransaction(),e,this.workflowManager.getWorkflow().name,t,(A=>this.updateVariationRecords(A)),this.workflowManager.getVariationRecords(),(A=>this.createPreviewImage(A)),n)}stepHasHandle(A){return A.type!==m.SilentIllustration&&A.type!==m.ProductOverlay}}function Ni(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}const vi=IA`
|
|
440
|
+
`,Ii=(A,t,e)=>{const n={};return t.steps.forEach((t=>{Object.assign(n,(t=>{const n={};if("Frame"===t.type){const i=A[t.stepName],a=t.data;if(!i||a.hideImageInCart&&e)return n;n[`${t.stepTitle} image`]=i.image}if("Illustration"===t.type){const i=A[t.stepName],a=t.data;if(!i||a.hideColorsInCart&&e||!i.colors)return n;if(i.colors.length>0){const A=i.colors.join(", ").toUpperCase();n[`${t.stepTitle} colors`]=A}}if("Module"===t.type){const i=A[t.stepName],a=t.data;if(!i||a.hideTextInCart&&e)return n;n[`${t.stepTitle} text`]=i.text}if("Text"===t.type){const i=A[t.stepName];if(!i)return n;const a=t.data;a.hideTextInCart&&e||(n[`${t.stepTitle} text`]=i.text),!i.color||a.hideColorInCart&&e||(n[`${t.stepTitle} color`]=i.color)}return n})(t))})),n},pi=(A,t,e,n,i,a,o,s,r)=>{const c={event:"onComplete",lineItemImageUrl:o||"",transactionId:A.id,designProductVariantId:A.externalDesignProductVariantId,designProductId:A.externalDesignProductId,baseCost:e,weight:t.weight,optionsCost:n,exportedData:a,workflowViewerLink:A.workflowViewerLink||"",workflowViewerReadOnlyLink:A.workflowViewerReadOnlyLink||""};return i&&(c.metadata=i),s&&(c.selectedVariants=s),r&&(c.sku=r),c},fi=async(A,t,e,n,i,a,o)=>{const s=(A.product?.basePrice||0)*(A.variationsCount||0),r=A.priceModifierTotal||0,c=((A,t,e,n)=>{const i={};let a;if(e){a=Ii(e,t,!1);for(const A of Object.keys(a))i[A]={value:a[A],priceModifier:0}}else if(n){a=n;for(const A of Object.keys(a))i[A]={value:a[A],priceModifier:0}}for(const e of Object.keys(A)){const n=A[e],a=t.steps.find((A=>A.stepTitle===e));if(1===n.length)i[`${a?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let A=0;A<n.length;A++)i[`${a?.stepTitle} selection ${A+1}`]={value:n[A].name,priceModifier:n[A].priceModifier}}return i})(n,e,void 0,a);return pi(A,t,s,r,a,c,o,n,i)},Mi=async(A,t,e,n,i,a,o,s,r,c,g,B,l)=>{r("workflow.steps.finish.finalize.buildingLayouts"),await A.outstandingRequestsPromise();const w=ht.getShadowGraphqlClient();await w.resetStore();const E=await w.query({query:In,variables:{id:a.id},errorPolicy:"all"}),d=E.data?.transactions[0].workflowState;!E.errors&&d||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),E.errors&&E.errors.forEach((A=>{E.errors&&console.log("Server Error:",A.message)})),await A.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const h=A.getPreviewService(),Q=t?.finalizeStepConfig?.lookAtAnimation,C=h&&100===h.getSceneInitializationProgress()&&t.showModelOnFinishStep&&!!Q,u=l&&Ii(l,t,!0),D=l&&Ii(l,t,!1),m=async A=>{const e={};let n=0;if(Object.keys(o).length>0)for(const i of Object.keys(o)){const a=o[i],s=t.steps.find((A=>A.stepName===i));for(let t=0;t<a.selections.length;++t){const i=a.selections[t];if(s&&(!A||s.option&&s.option.variants.length>1&&!s.data.hideSelectionInCart&&!s.data.hideSelectionsInCart)){const A=s.stepTitle;e[A]?e[A].push({id:i.id||"",name:i.name,priceModifier:i.priceModifier}):e[A]=[{id:i.id||"",name:i.name,priceModifier:i.priceModifier}]}n+=i.priceModifier}}return[e,n]},[I]=await m(!0),p=Object.fromEntries(Object.keys(I).map((A=>[A,I[A].map((A=>A.id))]))),[f]=await m(!1),M=Object.fromEntries(Object.keys(f).map((A=>[A,f[A].map((A=>A.id))]))),y=await B(C);r("workflow.steps.finish.finalize.creatingDesign"),a.bulk&&await c(g);const F=await(async A=>(await ht.getShadowGraphqlClient().mutate({mutation:mi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:A.name,layouts:A.layouts,workflowId:A.workflowId,transactionId:A.transactionId,previewImage:A.previewImage,useThreeDimPreview:A.useThreeDimPreview,metadata:A.metadata,selectedVariants:A.selectedVariants}})).data?.designCreate)((()=>{const A={name:s,layouts:e.map((A=>({index:A.index,panelId:A.panelId}))),workflowId:t.id,transactionId:a.id,useThreeDimPreview:C,previewImage:y};if(D){const t=[];for(const[A,e]of Object.entries(D))t.push({key:A,value:e});A.metadata=t}if(p){const t=[];for(const[A,e]of Object.entries(M))t.push({key:A,ids:e});A.selectedVariants=t}return A})()),Y=F?.transaction?.previewImageLink;r("workflow.steps.finish.finalize.updatingTransaction");const x=(await ht.getShadowGraphqlClient().query({query:mn,variables:{id:a.id}})).data.transactions[0];return a.bulk?((A,t,e)=>{const n=(A.product?.basePrice||0)*(A.variationsCount||0),i=A.priceModifierTotal||0,a={items:{value:A.variationsCount?`${A.variationsCount}`:"0",priceModifier:0}};return pi(A,t,n,i,void 0,a,e)})(x,i,Y):await fi(x,i,t,I,F?.sku,u,Y)};let yi;var Fi;(Fi=yi||(yi={})).Local="Local",Fi.Remote="Remote";const Yi=new class{constructor(){Di(this,"localPersistenceKey","designTransactions"),Di(this,"storageMethod",yi.Local),Di(this,"designSavedListeners",[])}attachSaveListener(A){this.designSavedListeners.push(A)}detachSaveListener(A){this.designSavedListeners=this.designSavedListeners.filter((t=>t!==A))}async getSavedDesigns(){return await this.getDesigns()}async getSavedDesignByTransaction(A){return(await this.getSavedDesigns()).find((t=>t.transactionId===A))}async addDesign(A){const t=(await this.getSavedDesigns()).filter((t=>t.transactionId!==A.transactionId));t.unshift(A),await this.setDesigns(t),this.notifyDesignSaved(A)}async removeDesign(A){const t=await this.getSavedDesigns();await this.setDesigns(t.filter((t=>t.transactionId!==A)))}async setDesigns(A){if(this.storageMethod!==yi.Local)throw new nt("Unexpected storage method requested");gt.set(this.localPersistenceKey,JSON.stringify(A))}async getDesigns(){if(this.storageMethod===yi.Local){const A=gt.get(this.localPersistenceKey);return A?JSON.parse(A):[]}throw new nt("Unexpected storage method requested")}notifyDesignSaved(A){this.designSavedListeners.forEach((t=>t(A)))}};function xi(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}class Si{constructor(t,e){if(xi(this,"client",void 0),xi(this,"commandContext",void 0),xi(this,"workflowManager",void 0),xi(this,"isReadOnly",void 0),xi(this,"renderableScenes",[]),xi(this,"renderableSceneCallbacks",[]),xi(this,"debouncedSavedDesignUpdate",VA((async()=>{await Yi.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const n=e.layouts;this.commandContext=new A,this.commandContext.initialize(n,e.reloadedState),this.isReadOnly=!!e.transaction.lineItem?.id||!gt.getMap("transactionOwnerIds")?.get(e.transaction.id)||!!e.readOnly,this.workflowManager=new ai(e.workflow,e.product.profanities?.map((A=>A.word))||[],n,this.commandContext,(A=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(A)}),e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly),this.workflowManager.addSelectionCallback((A=>{const t=A.traversableScenes.map((A=>{const t=A.renderableSteps.map((A=>A.stepName));return{id:A.name,title:A.title,renderableSteps:t}}));this.renderableScenes=t,this.renderableSceneCallbacks.forEach((A=>A(t)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(A){await ht.getShadowGraphqlClient().mutate({mutation:Dn,variables:{transactionId:this.workflowManager.getTransaction().id,updates:A.map((A=>({recordNumber:A.recordNumber,values:A.values.map((A=>({aspect:A.aspect,stepName:A.stepName,value:A.value})))})))}})}async createPreviewImage(A,t){const e=this.workflowManager.getWorkflow()?.finalizeStepConfig?.lookAtAnimation;if(A){if(!e)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,e))||""}const n=document.createElement("canvas");let i=2048;t&&t<=2048&&(i=t),n.width=i,n.height=i;const a=this.commandContext.getAllLayouts()[this.workflowManager.getWorkflow().defaultPreviewPanelIndex||0],o=a.layoutState.layout.previewRegion?{x:a.layoutState.layout.previewRegion.left,y:a.layoutState.layout.previewRegion.top,width:a.layoutState.layout.previewRegion.width,height:a.layoutState.layout.previewRegion.height}:{x:0,y:0,width:a.layoutState.layout.width,height:a.layoutState.layout.height},s=this.commandContext.getLayoutById(a.layoutState.layout.id),r=n.getContext("2d");if(!r)throw new ot("Failed to obtain 2D context for preview image creation");const c=H(s.layoutState.layout,s.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:o.x,top:o.y,width:o.width,height:o.height}}}),g=zA.renderToStaticMarkup(c),B=await OA.from(r,g,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await B.render();const l=await(async A=>new Promise(((t,e)=>{try{A.toBlob((A=>{if(A){const e=URL.createObjectURL(A);t(e)}}))}catch(A){e(A)}})))(n);return n.toDataURL(l)}getStepById(A){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepName===A));if(t&&this.stepHasHandle(t))return ui.get(this.getWorkflowManager(),t)}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const A=this.getWorkflowManager().getProduct().bulkConfiguration,t={type:m.Bulk,stepName:"Bulk",stepTitle:A?.stepTitle??"workflow.steps.bulk.title",helpText:A?.helpText,data:{aspects:pn(this.getWorkflowManager().getWorkflow())},conditions:[]};return ui.get(this.getWorkflowManager(),t)}}getStepByName(A){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepTitle===A));if(t&&this.stepHasHandle(t))return ui.get(this.getWorkflowManager(),t)}getStepsByType(A){return this.getWorkflowManager().getWorkflow().steps.filter((t=>t.type===A)).map((A=>ui.get(this.getWorkflowManager(),A)))}getStepsByScene(A){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((t=>t.name===A.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return A.stepNames.map((A=>this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepName===A)))).filter((A=>this.stepHasHandle(A))).map((A=>ui.get(this.getWorkflowManager(),A)))}async attachCustomerDetails(A){await ht.getShadowGraphqlClient().mutate({mutation:ci,variables:{id:this.getWorkflowManager().getTransaction().id,bulkEmailAddress:A.email}}),this.getWorkflowManager().setTransactionCustomerDetails(A)}attachRenderableSceneListener(A){this.renderableSceneCallbacks.push(A),A(this.renderableScenes)}detachRenderableSceneListener(A){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((t=>t!==A))}async save(A){if(!this.getCommandContext().getState())throw new nt("State undefined!");const t={title:await(async()=>{if(A)return A;const t=this.getWorkflowManager().getTransaction().id,e=(await Yi.getSavedDesigns()).find((A=>A.transactionId===t))?.title;return e||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Yi.addDesign(t),t}async copy(){const A=TA(this.getCommandContext().getState());if(!A)throw new nt("Internal state is undefined! Cannot copy experience!");const t=JSON.stringify(A.transaction),e=this.getWorkflowManager().getWorkflow(),n=new Ui({}),i=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!i)throw new nt("Integration product id is undefined!");await n.initFromIntegrationProduct(i);return await n.getWorkflowExperience(e.id,t,void 0)}async onDesignFinished(A,t,e,n){return Mi(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),A,this.workflowManager.getTransaction(),e,this.workflowManager.getWorkflow().name,t,(A=>this.updateVariationRecords(A)),this.workflowManager.getVariationRecords(),(A=>this.createPreviewImage(A)),n)}stepHasHandle(A){return A.type!==m.SilentIllustration&&A.type!==m.ProductOverlay}}function Ni(A,t,e){return(t=function(A){var t=function(A,t){if("object"!=typeof A||null===A)return A;var e=A[Symbol.toPrimitive];if(void 0!==e){var n=e.call(A,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(A)}(A,"string");return"symbol"==typeof t?t:String(t)}(t))in A?Object.defineProperty(A,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):A[t]=e,A}const vi=IA`
|
|
441
441
|
${Ct}
|
|
442
442
|
${Dt}
|
|
443
443
|
${Ft}
|