@spiffcommerce/core 14.10.0 → 14.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +41 -41
- package/dist/module.js +38 -38
- package/dist/types.d.ts +9 -1
- package/package.json +1 -1
package/dist/module.js
CHANGED
|
@@ -476,7 +476,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
476
476
|
workflowState
|
|
477
477
|
}
|
|
478
478
|
}
|
|
479
|
-
`,jn=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const a=A.data;a.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),a.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),a.varyColor&&a.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Kn=[m.SilentIllustration,m.ProductOverlay],Vn=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const a=Wn(A.stepName,t.stepGroups);if(a){const t=n.find((t=>t.name===a.name));t?Kn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:a.name,title:a.name,renderableSteps:Kn.includes(A.type)?[]:[A],silentSteps:Kn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Kn.includes(A.type)?[]:[A],silentSteps:Kn.includes(A.type)?[A]:[]})}if(e.bulkScene){const a=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:a?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:a?.stepTitle??e.bulkSceneTitle,helpText:a?.helpText,data:{aspects:jn(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},Wn=(t,e)=>e.find((e=>e.stepNames.includes(t))),Xn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),qn=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Xn(t,e))),silentSteps:t.silentSteps.filter((t=>Xn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),Zn=async(t,e)=>{const A=qn(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const a=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of a)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return a};function $n(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function _n(t,e,A,n){const a=A.width*t.zoom,i=A.height*t.zoom;if(n){const n=t,a=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(a,t.zoom);const i=A.width*n.zoom,o=A.height*n.zoom;return n.x=ta(t.x,e.width-i,0),n.y=ta(t.y,e.height-o,0),n}const o=t;return o.x=ta(o.x,-a,e.width),o.y=ta(o.y,-i,e.height),o}function ta(t,e,A){return Math.min(Math.max(t,e),A)}class ea{constructor(t){$n(this,"offsets",void 0),$n(this,"forceImageCover",void 0),$n(this,"targetElements",void 0),$n(this,"imageData",void 0),$n(this,"frameData",void 0),$n(this,"_debouncedUpdateFrameOffsets",void 0),$n(this,"minZoomScale",[.03]),$n(this,"maxZoomScale",[20]),$n(this,"onFrameDataChangeListeners",void 0),$n(this,"onZoomChangeListeners",void 0),$n(this,"workflowManager",void 0),$n(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],a=await N(n);Ot(a,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=a,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const a=this.frameData.map(((n,a)=>{const i=(e[a]-this.offsets[a].x)/this.offsets[a].zoom,o=(A[a]-this.offsets[a].y)/this.offsets[a].zoom;return{x:e[a]-i*t[a],y:A[a]-o*t[a],zoom:this.imageData.width*t[a]/this.imageData.width}}));this.updateOffsets(a,n),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,A){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))||A?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=_n(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,A,n,a){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const i=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{i(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),a&&a()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function Aa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class na{constructor(t,e,A){Aa(this,"configuration",void 0),Aa(this,"layouts",void 0),Aa(this,"product",void 0),Aa(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ie(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const a={stepName:this.configuration.stepName,id:F(),src:A,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:a.id,region:t},command:new o(a,e)}}{const a=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,i=async()=>new Promise(((t,e)=>{a?nt(a).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await S(await i()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await dt(r.svg),src:a,svg:r.svg,colors:r.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ie(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const aa=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ia(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class oa{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,A,n=3e3,a=10){ia(this,"pollingId",void 0),ia(this,"attempts",void 0),ia(this,"interval",void 0),ia(this,"maxAttempts",void 0),ia(this,"predicate",void 0),ia(this,"onSuccess",void 0),ia(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=a,this.poll()}}const ra=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{const A=n?.storage?.videoShortUrl,a=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:a})}))}async regenerateQRCode(t,e,A,n,a,i,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Pe([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new oa((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ae(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===i.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+i.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const w=B.toString();if(w.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const d=await aa(w);if(o(d),!i.data||!i.data.regions)throw new ie(i,"Missing regions.");const h=await this.regionElements(i),E=await this.command(d,h,a,i.stepName);E&&(E.command&&a.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await a.setSelectionsAndElements(i.stepName,[],h,(async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const a=A.getLayouts(),i=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=a.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:i,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new w(r),followup:async()=>{}}}};function sa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ca=new class{constructor(){sa(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ae(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=Oe.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,a=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:a,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(a?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(a)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const i=n.selectedVariants[0].id;if(t.option&&i){const n=t.option.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],a,(async()=>{const a=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:a}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],a,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new oa((async()=>{const t=(await Ue.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Ue.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await ut(t),n=A.width,a=A.height,i={src:t,width:n,height:a,aspect:n/a};b.set(t,i),e.setPatternData(i)}else{const A=await st(t),n=await v(A),a={src:t,width:n.width,height:n.height,aspect:n.width/n.height};b.set(t,a),e.setPatternData(a)}}async selectVariantCommand(t,e,A,n,a,i){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));a&&a(!0);const c=await Promise.all(t.data.regions.map((async(e,a)=>{const i=await N(r[a]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,i):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,w=F(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new Ae(e);return{command:this.getCreateElementCommand(w,e,d,{frameData:i,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:w,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new w([...g,...l]),followup:async()=>{a&&a(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),i){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ae(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),a=A.markUpdatePending(),i=A.getStepSpecificServices(e.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,i),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(a)}};const ga=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!i||!A)throw new Error("Required illustration variant no longer available");{const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,a){const i={};for(const[t,e]of a.entries())i[t]={browserValue:e,spotColor:i[t]?.spotColor};const o=Ct(t,e,A,i),r=await dt(o),s=[];for(const t of n){for(const[e,A]of a.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new w(s)}async changeColors(t,e,A,n,a){if(0===e.length)return;const i=y(e[0].id,n().map((t=>t.layoutState))),o={...i.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of a.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!i.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(i.svg,i.width,i.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n,a){if(!t.data||!t.data.regions)throw new ie(t,"Missing regions.");n(!0);const i=A.map((t=>new s(t.id)));a.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ae(o);const c=await S(await this.getIllustrationBody(r)),g=await dt(c.svg),l=t.data.regions.map((e=>{const A=a.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...i];let d=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{d=d.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),a.updateMetadata(t.stepName,{colors:d}),{command:new w(B),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const la=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(!i)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=i.variants?.find((t=>t.id===A));if(n){const A=n.material,o=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const a=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,i.id||"",A||{})));Promise.all(a).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){const a=A.getModelContainer();n(!0);const i=e.material;if(!i)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{a&&t.data.targetMaterials.forEach((e=>{t.option&&a.applyMaterialVariant(e,t.option.id||"",i)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ba=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const a=n.asset?.fileLink;if(!a)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:a,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){n(!0);const a=e.asset?.fileLink;if(!a)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:a,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const wa=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,a){const i=await this.changeTextCommand(t,e,A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,A,n,a){const i=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,a))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,a)=>{const i=a||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return a&&c.push(new s(i)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:i,svg:e,type:h.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:i,region:n,command:new w(c)}};if(i.length>0){const t=i.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),a=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(a),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const a=qt(e.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const da=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=e.asset;if(!a)throw new ne(e);const i=a?.fileLink;if(!i)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const a=F();return{regionElement:{id:a,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:a,src:i,type:h.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ha=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(Oe.getDefaultVariant(n)){const a=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,a?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const a=n.variants;if(!a)return null;const i=a.length>1?a.find((t=>t.id===e)):a[0];if(!i)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[i],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Ea=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=Oe.getDefaultVariant(n);if(!A)return null;const a={fill:A.color,stroke:A.color,variant:A};return this.selectVariantCommand(t,a,[],e)}return await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.updateStorage(t.stepName,{colour:n.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=n.getLayouts();if(A.length>0){const i=t=>{const A=t.region;if(!a.find((t=>t.panelId===A?.panelId)))throw new Ae(A);const n=e.variant?.color;return n?new Qt(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=A.map(i).filter((t=>!!t));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:e.fill||""})}}}{const A=A=>{const n=a.find((t=>t.panelId===A.panelId));if(!n)throw new Ae(A);const i=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=F();return{id:s,region:A,command:new o({stepRegion:A,stepName:t.stepName,colors:r,id:s,svg:i,type:h.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},i=t.data.regions.map(A),r=i.filter((t=>!!t)).map((t=>t?.command)),s=i.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new w(r),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function ua(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ca extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ca.name}}const Qa=["‘","’","“","”","\n"];class pa extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=pa.name}}const ma=new class{constructor(){ua(this,"cachedColors",new Map),ua(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],a=e?mt(e):void 0;if(a){const t=A.split("").filter((t=>!Qa.includes(t))).join(""),e=t.split("").map((t=>a.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),ua(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),ua(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const a=A.getProfanities(),i=qt(t.toLowerCase());for(const t of i)for(const e in a){if(t===a[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),a=A?.asset?.fileLink,i=a?await Z(a):void 0,o=i?{src:i.src,height:i.height,width:i.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=Oe.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const i=t.data.colorOption,o=i?this.createTextFillSpotColor(i,e.variant):void 0;i?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:i.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");a(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher(),i=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:i?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){a(new Dt(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const a=n.getStepStorage(A.stepName),i=this.getProcessedInput(t,A.data,!!a.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-i.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=U(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[i],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const a=A.data.curved?i:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,a,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:i}),a.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new w(c),o.command.varying=s,o}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),a=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:a,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),i=a.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],i,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=a.map((t=>new B(t.id,A))),i=new w(n);e.getCommandDispatcher()(i),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=ma.updateInputText(s||"",a,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Oe.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Oe.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Oe.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ae(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,a,i,o,r){const s=a.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new Dt(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,a,!!A.customiseAllText,i,o);l&&g.push(l);return{command:new w(g),followup:async()=>{a.markUpdateCompleted(s),await a.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,a),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,a,!!A.customiseAllText,i,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new Dt(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new w(l),followup:async()=>{a.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,a,i){if(!A||!A.regions)throw new Error("Step data not supplied");const r=i.getTransaction().bulk&&A.varyText||!1,s=r?"":a.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=i.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new pa("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let w;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];w=this.createTextFillSpotColor(B,e),i.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const d=await this.getDefaultColor(A),E=d||"#000000",u={stepRegion:e,stepName:t,align:this.textAlign(A),fill:a.color?a.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:w},C=[],Q=new Map,p=new Map;if(!u.fontData)throw new re("Failed to resolve font data for text.");const[m,D]=U(u.fontSize,u.fontData,{left:u.x,top:u.y,width:u.width,height:u.height,rotation:u.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(u.id,m),p.set(u.id,D);const f=A.curved||A.vertical?c:(D||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(m,A,u.id,f,r));const I=new o(u,g);return I.varying=r,{regionElement:{id:l,region:e},commands:[I,...C],newElement:u,fontData:n}}catch(t){throw console.log(t),new Ca("Error adding font to region")}}))).catch((t=>{throw t instanceof Ca?(dA.setLatestToast("Failed to load font.",fa.Error),t):t instanceof pa?t:new Error(t)}));return await i.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{i.updateMetadata(t,{text:s}),i.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,a){const i=[],o=new D(A,n);if(o.varying=a,i.push(o),!e.size){const e=new l(A,t);e.varying=a,i.push(e)}const r=new w(i);return r.varying=a,r}async changeInputTextWithRegion(t,e,A,n,a,i,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=i.getRegionElements(t.stepName),d=new Map,h=new Map;for(const n of B)if(n.region){const[a,i]=U(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,a),h.set(n.id,i)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=i.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))return r(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;i.updateStorage(t.stepName,{text:g}),i.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const u=i.getTransaction().bulk&&t.data.varyText||!1;a.defaultCleared&&i.setMandatoryFulfilled(t.stepName,!0);const C=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,A,u))}const Q=new w(C);return Q.varying=u,Q}};function Da(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let fa;var Ia;(Ia=fa||(fa={})).Error="Error",Ia.Warning="Warning",Ia.Info="Info";class ya extends VA{constructor(t){super(),Da(this,"update",void 0),Da(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ma{constructor(t,e,A,n,a,i,o,r,s,c,g=!1,l,B=!1){Da(this,"reloadedState",void 0),Da(this,"transaction",void 0),Da(this,"ownerCustomer",void 0),Da(this,"updateTransaction",void 0),Da(this,"confirmedDesign",void 0),Da(this,"editedSteps",void 0),Da(this,"informationResults",void 0),Da(this,"layouts",void 0),Da(this,"mandatorySteps",void 0),Da(this,"pendingUpdates",void 0),Da(this,"selectionCost",void 0),Da(this,"workflow",void 0),Da(this,"stepSpecificServices",void 0),Da(this,"previewService",void 0),Da(this,"profanityFilter",void 0),Da(this,"pollers",void 0),Da(this,"commandContext",void 0),Da(this,"stepElements",void 0),Da(this,"stepInitialised",void 0),Da(this,"stepMetadata",void 0),Da(this,"stepSelections",void 0),Da(this,"storage",void 0),Da(this,"confirmCallbacks",void 0),Da(this,"editedCallbacks",void 0),Da(this,"elementsCallbacks",void 0),Da(this,"informationResultCallbacks",void 0),Da(this,"initCallbacks",void 0),Da(this,"makingAdjustmentsCallback",void 0),Da(this,"mandatoryCallbacks",void 0),Da(this,"metadataCallbacks",void 0),Da(this,"selectionCallbacks",void 0),Da(this,"stepSpecificStorageCallbacks",void 0),Da(this,"storageCallbacks",void 0),Da(this,"currentVariationRecordCallbacks",void 0),Da(this,"variationRecordCallbacks",void 0),Da(this,"allScenes",void 0),Da(this,"product",void 0),Da(this,"invalidModelVariants",void 0),Da(this,"currentAdjustingStepId",void 0),Da(this,"renderableContextService",void 0),Da(this,"workflowStatePromiseQueue",new WA(1)),Da(this,"variationRecords",[]),Da(this,"currentVariationRecord",void 0),Da(this,"initializationPromise",void 0),Da(this,"initialized",!1),Da(this,"readOnly",!1),Da(this,"modelContainer",void 0),Da(this,"isReloadedTransaction",!1),Da(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=a,this.commandContext=n,this.reloadedState=c,this.transaction=i,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=A,this.product=o,this.previewService=r,this.modelContainer=l,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,i),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Vn(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=qn(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:a}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new w(a),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new ya((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new ya((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((A,n)=>{const a=[...t[n]||[]];return e.forEach((t=>{const e=a.findIndex((e=>e.id===t.id));e>-1&&a.splice(e,1)})),A[n]=a,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Xn(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Xn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new na(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new na(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},a=t.filter((t=>!this.stepInitialised[t.stepName])),i={stepElements:{},commands:[]},o=[];for(const t of a)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)i.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),i.commands=[...i.commands,...t.results.map((t=>t.command))];return i}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const a=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Xn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const i=this.allScenes,o=qn(i,a),r=qn(i,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{Xn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:d}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...d,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new w(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=qn(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(ra.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new ea(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(ca.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(ga.init(A,this,this.reloadedState));break;case m.Material:t.push(la.init(A,this,this.reloadedState));break;case m.Model:t.push(Ba.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await hn(A.data.module)},t.push(wa.init(A,this,this.reloadedState));break;case m.Picture:t.push(da.init(A,this,this.reloadedState));break;case m.Question:t.push(ha.init(A,this,this.reloadedState));break;case m.Shape:t.push(Ea.init(A,this,this.reloadedState));break;case m.Text:t.push(ma.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),a=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const t of a)await t();a.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return Zn(this.allScenes,this.stepSelections)}}function Fa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ya{constructor(t){Fa(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function Sa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class va{constructor(t,e){Sa(this,"manager",void 0),Sa(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){va.updateState.set(this.step.stepName,t)}getUpdateState(){return!!va.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new Ya(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new Ya(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new Ya(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.step.tags||[]}hasTag(t){return this.step.tags?.includes(t)||!1}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function xa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}Sa(va,"updateState",new Map);const Na=It`
|
|
479
|
+
`,jn=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const a=A.data;a.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),a.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),a.varyColor&&a.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Kn=[m.SilentIllustration,m.ProductOverlay],Vn=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const a=Wn(A.stepName,t.stepGroups);if(a){const t=n.find((t=>t.name===a.name));t?Kn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:a.name,title:a.name,renderableSteps:Kn.includes(A.type)?[]:[A],silentSteps:Kn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Kn.includes(A.type)?[]:[A],silentSteps:Kn.includes(A.type)?[A]:[]})}if(e.bulkScene){const a=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:a?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:a?.stepTitle??e.bulkSceneTitle,helpText:a?.helpText,data:{aspects:jn(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},Wn=(t,e)=>e.find((e=>e.stepNames.includes(t))),Xn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),qn=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Xn(t,e))),silentSteps:t.silentSteps.filter((t=>Xn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),Zn=async(t,e)=>{const A=qn(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const a=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of a)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return a};function $n(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function _n(t,e,A,n){const a=A.width*t.zoom,i=A.height*t.zoom;if(n){const n=t,a=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(a,t.zoom);const i=A.width*n.zoom,o=A.height*n.zoom;return n.x=ta(t.x,e.width-i,0),n.y=ta(t.y,e.height-o,0),n}const o=t;return o.x=ta(o.x,-a,e.width),o.y=ta(o.y,-i,e.height),o}function ta(t,e,A){return Math.min(Math.max(t,e),A)}class ea{constructor(t){$n(this,"offsets",void 0),$n(this,"forceImageCover",void 0),$n(this,"targetElements",void 0),$n(this,"imageData",void 0),$n(this,"frameData",void 0),$n(this,"_debouncedUpdateFrameOffsets",void 0),$n(this,"minZoomScale",[.03]),$n(this,"maxZoomScale",[20]),$n(this,"onFrameDataChangeListeners",void 0),$n(this,"onZoomChangeListeners",void 0),$n(this,"workflowManager",void 0),$n(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],a=await N(n);Ot(a,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=a,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const a=this.frameData.map(((n,a)=>{const i=(e[a]-this.offsets[a].x)/this.offsets[a].zoom,o=(A[a]-this.offsets[a].y)/this.offsets[a].zoom;return{x:e[a]-i*t[a],y:A[a]-o*t[a],zoom:this.imageData.width*t[a]/this.imageData.width}}));this.updateOffsets(a,n),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,A){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))||A?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=_n(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,A,n,a){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const i=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{i(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),a&&a()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function Aa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class na{constructor(t,e,A){Aa(this,"configuration",void 0),Aa(this,"layouts",void 0),Aa(this,"product",void 0),Aa(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ie(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const a={stepName:this.configuration.stepName,id:F(),src:A,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:a.id,region:t},command:new o(a,e)}}{const a=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,i=async()=>new Promise(((t,e)=>{a?nt(a).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await S(await i()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await dt(r.svg),src:a,svg:r.svg,colors:r.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ie(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const aa=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ia(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class oa{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,A,n=3e3,a=10){ia(this,"pollingId",void 0),ia(this,"attempts",void 0),ia(this,"interval",void 0),ia(this,"maxAttempts",void 0),ia(this,"predicate",void 0),ia(this,"onSuccess",void 0),ia(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=a,this.poll()}}const ra=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{const A=n?.storage?.videoShortUrl,a=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:a})}))}async regenerateQRCode(t,e,A,n,a,i,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Pe([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new oa((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ae(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===i.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+i.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const w=B.toString();if(w.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const d=await aa(w);if(o(d),!i.data||!i.data.regions)throw new ie(i,"Missing regions.");const h=await this.regionElements(i),E=await this.command(d,h,a,i.stepName);E&&(E.command&&a.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await a.setSelectionsAndElements(i.stepName,[],h,(async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const a=A.getLayouts(),i=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=a.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:i,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new w(r),followup:async()=>{}}}};function sa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ca=new class{constructor(){sa(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ae(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=Oe.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,a=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:a,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(a?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(a)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const i=n.selectedVariants[0].id;if(t.option&&i){const n=t.option.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],a,(async()=>{const a=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:a}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],a,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new oa((async()=>{const t=(await Ue.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Ue.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await ut(t),n=A.width,a=A.height,i={src:t,width:n,height:a,aspect:n/a};b.set(t,i),e.setPatternData(i)}else{const A=await st(t),n=await v(A),a={src:t,width:n.width,height:n.height,aspect:n.width/n.height};b.set(t,a),e.setPatternData(a)}}async selectVariantCommand(t,e,A,n,a,i){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));a&&a(!0);const c=await Promise.all(t.data.regions.map((async(e,a)=>{const i=await N(r[a]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,i):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,w=F(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new Ae(e);return{command:this.getCreateElementCommand(w,e,d,{frameData:i,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:w,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new w([...g,...l]),followup:async()=>{a&&a(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),i){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ae(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),a=A.markUpdatePending(),i=A.getStepSpecificServices(e.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,i),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(a)}};const ga=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!i||!A)throw new Error("Required illustration variant no longer available");{const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,a){const i={};for(const[t,e]of a.entries())i[t]={browserValue:e,spotColor:i[t]?.spotColor};const o=Ct(t,e,A,i),r=await dt(o),s=[];for(const t of n){for(const[e,A]of a.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new w(s)}async changeColors(t,e,A,n,a){if(0===e.length)return;const i=y(e[0].id,n().map((t=>t.layoutState))),o={...i.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of a.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!i.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(i.svg,i.width,i.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n,a){if(!t.data||!t.data.regions)throw new ie(t,"Missing regions.");n(!0);const i=A.map((t=>new s(t.id)));a.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ae(o);const c=await S(await this.getIllustrationBody(r)),g=await dt(c.svg),l=t.data.regions.map((e=>{const A=a.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...i];let d=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{d=d.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),a.updateMetadata(t.stepName,{colors:d}),{command:new w(B),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const la=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(!i)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=i.variants?.find((t=>t.id===A));if(n){const A=n.material,o=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const a=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,i.id||"",A||{})));Promise.all(a).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){const a=A.getModelContainer();n(!0);const i=e.material;if(!i)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{a&&t.data.targetMaterials.forEach((e=>{t.option&&a.applyMaterialVariant(e,t.option.id||"",i)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const Ba=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const a=n.asset?.fileLink;if(!a)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:a,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){n(!0);const a=e.asset?.fileLink;if(!a)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:a,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const wa=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],a,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,a){const i=await this.changeTextCommand(t,e,A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,A,n,a){const i=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,a))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,a)=>{const i=a||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return a&&c.push(new s(i)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:i,svg:e,type:h.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:i,region:n,command:new w(c)}};if(i.length>0){const t=i.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),a=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(a),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const a=qt(e.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const da=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=e.asset;if(!a)throw new ne(e);const i=a?.fileLink;if(!i)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const a=F();return{regionElement:{id:a,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:a,src:i,type:h.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ha=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(Oe.getDefaultVariant(n)){const a=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,a?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const a=n.variants;if(!a)return null;const i=a.length>1?a.find((t=>t.id===e)):a[0];if(!i)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[i],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};function Ea(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ua=new class{constructor(){Ea(this,"shapeFillId","spiff-fill-shape")}async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}setCustomColor(t,e,A){const n=A.getLayouts(),a=(A.getRegionElements(e.stepName)||[]).map((e=>{const A=e.region;if(!n.find((t=>t.panelId===A?.panelId)))throw new Ae(A);return new Qt(e.id,this.shapeFillId,t)})).filter((t=>!!t));A.getCommandDispatcher()(new w(a)),A.updateStorage(e.stepName,{colour:t})}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=Oe.getDefaultVariant(n);return A?this.selectVariantCommand(t,{fill:A.color,stroke:A.color,variant:A},[],e):null}return await this.reload(t,e,A),null}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariantCommand(t,e,A,n){const a=n.getLayouts(),i=n.getStepStorage(t.stepName)?.colour,r=()=>{if("#custom"===e.variant?.color)return i||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(A.length>0){const i=t=>{const e=t.region;if(!a.find((t=>t.panelId===e?.panelId)))throw new Ae(e);const A=r();return new Qt(t.id,this.shapeFillId,A)},o=A.map(i).filter((t=>!!t));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:r()})}}}{const A=e=>{const A=a.find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=r(),i=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="${this.shapeFillId}"\n fill="${n}"\n />\n </svg>\n `,s={};s[this.shapeFillId]={browserValue:n};const c=F();return{id:c,region:e,command:new o({stepRegion:e,stepName:t.stepName,colors:s,id:c,svg:i,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},i=t.data.regions.map(A),s=i.filter((t=>!!t)).map((t=>t?.command)),c=i.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new w(s),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],c,(async()=>{n.updateStorage(t.stepName,{colour:r()})}))}}}}};function Ca(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Qa extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Qa.name}}const pa=["‘","’","“","”","\n"];class ma extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ma.name}}const Da=new class{constructor(){Ca(this,"cachedColors",new Map),Ca(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],a=e?mt(e):void 0;if(a){const t=A.split("").filter((t=>!pa.includes(t))).join(""),e=t.split("").map((t=>a.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),Ca(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Ca(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const a=A.getProfanities(),i=qt(t.toLowerCase());for(const t of i)for(const e in a){if(t===a[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),a=A?.asset?.fileLink,i=a?await Z(a):void 0,o=i?{src:i.src,height:i.height,width:i.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=Oe.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const i=t.data.colorOption,o=i?this.createTextFillSpotColor(i,e.variant):void 0;i?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:i.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");a(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher(),i=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:i?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){a(new Dt(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const a=n.getStepStorage(A.stepName),i=this.getProcessedInput(t,A.data,!!a.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-i.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=U(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[i],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const a=A.data.curved?i:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,a,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:i}),a.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new w(c),o.command.varying=s,o}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),a=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:a,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),i=a.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],i,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=a.map((t=>new B(t.id,A))),i=new w(n);e.getCommandDispatcher()(i),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Da.updateInputText(s||"",a,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Oe.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Oe.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Oe.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ae(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,a,i,o,r){const s=a.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new Dt(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,a,!!A.customiseAllText,i,o);l&&g.push(l);return{command:new w(g),followup:async()=>{a.markUpdateCompleted(s),await a.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,a),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,a,!!A.customiseAllText,i,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new Dt(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new w(l),followup:async()=>{a.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,a,i){if(!A||!A.regions)throw new Error("Step data not supplied");const r=i.getTransaction().bulk&&A.varyText||!1,s=r?"":a.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=i.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new ma("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let w;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];w=this.createTextFillSpotColor(B,e),i.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const d=await this.getDefaultColor(A),E=d||"#000000",u={stepRegion:e,stepName:t,align:this.textAlign(A),fill:a.color?a.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:w},C=[],Q=new Map,p=new Map;if(!u.fontData)throw new re("Failed to resolve font data for text.");const[m,D]=U(u.fontSize,u.fontData,{left:u.x,top:u.y,width:u.width,height:u.height,rotation:u.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(u.id,m),p.set(u.id,D);const f=A.curved||A.vertical?c:(D||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(m,A,u.id,f,r));const I=new o(u,g);return I.varying=r,{regionElement:{id:l,region:e},commands:[I,...C],newElement:u,fontData:n}}catch(t){throw console.log(t),new Qa("Error adding font to region")}}))).catch((t=>{throw t instanceof Qa?(dA.setLatestToast("Failed to load font.",Ia.Error),t):t instanceof ma?t:new Error(t)}));return await i.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{i.updateMetadata(t,{text:s}),i.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,a){const i=[],o=new D(A,n);if(o.varying=a,i.push(o),!e.size){const e=new l(A,t);e.varying=a,i.push(e)}const r=new w(i);return r.varying=a,r}async changeInputTextWithRegion(t,e,A,n,a,i,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=i.getRegionElements(t.stepName),d=new Map,h=new Map;for(const n of B)if(n.region){const[a,i]=U(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,a),h.set(n.id,i)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=i.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))return r(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;i.updateStorage(t.stepName,{text:g}),i.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const u=i.getTransaction().bulk&&t.data.varyText||!1;a.defaultCleared&&i.setMandatoryFulfilled(t.stepName,!0);const C=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,A,u))}const Q=new w(C);return Q.varying=u,Q}};function fa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Ia;var ya;(ya=Ia||(Ia={})).Error="Error",ya.Warning="Warning",ya.Info="Info";class Ma extends VA{constructor(t){super(),fa(this,"update",void 0),fa(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Fa{constructor(t,e,A,n,a,i,o,r,s,c,g=!1,l,B=!1){fa(this,"reloadedState",void 0),fa(this,"transaction",void 0),fa(this,"ownerCustomer",void 0),fa(this,"updateTransaction",void 0),fa(this,"confirmedDesign",void 0),fa(this,"editedSteps",void 0),fa(this,"informationResults",void 0),fa(this,"layouts",void 0),fa(this,"mandatorySteps",void 0),fa(this,"pendingUpdates",void 0),fa(this,"selectionCost",void 0),fa(this,"workflow",void 0),fa(this,"stepSpecificServices",void 0),fa(this,"previewService",void 0),fa(this,"profanityFilter",void 0),fa(this,"pollers",void 0),fa(this,"commandContext",void 0),fa(this,"stepElements",void 0),fa(this,"stepInitialised",void 0),fa(this,"stepMetadata",void 0),fa(this,"stepSelections",void 0),fa(this,"storage",void 0),fa(this,"confirmCallbacks",void 0),fa(this,"editedCallbacks",void 0),fa(this,"elementsCallbacks",void 0),fa(this,"informationResultCallbacks",void 0),fa(this,"initCallbacks",void 0),fa(this,"makingAdjustmentsCallback",void 0),fa(this,"mandatoryCallbacks",void 0),fa(this,"metadataCallbacks",void 0),fa(this,"selectionCallbacks",void 0),fa(this,"stepSpecificStorageCallbacks",void 0),fa(this,"storageCallbacks",void 0),fa(this,"currentVariationRecordCallbacks",void 0),fa(this,"variationRecordCallbacks",void 0),fa(this,"allScenes",void 0),fa(this,"product",void 0),fa(this,"invalidModelVariants",void 0),fa(this,"currentAdjustingStepId",void 0),fa(this,"renderableContextService",void 0),fa(this,"workflowStatePromiseQueue",new WA(1)),fa(this,"variationRecords",[]),fa(this,"currentVariationRecord",void 0),fa(this,"initializationPromise",void 0),fa(this,"initialized",!1),fa(this,"readOnly",!1),fa(this,"modelContainer",void 0),fa(this,"isReloadedTransaction",!1),fa(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=a,this.commandContext=n,this.reloadedState=c,this.transaction=i,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=A,this.product=o,this.previewService=r,this.modelContainer=l,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,i),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Vn(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=qn(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:a}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new w(a),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Ma((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Ma((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((A,n)=>{const a=[...t[n]||[]];return e.forEach((t=>{const e=a.findIndex((e=>e.id===t.id));e>-1&&a.splice(e,1)})),A[n]=a,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Xn(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Xn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new na(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new na(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},a=t.filter((t=>!this.stepInitialised[t.stepName])),i={stepElements:{},commands:[]},o=[];for(const t of a)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)i.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),i.commands=[...i.commands,...t.results.map((t=>t.command))];return i}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const a=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Xn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const i=this.allScenes,o=qn(i,a),r=qn(i,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{Xn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:d}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...d,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new w(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=qn(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(ra.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new ea(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(ca.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(ga.init(A,this,this.reloadedState));break;case m.Material:t.push(la.init(A,this,this.reloadedState));break;case m.Model:t.push(Ba.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await hn(A.data.module)},t.push(wa.init(A,this,this.reloadedState));break;case m.Picture:t.push(da.init(A,this,this.reloadedState));break;case m.Question:t.push(ha.init(A,this,this.reloadedState));break;case m.Shape:t.push(ua.init(A,this,this.reloadedState));break;case m.Text:t.push(Da.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),a=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const t of a)await t();a.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return Zn(this.allScenes,this.stepSelections)}}function Ya(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Sa{constructor(t){Ya(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function va(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class xa{constructor(t,e){va(this,"manager",void 0),va(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){xa.updateState.set(this.step.stepName,t)}getUpdateState(){return!!xa.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new Sa(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new Sa(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new Sa(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.step.tags||[]}hasTag(t){return this.step.tags?.includes(t)||!1}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Na(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}va(xa,"updateState",new Map);const Pa=It`
|
|
480
480
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
481
481
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
482
482
|
id
|
|
@@ -490,13 +490,13 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
490
490
|
}
|
|
491
491
|
}
|
|
492
492
|
}
|
|
493
|
-
`,
|
|
493
|
+
`,Ra=It`
|
|
494
494
|
mutation UpdateDesignName($transactionId: String!, $designName: String!) {
|
|
495
495
|
transactionUpdate(id: $transactionId, designName: $designName) {
|
|
496
496
|
id
|
|
497
497
|
}
|
|
498
498
|
}
|
|
499
|
-
`;class
|
|
499
|
+
`;class Ha extends xa{constructor(t,e){super(t,e),Na(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:Ra,variables:{transactionId:this.manager.getTransaction().id,designName:t}});const e=this.manager.getTransaction();this.manager.setTransaction({...e,designName:t})}addVariationRecord(){const t=this.manager.addVariationRecord({transactionId:this.transaction.id,values:[]});return this.manager.setCurrentVariationRecord(t),t}updateBulkIsConnected(t){this.manager.updateStorage(this.getId(),{bulkIsConnected:t})}openBulkSourceUrl(){window.open(this.transaction.bulkSourceUrl,"_blank")}async sendGoogleSheetLinkToEmail(t){await ye.getShadowGraphqlClient().mutate({mutation:Pa,variables:{id:this.transaction.id,details:{emailAddress:t},type:"Owner"}}),this.openBulkSourceUrl()}deleteVariationRecord(t){this.manager.removeVariationRecord(t)}getAspects(){return this.step.data.aspects}}class Ua extends xa{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return ga.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],(t=>this.setUpdateState(t)),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(0!==t.length)try{return y(t[0].id,this.manager.getAllLayoutData()).colors}catch(t){console.error(t)}}setColor(t,e){const A=new Map;return A.set(t,e),ga.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,(()=>this.manager.getCommandContext().getAllLayouts()),A)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ga.availableColors(this.step,this.manager):Promise.resolve([])}hasVaryingSelection(){return this.step.data.varySelection}hasVaryingColors(){return this.step.data.varyColors}isColorPickerEnabled(){return this.step.data.colorPickerEnabled}}class ba extends xa{constructor(t,e){super(t,e)}selectVariant(t){return la.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class ka extends xa{constructor(t,e){super(t,e)}selectVariant(t){return Ba.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ga extends xa{constructor(t,e){super(t,e)}selectVariant(t){return da.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ja extends xa{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await ha.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Ta extends xa{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return ua.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return ua.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return ua.availableColours(this.step)}setCustomColor(t){if("#custom"!==this.getCurrentVariant()?.getColor())throw new Error("Custom colors can only be set on a non-custom variant. Please add a custom variant to the step.");return ua.setCustomColor(t,this.step,this.manager)}getCustomColor(){const t=this.manager.getStepStorage(this.step.stepName)?.colour;if("#custom"!==this.getCurrentVariant()?.getColor())throw new Error("Custom colors can only be set on a non-custom variant. Please add a custom variant to the step.");if(!t)throw new Error("Color not available on step. Set a default on the workflow to fix this.");return t}}class La extends xa{constructor(t,e){super(t,e)}async selectVariant(t){Da.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Ia.Error,stepID:this.step.stepName}]);else{const t=this.manager.getInformationResults().filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}}),(t=>{}))}getAvailableFillColors(){return this.step.data.colorPickerEnabled?Da.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await Da.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return Da.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await Da.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",A=void 0!==this.step.data.replaceableText?this.step.data.replaceableText.replace("{{}}",e):e,n=t?A:this.step.data.defaultText;this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1});return this.setText(n)}setText(t){const e={input:t},A=Da.findLayoutElements(this.manager,this.step),n=Da.filterUnsupportedCharacters(t,A[0]?.fontData);!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength||(e.input=n);const a=A.length<=0,i=a?{inputText:n,text:n}:{inputText:n};if(this.manager.updateStorage(this.step.stepName,i),this.manager.updateMetadata(this.step.stepName,{text:n}),a)return e;const{command:o,errors:r,helperText:s}=Da.updateInputText(n,A,this.step,this.manager);o&&this.manager.getCommandDispatcher()(o);const c=this.manager.getInformationResults(),g=r[0]?.localizationKey;if(g)this.manager.setInformationResults([...c,{message:`${g} - ${this.step.stepTitle}`,messageType:Ia.Error,stepID:this.step.stepName}]);else{const t=c.filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}return e.helperText=g||s,e.errorText=g,e}getText(){const t=this.step.data.defaultText;return this.manager.getStepStorage(this.step.stepName)?.text||t||""}isReplaceable(){return this.step.data.userCanReplaceText}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");return this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""}),t}}hasVaryingText(){return this.step.data.varyText}hasVaryingColor(){return this.step.data.varyColor}hasVaryingSelection(){return this.step.data.varySelection}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(void 0===t)return;return t-this.getText().length}}class Oa{static get(t,e){switch(e.type){case m.Question:return new Ja(t,e);case m.Text:return new La(t,e);case m.Illustration:return new Ua(t,e);case m.Picture:return new Ga(t,e);case m.Shape:return new Ta(t,e);case m.Material:return new ba(t,e);case m.Model:return new ka(t,e);case m.Frame:return new ao(t,e);case m.Bulk:return new Ha(t,e);default:throw new re(`Step type ${e.type} not yet supported in Core SDK`)}}}function za(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ja=It`
|
|
500
500
|
mutation CreateDesign(
|
|
501
501
|
$name: String!
|
|
502
502
|
$layouts: [LayoutInput]!
|
|
@@ -528,7 +528,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
528
528
|
}
|
|
529
529
|
}
|
|
530
530
|
}
|
|
531
|
-
`,ja=(t,e,A)=>{const n={};return e.steps.forEach((e=>{Object.assign(n,(e=>{const n={};if("Frame"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideImageInCart&&A)return n;n[`${e.stepTitle} image`]=a.image}if("Illustration"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideColorsInCart&&A||!a.colors)return n;if(a.colors.length>0){const t=a.colors.join(", ").toUpperCase();n[`${e.stepTitle} colors`]=t}}if("Module"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideTextInCart&&A)return n;n[`${e.stepTitle} text`]=a.text}if("Text"===e.type){const a=t[e.stepName];if(!a)return n;const i=e.data;i.hideTextInCart&&A||(n[`${e.stepTitle} text`]=a.text),!a.color||i.hideColorInCart&&A||(n[`${e.stepTitle} color`]=a.color)}return n})(e))})),n},Ka=(t,e,A,n,a,i,o,r,s,c)=>{const g=(de.getMap("transactionOwnerIds")||new Map).get(t.id),l={baseCost:A,designProductId:t.externalDesignProductId,designProductVariantId:t.externalDesignProductVariantId,event:"onComplete",exportedData:i,externalCartProductId:t.externalCartProductId,externalCartProductVariantId:t.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:n,processExecutionId:c,transactionId:t.id,transactionOwnerId:g,weight:e.weight,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return a&&(l.metadata=a),r&&(l.selectedVariants=r),s&&(l.sku=s),l},Va=async(t,e,A,n,a,i,o,r)=>{const s=t.product?.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=ja(A,e,!1);for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}else if(n){i=n;for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}for(const A of Object.keys(t)){const n=t[A],i=e.steps.find((t=>t.stepTitle===A));if(1===n.length)a[`${i?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)a[`${i?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return a})(n,A,void 0,i);return Ka(t,e,s,c,i,g,o,n,a,r)},Wa=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=ye.getShadowGraphqlClient(),d=await w.query({query:zn,variables:{id:i.id},fetchPolicy:"no-cache",errorPolicy:"all"}),h=d.data?.transactions[0].workflowState;!d.errors&&h||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),d.errors&&d.errors.forEach((t=>{d.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),u=e?.finalizeStepConfig?.lookAtAnimation,C=E&&100===E.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!u,Q=B&&ja(B,e,!0),p=B&&ja(B,e,!1),m=async t=>{const A={};let n=0;if(Object.keys(o).length>0)for(const a of Object.keys(o)){const i=o[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<i.selections.length;++e){const a=i.selections[e];if(r&&(!t||r.option&&(r.option.variants||[]).length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;A[t]?A[t].push({id:a.id||"",name:a.name,priceModifier:a.priceModifier}):A[t]=[{id:a.id||"",name:a.name,priceModifier:a.priceModifier}]}n+=a.priceModifier}}return[A,n]},[D]=await m(!0),f=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[I]=await m(!1),y=Object.fromEntries(Object.keys(I).map((t=>[t,I[t].map((t=>t.id))]))),M=await l(C);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const F=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:za,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!C,previewImage:M};if(p){const e=[];for(const[t,A]of Object.entries(p))e.push({key:t,value:A});t.metadata=e}if(f){const e=[];for(const[t,A]of Object.entries(y))e.push({key:t,ids:A});t.selectedVariants=e}return t})()),Y=F?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const S=(await ye.getShadowGraphqlClient().query({query:On,variables:{id:i.id}})).data.transactions[0];return i.bulk?((t,e,A,n)=>{const a=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Ka(t,e,a,i,void 0,o,A,void 0,void 0,n)})(S,a,Y,F?.processExecution?.id):await Va(S,a,e,D,F?.sku,Q,Y,F?.processExecution?.id)};let Xa;var qa;(qa=Xa||(Xa={})).Local="Local",qa.Remote="Remote";const Za=new class{constructor(){Oa(this,"localPersistenceKey","designTransactions"),Oa(this,"storageMethod",Xa.Local),Oa(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===Xa.Local){const t=de.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new re("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((e=>e.transactionId===t))}async addDesign(t){const e=(await this.getSavedDesigns()).filter((e=>e.transactionId!==t.transactionId));e.unshift(t),await this.setDesigns(e),this.designSavedListeners.forEach((e=>e(t)))}async renameDesign(t,e){const A=await this.getSavedDesigns(),n=A.find((e=>e.transactionId===t));if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(A)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter((e=>e.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==Xa.Local)throw new re("Unexpected storage method requested");de.set(this.localPersistenceKey,JSON.stringify(t))}};function $a(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class _a{constructor(e,A){if($a(this,"client",void 0),$a(this,"commandContext",void 0),$a(this,"workflowManager",void 0),$a(this,"isReadOnly",void 0),$a(this,"renderableScenes",[]),$a(this,"renderableSceneCallbacks",[]),$a(this,"debouncedSavedDesignUpdate",Xt((async()=>{await Za.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),$a(this,"getCanvasObjectURLAsync",(async t=>new Promise(((e,A)=>{try{t.toBlob((t=>{if(t){const A=URL.createObjectURL(t);e(A)}}))}catch(t){A(t)}})))),!A.workflow)throw new Error("No Workflow ID provided.");this.client=e;const n=A.layouts;this.commandContext=new t,this.commandContext.initialize(n,A.reloadedState),this.isReadOnly=A.transaction.isOrdered||!!A.readOnly,this.workflowManager=new Ma(A.workflow,A.product.profanities?.map((t=>t.word))||[],n,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly,A.modelContainer,A.isReloadedTransaction),this.workflowManager.addSelectionCallback((t=>{const e=t.traversableScenes.map((t=>{const e=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:e}}));this.renderableScenes=e,this.renderableSceneCallbacks.forEach((t=>t(e)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await ye.getShadowGraphqlClient().mutate({mutation:Ln,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,e){const A=this.workflowManager.getWorkflow(),n=A?.finalizeStepConfig?.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,n))||""}const a=document.createElement("canvas");let i=2048;e&&e<=2048&&(i=e),a.width=i,a.height=i;const o=this.commandContext.getAllLayouts(),r=A.defaultPreviewPanelIndex||0,s=A.panels[r],c=o.find((t=>t.layoutState?.layout.panelId===s?.name))||o[0],g=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},l=this.commandContext.getLayoutById(c.layoutState.layout.id),B=a.getContext("2d");if(!B)throw new ge("Failed to obtain 2D context for preview image creation");const w=P(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),d=Kt.renderToStaticMarkup(w),h=await jt.from(B,d,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await h.render();const E=await this.getCanvasObjectURLAsync(a);return a.toDataURL(E)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t));if(e&&this.stepHasHandle(e))return La.get(this.getWorkflowManager(),e)}getSteps(){return this.getScenes().flatMap((t=>this.getStepsByScene(t)))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map((t=>({id:t.id,name:t.name,stepIds:t.stepNames})))}getSelectionPriceSubunits(){const t=this.getWorkflowManager().getWorkflowSelections();let e=0;return Object.values(t).forEach((t=>{e+=t.selections.map((t=>t.priceModifier)).reduce(((t,e)=>t+e))})),e}getBasePriceSubunits(){return this.getWorkflowManager().getProduct().basePrice||0}getTotalPriceSubunits(){return this.getBasePriceSubunits()+this.getSelectionPriceSubunits()}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,e={type:m.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:jn(this.getWorkflowManager().getWorkflow())},conditions:[]};return La.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return La.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>La.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((e=>e.name===t.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map((t=>this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>La.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Na,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find((e=>e.customer?.emailAddress===t.emailAddress));if(e?.customer){this.getWorkflowManager().setTransactionCustomer(e.customer);const t=de.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),de.setMap("transactionCustomerIds",t)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((e=>e!==t))}async save(t){if(!this.getCommandContext().getState())throw new re("State undefined!");const e={title:await(async()=>{if(t)return t;const e=this.getWorkflowManager().getTransaction().id,A=(await Za.getSavedDesigns()).find((t=>t.transactionId===e))?.title;return A||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Za.addDesign(e),e}async copy(){const t=zt(this.getCommandContext().getState());if(!t)throw new re("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),A=this.getWorkflowManager().getWorkflow(),n=new qi({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new re("Integration product id is undefined!");await n.initFromIntegrationProduct(a);return await n.getWorkflowExperience(A.id,e,void 0)}async onDesignFinished(t){return Wa(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),this.workflowManager.getProduct(),this.workflowManager.getTransaction(),this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==m.SilentIllustration&&t.type!==m.ProductOverlay}getExportedData(){const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),A=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach((A=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===A));if(!n)return;t.has(n.stepTitle)||t.set(n.stepTitle,{});const a=e[A];Object.keys(a).forEach((e=>{t.get(n.stepTitle)[e]=a[e]}))})),Object.keys(A)?.forEach((e=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===e));n&&(t.has(n.stepTitle)||t.set(n.stepTitle,{}),t.get(n.stepTitle).selection=A[e].selections[0].name)})),t}}const ti=Zt`
|
|
531
|
+
`,Ka=(t,e,A)=>{const n={};return e.steps.forEach((e=>{Object.assign(n,(e=>{const n={};if("Frame"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideImageInCart&&A)return n;n[`${e.stepTitle} image`]=a.image}if("Illustration"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideColorsInCart&&A||!a.colors)return n;if(a.colors.length>0){const t=a.colors.join(", ").toUpperCase();n[`${e.stepTitle} colors`]=t}}if("Module"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideTextInCart&&A)return n;n[`${e.stepTitle} text`]=a.text}if("Text"===e.type){const a=t[e.stepName];if(!a)return n;const i=e.data;i.hideTextInCart&&A||(n[`${e.stepTitle} text`]=a.text),!a.color||i.hideColorInCart&&A||(n[`${e.stepTitle} color`]=a.color)}return n})(e))})),n},Va=(t,e,A,n,a,i,o,r,s,c)=>{const g=(de.getMap("transactionOwnerIds")||new Map).get(t.id),l={baseCost:A,designProductId:t.externalDesignProductId,designProductVariantId:t.externalDesignProductVariantId,event:"onComplete",exportedData:i,externalCartProductId:t.externalCartProductId,externalCartProductVariantId:t.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:n,processExecutionId:c,transactionId:t.id,transactionOwnerId:g,weight:e.weight,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return a&&(l.metadata=a),r&&(l.selectedVariants=r),s&&(l.sku=s),l},Wa=async(t,e,A,n,a,i,o,r)=>{const s=t.product?.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=Ka(A,e,!1);for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}else if(n){i=n;for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}for(const A of Object.keys(t)){const n=t[A],i=e.steps.find((t=>t.stepTitle===A));if(1===n.length)a[`${i?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)a[`${i?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return a})(n,A,void 0,i);return Va(t,e,s,c,i,g,o,n,a,r)},Xa=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=ye.getShadowGraphqlClient(),d=await w.query({query:zn,variables:{id:i.id},fetchPolicy:"no-cache",errorPolicy:"all"}),h=d.data?.transactions[0].workflowState;!d.errors&&h||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),d.errors&&d.errors.forEach((t=>{d.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),u=e?.finalizeStepConfig?.lookAtAnimation,C=E&&100===E.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!u,Q=B&&Ka(B,e,!0),p=B&&Ka(B,e,!1),m=async t=>{const A={};let n=0;if(Object.keys(o).length>0)for(const a of Object.keys(o)){const i=o[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<i.selections.length;++e){const a=i.selections[e];if(r&&(!t||r.option&&(r.option.variants||[]).length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;A[t]?A[t].push({id:a.id||"",name:a.name,priceModifier:a.priceModifier}):A[t]=[{id:a.id||"",name:a.name,priceModifier:a.priceModifier}]}n+=a.priceModifier}}return[A,n]},[D]=await m(!0),f=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[I]=await m(!1),y=Object.fromEntries(Object.keys(I).map((t=>[t,I[t].map((t=>t.id))]))),M=await l(C);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const F=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!C,previewImage:M};if(p){const e=[];for(const[t,A]of Object.entries(p))e.push({key:t,value:A});t.metadata=e}if(f){const e=[];for(const[t,A]of Object.entries(y))e.push({key:t,ids:A});t.selectedVariants=e}return t})()),Y=F?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const S=(await ye.getShadowGraphqlClient().query({query:On,variables:{id:i.id}})).data.transactions[0];return i.bulk?((t,e,A,n)=>{const a=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Va(t,e,a,i,void 0,o,A,void 0,void 0,n)})(S,a,Y,F?.processExecution?.id):await Wa(S,a,e,D,F?.sku,Q,Y,F?.processExecution?.id)};let qa;var Za;(Za=qa||(qa={})).Local="Local",Za.Remote="Remote";const $a=new class{constructor(){za(this,"localPersistenceKey","designTransactions"),za(this,"storageMethod",qa.Local),za(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===qa.Local){const t=de.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new re("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((e=>e.transactionId===t))}async addDesign(t){const e=(await this.getSavedDesigns()).filter((e=>e.transactionId!==t.transactionId));e.unshift(t),await this.setDesigns(e),this.designSavedListeners.forEach((e=>e(t)))}async renameDesign(t,e){const A=await this.getSavedDesigns(),n=A.find((e=>e.transactionId===t));if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(A)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter((e=>e.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==qa.Local)throw new re("Unexpected storage method requested");de.set(this.localPersistenceKey,JSON.stringify(t))}};function _a(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ti{constructor(e,A){if(_a(this,"client",void 0),_a(this,"commandContext",void 0),_a(this,"workflowManager",void 0),_a(this,"isReadOnly",void 0),_a(this,"renderableScenes",[]),_a(this,"renderableSceneCallbacks",[]),_a(this,"debouncedSavedDesignUpdate",Xt((async()=>{await $a.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),_a(this,"getCanvasObjectURLAsync",(async t=>new Promise(((e,A)=>{try{t.toBlob((t=>{if(t){const A=URL.createObjectURL(t);e(A)}}))}catch(t){A(t)}})))),!A.workflow)throw new Error("No Workflow ID provided.");this.client=e;const n=A.layouts;this.commandContext=new t,this.commandContext.initialize(n,A.reloadedState),this.isReadOnly=A.transaction.isOrdered||!!A.readOnly,this.workflowManager=new Fa(A.workflow,A.product.profanities?.map((t=>t.word))||[],n,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly,A.modelContainer,A.isReloadedTransaction),this.workflowManager.addSelectionCallback((t=>{const e=t.traversableScenes.map((t=>{const e=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:e}}));this.renderableScenes=e,this.renderableSceneCallbacks.forEach((t=>t(e)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await ye.getShadowGraphqlClient().mutate({mutation:Ln,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,e){const A=this.workflowManager.getWorkflow(),n=A?.finalizeStepConfig?.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,n))||""}const a=document.createElement("canvas");let i=2048;e&&e<=2048&&(i=e),a.width=i,a.height=i;const o=this.commandContext.getAllLayouts(),r=A.defaultPreviewPanelIndex||0,s=A.panels[r],c=o.find((t=>t.layoutState?.layout.panelId===s?.name))||o[0],g=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},l=this.commandContext.getLayoutById(c.layoutState.layout.id),B=a.getContext("2d");if(!B)throw new ge("Failed to obtain 2D context for preview image creation");const w=P(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),d=Kt.renderToStaticMarkup(w),h=await jt.from(B,d,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await h.render();const E=await this.getCanvasObjectURLAsync(a);return a.toDataURL(E)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t));if(e&&this.stepHasHandle(e))return Oa.get(this.getWorkflowManager(),e)}getSteps(){return this.getScenes().flatMap((t=>this.getStepsByScene(t)))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map((t=>({id:t.id,name:t.name,stepIds:t.stepNames})))}getSelectionPriceSubunits(){const t=this.getWorkflowManager().getWorkflowSelections();let e=0;return Object.values(t).forEach((t=>{e+=t.selections.map((t=>t.priceModifier)).reduce(((t,e)=>t+e))})),e}getBasePriceSubunits(){return this.getWorkflowManager().getProduct().basePrice||0}getTotalPriceSubunits(){return this.getBasePriceSubunits()+this.getSelectionPriceSubunits()}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,e={type:m.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:jn(this.getWorkflowManager().getWorkflow())},conditions:[]};return Oa.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return Oa.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>Oa.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((e=>e.name===t.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map((t=>this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>Oa.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Pa,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find((e=>e.customer?.emailAddress===t.emailAddress));if(e?.customer){this.getWorkflowManager().setTransactionCustomer(e.customer);const t=de.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),de.setMap("transactionCustomerIds",t)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((e=>e!==t))}async save(t){if(!this.getCommandContext().getState())throw new re("State undefined!");const e={title:await(async()=>{if(t)return t;const e=this.getWorkflowManager().getTransaction().id,A=(await $a.getSavedDesigns()).find((t=>t.transactionId===e))?.title;return A||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await $a.addDesign(e),e}async copy(){const t=zt(this.getCommandContext().getState());if(!t)throw new re("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),A=this.getWorkflowManager().getWorkflow(),n=new $i({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new re("Integration product id is undefined!");await n.initFromIntegrationProduct(a);return await n.getWorkflowExperience(A.id,e,void 0)}async onDesignFinished(t){return Xa(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),this.workflowManager.getProduct(),this.workflowManager.getTransaction(),this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==m.SilentIllustration&&t.type!==m.ProductOverlay}getExportedData(){const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),A=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach((A=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===A));if(!n)return;t.has(n.stepTitle)||t.set(n.stepTitle,{});const a=e[A];Object.keys(a).forEach((e=>{t.get(n.stepTitle)[e]=a[e]}))})),Object.keys(A)?.forEach((e=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===e));n&&(t.has(n.stepTitle)||t.set(n.stepTitle,{}),t.get(n.stepTitle).selection=A[e].selections[0].name)})),t}}const ei=Zt`
|
|
532
532
|
${Zt`
|
|
533
533
|
fragment ProductCollectionProductFields on Product {
|
|
534
534
|
id
|
|
@@ -609,8 +609,8 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
609
609
|
}
|
|
610
610
|
}
|
|
611
611
|
}
|
|
612
|
-
`,
|
|
613
|
-
${
|
|
612
|
+
`,Ai=Zt`
|
|
613
|
+
${ei}
|
|
614
614
|
query GetBundle($id: String!) {
|
|
615
615
|
bundles(ids: [$id]) {
|
|
616
616
|
id
|
|
@@ -631,7 +631,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
631
631
|
}
|
|
632
632
|
}
|
|
633
633
|
}
|
|
634
|
-
`,
|
|
634
|
+
`,ni=Zt`
|
|
635
635
|
query GetBundleStakeholders($id: String!) {
|
|
636
636
|
bundles(ids: [$id]) {
|
|
637
637
|
id
|
|
@@ -648,7 +648,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
648
648
|
}
|
|
649
649
|
}
|
|
650
650
|
}
|
|
651
|
-
`,
|
|
651
|
+
`,ai=Zt`
|
|
652
652
|
query GetBundlesForCustomer($id: String!) {
|
|
653
653
|
customers(ids: [$id]) {
|
|
654
654
|
bundleStakeholders {
|
|
@@ -666,8 +666,8 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
666
666
|
}
|
|
667
667
|
}
|
|
668
668
|
}
|
|
669
|
-
`,
|
|
670
|
-
${
|
|
669
|
+
`,ii=Zt`
|
|
670
|
+
${ei}
|
|
671
671
|
mutation CreateBundle($collectionId: String) {
|
|
672
672
|
bundleCreate(collectionId: $collectionId) {
|
|
673
673
|
id
|
|
@@ -685,25 +685,25 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
685
685
|
}
|
|
686
686
|
}
|
|
687
687
|
}
|
|
688
|
-
`,
|
|
688
|
+
`,oi=Zt`
|
|
689
689
|
mutation UpdateBundle($id: String!, $name: String, $metadata: [MetadataInput!], $bundleStateData: String) {
|
|
690
690
|
bundleUpdate(id: $id, name: $name, metadata: $metadata, bundleStateData: $bundleStateData) {
|
|
691
691
|
id
|
|
692
692
|
}
|
|
693
693
|
}
|
|
694
|
-
`,
|
|
694
|
+
`,ri=Zt`
|
|
695
695
|
mutation BundleAddTransaction($id: String!, $transactionId: String!) {
|
|
696
696
|
bundleAddTransaction(id: $id, transactionId: $transactionId) {
|
|
697
697
|
id
|
|
698
698
|
}
|
|
699
699
|
}
|
|
700
|
-
`,
|
|
700
|
+
`,si=Zt`
|
|
701
701
|
mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
|
|
702
702
|
bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
|
|
703
703
|
id
|
|
704
704
|
}
|
|
705
705
|
}
|
|
706
|
-
`,
|
|
706
|
+
`,ci=Zt`
|
|
707
707
|
mutation BundleRemoveTransaction($id: String!, $transactionId: String!, $name: String, $metadata: [MetadataInput!], $bundleStateData: String) {
|
|
708
708
|
bundleRemoveTransaction(id: $id, transactionId: $transactionId) {
|
|
709
709
|
id
|
|
@@ -712,7 +712,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
712
712
|
id
|
|
713
713
|
}
|
|
714
714
|
}
|
|
715
|
-
`,
|
|
715
|
+
`,gi=Zt`
|
|
716
716
|
mutation BundleRemoveTransactions($id: String!, $transactionIds: [String!]!, $name: String, $metadata: [MetadataInput!], $bundleStateData: String) {
|
|
717
717
|
bundleRemoveTransactions(id: $id, transactionIds: $transactionIds) {
|
|
718
718
|
id
|
|
@@ -721,25 +721,25 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
721
721
|
id
|
|
722
722
|
}
|
|
723
723
|
}
|
|
724
|
-
`,
|
|
724
|
+
`,li=Zt`
|
|
725
725
|
mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
|
|
726
726
|
bundleAddStakeholder(id: $id, details: $details, type: $type) {
|
|
727
727
|
id
|
|
728
728
|
}
|
|
729
729
|
}
|
|
730
|
-
`,
|
|
730
|
+
`,Bi=Zt`
|
|
731
731
|
mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
|
|
732
732
|
bundleUpdateStakeholders(id: $id, input: $input) {
|
|
733
733
|
id
|
|
734
734
|
}
|
|
735
735
|
}
|
|
736
|
-
`,
|
|
736
|
+
`,wi=Zt`
|
|
737
737
|
mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
|
|
738
738
|
bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
|
|
739
739
|
id
|
|
740
740
|
}
|
|
741
741
|
}
|
|
742
|
-
`;function
|
|
742
|
+
`;function di(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class hi{constructor(t){di(this,"bundle",void 0),di(this,"handleCache",{}),this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const A=e.aspects.find((e=>e.name===t.targetAspectName));return!!A&&t.requiredVariantSelections.some((t=>t===A.value))}))}async createHandle(t){switch(t.type){case ft.FileUpload:return new ui(this.bundle,t);case ft.Option:{const e=t.entityId?await Oe.getOption(t.entityId):void 0;return"Color"===e?.type?new pi(this.bundle,t,e):new Qi(this.bundle,t,e)}case ft.Text:return new Ci(this.bundle,t)}}}class Ei{constructor(t,e){di(this,"bundle",void 0),di(this,"property",void 0),this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap((t=>t.getSteps().filter((t=>t.getRaw().globalPropertyAspectConfigurations?.some((t=>t.globalPropertyConfigurationId===this.bundle.getProductCollection()?.globalPropertyConfiguration?.id&&t.aspectName===this.property.name))))))}}class ui extends Ei{constructor(t,e){super(t,e)}async selectImage(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.key),this.applyImageSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=await Ue.getLocalOrFromServer(e);return A?this.applyImageSelection(A,t):Promise.resolve()}async applyImageSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectImage(t)));await Promise.all(A)}}class Ci extends Ei{constructor(t,e){super(t,e)}getText(){const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const A=this.getSharedSteps(e).map((e=>{e.setText(t)}));await Promise.all(A)}}class Qi extends Ei{constructor(t,e,A){super(t,e),di(this,"optionResource",void 0),this.optionResource=A}getCurrentVariant(){if(!this.optionResource)return;const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!t)return;const e=this.optionResource.variants?.find((e=>e.id===t));return e?new Sa(e):void 0}getAvailableVariants(){return(this.optionResource?.variants?.filter((t=>t.enabled))||[]).map((t=>new Sa(t)))}getAllVariants(){return(this.optionResource?.variants||[]).map((t=>new Sa(t)))}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=this.optionResource?.variants?.find((t=>t.id===e));return A?this.applyVariantSelection(new Sa(A),t):Promise.resolve()}async applyVariantSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectVariant(t)));await Promise.all(A)}}class pi extends Qi{constructor(t,e,A){super(t,e,A)}setCustomColor(t){this.getSharedSteps().forEach((e=>e.setCustomColor(t)))}getCustomColor(){return this.getSharedSteps()[0].getCustomColor()}}const mi=Zt`
|
|
743
743
|
mutation CreateGlobalPropertyState($bundleId: String!) {
|
|
744
744
|
globalPropertyStateCreate(bundleId: $bundleId) {
|
|
745
745
|
id
|
|
@@ -749,7 +749,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
749
749
|
}
|
|
750
750
|
}
|
|
751
751
|
}
|
|
752
|
-
`,
|
|
752
|
+
`,Di=Zt`
|
|
753
753
|
mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
|
|
754
754
|
globalPropertyStateUpdate(id: $id, aspects: $aspects) {
|
|
755
755
|
id
|
|
@@ -759,7 +759,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
759
759
|
}
|
|
760
760
|
}
|
|
761
761
|
}
|
|
762
|
-
`,
|
|
762
|
+
`,fi=Zt`
|
|
763
763
|
query GetGlobalPropertyState($bundleId: String!) {
|
|
764
764
|
globalPropertyState(bundleId: $bundleId) {
|
|
765
765
|
id
|
|
@@ -769,7 +769,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
769
769
|
}
|
|
770
770
|
}
|
|
771
771
|
}
|
|
772
|
-
`;function Di(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class fi{constructor(t,e){Di(this,"bundleId",void 0),Di(this,"globalPropertyState",void 0),Di(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=zt(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=e:this.globalPropertyState.aspects.push({name:t,value:e}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ye.getShadowGraphqlClient().mutate({mutation:pi,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ye.getShadowGraphqlClient().query({query:mi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ye.getShadowGraphqlClient().mutate({mutation:Qi,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Ii(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class yi{constructor(t){Ii(this,"state",void 0),this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find((e=>e.transactionId===t.getWorkflowManager().getTransaction().id&&e.transform))?.transform;if(!e)return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale}setWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer())return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale;const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const a=this.state.transactions.find((t=>t.transactionId===n));a?a.transform=e:this.state.transactions.push({transactionId:n,transform:e})}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex((e=>e.transactionId===t));-1!==e&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return JSON.stringify(this.state)}}function Mi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Fi{constructor(t,e,A){Mi(this,"client",void 0),Mi(this,"id",void 0),Mi(this,"name",void 0),Mi(this,"metadata",void 0),Mi(this,"productCollection",void 0),Mi(this,"bundleStateManager",void 0),Mi(this,"globalConfiguration",void 0),Mi(this,"globalPropertyStateManager",void 0),Mi(this,"globalPropertyHandleService",void 0),Mi(this,"eventListeners",new Map),Mi(this,"initializationPromise",void 0),Mi(this,"workflowExperiences",[]),Mi(this,"previewService",void 0),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.bundleStateManager=new yi(e.bundleStateData),this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new fi(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new di(this),this.setPreviewService(A),this.initializationPromise=this.loadExistingBundles(e.transactions?.map((t=>t.id))||[])}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],n=A.indexOf(e);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===ft.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){await this.appendWorkflowExperience(t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))})()])}async addWorkflowExperiences(t){const e=t.map((t=>t.getWorkflowManager().getTransaction().id)),A=e.map((t=>this.workflowExperiences.find((e=>e.getWorkflowManager().getTransaction().id===t))));if(A.some((t=>!!t)))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter((t=>!!t)).map((t=>t?.getWorkflowManager().getTransaction().id)).join(", "));const n=de.getMap("transactionOwnerIds")||new Map,a=e.map((t=>n.get(t)));await ye.getShadowGraphqlClient().mutate({mutation:ri,variables:{id:this.id,transactionIds:e,transactionOwnerIds:a}}).catch((t=>{console.error(t)})),this.workflowExperiences.push(...t),await Promise.all([this.updateTransactionOrder(),(async()=>{for(const e of t)await this.injectExperienceIntoPreviewService(e);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState(t))))})()])}async appendWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");const A=(de.getMap("transactionOwnerIds")||new Map).get(e);await ye.getShadowGraphqlClient().mutate({mutation:oi,variables:{id:this.id,transactionId:e},context:{transactionOwnerId:A}}),this.workflowExperiences.push(t)}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(t){await this.removeTransactions(t.map((t=>t.getWorkflowManager().getTransaction())))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id);{const[A]=this.workflowExperiences.splice(t,1);this.previewService&&A.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await ye.getShadowGraphqlClient().mutate({mutation:si,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),await this.updateTransactionOrder()}}async removeTransactions(t){const e=t.map((t=>this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id))));if(e.some((t=>-1===t)))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter(((t,A)=>-1===e[A])).map((t=>t.id)).join(", "));const A=t.map((t=>this.workflowExperiences.splice(this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id)),1)[0]));this.previewService&&A.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t.forEach((t=>this.bundleStateManager.removeStateForTransaction(t.id))),await ye.getShadowGraphqlClient().mutate({mutation:ci,variables:{id:this.id,transactionIds:t.map((t=>t.id)),name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t),this.workflowExperiences.pop(),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))})()])}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ye.getShadowGraphqlClient().mutate({mutation:gi,variables:{id:this.id,details:t,type:e||gA.Owner}})}async updateStakeholders(t){await ye.getShadowGraphqlClient().mutate({mutation:li,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:Ai,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}setWorkflowExperienceTransform(t,e){return this.bundleStateManager.setWorkflowExperienceTransform(t,e),this.updateBundle()}onModelLoadEvent(t){"unload"!==t.eventType&&t.modelContainer&&(t.modelContainer.registerMaterialSelectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!0))),t.modelContainer.registerMaterialDeselectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!1))))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const A=t.metadata.get("workflowManager").getTransaction(),n=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===A.id));n&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:n})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(t){console.error(`Unable to apply state to workflow experience: ${t}`)}await e}}async loadExistingBundles(t){if(0===t.length)return;const e=await Promise.all(t.map((t=>this.client.getWorkflowExperience(void 0,void 0,void 0,{type:"transaction",transactionId:t}))));if(this.workflowExperiences=e,this.previewService)for(const t of e)await this.injectExperienceIntoPreviewService(t)}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:ii,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(A,t),a=this.globalPropertyHandleService.applyConditionsFromState(A,e);(()=>{if(n.length!==a.length)return!0;for(let t=0;t<n.length;t++)if(n[t].getName()!==a[t].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:a})}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach((A=>A({bundle:this,event:t,data:e})))}}function Yi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Si=It`
|
|
772
|
+
`;function Ii(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class yi{constructor(t,e){Ii(this,"bundleId",void 0),Ii(this,"globalPropertyState",void 0),Ii(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=zt(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=e:this.globalPropertyState.aspects.push({name:t,value:e}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ye.getShadowGraphqlClient().mutate({mutation:Di,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ye.getShadowGraphqlClient().query({query:fi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ye.getShadowGraphqlClient().mutate({mutation:mi,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Mi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Fi{constructor(t){Mi(this,"state",void 0),this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find((e=>e.transactionId===t.getWorkflowManager().getTransaction().id&&e.transform))?.transform;if(!e)return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale}setWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer())return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale;const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const a=this.state.transactions.find((t=>t.transactionId===n));a?a.transform=e:this.state.transactions.push({transactionId:n,transform:e})}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex((e=>e.transactionId===t));-1!==e&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return JSON.stringify(this.state)}}function Yi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Si{constructor(t,e,A){Yi(this,"client",void 0),Yi(this,"id",void 0),Yi(this,"name",void 0),Yi(this,"metadata",void 0),Yi(this,"productCollection",void 0),Yi(this,"bundleStateManager",void 0),Yi(this,"globalConfiguration",void 0),Yi(this,"globalPropertyStateManager",void 0),Yi(this,"globalPropertyHandleService",void 0),Yi(this,"eventListeners",new Map),Yi(this,"initializationPromise",void 0),Yi(this,"workflowExperiences",[]),Yi(this,"previewService",void 0),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.bundleStateManager=new Fi(e.bundleStateData),this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new yi(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new hi(this),this.setPreviewService(A),this.initializationPromise=this.loadExistingBundles(e.transactions?.map((t=>t.id))||[])}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],n=A.indexOf(e);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===ft.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))}async addWorkflowExperiences(t){const e=t.map((t=>t.getWorkflowManager().getTransaction().id)),A=e.map((t=>this.workflowExperiences.find((e=>e.getWorkflowManager().getTransaction().id===t))));if(A.some((t=>!!t)))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter((t=>!!t)).map((t=>t?.getWorkflowManager().getTransaction().id)).join(", "));const n=de.getMap("transactionOwnerIds")||new Map,a=e.map((t=>n.get(t)));await ye.getShadowGraphqlClient().mutate({mutation:si,variables:{id:this.id,transactionIds:e,transactionOwnerIds:a}}).catch((t=>{console.error(t)})),this.workflowExperiences.push(...t),await Promise.all([this.updateTransactionOrder(),(async()=>{for(const e of t)await this.injectExperienceIntoPreviewService(e);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState(t))))})()])}async appendWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");const A=(de.getMap("transactionOwnerIds")||new Map).get(e);await ye.getShadowGraphqlClient().mutate({mutation:ri,variables:{id:this.id,transactionId:e},context:{transactionOwnerId:A}}),this.workflowExperiences.push(t)}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(t){await this.removeTransactions(t.map((t=>t.getWorkflowManager().getTransaction())))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id);{const[A]=this.workflowExperiences.splice(t,1);this.previewService&&A.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await ye.getShadowGraphqlClient().mutate({mutation:ci,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),await this.updateTransactionOrder()}}async removeTransactions(t){const e=t.map((t=>this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id))));if(e.some((t=>-1===t)))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter(((t,A)=>-1===e[A])).map((t=>t.id)).join(", "));const A=t.map((t=>this.workflowExperiences.splice(this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id)),1)[0]));this.previewService&&A.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t.forEach((t=>this.bundleStateManager.removeStateForTransaction(t.id))),await ye.getShadowGraphqlClient().mutate({mutation:gi,variables:{id:this.id,transactionIds:t.map((t=>t.id)),name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t),this.workflowExperiences.pop(),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))})()])}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ye.getShadowGraphqlClient().mutate({mutation:li,variables:{id:this.id,details:t,type:e||gA.Owner}})}async updateStakeholders(t){await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:ni,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}setWorkflowExperienceTransform(t,e){return this.bundleStateManager.setWorkflowExperienceTransform(t,e),this.updateBundle()}onModelLoadEvent(t){"unload"!==t.eventType&&t.modelContainer&&(t.modelContainer.registerMaterialSelectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!0))),t.modelContainer.registerMaterialDeselectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!1))))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const A=t.metadata.get("workflowManager").getTransaction(),n=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===A.id));n&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:n})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(t){console.error(`Unable to apply state to workflow experience: ${t}`)}await e}}async loadExistingBundles(t){if(0===t.length)return;const e=await Promise.all(t.map((t=>this.client.getWorkflowExperience(void 0,void 0,void 0,{type:"transaction",transactionId:t}))));if(this.workflowExperiences=e,this.previewService)for(const t of e)await this.injectExperienceIntoPreviewService(t)}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:oi,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(A,t),a=this.globalPropertyHandleService.applyConditionsFromState(A,e);(()=>{if(n.length!==a.length)return!0;for(let t=0;t<n.length;t++)if(n[t].getName()!==a[t].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:a})}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach((A=>A({bundle:this,event:t,data:e})))}}function vi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const xi=It`
|
|
773
773
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
774
774
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
775
775
|
id
|
|
@@ -779,7 +779,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
779
779
|
}
|
|
780
780
|
}
|
|
781
781
|
}
|
|
782
|
-
`;class
|
|
782
|
+
`;class Ni{async execute(t,e,A){if(!(await ye.getShadowGraphqlClient().mutate({mutation:xi,variables:{processFlowId:t,inputs:[...e.map((t=>t.getValueForTransmission()))]}})).data?.processExecutionCreate?.id)throw new Error("Failed to create process execution.");function n(t){return new Promise((e=>{setTimeout(e,t)}))}let a,i=!1,o=0;for(;!i;){if(await n(A?.sleepTime?Math.max(A.sleepTime,500):2e3),a=await ye.getShadowGraphqlClient().query({query:It`
|
|
783
783
|
query getProcessFlowExecution($ids: [String]!) {
|
|
784
784
|
processExecutions(ids: $ids) {
|
|
785
785
|
id
|
|
@@ -791,7 +791,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
791
791
|
}
|
|
792
792
|
}
|
|
793
793
|
}
|
|
794
|
-
`,variables:{ids:[t]}}),!a||!a.data?.getProcessFlowExecution)throw new Error("Failed to retrieve server response for execution.");const e=a.data?.getProcessFlowExecution?.completedAt;if(e){i=!0;break}if(a.data?.getProcessFlowExecution?.failedAt)throw new Error("Execution has failed to complete. See Executions tab in partner account on SpiffCommerce Hub.");if(o+=1,o>=5)throw new Error("Maximum wait time exceeded for execution result.")}return Promise.resolve(a.data?.getProcessFlowExecution)}}class
|
|
794
|
+
`,variables:{ids:[t]}}),!a||!a.data?.getProcessFlowExecution)throw new Error("Failed to retrieve server response for execution.");const e=a.data?.getProcessFlowExecution?.completedAt;if(e){i=!0;break}if(a.data?.getProcessFlowExecution?.failedAt)throw new Error("Execution has failed to complete. See Executions tab in partner account on SpiffCommerce Hub.");if(o+=1,o>=5)throw new Error("Maximum wait time exceeded for execution result.")}return Promise.resolve(a.data?.getProcessFlowExecution)}}class Pi{constructor(t){vi(this,"value",void 0),this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):JSON.stringify(t)}}let Ri;var Hi;(Hi=Ri||(Ri={})).Transaction="Transaction",Hi.Bundle="Bundle",Hi.Product="Product",Hi.Variant="Variant",Hi.Option="Option",Hi.LineItem="LineItem",Hi.Asset="Asset";class Ui extends Pi{constructor(t,e){if("Asset"!==e&&!Ui.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class bi extends Pi{constructor(t){super(t)}}function ki(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Gi=It`
|
|
795
795
|
fragment RegionFields on Region {
|
|
796
796
|
width
|
|
797
797
|
top
|
|
@@ -809,7 +809,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
809
809
|
height
|
|
810
810
|
}
|
|
811
811
|
}
|
|
812
|
-
`,
|
|
812
|
+
`,Ji=It`
|
|
813
813
|
fragment LookAtAnimationFields on LookAtAnimation {
|
|
814
814
|
latDeg
|
|
815
815
|
lonDeg
|
|
@@ -820,7 +820,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
820
820
|
z
|
|
821
821
|
}
|
|
822
822
|
}
|
|
823
|
-
`,
|
|
823
|
+
`,Ti=It`
|
|
824
824
|
fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
|
|
825
825
|
antiAliasing {
|
|
826
826
|
samples
|
|
@@ -904,14 +904,14 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
904
904
|
weight
|
|
905
905
|
}
|
|
906
906
|
}
|
|
907
|
-
`,
|
|
907
|
+
`,Li=It`
|
|
908
908
|
fragment ModelAnimationFields on ModelAnimation {
|
|
909
909
|
from
|
|
910
910
|
to
|
|
911
911
|
loop
|
|
912
912
|
name
|
|
913
913
|
}
|
|
914
|
-
`,
|
|
914
|
+
`,Oi=It`
|
|
915
915
|
query GetTransactionForPartner($id: String!) {
|
|
916
916
|
transactions(ids: [$id]) {
|
|
917
917
|
id
|
|
@@ -928,7 +928,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
928
928
|
}
|
|
929
929
|
}
|
|
930
930
|
}
|
|
931
|
-
`,
|
|
931
|
+
`,zi=It`
|
|
932
932
|
${Ye(!1)}
|
|
933
933
|
query GetWorkflowForTheme($id: String!) {
|
|
934
934
|
workflow(id: $id) {
|
|
@@ -950,21 +950,21 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
950
950
|
}
|
|
951
951
|
}
|
|
952
952
|
}
|
|
953
|
-
`,
|
|
953
|
+
`,ji=It`
|
|
954
954
|
query GetCustomer($emailAddress: String!) {
|
|
955
955
|
customer(emailAddress: $emailAddress) {
|
|
956
956
|
id
|
|
957
957
|
emailAddress
|
|
958
958
|
}
|
|
959
959
|
}
|
|
960
|
-
`,
|
|
960
|
+
`,Ki=It`
|
|
961
961
|
mutation CustomerCreate($details: CustomerDetailsInput!) {
|
|
962
962
|
customerCreate(details: $details) {
|
|
963
963
|
id
|
|
964
964
|
emailAddress
|
|
965
965
|
}
|
|
966
966
|
}
|
|
967
|
-
`,
|
|
967
|
+
`,Vi=It`
|
|
968
968
|
mutation CustomerAuthenticate($loginToken: String!) {
|
|
969
969
|
customerAuthenticate(loginToken: $loginToken) {
|
|
970
970
|
id
|
|
@@ -988,11 +988,11 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
988
988
|
}
|
|
989
989
|
}
|
|
990
990
|
}
|
|
991
|
-
`,
|
|
991
|
+
`,Wi=It`
|
|
992
992
|
mutation CustomerGenerateVerificationCode($emailAddress: String!) {
|
|
993
993
|
customerGenerateVerificationCode(emailAddress: $emailAddress)
|
|
994
994
|
}
|
|
995
|
-
`,
|
|
995
|
+
`,Xi=It`
|
|
996
996
|
mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
|
|
997
997
|
customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
|
|
998
998
|
id
|
|
@@ -1020,14 +1020,14 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1020
1020
|
}
|
|
1021
1021
|
}
|
|
1022
1022
|
}
|
|
1023
|
-
`,
|
|
1023
|
+
`,qi=async(t,e)=>{const A=ke.get({id:t,options:e});return A||ke.set({id:t,options:e},(async(t,e)=>{var A;const n=(await ye.getShadowGraphqlClient().query({query:(A=e?.assets?.metadata||!1,It`
|
|
1024
1024
|
${Ye(A)}
|
|
1025
1025
|
${ve}
|
|
1026
1026
|
${Je}
|
|
1027
|
-
${bi}
|
|
1028
|
-
${ki}
|
|
1029
1027
|
${Gi}
|
|
1030
1028
|
${Ji}
|
|
1029
|
+
${Ti}
|
|
1030
|
+
${Li}
|
|
1031
1031
|
query GetWorkflow($id: String!) {
|
|
1032
1032
|
workflow(id: $id) {
|
|
1033
1033
|
allowProofDownload
|
|
@@ -1405,5 +1405,5 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1405
1405
|
}
|
|
1406
1406
|
}
|
|
1407
1407
|
}
|
|
1408
|
-
`),errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}})).data.workflow;return n.steps.forEach((t=>{delete t.data.__typename,t.option?.id&&(t.option.defaultVariant?.asset&&Ue.cacheAsset(t.option.defaultVariant.asset),t.option.colorProfile&&Ue.cacheAsset(t.option.colorProfile),t.option.variants?.forEach((t=>{t.asset&&Ue.cacheAsset(t.asset),t.displayImage&&Ue.cacheAsset(t.displayImage),t.thumbnail&&Ue.cacheAsset(t.thumbnail),t.material&&Ue.cacheMaterial(t.material)})),ke.set({id:t.option.id},Promise.resolve(t.option)))})),n})(t,e))},Xi=(t,e)=>{const A=t.workflowState,n=A?JSON.parse(A):void 0;return n?Object.values(n.layouts).map((t=>t.layout)):e.panels.sort(((t,e)=>t.index-e.index)).map((t=>({id:F(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})))};class qi{constructor(t){var e;Ui(this,"options",void 0),Ui(this,"initialized",void 0),Ui(this,"currencyCode",void 0),Ui(this,"customer",void 0),Ui(this,"experienceOptions",void 0),Ui(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:Jn})}catch(t){throw console.error(t),new ce("Critical - Unable to synchronize workflow state with server.")}})),this.initialized=!1,this.options=t,this.options.applicationKey&&(e=this.options.applicationKey,Ie=e)}getAssetManager(){return Ue}getCurrencyCode(){if(void 0===this.currencyCode)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!this.options.applicationKey)throw new Error("Application key required to use Flow Service.");return new vi}async authenticateBundleFromLocalStorage(t){const e=de.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:gA.Owner})}const A=de.getMap("bundleCustomerIds");if(A?.has(t)){const e=A.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=ye.getShadowGraphqlClient(),A=await e.query({query:Ti,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||0===A.data.transactions.length)throw new Error(`Transaction not found: ${t}`);const n=A.data.transactions[0],a=n.product?.partner?.id;if(!a)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=de.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:gA.Owner})}const o=de.getMap("transactionCustomerIds");if(o?.has(t)){const e=o.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.transactions?.some((e=>e.id===t))))||this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}const r=(await e.query({query:Li,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!r)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:r.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=de.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),de.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=ye.getShadowGraphqlClient(),A=(await e.query({query:Oi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:zi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.customer=A,{customer:A,isAuthenticated:!1}}const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=de.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:ji,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(fe(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:Ki,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:Vi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data?.customerVerifyCode;if(A?.loginToken){if(!A.partner?.id)throw new Error(`Unable to find customer: ${t}`);const e=de.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),de.setMap("customerTokens",e),fe(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:ai,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e)throw new Error("Unable to create bundle");me(e.bundleOwnerId);const A=de.getMap("bundleOwnerIds")||new Map;return A.set(e.id,e.bundleOwnerId),de.setMap("bundleOwnerIds",A),new Fi(this,e)}async getExistingBundle(t,e){const A=de.getMap("bundleOwnerIds")?.get(t);A&&me(A);const n=await ye.getShadowGraphqlClient().query({query:ei,variables:{id:t},fetchPolicy:"no-cache"});if(!n.data?.bundles||0===n.data?.bundles.length||!n.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const a=n.data?.bundles[0],i=new Fi(this,a,e);return await i.getInitializationPromise(),i}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:ni,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||0===t.data.customers.length)throw new Error("Unable to find customer.");return t.data.customers[0].bundleStakeholders||[]}async getWorkflowExperience(t,e,A,n){if(!n)return await this.getWorkflowExperienceDeprecated(t,e,A);const a=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}},{transaction:i,workflow:o,readOnly:r}=await(async()=>{const t=ye.getShadowGraphqlClient();if("transaction"===n.type){const{transactionId:e,readOnly:A}=n,a=await t.query({query:Gn,variables:{id:e},errorPolicy:"all",fetchPolicy:"no-cache"});if(!a.data?.transactions||0===a.data.transactions.length)throw new ce("Existing transaction not found.");const i=a.data?.transactions[0];if(!i.workflowId)throw new ce("Existing transaction has no workflow ID.");const o=await Wi(i.workflowId);if(!i.product)throw new ce("Failed to load transaction, product not available.");return{transaction:i,workflow:o,readOnly:A}}if("integration"===n.type||"external"===n.type){const e=async()=>{const e="integration"===n.type?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},A=await t.mutate({mutation:bn,variables:{...e,bulk:n.bulk,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new ce("Failed to create transaction, product not available.");return a},A=Wi(n.workflowId,n?.graphql),[a,i]=await Promise.all([e(),A]);return{transaction:a,workflow:i}}throw new ce("No workflow ID provided.")})();this.currencyCode=i.product.partner?.currencyCode;const s={product:i.product,transaction:i,layouts:[],stateMutationFunc:r?async()=>{throw new re("State mutation is forbidden in read only mode!")}:async t=>{const e=(de.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...t,context:{transactionOwnerId:e}})},readOnly:r,workflow:o};if("transaction"===n.type&&i.workflowState){const t=JSON.parse(i.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else if(!r&&n.workflowState){const t=JSON.parse(n.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else s.layouts=Xi(s.transaction,s.workflow);if(s.renderableContextService=new Yn(s.layouts),n.previewService?(s.previewService=n.previewService,s.product?.modelUrl&&(s.modelContainer=s.previewService.loadModel({model:s.product.modelUrl,contextService:s.renderableContextService}))):(s.previewService=A&&A(o),s.product?.modelUrl&&(s.previewService?.initialize({model:s.product.modelUrl,contextService:s.renderableContextService}),s.modelContainer=s.previewService?.getAllModels()[0])),"transaction"!==n.type){const t=de.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),de.setMap("transactionOwnerIds",t)}else{const t=(de.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new _a(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:bn,variables:{integrationProductId:t,bulk:this.options.bulk||!1,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new ce("Failed to create transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode;const a=de.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),de.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState},this.initialized=!0}async initFromTransaction(t,e=!1){if(""===t)throw new ce("No transaction ID provided.");const A=ye.getShadowGraphqlClient();if(e)return await(async()=>{const n=(await A.query({query:Gn,variables:{id:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async()=>{throw new re("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0})();const n=de.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Gn,variables:{id:t},errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");return this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},void(this.initialized=!0)}try{const a=(await A.mutate({mutation:kn,variables:{id:t},errorPolicy:"all"})).data?.transactionClaim;if(!a)throw new ce("Failed to read transaction.");if(!a.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=a.product.partner?.currencyCode,a.transactionOwnerId&&(n.set(a.id,a.transactionOwnerId),Qe(a.transactionOwnerId),de.setMap("transactionOwnerIds",n)),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},this.initialized=!0}catch{throw new ce("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot launch experience: Not initialized.");const n=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}};if(this.experienceOptions.transaction.workflowId){const t=await Wi(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=t,this.experienceOptions.transaction.workflowState){const t=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}this.experienceOptions.previewService=A&&A(t),this.experienceOptions.renderableContextService=new Yn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const e=new _a(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:Tn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=Wi(t);if(await Promise.all([a,i]),this.experienceOptions.workflow=await i,e){const t=JSON.parse(e);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}else this.experienceOptions.layouts=Xi(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new Yn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const o=new _a(this,this.experienceOptions);return await o.getWorkflowManager().getInitializationPromise(),o}throw new ce("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}function Zi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class $i{constructor(){Zi(this,"getProduct",void 0),Zi(this,"getCommandContext",void 0),Zi(this,"getAllLayoutData",void 0),Zi(this,"getMetadata",void 0),Zi(this,"getWorkflowMetadata",void 0),Zi(this,"getStepStorage",void 0),Zi(this,"setModelContainer",void 0),Zi(this,"getUpdatesPending",void 0)}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}getVariationRecords(){return[]}async reset(){}updateStateWithServer(t){}addVariationRecord(t){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(t){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addCurrentVariationCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}addVariationRecordsCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}setCurrentAdjustingStepId(t){}setCurrentVariationRecord(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}setVariationRecords(t){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}}function _i(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let to;var eo;(eo=to||(to={})).SelectFrame="SelectFrame",eo.SelectImage="SelectImage",eo.Position="Position";class Ao extends va{constructor(t,e){super(t,e),_i(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ca.selectVariant(this.step,t.getResource(),e,this.manager,(t=>this.setUpdateState(t)))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged((e=>{e&&t(e)}))}selectImage(t){return ca.selectImage(this.step,t,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(t,e,A,n){return n&&n.length>1&&void 0===t?to.SelectFrame:e||A||this.getImageData()?to.Position:to.SelectImage}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}hasVaryingUpload(){return this.step.data.varyUpload}hasVaryingSelection(){return this.step.data.varySelection}}const no=t=>{const e=Gt(null),A=Gt(void 0),[n,a]=Pt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=je(),[c,g]=Pt(!1),[l,B]=Pt(!1),{state:w,uiDispatcher:d}=eA(),h=Rt((t=>{const e=t;d(new tA({zoom:Math.max(.1,Math.min(e,w.maxZoom))}))}),[d,w.maxZoom]),E=Rt((t=>{o(t),1===s.length&&(A.current=void 0),2===s.length&&a(void 0);"touch"===t.pointerType&&s.length>1&&s.length-1==1&&(B(!1),g(!1))}),[o,s.length]),u=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(d(new tA({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,d]),C=Rt((t=>{r(t);const e=1===s.length&&"touch"!==s[0].pointerType,i=2===s.length&&"touch"===s[0].pointerType;if(c&&i){const[t,e]=s,A=Math.abs(t.clientX-e.clientX),i=n;i&&h(w.zoom-.0055*(i-A)),a(A)}if(l&&(e||i)&&t.isPrimary){const e=(A?.current?.x||t.screenX)-t.screenX,n=(A?.current?.y||t.screenY)-t.screenY;d(new tA({selectedElement:void 0,xTranslation:w.xTranslation-e/w.zoom,yTranslation:w.yTranslation-n/w.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,w.zoom,w.xTranslation,w.yTranslation,d]),Q=Rt((t=>{c&&h(w.zoom-.035*Math.sign(t.deltaY))}),[h,w.zoom,c]);Ut((()=>{if(!e.current||0===s.length)return;const t=s[0].pointerId,A=e.current.hasPointerCapture(t);l&&!A&&e.current.setPointerCapture(t),!l&&A&&e.current.releasePointerCapture(t)}),[e,l,s]),zA([" "],(()=>{B(!0),d(new tA({selectedElement:void 0}))}),(()=>B(!1))),zA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=kt((()=>({cursor:l&&0===s.length?"grab":l&&1===s.length?"grabbing":c?"zoom-in":void 0,width:"100%",height:"100%",overflow:"clip"})),[l,c,s]);return Jt("div",{ref:e,className:"transform-wrapper",onWheel:Q,onPointerDown:u,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:C,style:p,children:t.children})};export{qi as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,WA as PromiseQueue,VA as QueueablePromise,$i as MockWorkflowManager,fa as InformationMessageType,va as StepHandle,Ta as TextStepHandle,Ao as FrameStepHandle,Ra as BulkStepHandle,Ja as ShapeStepHandle,Ha as IllustrationStepHandle,Ua as MaterialStepHandle,ba as ModelStepHandle,ka as PictureStepHandle,Ga as QuestionStepHandle,aA as BulkPriceCalculationStrategy,Ya as Variant,_a as WorkflowExperienceImpl,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,Ue as assetService,Za as designService,Wa as createDesign,Oe as optionService,de as persistenceService,ye as graphQlManager,dA as toast,ea as FrameService,_n as getBoundedOffsets,ca as frameStepService,Ba as modelStepService,la as materialStepService,Ea as shapeStepService,ha as questionStepService,ra as digitalContentStepService,wa as moduleStepService,da as pictureStepService,ma as textStepService,ga as illustrationStepService,AA as ProductCameraRig,to as FrameStep,oA as ConversionLocation,sA as ConversionDataType,Wi as getWorkflow,aa as shortenUrl,Ri as ObjectInput,Hi as TextInput,Ni as ObjectInputType,e as AssetType,A as BringForwardCommand,n as BringToFrontCommand,a as BringToBackCommand,i as CanvasCommand,o as CreateElementCommand,r as CreateLayoutCommand,s as DeleteElementCommand,c as FontAlignmentCommand,g as FontColorCommand,l as FontSizeCommand,B as FontSourceCommand,w as GroupCommand,d as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,u as ResizeCommand,C as RotateCommand,Q as SendBackwardsCommand,gA as StakeholderType,p as StepAspectType,m as StepType,D as TextChangeCommand,f as UnitOfMeasurement,I as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,Y as getAxisAlignedBoundingBox,S as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,N as getFrameData,P as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,U as determineCorrectFontSizeAndLines,b as patternImageDataCache,Mn as generateCommands,k as registerJSDOM,TA as minZoom,Un as AdvancedEditor,no as TransformWrapper,Hn as EditorCore,Ke as useLayouts,eA as useEditorState,OA as useEditorInteraction,zA as useShortcutCombination,Ze as commandReducer,qe as getDefaultState,ze as CommandContextContext,_e as AdvancedEditorStateProvider,$e as AdvancedEditorContext,tA as UICommand,We as EditorSubMenu,hA as ElementEventType,uA as KeyEvent,jn as gatherVaryingStepAspects};
|
|
1408
|
+
`),errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}})).data.workflow;return n.steps.forEach((t=>{delete t.data.__typename,t.option?.id&&(t.option.defaultVariant?.asset&&Ue.cacheAsset(t.option.defaultVariant.asset),t.option.colorProfile&&Ue.cacheAsset(t.option.colorProfile),t.option.variants?.forEach((t=>{t.asset&&Ue.cacheAsset(t.asset),t.displayImage&&Ue.cacheAsset(t.displayImage),t.thumbnail&&Ue.cacheAsset(t.thumbnail),t.material&&Ue.cacheMaterial(t.material)})),ke.set({id:t.option.id},Promise.resolve(t.option)))})),n})(t,e))},Zi=(t,e)=>{const A=t.workflowState,n=A?JSON.parse(A):void 0;return n?Object.values(n.layouts).map((t=>t.layout)):e.panels.sort(((t,e)=>t.index-e.index)).map((t=>({id:F(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})))};class $i{constructor(t){var e;ki(this,"options",void 0),ki(this,"initialized",void 0),ki(this,"currencyCode",void 0),ki(this,"customer",void 0),ki(this,"experienceOptions",void 0),ki(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:Jn})}catch(t){throw console.error(t),new ce("Critical - Unable to synchronize workflow state with server.")}})),this.initialized=!1,this.options=t,this.options.applicationKey&&(e=this.options.applicationKey,Ie=e)}getAssetManager(){return Ue}getCurrencyCode(){if(void 0===this.currencyCode)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!this.options.applicationKey)throw new Error("Application key required to use Flow Service.");return new Ni}async authenticateBundleFromLocalStorage(t){const e=de.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:gA.Owner})}const A=de.getMap("bundleCustomerIds");if(A?.has(t)){const e=A.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=ye.getShadowGraphqlClient(),A=await e.query({query:Oi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||0===A.data.transactions.length)throw new Error(`Transaction not found: ${t}`);const n=A.data.transactions[0],a=n.product?.partner?.id;if(!a)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=de.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:gA.Owner})}const o=de.getMap("transactionCustomerIds");if(o?.has(t)){const e=o.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.transactions?.some((e=>e.id===t))))||this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}const r=(await e.query({query:zi,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!r)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:r.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=de.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),de.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=ye.getShadowGraphqlClient(),A=(await e.query({query:ji,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:Ki,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.customer=A,{customer:A,isAuthenticated:!1}}const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=de.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:Vi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(fe(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:Wi,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:Xi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data?.customerVerifyCode;if(A?.loginToken){if(!A.partner?.id)throw new Error(`Unable to find customer: ${t}`);const e=de.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),de.setMap("customerTokens",e),fe(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:ii,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e)throw new Error("Unable to create bundle");me(e.bundleOwnerId);const A=de.getMap("bundleOwnerIds")||new Map;return A.set(e.id,e.bundleOwnerId),de.setMap("bundleOwnerIds",A),new Si(this,e)}async getExistingBundle(t,e){const A=de.getMap("bundleOwnerIds")?.get(t);A&&me(A);const n=await ye.getShadowGraphqlClient().query({query:Ai,variables:{id:t},fetchPolicy:"no-cache"});if(!n.data?.bundles||0===n.data?.bundles.length||!n.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const a=n.data?.bundles[0],i=new Si(this,a,e);return await i.getInitializationPromise(),i}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:ai,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||0===t.data.customers.length)throw new Error("Unable to find customer.");return t.data.customers[0].bundleStakeholders||[]}async getWorkflowExperience(t,e,A,n){if(!n)return await this.getWorkflowExperienceDeprecated(t,e,A);const a=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}},{transaction:i,workflow:o,readOnly:r}=await(async()=>{const t=ye.getShadowGraphqlClient();if("transaction"===n.type){const{transactionId:e,readOnly:A}=n,a=await t.query({query:Gn,variables:{id:e},errorPolicy:"all",fetchPolicy:"no-cache"});if(!a.data?.transactions||0===a.data.transactions.length)throw new ce("Existing transaction not found.");const i=a.data?.transactions[0];if(!i.workflowId)throw new ce("Existing transaction has no workflow ID.");const o=await qi(i.workflowId);if(!i.product)throw new ce("Failed to load transaction, product not available.");return{transaction:i,workflow:o,readOnly:A}}if("integration"===n.type||"external"===n.type){const e=async()=>{const e="integration"===n.type?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},A=await t.mutate({mutation:bn,variables:{...e,bulk:n.bulk,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new ce("Failed to create transaction, product not available.");return a},A=qi(n.workflowId,n?.graphql),[a,i]=await Promise.all([e(),A]);return{transaction:a,workflow:i}}throw new ce("No workflow ID provided.")})();this.currencyCode=i.product.partner?.currencyCode;const s={product:i.product,transaction:i,layouts:[],stateMutationFunc:r?async()=>{throw new re("State mutation is forbidden in read only mode!")}:async t=>{const e=(de.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...t,context:{transactionOwnerId:e}})},readOnly:r,workflow:o};if("transaction"===n.type&&i.workflowState){const t=JSON.parse(i.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else if(!r&&n.workflowState){const t=JSON.parse(n.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else s.layouts=Zi(s.transaction,s.workflow);if(s.renderableContextService=new Yn(s.layouts),n.previewService?(s.previewService=n.previewService,s.product?.modelUrl&&(s.modelContainer=s.previewService.loadModel({model:s.product.modelUrl,contextService:s.renderableContextService}))):(s.previewService=A&&A(o),s.product?.modelUrl&&(s.previewService?.initialize({model:s.product.modelUrl,contextService:s.renderableContextService}),s.modelContainer=s.previewService?.getAllModels()[0])),"transaction"!==n.type){const t=de.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),de.setMap("transactionOwnerIds",t)}else{const t=(de.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new ti(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:bn,variables:{integrationProductId:t,bulk:this.options.bulk||!1,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new ce("Failed to create transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode;const a=de.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),de.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState},this.initialized=!0}async initFromTransaction(t,e=!1){if(""===t)throw new ce("No transaction ID provided.");const A=ye.getShadowGraphqlClient();if(e)return await(async()=>{const n=(await A.query({query:Gn,variables:{id:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async()=>{throw new re("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0})();const n=de.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Gn,variables:{id:t},errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");return this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},void(this.initialized=!0)}try{const a=(await A.mutate({mutation:kn,variables:{id:t},errorPolicy:"all"})).data?.transactionClaim;if(!a)throw new ce("Failed to read transaction.");if(!a.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=a.product.partner?.currencyCode,a.transactionOwnerId&&(n.set(a.id,a.transactionOwnerId),Qe(a.transactionOwnerId),de.setMap("transactionOwnerIds",n)),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},this.initialized=!0}catch{throw new ce("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot launch experience: Not initialized.");const n=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}};if(this.experienceOptions.transaction.workflowId){const t=await qi(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=t,this.experienceOptions.transaction.workflowState){const t=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}this.experienceOptions.previewService=A&&A(t),this.experienceOptions.renderableContextService=new Yn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const e=new ti(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:Tn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=qi(t);if(await Promise.all([a,i]),this.experienceOptions.workflow=await i,e){const t=JSON.parse(e);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}else this.experienceOptions.layouts=Zi(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new Yn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const o=new ti(this,this.experienceOptions);return await o.getWorkflowManager().getInitializationPromise(),o}throw new ce("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}function _i(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class to{constructor(){_i(this,"getProduct",void 0),_i(this,"getCommandContext",void 0),_i(this,"getAllLayoutData",void 0),_i(this,"getMetadata",void 0),_i(this,"getWorkflowMetadata",void 0),_i(this,"getStepStorage",void 0),_i(this,"setModelContainer",void 0),_i(this,"getUpdatesPending",void 0)}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}getVariationRecords(){return[]}async reset(){}updateStateWithServer(t){}addVariationRecord(t){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(t){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addCurrentVariationCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}addVariationRecordsCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}setCurrentAdjustingStepId(t){}setCurrentVariationRecord(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}setVariationRecords(t){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}}function eo(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Ao;var no;(no=Ao||(Ao={})).SelectFrame="SelectFrame",no.SelectImage="SelectImage",no.Position="Position";class ao extends xa{constructor(t,e){super(t,e),eo(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ca.selectVariant(this.step,t.getResource(),e,this.manager,(t=>this.setUpdateState(t)))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged((e=>{e&&t(e)}))}selectImage(t){return ca.selectImage(this.step,t,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(t,e,A,n){return n&&n.length>1&&void 0===t?Ao.SelectFrame:e||A||this.getImageData()?Ao.Position:Ao.SelectImage}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}hasVaryingUpload(){return this.step.data.varyUpload}hasVaryingSelection(){return this.step.data.varySelection}}const io=t=>{const e=Gt(null),A=Gt(void 0),[n,a]=Pt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=je(),[c,g]=Pt(!1),[l,B]=Pt(!1),{state:w,uiDispatcher:d}=eA(),h=Rt((t=>{const e=t;d(new tA({zoom:Math.max(.1,Math.min(e,w.maxZoom))}))}),[d,w.maxZoom]),E=Rt((t=>{o(t),1===s.length&&(A.current=void 0),2===s.length&&a(void 0);"touch"===t.pointerType&&s.length>1&&s.length-1==1&&(B(!1),g(!1))}),[o,s.length]),u=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(d(new tA({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,d]),C=Rt((t=>{r(t);const e=1===s.length&&"touch"!==s[0].pointerType,i=2===s.length&&"touch"===s[0].pointerType;if(c&&i){const[t,e]=s,A=Math.abs(t.clientX-e.clientX),i=n;i&&h(w.zoom-.0055*(i-A)),a(A)}if(l&&(e||i)&&t.isPrimary){const e=(A?.current?.x||t.screenX)-t.screenX,n=(A?.current?.y||t.screenY)-t.screenY;d(new tA({selectedElement:void 0,xTranslation:w.xTranslation-e/w.zoom,yTranslation:w.yTranslation-n/w.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,w.zoom,w.xTranslation,w.yTranslation,d]),Q=Rt((t=>{c&&h(w.zoom-.035*Math.sign(t.deltaY))}),[h,w.zoom,c]);Ut((()=>{if(!e.current||0===s.length)return;const t=s[0].pointerId,A=e.current.hasPointerCapture(t);l&&!A&&e.current.setPointerCapture(t),!l&&A&&e.current.releasePointerCapture(t)}),[e,l,s]),zA([" "],(()=>{B(!0),d(new tA({selectedElement:void 0}))}),(()=>B(!1))),zA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=kt((()=>({cursor:l&&0===s.length?"grab":l&&1===s.length?"grabbing":c?"zoom-in":void 0,width:"100%",height:"100%",overflow:"clip"})),[l,c,s]);return Jt("div",{ref:e,className:"transform-wrapper",onWheel:Q,onPointerDown:u,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:C,style:p,children:t.children})};export{$i as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,WA as PromiseQueue,VA as QueueablePromise,to as MockWorkflowManager,Ia as InformationMessageType,xa as StepHandle,La as TextStepHandle,ao as FrameStepHandle,Ha as BulkStepHandle,Ta as ShapeStepHandle,Ua as IllustrationStepHandle,ba as MaterialStepHandle,ka as ModelStepHandle,Ga as PictureStepHandle,Ja as QuestionStepHandle,aA as BulkPriceCalculationStrategy,Sa as Variant,ti as WorkflowExperienceImpl,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,Ue as assetService,$a as designService,Xa as createDesign,Oe as optionService,de as persistenceService,ye as graphQlManager,dA as toast,ea as FrameService,_n as getBoundedOffsets,ca as frameStepService,Ba as modelStepService,la as materialStepService,ua as shapeStepService,ha as questionStepService,ra as digitalContentStepService,wa as moduleStepService,da as pictureStepService,Da as textStepService,ga as illustrationStepService,AA as ProductCameraRig,Ao as FrameStep,oA as ConversionLocation,sA as ConversionDataType,qi as getWorkflow,aa as shortenUrl,Ui as ObjectInput,bi as TextInput,Ri as ObjectInputType,e as AssetType,A as BringForwardCommand,n as BringToFrontCommand,a as BringToBackCommand,i as CanvasCommand,o as CreateElementCommand,r as CreateLayoutCommand,s as DeleteElementCommand,c as FontAlignmentCommand,g as FontColorCommand,l as FontSizeCommand,B as FontSourceCommand,w as GroupCommand,d as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,u as ResizeCommand,C as RotateCommand,Q as SendBackwardsCommand,gA as StakeholderType,p as StepAspectType,m as StepType,D as TextChangeCommand,f as UnitOfMeasurement,I as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,Y as getAxisAlignedBoundingBox,S as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,N as getFrameData,P as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,U as determineCorrectFontSizeAndLines,b as patternImageDataCache,Mn as generateCommands,k as registerJSDOM,TA as minZoom,Un as AdvancedEditor,io as TransformWrapper,Hn as EditorCore,Ke as useLayouts,eA as useEditorState,OA as useEditorInteraction,zA as useShortcutCombination,Ze as commandReducer,qe as getDefaultState,ze as CommandContextContext,_e as AdvancedEditorStateProvider,$e as AdvancedEditorContext,tA as UICommand,We as EditorSubMenu,hA as ElementEventType,uA as KeyEvent,jn as gatherVaryingStepAspects};
|
|
1409
1409
|
//# sourceMappingURL=module.js.map
|