@spiffcommerce/core 3.2.0 → 3.3.1
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 +1 -1
- package/dist/module.js +22 -22
- package/dist/types.d.ts +6 -0
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -422,7 +422,7 @@ var t=require("@apollo/client"),A=require("lodash.clonedeep"),e=require("react/j
|
|
|
422
422
|
workflowState
|
|
423
423
|
}
|
|
424
424
|
}
|
|
425
|
-
`,da=t=>{const A=[];for(const e of t.steps)switch(e.type){case K.DigitalContent:e.data.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Frame:const t=e.data;t.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),t.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Illustration:const n=e.data;n.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),n.varyColors&&n.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Colors});break;case K.Material:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Model:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Picture:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Question:e.data.varySelections&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selections});break;case K.Shape:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Text:const i=e.data;i.varyText&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Text}),i.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),i.varyColor&&i.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Color})}return A},Ea=[K.SilentIllustration,K.ProductOverlay],ua=async(t,A,e)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:K.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const e of t.steps){if(A.bulkScene){let t=!1;switch(e.type){case K.DigitalContent:e.data.varyUpload&&(t=!0);break;case K.Frame:{const A=e.data;!A.varyUpload||!A.varySelection&&e.option||(t=!0)}break;case K.Illustration:{const A=e.data;!A.varySelection&&e.option&&1!==(e.option.variants||[]).length||!A.varyColors&&A.colorPickerEnabled||(t=!0)}break;case K.Material:e.data.varySelection&&(t=!0);break;case K.Model:e.data.varySelection&&(t=!0);break;case K.Picture:e.data.varySelection&&(t=!0);break;case K.Question:e.data.varySelections&&(t=!0);break;case K.Shape:e.data.varySelection&&(t=!0);break;case K.Text:{const A=e.data;!A.varySelection&&e.option&&1!==(e.option.variants||[]).length||!A.varyColor&&A.colorPickerEnabled&&A.colorOption||!A.varyText||(t=!0)}}if(t)continue}const i=Qa(e.stepName,t.stepGroups);if(i){const t=n.find((t=>t.name===i.name));t?Ea.includes(e.type)?t.silentSteps.push(e):t.renderableSteps.push(e):n.push({name:i.name,title:i.name,renderableSteps:Ea.includes(e.type)?[]:[e],silentSteps:Ea.includes(e.type)?[e]:[]})}else n.push({name:e.stepName,title:e.stepTitle,renderableSteps:Ea.includes(e.type)?[]:[e],silentSteps:Ea.includes(e.type)?[e]:[]})}if(A.bulkScene){const i=e?.product?.bulkConfiguration;n.push({name:"Bulk",title:i?.sceneTitle??A.bulkSceneTitle,renderableSteps:[{type:K.Bulk,stepName:"Bulk",stepTitle:i?.stepTitle??A.bulkSceneTitle,helpText:i?.helpText,data:{aspects:da(t)},conditions:[]}],silentSteps:[]})}return A.finishScene&&n.push({name:"Finish",title:A.finishSceneTitle,renderableSteps:[{type:K.Finish,stepName:"Finish",stepTitle:A.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},Qa=(t,A)=>A.find((A=>A.stepNames.includes(t))),Ca=(t,A)=>(t.conditions||[]).every((t=>{const e=A[t.targetStepName];if(e&&e.selectedVariants){const A=e.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==A.find((A=>A.id===t))))}return!1})),ma=(t,A)=>t.map((t=>((t,A)=>{const e={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ca(t,A))),silentSteps:t.silentSteps.filter((t=>Ca(t,A)))};return 0===e.silentSteps.length&&0===e.renderableSteps.length?null:e})(t,A))).filter((t=>null!==t)),pa=async(t,A)=>{const e=ma(t,A),n=[];for(const t of e)for(const A of t.renderableSteps)if(A.type===K.Model||A.type===K.Material||A.type===K.Picture||A.type===K.Shape){const t=(A.option?.variants||[]).length;t&&t>1&&n.push(A.stepName)}else n.push(A.stepName);const i=e.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of i)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return i};function fa(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}function Da(t,A,e,n){const i=e.width*t.zoom,a=e.height*t.zoom;if(n){const n=t,i=Math.max(A.width/e.width,A.height/e.height);n.zoom=Math.max(i,t.zoom);const a=e.width*n.zoom,o=e.height*n.zoom;return n.x=Ia(t.x,A.width-a,0),n.y=Ia(t.y,A.height-o,0),n}const o=t;return o.x=Ia(o.x,-i,A.width),o.y=Ia(o.y,-a,A.height),o}function Ia(t,A,e){return Math.min(Math.max(t,A),e)}class ya{constructor(t){fa(this,"offsets",void 0),fa(this,"forceImageCover",void 0),fa(this,"targetElements",void 0),fa(this,"imageData",void 0),fa(this,"frameData",void 0),fa(this,"_debouncedUpdateFrameOffsets",void 0),fa(this,"minZoomScale",.03),fa(this,"maxZoomScale",20),fa(this,"onFrameDataChangeListeners",void 0),fa(this,"onZoomChangeListeners",void 0),fa(this,"workflowManager",void 0),fa(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=I(p)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,A){A&&t.addStepSpecificStorageCallback((async t=>{if(t){const A=t;if(A.currentFrameSource){const t=await Qe(A.currentFrameSource);I(u)(t,this.frameData)||(this.frameData=t,this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.offsets=Ce(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),A),this.workflowManager=t,this.stepName=A}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}async setFrameData(t){const A=he.get(t);this.frameData=A}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,A,e,n){if(this.imageData&&this.offsets&&this.frameData){const i=(A-this.offsets.x)/this.offsets.zoom,a=(e-this.offsets.y)/this.offsets.zoom,o={x:A-i*t,y:e-a*t,zoom:this.imageData.width*t/this.imageData.width};this.updateOffsets(Da(o,this.frameData,this.imageData,this.forceImageCover),n),this.onZoomChangeListeners.forEach((A=>A(t)))}}setPatternData(t){(t&&this.frameData||t&&this.frameData&&!this.imageData)&&(this.offsets=Ce(t,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements),this.updateOffsets(Da(this.offsets,this.frameData,t,this.forceImageCover))),this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,A){const e=this.imageData;e&&this.frameData&&(this.offsets&&t.x===this.offsets.x&&t.y===this.offsets.y&&t.zoom===this.offsets.zoom?A&&A():(this.offsets=Da(t,this.frameData,e,this.forceImageCover),this._debouncedUpdateFrameOffsets(t,e,this.frameData,this.targetElements,A)))}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,A,e,n,i){if(!e)throw new Oe("Frame data not set. This is a bug");if(!this.workflowManager)throw new Oe("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach((e=>{a(new ZA(e,A,t))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:t}),i&&i()}recalculateZoomLimits(t,A){const e=Math.max(A.width/t.width,A.height/t.height);this.forceImageCover?(this.minZoomScale=e,this.maxZoomScale=2.5*e):(this.minZoomScale=e/10,this.maxZoomScale=2.5*e)}}function Ma(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class xa{constructor(t,A,e){Ma(this,"configuration",void 0),Ma(this,"layouts",void 0),Ma(this,"product",void 0),Ma(this,"processRegion",(async t=>{const A=this.layouts.find((A=>A.panelId===t.panelId));if(!A)throw new Ge(t);let e="";if(this.configuration.type===K.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),e=t,!t)throw new Je(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===N.Image){const e=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!e)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:e,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:t},command:new TA(i,A)}}{const i=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:e,a=async()=>new Promise(((t,A)=>{i?Nt(i).then((A=>{t(A)})).catch((t=>console.error(t))):A("Undefined vector silent step source")})),o=await IA(await a()),r={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await ve(o.svg),src:i,svg:o.svg,colors:o.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:r.id,region:t},command:new TA(r,A)}}})),this.configuration=t,this.layouts=A,this.product=e||void 0}async trigger(){if(!this.configuration.data.regions)throw new Je(this.configuration,"Missing regions.");if(this.configuration.type===K.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===K.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((A=>t.panelId===A.panelId)))throw new Ge(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===K.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?N.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),N.Illustration)}}const Fa=async t=>{const A=`${Ze.getServicesApiUrl()}/shortener`;try{const e=await fetch(A,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await e.json()).shortUrl}catch(t){throw console.error(t),new je("Failed to shorten URL, see console.")}};function Ya(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class va{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,A,e,n=3e3,i=10){Ya(this,"pollingId",void 0),Ya(this,"attempts",void 0),Ya(this,"interval",void 0),Ya(this,"maxAttempts",void 0),Ya(this,"predicate",void 0),Ya(this,"onSuccess",void 0),Ya(this,"onFailure",void 0),this.onSuccess=A,this.onFailure=e,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const Sa=new class{async init(t,A,e){return e&&await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{const e=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;A.updateStorage(t.stepName,{videoShortUrl:e,videoUrl:i})}))}async regenerateQRCode(t,A,e,n,i,a,o,r,s){if(A||""===e||""!==n)s(!1);else{const A=async()=>{const t=(await cn([e]))[0],A=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:A}},c=await new Promise(((t,e)=>{new va((async()=>!!(await A()).link),(async()=>{const e=await A();if(!e.link||!e.link)throw new be(e.asset);t({rel:"mpeg4",href:e.link})}),(()=>{e("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new zA(t.id))));const g="http"===a.data.baseUrl.slice(0,4)?"":"https://",l=new URL(g+a.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([c]))),l.pathname=l.pathname+("/"===l.pathname.slice(-1)?"":"/");const B=l.toString();if(B.length>=2e3)throw new je("Cannot create QR code, URL too long.");const w=await Fa(B);if(o(w),!a.data||!a.data.regions)throw new Je(a,"Missing regions.");const h=await this.regionElements(a),d=await this.command(w,h,i,a.stepName);d&&(d.command&&i.getCommandDispatcher()(d.command),d.followup&&await d.followup()),await i.setSelectionsAndElements(a.stepName,[],h,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:w,videoUrl:n}),s(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,A,e,n){const i=e.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,C.toString)(t,{type:"svg"}))}`,o=A.map((t=>{const A=t.region,e=i.find((t=>t.panelId===A?.panelId));if(!e&&A)throw new Ge(A);if(e&&!A)throw new Error("Region not found");if(!e||!A)throw new Error("Neither a region or layout found!");return new TA({stepRegion:A,stepName:n,id:t.id,src:a,type:N.Image,y:A.top,x:A.left,width:A.width,height:A.height,rotation:0},e)}));return{command:new JA(o),followup:async()=>{}}}};function Na(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Ra=new class{constructor(){Na(this,"frameSourceSvg",(async(t,A)=>{if(!t)return Ee(A.data.regions[0]);const e=t.asset;if(!e)throw new ke(t);const n=e.fileLink;if(n)return Nt(n);throw new be(e)}))}async init(t,A,e){if(e)return await this.reload(t,A,e),null;if(A.setMandatoryFulfilled(t.stepName,!1),A.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const e=t.option,n=En.getDefaultVariant(e);return n?this.selectVariantCommand(t,n,[],A,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],A,void 0,t.data.placeholderImageUrl)}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const e=Ee(t.data.regions[0]);A.updateStorage(t.stepName,{currentFrameSource:e})}if(n){const e=async()=>{const e=n.storage?.framePatternSrc,i=n.storage?.frameOffsets;if(A.updateMetadata(t.stepName,{frameOffsets:i,framePatternSrc:e}),e){const n=A.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(e,n),A.updateMetadata(t.stepName,{image:e}),A.updateStorage(t.stepName,{framePatternSrc:e})}if(i?.zoom){const e=A.getStepSpecificServices(t.stepName)?.frameService;e.updateOffsets(i)}A.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants?.find((t=>t.id===a));n&&await A.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=await this.frameSourceSvg(n,t);A.updateStorage(t.stepName,{currentFrameSource:i}),await e()}))}}else await A.setSelectionsAndElements(t.stepName,[],i,e)}}selectImage(t,A,e){e.setEditedStatus(t.stepName,!0);(A.fileLink||"").endsWith("pdf")?e.addPoller(new va((async()=>{const t=(await Bn.getLocalOrFromServer(A.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Bn.getLocalOrFromServer(A.key||"").then((A=>{this.loadPatternFromAsset(A,t,e)}))}),(()=>{throw new je("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(A,t,e)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,A,e,n){return new TA({id:t,type:N.Frame,x:A.left,y:A.top,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,scaleX:A.width/n.frameData.width,scaleY:A.height/n.frameData.height,path:n.frameData.path,stepRegion:A,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:A.immutable},e)}async loadPatternFromString(t,A){if(t.endsWith("svg")){const e=await pe(t),n=e.width,i=e.height,a={src:t,width:n,height:i,aspect:n/i};we.set(t,a),A.setPatternData(a)}else{const e=await St(t),n=await le(e),i={src:t,width:n.width,height:n.height,aspect:n.width/n.height};we.set(t,i),A.setPatternData(i)}}async selectVariantCommand(t,A,e,n,i,a){const o=n.getStepSpecificServices(t.stepName)?.frameService,r=await this.frameSourceSvg(A,t),s=await Qe(r),c=o.getImageData(),g=e.map((t=>new zA(t.id))),l=c?Ce(c,s):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0;i&&i(!0);const w=t.data.regions.map((A=>{const e=F(),i=n.getLayouts().find((t=>t.panelId===A.panelId));if(!i)throw new Ge(A);return{command:this.getCreateElementCommand(e,A,i,{frameData:s,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:e,region:A}}})),h=w.map((t=>t.command));return{command:new JA([...h,...g]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,A?[A]:[],[...w.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSource:r}),a){const A=n.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(a,A)}}))}}}patternSource(t){const A=t.versions?.find((t=>"svg"===t.name));if(A)return A.link;const e=t.fileLink;if(e)return e;throw new be(t)}async loadPatternFromAsset(t,A,e){const n=this.patternSource(t),i=e.markUpdatePending(),a=e.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(n,a),e.updateMetadata(A.stepName,{image:n}),e.updateStorage(A.stepName,{framePatternSrc:n}),e.markUpdateCompleted(i)}};const Ha=new class{async getIllustrationBody(t){return new Promise((A=>{Nt(t).then((t=>{A(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,A,e,n){return new TA({stepRegion:A,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:N.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},e)}getColors(t,A){const e=A.getRegionElements(t.stepName)||[];if(0===e.length)return[];try{return SA(e[0].id,A.getAllLayoutData()).colors}catch(t){return[]}}async init(t,A,e){const n=t.option;if(!n)return null;if(e)return this.reload(t,A,e);{const e=En.getDefaultVariant(n);if(e)return await this.selectVariantCommand(t,e,[],(()=>{}),A)}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(!a||!e)throw new Error("Required illustration variant no longer available");{const o=a.variants?.find((t=>t.id===e));if(o){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[o],e,(async()=>{A.updateMetadata(t.stepName,{colors:n.storage?.colors}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,A){const e=t.data.colorOption;return e&&e?e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,A,e,n,i){const a={};for(const[t,A]of i.entries())a[t]={browserValue:A,spotColor:a[t]?.spotColor};const o=DA(t,A,e,a),r=await ve(o),s=[];for(const t of n){for(const[A,e]of i.entries())s.push(new _A(t,A,e));s.push(new te(t,o,r))}return new JA(s)}async changeColors(t,A,e,n,i){if(0===A.length)return;const a=SA(A[0].id,n().map((t=>t.layoutState))),o={...a.colors},r={};Object.entries(o).forEach((([t,A])=>{const e={browserValue:A.browserValue},n=A.spotColor;n&&(e.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=e}));for(const[t,A]of i.entries())o[t]={browserValue:A,spotColor:o[t]?.spotColor},r[t]={browserValue:A};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),e.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,A])=>{g.set(t,A.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(a.svg,a.width,a.height,A.map((t=>t.id)),g);e.updateStorage(t.stepName,{colors:r}),e.getCommandDispatcher()(l)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,A,e,n,i){if(!t.data||!t.data.regions)throw new Je(t,"Missing regions.");n(!0);const a=e.map((t=>new zA(t.id)));i.setMandatoryFulfilled(t.stepName,!1);const o=A.asset;if(!o)throw new ke(A);const r=o.fileLink;if(!r)throw new be(o);const s=await IA(await this.getIllustrationBody(r)),c=await ve(s.svg),g=t.data.regions.map((A=>{const e=i.getLayouts().find((t=>t.panelId===A.panelId));if(!e)throw new Ge(A);const n=F();return{regionElement:{id:n,region:A},command:this.getCreateElementCommand(n,A,e,{stepName:t.stepName,src:r,objectURL:c,svg:s})}})),l=[...g.map((t=>t.command)),...a];let B=Array.from(Object.values(s.colors)).map((t=>t.browserValue));const w=t.data.colorOption;return w&&w.variants?.forEach((t=>{B=B.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),i.updateMetadata(t.stepName,{colors:B}),{command:new JA(l),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[A],g.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Pa=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=En.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(!a)throw new Ue(t);if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(e){const n=a.variants?.find((t=>t.id===e));if(n){const e=n.material,o=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=A.getPreviewService();if(n){const i=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id,e)));Promise.all(i).then((()=>A.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){const i=e.getPreviewService();n(!0);const a=A.material;if(!a)throw n(!1),new ke(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{i&&t.data.targetMaterials.forEach((A=>{t.option&&i.applyMaterialVariant(A,t.option.id,a)})),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ua=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=En.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants?.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{const e=A.getPreviewService();if(e&&t.option){const i=n.asset?.fileLink;if(!i)throw new ke(n);await e.applyModelVariant(t.option.id,{model:i,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){n(!0);const i=A.asset?.fileLink;if(!i)throw new ke(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{const A=e.getPreviewService();A&&t.option&&A.applyModelVariant(t.option.id,{model:i,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ga=new class{async init(t,A,e){return e?(await this.reload(t,A,e),null):(A.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",A,"",(()=>{})))}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{A.updateStorage(t.stepName,{text:n?.storage?.text}),A.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,A,e,n,i){const a=await this.changeTextCommand(t,A,e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,A,e,n,i){const a=e.getRegionElements(t.stepName),o=e.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const r=e.getProfanities();if(!this.validateInput(t,A,r,i))return e.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(e.setMandatoryFulfilled(t.stepName,""!==A),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;e.updateStorage(t.stepName,{text:A});const s=(A,n,i)=>{const a=i||F(),o=e.getLayouts().find((t=>t.panelId===n.panelId));if(!o)return console.error(`Can not find layout for region: ${n.panelId}`),null;const r=[];return i&&r.push(new zA(a)),r.push(new TA({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:A,type:N.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},o)),{id:a,region:n,command:new JA(r)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const e=o.svgPrint(A,t.region);return s(e,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>s(o.svgPrint(A,t),t))),i=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(i),followup:async()=>{const A=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await e.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,A,e,n){if(t.data&&t.data.maxLength){const e=t.data.maxLength;if(A.length>e)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(A))return n("Unsupported characters."),!1;const i=A.toLowerCase();for(const t in e)if(i===e[t].toLowerCase().trim()&&""!==i)return n("Blocked profanity."),!1;return n(""),!0}};const ka=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else if(n.defaultVariant)return A.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,A,(()=>{}));return A.markStepsAsInitialised([t.stepName]),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants?.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=A.asset;if(!i)throw new ke(A);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),e.setMandatoryFulfilled(t.stepName,!1);const o=e.getRegionElements(t.stepName).map((t=>new zA(t.id))),r=t.data.regions.map((A=>{const n=e.getLayouts().find((t=>t.panelId===A.panelId));if(!n)throw new Ge(A);const i=F();return{regionElement:{id:i,region:A},command:new TA({stepName:t.stepName,stepRegion:A,id:i,src:a,type:N.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},n)}}));return{command:new JA([...o,...r.map((t=>t.command))]),followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],r.map((t=>t.regionElement)),(async()=>{e.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ba=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{const e=n.variants;if(En.getDefaultVariant(n)){const i=e?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,i?.id||"",A)}}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(i&&e){const n=i.variants?.find((t=>t.id===e));n&&await A.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,A,e){await e.getInitializationPromise();const n=await this.selectVariantLambda(t,A,e);n&&(n.command&&e.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,A,e){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const a=i.length>1?i.find((t=>t.id===A)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[a],[],(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ja=new class{async availableColours(t){const A=t.option;return A&&A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(!e){const e=En.getDefaultVariant(n);if(!e)return null;const i={fill:e.color,stroke:e.color,variant:e};return this.selectVariantCommand(t,i,[],A)}return await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants?.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.updateStorage(t.stepName,{colour:n.color||""}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=n.getLayouts();if(e.length>0){const a=t=>{const e=t.region;if(!i.find((t=>t.panelId===e?.panelId)))throw new Ge(e);const n=A.variant?.color;return n?new _A(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=e.map(a).filter((t=>!!t));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],e),n.updateStorage(t.stepName,{colour:A.fill||""})}}}{const e=e=>{const n=i.find((t=>t.panelId===e.panelId));if(!n)throw new Ge(e);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${A.variant?.color}"\n />\n </svg>\n `,o={};o["spiff-fill-shape"]={browserValue:A.variant.color};const r=F();return{id:r,region:e,command:new TA({stepRegion:e,stepName:t.stepName,colors:o,id:r,svg:a,type:N.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},a=t.data.regions.map(e),o=a.filter((t=>!!t)).map((t=>t?.command)),r=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],r,(async()=>{n.updateStorage(t.stepName,{colour:A.fill||""})}))}}}}};function La(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Oa=new class{constructor(){La(this,"latestToast",void 0),La(this,"toastType",void 0),La(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}setLatestToast(t,A){this.latestToast=t,this.toastType=A,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((t=>t({toastMessage:this.latestToast,toastType:this.toastType})))}};function Ta(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class za extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=za.name}}const ja=["‘","’","“","”","\n"];class Ka extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ka.name}}const Va=new class{constructor(){Ta(this,"cachedColors",new Map),Ta(this,"filterUnsupportedCharacters",((t,A)=>{let e=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=A?Vt(A):void 0;if(i){const t=e.split("").filter((t=>!ja.includes(t))).join(""),A=t.split("").map((t=>i.getFont().charToGlyph(t)));for(let e=0;e<A.length;e++){".notdef"===A[e].name&&n.push(String.fromCharCode(t.charCodeAt(e)))}}for(let t=0;t<n.length;t++)e=e.replaceAll(n[t],"");return e})),Ta(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Ta(this,"getErrorsForText",((t,A,e)=>{const n=[];A.data&&A.data.maxLength&&t.length>A.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=e.getProfanities(),a=t.toLowerCase();if(""!==a)for(const t in i){if(a===i[t].toLowerCase().trim()){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!A.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{A.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data)}),A.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data)});const e=En.getDefaultVariant(n);if(e)return this.selectVariantCommand(t,e,{},[],A,(()=>{}),(()=>{}))}return null}findLayoutElements(t,A){return t.getRegionElements(A.stepName).map((A=>SA(A.id,t.getAllLayoutData())))}availableColors(t){const A=this.cachedColors.get(t.stepName);if(A)return A;const e=t.data.colorOption;if(e){const A=e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,A),A}return[]}async changeFill(t,A,e,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher();A.variant?n.updateMetadata(t.stepName,{color:A.variant.name}):n.updateMetadata(t.stepName,{color:A.fill});const a=await this.getColorOption(t),o=a?this.createTextFillSpotColor(a,A.variant):void 0;a?n.updateStorage(t.stepName,{color:A.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:A.fill});for(const t of e){if(!A.fill)throw new Error("Fill not set on new color selection!");i(new KA(t.id,A.fill,o))}}getProcessedInput(t,A,e){const n=e?t:this.injectReplaceableText(t,A);return oA(n,{vertical:A.vertical,uppercase:A.uppercase})}updateInputText(t,A,e,n){const i=n.getStepStorage(e.stepName),a=this.getProcessedInput(t,e.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,e,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(e.data.maxLength-a.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&e.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of A){if(!t.fontData)throw new Oe("Failed to resolve font data for text.");const[A,n]=ye(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});g.set(t.id,A),l.set(t.id,n);const i=e.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(A,e.data,t.id,i,s))}if(!e.data.curved&&A.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(e.stepName,{text:t}),n.updateMetadata(e.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(e.stepName,!0),o.command=new JA(c),o.command.varying=s,o}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e.getStepStorage(t.stepName)||{},e.getRegionElements(t.stepName),e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,A){const e=t.colorProfile;if(e){const t=(e.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),i=t.slice(n+1).slice(0,-4);if(!A.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:A.namedColor}}}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const o=a.variants?.find((t=>t.id===e));if(o){const e=await this.fontDataFromVariant(o),a=i.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await A.setSelectionsAndElements(t.stepName,[o],a,(async()=>{A.updateMetadata(t.stepName,{color:r,text:s}),A.updateStorage(t.stepName,{text:s,inputText:s});const n=i.map((t=>new XA(t.id,e))),a=new JA(n);A.getCommandDispatcher()(a),A.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Va.updateInputText(s||"",i,t,A);c&&A.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const A=t.colorOption;if(A)return En.getDefaultVariant(A)}async getDefaultColor(t){const A=t.colorOption;if(!A)return;return En.getDefaultVariant(A)?.color}async getColorOption(t){return t.data.colorOption}async fontDataFromVariant(t){const A=t.asset;if(!A)throw new ke(t);const e=A.fileLink;if(!e)throw new be(A);return{assetUrl:e,name:(await jt(e)).names.fullName.en}}async selectVariantCommand(t,A,e,n,i,a,o){const r=i.markUpdatePending(),s=await this.fontDataFromVariant(A);if(n.length>0){const c=n.map((t=>new XA(t.id,s))),g=await this.changeInputTextWithRegion(t,t.data.size||30,s,e.text||"",e,i,!!e.customiseAllText,a,o);g&&c.push(g);return{command:new JA(c),followup:async()=>{i.markUpdateCompleted(r),await i.setSelectionsAndElements(t.stepName,[A],n)}}}{const n=await this.createTextboxRegions(t.stepName,A,t.data,s,e,i),c=await this.changeInputTextWithRegion(t,t.data.size||30,s,n[0]?.newElement.input||e.text||t.data.defaultText||"",e,i,!!e.customiseAllText,a,o),g=n.flatMap((t=>t.commands));c&&g.push(c);return{command:new JA(g),followup:async()=>{i.markUpdateCompleted(r)}}}}injectReplaceableText(t,A){return A.replaceableText?A.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,A,e,n,i,a){if(!e||!e.regions)throw new Error("Step data not supplied");const o=a.getTransaction().bulk&&e.varyText||!1,r=o?"":i.text||e.defaultText||"",s=this.getProcessedInput(r,e,!1),c=await Promise.all(e.regions.map((async A=>{const c=a.getLayouts().find((t=>t.panelId===A.panelId)),g=F();try{if(!c)throw new Ka("Failed to find layout for region: "+A.panelId);const l=e.colorOption;let B;if(l&&l.variants){const A=l.variants.find((t=>t.id===l.defaultVariant?.id))||l.variants[0];B=this.createTextFillSpotColor(l,A),a.updateStorage(t,{colorProfileAssetKey:l.colorProfile?.key})}const w=await this.getDefaultColor(e),h=w||"#000000",d={stepRegion:A,stepName:t,align:this.textAlign(e),fill:i.color?i.color:h,fontSize:e.size||30,fontData:n,id:g,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:s,input:r,type:N.Textbox,vertical:e.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:e.verticalAlign||"middle",curved:e.curved,paths:e.paths,fillSpotColorDefinition:B},E=[],u=new Map,Q=new Map;if(!d.fontData)throw new Oe("Failed to resolve font data for text.");const[C,m]=ye(d.fontSize,d.fontData,{left:d.x,top:d.y,width:d.width,height:d.height,rotation:d.rotation,panelId:""},[s],{size:e.size,minSize:e.minSize,maxSize:e.maxSize});u.set(d.id,C),Q.set(d.id,m);const p=e.curved||e.vertical?s:(m||[]).join("\n");E.push(this.generateTextChangeCommandsForRegion(C,e,d.id,p,o));const f=new TA(d,c);return f.varying=o,{regionElement:{id:g,region:A},commands:[f,...E],newElement:d,fontData:n}}catch(t){throw console.log(t),new za("Error adding font to region")}}))).catch((t=>{throw t instanceof za?(Oa.setLatestToast("Failed to load font.",Xa.Error),t):t instanceof Ka?t:new Error(t)}));return await a.setSelectionsAndElements(t,[A],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:r}),a.updateStorage(t,{text:r})})),c}generateTextChangeCommandsForRegion(t,A,e,n,i){const a=[],o=new $A(e,n);if(o.varying=i,a.push(o),!A.size){const A=new VA(e,t);A.varying=i,a.push(A)}const r=new JA(a);return r.varying=i,r}async changeInputTextWithRegion(t,A,e,n,i,a,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=a.getRegionElements(t.stepName),w=new Map,h=new Map;for(const n of B)if(n.region){const[i,a]=ye(A,e,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});w.set(n.id,i),h.set(n.id,a)}const d=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const A=l.toLowerCase(),e=a.getProfanities();for(const t in e)if(A===e[t].toLowerCase().trim()&&""!==A)return r(!0),{error:"Blocked profanity."};if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(d.error)return void s(d.error);if(s(`${d.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:g}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const E=a.getTransaction().bulk&&t.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const A of B){const e=t.data.curved?l:(h.get(A.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(w.get(A.id)||1,t.data,A.id,e,E))}const Q=new JA(u);return Q.varying=E,Q}};function Wa(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}let Xa;var qa;(qa=Xa||(Xa={})).Error="Error",qa.Warning="Warning",qa.Info="Info";class Za extends Qi{constructor(t){super(),Wa(this,"update",void 0),Wa(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class $a{constructor(t,A,e,n,i,a,o,r,s,c,g=!1){Wa(this,"reloadedState",void 0),Wa(this,"transaction",void 0),Wa(this,"ownerCustomer",void 0),Wa(this,"updateTransaction",void 0),Wa(this,"confirmedDesign",void 0),Wa(this,"editedSteps",void 0),Wa(this,"informationResults",void 0),Wa(this,"layouts",void 0),Wa(this,"mandatorySteps",void 0),Wa(this,"pendingUpdates",void 0),Wa(this,"selectionCost",void 0),Wa(this,"workflow",void 0),Wa(this,"stepSpecificServices",void 0),Wa(this,"previewService",void 0),Wa(this,"profanityFilter",void 0),Wa(this,"pollers",void 0),Wa(this,"commandContext",void 0),Wa(this,"stepElements",void 0),Wa(this,"stepInitialised",void 0),Wa(this,"stepMetadata",void 0),Wa(this,"stepSelections",void 0),Wa(this,"storage",void 0),Wa(this,"confirmCallbacks",void 0),Wa(this,"editedCallbacks",void 0),Wa(this,"elementsCallbacks",void 0),Wa(this,"informationResultCallbacks",void 0),Wa(this,"initCallbacks",void 0),Wa(this,"makingAdjustmentsCallback",void 0),Wa(this,"mandatoryCallbacks",void 0),Wa(this,"metadataCallbacks",void 0),Wa(this,"selectionCallbacks",void 0),Wa(this,"stepSpecificStorageCallbacks",void 0),Wa(this,"storageCallbacks",void 0),Wa(this,"currentVariationRecordCallbacks",void 0),Wa(this,"variationRecordCallbacks",void 0),Wa(this,"allScenes",void 0),Wa(this,"product",void 0),Wa(this,"invalidModelVariants",void 0),Wa(this,"currentAdjustingStepId",void 0),Wa(this,"renderableContextService",void 0),Wa(this,"workflowStatePromiseQueue",new Ci(1)),Wa(this,"variationRecords",[]),Wa(this,"currentVariationRecord",void 0),Wa(this,"initializationPromise",void 0),Wa(this,"initialized",!1),Wa(this,"readOnly",!1),Wa(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),A=this.getLayoutPreviewService()?.getAll();if(A)for(const[,e]of A)e.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=A,this.pollers=[],this.allScenes=[],this.layouts=e,this.product=o,this.previewService=r,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,A){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await ua(t,{bulkScene:A.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},A);const e=ma(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(e,!!this.reloadedState);this.commandContext.apply(new JA(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.readOnly&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const A=t.lookAtAnimation,e=t.modelAnimation;A&&this.previewService?.executeCameraAnimation(A),e&&this.previewService?.executeModelAnimation(e)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const A={...t,recordNumber:this.variationRecords.reduce(((t,A)=>A.recordNumber>t?A.recordNumber:t),0)+1};return this.variationRecords.push(A),this.onVariationRecordsChange(),A}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((A=>A.recordNumber!==t)),this.variationRecords.forEach(((t,A)=>t.recordNumber=A+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,A=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(A||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const A=this.variationRecords.find((A=>A.recordNumber===t.recordNumber));A&&(A.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,A){Object.keys(this.storage).includes(A)||(this.storage[A]={}),t(this.storage[A]),Object.keys(this.stepSpecificStorageCallbacks).includes(A)||(this.stepSpecificStorageCallbacks[A]=[]),this.stepSpecificStorageCallbacks[A].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((A=>{const e=this.stepSelections[A.stepName];e&&e.selectedVariants&&e.selectedVariants.length>0&&(t[A.stepName]={selections:e.selectedVariants})})),t}markStepsAsInitialised(t){const A={...this.stepInitialised};t.forEach((t=>{A[t]=!0})),this.stepInitialised=A,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((A=>A!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,A){this.editedSteps={...this.editedSteps,[t]:A},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,A){this.mandatorySteps[t]!==A&&(this.mandatorySteps={...this.mandatorySteps,[t]:A},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async updateStorage(t,A){const e={...this.storage,[t]:{...this.storage[t],...A}};if(!I(u)(e,this.storage)){this.storage=e;const A=new UA(this.constructSerializableWorkflow());this.commandContext.apply(A,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((A=>{A.renderableSteps.forEach((A=>{const e={stepName:A.stepName};e.storage=this.storage[A.stepName],e.selectedVariants=this.stepSelections[A.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(e)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Za((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Za((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new Oe("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(I(A)(t.transaction))),n=t.variation;if(!n)return{transaction:e};const i={layouts:{},serializableWorkflow:{steps:[]},...I(A)(n)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(i))}}dehydrateState(t){for(const A of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===A.type&&(delete A.cachedObjectURL,A.src&&delete A.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,A){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...A}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,A)=>Object.keys(t).reduce(((e,n)=>{const i=[...t[n]||[]];return A.forEach((t=>{const A=i.findIndex((A=>A.id===t.id));A>-1&&i.splice(A,1)})),e[n]=i,e}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,A)=>(Ca(A,this.stepSelections)||this.stepElements[A.stepName]&&this.stepElements[A.stepName].forEach((A=>t.push(A))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,A)=>("Model"===A.type&&A.option?.id&&!Ca(A,this.stepSelections)&&t.push(A.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,A){const e=this.product;if(!e)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,A,e)=>{if(t.type===K.SilentIllustration){return{step:t,results:await new xa(t,A).trigger()}}if(t.type===K.ProductOverlay){return{step:t,results:await new xa(t,A,e).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},o=[];for(const t of i)this.markStepsAsInitialised([t.stepName]),A||o.push(n(t,this.layouts,e));const r=await Promise.all(o);for(const t of r)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,A){return A.find((A=>A.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new zA(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,A,e,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:A}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,A)=>t+A.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,A)=>t+A),0)),0),this.workflow.steps.forEach((t=>{Ca(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,o=ma(a,i),r=ma(a,this.stepSelections),s=o.map((t=>t.silentSteps)).flat(),c=r.map((t=>t.silentSteps)).flat().filter((t=>!s.some((A=>A.stepName===t.stepName))));s.forEach((t=>{Ca(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const g=this.getInvalidCanvasRegions(),{stepElements:l,commands:B}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...l,[t]:e},this.removeElements(g);if(this.workflow.steps.find((A=>A.stepName===t))?.type===K.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(e.map((t=>t.id)))}const w=[...B,...g.map((t=>new zA(t.id))),new UA(this.constructSerializableWorkflow())];w.length>0&&this.commandContext.apply(new JA(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],A=ma(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const e of A)if(!this.stepInitialised[e.stepName])switch(this.stepInitialised[e.stepName]=!0,e.type){case K.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case K.DigitalContent:t.push(Sa.init(e,this,this.reloadedState));break;case K.Frame:case K.Photo:{const A=new ya(e.data.forceImageCover);A.connectWorkflowManager(this,e.stepName),this.stepSpecificServices[e.stepName]={frameService:A},t.push(Ra.init(e,this,this.reloadedState))}break;case K.Illustration:t.push(Ha.init(e,this,this.reloadedState));break;case K.Material:t.push(Pa.init(e,this,this.reloadedState));break;case K.Model:t.push(Ua.init(e,this,this.reloadedState));break;case K.Module:this.stepSpecificServices[e.stepName]={module:await bi(e.data.module)},t.push(Ga.init(e,this,this.reloadedState));break;case K.Picture:t.push(ka.init(e,this,this.reloadedState));break;case K.Question:t.push(ba.init(e,this,this.reloadedState));break;case K.Shape:t.push(Ja.init(e,this,this.reloadedState));break;case K.Text:t.push(Va.init(e,this,this.reloadedState))}const e=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=e.filter((t=>!!t&&!!t.command)).map((t=>t.command)),i=e.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new JA(n),!0);for(const t of i)await t();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const A of this.selectionCallbacks)A({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((A=>A(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return pa(this.allScenes,this.stepSelections)}}function _a(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class to{constructor(t,A){_a(this,"manager",void 0),_a(this,"step",void 0),this.manager=t,this.step=A}setUpdateState(t){to.updateState.set(this.step.stepName,t)}getUpdateState(){return!!to.updateState.get(this.step.stepName)}async getCurrentVariant(){return(await this.manager.getWorkflowSelections())[this.step.stepName]?.selections[0]}async getAvailableVariants(){return this.step.option?.variants||[]}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}}function Ao(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}_a(to,"updateState",new Map);const eo=t.gql`
|
|
425
|
+
`,da=t=>{const A=[];for(const e of t.steps)switch(e.type){case K.DigitalContent:e.data.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Frame:const t=e.data;t.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),t.varyUpload&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Upload});break;case K.Illustration:const n=e.data;n.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),n.varyColors&&n.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Colors});break;case K.Material:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Model:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Picture:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Question:e.data.varySelections&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selections});break;case K.Shape:e.data.varySelection&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection});break;case K.Text:const i=e.data;i.varyText&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Text}),i.varySelection&&e.option&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Selection}),i.varyColor&&i.colorPickerEnabled&&A.push({stepName:e.stepName,stepType:e.type,aspectType:W.Color})}return A},Ea=[K.SilentIllustration,K.ProductOverlay],ua=async(t,A,e)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:K.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const e of t.steps){if(A.bulkScene){let t=!1;switch(e.type){case K.DigitalContent:e.data.varyUpload&&(t=!0);break;case K.Frame:{const A=e.data;!A.varyUpload||!A.varySelection&&e.option||(t=!0)}break;case K.Illustration:{const A=e.data;!A.varySelection&&e.option&&1!==(e.option.variants||[]).length||!A.varyColors&&A.colorPickerEnabled||(t=!0)}break;case K.Material:e.data.varySelection&&(t=!0);break;case K.Model:e.data.varySelection&&(t=!0);break;case K.Picture:e.data.varySelection&&(t=!0);break;case K.Question:e.data.varySelections&&(t=!0);break;case K.Shape:e.data.varySelection&&(t=!0);break;case K.Text:{const A=e.data;!A.varySelection&&e.option&&1!==(e.option.variants||[]).length||!A.varyColor&&A.colorPickerEnabled&&A.colorOption||!A.varyText||(t=!0)}}if(t)continue}const i=Qa(e.stepName,t.stepGroups);if(i){const t=n.find((t=>t.name===i.name));t?Ea.includes(e.type)?t.silentSteps.push(e):t.renderableSteps.push(e):n.push({name:i.name,title:i.name,renderableSteps:Ea.includes(e.type)?[]:[e],silentSteps:Ea.includes(e.type)?[e]:[]})}else n.push({name:e.stepName,title:e.stepTitle,renderableSteps:Ea.includes(e.type)?[]:[e],silentSteps:Ea.includes(e.type)?[e]:[]})}if(A.bulkScene){const i=e?.product?.bulkConfiguration;n.push({name:"Bulk",title:i?.sceneTitle??A.bulkSceneTitle,renderableSteps:[{type:K.Bulk,stepName:"Bulk",stepTitle:i?.stepTitle??A.bulkSceneTitle,helpText:i?.helpText,data:{aspects:da(t)},conditions:[]}],silentSteps:[]})}return A.finishScene&&n.push({name:"Finish",title:A.finishSceneTitle,renderableSteps:[{type:K.Finish,stepName:"Finish",stepTitle:A.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},Qa=(t,A)=>A.find((A=>A.stepNames.includes(t))),Ca=(t,A)=>(t.conditions||[]).every((t=>{const e=A[t.targetStepName];if(e&&e.selectedVariants){const A=e.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==A.find((A=>A.id===t))))}return!1})),ma=(t,A)=>t.map((t=>((t,A)=>{const e={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ca(t,A))),silentSteps:t.silentSteps.filter((t=>Ca(t,A)))};return 0===e.silentSteps.length&&0===e.renderableSteps.length?null:e})(t,A))).filter((t=>null!==t)),pa=async(t,A)=>{const e=ma(t,A),n=[];for(const t of e)for(const A of t.renderableSteps)if(A.type===K.Model||A.type===K.Material||A.type===K.Picture||A.type===K.Shape){const t=(A.option?.variants||[]).length;t&&t>1&&n.push(A.stepName)}else n.push(A.stepName);const i=e.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of i)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return i};function fa(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}function Da(t,A,e,n){const i=e.width*t.zoom,a=e.height*t.zoom;if(n){const n=t,i=Math.max(A.width/e.width,A.height/e.height);n.zoom=Math.max(i,t.zoom);const a=e.width*n.zoom,o=e.height*n.zoom;return n.x=Ia(t.x,A.width-a,0),n.y=Ia(t.y,A.height-o,0),n}const o=t;return o.x=Ia(o.x,-i,A.width),o.y=Ia(o.y,-a,A.height),o}function Ia(t,A,e){return Math.min(Math.max(t,A),e)}class ya{constructor(t){fa(this,"offsets",void 0),fa(this,"forceImageCover",void 0),fa(this,"targetElements",void 0),fa(this,"imageData",void 0),fa(this,"frameData",void 0),fa(this,"_debouncedUpdateFrameOffsets",void 0),fa(this,"minZoomScale",.03),fa(this,"maxZoomScale",20),fa(this,"onFrameDataChangeListeners",void 0),fa(this,"onZoomChangeListeners",void 0),fa(this,"workflowManager",void 0),fa(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=I(p)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,A){A&&t.addStepSpecificStorageCallback((async t=>{if(t){const A=t;if(A.currentFrameSource){const t=await Qe(A.currentFrameSource);I(u)(t,this.frameData)||(this.frameData=t,this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.offsets=Ce(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),A),this.workflowManager=t,this.stepName=A}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}async setFrameData(t){const A=he.get(t);this.frameData=A}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,A,e,n){if(this.imageData&&this.offsets&&this.frameData){const i=(A-this.offsets.x)/this.offsets.zoom,a=(e-this.offsets.y)/this.offsets.zoom,o={x:A-i*t,y:e-a*t,zoom:this.imageData.width*t/this.imageData.width};this.updateOffsets(Da(o,this.frameData,this.imageData,this.forceImageCover),n),this.onZoomChangeListeners.forEach((A=>A(t)))}}setPatternData(t){(t&&this.frameData||t&&this.frameData&&!this.imageData)&&(this.offsets=Ce(t,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements),this.updateOffsets(Da(this.offsets,this.frameData,t,this.forceImageCover))),this.imageData=t,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,A){const e=this.imageData;e&&this.frameData&&(this.offsets&&t.x===this.offsets.x&&t.y===this.offsets.y&&t.zoom===this.offsets.zoom?A&&A():(this.offsets=Da(t,this.frameData,e,this.forceImageCover),this._debouncedUpdateFrameOffsets(t,e,this.frameData,this.targetElements,A)))}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,A,e,n,i){if(!e)throw new Oe("Frame data not set. This is a bug");if(!this.workflowManager)throw new Oe("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach((e=>{a(new ZA(e,A,t))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:t}),i&&i()}recalculateZoomLimits(t,A){const e=Math.max(A.width/t.width,A.height/t.height);this.forceImageCover?(this.minZoomScale=e,this.maxZoomScale=2.5*e):(this.minZoomScale=e/10,this.maxZoomScale=2.5*e)}}function Ma(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class xa{constructor(t,A,e){Ma(this,"configuration",void 0),Ma(this,"layouts",void 0),Ma(this,"product",void 0),Ma(this,"processRegion",(async t=>{const A=this.layouts.find((A=>A.panelId===t.panelId));if(!A)throw new Ge(t);let e="";if(this.configuration.type===K.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),e=t,!t)throw new Je(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===N.Image){const e=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!e)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:e,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:t},command:new TA(i,A)}}{const i=this.configuration.type===K.SilentIllustration?this.configuration.data.asset?.fileLink:e,a=async()=>new Promise(((t,A)=>{i?Nt(i).then((A=>{t(A)})).catch((t=>console.error(t))):A("Undefined vector silent step source")})),o=await IA(await a()),r={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await ve(o.svg),src:i,svg:o.svg,colors:o.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===K.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:r.id,region:t},command:new TA(r,A)}}})),this.configuration=t,this.layouts=A,this.product=e||void 0}async trigger(){if(!this.configuration.data.regions)throw new Je(this.configuration,"Missing regions.");if(this.configuration.type===K.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===K.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((A=>t.panelId===A.panelId)))throw new Ge(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===K.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?N.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),N.Illustration)}}const Fa=async t=>{const A=`${Ze.getServicesApiUrl()}/shortener`;try{const e=await fetch(A,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await e.json()).shortUrl}catch(t){throw console.error(t),new je("Failed to shorten URL, see console.")}};function Ya(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class va{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,A,e,n=3e3,i=10){Ya(this,"pollingId",void 0),Ya(this,"attempts",void 0),Ya(this,"interval",void 0),Ya(this,"maxAttempts",void 0),Ya(this,"predicate",void 0),Ya(this,"onSuccess",void 0),Ya(this,"onFailure",void 0),this.onSuccess=A,this.onFailure=e,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const Sa=new class{async init(t,A,e){return e&&await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{const e=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;A.updateStorage(t.stepName,{videoShortUrl:e,videoUrl:i})}))}async regenerateQRCode(t,A,e,n,i,a,o,r,s){if(A||""===e||""!==n)s(!1);else{const A=async()=>{const t=(await cn([e]))[0],A=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:A}},c=await new Promise(((t,e)=>{new va((async()=>!!(await A()).link),(async()=>{const e=await A();if(!e.link||!e.link)throw new be(e.asset);t({rel:"mpeg4",href:e.link})}),(()=>{e("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new zA(t.id))));const g="http"===a.data.baseUrl.slice(0,4)?"":"https://",l=new URL(g+a.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([c]))),l.pathname=l.pathname+("/"===l.pathname.slice(-1)?"":"/");const B=l.toString();if(B.length>=2e3)throw new je("Cannot create QR code, URL too long.");const w=await Fa(B);if(o(w),!a.data||!a.data.regions)throw new Je(a,"Missing regions.");const h=await this.regionElements(a),d=await this.command(w,h,i,a.stepName);d&&(d.command&&i.getCommandDispatcher()(d.command),d.followup&&await d.followup()),await i.setSelectionsAndElements(a.stepName,[],h,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:w,videoUrl:n}),s(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,A,e,n){const i=e.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,C.toString)(t,{type:"svg"}))}`,o=A.map((t=>{const A=t.region,e=i.find((t=>t.panelId===A?.panelId));if(!e&&A)throw new Ge(A);if(e&&!A)throw new Error("Region not found");if(!e||!A)throw new Error("Neither a region or layout found!");return new TA({stepRegion:A,stepName:n,id:t.id,src:a,type:N.Image,y:A.top,x:A.left,width:A.width,height:A.height,rotation:0},e)}));return{command:new JA(o),followup:async()=>{}}}};function Na(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Ra=new class{constructor(){Na(this,"frameSourceSvg",(async(t,A)=>{if(!t)return Ee(A.data.regions[0]);const e=t.asset;if(!e)throw new ke(t);const n=e.fileLink;if(n)return Nt(n);throw new be(e)}))}async init(t,A,e){if(e)return await this.reload(t,A,e),null;if(A.setMandatoryFulfilled(t.stepName,!1),A.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const e=t.option,n=En.getDefaultVariant(e);return n?this.selectVariantCommand(t,n,[],A,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],A,void 0,t.data.placeholderImageUrl)}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const e=Ee(t.data.regions[0]);A.updateStorage(t.stepName,{currentFrameSource:e})}if(n){const e=async()=>{const e=n.storage?.framePatternSrc,i=n.storage?.frameOffsets;if(A.updateMetadata(t.stepName,{frameOffsets:i,framePatternSrc:e}),e){const n=A.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(e,n),A.updateMetadata(t.stepName,{image:e}),A.updateStorage(t.stepName,{framePatternSrc:e})}if(i?.zoom){const e=A.getStepSpecificServices(t.stepName)?.frameService;e.updateOffsets(i)}A.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants?.find((t=>t.id===a));n&&await A.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=await this.frameSourceSvg(n,t);A.updateStorage(t.stepName,{currentFrameSource:i}),await e()}))}}else await A.setSelectionsAndElements(t.stepName,[],i,e)}}selectImage(t,A,e){e.setEditedStatus(t.stepName,!0);(A.fileLink||"").endsWith("pdf")?e.addPoller(new va((async()=>{const t=(await Bn.getLocalOrFromServer(A.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Bn.getLocalOrFromServer(A.key||"").then((A=>{this.loadPatternFromAsset(A,t,e)}))}),(()=>{throw new je("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(A,t,e)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,A,e,n){return new TA({id:t,type:N.Frame,x:A.left,y:A.top,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,scaleX:A.width/n.frameData.width,scaleY:A.height/n.frameData.height,path:n.frameData.path,stepRegion:A,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:A.immutable},e)}async loadPatternFromString(t,A){if(t.endsWith("svg")){const e=await pe(t),n=e.width,i=e.height,a={src:t,width:n,height:i,aspect:n/i};we.set(t,a),A.setPatternData(a)}else{const e=await St(t),n=await le(e),i={src:t,width:n.width,height:n.height,aspect:n.width/n.height};we.set(t,i),A.setPatternData(i)}}async selectVariantCommand(t,A,e,n,i,a){const o=n.getStepSpecificServices(t.stepName)?.frameService,r=await this.frameSourceSvg(A,t),s=await Qe(r),c=o.getImageData(),g=e.map((t=>new zA(t.id))),l=c?Ce(c,s):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0;i&&i(!0);const w=t.data.regions.map((A=>{const e=F(),i=n.getLayouts().find((t=>t.panelId===A.panelId));if(!i)throw new Ge(A);return{command:this.getCreateElementCommand(e,A,i,{frameData:s,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:e,region:A}}})),h=w.map((t=>t.command));return{command:new JA([...h,...g]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,A?[A]:[],[...w.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSource:r}),a){const A=n.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(a,A)}}))}}}patternSource(t){const A=t.versions?.find((t=>"svg"===t.name));if(A)return A.link;const e=t.fileLink;if(e)return e;throw new be(t)}async loadPatternFromAsset(t,A,e){const n=this.patternSource(t),i=e.markUpdatePending(),a=e.getStepSpecificServices(A.stepName)?.frameService;await this.loadPatternFromString(n,a),e.updateMetadata(A.stepName,{image:n}),e.updateStorage(A.stepName,{framePatternSrc:n}),e.markUpdateCompleted(i)}};const Ha=new class{async getIllustrationBody(t){return new Promise((A=>{Nt(t).then((t=>{A(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,A,e,n){return new TA({stepRegion:A,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:N.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},e)}getColors(t,A){const e=A.getRegionElements(t.stepName)||[];if(0===e.length)return[];try{return SA(e[0].id,A.getAllLayoutData()).colors}catch(t){return[]}}async init(t,A,e){const n=t.option;if(!n)return null;if(e)return this.reload(t,A,e);{const e=En.getDefaultVariant(n);if(e)return await this.selectVariantCommand(t,e,[],(()=>{}),A)}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(!a||!e)throw new Error("Required illustration variant no longer available");{const o=a.variants?.find((t=>t.id===e));if(o){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[o],e,(async()=>{A.updateMetadata(t.stepName,{colors:n.storage?.colors}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,A){const e=t.data.colorOption;return e&&e?e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,A,e,n,i){const a={};for(const[t,A]of i.entries())a[t]={browserValue:A,spotColor:a[t]?.spotColor};const o=DA(t,A,e,a),r=await ve(o),s=[];for(const t of n){for(const[A,e]of i.entries())s.push(new _A(t,A,e));s.push(new te(t,o,r))}return new JA(s)}async changeColors(t,A,e,n,i){if(0===A.length)return;const a=SA(A[0].id,n().map((t=>t.layoutState))),o={...a.colors},r={};Object.entries(o).forEach((([t,A])=>{const e={browserValue:A.browserValue},n=A.spotColor;n&&(e.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=e}));for(const[t,A]of i.entries())o[t]={browserValue:A,spotColor:o[t]?.spotColor},r[t]={browserValue:A};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),e.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,A])=>{g.set(t,A.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(a.svg,a.width,a.height,A.map((t=>t.id)),g);e.updateStorage(t.stepName,{colors:r}),e.getCommandDispatcher()(l)}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,A,e,n,i){if(!t.data||!t.data.regions)throw new Je(t,"Missing regions.");n(!0);const a=e.map((t=>new zA(t.id)));i.setMandatoryFulfilled(t.stepName,!1);const o=A.asset;if(!o)throw new ke(A);const r=o.fileLink;if(!r)throw new be(o);const s=await IA(await this.getIllustrationBody(r)),c=await ve(s.svg),g=t.data.regions.map((A=>{const e=i.getLayouts().find((t=>t.panelId===A.panelId));if(!e)throw new Ge(A);const n=F();return{regionElement:{id:n,region:A},command:this.getCreateElementCommand(n,A,e,{stepName:t.stepName,src:r,objectURL:c,svg:s})}})),l=[...g.map((t=>t.command)),...a];let B=Array.from(Object.values(s.colors)).map((t=>t.browserValue));const w=t.data.colorOption;return w&&w.variants?.forEach((t=>{B=B.map((A=>A.toLowerCase()===t.color?.toLowerCase()?t.name:A))})),i.updateMetadata(t.stepName,{colors:B}),{command:new JA(l),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[A],g.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Pa=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=En.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(!a)throw new Ue(t);if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(e){const n=a.variants?.find((t=>t.id===e));if(n){const e=n.material,o=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=A.getPreviewService();if(n){const i=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id,e)));Promise.all(i).then((()=>A.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){const i=e.getPreviewService();n(!0);const a=A.material;if(!a)throw n(!1),new ke(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{i&&t.data.targetMaterials.forEach((A=>{t.option&&i.applyMaterialVariant(A,t.option.id,a)})),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ua=new class{async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(e)await this.reload(t,A,e);else{const e=En.getDefaultVariant(n);if(e)return await this.selectVariantLambda(t,e,A,(()=>{}))}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants?.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{const e=A.getPreviewService();if(e&&t.option){const i=n.asset?.fileLink;if(!i)throw new ke(n);await e.applyModelVariant(t.option.id,{model:i,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantLambda(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,A,e,n){n(!0);const i=A.asset?.fileLink;if(!i)throw new ke(A);return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],[],(async()=>{try{const A=e.getPreviewService();A&&t.option&&A.applyModelVariant(t.option.id,{model:i,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ga=new class{async init(t,A,e){return e?(await this.reload(t,A,e),null):(A.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",A,"",(()=>{})))}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[],i,(async()=>{A.updateStorage(t.stepName,{text:n?.storage?.text}),A.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,A,e,n,i){const a=await this.changeTextCommand(t,A,e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,A,e,n,i){const a=e.getRegionElements(t.stepName),o=e.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const r=e.getProfanities();if(!this.validateInput(t,A,r,i))return e.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(e.setMandatoryFulfilled(t.stepName,""!==A),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;e.updateStorage(t.stepName,{text:A});const s=(A,n,i)=>{const a=i||F(),o=e.getLayouts().find((t=>t.panelId===n.panelId));if(!o)return console.error(`Can not find layout for region: ${n.panelId}`),null;const r=[];return i&&r.push(new zA(a)),r.push(new TA({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:A,type:N.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},o)),{id:a,region:n,command:new JA(r)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const e=o.svgPrint(A,t.region);return s(e,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>s(o.svgPrint(A,t),t))),i=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new JA(i),followup:async()=>{const A=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await e.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,A,e,n){if(t.data&&t.data.maxLength){const e=t.data.maxLength;if(A.length>e)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(A))return n("Unsupported characters."),!1;const i=A.toLowerCase();for(const t in e)if(i===e[t].toLowerCase().trim()&&""!==i)return n("Blocked profanity."),!1;return n(""),!0}};const ka=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else if(n.defaultVariant)return A.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,A,(()=>{}));return A.markStepsAsInitialised([t.stepName]),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants?.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&e.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=A.asset;if(!i)throw new ke(A);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),e.setMandatoryFulfilled(t.stepName,!1);const o=e.getRegionElements(t.stepName).map((t=>new zA(t.id))),r=t.data.regions.map((A=>{const n=e.getLayouts().find((t=>t.panelId===A.panelId));if(!n)throw new Ge(A);const i=F();return{regionElement:{id:i,region:A},command:new TA({stepName:t.stepName,stepRegion:A,id:i,src:a,type:N.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},n)}}));return{command:new JA([...o,...r.map((t=>t.command))]),followup:async()=>{await e.setSelectionsAndElements(t.stepName,[A],r.map((t=>t.regionElement)),(async()=>{e.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ba=new class{async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{const e=n.variants;if(En.getDefaultVariant(n)){const i=e?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,i?.id||"",A)}}return null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(i&&e){const n=i.variants?.find((t=>t.id===e));n&&await A.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,A,e){await e.getInitializationPromise();const n=await this.selectVariantLambda(t,A,e);n&&(n.command&&e.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,A,e){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const a=i.length>1?i.find((t=>t.id===A)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await e.setSelectionsAndElements(t.stepName,[a],[],(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ja=new class{async availableColours(t){const A=t.option;return A&&A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,A,e){const n=t.option;if(!n)throw new Ue(t);if(!e){const e=En.getDefaultVariant(n);if(!e)return null;const i={fill:e.color,stroke:e.color,variant:e};return this.selectVariantCommand(t,i,[],A)}return await this.reload(t,A,e),null}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const n=a.variants?.find((t=>t.id===e));if(n){const e=i.map((t=>({id:t.id,region:t.stepRegion})));await A.setSelectionsAndElements(t.stepName,[n],e,(async()=>{A.updateStorage(t.stepName,{colour:n.color||""}),A.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,A,e,n){const i=await this.selectVariantCommand(t,A,e,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,A,e,n){const i=n.getLayouts();if(e.length>0){const a=t=>{const e=t.region;if(!i.find((t=>t.panelId===e?.panelId)))throw new Ge(e);const n=A.variant?.color;return n?new _A(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=e.map(a).filter((t=>!!t));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],e),n.updateStorage(t.stepName,{colour:A.fill||""})}}}{const e=e=>{const n=i.find((t=>t.panelId===e.panelId));if(!n)throw new Ge(e);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${A.variant?.color}"\n />\n </svg>\n `,o={};o["spiff-fill-shape"]={browserValue:A.variant.color};const r=F();return{id:r,region:e,command:new TA({stepRegion:e,stepName:t.stepName,colors:o,id:r,svg:a,type:N.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},a=t.data.regions.map(e),o=a.filter((t=>!!t)).map((t=>t?.command)),r=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new JA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,A.variant?[A.variant]:[],r,(async()=>{n.updateStorage(t.stepName,{colour:A.fill||""})}))}}}}};function La(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}const Oa=new class{constructor(){La(this,"latestToast",void 0),La(this,"toastType",void 0),La(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}setLatestToast(t,A){this.latestToast=t,this.toastType=A,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((t=>t({toastMessage:this.latestToast,toastType:this.toastType})))}};function Ta(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class za extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=za.name}}const ja=["‘","’","“","”","\n"];class Ka extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ka.name}}const Va=new class{constructor(){Ta(this,"cachedColors",new Map),Ta(this,"filterUnsupportedCharacters",((t,A)=>{let e=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=A?Vt(A):void 0;if(i){const t=e.split("").filter((t=>!ja.includes(t))).join(""),A=t.split("").map((t=>i.getFont().charToGlyph(t)));for(let e=0;e<A.length;e++){".notdef"===A[e].name&&n.push(String.fromCharCode(t.charCodeAt(e)))}}for(let t=0;t<n.length;t++)e=e.replaceAll(n[t],"");return e})),Ta(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Ta(this,"getErrorsForText",((t,A,e)=>{const n=[];A.data&&A.data.maxLength&&t.length>A.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=e.getProfanities(),a=t.toLowerCase();if(""!==a)for(const t in i){if(a===i[t].toLowerCase().trim()){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!A.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,A,e){const n=t.option;if(!n)return null;if(e)await this.reload(t,A,e);else{A.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data)}),A.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data)});const e=En.getDefaultVariant(n);if(e)return this.selectVariantCommand(t,e,{},[],A,(()=>{}),(()=>{}))}return null}findLayoutElements(t,A){return t.getRegionElements(A.stepName).map((A=>SA(A.id,t.getAllLayoutData())))}availableColors(t){const A=this.cachedColors.get(t.stepName);if(A)return A;const e=t.data.colorOption;if(e){const A=e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,A),A}return[]}async changeFill(t,A,e,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher();A.variant?n.updateMetadata(t.stepName,{color:A.variant.name}):n.updateMetadata(t.stepName,{color:A.fill});const a=await this.getColorOption(t),o=a?this.createTextFillSpotColor(a,A.variant):void 0;a?n.updateStorage(t.stepName,{color:A.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:A.fill});for(const t of e){if(!A.fill)throw new Error("Fill not set on new color selection!");i(new KA(t.id,A.fill,o))}}getProcessedInput(t,A,e){const n=e?t:this.injectReplaceableText(t,A);return oA(n,{vertical:A.vertical,uppercase:A.uppercase})}updateInputText(t,A,e,n){const i=n.getStepStorage(e.stepName),a=this.getProcessedInput(t,e.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,e,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(e.data.maxLength-a.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&e.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of A){if(!t.fontData)throw new Oe("Failed to resolve font data for text.");const[A,n]=ye(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});g.set(t.id,A),l.set(t.id,n);const i=e.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(A,e.data,t.id,i,s))}if(!e.data.curved&&A.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(e.stepName,{text:t}),n.updateMetadata(e.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(e.stepName,!0),o.command=new JA(c),o.command.varying=s,o}async selectVariant(t,A,e,n,i){const a=await this.selectVariantCommand(t,A,e.getStepStorage(t.stepName)||{},e.getRegionElements(t.stepName),e,n,i);a&&(a.command&&e.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,A){const e=t.colorProfile;if(e){const t=(e.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),i=t.slice(n+1).slice(0,-4);if(!A.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:A.namedColor}}}async reload(t,A,e){const n=A.getSerializedStep(t.stepName,e.serializableWorkflow.steps),i=Object.values(e.layouts).map((t=>t.elements)).flat().filter((A=>A.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const e=n.selectedVariants[0].id;if(a&&e){const o=a.variants?.find((t=>t.id===e));if(o){const e=await this.fontDataFromVariant(o),a=i.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await A.setSelectionsAndElements(t.stepName,[o],a,(async()=>{A.updateMetadata(t.stepName,{color:r,text:s}),A.updateStorage(t.stepName,{text:s,inputText:s});const n=i.map((t=>new XA(t.id,e))),a=new JA(n);A.getCommandDispatcher()(a),A.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Va.updateInputText(s||"",i,t,A);c&&A.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const A=t.colorOption;if(A)return En.getDefaultVariant(A)}async getDefaultColor(t){const A=t.colorOption;if(!A)return;return En.getDefaultVariant(A)?.color}async getColorOption(t){return t.data.colorOption}async fontDataFromVariant(t){const A=t.asset;if(!A)throw new ke(t);const e=A.fileLink;if(!e)throw new be(A);return{assetUrl:e,name:(await jt(e)).names.fullName.en}}async selectVariantCommand(t,A,e,n,i,a,o){const r=i.markUpdatePending(),s=await this.fontDataFromVariant(A);if(n.length>0){const c=n.map((t=>new XA(t.id,s))),g=await this.changeInputTextWithRegion(t,t.data.size||30,s,e.text||"",e,i,!!e.customiseAllText,a,o);g&&c.push(g);return{command:new JA(c),followup:async()=>{i.markUpdateCompleted(r),await i.setSelectionsAndElements(t.stepName,[A],n)}}}{const n=await this.createTextboxRegions(t.stepName,A,t.data,s,e,i),c=await this.changeInputTextWithRegion(t,t.data.size||30,s,n[0]?.newElement.input||e.text||t.data.defaultText||"",e,i,!!e.customiseAllText,a,o),g=n.flatMap((t=>t.commands));c&&g.push(c);return{command:new JA(g),followup:async()=>{i.markUpdateCompleted(r)}}}}injectReplaceableText(t,A){return A.replaceableText?A.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,A,e,n,i,a){if(!e||!e.regions)throw new Error("Step data not supplied");const o=a.getTransaction().bulk&&e.varyText||!1,r=o?"":i.text||e.defaultText||"",s=this.getProcessedInput(r,e,!1),c=await Promise.all(e.regions.map((async A=>{const c=a.getLayouts().find((t=>t.panelId===A.panelId)),g=F();try{if(!c)throw new Ka("Failed to find layout for region: "+A.panelId);const l=e.colorOption;let B;if(l&&l.variants){const A=l.variants.find((t=>t.id===l.defaultVariant?.id))||l.variants[0];B=this.createTextFillSpotColor(l,A),a.updateStorage(t,{colorProfileAssetKey:l.colorProfile?.key})}const w=await this.getDefaultColor(e),h=w||"#000000",d={stepRegion:A,stepName:t,align:this.textAlign(e),fill:i.color?i.color:h,fontSize:e.size||30,fontData:n,id:g,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:s,input:r,type:N.Textbox,vertical:e.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:e.verticalAlign||"middle",curved:e.curved,paths:e.paths,fillSpotColorDefinition:B},E=[],u=new Map,Q=new Map;if(!d.fontData)throw new Oe("Failed to resolve font data for text.");const[C,m]=ye(d.fontSize,d.fontData,{left:d.x,top:d.y,width:d.width,height:d.height,rotation:d.rotation,panelId:""},[s],{size:e.size,minSize:e.minSize,maxSize:e.maxSize});u.set(d.id,C),Q.set(d.id,m);const p=e.curved||e.vertical?s:(m||[]).join("\n");E.push(this.generateTextChangeCommandsForRegion(C,e,d.id,p,o));const f=new TA(d,c);return f.varying=o,{regionElement:{id:g,region:A},commands:[f,...E],newElement:d,fontData:n}}catch(t){throw console.log(t),new za("Error adding font to region")}}))).catch((t=>{throw t instanceof za?(Oa.setLatestToast("Failed to load font.",Xa.Error),t):t instanceof Ka?t:new Error(t)}));return await a.setSelectionsAndElements(t,[A],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:r}),a.updateStorage(t,{text:r})})),c}generateTextChangeCommandsForRegion(t,A,e,n,i){const a=[],o=new $A(e,n);if(o.varying=i,a.push(o),!A.size){const A=new VA(e,t);A.varying=i,a.push(A)}const r=new JA(a);return r.varying=i,r}async changeInputTextWithRegion(t,A,e,n,i,a,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=a.getRegionElements(t.stepName),w=new Map,h=new Map;for(const n of B)if(n.region){const[i,a]=ye(A,e,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});w.set(n.id,i),h.set(n.id,a)}const d=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const A=l.toLowerCase(),e=a.getProfanities();for(const t in e)if(A===e[t].toLowerCase().trim()&&""!==A)return r(!0),{error:"Blocked profanity."};if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(d.error)return void s(d.error);if(s(`${d.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:g}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const E=a.getTransaction().bulk&&t.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const A of B){const e=t.data.curved?l:(h.get(A.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(w.get(A.id)||1,t.data,A.id,e,E))}const Q=new JA(u);return Q.varying=E,Q}};function Wa(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}let Xa;var qa;(qa=Xa||(Xa={})).Error="Error",qa.Warning="Warning",qa.Info="Info";class Za extends Qi{constructor(t){super(),Wa(this,"update",void 0),Wa(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class $a{constructor(t,A,e,n,i,a,o,r,s,c,g=!1){Wa(this,"reloadedState",void 0),Wa(this,"transaction",void 0),Wa(this,"ownerCustomer",void 0),Wa(this,"updateTransaction",void 0),Wa(this,"confirmedDesign",void 0),Wa(this,"editedSteps",void 0),Wa(this,"informationResults",void 0),Wa(this,"layouts",void 0),Wa(this,"mandatorySteps",void 0),Wa(this,"pendingUpdates",void 0),Wa(this,"selectionCost",void 0),Wa(this,"workflow",void 0),Wa(this,"stepSpecificServices",void 0),Wa(this,"previewService",void 0),Wa(this,"profanityFilter",void 0),Wa(this,"pollers",void 0),Wa(this,"commandContext",void 0),Wa(this,"stepElements",void 0),Wa(this,"stepInitialised",void 0),Wa(this,"stepMetadata",void 0),Wa(this,"stepSelections",void 0),Wa(this,"storage",void 0),Wa(this,"confirmCallbacks",void 0),Wa(this,"editedCallbacks",void 0),Wa(this,"elementsCallbacks",void 0),Wa(this,"informationResultCallbacks",void 0),Wa(this,"initCallbacks",void 0),Wa(this,"makingAdjustmentsCallback",void 0),Wa(this,"mandatoryCallbacks",void 0),Wa(this,"metadataCallbacks",void 0),Wa(this,"selectionCallbacks",void 0),Wa(this,"stepSpecificStorageCallbacks",void 0),Wa(this,"storageCallbacks",void 0),Wa(this,"currentVariationRecordCallbacks",void 0),Wa(this,"variationRecordCallbacks",void 0),Wa(this,"allScenes",void 0),Wa(this,"product",void 0),Wa(this,"invalidModelVariants",void 0),Wa(this,"currentAdjustingStepId",void 0),Wa(this,"renderableContextService",void 0),Wa(this,"workflowStatePromiseQueue",new Ci(1)),Wa(this,"variationRecords",[]),Wa(this,"currentVariationRecord",void 0),Wa(this,"initializationPromise",void 0),Wa(this,"initialized",!1),Wa(this,"readOnly",!1),Wa(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),A=this.getLayoutPreviewService()?.getAll();if(A)for(const[,e]of A)e.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=A,this.pollers=[],this.allScenes=[],this.layouts=e,this.product=o,this.previewService=r,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,A){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await ua(t,{bulkScene:A.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},A);const e=ma(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(e,!!this.reloadedState);this.commandContext.apply(new JA(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.readOnly&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const A=t.lookAtAnimation,e=t.modelAnimation;A&&this.previewService?.executeCameraAnimation(A),e&&this.previewService?.executeModelAnimation(e)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const A={...t,recordNumber:this.variationRecords.reduce(((t,A)=>A.recordNumber>t?A.recordNumber:t),0)+1};return this.variationRecords.push(A),this.onVariationRecordsChange(),A}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((A=>A.recordNumber!==t)),this.variationRecords.forEach(((t,A)=>t.recordNumber=A+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,A=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(A||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const A=this.variationRecords.find((A=>A.recordNumber===t.recordNumber));A&&(A.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,A){Object.keys(this.storage).includes(A)||(this.storage[A]={}),t(this.storage[A]),Object.keys(this.stepSpecificStorageCallbacks).includes(A)||(this.stepSpecificStorageCallbacks[A]=[]),this.stepSpecificStorageCallbacks[A].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((A=>{const e=this.stepSelections[A.stepName];e&&e.selectedVariants&&e.selectedVariants.length>0&&(t[A.stepName]={selections:e.selectedVariants})})),t}markStepsAsInitialised(t){const A={...this.stepInitialised};t.forEach((t=>{A[t]=!0})),this.stepInitialised=A,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((A=>A!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,A){this.editedSteps={...this.editedSteps,[t]:A},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,A){this.mandatorySteps[t]!==A&&(this.mandatorySteps={...this.mandatorySteps,[t]:A},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async updateStorage(t,A){const e={...this.storage,[t]:{...this.storage[t],...A}};if(!I(u)(e,this.storage)){this.storage=e;const A=new UA(this.constructSerializableWorkflow());this.commandContext.apply(A,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((A=>{A.renderableSteps.forEach((A=>{const e={stepName:A.stepName};e.storage=this.storage[A.stepName],e.selectedVariants=this.stepSelections[A.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(e)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Za((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Za((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new Oe("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(I(A)(t.transaction))),n=t.variation;if(!n)return{transaction:e};const i={layouts:{},serializableWorkflow:{steps:[]},...I(A)(n)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(i))}}dehydrateState(t){for(const A of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===A.type&&(delete A.cachedObjectURL,A.src&&delete A.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,A){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...A}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,A)=>Object.keys(t).reduce(((e,n)=>{const i=[...t[n]||[]];return A.forEach((t=>{const A=i.findIndex((A=>A.id===t.id));A>-1&&i.splice(A,1)})),e[n]=i,e}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,A)=>(Ca(A,this.stepSelections)||this.stepElements[A.stepName]&&this.stepElements[A.stepName].forEach((A=>t.push(A))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,A)=>("Model"===A.type&&A.option?.id&&!Ca(A,this.stepSelections)&&t.push(A.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,A){const e=this.product;if(!e)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,A,e)=>{if(t.type===K.SilentIllustration){return{step:t,results:await new xa(t,A).trigger()}}if(t.type===K.ProductOverlay){return{step:t,results:await new xa(t,A,e).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},o=[];for(const t of i)this.markStepsAsInitialised([t.stepName]),A||o.push(n(t,this.layouts,e));const r=await Promise.all(o);for(const t of r)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,A){return A.find((A=>A.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new zA(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,A,e,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:A}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,A)=>t+A.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,A)=>t+A),0)),0),this.workflow.steps.forEach((t=>{Ca(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,o=ma(a,i),r=ma(a,this.stepSelections),s=o.map((t=>t.silentSteps)).flat(),c=r.map((t=>t.silentSteps)).flat().filter((t=>!s.some((A=>A.stepName===t.stepName))));s.forEach((t=>{Ca(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const g=this.getInvalidCanvasRegions(),{stepElements:l,commands:B}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...l,[t]:e},this.removeElements(g);if(this.workflow.steps.find((A=>A.stepName===t))?.type===K.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(e.map((t=>t.id)))}const w=[...B,...g.map((t=>new zA(t.id))),new UA(this.constructSerializableWorkflow())];w.length>0&&this.commandContext.apply(new JA(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],A=ma(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const e of A)if(!this.stepInitialised[e.stepName])switch(this.stepInitialised[e.stepName]=!0,e.type){case K.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case K.DigitalContent:t.push(Sa.init(e,this,this.reloadedState));break;case K.Frame:case K.Photo:{const A=new ya(e.data.forceImageCover);A.connectWorkflowManager(this,e.stepName),this.stepSpecificServices[e.stepName]={frameService:A},t.push(Ra.init(e,this,this.reloadedState))}break;case K.Illustration:t.push(Ha.init(e,this,this.reloadedState));break;case K.Material:t.push(Pa.init(e,this,this.reloadedState));break;case K.Model:t.push(Ua.init(e,this,this.reloadedState));break;case K.Module:this.stepSpecificServices[e.stepName]={module:await bi(e.data.module)},t.push(Ga.init(e,this,this.reloadedState));break;case K.Picture:t.push(ka.init(e,this,this.reloadedState));break;case K.Question:t.push(ba.init(e,this,this.reloadedState));break;case K.Shape:t.push(Ja.init(e,this,this.reloadedState));break;case K.Text:t.push(Va.init(e,this,this.reloadedState))}const e=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=e.filter((t=>!!t&&!!t.command)).map((t=>t.command)),i=e.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new JA(n),!0);for(const t of i)await t();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const A of this.selectionCallbacks)A({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((A=>A(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return pa(this.allScenes,this.stepSelections)}}function _a(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}class to{constructor(t,A){_a(this,"manager",void 0),_a(this,"step",void 0),this.manager=t,this.step=A}setUpdateState(t){to.updateState.set(this.step.stepName,t)}getUpdateState(){return!!to.updateState.get(this.step.stepName)}async getCurrentVariant(){return(await this.manager.getWorkflowSelections())[this.step.stepName]?.selections[0]}async getAvailableVariants(){return this.step.option?.variants||[]}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}executeAnimations(){const t=this.manager.getPreviewService(),A=this.step.data.modelAnimation,e=this.step.data.lookAtAnimation;t&&(e&&t.executeCameraAnimation(e),A&&t.executeModelAnimation(A))}}function Ao(t,A,e){return(A=function(t){var A=function(t,A){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,A||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===A?String:Number)(t)}(t,"string");return"symbol"==typeof A?A:String(A)}(A))in t?Object.defineProperty(t,A,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[A]=e,t}_a(to,"updateState",new Map);const eo=t.gql`
|
|
426
426
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
427
427
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
428
428
|
id
|