@spiffcommerce/core 14.0.1 → 14.1.1-alpha.0
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 +3 -3
- package/dist/module.js +3 -3
- package/dist/types.d.ts +4 -0
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -467,7 +467,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
|
|
|
467
467
|
workflowState
|
|
468
468
|
}
|
|
469
469
|
}
|
|
470
|
-
`,Us=t=>{const e=[];for(const i of t.steps)switch(i.type){case si.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Frame:const t=i.data;t.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),t.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Illustration:const A=i.data;A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColors&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case si.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case si.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Text:const n=i.data;n.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColor&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Gs=[si.SilentIllustration,si.ProductOverlay],Ts=async(t,e,i)=>{const A=[];t.introduction&&A.push({name:"Introduction",title:t.name,renderableSteps:[{type:si.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of t.steps){if(e.bulkScene){let t=!1;switch(i.type){case si.DigitalContent:i.data.varyUpload&&(t=!0);break;case si.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case si.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case si.Material:i.data.varySelection&&(t=!0);break;case si.Model:i.data.varySelection&&(t=!0);break;case si.Picture:i.data.varySelection&&(t=!0);break;case si.Question:i.data.varySelections&&(t=!0);break;case si.Shape:i.data.varySelection&&(t=!0);break;case si.Text:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const n=Os(i.stepName,t.stepGroups);if(n){const t=A.find((t=>t.name===n.name));t?Gs.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):A.push({name:n.name,title:n.name,renderableSteps:Gs.includes(i.type)?[]:[i],silentSteps:Gs.includes(i.type)?[i]:[]})}else A.push({name:i.stepName,title:i.stepTitle,renderableSteps:Gs.includes(i.type)?[]:[i],silentSteps:Gs.includes(i.type)?[i]:[]})}if(e.bulkScene){const n=i?.product?.bulkConfiguration;A.push({name:"Bulk",title:n?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:si.Bulk,stepName:"Bulk",stepTitle:n?.stepTitle??e.bulkSceneTitle,helpText:n?.helpText,data:{aspects:Us(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&A.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:si.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),A},Os=(t,e)=>e.find((e=>e.stepNames.includes(t))),Js=(t,e)=>(t.conditions||[]).every((t=>{const i=e[t.targetStepName];if(i&&i.selectedVariants){const e=i.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),Ls=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Js(t,e))),silentSteps:t.silentSteps.filter((t=>Js(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),zs=async(t,e)=>{const i=Ls(t,e),A=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===si.Model||e.type===si.Material||e.type===si.Picture||e.type===si.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&A.push(e.stepName)}else A.push(e.stepName);const n=i.filter((t=>t.renderableSteps.filter((t=>A.includes(t.stepName))).length>0));for(const t of n)t.renderableSteps=t.renderableSteps.filter((t=>A.includes(t.stepName)));return n};function js(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Vs(t,e,i,A){const n=i.width*t.zoom,a=i.height*t.zoom;if(A){const A=t,n=Math.max(e.width/i.width,e.height/i.height);A.zoom=Math.max(n,t.zoom);const a=i.width*A.zoom,r=i.height*A.zoom;return A.x=Ks(t.x,e.width-a,0),A.y=Ks(t.y,e.height-r,0),A}const r=t;return r.x=Ks(r.x,-n,e.width),r.y=Ks(r.y,-a,e.height),r}function Ks(t,e,i){return Math.min(Math.max(t,e),i)}class Ws{constructor(t){js(this,"offsets",void 0),js(this,"forceImageCover",void 0),js(this,"targetElements",void 0),js(this,"imageData",void 0),js(this,"frameData",void 0),js(this,"_debouncedUpdateFrameOffsets",void 0),js(this,"minZoomScale",[.03]),js(this,"maxZoomScale",[20]),js(this,"onFrameDataChangeListeners",void 0),js(this,"onZoomChangeListeners",void 0),js(this,"workflowManager",void 0),js(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=F(I)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let i=0;i<e.currentFrameSources.length;i++){const A=e.currentFrameSources[i],n=await Rn(A);F(C)(n,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=n,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,i)=>{const A=bn.get(e);A&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=A)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,A){this.imageData&&this.offsets&&this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((A,n)=>{const a=(e[n]-this.offsets[n].x)/this.offsets[n].zoom,r=(i[n]-this.offsets[n].y)/this.offsets[n].zoom,s={x:e[n]-a*t[n],y:i[n]-r*t[n],zoom:this.imageData.width*t[n]/this.imageData.width};this.offsets[n]=Vs(s,A,this.imageData,this.forceImageCover)})),this.updateOffsets(this.offsets,A),this.onZoomChangeListeners.forEach((e=>e(t))))}setPatternData(t){if(t&&this.frameData){this.recalculateOffsets(t);const e=this.offsets.map(((e,i)=>Vs(e,this.frameData[i],t,this.forceImageCover)));this.updateOffsets(e)}this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==t.length)throw new aa("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,i)=>t[i].x===e.x&&t[i].y===e.y&&t[i].zoom===e.zoom))?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Vs(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,i,A,n){if(!i||0===i.length||i.some((t=>!t)))throw new aa("Frame data not set. This is a bug");if(!this.workflowManager)throw new aa("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();A.forEach(((i,A)=>{a(new un(i,e,t[A]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),n&&n()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,i)=>{const A=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=A,this.maxZoomScale[i]=2.5*A):(this.minZoomScale[i]=A/10,this.maxZoomScale[i]=2.5*A)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=kn(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function Xs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class qs{constructor(t,e,i){Xs(this,"configuration",void 0),Xs(this,"layouts",void 0),Xs(this,"product",void 0),Xs(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new ta(t);let i="";if(this.configuration.type===si.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new Aa(this.configuration,"Couldn't find an asset for product overlay step")}const A=this.evaluateAssetType();if(A===ze.Image){const i=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const n={stepName:this.configuration.stepName,id:Te(),src:i,type:A,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===si.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:n.id,region:t},command:new an(n,e)}}{const n=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:i,a=async()=>new Promise(((t,e)=>{n?Ki(n).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await GA(await a()),s={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await Kn(r.svg),src:n,svg:r.svg,colors:r.colors,type:A,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===si.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new an(s,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new Aa(this.configuration,"Missing regions.");if(this.configuration.type===si.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===si.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new ta(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===si.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")?ze.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),ze.Illustration)}}const Zs=async t=>{const e=`${ua.getServicesApiUrl()}/shortener`;try{const i=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await i.json()).shortUrl}catch(t){throw console.error(t),new oa("Failed to shorten URL, see console.")}};function $s(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class _s{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,e,i,A=3e3,n=10){$s(this,"pollingId",void 0),$s(this,"attempts",void 0),$s(this,"interval",void 0),$s(this,"maxAttempts",void 0),$s(this,"predicate",void 0),$s(this,"onSuccess",void 0),$s(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=A,this.maxAttempts=n,this.poll()}}const to=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{const i=A?.storage?.videoShortUrl,n=A?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:n})}))}async regenerateQRCode(t,e,i,A,n,a,r,s,o){if(e||""===i||""!==A)o(!1);else{const e=async()=>{const t=(await Fa([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new _s((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new ia(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>s(new rn(t.id))));const l="http"===a.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+a.data.baseUrl);g.searchParams.append("video",btoa(JSON.stringify([c]))),g.pathname=g.pathname+("/"===g.pathname.slice(-1)?"":"/");const h=g.toString();if(h.length>=2e3)throw new oa("Cannot create QR code, URL too long.");const d=await Zs(h);if(r(d),!a.data||!a.data.regions)throw new Aa(a,"Missing regions.");const u=await this.regionElements(a),w=await this.command(d,u,n,a.stepName);w&&(w.command&&n.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await n.setSelectionsAndElements(a.stepName,[],u,(async()=>{n.updateStorage(a.stepName,{videoShortUrl:d,videoUrl:A}),o(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,A){const n=i.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,i=n.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new ta(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new an({stepRegion:e,stepName:A,id:t.id,src:a,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new en(r),followup:async()=>{}}}};function eo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const io=new class{constructor(){eo(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Pn(e);const i=t.asset;if(!i)throw new ea(t);const A=i.fileLink;if(A)return Ki(A);throw new ia(i)}))}async init(t,e,i){if(i)return await this.reload(t,e,i),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const i=t.option,A=Ha.getDefaultVariant(i);return A?this.selectVariantCommand(t,A,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const i=t.data.regions.map((t=>Pn(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(A){const i=async()=>{const i=A.storage?.framePatternSrc,n=A.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:n,framePatternSrc:i}),i){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,A),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(n?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(n)}e.setMandatoryFulfilled(t.stepName,!0)};if(A.selectedVariants&&A.selectedVariants.length>0){const a=A.selectedVariants[0].id;if(t.option&&a){const A=t.option.variants?.find((t=>t.id===a));A&&await e.setSelectionsAndElements(t.stepName,[A],n,(async()=>{const n=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(A,t))));e.updateStorage(t.stepName,{currentFrameSources:n}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],n,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new _s((async()=>{const t=(await Pa.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Pa.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new oa("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,A,n){const a=await this.selectVariantCommand(t,e,i,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,e,i,A){return new an({id:t,type:ze.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/A.frameData.width,scaleY:e.height/A.frameData.height,path:A.frameData.path,dataWidth:A.frameData.width,dataHeight:A.frameData.height,stepRegion:e,stepName:A.stepName,disablePlaceholder:A.disablePlaceholder,focalBlur:A.focalBlur,focalBlurStrength:A.focalBlurStrength,focalBlurRadius:A.focalBlurRadius,pattern:A.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await Un(t),A=i.width,n=i.height,a={src:t,width:A,height:n,aspect:A/n};Fn.set(t,a),e.setPatternData(a)}else{const i=await Vi(t),A=await Mn(i),n={src:t,width:A.width,height:A.height,aspect:A.width/A.height};Fn.set(t,n),e.setPatternData(n)}}async selectVariantCommand(t,e,i,A,n,a){const r=A.getStepSpecificServices(t.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");const s=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));n&&n(!0);const o=await Promise.all(t.data.regions.map((async(e,n)=>{const a=await Rn(s[n]),o=r.getImageData(),c=i.map((t=>new rn(t.id))),l=o?kn(o,a):void 0,g=o?{id:Te(),src:o.src,x:l?.x||0,y:l?.y||0,width:o.width,height:o.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=A.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new ta(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:a,pattern:g,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:h,region:e},removeExistingCommands:c}}))),c=o.map((t=>t.command)),l=o.map((t=>t.removeExistingCommands)).flat();return{command:new en([...c,...l]),followup:async()=>{n&&n(!1),await A.setSelectionsAndElements(t.stepName,e?[e]:[],[...o.map((t=>t.regionEl))],(async()=>{if(A.updateStorage(t.stepName,{currentFrameSources:s}),a){const e=A.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(a,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const i=t.fileLink;if(i)return i;throw new ia(t)}async loadPatternFromAsset(t,e,i){const A=this.patternSource(t),n=i.markUpdatePending(),a=i.getStepSpecificServices(e.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,a),i.updateMetadata(e.stepName,{image:A}),i.updateStorage(e.stepName,{framePatternSrc:A}),i.markUpdateCompleted(n)}};const Ao=new class{async getIllustrationBody(t){return new Promise((e=>{Ki(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,A){return new an({stepRegion:e,stepName:A.stepName,colors:A.svg.colors,id:t,src:A.src,svg:A.svg.svg,cachedObjectURL:A.objectURL,type:ze.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},i)}getColors(t,e){const i=e.getRegionElements(t.stepName)||[];if(0===i.length)return[];try{return VA(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const A=t.option;if(!A)return null;if(i)return this.reload(t,e,i);{const i=Ha.getDefaultVariant(A);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(!a||!i)throw new Error("Required illustration variant no longer available");{const r=a.variants?.find((t=>t.id===i));if(r){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[r],i,(async()=>{e.updateMetadata(t.stepName,{colors:A.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const i=t.data.colorOption;return i&&i?i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,i,A,n){const a={};for(const[t,e]of n.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor};const r=UA(t,e,i,a),s=await Kn(r),o=[];for(const t of A){for(const[e,i]of n.entries())o.push(new Bn(t,e,i));o.push(new pn(t,r,s))}return new en(o)}async changeColors(t,e,i,A,n){if(0===e.length)return;const a=VA(e[0].id,A().map((t=>t.layoutState))),r={...a.colors},s={};Object.entries(r).forEach((([t,e])=>{const i={browserValue:e.browserValue},A=e.spotColor;A&&(i.spotColor={profileName:A.profileName,namedColor:A.namedColor}),s[t]=i}));for(const[t,e]of n.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor},s[t]={browserValue:e};let o=Array.from(Object.values(r)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{o=o.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:o});const l=new Map;if(Object.entries(r).forEach((([t,e])=>{l.set(t,e.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(a.svg,a.width,a.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:s}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,A,n){const a=await this.selectVariantCommand(t,e,i,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,i,A,n){if(!t.data||!t.data.regions)throw new Aa(t,"Missing regions.");A(!0);const a=i.map((t=>new rn(t.id)));n.setMandatoryFulfilled(t.stepName,!1);const r=e.asset;if(!r)throw new ea(e);const s=r.fileLink;if(!s)throw new ia(r);const o=await GA(await this.getIllustrationBody(s)),c=await Kn(o.svg),l=t.data.regions.map((e=>{const i=n.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new ta(e);const A=Te();return{regionElement:{id:A,region:e},command:this.getCreateElementCommand(A,e,i,{stepName:t.stepName,src:s,objectURL:c,svg:o})}})),g=[...l.map((t=>t.command)),...a];let h=Array.from(Object.values(o.colors)).map((t=>t.browserValue));const d=t.data.colorOption;return d&&d.variants?.forEach((t=>{h=h.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),n.updateMetadata(t.stepName,{colors:h}),{command:new en(g),followup:async()=>{await n.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{n.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const no=new class{async init(t,e,i){const A=t.option;if(!A)throw new _n(t);if(i)await this.reload(t,e,i);else{const i=Ha.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(!a)throw new _n(t);if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(i){const A=a.variants?.find((t=>t.id===i));if(A){const i=A.material,r=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],r,(async()=>{const A=e.getModelContainer();if(A){const n=t.data.targetMaterials.map((t=>A.applyMaterialVariant(t,a.id||"",i||{})));Promise.all(n).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){const n=i.getModelContainer();A(!0);const a=e.material;if(!a)throw A(!1),new ea(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{n&&t.data.targetMaterials.forEach((e=>{t.option&&n.applyMaterialVariant(e,t.option.id||"",a)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ao=new class{async init(t,e,i){const A=t.option;if(!A)throw new _n(t);if(i)await this.reload(t,e,i);else{const i=Ha.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const A=a.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const n=A.asset?.fileLink;if(!n)throw new ea(A);await i.applyModelVariant(t.option.id||"",{model:n,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){A(!0);const n=e.asset?.fileLink;if(!n)throw new ea(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=i.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:n,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ro=new class{async init(t,e,i){return i?(await this.reload(t,e,i),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{e.updateStorage(t.stepName,{text:A?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==A?.storage?.text)}))}async changeText(t,e,i,A,n){const a=await this.changeTextCommand(t,e,i,A,n);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,e,i,A,n){const a=i.getRegionElements(t.stepName),r=i.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const s=i.getProfanities();if(!this.validateInput(t,e,s,n))return i.setMandatoryFulfilled(t.stepName,!1),console.error(A),null;if(i.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(t.stepName,{text:e});const o=(e,A,n)=>{const a=n||Te(),r=i.getLayouts().find((t=>t.panelId===A.panelId));if(!r)return console.error(`Can not find layout for region: ${A.panelId}`),null;const s=[];return n&&s.push(new rn(a)),s.push(new an({stepRegion:A,stepName:t.stepName,colors:{},id:a,svg:e,type:ze.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},r)),{id:a,region:A,command:new en(s)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const i=r.svgPrint(e,t.region);return o(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new en(t),followup:async()=>{}}}{const A=t.data.regions.map((t=>o(r.svgPrint(e,t),t))),n=A.filter((t=>!!t)).map((t=>t&&t.command));return{command:new en(n),followup:async()=>{const e=A.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,A){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return A("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return A("Unsupported characters."),!1;const n=(0,x.split)(e.toLowerCase());for(const t of n)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return A("Blocked profanity."),!1}return A(""),!0}};const so=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else if(A.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,A.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const A=a.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=e.asset;if(!n)throw new ea(e);const a=n?.fileLink;if(!a)return console.error("No URL for picture!"),null;A(!0),i.setMandatoryFulfilled(t.stepName,!1);const r=i.getRegionElements(t.stepName).map((t=>new rn(t.id))),s=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new ta(e);const n=Te();return{regionElement:{id:n,region:e},command:new an({stepName:t.stepName,stepRegion:e,id:n,src:a,type:ze.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},A)}}));return{command:new en([...r,...s.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],s.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const oo=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=A.variants;if(Ha.getDefaultVariant(A)){const n=i?.find((t=>t.id===A.defaultVariant?.id));return this.selectVariantLambda(t,n?.id||"",e)}}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(n&&i){const A=n.variants?.find((t=>t.id===i));A&&await e.setSelectionsAndElements(t.stepName,[A],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const A=await this.selectVariantLambda(t,e,i);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i){const A=t.option;if(!A)return null;const n=A.variants;if(!n)return null;const a=n.length>1?n.find((t=>t.id===e)):n[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 i.setSelectionsAndElements(t.stepName,[a],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};const co=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,i){const A=t.option;if(!A)throw new _n(t);if(!i){const i=Ha.getDefaultVariant(A);if(!i)return null;const n={fill:i.color,stroke:i.color,variant:i};return this.selectVariantCommand(t,n,[],e)}return await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const A=a.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.updateStorage(t.stepName,{colour:A.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=A.getLayouts();if(i.length>0){const a=t=>{const i=t.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new ta(i);const A=e.variant?.color;return A?new Bn(t.id,"spiff-fill-shape",A):(console.error("Failed to change color."),null)},r=i.map(a).filter((t=>!!t));return{command:new en(r),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),A.updateStorage(t.stepName,{colour:e.fill||""})}}}{const i=i=>{const A=n.find((t=>t.panelId===i.panelId));if(!A)throw new ta(i);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="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=Te();return{id:s,region:i,command:new an({stepRegion:i,stepName:t.stepName,colors:r,id:s,svg:a,type:ze.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},a=t.data.regions.map(i),r=a.filter((t=>!!t)).map((t=>t?.command)),s=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new en(r),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{A.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function lo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class go extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=go.name}}const ho=["‘","’","“","”","\n"];class uo extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=uo.name}}const wo=new class{constructor(){lo(this,"cachedColors",new Map),lo(this,"filterUnsupportedCharacters",((t,e)=>{let i=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const A=[],n=e?oA(e):void 0;if(n){const t=i.split("").filter((t=>!ho.includes(t))).join(""),e=t.split("").map((t=>n.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&A.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<A.length;t++)i=i.replaceAll(A[t],"");return i})),lo(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),lo(this,"getErrorsForText",((t,e,i)=>{const A=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&A.push({localizationKey:"workflow.steps.text.characterLimit"});const n=i.getProfanities(),a=(0,x.split)(t.toLowerCase());for(const t of a)for(const e in n){if(t===n[e].toLowerCase().replace(/\s/g,"")){A.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&A.push({localizationKey:"workflow.steps.text.multipleLines"}),A}))}async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),n=i?.asset?.fileLink,a=n?await Hn(n):void 0,r=a?{src:a.src,height:a.height,width:a.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:r}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const s=Ha.getDefaultVariant(A);if(s)return this.selectVariantCommand(t,s,{},[],e,(()=>{}),(()=>{}),r)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>VA(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const i=t.data.colorOption;if(i){const e=i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher();e.variant?A.updateMetadata(t.stepName,{color:e.variant.name}):A.updateMetadata(t.stepName,{color:e.fill});const a=t.data.colorOption,r=a?this.createTextFillSpotColor(a,e.variant):void 0;a?A.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:a.colorProfile?.key}):A.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");n(new on(t.id,e.fill,r))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const i=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(i.map((async e=>{const i=await Hn(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher(),a=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));A.updateMetadata(t.stepName,{fillImage:a?.name}),A.updateStorage(t.stepName,{fillImage:e});for(const t of i){n(new cn(t.id,e))}}getProcessedInput(t,e,i){const A=i?t:this.injectReplaceableText(t,e);return CA(A,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,A){const n=A.getStepStorage(i.stepName),a=this.getProcessedInput(t,i.data,!!n.customiseAllText),r={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,A)};if(r.errors.length>0)return r.helperText=r.errors[0].localizationKey,r;const s=(i.data.maxLength-a.length).toString();r.helperText=`${s} characters remaining`;const o=A.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new aa("Failed to resolve font data for text.");const[e,A]=Jn(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,A);const n=i.data.curved?a:(A||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,n,o))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return r.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),r}return A.updateStorage(i.stepName,{text:t}),A.updateMetadata(i.stepName,{text:a}),n.defaultCleared&&A.setMandatoryFulfilled(i.stepName,!0),r.command=new en(c),r.command.varying=o,r}async selectVariant(t,e,i,A,n){const a=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,A,n);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),A=t.lastIndexOf("/"),n=t.slice(A+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:n,namedColor:e.namedColor}}}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const r=a.variants?.find((t=>t.id===i));if(r){const i=await this.fontDataFromVariant(r),a=n.map((t=>({id:t.id,region:t.stepRegion}))),s=A.storage?.color,o=A.storage?.text;await e.setSelectionsAndElements(t.stepName,[r],a,(async()=>{e.updateMetadata(t.stepName,{color:s,text:o}),e.updateStorage(t.stepName,{text:o,inputText:o});const A=n.map((t=>new hn(t.id,i))),a=new en(A);e.getCommandDispatcher()(a),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=wo.updateInputText(o||"",n,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ha.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ha.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ha.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ea(t);const i=e.fileLink;if(!i)throw new ia(e);return{assetUrl:i,name:(await rA(i)).names.fullName.en}}async selectVariantCommand(t,e,i,A,n,a,r,s){const o=n.markUpdatePending(),c=await this.fontDataFromVariant(e);if(A.length>0){const l=A.map((t=>new hn(t.id,c)));if(s){const t=A.map((t=>new cn(t.id,s)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,n,!!i.customiseAllText,a,r);g&&l.push(g);return{command:new en(l),followup:async()=>{n.markUpdateCompleted(o),await n.setSelectionsAndElements(t.stepName,[e],A)}}}{const A=await this.createTextboxRegions(t.stepName,e,t.data,c,i,n),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A[0]?.newElement.input||i.text||t.data.defaultText||"",i,n,!!i.customiseAllText,a,r),g=A.flatMap((t=>t.commands));if(s){const t=A.map((t=>new cn(t.regionElement.id,s)));g.push(...t)}l&&g.push(l);return{command:new en(g),followup:async()=>{n.markUpdateCompleted(o)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,A,n,a){if(!i||!i.regions)throw new Error("Step data not supplied");const r=a.getTransaction().bulk&&i.varyText||!1,s=r?"":n.text||i.defaultText||"",o=this.getProcessedInput(s,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=a.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new uo("Failed to find layout for region: "+e.panelId);const g=i.colorOption;let h;if(g&&g.variants){const e=g.variants.find((t=>t.id===g.defaultVariant?.id))||g.variants[0];h=this.createTextFillSpotColor(g,e),a.updateStorage(t,{colorProfileAssetKey:g.colorProfile?.key})}const d=await this.getDefaultColor(i),u=d||"#000000",w={stepRegion:e,stepName:t,align:this.textAlign(i),fill:n.color?n.color:u,fontSize:i.size||30,fontData:A,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:o,input:s,type:ze.Textbox,vertical:i.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths,fillSpotColorDefinition:h},B=[],p=new Map,E=new Map;if(!w.fontData)throw new aa("Failed to resolve font data for text.");const[m,f]=Jn(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[o],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,m),E.set(w.id,f);const C=i.curved||i.vertical?o:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(m,i,w.id,C,r));const Q=new an(w,c);return Q.varying=r,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:A}}catch(t){throw console.log(t),new go("Error adding font to region")}}))).catch((t=>{throw t instanceof go?(or.setLatestToast("Failed to load font.",po.Error),t):t instanceof uo?t:new Error(t)}));return await a.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:s}),a.updateStorage(t,{text:s})})),c}generateTextChangeCommandsForRegion(t,e,i,A,n){const a=[],r=new wn(i,A);if(r.varying=n,a.push(r),!e.size){const e=new ln(i,t);e.varying=n,a.push(e)}const s=new en(a);return s.varying=n,s}async changeInputTextWithRegion(t,e,i,A,n,a,r,s,o,c){const l=(A||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,r),h=a.getRegionElements(t.stepName),d=new Map,u=new Map;for(const A of h)if(A.region){const[n,a]=Jn(e,i,A.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(A.id,n),u.set(A.id,a)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=a.getProfanities(),i=(0,x.split)(g.toLowerCase());for(const t of i)for(const i in e){if(t===e[i].toLowerCase().replace(/\s/g,""))return s(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void o(w.error);if(o(`${w.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:l}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=a.getTransaction().bulk&&t.data.varyText||!1;n.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const p=[];for(const e of h){const i=t.data.curved?g:(u.get(e.id)||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,i,B))}const E=new en(p);return E.varying=B,E}};function Bo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}let po;var Eo;(Eo=po||(po={})).Error="Error",Eo.Warning="Warning",Eo.Info="Info";class mo extends Or{constructor(t){super(),Bo(this,"update",void 0),Bo(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class fo{constructor(t,e,i,A,n,a,r,s,o,c,l=!1,g,h=!1){Bo(this,"reloadedState",void 0),Bo(this,"transaction",void 0),Bo(this,"ownerCustomer",void 0),Bo(this,"updateTransaction",void 0),Bo(this,"confirmedDesign",void 0),Bo(this,"editedSteps",void 0),Bo(this,"informationResults",void 0),Bo(this,"layouts",void 0),Bo(this,"mandatorySteps",void 0),Bo(this,"pendingUpdates",void 0),Bo(this,"selectionCost",void 0),Bo(this,"workflow",void 0),Bo(this,"stepSpecificServices",void 0),Bo(this,"previewService",void 0),Bo(this,"profanityFilter",void 0),Bo(this,"pollers",void 0),Bo(this,"commandContext",void 0),Bo(this,"stepElements",void 0),Bo(this,"stepInitialised",void 0),Bo(this,"stepMetadata",void 0),Bo(this,"stepSelections",void 0),Bo(this,"storage",void 0),Bo(this,"confirmCallbacks",void 0),Bo(this,"editedCallbacks",void 0),Bo(this,"elementsCallbacks",void 0),Bo(this,"informationResultCallbacks",void 0),Bo(this,"initCallbacks",void 0),Bo(this,"makingAdjustmentsCallback",void 0),Bo(this,"mandatoryCallbacks",void 0),Bo(this,"metadataCallbacks",void 0),Bo(this,"selectionCallbacks",void 0),Bo(this,"stepSpecificStorageCallbacks",void 0),Bo(this,"storageCallbacks",void 0),Bo(this,"currentVariationRecordCallbacks",void 0),Bo(this,"variationRecordCallbacks",void 0),Bo(this,"allScenes",void 0),Bo(this,"product",void 0),Bo(this,"invalidModelVariants",void 0),Bo(this,"currentAdjustingStepId",void 0),Bo(this,"renderableContextService",void 0),Bo(this,"workflowStatePromiseQueue",new Jr(1)),Bo(this,"variationRecords",[]),Bo(this,"currentVariationRecord",void 0),Bo(this,"initializationPromise",void 0),Bo(this,"initialized",!1),Bo(this,"readOnly",!1),Bo(this,"modelContainer",void 0),Bo(this,"isReloadedTransaction",!1),Bo(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,i]of e)i.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=n,this.commandContext=A,this.reloadedState=c,this.transaction=a,this.readOnly=l,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=r,this.previewService=s,this.modelContainer=g,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=o,this.currentVariationRecord=null,this.isReloadedTransaction=h,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(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Ts(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=Ls(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:A,commands:n}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new en(n),!0),this.stepElements={...this.stepElements,...A},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,i=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),i&&this.modelContainer?.executeAnimation(i)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||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 e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.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,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].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}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}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((e=>{const i=this.stepSelections[e.stepName];i&&i.selectedVariants&&i.selectedVariants.length>0&&(t[e.stepName]={selections:i.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=Te();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.previewService=t,!this.getProduct().modelUrl)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}}async updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!F(C)(i,this.storage)){this.storage=i;const e=new ZA(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const i={stepName:e.stepName};i.storage=this.storage[e.stepName],i.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(i)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new aa("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(F(e)(t.transaction))),A=t.variation;if(!A)return{transaction:i};const n={layouts:{},serializableWorkflow:{steps:[]},...F(e)(A)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((i,A)=>{const n=[...t[A]||[]];return e.forEach((t=>{const e=n.findIndex((e=>e.id===t.id));e>-1&&n.splice(e,1)})),i[A]=n,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Js(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Js(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const i=this.product;if(!i)return Promise.resolve({stepElements:{},commands:[]});const A=async(t,e,i)=>{if(t.type===si.SilentIllustration){return{step:t,results:await new qs(t,e).trigger()}}if(t.type===si.ProductOverlay){return{step:t,results:await new qs(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},n=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},r=[];for(const t of n)this.markStepsAsInitialised([t.stepName]),e||r.push(A(t,this.layouts,i));const s=await Promise.all(r);for(const t of s)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,e){return e.find((e=>e.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 rn(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,A){const n=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Js(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,r=Ls(a,n),s=Ls(a,this.stepSelections),o=r.map((t=>t.silentSteps)).flat(),c=s.map((t=>t.silentSteps)).flat().filter((t=>!o.some((e=>e.stepName===t.stepName))));o.forEach((t=>{Js(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:g,commands:h}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...g,[t]:i},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===si.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new rn(t.id))),new ZA(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new en(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),A&&await A()}async ensureStepsAreLoaded(){const t=[],e=Ls(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const i of e)if(!this.stepInitialised[i.stepName])switch(this.stepInitialised[i.stepName]=!0,i.type){case si.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case si.DigitalContent:t.push(to.init(i,this,this.reloadedState));break;case si.Frame:case si.Photo:{const e=new Ws(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(io.init(i,this,this.reloadedState))}break;case si.Illustration:t.push(Ao.init(i,this,this.reloadedState));break;case si.Material:t.push(no.init(i,this,this.reloadedState));break;case si.Model:t.push(ao.init(i,this,this.reloadedState));break;case si.Module:this.stepSpecificServices[i.stepName]={module:await os(i.data.module)},t.push(ro.init(i,this,this.reloadedState));break;case si.Picture:t.push(so.init(i,this,this.reloadedState));break;case si.Question:t.push(oo.init(i,this,this.reloadedState));break;case si.Shape:t.push(co.init(i,this,this.reloadedState));break;case si.Text:t.push(wo.init(i,this,this.reloadedState))}const i=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),A=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),n=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));A&&A.length>0&&this.commandContext.apply(new en(A),!0);for(const t of n)await t();n.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 e of this.selectionCallbacks)e({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((e=>e(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)})),this.render3DScene()}traversableScenes(){return zs(this.allScenes,this.stepSelections)}}function Co(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Qo{constructor(t){Co(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function yo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Do{constructor(t,e){yo(this,"manager",void 0),yo(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Do.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Do.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new Qo(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new Qo(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new Qo(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),i=this.step.data.modelAnimation,A=this.step.data.lookAtAnimation;t&&A&&t.executeCameraAnimation(A),e&&i&&e.executeAnimation(i)}}function Io(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}yo(Do,"updateState",new Map);const xo=t.gql`
|
|
470
|
+
`,Us=t=>{const e=[];for(const i of t.steps)switch(i.type){case si.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Frame:const t=i.data;t.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),t.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Illustration:const A=i.data;A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColors&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case si.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case si.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Text:const n=i.data;n.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColor&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Gs=[si.SilentIllustration,si.ProductOverlay],Ts=async(t,e,i)=>{const A=[];t.introduction&&A.push({name:"Introduction",title:t.name,renderableSteps:[{type:si.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of t.steps){if(e.bulkScene){let t=!1;switch(i.type){case si.DigitalContent:i.data.varyUpload&&(t=!0);break;case si.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case si.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case si.Material:i.data.varySelection&&(t=!0);break;case si.Model:i.data.varySelection&&(t=!0);break;case si.Picture:i.data.varySelection&&(t=!0);break;case si.Question:i.data.varySelections&&(t=!0);break;case si.Shape:i.data.varySelection&&(t=!0);break;case si.Text:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const n=Os(i.stepName,t.stepGroups);if(n){const t=A.find((t=>t.name===n.name));t?Gs.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):A.push({name:n.name,title:n.name,renderableSteps:Gs.includes(i.type)?[]:[i],silentSteps:Gs.includes(i.type)?[i]:[]})}else A.push({name:i.stepName,title:i.stepTitle,renderableSteps:Gs.includes(i.type)?[]:[i],silentSteps:Gs.includes(i.type)?[i]:[]})}if(e.bulkScene){const n=i?.product?.bulkConfiguration;A.push({name:"Bulk",title:n?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:si.Bulk,stepName:"Bulk",stepTitle:n?.stepTitle??e.bulkSceneTitle,helpText:n?.helpText,data:{aspects:Us(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&A.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:si.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),A},Os=(t,e)=>e.find((e=>e.stepNames.includes(t))),Js=(t,e)=>(t.conditions||[]).every((t=>{const i=e[t.targetStepName];if(i&&i.selectedVariants){const e=i.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),Ls=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Js(t,e))),silentSteps:t.silentSteps.filter((t=>Js(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),zs=async(t,e)=>{const i=Ls(t,e),A=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===si.Model||e.type===si.Material||e.type===si.Picture||e.type===si.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&A.push(e.stepName)}else A.push(e.stepName);const n=i.filter((t=>t.renderableSteps.filter((t=>A.includes(t.stepName))).length>0));for(const t of n)t.renderableSteps=t.renderableSteps.filter((t=>A.includes(t.stepName)));return n};function js(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Vs(t,e,i,A){const n=i.width*t.zoom,a=i.height*t.zoom;if(A){const A=t,n=Math.max(e.width/i.width,e.height/i.height);A.zoom=Math.max(n,t.zoom);const a=i.width*A.zoom,r=i.height*A.zoom;return A.x=Ks(t.x,e.width-a,0),A.y=Ks(t.y,e.height-r,0),A}const r=t;return r.x=Ks(r.x,-n,e.width),r.y=Ks(r.y,-a,e.height),r}function Ks(t,e,i){return Math.min(Math.max(t,e),i)}class Ws{constructor(t){js(this,"offsets",void 0),js(this,"forceImageCover",void 0),js(this,"targetElements",void 0),js(this,"imageData",void 0),js(this,"frameData",void 0),js(this,"_debouncedUpdateFrameOffsets",void 0),js(this,"minZoomScale",[.03]),js(this,"maxZoomScale",[20]),js(this,"onFrameDataChangeListeners",void 0),js(this,"onZoomChangeListeners",void 0),js(this,"workflowManager",void 0),js(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=F(I)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let i=0;i<e.currentFrameSources.length;i++){const A=e.currentFrameSources[i],n=await Rn(A);F(C)(n,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=n,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,i)=>{const A=bn.get(e);A&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=A)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,A){this.imageData&&this.offsets&&this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((A,n)=>{const a=(e[n]-this.offsets[n].x)/this.offsets[n].zoom,r=(i[n]-this.offsets[n].y)/this.offsets[n].zoom,s={x:e[n]-a*t[n],y:i[n]-r*t[n],zoom:this.imageData.width*t[n]/this.imageData.width};this.offsets[n]=Vs(s,A,this.imageData,this.forceImageCover)})),this.updateOffsets(this.offsets,A),this.onZoomChangeListeners.forEach((e=>e(t))))}setPatternData(t){if(t&&this.frameData){this.recalculateOffsets(t);const e=this.offsets.map(((e,i)=>Vs(e,this.frameData[i],t,this.forceImageCover)));this.updateOffsets(e)}this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==t.length)throw new aa("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,i)=>t[i].x!==e.x||t[i].y!==e.y||t[i].zoom!==e.zoom))?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Vs(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,i,A,n){if(!i||0===i.length||i.some((t=>!t)))throw new aa("Frame data not set. This is a bug");if(!this.workflowManager)throw new aa("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();A.forEach(((i,A)=>{a(new un(i,e,t[A]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),n&&n()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,i)=>{const A=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=A,this.maxZoomScale[i]=2.5*A):(this.minZoomScale[i]=A/10,this.maxZoomScale[i]=2.5*A)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=kn(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function Xs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class qs{constructor(t,e,i){Xs(this,"configuration",void 0),Xs(this,"layouts",void 0),Xs(this,"product",void 0),Xs(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new ta(t);let i="";if(this.configuration.type===si.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new Aa(this.configuration,"Couldn't find an asset for product overlay step")}const A=this.evaluateAssetType();if(A===ze.Image){const i=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const n={stepName:this.configuration.stepName,id:Te(),src:i,type:A,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===si.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:n.id,region:t},command:new an(n,e)}}{const n=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:i,a=async()=>new Promise(((t,e)=>{n?Ki(n).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await GA(await a()),s={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await Kn(r.svg),src:n,svg:r.svg,colors:r.colors,type:A,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===si.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new an(s,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new Aa(this.configuration,"Missing regions.");if(this.configuration.type===si.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===si.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new ta(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===si.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")?ze.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),ze.Illustration)}}const Zs=async t=>{const e=`${ua.getServicesApiUrl()}/shortener`;try{const i=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await i.json()).shortUrl}catch(t){throw console.error(t),new oa("Failed to shorten URL, see console.")}};function $s(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class _s{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,e,i,A=3e3,n=10){$s(this,"pollingId",void 0),$s(this,"attempts",void 0),$s(this,"interval",void 0),$s(this,"maxAttempts",void 0),$s(this,"predicate",void 0),$s(this,"onSuccess",void 0),$s(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=A,this.maxAttempts=n,this.poll()}}const to=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{const i=A?.storage?.videoShortUrl,n=A?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:n})}))}async regenerateQRCode(t,e,i,A,n,a,r,s,o){if(e||""===i||""!==A)o(!1);else{const e=async()=>{const t=(await Fa([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new _s((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new ia(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>s(new rn(t.id))));const l="http"===a.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+a.data.baseUrl);g.searchParams.append("video",btoa(JSON.stringify([c]))),g.pathname=g.pathname+("/"===g.pathname.slice(-1)?"":"/");const h=g.toString();if(h.length>=2e3)throw new oa("Cannot create QR code, URL too long.");const d=await Zs(h);if(r(d),!a.data||!a.data.regions)throw new Aa(a,"Missing regions.");const u=await this.regionElements(a),w=await this.command(d,u,n,a.stepName);w&&(w.command&&n.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await n.setSelectionsAndElements(a.stepName,[],u,(async()=>{n.updateStorage(a.stepName,{videoShortUrl:d,videoUrl:A}),o(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,A){const n=i.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,i=n.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new ta(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new an({stepRegion:e,stepName:A,id:t.id,src:a,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new en(r),followup:async()=>{}}}};function eo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const io=new class{constructor(){eo(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Pn(e);const i=t.asset;if(!i)throw new ea(t);const A=i.fileLink;if(A)return Ki(A);throw new ia(i)}))}async init(t,e,i){if(i)return await this.reload(t,e,i),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const i=t.option,A=Ha.getDefaultVariant(i);return A?this.selectVariantCommand(t,A,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const i=t.data.regions.map((t=>Pn(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(A){const i=async()=>{const i=A.storage?.framePatternSrc,n=A.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:n,framePatternSrc:i}),i){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,A),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(n?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(n)}e.setMandatoryFulfilled(t.stepName,!0)};if(A.selectedVariants&&A.selectedVariants.length>0){const a=A.selectedVariants[0].id;if(t.option&&a){const A=t.option.variants?.find((t=>t.id===a));A&&await e.setSelectionsAndElements(t.stepName,[A],n,(async()=>{const n=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(A,t))));e.updateStorage(t.stepName,{currentFrameSources:n}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],n,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new _s((async()=>{const t=(await Pa.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Pa.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new oa("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,A,n){const a=await this.selectVariantCommand(t,e,i,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,e,i,A){return new an({id:t,type:ze.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/A.frameData.width,scaleY:e.height/A.frameData.height,path:A.frameData.path,dataWidth:A.frameData.width,dataHeight:A.frameData.height,stepRegion:e,stepName:A.stepName,disablePlaceholder:A.disablePlaceholder,focalBlur:A.focalBlur,focalBlurStrength:A.focalBlurStrength,focalBlurRadius:A.focalBlurRadius,pattern:A.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await Un(t),A=i.width,n=i.height,a={src:t,width:A,height:n,aspect:A/n};Fn.set(t,a),e.setPatternData(a)}else{const i=await Vi(t),A=await Mn(i),n={src:t,width:A.width,height:A.height,aspect:A.width/A.height};Fn.set(t,n),e.setPatternData(n)}}async selectVariantCommand(t,e,i,A,n,a){const r=A.getStepSpecificServices(t.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");const s=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));n&&n(!0);const o=await Promise.all(t.data.regions.map((async(e,n)=>{const a=await Rn(s[n]),o=r.getImageData(),c=i.map((t=>new rn(t.id))),l=o?kn(o,a):void 0,g=o?{id:Te(),src:o.src,x:l?.x||0,y:l?.y||0,width:o.width,height:o.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=A.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new ta(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:a,pattern:g,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:h,region:e},removeExistingCommands:c}}))),c=o.map((t=>t.command)),l=o.map((t=>t.removeExistingCommands)).flat();return{command:new en([...c,...l]),followup:async()=>{n&&n(!1),await A.setSelectionsAndElements(t.stepName,e?[e]:[],[...o.map((t=>t.regionEl))],(async()=>{if(A.updateStorage(t.stepName,{currentFrameSources:s}),a){const e=A.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(a,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const i=t.fileLink;if(i)return i;throw new ia(t)}async loadPatternFromAsset(t,e,i){const A=this.patternSource(t),n=i.markUpdatePending(),a=i.getStepSpecificServices(e.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,a),i.updateMetadata(e.stepName,{image:A}),i.updateStorage(e.stepName,{framePatternSrc:A}),i.markUpdateCompleted(n)}};const Ao=new class{async getIllustrationBody(t){return new Promise((e=>{Ki(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,A){return new an({stepRegion:e,stepName:A.stepName,colors:A.svg.colors,id:t,src:A.src,svg:A.svg.svg,cachedObjectURL:A.objectURL,type:ze.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},i)}getColors(t,e){const i=e.getRegionElements(t.stepName)||[];if(0===i.length)return[];try{return VA(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const A=t.option;if(!A)return null;if(i)return this.reload(t,e,i);{const i=Ha.getDefaultVariant(A);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(!a||!i)throw new Error("Required illustration variant no longer available");{const r=a.variants?.find((t=>t.id===i));if(r){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[r],i,(async()=>{e.updateMetadata(t.stepName,{colors:A.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const i=t.data.colorOption;return i&&i?i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,i,A,n){const a={};for(const[t,e]of n.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor};const r=UA(t,e,i,a),s=await Kn(r),o=[];for(const t of A){for(const[e,i]of n.entries())o.push(new Bn(t,e,i));o.push(new pn(t,r,s))}return new en(o)}async changeColors(t,e,i,A,n){if(0===e.length)return;const a=VA(e[0].id,A().map((t=>t.layoutState))),r={...a.colors},s={};Object.entries(r).forEach((([t,e])=>{const i={browserValue:e.browserValue},A=e.spotColor;A&&(i.spotColor={profileName:A.profileName,namedColor:A.namedColor}),s[t]=i}));for(const[t,e]of n.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor},s[t]={browserValue:e};let o=Array.from(Object.values(r)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{o=o.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:o});const l=new Map;if(Object.entries(r).forEach((([t,e])=>{l.set(t,e.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(a.svg,a.width,a.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:s}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,A,n){const a=await this.selectVariantCommand(t,e,i,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,i,A,n){if(!t.data||!t.data.regions)throw new Aa(t,"Missing regions.");A(!0);const a=i.map((t=>new rn(t.id)));n.setMandatoryFulfilled(t.stepName,!1);const r=e.asset;if(!r)throw new ea(e);const s=r.fileLink;if(!s)throw new ia(r);const o=await GA(await this.getIllustrationBody(s)),c=await Kn(o.svg),l=t.data.regions.map((e=>{const i=n.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new ta(e);const A=Te();return{regionElement:{id:A,region:e},command:this.getCreateElementCommand(A,e,i,{stepName:t.stepName,src:s,objectURL:c,svg:o})}})),g=[...l.map((t=>t.command)),...a];let h=Array.from(Object.values(o.colors)).map((t=>t.browserValue));const d=t.data.colorOption;return d&&d.variants?.forEach((t=>{h=h.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),n.updateMetadata(t.stepName,{colors:h}),{command:new en(g),followup:async()=>{await n.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{n.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const no=new class{async init(t,e,i){const A=t.option;if(!A)throw new _n(t);if(i)await this.reload(t,e,i);else{const i=Ha.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(!a)throw new _n(t);if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(i){const A=a.variants?.find((t=>t.id===i));if(A){const i=A.material,r=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],r,(async()=>{const A=e.getModelContainer();if(A){const n=t.data.targetMaterials.map((t=>A.applyMaterialVariant(t,a.id||"",i||{})));Promise.all(n).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){const n=i.getModelContainer();A(!0);const a=e.material;if(!a)throw A(!1),new ea(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{n&&t.data.targetMaterials.forEach((e=>{t.option&&n.applyMaterialVariant(e,t.option.id||"",a)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ao=new class{async init(t,e,i){const A=t.option;if(!A)throw new _n(t);if(i)await this.reload(t,e,i);else{const i=Ha.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const A=a.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const n=A.asset?.fileLink;if(!n)throw new ea(A);await i.applyModelVariant(t.option.id||"",{model:n,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){A(!0);const n=e.asset?.fileLink;if(!n)throw new ea(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=i.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:n,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ro=new class{async init(t,e,i){return i?(await this.reload(t,e,i),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{e.updateStorage(t.stepName,{text:A?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==A?.storage?.text)}))}async changeText(t,e,i,A,n){const a=await this.changeTextCommand(t,e,i,A,n);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,e,i,A,n){const a=i.getRegionElements(t.stepName),r=i.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const s=i.getProfanities();if(!this.validateInput(t,e,s,n))return i.setMandatoryFulfilled(t.stepName,!1),console.error(A),null;if(i.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(t.stepName,{text:e});const o=(e,A,n)=>{const a=n||Te(),r=i.getLayouts().find((t=>t.panelId===A.panelId));if(!r)return console.error(`Can not find layout for region: ${A.panelId}`),null;const s=[];return n&&s.push(new rn(a)),s.push(new an({stepRegion:A,stepName:t.stepName,colors:{},id:a,svg:e,type:ze.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},r)),{id:a,region:A,command:new en(s)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const i=r.svgPrint(e,t.region);return o(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new en(t),followup:async()=>{}}}{const A=t.data.regions.map((t=>o(r.svgPrint(e,t),t))),n=A.filter((t=>!!t)).map((t=>t&&t.command));return{command:new en(n),followup:async()=>{const e=A.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,A){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return A("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return A("Unsupported characters."),!1;const n=(0,x.split)(e.toLowerCase());for(const t of n)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return A("Blocked profanity."),!1}return A(""),!0}};const so=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else if(A.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,A.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const A=a.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=e.asset;if(!n)throw new ea(e);const a=n?.fileLink;if(!a)return console.error("No URL for picture!"),null;A(!0),i.setMandatoryFulfilled(t.stepName,!1);const r=i.getRegionElements(t.stepName).map((t=>new rn(t.id))),s=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new ta(e);const n=Te();return{regionElement:{id:n,region:e},command:new an({stepName:t.stepName,stepRegion:e,id:n,src:a,type:ze.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},A)}}));return{command:new en([...r,...s.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],s.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const oo=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=A.variants;if(Ha.getDefaultVariant(A)){const n=i?.find((t=>t.id===A.defaultVariant?.id));return this.selectVariantLambda(t,n?.id||"",e)}}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(n&&i){const A=n.variants?.find((t=>t.id===i));A&&await e.setSelectionsAndElements(t.stepName,[A],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const A=await this.selectVariantLambda(t,e,i);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i){const A=t.option;if(!A)return null;const n=A.variants;if(!n)return null;const a=n.length>1?n.find((t=>t.id===e)):n[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 i.setSelectionsAndElements(t.stepName,[a],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};const co=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,i){const A=t.option;if(!A)throw new _n(t);if(!i){const i=Ha.getDefaultVariant(A);if(!i)return null;const n={fill:i.color,stroke:i.color,variant:i};return this.selectVariantCommand(t,n,[],e)}return await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const A=a.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.updateStorage(t.stepName,{colour:A.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=A.getLayouts();if(i.length>0){const a=t=>{const i=t.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new ta(i);const A=e.variant?.color;return A?new Bn(t.id,"spiff-fill-shape",A):(console.error("Failed to change color."),null)},r=i.map(a).filter((t=>!!t));return{command:new en(r),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),A.updateStorage(t.stepName,{colour:e.fill||""})}}}{const i=i=>{const A=n.find((t=>t.panelId===i.panelId));if(!A)throw new ta(i);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="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=Te();return{id:s,region:i,command:new an({stepRegion:i,stepName:t.stepName,colors:r,id:s,svg:a,type:ze.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},a=t.data.regions.map(i),r=a.filter((t=>!!t)).map((t=>t?.command)),s=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new en(r),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{A.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function lo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class go extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=go.name}}const ho=["‘","’","“","”","\n"];class uo extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=uo.name}}const wo=new class{constructor(){lo(this,"cachedColors",new Map),lo(this,"filterUnsupportedCharacters",((t,e)=>{let i=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const A=[],n=e?oA(e):void 0;if(n){const t=i.split("").filter((t=>!ho.includes(t))).join(""),e=t.split("").map((t=>n.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&A.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<A.length;t++)i=i.replaceAll(A[t],"");return i})),lo(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),lo(this,"getErrorsForText",((t,e,i)=>{const A=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&A.push({localizationKey:"workflow.steps.text.characterLimit"});const n=i.getProfanities(),a=(0,x.split)(t.toLowerCase());for(const t of a)for(const e in n){if(t===n[e].toLowerCase().replace(/\s/g,"")){A.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&A.push({localizationKey:"workflow.steps.text.multipleLines"}),A}))}async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),n=i?.asset?.fileLink,a=n?await Hn(n):void 0,r=a?{src:a.src,height:a.height,width:a.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:r}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const s=Ha.getDefaultVariant(A);if(s)return this.selectVariantCommand(t,s,{},[],e,(()=>{}),(()=>{}),r)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>VA(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const i=t.data.colorOption;if(i){const e=i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher();e.variant?A.updateMetadata(t.stepName,{color:e.variant.name}):A.updateMetadata(t.stepName,{color:e.fill});const a=t.data.colorOption,r=a?this.createTextFillSpotColor(a,e.variant):void 0;a?A.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:a.colorProfile?.key}):A.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");n(new on(t.id,e.fill,r))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const i=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(i.map((async e=>{const i=await Hn(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher(),a=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));A.updateMetadata(t.stepName,{fillImage:a?.name}),A.updateStorage(t.stepName,{fillImage:e});for(const t of i){n(new cn(t.id,e))}}getProcessedInput(t,e,i){const A=i?t:this.injectReplaceableText(t,e);return CA(A,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,A){const n=A.getStepStorage(i.stepName),a=this.getProcessedInput(t,i.data,!!n.customiseAllText),r={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,A)};if(r.errors.length>0)return r.helperText=r.errors[0].localizationKey,r;const s=(i.data.maxLength-a.length).toString();r.helperText=`${s} characters remaining`;const o=A.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new aa("Failed to resolve font data for text.");const[e,A]=Jn(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,A);const n=i.data.curved?a:(A||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,n,o))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return r.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),r}return A.updateStorage(i.stepName,{text:t}),A.updateMetadata(i.stepName,{text:a}),n.defaultCleared&&A.setMandatoryFulfilled(i.stepName,!0),r.command=new en(c),r.command.varying=o,r}async selectVariant(t,e,i,A,n){const a=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,A,n);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),A=t.lastIndexOf("/"),n=t.slice(A+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:n,namedColor:e.namedColor}}}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(a&&i){const r=a.variants?.find((t=>t.id===i));if(r){const i=await this.fontDataFromVariant(r),a=n.map((t=>({id:t.id,region:t.stepRegion}))),s=A.storage?.color,o=A.storage?.text;await e.setSelectionsAndElements(t.stepName,[r],a,(async()=>{e.updateMetadata(t.stepName,{color:s,text:o}),e.updateStorage(t.stepName,{text:o,inputText:o});const A=n.map((t=>new hn(t.id,i))),a=new en(A);e.getCommandDispatcher()(a),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=wo.updateInputText(o||"",n,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ha.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ha.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ha.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ea(t);const i=e.fileLink;if(!i)throw new ia(e);return{assetUrl:i,name:(await rA(i)).names.fullName.en}}async selectVariantCommand(t,e,i,A,n,a,r,s){const o=n.markUpdatePending(),c=await this.fontDataFromVariant(e);if(A.length>0){const l=A.map((t=>new hn(t.id,c)));if(s){const t=A.map((t=>new cn(t.id,s)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,n,!!i.customiseAllText,a,r);g&&l.push(g);return{command:new en(l),followup:async()=>{n.markUpdateCompleted(o),await n.setSelectionsAndElements(t.stepName,[e],A)}}}{const A=await this.createTextboxRegions(t.stepName,e,t.data,c,i,n),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A[0]?.newElement.input||i.text||t.data.defaultText||"",i,n,!!i.customiseAllText,a,r),g=A.flatMap((t=>t.commands));if(s){const t=A.map((t=>new cn(t.regionElement.id,s)));g.push(...t)}l&&g.push(l);return{command:new en(g),followup:async()=>{n.markUpdateCompleted(o)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,A,n,a){if(!i||!i.regions)throw new Error("Step data not supplied");const r=a.getTransaction().bulk&&i.varyText||!1,s=r?"":n.text||i.defaultText||"",o=this.getProcessedInput(s,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=a.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new uo("Failed to find layout for region: "+e.panelId);const g=i.colorOption;let h;if(g&&g.variants){const e=g.variants.find((t=>t.id===g.defaultVariant?.id))||g.variants[0];h=this.createTextFillSpotColor(g,e),a.updateStorage(t,{colorProfileAssetKey:g.colorProfile?.key})}const d=await this.getDefaultColor(i),u=d||"#000000",w={stepRegion:e,stepName:t,align:this.textAlign(i),fill:n.color?n.color:u,fontSize:i.size||30,fontData:A,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:o,input:s,type:ze.Textbox,vertical:i.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths,fillSpotColorDefinition:h},B=[],p=new Map,E=new Map;if(!w.fontData)throw new aa("Failed to resolve font data for text.");const[m,f]=Jn(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[o],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,m),E.set(w.id,f);const C=i.curved||i.vertical?o:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(m,i,w.id,C,r));const Q=new an(w,c);return Q.varying=r,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:A}}catch(t){throw console.log(t),new go("Error adding font to region")}}))).catch((t=>{throw t instanceof go?(or.setLatestToast("Failed to load font.",po.Error),t):t instanceof uo?t:new Error(t)}));return await a.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:s}),a.updateStorage(t,{text:s})})),c}generateTextChangeCommandsForRegion(t,e,i,A,n){const a=[],r=new wn(i,A);if(r.varying=n,a.push(r),!e.size){const e=new ln(i,t);e.varying=n,a.push(e)}const s=new en(a);return s.varying=n,s}async changeInputTextWithRegion(t,e,i,A,n,a,r,s,o,c){const l=(A||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,r),h=a.getRegionElements(t.stepName),d=new Map,u=new Map;for(const A of h)if(A.region){const[n,a]=Jn(e,i,A.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(A.id,n),u.set(A.id,a)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=a.getProfanities(),i=(0,x.split)(g.toLowerCase());for(const t of i)for(const i in e){if(t===e[i].toLowerCase().replace(/\s/g,""))return s(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void o(w.error);if(o(`${w.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:l}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=a.getTransaction().bulk&&t.data.varyText||!1;n.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const p=[];for(const e of h){const i=t.data.curved?g:(u.get(e.id)||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,i,B))}const E=new en(p);return E.varying=B,E}};function Bo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}let po;var Eo;(Eo=po||(po={})).Error="Error",Eo.Warning="Warning",Eo.Info="Info";class mo extends Or{constructor(t){super(),Bo(this,"update",void 0),Bo(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class fo{constructor(t,e,i,A,n,a,r,s,o,c,l=!1,g,h=!1){Bo(this,"reloadedState",void 0),Bo(this,"transaction",void 0),Bo(this,"ownerCustomer",void 0),Bo(this,"updateTransaction",void 0),Bo(this,"confirmedDesign",void 0),Bo(this,"editedSteps",void 0),Bo(this,"informationResults",void 0),Bo(this,"layouts",void 0),Bo(this,"mandatorySteps",void 0),Bo(this,"pendingUpdates",void 0),Bo(this,"selectionCost",void 0),Bo(this,"workflow",void 0),Bo(this,"stepSpecificServices",void 0),Bo(this,"previewService",void 0),Bo(this,"profanityFilter",void 0),Bo(this,"pollers",void 0),Bo(this,"commandContext",void 0),Bo(this,"stepElements",void 0),Bo(this,"stepInitialised",void 0),Bo(this,"stepMetadata",void 0),Bo(this,"stepSelections",void 0),Bo(this,"storage",void 0),Bo(this,"confirmCallbacks",void 0),Bo(this,"editedCallbacks",void 0),Bo(this,"elementsCallbacks",void 0),Bo(this,"informationResultCallbacks",void 0),Bo(this,"initCallbacks",void 0),Bo(this,"makingAdjustmentsCallback",void 0),Bo(this,"mandatoryCallbacks",void 0),Bo(this,"metadataCallbacks",void 0),Bo(this,"selectionCallbacks",void 0),Bo(this,"stepSpecificStorageCallbacks",void 0),Bo(this,"storageCallbacks",void 0),Bo(this,"currentVariationRecordCallbacks",void 0),Bo(this,"variationRecordCallbacks",void 0),Bo(this,"allScenes",void 0),Bo(this,"product",void 0),Bo(this,"invalidModelVariants",void 0),Bo(this,"currentAdjustingStepId",void 0),Bo(this,"renderableContextService",void 0),Bo(this,"workflowStatePromiseQueue",new Jr(1)),Bo(this,"variationRecords",[]),Bo(this,"currentVariationRecord",void 0),Bo(this,"initializationPromise",void 0),Bo(this,"initialized",!1),Bo(this,"readOnly",!1),Bo(this,"modelContainer",void 0),Bo(this,"isReloadedTransaction",!1),Bo(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,i]of e)i.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=n,this.commandContext=A,this.reloadedState=c,this.transaction=a,this.readOnly=l,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=r,this.previewService=s,this.modelContainer=g,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=o,this.currentVariationRecord=null,this.isReloadedTransaction=h,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(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Ts(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=Ls(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:A,commands:n}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new en(n),!0),this.stepElements={...this.stepElements,...A},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,i=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),i&&this.modelContainer?.executeAnimation(i)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||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 e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.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,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].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}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}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((e=>{const i=this.stepSelections[e.stepName];i&&i.selectedVariants&&i.selectedVariants.length>0&&(t[e.stepName]={selections:i.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=Te();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.previewService=t,!this.getProduct().modelUrl)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}}async updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!F(C)(i,this.storage)){this.storage=i;const e=new ZA(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const i={stepName:e.stepName};i.storage=this.storage[e.stepName],i.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(i)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new aa("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(F(e)(t.transaction))),A=t.variation;if(!A)return{transaction:i};const n={layouts:{},serializableWorkflow:{steps:[]},...F(e)(A)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((i,A)=>{const n=[...t[A]||[]];return e.forEach((t=>{const e=n.findIndex((e=>e.id===t.id));e>-1&&n.splice(e,1)})),i[A]=n,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Js(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Js(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const i=this.product;if(!i)return Promise.resolve({stepElements:{},commands:[]});const A=async(t,e,i)=>{if(t.type===si.SilentIllustration){return{step:t,results:await new qs(t,e).trigger()}}if(t.type===si.ProductOverlay){return{step:t,results:await new qs(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},n=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},r=[];for(const t of n)this.markStepsAsInitialised([t.stepName]),e||r.push(A(t,this.layouts,i));const s=await Promise.all(r);for(const t of s)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,e){return e.find((e=>e.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 rn(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,A){const n=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Js(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,r=Ls(a,n),s=Ls(a,this.stepSelections),o=r.map((t=>t.silentSteps)).flat(),c=s.map((t=>t.silentSteps)).flat().filter((t=>!o.some((e=>e.stepName===t.stepName))));o.forEach((t=>{Js(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:g,commands:h}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...g,[t]:i},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===si.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new rn(t.id))),new ZA(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new en(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),A&&await A()}async ensureStepsAreLoaded(){const t=[],e=Ls(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const i of e)if(!this.stepInitialised[i.stepName])switch(this.stepInitialised[i.stepName]=!0,i.type){case si.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case si.DigitalContent:t.push(to.init(i,this,this.reloadedState));break;case si.Frame:case si.Photo:{const e=new Ws(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(io.init(i,this,this.reloadedState))}break;case si.Illustration:t.push(Ao.init(i,this,this.reloadedState));break;case si.Material:t.push(no.init(i,this,this.reloadedState));break;case si.Model:t.push(ao.init(i,this,this.reloadedState));break;case si.Module:this.stepSpecificServices[i.stepName]={module:await os(i.data.module)},t.push(ro.init(i,this,this.reloadedState));break;case si.Picture:t.push(so.init(i,this,this.reloadedState));break;case si.Question:t.push(oo.init(i,this,this.reloadedState));break;case si.Shape:t.push(co.init(i,this,this.reloadedState));break;case si.Text:t.push(wo.init(i,this,this.reloadedState))}const i=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),A=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),n=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));A&&A.length>0&&this.commandContext.apply(new en(A),!0);for(const t of n)await t();n.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 e of this.selectionCallbacks)e({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((e=>e(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)})),this.render3DScene()}traversableScenes(){return zs(this.allScenes,this.stepSelections)}}function Co(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Qo{constructor(t){Co(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function yo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Do{constructor(t,e){yo(this,"manager",void 0),yo(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Do.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Do.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new Qo(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new Qo(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new Qo(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),i=this.step.data.modelAnimation,A=this.step.data.lookAtAnimation;t&&A&&t.executeCameraAnimation(A),e&&i&&e.executeAnimation(i)}}function Io(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}yo(Do,"updateState",new Map);const xo=t.gql`
|
|
471
471
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
472
472
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
473
473
|
id
|
|
@@ -670,7 +670,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
|
|
|
670
670
|
id
|
|
671
671
|
}
|
|
672
672
|
}
|
|
673
|
-
`;function ac(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class rc{constructor(t){ac(this,"bundle",void 0),ac(this,"handleCache",{}),this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const i=e.aspects.find((e=>e.name===t.targetAspectName));return!!i&&t.requiredVariantSelections.some((t=>t===i.value))}))}async createHandle(t){switch(t.type){case ei.FileUpload:return new oc(this.bundle,t);case ei.Option:const e=t.entityId?await Ha.getOption(t.entityId):void 0;return new lc(this.bundle,t,e);case ei.Text:return new cc(this.bundle,t)}}}class sc{constructor(t,e){ac(this,"bundle",void 0),ac(this,"property",void 0),this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){
|
|
673
|
+
`;function ac(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class rc{constructor(t){ac(this,"bundle",void 0),ac(this,"handleCache",{}),this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const i=e.aspects.find((e=>e.name===t.targetAspectName));return!!i&&t.requiredVariantSelections.some((t=>t===i.value))}))}async createHandle(t){switch(t.type){case ei.FileUpload:return new oc(this.bundle,t);case ei.Option:const e=t.entityId?await Ha.getOption(t.entityId):void 0;return new lc(this.bundle,t,e);case ei.Text:return new cc(this.bundle,t)}}}class sc{constructor(t,e){ac(this,"bundle",void 0),ac(this,"property",void 0),this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap((t=>t.getSteps().filter((t=>t.getRaw().globalPropertyAspectConfigurations?.some((t=>t.globalPropertyConfigurationId===this.bundle.getProductCollection()?.globalPropertyConfiguration?.id&&t.aspectName===this.property.name))))))}}class oc extends sc{constructor(t,e){super(t,e)}async selectImage(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.key),this.applyImageSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const i=await Pa.getLocalOrFromServer(e);return i?this.applyImageSelection(i,t):Promise.resolve()}async applyImageSelection(t,e){const i=this.getSharedSteps(e).map((e=>e.selectImage(t)));await Promise.all(i)}}class cc extends sc{constructor(t,e){super(t,e)}getText(){const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const i=this.getSharedSteps(e).map((e=>{e.setText(t)}));await Promise.all(i)}}class lc extends sc{constructor(t,e,i){super(t,e),ac(this,"optionResource",void 0),this.optionResource=i}getCurrentVariant(){if(!this.optionResource)return;const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!t)return;const e=this.optionResource.variants?.find((e=>e.id===t));return e?new Qo(e):void 0}getAvailableVariants(){return(this.optionResource?.variants?.filter((t=>t.enabled))||[]).map((t=>new Qo(t)))}getAllVariants(){return(this.optionResource?.variants||[]).map((t=>new Qo(t)))}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const i=this.optionResource?.variants?.find((t=>t.id===e));return i?this.applyVariantSelection(new Qo(i),t):Promise.resolve()}async applyVariantSelection(t,e){const i=this.getSharedSteps(e).map((e=>e.selectVariant(t)));await Promise.all(i)}}const gc=v.gql`
|
|
674
674
|
mutation CreateGlobalPropertyState($bundleId: String!) {
|
|
675
675
|
globalPropertyStateCreate(bundleId: $bundleId) {
|
|
676
676
|
id
|
|
@@ -700,7 +700,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
|
|
|
700
700
|
}
|
|
701
701
|
}
|
|
702
702
|
}
|
|
703
|
-
`;function uc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class wc{constructor(t,e){uc(this,"bundleId",void 0),uc(this,"globalPropertyState",void 0),uc(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,i){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=F(e)(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=i:this.globalPropertyState.aspects.push({name:t,value:i}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ya.getShadowGraphqlClient().mutate({mutation:hc,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ya.getShadowGraphqlClient().query({query:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ya.getShadowGraphqlClient().mutate({mutation:gc,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Bc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class pc{constructor(t,e){Bc(this,"client",void 0),Bc(this,"id",void 0),Bc(this,"name",void 0),Bc(this,"metadata",void 0),Bc(this,"productCollection",void 0),Bc(this,"globalConfiguration",void 0),Bc(this,"globalPropertyStateManager",void 0),Bc(this,"globalPropertyHandleService",void 0),Bc(this,"eventListeners",new Map),Bc(this,"workflowExperiences",[]),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new wc(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new rc(this)}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const i=this.eventListeners.get(t)||[],A=i.indexOf(e);A>-1&&i.splice(A,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await ya.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t);const i=await this.getGlobalProperties();await Promise.all(i.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");await ya.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,transactionId:e.id}}),this.workflowExperiences.splice(t,1)}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await ya.getShadowGraphqlClient().mutate({mutation:nc,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ya.getShadowGraphqlClient().mutate({mutation:ic,variables:{id:this.id,details:t,type:e||nr.Owner}})}async updateStakeholders(t){await ya.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ya.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}_setWorkflowExperiencesInternal(t){this.workflowExperiences=t}async updateBundle(){if(!(await ya.getShadowGraphqlClient().mutate({mutation:_o,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(i=>{const A=this.globalPropertyHandleService.applyConditionsFromState(i,t),n=this.globalPropertyHandleService.applyConditionsFromState(i,e);if(A.length!==n.length)return!0;for(let t=0;t<A.length;t++)if(A[t].getName()!==n[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function Ec(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const mc=t.gql`
|
|
703
|
+
`;function uc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class wc{constructor(t,e){uc(this,"bundleId",void 0),uc(this,"globalPropertyState",void 0),uc(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,i){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=F(e)(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=i:this.globalPropertyState.aspects.push({name:t,value:i}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ya.getShadowGraphqlClient().mutate({mutation:hc,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ya.getShadowGraphqlClient().query({query:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ya.getShadowGraphqlClient().mutate({mutation:gc,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Bc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class pc{constructor(t,e){Bc(this,"client",void 0),Bc(this,"id",void 0),Bc(this,"name",void 0),Bc(this,"metadata",void 0),Bc(this,"productCollection",void 0),Bc(this,"globalConfiguration",void 0),Bc(this,"globalPropertyStateManager",void 0),Bc(this,"globalPropertyHandleService",void 0),Bc(this,"eventListeners",new Map),Bc(this,"workflowExperiences",[]),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new wc(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new rc(this)}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const i=this.eventListeners.get(t)||[],A=i.indexOf(e);A>-1&&i.splice(A,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===ei.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await ya.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t);const i=await this.getGlobalProperties();await Promise.all(i.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");await ya.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,transactionId:e.id}}),this.workflowExperiences.splice(t,1)}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await ya.getShadowGraphqlClient().mutate({mutation:nc,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ya.getShadowGraphqlClient().mutate({mutation:ic,variables:{id:this.id,details:t,type:e||nr.Owner}})}async updateStakeholders(t){await ya.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ya.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}_setWorkflowExperiencesInternal(t){this.workflowExperiences=t}async updateBundle(){if(!(await ya.getShadowGraphqlClient().mutate({mutation:_o,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(i=>{const A=this.globalPropertyHandleService.applyConditionsFromState(i,t),n=this.globalPropertyHandleService.applyConditionsFromState(i,e);if(A.length!==n.length)return!0;for(let t=0;t<A.length;t++)if(A[t].getName()!==n[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function Ec(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const mc=t.gql`
|
|
704
704
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
705
705
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
706
706
|
id
|
package/dist/module.js
CHANGED
|
@@ -467,7 +467,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
467
467
|
workflowState
|
|
468
468
|
}
|
|
469
469
|
}
|
|
470
|
-
`,Ln=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const a=A.data;a.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),a.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),a.varyColor&&a.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Tn=[m.SilentIllustration,m.ProductOverlay],On=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const a=zn(A.stepName,t.stepGroups);if(a){const t=n.find((t=>t.name===a.name));t?Tn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:a.name,title:a.name,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}if(e.bulkScene){const a=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:a?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:a?.stepTitle??e.bulkSceneTitle,helpText:a?.helpText,data:{aspects:Ln(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},zn=(t,e)=>e.find((e=>e.stepNames.includes(t))),jn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),Kn=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>jn(t,e))),silentSteps:t.silentSteps.filter((t=>jn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),Vn=async(t,e)=>{const A=Kn(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const a=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of a)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return a};function Wn(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function Xn(t,e,A,n){const a=A.width*t.zoom,i=A.height*t.zoom;if(n){const n=t,a=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(a,t.zoom);const i=A.width*n.zoom,o=A.height*n.zoom;return n.x=qn(t.x,e.width-i,0),n.y=qn(t.y,e.height-o,0),n}const o=t;return o.x=qn(o.x,-a,e.width),o.y=qn(o.y,-i,e.height),o}function qn(t,e,A){return Math.min(Math.max(t,e),A)}class Zn{constructor(t){Wn(this,"offsets",void 0),Wn(this,"forceImageCover",void 0),Wn(this,"targetElements",void 0),Wn(this,"imageData",void 0),Wn(this,"frameData",void 0),Wn(this,"_debouncedUpdateFrameOffsets",void 0),Wn(this,"minZoomScale",[.03]),Wn(this,"maxZoomScale",[20]),Wn(this,"onFrameDataChangeListeners",void 0),Wn(this,"onZoomChangeListeners",void 0),Wn(this,"workflowManager",void 0),Wn(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],a=await N(n);Ot(a,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=a,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){this.imageData&&this.offsets&&this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((n,a)=>{const i=(e[a]-this.offsets[a].x)/this.offsets[a].zoom,o=(A[a]-this.offsets[a].y)/this.offsets[a].zoom,r={x:e[a]-i*t[a],y:A[a]-o*t[a],zoom:this.imageData.width*t[a]/this.imageData.width};this.offsets[a]=Xn(r,n,this.imageData,this.forceImageCover)})),this.updateOffsets(this.offsets,n),this.onZoomChangeListeners.forEach((e=>e(t))))}setPatternData(t){if(t&&this.frameData){this.recalculateOffsets(t);const e=this.offsets.map(((e,A)=>Xn(e,this.frameData[A],t,this.forceImageCover)));this.updateOffsets(e)}this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e){const A=this.imageData;if(!A||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x===e.x&&t[A].y===e.y&&t[A].zoom===e.zoom))?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=Xn(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,A,n,a){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const i=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{i(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),a&&a()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function $n(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class _n{constructor(t,e,A){$n(this,"configuration",void 0),$n(this,"layouts",void 0),$n(this,"product",void 0),$n(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ie(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const a={stepName:this.configuration.stepName,id:F(),src:A,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===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:a.id,region:t},command:new o(a,e)}}{const a=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,i=async()=>new Promise(((t,e)=>{a?nt(a).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await S(await i()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await dt(r.svg),src:a,svg:r.svg,colors:r.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===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ie(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.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")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const ta=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ea(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Aa{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,e,A,n=3e3,a=10){ea(this,"pollingId",void 0),ea(this,"attempts",void 0),ea(this,"interval",void 0),ea(this,"maxAttempts",void 0),ea(this,"predicate",void 0),ea(this,"onSuccess",void 0),ea(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=a,this.poll()}}const na=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{const A=n?.storage?.videoShortUrl,a=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:a})}))}async regenerateQRCode(t,e,A,n,a,i,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Ne([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new Aa((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ae(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===i.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+i.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const w=B.toString();if(w.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const d=await ta(w);if(o(d),!i.data||!i.data.regions)throw new ie(i,"Missing regions.");const h=await this.regionElements(i),E=await this.command(d,h,a,i.stepName);E&&(E.command&&a.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await a.setSelectionsAndElements(i.stepName,[],h,(async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const a=A.getLayouts(),i=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=a.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:i,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new w(r),followup:async()=>{}}}};function aa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ia=new class{constructor(){aa(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ae(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=ke.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,a=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:a,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(a?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(a)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const i=n.selectedVariants[0].id;if(t.option&&i){const n=t.option.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],a,(async()=>{const a=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:a}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],a,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new Aa((async()=>{const t=(await He.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{He.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await Ct(t),n=A.width,a=A.height,i={src:t,width:n,height:a,aspect:n/a};b.set(t,i),e.setPatternData(i)}else{const A=await st(t),n=await v(A),a={src:t,width:n.width,height:n.height,aspect:n.width/n.height};b.set(t,a),e.setPatternData(a)}}async selectVariantCommand(t,e,A,n,a,i){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));a&&a(!0);const c=await Promise.all(t.data.regions.map((async(e,a)=>{const i=await N(r[a]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,i):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,w=F(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new Ae(e);return{command:this.getCreateElementCommand(w,e,d,{frameData:i,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:w,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new w([...g,...l]),followup:async()=>{a&&a(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),i){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ae(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),a=A.markUpdatePending(),i=A.getStepSpecificServices(e.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,i),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(a)}};const oa=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.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},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!i||!A)throw new Error("Required illustration variant no longer available");{const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,a){const i={};for(const[t,e]of a.entries())i[t]={browserValue:e,spotColor:i[t]?.spotColor};const o=ut(t,e,A,i),r=await dt(o),s=[];for(const t of n){for(const[e,A]of a.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new w(s)}async changeColors(t,e,A,n,a){if(0===e.length)return;const i=y(e[0].id,n().map((t=>t.layoutState))),o={...i.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of a.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!i.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(i.svg,i.width,i.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n,a){if(!t.data||!t.data.regions)throw new ie(t,"Missing regions.");n(!0);const i=A.map((t=>new s(t.id)));a.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ae(o);const c=await S(await this.getIllustrationBody(r)),g=await dt(c.svg),l=t.data.regions.map((e=>{const A=a.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...i];let d=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{d=d.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),a.updateMetadata(t.stepName,{colors:d}),{command:new w(B),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ra=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(!i)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=i.variants?.find((t=>t.id===A));if(n){const A=n.material,o=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const a=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,i.id||"",A||{})));Promise.all(a).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){const a=A.getModelContainer();n(!0);const i=e.material;if(!i)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{a&&t.data.targetMaterials.forEach((e=>{t.option&&a.applyMaterialVariant(e,t.option.id||"",i)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const sa=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const a=n.asset?.fileLink;if(!a)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:a,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){n(!0);const a=e.asset?.fileLink;if(!a)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:a,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ca=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,a){const i=await this.changeTextCommand(t,e,A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,A,n,a){const i=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,a))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,a)=>{const i=a||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return a&&c.push(new s(i)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:i,svg:e,type:h.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},r)),{id:i,region:n,command:new w(c)}};if(i.length>0){const t=i.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),a=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(a),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const a=qt(e.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const ga=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=e.asset;if(!a)throw new ne(e);const i=a?.fileLink;if(!i)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const a=F();return{regionElement:{id:a,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:a,src:i,type:h.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const la=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(ke.getDefaultVariant(n)){const a=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,a?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const a=n.variants;if(!a)return null;const i=a.length>1?a.find((t=>t.id===e)):a[0];if(!i)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[i],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ba=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=ke.getDefaultVariant(n);if(!A)return null;const a={fill:A.color,stroke:A.color,variant:A};return this.selectVariantCommand(t,a,[],e)}return await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.updateStorage(t.stepName,{colour:n.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=n.getLayouts();if(A.length>0){const i=t=>{const A=t.region;if(!a.find((t=>t.panelId===A?.panelId)))throw new Ae(A);const n=e.variant?.color;return n?new Qt(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=A.map(i).filter((t=>!!t));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:e.fill||""})}}}{const A=A=>{const n=a.find((t=>t.panelId===A.panelId));if(!n)throw new Ae(A);const i=`\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="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=F();return{id:s,region:A,command:new o({stepRegion:A,stepName:t.stepName,colors:r,id:s,svg:i,type:h.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,excludeFromExport:t.data.excludeFromPrint},n)}},i=t.data.regions.map(A),r=i.filter((t=>!!t)).map((t=>t?.command)),s=i.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new w(r),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function wa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class da extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=da.name}}const ha=["‘","’","“","”","\n"];class Ea extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ea.name}}const Ca=new class{constructor(){wa(this,"cachedColors",new Map),wa(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],a=e?mt(e):void 0;if(a){const t=A.split("").filter((t=>!ha.includes(t))).join(""),e=t.split("").map((t=>a.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),wa(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),wa(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const a=A.getProfanities(),i=qt(t.toLowerCase());for(const t of i)for(const e in a){if(t===a[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),a=A?.asset?.fileLink,i=a?await Z(a):void 0,o=i?{src:i.src,height:i.height,width:i.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=ke.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const i=t.data.colorOption,o=i?this.createTextFillSpotColor(i,e.variant):void 0;i?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:i.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");a(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher(),i=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:i?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){a(new Dt(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const a=n.getStepStorage(A.stepName),i=this.getProcessedInput(t,A.data,!!a.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-i.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=U(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[i],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const a=A.data.curved?i:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,a,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:i}),a.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new w(c),o.command.varying=s,o}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),a=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:a,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),i=a.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],i,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=a.map((t=>new B(t.id,A))),i=new w(n);e.getCommandDispatcher()(i),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Ca.updateInputText(s||"",a,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return ke.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return ke.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return ke.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ae(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,a,i,o,r){const s=a.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new Dt(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,a,!!A.customiseAllText,i,o);l&&g.push(l);return{command:new w(g),followup:async()=>{a.markUpdateCompleted(s),await a.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,a),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,a,!!A.customiseAllText,i,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new Dt(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new w(l),followup:async()=>{a.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,a,i){if(!A||!A.regions)throw new Error("Step data not supplied");const r=i.getTransaction().bulk&&A.varyText||!1,s=r?"":a.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=i.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new Ea("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let w;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];w=this.createTextFillSpotColor(B,e),i.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const d=await this.getDefaultColor(A),E=d||"#000000",C={stepRegion:e,stepName:t,align:this.textAlign(A),fill:a.color?a.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:w},u=[],Q=new Map,p=new Map;if(!C.fontData)throw new re("Failed to resolve font data for text.");const[m,D]=U(C.fontSize,C.fontData,{left:C.x,top:C.y,width:C.width,height:C.height,rotation:C.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(C.id,m),p.set(C.id,D);const I=A.curved||A.vertical?c:(D||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(m,A,C.id,I,r));const f=new o(C,g);return f.varying=r,{regionElement:{id:l,region:e},commands:[f,...u],newElement:C,fontData:n}}catch(t){throw console.log(t),new da("Error adding font to region")}}))).catch((t=>{throw t instanceof da?(gA.setLatestToast("Failed to load font.",Qa.Error),t):t instanceof Ea?t:new Error(t)}));return await i.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{i.updateMetadata(t,{text:s}),i.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,a){const i=[],o=new D(A,n);if(o.varying=a,i.push(o),!e.size){const e=new l(A,t);e.varying=a,i.push(e)}const r=new w(i);return r.varying=a,r}async changeInputTextWithRegion(t,e,A,n,a,i,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=i.getRegionElements(t.stepName),d=new Map,h=new Map;for(const n of B)if(n.region){const[a,i]=U(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,a),h.set(n.id,i)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=i.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))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(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;i.updateStorage(t.stepName,{text:g}),i.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const C=i.getTransaction().bulk&&t.data.varyText||!1;a.defaultCleared&&i.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,A,C))}const Q=new w(u);return Q.varying=C,Q}};function ua(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Qa;var pa;(pa=Qa||(Qa={})).Error="Error",pa.Warning="Warning",pa.Info="Info";class ma extends OA{constructor(t){super(),ua(this,"update",void 0),ua(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Da{constructor(t,e,A,n,a,i,o,r,s,c,g=!1,l,B=!1){ua(this,"reloadedState",void 0),ua(this,"transaction",void 0),ua(this,"ownerCustomer",void 0),ua(this,"updateTransaction",void 0),ua(this,"confirmedDesign",void 0),ua(this,"editedSteps",void 0),ua(this,"informationResults",void 0),ua(this,"layouts",void 0),ua(this,"mandatorySteps",void 0),ua(this,"pendingUpdates",void 0),ua(this,"selectionCost",void 0),ua(this,"workflow",void 0),ua(this,"stepSpecificServices",void 0),ua(this,"previewService",void 0),ua(this,"profanityFilter",void 0),ua(this,"pollers",void 0),ua(this,"commandContext",void 0),ua(this,"stepElements",void 0),ua(this,"stepInitialised",void 0),ua(this,"stepMetadata",void 0),ua(this,"stepSelections",void 0),ua(this,"storage",void 0),ua(this,"confirmCallbacks",void 0),ua(this,"editedCallbacks",void 0),ua(this,"elementsCallbacks",void 0),ua(this,"informationResultCallbacks",void 0),ua(this,"initCallbacks",void 0),ua(this,"makingAdjustmentsCallback",void 0),ua(this,"mandatoryCallbacks",void 0),ua(this,"metadataCallbacks",void 0),ua(this,"selectionCallbacks",void 0),ua(this,"stepSpecificStorageCallbacks",void 0),ua(this,"storageCallbacks",void 0),ua(this,"currentVariationRecordCallbacks",void 0),ua(this,"variationRecordCallbacks",void 0),ua(this,"allScenes",void 0),ua(this,"product",void 0),ua(this,"invalidModelVariants",void 0),ua(this,"currentAdjustingStepId",void 0),ua(this,"renderableContextService",void 0),ua(this,"workflowStatePromiseQueue",new zA(1)),ua(this,"variationRecords",[]),ua(this,"currentVariationRecord",void 0),ua(this,"initializationPromise",void 0),ua(this,"initialized",!1),ua(this,"readOnly",!1),ua(this,"modelContainer",void 0),ua(this,"isReloadedTransaction",!1),ua(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=a,this.commandContext=n,this.reloadedState=c,this.transaction=i,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=A,this.product=o,this.previewService=r,this.modelContainer=l,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.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,i),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(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await On(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=Kn(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:a}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new w(a),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||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 e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.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,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].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}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}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((e=>{const A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.previewService=t,!this.getProduct().modelUrl)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}}async updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new ma((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new ma((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((A,n)=>{const a=[...t[n]||[]];return e.forEach((t=>{const e=a.findIndex((e=>e.id===t.id));e>-1&&a.splice(e,1)})),A[n]=a,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(jn(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!jn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new _n(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new _n(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},a=t.filter((t=>!this.stepInitialised[t.stepName])),i={stepElements:{},commands:[]},o=[];for(const t of a)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)i.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),i.commands=[...i.commands,...t.results.map((t=>t.command))];return i}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.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 s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const a=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const i=this.allScenes,o=Kn(i,a),r=Kn(i,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:d}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...d,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new w(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=Kn(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(na.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new Zn(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(ia.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(oa.init(A,this,this.reloadedState));break;case m.Material:t.push(ra.init(A,this,this.reloadedState));break;case m.Model:t.push(sa.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await ln(A.data.module)},t.push(ca.init(A,this,this.reloadedState));break;case m.Picture:t.push(ga.init(A,this,this.reloadedState));break;case m.Question:t.push(la.init(A,this,this.reloadedState));break;case m.Shape:t.push(Ba.init(A,this,this.reloadedState));break;case m.Text:t.push(Ca.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),a=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const t of a)await t();a.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 e of this.selectionCallbacks)e({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((e=>e(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)})),this.render3DScene()}traversableScenes(){return Vn(this.allScenes,this.stepSelections)}}function Ia(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class fa{constructor(t){Ia(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function ya(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ma{constructor(t,e){ya(this,"manager",void 0),ya(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Ma.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Ma.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new fa(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new fa(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new fa(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Fa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}ya(Ma,"updateState",new Map);const Ya=ft`
|
|
470
|
+
`,Ln=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const a=A.data;a.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),a.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),a.varyColor&&a.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Tn=[m.SilentIllustration,m.ProductOverlay],On=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const a=zn(A.stepName,t.stepGroups);if(a){const t=n.find((t=>t.name===a.name));t?Tn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:a.name,title:a.name,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}if(e.bulkScene){const a=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:a?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:a?.stepTitle??e.bulkSceneTitle,helpText:a?.helpText,data:{aspects:Ln(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},zn=(t,e)=>e.find((e=>e.stepNames.includes(t))),jn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),Kn=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>jn(t,e))),silentSteps:t.silentSteps.filter((t=>jn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),Vn=async(t,e)=>{const A=Kn(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const a=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of a)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return a};function Wn(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function Xn(t,e,A,n){const a=A.width*t.zoom,i=A.height*t.zoom;if(n){const n=t,a=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(a,t.zoom);const i=A.width*n.zoom,o=A.height*n.zoom;return n.x=qn(t.x,e.width-i,0),n.y=qn(t.y,e.height-o,0),n}const o=t;return o.x=qn(o.x,-a,e.width),o.y=qn(o.y,-i,e.height),o}function qn(t,e,A){return Math.min(Math.max(t,e),A)}class Zn{constructor(t){Wn(this,"offsets",void 0),Wn(this,"forceImageCover",void 0),Wn(this,"targetElements",void 0),Wn(this,"imageData",void 0),Wn(this,"frameData",void 0),Wn(this,"_debouncedUpdateFrameOffsets",void 0),Wn(this,"minZoomScale",[.03]),Wn(this,"maxZoomScale",[20]),Wn(this,"onFrameDataChangeListeners",void 0),Wn(this,"onZoomChangeListeners",void 0),Wn(this,"workflowManager",void 0),Wn(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],a=await N(n);Ot(a,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=a,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){this.imageData&&this.offsets&&this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((n,a)=>{const i=(e[a]-this.offsets[a].x)/this.offsets[a].zoom,o=(A[a]-this.offsets[a].y)/this.offsets[a].zoom,r={x:e[a]-i*t[a],y:A[a]-o*t[a],zoom:this.imageData.width*t[a]/this.imageData.width};this.offsets[a]=Xn(r,n,this.imageData,this.forceImageCover)})),this.updateOffsets(this.offsets,n),this.onZoomChangeListeners.forEach((e=>e(t))))}setPatternData(t){if(t&&this.frameData){this.recalculateOffsets(t);const e=this.offsets.map(((e,A)=>Xn(e,this.frameData[A],t,this.forceImageCover)));this.updateOffsets(e)}this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e){const A=this.imageData;if(!A||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=Xn(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,A,n,a){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const i=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{i(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),a&&a()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function $n(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class _n{constructor(t,e,A){$n(this,"configuration",void 0),$n(this,"layouts",void 0),$n(this,"product",void 0),$n(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ie(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const a={stepName:this.configuration.stepName,id:F(),src:A,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===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:a.id,region:t},command:new o(a,e)}}{const a=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,i=async()=>new Promise(((t,e)=>{a?nt(a).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await S(await i()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await dt(r.svg),src:a,svg:r.svg,colors:r.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===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ie(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.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")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const ta=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ea(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Aa{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,e,A,n=3e3,a=10){ea(this,"pollingId",void 0),ea(this,"attempts",void 0),ea(this,"interval",void 0),ea(this,"maxAttempts",void 0),ea(this,"predicate",void 0),ea(this,"onSuccess",void 0),ea(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=a,this.poll()}}const na=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{const A=n?.storage?.videoShortUrl,a=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:a})}))}async regenerateQRCode(t,e,A,n,a,i,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Ne([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new Aa((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ae(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===i.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+i.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const w=B.toString();if(w.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const d=await ta(w);if(o(d),!i.data||!i.data.regions)throw new ie(i,"Missing regions.");const h=await this.regionElements(i),E=await this.command(d,h,a,i.stepName);E&&(E.command&&a.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await a.setSelectionsAndElements(i.stepName,[],h,(async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const a=A.getLayouts(),i=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=a.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:i,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new w(r),followup:async()=>{}}}};function aa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ia=new class{constructor(){aa(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ae(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=ke.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,a=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:a,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(a?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(a)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const i=n.selectedVariants[0].id;if(t.option&&i){const n=t.option.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],a,(async()=>{const a=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:a}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],a,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new Aa((async()=>{const t=(await He.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{He.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await Ct(t),n=A.width,a=A.height,i={src:t,width:n,height:a,aspect:n/a};b.set(t,i),e.setPatternData(i)}else{const A=await st(t),n=await v(A),a={src:t,width:n.width,height:n.height,aspect:n.width/n.height};b.set(t,a),e.setPatternData(a)}}async selectVariantCommand(t,e,A,n,a,i){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));a&&a(!0);const c=await Promise.all(t.data.regions.map((async(e,a)=>{const i=await N(r[a]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,i):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,w=F(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new Ae(e);return{command:this.getCreateElementCommand(w,e,d,{frameData:i,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:w,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new w([...g,...l]),followup:async()=>{a&&a(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),i){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ae(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),a=A.markUpdatePending(),i=A.getStepSpecificServices(e.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,i),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(a)}};const oa=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.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},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!i||!A)throw new Error("Required illustration variant no longer available");{const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,a){const i={};for(const[t,e]of a.entries())i[t]={browserValue:e,spotColor:i[t]?.spotColor};const o=ut(t,e,A,i),r=await dt(o),s=[];for(const t of n){for(const[e,A]of a.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new w(s)}async changeColors(t,e,A,n,a){if(0===e.length)return;const i=y(e[0].id,n().map((t=>t.layoutState))),o={...i.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of a.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!i.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(i.svg,i.width,i.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n,a){if(!t.data||!t.data.regions)throw new ie(t,"Missing regions.");n(!0);const i=A.map((t=>new s(t.id)));a.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ae(o);const c=await S(await this.getIllustrationBody(r)),g=await dt(c.svg),l=t.data.regions.map((e=>{const A=a.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...i];let d=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{d=d.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),a.updateMetadata(t.stepName,{colors:d}),{command:new w(B),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ra=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(!i)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=i.variants?.find((t=>t.id===A));if(n){const A=n.material,o=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const a=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,i.id||"",A||{})));Promise.all(a).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){const a=A.getModelContainer();n(!0);const i=e.material;if(!i)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{a&&t.data.targetMaterials.forEach((e=>{t.option&&a.applyMaterialVariant(e,t.option.id||"",i)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const sa=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const a=n.asset?.fileLink;if(!a)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:a,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){n(!0);const a=e.asset?.fileLink;if(!a)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:a,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ca=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,a){const i=await this.changeTextCommand(t,e,A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,A,n,a){const i=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,a))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,a)=>{const i=a||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return a&&c.push(new s(i)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:i,svg:e,type:h.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},r)),{id:i,region:n,command:new w(c)}};if(i.length>0){const t=i.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),a=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(a),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const a=qt(e.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const ga=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=e.asset;if(!a)throw new ne(e);const i=a?.fileLink;if(!i)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const a=F();return{regionElement:{id:a,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:a,src:i,type:h.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const la=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(ke.getDefaultVariant(n)){const a=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,a?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const a=n.variants;if(!a)return null;const i=a.length>1?a.find((t=>t.id===e)):a[0];if(!i)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[i],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ba=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=ke.getDefaultVariant(n);if(!A)return null;const a={fill:A.color,stroke:A.color,variant:A};return this.selectVariantCommand(t,a,[],e)}return await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.updateStorage(t.stepName,{colour:n.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=n.getLayouts();if(A.length>0){const i=t=>{const A=t.region;if(!a.find((t=>t.panelId===A?.panelId)))throw new Ae(A);const n=e.variant?.color;return n?new Qt(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=A.map(i).filter((t=>!!t));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:e.fill||""})}}}{const A=A=>{const n=a.find((t=>t.panelId===A.panelId));if(!n)throw new Ae(A);const i=`\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="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=F();return{id:s,region:A,command:new o({stepRegion:A,stepName:t.stepName,colors:r,id:s,svg:i,type:h.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,excludeFromExport:t.data.excludeFromPrint},n)}},i=t.data.regions.map(A),r=i.filter((t=>!!t)).map((t=>t?.command)),s=i.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new w(r),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function wa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class da extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=da.name}}const ha=["‘","’","“","”","\n"];class Ea extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ea.name}}const Ca=new class{constructor(){wa(this,"cachedColors",new Map),wa(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],a=e?mt(e):void 0;if(a){const t=A.split("").filter((t=>!ha.includes(t))).join(""),e=t.split("").map((t=>a.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),wa(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),wa(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const a=A.getProfanities(),i=qt(t.toLowerCase());for(const t of i)for(const e in a){if(t===a[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),a=A?.asset?.fileLink,i=a?await Z(a):void 0,o=i?{src:i.src,height:i.height,width:i.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=ke.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const i=t.data.colorOption,o=i?this.createTextFillSpotColor(i,e.variant):void 0;i?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:i.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");a(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher(),i=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:i?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){a(new Dt(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const a=n.getStepStorage(A.stepName),i=this.getProcessedInput(t,A.data,!!a.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-i.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=U(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[i],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const a=A.data.curved?i:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,a,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:i}),a.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new w(c),o.command.varying=s,o}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),a=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:a,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),i=a.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],i,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=a.map((t=>new B(t.id,A))),i=new w(n);e.getCommandDispatcher()(i),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Ca.updateInputText(s||"",a,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return ke.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return ke.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return ke.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ae(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,a,i,o,r){const s=a.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new Dt(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,a,!!A.customiseAllText,i,o);l&&g.push(l);return{command:new w(g),followup:async()=>{a.markUpdateCompleted(s),await a.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,a),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,a,!!A.customiseAllText,i,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new Dt(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new w(l),followup:async()=>{a.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,a,i){if(!A||!A.regions)throw new Error("Step data not supplied");const r=i.getTransaction().bulk&&A.varyText||!1,s=r?"":a.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=i.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new Ea("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let w;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];w=this.createTextFillSpotColor(B,e),i.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const d=await this.getDefaultColor(A),E=d||"#000000",C={stepRegion:e,stepName:t,align:this.textAlign(A),fill:a.color?a.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:w},u=[],Q=new Map,p=new Map;if(!C.fontData)throw new re("Failed to resolve font data for text.");const[m,D]=U(C.fontSize,C.fontData,{left:C.x,top:C.y,width:C.width,height:C.height,rotation:C.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(C.id,m),p.set(C.id,D);const I=A.curved||A.vertical?c:(D||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(m,A,C.id,I,r));const f=new o(C,g);return f.varying=r,{regionElement:{id:l,region:e},commands:[f,...u],newElement:C,fontData:n}}catch(t){throw console.log(t),new da("Error adding font to region")}}))).catch((t=>{throw t instanceof da?(gA.setLatestToast("Failed to load font.",Qa.Error),t):t instanceof Ea?t:new Error(t)}));return await i.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{i.updateMetadata(t,{text:s}),i.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,a){const i=[],o=new D(A,n);if(o.varying=a,i.push(o),!e.size){const e=new l(A,t);e.varying=a,i.push(e)}const r=new w(i);return r.varying=a,r}async changeInputTextWithRegion(t,e,A,n,a,i,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=i.getRegionElements(t.stepName),d=new Map,h=new Map;for(const n of B)if(n.region){const[a,i]=U(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,a),h.set(n.id,i)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=i.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))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(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;i.updateStorage(t.stepName,{text:g}),i.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const C=i.getTransaction().bulk&&t.data.varyText||!1;a.defaultCleared&&i.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,A,C))}const Q=new w(u);return Q.varying=C,Q}};function ua(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Qa;var pa;(pa=Qa||(Qa={})).Error="Error",pa.Warning="Warning",pa.Info="Info";class ma extends OA{constructor(t){super(),ua(this,"update",void 0),ua(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Da{constructor(t,e,A,n,a,i,o,r,s,c,g=!1,l,B=!1){ua(this,"reloadedState",void 0),ua(this,"transaction",void 0),ua(this,"ownerCustomer",void 0),ua(this,"updateTransaction",void 0),ua(this,"confirmedDesign",void 0),ua(this,"editedSteps",void 0),ua(this,"informationResults",void 0),ua(this,"layouts",void 0),ua(this,"mandatorySteps",void 0),ua(this,"pendingUpdates",void 0),ua(this,"selectionCost",void 0),ua(this,"workflow",void 0),ua(this,"stepSpecificServices",void 0),ua(this,"previewService",void 0),ua(this,"profanityFilter",void 0),ua(this,"pollers",void 0),ua(this,"commandContext",void 0),ua(this,"stepElements",void 0),ua(this,"stepInitialised",void 0),ua(this,"stepMetadata",void 0),ua(this,"stepSelections",void 0),ua(this,"storage",void 0),ua(this,"confirmCallbacks",void 0),ua(this,"editedCallbacks",void 0),ua(this,"elementsCallbacks",void 0),ua(this,"informationResultCallbacks",void 0),ua(this,"initCallbacks",void 0),ua(this,"makingAdjustmentsCallback",void 0),ua(this,"mandatoryCallbacks",void 0),ua(this,"metadataCallbacks",void 0),ua(this,"selectionCallbacks",void 0),ua(this,"stepSpecificStorageCallbacks",void 0),ua(this,"storageCallbacks",void 0),ua(this,"currentVariationRecordCallbacks",void 0),ua(this,"variationRecordCallbacks",void 0),ua(this,"allScenes",void 0),ua(this,"product",void 0),ua(this,"invalidModelVariants",void 0),ua(this,"currentAdjustingStepId",void 0),ua(this,"renderableContextService",void 0),ua(this,"workflowStatePromiseQueue",new zA(1)),ua(this,"variationRecords",[]),ua(this,"currentVariationRecord",void 0),ua(this,"initializationPromise",void 0),ua(this,"initialized",!1),ua(this,"readOnly",!1),ua(this,"modelContainer",void 0),ua(this,"isReloadedTransaction",!1),ua(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=a,this.commandContext=n,this.reloadedState=c,this.transaction=i,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=A,this.product=o,this.previewService=r,this.modelContainer=l,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.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,i),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(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await On(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=Kn(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:a}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new w(a),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||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 e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.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,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].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}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}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((e=>{const A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.previewService=t,!this.getProduct().modelUrl)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}}async updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new ma((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new ma((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((A,n)=>{const a=[...t[n]||[]];return e.forEach((t=>{const e=a.findIndex((e=>e.id===t.id));e>-1&&a.splice(e,1)})),A[n]=a,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(jn(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!jn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new _n(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new _n(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},a=t.filter((t=>!this.stepInitialised[t.stepName])),i={stepElements:{},commands:[]},o=[];for(const t of a)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)i.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),i.commands=[...i.commands,...t.results.map((t=>t.command))];return i}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.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 s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const a=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const i=this.allScenes,o=Kn(i,a),r=Kn(i,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:d}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...d,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new w(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=Kn(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(na.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new Zn(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(ia.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(oa.init(A,this,this.reloadedState));break;case m.Material:t.push(ra.init(A,this,this.reloadedState));break;case m.Model:t.push(sa.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await ln(A.data.module)},t.push(ca.init(A,this,this.reloadedState));break;case m.Picture:t.push(ga.init(A,this,this.reloadedState));break;case m.Question:t.push(la.init(A,this,this.reloadedState));break;case m.Shape:t.push(Ba.init(A,this,this.reloadedState));break;case m.Text:t.push(Ca.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),a=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const t of a)await t();a.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 e of this.selectionCallbacks)e({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((e=>e(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)})),this.render3DScene()}traversableScenes(){return Vn(this.allScenes,this.stepSelections)}}function Ia(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class fa{constructor(t){Ia(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function ya(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ma{constructor(t,e){ya(this,"manager",void 0),ya(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Ma.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Ma.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new fa(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new fa(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new fa(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Fa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}ya(Ma,"updateState",new Map);const Ya=ft`
|
|
471
471
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
472
472
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
473
473
|
id
|
|
@@ -670,7 +670,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
670
670
|
id
|
|
671
671
|
}
|
|
672
672
|
}
|
|
673
|
-
`;function oi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ri{constructor(t){oi(this,"bundle",void 0),oi(this,"handleCache",{}),this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const A=e.aspects.find((e=>e.name===t.targetAspectName));return!!A&&t.requiredVariantSelections.some((t=>t===A.value))}))}async createHandle(t){switch(t.type){case It.FileUpload:return new ci(this.bundle,t);case It.Option:const e=t.entityId?await ke.getOption(t.entityId):void 0;return new li(this.bundle,t,e);case It.Text:return new gi(this.bundle,t)}}}class si{constructor(t,e){oi(this,"bundle",void 0),oi(this,"property",void 0),this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){
|
|
673
|
+
`;function oi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ri{constructor(t){oi(this,"bundle",void 0),oi(this,"handleCache",{}),this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const A=e.aspects.find((e=>e.name===t.targetAspectName));return!!A&&t.requiredVariantSelections.some((t=>t===A.value))}))}async createHandle(t){switch(t.type){case It.FileUpload:return new ci(this.bundle,t);case It.Option:const e=t.entityId?await ke.getOption(t.entityId):void 0;return new li(this.bundle,t,e);case It.Text:return new gi(this.bundle,t)}}}class si{constructor(t,e){oi(this,"bundle",void 0),oi(this,"property",void 0),this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap((t=>t.getSteps().filter((t=>t.getRaw().globalPropertyAspectConfigurations?.some((t=>t.globalPropertyConfigurationId===this.bundle.getProductCollection()?.globalPropertyConfiguration?.id&&t.aspectName===this.property.name))))))}}class ci extends si{constructor(t,e){super(t,e)}async selectImage(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.key),this.applyImageSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=await He.getLocalOrFromServer(e);return A?this.applyImageSelection(A,t):Promise.resolve()}async applyImageSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectImage(t)));await Promise.all(A)}}class gi extends si{constructor(t,e){super(t,e)}getText(){const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const A=this.getSharedSteps(e).map((e=>{e.setText(t)}));await Promise.all(A)}}class li extends si{constructor(t,e,A){super(t,e),oi(this,"optionResource",void 0),this.optionResource=A}getCurrentVariant(){if(!this.optionResource)return;const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!t)return;const e=this.optionResource.variants?.find((e=>e.id===t));return e?new fa(e):void 0}getAvailableVariants(){return(this.optionResource?.variants?.filter((t=>t.enabled))||[]).map((t=>new fa(t)))}getAllVariants(){return(this.optionResource?.variants||[]).map((t=>new fa(t)))}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=this.optionResource?.variants?.find((t=>t.id===e));return A?this.applyVariantSelection(new fa(A),t):Promise.resolve()}async applyVariantSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectVariant(t)));await Promise.all(A)}}const Bi=Zt`
|
|
674
674
|
mutation CreateGlobalPropertyState($bundleId: String!) {
|
|
675
675
|
globalPropertyStateCreate(bundleId: $bundleId) {
|
|
676
676
|
id
|
|
@@ -700,7 +700,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
700
700
|
}
|
|
701
701
|
}
|
|
702
702
|
}
|
|
703
|
-
`;function hi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ei{constructor(t,e){hi(this,"bundleId",void 0),hi(this,"globalPropertyState",void 0),hi(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=zt(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=e:this.globalPropertyState.aspects.push({name:t,value:e}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ye.getShadowGraphqlClient().query({query:di,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Ci(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ui{constructor(t,e){Ci(this,"client",void 0),Ci(this,"id",void 0),Ci(this,"name",void 0),Ci(this,"metadata",void 0),Ci(this,"productCollection",void 0),Ci(this,"globalConfiguration",void 0),Ci(this,"globalPropertyStateManager",void 0),Ci(this,"globalPropertyHandleService",void 0),Ci(this,"eventListeners",new Map),Ci(this,"workflowExperiences",[]),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new Ei(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new ri(this)}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],n=A.indexOf(e);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await ye.getShadowGraphqlClient().mutate({mutation:ei,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t);const A=await this.getGlobalProperties();await Promise.all(A.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");await ye.getShadowGraphqlClient().mutate({mutation:Ai,variables:{id:this.id,transactionId:e.id}}),this.workflowExperiences.splice(t,1)}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await ye.getShadowGraphqlClient().mutate({mutation:ii,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ye.getShadowGraphqlClient().mutate({mutation:ni,variables:{id:this.id,details:t,type:e||oA.Owner}})}async updateStakeholders(t){await ye.getShadowGraphqlClient().mutate({mutation:ai,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:$a,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}_setWorkflowExperiencesInternal(t){this.workflowExperiences=t}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:ti,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(A=>{const n=this.globalPropertyHandleService.applyConditionsFromState(A,t),a=this.globalPropertyHandleService.applyConditionsFromState(A,e);if(n.length!==a.length)return!0;for(let t=0;t<n.length;t++)if(n[t].getName()!==a[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function Qi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const pi=ft`
|
|
703
|
+
`;function hi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ei{constructor(t,e){hi(this,"bundleId",void 0),hi(this,"globalPropertyState",void 0),hi(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=zt(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=e:this.globalPropertyState.aspects.push({name:t,value:e}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ye.getShadowGraphqlClient().query({query:di,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Ci(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ui{constructor(t,e){Ci(this,"client",void 0),Ci(this,"id",void 0),Ci(this,"name",void 0),Ci(this,"metadata",void 0),Ci(this,"productCollection",void 0),Ci(this,"globalConfiguration",void 0),Ci(this,"globalPropertyStateManager",void 0),Ci(this,"globalPropertyHandleService",void 0),Ci(this,"eventListeners",new Map),Ci(this,"workflowExperiences",[]),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new Ei(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new ri(this)}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],n=A.indexOf(e);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===It.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await ye.getShadowGraphqlClient().mutate({mutation:ei,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t);const A=await this.getGlobalProperties();await Promise.all(A.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");await ye.getShadowGraphqlClient().mutate({mutation:Ai,variables:{id:this.id,transactionId:e.id}}),this.workflowExperiences.splice(t,1)}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await ye.getShadowGraphqlClient().mutate({mutation:ii,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ye.getShadowGraphqlClient().mutate({mutation:ni,variables:{id:this.id,details:t,type:e||oA.Owner}})}async updateStakeholders(t){await ye.getShadowGraphqlClient().mutate({mutation:ai,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:$a,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}_setWorkflowExperiencesInternal(t){this.workflowExperiences=t}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:ti,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(A=>{const n=this.globalPropertyHandleService.applyConditionsFromState(A,t),a=this.globalPropertyHandleService.applyConditionsFromState(A,e);if(n.length!==a.length)return!0;for(let t=0;t<n.length;t++)if(n[t].getName()!==a[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function Qi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const pi=ft`
|
|
704
704
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
705
705
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
706
706
|
id
|
package/dist/types.d.ts
CHANGED
|
@@ -2011,6 +2011,10 @@ interface _Bundle1 {
|
|
|
2011
2011
|
* Get the low level state manager for this bundle. Don't use this unless you know what you're doing.
|
|
2012
2012
|
*/
|
|
2013
2013
|
getGlobalPropertyStateManager(): GlobalPropertyStateManager;
|
|
2014
|
+
/**
|
|
2015
|
+
* Get the total in subunits for all global properties in this bundle.
|
|
2016
|
+
*/
|
|
2017
|
+
getGlobalPropertyTotalSubunits(): Promise<number>;
|
|
2014
2018
|
/**
|
|
2015
2019
|
* Return the total in subunits for this bundle. This is the sum of the total for all individual transactions.
|
|
2016
2020
|
*/
|