@spiffcommerce/core 0.4.1 → 0.4.3

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 CHANGED
@@ -1,4 +1,4 @@
1
- var e=require("papyrus/build/main/CommandContext"),t=require("papyrus/build/main/command"),a=(require("papyrus/build/main/Elements/factory"),require("spiff-preview"),require("papyrus/build/main/font")),i=require("swagger-client"),n=require("@apollo/client"),o=require("@apollo/client/link/context"),r=require("@apollo/client/link/error"),s=require("cross-fetch"),l=require("react"),c=require("react/jsx-runtime"),d=require("papyrus/build/main/types"),h=require("lodash.isequal"),p=require("papyrus/build/main/LayoutsState/types"),u=require("papyrus/build/main/math"),m=require("papyrus/build/main/text/algorithm/traditional"),f=require("papyrus/build/main/text/shared"),g=require("papyrus/build/main/image"),w=require("canvg"),y=require("papyrus/build/main/generation/Workflow"),S=require("lodash.clonedeep"),v=require("papyrus/build/main/module/resolver"),x=require("lodash.debounce"),C=require("papyrus/build/main/frame"),b=require("papyrus/build/main/illustration"),k=require("papyrus/build/main/LayoutsState"),E=require("qrcode"),I=require("papyrus/build/main/crossplatform"),N=require("react-dom/server"),R=require("papyrus/build/main/Elements/Patchwork"),O=require("papyrus/build/main/text/algorithm/autosize"),M=require("papyrus/build/main/generation");function T(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}function A(e){return e&&e.__esModule?e.default:e}function L(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}T(module.exports,"Client",(()=>Ut)),T(module.exports,"CommandContext",(()=>$eb7869949b641a40$re_export$CommandContext)),T(module.exports,"spiffCoreConfiguration",(()=>V)),T(module.exports,"PromiseQueue",(()=>He)),T(module.exports,"QueueablePromise",(()=>Ge)),T(module.exports,"MockWorkflowManager",(()=>Ft)),T(module.exports,"InformationMessageType",(()=>Ct)),T(module.exports,"assetService",(()=>Ce)),T(module.exports,"optionService",(()=>P)),T(module.exports,"server",(()=>q)),T(module.exports,"persistenceService",(()=>Ee)),T(module.exports,"graphQlManager",(()=>W)),T(module.exports,"toast",(()=>gt)),T(module.exports,"FrameService",(()=>Ze)),T(module.exports,"frameStepService",(()=>rt)),T(module.exports,"modelStepService",(()=>lt)),T(module.exports,"materialStepService",(()=>st)),T(module.exports,"patchworkStepService",(()=>pt)),T(module.exports,"shapeStepService",(()=>mt)),T(module.exports,"questionStepService",(()=>Pe)),T(module.exports,"digitalContentStepService",(()=>ot)),T(module.exports,"moduleStepService",(()=>ct)),T(module.exports,"pictureStepService",(()=>ut)),T(module.exports,"textStepService",(()=>vt)),T(module.exports,"illustrationStepService",(()=>Je)),T(module.exports,"svgObjectURL",(()=>Qe)),T(module.exports,"generate",(()=>de)),T(module.exports,"CreateElementCommand",(()=>$eb7869949b641a40$re_export$CreateElementCommand)),T(module.exports,"TextChangeCommand",(()=>$eb7869949b641a40$re_export$TextChangeCommand)),T(module.exports,"FontAlignmentCommand",(()=>$eb7869949b641a40$re_export$FontAlignmentCommand)),T(module.exports,"FontColorCommand",(()=>$eb7869949b641a40$re_export$FontColorCommand)),T(module.exports,"LayoutElementFactory",(()=>$eb7869949b641a40$re_export$LayoutElementFactory)),T(module.exports,"minZoom",(()=>he)),T(module.exports,"AdvancedEditor",(()=>ve)),T(module.exports,"EditorCore",(()=>Se)),T(module.exports,"useLayouts",(()=>B)),T(module.exports,"useEditorState",(()=>Q)),T(module.exports,"useEditorInteraction",(()=>pe)),T(module.exports,"commandReducer",(()=>X)),T(module.exports,"getDefaultState",(()=>H)),T(module.exports,"CommandContextContext",(()=>$)),T(module.exports,"AdvancedEditorStateProvider",(()=>Y)),T(module.exports,"AdvancedEditorContext",(()=>_)),T(module.exports,"UICommand",(()=>Z)),T(module.exports,"EditorSubMenu",(()=>K)),T(module.exports,"gatherVaryingStepAspects",(()=>ze)),T(module.exports,"SpiffCommerce3DPreviewService",(()=>$eb7869949b641a40$re_export$SpiffCommerce3DPreviewService));const P=new class{constructor(){L(this,"cache",new Map),L(this,"getDisplayImageSource",(e=>{if(e){const t=e.displayImage?.links.find((e=>"cdn"===e.rel));if(t)return t.href}})),L(this,"getSelectedVariant",((e,t)=>{if(e&&0!==t.length)return e.variants.find((e=>e.id===t[0]))})),L(this,"getSelectedVariants",((e,t)=>e?.variants.filter((e=>t.includes(e.id)))||[]))}async cacheRequiredOptions(e){const t=e.steps.map((e=>e.optionId)).filter((e=>void 0!==e)),i=e.steps.map((e=>e.data.colourOptionId)).filter((e=>void 0!==e)),n=[...new Set([...t,...i])].map((async e=>{const t=await P.getLocalOrFromServer(q,e);"Font"===t.data.type&&t.data.variants.forEach((async e=>{if(e.assetKey){const t=(await Ce.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel))?.href;t&&await(0,a.loadFontFromExternalUrl)(t)}}))}));await Promise.allSettled([...n])}async getLocalOrFromServer(e,t){if(this.cache.has(t))return this.cache.get(t);const a=(await e.execute("getOptionV2",{id:t})).body;return this.cache.set(t,a),a}getLocalOrUndefined(e){if(e)return this.cache.get(e)}async getAssetTileImageForVariant(e){if(e.thumbnailKey){const t=await Ce.getLocalOrFromServer(e.thumbnailKey),a=t.links.find((e=>"thumbnail"===e.rel)),i=t.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}const t=e.assetKey;if(t){const e=await Ce.getLocalOrFromServer(t),a=e.links.find((e=>"thumbnail"===e.rel)),i=e.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}return e.materialId?e.materialId:""}getDefaultVariant(e){const t=e.variants;return 1===t.length?t[0]:void 0!==e.defaultVariant?t.find((t=>t.id===e.defaultVariant)):void 0}};function D(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const V=new class{constructor(){D(this,"defaultServerUrl","https://api.spiff.com.au"),D(this,"defaultServicesApiUrl","https://services.spiff.com.au"),D(this,"serverUrl",void 0),D(this,"servicesApiUrl",void 0),D(this,"serverUrlCallbacks",void 0),this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}setServerUrl(e){this.serverUrl=e,this.serverUrlCallbacks.forEach((e=>e()))}setServicesApiUrl(e){this.servicesApiUrl=e}addServerUrlCallback(e){this.serverUrlCallbacks.push(e)}};function z(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}let U;const F=e=>{U=e},j=async()=>({transactionOwnerId:U});const q=new class{constructor(){z(this,"client",void 0),z(this,"uncachedOperations",[]),V.addServerUrlCallback((async()=>{this.client=void 0,this.client=await this.constructClient()}))}setUncachedOperations(e){this.uncachedOperations=e}async execute(e,t){const a=this.uncachedOperations.includes(e)?e+"_private":e;return new Promise(((e,i)=>{this.getClient().then((n=>{n.execute({operationId:a,parameters:t}).then((t=>e(t))).catch((e=>{e.response&&e.response.status&&e.response.status>=500||(!e.response&&i(new Error(e)),e.response&&i(new Error(`${e.response.status} ${e.response.url}`)))}))})).catch((e=>{i(e)}))}))}async syncAuth(e){const t=await j();if(t.bearer?e.authorizations={...e.authorizations,OAuth2:{token:{access_token:t.bearer,token_type:"Bearer"}}}:e.authorizations={...e.authorizations,OAuth2:{token:{access_token:"",token_type:"Bearer"}}},t.activeIntegration)e.authorizations={...e.authorizations,ActiveIntegration:t.activeIntegration};else{const t={...e.authorizations};delete t.ActiveIntegration,e.authorizations=t}if(t.partnerId)e.authorizations={...e.authorizations,PartnerId:t.partnerId};else{const t={...e.authorizations};delete t.PartnerId,e.authorizations=t}}async getClient(){return this.client||(this.client=await this.constructClient()),this.syncAuth(this.client),Promise.resolve(this.client)}async constructClient(){const e=await j(),t=V.getServerUrl()+"/v2/api-docs";return await A(i)(t,{authorizations:{OAuth2:{token:{access_token:e.bearer,token_type:"Bearer"}},PartnerId:e.partnerId}})}};const W=new class{constructor(){z(this,"shadowGraphqlClient",void 0),this.shadowGraphqlClient=this.constructShadowGraphqlClient(),V.addServerUrlCallback((()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()}))}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const e=(0,n.createHttpLink)({uri:`${V.getServerUrl()}/graphql`,fetch:A(s)}),t=(0,o.setContext)((async(e,{headers:t})=>{const a=t||{},i=await j();return i.bearer&&(a.Authorization=`Bearer ${i.bearer}`),i.partnerId&&(a.partnerId=i.partnerId),i.activeIntegration&&(a.activeIntegration=i.activeIntegration),i.transactionOwnerId&&(a.transactionOwnerId=i.transactionOwnerId),{headers:a}})),a=(0,r.onError)((({operation:e,graphQLErrors:t,networkError:a})=>{(t||[]).forEach((({message:t,locations:a,path:i})=>{console.log("[GraphQL Operation Error]"),console.log("Name:"+e.operationName),console.log("Query:"+JSON.stringify(e.query)),console.log(`Message: ${t}, Location: ${JSON.stringify(a,null,2)}, Path: ${i}`),console.log("Variables:"+JSON.stringify(e.variables))})),a&&console.log("GraphQL Network error")}));const i=new(0,n.InMemoryCache)({typePolicies:{Transaction:{fields:{transactionOwnerId:{read:(e=null)=>e},customLogoLink:{read:(e=null)=>e},workflowFooterLogoLink:{read:(e=null)=>e},workflowState:{read:(e=null)=>e},bulkSourceUrl:{read:(e=null)=>e}}}}});return new(0,n.ApolloClient)({link:(0,n.from)([a,t,e]),cache:i,name:"Core"})}},$=(0,l.createContext)(new(0,e.CommandContext)),B=()=>{const e=(0,l.useContext)($);(0,l.useEffect)((()=>{e.registerStateCallback((()=>{a(new Date)}))}),[e]);const[t,a]=(0,l.useState)(new Date);return{commandDispatcher:t=>{e.apply(t)},getLayoutById:t=>e.getLayoutById(t),getAllLayouts:()=>e.getAllLayouts(),getReducerState:()=>{const t=e.getState();return t||{transaction:{layouts:{},serializableWorkflow:{steps:[]}}}},lastUpdated:t,flattenSequence:(t,a)=>{e.flattenSequence(t,a)}}};let K;var G;(G=K||(K={})).None="None",G.FrameAdjustment="FrameAdjustment",G.FinalizeDesign="FinalizeDesign";const H=(e,t)=>({layoutId:e()[0].layoutState.layout.id,selectedElement:void 0,zoom:t,maxZoom:5,units:d.UnitOfMeasurement.Pixel,subMenu:K.None,activeModifierKeys:[],metaPressed:!1,elementEvent:void 0,scrolledMovement:!1}),X=(e,t)=>A(h)(e,t.apply(e))?e:t.apply(e),_=(0,l.createContext)({}),Y=e=>{const{getAllLayouts:t}=B(),[a,i]=(0,l.useReducer)(X,H(t,e.defaultZoom||1)),n=(0,l.useMemo)((()=>({state:a,uiDispatcher:i})),[a,i]);return(0,c.jsx)(_.Provider,{value:n,children:e.children})};class Z{constructor(e){var t,a,i;i=void 0,(a="changes")in(t=this)?Object.defineProperty(t,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[a]=i,this.changes=e}apply(e){return{...e,...this.changes}}}const Q=()=>(0,l.useContext)(_),J=7*window.devicePixelRatio,ee=(e,t,a,i)=>{const n=t.layout.width,o=t.layout.height,r=t.elements.filter((t=>t.id!==e.id&&!t.immutable&&!t.productOverlay)),s=r.map((e=>(0,u.getAxisAlignedBoundingBox)(e.x,e.y,e.width,e.height,e.rotation))),l=[],d=new Set;s.forEach((e=>d.add(e.minX))),s.forEach((e=>d.add(e.maxX))),[0,n/2,n].forEach((e=>d.add(e)));const h=new Set;s.forEach((e=>h.add(e.minY))),s.forEach((e=>h.add(e.maxY))),[0,o/2,o].forEach((e=>h.add(e)));const p=r.map((e=>e.y));for(let e=-315;e<=315;e+=45)p.push(e);const m=(0,u.getAxisAlignedBoundingBox)(e.x,e.y,e.width,e.height,e.rotation),f=[{value:m.minX,anchor:-1},{value:m.minX+(m.maxX-m.minX)/2,anchor:0},{value:m.minX+(m.maxX-m.minX),anchor:1}],g=[{value:m.minY,anchor:-1},{value:m.minY+(m.maxY-m.minY)/2,anchor:0},{value:m.minY+(m.maxY-m.minY),anchor:1}],w=[{value:e.rotation,anchor:0}],y=(e,t,i,r)=>{const s=[];return t.forEach((t=>{const l=i.find((e=>(0,u.isCloseToValue)(t,e.value,2*a))),[d,h]=((e,t)=>[{x:"x"===e?t:0,y:"x"===e?0:t},{x:"x"===e?t:n,y:"x"===e?o:t}])(e,t),p="rotation"===e?null:(0,c.jsx)("line",{x1:d.x,y1:d.y,x2:h.x,y2:h.y,stroke:r||"#D61B5C",strokeDasharray:5*a,strokeWidth:1.2*a,overflow:"overlay"},`${e}-${t}-${d.x}-${d.y}-${h.x}-${h.y}`);void 0!==l&&s.push({type:e,value:t,anchorPoint:l.anchor,svgNode:p,guidelineCoordinates:[d,h]})})),s};return l.push(...y("x",Array.from(d),f,i)),l.push(...y("y",Array.from(h),g,i)),l.push(...y("rotation",p,w,i)),l};let te;var ae;let ie;var ne;(ae=te||(te={})).Translate="Translate",ae.Rotate="Rotate",ae.Resize="Resize",(ne=ie||(ie={})).ControlLeft="ControlLeft",ne.ControlRight="ControlRight",ne.Equal="Equal",ne.MetaLeft="MetaLeft",ne.MetaRight="MetaRight",ne.Minus="Minus",ne.ArrowLeft="ArrowLeft",ne.ArrowRight="ArrowRight",ne.ArrowUp="ArrowUp",ne.ArrowDown="ArrowDown",ne.AltLeft="AltLeft",ne.AltRight="AltRight",ne.Delete="Delete",ne.Backspace="Backspace";const oe=(e,a,i,n)=>{const o=()=>{switch(i){case d.UnitOfMeasurement.Pixel:return 1;case d.UnitOfMeasurement.Millimeter:return u.mmPerPixel;case d.UnitOfMeasurement.Centimeter:return u.cmPerPixel;default:throw new Error("Unknown unit of measurement")}};let r=a.x,s=a.y,l=a.x,c=a.y;switch(e){case ie.ArrowLeft:l=a.x-1/o();break;case ie.ArrowUp:c=a.y-1/o();break;case ie.ArrowRight:l=a.x+1/o();break;case ie.ArrowDown:c=a.y+1/o();break;default:throw new Error("Unhandled element interaction!")}const h=(0,u.getAxisAlignedBoundingBox)(l,c,a.width,a.height,a.rotation);return(!n||h.minX>=n.left&&h.maxX<=n.left+n.width&&h.minY>=n.top&&h.maxY<=n.top+n.height)&&(r=l,s=c),new(0,t.MoveCommand)(a.id,r,s)};var re=0,se=0,le=0;const ce=(e,a,i,n,o,r,s)=>{const l=((e,t,a,i,n,o,r)=>{const s=i.width/t.width,l=i.height/t.height,c=e.movementX/s,h=e.movementY/l,g=a.rotation*Math.PI/180,w=Math.sin(g),y=Math.cos(g);let S;switch(n.type){case te.Resize:let t={top:a.y,left:a.x,width:a.width,height:a.height,rotation:a.rotation,fontSize:a.fontSize},v=t;switch(n.screenAxis){case d.ScaleAxis.North:{const e=-c*w+h*y,i=a.y+e,n=a.height-e,o=(0,u.getElementVertices)({...a}).center,r=(0,u.getElementVertices)({...a,y:i,height:n}).center,s=(0,u.rotateAroundPoint)(r,o,g),l=s.x-a.width/2,d=s.y-n/2;v={...t,left:l,top:d,height:n}}break;case d.ScaleAxis.East:{const e=c*y+h*w,i=a.width+e;let n=a.height;if(a.type===p.LayoutElementType.Textbox){const e=a;n=(0,m.calculateTextboxLines)(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const o=(0,u.getElementVertices)({...a}).center,r=(0,u.getElementVertices)({...a,width:i,height:n}).center,s=(0,u.rotateAroundPoint)(r,o,g),l=s.x-i/2,d=s.y-n/2;v={...t,left:l,top:d,width:i,height:n}}break;case d.ScaleAxis.West:{const e=c*y+h*w,i=a.x+e,n=a.width-e;let o=a.height;if(a.type===p.LayoutElementType.Textbox){const e=a;o=(0,m.calculateTextboxLines)(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const r=(0,u.getElementVertices)({...a}).center,s=(0,u.getElementVertices)({...a,width:n,height:o,x:i}).center,l=(0,u.rotateAroundPoint)(s,r,g),d=l.x-n/2,f=l.y-o/2;v={...t,left:d,top:f,width:n,height:o}}break;case d.ScaleAxis.South:{const e=-c*w+h*y,i=a.height+e,n=(0,u.getElementVertices)({...a}).center,o=(0,u.getElementVertices)({...a,height:i}).center,r=(0,u.rotateAroundPoint)(o,n,g),s=r.x-a.width/2,l=r.y-i/2;v={...t,left:s,top:l,height:i}}break;case d.ScaleAxis.Northeast:{const e=c*y+h*w,i=a.width+e;let n=a.height+e,o=a.y-e,r=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;r=t.fontSize+e/8,n=(0,m.calculateTextboxLines)(r,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||f.defaultLineHeightFactor;o=a.y-e*i/8}const s=(0,u.getElementVertices)({...a}).center,l=(0,u.getElementVertices)({...a,width:i,height:n,y:o}).center,d=(0,u.rotateAroundPoint)(l,s,g),S=d.x-i/2,x=d.y-n/2;v={...t,left:S,top:x,width:i,height:n,fontSize:r}}break;case d.ScaleAxis.Northwest:{const e=-c*y+-h*w,i=a.x-e,n=a.width+e;let o=a.y-e,r=a.height+e,s=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;s=t.fontSize+e/8,r=(0,m.calculateTextboxLines)(s,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||f.defaultLineHeightFactor;o=a.y-e*i/8}const l=(0,u.getElementVertices)({...a}).center,d=(0,u.getElementVertices)({...a,x:i,y:o,width:n,height:r}).center,S=(0,u.rotateAroundPoint)(d,l,g),x=S.x-n/2,C=S.y-r/2;v={...t,left:x,top:C,width:n,height:r,fontSize:s}}break;case d.ScaleAxis.Southeast:{const e=c*y+h*w,i=a.width+e;let n=a.height+e,o=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;o=t.fontSize+e/8,n=(0,m.calculateTextboxLines)(o,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const r=(0,u.getElementVertices)({...a}).center,s=(0,u.getElementVertices)({...a,width:i,height:n}).center,l=(0,u.rotateAroundPoint)(s,r,g),d=l.x-i/2,f=l.y-n/2;v={...t,left:d,top:f,width:i,height:n,fontSize:o}}break;case d.ScaleAxis.Southwest:{const e=-c*y+-h*w,i=a.width+e;let n=a.x-e,o=a.height+e,r=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;r=t.fontSize+e/8,o=(0,m.calculateTextboxLines)(r,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const s=(0,u.getElementVertices)({...a}).center,l=(0,u.getElementVertices)({...a,width:i,height:o,x:n}).center,d=(0,u.rotateAroundPoint)(l,s,g),f=d.x-i/2,S=d.y-o/2;v={...t,left:f,top:S,width:i,height:o,fontSize:r}}}return S=(0,u.getAxisAlignedBoundingBox)(v.left,v.top,v.width,v.height,v.rotation),(!r||S.minX>=r.left&&S.maxX<=r.left+r.width&&S.minY>=r.top&&S.maxY<=r.top+r.height)&&(t=v),t;case te.Rotate:const x={x:e.clientX,y:e.clientY};let C,b=a.rotation;const k=(0,u.getElementVertices)(a,i,{x:s,y:l}),E=(0,u.findAngle)(x,k.c,k.d),I=(0,u.findAngle)(x,k.d,k.c);if(0===o.filter((e=>"rotation"===e.type)).length)le=0,C=(a.rotation+E-I)%360;else{le+=Math.sqrt(c**2+h**2);const e=Math.abs(le)>J/s;C=e?(a.rotation+E-I)%360:o.find((e=>"rotation"===e.type))?.value||0,e&&(le=0)}return S=(0,u.getAxisAlignedBoundingBox)(a.x,a.y,a.width,a.height,C),(!r||S.minX>=r.left&&S.maxX<=r.left+r.width&&S.minY>=r.top&&S.maxY<=r.top+r.height)&&(b=C),{top:a.y,left:a.x,width:a.width,height:a.height,rotation:b};case te.Translate:let N,R,O=a.x,M=a.y;if(0===o.filter((e=>"rotation"!==e.type)).length)re=0,se=0,N=a.x+c,R=a.y+h;else{const e=o.find((e=>"x"===e.type)),t=o.find((e=>"y"===e.type));e||(re=0),t||(se=0);const i=Math.abs(re)>J/s,n=Math.abs(se)>J/l;N=e?i?a.x+re:a.x:a.x+c,R=t?n?a.y+se:a.y:a.y+h,re=i?0:re+c,se=n?0:se+h}return S=(0,u.getAxisAlignedBoundingBox)(N,R,a.width,a.height,a.rotation),(!r||S.minX>=r.left&&S.maxX<=r.left+r.width&&S.minY>=r.top&&S.maxY<=r.top+r.height)&&(O=N,M=R),{top:M,left:O,width:a.width,height:a.height,rotation:a.rotation}}})(e,a,i,n,o,r,s),c=[];if(i.type===p.LayoutElementType.Textbox){const e=i;c.push(new(0,t.TextChangeCommand)(e.id,e.text||e.input||""))}if(c.push(new(0,t.MoveCommand)(i.id,l.left,l.top),new(0,t.ResizeCommand)(i.id,l.width,l.height),new(0,t.RotateCommand)(i.id,l.rotation)),i.type===p.LayoutElementType.Textbox){const e=i;l.fontSize&&e.fontSize!==l.fontSize&&c.push(new(0,t.FontSizeCommand)(e.id,l.fontSize))}return c},de=()=>{const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},he=.5,pe=(e,a,i,n,o,r,s)=>{const{state:c,uiDispatcher:d}=(0,l.useContext)(_),{getLayoutById:h,getReducerState:p,flattenSequence:u}=B(),[m,f]=(0,l.useState)(void 0),[g,w]=(0,l.useState)(void 0),y=h(c.layoutId);(0,l.useEffect)((()=>{if("adjustment"===o&&e?.current&&n){if(n<he)return void d(new Z({zoom:he}));if(n>c.maxZoom)return void d(new Z({zoom:c.maxZoom}));d(new Z({zoom:n}))}}),[n,d,e,o,c.maxZoom]);const S=(0,l.useCallback)(((e,t)=>{d(new Z({zoom:t}));const n=a?.current?.scrollWidth-a?.current?.clientWidth!=0,r=a?.current?.scrollHeight-a?.current?.clientHeight!=0;a.current&&i.current&&!c.scrolledMovement&&"advanced"===o&&(r&&(a.current.scrollTop=i.current.offsetTop+(a.current.scrollHeight-a.current.clientHeight)/2),n&&(a.current.scrollLeft=(i.current.offsetLeft+a.current.scrollWidth-a.current.clientWidth)/2))}),[d,a,i,c.scrolledMovement,o]);(0,l.useEffect)((()=>{c.zoom<=1&&d(new Z({scrolledMovement:!1}))}),[d,c.zoom]);const v=a?.current?.getBoundingClientRect(),x=((v?.width||1)+(v?.height||1))/2,C=(y.layoutState.layout.width+y.layoutState.layout.height)/2/x/c.zoom,b=(0,l.useMemo)((()=>{const e=c.activeModifierKeys,t=c.elementEvent,a=e.includes(ie.ControlLeft)||e.includes(ie.MetaLeft)||e.includes(ie.ControlRight)||e.includes(ie.MetaRight);if(!c.selectedElement||!t||a)return[];const i=t&&t.type===te.Translate,n=t&&t.type===te.Rotate,o=y.layoutState.elements.find((e=>e.id===c.selectedElement));return(i||n)&&o?ee(o,y.layoutState,C,s):[]}),[c.selectedElement,c.elementEvent,c.activeModifierKeys,y.layoutState,C]),k=(0,l.useCallback)((()=>{const e=de();f(e),w(p().transaction)}),[p]),E=(0,l.useCallback)((()=>{d(new Z({selectedElement:void 0}))}),[d]),I=(0,l.useCallback)((()=>{d(new Z({scrolledMovement:!0}))}),[d]),N=(0,l.useCallback)(((i,n)=>{const o=y.layoutState.elements.find((e=>e.id===c.selectedElement));if(!(c.elementEvent&&e.current&&a.current&&c.selectedElement&&o))return;a.current.hasPointerCapture(i.pointerId)||a.current.setPointerCapture(i.pointerId);const s=e.current.getBoundingClientRect(),l=new(0,t.GroupCommand)(ce(i,y.layoutState.layout,o,s,c.elementEvent,b,n));l.sequenceId=m,r(l)}),[y.layoutState.elements,y.layoutState.layout,c.elementEvent,e,c.selectedElement,a,b,r]),R=(0,l.useCallback)((e=>{d(new Z({elementEvent:e}))}),[d]),O=(0,l.useCallback)((()=>{d(new Z({elementEvent:void 0})),m&&g&&(u(m,g),f(void 0),w(void 0))}),[d,m,g,u]),M=(0,l.useCallback)(((e,a)=>{let i=c.zoom;const n=c.maxZoom,s=c.selectedElement,l=c.activeModifierKeys;if((l.includes(ie.AltLeft)||l.includes(ie.AltRight))&&(e.code===ie.Equal||e.code===ie.Minus)){const t=.05*n;e.code===ie.Equal?d(new Z({zoom:i+t<=n?i+=t:i})):d(new Z({zoom:i-t>=he?i-t:i}))}const h=y.layoutState.elements.find((e=>e.id===s));if(s&&h){if(e.code===ie.MetaLeft||e.code===ie.ControlLeft||e.code===ie.MetaRight||e.code===ie.ControlRight){const t=e.code,a=c.activeModifierKeys;if(!a.includes(t))return d(new Z({activeModifierKeys:a.concat(t)}))}if(e.code===ie.ArrowDown||e.code===ie.ArrowUp||e.code===ie.ArrowLeft||e.code===ie.ArrowRight){d(new Z({elementEvent:{type:te.Translate}}));const t=oe(e.code,h,c.units,a);r(t),d(new Z({elementEvent:void 0}))}e.code!==ie.Delete&&e.code!==ie.Backspace||"advanced"!==o||(d(new Z({selectedElement:void 0})),r(new(0,t.DeleteElementCommand)(h.id)))}}),[r,d,y.layoutState.elements,o,c.activeModifierKeys,c.maxZoom,c.selectedElement,c.units,c.zoom]),T=(0,l.useCallback)((e=>{if(e.code===ie.MetaLeft||e.code===ie.ControlLeft||e.code===ie.MetaRight||e.code===ie.ControlRight){const t=c.activeModifierKeys,a=e.code;d(new Z({activeModifierKeys:t.filter((e=>e!==a))}))}}),[d,c.activeModifierKeys]);return{guidelines:b,scale:C,zoomableElementRef:i,setElementEvent:R,handleZoom:S,handleKeyDown:M,handleKeyUp:T,handlePointerPressedBackground:E,handlePointerReleased:O,handlePointerMove:N,handleScroll:I,handleSequenceStart:k}},ue=e=>{const{x:t,y:a,cursorStyle:i,onPointerDown:n,handleClass:o,cornerRadius:r,color:s,strokeWidth:l}=e;return(0,c.jsx)("circle",{className:o,cx:t,cy:a,r:r,fill:"#ffffff",style:{cursor:i},stroke:s,strokeWidth:l,onPointerDown:n})},me=e=>{const{x:t,y:a,width:i,height:n,cursorStyle:o,onPointerDown:r,edgeHandleRadius:s,color:l,strokeWidth:d}=e;return(0,c.jsx)("rect",{x:t,y:a,width:i,height:n,rx:s,fill:"#ffffff",style:{cursor:o},stroke:l,strokeWidth:d,onPointerDown:r})},fe=e=>{const{color:t,elementHeight:a,elementWidth:i,onBeginResize:n,rotation:o,scaleFactor:r,disableX:s,disableY:h}=e,p=7.5*r,m=3*r,f=28*r,g=6*r,w=1.2*r,y=a-2*p,S=(0,l.useCallback)(((e,t,a)=>{e.stopPropagation(),n(t,a)}),[n]),v=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.West,360-o),d.ScaleAxis.West)),[S,o]),x=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.East,360-o),d.ScaleAxis.East)),[S,o]),C=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.North,360-o),d.ScaleAxis.North)),[S,o]),b=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.South,360-o),d.ScaleAxis.South)),[S,o]),k=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Northwest,d.ScaleAxis.Northwest)),[S]),E=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Northeast,d.ScaleAxis.Northeast)),[S]),I=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Southwest,d.ScaleAxis.Southwest)),[S]),N=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Northeast,d.ScaleAxis.Southeast)),[S]),R=f<=y;return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ue,{x:0,y:0,cursorStyle:"nwse-resize",onPointerDown:k,handleClass:"cornerNorthWest",cornerRadius:p,color:t,strokeWidth:w}),R?(0,c.jsx)(ue,{x:i,y:0,cursorStyle:"nesw-resize",onPointerDown:E,handleClass:"cornerNorthEast",cornerRadius:p,color:t,strokeWidth:w}):void 0,R?(0,c.jsx)(ue,{x:i,y:a,cursorStyle:"nwse-resize",onPointerDown:N,handleClass:"cornerSouthEast",cornerRadius:p,color:t,strokeWidth:w}):void 0,R?(0,c.jsx)(ue,{x:0,y:a,cursorStyle:"nesw-resize",onPointerDown:I,handleClass:"cornerSouthWest",cornerRadius:p,color:t,strokeWidth:w}):void 0,R&&!s?(0,c.jsx)(me,{x:-g/2,y:a/2-f/2,width:g,height:f,onPointerDown:v,edgeHandleRadius:m,cursorStyle:"ew-resize",color:t,strokeWidth:w}):void 0,R&&!h?(0,c.jsx)(me,{x:i/2-f/2,y:a-g/2,width:f,height:g,onPointerDown:b,edgeHandleRadius:m,cursorStyle:"ns-resize",color:t,strokeWidth:w}):void 0,s?void 0:(0,c.jsx)(me,{x:i-g/2,y:a/2-Math.min(f,.8*a)/2,width:g,height:Math.min(f,.8*a),onPointerDown:x,edgeHandleRadius:m,cursorStyle:"ew-resize",color:t,strokeWidth:w}),R&&!h?(0,c.jsx)(me,{x:i/2-f/2,y:-g/2,width:f,height:g,onPointerDown:C,edgeHandleRadius:m,cursorStyle:"ns-resize",color:t,strokeWidth:w}):void 0]})},ge=e=>{const{color:t,elementWidth:a,onBeginRotate:i,scaleFactor:n}=e,o=(0,l.useCallback)((e=>{e.stopPropagation(),i()}),[i]),r=10*n,s=1.2*n;return(0,c.jsxs)("g",{children:[(0,c.jsx)("circle",{cx:a/2,cy:-2.5*r,r:1.3*r,fill:"rgba(0, 0, 0, 0.5)",opacity:.4,style:{cursor:"ew-resize"},onPointerDown:o}),(0,c.jsx)("circle",{cx:a/2,cy:-2.5*r,r:r,fill:"#fff",style:{cursor:"ew-resize"},stroke:t,strokeWidth:s,onPointerDown:o}),(0,c.jsxs)("svg",{x:a/2-r,y:-2.5*r-r,xmlns:"http://www.w3.org/2000/svg",style:{cursor:"ew-resize"},height:2*r,viewBox:"0 0 24 24",width:2*r,fill:t,onPointerDown:o,children:[(0,c.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,c.jsx)("path",{d:"M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z"})]})]})},we=e=>{const{color:t,height:a,highlighted:i,id:n,immutable:o,onBeginMove:r,onBeginResize:s,onBeginRotate:d,onPointerEnter:h,onPointerLeave:p,onSelected:u,pressed:m,rotation:f,scaleFactor:g,selected:w,width:y,x:S,y:v,disableX:x,disableY:C}=e,b=1.2*g,k=(0,l.useCallback)((e=>{2===e.button&&(e.stopPropagation(),u(n,e)),0===e.button&&(e.stopPropagation(),!w&&u(n,e),r())}),[n,w,u,r]),E=(0,l.useCallback)((()=>{h(n)}),[n,h]),I=(0,l.useCallback)((()=>{p(n)}),[n,p]),N=o?void 0:w?m?"grabbing":"grab":"pointer",R=o?"none":"visibleFill";return(0,c.jsxs)("g",{transform:`translate(${S}, ${v}) rotate(${f} ${y/2} ${a/2})`,children:[(0,c.jsx)("rect",{className:"interactableInnerRect",width:y,height:a,stroke:w||i?t:"none",pointerEvents:R,fill:"none",strokeWidth:b,style:{cursor:N},onPointerDown:o?void 0:k,onPointerEnter:o?void 0:E,onPointerLeave:o?void 0:I}),w&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ge,{color:t,elementWidth:y,onBeginRotate:d,scaleFactor:g}),(0,c.jsx)(fe,{color:t,elementHeight:a,elementWidth:y,rotation:f,scaleFactor:g,onBeginResize:s,disableX:x,disableY:C})]})]})},ye=({primaryColor:e,containerHeight:t,containerWidth:a,customViewbox:i,editorRef:n,elementEvent:o,guidelines:r,layoutHeight:s,layoutWidth:d,targetedElements:h,scale:u,selectedElement:m,onElementEvent:f,onElementSelected:g,onSequenceStart:w})=>{const{state:y}=Q(),{getLayoutById:S}=B(),v=S(y.layoutId),[x,C]=(0,l.useState)(void 0),b=(0,l.useCallback)((e=>{C(e)}),[]),k=(0,l.useCallback)((e=>{x===e&&C(void 0)}),[x]),E=(0,l.useCallback)((()=>{w(),f({type:te.Translate})}),[f]),I=(0,l.useCallback)(((e,t)=>{w(),f({type:te.Resize,relativeAxis:e,screenAxis:t})}),[f]),N=(0,l.useCallback)((()=>{w(),f({type:te.Rotate})}),[f]),R=i||{x:0,y:0,width:d,height:s},O=u*(Math.sqrt(R.width*R.height)/1e3)*(100/Math.sqrt(t*a))*Math.sqrt((M=a/t,Math.exp(Math.abs(Math.log(M)))));var M;const T=v.layoutState.elements.findIndex((({id:e})=>e===m)),A=[...v.layoutState.elements];return T>=0&&A.push(A.splice(T,1)[0]),(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",style:{touchAction:"none",position:"absolute",maxWidth:"100%",maxHeight:"100%"},width:"100%",height:"100%",viewBox:`${R.x} ${R.y} ${R.width} ${R.height}`,overflow:"overlay",children:[(0,c.jsx)("rect",{fill:"none",stroke:"none",ref:n,width:d,height:s}),r.map((e=>e.svgNode)),A.map((t=>{const a=void 0!==m&&t.id===m,i=a&&void 0!==o,n=void 0!==x&&t.id===x;return(0,c.jsx)(we,{color:e,id:t.id,selected:a,highlighted:n,pressed:i,x:t.x,y:t.y,disableX:t.type===p.LayoutElementType.Frame,disableY:t.type===p.LayoutElementType.Textbox||t.type===p.LayoutElementType.Frame,width:t.width,height:t.height,rotation:t.rotation,immutable:t.immutable||h&&!h.includes(t.id),onSelected:g,onBeginMove:E,onBeginResize:I,onBeginRotate:N,onPointerEnter:b,onPointerLeave:k,scaleFactor:O},t.id)}))]})},Se=e=>{const{color:t,editorRef:a,zoomableElementRef:i,interactionElementRef:n,guidelines:o,isMakingAdjustments:r,viewmask:s,visibleLayoutId:d,xTranslation:h,yTranslation:p,targetedElements:u,borderRadius:m,handleContextMenu:f,handleKeyDown:g,handleKeyUp:w,handlePointerMove:y,handlePointerPressedBackground:S,handlePointerReleased:v,handleScroll:x,onSequenceStart:C,setElementEvent:b,onElementSelected:k}=e,{getLayoutById:E}=B(),I=E(d),N=I.layoutState,{state:R}=Q(),O=(0,l.useCallback)((e=>{if(s){const t={left:s.x,top:s.y,width:s.width,height:s.height,panelId:"",rotation:0};return g(e,t)}return g(e)}),[g,s]),M=(0,l.useCallback)((e=>{if(s){const t={left:s.x,top:s.y,width:s.width,height:s.height,panelId:"",rotation:0};return y(e,t)}return y(e)}),[y,s]);return(0,c.jsx)("div",{style:{justifyContent:"center",position:"relative",height:"100%",width:"100%",scrollbarWidth:"none",outline:"none"},onContextMenu:f,onKeyDown:O,onKeyUp:w,onPointerDown:S,onPointerMoveCapture:M,onPointerUp:v,onWheelCapture:x,ref:n,tabIndex:-1,children:(0,c.jsxs)("div",{ref:i,style:{height:"100%",transform:`scale(${R.zoom}) translate(${h}px, ${p}px)`,display:"grid",filter:"drop-shadow(rgba(0, 0, 0, 0.2) 0px 0px 6px)"},children:[e.children,I.getComponentWithProps({height:r?"100%":"auto",maxHeight:"100%",maxWidth:"100%",position:"absolute",viewmask:s,width:r?"100%":"auto",borderRadius:m}),(0,c.jsx)(ye,{primaryColor:t,containerHeight:i.current?.offsetHeight||1024,containerWidth:i.current?.offsetWidth||1024,editorRef:a,elementEvent:R.elementEvent,guidelines:o,layoutHeight:N.layout.height,layoutWidth:N.layout.width,onElementEvent:b,onSequenceStart:C,onElementSelected:k,scale:10/R.zoom,selectedElement:R.selectedElement,targetedElements:u})]})})},ve=({color:e,borderRadius:a,guidelineColor:i,handleContextMenu:n,onElementSelected:o})=>{const{commandDispatcher:r,getLayoutById:s}=B(),{state:d,uiDispatcher:h}=Q(),u=(0,l.useRef)(null),m=(0,l.useRef)(null),f=(0,l.useRef)(null),{guidelines:g,handleKeyDown:w,handleKeyUp:y,handlePointerMove:S,handlePointerPressedBackground:v,handlePointerReleased:x,handleScroll:C,handleSequenceStart:b,setElementEvent:k}=pe(u,m,f,void 0,"advanced",r,i),E=(0,l.useCallback)(((e,a)=>{const i=s(d.layoutId).layoutState.elements.find((t=>t.id===e));if(e&&i&&i.type===p.LayoutElementType.Textbox){const a=i.algorithm;(!a||a===p.TextAlgorithm.Autosize)&&r(new(0,t.FontAlgorithmCommand)(e,p.TextAlgorithm.Traditional))}o&&o(e,a),h(new Z({selectedElement:e}))}),[r,s,d.layoutId,h]);return(0,c.jsx)(Se,{color:e,editorRef:u,interactionElementRef:m,zoomableElementRef:f,guidelines:g,visibleLayoutId:d.layoutId,xTranslation:0,yTranslation:0,borderRadius:a,handleContextMenu:n,handleKeyDown:w,handleKeyUp:y,handlePointerMove:S,handlePointerPressedBackground:v,handlePointerReleased:x,handleScroll:C,onSequenceStart:b,setElementEvent:k,onElementSelected:E})};function xe(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Ce=new class{constructor(){xe(this,"server",void 0),xe(this,"cache",new Map),xe(this,"materialCache",new Map),xe(this,"loadImageAsFileInfo",(async e=>{const t=await e.arrayBuffer(),a=await(0,g.getAttributesFromArrayBuffer)(t);return{name:e.name.substring(e.name.lastIndexOf("/")+1),blob:((e,t)=>{let a=atob(e.split(",")[1]),i=[];for(let e=0;e<a.length;e++)i.push(a.charCodeAt(e));return new Blob([new Uint8Array(i)],{type:t})})(a.dataUrl,e.type)}})),this.server=q}async getLocalOrFromServer(e){if(this.cache.has(e))return this.cache.get(e);const t=(async()=>(await q.execute("getAssetByKeyV2",{assetKey:e.replace(/\//g,"_")})).body)();return this.cache.set(e,t),t}async getMaterialLocalOrFromServer(e){if(this.materialCache.has(e))return this.materialCache.get(e);const t=(async()=>(await q.execute("getMaterialV2",{id:e})).body)();return this.materialCache.set(e,t),t}async uploadAssetWithProgress(e,t,a,i,n,o){const r=await this.dispatchCreateAssetRequest(e,t,n,o);var s=new XMLHttpRequest;return s.open("PUT",r.assetResponse.uploadUrl,!0),s.setRequestHeader("Content-Type",r.mimeType),s.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),s.upload.onprogress=e=>{e.lengthComputable&&a(100*e.loaded/e.total)},s.onload=()=>{const e=r.assetResponse.asset;i(e)},s.onerror=()=>{console.warn("Asset upload failed")},s.send(e.blob),r.assetResponse.asset}async dispatchCreateAssetRequest(e,t,a,i){const n=e.blob.type?e.blob.type:this.guessMIME(e.name);return{assetResponse:(await this.server.execute("createAsset",{assetDetails:{name:e.name,type:t,mimeType:n,storageOwnerId:i,userAnonymous:!0}},a)).body,mimeType:n}}guessMIME(e){const t=e.split(".").pop();switch(t){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new Error("Unexpected mimetype: "+t)}}};class be{get(e){return localStorage.getItem(e)||void 0}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}class ke{constructor(){var e,t,a;e=this,t="storage",a=new Map,t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}get(e){return this.storage.get(e)||void 0}set(e,t){this.storage.set(e,t)}remove(e){this.storage.delete(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}const Ee=(()=>{try{return localStorage?new be:new ke}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new ke}})(),Ie=n.gql`
1
+ var e=require("papyrus/build/main/CommandContext"),t=require("papyrus/build/main/command"),a=(require("papyrus/build/main/Elements/factory"),require("spiff-preview"),require("papyrus/build/main/font")),i=require("swagger-client"),n=require("@apollo/client"),o=require("@apollo/client/link/context"),r=require("@apollo/client/link/error"),s=require("cross-fetch"),l=require("react"),c=require("react/jsx-runtime"),d=require("papyrus/build/main/types"),h=require("lodash.isequal"),p=require("papyrus/build/main/LayoutsState/types"),u=require("papyrus/build/main/math"),m=require("papyrus/build/main/text/algorithm/traditional"),f=require("papyrus/build/main/text/shared"),g=require("papyrus/build/main/image"),w=require("canvg"),y=require("papyrus/build/main/generation/Workflow"),S=require("lodash.clonedeep"),v=require("papyrus/build/main/module/resolver"),x=require("lodash.debounce"),C=require("papyrus/build/main/frame"),b=require("papyrus/build/main/illustration"),k=require("papyrus/build/main/LayoutsState"),E=require("qrcode"),I=require("papyrus/build/main/crossplatform"),N=require("react-dom/server"),R=require("papyrus/build/main/Elements/Patchwork"),O=require("papyrus/build/main/text/algorithm/autosize"),M=require("papyrus/build/main/generation");function T(e,t,a,i){Object.defineProperty(e,t,{get:a,set:i,enumerable:!0,configurable:!0})}function A(e){return e&&e.__esModule?e.default:e}function L(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}T(module.exports,"Client",(()=>Ut)),T(module.exports,"CommandContext",(()=>$eb7869949b641a40$re_export$CommandContext)),T(module.exports,"spiffCoreConfiguration",(()=>V)),T(module.exports,"PromiseQueue",(()=>He)),T(module.exports,"QueueablePromise",(()=>Ge)),T(module.exports,"MockWorkflowManager",(()=>Ft)),T(module.exports,"InformationMessageType",(()=>Ct)),T(module.exports,"assetService",(()=>Ce)),T(module.exports,"optionService",(()=>P)),T(module.exports,"server",(()=>q)),T(module.exports,"persistenceService",(()=>Ee)),T(module.exports,"graphQlManager",(()=>W)),T(module.exports,"toast",(()=>gt)),T(module.exports,"FrameService",(()=>Ze)),T(module.exports,"frameStepService",(()=>rt)),T(module.exports,"modelStepService",(()=>lt)),T(module.exports,"materialStepService",(()=>st)),T(module.exports,"patchworkStepService",(()=>pt)),T(module.exports,"shapeStepService",(()=>mt)),T(module.exports,"questionStepService",(()=>Pe)),T(module.exports,"digitalContentStepService",(()=>ot)),T(module.exports,"moduleStepService",(()=>ct)),T(module.exports,"pictureStepService",(()=>ut)),T(module.exports,"textStepService",(()=>vt)),T(module.exports,"illustrationStepService",(()=>Je)),T(module.exports,"svgObjectURL",(()=>Qe)),T(module.exports,"generate",(()=>de)),T(module.exports,"CreateElementCommand",(()=>$eb7869949b641a40$re_export$CreateElementCommand)),T(module.exports,"TextChangeCommand",(()=>$eb7869949b641a40$re_export$TextChangeCommand)),T(module.exports,"FontAlignmentCommand",(()=>$eb7869949b641a40$re_export$FontAlignmentCommand)),T(module.exports,"FontColorCommand",(()=>$eb7869949b641a40$re_export$FontColorCommand)),T(module.exports,"LayoutElementFactory",(()=>$eb7869949b641a40$re_export$LayoutElementFactory)),T(module.exports,"minZoom",(()=>he)),T(module.exports,"AdvancedEditor",(()=>ve)),T(module.exports,"EditorCore",(()=>Se)),T(module.exports,"useLayouts",(()=>B)),T(module.exports,"useEditorState",(()=>Q)),T(module.exports,"useEditorInteraction",(()=>pe)),T(module.exports,"commandReducer",(()=>X)),T(module.exports,"getDefaultState",(()=>H)),T(module.exports,"CommandContextContext",(()=>$)),T(module.exports,"AdvancedEditorStateProvider",(()=>Y)),T(module.exports,"AdvancedEditorContext",(()=>_)),T(module.exports,"UICommand",(()=>Z)),T(module.exports,"EditorSubMenu",(()=>K)),T(module.exports,"gatherVaryingStepAspects",(()=>ze)),T(module.exports,"SpiffCommerce3DPreviewService",(()=>$eb7869949b641a40$re_export$SpiffCommerce3DPreviewService)),T(module.exports,"ProductCameraRig",(()=>$eb7869949b641a40$re_export$ProductCameraRig));const P=new class{constructor(){L(this,"cache",new Map),L(this,"getDisplayImageSource",(e=>{if(e){const t=e.displayImage?.links.find((e=>"cdn"===e.rel));if(t)return t.href}})),L(this,"getSelectedVariant",((e,t)=>{if(e&&0!==t.length)return e.variants.find((e=>e.id===t[0]))})),L(this,"getSelectedVariants",((e,t)=>e?.variants.filter((e=>t.includes(e.id)))||[]))}async cacheRequiredOptions(e){const t=e.steps.map((e=>e.optionId)).filter((e=>void 0!==e)),i=e.steps.map((e=>e.data.colourOptionId)).filter((e=>void 0!==e)),n=[...new Set([...t,...i])].map((async e=>{const t=await P.getLocalOrFromServer(q,e);"Font"===t.data.type&&t.data.variants.forEach((async e=>{if(e.assetKey){const t=(await Ce.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel))?.href;t&&await(0,a.loadFontFromExternalUrl)(t)}}))}));await Promise.allSettled([...n])}async getLocalOrFromServer(e,t){if(this.cache.has(t))return this.cache.get(t);const a=(await e.execute("getOptionV2",{id:t})).body;return this.cache.set(t,a),a}getLocalOrUndefined(e){if(e)return this.cache.get(e)}async getAssetTileImageForVariant(e){if(e.thumbnailKey){const t=await Ce.getLocalOrFromServer(e.thumbnailKey),a=t.links.find((e=>"thumbnail"===e.rel)),i=t.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}const t=e.assetKey;if(t){const e=await Ce.getLocalOrFromServer(t),a=e.links.find((e=>"thumbnail"===e.rel)),i=e.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}return e.materialId?e.materialId:""}getDefaultVariant(e){const t=e.variants;return 1===t.length?t[0]:void 0!==e.defaultVariant?t.find((t=>t.id===e.defaultVariant)):void 0}};function D(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const V=new class{constructor(){D(this,"defaultServerUrl","https://api.spiff.com.au"),D(this,"defaultServicesApiUrl","https://services.spiff.com.au"),D(this,"serverUrl",void 0),D(this,"servicesApiUrl",void 0),D(this,"serverUrlCallbacks",void 0),this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}setServerUrl(e){this.serverUrl=e,this.serverUrlCallbacks.forEach((e=>e()))}setServicesApiUrl(e){this.servicesApiUrl=e}addServerUrlCallback(e){this.serverUrlCallbacks.push(e)}};function z(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}let U;const F=e=>{U=e},j=async()=>({transactionOwnerId:U});const q=new class{constructor(){z(this,"client",void 0),z(this,"uncachedOperations",[]),V.addServerUrlCallback((async()=>{this.client=void 0,this.client=await this.constructClient()}))}setUncachedOperations(e){this.uncachedOperations=e}async execute(e,t){const a=this.uncachedOperations.includes(e)?e+"_private":e;return new Promise(((e,i)=>{this.getClient().then((n=>{n.execute({operationId:a,parameters:t}).then((t=>e(t))).catch((e=>{e.response&&e.response.status&&e.response.status>=500||(!e.response&&i(new Error(e)),e.response&&i(new Error(`${e.response.status} ${e.response.url}`)))}))})).catch((e=>{i(e)}))}))}async syncAuth(e){const t=await j();if(t.bearer?e.authorizations={...e.authorizations,OAuth2:{token:{access_token:t.bearer,token_type:"Bearer"}}}:e.authorizations={...e.authorizations,OAuth2:{token:{access_token:"",token_type:"Bearer"}}},t.activeIntegration)e.authorizations={...e.authorizations,ActiveIntegration:t.activeIntegration};else{const t={...e.authorizations};delete t.ActiveIntegration,e.authorizations=t}if(t.partnerId)e.authorizations={...e.authorizations,PartnerId:t.partnerId};else{const t={...e.authorizations};delete t.PartnerId,e.authorizations=t}}async getClient(){return this.client||(this.client=await this.constructClient()),this.syncAuth(this.client),Promise.resolve(this.client)}async constructClient(){const e=await j(),t=V.getServerUrl()+"/v2/api-docs";return await A(i)(t,{authorizations:{OAuth2:{token:{access_token:e.bearer,token_type:"Bearer"}},PartnerId:e.partnerId}})}};const W=new class{constructor(){z(this,"shadowGraphqlClient",void 0),this.shadowGraphqlClient=this.constructShadowGraphqlClient(),V.addServerUrlCallback((()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()}))}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const e=(0,n.createHttpLink)({uri:`${V.getServerUrl()}/graphql`,fetch:A(s)}),t=(0,o.setContext)((async(e,{headers:t})=>{const a=t||{},i=await j();return i.bearer&&(a.Authorization=`Bearer ${i.bearer}`),i.partnerId&&(a.partnerId=i.partnerId),i.activeIntegration&&(a.activeIntegration=i.activeIntegration),i.transactionOwnerId&&(a.transactionOwnerId=i.transactionOwnerId),{headers:a}})),a=(0,r.onError)((({operation:e,graphQLErrors:t,networkError:a})=>{(t||[]).forEach((({message:t,locations:a,path:i})=>{console.log("[GraphQL Operation Error]"),console.log("Name:"+e.operationName),console.log("Query:"+JSON.stringify(e.query)),console.log(`Message: ${t}, Location: ${JSON.stringify(a,null,2)}, Path: ${i}`),console.log("Variables:"+JSON.stringify(e.variables))})),a&&console.log("GraphQL Network error")}));const i=new(0,n.InMemoryCache)({typePolicies:{Transaction:{fields:{transactionOwnerId:{read:(e=null)=>e},customLogoLink:{read:(e=null)=>e},workflowFooterLogoLink:{read:(e=null)=>e},workflowState:{read:(e=null)=>e},bulkSourceUrl:{read:(e=null)=>e}}}}});return new(0,n.ApolloClient)({link:(0,n.from)([a,t,e]),cache:i,name:"Core"})}},$=(0,l.createContext)(new(0,e.CommandContext)),B=()=>{const e=(0,l.useContext)($);(0,l.useEffect)((()=>{e.registerStateCallback((()=>{a(new Date)}))}),[e]);const[t,a]=(0,l.useState)(new Date);return{commandDispatcher:t=>{e.apply(t)},getLayoutById:t=>e.getLayoutById(t),getAllLayouts:()=>e.getAllLayouts(),getReducerState:()=>{const t=e.getState();return t||{transaction:{layouts:{},serializableWorkflow:{steps:[]}}}},lastUpdated:t,flattenSequence:(t,a)=>{e.flattenSequence(t,a)}}};let K;var G;(G=K||(K={})).None="None",G.FrameAdjustment="FrameAdjustment",G.FinalizeDesign="FinalizeDesign";const H=(e,t)=>({layoutId:e()[0].layoutState.layout.id,selectedElement:void 0,zoom:t,maxZoom:5,units:d.UnitOfMeasurement.Pixel,subMenu:K.None,activeModifierKeys:[],metaPressed:!1,elementEvent:void 0,scrolledMovement:!1}),X=(e,t)=>A(h)(e,t.apply(e))?e:t.apply(e),_=(0,l.createContext)({}),Y=e=>{const{getAllLayouts:t}=B(),[a,i]=(0,l.useReducer)(X,H(t,e.defaultZoom||1)),n=(0,l.useMemo)((()=>({state:a,uiDispatcher:i})),[a,i]);return(0,c.jsx)(_.Provider,{value:n,children:e.children})};class Z{constructor(e){var t,a,i;i=void 0,(a="changes")in(t=this)?Object.defineProperty(t,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[a]=i,this.changes=e}apply(e){return{...e,...this.changes}}}const Q=()=>(0,l.useContext)(_),J=7*window.devicePixelRatio,ee=(e,t,a,i)=>{const n=t.layout.width,o=t.layout.height,r=t.elements.filter((t=>t.id!==e.id&&!t.immutable&&!t.productOverlay)),s=r.map((e=>(0,u.getAxisAlignedBoundingBox)(e.x,e.y,e.width,e.height,e.rotation))),l=[],d=new Set;s.forEach((e=>d.add(e.minX))),s.forEach((e=>d.add(e.maxX))),[0,n/2,n].forEach((e=>d.add(e)));const h=new Set;s.forEach((e=>h.add(e.minY))),s.forEach((e=>h.add(e.maxY))),[0,o/2,o].forEach((e=>h.add(e)));const p=r.map((e=>e.y));for(let e=-315;e<=315;e+=45)p.push(e);const m=(0,u.getAxisAlignedBoundingBox)(e.x,e.y,e.width,e.height,e.rotation),f=[{value:m.minX,anchor:-1},{value:m.minX+(m.maxX-m.minX)/2,anchor:0},{value:m.minX+(m.maxX-m.minX),anchor:1}],g=[{value:m.minY,anchor:-1},{value:m.minY+(m.maxY-m.minY)/2,anchor:0},{value:m.minY+(m.maxY-m.minY),anchor:1}],w=[{value:e.rotation,anchor:0}],y=(e,t,i,r)=>{const s=[];return t.forEach((t=>{const l=i.find((e=>(0,u.isCloseToValue)(t,e.value,2*a))),[d,h]=((e,t)=>[{x:"x"===e?t:0,y:"x"===e?0:t},{x:"x"===e?t:n,y:"x"===e?o:t}])(e,t),p="rotation"===e?null:(0,c.jsx)("line",{x1:d.x,y1:d.y,x2:h.x,y2:h.y,stroke:r||"#D61B5C",strokeDasharray:5*a,strokeWidth:1.2*a,overflow:"overlay"},`${e}-${t}-${d.x}-${d.y}-${h.x}-${h.y}`);void 0!==l&&s.push({type:e,value:t,anchorPoint:l.anchor,svgNode:p,guidelineCoordinates:[d,h]})})),s};return l.push(...y("x",Array.from(d),f,i)),l.push(...y("y",Array.from(h),g,i)),l.push(...y("rotation",p,w,i)),l};let te;var ae;let ie;var ne;(ae=te||(te={})).Translate="Translate",ae.Rotate="Rotate",ae.Resize="Resize",(ne=ie||(ie={})).ControlLeft="ControlLeft",ne.ControlRight="ControlRight",ne.Equal="Equal",ne.MetaLeft="MetaLeft",ne.MetaRight="MetaRight",ne.Minus="Minus",ne.ArrowLeft="ArrowLeft",ne.ArrowRight="ArrowRight",ne.ArrowUp="ArrowUp",ne.ArrowDown="ArrowDown",ne.AltLeft="AltLeft",ne.AltRight="AltRight",ne.Delete="Delete",ne.Backspace="Backspace";const oe=(e,a,i,n)=>{const o=()=>{switch(i){case d.UnitOfMeasurement.Pixel:return 1;case d.UnitOfMeasurement.Millimeter:return u.mmPerPixel;case d.UnitOfMeasurement.Centimeter:return u.cmPerPixel;default:throw new Error("Unknown unit of measurement")}};let r=a.x,s=a.y,l=a.x,c=a.y;switch(e){case ie.ArrowLeft:l=a.x-1/o();break;case ie.ArrowUp:c=a.y-1/o();break;case ie.ArrowRight:l=a.x+1/o();break;case ie.ArrowDown:c=a.y+1/o();break;default:throw new Error("Unhandled element interaction!")}const h=(0,u.getAxisAlignedBoundingBox)(l,c,a.width,a.height,a.rotation);return(!n||h.minX>=n.left&&h.maxX<=n.left+n.width&&h.minY>=n.top&&h.maxY<=n.top+n.height)&&(r=l,s=c),new(0,t.MoveCommand)(a.id,r,s)};var re=0,se=0,le=0;const ce=(e,a,i,n,o,r,s)=>{const l=((e,t,a,i,n,o,r)=>{const s=i.width/t.width,l=i.height/t.height,c=e.movementX/s,h=e.movementY/l,g=a.rotation*Math.PI/180,w=Math.sin(g),y=Math.cos(g);let S;switch(n.type){case te.Resize:let t={top:a.y,left:a.x,width:a.width,height:a.height,rotation:a.rotation,fontSize:a.fontSize},v=t;switch(n.screenAxis){case d.ScaleAxis.North:{const e=-c*w+h*y,i=a.y+e,n=a.height-e,o=(0,u.getElementVertices)({...a}).center,r=(0,u.getElementVertices)({...a,y:i,height:n}).center,s=(0,u.rotateAroundPoint)(r,o,g),l=s.x-a.width/2,d=s.y-n/2;v={...t,left:l,top:d,height:n}}break;case d.ScaleAxis.East:{const e=c*y+h*w,i=a.width+e;let n=a.height;if(a.type===p.LayoutElementType.Textbox){const e=a;n=(0,m.calculateTextboxLines)(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const o=(0,u.getElementVertices)({...a}).center,r=(0,u.getElementVertices)({...a,width:i,height:n}).center,s=(0,u.rotateAroundPoint)(r,o,g),l=s.x-i/2,d=s.y-n/2;v={...t,left:l,top:d,width:i,height:n}}break;case d.ScaleAxis.West:{const e=c*y+h*w,i=a.x+e,n=a.width-e;let o=a.height;if(a.type===p.LayoutElementType.Textbox){const e=a;o=(0,m.calculateTextboxLines)(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const r=(0,u.getElementVertices)({...a}).center,s=(0,u.getElementVertices)({...a,width:n,height:o,x:i}).center,l=(0,u.rotateAroundPoint)(s,r,g),d=l.x-n/2,f=l.y-o/2;v={...t,left:d,top:f,width:n,height:o}}break;case d.ScaleAxis.South:{const e=-c*w+h*y,i=a.height+e,n=(0,u.getElementVertices)({...a}).center,o=(0,u.getElementVertices)({...a,height:i}).center,r=(0,u.rotateAroundPoint)(o,n,g),s=r.x-a.width/2,l=r.y-i/2;v={...t,left:s,top:l,height:i}}break;case d.ScaleAxis.Northeast:{const e=c*y+h*w,i=a.width+e;let n=a.height+e,o=a.y-e,r=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;r=t.fontSize+e/8,n=(0,m.calculateTextboxLines)(r,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||f.defaultLineHeightFactor;o=a.y-e*i/8}const s=(0,u.getElementVertices)({...a}).center,l=(0,u.getElementVertices)({...a,width:i,height:n,y:o}).center,d=(0,u.rotateAroundPoint)(l,s,g),S=d.x-i/2,x=d.y-n/2;v={...t,left:S,top:x,width:i,height:n,fontSize:r}}break;case d.ScaleAxis.Northwest:{const e=-c*y+-h*w,i=a.x-e,n=a.width+e;let o=a.y-e,r=a.height+e,s=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;s=t.fontSize+e/8,r=(0,m.calculateTextboxLines)(s,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||f.defaultLineHeightFactor;o=a.y-e*i/8}const l=(0,u.getElementVertices)({...a}).center,d=(0,u.getElementVertices)({...a,x:i,y:o,width:n,height:r}).center,S=(0,u.rotateAroundPoint)(d,l,g),x=S.x-n/2,C=S.y-r/2;v={...t,left:x,top:C,width:n,height:r,fontSize:s}}break;case d.ScaleAxis.Southeast:{const e=c*y+h*w,i=a.width+e;let n=a.height+e,o=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;o=t.fontSize+e/8,n=(0,m.calculateTextboxLines)(o,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const r=(0,u.getElementVertices)({...a}).center,s=(0,u.getElementVertices)({...a,width:i,height:n}).center,l=(0,u.rotateAroundPoint)(s,r,g),d=l.x-i/2,f=l.y-n/2;v={...t,left:d,top:f,width:i,height:n,fontSize:o}}break;case d.ScaleAxis.Southwest:{const e=-c*y+-h*w,i=a.width+e;let n=a.x-e,o=a.height+e,r=a.fontSize;if(a.type===p.LayoutElementType.Textbox){const t=a;r=t.fontSize+e/8,o=(0,m.calculateTextboxLines)(r,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const s=(0,u.getElementVertices)({...a}).center,l=(0,u.getElementVertices)({...a,width:i,height:o,x:n}).center,d=(0,u.rotateAroundPoint)(l,s,g),f=d.x-i/2,S=d.y-o/2;v={...t,left:f,top:S,width:i,height:o,fontSize:r}}}return S=(0,u.getAxisAlignedBoundingBox)(v.left,v.top,v.width,v.height,v.rotation),(!r||S.minX>=r.left&&S.maxX<=r.left+r.width&&S.minY>=r.top&&S.maxY<=r.top+r.height)&&(t=v),t;case te.Rotate:const x={x:e.clientX,y:e.clientY};let C,b=a.rotation;const k=(0,u.getElementVertices)(a,i,{x:s,y:l}),E=(0,u.findAngle)(x,k.c,k.d),I=(0,u.findAngle)(x,k.d,k.c);if(0===o.filter((e=>"rotation"===e.type)).length)le=0,C=(a.rotation+E-I)%360;else{le+=Math.sqrt(c**2+h**2);const e=Math.abs(le)>J/s;C=e?(a.rotation+E-I)%360:o.find((e=>"rotation"===e.type))?.value||0,e&&(le=0)}return S=(0,u.getAxisAlignedBoundingBox)(a.x,a.y,a.width,a.height,C),(!r||S.minX>=r.left&&S.maxX<=r.left+r.width&&S.minY>=r.top&&S.maxY<=r.top+r.height)&&(b=C),{top:a.y,left:a.x,width:a.width,height:a.height,rotation:b};case te.Translate:let N,R,O=a.x,M=a.y;if(0===o.filter((e=>"rotation"!==e.type)).length)re=0,se=0,N=a.x+c,R=a.y+h;else{const e=o.find((e=>"x"===e.type)),t=o.find((e=>"y"===e.type));e||(re=0),t||(se=0);const i=Math.abs(re)>J/s,n=Math.abs(se)>J/l;N=e?i?a.x+re:a.x:a.x+c,R=t?n?a.y+se:a.y:a.y+h,re=i?0:re+c,se=n?0:se+h}return S=(0,u.getAxisAlignedBoundingBox)(N,R,a.width,a.height,a.rotation),(!r||S.minX>=r.left&&S.maxX<=r.left+r.width&&S.minY>=r.top&&S.maxY<=r.top+r.height)&&(O=N,M=R),{top:M,left:O,width:a.width,height:a.height,rotation:a.rotation}}})(e,a,i,n,o,r,s),c=[];if(i.type===p.LayoutElementType.Textbox){const e=i;c.push(new(0,t.TextChangeCommand)(e.id,e.text||e.input||""))}if(c.push(new(0,t.MoveCommand)(i.id,l.left,l.top),new(0,t.ResizeCommand)(i.id,l.width,l.height),new(0,t.RotateCommand)(i.id,l.rotation)),i.type===p.LayoutElementType.Textbox){const e=i;l.fontSize&&e.fontSize!==l.fontSize&&c.push(new(0,t.FontSizeCommand)(e.id,l.fontSize))}return c},de=()=>{const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},he=.5,pe=(e,a,i,n,o,r,s)=>{const{state:c,uiDispatcher:d}=(0,l.useContext)(_),{getLayoutById:h,getReducerState:p,flattenSequence:u}=B(),[m,f]=(0,l.useState)(void 0),[g,w]=(0,l.useState)(void 0),y=h(c.layoutId);(0,l.useEffect)((()=>{if("adjustment"===o&&e?.current&&n){if(n<he)return void d(new Z({zoom:he}));if(n>c.maxZoom)return void d(new Z({zoom:c.maxZoom}));d(new Z({zoom:n}))}}),[n,d,e,o,c.maxZoom]);const S=(0,l.useCallback)(((e,t)=>{d(new Z({zoom:t}));const n=a?.current?.scrollWidth-a?.current?.clientWidth!=0,r=a?.current?.scrollHeight-a?.current?.clientHeight!=0;a.current&&i.current&&!c.scrolledMovement&&"advanced"===o&&(r&&(a.current.scrollTop=i.current.offsetTop+(a.current.scrollHeight-a.current.clientHeight)/2),n&&(a.current.scrollLeft=(i.current.offsetLeft+a.current.scrollWidth-a.current.clientWidth)/2))}),[d,a,i,c.scrolledMovement,o]);(0,l.useEffect)((()=>{c.zoom<=1&&d(new Z({scrolledMovement:!1}))}),[d,c.zoom]);const v=a?.current?.getBoundingClientRect(),x=((v?.width||1)+(v?.height||1))/2,C=(y.layoutState.layout.width+y.layoutState.layout.height)/2/x/c.zoom,b=(0,l.useMemo)((()=>{const e=c.activeModifierKeys,t=c.elementEvent,a=e.includes(ie.ControlLeft)||e.includes(ie.MetaLeft)||e.includes(ie.ControlRight)||e.includes(ie.MetaRight);if(!c.selectedElement||!t||a)return[];const i=t&&t.type===te.Translate,n=t&&t.type===te.Rotate,o=y.layoutState.elements.find((e=>e.id===c.selectedElement));return(i||n)&&o?ee(o,y.layoutState,C,s):[]}),[c.selectedElement,c.elementEvent,c.activeModifierKeys,y.layoutState,C]),k=(0,l.useCallback)((()=>{const e=de();f(e),w(p().transaction)}),[p]),E=(0,l.useCallback)((()=>{d(new Z({selectedElement:void 0}))}),[d]),I=(0,l.useCallback)((()=>{d(new Z({scrolledMovement:!0}))}),[d]),N=(0,l.useCallback)(((i,n)=>{const o=y.layoutState.elements.find((e=>e.id===c.selectedElement));if(!(c.elementEvent&&e.current&&a.current&&c.selectedElement&&o))return;a.current.hasPointerCapture(i.pointerId)||a.current.setPointerCapture(i.pointerId);const s=e.current.getBoundingClientRect(),l=new(0,t.GroupCommand)(ce(i,y.layoutState.layout,o,s,c.elementEvent,b,n));l.sequenceId=m,r(l)}),[y.layoutState.elements,y.layoutState.layout,c.elementEvent,e,c.selectedElement,a,b,r]),R=(0,l.useCallback)((e=>{d(new Z({elementEvent:e}))}),[d]),O=(0,l.useCallback)((()=>{d(new Z({elementEvent:void 0})),m&&g&&(u(m,g),f(void 0),w(void 0))}),[d,m,g,u]),M=(0,l.useCallback)(((e,a)=>{let i=c.zoom;const n=c.maxZoom,s=c.selectedElement,l=c.activeModifierKeys;if((l.includes(ie.AltLeft)||l.includes(ie.AltRight))&&(e.code===ie.Equal||e.code===ie.Minus)){const t=.05*n;e.code===ie.Equal?d(new Z({zoom:i+t<=n?i+=t:i})):d(new Z({zoom:i-t>=he?i-t:i}))}const h=y.layoutState.elements.find((e=>e.id===s));if(s&&h){if(e.code===ie.MetaLeft||e.code===ie.ControlLeft||e.code===ie.MetaRight||e.code===ie.ControlRight){const t=e.code,a=c.activeModifierKeys;if(!a.includes(t))return d(new Z({activeModifierKeys:a.concat(t)}))}if(e.code===ie.ArrowDown||e.code===ie.ArrowUp||e.code===ie.ArrowLeft||e.code===ie.ArrowRight){d(new Z({elementEvent:{type:te.Translate}}));const t=oe(e.code,h,c.units,a);r(t),d(new Z({elementEvent:void 0}))}e.code!==ie.Delete&&e.code!==ie.Backspace||"advanced"!==o||(d(new Z({selectedElement:void 0})),r(new(0,t.DeleteElementCommand)(h.id)))}}),[r,d,y.layoutState.elements,o,c.activeModifierKeys,c.maxZoom,c.selectedElement,c.units,c.zoom]),T=(0,l.useCallback)((e=>{if(e.code===ie.MetaLeft||e.code===ie.ControlLeft||e.code===ie.MetaRight||e.code===ie.ControlRight){const t=c.activeModifierKeys,a=e.code;d(new Z({activeModifierKeys:t.filter((e=>e!==a))}))}}),[d,c.activeModifierKeys]);return{guidelines:b,scale:C,zoomableElementRef:i,setElementEvent:R,handleZoom:S,handleKeyDown:M,handleKeyUp:T,handlePointerPressedBackground:E,handlePointerReleased:O,handlePointerMove:N,handleScroll:I,handleSequenceStart:k}},ue=e=>{const{x:t,y:a,cursorStyle:i,onPointerDown:n,handleClass:o,cornerRadius:r,color:s,strokeWidth:l}=e;return(0,c.jsx)("circle",{className:o,cx:t,cy:a,r:r,fill:"#ffffff",style:{cursor:i},stroke:s,strokeWidth:l,onPointerDown:n})},me=e=>{const{x:t,y:a,width:i,height:n,cursorStyle:o,onPointerDown:r,edgeHandleRadius:s,color:l,strokeWidth:d}=e;return(0,c.jsx)("rect",{x:t,y:a,width:i,height:n,rx:s,fill:"#ffffff",style:{cursor:o},stroke:l,strokeWidth:d,onPointerDown:r})},fe=e=>{const{color:t,elementHeight:a,elementWidth:i,onBeginResize:n,rotation:o,scaleFactor:r,disableX:s,disableY:h}=e,p=7.5*r,m=3*r,f=28*r,g=6*r,w=1.2*r,y=a-2*p,S=(0,l.useCallback)(((e,t,a)=>{e.stopPropagation(),n(t,a)}),[n]),v=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.West,360-o),d.ScaleAxis.West)),[S,o]),x=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.East,360-o),d.ScaleAxis.East)),[S,o]),C=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.North,360-o),d.ScaleAxis.North)),[S,o]),b=(0,l.useCallback)((e=>S(e,(0,u.currentDirection)(d.ScaleAxis.South,360-o),d.ScaleAxis.South)),[S,o]),k=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Northwest,d.ScaleAxis.Northwest)),[S]),E=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Northeast,d.ScaleAxis.Northeast)),[S]),I=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Southwest,d.ScaleAxis.Southwest)),[S]),N=(0,l.useCallback)((e=>S(e,d.ScaleAxis.Northeast,d.ScaleAxis.Southeast)),[S]),R=f<=y;return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ue,{x:0,y:0,cursorStyle:"nwse-resize",onPointerDown:k,handleClass:"cornerNorthWest",cornerRadius:p,color:t,strokeWidth:w}),R?(0,c.jsx)(ue,{x:i,y:0,cursorStyle:"nesw-resize",onPointerDown:E,handleClass:"cornerNorthEast",cornerRadius:p,color:t,strokeWidth:w}):void 0,R?(0,c.jsx)(ue,{x:i,y:a,cursorStyle:"nwse-resize",onPointerDown:N,handleClass:"cornerSouthEast",cornerRadius:p,color:t,strokeWidth:w}):void 0,R?(0,c.jsx)(ue,{x:0,y:a,cursorStyle:"nesw-resize",onPointerDown:I,handleClass:"cornerSouthWest",cornerRadius:p,color:t,strokeWidth:w}):void 0,R&&!s?(0,c.jsx)(me,{x:-g/2,y:a/2-f/2,width:g,height:f,onPointerDown:v,edgeHandleRadius:m,cursorStyle:"ew-resize",color:t,strokeWidth:w}):void 0,R&&!h?(0,c.jsx)(me,{x:i/2-f/2,y:a-g/2,width:f,height:g,onPointerDown:b,edgeHandleRadius:m,cursorStyle:"ns-resize",color:t,strokeWidth:w}):void 0,s?void 0:(0,c.jsx)(me,{x:i-g/2,y:a/2-Math.min(f,.8*a)/2,width:g,height:Math.min(f,.8*a),onPointerDown:x,edgeHandleRadius:m,cursorStyle:"ew-resize",color:t,strokeWidth:w}),R&&!h?(0,c.jsx)(me,{x:i/2-f/2,y:-g/2,width:f,height:g,onPointerDown:C,edgeHandleRadius:m,cursorStyle:"ns-resize",color:t,strokeWidth:w}):void 0]})},ge=e=>{const{color:t,elementWidth:a,onBeginRotate:i,scaleFactor:n}=e,o=(0,l.useCallback)((e=>{e.stopPropagation(),i()}),[i]),r=10*n,s=1.2*n;return(0,c.jsxs)("g",{children:[(0,c.jsx)("circle",{cx:a/2,cy:-2.5*r,r:1.3*r,fill:"rgba(0, 0, 0, 0.5)",opacity:.4,style:{cursor:"ew-resize"},onPointerDown:o}),(0,c.jsx)("circle",{cx:a/2,cy:-2.5*r,r:r,fill:"#fff",style:{cursor:"ew-resize"},stroke:t,strokeWidth:s,onPointerDown:o}),(0,c.jsxs)("svg",{x:a/2-r,y:-2.5*r-r,xmlns:"http://www.w3.org/2000/svg",style:{cursor:"ew-resize"},height:2*r,viewBox:"0 0 24 24",width:2*r,fill:t,onPointerDown:o,children:[(0,c.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,c.jsx)("path",{d:"M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z"})]})]})},we=e=>{const{color:t,height:a,highlighted:i,id:n,immutable:o,onBeginMove:r,onBeginResize:s,onBeginRotate:d,onPointerEnter:h,onPointerLeave:p,onSelected:u,pressed:m,rotation:f,scaleFactor:g,selected:w,width:y,x:S,y:v,disableX:x,disableY:C}=e,b=1.2*g,k=(0,l.useCallback)((e=>{2===e.button&&(e.stopPropagation(),u(n,e)),0===e.button&&(e.stopPropagation(),!w&&u(n,e),r())}),[n,w,u,r]),E=(0,l.useCallback)((()=>{h(n)}),[n,h]),I=(0,l.useCallback)((()=>{p(n)}),[n,p]),N=o?void 0:w?m?"grabbing":"grab":"pointer",R=o?"none":"visibleFill";return(0,c.jsxs)("g",{transform:`translate(${S}, ${v}) rotate(${f} ${y/2} ${a/2})`,children:[(0,c.jsx)("rect",{className:"interactableInnerRect",width:y,height:a,stroke:w||i?t:"none",pointerEvents:R,fill:"none",strokeWidth:b,style:{cursor:N},onPointerDown:o?void 0:k,onPointerEnter:o?void 0:E,onPointerLeave:o?void 0:I}),w&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ge,{color:t,elementWidth:y,onBeginRotate:d,scaleFactor:g}),(0,c.jsx)(fe,{color:t,elementHeight:a,elementWidth:y,rotation:f,scaleFactor:g,onBeginResize:s,disableX:x,disableY:C})]})]})},ye=({primaryColor:e,containerHeight:t,containerWidth:a,customViewbox:i,editorRef:n,elementEvent:o,guidelines:r,layoutHeight:s,layoutWidth:d,targetedElements:h,scale:u,selectedElement:m,onElementEvent:f,onElementSelected:g,onSequenceStart:w})=>{const{state:y}=Q(),{getLayoutById:S}=B(),v=S(y.layoutId),[x,C]=(0,l.useState)(void 0),b=(0,l.useCallback)((e=>{C(e)}),[]),k=(0,l.useCallback)((e=>{x===e&&C(void 0)}),[x]),E=(0,l.useCallback)((()=>{w(),f({type:te.Translate})}),[f]),I=(0,l.useCallback)(((e,t)=>{w(),f({type:te.Resize,relativeAxis:e,screenAxis:t})}),[f]),N=(0,l.useCallback)((()=>{w(),f({type:te.Rotate})}),[f]),R=i||{x:0,y:0,width:d,height:s},O=u*(Math.sqrt(R.width*R.height)/1e3)*(100/Math.sqrt(t*a))*Math.sqrt((M=a/t,Math.exp(Math.abs(Math.log(M)))));var M;const T=v.layoutState.elements.findIndex((({id:e})=>e===m)),A=[...v.layoutState.elements];return T>=0&&A.push(A.splice(T,1)[0]),(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",style:{touchAction:"none",position:"absolute",maxWidth:"100%",maxHeight:"100%"},width:"100%",height:"100%",viewBox:`${R.x} ${R.y} ${R.width} ${R.height}`,overflow:"overlay",children:[(0,c.jsx)("rect",{fill:"none",stroke:"none",ref:n,width:d,height:s}),r.map((e=>e.svgNode)),A.map((t=>{const a=void 0!==m&&t.id===m,i=a&&void 0!==o,n=void 0!==x&&t.id===x;return(0,c.jsx)(we,{color:e,id:t.id,selected:a,highlighted:n,pressed:i,x:t.x,y:t.y,disableX:t.type===p.LayoutElementType.Frame,disableY:t.type===p.LayoutElementType.Textbox||t.type===p.LayoutElementType.Frame,width:t.width,height:t.height,rotation:t.rotation,immutable:t.immutable||h&&!h.includes(t.id),onSelected:g,onBeginMove:E,onBeginResize:I,onBeginRotate:N,onPointerEnter:b,onPointerLeave:k,scaleFactor:O},t.id)}))]})},Se=e=>{const{color:t,editorRef:a,zoomableElementRef:i,interactionElementRef:n,guidelines:o,isMakingAdjustments:r,viewmask:s,visibleLayoutId:d,xTranslation:h,yTranslation:p,targetedElements:u,borderRadius:m,handleContextMenu:f,handleKeyDown:g,handleKeyUp:w,handlePointerMove:y,handlePointerPressedBackground:S,handlePointerReleased:v,handleScroll:x,onSequenceStart:C,setElementEvent:b,onElementSelected:k}=e,{getLayoutById:E}=B(),I=E(d),N=I.layoutState,{state:R}=Q(),O=(0,l.useCallback)((e=>{if(s){const t={left:s.x,top:s.y,width:s.width,height:s.height,panelId:"",rotation:0};return g(e,t)}return g(e)}),[g,s]),M=(0,l.useCallback)((e=>{if(s){const t={left:s.x,top:s.y,width:s.width,height:s.height,panelId:"",rotation:0};return y(e,t)}return y(e)}),[y,s]);return(0,c.jsx)("div",{style:{justifyContent:"center",position:"relative",height:"100%",width:"100%",scrollbarWidth:"none",outline:"none"},onContextMenu:f,onKeyDown:O,onKeyUp:w,onPointerDown:S,onPointerMoveCapture:M,onPointerUp:v,onWheelCapture:x,ref:n,tabIndex:-1,children:(0,c.jsxs)("div",{ref:i,style:{height:"100%",transform:`scale(${R.zoom}) translate(${h}px, ${p}px)`,display:"grid",filter:"drop-shadow(rgba(0, 0, 0, 0.2) 0px 0px 6px)"},children:[e.children,I.getComponentWithProps({height:r?"100%":"auto",maxHeight:"100%",maxWidth:"100%",position:"absolute",viewmask:s,width:r?"100%":"auto",borderRadius:m}),(0,c.jsx)(ye,{primaryColor:t,containerHeight:i.current?.offsetHeight||1024,containerWidth:i.current?.offsetWidth||1024,editorRef:a,elementEvent:R.elementEvent,guidelines:o,layoutHeight:N.layout.height,layoutWidth:N.layout.width,onElementEvent:b,onSequenceStart:C,onElementSelected:k,scale:10/R.zoom,selectedElement:R.selectedElement,targetedElements:u})]})})},ve=({color:e,borderRadius:a,guidelineColor:i,handleContextMenu:n,onElementSelected:o})=>{const{commandDispatcher:r,getLayoutById:s}=B(),{state:d,uiDispatcher:h}=Q(),u=(0,l.useRef)(null),m=(0,l.useRef)(null),f=(0,l.useRef)(null),{guidelines:g,handleKeyDown:w,handleKeyUp:y,handlePointerMove:S,handlePointerPressedBackground:v,handlePointerReleased:x,handleScroll:C,handleSequenceStart:b,setElementEvent:k}=pe(u,m,f,void 0,"advanced",r,i),E=(0,l.useCallback)(((e,a)=>{const i=s(d.layoutId).layoutState.elements.find((t=>t.id===e));if(e&&i&&i.type===p.LayoutElementType.Textbox){const a=i.algorithm;(!a||a===p.TextAlgorithm.Autosize)&&r(new(0,t.FontAlgorithmCommand)(e,p.TextAlgorithm.Traditional))}o&&o(e,a),h(new Z({selectedElement:e}))}),[r,s,d.layoutId,h]);return(0,c.jsx)(Se,{color:e,editorRef:u,interactionElementRef:m,zoomableElementRef:f,guidelines:g,visibleLayoutId:d.layoutId,xTranslation:0,yTranslation:0,borderRadius:a,handleContextMenu:n,handleKeyDown:w,handleKeyUp:y,handlePointerMove:S,handlePointerPressedBackground:v,handlePointerReleased:x,handleScroll:C,onSequenceStart:b,setElementEvent:k,onElementSelected:E})};function xe(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Ce=new class{constructor(){xe(this,"server",void 0),xe(this,"cache",new Map),xe(this,"materialCache",new Map),xe(this,"loadImageAsFileInfo",(async e=>{const t=await e.arrayBuffer(),a=await(0,g.getAttributesFromArrayBuffer)(t);return{name:e.name.substring(e.name.lastIndexOf("/")+1),blob:((e,t)=>{let a=atob(e.split(",")[1]),i=[];for(let e=0;e<a.length;e++)i.push(a.charCodeAt(e));return new Blob([new Uint8Array(i)],{type:t})})(a.dataUrl,e.type)}})),this.server=q}async getLocalOrFromServer(e){if(this.cache.has(e))return this.cache.get(e);const t=(async()=>(await q.execute("getAssetByKeyV2",{assetKey:e.replace(/\//g,"_")})).body)();return this.cache.set(e,t),t}async getMaterialLocalOrFromServer(e){if(this.materialCache.has(e))return this.materialCache.get(e);const t=(async()=>(await q.execute("getMaterialV2",{id:e})).body)();return this.materialCache.set(e,t),t}async uploadAssetWithProgress(e,t,a,i,n,o){const r=await this.dispatchCreateAssetRequest(e,t,n,o);var s=new XMLHttpRequest;return s.open("PUT",r.assetResponse.uploadUrl,!0),s.setRequestHeader("Content-Type",r.mimeType),s.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),s.upload.onprogress=e=>{e.lengthComputable&&a(100*e.loaded/e.total)},s.onload=()=>{const e=r.assetResponse.asset;i(e)},s.onerror=()=>{console.warn("Asset upload failed")},s.send(e.blob),r.assetResponse.asset}async dispatchCreateAssetRequest(e,t,a,i){const n=e.blob.type?e.blob.type:this.guessMIME(e.name);return{assetResponse:(await this.server.execute("createAsset",{assetDetails:{name:e.name,type:t,mimeType:n,storageOwnerId:i,userAnonymous:!0}},a)).body,mimeType:n}}guessMIME(e){const t=e.split(".").pop();switch(t){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new Error("Unexpected mimetype: "+t)}}};class be{get(e){return localStorage.getItem(e)||void 0}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}class ke{constructor(){var e,t,a;e=this,t="storage",a=new Map,t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}get(e){return this.storage.get(e)||void 0}set(e,t){this.storage.set(e,t)}remove(e){this.storage.delete(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}const Ee=(()=>{try{return localStorage?new be:new ke}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new ke}})(),Ie=n.gql`
2
2
  mutation CreateTransaction($integrationProductId: String!, $bulk: Boolean) {
3
3
  transactionCreate(integrationProductId: $integrationProductId, bulk: $bulk) {
4
4
  id
package/dist/module.js CHANGED
@@ -1,4 +1,4 @@
1
- import{CommandContext as e,getSvgString as t}from"papyrus/build/main/CommandContext";import{CreateElementCommand as a,TextChangeCommand as i,FontAlignmentCommand as n,FontColorCommand as o,FontAlgorithmCommand as s,GroupCommand as r,DeleteElementCommand as l,MoveCommand as c,ResizeCommand as d,RotateCommand as h,FontSizeCommand as p,UpdateWorkflowStateCommand as u,UpdateFramePattern as m,IllustrationColorCommand as f,IllustrationCacheCommand as g,ShiftPatchworkCommand as w,FontSourceCommand as y,CreateLayoutCommand as v}from"papyrus/build/main/command";import{LayoutElementFactory as S}from"papyrus/build/main/Elements/factory";import{SpiffCommerce3DPreviewService as b}from"spiff-preview";import{loadFontFromExternalUrl as C,getFontMetrics as x}from"papyrus/build/main/font";import k from"swagger-client";import{createHttpLink as I,InMemoryCache as E,ApolloClient as N,from as R,gql as O}from"@apollo/client";import{setContext as M}from"@apollo/client/link/context";import{onError as P}from"@apollo/client/link/error";import L from"cross-fetch";import{createContext as D,useContext as A,useEffect as T,useState as z,useReducer as V,useMemo as U,useRef as F,useCallback as W}from"react";import{jsx as j,jsxs as q,Fragment as $}from"react/jsx-runtime";import{UnitOfMeasurement as B,ScaleAxis as K}from"papyrus/build/main/types";import H from"lodash.isequal";import{LayoutElementType as X,TextAlgorithm as G}from"papyrus/build/main/LayoutsState/types";import{getAxisAlignedBoundingBox as Y,isCloseToValue as Z,mmPerPixel as Q,cmPerPixel as _,getElementVertices as J,rotateAroundPoint as ee,findAngle as te,currentDirection as ae}from"papyrus/build/main/math";import{calculateTextboxLines as ie}from"papyrus/build/main/text/algorithm/traditional";import{defaultLineHeightFactor as ne,applyTextTransformations as oe}from"papyrus/build/main/text/shared";import{getAttributesFromArrayBuffer as se}from"papyrus/build/main/image";import re,{Canvg as le}from"canvg";import{StepType as ce,StepAspectType as de}from"papyrus/build/main/generation/Workflow";import he from"lodash.clonedeep";import pe from"papyrus/build/main/module/resolver";import ue from"lodash.debounce";import{getFrameData as me,calculateOffsets as fe,frameDataCache as ge,generateDefaultRectangleFrameSvg as we,GetSVGDimensions as ye,patternImageDataCache as ve}from"papyrus/build/main/frame";import{generateSVGWithUnknownColors as Se,modifySVGWithElementProperties as be,sanitizeSvgTree as Ce}from"papyrus/build/main/illustration";import{findElement as xe,rehydrateSerializedLayout as ke}from"papyrus/build/main/LayoutsState";import{toString as Ie}from"qrcode";import{fetchAsString as Ee}from"papyrus/build/main/crossplatform";import Ne from"react-dom/server";import Re from"papyrus/build/main/Elements/Patchwork";import{determineCorrectFontSizeAndLines as Oe}from"papyrus/build/main/text/algorithm/autosize";import{generateCommands as Me}from"papyrus/build/main/generation";function Pe(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Le=new class{constructor(){Pe(this,"cache",new Map),Pe(this,"getDisplayImageSource",(e=>{if(e){const t=e.displayImage?.links.find((e=>"cdn"===e.rel));if(t)return t.href}})),Pe(this,"getSelectedVariant",((e,t)=>{if(e&&0!==t.length)return e.variants.find((e=>e.id===t[0]))})),Pe(this,"getSelectedVariants",((e,t)=>e?.variants.filter((e=>t.includes(e.id)))||[]))}async cacheRequiredOptions(e){const t=e.steps.map((e=>e.optionId)).filter((e=>void 0!==e)),a=e.steps.map((e=>e.data.colourOptionId)).filter((e=>void 0!==e)),i=[...new Set([...t,...a])].map((async e=>{const t=await Le.getLocalOrFromServer(Fe,e);"Font"===t.data.type&&t.data.variants.forEach((async e=>{if(e.assetKey){const t=(await St.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel))?.href;t&&await C(t)}}))}));await Promise.allSettled([...i])}async getLocalOrFromServer(e,t){if(this.cache.has(t))return this.cache.get(t);const a=(await e.execute("getOptionV2",{id:t})).body;return this.cache.set(t,a),a}getLocalOrUndefined(e){if(e)return this.cache.get(e)}async getAssetTileImageForVariant(e){if(e.thumbnailKey){const t=await St.getLocalOrFromServer(e.thumbnailKey),a=t.links.find((e=>"thumbnail"===e.rel)),i=t.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}const t=e.assetKey;if(t){const e=await St.getLocalOrFromServer(t),a=e.links.find((e=>"thumbnail"===e.rel)),i=e.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}return e.materialId?e.materialId:""}getDefaultVariant(e){const t=e.variants;return 1===t.length?t[0]:void 0!==e.defaultVariant?t.find((t=>t.id===e.defaultVariant)):void 0}};function De(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Ae=new class{constructor(){De(this,"defaultServerUrl","https://api.spiff.com.au"),De(this,"defaultServicesApiUrl","https://services.spiff.com.au"),De(this,"serverUrl",void 0),De(this,"servicesApiUrl",void 0),De(this,"serverUrlCallbacks",void 0),this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}setServerUrl(e){this.serverUrl=e,this.serverUrlCallbacks.forEach((e=>e()))}setServicesApiUrl(e){this.servicesApiUrl=e}addServerUrlCallback(e){this.serverUrlCallbacks.push(e)}};function Te(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}let ze;const Ve=e=>{ze=e},Ue=async()=>({transactionOwnerId:ze});const Fe=new class{constructor(){Te(this,"client",void 0),Te(this,"uncachedOperations",[]),Ae.addServerUrlCallback((async()=>{this.client=void 0,this.client=await this.constructClient()}))}setUncachedOperations(e){this.uncachedOperations=e}async execute(e,t){const a=this.uncachedOperations.includes(e)?e+"_private":e;return new Promise(((e,i)=>{this.getClient().then((n=>{n.execute({operationId:a,parameters:t}).then((t=>e(t))).catch((e=>{e.response&&e.response.status&&e.response.status>=500||(!e.response&&i(new Error(e)),e.response&&i(new Error(`${e.response.status} ${e.response.url}`)))}))})).catch((e=>{i(e)}))}))}async syncAuth(e){const t=await Ue();if(t.bearer?e.authorizations={...e.authorizations,OAuth2:{token:{access_token:t.bearer,token_type:"Bearer"}}}:e.authorizations={...e.authorizations,OAuth2:{token:{access_token:"",token_type:"Bearer"}}},t.activeIntegration)e.authorizations={...e.authorizations,ActiveIntegration:t.activeIntegration};else{const t={...e.authorizations};delete t.ActiveIntegration,e.authorizations=t}if(t.partnerId)e.authorizations={...e.authorizations,PartnerId:t.partnerId};else{const t={...e.authorizations};delete t.PartnerId,e.authorizations=t}}async getClient(){return this.client||(this.client=await this.constructClient()),this.syncAuth(this.client),Promise.resolve(this.client)}async constructClient(){const e=await Ue(),t=Ae.getServerUrl()+"/v2/api-docs";return await k(t,{authorizations:{OAuth2:{token:{access_token:e.bearer,token_type:"Bearer"}},PartnerId:e.partnerId}})}};const We=new class{constructor(){Te(this,"shadowGraphqlClient",void 0),this.shadowGraphqlClient=this.constructShadowGraphqlClient(),Ae.addServerUrlCallback((()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()}))}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const e=I({uri:`${Ae.getServerUrl()}/graphql`,fetch:L}),t=M((async(e,{headers:t})=>{const a=t||{},i=await Ue();return i.bearer&&(a.Authorization=`Bearer ${i.bearer}`),i.partnerId&&(a.partnerId=i.partnerId),i.activeIntegration&&(a.activeIntegration=i.activeIntegration),i.transactionOwnerId&&(a.transactionOwnerId=i.transactionOwnerId),{headers:a}})),a=P((({operation:e,graphQLErrors:t,networkError:a})=>{(t||[]).forEach((({message:t,locations:a,path:i})=>{console.log("[GraphQL Operation Error]"),console.log("Name:"+e.operationName),console.log("Query:"+JSON.stringify(e.query)),console.log(`Message: ${t}, Location: ${JSON.stringify(a,null,2)}, Path: ${i}`),console.log("Variables:"+JSON.stringify(e.variables))})),a&&console.log("GraphQL Network error")}));const i=new E({typePolicies:{Transaction:{fields:{transactionOwnerId:{read:(e=null)=>e},customLogoLink:{read:(e=null)=>e},workflowFooterLogoLink:{read:(e=null)=>e},workflowState:{read:(e=null)=>e},bulkSourceUrl:{read:(e=null)=>e}}}}});return new N({link:R([a,t,e]),cache:i,name:"Core"})}},je=D(new e),qe=()=>{const e=A(je);T((()=>{e.registerStateCallback((()=>{a(new Date)}))}),[e]);const[t,a]=z(new Date);return{commandDispatcher:t=>{e.apply(t)},getLayoutById:t=>e.getLayoutById(t),getAllLayouts:()=>e.getAllLayouts(),getReducerState:()=>{const t=e.getState();return t||{transaction:{layouts:{},serializableWorkflow:{steps:[]}}}},lastUpdated:t,flattenSequence:(t,a)=>{e.flattenSequence(t,a)}}};let $e;var Be;(Be=$e||($e={})).None="None",Be.FrameAdjustment="FrameAdjustment",Be.FinalizeDesign="FinalizeDesign";const Ke=(e,t)=>({layoutId:e()[0].layoutState.layout.id,selectedElement:void 0,zoom:t,maxZoom:5,units:B.Pixel,subMenu:$e.None,activeModifierKeys:[],metaPressed:!1,elementEvent:void 0,scrolledMovement:!1}),He=(e,t)=>H(e,t.apply(e))?e:t.apply(e),Xe=D({}),Ge=e=>{const{getAllLayouts:t}=qe(),[a,i]=V(He,Ke(t,e.defaultZoom||1)),n=U((()=>({state:a,uiDispatcher:i})),[a,i]);return j(Xe.Provider,{value:n,children:e.children})};class Ye{constructor(e){var t,a,i;i=void 0,(a="changes")in(t=this)?Object.defineProperty(t,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[a]=i,this.changes=e}apply(e){return{...e,...this.changes}}}const Ze=()=>A(Xe),Qe=7*window.devicePixelRatio,_e=(e,t,a,i)=>{const n=t.layout.width,o=t.layout.height,s=t.elements.filter((t=>t.id!==e.id&&!t.immutable&&!t.productOverlay)),r=s.map((e=>Y(e.x,e.y,e.width,e.height,e.rotation))),l=[],c=new Set;r.forEach((e=>c.add(e.minX))),r.forEach((e=>c.add(e.maxX))),[0,n/2,n].forEach((e=>c.add(e)));const d=new Set;r.forEach((e=>d.add(e.minY))),r.forEach((e=>d.add(e.maxY))),[0,o/2,o].forEach((e=>d.add(e)));const h=s.map((e=>e.y));for(let e=-315;e<=315;e+=45)h.push(e);const p=Y(e.x,e.y,e.width,e.height,e.rotation),u=[{value:p.minX,anchor:-1},{value:p.minX+(p.maxX-p.minX)/2,anchor:0},{value:p.minX+(p.maxX-p.minX),anchor:1}],m=[{value:p.minY,anchor:-1},{value:p.minY+(p.maxY-p.minY)/2,anchor:0},{value:p.minY+(p.maxY-p.minY),anchor:1}],f=[{value:e.rotation,anchor:0}],g=(e,t,i,s)=>{const r=[];return t.forEach((t=>{const l=i.find((e=>Z(t,e.value,2*a))),[c,d]=((e,t)=>[{x:"x"===e?t:0,y:"x"===e?0:t},{x:"x"===e?t:n,y:"x"===e?o:t}])(e,t),h="rotation"===e?null:j("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:s||"#D61B5C",strokeDasharray:5*a,strokeWidth:1.2*a,overflow:"overlay"},`${e}-${t}-${c.x}-${c.y}-${d.x}-${d.y}`);void 0!==l&&r.push({type:e,value:t,anchorPoint:l.anchor,svgNode:h,guidelineCoordinates:[c,d]})})),r};return l.push(...g("x",Array.from(c),u,i)),l.push(...g("y",Array.from(d),m,i)),l.push(...g("rotation",h,f,i)),l};let Je;var et;let tt;var at;(et=Je||(Je={})).Translate="Translate",et.Rotate="Rotate",et.Resize="Resize",(at=tt||(tt={})).ControlLeft="ControlLeft",at.ControlRight="ControlRight",at.Equal="Equal",at.MetaLeft="MetaLeft",at.MetaRight="MetaRight",at.Minus="Minus",at.ArrowLeft="ArrowLeft",at.ArrowRight="ArrowRight",at.ArrowUp="ArrowUp",at.ArrowDown="ArrowDown",at.AltLeft="AltLeft",at.AltRight="AltRight",at.Delete="Delete",at.Backspace="Backspace";const it=(e,t,a,i)=>{const n=()=>{switch(a){case B.Pixel:return 1;case B.Millimeter:return Q;case B.Centimeter:return _;default:throw new Error("Unknown unit of measurement")}};let o=t.x,s=t.y,r=t.x,l=t.y;switch(e){case tt.ArrowLeft:r=t.x-1/n();break;case tt.ArrowUp:l=t.y-1/n();break;case tt.ArrowRight:r=t.x+1/n();break;case tt.ArrowDown:l=t.y+1/n();break;default:throw new Error("Unhandled element interaction!")}const d=Y(r,l,t.width,t.height,t.rotation);return(!i||d.minX>=i.left&&d.maxX<=i.left+i.width&&d.minY>=i.top&&d.maxY<=i.top+i.height)&&(o=r,s=l),new c(t.id,o,s)};var nt=0,ot=0,st=0;const rt=(e,t,a,n,o,s,r)=>{const l=((e,t,a,i,n,o,s)=>{const r=i.width/t.width,l=i.height/t.height,c=e.movementX/r,d=e.movementY/l,h=a.rotation*Math.PI/180,p=Math.sin(h),u=Math.cos(h);let m;switch(n.type){case Je.Resize:let t={top:a.y,left:a.x,width:a.width,height:a.height,rotation:a.rotation,fontSize:a.fontSize},f=t;switch(n.screenAxis){case K.North:{const e=-c*p+d*u,i=a.y+e,n=a.height-e,o=J({...a}).center,s=J({...a,y:i,height:n}).center,r=ee(s,o,h),l=r.x-a.width/2,m=r.y-n/2;f={...t,left:l,top:m,height:n}}break;case K.East:{const e=c*u+d*p,i=a.width+e;let n=a.height;if(a.type===X.Textbox){const e=a;n=ie(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const o=J({...a}).center,s=J({...a,width:i,height:n}).center,r=ee(s,o,h),l=r.x-i/2,m=r.y-n/2;f={...t,left:l,top:m,width:i,height:n}}break;case K.West:{const e=c*u+d*p,i=a.x+e,n=a.width-e;let o=a.height;if(a.type===X.Textbox){const e=a;o=ie(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const s=J({...a}).center,r=J({...a,width:n,height:o,x:i}).center,l=ee(r,s,h),m=l.x-n/2,g=l.y-o/2;f={...t,left:m,top:g,width:n,height:o}}break;case K.South:{const e=-c*p+d*u,i=a.height+e,n=J({...a}).center,o=J({...a,height:i}).center,s=ee(o,n,h),r=s.x-a.width/2,l=s.y-i/2;f={...t,left:r,top:l,height:i}}break;case K.Northeast:{const e=c*u+d*p,i=a.width+e;let n=a.height+e,o=a.y-e,s=a.fontSize;if(a.type===X.Textbox){const t=a;s=t.fontSize+e/8,n=ie(s,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||ne;o=a.y-e*i/8}const r=J({...a}).center,l=J({...a,width:i,height:n,y:o}).center,m=ee(l,r,h),g=m.x-i/2,w=m.y-n/2;f={...t,left:g,top:w,width:i,height:n,fontSize:s}}break;case K.Northwest:{const e=-c*u+-d*p,i=a.x-e,n=a.width+e;let o=a.y-e,s=a.height+e,r=a.fontSize;if(a.type===X.Textbox){const t=a;r=t.fontSize+e/8,s=ie(r,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||ne;o=a.y-e*i/8}const l=J({...a}).center,m=J({...a,x:i,y:o,width:n,height:s}).center,g=ee(m,l,h),w=g.x-n/2,y=g.y-s/2;f={...t,left:w,top:y,width:n,height:s,fontSize:r}}break;case K.Southeast:{const e=c*u+d*p,i=a.width+e;let n=a.height+e,o=a.fontSize;if(a.type===X.Textbox){const t=a;o=t.fontSize+e/8,n=ie(o,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const s=J({...a}).center,r=J({...a,width:i,height:n}).center,l=ee(r,s,h),m=l.x-i/2,g=l.y-n/2;f={...t,left:m,top:g,width:i,height:n,fontSize:o}}break;case K.Southwest:{const e=-c*u+-d*p,i=a.width+e;let n=a.x-e,o=a.height+e,s=a.fontSize;if(a.type===X.Textbox){const t=a;s=t.fontSize+e/8,o=ie(s,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const r=J({...a}).center,l=J({...a,width:i,height:o,x:n}).center,m=ee(l,r,h),g=m.x-i/2,w=m.y-o/2;f={...t,left:g,top:w,width:i,height:o,fontSize:s}}}return m=Y(f.left,f.top,f.width,f.height,f.rotation),(!s||m.minX>=s.left&&m.maxX<=s.left+s.width&&m.minY>=s.top&&m.maxY<=s.top+s.height)&&(t=f),t;case Je.Rotate:const g={x:e.clientX,y:e.clientY};let w,y=a.rotation;const v=J(a,i,{x:r,y:l}),S=te(g,v.c,v.d),b=te(g,v.d,v.c);if(0===o.filter((e=>"rotation"===e.type)).length)st=0,w=(a.rotation+S-b)%360;else{st+=Math.sqrt(c**2+d**2);const e=Math.abs(st)>Qe/r;w=e?(a.rotation+S-b)%360:o.find((e=>"rotation"===e.type))?.value||0,e&&(st=0)}return m=Y(a.x,a.y,a.width,a.height,w),(!s||m.minX>=s.left&&m.maxX<=s.left+s.width&&m.minY>=s.top&&m.maxY<=s.top+s.height)&&(y=w),{top:a.y,left:a.x,width:a.width,height:a.height,rotation:y};case Je.Translate:let C,x,k=a.x,I=a.y;if(0===o.filter((e=>"rotation"!==e.type)).length)nt=0,ot=0,C=a.x+c,x=a.y+d;else{const e=o.find((e=>"x"===e.type)),t=o.find((e=>"y"===e.type));e||(nt=0),t||(ot=0);const i=Math.abs(nt)>Qe/r,n=Math.abs(ot)>Qe/l;C=e?i?a.x+nt:a.x:a.x+c,x=t?n?a.y+ot:a.y:a.y+d,nt=i?0:nt+c,ot=n?0:ot+d}return m=Y(C,x,a.width,a.height,a.rotation),(!s||m.minX>=s.left&&m.maxX<=s.left+s.width&&m.minY>=s.top&&m.maxY<=s.top+s.height)&&(k=C,I=x),{top:I,left:k,width:a.width,height:a.height,rotation:a.rotation}}})(e,t,a,n,o,s,r),u=[];if(a.type===X.Textbox){const e=a;u.push(new i(e.id,e.text||e.input||""))}if(u.push(new c(a.id,l.left,l.top),new d(a.id,l.width,l.height),new h(a.id,l.rotation)),a.type===X.Textbox){const e=a;l.fontSize&&e.fontSize!==l.fontSize&&u.push(new p(e.id,l.fontSize))}return u},lt=()=>{const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},ct=.5,dt=(e,t,a,i,n,o,s)=>{const{state:c,uiDispatcher:d}=A(Xe),{getLayoutById:h,getReducerState:p,flattenSequence:u}=qe(),[m,f]=z(void 0),[g,w]=z(void 0),y=h(c.layoutId);T((()=>{if("adjustment"===n&&e?.current&&i){if(i<.5)return void d(new Ye({zoom:.5}));if(i>c.maxZoom)return void d(new Ye({zoom:c.maxZoom}));d(new Ye({zoom:i}))}}),[i,d,e,n,c.maxZoom]);const v=W(((e,i)=>{d(new Ye({zoom:i}));const o=t?.current?.scrollWidth-t?.current?.clientWidth!=0,s=t?.current?.scrollHeight-t?.current?.clientHeight!=0;t.current&&a.current&&!c.scrolledMovement&&"advanced"===n&&(s&&(t.current.scrollTop=a.current.offsetTop+(t.current.scrollHeight-t.current.clientHeight)/2),o&&(t.current.scrollLeft=(a.current.offsetLeft+t.current.scrollWidth-t.current.clientWidth)/2))}),[d,t,a,c.scrolledMovement,n]);T((()=>{c.zoom<=1&&d(new Ye({scrolledMovement:!1}))}),[d,c.zoom]);const S=t?.current?.getBoundingClientRect(),b=((S?.width||1)+(S?.height||1))/2,C=(y.layoutState.layout.width+y.layoutState.layout.height)/2/b/c.zoom,x=U((()=>{const e=c.activeModifierKeys,t=c.elementEvent,a=e.includes(tt.ControlLeft)||e.includes(tt.MetaLeft)||e.includes(tt.ControlRight)||e.includes(tt.MetaRight);if(!c.selectedElement||!t||a)return[];const i=t&&t.type===Je.Translate,n=t&&t.type===Je.Rotate,o=y.layoutState.elements.find((e=>e.id===c.selectedElement));return(i||n)&&o?_e(o,y.layoutState,C,s):[]}),[c.selectedElement,c.elementEvent,c.activeModifierKeys,y.layoutState,C]),k=W((()=>{const e=lt();f(e),w(p().transaction)}),[p]),I=W((()=>{d(new Ye({selectedElement:void 0}))}),[d]),E=W((()=>{d(new Ye({scrolledMovement:!0}))}),[d]),N=W(((a,i)=>{const n=y.layoutState.elements.find((e=>e.id===c.selectedElement));if(!(c.elementEvent&&e.current&&t.current&&c.selectedElement&&n))return;t.current.hasPointerCapture(a.pointerId)||t.current.setPointerCapture(a.pointerId);const s=e.current.getBoundingClientRect(),l=new r(rt(a,y.layoutState.layout,n,s,c.elementEvent,x,i));l.sequenceId=m,o(l)}),[y.layoutState.elements,y.layoutState.layout,c.elementEvent,e,c.selectedElement,t,x,o]),R=W((e=>{d(new Ye({elementEvent:e}))}),[d]),O=W((()=>{d(new Ye({elementEvent:void 0})),m&&g&&(u(m,g),f(void 0),w(void 0))}),[d,m,g,u]),M=W(((e,t)=>{let a=c.zoom;const i=c.maxZoom,s=c.selectedElement,r=c.activeModifierKeys;if((r.includes(tt.AltLeft)||r.includes(tt.AltRight))&&(e.code===tt.Equal||e.code===tt.Minus)){const t=.05*i;e.code===tt.Equal?d(new Ye({zoom:a+t<=i?a+=t:a})):d(new Ye({zoom:a-t>=.5?a-t:a}))}const h=y.layoutState.elements.find((e=>e.id===s));if(s&&h){if(e.code===tt.MetaLeft||e.code===tt.ControlLeft||e.code===tt.MetaRight||e.code===tt.ControlRight){const t=e.code,a=c.activeModifierKeys;if(!a.includes(t))return d(new Ye({activeModifierKeys:a.concat(t)}))}if(e.code===tt.ArrowDown||e.code===tt.ArrowUp||e.code===tt.ArrowLeft||e.code===tt.ArrowRight){d(new Ye({elementEvent:{type:Je.Translate}}));const a=it(e.code,h,c.units,t);o(a),d(new Ye({elementEvent:void 0}))}e.code!==tt.Delete&&e.code!==tt.Backspace||"advanced"!==n||(d(new Ye({selectedElement:void 0})),o(new l(h.id)))}}),[o,d,y.layoutState.elements,n,c.activeModifierKeys,c.maxZoom,c.selectedElement,c.units,c.zoom]),P=W((e=>{if(e.code===tt.MetaLeft||e.code===tt.ControlLeft||e.code===tt.MetaRight||e.code===tt.ControlRight){const t=c.activeModifierKeys,a=e.code;d(new Ye({activeModifierKeys:t.filter((e=>e!==a))}))}}),[d,c.activeModifierKeys]);return{guidelines:x,scale:C,zoomableElementRef:a,setElementEvent:R,handleZoom:v,handleKeyDown:M,handleKeyUp:P,handlePointerPressedBackground:I,handlePointerReleased:O,handlePointerMove:N,handleScroll:E,handleSequenceStart:k}},ht=e=>{const{x:t,y:a,cursorStyle:i,onPointerDown:n,handleClass:o,cornerRadius:s,color:r,strokeWidth:l}=e;return j("circle",{className:o,cx:t,cy:a,r:s,fill:"#ffffff",style:{cursor:i},stroke:r,strokeWidth:l,onPointerDown:n})},pt=e=>{const{x:t,y:a,width:i,height:n,cursorStyle:o,onPointerDown:s,edgeHandleRadius:r,color:l,strokeWidth:c}=e;return j("rect",{x:t,y:a,width:i,height:n,rx:r,fill:"#ffffff",style:{cursor:o},stroke:l,strokeWidth:c,onPointerDown:s})},ut=e=>{const{color:t,elementHeight:a,elementWidth:i,onBeginResize:n,rotation:o,scaleFactor:s,disableX:r,disableY:l}=e,c=7.5*s,d=3*s,h=28*s,p=6*s,u=1.2*s,m=a-2*c,f=W(((e,t,a)=>{e.stopPropagation(),n(t,a)}),[n]),g=W((e=>f(e,ae(K.West,360-o),K.West)),[f,o]),w=W((e=>f(e,ae(K.East,360-o),K.East)),[f,o]),y=W((e=>f(e,ae(K.North,360-o),K.North)),[f,o]),v=W((e=>f(e,ae(K.South,360-o),K.South)),[f,o]),S=W((e=>f(e,K.Northwest,K.Northwest)),[f]),b=W((e=>f(e,K.Northeast,K.Northeast)),[f]),C=W((e=>f(e,K.Southwest,K.Southwest)),[f]),x=W((e=>f(e,K.Northeast,K.Southeast)),[f]),k=h<=m;return q($,{children:[j(ht,{x:0,y:0,cursorStyle:"nwse-resize",onPointerDown:S,handleClass:"cornerNorthWest",cornerRadius:c,color:t,strokeWidth:u}),k?j(ht,{x:i,y:0,cursorStyle:"nesw-resize",onPointerDown:b,handleClass:"cornerNorthEast",cornerRadius:c,color:t,strokeWidth:u}):void 0,k?j(ht,{x:i,y:a,cursorStyle:"nwse-resize",onPointerDown:x,handleClass:"cornerSouthEast",cornerRadius:c,color:t,strokeWidth:u}):void 0,k?j(ht,{x:0,y:a,cursorStyle:"nesw-resize",onPointerDown:C,handleClass:"cornerSouthWest",cornerRadius:c,color:t,strokeWidth:u}):void 0,k&&!r?j(pt,{x:-p/2,y:a/2-h/2,width:p,height:h,onPointerDown:g,edgeHandleRadius:d,cursorStyle:"ew-resize",color:t,strokeWidth:u}):void 0,k&&!l?j(pt,{x:i/2-h/2,y:a-p/2,width:h,height:p,onPointerDown:v,edgeHandleRadius:d,cursorStyle:"ns-resize",color:t,strokeWidth:u}):void 0,r?void 0:j(pt,{x:i-p/2,y:a/2-Math.min(h,.8*a)/2,width:p,height:Math.min(h,.8*a),onPointerDown:w,edgeHandleRadius:d,cursorStyle:"ew-resize",color:t,strokeWidth:u}),k&&!l?j(pt,{x:i/2-h/2,y:-p/2,width:h,height:p,onPointerDown:y,edgeHandleRadius:d,cursorStyle:"ns-resize",color:t,strokeWidth:u}):void 0]})},mt=e=>{const{color:t,elementWidth:a,onBeginRotate:i,scaleFactor:n}=e,o=W((e=>{e.stopPropagation(),i()}),[i]),s=10*n,r=1.2*n;return q("g",{children:[j("circle",{cx:a/2,cy:-2.5*s,r:1.3*s,fill:"rgba(0, 0, 0, 0.5)",opacity:.4,style:{cursor:"ew-resize"},onPointerDown:o}),j("circle",{cx:a/2,cy:-2.5*s,r:s,fill:"#fff",style:{cursor:"ew-resize"},stroke:t,strokeWidth:r,onPointerDown:o}),q("svg",{x:a/2-s,y:-2.5*s-s,xmlns:"http://www.w3.org/2000/svg",style:{cursor:"ew-resize"},height:2*s,viewBox:"0 0 24 24",width:2*s,fill:t,onPointerDown:o,children:[j("path",{d:"M0 0h24v24H0z",fill:"none"}),j("path",{d:"M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z"})]})]})},ft=e=>{const{color:t,height:a,highlighted:i,id:n,immutable:o,onBeginMove:s,onBeginResize:r,onBeginRotate:l,onPointerEnter:c,onPointerLeave:d,onSelected:h,pressed:p,rotation:u,scaleFactor:m,selected:f,width:g,x:w,y:y,disableX:v,disableY:S}=e,b=1.2*m,C=W((e=>{2===e.button&&(e.stopPropagation(),h(n,e)),0===e.button&&(e.stopPropagation(),!f&&h(n,e),s())}),[n,f,h,s]),x=W((()=>{c(n)}),[n,c]),k=W((()=>{d(n)}),[n,d]);return q("g",{transform:`translate(${w}, ${y}) rotate(${u} ${g/2} ${a/2})`,children:[j("rect",{className:"interactableInnerRect",width:g,height:a,stroke:f||i?t:"none",pointerEvents:o?"none":"visibleFill",fill:"none",strokeWidth:b,style:{cursor:o?void 0:f?p?"grabbing":"grab":"pointer"},onPointerDown:o?void 0:C,onPointerEnter:o?void 0:x,onPointerLeave:o?void 0:k}),f&&q($,{children:[j(mt,{color:t,elementWidth:g,onBeginRotate:l,scaleFactor:m}),j(ut,{color:t,elementHeight:a,elementWidth:g,rotation:u,scaleFactor:m,onBeginResize:r,disableX:v,disableY:S})]})]})},gt=({primaryColor:e,containerHeight:t,containerWidth:a,customViewbox:i,editorRef:n,elementEvent:o,guidelines:s,layoutHeight:r,layoutWidth:l,targetedElements:c,scale:d,selectedElement:h,onElementEvent:p,onElementSelected:u,onSequenceStart:m})=>{const{state:f}=Ze(),{getLayoutById:g}=qe(),w=g(f.layoutId),[y,v]=z(void 0),S=W((e=>{v(e)}),[]),b=W((e=>{y===e&&v(void 0)}),[y]),C=W((()=>{m(),p({type:Je.Translate})}),[p]),x=W(((e,t)=>{m(),p({type:Je.Resize,relativeAxis:e,screenAxis:t})}),[p]),k=W((()=>{m(),p({type:Je.Rotate})}),[p]),I=i||{x:0,y:0,width:l,height:r},E=d*(Math.sqrt(I.width*I.height)/1e3)*(100/Math.sqrt(t*a))*Math.sqrt((N=a/t,Math.exp(Math.abs(Math.log(N)))));var N;const R=w.layoutState.elements.findIndex((({id:e})=>e===h)),O=[...w.layoutState.elements];return R>=0&&O.push(O.splice(R,1)[0]),q("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",style:{touchAction:"none",position:"absolute",maxWidth:"100%",maxHeight:"100%"},width:"100%",height:"100%",viewBox:`${I.x} ${I.y} ${I.width} ${I.height}`,overflow:"overlay",children:[j("rect",{fill:"none",stroke:"none",ref:n,width:l,height:r}),s.map((e=>e.svgNode)),O.map((t=>{const a=void 0!==h&&t.id===h,i=a&&void 0!==o,n=void 0!==y&&t.id===y;return j(ft,{color:e,id:t.id,selected:a,highlighted:n,pressed:i,x:t.x,y:t.y,disableX:t.type===X.Frame,disableY:t.type===X.Textbox||t.type===X.Frame,width:t.width,height:t.height,rotation:t.rotation,immutable:t.immutable||c&&!c.includes(t.id),onSelected:u,onBeginMove:C,onBeginResize:x,onBeginRotate:k,onPointerEnter:S,onPointerLeave:b,scaleFactor:E},t.id)}))]})},wt=e=>{const{color:t,editorRef:a,zoomableElementRef:i,interactionElementRef:n,guidelines:o,isMakingAdjustments:s,viewmask:r,visibleLayoutId:l,xTranslation:c,yTranslation:d,targetedElements:h,borderRadius:p,handleContextMenu:u,handleKeyDown:m,handleKeyUp:f,handlePointerMove:g,handlePointerPressedBackground:w,handlePointerReleased:y,handleScroll:v,onSequenceStart:S,setElementEvent:b,onElementSelected:C}=e,{getLayoutById:x}=qe(),k=x(l),I=k.layoutState,{state:E}=Ze(),N=W((e=>{if(r){const t={left:r.x,top:r.y,width:r.width,height:r.height,panelId:"",rotation:0};return m(e,t)}return m(e)}),[m,r]),R=W((e=>{if(r){const t={left:r.x,top:r.y,width:r.width,height:r.height,panelId:"",rotation:0};return g(e,t)}return g(e)}),[g,r]);return j("div",{style:{justifyContent:"center",position:"relative",height:"100%",width:"100%",scrollbarWidth:"none",outline:"none"},onContextMenu:u,onKeyDown:N,onKeyUp:f,onPointerDown:w,onPointerMoveCapture:R,onPointerUp:y,onWheelCapture:v,ref:n,tabIndex:-1,children:q("div",{ref:i,style:{height:"100%",transform:`scale(${E.zoom}) translate(${c}px, ${d}px)`,display:"grid",filter:"drop-shadow(rgba(0, 0, 0, 0.2) 0px 0px 6px)"},children:[e.children,k.getComponentWithProps({height:s?"100%":"auto",maxHeight:"100%",maxWidth:"100%",position:"absolute",viewmask:r,width:s?"100%":"auto",borderRadius:p}),j(gt,{primaryColor:t,containerHeight:i.current?.offsetHeight||1024,containerWidth:i.current?.offsetWidth||1024,editorRef:a,elementEvent:E.elementEvent,guidelines:o,layoutHeight:I.layout.height,layoutWidth:I.layout.width,onElementEvent:b,onSequenceStart:S,onElementSelected:C,scale:10/E.zoom,selectedElement:E.selectedElement,targetedElements:h})]})})},yt=({color:e,borderRadius:t,guidelineColor:a,handleContextMenu:i,onElementSelected:n})=>{const{commandDispatcher:o,getLayoutById:r}=qe(),{state:l,uiDispatcher:c}=Ze(),d=F(null),h=F(null),p=F(null),{guidelines:u,handleKeyDown:m,handleKeyUp:f,handlePointerMove:g,handlePointerPressedBackground:w,handlePointerReleased:y,handleScroll:v,handleSequenceStart:S,setElementEvent:b}=dt(d,h,p,void 0,"advanced",o,a),C=W(((e,t)=>{const a=r(l.layoutId).layoutState.elements.find((t=>t.id===e));if(e&&a&&a.type===X.Textbox){const t=a.algorithm;(!t||t===G.Autosize)&&o(new s(e,G.Traditional))}n&&n(e,t),c(new Ye({selectedElement:e}))}),[o,r,l.layoutId,c]);return j(wt,{color:e,editorRef:d,interactionElementRef:h,zoomableElementRef:p,guidelines:u,visibleLayoutId:l.layoutId,xTranslation:0,yTranslation:0,borderRadius:t,handleContextMenu:i,handleKeyDown:m,handleKeyUp:f,handlePointerMove:g,handlePointerPressedBackground:w,handlePointerReleased:y,handleScroll:v,onSequenceStart:S,setElementEvent:b,onElementSelected:C})};function vt(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const St=new class{constructor(){vt(this,"server",void 0),vt(this,"cache",new Map),vt(this,"materialCache",new Map),vt(this,"loadImageAsFileInfo",(async e=>{const t=await e.arrayBuffer(),a=await se(t);return{name:e.name.substring(e.name.lastIndexOf("/")+1),blob:((e,t)=>{let a=atob(e.split(",")[1]),i=[];for(let e=0;e<a.length;e++)i.push(a.charCodeAt(e));return new Blob([new Uint8Array(i)],{type:t})})(a.dataUrl,e.type)}})),this.server=Fe}async getLocalOrFromServer(e){if(this.cache.has(e))return this.cache.get(e);const t=(async()=>(await Fe.execute("getAssetByKeyV2",{assetKey:e.replace(/\//g,"_")})).body)();return this.cache.set(e,t),t}async getMaterialLocalOrFromServer(e){if(this.materialCache.has(e))return this.materialCache.get(e);const t=(async()=>(await Fe.execute("getMaterialV2",{id:e})).body)();return this.materialCache.set(e,t),t}async uploadAssetWithProgress(e,t,a,i,n,o){const s=await this.dispatchCreateAssetRequest(e,t,n,o);var r=new XMLHttpRequest;return r.open("PUT",s.assetResponse.uploadUrl,!0),r.setRequestHeader("Content-Type",s.mimeType),r.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),r.upload.onprogress=e=>{e.lengthComputable&&a(100*e.loaded/e.total)},r.onload=()=>{const e=s.assetResponse.asset;i(e)},r.onerror=()=>{console.warn("Asset upload failed")},r.send(e.blob),s.assetResponse.asset}async dispatchCreateAssetRequest(e,t,a,i){const n=e.blob.type?e.blob.type:this.guessMIME(e.name);return{assetResponse:(await this.server.execute("createAsset",{assetDetails:{name:e.name,type:t,mimeType:n,storageOwnerId:i,userAnonymous:!0}},a)).body,mimeType:n}}guessMIME(e){const t=e.split(".").pop();switch(t){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new Error("Unexpected mimetype: "+t)}}};class bt{get(e){return localStorage.getItem(e)||void 0}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}class Ct{constructor(){var e,t,a;e=this,t="storage",a=new Map,t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}get(e){return this.storage.get(e)||void 0}set(e,t){this.storage.set(e,t)}remove(e){this.storage.delete(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}const xt=(()=>{try{return localStorage?new bt:new Ct}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new Ct}})(),kt=O`
1
+ import{CommandContext as e,getSvgString as t}from"papyrus/build/main/CommandContext";import{CreateElementCommand as a,TextChangeCommand as i,FontAlignmentCommand as n,FontColorCommand as o,FontAlgorithmCommand as s,GroupCommand as r,DeleteElementCommand as l,MoveCommand as c,ResizeCommand as d,RotateCommand as h,FontSizeCommand as p,UpdateWorkflowStateCommand as u,UpdateFramePattern as m,IllustrationColorCommand as f,IllustrationCacheCommand as g,ShiftPatchworkCommand as w,FontSourceCommand as y,CreateLayoutCommand as v}from"papyrus/build/main/command";import{LayoutElementFactory as S}from"papyrus/build/main/Elements/factory";import{SpiffCommerce3DPreviewService as b,ProductCameraRig as C}from"spiff-preview";import{loadFontFromExternalUrl as x,getFontMetrics as k}from"papyrus/build/main/font";import I from"swagger-client";import{createHttpLink as E,InMemoryCache as N,ApolloClient as R,from as O,gql as M}from"@apollo/client";import{setContext as P}from"@apollo/client/link/context";import{onError as L}from"@apollo/client/link/error";import D from"cross-fetch";import{createContext as A,useContext as T,useEffect as z,useState as V,useReducer as U,useMemo as F,useRef as W,useCallback as j}from"react";import{jsx as q,jsxs as $,Fragment as B}from"react/jsx-runtime";import{UnitOfMeasurement as K,ScaleAxis as H}from"papyrus/build/main/types";import X from"lodash.isequal";import{LayoutElementType as G,TextAlgorithm as Y}from"papyrus/build/main/LayoutsState/types";import{getAxisAlignedBoundingBox as Z,isCloseToValue as Q,mmPerPixel as _,cmPerPixel as J,getElementVertices as ee,rotateAroundPoint as te,findAngle as ae,currentDirection as ie}from"papyrus/build/main/math";import{calculateTextboxLines as ne}from"papyrus/build/main/text/algorithm/traditional";import{defaultLineHeightFactor as oe,applyTextTransformations as se}from"papyrus/build/main/text/shared";import{getAttributesFromArrayBuffer as re}from"papyrus/build/main/image";import le,{Canvg as ce}from"canvg";import{StepType as de,StepAspectType as he}from"papyrus/build/main/generation/Workflow";import pe from"lodash.clonedeep";import ue from"papyrus/build/main/module/resolver";import me from"lodash.debounce";import{getFrameData as fe,calculateOffsets as ge,frameDataCache as we,generateDefaultRectangleFrameSvg as ye,GetSVGDimensions as ve,patternImageDataCache as Se}from"papyrus/build/main/frame";import{generateSVGWithUnknownColors as be,modifySVGWithElementProperties as Ce,sanitizeSvgTree as xe}from"papyrus/build/main/illustration";import{findElement as ke,rehydrateSerializedLayout as Ie}from"papyrus/build/main/LayoutsState";import{toString as Ee}from"qrcode";import{fetchAsString as Ne}from"papyrus/build/main/crossplatform";import Re from"react-dom/server";import Oe from"papyrus/build/main/Elements/Patchwork";import{determineCorrectFontSizeAndLines as Me}from"papyrus/build/main/text/algorithm/autosize";import{generateCommands as Pe}from"papyrus/build/main/generation";function Le(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const De=new class{constructor(){Le(this,"cache",new Map),Le(this,"getDisplayImageSource",(e=>{if(e){const t=e.displayImage?.links.find((e=>"cdn"===e.rel));if(t)return t.href}})),Le(this,"getSelectedVariant",((e,t)=>{if(e&&0!==t.length)return e.variants.find((e=>e.id===t[0]))})),Le(this,"getSelectedVariants",((e,t)=>e?.variants.filter((e=>t.includes(e.id)))||[]))}async cacheRequiredOptions(e){const t=e.steps.map((e=>e.optionId)).filter((e=>void 0!==e)),a=e.steps.map((e=>e.data.colourOptionId)).filter((e=>void 0!==e)),i=[...new Set([...t,...a])].map((async e=>{const t=await De.getLocalOrFromServer(We,e);"Font"===t.data.type&&t.data.variants.forEach((async e=>{if(e.assetKey){const t=(await bt.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel))?.href;t&&await x(t)}}))}));await Promise.allSettled([...i])}async getLocalOrFromServer(e,t){if(this.cache.has(t))return this.cache.get(t);const a=(await e.execute("getOptionV2",{id:t})).body;return this.cache.set(t,a),a}getLocalOrUndefined(e){if(e)return this.cache.get(e)}async getAssetTileImageForVariant(e){if(e.thumbnailKey){const t=await bt.getLocalOrFromServer(e.thumbnailKey),a=t.links.find((e=>"thumbnail"===e.rel)),i=t.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}const t=e.assetKey;if(t){const e=await bt.getLocalOrFromServer(t),a=e.links.find((e=>"thumbnail"===e.rel)),i=e.links.find((e=>"cdn"===e.rel));return a?.href||i?.href}return e.materialId?e.materialId:""}getDefaultVariant(e){const t=e.variants;return 1===t.length?t[0]:void 0!==e.defaultVariant?t.find((t=>t.id===e.defaultVariant)):void 0}};function Ae(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Te=new class{constructor(){Ae(this,"defaultServerUrl","https://api.spiff.com.au"),Ae(this,"defaultServicesApiUrl","https://services.spiff.com.au"),Ae(this,"serverUrl",void 0),Ae(this,"servicesApiUrl",void 0),Ae(this,"serverUrlCallbacks",void 0),this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}setServerUrl(e){this.serverUrl=e,this.serverUrlCallbacks.forEach((e=>e()))}setServicesApiUrl(e){this.servicesApiUrl=e}addServerUrlCallback(e){this.serverUrlCallbacks.push(e)}};function ze(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}let Ve;const Ue=e=>{Ve=e},Fe=async()=>({transactionOwnerId:Ve});const We=new class{constructor(){ze(this,"client",void 0),ze(this,"uncachedOperations",[]),Te.addServerUrlCallback((async()=>{this.client=void 0,this.client=await this.constructClient()}))}setUncachedOperations(e){this.uncachedOperations=e}async execute(e,t){const a=this.uncachedOperations.includes(e)?e+"_private":e;return new Promise(((e,i)=>{this.getClient().then((n=>{n.execute({operationId:a,parameters:t}).then((t=>e(t))).catch((e=>{e.response&&e.response.status&&e.response.status>=500||(!e.response&&i(new Error(e)),e.response&&i(new Error(`${e.response.status} ${e.response.url}`)))}))})).catch((e=>{i(e)}))}))}async syncAuth(e){const t=await Fe();if(t.bearer?e.authorizations={...e.authorizations,OAuth2:{token:{access_token:t.bearer,token_type:"Bearer"}}}:e.authorizations={...e.authorizations,OAuth2:{token:{access_token:"",token_type:"Bearer"}}},t.activeIntegration)e.authorizations={...e.authorizations,ActiveIntegration:t.activeIntegration};else{const t={...e.authorizations};delete t.ActiveIntegration,e.authorizations=t}if(t.partnerId)e.authorizations={...e.authorizations,PartnerId:t.partnerId};else{const t={...e.authorizations};delete t.PartnerId,e.authorizations=t}}async getClient(){return this.client||(this.client=await this.constructClient()),this.syncAuth(this.client),Promise.resolve(this.client)}async constructClient(){const e=await Fe(),t=Te.getServerUrl()+"/v2/api-docs";return await I(t,{authorizations:{OAuth2:{token:{access_token:e.bearer,token_type:"Bearer"}},PartnerId:e.partnerId}})}};const je=new class{constructor(){ze(this,"shadowGraphqlClient",void 0),this.shadowGraphqlClient=this.constructShadowGraphqlClient(),Te.addServerUrlCallback((()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()}))}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const e=E({uri:`${Te.getServerUrl()}/graphql`,fetch:D}),t=P((async(e,{headers:t})=>{const a=t||{},i=await Fe();return i.bearer&&(a.Authorization=`Bearer ${i.bearer}`),i.partnerId&&(a.partnerId=i.partnerId),i.activeIntegration&&(a.activeIntegration=i.activeIntegration),i.transactionOwnerId&&(a.transactionOwnerId=i.transactionOwnerId),{headers:a}})),a=L((({operation:e,graphQLErrors:t,networkError:a})=>{(t||[]).forEach((({message:t,locations:a,path:i})=>{console.log("[GraphQL Operation Error]"),console.log("Name:"+e.operationName),console.log("Query:"+JSON.stringify(e.query)),console.log(`Message: ${t}, Location: ${JSON.stringify(a,null,2)}, Path: ${i}`),console.log("Variables:"+JSON.stringify(e.variables))})),a&&console.log("GraphQL Network error")}));const i=new N({typePolicies:{Transaction:{fields:{transactionOwnerId:{read:(e=null)=>e},customLogoLink:{read:(e=null)=>e},workflowFooterLogoLink:{read:(e=null)=>e},workflowState:{read:(e=null)=>e},bulkSourceUrl:{read:(e=null)=>e}}}}});return new R({link:O([a,t,e]),cache:i,name:"Core"})}},qe=A(new e),$e=()=>{const e=T(qe);z((()=>{e.registerStateCallback((()=>{a(new Date)}))}),[e]);const[t,a]=V(new Date);return{commandDispatcher:t=>{e.apply(t)},getLayoutById:t=>e.getLayoutById(t),getAllLayouts:()=>e.getAllLayouts(),getReducerState:()=>{const t=e.getState();return t||{transaction:{layouts:{},serializableWorkflow:{steps:[]}}}},lastUpdated:t,flattenSequence:(t,a)=>{e.flattenSequence(t,a)}}};let Be;var Ke;(Ke=Be||(Be={})).None="None",Ke.FrameAdjustment="FrameAdjustment",Ke.FinalizeDesign="FinalizeDesign";const He=(e,t)=>({layoutId:e()[0].layoutState.layout.id,selectedElement:void 0,zoom:t,maxZoom:5,units:K.Pixel,subMenu:Be.None,activeModifierKeys:[],metaPressed:!1,elementEvent:void 0,scrolledMovement:!1}),Xe=(e,t)=>X(e,t.apply(e))?e:t.apply(e),Ge=A({}),Ye=e=>{const{getAllLayouts:t}=$e(),[a,i]=U(Xe,He(t,e.defaultZoom||1)),n=F((()=>({state:a,uiDispatcher:i})),[a,i]);return q(Ge.Provider,{value:n,children:e.children})};class Ze{constructor(e){var t,a,i;i=void 0,(a="changes")in(t=this)?Object.defineProperty(t,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[a]=i,this.changes=e}apply(e){return{...e,...this.changes}}}const Qe=()=>T(Ge),_e=7*window.devicePixelRatio,Je=(e,t,a,i)=>{const n=t.layout.width,o=t.layout.height,s=t.elements.filter((t=>t.id!==e.id&&!t.immutable&&!t.productOverlay)),r=s.map((e=>Z(e.x,e.y,e.width,e.height,e.rotation))),l=[],c=new Set;r.forEach((e=>c.add(e.minX))),r.forEach((e=>c.add(e.maxX))),[0,n/2,n].forEach((e=>c.add(e)));const d=new Set;r.forEach((e=>d.add(e.minY))),r.forEach((e=>d.add(e.maxY))),[0,o/2,o].forEach((e=>d.add(e)));const h=s.map((e=>e.y));for(let e=-315;e<=315;e+=45)h.push(e);const p=Z(e.x,e.y,e.width,e.height,e.rotation),u=[{value:p.minX,anchor:-1},{value:p.minX+(p.maxX-p.minX)/2,anchor:0},{value:p.minX+(p.maxX-p.minX),anchor:1}],m=[{value:p.minY,anchor:-1},{value:p.minY+(p.maxY-p.minY)/2,anchor:0},{value:p.minY+(p.maxY-p.minY),anchor:1}],f=[{value:e.rotation,anchor:0}],g=(e,t,i,s)=>{const r=[];return t.forEach((t=>{const l=i.find((e=>Q(t,e.value,2*a))),[c,d]=((e,t)=>[{x:"x"===e?t:0,y:"x"===e?0:t},{x:"x"===e?t:n,y:"x"===e?o:t}])(e,t),h="rotation"===e?null:q("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:s||"#D61B5C",strokeDasharray:5*a,strokeWidth:1.2*a,overflow:"overlay"},`${e}-${t}-${c.x}-${c.y}-${d.x}-${d.y}`);void 0!==l&&r.push({type:e,value:t,anchorPoint:l.anchor,svgNode:h,guidelineCoordinates:[c,d]})})),r};return l.push(...g("x",Array.from(c),u,i)),l.push(...g("y",Array.from(d),m,i)),l.push(...g("rotation",h,f,i)),l};let et;var tt;let at;var it;(tt=et||(et={})).Translate="Translate",tt.Rotate="Rotate",tt.Resize="Resize",(it=at||(at={})).ControlLeft="ControlLeft",it.ControlRight="ControlRight",it.Equal="Equal",it.MetaLeft="MetaLeft",it.MetaRight="MetaRight",it.Minus="Minus",it.ArrowLeft="ArrowLeft",it.ArrowRight="ArrowRight",it.ArrowUp="ArrowUp",it.ArrowDown="ArrowDown",it.AltLeft="AltLeft",it.AltRight="AltRight",it.Delete="Delete",it.Backspace="Backspace";const nt=(e,t,a,i)=>{const n=()=>{switch(a){case K.Pixel:return 1;case K.Millimeter:return _;case K.Centimeter:return J;default:throw new Error("Unknown unit of measurement")}};let o=t.x,s=t.y,r=t.x,l=t.y;switch(e){case at.ArrowLeft:r=t.x-1/n();break;case at.ArrowUp:l=t.y-1/n();break;case at.ArrowRight:r=t.x+1/n();break;case at.ArrowDown:l=t.y+1/n();break;default:throw new Error("Unhandled element interaction!")}const d=Z(r,l,t.width,t.height,t.rotation);return(!i||d.minX>=i.left&&d.maxX<=i.left+i.width&&d.minY>=i.top&&d.maxY<=i.top+i.height)&&(o=r,s=l),new c(t.id,o,s)};var ot=0,st=0,rt=0;const lt=(e,t,a,n,o,s,r)=>{const l=((e,t,a,i,n,o,s)=>{const r=i.width/t.width,l=i.height/t.height,c=e.movementX/r,d=e.movementY/l,h=a.rotation*Math.PI/180,p=Math.sin(h),u=Math.cos(h);let m;switch(n.type){case et.Resize:let t={top:a.y,left:a.x,width:a.width,height:a.height,rotation:a.rotation,fontSize:a.fontSize},f=t;switch(n.screenAxis){case H.North:{const e=-c*p+d*u,i=a.y+e,n=a.height-e,o=ee({...a}).center,s=ee({...a,y:i,height:n}).center,r=te(s,o,h),l=r.x-a.width/2,m=r.y-n/2;f={...t,left:l,top:m,height:n}}break;case H.East:{const e=c*u+d*p,i=a.width+e;let n=a.height;if(a.type===G.Textbox){const e=a;n=ne(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const o=ee({...a}).center,s=ee({...a,width:i,height:n}).center,r=te(s,o,h),l=r.x-i/2,m=r.y-n/2;f={...t,left:l,top:m,width:i,height:n}}break;case H.West:{const e=c*u+d*p,i=a.x+e,n=a.width-e;let o=a.height;if(a.type===G.Textbox){const e=a;o=ne(e.fontSize,e.fontData,e,e.input||e.text||"",e.lineHeight).requiredHeight}const s=ee({...a}).center,r=ee({...a,width:n,height:o,x:i}).center,l=te(r,s,h),m=l.x-n/2,g=l.y-o/2;f={...t,left:m,top:g,width:n,height:o}}break;case H.South:{const e=-c*p+d*u,i=a.height+e,n=ee({...a}).center,o=ee({...a,height:i}).center,s=te(o,n,h),r=s.x-a.width/2,l=s.y-i/2;f={...t,left:r,top:l,height:i}}break;case H.Northeast:{const e=c*u+d*p,i=a.width+e;let n=a.height+e,o=a.y-e,s=a.fontSize;if(a.type===G.Textbox){const t=a;s=t.fontSize+e/8,n=ne(s,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||oe;o=a.y-e*i/8}const r=ee({...a}).center,l=ee({...a,width:i,height:n,y:o}).center,m=te(l,r,h),g=m.x-i/2,w=m.y-n/2;f={...t,left:g,top:w,width:i,height:n,fontSize:s}}break;case H.Northwest:{const e=-c*u+-d*p,i=a.x-e,n=a.width+e;let o=a.y-e,s=a.height+e,r=a.fontSize;if(a.type===G.Textbox){const t=a;r=t.fontSize+e/8,s=ne(r,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight;const i=t.lineHeight||oe;o=a.y-e*i/8}const l=ee({...a}).center,m=ee({...a,x:i,y:o,width:n,height:s}).center,g=te(m,l,h),w=g.x-n/2,y=g.y-s/2;f={...t,left:w,top:y,width:n,height:s,fontSize:r}}break;case H.Southeast:{const e=c*u+d*p,i=a.width+e;let n=a.height+e,o=a.fontSize;if(a.type===G.Textbox){const t=a;o=t.fontSize+e/8,n=ne(o,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const s=ee({...a}).center,r=ee({...a,width:i,height:n}).center,l=te(r,s,h),m=l.x-i/2,g=l.y-n/2;f={...t,left:m,top:g,width:i,height:n,fontSize:o}}break;case H.Southwest:{const e=-c*u+-d*p,i=a.width+e;let n=a.x-e,o=a.height+e,s=a.fontSize;if(a.type===G.Textbox){const t=a;s=t.fontSize+e/8,o=ne(s,t.fontData,t,t.input||t.text||"",t.lineHeight).requiredHeight}const r=ee({...a}).center,l=ee({...a,width:i,height:o,x:n}).center,m=te(l,r,h),g=m.x-i/2,w=m.y-o/2;f={...t,left:g,top:w,width:i,height:o,fontSize:s}}}return m=Z(f.left,f.top,f.width,f.height,f.rotation),(!s||m.minX>=s.left&&m.maxX<=s.left+s.width&&m.minY>=s.top&&m.maxY<=s.top+s.height)&&(t=f),t;case et.Rotate:const g={x:e.clientX,y:e.clientY};let w,y=a.rotation;const v=ee(a,i,{x:r,y:l}),S=ae(g,v.c,v.d),b=ae(g,v.d,v.c);if(0===o.filter((e=>"rotation"===e.type)).length)rt=0,w=(a.rotation+S-b)%360;else{rt+=Math.sqrt(c**2+d**2);const e=Math.abs(rt)>_e/r;w=e?(a.rotation+S-b)%360:o.find((e=>"rotation"===e.type))?.value||0,e&&(rt=0)}return m=Z(a.x,a.y,a.width,a.height,w),(!s||m.minX>=s.left&&m.maxX<=s.left+s.width&&m.minY>=s.top&&m.maxY<=s.top+s.height)&&(y=w),{top:a.y,left:a.x,width:a.width,height:a.height,rotation:y};case et.Translate:let C,x,k=a.x,I=a.y;if(0===o.filter((e=>"rotation"!==e.type)).length)ot=0,st=0,C=a.x+c,x=a.y+d;else{const e=o.find((e=>"x"===e.type)),t=o.find((e=>"y"===e.type));e||(ot=0),t||(st=0);const i=Math.abs(ot)>_e/r,n=Math.abs(st)>_e/l;C=e?i?a.x+ot:a.x:a.x+c,x=t?n?a.y+st:a.y:a.y+d,ot=i?0:ot+c,st=n?0:st+d}return m=Z(C,x,a.width,a.height,a.rotation),(!s||m.minX>=s.left&&m.maxX<=s.left+s.width&&m.minY>=s.top&&m.maxY<=s.top+s.height)&&(k=C,I=x),{top:I,left:k,width:a.width,height:a.height,rotation:a.rotation}}})(e,t,a,n,o,s,r),u=[];if(a.type===G.Textbox){const e=a;u.push(new i(e.id,e.text||e.input||""))}if(u.push(new c(a.id,l.left,l.top),new d(a.id,l.width,l.height),new h(a.id,l.rotation)),a.type===G.Textbox){const e=a;l.fontSize&&e.fontSize!==l.fontSize&&u.push(new p(e.id,l.fontSize))}return u},ct=()=>{const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},dt=.5,ht=(e,t,a,i,n,o,s)=>{const{state:c,uiDispatcher:d}=T(Ge),{getLayoutById:h,getReducerState:p,flattenSequence:u}=$e(),[m,f]=V(void 0),[g,w]=V(void 0),y=h(c.layoutId);z((()=>{if("adjustment"===n&&e?.current&&i){if(i<.5)return void d(new Ze({zoom:.5}));if(i>c.maxZoom)return void d(new Ze({zoom:c.maxZoom}));d(new Ze({zoom:i}))}}),[i,d,e,n,c.maxZoom]);const v=j(((e,i)=>{d(new Ze({zoom:i}));const o=t?.current?.scrollWidth-t?.current?.clientWidth!=0,s=t?.current?.scrollHeight-t?.current?.clientHeight!=0;t.current&&a.current&&!c.scrolledMovement&&"advanced"===n&&(s&&(t.current.scrollTop=a.current.offsetTop+(t.current.scrollHeight-t.current.clientHeight)/2),o&&(t.current.scrollLeft=(a.current.offsetLeft+t.current.scrollWidth-t.current.clientWidth)/2))}),[d,t,a,c.scrolledMovement,n]);z((()=>{c.zoom<=1&&d(new Ze({scrolledMovement:!1}))}),[d,c.zoom]);const S=t?.current?.getBoundingClientRect(),b=((S?.width||1)+(S?.height||1))/2,C=(y.layoutState.layout.width+y.layoutState.layout.height)/2/b/c.zoom,x=F((()=>{const e=c.activeModifierKeys,t=c.elementEvent,a=e.includes(at.ControlLeft)||e.includes(at.MetaLeft)||e.includes(at.ControlRight)||e.includes(at.MetaRight);if(!c.selectedElement||!t||a)return[];const i=t&&t.type===et.Translate,n=t&&t.type===et.Rotate,o=y.layoutState.elements.find((e=>e.id===c.selectedElement));return(i||n)&&o?Je(o,y.layoutState,C,s):[]}),[c.selectedElement,c.elementEvent,c.activeModifierKeys,y.layoutState,C]),k=j((()=>{const e=ct();f(e),w(p().transaction)}),[p]),I=j((()=>{d(new Ze({selectedElement:void 0}))}),[d]),E=j((()=>{d(new Ze({scrolledMovement:!0}))}),[d]),N=j(((a,i)=>{const n=y.layoutState.elements.find((e=>e.id===c.selectedElement));if(!(c.elementEvent&&e.current&&t.current&&c.selectedElement&&n))return;t.current.hasPointerCapture(a.pointerId)||t.current.setPointerCapture(a.pointerId);const s=e.current.getBoundingClientRect(),l=new r(lt(a,y.layoutState.layout,n,s,c.elementEvent,x,i));l.sequenceId=m,o(l)}),[y.layoutState.elements,y.layoutState.layout,c.elementEvent,e,c.selectedElement,t,x,o]),R=j((e=>{d(new Ze({elementEvent:e}))}),[d]),O=j((()=>{d(new Ze({elementEvent:void 0})),m&&g&&(u(m,g),f(void 0),w(void 0))}),[d,m,g,u]),M=j(((e,t)=>{let a=c.zoom;const i=c.maxZoom,s=c.selectedElement,r=c.activeModifierKeys;if((r.includes(at.AltLeft)||r.includes(at.AltRight))&&(e.code===at.Equal||e.code===at.Minus)){const t=.05*i;e.code===at.Equal?d(new Ze({zoom:a+t<=i?a+=t:a})):d(new Ze({zoom:a-t>=.5?a-t:a}))}const h=y.layoutState.elements.find((e=>e.id===s));if(s&&h){if(e.code===at.MetaLeft||e.code===at.ControlLeft||e.code===at.MetaRight||e.code===at.ControlRight){const t=e.code,a=c.activeModifierKeys;if(!a.includes(t))return d(new Ze({activeModifierKeys:a.concat(t)}))}if(e.code===at.ArrowDown||e.code===at.ArrowUp||e.code===at.ArrowLeft||e.code===at.ArrowRight){d(new Ze({elementEvent:{type:et.Translate}}));const a=nt(e.code,h,c.units,t);o(a),d(new Ze({elementEvent:void 0}))}e.code!==at.Delete&&e.code!==at.Backspace||"advanced"!==n||(d(new Ze({selectedElement:void 0})),o(new l(h.id)))}}),[o,d,y.layoutState.elements,n,c.activeModifierKeys,c.maxZoom,c.selectedElement,c.units,c.zoom]),P=j((e=>{if(e.code===at.MetaLeft||e.code===at.ControlLeft||e.code===at.MetaRight||e.code===at.ControlRight){const t=c.activeModifierKeys,a=e.code;d(new Ze({activeModifierKeys:t.filter((e=>e!==a))}))}}),[d,c.activeModifierKeys]);return{guidelines:x,scale:C,zoomableElementRef:a,setElementEvent:R,handleZoom:v,handleKeyDown:M,handleKeyUp:P,handlePointerPressedBackground:I,handlePointerReleased:O,handlePointerMove:N,handleScroll:E,handleSequenceStart:k}},pt=e=>{const{x:t,y:a,cursorStyle:i,onPointerDown:n,handleClass:o,cornerRadius:s,color:r,strokeWidth:l}=e;return q("circle",{className:o,cx:t,cy:a,r:s,fill:"#ffffff",style:{cursor:i},stroke:r,strokeWidth:l,onPointerDown:n})},ut=e=>{const{x:t,y:a,width:i,height:n,cursorStyle:o,onPointerDown:s,edgeHandleRadius:r,color:l,strokeWidth:c}=e;return q("rect",{x:t,y:a,width:i,height:n,rx:r,fill:"#ffffff",style:{cursor:o},stroke:l,strokeWidth:c,onPointerDown:s})},mt=e=>{const{color:t,elementHeight:a,elementWidth:i,onBeginResize:n,rotation:o,scaleFactor:s,disableX:r,disableY:l}=e,c=7.5*s,d=3*s,h=28*s,p=6*s,u=1.2*s,m=a-2*c,f=j(((e,t,a)=>{e.stopPropagation(),n(t,a)}),[n]),g=j((e=>f(e,ie(H.West,360-o),H.West)),[f,o]),w=j((e=>f(e,ie(H.East,360-o),H.East)),[f,o]),y=j((e=>f(e,ie(H.North,360-o),H.North)),[f,o]),v=j((e=>f(e,ie(H.South,360-o),H.South)),[f,o]),S=j((e=>f(e,H.Northwest,H.Northwest)),[f]),b=j((e=>f(e,H.Northeast,H.Northeast)),[f]),C=j((e=>f(e,H.Southwest,H.Southwest)),[f]),x=j((e=>f(e,H.Northeast,H.Southeast)),[f]),k=h<=m;return $(B,{children:[q(pt,{x:0,y:0,cursorStyle:"nwse-resize",onPointerDown:S,handleClass:"cornerNorthWest",cornerRadius:c,color:t,strokeWidth:u}),k?q(pt,{x:i,y:0,cursorStyle:"nesw-resize",onPointerDown:b,handleClass:"cornerNorthEast",cornerRadius:c,color:t,strokeWidth:u}):void 0,k?q(pt,{x:i,y:a,cursorStyle:"nwse-resize",onPointerDown:x,handleClass:"cornerSouthEast",cornerRadius:c,color:t,strokeWidth:u}):void 0,k?q(pt,{x:0,y:a,cursorStyle:"nesw-resize",onPointerDown:C,handleClass:"cornerSouthWest",cornerRadius:c,color:t,strokeWidth:u}):void 0,k&&!r?q(ut,{x:-p/2,y:a/2-h/2,width:p,height:h,onPointerDown:g,edgeHandleRadius:d,cursorStyle:"ew-resize",color:t,strokeWidth:u}):void 0,k&&!l?q(ut,{x:i/2-h/2,y:a-p/2,width:h,height:p,onPointerDown:v,edgeHandleRadius:d,cursorStyle:"ns-resize",color:t,strokeWidth:u}):void 0,r?void 0:q(ut,{x:i-p/2,y:a/2-Math.min(h,.8*a)/2,width:p,height:Math.min(h,.8*a),onPointerDown:w,edgeHandleRadius:d,cursorStyle:"ew-resize",color:t,strokeWidth:u}),k&&!l?q(ut,{x:i/2-h/2,y:-p/2,width:h,height:p,onPointerDown:y,edgeHandleRadius:d,cursorStyle:"ns-resize",color:t,strokeWidth:u}):void 0]})},ft=e=>{const{color:t,elementWidth:a,onBeginRotate:i,scaleFactor:n}=e,o=j((e=>{e.stopPropagation(),i()}),[i]),s=10*n,r=1.2*n;return $("g",{children:[q("circle",{cx:a/2,cy:-2.5*s,r:1.3*s,fill:"rgba(0, 0, 0, 0.5)",opacity:.4,style:{cursor:"ew-resize"},onPointerDown:o}),q("circle",{cx:a/2,cy:-2.5*s,r:s,fill:"#fff",style:{cursor:"ew-resize"},stroke:t,strokeWidth:r,onPointerDown:o}),$("svg",{x:a/2-s,y:-2.5*s-s,xmlns:"http://www.w3.org/2000/svg",style:{cursor:"ew-resize"},height:2*s,viewBox:"0 0 24 24",width:2*s,fill:t,onPointerDown:o,children:[q("path",{d:"M0 0h24v24H0z",fill:"none"}),q("path",{d:"M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z"})]})]})},gt=e=>{const{color:t,height:a,highlighted:i,id:n,immutable:o,onBeginMove:s,onBeginResize:r,onBeginRotate:l,onPointerEnter:c,onPointerLeave:d,onSelected:h,pressed:p,rotation:u,scaleFactor:m,selected:f,width:g,x:w,y:y,disableX:v,disableY:S}=e,b=1.2*m,C=j((e=>{2===e.button&&(e.stopPropagation(),h(n,e)),0===e.button&&(e.stopPropagation(),!f&&h(n,e),s())}),[n,f,h,s]),x=j((()=>{c(n)}),[n,c]),k=j((()=>{d(n)}),[n,d]);return $("g",{transform:`translate(${w}, ${y}) rotate(${u} ${g/2} ${a/2})`,children:[q("rect",{className:"interactableInnerRect",width:g,height:a,stroke:f||i?t:"none",pointerEvents:o?"none":"visibleFill",fill:"none",strokeWidth:b,style:{cursor:o?void 0:f?p?"grabbing":"grab":"pointer"},onPointerDown:o?void 0:C,onPointerEnter:o?void 0:x,onPointerLeave:o?void 0:k}),f&&$(B,{children:[q(ft,{color:t,elementWidth:g,onBeginRotate:l,scaleFactor:m}),q(mt,{color:t,elementHeight:a,elementWidth:g,rotation:u,scaleFactor:m,onBeginResize:r,disableX:v,disableY:S})]})]})},wt=({primaryColor:e,containerHeight:t,containerWidth:a,customViewbox:i,editorRef:n,elementEvent:o,guidelines:s,layoutHeight:r,layoutWidth:l,targetedElements:c,scale:d,selectedElement:h,onElementEvent:p,onElementSelected:u,onSequenceStart:m})=>{const{state:f}=Qe(),{getLayoutById:g}=$e(),w=g(f.layoutId),[y,v]=V(void 0),S=j((e=>{v(e)}),[]),b=j((e=>{y===e&&v(void 0)}),[y]),C=j((()=>{m(),p({type:et.Translate})}),[p]),x=j(((e,t)=>{m(),p({type:et.Resize,relativeAxis:e,screenAxis:t})}),[p]),k=j((()=>{m(),p({type:et.Rotate})}),[p]),I=i||{x:0,y:0,width:l,height:r},E=d*(Math.sqrt(I.width*I.height)/1e3)*(100/Math.sqrt(t*a))*Math.sqrt((N=a/t,Math.exp(Math.abs(Math.log(N)))));var N;const R=w.layoutState.elements.findIndex((({id:e})=>e===h)),O=[...w.layoutState.elements];return R>=0&&O.push(O.splice(R,1)[0]),$("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",style:{touchAction:"none",position:"absolute",maxWidth:"100%",maxHeight:"100%"},width:"100%",height:"100%",viewBox:`${I.x} ${I.y} ${I.width} ${I.height}`,overflow:"overlay",children:[q("rect",{fill:"none",stroke:"none",ref:n,width:l,height:r}),s.map((e=>e.svgNode)),O.map((t=>{const a=void 0!==h&&t.id===h,i=a&&void 0!==o,n=void 0!==y&&t.id===y;return q(gt,{color:e,id:t.id,selected:a,highlighted:n,pressed:i,x:t.x,y:t.y,disableX:t.type===G.Frame,disableY:t.type===G.Textbox||t.type===G.Frame,width:t.width,height:t.height,rotation:t.rotation,immutable:t.immutable||c&&!c.includes(t.id),onSelected:u,onBeginMove:C,onBeginResize:x,onBeginRotate:k,onPointerEnter:S,onPointerLeave:b,scaleFactor:E},t.id)}))]})},yt=e=>{const{color:t,editorRef:a,zoomableElementRef:i,interactionElementRef:n,guidelines:o,isMakingAdjustments:s,viewmask:r,visibleLayoutId:l,xTranslation:c,yTranslation:d,targetedElements:h,borderRadius:p,handleContextMenu:u,handleKeyDown:m,handleKeyUp:f,handlePointerMove:g,handlePointerPressedBackground:w,handlePointerReleased:y,handleScroll:v,onSequenceStart:S,setElementEvent:b,onElementSelected:C}=e,{getLayoutById:x}=$e(),k=x(l),I=k.layoutState,{state:E}=Qe(),N=j((e=>{if(r){const t={left:r.x,top:r.y,width:r.width,height:r.height,panelId:"",rotation:0};return m(e,t)}return m(e)}),[m,r]),R=j((e=>{if(r){const t={left:r.x,top:r.y,width:r.width,height:r.height,panelId:"",rotation:0};return g(e,t)}return g(e)}),[g,r]);return q("div",{style:{justifyContent:"center",position:"relative",height:"100%",width:"100%",scrollbarWidth:"none",outline:"none"},onContextMenu:u,onKeyDown:N,onKeyUp:f,onPointerDown:w,onPointerMoveCapture:R,onPointerUp:y,onWheelCapture:v,ref:n,tabIndex:-1,children:$("div",{ref:i,style:{height:"100%",transform:`scale(${E.zoom}) translate(${c}px, ${d}px)`,display:"grid",filter:"drop-shadow(rgba(0, 0, 0, 0.2) 0px 0px 6px)"},children:[e.children,k.getComponentWithProps({height:s?"100%":"auto",maxHeight:"100%",maxWidth:"100%",position:"absolute",viewmask:r,width:s?"100%":"auto",borderRadius:p}),q(wt,{primaryColor:t,containerHeight:i.current?.offsetHeight||1024,containerWidth:i.current?.offsetWidth||1024,editorRef:a,elementEvent:E.elementEvent,guidelines:o,layoutHeight:I.layout.height,layoutWidth:I.layout.width,onElementEvent:b,onSequenceStart:S,onElementSelected:C,scale:10/E.zoom,selectedElement:E.selectedElement,targetedElements:h})]})})},vt=({color:e,borderRadius:t,guidelineColor:a,handleContextMenu:i,onElementSelected:n})=>{const{commandDispatcher:o,getLayoutById:r}=$e(),{state:l,uiDispatcher:c}=Qe(),d=W(null),h=W(null),p=W(null),{guidelines:u,handleKeyDown:m,handleKeyUp:f,handlePointerMove:g,handlePointerPressedBackground:w,handlePointerReleased:y,handleScroll:v,handleSequenceStart:S,setElementEvent:b}=ht(d,h,p,void 0,"advanced",o,a),C=j(((e,t)=>{const a=r(l.layoutId).layoutState.elements.find((t=>t.id===e));if(e&&a&&a.type===G.Textbox){const t=a.algorithm;(!t||t===Y.Autosize)&&o(new s(e,Y.Traditional))}n&&n(e,t),c(new Ze({selectedElement:e}))}),[o,r,l.layoutId,c]);return q(yt,{color:e,editorRef:d,interactionElementRef:h,zoomableElementRef:p,guidelines:u,visibleLayoutId:l.layoutId,xTranslation:0,yTranslation:0,borderRadius:t,handleContextMenu:i,handleKeyDown:m,handleKeyUp:f,handlePointerMove:g,handlePointerPressedBackground:w,handlePointerReleased:y,handleScroll:v,onSequenceStart:S,setElementEvent:b,onElementSelected:C})};function St(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const bt=new class{constructor(){St(this,"server",void 0),St(this,"cache",new Map),St(this,"materialCache",new Map),St(this,"loadImageAsFileInfo",(async e=>{const t=await e.arrayBuffer(),a=await re(t);return{name:e.name.substring(e.name.lastIndexOf("/")+1),blob:((e,t)=>{let a=atob(e.split(",")[1]),i=[];for(let e=0;e<a.length;e++)i.push(a.charCodeAt(e));return new Blob([new Uint8Array(i)],{type:t})})(a.dataUrl,e.type)}})),this.server=We}async getLocalOrFromServer(e){if(this.cache.has(e))return this.cache.get(e);const t=(async()=>(await We.execute("getAssetByKeyV2",{assetKey:e.replace(/\//g,"_")})).body)();return this.cache.set(e,t),t}async getMaterialLocalOrFromServer(e){if(this.materialCache.has(e))return this.materialCache.get(e);const t=(async()=>(await We.execute("getMaterialV2",{id:e})).body)();return this.materialCache.set(e,t),t}async uploadAssetWithProgress(e,t,a,i,n,o){const s=await this.dispatchCreateAssetRequest(e,t,n,o);var r=new XMLHttpRequest;return r.open("PUT",s.assetResponse.uploadUrl,!0),r.setRequestHeader("Content-Type",s.mimeType),r.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),r.upload.onprogress=e=>{e.lengthComputable&&a(100*e.loaded/e.total)},r.onload=()=>{const e=s.assetResponse.asset;i(e)},r.onerror=()=>{console.warn("Asset upload failed")},r.send(e.blob),s.assetResponse.asset}async dispatchCreateAssetRequest(e,t,a,i){const n=e.blob.type?e.blob.type:this.guessMIME(e.name);return{assetResponse:(await this.server.execute("createAsset",{assetDetails:{name:e.name,type:t,mimeType:n,storageOwnerId:i,userAnonymous:!0}},a)).body,mimeType:n}}guessMIME(e){const t=e.split(".").pop();switch(t){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new Error("Unexpected mimetype: "+t)}}};class Ct{get(e){return localStorage.getItem(e)||void 0}set(e,t){localStorage.setItem(e,t)}remove(e){localStorage.removeItem(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}class xt{constructor(){var e,t,a;e=this,t="storage",a=new Map,t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}get(e){return this.storage.get(e)||void 0}set(e,t){this.storage.set(e,t)}remove(e){this.storage.delete(e)}getMap(e){const t=this.get(e);if(t)return new Map(JSON.parse(t))}setMap(e,t){const a=JSON.stringify([...t.entries()]);this.set(e,a)}}const kt=(()=>{try{return localStorage?new Ct:new xt}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new xt}})(),It=M`
2
2
  mutation CreateTransaction($integrationProductId: String!, $bulk: Boolean) {
3
3
  transactionCreate(integrationProductId: $integrationProductId, bulk: $bulk) {
4
4
  id
@@ -14,7 +14,7 @@ import{CommandContext as e,getSvgString as t}from"papyrus/build/main/CommandCont
14
14
  bulkSourceUrl
15
15
  }
16
16
  }
17
- `,It=O`
17
+ `,Et=M`
18
18
  mutation ClaimTransaction($id: String!) {
19
19
  transactionClaim(id: $id) {
20
20
  id
@@ -33,7 +33,7 @@ import{CommandContext as e,getSvgString as t}from"papyrus/build/main/CommandCont
33
33
  }
34
34
  }
35
35
  }
36
- `,Et=O`
36
+ `,Nt=M`
37
37
  query ReadTransaction($id: String!) {
38
38
  transactions(ids: [$id]) {
39
39
  id
@@ -54,25 +54,25 @@ import{CommandContext as e,getSvgString as t}from"papyrus/build/main/CommandCont
54
54
  bulkSourceUrl
55
55
  }
56
56
  }
57
- `,Nt=O`
57
+ `,Rt=M`
58
58
  mutation UpdateTransactionWorkflowState($id: String!, $workflowState: String!) {
59
59
  transactionUpdate(id: $id, workflowState: $workflowState) {
60
60
  id
61
61
  }
62
62
  }
63
- `,Rt=O`
63
+ `,Ot=M`
64
64
  mutation UpdateTransactionWorkflowId($id: String!, $workflowId: String!) {
65
65
  transactionUpdate(id: $id, workflowId: $workflowId) {
66
66
  id
67
67
  }
68
68
  }
69
- `,Ot=O`
69
+ `,Mt=M`
70
70
  mutation UpdateVariationRecords($transactionId: String!, $updates: [VariationRecordUpdateInput]!) {
71
71
  variationRecordsUpdate(transactionId: $transactionId, updates: $updates) {
72
72
  recordNumber
73
73
  }
74
74
  }
75
- `,Mt=O`
75
+ `,Pt=M`
76
76
  query ReadTransactionForDesignCreation($id: String!) {
77
77
  transactions(ids: [$id]) {
78
78
  id
@@ -87,12 +87,12 @@ import{CommandContext as e,getSvgString as t}from"papyrus/build/main/CommandCont
87
87
  workflowViewerLink
88
88
  }
89
89
  }
90
- `,Pt=O`
90
+ `,Lt=M`
91
91
  query ReadWorkflowState($id: String!) {
92
92
  transactions(ids: [$id]) {
93
93
  id
94
94
  workflowState
95
95
  }
96
96
  }
97
- `;const Lt=new class{async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=i.data.variants,n=Le.getDefaultVariant(i.data);if(!e.data.allowMultipleSelections&&n){const n=a.find((e=>e.id===i.data.defaultVariant));return this.selectVariantLambda(e,n?.id||"",t)}}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(n&&a){const i=n.variants.find((e=>e.id===a));i&&await t.setSelectionsAndElements(e.stepName,[i],[])}}}selectVariant(e,t,a){this.selectVariantLambda(e,t,a).then((e=>e&&e()))}async selectVariantLambda(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;const n=i.data.variants,o=n.length>1?n.find((e=>e.id===t)):n[0];if(!o)throw new Error("Failed to find selected variant in step variants, this should never happen!");return async()=>{await a.setSelectionsAndElements(e.stepName,[o],[]),a.setMandatoryFulfilled(e.stepName,!0)}}};function Dt(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class At{constructor(e,t){Dt(this,"manager",void 0),Dt(this,"stepConfiguration",void 0),this.manager=e,this.stepConfiguration=t}getCurrentVariant(){return this.manager.getWorkflowSelections()[this.stepConfiguration.stepName].selections}async getAvailableVariants(){const e=this.stepConfiguration.optionId;return(await Le.getLocalOrFromServer(Fe,e)).data.variants}selectVariant(e){if(this.stepConfiguration.type!==ce.Question)throw new Error(`Step type ${this.stepConfiguration.type} not yet supported in Core SDK`);Lt.selectVariant(this.stepConfiguration,e.id,this.manager)}}const Tt=e=>{const t=[];for(const a of e.steps)switch(a.type){case ce.DigitalContent:a.data.varyUpload&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Upload});break;case ce.Frame:const e=a.data;e.varySelection&&a.optionId&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection}),e.varyUpload&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Upload});break;case ce.Illustration:const i=a.data;i.varySelection&&a.optionId&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection}),i.varyColors&&i.colourPickerEnabled&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Colors});break;case ce.Material:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection});break;case ce.Model:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection});break;case ce.Picture:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection});break;case ce.Question:a.data.varySelections&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selections});break;case ce.Shape:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection});break;case ce.Text:const n=a.data;n.varyText&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Text}),n.varySelection&&a.optionId&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Selection}),n.varyColor&&n.colourPickerEnabled&&t.push({stepName:a.stepName,stepType:a.type,aspectType:de.Color})}return t},zt=[ce.SilentIllustration,"ProductOverlay"],Vt=(e,t)=>{const a=[];e.introduction&&a.push({name:"Introduction",title:e.name,renderableSteps:[{type:ce.Introduction,stepName:"Introduction",stepTitle:e.name,helpText:e.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of e.steps){if(t.bulkScene){let e=!1;switch(i.type){case ce.DigitalContent:i.data.varyUpload&&(e=!0);break;case ce.Frame:const t=i.data;!t.varyUpload||!t.varySelection&&i.optionId||(e=!0);break;case ce.Illustration:const a=i.data;!a.varySelection&&i.optionId&&1!==Le.getLocalOrUndefined(i.optionId)?.data.variants.length||!a.varyColors&&a.colourPickerEnabled||(e=!0);break;case ce.Material:i.data.varySelection&&(e=!0);break;case ce.Model:i.data.varySelection&&(e=!0);break;case ce.Picture:i.data.varySelection&&(e=!0);break;case ce.Question:i.data.varySelections&&(e=!0);break;case ce.Shape:i.data.varySelection&&(e=!0);break;case ce.Text:const n=i.data;!n.varySelection&&i.optionId&&1!==Le.getLocalOrUndefined(i.optionId)?.data.variants.length||!n.varyColor&&n.colourPickerEnabled&&n.colourOptionId||!n.varyText||(e=!0)}if(e)continue}const n=Ut(i.stepName,e.stepGroups);if(n){const e=a.find((e=>e.name===n.name));e?zt.includes(i.type)?e.silentSteps.push(i):e.renderableSteps.push(i):a.push({name:n.name,title:n.name,renderableSteps:zt.includes(i.type)?[]:[i],silentSteps:zt.includes(i.type)?[i]:[]})}else a.push({name:i.stepName,title:i.stepTitle,renderableSteps:zt.includes(i.type)?[]:[i],silentSteps:zt.includes(i.type)?[i]:[]})}return t.bulkScene&&a.push({name:"Bulk",title:t.bulkSceneTitle,renderableSteps:[{type:ce.Bulk,stepName:"Bulk",stepTitle:t.bulkSceneTitle,helpText:"help:/billing/bulk-ordering.md",data:{aspects:Tt(e)},conditions:[]}],silentSteps:[]}),t.finishScene&&a.push({name:"Finish",title:t.finishSceneTitle,renderableSteps:[{type:ce.Finish,stepName:"Finish",stepTitle:t.finishSceneTitle,helpText:"",data:{modelAnimation:e.finalizeStepConfig?e.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:e.finalizeStepConfig?e.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),a},Ut=(e,t)=>t.find((t=>t.stepNames.includes(e))),Ft=(e,t)=>(e.conditions||[]).every((e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const t=a.selectedVariants;return e.requiredVariantSelections.some((e=>void 0!==t.find((t=>t.id===e))))}return!1})),Wt=(e,t)=>e.map((e=>((e,t)=>{const a={name:e.name,title:e.title,renderableSteps:e.renderableSteps.filter((e=>Ft(e,t))),silentSteps:e.silentSteps.filter((e=>Ft(e,t)))};return 0===a.silentSteps.length&&0===a.renderableSteps.length?null:a})(e,t))).filter((e=>null!==e)),jt=(e,t)=>Wt(e,t).filter((e=>e.renderableSteps.filter(((e,t,a)=>e.type===ce.Model||e.type===ce.Material||e.type===ce.Picture||e.type===ce.Shape?Le.getLocalOrUndefined(e.optionId)?.data.variants&&Le.getLocalOrUndefined(e.optionId).data.variants.length>1?e:null:e)).length>0)),qt=(e,t)=>Wt(e,t).filter((e=>e.renderableSteps.filter((e=>e)).length>0));function $t(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Bt{constructor(){$t(this,"timestamp",Date.now())}}class Kt{constructor(e){$t(this,"queue",[]),$t(this,"activePromise",void 0),$t(this,"queueMaxSize",void 0),this.queueMaxSize=e}enqueue(e){if(this.queue.push(e),void 0!==this.queueMaxSize&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let t=0;t<e;++t)this.queue.shift()}return this.process()}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async process(){return this.activePromise||(this.activePromise=this.dequeue(),this.activePromise.then((()=>{this.activePromise=void 0}))),this.activePromise}async dequeue(){const e=this.queue.shift();if(e)try{await e.execute(),await this.dequeue()}catch(e){await this.dequeue()}}}function Ht(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function Xt(e,t,a,i){const n=a.width*e.zoom,o=a.height*e.zoom;if(i){const i=e,n=Math.max(t.width/a.width,t.height/a.height);i.zoom=Math.max(n,e.zoom);const o=a.width*i.zoom,s=a.height*i.zoom;return i.x=Gt(e.x,t.width-o,0),i.y=Gt(e.y,t.height-s,0),i}const s=e;return s.x=Gt(s.x,-n,t.width),s.y=Gt(s.y,-o,t.height),s}function Gt(e,t,a){return Math.min(Math.max(e,t),a)}class Yt{constructor(e){Ht(this,"offsets",void 0),Ht(this,"forceImageCover",void 0),Ht(this,"targetElements",void 0),Ht(this,"imageData",void 0),Ht(this,"frameData",void 0),Ht(this,"_debouncedUpdateFrameOffsets",void 0),Ht(this,"minZoomScale",.03),Ht(this,"maxZoomScale",20),Ht(this,"onFrameDataChangeListeners",void 0),Ht(this,"onZoomChangeListeners",void 0),Ht(this,"workflowManager",void 0),Ht(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=ue(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=e}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback((async e=>{if(e){const t=e;if(t.currentFrameSource){const e=await me(t.currentFrameSource);H(e,this.frameData)||(this.frameData=e,this.onFrameDataChangeListeners.forEach((e=>e(this.frameData))),this.frameData&&this.imageData&&(this.offsets=fe(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}async setFrameData(e){const t=ge.get(e);this.frameData=t}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,a,i){if(this.imageData&&this.offsets&&this.frameData){const n=(t-this.offsets.x)/this.offsets.zoom,o=(a-this.offsets.y)/this.offsets.zoom,s={x:t-n*e,y:a-o*e,zoom:this.imageData.width*e/this.imageData.width};this.updateOffsets(Xt(s,this.frameData,this.imageData,this.forceImageCover),i),this.onZoomChangeListeners.forEach((t=>t(e)))}}setPatternData(e){(e&&this.frameData||e&&this.frameData&&!this.imageData)&&(this.offsets=fe(e,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.targetElements),this.updateOffsets(Xt(this.offsets,this.frameData,e,this.forceImageCover))),this.imageData=e,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t){const a=this.imageData;a&&this.frameData&&(this.offsets&&e.x===this.offsets.x&&e.y===this.offsets.y&&e.zoom===this.offsets.zoom?t&&t():(this.offsets=Xt(e,this.frameData,a,this.forceImageCover),this._debouncedUpdateFrameOffsets(e,a,this.frameData,this.targetElements,t)))}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}updateFrameOffsets(e,t,a,i,n){if(!a)throw new Error("Frame data not set. This is a bug");if(!this.workflowManager)throw new Error("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();i.forEach((a=>{o(new m(a,t,e))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:e}),n&&n()}recalculateZoomLimits(e,t){const a=Math.max(t.width/e.width,t.height/e.height);this.forceImageCover?(this.minZoomScale=a,this.maxZoomScale=2.5*a):(this.minZoomScale=a/10,this.maxZoomScale=2.5*a)}}const Zt=async e=>{const t=(new DOMParser).parseFromString(e,"image/svg+xml").firstElementChild;if(!t)throw new Error("Failed to read SVG");const a=(new XMLSerializer).serializeToString(t),i=document.createElement("canvas"),n=i.getContext("2d"),o=await le.from(n,a,{anonymousCrossOrigin:!0,ignoreDimensions:!1}),s=t.getAttribute("width"),r=t.getAttribute("height");if(r&&s){const e=parseFloat(r),t=parseFloat(s)/e;t>1?o.resize(2048,2048/t):o.resize(2048*t,2048)}else o.resize(2048,2048);return await o.render(),await(async e=>new Promise(((t,a)=>{try{e.toBlob((e=>{if(e){const a=URL.createObjectURL(e);t(a)}else a("Failed to generate canvas object URL")}))}catch(e){a(e)}})))(i)},Qt=new class{async getIllustrationBody(e){return new Promise((t=>{fetch(e).then((e=>{t(e.text())})).catch((e=>console.error(e)))}))}getCreateElementCommand(e,t,i,n){return new a({stepRegion:t,stepName:n.stepName,colors:n.svg.colors,id:e,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:X.Illustration,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layerIndex:t.layerIndex,immutable:t.immutable},i)}async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)return this.reload(e,t,a);{t.updateMetadata(e.stepName,{colors:[]});const a=Le.getDefaultVariant(i.data);if(a)return this.selectVariantCommand(e,a,[],(()=>{}),t)}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(!o||!a)throw new Error("Required illustration variant no longer available");{const s=o.variants.find((e=>e.id===a));if(s){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[s],a),t.updateMetadata(e.stepName,{colors:i.storage?.colors}),t.setMandatoryFulfilled(e.stepName,!0)}}}return null}availableColors(e){return Le.getLocalOrUndefined(e.data.colourOptionId)?Le.getLocalOrUndefined(e.data.colourOptionId).data.variants.map((e=>({fill:e.color,stroke:e.color,variant:e}))):(e.data.colours||[]).map((e=>({fill:e,stroke:e})))}async changeColorsCommand(e,t,a,i,n){const o={};for(const[e,t]of n.entries())o[e]={browserValue:t,spotColor:o[e]?.spotColor};const s=be(e,t,a,o),l=await Zt(s),c=[];for(const e of i){for(const[t,a]of n.entries())c.push(new f(e,t,a));c.push(new g(e,s,l))}return new r(c)}async changeColors(e,t,a,i,n){if(0===t.length)return;const o=xe(t[0].id,i().map((e=>e.layoutState))),s={...o.colors},r={};Object.entries(s).forEach((([e,t])=>{const a={browserValue:t.browserValue},i=t.spotColor;i&&(a.spotColor={profileName:i.profileName,namedColor:i.namedColor}),r[e]=a}));for(const[e,t]of n.entries())s[e]={browserValue:t,spotColor:s[e]?.spotColor},r[e]={browserValue:t};a.updateStorage(e.stepName,{colors:r});let l=Array.from(Object.values(s)).map((e=>e.browserValue));Le.getLocalOrUndefined(e.data.colourOptionId)&&Le.getLocalOrUndefined(e.data.colourOptionId).data.variants.forEach((e=>{l=l.map((t=>t.toLowerCase()===e.color?.toLowerCase()?e.name:t))})),a.updateMetadata(e.stepName,{colors:l});const c=new Map;if(Object.entries(s).forEach((([e,t])=>{c.set(e,t.browserValue)})),!o.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const d=await this.changeColorsCommand(o.svg,o.width,o.height,t.map((e=>e.id)),c);a.getCommandDispatcher()(d)}selectVariant(e,t,a,i,n){this.selectVariantCommand(e,t,a,i,n).then((e=>{n.getCommandDispatcher()(e.command),e.followup()}))}selectVariantCommand(e,t,a,i,n){if(!e.data||!e.data.regions)throw new Error("Missing config data.");i(!0);const o=a.map((e=>new l(e.id)));return n.setMandatoryFulfilled(e.stepName,!1),new Promise((async a=>{if(!t.assetKey)throw new Error("No Asset for Variant");const s=(await St.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));if(!s)throw new Error("CDN Link not found on SVG Asset entity!");const l=await Se(await this.getIllustrationBody(s.href)),c=await Zt(l.svg),d=e.data.regions.map((t=>{const a=n.getLayouts().find((e=>e.panelId===t.panelId));if(!a)throw new Error("Tried to create illustration but no layout.");const i=lt();return{regionElement:{id:i,region:t},command:this.getCreateElementCommand(i,t,a,{stepName:e.stepName,src:s.href,objectURL:c,svg:l})}})),h=[...d.map((e=>e.command)),...o];a({command:new r(h),followup:async()=>{await n.setSelectionsAndElements(e.stepName,[t],d.map((e=>e.regionElement))),n.setMandatoryFulfilled(e.stepName,!0),i(!1)}})}))}};function _t(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Jt{constructor(e,t,i){_t(this,"configuration",void 0),_t(this,"layouts",void 0),_t(this,"product",void 0),_t(this,"processRegion",(async e=>{const t=this.layouts.find((t=>t.panelId===e.panelId));if(!t)throw new Error(`Can not find layout for region: ${e.panelId}`);let i="";if("ProductOverlay"===this.configuration.type){let e="";if(this.product?.overlayImageUrl&&(e=this.product.overlayImageUrl),i=e,!e)throw new Error("Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if("image"===n){const i="SilentIllustration"===this.configuration.type?this.configuration.data.assetKey:this.product?.overlayImageUrl,o={id:lt(),src:i,type:n,y:e.top,x:e.left,width:e.width,height:e.height,layerIndex:e.layerIndex,immutable:e.immutable,productOverlay:"ProductOverlay"===this.configuration.type||void 0,rotation:e.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:o.id,region:e},command:new a(o,t)}}{const o="SilentIllustration"===this.configuration.type?this.configuration.data.assetKey:i,s=async()=>new Promise((e=>{fetch(o).then((t=>{e(t.text())})).catch((e=>console.error(e)))})),r=await Se(await s()),l={id:lt(),cachedObjectURL:await Zt(r.svg),src:o,svg:r.svg,colors:r.colors,type:n,y:e.top,x:e.left,width:e.width,height:e.height,layerIndex:e.layerIndex,rotation:e.rotation,immutable:e.immutable,productOverlay:"ProductOverlay"===this.configuration.type||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:l.id,region:e},command:new a(l,t)}}})),this.configuration=e,this.layouts=t,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new Error("Missing regions.");if("SilentIllustration"===this.configuration.type){const e=this.configuration.data.regions.map(this.processRegion);return Promise.all(e)}return"ProductOverlay"===this.configuration.type?Promise.all(this.configuration.data.regions.map((e=>{if(!this.layouts.find((t=>e.panelId===t.panelId)))throw new Error("Can't find layout from region. This is a bug");return this.processRegion(e)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const e="ProductOverlay"===this.configuration.type&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.assetKey?.toLowerCase().split("?")[0];return e?.endsWith(".jpeg")||e?.endsWith(".jpg")||e?.endsWith(".png")?X.Image:(e?.endsWith(".svg"),X.Illustration)}}const ea=async e=>{const t=`${Ae.getServicesApiUrl()}/shortener`;try{const a=await fetch(t,{method:"POST",body:JSON.stringify({longUrl:e}),headers:{"Content-Type":"application/json"}});return(await a.json()).shortUrl}catch(e){throw console.error(e),new Error("Failed to shorten URL.")}};function ta(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class aa{async poll(){if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId));this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(e,t,a,i=3e3,n=10){ta(this,"pollingId",void 0),ta(this,"attempts",void 0),ta(this,"interval",void 0),ta(this,"maxAttempts",void 0),ta(this,"predicate",void 0),ta(this,"onSuccess",void 0),ta(this,"onFailure",void 0),this.onSuccess=t,this.onFailure=a,this.predicate=e,this.attempts=0,this.pollingId=-1,this.interval=i,this.maxAttempts=n,this.poll()}}const ia=new class{async init(e,t,a){return a&&await this.reload(e,t,a),null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)).map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[],n);const o=i?.storage?.videoShortUrl,s=i?.storage?.videoUrl;t.updateStorage(e.stepName,{videoShortUrl:o,videoUrl:s})}async regenerateQRCode(e,t,a,i,n,o,s,r,c){if(!t&&""!==a&&""===i){const t=async()=>(await Fe.execute("getAssetByKeyV2_private",{assetKey:a.replace(/\//g,"_")})).body.links.find((e=>"mpeg4"===e.rel)),c=await new Promise(((e,a)=>{new aa((async()=>!!await t()),(async()=>{const a=await t();if(!a||!a.href)throw new Error("Poller succeeded but no mpeg link found");e(a)}),(()=>{a("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));e.forEach((e=>r(new l(e.id))));const d="http"===o.data.baseUrl.slice(0,4)?"":"https://",h=new URL(d+o.data.baseUrl);h.searchParams.append("video",btoa(JSON.stringify([c]))),h.pathname=h.pathname+("/"===h.pathname.slice(-1)?"":"/");const p=h.toString();if(p.length>=2e3)throw new Error("Cannot create QR code, URL too long.");const u=await ea(p);if(s(u),!o.data||!o.data.regions)throw new Error("Missing config data.");const m=await this.regionElements(o),f=await this.command(u,m,n,o.stepName);f&&r(f.command),await n.setSelectionsAndElements(o.stepName,[],m),n.updateStorage(o.stepName,{videoShortUrl:u,videoUrl:i})}c(!1)}async regionElements(e){return e.data.regions.map((e=>({id:lt(),region:e})))}async command(e,t,i,n){const o=i.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Ie(e,{type:"svg"}))}`,l=t.map((e=>{const t=e.region,i=o.find((e=>e.panelId===t?.panelId));if(!i||!t)throw new Error(`Can not find layout for region: ${t?.panelId}`);return new a({stepRegion:t,stepName:n,id:e.id,src:s,type:X.Image,y:t.top,x:t.left,width:t.width,height:t.height,rotation:0},i)}));return{command:new r(l),followup:async()=>{}}}};const na=new class{constructor(){var e,t,a;a=async(e,t)=>{if(!e)return we(t.data.regions[0]);if(!e.assetKey)throw new Error("No Asset for Variant");const a=(await St.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel));if(a)return Ee(a.href);throw new Error("No URL for frame!")},(t="frameSourceSvg")in(e=this)?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(a)await this.reload(e,t,a);else{if(t.setMandatoryFulfilled(e.stepName,!1),t.markStepsAsInitialised([e.stepName]),!i||0===i.data.variants.length)return this.selectVariantCommand(e,void 0,[],t,void 0,e.data.placeholderImageKey);{const a=Le.getDefaultVariant(i.data);if(a)return this.selectVariantCommand(e,a,[],t,void 0,e.data.placeholderImageKey)}}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)).map((e=>({id:e.id,region:e.stepRegion}))),o=Le.getLocalOrUndefined(e.optionId)?.data;if(!o||0===o.variants.length){const a=we(e.data.regions[0]);t.updateStorage(e.stepName,{currentFrameSource:a})}if(i){if(i.selectedVariants&&i.selectedVariants.length>0){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){await t.setSelectionsAndElements(e.stepName,[i],n);const a=await this.frameSourceSvg(i,e);t.updateStorage(e.stepName,{currentFrameSource:a})}}}else await t.setSelectionsAndElements(e.stepName,[],n);const a=i.storage?.framePatternSrc,s=i.storage?.frameOffsets;if(t.updateMetadata(e.stepName,{frameOffsets:s,framePatternSrc:a}),a){const i=t.getStepSpecificServices(e.stepName)?.frameService;await this.loadPatternFromString(a,i),t.updateMetadata(e.stepName,{image:a}),t.updateStorage(e.stepName,{framePatternSrc:a})}if(s?.zoom){const a=t.getStepSpecificServices(e.stepName)?.frameService;a.updateOffsets(s)}t.setMandatoryFulfilled(e.stepName,!0)}}selectImage(e,t,a){a.setEditedStatus(e.stepName,!0);t.links.find((e=>"cdn"===e.rel)).href.endsWith("pdf")?a.addPoller(new aa((async()=>{const e=(await Fe.execute("getAssetByKeyV2_private",{assetKey:t.data.key.replace(/\//g,"_")})).body.links.find((e=>"svg"===e.rel));if(!e)return!1;return 200===(await fetch(e.href)).status}),(()=>{Fe.execute("getAssetByKeyV2_private",{assetKey:t.data.key.replace(/\//g,"_")}).then((t=>{const i=t.body;this.loadPatternFromAsset(i,e,a)}))}),(()=>{throw new Error("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(t,e,a)}selectVariant(e,t,a,i,n){this.selectVariantCommand(e,t,a,i,n).then((e=>{i.getCommandDispatcher()(e.command),e.followup()}))}getCreateElementCommand(e,t,i,n){return new a({id:e,type:X.Frame,x:t.left,y:t.top,width:t.width,height:t.height,layerIndex:t.layerIndex,rotation:t.rotation,scaleX:t.width/n.frameData.width,scaleY:t.height/n.frameData.height,path:n.frameData.path,stepRegion:t,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:t.immutable},i)}async loadPatternFromString(e,t){if(e.endsWith("svg")){const a=await ye(e),i=a.width,n=a.height,o={src:e,width:i,height:n,aspect:i/n};ve.set(e,o),t.setPatternData(o)}else{const a=await fetch(e),i=await a.arrayBuffer(),n=await se(i),o={src:e,width:n.width,height:n.height,aspect:n.width/n.height};ve.set(e,o),t.setPatternData(o)}}async selectVariantCommand(e,t,a,i,n,o){const s=i.getStepSpecificServices(e.stepName)?.frameService,c=await this.frameSourceSvg(t,e),d=await me(c),h=s.getImageData(),p=a.map((e=>new l(e.id))),u=h?fe(h,d):void 0,m=h?{id:lt(),src:h.src,x:u?.x||0,y:u?.y||0,width:h.width,height:h.height,scaleX:u?.zoom||1,scaleY:u?.zoom||1,rotation:0}:void 0;n&&n(!0);const f=e.data.regions.map((t=>{const a=lt(),n=i.getLayouts().find((e=>e.panelId===t.panelId));if(!n)throw new Error(`Can not find layout for region: ${t.panelId}`);return{command:this.getCreateElementCommand(a,t,n,{frameData:d,pattern:m,disablePlaceholder:e.data.disablePlaceholder,focalBlur:e.data.focalBlur,focalBlurStrength:e.data.focalBlurStrength,focalBlurRadius:e.data.focalBlurRadius,stepName:e.stepName}),regionEl:{id:a,region:t}}})),g=f.map((e=>e.command));return{command:new r([...g,...p]),followup:async()=>{if(n&&n(!1),await i.setSelectionsAndElements(e.stepName,t?[t]:[],[...f.map((e=>e.regionEl))]),i.updateStorage(e.stepName,{currentFrameSource:c}),o){const t=i.getStepSpecificServices(e.stepName)?.frameService;await this.loadPatternFromString(o,t)}}}}patternSource(e){const t=e.links.find((e=>"svg"===e.rel));if(t)return t.href;const a=e.links.find((e=>"cdn"===e.rel));if(a)return a.href;throw new Error("Frame pattern source file could not be find, neither svg or cdn assets existed on requested variant!")}async loadPatternFromAsset(e,t,a){const i=this.patternSource(e),n=lt();a.markUpdatePending(n);const o=a.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(i,o),a.updateMetadata(t.stepName,{image:i}),a.updateStorage(t.stepName,{framePatternSrc:i}),a.markUpdateCompleted(n)}};const oa=new class{async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=Le.getDefaultVariant(i.data);if(a)return this.selectVariantLambda(e,a,t,(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=await St.getMaterialLocalOrFromServer(i.materialId),o=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],o);const s=t.getPreviewService();if(s){const i=e.data.targetMaterials.map((t=>s.applyMaterialVariant(t,e.optionId,a.data)));Promise.all(i).then((()=>t.setMandatoryFulfilled(e.stepName,!0)))}}}}}selectVariant(e,t,a,i){this.selectVariantLambda(e,t,a,i).then((e=>e&&e()))}async selectVariantLambda(e,t,a,i){const n=a.getPreviewService();if(!n)return null;i(!0);const o=await St.getMaterialLocalOrFromServer(t.materialId);if(!o)throw i(!1),new Error("No material set on variant");return async()=>{await a.setSelectionsAndElements(e.stepName,[t],[]);const s=e.data.targetMaterials.map((t=>n.applyMaterialVariant(t,e.optionId,o.data)));Promise.all(s).then((()=>a.setMandatoryFulfilled(e.stepName,!0))).finally((()=>i(!1)))}}};const sa=new class{async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=Le.getDefaultVariant(i.data);if(a)return this.selectVariantLambda(e,a,t,(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],a);const o=t.getPreviewService();if(o){if(!i.assetKey)throw new Error("No Asset for Variant");const a=(await St.getLocalOrFromServer(i.assetKey)).links.find((e=>"cdn"===e.rel));o.applyModelVariant(e.optionId,{model:a.href,contextService:t.getLayoutPreviewService()},e.data.replaceProductModel||!1).then((()=>{t.setMandatoryFulfilled(e.stepName,!0)}))}}}}}selectVariant(e,t,a,i){this.selectVariantLambda(e,t,a,i).then((e=>e&&e()))}async selectVariantLambda(e,t,a,i){const n=a.getPreviewService();if(!n)return null;if(i(!0),!t.assetKey)throw new Error("No Asset for Variant");const o=(await St.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));return async()=>{if(await a.setSelectionsAndElements(e.stepName,[t],[]),!o)throw new Error("Asset not found:"+t.assetKey);n.applyModelVariant(e.optionId,{model:o.href,contextService:a.getLayoutPreviewService()},e.data.replaceProductModel||!1).then((()=>{a.setMandatoryFulfilled(e.stepName,!0)})).finally((()=>i(!1)))}}};const ra=new class{async init(e,t,a){return a?(await this.reload(e,t,a),null):(t.updateMetadata(e.stepName,{text:""}),this.changeTextCommand(e,"",t,"",(()=>{})))}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)).map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[],n),t.updateStorage(e.stepName,{text:i?.storage?.text}),t.setMandatoryFulfilled(e.stepName,""!==i?.storage?.text)}changeText(e,t,a,i,n){this.changeTextCommand(e,t,a,i,n).then((e=>{e&&(a.getCommandDispatcher()(e.command),e.followup())}))}async changeTextCommand(e,t,i,n,o){const s=i.getRegionElements(e.stepName),c=i.getStepSpecificServices(e.stepName)?.module;if(!c)return console.error("Missing module."),null;const d=i.getProfanities();if(!this.validateInput(e,t,d,o))return i.setMandatoryFulfilled(e.stepName,!1),console.error(n),null;if(i.setMandatoryFulfilled(e.stepName,""!==t),!e.data||!e.data.regions||e.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(e.stepName,{text:t});const h=(t,n,o)=>{const s=o||lt(),c=i.getLayouts().find((e=>e.panelId===n.panelId));if(!c)return console.error(`Can not find layout for region: ${n.panelId}`),null;const d=[];return o&&d.push(new l(s)),d.push(new a({stepRegion:n,stepName:e.stepName,colors:{},id:s,svg:t,type:X.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layerIndex:n.layerIndex,immutable:n.immutable},c)),{id:s,region:n,command:new r(d)}},p=c.svgPrint(t);if(s.length>0){const e=s.map((e=>e.region?h(p,e.region,e.id):null)).filter((e=>!!e)).filter((e=>!!e)).map((e=>e&&e.command));return{command:new r(e),followup:async()=>{}}}{const t=e.data.regions.map((e=>h(p,e))),a=t.filter((e=>!!e)).map((e=>e&&e.command));return{command:new r(a),followup:async()=>{const a=t.filter((e=>e)).map((e=>e&&{id:e.id,region:e.region}));await i.setSelectionsAndElements(e.stepName,[],a)}}}}validateInput(e,t,a,i){if(e.data&&e.data.maxLength){const a=e.data.maxLength;if(t.length>a)return i("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(t))return i("Unsupported characters."),!1;const n=t.toLowerCase();for(const e in a)if(n===a[e].toLowerCase().trim()&&""!==n)return i("Blocked profanity."),!1;return i(""),!0}};const la=e=>new Promise((t=>{fetch(e).then((e=>e.text())).then((e=>{t(e)})).catch((e=>console.error(e)))})),ca=e=>{const t=e.match(/<svg.*?<\/svg>/s)||[],a=t?.length>0?t[0]:"",i=(new DOMParser).parseFromString(a,"image/svg+xml").firstElementChild;if(!i)throw new Error("Failed to read SVG.");Ce(i,!0);return(new XMLSerializer).serializeToString(i)},da=new class{async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return console.error(`Patchwork step ${e.stepName} is missing option.`),null;if(a)await this.reload(e,t,a);else{const a=Le.getDefaultVariant(i.data);if(a&&a.assetKey)return this.selectVariantCommand(e,a,[],t,(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const s=o.variants.find((e=>e.id===a));if(s){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[s],a),t.updateStorage(e.stepName,{patchworkOffsets:i.storage?.patchworkOffsets}),t.setMandatoryFulfilled(e.stepName,!0)}}}}recalculate(e,t,a,i){const n=a.getCommandDispatcher();var o;i(!0);const s=t.map((e=>e.region?this.getRandomPosition(e.region):null)).filter((e=>!!e));n(new r(t.map(((e,t)=>{const a=s[t];return 0===t&&(o=a),new w(e.id,a.scale,-a.xOffset,-a.yOffset)})))),o&&a.updateStorage(e.stepName,{patchworkOffsets:s}),i(!1)}selectVariant(e,t,a,i,n){this.selectVariantCommand(e,t,a,i,n).then((e=>{e&&(i.getCommandDispatcher()(e.command),e.followup())}))}async selectVariantCommand(e,t,i,n,o){if(!t.assetKey)throw new Error("No Asset for Variant");const s=(await St.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));if(!s)throw new Error("Could not find CDN link for patchwork.");if(!e.data||!e.data.regions)return console.error("Trying to update patchwork in design with no region data"),null;o(!0);const c=s.href,d=n.getLayouts();var h;const p=e.data.regions.map((e=>this.getRandomPosition(e))),u=await la(c),m=ca(u),f=e.data.regions.map(((t,i)=>((t,i,n)=>{const o=d.find((e=>e.panelId===t.panelId));if(!o)throw new Error("Can't find layout");const s=p[i],r=lt();return 0===i&&(h=s),{regionElement:{id:r,region:t},command:new a({stepRegion:t,stepName:e.stepName,id:r,svg:n,type:X.Patchwork,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layerIndex:t.layerIndex,immutable:t.immutable,patchX:-s.xOffset,patchY:-s.yOffset,patchScale:s.scale},o)}})(t,i,m))),g=i.map((e=>new l(e.id))),w=f.map((e=>e.command));return{command:new r([...g,...w]),followup:async()=>{await n.setSelectionsAndElements(e.stepName,[t],f.map((e=>e.regionElement))),h&&n.updateStorage(e.stepName,{patchworkOffsets:p}),o(!1)}}}getRandomPosition(e){const t=Math.random()*(.7-.25)+.25,a=1/t,i=1-t;return{scale:a,xOffset:Math.random()*i*a*e.width,yOffset:Math.random()*i*a*e.height}}constructPreviewSvg(e,t,a,i){if(!i||0===t.length)return null;try{const n=xe(t[0].id,a().map((e=>e.layoutState))).svg,o=e.data.regions[0],s={x:0,y:0,width:o.width,height:o.height,rotation:0,id:"patchwork-preview",svg:n,patchX:-i.xOffset,patchY:-i.yOffset,patchScale:i.scale},r=j(Re,{...s}),l=Ne.renderToStaticMarkup(r);return`\n <svg\n version="1.1"\n xmlns="http://www.w3.org/2000/svg"\n xmlns:xlink="http://www.w3.org/1999/xlink"\n width="${s.width}px"\n height="${s.height}px"\n viewBox="0 0 ${s.width} ${s.height}"\n >\n ${l}\n </svg>\n `}catch(e){return null}}};const ha=new class{async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId)?.data;if(!i)return null;if(a)await this.reload(e,t,a);else if(i.defaultVariant){const a=i.defaultVariant,n=i.variants.find((e=>!!e.assetKey&&e.id===a));if(n)return t.markStepsAsInitialised([e.stepName]),this.selectVariantCommand(e,n,t,(()=>{}))}return t.markStepsAsInitialised([e.stepName]),null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],a),t.setMandatoryFulfilled(e.stepName,!0)}}}}selectVariant(e,t,a,i){this.selectVariantCommand(e,t,a,i).then((e=>{e&&(a.getCommandDispatcher()(e.command),e.followup())}))}async selectVariantCommand(e,t,i,n){if(!t.assetKey)throw new Error("No Asset for Variant");const o=(await St.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));if(!o)return console.error("No URL for picture!"),null;const s=o.href;n(!0),i.setMandatoryFulfilled(e.stepName,!1);const c=i.getRegionElements(e.stepName).map((e=>new l(e.id))),d=e.data.regions.map((t=>{const n=i.getLayouts().find((e=>e.panelId===t.panelId));if(!n)throw new Error(`Can not find layout for region: ${t.panelId}`);const o=lt();return{regionElement:{id:o,region:t},command:new a({stepName:e.stepName,stepRegion:t,id:o,src:s,type:X.Image,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layerIndex:t.layerIndex,immutable:t.immutable,preserveAspectRatio:"none"},n)}}));return{command:new r([...c,...d.map((e=>e.command))]),followup:async()=>{await i.setSelectionsAndElements(e.stepName,[t],d.map((e=>e.regionElement))),i.setMandatoryFulfilled(e.stepName,!0),n(!1)}}}};const pa=new class{colourOptions(e){return Le.getLocalOrUndefined(e.optionId)?Le.getLocalOrUndefined(e.optionId).data.variants.map((e=>({fill:e.color,stroke:e.color,variant:e}))):e.data.colours.length>0?e.data.colours.map((e=>({fill:e,stroke:e}))):[]}async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;if(!a){const a=Le.getDefaultVariant(i.data);if(!a)return null;const n={fill:a.color,stroke:a.color,variant:a};return this.selectVariantCommand(e,n,[],t)}return await this.reload(e,t,a),null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=Le.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],a),t.updateStorage(e.stepName,{colour:i.color||""}),t.setMandatoryFulfilled(e.stepName,!0)}}}}selectVariant(e,t,a,i){this.selectVariantCommand(e,t,a,i).then((e=>{e&&(i.getCommandDispatcher()(e.command),e.followup())}))}async selectVariantCommand(e,t,i,n){const o=n.getLayouts();if(i.length>0){const a=a=>{const i=a.region;if(!o.find((e=>e.panelId===i?.panelId)))return console.error(`Step ${e.stepName} missing layout for panel: ${i?.panelId}.`),null;const n=t.variant?.color;return n?new f(a.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},s=i.map(a).filter((e=>!!e));return{command:new r(s),followup:async()=>{n.setSelectionsAndElements(e.stepName,t.variant?[t.variant]:[],i),n.updateStorage(e.stepName,{colour:t.fill||""})}}}{const i=i=>{const n=o.find((e=>e.panelId===i.panelId));if(!n)return console.error(`Step ${e.stepName} missing layout for panel: ${i.panelId}.`),null;const s=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${t.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:t.variant.color};const l=lt();return{id:l,region:i,command:new a({stepRegion:i,stepName:e.stepName,colors:r,id:l,svg:s,type:X.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:e.data.excludeFromPrint},n)}},s=e.data.regions.map(i),l=s.filter((e=>!!e)).map((e=>e?.command)),c=s.filter((e=>!!e)).map((e=>({id:e.id,region:e.region})));return{command:new r(l),followup:async()=>{await n.setSelectionsAndElements(e.stepName,t.variant?[t.variant]:[],c),n.updateStorage(e.stepName,{colour:t.fill||""})}}}}};function ua(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const ma=new class{constructor(){ua(this,"latestToast",void 0),ua(this,"toastType",void 0),ua(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(e){e({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(e)}setLatestToast(e,t){this.latestToast=e,this.toastType=t,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((e=>e({toastMessage:this.latestToast,toastType:this.toastType})))}};function fa(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class ga extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=ga.name}}class wa extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=wa.name}}const ya=new class{constructor(){fa(this,"cachedColors",new Map),fa(this,"filterUnsupportedCharacters",((e,t)=>{let a=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const i=[],n=e?.fontData?x(e?.fontData):void 0;if(n){const e=a.split("").map((e=>n.getFont().charToGlyph(e)));for(let t=0;t<e.length;t++){const n=".notdef"===e[t].name;"\n"===a.charAt(t)||n&&i.push(String.fromCharCode(a.charCodeAt(t)))}}for(let e=0;e<i.length;e++)a=a.replaceAll(i[e],"");return a})),fa(this,"getErrorsForText",((e,t,a)=>{const i=[];t.data&&t.data.maxLength&&e.length>t.data.maxLength&&i.push({localizationKey:"workflow.steps.text.characterLimit"});const n=a.getProfanities(),o=e.toLowerCase();if(""!==o)for(const e in n){if(o===n[e].toLowerCase().trim()){i.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!t.data.allowNewlines&&(e.includes("\n")||e.includes("\r"))&&i.push({localizationKey:"workflow.steps.text.multipleLines"}),i})),fa(this,"textAlign",(e=>e.vertical?"center":e.textAlign||"center"))}async init(e,t,a){const i=Le.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=e.data.defaultText||"";t.updateStorage(e.stepName,{inputText:a});this.getDefaultColor(e.data)&&t.updateMetadata(e.stepName,{color:e.data.colour});const n=Le.getDefaultVariant(i.data);if(n)return this.selectVariantCommand(e,n,{},[],t,!1,(()=>{}),(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=(await Le.getLocalOrFromServer(Fe,e.optionId))?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const s=o.variants.find((e=>e.id===a));if(s){const a=await this.fontDataFromVariant(s),o=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[s],o),t.updateMetadata(e.stepName,{color:i.storage?.color,text:i.storage?.text}),t.updateStorage(e.stepName,{text:i.storage?.text});const l=n.map((e=>new y(e.id,a))),c=new r(l);t.getCommandDispatcher()(c),t.setMandatoryFulfilled(e.stepName,!0)}}}}getDefaultColor(e){if(Le.getLocalOrUndefined(e.colourOptionId)){const t=Le.getDefaultVariant(Le.getLocalOrUndefined(e.colourOptionId).data);if(t)return t.color}if(e.colour)return e.colour}findLayoutElement(e,t,a){const i=e.getRegionElements(t.stepName);if(i[0])return xe(i[0].id,a().map((e=>e.layoutState)))}findLayoutElements(e,t,a){return e.getRegionElements(t.stepName).map((e=>xe(e.id,a().map((e=>e.layoutState)))))}availableColors(e){const t=this.cachedColors.get(e.stepName);if(t)return t;if(Le.getLocalOrUndefined(e.data.colourOptionId)){const t=Le.getLocalOrUndefined(e.data.colourOptionId).data.variants.map((e=>({fill:e.color,stroke:e.color,variant:e})));return this.cachedColors.set(e.stepName,t),t}if(e.data.colours&&e.data.colours.length>0){const t=e.data.colours.map((e=>({fill:e,stroke:e})));return this.cachedColors.set(e.stepName,t),t}return[]}changeColor(e,t,a,i){if(!e.data||!e.data.regions)return;const n=i.getCommandDispatcher();i.updateStorage(e.stepName,{color:t.fill}),t.variant?i.updateMetadata(e.stepName,{color:t.variant.name}):i.updateMetadata(e.stepName,{color:t.fill});for(const e of a){if(!t.fill)throw new Error("Fill not set on new color selection!");n(new o(e.id,t.fill))}}updateInputText(e,t,a,i,n,o){const s=t?e:this.injectReplaceableText(e,i.data),l=oe(s,{vertical:i.data.vertical,uppercase:i.data.uppercase});let c={command:void 0,helperText:"",errors:this.getErrorsForText(e,i,o)};if(c.errors.length>0)return c.helperText=c.errors[0].localizationKey,c;const d=(i.data.maxLength-s.length).toString();c.helperText=`${d} characters remaining`,o.updateStorage(i.stepName,{text:e}),o.updateMetadata(i.stepName,{text:l}),n.defaultCleared&&o.setMandatoryFulfilled(i.stepName,!0);const h=o.getTransaction().bulk&&i.data.varyText||!1,p=[],u=new Map,m=new Map;for(const e of a){if(!e.fontData)throw new Error("Failed to resolve font data for text.");const[t,a]=Oe(e.fontSize,e.fontData,{left:e.x,top:e.y,width:e.width,height:e.height,rotation:e.rotation,panelId:""},l,{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});u.set(e.id,t),m.set(e.id,a);const n=i.data.curved?l:(a||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(t,i.data,e.id,n,h))}if(!i.data.curved&&a.length>0){if(!Array.from(m.values()).every((e=>e)))return c.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),c}return c.command=new r(p),c.command.varying=h,c}async changeInputTextWithRegion(e,t,a,i,n,o,s,l,c,d){const h=i.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),p=s?h:this.injectReplaceableText(h,e.data),u=o.getRegionElements(e.stepName),m=new Map,f=new Map;for(const i of u)if(i.region){const[n,o]=Oe(t,a,i.region,p,{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});m.set(i.id,n),f.set(i.id,o)}const g=(()=>{if(e.data&&e.data.maxLength&&p.length>e.data.maxLength)return d&&d(!0),{info:"0"};var t=p.toLowerCase();const a=o.getProfanities();for(const e in a)if(t===a[e].toLowerCase().trim()&&""!==t)return l(!0),{error:"Blocked profanity."};if(!e.data.allowNewlines&&(p.includes("\n")||p.includes("\r")))return l(!0),{error:"Cannot span multiple lines."};if(!e.data.curved){if(!Array.from(f.values()).every((e=>e)))return l(!0),{error:"Does not fit."}}return l(!1),{info:(e.data.maxLength-p.length).toString()}})();if(g.error)return void c(g.error);if(c(`${g.info} characters remaining`||""),d)return;o.updateStorage(e.stepName,{text:h}),o.updateMetadata(e.stepName,{text:this.injectReplaceableText(h,e.data)});const w=o.getTransaction().bulk&&e.data.varyText||!1;n.defaultCleared&&o.setMandatoryFulfilled(e.stepName,!0);const y=[];for(const t of u){const a=e.data.curved?p:(f.get(t.id)||[]).join("\n");y.push(this.generateTextChangeCommandsForRegion(m.get(t.id)||1,e.data,t.id,a,w))}const v=new r(y);return v.varying=w,v}selectVariant(e,t,a,i,n,o,s,r){this.selectVariantCommand(e,t,a,i,n,o,s,r).then((e=>{n.getCommandDispatcher()(e.command),e.followup()}))}async fontDataFromVariant(e){if(!e.assetKey)throw new Error("No Asset for Variant");const t=(await St.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel))?.href;if(!t)throw new Error("Failed to find resource link for font in text step.");return{assetUrl:t,name:(await C(t)).names.fullName.en}}async findOrCreateElements(e,t,a){const i=e.getTransaction().bulk&&t.data.varyText||!1,n=this.findLayoutElements(e,t,a);if(n.length>0)return n;const o=Le.getLocalOrUndefined(t.optionId);if(!o)throw new Error(`No option for step ${t.stepName}`);const s=Le.getDefaultVariant(o.data);if(!s)throw new Error(`No default variant for step ${t.stepName}`);const l=await this.fontDataFromVariant(s),c=await this.createTextboxRegions(t.stepName,s,t.data,l,{},e),d=c.map((e=>e.commands)),h=new r(d.flat());return h.varying=i,e.getCommandDispatcher()(h),c.map((e=>e.newElement))}async selectVariantCommand(e,t,a,i,n,o,s,l){const c=lt();n.markUpdatePending(c);const d=await this.fontDataFromVariant(t);if(i.length>0){const h=i.map((e=>new y(e.id,d))),p=await this.changeInputTextWithRegion(e,e.data.size||30,d,a.text||"",a,n,o,s,l);p&&h.push(p);return{command:new r(h),followup:async()=>{n.markUpdateCompleted(c),await n.setSelectionsAndElements(e.stepName,[t],i)}}}{const i=await this.createTextboxRegions(e.stepName,t,e.data,d,a,n),h=await this.changeInputTextWithRegion(e,e.data.size||30,d,i[0]?.newElement.text||a.text||"",a,n,o,s,l),p=i.flatMap((e=>e.commands));h&&p.push(h);return{command:new r(p),followup:async()=>{n.markUpdateCompleted(c)}}}}injectReplaceableText(e,t){return t.replaceableText?t.replaceableText.replace("{{}}",e):e}async createTextboxRegions(e,t,i,n,o,s){if(!i||!i.regions)throw new Error("Step data not supplied");const r=s.getTransaction().bulk&&i.varyText||!1,l=r?"":o.text||i.defaultText||"",c=await Promise.all(i.regions.map((t=>{const c=s.getLayouts().find((e=>e.panelId===t.panelId)),d=lt();try{const s=this.getDefaultColor(i),h=s||"#000000";if(!c)throw new wa("Failed to find layout for region: "+t.panelId);const p={stepRegion:t,stepName:e,align:this.textAlign(i),fill:o.color?o.color:h,fontSize:i.size||30,fontData:n,id:d,layerIndex:t.layerIndex,rotation:t.rotation,text:oe(l,{vertical:i.vertical,uppercase:i.uppercase}),input:l,type:X.Textbox,vertical:i.vertical,x:t.left,y:t.top,height:t.height,width:t.width,immutable:t.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths},u=[];if(!i.curved){if(!p.fontData)throw new Error("Failed to resolve font data for text.");const e=new Map,a=new Map,[n,o]=Oe(p.fontSize,p.fontData,t,l,{size:i.size,minSize:i.minSize,maxSize:i.maxSize});e.set(d,n),a.set(d,o);const s=(a.get(d)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(e.get(d)||1,i,d,s,r))}const m=new a(p,c);return m.varying=r,{regionElement:{id:d,region:t},commands:[m,...u],newElement:p,fontData:n}}catch(e){throw console.log(e),new ga("Error adding font to region")}}))).catch((e=>{throw e instanceof ga?(ma.setLatestToast("Failed to load font.",Sa.Error),e):e instanceof wa?e:new Error(e)}));return await s.setSelectionsAndElements(e,[t],c.map((e=>e.regionElement))),s.updateMetadata(e,{text:l}),s.updateStorage(e,{text:l}),c}generateTextChangeCommandsForRegion(e,t,a,n,o){const s=[],l=new i(a,n);if(l.varying=o,s.push(l),!t.size){const t=new p(a,e);t.varying=o,s.push(t)}const c=new r(s);return c.varying=o,c}};function va(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}let Sa;var ba;(ba=Sa||(Sa={})).Error="Error",ba.Warning="Warning";class Ca extends Bt{constructor(e){super(),va(this,"update",void 0),va(this,"createdAt",new Date),this.update=e}async execute(){await this.update(),await new Promise((e=>{window.setTimeout((()=>{e()}),1e3)}))}}class xa{constructor(e,t,a,i,n,o,s,r,l){va(this,"initialReducerState",void 0),va(this,"transaction",void 0),va(this,"updateTransaction",void 0),va(this,"ensuredInitialised",void 0),va(this,"confirmedDesign",void 0),va(this,"editedSteps",void 0),va(this,"informationResults",void 0),va(this,"layouts",void 0),va(this,"mandatorySteps",void 0),va(this,"pendingUpdates",void 0),va(this,"selectionCost",void 0),va(this,"workflow",void 0),va(this,"stepSpecificServices",void 0),va(this,"previewService",void 0),va(this,"profanityFilter",void 0),va(this,"pollers",void 0),va(this,"commandContext",void 0),va(this,"stepElements",void 0),va(this,"stepInitialised",void 0),va(this,"stepMetadata",void 0),va(this,"stepSelections",void 0),va(this,"storage",void 0),va(this,"confirmCallbacks",void 0),va(this,"editedCallbacks",void 0),va(this,"elementsCallbacks",void 0),va(this,"ensuredInitialisedCallbacks",void 0),va(this,"informationResultCallbacks",void 0),va(this,"initCallbacks",void 0),va(this,"makingAdjustmentsCallback",void 0),va(this,"mandatoryCallbacks",void 0),va(this,"metadataCallbacks",void 0),va(this,"selectionCallbacks",void 0),va(this,"stepSpecificStorageCallbacks",void 0),va(this,"storageCallbacks",void 0),va(this,"updateCallbacks",void 0),va(this,"currentVariationRecordCallbacks",void 0),va(this,"variationRecordCallbacks",void 0),va(this,"processingStepInitialisation",void 0),va(this,"allScenes",void 0),va(this,"product",void 0),va(this,"invalidModelVariants",void 0),va(this,"currentAdjustingStepId",void 0),va(this,"renderableContextService",void 0),va(this,"workflowStatePromiseQueue",new Kt(1)),va(this,"variationRecords",[]),va(this,"currentVariationRecord",void 0),this.updateTransaction=n,this.commandContext=i,this.initialReducerState=o.workflowState,this.transaction=o,this.ensuredInitialised=!1,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=e,this.stepSpecificServices={},this.profanityFilter=t,this.pollers=[],this.allScenes=[],this.processingStepInitialisation=!1,this.layouts=a,this.product=l,this.previewService=s,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.ensuredInitialisedCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.updateCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=r,this.currentVariationRecord=null,this.ensureStepsAreLoaded(),this.fireReloadAnimation()}addVariationRecord(e){const t={...e,recordNumber:this.variationRecords.reduce(((e,t)=>t.recordNumber>e?t.recordNumber:e),0)+1};return this.variationRecords.push(t),this.onVariationRecordsChange(),t}removeVariationRecord(e){if(this.variationRecords=this.variationRecords.filter((t=>t.recordNumber!==e)),this.variationRecords.forEach(((e,t)=>{e.recordNumber=t+1})),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===e){const e=this.currentVariationRecord.recordNumber,t=e>1?this.variationRecords[e-2]:this.variationRecords[0];this.setCurrentVariationRecord(t||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(e){this.variationRecords=e,this.onVariationRecordsChange(),0===e.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(e[0])}setCurrentVariationRecord(e){this.currentVariationRecord=e,this.onCurrentVariationRecordChange()}fireReloadAnimation(){if(!this.initialReducerState)return;const e=this.workflow.finalizeStepConfig;e&&(e.lookAtAnimation&&this.previewService?.executeCameraAnimation(e.lookAtAnimation),e.modelAnimation&&this.previewService?.executeModelAnimation(e.modelAnimation))}addConfirmCallback(e){e(this.confirmedDesign),this.confirmCallbacks.push(e)}addEditedCallback(e){e(this.editedSteps),this.editedCallbacks.push(e)}addElementsCallback(e){e(this.stepElements),this.elementsCallbacks.push(e)}addEnsuredInitialisedCallback(e){e(this.ensuredInitialised),this.ensuredInitialisedCallbacks.push(e)}addInformationResultCallback(e){e(this.informationResults),this.informationResultCallbacks.push(e)}addInitCallback(e){e(this.stepInitialised),this.initCallbacks.push(e)}addMandatoryCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}addMetadataCallback(e){e(this.stepMetadata),this.metadataCallbacks.push(e)}addSelectionCallback(e){e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:this.traversableScenes()}),this.selectionCallbacks.push(e)}addStepSpecificStorageCallback(e,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),e(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(e)}addStorageCallback(e){e(this.storage),this.storageCallbacks.push(e)}addUpdateCallback(e){e(this.pendingUpdates.length>0),this.updateCallbacks.push(e)}addMakingAdjustmentsCallback(e){e(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(e)}addCurrentVariationCallback(e){e(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(e)}addVariationRecordsCallback(e){e(this.variationRecords),this.variationRecordCallbacks.push(e)}addPoller(e){this.pollers.push(e)}getLayouts(){return this.layouts}getLayoutPreviewService(){return this.renderableContextService}getPreviewService(){return this.previewService}getProductName(){return this.product?.name}getProfanities(){return this.profanityFilter}getRegionElements(e){return this.stepElements[e]||[]}getStepSpecificServices(e){return this.stepSpecificServices[e]}getTransaction(){return this.transaction}getWorkflow(){return this.workflow}getCommandDispatcher(){return e=>this.commandContext.apply(e)}getWorkflowSelections(){const e={};return this.workflow.steps.forEach((t=>{const a=this.stepSelections[t.stepName];if(a&&a.selectedVariants&&a.selectedVariants.length>0){const i=this.workflow.stepGroups.find((e=>e.stepNames.includes(t.stepName)));Le.getLocalOrUndefined(t.optionId)&&(e[t.stepName]={groupName:i?i.name:void 0,optionName:Le.getLocalOrUndefined(t.optionId).data.name,selections:a.selectedVariants})}})),e}markStepsAsInitialised(e){const t={...this.stepInitialised};e.forEach((e=>{t[e]=!0})),this.stepInitialised=t,this.onInitChange()}markUpdateCompleted(e){this.pendingUpdates=this.pendingUpdates.filter((t=>t!==e)),this.onUpdateChange()}markUpdatePending(e){this.pendingUpdates=[...this.pendingUpdates,e],this.onUpdateChange()}setAllScenes(e){const t=this.allScenes;this.allScenes=Vt(this.workflow,e),H(t,this.allScenes)||this.ensureStepsAreLoaded()}setEditedStatus(e,t){this.editedSteps={...this.editedSteps,[e]:t},this.onEditedChange()}setInformationResults(e){this.informationResults=[...e],this.onInformationResultChange()}setCurrentAdjustingStepId(e){this.currentAdjustingStepId=e,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(e,t){this.mandatorySteps[e]!==t&&(this.mandatorySteps={...this.mandatorySteps,[e]:t},this.onMandatoryChange())}async setSelectionsAndElements(e,t,a){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[e]:{selectedVariants:t}},this.selectionCost=Object.values(this.stepSelections).reduce(((e,t)=>e+t.selectedVariants.map((e=>e.priceModifier)).reduce(((e,t)=>e+t),0)),0),this.workflow.steps.forEach((e=>{Ft(e,this.stepSelections)||(this.stepInitialised[e.stepName]=!1,delete this.stepMetadata[e.stepName],delete this.stepSelections[e.stepName],delete this.storage[e.stepName])}));const n=this.allScenes,o=Wt(n,i),s=Wt(n,this.stepSelections),c=o.map((e=>e.silentSteps)).flat(),d=s.map((e=>e.silentSteps)).flat().filter((e=>!c.some((t=>t.stepName===e.stepName))));c.forEach((e=>{Ft(e,this.stepSelections)||(this.stepInitialised[e.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const h=this.getInvalidCanvasRegions(),{stepElements:p,commands:m}=await this.stepElementsForIntroducedSilentSteps(d);this.processingStepInitialisation||this.ensureStepsAreLoaded(),this.stepElements={...this.stepElements,...p,[e]:a},this.removeElements(h),this.onElementsChange();if(this.workflow.steps.find((t=>t.stepName===e))?.type===ce.Frame){this.getStepSpecificServices(e)?.frameService?.setTargetElements(a.map((e=>e.id)))}const f=[...h.map((e=>new l(e.id))),...m,new u(this.constructSerializableWorkflow())];f.length>0&&this.commandContext.apply(new r(f)),this.onSelectionChange()}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}async updateStorage(e,t){const a={...this.storage,[e]:{...this.storage[e],...t}};if(!H(a,this.storage)){this.storage=a;const t=new u(this.constructSerializableWorkflow());this.commandContext.apply(t),this.onStepSpecificStorageChange(e),this.onStorageChange()}}constructSerializableWorkflow(){const e=[];return this.allScenes.forEach((t=>{t.renderableSteps.forEach((t=>{const a={stepName:t.stepName};a.storage=this.storage[t.stepName],a.selectedVariants=this.stepSelections[t.stepName]?.selectedVariants?.map((e=>({id:e.id,priceModifier:e.priceModifier}))),e.push(a)}))})),{steps:e}}updateStateWithServer(e){const t=this.serialize(e);this.workflowStatePromiseQueue.enqueue(new Ca((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(e){const t=this.serialize(e);return new Ca((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(e){const t=JSON.stringify(this.dehydrateState(he(e().transaction))),a=e().variation;if(!a)return{transaction:t};const i={layouts:{},serializableWorkflow:{steps:[]},...he(a)||{}};return{transaction:t,variation:JSON.stringify(this.dehydrateState(i))}}dehydrateState(e){for(const t of Object.values(e.layouts).map((e=>e.elements)).flat())"illustration"===t.type&&(delete t.cachedObjectURL,t.src&&delete t.svg);return e}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(e,t){this.stepMetadata={...this.stepMetadata,[e]:{...this.stepMetadata[e],...t}},this.onMetadataChange()}removeElements(e){this.stepElements=((e,t)=>Object.keys(e).reduce(((a,i)=>{const n=[...e[i]||[]];return t.forEach((e=>{const t=n.findIndex((t=>t.id===e.id));t>-1&&n.splice(t,1)})),a[i]=n,a}),{}))(this.stepElements,e)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((e,t)=>(Ft(t,this.stepSelections)||this.stepElements[t.stepName]&&this.stepElements[t.stepName].forEach((t=>e.push(t))),e)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((e,t)=>(!Ft(t,this.stepSelections)&&Le.getLocalOrUndefined(t.optionId)&&"Model"===t.type&&e.push(Le.getLocalOrUndefined(t.optionId).data.id),e)),[])}async stepElementsForIntroducedSilentSteps(e){const t=this.product;if(!t)return Promise.resolve({stepElements:{},commands:[]});const a=(e,t,a)=>"SilentIllustration"===e.type?new Jt(e,t).trigger():"ProductOverlay"===e.type?new Jt(e,t,a).trigger():Promise.reject("Unknown silent step. This is a bug"),i=e.filter((e=>!this.stepInitialised[e.stepName]));let n={stepElements:{},commands:[]};for(const e of i){this.markStepsAsInitialised([e.stepName]);const i=await a(e,this.layouts,t);n.stepElements[e.stepName]=i.map((e=>e.regionElement)),n.commands=[...n.commands,...i.map((e=>e.command))]}return n}getSerializedStep(e,t){return t.find((t=>t.stepName===e))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}stepNotReadyForInitialization(e){return("Model"===e.type||"Material"===e.type)&&!this.previewService}async reset(){this.commandContext.getAllLayouts().forEach((e=>e.layoutState.elements.forEach((e=>{this.getCommandDispatcher()(new l(e.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async ensureStepsAreLoaded(){const e=this.initialReducerState?JSON.parse(this.initialReducerState):void 0;this.processingStepInitialisation=!0,await Le.cacheRequiredOptions(this.workflow);const t=this.allScenes,a=Wt(t,this.stepSelections).map((e=>e.silentSteps)).flat(),{stepElements:i,commands:n}=await this.stepElementsForIntroducedSilentSteps(a);this.stepElements={...this.stepElements,...i};const o=qt(this.allScenes,this.stepSelections).map((e=>e.renderableSteps)),s=[],r=[];n.forEach((e=>s.push({command:e,followup:async()=>{}})));const l=o.flat();for(const t of l)if(!this.stepInitialised[t.stepName]&&!this.stepNotReadyForInitialization(t))switch(this.stepInitialised[t.stepName]=!0,t.type){case"Bulk":this.updateStorage("Bulk",e?.serializableWorkflow.steps.find((e=>"Bulk"===e.stepName))?.storage||{});break;case"DigitalContent":s.push(await ia.init(t,this,e));break;case"Finish":case"Introduction":default:break;case"Frame":case"Photo":const a=new Yt(t.data.forceImageCover);a.connectWorkflowManager(this,t.stepName),this.stepSpecificServices[t.stepName]={frameService:a},s.push(await na.init(t,this,e));break;case"Illustration":s.push(await Qt.init(t,this,e));break;case"Material":r.push(await oa.init(t,this,e));break;case"Model":r.push(await sa.init(t,this,e));break;case"Module":const i=t.data.module;this.stepSpecificServices[t.stepName]={module:await pe(i)},s.push(await ra.init(t,this,e));break;case"Patchwork":s.push(await da.init(t,this,e));break;case"Picture":s.push(await ha.init(t,this,e));break;case"Question":r.push(await Lt.init(t,this,e));break;case"Shape":s.push(await pa.init(t,this,e));break;case"Text":s.push(await ya.init(t,this,e))}const c=s.filter((e=>!!e));for(const e of c)this.commandContext.apply(e.command),await e.followup();const d=r.filter((e=>!!e));if(d.length>0)for(const e of d)await e();(c.length>0||d.length>0)&&await this.ensureStepsAreLoaded();const h=l.map((e=>{if(Le.getLocalOrUndefined(e.optionId))return Le.getDefaultVariant(Le.getLocalOrUndefined(e.optionId).data)}));(e||l.length>0&&!h.some((e=>!!e))||c.length>0||d.length>0)&&(this.ensuredInitialised=!0,this.onEnsuredInitialisedChange()),this.processingStepInitialisation=!1,this.onSelectionChange(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((e=>e(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((e=>e(this.editedSteps)))}onEnsuredInitialisedChange(){this.ensuredInitialisedCallbacks.forEach((e=>e(this.ensuredInitialised)))}onElementsChange(){this.elementsCallbacks.forEach((e=>e(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((e=>e(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((e=>e(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((e=>{e(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((e=>e(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((e=>{e(this.stepMetadata)}))}onSelectionChange(){this.selectionCallbacks.forEach((e=>e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:this.traversableScenes()})))}onStepSpecificStorageChange(e){Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].forEach((t=>t(this.storage[e])))}onStorageChange(){this.storageCallbacks.forEach((e=>e(this.storage)))}onUpdateChange(){this.updateCallbacks.forEach((e=>{e(this.pendingUpdates.length>0)}))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((e=>{e(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((e=>{e(this.variationRecords)}))}traversableScenes(){const e=this.allScenes;return jt(e,this.stepSelections)}}function ka(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Ia{constructor(t){if(ka(this,"commandContext",void 0),ka(this,"workflowManager",void 0),ka(this,"isReadOnly",void 0),!t.workflow)throw new Error("No Workflow ID provided.");const a=t.layouts;this.commandContext=new e;const i=t.transaction.workflowState?JSON.parse(t.transaction.workflowState):void 0;this.commandContext.initialize(a,i),this.isReadOnly=!!t.transaction.lineItem?.id||!xt.getMap("transactionOwnerIds")?.get(t.transaction.id);this.workflowManager=new xa(t.workflow,t.product.profanities?.map((e=>e.word))||[],a,this.commandContext,(async e=>{this.isReadOnly||We.getShadowGraphqlClient().mutate({...e,mutation:Nt})}),t.transaction,t.previewService,t.renderableContextService,t.product)}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(e){await We.getShadowGraphqlClient().mutate({mutation:Ot,variables:{transactionId:this.workflowManager.getTransaction().id,updates:e.map((e=>({recordNumber:e.recordNumber,values:e.values.map((e=>({aspect:e.aspect,stepName:e.stepName,value:e.value})))})))}})}async createPreviewImage(){const e=document.createElement("canvas");e.width=1024,e.height=1024;const a=this.commandContext.getAllLayouts()[this.workflowManager.getWorkflow().defaultPreviewPanelIndex||0],i=a.layoutState.layout.previewRegion?{x:a.layoutState.layout.previewRegion.left,y:a.layoutState.layout.previewRegion.top,width:a.layoutState.layout.previewRegion.width,height:a.layoutState.layout.previewRegion.height}:{x:0,y:0,width:a.layoutState.layout.width,height:a.layoutState.layout.height},n=this.commandContext.getLayoutById(a.layoutState.layout.id),o=e.getContext("2d");if(!o)throw new Error("Failed to build 2D context for preview image creation.");const s=t(n.layoutState.layout,n.layoutState.elements,{region:i}),r=await re.from(o,s,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await r.render();const l=await(async e=>new Promise(((t,a)=>{try{e.toBlob((e=>{if(e){const a=URL.createObjectURL(e);t(a)}}))}catch(e){a(e)}})))(e);return e.toDataURL(l)}getStepById(e){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepName===e));if(t)return new At(this.getWorkflowManager(),t)}getStepByName(e){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepTitle===e));if(t)return new At(this.getWorkflowManager(),t)}getStepsByType(e){return this.getWorkflowManager().getWorkflow().steps.filter((t=>t.type===e)).map((e=>new At(this.getWorkflowManager(),e)))}async onDesignFinished(e,t,a,i){const n=(e,t,a)=>{const i={};return t.steps.forEach((t=>{Object.assign(i,(t=>{const i={};if("Frame"===t.type){const n=e[t.stepName],o=t.data;if(!n||o.hideImageInCart&&a)return i;i[`${t.stepTitle} exportedData.image`]=n.image}if("Illustration"===t.type){const n=e[t.stepName],o=t.data;if(!n||o.hideColorsInCart&&a||!n.colors)return i;if(n.colors.length>0){const e=n.colors.join(", ").toUpperCase();i[`${t.stepTitle} exportedData.colors`]=e}}if("Module"===t.type){const n=e[t.stepName],o=t.data;if(!n||o.hideTextInCart&&a)return i;i[`${t.stepTitle} exportedData.text`]=n.text}if("Text"===t.type){const n=e[t.stepName];if(!n)return i;const o=t.data;o.hideTextInCart&&a||(i[`${t.stepTitle} exportedData.text`]=n.text),!n.color||o.hideColorInCart&&a||(i[`${t.stepTitle} exportedData.color`]=n.color)}return i})(t))})),i},o=(e,t,a,i,n,o,s,r,l)=>({event:"onComplete",lineItemImageUrl:s?s.href:"",transactionId:e.id,metadata:n,selectedVariants:r,designProductVariantId:e.externalDesignProductVariantId,designProductId:e.externalDesignProductId,baseCost:a,weight:t.weight,optionsCost:i,exportedData:o,sku:l,workflowViewerLink:e.workflowViewerLink||""}),s=async(e,t,a,i,s,r,l)=>{const c=(e.product?.basePrice||0)*(e.variationsCount||0),d=e.priceModifierTotal||0,h=((e,t,a,i)=>{const o={};let s;if(a){s=n(a,t,!1);for(const e of Object.keys(s))o[e]={value:s[e],priceModifier:0}}else if(i){s=i;for(const e of Object.keys(s))o[e]={value:s[e],priceModifier:0}}for(const a of Object.keys(e)){const i=e[a],n=t.steps.find((e=>e.stepTitle===a));if(1===i.length)o[`${n?.stepTitle} exportedData.selection`]={value:i[0].name,priceModifier:i[0].priceModifier};else if(i.length>1)for(let e=0;e<i.length;e++)o[`${n?.stepTitle} exportedData.selection ${e+1}`]={value:i[e].name,priceModifier:i[e].priceModifier}}return o})(i,a,void 0,r);return o(e,t,c,d,r,h,l,i,s)};return(async(e,t,a,i,r,l,c,d,h,p,u,m)=>{h("workflow.steps.finish.finalize.buildingLayouts"),await e.outstandingRequestsPromise();const f=We.getShadowGraphqlClient();await f.resetStore();const g=await f.mutate({mutation:Pt,variables:{id:l.id}}),w=g.data?.transactions[0].workflowState;!g.errors&&w||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(i())),g.errors&&g.errors.forEach((e=>{g.errors&&console.log("Server Error:",e.message)})),await e.updateStateWithServerImmediate(i),console.log("Server state is undefined @ Workflow completion"));const y=e.getPreviewService(),v=t?.finalizeStepConfig?.lookAtAnimation,S=y&&100===y.getSceneInitializationProgress()&&t.showModelOnFinishStep&&v,b=m&&n(m,t,!0),C=m&&n(m,t,!1),x=e=>{const a={};let i=0;if(Object.keys(c).length>0)for(const n of Object.keys(c)){const o=c[n],s=t.steps.find((e=>e.stepName===n));for(let t=0;t<o.selections.length;++t){const n=o.selections[t];if(s&&(!e||Le.getLocalOrUndefined(s.optionId)&&Le.getLocalOrUndefined(s.optionId).data.variants.length>1&&!s.data.hideSelectionInCart&&!s.data.hideSelectionsInCart)){const e=s.stepTitle;a[e]?a[e].push({id:n.id||"",name:n.name,priceModifier:n.priceModifier}):a[e]=[{id:n.id||"",name:n.name,priceModifier:n.priceModifier}]}i+=n.priceModifier}}return[a,i]},[k]=x(!0),I=Object.fromEntries(Object.keys(k).map((e=>[e,k[e].map((e=>e.id))]))),[E]=x(!1),N=Object.fromEntries(Object.keys(E).map((e=>[e,E[e].map((e=>e.id))]))),R=await this.createPreviewImage();h("workflow.steps.finish.finalize.creatingDesign");const O=(await Fe.execute("createDesign",{designDetails:(()=>{const e={designName:d,layouts:a.map((e=>({index:e.index,panelId:e.panelId}))),workflowId:t.id,productId:r.id,transactionId:l.id,threeDimPreview:!!S,previewImage:R};return m&&(e.metadata=C),I&&(e.selectedVariants=N),e})()})).body,M=O.links.find((e=>"image"===e.rel));h("workflow.steps.finish.finalize.updatingTransaction");const P=(await We.getShadowGraphqlClient().query({query:Mt,variables:{id:l.id}})).data.transactions[0];return l.bulk?(await p(u),((e,t,a)=>{const i=(e.product?.basePrice||0)*(e.variationsCount||0),n=e.priceModifierTotal||0,s={items:{value:e.variationsCount?`${e.variationsCount}`:"0",priceModifier:0}};return o(e,t,i,n,void 0,s,a)})(P,r,M)):await s(P,r,t,k,O.data.sku,b,M)})(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),e,this.workflowManager.getTransaction(),a,this.workflowManager.getWorkflow().name,t,(e=>this.updateVariationRecords(e)),this.workflowManager.getVariationRecords(),i)}}function Ea(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Na{constructor(e){Ea(this,"layouts",void 0),Ea(this,"handleCompleteRender",void 0),this.handleCompleteRender=null;const t=new Map;e.forEach((e=>t.set(e.id,new Oa(e.id,e.name,this)))),this.layouts=t}setCompleteRenderCallback(e){this.handleCompleteRender=e,e(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}}let Ra;class Oa{constructor(e,t,a){Ea(this,"hasSetStaticContext",!1),Ea(this,"id",void 0),Ea(this,"name",void 0),Ea(this,"service",void 0),Ea(this,"interactiveDirty",!1),Ea(this,"textureCtx",void 0),Ea(this,"staticCtxDirty",!1),Ea(this,"lastRequestedRenderArguments",void 0),Ea(this,"lastCompletedStaticRender",void 0),Ea(this,"lastModificationID",void 0),Ea(this,"renderQueue",new Kt(2)),Ea(this,"rehydrated",!1),this.id=e,this.name=t,this.service=a}getID(){return this.id}getName(){return this.name}getStaticContext(){return this.textureCtx}setStaticContext(e){if(this.textureCtx=e,this.lastRequestedRenderArguments){const{workflow:e,layouts:t,variationRecord:a,productOverlayImageUrl:i}=this.lastRequestedRenderArguments;this.render(e,t,a,i)}}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(e){this.staticCtxDirty=e}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(e){this.interactiveDirty=e}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}getLastModificationID(){return this.lastModificationID}async render(e,t,a,i){const n=he(t);this.lastRequestedRenderArguments={workflow:e,layouts:n,variationRecord:a,productOverlayImageUrl:i};const o=this.getStaticContext();if(!o)return this.markLastCompletedStaticRender(),void this.setStaticContextDirty(!1);this.renderQueue.enqueue(new Ma(this.getID(),o,(()=>{if(void 0!==Ra)return Ra;const e=document.createElement("canvas").getContext("webgl2");return Ra=!!e,Ra})(),(()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)}),e,n,a,(async()=>{const e={layouts:{},serializableWorkflow:{steps:[]}};if(t.forEach((t=>{e.layouts[t.layoutState.layout.id]=t.layoutState})),!this.rehydrated){await ke(e);const t=Object.keys(e.layouts);for(let a=0;a<t.length;a++){const i=t[a],n=e.layouts[i].elements.filter((e=>"illustration"===e.type));for(let e=0;e<n.length;++e){const t=n[e];t.src&&t.svg&&(t.cachedObjectURL=await Zt(t.svg))}}this.rehydrated=!0}}),i))}}class Ma extends Bt{constructor(e,t,a,i,n,o,s,r,l){super(),Ea(this,"layoutId",void 0),Ea(this,"ctx",void 0),Ea(this,"nonPOTSupport",void 0),Ea(this,"onRender",void 0),Ea(this,"workflow",void 0),Ea(this,"layouts",void 0),Ea(this,"variationRecord",void 0),Ea(this,"preprocess",void 0),Ea(this,"productOverlayImageUrl",void 0),this.layoutId=e,this.ctx=t,this.nonPOTSupport=a,this.onRender=i,this.workflow=n,this.layouts=o,this.variationRecord=s,this.preprocess=r,this.productOverlayImageUrl=l}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}async execute(){const e=this.layouts.find((e=>e.layoutState.layout.id===this.layoutId));if(!e)return;const a=e.layoutState.elements||[];if(await this.preprocess(),this.variationRecord){const t=this.variationRecord.values.map((e=>({stepName:e.stepName,stepAspectType:e.aspect,value:e.value})));for(const e of this.workflow.steps)if(e.optionId&&!e.option){e.option=await Le.getLocalOrFromServer(Fe,e.optionId);for(const t of e.option.data.variants)t.assetKey&&!t.asset&&(t.asset=await St.getLocalOrFromServer(t.assetKey))}const i=await La(Pa(t,this.workflow),this.workflow,this.layouts.map((e=>e.layoutState.layout)),this.productOverlayImageUrl),n=i?.layouts[e.layoutState.layout.id];(n?.elements||[]).forEach((e=>{const t=a.find((t=>t.stepName===e.stepName));t&&t.type===X.Textbox?(t.text=e.text,t.fontSize=e.fontSize):a.push(e)})),a.sort(((e,t)=>void 0!==e.layerIndex&&void 0!==t.layerIndex?e.layerIndex-t.layerIndex:0))}const i=e.layoutState.layout.width,n=e.layoutState.layout.height,o=this.getDynamicTextureResolution().width,s=this.getDynamicTextureResolution().height;let r,l;if(this.nonPOTSupport){i/n<o/s?(r=o,l=n*(o/i)):(r=i*(s/n),l=s)}else r=this.getDynamicTextureResolution().width,l=this.getDynamicTextureResolution().height;const c=t(e.layoutState.layout,a),d=await le.from(this.ctx,c,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1});d.resize(r,l),await d.render(),this.onRender()}}const Pa=(e,t)=>{const a=[];return e.forEach((e=>{const i=t.steps.find((t=>t.stepName===e.stepName));i?.type===ce.Text&&"Text"===e.stepAspectType&&a.push({name:i.stepName,data:{text:e.value}})})),a},La=async(e,t,a,i)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};a.forEach((e=>{n=new v(e).apply(n)}));return(await Me(e,t,a,i)).forEach((e=>{n=e.apply(n)})),n};function Da(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Aa=async e=>(await Fe.execute("getProductById",{productId:e})).body,Ta=(e,t)=>{const a=e.workflowState,i=a?JSON.parse(a):void 0;return i?Object.values(i.layouts).map((e=>e.layout)):t.panels.sort(((e,t)=>e.index-t.index)).map((e=>({id:lt(),panelId:e.name,name:e.name,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion})))};class za{constructor(e){Da(this,"options",void 0),Da(this,"initialized",void 0),Da(this,"experienceOptions",void 0),this.initialized=!1,this.options=e}async initFromIntegrationProduct(e){if(""===e)throw new Error("No integration product ID provided.");this.options.useUncachedEndpoints&&Fe.setUncachedOperations(["getAssetByKeyV2","getWorkflowV2","getMaterialV2","getOptionV2"]);const t=We.getShadowGraphqlClient();await t.resetStore();const a=await t.mutate({mutation:kt,variables:{integrationProductId:e,bulk:this.options.bulk||!1}}),i=(await t.mutate({mutation:It,variables:{id:a.data?.transactionCreate.id}})).data?.transactionClaim;if(!i)throw new Error("Failed to create transaction.");const n=xt.getMap("transactionOwnerIds")||new Map;n.set(i.id,i.transactionOwnerId),Ve(i.transactionOwnerId||""),xt.setMap("transactionOwnerIds",n);const o=await Aa(i.product?.id||"");this.experienceOptions={product:o.data,transaction:i,layouts:[]},this.initialized=!0}async initFromTransaction(e){if(""===e)throw new Error("No transaction ID provided.");const t=We.getShadowGraphqlClient();await t.resetStore();const a=xt.getMap("transactionOwnerIds")||new Map,i=a.get(e);if(i){Ve(i);const a=(await t.query({query:Et,variables:{id:e}})).data?.transactions[0];if(!a)throw new Error("Failed to read transaction.");const n=await Aa(a.product?.id||"");return this.experienceOptions={product:n.data,transaction:a,layouts:[]},void(this.initialized=!0)}const n=(await t.mutate({mutation:It,variables:{id:e}})).data?.transactionClaim;if(!n)throw new Error("Failed to read transaction.");n.transactionOwnerId&&(a.set(n.id,n.transactionOwnerId),Ve(n.transactionOwnerId),xt.setMap("transactionOwnerIds",a));const o=await Aa(n.product?.id||"");this.experienceOptions={product:o.data,transaction:n,layouts:[]},this.initialized=!0}async getWorkflowExperience(e,t,a){if(!this.initialized||!this.experienceOptions)throw new Error("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const e=(await Fe.execute("getWorkflowV2",{workflowSlug:this.experienceOptions.transaction.workflowId})).body.data;if(this.experienceOptions.workflow=e,this.experienceOptions.transaction.workflowState){const e=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(e.layouts).map((e=>e.layout))}return this.experienceOptions.previewService=a&&a(e),this.experienceOptions.renderableContextService=new Na(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&await(this.experienceOptions.previewService?.initialize(this.experienceOptions.product.modelUrl,this.experienceOptions.renderableContextService)),new Ia(this.experienceOptions)}if(e){const i=(await Fe.execute("getWorkflowV2",{workflowSlug:e})).body.data;if(this.experienceOptions.workflow=i,await We.getShadowGraphqlClient().mutate({mutation:Rt,variables:{workflowId:e,id:this.experienceOptions.transaction.id}}),t){this.experienceOptions.transaction.workflowState=t;const e=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(e.layouts).map((e=>e.layout))}else this.experienceOptions.layouts=Ta(this.experienceOptions.transaction,this.experienceOptions.workflow);return this.experienceOptions.previewService=a&&a(i),this.experienceOptions.renderableContextService=new Na(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&await(this.experienceOptions.previewService?.initialize(this.experienceOptions.product.modelUrl,this.experienceOptions.renderableContextService)),new Ia(this.experienceOptions)}throw new Error("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new Error("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new Error("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}class Va{getVariationRecords(){return[]}async reset(){}updateStateWithServer(e){}addVariationRecord(e){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(e){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addCurrentVariationCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}addUpdateCallback(e){}addVariationRecordsCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getProductName(){return""}getProfanities(){return[]}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(e){}getWorkflowSelections(){return{}}setCurrentAdjustingStepId(e){}setAllScenes(e){}setCurrentVariationRecord(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,a){}setVariationRecords(e){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}}export{za as Client,e as CommandContext,Ae as spiffCoreConfiguration,Kt as PromiseQueue,Bt as QueueablePromise,Va as MockWorkflowManager,Sa as InformationMessageType,St as assetService,Le as optionService,Fe as server,xt as persistenceService,We as graphQlManager,ma as toast,Yt as FrameService,na as frameStepService,sa as modelStepService,oa as materialStepService,da as patchworkStepService,pa as shapeStepService,Lt as questionStepService,ia as digitalContentStepService,ra as moduleStepService,ha as pictureStepService,ya as textStepService,Qt as illustrationStepService,Zt as svgObjectURL,lt as generate,a as CreateElementCommand,i as TextChangeCommand,n as FontAlignmentCommand,o as FontColorCommand,S as LayoutElementFactory,ct as minZoom,yt as AdvancedEditor,wt as EditorCore,qe as useLayouts,Ze as useEditorState,dt as useEditorInteraction,He as commandReducer,Ke as getDefaultState,je as CommandContextContext,Ge as AdvancedEditorStateProvider,Xe as AdvancedEditorContext,Ye as UICommand,$e as EditorSubMenu,Tt as gatherVaryingStepAspects,b as SpiffCommerce3DPreviewService};
97
+ `;const Dt=new class{async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=i.data.variants,n=De.getDefaultVariant(i.data);if(!e.data.allowMultipleSelections&&n){const n=a.find((e=>e.id===i.data.defaultVariant));return this.selectVariantLambda(e,n?.id||"",t)}}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(n&&a){const i=n.variants.find((e=>e.id===a));i&&await t.setSelectionsAndElements(e.stepName,[i],[])}}}selectVariant(e,t,a){this.selectVariantLambda(e,t,a).then((e=>e&&e()))}async selectVariantLambda(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;const n=i.data.variants,o=n.length>1?n.find((e=>e.id===t)):n[0];if(!o)throw new Error("Failed to find selected variant in step variants, this should never happen!");return async()=>{await a.setSelectionsAndElements(e.stepName,[o],[]),a.setMandatoryFulfilled(e.stepName,!0)}}};function At(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Tt{constructor(e,t){At(this,"manager",void 0),At(this,"stepConfiguration",void 0),this.manager=e,this.stepConfiguration=t}getCurrentVariant(){return this.manager.getWorkflowSelections()[this.stepConfiguration.stepName].selections}async getAvailableVariants(){const e=this.stepConfiguration.optionId;return(await De.getLocalOrFromServer(We,e)).data.variants}selectVariant(e){if(this.stepConfiguration.type!==de.Question)throw new Error(`Step type ${this.stepConfiguration.type} not yet supported in Core SDK`);Dt.selectVariant(this.stepConfiguration,e.id,this.manager)}}const zt=e=>{const t=[];for(const a of e.steps)switch(a.type){case de.DigitalContent:a.data.varyUpload&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Upload});break;case de.Frame:const e=a.data;e.varySelection&&a.optionId&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection}),e.varyUpload&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Upload});break;case de.Illustration:const i=a.data;i.varySelection&&a.optionId&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection}),i.varyColors&&i.colourPickerEnabled&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Colors});break;case de.Material:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection});break;case de.Model:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection});break;case de.Picture:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection});break;case de.Question:a.data.varySelections&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selections});break;case de.Shape:a.data.varySelection&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection});break;case de.Text:const n=a.data;n.varyText&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Text}),n.varySelection&&a.optionId&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Selection}),n.varyColor&&n.colourPickerEnabled&&t.push({stepName:a.stepName,stepType:a.type,aspectType:he.Color})}return t},Vt=[de.SilentIllustration,"ProductOverlay"],Ut=(e,t)=>{const a=[];e.introduction&&a.push({name:"Introduction",title:e.name,renderableSteps:[{type:de.Introduction,stepName:"Introduction",stepTitle:e.name,helpText:e.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of e.steps){if(t.bulkScene){let e=!1;switch(i.type){case de.DigitalContent:i.data.varyUpload&&(e=!0);break;case de.Frame:const t=i.data;!t.varyUpload||!t.varySelection&&i.optionId||(e=!0);break;case de.Illustration:const a=i.data;!a.varySelection&&i.optionId&&1!==De.getLocalOrUndefined(i.optionId)?.data.variants.length||!a.varyColors&&a.colourPickerEnabled||(e=!0);break;case de.Material:i.data.varySelection&&(e=!0);break;case de.Model:i.data.varySelection&&(e=!0);break;case de.Picture:i.data.varySelection&&(e=!0);break;case de.Question:i.data.varySelections&&(e=!0);break;case de.Shape:i.data.varySelection&&(e=!0);break;case de.Text:const n=i.data;!n.varySelection&&i.optionId&&1!==De.getLocalOrUndefined(i.optionId)?.data.variants.length||!n.varyColor&&n.colourPickerEnabled&&n.colourOptionId||!n.varyText||(e=!0)}if(e)continue}const n=Ft(i.stepName,e.stepGroups);if(n){const e=a.find((e=>e.name===n.name));e?Vt.includes(i.type)?e.silentSteps.push(i):e.renderableSteps.push(i):a.push({name:n.name,title:n.name,renderableSteps:Vt.includes(i.type)?[]:[i],silentSteps:Vt.includes(i.type)?[i]:[]})}else a.push({name:i.stepName,title:i.stepTitle,renderableSteps:Vt.includes(i.type)?[]:[i],silentSteps:Vt.includes(i.type)?[i]:[]})}return t.bulkScene&&a.push({name:"Bulk",title:t.bulkSceneTitle,renderableSteps:[{type:de.Bulk,stepName:"Bulk",stepTitle:t.bulkSceneTitle,helpText:"help:/billing/bulk-ordering.md",data:{aspects:zt(e)},conditions:[]}],silentSteps:[]}),t.finishScene&&a.push({name:"Finish",title:t.finishSceneTitle,renderableSteps:[{type:de.Finish,stepName:"Finish",stepTitle:t.finishSceneTitle,helpText:"",data:{modelAnimation:e.finalizeStepConfig?e.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:e.finalizeStepConfig?e.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),a},Ft=(e,t)=>t.find((t=>t.stepNames.includes(e))),Wt=(e,t)=>(e.conditions||[]).every((e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const t=a.selectedVariants;return e.requiredVariantSelections.some((e=>void 0!==t.find((t=>t.id===e))))}return!1})),jt=(e,t)=>e.map((e=>((e,t)=>{const a={name:e.name,title:e.title,renderableSteps:e.renderableSteps.filter((e=>Wt(e,t))),silentSteps:e.silentSteps.filter((e=>Wt(e,t)))};return 0===a.silentSteps.length&&0===a.renderableSteps.length?null:a})(e,t))).filter((e=>null!==e)),qt=(e,t)=>jt(e,t).filter((e=>e.renderableSteps.filter(((e,t,a)=>e.type===de.Model||e.type===de.Material||e.type===de.Picture||e.type===de.Shape?De.getLocalOrUndefined(e.optionId)?.data.variants&&De.getLocalOrUndefined(e.optionId).data.variants.length>1?e:null:e)).length>0)),$t=(e,t)=>jt(e,t).filter((e=>e.renderableSteps.filter((e=>e)).length>0));function Bt(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Kt{constructor(){Bt(this,"timestamp",Date.now())}}class Ht{constructor(e){Bt(this,"queue",[]),Bt(this,"activePromise",void 0),Bt(this,"queueMaxSize",void 0),this.queueMaxSize=e}enqueue(e){if(this.queue.push(e),void 0!==this.queueMaxSize&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let t=0;t<e;++t)this.queue.shift()}return this.process()}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async process(){return this.activePromise||(this.activePromise=this.dequeue(),this.activePromise.then((()=>{this.activePromise=void 0}))),this.activePromise}async dequeue(){const e=this.queue.shift();if(e)try{await e.execute(),await this.dequeue()}catch(e){await this.dequeue()}}}function Xt(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function Gt(e,t,a,i){const n=a.width*e.zoom,o=a.height*e.zoom;if(i){const i=e,n=Math.max(t.width/a.width,t.height/a.height);i.zoom=Math.max(n,e.zoom);const o=a.width*i.zoom,s=a.height*i.zoom;return i.x=Yt(e.x,t.width-o,0),i.y=Yt(e.y,t.height-s,0),i}const s=e;return s.x=Yt(s.x,-n,t.width),s.y=Yt(s.y,-o,t.height),s}function Yt(e,t,a){return Math.min(Math.max(e,t),a)}class Zt{constructor(e){Xt(this,"offsets",void 0),Xt(this,"forceImageCover",void 0),Xt(this,"targetElements",void 0),Xt(this,"imageData",void 0),Xt(this,"frameData",void 0),Xt(this,"_debouncedUpdateFrameOffsets",void 0),Xt(this,"minZoomScale",.03),Xt(this,"maxZoomScale",20),Xt(this,"onFrameDataChangeListeners",void 0),Xt(this,"onZoomChangeListeners",void 0),Xt(this,"workflowManager",void 0),Xt(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=me(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=e}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback((async e=>{if(e){const t=e;if(t.currentFrameSource){const e=await fe(t.currentFrameSource);X(e,this.frameData)||(this.frameData=e,this.onFrameDataChangeListeners.forEach((e=>e(this.frameData))),this.frameData&&this.imageData&&(this.offsets=ge(this.imageData,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,this.targetElements),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}async setFrameData(e){const t=we.get(e);this.frameData=t}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,a,i){if(this.imageData&&this.offsets&&this.frameData){const n=(t-this.offsets.x)/this.offsets.zoom,o=(a-this.offsets.y)/this.offsets.zoom,s={x:t-n*e,y:a-o*e,zoom:this.imageData.width*e/this.imageData.width};this.updateOffsets(Gt(s,this.frameData,this.imageData,this.forceImageCover),i),this.onZoomChangeListeners.forEach((t=>t(e)))}}setPatternData(e){(e&&this.frameData||e&&this.frameData&&!this.imageData)&&(this.offsets=ge(e,this.frameData),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.targetElements),this.updateOffsets(Gt(this.offsets,this.frameData,e,this.forceImageCover))),this.imageData=e,this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t){const a=this.imageData;a&&this.frameData&&(this.offsets&&e.x===this.offsets.x&&e.y===this.offsets.y&&e.zoom===this.offsets.zoom?t&&t():(this.offsets=Gt(e,this.frameData,a,this.forceImageCover),this._debouncedUpdateFrameOffsets(e,a,this.frameData,this.targetElements,t)))}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}updateFrameOffsets(e,t,a,i,n){if(!a)throw new Error("Frame data not set. This is a bug");if(!this.workflowManager)throw new Error("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();i.forEach((a=>{o(new m(a,t,e))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsets:e}),n&&n()}recalculateZoomLimits(e,t){const a=Math.max(t.width/e.width,t.height/e.height);this.forceImageCover?(this.minZoomScale=a,this.maxZoomScale=2.5*a):(this.minZoomScale=a/10,this.maxZoomScale=2.5*a)}}const Qt=async e=>{const t=(new DOMParser).parseFromString(e,"image/svg+xml").firstElementChild;if(!t)throw new Error("Failed to read SVG");const a=(new XMLSerializer).serializeToString(t),i=document.createElement("canvas"),n=i.getContext("2d"),o=await ce.from(n,a,{anonymousCrossOrigin:!0,ignoreDimensions:!1}),s=t.getAttribute("width"),r=t.getAttribute("height");if(r&&s){const e=parseFloat(r),t=parseFloat(s)/e;t>1?o.resize(2048,2048/t):o.resize(2048*t,2048)}else o.resize(2048,2048);return await o.render(),await(async e=>new Promise(((t,a)=>{try{e.toBlob((e=>{if(e){const a=URL.createObjectURL(e);t(a)}else a("Failed to generate canvas object URL")}))}catch(e){a(e)}})))(i)},_t=new class{async getIllustrationBody(e){return new Promise((t=>{fetch(e).then((e=>{t(e.text())})).catch((e=>console.error(e)))}))}getCreateElementCommand(e,t,i,n){return new a({stepRegion:t,stepName:n.stepName,colors:n.svg.colors,id:e,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:G.Illustration,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layerIndex:t.layerIndex,immutable:t.immutable},i)}async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)return this.reload(e,t,a);{t.updateMetadata(e.stepName,{colors:[]});const a=De.getDefaultVariant(i.data);if(a)return this.selectVariantCommand(e,a,[],(()=>{}),t)}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(!o||!a)throw new Error("Required illustration variant no longer available");{const s=o.variants.find((e=>e.id===a));if(s){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[s],a),t.updateMetadata(e.stepName,{colors:i.storage?.colors}),t.setMandatoryFulfilled(e.stepName,!0)}}}return null}availableColors(e){return De.getLocalOrUndefined(e.data.colourOptionId)?De.getLocalOrUndefined(e.data.colourOptionId).data.variants.map((e=>({fill:e.color,stroke:e.color,variant:e}))):(e.data.colours||[]).map((e=>({fill:e,stroke:e})))}async changeColorsCommand(e,t,a,i,n){const o={};for(const[e,t]of n.entries())o[e]={browserValue:t,spotColor:o[e]?.spotColor};const s=Ce(e,t,a,o),l=await Qt(s),c=[];for(const e of i){for(const[t,a]of n.entries())c.push(new f(e,t,a));c.push(new g(e,s,l))}return new r(c)}async changeColors(e,t,a,i,n){if(0===t.length)return;const o=ke(t[0].id,i().map((e=>e.layoutState))),s={...o.colors},r={};Object.entries(s).forEach((([e,t])=>{const a={browserValue:t.browserValue},i=t.spotColor;i&&(a.spotColor={profileName:i.profileName,namedColor:i.namedColor}),r[e]=a}));for(const[e,t]of n.entries())s[e]={browserValue:t,spotColor:s[e]?.spotColor},r[e]={browserValue:t};a.updateStorage(e.stepName,{colors:r});let l=Array.from(Object.values(s)).map((e=>e.browserValue));De.getLocalOrUndefined(e.data.colourOptionId)&&De.getLocalOrUndefined(e.data.colourOptionId).data.variants.forEach((e=>{l=l.map((t=>t.toLowerCase()===e.color?.toLowerCase()?e.name:t))})),a.updateMetadata(e.stepName,{colors:l});const c=new Map;if(Object.entries(s).forEach((([e,t])=>{c.set(e,t.browserValue)})),!o.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const d=await this.changeColorsCommand(o.svg,o.width,o.height,t.map((e=>e.id)),c);a.getCommandDispatcher()(d)}selectVariant(e,t,a,i,n){this.selectVariantCommand(e,t,a,i,n).then((e=>{n.getCommandDispatcher()(e.command),e.followup()}))}selectVariantCommand(e,t,a,i,n){if(!e.data||!e.data.regions)throw new Error("Missing config data.");i(!0);const o=a.map((e=>new l(e.id)));return n.setMandatoryFulfilled(e.stepName,!1),new Promise((async a=>{if(!t.assetKey)throw new Error("No Asset for Variant");const s=(await bt.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));if(!s)throw new Error("CDN Link not found on SVG Asset entity!");const l=await be(await this.getIllustrationBody(s.href)),c=await Qt(l.svg),d=e.data.regions.map((t=>{const a=n.getLayouts().find((e=>e.panelId===t.panelId));if(!a)throw new Error("Tried to create illustration but no layout.");const i=ct();return{regionElement:{id:i,region:t},command:this.getCreateElementCommand(i,t,a,{stepName:e.stepName,src:s.href,objectURL:c,svg:l})}})),h=[...d.map((e=>e.command)),...o];a({command:new r(h),followup:async()=>{await n.setSelectionsAndElements(e.stepName,[t],d.map((e=>e.regionElement))),n.setMandatoryFulfilled(e.stepName,!0),i(!1)}})}))}};function Jt(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class ea{constructor(e,t,i){Jt(this,"configuration",void 0),Jt(this,"layouts",void 0),Jt(this,"product",void 0),Jt(this,"processRegion",(async e=>{const t=this.layouts.find((t=>t.panelId===e.panelId));if(!t)throw new Error(`Can not find layout for region: ${e.panelId}`);let i="";if("ProductOverlay"===this.configuration.type){let e="";if(this.product?.overlayImageUrl&&(e=this.product.overlayImageUrl),i=e,!e)throw new Error("Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if("image"===n){const i="SilentIllustration"===this.configuration.type?this.configuration.data.assetKey:this.product?.overlayImageUrl,o={id:ct(),src:i,type:n,y:e.top,x:e.left,width:e.width,height:e.height,layerIndex:e.layerIndex,immutable:e.immutable,productOverlay:"ProductOverlay"===this.configuration.type||void 0,rotation:e.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:o.id,region:e},command:new a(o,t)}}{const o="SilentIllustration"===this.configuration.type?this.configuration.data.assetKey:i,s=async()=>new Promise((e=>{fetch(o).then((t=>{e(t.text())})).catch((e=>console.error(e)))})),r=await be(await s()),l={id:ct(),cachedObjectURL:await Qt(r.svg),src:o,svg:r.svg,colors:r.colors,type:n,y:e.top,x:e.left,width:e.width,height:e.height,layerIndex:e.layerIndex,rotation:e.rotation,immutable:e.immutable,productOverlay:"ProductOverlay"===this.configuration.type||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:l.id,region:e},command:new a(l,t)}}})),this.configuration=e,this.layouts=t,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new Error("Missing regions.");if("SilentIllustration"===this.configuration.type){const e=this.configuration.data.regions.map(this.processRegion);return Promise.all(e)}return"ProductOverlay"===this.configuration.type?Promise.all(this.configuration.data.regions.map((e=>{if(!this.layouts.find((t=>e.panelId===t.panelId)))throw new Error("Can't find layout from region. This is a bug");return this.processRegion(e)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const e="ProductOverlay"===this.configuration.type&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.assetKey?.toLowerCase().split("?")[0];return e?.endsWith(".jpeg")||e?.endsWith(".jpg")||e?.endsWith(".png")?G.Image:(e?.endsWith(".svg"),G.Illustration)}}const ta=async e=>{const t=`${Te.getServicesApiUrl()}/shortener`;try{const a=await fetch(t,{method:"POST",body:JSON.stringify({longUrl:e}),headers:{"Content-Type":"application/json"}});return(await a.json()).shortUrl}catch(e){throw console.error(e),new Error("Failed to shorten URL.")}};function aa(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class ia{async poll(){if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId));this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(e,t,a,i=3e3,n=10){aa(this,"pollingId",void 0),aa(this,"attempts",void 0),aa(this,"interval",void 0),aa(this,"maxAttempts",void 0),aa(this,"predicate",void 0),aa(this,"onSuccess",void 0),aa(this,"onFailure",void 0),this.onSuccess=t,this.onFailure=a,this.predicate=e,this.attempts=0,this.pollingId=-1,this.interval=i,this.maxAttempts=n,this.poll()}}const na=new class{async init(e,t,a){return a&&await this.reload(e,t,a),null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)).map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[],n);const o=i?.storage?.videoShortUrl,s=i?.storage?.videoUrl;t.updateStorage(e.stepName,{videoShortUrl:o,videoUrl:s})}async regenerateQRCode(e,t,a,i,n,o,s,r,c){if(!t&&""!==a&&""===i){const t=async()=>(await We.execute("getAssetByKeyV2_private",{assetKey:a.replace(/\//g,"_")})).body.links.find((e=>"mpeg4"===e.rel)),c=await new Promise(((e,a)=>{new ia((async()=>!!await t()),(async()=>{const a=await t();if(!a||!a.href)throw new Error("Poller succeeded but no mpeg link found");e(a)}),(()=>{a("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));e.forEach((e=>r(new l(e.id))));const d="http"===o.data.baseUrl.slice(0,4)?"":"https://",h=new URL(d+o.data.baseUrl);h.searchParams.append("video",btoa(JSON.stringify([c]))),h.pathname=h.pathname+("/"===h.pathname.slice(-1)?"":"/");const p=h.toString();if(p.length>=2e3)throw new Error("Cannot create QR code, URL too long.");const u=await ta(p);if(s(u),!o.data||!o.data.regions)throw new Error("Missing config data.");const m=await this.regionElements(o),f=await this.command(u,m,n,o.stepName);f&&r(f.command),await n.setSelectionsAndElements(o.stepName,[],m),n.updateStorage(o.stepName,{videoShortUrl:u,videoUrl:i})}c(!1)}async regionElements(e){return e.data.regions.map((e=>({id:ct(),region:e})))}async command(e,t,i,n){const o=i.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Ee(e,{type:"svg"}))}`,l=t.map((e=>{const t=e.region,i=o.find((e=>e.panelId===t?.panelId));if(!i||!t)throw new Error(`Can not find layout for region: ${t?.panelId}`);return new a({stepRegion:t,stepName:n,id:e.id,src:s,type:G.Image,y:t.top,x:t.left,width:t.width,height:t.height,rotation:0},i)}));return{command:new r(l),followup:async()=>{}}}};const oa=new class{constructor(){var e,t,a;a=async(e,t)=>{if(!e)return ye(t.data.regions[0]);if(!e.assetKey)throw new Error("No Asset for Variant");const a=(await bt.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel));if(a)return Ne(a.href);throw new Error("No URL for frame!")},(t="frameSourceSvg")in(e=this)?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a}async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(a)await this.reload(e,t,a);else{if(t.setMandatoryFulfilled(e.stepName,!1),t.markStepsAsInitialised([e.stepName]),!i||0===i.data.variants.length)return this.selectVariantCommand(e,void 0,[],t,void 0,e.data.placeholderImageKey);{const a=De.getDefaultVariant(i.data);if(a)return this.selectVariantCommand(e,a,[],t,void 0,e.data.placeholderImageKey)}}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)).map((e=>({id:e.id,region:e.stepRegion}))),o=De.getLocalOrUndefined(e.optionId)?.data;if(!o||0===o.variants.length){const a=ye(e.data.regions[0]);t.updateStorage(e.stepName,{currentFrameSource:a})}if(i){if(i.selectedVariants&&i.selectedVariants.length>0){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){await t.setSelectionsAndElements(e.stepName,[i],n);const a=await this.frameSourceSvg(i,e);t.updateStorage(e.stepName,{currentFrameSource:a})}}}else await t.setSelectionsAndElements(e.stepName,[],n);const a=i.storage?.framePatternSrc,s=i.storage?.frameOffsets;if(t.updateMetadata(e.stepName,{frameOffsets:s,framePatternSrc:a}),a){const i=t.getStepSpecificServices(e.stepName)?.frameService;await this.loadPatternFromString(a,i),t.updateMetadata(e.stepName,{image:a}),t.updateStorage(e.stepName,{framePatternSrc:a})}if(s?.zoom){const a=t.getStepSpecificServices(e.stepName)?.frameService;a.updateOffsets(s)}t.setMandatoryFulfilled(e.stepName,!0)}}selectImage(e,t,a){a.setEditedStatus(e.stepName,!0);t.links.find((e=>"cdn"===e.rel)).href.endsWith("pdf")?a.addPoller(new ia((async()=>{const e=(await We.execute("getAssetByKeyV2_private",{assetKey:t.data.key.replace(/\//g,"_")})).body.links.find((e=>"svg"===e.rel));if(!e)return!1;return 200===(await fetch(e.href)).status}),(()=>{We.execute("getAssetByKeyV2_private",{assetKey:t.data.key.replace(/\//g,"_")}).then((t=>{const i=t.body;this.loadPatternFromAsset(i,e,a)}))}),(()=>{throw new Error("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(t,e,a)}selectVariant(e,t,a,i,n){this.selectVariantCommand(e,t,a,i,n).then((e=>{i.getCommandDispatcher()(e.command),e.followup()}))}getCreateElementCommand(e,t,i,n){return new a({id:e,type:G.Frame,x:t.left,y:t.top,width:t.width,height:t.height,layerIndex:t.layerIndex,rotation:t.rotation,scaleX:t.width/n.frameData.width,scaleY:t.height/n.frameData.height,path:n.frameData.path,stepRegion:t,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:t.immutable},i)}async loadPatternFromString(e,t){if(e.endsWith("svg")){const a=await ve(e),i=a.width,n=a.height,o={src:e,width:i,height:n,aspect:i/n};Se.set(e,o),t.setPatternData(o)}else{const a=await fetch(e),i=await a.arrayBuffer(),n=await re(i),o={src:e,width:n.width,height:n.height,aspect:n.width/n.height};Se.set(e,o),t.setPatternData(o)}}async selectVariantCommand(e,t,a,i,n,o){const s=i.getStepSpecificServices(e.stepName)?.frameService,c=await this.frameSourceSvg(t,e),d=await fe(c),h=s.getImageData(),p=a.map((e=>new l(e.id))),u=h?ge(h,d):void 0,m=h?{id:ct(),src:h.src,x:u?.x||0,y:u?.y||0,width:h.width,height:h.height,scaleX:u?.zoom||1,scaleY:u?.zoom||1,rotation:0}:void 0;n&&n(!0);const f=e.data.regions.map((t=>{const a=ct(),n=i.getLayouts().find((e=>e.panelId===t.panelId));if(!n)throw new Error(`Can not find layout for region: ${t.panelId}`);return{command:this.getCreateElementCommand(a,t,n,{frameData:d,pattern:m,disablePlaceholder:e.data.disablePlaceholder,focalBlur:e.data.focalBlur,focalBlurStrength:e.data.focalBlurStrength,focalBlurRadius:e.data.focalBlurRadius,stepName:e.stepName}),regionEl:{id:a,region:t}}})),g=f.map((e=>e.command));return{command:new r([...g,...p]),followup:async()=>{if(n&&n(!1),await i.setSelectionsAndElements(e.stepName,t?[t]:[],[...f.map((e=>e.regionEl))]),i.updateStorage(e.stepName,{currentFrameSource:c}),o){const t=i.getStepSpecificServices(e.stepName)?.frameService;await this.loadPatternFromString(o,t)}}}}patternSource(e){const t=e.links.find((e=>"svg"===e.rel));if(t)return t.href;const a=e.links.find((e=>"cdn"===e.rel));if(a)return a.href;throw new Error("Frame pattern source file could not be find, neither svg or cdn assets existed on requested variant!")}async loadPatternFromAsset(e,t,a){const i=this.patternSource(e),n=ct();a.markUpdatePending(n);const o=a.getStepSpecificServices(t.stepName)?.frameService;await this.loadPatternFromString(i,o),a.updateMetadata(t.stepName,{image:i}),a.updateStorage(t.stepName,{framePatternSrc:i}),a.markUpdateCompleted(n)}};const sa=new class{async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=De.getDefaultVariant(i.data);if(a)return this.selectVariantLambda(e,a,t,(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=await bt.getMaterialLocalOrFromServer(i.materialId),o=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],o);const s=t.getPreviewService();if(s){const i=e.data.targetMaterials.map((t=>s.applyMaterialVariant(t,e.optionId,a.data)));Promise.all(i).then((()=>t.setMandatoryFulfilled(e.stepName,!0)))}}}}}selectVariant(e,t,a,i){this.selectVariantLambda(e,t,a,i).then((e=>e&&e()))}async selectVariantLambda(e,t,a,i){const n=a.getPreviewService();if(!n)return null;i(!0);const o=await bt.getMaterialLocalOrFromServer(t.materialId);if(!o)throw i(!1),new Error("No material set on variant");return async()=>{await a.setSelectionsAndElements(e.stepName,[t],[]);const s=e.data.targetMaterials.map((t=>n.applyMaterialVariant(t,e.optionId,o.data)));Promise.all(s).then((()=>a.setMandatoryFulfilled(e.stepName,!0))).finally((()=>i(!1)))}}};const ra=new class{async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=De.getDefaultVariant(i.data);if(a)return this.selectVariantLambda(e,a,t,(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],a);const o=t.getPreviewService();if(o){if(!i.assetKey)throw new Error("No Asset for Variant");const a=(await bt.getLocalOrFromServer(i.assetKey)).links.find((e=>"cdn"===e.rel));o.applyModelVariant(e.optionId,{model:a.href,contextService:t.getLayoutPreviewService()},e.data.replaceProductModel||!1).then((()=>{t.setMandatoryFulfilled(e.stepName,!0)}))}}}}}selectVariant(e,t,a,i){this.selectVariantLambda(e,t,a,i).then((e=>e&&e()))}async selectVariantLambda(e,t,a,i){const n=a.getPreviewService();if(!n)return null;if(i(!0),!t.assetKey)throw new Error("No Asset for Variant");const o=(await bt.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));return async()=>{if(await a.setSelectionsAndElements(e.stepName,[t],[]),!o)throw new Error("Asset not found:"+t.assetKey);n.applyModelVariant(e.optionId,{model:o.href,contextService:a.getLayoutPreviewService()},e.data.replaceProductModel||!1).then((()=>{a.setMandatoryFulfilled(e.stepName,!0)})).finally((()=>i(!1)))}}};const la=new class{async init(e,t,a){return a?(await this.reload(e,t,a),null):(t.updateMetadata(e.stepName,{text:""}),this.changeTextCommand(e,"",t,"",(()=>{})))}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)).map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[],n),t.updateStorage(e.stepName,{text:i?.storage?.text}),t.setMandatoryFulfilled(e.stepName,""!==i?.storage?.text)}changeText(e,t,a,i,n){this.changeTextCommand(e,t,a,i,n).then((e=>{e&&(a.getCommandDispatcher()(e.command),e.followup())}))}async changeTextCommand(e,t,i,n,o){const s=i.getRegionElements(e.stepName),c=i.getStepSpecificServices(e.stepName)?.module;if(!c)return console.error("Missing module."),null;const d=i.getProfanities();if(!this.validateInput(e,t,d,o))return i.setMandatoryFulfilled(e.stepName,!1),console.error(n),null;if(i.setMandatoryFulfilled(e.stepName,""!==t),!e.data||!e.data.regions||e.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(e.stepName,{text:t});const h=(t,n,o)=>{const s=o||ct(),c=i.getLayouts().find((e=>e.panelId===n.panelId));if(!c)return console.error(`Can not find layout for region: ${n.panelId}`),null;const d=[];return o&&d.push(new l(s)),d.push(new a({stepRegion:n,stepName:e.stepName,colors:{},id:s,svg:t,type:G.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layerIndex:n.layerIndex,immutable:n.immutable},c)),{id:s,region:n,command:new r(d)}},p=c.svgPrint(t);if(s.length>0){const e=s.map((e=>e.region?h(p,e.region,e.id):null)).filter((e=>!!e)).filter((e=>!!e)).map((e=>e&&e.command));return{command:new r(e),followup:async()=>{}}}{const t=e.data.regions.map((e=>h(p,e))),a=t.filter((e=>!!e)).map((e=>e&&e.command));return{command:new r(a),followup:async()=>{const a=t.filter((e=>e)).map((e=>e&&{id:e.id,region:e.region}));await i.setSelectionsAndElements(e.stepName,[],a)}}}}validateInput(e,t,a,i){if(e.data&&e.data.maxLength){const a=e.data.maxLength;if(t.length>a)return i("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(t))return i("Unsupported characters."),!1;const n=t.toLowerCase();for(const e in a)if(n===a[e].toLowerCase().trim()&&""!==n)return i("Blocked profanity."),!1;return i(""),!0}};const ca=e=>new Promise((t=>{fetch(e).then((e=>e.text())).then((e=>{t(e)})).catch((e=>console.error(e)))})),da=e=>{const t=e.match(/<svg.*?<\/svg>/s)||[],a=t?.length>0?t[0]:"",i=(new DOMParser).parseFromString(a,"image/svg+xml").firstElementChild;if(!i)throw new Error("Failed to read SVG.");xe(i,!0);return(new XMLSerializer).serializeToString(i)},ha=new class{async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return console.error(`Patchwork step ${e.stepName} is missing option.`),null;if(a)await this.reload(e,t,a);else{const a=De.getDefaultVariant(i.data);if(a&&a.assetKey)return this.selectVariantCommand(e,a,[],t,(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const s=o.variants.find((e=>e.id===a));if(s){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[s],a),t.updateStorage(e.stepName,{patchworkOffsets:i.storage?.patchworkOffsets}),t.setMandatoryFulfilled(e.stepName,!0)}}}}recalculate(e,t,a,i){const n=a.getCommandDispatcher();var o;i(!0);const s=t.map((e=>e.region?this.getRandomPosition(e.region):null)).filter((e=>!!e));n(new r(t.map(((e,t)=>{const a=s[t];return 0===t&&(o=a),new w(e.id,a.scale,-a.xOffset,-a.yOffset)})))),o&&a.updateStorage(e.stepName,{patchworkOffsets:s}),i(!1)}selectVariant(e,t,a,i,n){this.selectVariantCommand(e,t,a,i,n).then((e=>{e&&(i.getCommandDispatcher()(e.command),e.followup())}))}async selectVariantCommand(e,t,i,n,o){if(!t.assetKey)throw new Error("No Asset for Variant");const s=(await bt.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));if(!s)throw new Error("Could not find CDN link for patchwork.");if(!e.data||!e.data.regions)return console.error("Trying to update patchwork in design with no region data"),null;o(!0);const c=s.href,d=n.getLayouts();var h;const p=e.data.regions.map((e=>this.getRandomPosition(e))),u=await ca(c),m=da(u),f=e.data.regions.map(((t,i)=>((t,i,n)=>{const o=d.find((e=>e.panelId===t.panelId));if(!o)throw new Error("Can't find layout");const s=p[i],r=ct();return 0===i&&(h=s),{regionElement:{id:r,region:t},command:new a({stepRegion:t,stepName:e.stepName,id:r,svg:n,type:G.Patchwork,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layerIndex:t.layerIndex,immutable:t.immutable,patchX:-s.xOffset,patchY:-s.yOffset,patchScale:s.scale},o)}})(t,i,m))),g=i.map((e=>new l(e.id))),w=f.map((e=>e.command));return{command:new r([...g,...w]),followup:async()=>{await n.setSelectionsAndElements(e.stepName,[t],f.map((e=>e.regionElement))),h&&n.updateStorage(e.stepName,{patchworkOffsets:p}),o(!1)}}}getRandomPosition(e){const t=Math.random()*(.7-.25)+.25,a=1/t,i=1-t;return{scale:a,xOffset:Math.random()*i*a*e.width,yOffset:Math.random()*i*a*e.height}}constructPreviewSvg(e,t,a,i){if(!i||0===t.length)return null;try{const n=ke(t[0].id,a().map((e=>e.layoutState))).svg,o=e.data.regions[0],s={x:0,y:0,width:o.width,height:o.height,rotation:0,id:"patchwork-preview",svg:n,patchX:-i.xOffset,patchY:-i.yOffset,patchScale:i.scale},r=q(Oe,{...s}),l=Re.renderToStaticMarkup(r);return`\n <svg\n version="1.1"\n xmlns="http://www.w3.org/2000/svg"\n xmlns:xlink="http://www.w3.org/1999/xlink"\n width="${s.width}px"\n height="${s.height}px"\n viewBox="0 0 ${s.width} ${s.height}"\n >\n ${l}\n </svg>\n `}catch(e){return null}}};const pa=new class{async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId)?.data;if(!i)return null;if(a)await this.reload(e,t,a);else if(i.defaultVariant){const a=i.defaultVariant,n=i.variants.find((e=>!!e.assetKey&&e.id===a));if(n)return t.markStepsAsInitialised([e.stepName]),this.selectVariantCommand(e,n,t,(()=>{}))}return t.markStepsAsInitialised([e.stepName]),null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],a),t.setMandatoryFulfilled(e.stepName,!0)}}}}selectVariant(e,t,a,i){this.selectVariantCommand(e,t,a,i).then((e=>{e&&(a.getCommandDispatcher()(e.command),e.followup())}))}async selectVariantCommand(e,t,i,n){if(!t.assetKey)throw new Error("No Asset for Variant");const o=(await bt.getLocalOrFromServer(t.assetKey)).links.find((e=>"cdn"===e.rel));if(!o)return console.error("No URL for picture!"),null;const s=o.href;n(!0),i.setMandatoryFulfilled(e.stepName,!1);const c=i.getRegionElements(e.stepName).map((e=>new l(e.id))),d=e.data.regions.map((t=>{const n=i.getLayouts().find((e=>e.panelId===t.panelId));if(!n)throw new Error(`Can not find layout for region: ${t.panelId}`);const o=ct();return{regionElement:{id:o,region:t},command:new a({stepName:e.stepName,stepRegion:t,id:o,src:s,type:G.Image,y:t.top,x:t.left,rotation:t.rotation,width:t.width,height:t.height,layerIndex:t.layerIndex,immutable:t.immutable,preserveAspectRatio:"none"},n)}}));return{command:new r([...c,...d.map((e=>e.command))]),followup:async()=>{await i.setSelectionsAndElements(e.stepName,[t],d.map((e=>e.regionElement))),i.setMandatoryFulfilled(e.stepName,!0),n(!1)}}}};const ua=new class{colourOptions(e){return De.getLocalOrUndefined(e.optionId)?De.getLocalOrUndefined(e.optionId).data.variants.map((e=>({fill:e.color,stroke:e.color,variant:e}))):e.data.colours.length>0?e.data.colours.map((e=>({fill:e,stroke:e}))):[]}async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;if(!a){const a=De.getDefaultVariant(i.data);if(!a)return null;const n={fill:a.color,stroke:a.color,variant:a};return this.selectVariantCommand(e,n,[],t)}return await this.reload(e,t,a),null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=De.getLocalOrUndefined(e.optionId)?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const i=o.variants.find((e=>e.id===a));if(i){const a=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[i],a),t.updateStorage(e.stepName,{colour:i.color||""}),t.setMandatoryFulfilled(e.stepName,!0)}}}}selectVariant(e,t,a,i){this.selectVariantCommand(e,t,a,i).then((e=>{e&&(i.getCommandDispatcher()(e.command),e.followup())}))}async selectVariantCommand(e,t,i,n){const o=n.getLayouts();if(i.length>0){const a=a=>{const i=a.region;if(!o.find((e=>e.panelId===i?.panelId)))return console.error(`Step ${e.stepName} missing layout for panel: ${i?.panelId}.`),null;const n=t.variant?.color;return n?new f(a.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},s=i.map(a).filter((e=>!!e));return{command:new r(s),followup:async()=>{n.setSelectionsAndElements(e.stepName,t.variant?[t.variant]:[],i),n.updateStorage(e.stepName,{colour:t.fill||""})}}}{const i=i=>{const n=o.find((e=>e.panelId===i.panelId));if(!n)return console.error(`Step ${e.stepName} missing layout for panel: ${i.panelId}.`),null;const s=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${t.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:t.variant.color};const l=ct();return{id:l,region:i,command:new a({stepRegion:i,stepName:e.stepName,colors:r,id:l,svg:s,type:G.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:e.data.excludeFromPrint},n)}},s=e.data.regions.map(i),l=s.filter((e=>!!e)).map((e=>e?.command)),c=s.filter((e=>!!e)).map((e=>({id:e.id,region:e.region})));return{command:new r(l),followup:async()=>{await n.setSelectionsAndElements(e.stepName,t.variant?[t.variant]:[],c),n.updateStorage(e.stepName,{colour:t.fill||""})}}}}};function ma(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const fa=new class{constructor(){ma(this,"latestToast",void 0),ma(this,"toastType",void 0),ma(this,"toastCallbacks",void 0),this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(e){e({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(e)}setLatestToast(e,t){this.latestToast=e,this.toastType=t,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach((e=>e({toastMessage:this.latestToast,toastType:this.toastType})))}};function ga(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class wa extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=wa.name}}class ya extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=ya.name}}const va=new class{constructor(){ga(this,"cachedColors",new Map),ga(this,"filterUnsupportedCharacters",((e,t)=>{let a=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const i=[],n=e?.fontData?k(e?.fontData):void 0;if(n){const e=a.split("").map((e=>n.getFont().charToGlyph(e)));for(let t=0;t<e.length;t++){const n=".notdef"===e[t].name;"\n"===a.charAt(t)||n&&i.push(String.fromCharCode(a.charCodeAt(t)))}}for(let e=0;e<i.length;e++)a=a.replaceAll(i[e],"");return a})),ga(this,"getErrorsForText",((e,t,a)=>{const i=[];t.data&&t.data.maxLength&&e.length>t.data.maxLength&&i.push({localizationKey:"workflow.steps.text.characterLimit"});const n=a.getProfanities(),o=e.toLowerCase();if(""!==o)for(const e in n){if(o===n[e].toLowerCase().trim()){i.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!t.data.allowNewlines&&(e.includes("\n")||e.includes("\r"))&&i.push({localizationKey:"workflow.steps.text.multipleLines"}),i})),ga(this,"textAlign",(e=>e.vertical?"center":e.textAlign||"center"))}async init(e,t,a){const i=De.getLocalOrUndefined(e.optionId);if(!i)return null;if(a)await this.reload(e,t,a);else{const a=e.data.defaultText||"";t.updateStorage(e.stepName,{inputText:a});this.getDefaultColor(e.data)&&t.updateMetadata(e.stepName,{color:e.data.colour});const n=De.getDefaultVariant(i.data);if(n)return this.selectVariantCommand(e,n,{},[],t,!1,(()=>{}),(()=>{}))}return null}async reload(e,t,a){const i=t.getSerializedStep(e.stepName,a.serializableWorkflow.steps),n=Object.values(a.layouts).map((e=>e.elements)).flat().filter((t=>t.stepName===e.stepName)),o=(await De.getLocalOrFromServer(We,e.optionId))?.data;if(i?.selectedVariants){const a=i.selectedVariants[0].id;if(o&&a){const s=o.variants.find((e=>e.id===a));if(s){const a=await this.fontDataFromVariant(s),o=n.map((e=>({id:e.id,region:e.stepRegion})));await t.setSelectionsAndElements(e.stepName,[s],o),t.updateMetadata(e.stepName,{color:i.storage?.color,text:i.storage?.text}),t.updateStorage(e.stepName,{text:i.storage?.text});const l=n.map((e=>new y(e.id,a))),c=new r(l);t.getCommandDispatcher()(c),t.setMandatoryFulfilled(e.stepName,!0)}}}}getDefaultColor(e){if(De.getLocalOrUndefined(e.colourOptionId)){const t=De.getDefaultVariant(De.getLocalOrUndefined(e.colourOptionId).data);if(t)return t.color}if(e.colour)return e.colour}findLayoutElement(e,t,a){const i=e.getRegionElements(t.stepName);if(i[0])return ke(i[0].id,a().map((e=>e.layoutState)))}findLayoutElements(e,t,a){return e.getRegionElements(t.stepName).map((e=>ke(e.id,a().map((e=>e.layoutState)))))}availableColors(e){const t=this.cachedColors.get(e.stepName);if(t)return t;if(De.getLocalOrUndefined(e.data.colourOptionId)){const t=De.getLocalOrUndefined(e.data.colourOptionId).data.variants.map((e=>({fill:e.color,stroke:e.color,variant:e})));return this.cachedColors.set(e.stepName,t),t}if(e.data.colours&&e.data.colours.length>0){const t=e.data.colours.map((e=>({fill:e,stroke:e})));return this.cachedColors.set(e.stepName,t),t}return[]}changeColor(e,t,a,i){if(!e.data||!e.data.regions)return;const n=i.getCommandDispatcher();i.updateStorage(e.stepName,{color:t.fill}),t.variant?i.updateMetadata(e.stepName,{color:t.variant.name}):i.updateMetadata(e.stepName,{color:t.fill});for(const e of a){if(!t.fill)throw new Error("Fill not set on new color selection!");n(new o(e.id,t.fill))}}updateInputText(e,t,a,i,n,o){const s=t?e:this.injectReplaceableText(e,i.data),l=se(s,{vertical:i.data.vertical,uppercase:i.data.uppercase});let c={command:void 0,helperText:"",errors:this.getErrorsForText(e,i,o)};if(c.errors.length>0)return c.helperText=c.errors[0].localizationKey,c;const d=(i.data.maxLength-s.length).toString();c.helperText=`${d} characters remaining`,o.updateStorage(i.stepName,{text:e}),o.updateMetadata(i.stepName,{text:l}),n.defaultCleared&&o.setMandatoryFulfilled(i.stepName,!0);const h=o.getTransaction().bulk&&i.data.varyText||!1,p=[],u=new Map,m=new Map;for(const e of a){if(!e.fontData)throw new Error("Failed to resolve font data for text.");const[t,a]=Me(e.fontSize,e.fontData,{left:e.x,top:e.y,width:e.width,height:e.height,rotation:e.rotation,panelId:""},l,{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});u.set(e.id,t),m.set(e.id,a);const n=i.data.curved?l:(a||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(t,i.data,e.id,n,h))}if(!i.data.curved&&a.length>0){if(!Array.from(m.values()).every((e=>e)))return c.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),c}return c.command=new r(p),c.command.varying=h,c}async changeInputTextWithRegion(e,t,a,i,n,o,s,l,c,d){const h=i.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),p=s?h:this.injectReplaceableText(h,e.data),u=o.getRegionElements(e.stepName),m=new Map,f=new Map;for(const i of u)if(i.region){const[n,o]=Me(t,a,i.region,p,{size:e.data.size,minSize:e.data.minSize,maxSize:e.data.maxSize});m.set(i.id,n),f.set(i.id,o)}const g=(()=>{if(e.data&&e.data.maxLength&&p.length>e.data.maxLength)return d&&d(!0),{info:"0"};var t=p.toLowerCase();const a=o.getProfanities();for(const e in a)if(t===a[e].toLowerCase().trim()&&""!==t)return l(!0),{error:"Blocked profanity."};if(!e.data.allowNewlines&&(p.includes("\n")||p.includes("\r")))return l(!0),{error:"Cannot span multiple lines."};if(!e.data.curved){if(!Array.from(f.values()).every((e=>e)))return l(!0),{error:"Does not fit."}}return l(!1),{info:(e.data.maxLength-p.length).toString()}})();if(g.error)return void c(g.error);if(c(`${g.info} characters remaining`||""),d)return;o.updateStorage(e.stepName,{text:h}),o.updateMetadata(e.stepName,{text:this.injectReplaceableText(h,e.data)});const w=o.getTransaction().bulk&&e.data.varyText||!1;n.defaultCleared&&o.setMandatoryFulfilled(e.stepName,!0);const y=[];for(const t of u){const a=e.data.curved?p:(f.get(t.id)||[]).join("\n");y.push(this.generateTextChangeCommandsForRegion(m.get(t.id)||1,e.data,t.id,a,w))}const v=new r(y);return v.varying=w,v}selectVariant(e,t,a,i,n,o,s,r){this.selectVariantCommand(e,t,a,i,n,o,s,r).then((e=>{n.getCommandDispatcher()(e.command),e.followup()}))}async fontDataFromVariant(e){if(!e.assetKey)throw new Error("No Asset for Variant");const t=(await bt.getLocalOrFromServer(e.assetKey)).links.find((e=>"cdn"===e.rel))?.href;if(!t)throw new Error("Failed to find resource link for font in text step.");return{assetUrl:t,name:(await x(t)).names.fullName.en}}async findOrCreateElements(e,t,a){const i=e.getTransaction().bulk&&t.data.varyText||!1,n=this.findLayoutElements(e,t,a);if(n.length>0)return n;const o=De.getLocalOrUndefined(t.optionId);if(!o)throw new Error(`No option for step ${t.stepName}`);const s=De.getDefaultVariant(o.data);if(!s)throw new Error(`No default variant for step ${t.stepName}`);const l=await this.fontDataFromVariant(s),c=await this.createTextboxRegions(t.stepName,s,t.data,l,{},e),d=c.map((e=>e.commands)),h=new r(d.flat());return h.varying=i,e.getCommandDispatcher()(h),c.map((e=>e.newElement))}async selectVariantCommand(e,t,a,i,n,o,s,l){const c=ct();n.markUpdatePending(c);const d=await this.fontDataFromVariant(t);if(i.length>0){const h=i.map((e=>new y(e.id,d))),p=await this.changeInputTextWithRegion(e,e.data.size||30,d,a.text||"",a,n,o,s,l);p&&h.push(p);return{command:new r(h),followup:async()=>{n.markUpdateCompleted(c),await n.setSelectionsAndElements(e.stepName,[t],i)}}}{const i=await this.createTextboxRegions(e.stepName,t,e.data,d,a,n),h=await this.changeInputTextWithRegion(e,e.data.size||30,d,i[0]?.newElement.text||a.text||"",a,n,o,s,l),p=i.flatMap((e=>e.commands));h&&p.push(h);return{command:new r(p),followup:async()=>{n.markUpdateCompleted(c)}}}}injectReplaceableText(e,t){return t.replaceableText?t.replaceableText.replace("{{}}",e):e}async createTextboxRegions(e,t,i,n,o,s){if(!i||!i.regions)throw new Error("Step data not supplied");const r=s.getTransaction().bulk&&i.varyText||!1,l=r?"":o.text||i.defaultText||"",c=await Promise.all(i.regions.map((t=>{const c=s.getLayouts().find((e=>e.panelId===t.panelId)),d=ct();try{const s=this.getDefaultColor(i),h=s||"#000000";if(!c)throw new ya("Failed to find layout for region: "+t.panelId);const p={stepRegion:t,stepName:e,align:this.textAlign(i),fill:o.color?o.color:h,fontSize:i.size||30,fontData:n,id:d,layerIndex:t.layerIndex,rotation:t.rotation,text:se(l,{vertical:i.vertical,uppercase:i.uppercase}),input:l,type:G.Textbox,vertical:i.vertical,x:t.left,y:t.top,height:t.height,width:t.width,immutable:t.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths},u=[];if(!i.curved){if(!p.fontData)throw new Error("Failed to resolve font data for text.");const e=new Map,a=new Map,[n,o]=Me(p.fontSize,p.fontData,t,l,{size:i.size,minSize:i.minSize,maxSize:i.maxSize});e.set(d,n),a.set(d,o);const s=(a.get(d)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(e.get(d)||1,i,d,s,r))}const m=new a(p,c);return m.varying=r,{regionElement:{id:d,region:t},commands:[m,...u],newElement:p,fontData:n}}catch(e){throw console.log(e),new wa("Error adding font to region")}}))).catch((e=>{throw e instanceof wa?(fa.setLatestToast("Failed to load font.",ba.Error),e):e instanceof ya?e:new Error(e)}));return await s.setSelectionsAndElements(e,[t],c.map((e=>e.regionElement))),s.updateMetadata(e,{text:l}),s.updateStorage(e,{text:l}),c}generateTextChangeCommandsForRegion(e,t,a,n,o){const s=[],l=new i(a,n);if(l.varying=o,s.push(l),!t.size){const t=new p(a,e);t.varying=o,s.push(t)}const c=new r(s);return c.varying=o,c}};function Sa(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}let ba;var Ca;(Ca=ba||(ba={})).Error="Error",Ca.Warning="Warning";class xa extends Kt{constructor(e){super(),Sa(this,"update",void 0),Sa(this,"createdAt",new Date),this.update=e}async execute(){await this.update(),await new Promise((e=>{window.setTimeout((()=>{e()}),1e3)}))}}class ka{constructor(e,t,a,i,n,o,s,r,l){Sa(this,"initialReducerState",void 0),Sa(this,"transaction",void 0),Sa(this,"updateTransaction",void 0),Sa(this,"ensuredInitialised",void 0),Sa(this,"confirmedDesign",void 0),Sa(this,"editedSteps",void 0),Sa(this,"informationResults",void 0),Sa(this,"layouts",void 0),Sa(this,"mandatorySteps",void 0),Sa(this,"pendingUpdates",void 0),Sa(this,"selectionCost",void 0),Sa(this,"workflow",void 0),Sa(this,"stepSpecificServices",void 0),Sa(this,"previewService",void 0),Sa(this,"profanityFilter",void 0),Sa(this,"pollers",void 0),Sa(this,"commandContext",void 0),Sa(this,"stepElements",void 0),Sa(this,"stepInitialised",void 0),Sa(this,"stepMetadata",void 0),Sa(this,"stepSelections",void 0),Sa(this,"storage",void 0),Sa(this,"confirmCallbacks",void 0),Sa(this,"editedCallbacks",void 0),Sa(this,"elementsCallbacks",void 0),Sa(this,"ensuredInitialisedCallbacks",void 0),Sa(this,"informationResultCallbacks",void 0),Sa(this,"initCallbacks",void 0),Sa(this,"makingAdjustmentsCallback",void 0),Sa(this,"mandatoryCallbacks",void 0),Sa(this,"metadataCallbacks",void 0),Sa(this,"selectionCallbacks",void 0),Sa(this,"stepSpecificStorageCallbacks",void 0),Sa(this,"storageCallbacks",void 0),Sa(this,"updateCallbacks",void 0),Sa(this,"currentVariationRecordCallbacks",void 0),Sa(this,"variationRecordCallbacks",void 0),Sa(this,"processingStepInitialisation",void 0),Sa(this,"allScenes",void 0),Sa(this,"product",void 0),Sa(this,"invalidModelVariants",void 0),Sa(this,"currentAdjustingStepId",void 0),Sa(this,"renderableContextService",void 0),Sa(this,"workflowStatePromiseQueue",new Ht(1)),Sa(this,"variationRecords",[]),Sa(this,"currentVariationRecord",void 0),this.updateTransaction=n,this.commandContext=i,this.initialReducerState=o.workflowState,this.transaction=o,this.ensuredInitialised=!1,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=e,this.stepSpecificServices={},this.profanityFilter=t,this.pollers=[],this.allScenes=[],this.processingStepInitialisation=!1,this.layouts=a,this.product=l,this.previewService=s,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.ensuredInitialisedCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.updateCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=r,this.currentVariationRecord=null,this.ensureStepsAreLoaded(),this.fireReloadAnimation()}addVariationRecord(e){const t={...e,recordNumber:this.variationRecords.reduce(((e,t)=>t.recordNumber>e?t.recordNumber:e),0)+1};return this.variationRecords.push(t),this.onVariationRecordsChange(),t}removeVariationRecord(e){if(this.variationRecords=this.variationRecords.filter((t=>t.recordNumber!==e)),this.variationRecords.forEach(((e,t)=>{e.recordNumber=t+1})),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===e){const e=this.currentVariationRecord.recordNumber,t=e>1?this.variationRecords[e-2]:this.variationRecords[0];this.setCurrentVariationRecord(t||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(e){this.variationRecords=e,this.onVariationRecordsChange(),0===e.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(e[0])}setCurrentVariationRecord(e){this.currentVariationRecord=e,this.onCurrentVariationRecordChange()}fireReloadAnimation(){if(!this.initialReducerState)return;const e=this.workflow.finalizeStepConfig;e&&(e.lookAtAnimation&&this.previewService?.executeCameraAnimation(e.lookAtAnimation),e.modelAnimation&&this.previewService?.executeModelAnimation(e.modelAnimation))}addConfirmCallback(e){e(this.confirmedDesign),this.confirmCallbacks.push(e)}addEditedCallback(e){e(this.editedSteps),this.editedCallbacks.push(e)}addElementsCallback(e){e(this.stepElements),this.elementsCallbacks.push(e)}addEnsuredInitialisedCallback(e){e(this.ensuredInitialised),this.ensuredInitialisedCallbacks.push(e)}addInformationResultCallback(e){e(this.informationResults),this.informationResultCallbacks.push(e)}addInitCallback(e){e(this.stepInitialised),this.initCallbacks.push(e)}addMandatoryCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}addMetadataCallback(e){e(this.stepMetadata),this.metadataCallbacks.push(e)}addSelectionCallback(e){e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:this.traversableScenes()}),this.selectionCallbacks.push(e)}addStepSpecificStorageCallback(e,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),e(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(e)}addStorageCallback(e){e(this.storage),this.storageCallbacks.push(e)}addUpdateCallback(e){e(this.pendingUpdates.length>0),this.updateCallbacks.push(e)}addMakingAdjustmentsCallback(e){e(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(e)}addCurrentVariationCallback(e){e(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(e)}addVariationRecordsCallback(e){e(this.variationRecords),this.variationRecordCallbacks.push(e)}addPoller(e){this.pollers.push(e)}getLayouts(){return this.layouts}getLayoutPreviewService(){return this.renderableContextService}getPreviewService(){return this.previewService}getProductName(){return this.product?.name}getProfanities(){return this.profanityFilter}getRegionElements(e){return this.stepElements[e]||[]}getStepSpecificServices(e){return this.stepSpecificServices[e]}getTransaction(){return this.transaction}getWorkflow(){return this.workflow}getCommandDispatcher(){return e=>this.commandContext.apply(e)}getWorkflowSelections(){const e={};return this.workflow.steps.forEach((t=>{const a=this.stepSelections[t.stepName];if(a&&a.selectedVariants&&a.selectedVariants.length>0){const i=this.workflow.stepGroups.find((e=>e.stepNames.includes(t.stepName)));De.getLocalOrUndefined(t.optionId)&&(e[t.stepName]={groupName:i?i.name:void 0,optionName:De.getLocalOrUndefined(t.optionId).data.name,selections:a.selectedVariants})}})),e}markStepsAsInitialised(e){const t={...this.stepInitialised};e.forEach((e=>{t[e]=!0})),this.stepInitialised=t,this.onInitChange()}markUpdateCompleted(e){this.pendingUpdates=this.pendingUpdates.filter((t=>t!==e)),this.onUpdateChange()}markUpdatePending(e){this.pendingUpdates=[...this.pendingUpdates,e],this.onUpdateChange()}setAllScenes(e){const t=this.allScenes;this.allScenes=Ut(this.workflow,e),X(t,this.allScenes)||this.ensureStepsAreLoaded()}setEditedStatus(e,t){this.editedSteps={...this.editedSteps,[e]:t},this.onEditedChange()}setInformationResults(e){this.informationResults=[...e],this.onInformationResultChange()}setCurrentAdjustingStepId(e){this.currentAdjustingStepId=e,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(e,t){this.mandatorySteps[e]!==t&&(this.mandatorySteps={...this.mandatorySteps,[e]:t},this.onMandatoryChange())}async setSelectionsAndElements(e,t,a){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[e]:{selectedVariants:t}},this.selectionCost=Object.values(this.stepSelections).reduce(((e,t)=>e+t.selectedVariants.map((e=>e.priceModifier)).reduce(((e,t)=>e+t),0)),0),this.workflow.steps.forEach((e=>{Wt(e,this.stepSelections)||(this.stepInitialised[e.stepName]=!1,delete this.stepMetadata[e.stepName],delete this.stepSelections[e.stepName],delete this.storage[e.stepName])}));const n=this.allScenes,o=jt(n,i),s=jt(n,this.stepSelections),c=o.map((e=>e.silentSteps)).flat(),d=s.map((e=>e.silentSteps)).flat().filter((e=>!c.some((t=>t.stepName===e.stepName))));c.forEach((e=>{Wt(e,this.stepSelections)||(this.stepInitialised[e.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const h=this.getInvalidCanvasRegions(),{stepElements:p,commands:m}=await this.stepElementsForIntroducedSilentSteps(d);this.processingStepInitialisation||this.ensureStepsAreLoaded(),this.stepElements={...this.stepElements,...p,[e]:a},this.removeElements(h),this.onElementsChange();if(this.workflow.steps.find((t=>t.stepName===e))?.type===de.Frame){this.getStepSpecificServices(e)?.frameService?.setTargetElements(a.map((e=>e.id)))}const f=[...h.map((e=>new l(e.id))),...m,new u(this.constructSerializableWorkflow())];f.length>0&&this.commandContext.apply(new r(f)),this.onSelectionChange()}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}async updateStorage(e,t){const a={...this.storage,[e]:{...this.storage[e],...t}};if(!X(a,this.storage)){this.storage=a;const t=new u(this.constructSerializableWorkflow());this.commandContext.apply(t),this.onStepSpecificStorageChange(e),this.onStorageChange()}}constructSerializableWorkflow(){const e=[];return this.allScenes.forEach((t=>{t.renderableSteps.forEach((t=>{const a={stepName:t.stepName};a.storage=this.storage[t.stepName],a.selectedVariants=this.stepSelections[t.stepName]?.selectedVariants?.map((e=>({id:e.id,priceModifier:e.priceModifier}))),e.push(a)}))})),{steps:e}}updateStateWithServer(e){const t=this.serialize(e);this.workflowStatePromiseQueue.enqueue(new xa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(e){const t=this.serialize(e);return new xa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(e){const t=JSON.stringify(this.dehydrateState(pe(e().transaction))),a=e().variation;if(!a)return{transaction:t};const i={layouts:{},serializableWorkflow:{steps:[]},...pe(a)||{}};return{transaction:t,variation:JSON.stringify(this.dehydrateState(i))}}dehydrateState(e){for(const t of Object.values(e.layouts).map((e=>e.elements)).flat())"illustration"===t.type&&(delete t.cachedObjectURL,t.src&&delete t.svg);return e}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(e,t){this.stepMetadata={...this.stepMetadata,[e]:{...this.stepMetadata[e],...t}},this.onMetadataChange()}removeElements(e){this.stepElements=((e,t)=>Object.keys(e).reduce(((a,i)=>{const n=[...e[i]||[]];return t.forEach((e=>{const t=n.findIndex((t=>t.id===e.id));t>-1&&n.splice(t,1)})),a[i]=n,a}),{}))(this.stepElements,e)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((e,t)=>(Wt(t,this.stepSelections)||this.stepElements[t.stepName]&&this.stepElements[t.stepName].forEach((t=>e.push(t))),e)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((e,t)=>(!Wt(t,this.stepSelections)&&De.getLocalOrUndefined(t.optionId)&&"Model"===t.type&&e.push(De.getLocalOrUndefined(t.optionId).data.id),e)),[])}async stepElementsForIntroducedSilentSteps(e){const t=this.product;if(!t)return Promise.resolve({stepElements:{},commands:[]});const a=(e,t,a)=>"SilentIllustration"===e.type?new ea(e,t).trigger():"ProductOverlay"===e.type?new ea(e,t,a).trigger():Promise.reject("Unknown silent step. This is a bug"),i=e.filter((e=>!this.stepInitialised[e.stepName]));let n={stepElements:{},commands:[]};for(const e of i){this.markStepsAsInitialised([e.stepName]);const i=await a(e,this.layouts,t);n.stepElements[e.stepName]=i.map((e=>e.regionElement)),n.commands=[...n.commands,...i.map((e=>e.command))]}return n}getSerializedStep(e,t){return t.find((t=>t.stepName===e))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}stepNotReadyForInitialization(e){return("Model"===e.type||"Material"===e.type)&&!this.previewService}async reset(){this.commandContext.getAllLayouts().forEach((e=>e.layoutState.elements.forEach((e=>{this.getCommandDispatcher()(new l(e.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async ensureStepsAreLoaded(){const e=this.initialReducerState?JSON.parse(this.initialReducerState):void 0;this.processingStepInitialisation=!0,await De.cacheRequiredOptions(this.workflow);const t=this.allScenes,a=jt(t,this.stepSelections).map((e=>e.silentSteps)).flat(),{stepElements:i,commands:n}=await this.stepElementsForIntroducedSilentSteps(a);this.stepElements={...this.stepElements,...i};const o=$t(this.allScenes,this.stepSelections).map((e=>e.renderableSteps)),s=[],r=[];n.forEach((e=>s.push({command:e,followup:async()=>{}})));const l=o.flat();for(const t of l)if(!this.stepInitialised[t.stepName]&&!this.stepNotReadyForInitialization(t))switch(this.stepInitialised[t.stepName]=!0,t.type){case"Bulk":this.updateStorage("Bulk",e?.serializableWorkflow.steps.find((e=>"Bulk"===e.stepName))?.storage||{});break;case"DigitalContent":s.push(await na.init(t,this,e));break;case"Finish":case"Introduction":default:break;case"Frame":case"Photo":const a=new Zt(t.data.forceImageCover);a.connectWorkflowManager(this,t.stepName),this.stepSpecificServices[t.stepName]={frameService:a},s.push(await oa.init(t,this,e));break;case"Illustration":s.push(await _t.init(t,this,e));break;case"Material":r.push(await sa.init(t,this,e));break;case"Model":r.push(await ra.init(t,this,e));break;case"Module":const i=t.data.module;this.stepSpecificServices[t.stepName]={module:await ue(i)},s.push(await la.init(t,this,e));break;case"Patchwork":s.push(await ha.init(t,this,e));break;case"Picture":s.push(await pa.init(t,this,e));break;case"Question":r.push(await Dt.init(t,this,e));break;case"Shape":s.push(await ua.init(t,this,e));break;case"Text":s.push(await va.init(t,this,e))}const c=s.filter((e=>!!e));for(const e of c)this.commandContext.apply(e.command),await e.followup();const d=r.filter((e=>!!e));if(d.length>0)for(const e of d)await e();(c.length>0||d.length>0)&&await this.ensureStepsAreLoaded();const h=l.map((e=>{if(De.getLocalOrUndefined(e.optionId))return De.getDefaultVariant(De.getLocalOrUndefined(e.optionId).data)}));(e||l.length>0&&!h.some((e=>!!e))||c.length>0||d.length>0)&&(this.ensuredInitialised=!0,this.onEnsuredInitialisedChange()),this.processingStepInitialisation=!1,this.onSelectionChange(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((e=>e(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((e=>e(this.editedSteps)))}onEnsuredInitialisedChange(){this.ensuredInitialisedCallbacks.forEach((e=>e(this.ensuredInitialised)))}onElementsChange(){this.elementsCallbacks.forEach((e=>e(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((e=>e(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((e=>e(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((e=>{e(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((e=>e(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((e=>{e(this.stepMetadata)}))}onSelectionChange(){this.selectionCallbacks.forEach((e=>e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:this.traversableScenes()})))}onStepSpecificStorageChange(e){Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].forEach((t=>t(this.storage[e])))}onStorageChange(){this.storageCallbacks.forEach((e=>e(this.storage)))}onUpdateChange(){this.updateCallbacks.forEach((e=>{e(this.pendingUpdates.length>0)}))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((e=>{e(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((e=>{e(this.variationRecords)}))}traversableScenes(){const e=this.allScenes;return qt(e,this.stepSelections)}}function Ia(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Ea{constructor(t){if(Ia(this,"commandContext",void 0),Ia(this,"workflowManager",void 0),Ia(this,"isReadOnly",void 0),!t.workflow)throw new Error("No Workflow ID provided.");const a=t.layouts;this.commandContext=new e;const i=t.transaction.workflowState?JSON.parse(t.transaction.workflowState):void 0;this.commandContext.initialize(a,i),this.isReadOnly=!!t.transaction.lineItem?.id||!kt.getMap("transactionOwnerIds")?.get(t.transaction.id);this.workflowManager=new ka(t.workflow,t.product.profanities?.map((e=>e.word))||[],a,this.commandContext,(async e=>{this.isReadOnly||je.getShadowGraphqlClient().mutate({...e,mutation:Rt})}),t.transaction,t.previewService,t.renderableContextService,t.product)}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(e){await je.getShadowGraphqlClient().mutate({mutation:Mt,variables:{transactionId:this.workflowManager.getTransaction().id,updates:e.map((e=>({recordNumber:e.recordNumber,values:e.values.map((e=>({aspect:e.aspect,stepName:e.stepName,value:e.value})))})))}})}async createPreviewImage(){const e=document.createElement("canvas");e.width=1024,e.height=1024;const a=this.commandContext.getAllLayouts()[this.workflowManager.getWorkflow().defaultPreviewPanelIndex||0],i=a.layoutState.layout.previewRegion?{x:a.layoutState.layout.previewRegion.left,y:a.layoutState.layout.previewRegion.top,width:a.layoutState.layout.previewRegion.width,height:a.layoutState.layout.previewRegion.height}:{x:0,y:0,width:a.layoutState.layout.width,height:a.layoutState.layout.height},n=this.commandContext.getLayoutById(a.layoutState.layout.id),o=e.getContext("2d");if(!o)throw new Error("Failed to build 2D context for preview image creation.");const s=t(n.layoutState.layout,n.layoutState.elements,{region:i}),r=await le.from(o,s,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await r.render();const l=await(async e=>new Promise(((t,a)=>{try{e.toBlob((e=>{if(e){const a=URL.createObjectURL(e);t(a)}}))}catch(e){a(e)}})))(e);return e.toDataURL(l)}getStepById(e){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepName===e));if(t)return new Tt(this.getWorkflowManager(),t)}getStepByName(e){const t=this.getWorkflowManager().getWorkflow().steps.find((t=>t.stepTitle===e));if(t)return new Tt(this.getWorkflowManager(),t)}getStepsByType(e){return this.getWorkflowManager().getWorkflow().steps.filter((t=>t.type===e)).map((e=>new Tt(this.getWorkflowManager(),e)))}async onDesignFinished(e,t,a,i){const n=(e,t,a)=>{const i={};return t.steps.forEach((t=>{Object.assign(i,(t=>{const i={};if("Frame"===t.type){const n=e[t.stepName],o=t.data;if(!n||o.hideImageInCart&&a)return i;i[`${t.stepTitle} exportedData.image`]=n.image}if("Illustration"===t.type){const n=e[t.stepName],o=t.data;if(!n||o.hideColorsInCart&&a||!n.colors)return i;if(n.colors.length>0){const e=n.colors.join(", ").toUpperCase();i[`${t.stepTitle} exportedData.colors`]=e}}if("Module"===t.type){const n=e[t.stepName],o=t.data;if(!n||o.hideTextInCart&&a)return i;i[`${t.stepTitle} exportedData.text`]=n.text}if("Text"===t.type){const n=e[t.stepName];if(!n)return i;const o=t.data;o.hideTextInCart&&a||(i[`${t.stepTitle} exportedData.text`]=n.text),!n.color||o.hideColorInCart&&a||(i[`${t.stepTitle} exportedData.color`]=n.color)}return i})(t))})),i},o=(e,t,a,i,n,o,s,r,l)=>({event:"onComplete",lineItemImageUrl:s?s.href:"",transactionId:e.id,metadata:n,selectedVariants:r,designProductVariantId:e.externalDesignProductVariantId,designProductId:e.externalDesignProductId,baseCost:a,weight:t.weight,optionsCost:i,exportedData:o,sku:l,workflowViewerLink:e.workflowViewerLink||""}),s=async(e,t,a,i,s,r,l)=>{const c=(e.product?.basePrice||0)*(e.variationsCount||0),d=e.priceModifierTotal||0,h=((e,t,a,i)=>{const o={};let s;if(a){s=n(a,t,!1);for(const e of Object.keys(s))o[e]={value:s[e],priceModifier:0}}else if(i){s=i;for(const e of Object.keys(s))o[e]={value:s[e],priceModifier:0}}for(const a of Object.keys(e)){const i=e[a],n=t.steps.find((e=>e.stepTitle===a));if(1===i.length)o[`${n?.stepTitle} exportedData.selection`]={value:i[0].name,priceModifier:i[0].priceModifier};else if(i.length>1)for(let e=0;e<i.length;e++)o[`${n?.stepTitle} exportedData.selection ${e+1}`]={value:i[e].name,priceModifier:i[e].priceModifier}}return o})(i,a,void 0,r);return o(e,t,c,d,r,h,l,i,s)};return(async(e,t,a,i,r,l,c,d,h,p,u,m)=>{h("workflow.steps.finish.finalize.buildingLayouts"),await e.outstandingRequestsPromise();const f=je.getShadowGraphqlClient();await f.resetStore();const g=await f.mutate({mutation:Lt,variables:{id:l.id}}),w=g.data?.transactions[0].workflowState;!g.errors&&w||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(i())),g.errors&&g.errors.forEach((e=>{g.errors&&console.log("Server Error:",e.message)})),await e.updateStateWithServerImmediate(i),console.log("Server state is undefined @ Workflow completion"));const y=e.getPreviewService(),v=t?.finalizeStepConfig?.lookAtAnimation,S=y&&100===y.getSceneInitializationProgress()&&t.showModelOnFinishStep&&v,b=m&&n(m,t,!0),C=m&&n(m,t,!1),x=e=>{const a={};let i=0;if(Object.keys(c).length>0)for(const n of Object.keys(c)){const o=c[n],s=t.steps.find((e=>e.stepName===n));for(let t=0;t<o.selections.length;++t){const n=o.selections[t];if(s&&(!e||De.getLocalOrUndefined(s.optionId)&&De.getLocalOrUndefined(s.optionId).data.variants.length>1&&!s.data.hideSelectionInCart&&!s.data.hideSelectionsInCart)){const e=s.stepTitle;a[e]?a[e].push({id:n.id||"",name:n.name,priceModifier:n.priceModifier}):a[e]=[{id:n.id||"",name:n.name,priceModifier:n.priceModifier}]}i+=n.priceModifier}}return[a,i]},[k]=x(!0),I=Object.fromEntries(Object.keys(k).map((e=>[e,k[e].map((e=>e.id))]))),[E]=x(!1),N=Object.fromEntries(Object.keys(E).map((e=>[e,E[e].map((e=>e.id))]))),R=await this.createPreviewImage();h("workflow.steps.finish.finalize.creatingDesign");const O=(await We.execute("createDesign",{designDetails:(()=>{const e={designName:d,layouts:a.map((e=>({index:e.index,panelId:e.panelId}))),workflowId:t.id,productId:r.id,transactionId:l.id,threeDimPreview:!!S,previewImage:R};return m&&(e.metadata=C),I&&(e.selectedVariants=N),e})()})).body,M=O.links.find((e=>"image"===e.rel));h("workflow.steps.finish.finalize.updatingTransaction");const P=(await je.getShadowGraphqlClient().query({query:Pt,variables:{id:l.id}})).data.transactions[0];return l.bulk?(await p(u),((e,t,a)=>{const i=(e.product?.basePrice||0)*(e.variationsCount||0),n=e.priceModifierTotal||0,s={items:{value:e.variationsCount?`${e.variationsCount}`:"0",priceModifier:0}};return o(e,t,i,n,void 0,s,a)})(P,r,M)):await s(P,r,t,k,O.data.sku,b,M)})(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),e,this.workflowManager.getTransaction(),a,this.workflowManager.getWorkflow().name,t,(e=>this.updateVariationRecords(e)),this.workflowManager.getVariationRecords(),i)}}function Na(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}class Ra{constructor(e){Na(this,"layouts",void 0),Na(this,"handleCompleteRender",void 0),this.handleCompleteRender=null;const t=new Map;e.forEach((e=>t.set(e.id,new Ma(e.id,e.name,this)))),this.layouts=t}setCompleteRenderCallback(e){this.handleCompleteRender=e,e(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}}let Oa;class Ma{constructor(e,t,a){Na(this,"hasSetStaticContext",!1),Na(this,"id",void 0),Na(this,"name",void 0),Na(this,"service",void 0),Na(this,"interactiveDirty",!1),Na(this,"textureCtx",void 0),Na(this,"staticCtxDirty",!1),Na(this,"lastRequestedRenderArguments",void 0),Na(this,"lastCompletedStaticRender",void 0),Na(this,"lastModificationID",void 0),Na(this,"renderQueue",new Ht(2)),Na(this,"rehydrated",!1),this.id=e,this.name=t,this.service=a}getID(){return this.id}getName(){return this.name}getStaticContext(){return this.textureCtx}setStaticContext(e){if(this.textureCtx=e,this.lastRequestedRenderArguments){const{workflow:e,layouts:t,variationRecord:a,productOverlayImageUrl:i}=this.lastRequestedRenderArguments;this.render(e,t,a,i)}}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(e){this.staticCtxDirty=e}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(e){this.interactiveDirty=e}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}getLastModificationID(){return this.lastModificationID}async render(e,t,a,i){const n=pe(t);this.lastRequestedRenderArguments={workflow:e,layouts:n,variationRecord:a,productOverlayImageUrl:i};const o=this.getStaticContext();if(!o)return this.markLastCompletedStaticRender(),void this.setStaticContextDirty(!1);this.renderQueue.enqueue(new Pa(this.getID(),o,(()=>{if(void 0!==Oa)return Oa;const e=document.createElement("canvas").getContext("webgl2");return Oa=!!e,Oa})(),(()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)}),e,n,a,(async()=>{const e={layouts:{},serializableWorkflow:{steps:[]}};if(t.forEach((t=>{e.layouts[t.layoutState.layout.id]=t.layoutState})),!this.rehydrated){await Ie(e);const t=Object.keys(e.layouts);for(let a=0;a<t.length;a++){const i=t[a],n=e.layouts[i].elements.filter((e=>"illustration"===e.type));for(let e=0;e<n.length;++e){const t=n[e];t.src&&t.svg&&(t.cachedObjectURL=await Qt(t.svg))}}this.rehydrated=!0}}),i))}}class Pa extends Kt{constructor(e,t,a,i,n,o,s,r,l){super(),Na(this,"layoutId",void 0),Na(this,"ctx",void 0),Na(this,"nonPOTSupport",void 0),Na(this,"onRender",void 0),Na(this,"workflow",void 0),Na(this,"layouts",void 0),Na(this,"variationRecord",void 0),Na(this,"preprocess",void 0),Na(this,"productOverlayImageUrl",void 0),this.layoutId=e,this.ctx=t,this.nonPOTSupport=a,this.onRender=i,this.workflow=n,this.layouts=o,this.variationRecord=s,this.preprocess=r,this.productOverlayImageUrl=l}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return!navigator.userAgent.includes("SamsungBrowser")&&(!!window.Worker&&!!window.OffscreenCanvas)}async execute(){const e=this.layouts.find((e=>e.layoutState.layout.id===this.layoutId));if(!e)return;const a=e.layoutState.elements||[];if(await this.preprocess(),this.variationRecord){const t=this.variationRecord.values.map((e=>({stepName:e.stepName,stepAspectType:e.aspect,value:e.value})));for(const e of this.workflow.steps)if(e.optionId&&!e.option){e.option=await De.getLocalOrFromServer(We,e.optionId);for(const t of e.option.data.variants)t.assetKey&&!t.asset&&(t.asset=await bt.getLocalOrFromServer(t.assetKey))}const i=await Da(La(t,this.workflow),this.workflow,this.layouts.map((e=>e.layoutState.layout)),this.productOverlayImageUrl),n=i?.layouts[e.layoutState.layout.id];(n?.elements||[]).forEach((e=>{const t=a.find((t=>t.stepName===e.stepName));t&&t.type===G.Textbox?(t.text=e.text,t.fontSize=e.fontSize):a.push(e)})),a.sort(((e,t)=>void 0!==e.layerIndex&&void 0!==t.layerIndex?e.layerIndex-t.layerIndex:0))}const i=e.layoutState.layout.width,n=e.layoutState.layout.height,o=this.getDynamicTextureResolution().width,s=this.getDynamicTextureResolution().height;let r,l;if(this.nonPOTSupport){i/n<o/s?(r=o,l=n*(o/i)):(r=i*(s/n),l=s)}else r=this.getDynamicTextureResolution().width,l=this.getDynamicTextureResolution().height;const c=t(e.layoutState.layout,a),d=await ce.from(this.ctx,c,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1});d.resize(r,l),await d.render(),this.onRender()}}const La=(e,t)=>{const a=[];return e.forEach((e=>{const i=t.steps.find((t=>t.stepName===e.stepName));i?.type===de.Text&&"Text"===e.stepAspectType&&a.push({name:i.stepName,data:{text:e.value}})})),a},Da=async(e,t,a,i)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};a.forEach((e=>{n=new v(e).apply(n)}));return(await Pe(e,t,a,i)).forEach((e=>{n=e.apply(n)})),n};function Aa(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}const Ta=async e=>(await We.execute("getProductById",{productId:e})).body,za=(e,t)=>{const a=e.workflowState,i=a?JSON.parse(a):void 0;return i?Object.values(i.layouts).map((e=>e.layout)):t.panels.sort(((e,t)=>e.index-t.index)).map((e=>({id:ct(),panelId:e.name,name:e.name,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion})))};class Va{constructor(e){Aa(this,"options",void 0),Aa(this,"initialized",void 0),Aa(this,"experienceOptions",void 0),this.initialized=!1,this.options=e}async initFromIntegrationProduct(e){if(""===e)throw new Error("No integration product ID provided.");this.options.useUncachedEndpoints&&We.setUncachedOperations(["getAssetByKeyV2","getWorkflowV2","getMaterialV2","getOptionV2"]);const t=je.getShadowGraphqlClient();await t.resetStore();const a=await t.mutate({mutation:It,variables:{integrationProductId:e,bulk:this.options.bulk||!1}}),i=(await t.mutate({mutation:Et,variables:{id:a.data?.transactionCreate.id}})).data?.transactionClaim;if(!i)throw new Error("Failed to create transaction.");const n=kt.getMap("transactionOwnerIds")||new Map;n.set(i.id,i.transactionOwnerId),Ue(i.transactionOwnerId||""),kt.setMap("transactionOwnerIds",n);const o=await Ta(i.product?.id||"");this.experienceOptions={product:o.data,transaction:i,layouts:[]},this.initialized=!0}async initFromTransaction(e){if(""===e)throw new Error("No transaction ID provided.");const t=je.getShadowGraphqlClient();await t.resetStore();const a=kt.getMap("transactionOwnerIds")||new Map,i=a.get(e);if(i){Ue(i);const a=(await t.query({query:Nt,variables:{id:e}})).data?.transactions[0];if(!a)throw new Error("Failed to read transaction.");const n=await Ta(a.product?.id||"");return this.experienceOptions={product:n.data,transaction:a,layouts:[]},void(this.initialized=!0)}const n=(await t.mutate({mutation:Et,variables:{id:e}})).data?.transactionClaim;if(!n)throw new Error("Failed to read transaction.");n.transactionOwnerId&&(a.set(n.id,n.transactionOwnerId),Ue(n.transactionOwnerId),kt.setMap("transactionOwnerIds",a));const o=await Ta(n.product?.id||"");this.experienceOptions={product:o.data,transaction:n,layouts:[]},this.initialized=!0}async getWorkflowExperience(e,t,a){if(!this.initialized||!this.experienceOptions)throw new Error("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const e=(await We.execute("getWorkflowV2",{workflowSlug:this.experienceOptions.transaction.workflowId})).body.data;if(this.experienceOptions.workflow=e,this.experienceOptions.transaction.workflowState){const e=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(e.layouts).map((e=>e.layout))}return this.experienceOptions.previewService=a&&a(e),this.experienceOptions.renderableContextService=new Ra(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&await(this.experienceOptions.previewService?.initialize(this.experienceOptions.product.modelUrl,this.experienceOptions.renderableContextService)),new Ea(this.experienceOptions)}if(e){const i=(await We.execute("getWorkflowV2",{workflowSlug:e})).body.data;if(this.experienceOptions.workflow=i,await je.getShadowGraphqlClient().mutate({mutation:Ot,variables:{workflowId:e,id:this.experienceOptions.transaction.id}}),t){this.experienceOptions.transaction.workflowState=t;const e=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(e.layouts).map((e=>e.layout))}else this.experienceOptions.layouts=za(this.experienceOptions.transaction,this.experienceOptions.workflow);return this.experienceOptions.previewService=a&&a(i),this.experienceOptions.renderableContextService=new Ra(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&await(this.experienceOptions.previewService?.initialize(this.experienceOptions.product.modelUrl,this.experienceOptions.renderableContextService)),new Ea(this.experienceOptions)}throw new Error("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new Error("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new Error("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}class Ua{getVariationRecords(){return[]}async reset(){}updateStateWithServer(e){}addVariationRecord(e){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(e){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addCurrentVariationCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}addUpdateCallback(e){}addVariationRecordsCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getProductName(){return""}getProfanities(){return[]}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(e){}getWorkflowSelections(){return{}}setCurrentAdjustingStepId(e){}setAllScenes(e){}setCurrentVariationRecord(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,a){}setVariationRecords(e){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}}export{Va as Client,e as CommandContext,Te as spiffCoreConfiguration,Ht as PromiseQueue,Kt as QueueablePromise,Ua as MockWorkflowManager,ba as InformationMessageType,bt as assetService,De as optionService,We as server,kt as persistenceService,je as graphQlManager,fa as toast,Zt as FrameService,oa as frameStepService,ra as modelStepService,sa as materialStepService,ha as patchworkStepService,ua as shapeStepService,Dt as questionStepService,na as digitalContentStepService,la as moduleStepService,pa as pictureStepService,va as textStepService,_t as illustrationStepService,Qt as svgObjectURL,ct as generate,a as CreateElementCommand,i as TextChangeCommand,n as FontAlignmentCommand,o as FontColorCommand,S as LayoutElementFactory,dt as minZoom,vt as AdvancedEditor,yt as EditorCore,$e as useLayouts,Qe as useEditorState,ht as useEditorInteraction,Xe as commandReducer,He as getDefaultState,qe as CommandContextContext,Ye as AdvancedEditorStateProvider,Ge as AdvancedEditorContext,Ze as UICommand,Be as EditorSubMenu,zt as gatherVaryingStepAspects,b as SpiffCommerce3DPreviewService,C as ProductCameraRig};
98
98
  //# sourceMappingURL=module.js.map
package/dist/types.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { StepAspect, Workflow, AnyStepData, Step, Asset, AssetType, IServerModel, MaterialResource, IllustrationStepData, VariantResource, DigitalContentStepData, FrameStepData, MaterialStepData, ModelStepData, ModuleStepData, PatchworkStepData, PictureStepData, QuestionStepData, ShapeStepData, TextStepData as _TextStepData1, CameraAnimation, ModelAnimation, OptionResource, StepType, TextStepData } from "papyrus/build/main/generation/Workflow";
1
+ import { StepAspect, Workflow, AnyStepData, Step, Asset, AssetType, IServerModel, MaterialResource, IllustrationStepData, VariantResource, DigitalContentStepData, FrameStepData, MaterialStepData, ModelStepData, ModuleStepData, PatchworkStepData, PictureStepData, QuestionStepData, ShapeStepData, TextStepData as _TextStepData1, OptionResource, StepType, TextStepData } from "papyrus/build/main/generation/Workflow";
2
2
  import { PatternImageData, FrameData as _FrameData1, Point, ScaleAxis, UnitOfMeasurement } from "papyrus/build/main/types";
3
3
  import { FrameOffsets, ColorDefinition, ILayout, IllustrationElement as _IllustrationElement1, LayoutsState as _LayoutsState1, Region, FrameElement as _FrameElement1, PatchworkOffsets, TextboxElement as _TextboxElement1, FontData, SerializableStep, StepStorage, FrameElement, IllustrationElement, LayoutElement, LayoutsState, PatchworkElement, TextboxElement, ImageElement } from "papyrus/build/main/LayoutsState/types";
4
4
  import { ApolloClient } from "@apollo/client";
5
5
  import { CanvasCommand, CreateElementCommand as _CreateElementCommand1, GroupCommand, CreateElementCommand, FontAlignmentCommand, FontColorCommand, TextChangeCommand } from "papyrus/build/main/command";
6
6
  import { LayoutData as _LayoutData1, CommandState, CommandContext as _CommandContext1, CommandContext, LayoutData } from "papyrus/build/main/CommandContext";
7
7
  import { ModuleProduct } from "papyrus/build/main/module/ModuleProduct";
8
+ import { ThreeDPreviewService as _ThreeDPreviewService1, LoadProgressEventData, ProductCameraRig, SpiffCommerce3DPreviewService, ThreeDPreviewService } from "spiff-preview";
8
9
  import { ReactNode, Dispatch, FunctionComponent, RefObject, PointerEvent, KeyboardEvent, MouseEvent } from "react";
9
- import { ThreeDPreviewService as _ThreeDPreviewService1, SpiffCommerce3DPreviewService } from "spiff-preview";
10
10
  import { LayoutElementFactory } from "papyrus/build/main/Elements/factory";
11
11
  export const gatherVaryingStepAspects: (workflow: Workflow) => StepAspect[];
12
12
  export interface WorkflowScene {
@@ -418,7 +418,7 @@ export interface WorkflowManager {
418
418
  getVariationRecords: () => VariationRecord[];
419
419
  getLayouts: () => ILayout[];
420
420
  getLayoutPreviewService: () => any;
421
- getPreviewService: () => ThreeDPreviewService | undefined;
421
+ getPreviewService: () => _ThreeDPreviewService1 | undefined;
422
422
  getProductName: () => string | undefined;
423
423
  getProfanities: () => string[];
424
424
  getRegionElements: (stepName: string) => RegionElement[];
@@ -760,316 +760,6 @@ interface FrameData {
760
760
  */
761
761
  height: number;
762
762
  }
763
- type ThreeDPreviewService = {
764
- /**
765
- * Allows listeners to be aware of the camera losing focus of the
766
- * main product.
767
- * @param listener A function to be called when focus is lost.
768
- */
769
- registerFocusLostListener(listener: () => void): void;
770
- /**
771
- * Removes a listener from the focusLost observers. The listener will
772
- * no longer be notified
773
- * @param listener The listener to remove.
774
- */
775
- unregisterFocusLostListener(listener: () => void): void;
776
- /**
777
- * Providers listeners with information about load progress when
778
- * the preview is loading scenes.
779
- * @param listener A function to get load progress updates
780
- */
781
- registerLoadProgressListener(listener: (e: LoadProgressEventData) => void): void;
782
- /**
783
- * Allows you to pass any function that originally called registerLoadProgressListener()
784
- * to have it excluded from load progress updates.
785
- * If the function was never registered this call has no effect.
786
- * @param listener The listener to exclude from load progress.
787
- */
788
- unregisterLoadProgressListener(listener: (e: LoadProgressEventData) => void): void;
789
- /**
790
- * Request that the scene renders to a given canvas
791
- * @param canvas The canvas we should render to.
792
- */
793
- registerView(canvas: HTMLCanvasElement): void;
794
- /**
795
- * Returns the number of active viewers of the scene. Useful for
796
- * avoiding unnecessary rendering when there are no active viewers.
797
- */
798
- getNumViewports(): number;
799
- /**
800
- * Tells babylon that we no longer want the given canvas to be rendered to.
801
- * @param canvas The canvas to be excluded from rendering.
802
- */
803
- unregisterView(canvas: HTMLCanvasElement): void;
804
- /**
805
- * Shutdown the preview engine. Noop if the engine is not initialized.
806
- */
807
- shutdown(): void;
808
- /**
809
- * Initialize the scene. Also initialize the engine, if it hasn't been done already.
810
- */
811
- initialize(src: string, contextService?: RenderableContextService): Promise<void>;
812
- /**
813
- * Executes an animation in the currently loaded scene.
814
- * @param animation The current animation track to run.
815
- */
816
- executeModelAnimation(animation: ModelAnimation): void;
817
- /**
818
- * Executes an animation of the camera.
819
- * @param animation The animation to execute.
820
- */
821
- executeCameraAnimation(animation: CameraAnimation): void;
822
- /**
823
- * Returns the values of the Arc Rotate Camera
824
- */
825
- getCameraPose(): CameraPose | undefined;
826
- /**
827
- * Sets the values of the Arc Rotate Camera
828
- */
829
- setCameraPose(cameraPose: CameraPose): void;
830
- /**
831
- * Applies a given material modifier to a target material in the scene.
832
- * @param targetMaterial The material to target.
833
- * @param key A unique key used to identify this action.
834
- * @param material The material modifier to apply.
835
- */
836
- applyMaterialVariant(targetMaterial: string, key: string, material: MaterialResource, removeWhenUndefined?: boolean): Promise<void>;
837
- /**
838
- * Applies a given model variant to the scene.
839
- * @param key A unique key used to identify this action.
840
- * @param modelDetails An asset containing a model file to be loaded into the scene.
841
- */
842
- applyModelVariant(key: string, modelDetails: ModelDetails, replaceProductModel: boolean): Promise<void>;
843
- /**
844
- * Controls the current control state of the camera.
845
- * @param rigType The control type to use.
846
- */
847
- setCameraState(rigType: ProductCameraRig): void;
848
- /**
849
- * Restores the product camera to it's last set focus point. If the user has
850
- * been panning this will animate the camera to the original focus point. If the camera is still
851
- * focused on it's origin point this function is a noop.
852
- */
853
- animateToLastCameraFocus(): Promise<void>;
854
- /**
855
- * When configuration has allowed for auto rotation we
856
- * can pause the rotation via this function.
857
- * @param shouldAutoRotate When true rotation is running, paused otherwise.
858
- */
859
- setAutoRotation(shouldAutoRotate: boolean): void;
860
- /**
861
- * Get current load progress for the scene.
862
- */
863
- getSceneInitializationProgress(): number;
864
- /**
865
- * Returns the current configuration object applied to the scene.
866
- */
867
- getCurrentConfiguration(): PreviewOptions | undefined;
868
- /**
869
- * Takes a screenshot of the scene using a given
870
- * camera animation otherwise using the existing orientation
871
- * of the camera in the scene. A resolution must be provided
872
- * to render the scene at.
873
- */
874
- renderSceneScreenshot(resolution: number, cameraAnimation: CameraAnimation): Promise<string>;
875
- /**
876
- * Returns true when the current configuration allows the user
877
- * to rotate around the product.
878
- */
879
- orbitEnabled(): boolean;
880
- /**
881
- * When called will trigger the internal engine to match the current
882
- * canvas size. This ensures the image renders correctly in the view and
883
- * also prevents performance problems.
884
- */
885
- fireResizeEvent(): void;
886
- /**
887
- * A callback when the user clicks in the scene and a material is hit.
888
- */
889
- onMaterialSelected(cb: (material: MaterialHandle) => void): void;
890
- /**
891
- * Designed for use when utilizing the 3D preview in an editor format.
892
- * List named materials that are available in the scene.
893
- */
894
- listMaterials(): readonly MaterialHandle[];
895
- /**
896
- * Designed for use when utilizing the 3D preview in an editor format.
897
- * Given a list of material names, highlights the associated meshes in the scene.
898
- */
899
- setHighlights(materials: readonly MaterialHandle[], color?: readonly [number, number, number]): void;
900
- };
901
- /**
902
- * Details relating to a model for use in the preview.
903
- */
904
- type ModelDetails = {
905
- readonly model?: string;
906
- readonly contextService: RenderableContextService;
907
- };
908
- /**
909
- * Represents a service capable of managing and returning contexts that
910
- * can be used for rendering to textures in the 3D preview.
911
- */
912
- type RenderableContextService = {
913
- /**
914
- * Returns all managed renderable contexts.
915
- */
916
- getAll(): ReadonlyMap<string, RenderableContext>;
917
- };
918
- /**
919
- * A renderable context represents the relationship of a texture in the 3D preview
920
- * with an external canvas. This context allows external clients to render to a texture
921
- * in the 3D preview with a simple interface.
922
- */
923
- type RenderableContext = {
924
- /**
925
- * A unique identifier for this renderable context.
926
- */
927
- getID(): string;
928
- /**
929
- * A name for this renderable.
930
- */
931
- getName(): string;
932
- /**
933
- * Sets the render context associated to this renderable.
934
- * @param ctx The context to use for rendering.
935
- */
936
- setStaticContext(ctx: CanvasRenderingContext2D): void;
937
- /**
938
- * Get the render context associated to this renderable.
939
- */
940
- getStaticContext(): CanvasRenderingContext2D | undefined;
941
- /**
942
- * Sets whether or not this renderable is dirty and will need re-rendering.
943
- * @param value The new value
944
- */
945
- setStaticContextDirty(value: boolean): void;
946
- /**
947
- * When this context has been set as dirty, returns true.
948
- */
949
- getStaticContextDirty(): boolean;
950
- /**
951
- * A timestamp for the last successful render of the context.
952
- */
953
- getLastCompletedStaticRender(): number | undefined;
954
- };
955
- /**
956
- * Represents a handle to a material in the 3D scene. The underlying complexity of materials is abstracted
957
- * away so the client doesn't need to know anything more than the ID they're given and the name.
958
- */
959
- type MaterialHandle = {
960
- /**
961
- * The identifier for the material.
962
- */
963
- readonly id: string;
964
- /**
965
- * The human readable name for the material.
966
- */
967
- readonly name: string;
968
- };
969
- /**
970
- * Settings related to the 3D preview.
971
- */
972
- type PreviewOptions = {
973
- /**
974
- * The color expected to be seen in the background of the product. Expects a hexadecimal value.
975
- */
976
- readonly backgroundColor?: string;
977
- /**
978
- * Image to be used as a background when running withh transparency, the image
979
- * will be scaled and centered to fill the preview based on aspect ratio.
980
- */
981
- readonly backgroundImage?: string;
982
- /**
983
- * The closest zoom the camera can achieve to the product.
984
- */
985
- readonly maxZoomOverride?: number;
986
- /**
987
- * The furthest zoom the camera can achieve to the product.
988
- */
989
- readonly minZoomOverride?: number;
990
- /**
991
- * The environment file used to calculate product lighting.
992
- */
993
- readonly environmentFile?: string;
994
- /**
995
- * The lowest point, vertically, that the camera can rotate to.
996
- * https://doc.babylonjs.com/divingDeeper/cameras/camera_introduction
997
- */
998
- readonly lowerBetaLimitDeg?: number;
999
- /**
1000
- * The highest point, vertically, that the camera can rotate to.
1001
- * https://doc.babylonjs.com/divingDeeper/cameras/camera_introduction
1002
- */
1003
- readonly upperBetaLimitDeg?: number;
1004
- /**
1005
- * The leftmost point, horizontally, that the camera can rotate to.
1006
- * https://doc.babylonjs.com/divingDeeper/cameras/camera_introduction
1007
- */
1008
- readonly lowerAlphaLimitDeg?: number;
1009
- /**
1010
- * The rightmost point, horizontally, that the camera can rotate to.
1011
- * https://doc.babylonjs.com/divingDeeper/cameras/camera_introduction
1012
- */
1013
- readonly upperAlphaLimitDeg?: number;
1014
- /**
1015
- * When set the product while rotate slowly
1016
- */
1017
- readonly autoRotation?: boolean;
1018
- /**
1019
- * Time in milliseconds before the product starts rotating after a user input has taken control.
1020
- */
1021
- readonly idleTimeBeforeRotation?: number;
1022
- /**
1023
- * When set the 3D preview won't attempt to orient the product automatically to its front view at load.
1024
- */
1025
- readonly disableAutomaticOrientation?: boolean;
1026
- /**
1027
- * When true the action bar won't be displayed to the user.
1028
- */
1029
- readonly disableActionBar?: boolean;
1030
- /**
1031
- * When set, mousing over the model in this preview will highlight the associated mesh/material.
1032
- * When layout contexts are provided, only the materials with matching names will highlight.
1033
- */
1034
- readonly highlightOnMaterialHover?: boolean;
1035
- /**
1036
- * Sets the color of highlights when enabled. Expects hexadecimal value.
1037
- */
1038
- readonly highlightColor?: string;
1039
- };
1040
- /**
1041
- * Defines the different behaviors supported by the camera system
1042
- * for control when viewing a product.
1043
- */
1044
- enum ProductCameraRig {
1045
- Orbit = 0,
1046
- Pan = 1
1047
- }
1048
- /**
1049
- * Identical to CameraAnimation typing, however the
1050
- * target is always available and hence is not optional.
1051
- */
1052
- type CameraPose = {
1053
- readonly lonDeg: number;
1054
- readonly radius: number;
1055
- readonly latDeg: number;
1056
- readonly target: {
1057
- readonly x: number;
1058
- readonly y: number;
1059
- readonly z: number;
1060
- };
1061
- };
1062
- type LoadProgressEventData = {
1063
- /**
1064
- * The total load value of the scene, this is an average of all
1065
- * 'in progress' loading events. when all events are fully loaded this value will be 100.
1066
- */
1067
- readonly loadValue: number;
1068
- /**
1069
- * This value is true when the base model and scene have been initialized.
1070
- */
1071
- readonly sceneInitialized: boolean;
1072
- };
1073
763
  declare class OptionService {
1074
764
  /**
1075
765
  * Returns a promise that resolves once all options required for a given workflow
@@ -1434,7 +1124,7 @@ export class Client {
1434
1124
  /**
1435
1125
  * @returns The preview service that was provided during construction.
1436
1126
  */
1437
- getPreviewService(): import("types")._ThreeDPreviewService1;
1127
+ getPreviewService(): _ThreeDPreviewService1;
1438
1128
  /**
1439
1129
  * @returns The product associated with this client.
1440
1130
  */
@@ -1515,6 +1205,7 @@ export class MockWorkflowManager implements WorkflowManager {
1515
1205
  export { CommandContext };
1516
1206
  export { CreateElementCommand, TextChangeCommand, FontAlignmentCommand, FontColorCommand, LayoutElementFactory };
1517
1207
  export { LayoutElement, ImageElement, TextboxElement, TextStepData, FrameElement, PatchworkElement, IllustrationElement, LayoutData, LayoutsState };
1518
- export { SpiffCommerce3DPreviewService };
1208
+ export { SpiffCommerce3DPreviewService, ProductCameraRig };
1209
+ export { ThreeDPreviewService, LoadProgressEventData };
1519
1210
 
1520
1211
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/main.js",