@vvfx/sdk 0.0.0-alpha.48 → 0.0.0-alpha.49

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/index.js CHANGED
@@ -1 +1 @@
1
- var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=t=>{throw TypeError(t)},a=(e,i)=>{for(var s in i)t(e,s,{get:i[s],enumerable:!0})},n=(r,a,n,o)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let c of i(a))s.call(r,c)||c===n||t(r,c,{get:()=>a[c],enumerable:!(o=e(a,c))||o.enumerable});return r},o=(t,e,i)=>(n(t,e,"default"),i&&n(i,e,"default")),c=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),h=(t,e,i)=>e.has(t)||r("Cannot "+i),l=(t,e,i)=>(h(t,e,"read from private field"),i?i.call(t):e.get(t)),p=(t,e,i)=>e.has(t)?r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),m=(t,e,i,s)=>(h(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i),d=(t=>(t[t.BringToFront=0]="BringToFront",t[t.SendToBack=1]="SendToBack",t[t.BringForward=2]="BringForward",t[t.SendBackward=3]="SendBackward",t))(d||{});import"@galacean/effects";import{spec as g,VFXItem as u,Player as f,math as y,Composition as x,EventEmitter as w,assertExist as v,SpriteComponent as I,TextComponent as P,Texture as C,generateGUID as b}from"@galacean/effects";import"@galacean/effects-plugin-rich-text";import{RichTextComponent as D}from"@galacean/effects-plugin-rich-text";import"@galacean/effects-plugin-model";import"@galacean/effects-plugin-multimedia";import{VideoComponent as z}from"@galacean/effects-plugin-multimedia";import"@galacean/effects-plugin-spine";import{Application as S}from"@pixi/app";var A=class{constructor(){c(this,"type"),c(this,"active"),this.type="null",this.active=!1}get interactive(){return this.active}set interactive(t){this.active=t}},T=1e-6;function k(t,e,i){const s=isNaN(e)?-1/0:e,r=isNaN(i)?1/0:i,a=Math.min(s,r),n=Math.max(s,r);return Math.min(Math.max(t,a),n)}var _=Math.PI/180,E=180/Math.PI;function B(t){return Math.atan2(-t.y,-t.x)+Math.PI}function M(t,e){const i=Math.min(Math.max(t.dot(e)/t.length()/e.length(),-1),1);let s=Math.acos(i);return s=t.x*e.y-t.y*e.x>0?s:-s,s}function V(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function G(t,e){return Math.abs(t-e)<T||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function U(t){return isNaN(t)||Math.abs(t)<T}var F=class t extends y.Vector2{subtract(t){return this.x-=t.x,this.y-=t.y,this}toViewCoordinate(t,e){return this.x=(this.x+1)/2*t,this.y=(1-(this.y+1)/2)*e,this}clone(){return new t(this.x,this.y)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}scaleByCenter(e,i=new t){const s=(new t).subtractVectors(i,this).multiply(e);return this.subtractVectors(i,s)}round(t=0){const e=Math.pow(10,t);return this.x=Math.round(this.x*e)/e,this.y=Math.round(this.y*e)/e,this}distanceToLine(e){const i=Math.pow(e.length(),2),{start:s,end:r}=e;if(0===i)return{d:(new t).subtractVectors(this,s).length(),t:0};const a=k(((this.x-s.x)*(r.x-s.x)+(this.y-s.y)*(r.y-s.y))/i,0,1);return{d:(new t).subtractVectors(this,e.at(a)).length(),t:a}}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*s+t.x,this.y=r*s+a*i+t.y,this}},R=class t{constructor(t=new F,e=new F){c(this,"start",new F),c(this,"end",new F),this.start.copyFrom(t),this.end.copyFrom(e)}set(t,e){return this.start.copyFrom(t),this.end.copyFrom(e),this}copyFrom(t){return this.start.copyFrom(t.start),this.end.copyFrom(t.end),this}direction(){return(new F).subtractVectors(this.end,this.start).normalize()}getCenter(t=new F){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new F){return t.subtractVectors(this.end,this.start)}distanceSq(){return this.start.distanceSquared(this.end)}distance(){return this.start.distance(this.end)}at(t,e=new F){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new F,s=new F;i.subtractVectors(t,this.start),s.subtractVectors(this.end,this.start);const r=s.dot(s);let a=s.dot(i)/r;return e&&(a=k(a,0,1)),a}closestPointToPoint(t,e,i=new F){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiply(s).add(this.start)}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new t).copyFrom(this)}length(){return(new F).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new F).subtractVectors(t.start,this.start),r=(new F).subtractVectors(t.end,this.start),a=(new F).subtractVectors(this.start,t.start),n=(new F).subtractVectors(this.end,t.start),o=s.cross(e),c=r.cross(e),h=a.cross(i),l=n.cross(i);return o*c<0&&h*l<0}},W=class t{constructor(t=new F(1/0,1/0),e=new F(-1/0,-1/0)){c(this,"corners",[]),c(this,"min",new F(1/0,1/0)),c(this,"max",new F(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[new F(e.x,t.y),e.clone(),new F(t.x,e.y),t.clone()]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[new F(e.x,t.y),e.clone(),new F(t.x,e.y),t.clone()],this}setFromVec2Array(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min.min(t),this.max.max(t),this.corners.push(t.clone())}),this}setFromVec2ArrayWithOutCorners(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new F(this.max.x,this.min.y)),this.corners.push(new F(this.max.x,this.max.y)),this.corners.push(new F(this.min.x,this.max.y)),this.corners.push(new F(this.min.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new F).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y),this.min.clone()],this}clone(){return(new t).copyFrom(this)}copyFrom(t){return this.corners=[],this.min.copyFrom(t.min),this.max.copyFrom(t.max),t.corners.forEach(t=>{this.corners.push(t.clone())}),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this.corners=[],this}isEmpty(){return this.max.x<=this.min.x||this.max.y<=this.min.y}getCorners(){const t=[];return this.corners.forEach(e=>{t.push(e.clone())}),t}getCenter(t=new F){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new F){return this.isEmpty()?t.set(0,0):t.subtractVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.subtract(t),this.max.add(t),this}expandByScalar(t){return this.min.add(-t),this.max.add(t),this}containsPoint(t,e=!0){if(e)return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y);if(this.isEmpty())return!1;for(let e=0;e<this.corners.length;e++){const i=this.corners[e],s=this.corners[(e+1)%4],r=new F(s.x-i.x,s.y-i.y),a=new F(t.x-i.x,t.y-i.y);if(r.cross(a)<0)return!1}return!0}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e=new F){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}clampPoint(t,e=new F){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new F).copyFrom(t).clamp(this.min,this.max).subtract(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.min.x>this.max.x||this.min.y>this.max.y?this.makeEmpty():this}union(t){return this.min.min(t.min),this.max.max(t.max),this.corners=[new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y),this.min.clone()],this}translate(t){return this.min.add(t),this.max.add(t),this.corners.forEach(e=>{e.add(t)}),this}scaleByCenter(t,e){e??(e=this.getCenter());const i="number"==typeof t?new F(t,t):new F(t.x,t.y);return this.min.scaleByCenter(i,e),this.max.scaleByCenter(i,e),this.corners.forEach(t=>{t.scaleByCenter(i,e)}),this}scale(t,e){e??(e=this.getCenter());const i=i=>{const s=i.clone().add(e);i.add(s.multiply(t-1))};return i(this.min),i(this.max),this.corners.forEach(t=>{i(t)}),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}intersectsBox(t,e=!0){if(e)return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y);if(!this.isEmpty())for(let e=0;e<this.corners.length;e++){const i=new R(this.corners[e],this.corners[(e+1)%4]);if(t.containsPoint(this.corners[e],!1))return!0;for(let e=0;e<t.corners.length;e++){const s=new R(t.corners[e],t.corners[(e+1)%4]);if(this.containsPoint(t.corners[e],!1))return!0;if(i.crossWithLine(s))return!0}}for(let e=0;e<t.corners.length;e++){const i=this.containsPoint(t.corners[e],!1),s=t.containsPoint(this.corners[e],!1);if(i||s)return!0}return!1}rotate(t,e){e??(e=this.getCenter());const i=this.corners.map(i=>i.rotateAround(e,t));return this.makeEmpty(),this.setFromVec2Array(i),this}},L=class t{constructor(t=new F,e=0){c(this,"center"),c(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new F).copyFrom(t),this.radius=e,this}clone(){return(new t).copy(this)}copy(t){return this.center.copyFrom(t.center),this.radius=t.radius,this}makeEmpty(){return this.center=new F,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new F){return t.copyFrom(this.center),t}getRadius(){return this.radius}expandByPoint(t){return this.radius=this.center.distanceTo(t),this}expandByScalar(t){return this.radius+=t,this}containsPoint(t){return this.center.distanceTo(t)<this.radius}containsBox(t){for(let e=0;e<4;e++)if(!this.containsPoint(t.corners[e]))return!1;return!0}intersectsBox(t){for(let e=0;e<4;e++)if(this.containsPoint(t.corners[e]))return!0;return!1}distanceToPoint(t){return this.center.distanceTo(t)-this.radius}},H=class extends y.Quaternion{},N=class t extends y.Vector3{clone(){return new t(this.x,this.y,this.z)}setFromMatrixColumn(t,e){return this.set(...t.elements.slice(4*e))}applyEuler(t,e){return this.applyQuaternion((new H).setFromEuler(t))}applyQuaternion(e,i=new t){const{x:s,y:r,z:a,w:n}=e,{x:o,y:c,z:h}=this.subtract(i),l=n*o+r*h-a*c,p=n*c+a*o-s*h,m=n*h+s*c-r*o,d=-s*o-r*c-a*h;return this.x=l*n+d*-s+p*-a-m*-r+i.x,this.y=p*n+d*-r+m*-s-l*-a+i.y,this.z=m*n+d*-a+l*-r-p*-s+i.z,this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}applyMatrix(e,i=new t){const s=e.elements,{x:r,y:a,z:n}=this.subtract(i);let o=1/(s[3]*r+s[7]*a+s[11]*n+s[15]);return o=isNaN(o)?1:o,this.x=(s[0]*r+s[4]*a+s[8]*n+s[12])*o+i.x,this.y=(s[1]*r+s[5]*a+s[9]*n+s[13])*o+i.y,this.z=(s[2]*r+s[6]*a+s[10]*n+s[14])*o+i.z,this}},O=class t extends y.Matrix4{static fromArray(e,i=0){return(new t).setFromArray(e,i)}clone(){const e=this.elements;return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}compose(t,e,i,s=N.ZERO){const r=this.elements,{x:a,y:n,z:o,w:c}=e,h=-s.x,l=-s.y,p=-s.z,m=a+a,d=n+n,g=o+o,u=a*m,f=a*d,y=a*g,x=n*d,w=n*g,v=o*g,I=c*m,P=c*d,C=c*g,{x:b,y:D,z:z}=i;return r[0]=(1-(x+v))*b,r[1]=(f+C)*b,r[2]=(y-P)*b,r[3]=0,r[4]=(f-C)*D,r[5]=(1-(u+v))*D,r[6]=(w+I)*D,r[7]=0,r[8]=(y+P)*z,r[9]=(w-I)*z,r[10]=(1-(u+x))*z,r[11]=0,r[12]=h*r[0]+l*r[4]+p*r[8]-h+t.x,r[13]=h*r[1]+l*r[5]+p*r[9]-l+t.y,r[14]=h*r[2]+l*r[6]+p*r[10]-p+t.z,this}extractRotation(t){const e=new N,i=t.elements,s=this.elements,r=1/e.setFromMatrixColumn(t,0).length(),a=1/e.setFromMatrixColumn(t,1).length(),n=1/e.setFromMatrixColumn(t,2).length();return s[0]=i[0]*r,s[1]=i[1]*r,s[2]=i[2]*r,s[3]=0,s[4]=i[4]*a,s[5]=i[5]*a,s[6]=i[6]*a,s[7]=0,s[8]=i[8]*n,s[9]=i[9]*n,s[10]=i[10]*n,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,a=Math.cos(i),n=Math.sin(i),o=Math.cos(s),c=Math.sin(s),h=Math.cos(r),l=Math.sin(r);if(t.order===y.EulerOrder.XYZ){const t=a*h,i=a*l,s=n*h,r=n*l;e[0]=o*h,e[4]=-o*l,e[8]=c,e[1]=i+s*c,e[5]=t-r*c,e[9]=-n*o,e[2]=r-t*c,e[6]=s+i*c,e[10]=a*o}else if(t.order===y.EulerOrder.YXZ){const t=o*h,i=o*l,s=c*h,r=c*l;e[0]=t+r*n,e[4]=s*n-i,e[8]=a*c,e[1]=a*l,e[5]=a*h,e[9]=-n,e[2]=i*n-s,e[6]=r+t*n,e[10]=a*o}else if(t.order===y.EulerOrder.ZXY){const t=o*h,i=o*l,s=c*h,r=c*l;e[0]=t-r*n,e[4]=-a*l,e[8]=s+i*n,e[1]=i+s*n,e[5]=a*h,e[9]=r-t*n,e[2]=-a*c,e[6]=n,e[10]=a*o}else if(t.order===y.EulerOrder.ZYX){const t=a*h,i=a*l,s=n*h,r=n*l;e[0]=o*h,e[4]=s*c-i,e[8]=t*c+r,e[1]=o*l,e[5]=r*c+t,e[9]=i*c-s,e[2]=-c,e[6]=n*o,e[10]=a*o}else if(t.order===y.EulerOrder.YZX){const t=a*o,i=a*c,s=n*o,r=n*c;e[0]=o*h,e[4]=r-t*l,e[8]=s*l+i,e[1]=l,e[5]=a*h,e[9]=-n*h,e[2]=-c*h,e[6]=i*l+s,e[10]=t-r*l}else if(t.order===y.EulerOrder.XZY){const t=a*o,i=a*c,s=n*o,r=n*c;e[0]=o*h,e[4]=-l,e[8]=c*h,e[1]=t*l+r,e[5]=a*h,e[9]=i*l-s,e[2]=s*l-i,e[6]=n*h,e[10]=r*l+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setPosition(t){return this.elements[12]=t.x,this.elements[13]=t.y,this.elements[14]=t.z,this}},K=class extends y.Euler{constructor(t=0,e=0,i=0,s=y.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new O).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*E,this.y*E,this.z*E):new N(this.x*E,this.y*E,this.z*E)}setFromDegreeVector3(t,e){return this.set(t.x*_,t.y*_,t.z*_,e??this.order)}},j=class t{constructor(t=0,e=new N(0,0,1)){c(this,"distance"),c(this,"normal");const i=e.length();0===i&&(this.normal=new N(0,0,1)),this.distance=t/(i??1),this.normal=e.normalize()}static set(e,i){return new t(e,i)}set(t,e){const i=e.length();return 0===i&&(this.normal=new N(0,0,1)),this.distance=t/i,this.normal=e.normalize(),this}static copy(e){return new t(e.distance,e.normal.clone())}copy(t){return this.distance=t.distance,this.normal.copyFrom(t.normal),this}static setFromNormalAndCoplanarPoint(e,i){const s=-e.dot(i);return new t(s,i)}setFromNormalAndCoplanarPoint(t,e){return this.normal.copyFrom(e),this.distance=-t.dot(this.normal),this}clone(){return new t(this.distance,this.normal.clone())}distanceToPoint(t){return this.normal.dot(t)+this.distance}},Y=class t extends y.Ray{constructor(t=new N,e=new N(1,0,0)){super(t,e),c(this,"origin"),c(this,"direction"),this.origin=t.clone(),this.direction=e.clone()}clone(){return new t(this.origin,this.direction)}rayCastPlane(t,e){const i=this.distanceToPlane(t);return isNaN(i)||this.at(i),i}at(t){return this.direction.clone().normalize().multiply(t).add(this.origin)}distanceToPlane(t){const e=t.normal.dot(this.direction);if(U(e))return U(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},$=class{constructor(t=new Y){c(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new N(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new N,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},J=class extends A{constructor(t){super(),c(this,"defaultInteractive",!0),c(this,"type","control"),c(this,"_interactionType","mouse"),c(this,"active",!1),c(this,"lastPoint",new F),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"SDKUtils"),this.SDKUtils=t}get interactive(){return ci.config.gestureHandlerConfig.controlGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.controlGizmoEnabled=!0}get interactionType(){return this._interactionType}set interactionType(t){t===this._interactionType&&(this._interactionType=t,this.refreshCursorResult())}get useCameraControl(){return"editor"===ci.config.mode}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(t){return"mouse"===this.interactionType&&(this.active=!0,this.lastPoint=new F(t.clientX,t.clientY)),this.refreshCursorResult(),"mouse"===this.interactionType?this.type:void 0}action(t){if(!ci.config.gestureHandlerConfig.controlGizmoEnabled)return void console.warn("Control gizmo is not opened, use #SDK.setControlConfig() open this feature.");const{metaKey:e,ctrlKey:i,shiftKey:s}=t;if(0===t.buttons){const{deltaX:r,deltaY:a,offsetX:n,offsetY:o}=t,c=new F(r,a);if(e||i){const t=this.useCameraControl?new F(n,o):new F,e=-c.y*ci.config.gestureHandlerConfig.controlGizmoConfig.zoomStep;this.SDKUtils.pageZoom(e,t)}else c.x=s&&0!==c.y?Math.sqrt(c.x**2+c.y**2)*c.y/Math.abs(c.y):c.x,c.y=s?0:c.y,this.SDKUtils.pageMove(c.negate())}else if(this.active&&t instanceof MouseEvent&&[1,4].includes(t.buttons)){const{clientX:e,clientY:i}=t,r=new F(e,i),a=(new F).subtractVectors(r,this.lastPoint);a.x=s&&0!==a.y?Math.sqrt(a.x**2+a.y**2)*a.y/Math.abs(a.y):a.x,a.y=s?0:a.y,this.SDKUtils.pageMove(a),this.lastPoint.copyFrom(r)}}endAction(){return this.active=!1,this.refreshCursorResult(),"mouse"===this.interactionType?this.type:void 0}interruption(){return this.type}actionKey(){}endActionKey(){}refreshCursorResult(){"mouse"===this.interactionType?this.cursorResult={type:this.active?"active-hand":"hand",angle:0}:this.cursorResult={type:"normal",angle:0}}getRenderObjects(){return[]}};import{Graphics as X}from"@pixi/graphics";function Z(t,e){t.includes(e)||t.push(e)}var q=class extends A{constructor(t){super(),c(this,"result",{type:"null",box:new W}),c(this,"selectedItemIds",[]),c(this,"activeParentIds",[]),c(this,"cursorPoint",new F),c(this,"startPoint",new F),c(this,"firstClickPoint",new F),c(this,"graphics",new X),c(this,"pageDataUtils"),c(this,"clearResult",!1),c(this,"type","selector"),this.pageDataUtils=t}get interactive(){return ci.config.gestureHandlerConfig.selectorGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.selectorGizmoEnabled=!0}actionKey(){}endActionKey(){}getRenderObjects(){return this.interactive?this.clearResult?(this.result={type:"null",box:new W},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t,e){if(this.result.box=new W,!this.interactive)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const i=new F(t.offsetX,t.offsetY),s=this.hitTest(i);this.selectedItemIds=this.filterSelectedItems(s);const r=this.selectedItemIds[0]??"",a=this.pageDataUtils.getPageData().activeData.selectedItems.flatMap(t=>this.pageDataUtils.getChildrenIds(t));return r.length&&e&&!a.includes(r)||!e?(!r.length||this.pageDataUtils.isItemSelected(r)||a.includes(r)?this.pageDataUtils.clearPreSelectedItem():this.pageDataUtils.addPreSelectedItem(r),this.type):(this.pageDataUtils.clearPreSelectedItem(),e)}preAction(t,e=!1,i){switch(this.pageDataUtils.clearPreSelectedItem(),t.buttons){case 1:{const s=new F(t.offsetX,t.offsetY);if(i??(i=this.firstClickPoint),e&&s.distanceTo(i)<4){const e=new F(t.offsetX,t.offsetY),i=this.hitTest(e);this.selectedItemIds=this.filterSelectedItems(i)}if(e||this.firstClickPoint.set(t.offsetX,t.offsetY),t.shiftKey){if(e){const t=this.pageDataUtils.getViewItemById(this.selectedItemIds[0]);t?.parentId&&this.pageDataUtils.removeSelectedItems([t.parentId])}}else this.pageDataUtils.clearSelectedItems(0===this.selectedItemIds.length);if(0===this.selectedItemIds.length)return this.startPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),this.activeParentIds=[],this.active=!0,this.type;{this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]);const t=this.pageDataUtils.getPageData()?.activeData?.selectedItems;return this.addActiveParentIds(t),this.clearResult=!0,1===t?.length&&this.pageDataUtils.getViewItemById(t[0])?.type===g.ItemType.text?"text":"transform"}}case 2:{const e=[...this.pageDataUtils.getPageData().activeData.selectedItems,...this.pageDataUtils.getPageData().activeData.selectedItems.flatMap(t=>this.pageDataUtils.getChildrenIds(t))];return void(this.selectedItemIds.length&&!e.includes(this.selectedItemIds[0])&&(t.shiftKey||this.pageDataUtils.clearSelectedItems(),this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0))}default:return}}action(t){const e=(new F).addVectors(this.cursorPoint,(new F).subtractVectors(new F(t.clientX,t.clientY),this.startPoint)),i=(new F).subtractVectors(this.cursorPoint,e),s=(new F).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new W).setFromCenterAndSize(s,i);this.result.type="region",this.result.box=r,this.pageDataUtils.clearSelectedItems();const a=this.pageDataUtils.getPageData().items?.filter(t=>this.pageDataUtils.getItemEditEnable(t.id)),n=[];a?.forEach(t=>{r.intersectsBox(this.pageDataUtils.getViewBoxById(t.id),!1)&&n.push(t.id)});const o=this.filterSelectedItems(n);this.pageDataUtils.addSelectedItems(o)}endAction(){this.active=!1,this.result.type="null"}interruption(){this.active=!1,this.result.type="null"}hitTest(t){const e=this.pageDataUtils.getCurrentComposition();if(!e?.items)return[];const{x:i,y:s}=this.pageDataUtils.getViewportByViewPoint(t),r={ray:new Y,regions:[]};try{r.regions=e.hitTest(i,s,!0),r.ray=e.getHitTestRay(i,s)}catch(t){console.warn(t)}return this.reorderHitTestResult(r,e).filter(t=>"extra-camera"!==t&&this.pageDataUtils.getItemEditEnable(t))}reorderHitTestResult(t,e){if(0===t.regions.length||!e)return[];const{ray:i}=t,s=t.regions.reverse(),r=[];return s.forEach(t=>{let s;const a=(t,e)=>{for(const i of t){if(i.getInstanceId()===e&&(s=i),s)return;a(i.children,e)}};if(a(e.items,t.item.getInstanceId()),void 0===s)return;const n="rootItem"===t.compContent?.name?s.getInstanceId():t.compContent.getInstanceId(),o=i.origin.clone().distance(t.position.clone());if((s.type===g.ItemType.mesh||s.getComponent(I)?.renderer?.occlusion||s.getComponent(P)?.renderer?.occlusion||s.getComponent(z)?.renderer?.occlusion||s.getComponent(D)?.renderer?.occlusion)&&r.length>0){let t=!0;r.forEach((e,i)=>{if(t)return o<=e[1]?(r.splice(i,0,[n,o]),void(t=!1)):void(i===r.length-1&&r.push([n,o]))})}else r.push([n,o])}),r.map(t=>t[0])}filterSelectedItems(t){const e=[],i=t=>{const e=this.pageDataUtils.getViewItemById(t);return!e.parentId||this.activeParentIds.includes(e.parentId)?e.id:i(e.parentId)},s=this.pageDataUtils.getPageData()?.activeData.loadingItems??[];return t.forEach(t=>{const r=i(t);s.includes(r)||Z(e,r)}),e}addActiveParentIds(t){this.activeParentIds=[],t?.forEach(t=>{if(!this.pageDataUtils.getViewItemById(t))return;const e=t=>{this.activeParentIds.push(t);const i=this.pageDataUtils.getViewItemById(t);i.parentId&&e(i.parentId)};e(t)})}resetActiveParentIds(t){const e=this.pageDataUtils.getViewItemById(t);e&&(this.activeParentIds=this.activeParentIds.filter(t=>t===e.parentId))}refreshResults(){const{box:t}=this.result;this.graphics.clear();const e=this.pageDataUtils.getPreSelectedItem(),i=this.pageDataUtils.getViewBoxById(e?.id??""),{regionBoxColor:s,regionBoxAlpha:r,preSelectedWidth:a,preSelectedColor:n,regionWireframeWidth:o,regionWireframeColor:c,regionWireframeAlpha:h}=ci.config.gestureHandlerConfig.selectorGizmoConfig;if(i?.isEmpty()||(this.graphics.lineStyle(a,n),this.graphics.drawBox(i)),!t.isEmpty()&&"region"===this.result.type)this.graphics.lineStyle(o,c,h),this.graphics.drawBox(t),this.graphics.beginFill(s,r),this.graphics.fillBox(t),this.graphics.endFill()}};import{Graphics as Q}from"@pixi/graphics";import{assertExist as tt}from"@galacean/effects";import{Text as et}from"@pixi/text";import{Sprite as it}from"@pixi/sprite";var st=class extends A{constructor(t,e,i){super(),c(this,"type","transform"),c(this,"wireframe"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"cursorPoint",new F),c(this,"lastPoint",new F),c(this,"rotationAngle",0),c(this,"active",!1),c(this,"enableAdsorption",!0),c(this,"scaleParam"),c(this,"activeType","null"),c(this,"lastWorldPosition",new N),c(this,"firstClickPoint",new F),c(this,"pageDataUtils"),c(this,"adsorptionGizmo"),c(this,"selectorGizmo"),c(this,"graphics",new Q),c(this,"nameText",new et("",{fontSize:14,fill:ci.config.gestureHandlerConfig.transformGizmoConfig.sizeTextColor,align:"left"})),c(this,"imageSprite"),c(this,"nullSprite"),this.pageDataUtils=t,this.selectorGizmo=i,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new F,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,rotationEnabled:!0,scaleEnabled:!0,box:new W,totalBox:new W,childrenBoxes:[],activeType:"null",interactiveDirection:new F,scaleCorner:new F,scaleEdgeCorners:[]},this.imageSprite=it.from(ci.config.gestureHandlerConfig.transformGizmoConfig.pictureLogoUrl),this.imageSprite._width=15,this.imageSprite._height=15,this.nullSprite=it.from(ci.config.gestureHandlerConfig.transformGizmoConfig.nullLogoUrl),this.nullSprite._width=15,this.nullSprite._height=15}get interactive(){return ci.config.gestureHandlerConfig.transformGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.transformGizmoEnabled=t}get infoType(){const t=this.pageDataUtils.getSelectedItems();return 1===t.length?t[0].type:g.ItemType.base}actionKey(){}endActionKey(){}getRenderObjects(){const t=[];if(!this.interactive)return t;if(this.refreshRenderObject(),t.push(this.graphics),this.infoType!==g.ItemType.base)switch(t.push(this.nameText),this.infoType){case g.ItemType.sprite:t.push(this.imageSprite);break;case g.ItemType.null:t.push(this.nullSprite)}return t}cancelPreparation(){this.active=!1,this.wireframe.activeType="null"}preparationAction(t){if(!this.interactive)return void console.warn("Transform gizmo is not opened, use #SDK.openTransformGizmo() open this feature.");const e=new F(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;this.refreshCursorResult(this.activeType,B(s));const r="translation"===this.activeType?this.selectorGizmo.preparationAction(t,"transform"):this.type;return this.active="transform"===r&&"null"!==this.activeType,this.active&&r?r:void 0}preAction(t,e=!1){if(this.active=1===t.buttons,this.lastPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),1!==t.buttons)return;if(e)return this.selectorGizmo.preAction(t,e,new F(t.offsetX,t.offsetY));this.active=!0,"null"===this.wireframe.activeType&&(this.wireframe.activeType="translation");const i=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());return this.initInteractionPlane(i),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(i)??new N,this.activeType=e?"null":this.activeType,this.type}action(t){if(!this.interactive)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(!this.active){this.active=!0,this.refreshWireframeBySelectedItems(),this.wireframe.activeType="translation",this.lastPoint.set(t.clientX,t.clientY),this.cursorPoint.set(t.offsetX,t.offsetY);const e=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new N}const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);if(!this.wireframe.interactive)return;const s=this.pageDataUtils.getSelectedItems(),{anchor:r,activeType:a,interactiveDirection:n}=this.wireframe,o=this.pageDataUtils.getPageData();tt(o);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new N,a=V(M((new F).subtractVectors(this.cursorPoint,t),(new F).subtractVectors(this.cursorPoint.add(i),t))*E,3);e.z=a,this.rotationAngle+=a,c=B(n)+this.rotationAngle*_,s.forEach(t=>{this.pageDataUtils.rotateItem(t.id,e)});break}case"translation":{const t=i.clone();if(this.enableAdsorption){const e=o.items.map(t=>s.find(e=>e.id===t.id)||0!==s.filter(e=>t.parentId&&t.parentId===e.id).length||!this.pageDataUtils.getItemEditEnable(t.id)||s.find(e=>e.parentId===t.id)?new W:this.pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),i=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);t.add(i).subtract(r)}const e=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(t).clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(e){const t=e.clone().subtract(this.lastWorldPosition);s.forEach(e=>{e.type!==g.ItemType.camera&&(t.x=V(t.x,5),t.y=V(t.y,5),t.z=V(t.z,5),this.pageDataUtils.moveItem(e.id,t))}),this.lastWorldPosition.copyFrom(e)}break}case"scale":{const t=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(i).clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(i.length()&&t&&this.scaleParam){const{corner:e,center:i,shift:r,lastScalar:a}=this.scaleParam,n=this.pageDataUtils.getSelectedItems()[0]??void 0,o=this.pageDataUtils.getItemTransformById(n?.id??""),c=(new O).extractRotation(o.matrix).invert(),h=(new N).subtractVectors(e,i).applyMatrix(c),l=h.clone().multiply(a),p=t.clone().subtract(r).subtract(i).applyMatrix(c),m=new N(1,1,1),d=function(t){let e,i=0;return t.forEach((t,s)=>{if(0===s)e=Math.abs(t);else{const r=Math.abs(t);e<r&&(e=r,i=s)}}),i}([G(h.x,0)?1:Math.abs(p.x/h.x),G(h.y,0)?1:Math.abs(p.y/h.y)]),g=p.toArray()[d],u=l.toArray()[d];if(G(a.x,a.y)&&G(a.z,a.x)){const t=G(u,0)?1:Math.abs(g/u);m.set(t,t,t)}else if(0===d){m.x=G(u,0)?1:Math.abs(g/u);const t=h.y*g/h.x;m.y=G(l.y,0)?1:t/l.y;const e=h.z*g/h.x;m.z=G(l.z,0)?1:e/l.z}else if(1===d){m.y=G(u,0)?1:Math.abs(g/u);const t=h.x*g/h.y;m.x=G(l.x,0)?1:t/l.x;const e=h.z*g/h.y;m.z=G(l.z,0)?1:e/l.z}else{m.z=G(u,0)?1:Math.abs(g/u);const t=h.x*g/h.z;m.x=G(l.x,0)?1:t/l.x;const e=h.y*g/h.z;m.y=G(l.y,0)?1:e/l.y}const f=m.clone().subtract(new N(1,1,0)).divide(2).add(new N(1,1,.5)),y=i.clone().add((new N).subtractVectors(e,i).multiply(a.x));this.scaleParam.lastScalar.multiply(f);const x=i.clone().add((new N).subtractVectors(e,i).multiply(this.scaleParam.lastScalar.x)),w=(new N).subtractVectors(x,y);w.x=V(w.x,5),w.y=V(w.y,5),w.z=V(w.z,5),this.scaleParam.center.add(w),this.scaleParam.corner.add(w),s.forEach(t=>{this.pageDataUtils.scaleItem(t.id,f),this.pageDataUtils.moveItem(t.id,w)}),this.lastWorldPosition.copyFrom(t)}c=B(n);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);this.cursorPoint.add(i);const s=this.wireframe;this.refreshTransformType(this.cursorPoint);const{activeType:r,interactiveDirection:a}=s;this.refreshCursorResult(r,B(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new F,this.lastPoint=new F}interruption(){this.active=!1,this.cursorResult.type="normal",this.adsorptionGizmo.clearAbsorptionResult()}refreshCursorResult(t,e=0){switch(t){case"scale":this.cursorResult={type:"scale",angle:(e+Math.PI/4)*E};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*E};break;case"translation":case"null":this.cursorResult={type:"normal",angle:0}}}refreshResults(){const t=this.wireframe.activeType;this.refreshWireframeBySelectedItems(),t!==this.wireframe.activeType&&this.refreshCursorResult(this.wireframe.activeType)}initInteractionPlane(t){const e=this.pageDataUtils.getSelectedItems();switch(this.wireframe.activeType){case"scale":{const i=1==e.length?e[0]:void 0;let s,r,a;if(i){const t=this.pageDataUtils.getItemTransformById(i.id);s=(new N).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new N).setFromMatrixPosition(t.matrix),a=(new K).setFromQuaternion((new H).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new N,center:new N,corner:new N,lastScalar:new N(1,1,1)},this.scaleParam.center=s??r;const n=this.pageDataUtils.getViewportLeftTopPosition();if(["scale"].includes(this.wireframe.activeType)&&this.wireframe.scaleCorner){const t=this.wireframe.scaleCorner.clone().subtract(n);this.scaleParam.corner=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new N}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new N).subtract(this.scaleParam.corner);break}case"translation":case"rotation":this.pageDataUtils.interactionUtils.initInteractionPlane()}}refreshRenderObject(){this.graphics.clear(),this.nameText.text="";const{wireframeAlpha:t,wireframeColor:e,wireframeWidth:i,cornerFillColor:s,cornerLineWidth:r,cornerLineColor:a,cornerLineAlpha:n}=ci.config.gestureHandlerConfig.transformGizmoConfig;if(!this.wireframe.box.isEmpty()){this.graphics.lineStyle(i,e,t),this.wireframe.edges.forEach(t=>{this.graphics.drawLine(t)});const o=t=>{t.corners.forEach((e,i)=>{const s=new R(e,t.corners[(i+1)%4]);this.graphics.drawLine(s)})};if(this.wireframe.childrenBoxes.forEach(t=>{o(t)}),this.wireframe.cornerEnable&&(this.graphics.beginFill(s),this.graphics.lineStyle(r,a,n),this.wireframe.scaleCorners.forEach(t=>{this.graphics.drawCircle(t.center.x,t.center.y,t.radius)}),this.graphics.endFill()),this.infoType!==g.ItemType.base){const t=this.pageDataUtils.getSelectedItems()[0],e=t.type===g.ItemType.null?"编组":"图片",{size:i,rotation:s}=t.property,r=this.infoType===g.ItemType.sprite?this.imageSprite:this.nullSprite,a=this.wireframe.box.corners[3],n=s[2]*_;r.anchor.set(0,1),r.x=a.x,r.y=a.y-5,r.rotation=-n;const o=a.clone().add(new F(20,0)).rotateAround(a,-n),c=new F(0,4).rotateAround(new F,n);this.nameText.text=` ${e} ${i.map(t=>V(t,0)).join(" * ")}`,this.nameText.anchor.set(0,1),this.nameText.x=o.x+c.x,this.nameText.y=o.y-c.y,this.nameText.rotation=-n}}}refreshTransformType(t){this.activeType="null";let e=!0;if(this.wireframe.interactiveDirection=new F,this.wireframe.scaleCorner=void 0,this.wireframe.scaleEdgeCorners=void 0,e&&this.wireframe.totalBox.containsPoint(t)){if(this.wireframe.scaleEnabled)for(let i=0,s=this.wireframe.scaleCorners.length;i<s;i++){if(this.wireframe.scaleCorners[i].containsPoint(t)){e=!1,this.activeType="scale",this.wireframe.activeType="scale",this.wireframe.scaleCorner=this.wireframe.scaleCorners[i].center.clone(),this.wireframe.interactiveDirection.copyFrom(this.wireframe.scaleCorners[i].center).subtract(this.wireframe.box.getCenter());break}}if(e&&this.wireframe.box.containsPoint(t,!1)&&(e=!1,this.activeType="translation",this.wireframe.activeType="translation"),this.wireframe.rotationEnabled)for(let i=0,s=this.wireframe.scaleCorners.length;i<s;i++){if(this.wireframe.rotationCorners[i].containsPoint(t)&&e){e=!1,this.activeType="rotation",this.wireframe.activeType="rotation",this.wireframe.interactiveDirection.copyFrom(this.wireframe.rotationCorners[i].center).subtract(this.wireframe.box.getCenter());break}}}}refreshWireframeBySelectedItems(){const t=this.pageDataUtils.getSelectedItems(),e=new W;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],this.wireframe.rotationEnabled=1===t.length&&t[0].type!==g.ItemType.null,this.wireframe.scaleEnabled=1===t.length&&t[0].type!==g.ItemType.null,this.wireframe.cornerEnable=1===t.length&&t[0].type!==g.ItemType.null,t.length>1)t.forEach(t=>{if(this.pageDataUtils.getItemShow(t.id)){const i=this.pageDataUtils.getViewBoxById(t.id);e.union(i),this.wireframe.childrenBoxes.push((new W).copyFrom(i).expandByScalar(1))}}),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=!0;else if(1===t.length){const i=t[0];if(i.type!==g.ItemType.text&&this.pageDataUtils.getItemShow(i.id)){const t=this.pageDataUtils.getViewBoxById(i.id);e.copyFrom(t),this.wireframe.anchor=this.pageDataUtils.getItemViewAnchor(i.id)??e.getCenter(),this.wireframe.interactive=i.type!==g.ItemType.mesh&&this.pageDataUtils.getItemEditEnable(i.id)}}const i=e.isEmpty(),s=i?0:1,r=i?0:16;this.wireframe.activeType=t.length?this.wireframe.activeType:"null",this.wireframe.box.copyFrom(e).expandByScalar(s),this.wireframe.totalBox.copyFrom(e).expandByScalar(r);const a=this.wireframe.box.corners;a.forEach((t,e)=>{this.wireframe.edges.push(new R((new F).copyFrom(t),(new F).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:n,rotationCircleSize:o}=ci.config.gestureHandlerConfig.transformGizmoConfig;1===t.length&&this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new L(t,n));const e=(new F).subtractVectors(t,this.wireframe.box.getCenter()),i=(new F).copyFrom(this.wireframe.box.getCenter()).add((new F).copyFrom(e).normalize().multiply(e.length()+o-n));this.wireframe.rotationCorners.push(new L(i,o))})}setAdsorptionEnabled(t){this.enableAdsorption=t}};import{Graphics as rt}from"@pixi/graphics";var at=class extends A{constructor(){super(...arguments),c(this,"results",[]),c(this,"graphics",new rt),c(this,"absorptionResult",{}),c(this,"type","adsorption")}get interactive(){return ci.config.gestureHandlerConfig.adsorptionGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.adsorptionGizmoEnabled=t}preparationAction(){}getCursorState(){}preAction(){}action(){}cancelPreparation(){}actionKey(){}endActionKey(){}endAction(){}interruption(){}boxTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!this.interactive)return void console.warn("Adsorption gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(e.isEmpty())return;const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),n=e.clone().translate(a),o=n.getCenter();this.absorptionResult={},i.forEach(t=>{if(t.isEmpty())return;t.corners.forEach(t=>{n.corners.forEach(e=>{this.getPointAbsorption(e,t,s,r)}),this.getPointAbsorption(o,t,s,r)});const e=t.getCenter();this.getPointAbsorption(o,e,s,r),n.corners.forEach(t=>{this.getPointAbsorption(t,e,s,r)})})}pointTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!this.interactive)return void console.warn("Adsorption is not opened, use #SDK.setAdsorptionConfig() open this feature.");const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),n=e.clone().add(a);this.absorptionResult={},i.forEach(t=>{this.getPointAbsorption(n,t,s,r)})}getPointAbsorption(t,e,i=!0,s=!0){i&&Math.abs(t.x-e.x)<ci.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<ci.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"y")}refreshPointAbsorptionResult(t,e,i){const s=t[i]-e[i],r="x"===i?"xPoints":"yPoints";if(this.absorptionResult&&void 0===this.absorptionResult[i])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else if(Math.abs(s)-Math.abs(this.absorptionResult[i]??0)<=.005)if(Math.abs(Math.abs(s)-Math.abs(this.absorptionResult[i]??0))<.05&&s*(this.absorptionResult[i]??0)>0)if(void 0===this.absorptionResult[r])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else{const i=this.absorptionResult[r].filter(e=>e.point.equals(t));void 0===i||0===i.length?this.absorptionResult[r]?.push({point:t,targets:[e]}):i[0]?.targets.push(e)}else this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}]}refreshResults(){if(void 0===this.absorptionResult)return;const{x:t,y:e,xPoints:i,yPoints:s}=this.absorptionResult,r=new F(t??0,e??0);void 0!==t&&void 0!==i&&i.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.x=t.x,i.y=Math.min(i.y,t.y),s.x=t.x,s.y=Math.max(s.y,t.y)}),this.results.push(new R(i,s))}),void 0!==e&&void 0!==s&&s.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.y=t.y,i.x=Math.min(i.x,t.x),s.y=t.y,s.x=Math.max(s.x,t.x)}),this.results.push(new R(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=ci.config.gestureHandlerConfig.adsorptionGizmoConfig;this.results.forEach(i=>{this.graphics.lineStyle(t,e),this.graphics.drawLine(i)})}getRenderObjects(){return this.interactive?(this.refreshResults(),this.refreshRenderObject(),[this.graphics]):[]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},nt={};a(nt,{Application:()=>lt,utils:()=>ct});var ot={};a(ot,{Application:()=>lt,utils:()=>ct}),o(ot,ut),o(ot,ft),o(ot,yt),o(ot,xt),o(ot,wt),o(ot,vt),o(ot,It),o(ot,Pt),o(ot,Ct),o(ot,bt),o(ot,Dt),o(ot,zt);import"@pixi/polyfill";import*as ct from"@pixi/utils";import{InteractionManager as ht}from"@pixi/interaction";import{Application as lt}from"@pixi/app";import{Renderer as pt,BatchRenderer as mt}from"@pixi/core";import{AppLoaderPlugin as dt}from"@pixi/loaders";import{TickerPlugin as gt}from"@pixi/ticker";import*as ut from"@pixi/constants";import*as ft from"@pixi/core";import*as yt from"@pixi/display";import*as xt from"@pixi/graphics";import*as wt from"@pixi/loaders";import*as vt from"@pixi/interaction";import*as It from"@pixi/math";import*as Pt from"@pixi/runner";import*as Ct from"@pixi/sprite";import*as bt from"@pixi/text";import*as Dt from"@pixi/ticker";import*as zt from"@pixi/settings";ct.skipHello(),pt.registerPlugin("interaction",ht),pt.registerPlugin("batch",mt),lt.registerPlugin(gt),lt.registerPlugin(dt),ot.Graphics.prototype.drawBox=function(t){const e=t.getCorners();this.beginFill();for(let t=0;t<4;t++)this.moveTo(e[t].x,e[t].y),this.lineTo(e[(t+1)%4].x,e[(t+1)%4].y);this.endFill()},ot.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},ot.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof R)this.moveTo(t.start.x,t.start.y),this.lineTo(t.end.x,t.end.y);else for(let e=0;e<t.length-1;e++)this.moveTo(t[e].x,t[e].y),this.lineTo(t[e+1].x,t[e+1].y);this.endFill()},o(nt,ot);var St=class extends A{constructor(t){super(),c(this,"box",new W),c(this,"graphics",new nt.Graphics),c(this,"PageDataUtils"),c(this,"type","preference"),this.PageDataUtils=t}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.box=new W,!this.interactive)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if("editor"===ci.config.mode)return;const t=this.PageDataUtils.getPageData();v(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new F(s,r).multiply(i),n=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new W).setFromCenterAndSize(n,a)}}refreshRenderObjects(){if("editor"===ci.config.mode)return;const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:n}=ci.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new nt.Graphics;const{offsetWidth:o,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new W(new F(0,0),new F(o,this.box.min.y)),l=new W(new F(0,this.box.min.y),new F(this.box.min.x,c)),p=new W(new F(this.box.min.x,this.box.max.y),new F(o,c)),m=new W(new F(this.box.max.x,this.box.min.y),new F(o,this.box.max.y));if(this.graphics.beginFill(i,s),this.graphics.fillBox(h),this.graphics.fillBox(l),this.graphics.fillBox(p),this.graphics.fillBox(m),this.graphics.endFill(),r){const t=this.PageDataUtils.getViewProperty();if(t){const{size:e,safeArea:i,previewSafeAreas:s}=t,[r,o,c,h]=i,l=this.box.getSize(),p=r/e[1]*l.y,m=c/e[0]*l.x,d=h/e[0]*l.x,g=o/e[1]*l.y,{min:u,max:f}=this.box;this.graphics.beginFill(a,n);const y=new W(u,new F(f.x,u.y+p)),x=new W(new F(u.x,u.y+p),new F(u.x+m,f.y)),w=new W(new F(f.x-d,u.y+p),new F(f.x,f.y)),v=new W(new F(u.x+m,f.y-g),new F(f.x-d,f.y));this.graphics.fillBox(y),this.graphics.fillBox(x),this.graphics.fillBox(w),this.graphics.fillBox(v),this.graphics.endFill(),s.forEach(t=>{const{box:[i,s,r,a],color:n}=t,o=this.box.getSize(),c=new F(r/e[0]*o.x,a/e[1]*o.y),h=new F(i/e[0]*o.x+c.x/2,s/e[1]*o.y+c.y/2).add(u),l=(new W).setFromCenterAndSize(h,c),p=n?.[3]??.3,m=n?.slice(0,3)??[255,0,0],d=m[0]<<16|m[1]<<8|m[2];this.graphics.beginFill(d,p),this.graphics.fillBox(l),this.graphics.endFill()})}}this.graphics.lineStyle(t,e),this.graphics.drawBox(this.box)}getRenderObjects(){return ci.config.gestureHandlerConfig.preferenceGizmoEnabled&&"editor"!==ci.config.mode?(this.refreshRenderObjects(),[this.graphics]):[]}get interactive(){return ci.config.gestureHandlerConfig.preferenceGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.preferenceGizmoEnabled=t}},At="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",Tt={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${At}/icons/cursor-rotate-32.svg`},circle:{type:"svg",content:"default",url:`${At}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${At}/icons/cursor-scale-32.svg`},hand:{type:"preset",content:"grab"},"active-hand":{type:"preset",content:"grabbing"},"text-rotation":{type:"svg",content:"default",url:"https://mdn.alipayobjects.com/huamei_ixsp8m/afts/img/A*R722QoloC44AAAAAKkAAAAgAev-aAQ/original"}};function kt(t,e="item doesn't exist"){if(null==t)throw new Error(e)}function _t(t,e="asserts failed"){if(!t)throw new Error(e)}function Et(t,e,...i){const s=e.reduce((t,e)=>t?`${t} ${e}`:e,""),r="color: #108ee9;";switch(t){case"error":console.error(`%c[${s}]`,r,...i);break;case"info":console.info(`%c[${s}]`,r,...i);break;case"debug":console.debug(`%c[${s}]`,r,...i);break;case"warn":console.warn(`%c[${s}]`,r,...i);break;default:console.log(`%c[${s}]`,r,...i)}}function Bt(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||"object"!=typeof t)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(Array.isArray(t)!==Array.isArray(e))return!1;const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!Object.prototype.hasOwnProperty.call(e,s))return!1;if(!Bt(t[s],e[s]))return!1}return!0}var Mt=class extends A{constructor(t,e){super(),c(this,"result",{type:"invalid"}),c(this,"interactionParam",{type:"none"}),c(this,"graphics",new nt.Graphics),c(this,"isShiftDown",!1),c(this,"_isLockScale",!1),c(this,"_pageDataUtils"),c(this,"_eventEmitter"),c(this,"type","picture-cut"),c(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return ci.config.gestureHandlerConfig.pictureCutGizmoEnabled}set interactive(t){t!==ci.config.gestureHandlerConfig.pictureCutGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture cut gizmo can not open."):ci.config.gestureHandlerConfig.pictureCutGizmoEnabled=t)}get isLockScale(){return this._isLockScale}set isLockScale(t){t===this.isLockScale&&(this._isLockScale=t)}preparationAction(t){if(!this.interactive)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),"picture-cut"}preAction(t,e){if(this.interactive&&"none"!==this.interactionParam.type)return"picture-cut"}action(t){var e;if(!this.interactive||"none"===this.interactionParam.type||"invalid"===this.result.type)return;const i=new F(t.clientX,t.clientY),{startMouse:s,box:r}=this.interactionParam,a=(new F).subtractVectors(i,s),{itemBox:{min:n,max:o}}=this.result;switch(this.interactionParam.type){case"move":{const{min:t,max:e}=r,i=n.x-t.x,s=o.x-e.x,c=n.y-t.y,h=o.y-e.y;a.x=Math.min(Math.max(a.x,i),s),a.y=Math.min(Math.max(a.y,c),h);const l=r.clone().translate(a);this.result.cutBox.copyFrom(l),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}case"scale":{const{startCorner:t,anchor:i}=this.interactionParam,s=new F;if(s.x=Math.min(Math.max(t.x+a.x,n.x),o.x),s.y=Math.min(Math.max(t.y+a.y,n.y),o.y),this.isShiftDown||this.isLockScale){const{x:a,y:c}=this.result.cutBox.getSize(),{x:h,y:l}=r.getSize();if((e=this.interactionParam).lockedAspect??(e.lockedAspect=a/c),Math.abs(s.x-i.x)/h>Math.abs(s.y-i.y)/l){const e=Math.abs(s.x-i.x)/this.interactionParam.lockedAspect;s.y=(t.y-i.y)/Math.abs(t.y-i.y)*e+i.y,s.y=Math.min(Math.max(s.y,n.y),o.y)}else{const e=Math.abs(s.y-i.y)*this.interactionParam.lockedAspect;s.x=(t.x-i.x)/Math.abs(t.x-i.x)*e+i.x,s.x=Math.min(Math.max(s.x,n.x),o.x)}}const c=(s.x-i.x)/(t.x-i.x),h=(s.y-i.y)/(t.y-i.y),l=new F(c,h);this.result.cutBox.copyFrom(r.clone().scaleByCenter(l,i)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}case"direction-scale":{const{index:t}=this.interactionParam,e=r.corners[t].clone();t%2==0?(a.x=Math.min(Math.max(e.x+a.x,n.x),o.x)-e.x,a.y=0):(a.x=0,a.y=Math.min(Math.max(e.y+a.y,n.y),o.y)-e.y);const i=r.corners.map((e,i)=>[t,(t+1)%4].includes(i)?e.clone().add(a):e.clone());this.result.cutBox.copyFrom((new W).setFromVec2Array(i)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),"picture-cut"}interruption(){this.interactionParam={type:"none"}}actionKey(t){this.isShiftDown=t.shiftKey}endActionKey(t){this.isShiftDown=t.shiftKey,"lockedAspect"in this.interactionParam&&delete this.interactionParam.lockedAspect}cancelPreparation(){this.interactionParam={type:"none"}}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(kt(t,"You must call SDK#run() first"),1!==t.activeData.selectedItems.length)console.warn("Picture Cut Gizmo can edit one picture at a time.");else if("invalid"===this.result.type){const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]);this.result={type:"valid",itemBox:e.clone(),cutBox:e.clone()}}else{const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]),i=e.getCenter().subtract(this.result.itemBox.getCenter()),s=e.getSize().x/this.result.itemBox.getSize().x;this.result.itemBox.scale(s),this.result.cutBox.scale(s),this.result.itemBox.translate(i),this.result.cutBox.translate(i)}}else this.result={type:"invalid"}}refreshRenderObjects(){if(this.graphics.clear(),!this.interactive||"invalid"===this.result.type)return;const{maskColor:t,maskAlpha:e,cutBoxLineWidth:i,cutBoxLineColor:s,cutBoxLineAlpha:r,itemBoxLineWidth:a,itemBoxLineColor:n,itemBoxLineAlpha:o,cutBoxCornerRadius:c,cutBoxCornerFillColor:h,cutBoxCornerLineWidth:l,cutBoxCornerLineColor:p,cutBoxCornerLineAlpha:m}=ci.config.gestureHandlerConfig.pictureCutGizmoConfig,{cutBox:d,itemBox:g}=this.result,{min:u,max:f}=d,{min:y,max:x}=g,w=new W(y.clone(),new F(x.x,u.y)),v=new W(new F(y.x,u.y),new F(u.x,x.y)),I=new W(new F(f.x,u.y),new F(x.x,f.y)),P=new W(new F(u.x,f.y),x.clone());this.graphics.beginFill(t,e),this.graphics.fillBox(w),this.graphics.fillBox(v),this.graphics.fillBox(I),this.graphics.fillBox(P),this.graphics.endFill(),this.graphics.lineStyle(a,n,o),this.graphics.drawBox(g),this.graphics.lineStyle(i,s,r),this.graphics.drawBox(d),this.graphics.beginFill(h),this.graphics.lineStyle(l,p,m),d.corners.forEach(t=>{this.graphics.drawCircle(t.x,t.y,c)}),this.graphics.endFill()}refreshCursorResult(t,e=0){switch(t){case"scale":case"direction-scale":this.cursorResult={type:"scale",angle:e};break;case"move":case"none":this.cursorResult={type:"normal",angle:0}}}getRenderObjects(){return this.interactive?(this.refreshRenderObjects(),[this.graphics]):[]}refreshInteractionType(t,e){if(this.interactionParam={type:"none"},!this.interactive||"invalid"===this.result.type)return;const{cutBox:i}=this.result;let s=!1,r=0;i.corners.forEach((a,n)=>{s||a.distanceTo(t)<ci.config.gestureHandlerConfig.pictureCutGizmoConfig.scaleInteractionDistance&&(s=!0,this.interactionParam={type:"scale",box:i.clone(),startMouse:e,startCorner:a.clone(),anchor:i.corners[(n+2)%4]},r=Math.PI/2*n)}),i.corners.forEach((a,n)=>{if(s)return;const o=new R(a.clone(),i.corners[(n+1)%4]),c=t.distanceToLine(o);if(c.d>=0&&c.d<=8&&c.t>=0&&c.t<=1){s=!0;const t=o.at(c.t);this.interactionParam={type:"direction-scale",index:n,point:t,box:i.clone(),startMouse:e},r=Math.PI/2*n+Math.PI/4}}),i.containsPoint(t)&&!s&&(this.interactionParam={type:"move",point:t.clone(),box:i.clone(),startMouse:e},s=!0),this.refreshCursorResult(this.interactionParam.type,r*E)}getCutInfo(){if(this.interactive&&"invalid"!==this.result.type)return{cutBox:this.result.cutBox,itemBox:this.result.itemBox}}setCutBox(t,e){if(!this.interactive||"invalid"===this.result.type)return;const{itemBox:{min:i,max:s}}=this.result;return this.result.cutBox.set(new F(Math.max(i.x,t.x),Math.max(i.y,t.y)),new F(Math.min(s.x,e.x),Math.min(s.y,e.y))),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone()),this.result.cutBox.clone()}};import{Graphics as Vt}from"@pixi/graphics";import{Sprite as Gt}from"@pixi/sprite";import{DEG2RAD as Ut}from"@galacean/effects-plugin-model";var Ft=class extends A{constructor(t,e,i,s,r){super(),c(this,"type","text"),c(this,"_eventEmitter"),c(this,"textAreaElement"),c(this,"graphics",new Vt),c(this,"_pageDataUtils"),c(this,"result"),c(this,"interactionParam"),c(this,"_adsorptionGizmo"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"rotationSprite",new Gt),c(this,"_selectorGizmo"),c(this,"handleInput",async t=>{const e=t.target;await this._pageDataUtils.changeItemProperty({itemId:this._pageDataUtils.getSelectedItems()[0].id,type:g.ItemType.text,propertyName:"text",propertyValue:e.value}),this._eventEmitter.emit("textInput",{text:e.value,fontFamily:e.style.fontFamily})}),c(this,"handleBlur",()=>{this.interactionParam.type="scale",this.textAreaElement.style.display="none",this.textAreaElement.removeEventListener("input",this.handleInput),this.textAreaElement.removeEventListener("blur",this.handleBlur)}),this._pageDataUtils=t,this._adsorptionGizmo=e,this._selectorGizmo=i,this._eventEmitter=s,this.textAreaElement=document.createElement("textarea"),this.textAreaElement.style.display="none",r?.appendChild(this.textAreaElement),function(t,e,i){const s=i.replace(/&/g,`.${e}`),r=document.createElement("style");r.textContent=`\n .${e} {\n ${s}\n }\n `,document.head.appendChild(r),t.classList.add(e)}(this.textAreaElement,"text-gizmo-custom-style","\n word-break: break-all;\n position: absolute;\n border: none;\n margin: 0;\n padding: 0;\n outline: none !important;\n overflow: hidden;\n resize: none;\n display: none;\n background: transparent;\n opacity: .8;\n field-sizing: content;\n &::selection {\n background: rgba(221, 63, 23, .5);\n }\n -webkit-text-fill-color: transparent;\n text-fill-color: transparent;\n"),this.result={type:"empty"},this.interactionParam={active:!1,type:"none",anchor:new F,lastPoint:new F,startPoint:new F,lastWorldPosition:new N}}get interactive(){return ci.config.gestureHandlerConfig.textGizmoEnbaled}set interactive(t){ci.config.gestureHandlerConfig.textGizmoEnbaled=t}preparationAction(t){if(!this.interactive)return void console.warn("Text gizmo is not opened, use #SDK.openTextGizmo() open this feature.");if("empty"===this.result.type)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);if(this.refreshInteractionParam(e,i),this.refreshCursorResult(),"none"!==this.interactionParam.type){const e="translation"===this.interactionParam.type?this._selectorGizmo.preparationAction(t,"text"):this.type;return this.interactionParam.active="text"===e,this.interactionParam.active?e:void 0}}preAction(t,e){if(1!==t.buttons)return this.type;const{offsetX:i,offsetY:s}=t,r=new F(i,s);if(e){if("empty"===this.result.type||this.result.box.containsPoint(r))this.interactionParam.type="edit";else if("none"===this.interactionParam.type)return this.result={type:"empty"},void this._pageDataUtils.clearSelectedItems(!0)}else if("empty"===this.result.type||this.result.box.containsPoint(r)){const t=r.subtract(this._pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(t),this.interactionParam.lastWorldPosition=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new N,this.refreshCursorResult()}else if("edit"===this.interactionParam.type)this.interactionParam.type="none";else if("none"===this.interactionParam.type)return void(this.result={type:"empty"});return this.type}action(t){if(!this.interactive)return void console.warn("Text gizmo is not opened, use #SDK.setTextConfig() open this feature.");if("edit"===this.interactionParam.type||"empty"===this.result.type)return;if(!this.interactionParam.active){this.interactionParam.active=!0,this.interactionParam.type="translation",this.interactionParam.lastPoint=new F(t.clientX,t.clientY),this.interactionParam.startPoint=new F(t.offsetX,t.offsetY);const e=new F(t.offsetX,t.offsetY).subtract(this._pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.interactionParam.lastWorldPosition=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new N}const e=new F(t.clientX,t.clientY),{type:i,lastPoint:s,startPoint:r,anchor:a}=this.interactionParam,n=(new F).subtractVectors(e,s),o=this._pageDataUtils.getSelectedItems();switch(i){case"rotation":{const t=new N,e=V(M((new F).subtractVectors(r,a),(new F).subtractVectors(r.add(n),a))*E,3);t.z=e,o.forEach(e=>{this._pageDataUtils.rotateItem(e.id,t)});break}case"translation":{const t=n.clone();if(this._adsorptionGizmo.interactive){const e=this._pageDataUtils.getPageData();v(e);const i=e.items.map(t=>o.find(e=>e.id===t.id)||0!==o.filter(e=>t.parentId&&t.parentId===e.id).length||!this._pageDataUtils.getItemEditEnable(t.id)||o.find(e=>e.parentId===t.id)?new W:this._pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),s=new F(this._adsorptionGizmo.absorptionResult.x??0,this._adsorptionGizmo.absorptionResult.y??0);this._adsorptionGizmo.boxTranslationAdsorption(t,this.result.box,i);const r=new F(this._adsorptionGizmo.absorptionResult.x??0,this._adsorptionGizmo.absorptionResult.y??0);t.add(s).subtract(r)}const e=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(r.add(t).clone().subtract(this._pageDataUtils.getViewportLeftTopPosition()));if(e){const t=e.clone().subtract(this.interactionParam.lastWorldPosition);o.forEach(e=>{e.type!==g.ItemType.camera&&(t.x=V(t.x,5),t.y=V(t.y,5),t.z=V(t.z,5),this._pageDataUtils.moveItem(e.id,t))}),this.interactionParam.lastWorldPosition.copyFrom(e)}break}case"scale":{const t=r.clone(),e=r.clone().add(n);if(n.length()){const i=(new F).subtractVectors(t,a),s=(new F).subtractVectors(e,a),n=Math.max(s.dot(i)/i.length(),1),c=i.length(),h=(n/c-1)/2+1,l=a.clone().add(i.clone().normalize().scale(c*h)),p=(new F).subtractVectors(l,t);r.add(p);const m=this._pageDataUtils.interactionUtils.getWorldSizeByViewSize(p);m.x=V(m.x,5),m.y=V(m.y,5),m.z=V(m.z,5),o.forEach(t=>{this._pageDataUtils.moveItem(t.id,m)}),o.forEach(t=>{this._pageDataUtils.scaleTextItem(t.id,h)})}break}}this.refreshCursorResult(),this.interactionParam.lastPoint.copyFrom(e)}endAction(t){const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this._adsorptionGizmo.clearAbsorptionResult(),this.refreshInteractionParam(e,i),this.refreshCursorResult(),this.type}interruption(){return this.interactionParam.type="none",this._adsorptionGizmo.clearAbsorptionResult(),this.type}actionKey(t){}endActionKey(t){}cancelPreparation(){}refreshResults(){if(!this.interactive)return;const t=this._pageDataUtils.getPageData()?.activeData?.selectedItems,e=this._pageDataUtils.getViewItemById(t?.[0]);if(!t||1!==t.length||e?.type!==g.ItemType.text)return void(this.result={type:"empty"});const i=this._pageDataUtils.getViewBoxById(t[0]);if(i.isEmpty())this.result={type:"empty"};else{const t=[new R(i.corners[0],i.corners[1]).at(.5),new R(i.corners[2],i.corners[3]).at(.5)],s=new R(i.getCenter(),new R(i.corners[0],i.corners[3]).at(.5)),r=s.at((s.length()+22)/s.length());this.result={type:"valid",box:i.clone(),scaleCorners:t,rotationCorner:r,rotation:-e.property.rotation[2]*Ut}}}refreshInteractionParam(t,e){if("empty"===this.result.type)return this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new F,this.interactionParam.startPoint=new F,void(this.interactionParam.lastWorldPosition=new N);if("edit"===this.interactionParam.type)return;const i=this.result.box.getCenter();if(t.distanceTo(this.result.rotationCorner)<14)return this.interactionParam.active=!0,this.interactionParam.type="rotation",this.interactionParam.anchor=i,this.interactionParam.lastPoint=e.clone(),this.interactionParam.startPoint=this.result.rotationCorner.clone(),void(this.interactionParam.lastWorldPosition=new N);const s=this.result.scaleCorners.find(e=>e.distanceTo(t)<10);return s?(this.interactionParam.active=!0,this.interactionParam.type="scale",this.interactionParam.anchor=i,this.interactionParam.lastPoint=e.clone(),this.interactionParam.startPoint=s.clone(),void(this.interactionParam.lastWorldPosition=new N)):this.result.box.containsPoint(t,!1)?(this.interactionParam.active=!0,this.interactionParam.type="translation",this.interactionParam.lastPoint=e.clone(),this.interactionParam.startPoint=t.clone(),void(this.interactionParam.lastWorldPosition=new N)):(this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new F,this.interactionParam.startPoint=new F,void(this.interactionParam.lastWorldPosition=new N))}refreshCursorResult(){const t=(new F).subtractVectors(this.interactionParam.startPoint,this.interactionParam.anchor).angle();switch(this.interactionParam.type){case"edit":case"none":case"translation":this.cursorResult={type:"normal",angle:0};break;case"scale":this.cursorResult={type:"scale",angle:(t+Math.PI/4)*E};break;case"rotation":this.cursorResult={type:"rotation",angle:(t+Math.PI/4)*E}}}getRenderObjects(){const t=[];if(!this.interactive||"empty"===this.result.type)return[];this.graphics.clear();const{box:e,scaleCorners:i,rotationCorner:s,rotation:r}=this.result,{boxLineWidth:a,boxLineColor:n,scaleCornerRadius:o,rotationCornerWidth:c,scaleCornerFillColor:h,scaleCornerStrokeWidth:l,scaleCornerStrokeColor:p}=ci.config.gestureHandlerConfig.textGizmoConfig;if(this.graphics.lineStyle(a,n),this.graphics.drawBox(e),"edit"!==this.interactionParam.type)i.forEach(t=>{this.graphics.lineStyle(l,p),this.graphics.beginFill(h),this.graphics.drawCircle(t.x,t.y,o),this.graphics.endFill()}),this.rotationSprite.width=c,this.rotationSprite.height=c,this.rotationSprite.anchor.set(.5,.5),this.rotationSprite.x=s.x,this.rotationSprite.y=s.y,this.rotationSprite.rotation=r,t.push(this.rotationSprite);else if("edit"===this.interactionParam.type&&"none"===this.textAreaElement.style.display){const t=this._pageDataUtils.getSelectedItems(),i=this._pageDataUtils.interactionUtils.viewportParam,s=t[0],r=s?.property,a=e.clone().rotate(r.rotation[2]*Ut),n=a.min.clone(),o=a.getSize();this.textAreaElement.value=r.text??"",this.textAreaElement.style.fontFamily=r.fontFamily,this.textAreaElement.style.fontSize=r.fontSize*i.scale+"px",this.textAreaElement.style.fontWeight=r.fontWeight,this.textAreaElement.style.color=`rgba(${r.textColor.join(",")})`,this.textAreaElement.style.display="block",this.textAreaElement.style.wordBreak="break-all",this.textAreaElement.style.whiteSpace="pre-wrap",this.textAreaElement.style.overflowWrap="break-word",this.textAreaElement.style.left=`${n.x}px`,this.textAreaElement.style.top=`${n.y}px`,this.textAreaElement.style.width=`${o.x}px`,this.textAreaElement.style.height="auto",this.textAreaElement.style.lineHeight=`${r.lineHeight}px`,this.textAreaElement.style.transformOrigin="center center",this.textAreaElement.style.paintOrder="stroke fill",void 0!==r.rotation[2]&&(this.textAreaElement.style.transform=`\n rotateZ(${-r.rotation[2]}deg)\n `),this.textAreaElement.addEventListener("input",this.handleInput),this.textAreaElement.addEventListener("blur",this.handleBlur),window.setTimeout(()=>{this.textAreaElement.focus()},50)}else if("edit"===this.interactionParam.type&&"block"===this.textAreaElement.style.display){const t=this._pageDataUtils.getSelectedItems(),i=this._pageDataUtils.interactionUtils.viewportParam,s=t[0],r=s?.property,a=e.clone().rotate(r.rotation[2]*Ut),n=a.min.clone(),o=a.getSize();this.textAreaElement.style.left=`${n.x}px`,this.textAreaElement.style.top=`${n.y}px`,this.textAreaElement.style.width=`${o.x}px`,this.textAreaElement.style.fontSize=r.fontSize*i.scale+"px",r.rotation[2]&&(this.textAreaElement.style.transform=`\n rotateZ(${-r.rotation[2]}deg)\n `)}return t.push(this.graphics),t}initInteractionPlane(t){switch(this.interactionParam.type){case"scale":case"translation":case"rotation":this._pageDataUtils.interactionUtils.initInteractionPlane()}}};import{Texture as Rt}from"@pixi/core";var Wt=class extends A{constructor(t){super(),c(this,"_pageDataUtils"),c(this,"_config",{}),c(this,"type","mask"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"result",{status:"init",lines:[]}),c(this,"graphics",new nt.Graphics),c(this,"linesMaskGraphics",new nt.Graphics),c(this,"rectMaskGraphics",new nt.Graphics),this._pageDataUtils=t}get interactive(){return ci.config.gestureHandlerConfig.maskGizmoEnabled}set interactive(t){t!==ci.config.gestureHandlerConfig.maskGizmoEnabled&&(t||(this.result.status="init"),ci.config.gestureHandlerConfig.maskGizmoEnabled=t)}get config(){return{...ci.config.gestureHandlerConfig.maskGizmoConfig,...this._config}}set config(t){this._config={...this._config,...t}}initialize(){}preparationAction(t){if(this.interactive)return this.result.point=new F(t.offsetX,t.offsetY),this.type}preAction(t){if(this.interactive)return this.result.point=new F(t.offsetX,t.offsetY),this.result.lines.push([]),this.type}action(t){if(!this.interactive||"init"===this.result.status)return;const e=new F(t.offsetX,t.offsetY);this.result.point=e,this.result.lines[this.result.lines.length-1]?.push(e)}endAction(){if(this.interactive)return this.type}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(kt(t,"You must call SDK#run() first"),1!==t.activeData.selectedItems.length)console.warn("Mask Gizmo can edit one picture at a time.");else{if("init"===this.result.status){const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]);this.result={status:"done",box:e.clone(),lines:[]}}else{const e=this.result.box,i=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]),s=i.getCenter().subtract(e.getCenter()),r=i.getSize().x/e.getSize().x;e.scale(r),e.translate(s)}this.refreshCursorResult()}}else this.result={status:"init",lines:[]}}getRenderObjects(){return this.interactive?this.refreshRenderObjects():[]}refreshRenderObjects(){if(this.graphics.clear(),this.linesMaskGraphics.clear(),this.rectMaskGraphics.clear(),!this.interactive||"init"===this.result.status)return[];const{brushColor:t,brushAlpha:e,boxLineWidth:i,boxLineColor:s,boxLineAlpha:r}=this.config,a=this.result.box,{min:n,max:o}=a,c=new W(new F(n.x,n.y),new F(o.x,n.y)),h=new W(new F(n.x,n.y),new F(n.x,o.y)),l=new W(new F(o.x,n.y),new F(o.x,n.y)),p=new W(new F(n.x,o.y),new F(o.x,o.y));this.graphics.fillBox(c),this.graphics.fillBox(h),this.graphics.fillBox(l),this.graphics.fillBox(p),this.graphics.lineStyle(i,s,r),this.graphics.drawBox(a),this.graphics.endFill();for(let t=0;t<this.result.lines.length;t++){0===t&&this.linesMaskGraphics.lineStyle({width:this.config.brushSize,color:0,cap:nt.LINE_CAP.ROUND,join:nt.LINE_JOIN.ROUND,alignment:.5});const e=this.result.lines[t];if(e)for(let t=0;t<e.length;t++){const i=e[t];i&&(0===t?this.linesMaskGraphics.moveTo(i.x,i.y):this.linesMaskGraphics.lineTo(i.x,i.y))}}return this.linesMaskGraphics.endFill(),this.rectMaskGraphics.beginFill(t,e),this.rectMaskGraphics.drawRect(a.min.x,a.min.y,a.max.x-a.min.x,a.max.y-a.min.y),this.rectMaskGraphics.endFill(),this.rectMaskGraphics.mask=this.linesMaskGraphics,[this.graphics,this.linesMaskGraphics,this.rectMaskGraphics]}refreshCursorResult(){const{point:t,box:e}=this.result;this.cursorResult={type:"normal",angle:0},t&&e&&t.x>=e.min.x&&t.x<=e.max.x&&t.y>=e.min.y&&t.y<=e.max.y&&(this.cursorResult={type:"circle",angle:0})}clearMask(){this.result.lines=[]}getMask(){if(0===this.result.lines.length)return null;const t=this.rectMaskGraphics.getBounds(),e=new nt.Renderer({width:Math.ceil(t.width),height:Math.ceil(t.height),backgroundColor:16777215}),i=new nt.Container,s=this.rectMaskGraphics.clone();s.beginFill(this.config.maskColor),s.position.set(-t.x,-t.y),s.drawRect(t.x,t.y,t.width,t.height),s.endFill(),i.addChild(s);const r=this.linesMaskGraphics.clone();s.mask=r,r.position.set(-t.x,-t.y),i.addChild(r),e.render(i);const a=e.view.toDataURL("image/png");return e.destroy(!0),a}},Lt=class extends A{constructor(t){super(),c(this,"type","loading"),c(this,"_pageDataUtils"),c(this,"_idMap",new Map),c(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t}addId(t){const e=this._pageDataUtils.getViewBoxById(t);"string"==typeof t&&(this._idMap.set(t,{status:"init",box:e,graphics:new nt.Graphics,ticker:new nt.Ticker}),this._pageDataUtils.addLoadingItems([t]),this._pageDataUtils.removeSelectedItems([t]))}deleteId(t){const e=this._idMap.get(t);if(e){const{graphics:i,ticker:s}=e;i.clear(),s.destroy(),this._idMap.delete(t),this._pageDataUtils.removeLoadingItems([t])}}initialize(){}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(0!==this._idMap.size)for(const t of this._idMap.keys()){const e=this._idMap.get(t);if(e){const{box:i}=e,s=this._pageDataUtils.getViewBoxById(t),r=s.getCenter().subtract(i.getCenter()),a=s.getSize().x/i.getSize().x;i.scale(a),i.translate(r)}}}getRenderObjects(){return 0===this._idMap.size?[]:this.refreshRenderObjects()}refreshRenderObjects(){if(0===this._idMap.size)return[];const t=[];for(const e of this._idMap.keys()){const i=this._idMap.get(e);if(!i)continue;if(t.push(i.graphics),"done"===i.status){i.ticker.update();continue}i.status="done";const{min:s,max:r}=i.box;let a=.006,n=.5;i.ticker.add(()=>{n>.6?a=-.003:n<.4&&(a=.006),n+=a,i.graphics.clear(),i.graphics.beginFill(0,n),i.graphics.drawRect(s.x,s.y,r.x-s.x,r.y-s.y),i.graphics.endFill()}),i.ticker.start()}return t}},Ht=class extends A{constructor(t,e){super(),c(this,"result",{type:"invalid"}),c(this,"interactionParam",{type:"none"}),c(this,"graphics",new nt.Graphics),c(this,"isShiftDown",!1),c(this,"_isLockScale",!1),c(this,"_pageDataUtils"),c(this,"_eventEmitter"),c(this,"type","picture-expand"),c(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return ci.config.gestureHandlerConfig.pictureExpandGizmoEnabled}set interactive(t){t!==ci.config.gestureHandlerConfig.pictureExpandGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture expand gizmo can not open."):ci.config.gestureHandlerConfig.pictureExpandGizmoEnabled=t)}get isLockScale(){return this._isLockScale}set isLockScale(t){t===this.isLockScale&&(this._isLockScale=t)}preparationAction(t){if(!this.interactive)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),this.type}preAction(t,e){if(this.interactive&&"none"!==this.interactionParam.type)return this.type}action(t){var e;if(!this.interactive||"none"===this.interactionParam.type||"invalid"===this.result.type)return;const i=new F(t.clientX,t.clientY),{startMouse:s,box:r}=this.interactionParam,a=(new F).subtractVectors(i,s),{itemBox:{min:n,max:o}}=this.result;switch(this.interactionParam.type){case"move":{const{min:t,max:e}=r,i=o.x-e.x,s=n.x-t.x,c=o.y-e.y,h=n.y-t.y;a.x=Math.min(Math.max(a.x,i),s),a.y=Math.min(Math.max(a.y,c),h);const l=r.clone().translate(a);this.result.expandBox.copyFrom(l),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}case"scale":{const{index:t}=this.interactionParam,{min:i,max:s}=r,c=r.corners[t],h=r.corners[(t+2)%4],l=new F(c.x+a.x,c.y+a.y);if(c.x>=s.x?l.x=Math.max(l.x,o.x):c.x<=i.x?l.x=Math.min(l.x,n.x):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.x=Math.abs(l.x-i.x)>Math.abs(l.x-s.x)?s.x:i.x),c.y>=s.y?l.y=Math.max(l.y,o.y):c.y<=i.y?l.y=Math.min(l.y,n.y):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.y=Math.abs(l.y-i.y)>Math.abs(l.y-s.y)?s.y:i.y),this.isShiftDown||this.isLockScale){const{x:t,y:a}=this.result.expandBox.getSize(),{x:p,y:m}=r.getSize();if((e=this.interactionParam).lockedAspect??(e.lockedAspect=t/a),Math.abs(l.x-h.x)/p>Math.abs(l.y-h.y)/m){const t=Math.abs(l.x-h.x)/this.interactionParam.lockedAspect;l.y=(c.y-h.y)/Math.abs(c.y-h.y)*t+h.y,c.y>=s.y?l.y=Math.max(l.y,o.y):c.y<=i.y?l.y=Math.min(l.y,n.y):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.y=Math.abs(l.y-i.y)>Math.abs(l.y-s.y)?s.y:i.y)}else{const t=Math.abs(l.y-h.y)*this.interactionParam.lockedAspect;console.log("result width is ",t),l.x=(c.x-h.x)/Math.abs(c.x-h.x)*t+h.x,c.x>=s.x?l.x=Math.max(l.x,o.x):c.x<=i.x?l.x=Math.min(l.x,n.x):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.x=Math.abs(l.x-i.x)>Math.abs(l.x-s.x)?s.x:i.x)}}this.result.expandBox.copyFrom((new W).setFromVec2ArrayWithOutCorners([l,h])),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}case"direction-scale":{const{index:t,point:e}=this.interactionParam,i=r.corners[t].clone();e.x>=o.x?(a.x=Math.max(r.corners[t].x+a.x,o.x)-i.x,a.y=0):e.x<=n.x&&(a.x=Math.min(r.corners[t].x+a.x,n.x)-i.x,a.y=0),e.y>=o.y?(a.y=Math.max(r.corners[t].y+a.y,o.y)-i.y,a.x=0):e.y<=n.y&&(a.y=Math.min(r.corners[t].y+a.y,n.y)-i.y,a.x=0);const s=r.corners.map((e,i)=>[t,(t+1)%4].includes(i)?e.clone().add(a):e.clone());this.result.expandBox.copyFrom((new W).setFromVec2Array(s)),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),this.type}interruption(){this.interactionParam={type:"none"}}actionKey(t){this.isShiftDown=t.shiftKey}endActionKey(t){this.isShiftDown=t.shiftKey,"lockedAspect"in this.interactionParam&&delete this.interactionParam.lockedAspect}cancelPreparation(){this.interactionParam={type:"none"}}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(kt(t,"You must call SDK#run() first"),1!==t.activeData.selectedItems.length)console.warn("Picture Expand Gizmo can edit one picture at a time.");else if("invalid"===this.result.type){const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]);this.result={type:"valid",itemBox:e.clone(),expandBox:e.clone()}}else{const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]),i=e.getCenter().subtract(this.result.itemBox.getCenter()),s=e.getSize().x/this.result.itemBox.getSize().x;this.result.itemBox.scale(s),this.result.expandBox.scale(s),this.result.itemBox.translate(i),this.result.expandBox.translate(i)}}else this.result={type:"invalid"}}refreshRenderObjects(){if(this.graphics.clear(),!this.interactive||"invalid"===this.result.type)return;const{maskColor:t,maskAlpha:e,expandBoxLineWidth:i,expandBoxLineColor:s,expandBoxLineAlpha:r,expandBoxCornerRadius:a,expandBoxCornerFillColor:n,expandBoxCornerLineWidth:o,expandBoxCornerLineColor:c,expandBoxCornerLineAlpha:h}=ci.config.gestureHandlerConfig.pictureExpandGizmoConfig,{expandBox:l}=this.result;this.graphics.beginFill(t,e),this.graphics.fillBox(l),this.graphics.endFill(),this.graphics.lineStyle(i,s,r),this.graphics.drawBox(l),this.graphics.beginFill(n),this.graphics.lineStyle(o,c,h),l.corners.forEach(t=>{this.graphics.drawCircle(t.x,t.y,a)}),this.graphics.endFill()}refreshCursorResult(t,e=0){switch(t){case"scale":case"direction-scale":this.cursorResult={type:"scale",angle:e};break;case"move":case"none":this.cursorResult={type:"normal",angle:0}}}getRenderObjects(){return this.interactive?(this.refreshRenderObjects(),[this.graphics]):[]}refreshInteractionType(t,e){if(this.interactionParam.type="none",!this.interactive||"invalid"===this.result.type)return;const{expandBox:i}=this.result;let s=!1,r=0;i.corners.forEach((a,n)=>{s||a.distanceTo(t)<ci.config.gestureHandlerConfig.pictureExpandGizmoConfig.scaleInteractionDistance&&(s=!0,this.interactionParam={type:"scale",index:n,box:i.clone(),startMouse:e},r=Math.PI/2*n)}),i.corners.forEach((a,n)=>{if(s)return;const o=new R(a.clone(),i.corners[(n+1)%4]),c=t.distanceToLine(o);if(c.d>=0&&c.d<=8&&c.t>=0&&c.t<=1){s=!0;const t=o.at(c.t);this.interactionParam={type:"direction-scale",index:n,point:t,box:i.clone(),startMouse:e},r=Math.PI/2*n+Math.PI/4}}),i.containsPoint(t)&&!s&&(this.interactionParam={type:"move",point:t.clone(),box:i.clone(),startMouse:e},s=!0),this.refreshCursorResult(this.interactionParam.type,r*E)}getExpandInfo(){if(this.interactive&&"invalid"!==this.result.type)return{expandBox:this.result.expandBox,itemBox:this.result.itemBox}}setExpandBox(t,e){if(!this.interactive||"invalid"===this.result.type)return;const{itemBox:{min:i,max:s}}=this.result;return this.result.expandBox.set(new F(Math.min(i.x,t.x),Math.min(i.y,t.y)),new F(Math.max(s.x,e.x),Math.max(s.y,e.y))),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone()),this.result.expandBox.clone()}},Nt=class{constructor(t){c(this,"wireframeApplication"),c(this,"gizmos",[]),c(this,"activeGizmo"),c(this,"selectorGizmo"),c(this,"transformGizmo"),c(this,"controlGizmo"),c(this,"preferenceGizmo"),c(this,"pictureCutGizmo"),c(this,"pictureExpandGizmo"),c(this,"textGizmo"),c(this,"maskGizmo"),c(this,"loadingGizmo"),c(this,"_ignoreInteraction",!1),c(this,"clickButtons",0),c(this,"container"),c(this,"_emitter"),c(this,"clickTime",0),c(this,"firstClick",!0),c(this,"dblclickTimeSpan",500),c(this,"spaceEmit",!1),c(this,"interactType","select"),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new S({backgroundAlpha:0,width:e,height:i,resolution:1,antialias:!0}),this.container=t,this.wireframeApplication.view.style.position="absolute",this.wireframeApplication.view.id="wireframeApplicationCanvas",t.appendChild(this.wireframeApplication.view),this.wireframeApplication.stage.sortableChildren=!0,async function(){await Promise.all(Object.entries(Tt).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>Tt[t]={...e,content:i})})).catch(t=>{console.error(t)})}()}set ignoreInteraction(t){t!==this._ignoreInteraction&&(this._ignoreInteraction=t,t&&(this.activeGizmo?.cancelPreparation(),this.activeGizmo=void 0))}get ignoreInteraction(){return this._ignoreInteraction}resize(){this.wireframeApplication&&(this.wireframeApplication.resizeTo=this.container,this.render())}refresh(){this.gizmos.forEach(t=>{t.refreshResults()})}render(){if(this.refresh(),!this.wireframeApplication?.stage)return;this.wireframeApplication?.stage?.removeChildren();const t=(this.ignoreInteraction?[this.preferenceGizmo]:this.gizmos).flatMap(t=>t.getRenderObjects());this.wireframeApplication?.stage?.addChild(...t),this.wireframeApplication?.render();const e=this.activeGizmo instanceof st||this.activeGizmo instanceof Mt||this.activeGizmo instanceof Ht||this.activeGizmo instanceof Wt||this.activeGizmo instanceof Ft||this.activeGizmo instanceof J?this.activeGizmo.cursorResult:void 0;this.setCursor(e)}async init(t,e){if(null===this.wireframeApplication)return void setTimeout(async()=>{await this.init(t,e)},50);this.gizmos=[],this.controlGizmo=new J(t),this.selectorGizmo=new q(t);const i=new at;this.transformGizmo=new st(t,i,this.selectorGizmo),this.preferenceGizmo=new St(t),this.pictureCutGizmo=new Mt(t,e),this.pictureExpandGizmo=new Ht(t,e),this.textGizmo=new Ft(t,i,this.selectorGizmo,e,this.wireframeApplication?.view.parentElement),this.textGizmo.rotationSprite.texture=await Rt.fromURL(ci.config.gestureHandlerConfig.textGizmoConfig.rotationCornerTexture),this.maskGizmo=new Wt(t),this.loadingGizmo=new Lt(t),this.gizmos.push(this.maskGizmo,this.pictureCutGizmo,this.pictureExpandGizmo,this.loadingGizmo,this.transformGizmo,this.textGizmo,this.selectorGizmo,this.controlGizmo,this.preferenceGizmo,i),this._emitter=e,this.initEvents(),this.registerViewEvent()}initEvents(){this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp)}registerViewEvent(){this.wireframeApplication.view.onmousedown=t=>{this.onMouseDown(t)},this.wireframeApplication.view.onmousemove=t=>{0===t.buttons&&this.onMouseMove(t)},this.wireframeApplication.view.onmouseout=()=>{this.selectorGizmo?.cancelPreparation(),this.render()},this.wireframeApplication.view.onwheel=t=>{this.onWheel(t)},this.wireframeApplication.view.oncontextmenu=t=>{t.stopPropagation(),t.preventDefault()}}onMouseDown(t){if(!this.ignoreInteraction){switch(this.clickButtons=t.buttons,this.interactType){case"select":if(4===this.clickButtons&&(this.activeGizmo=this.controlGizmo,this.controlGizmo.preAction(t)),this.firstClick=!!this.firstClick&&Date.now()-this.clickTime<this.dblclickTimeSpan,this.firstClick){if(this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.activeGizmo&&["transform","text"].includes(this.activeGizmo.type)){const e=this.activeGizmo.preAction(t,!0);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null"))}else{this.activeGizmo=void 0;const e=this.selectorGizmo?.preAction(t,!0);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null"))}this.firstClick=!1}else{void 0===this.activeGizmo&&this.gizmos.forEach(e=>{if(!e.interactive||this.activeGizmo)return;const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)});const e=this.activeGizmo?.preAction(t);"selector"!==e&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===e),this.clickTime=Date.now(),this.firstClick=!0}break;case"hand":this.activeGizmo=this.controlGizmo,this.activeGizmo.preAction(t)}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}}onMouseMove(t){if(!this.ignoreInteraction){if(0!==t.buttons)this.activeGizmo?.action(t);else switch(this.interactType){case"select":this.activeGizmo=void 0,this.spaceEmit?(this.activeGizmo=this.controlGizmo,this.controlGizmo.interactionType="mouse"):this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);"selector"!==i&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()});break;case"hand":this.activeGizmo=this.controlGizmo,this.activeGizmo.preparationAction(t)}this.render()}}onWheel(t){this.ignoreInteraction||(t.preventDefault(),this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.controlGizmo?.action(t))}onMouseUp(t){if(this.ignoreInteraction)return;const e=this.activeGizmo?.endAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===e),void 0===this.activeGizmo&&1===this.clickButtons&&this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.clickButtons=0,this.render(),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}onKeyDown(t){this.ignoreInteraction||("escape"===t.code.toLocaleLowerCase()&&"select"!==this.interactType&&this.setInteractType("select"),"space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active?this.gizmos.forEach(e=>{e.actionKey(t)}):(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.controlGizmo.interactionType="hand"===this.interactType||this.spaceEmit?"mouse":"wheel"),this.render())}onKeyUp(t){this.ignoreInteraction||(this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceEmit=!1,this.controlGizmo.interactionType="hand"===this.interactType||this.spaceEmit?"mouse":"wheel"),this.render())}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}setCursor(t){let e="default";if(t?.type&&["scale","rotation","circle","hand","active-hand"].includes(t.type)){const i=Tt[t.type];if("svg"===i.type){const s=16;e=encodeURIComponent(i.content.replace("rotate(0.00)",`rotate(${t.angle??0})`)),e=`url("data:image/svg+xml,${e}") ${s} ${s}, auto`}else e=i.content}this.wireframeApplication.view.style.cursor=e}openPictureCutGizmo(){if(!this.pictureCutGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureCutGizmo.interactive=!0,this.pictureCutGizmo.interactive&&(this.pictureExpandGizmo.interactive=!1,this.maskGizmo.interactive=!1,this.selectorGizmo.interactive=!1,this.transformGizmo.interactive=!1,this.textGizmo.interactive=!1);const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureCutGizmo(){if(!this.pictureCutGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureCutGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}setInteractType(t){t!==this.interactType&&(this.interactType=t,this.controlGizmo.interactionType="hand"===this.interactType||this.spaceEmit?"mouse":"wheel")}getCutInfo(){return this.pictureCutGizmo?.getCutInfo()}setCutBox(t,e){const i=this.pictureCutGizmo?.setCutBox(t,e);return this.render(),i}openPictureExpandGizmo(){if(!this.pictureExpandGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureExpandGizmo.interactive=!0,this.pictureExpandGizmo.interactive&&(this.pictureCutGizmo.interactive=!1,this.maskGizmo.interactive=!1,this.selectorGizmo.interactive=!1,this.transformGizmo.interactive=!1,this.textGizmo.interactive=!1);const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureExpandGizmo(){if(!this.pictureExpandGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureExpandGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}getExpandInfo(){return this.pictureExpandGizmo?.getExpandInfo()}setExpandBox(t,e){const i=this.pictureExpandGizmo?.setExpandBox(t,e);return this.render(),i}openMaskGizmo(t){if(!this.maskGizmo)return;const e=JSON.parse(JSON.stringify(ci.config));this.maskGizmo.interactive=!0,this.maskGizmo.config={brushSize:t},this.maskGizmo.interactive&&(this.pictureCutGizmo.interactive=!1,this.pictureExpandGizmo.interactive=!1,this.transformGizmo.interactive=!1,this.selectorGizmo.interactive=!1);const i=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}clearMaskGizmo(){this.maskGizmo&&(this.maskGizmo.clearMask(),this.render())}closeMaskGizmo(){if(!this.maskGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.maskGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}setMaskGizmoConfig(t){this.maskGizmo&&(this.maskGizmo.config=t)}getMask(){if(this.maskGizmo)return this.maskGizmo.getMask()}openLoadingGizmo(t){if(!this.loadingGizmo)return;const e=JSON.parse(JSON.stringify(ci.config));this.loadingGizmo.addId(t),this.loadingGizmo.interactive&&(this.maskGizmo.interactive=!1,this.pictureCutGizmo.interactive=!1);const i=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}closeLoadingGizmo(t){if(!this.loadingGizmo)return;const e=JSON.parse(JSON.stringify(ci.config));this.loadingGizmo.deleteId(t);const i=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}setPictureCutGizmoLockScale(t){this.pictureCutGizmo.isLockScale=t}setPictureExpandGizmoLockScale(t){this.pictureExpandGizmo.isLockScale=t}};import{assertExist as Ot}from"@galacean/effects";var Kt=class{constructor(t){c(this,"plane",new j),c(this,"ray",new Y),c(this,"viewportParam",{width:0,height:0,scale:1,translation:new F,rulerWidth:0}),c(this,"cameraParam",{position:new N,rotation:new N,focusPosition:new N,focusRotation:new N,viewProjectionMatrix:new O,inverseViewProjectionMatrix:new O}),c(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();Ot(t,"You must run SDK first");const e=new F(this.pageDataUtils.container.offsetWidth,this.pageDataUtils.container.offsetHeight),{zoom:i,translation:s}=t.property;this.viewportParam.width=e.x,this.viewportParam.height=e.y,this.viewportParam.scale=i,this.viewportParam.translation=new F(...s),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=O.fromArray(e.getViewProjectionMatrix().toArray()),i=O.fromArray(e.getViewMatrix().toArray()).invert(),s=new H;i.decompose(this.cameraParam.position,s,new N),this.cameraParam.rotation=(new K).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new N(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new K).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new K).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=O.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new K).setFromDegreeVector3(this.cameraParam.rotation));const i=new N(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new K).setFromDegreeVector3(this.cameraParam.rotation):(new K).setFromQuaternion((new H).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i).matrix)),r=i?(new N).setFromMatrixPosition(this.pageDataUtils.getItemTransformById(i).matrix):this.cameraParam.focusPosition,a="editor"===ci.config.mode?1:this.viewportParam.scale;t.multiply(a);const n=this.projectPoint(r.clone()),o=this.getWorldPositionByViewPoint(n.add(t));if(!o)return console.warn("size is out of bounds."),new N(0,0,0);const c=(new K).setFromQuaternion((new H).setFromEuler(s).invert());return(e||!i?o.applyEuler(c,r):o).subtract(r)}projectPoint(t){const{width:e,height:i,scale:s}=this.viewportParam,{viewProjectionMatrix:r}=this.cameraParam,a="editor"===ci.config.mode?1:s;return(new F).copyFrom(t.applyMatrix(r).toVector2()).toViewCoordinate(e*a,i*a)}getWorldPositionByViewPoint(t){const{position:e,inverseViewProjectionMatrix:i}=this.cameraParam,s=this.getNDCPositionByScreenPosition(t),r=(new $).setFromCamera(s,{position:e,inverseViewProjectMatrix:i}).rayCastPlane(this.plane);return r?.point}getNDCPositionByScreenPosition(t){const{width:e,height:i,scale:s}=this.viewportParam,r="editor"===ci.config.mode?1:s;return new F(t.x/(e*r)*2-1,1-t.y/(i*r)*2)}getNDCSizeByPixelSize(t){const{width:e,height:i}=this.viewportParam;return new F(t.x/e*2,-t.y/i*2)}getPixelSizeByNDCSize(t){const{width:e,height:i}=this.viewportParam;return new F(t.x/2*e,-t.y/2*i)}getViewPositionWWithOutTransform(t){const{scale:e}=this.viewportParam,i="editor"===ci.config.mode?1:e;return t.divide(i)}getViewPositionByPixelPoint(t){if("template"===ci.config.mode)return t.clone();const{width:e,height:i,scale:s,translation:r}=this.viewportParam;return t.clone().scaleByCenter(new F(s,s),new F(e/2,i/2)).add(r)}};import{FFmpeg as jt}from"@ffmpeg/ffmpeg";import{toBlobURL as Yt}from"@ffmpeg/util";var $t={SCRIPT:"https://gw.alipayobjects.com/os/gltf-asset/99531561844014/img2webp.js",WASM:"https://mdn.alipayobjects.com/mars/uri/file/as/0.0.4/wasm/img2webp/img2webp.wasm"},Jt={CLASSWORKER:"https://mdn.alipayobjects.com/rms/uri/file/as/ffmpeg/core/0.12.10/dist/worker.js",DEFAULT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.wasm"},MT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.wasm",WORKER:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.worker.js"}};function Xt(t,e,i,s){const r=e.getContext("2d");_t(r),r.clearRect(0,0,e.width,e.height),i&&(r.save(),r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.restore()),s&&r.drawImage(s,0,0,s.width,s.height,0,0,e.width,e.height),r.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height)}async function Zt(){return new Promise(async(t,e)=>{try{await function(t,e={}){return new Promise((i,s)=>{const r=document.querySelector(`script[src="${t}"]`);if(r)return"true"===r.dataset.loaded?void i(r):(r.addEventListener("load",()=>{i(r)}),void r.addEventListener("error",()=>{s(new Error(`Script already failed: ${t}`))}));const a=document.createElement("script");a.src=t,a.async=!0,Object.keys(e).forEach(t=>{a.setAttribute(t,e[t]??"")}),a.onload=()=>{a.dataset.loaded="true",i(a)},a.onerror=()=>{s(new Error(`Failed to load script: ${t}`))},document.head.appendChild(a)})}($t.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?$t.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function qt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.disposed||t.destroyCurrentCompositions()}function Qt(t=[750,750]){const e=b(),i={id:b(),dataType:g.DataType.TimelineAsset,tracks:[]},s={id:b(),item:{id:e},dataType:g.DataType.CompositionComponent,items:[],timelineAsset:{id:i.id},sceneBindings:[]},r={id:e,name:"AI 设计师画布",duration:999,startTime:0,endBehavior:g.EndBehavior.forward,previewSize:[...t],camera:{fov:60,far:40,near:.1,clipMode:1,position:[0,0,8],rotation:[0,0,0],aspect:t[0]/t[1]},components:[{id:s.id}]},a={version:g.JSONSceneVersion.LATEST,playerVersion:{web:"2.7.3",native:"10.7.6"},type:"ge",compositionId:e,compositions:[],images:[],plugins:[],bins:[],textures:[],items:[],components:[],materials:[],shaders:[],geometries:[],animations:[],miscs:[]};return a.miscs.push(i),a.compositions.push(r),a.components.push(s),a}function te(t,e,i,s,r,a,n){const o=b(),c={id:t,name:a,dataType:g.DataType.VFXItemData,components:[{id:o}],delay:0,duration:999,endBehavior:g.EndBehavior.restart,renderLevel:g.RenderLevel.BPlus,type:g.ItemType.sprite,visible:!0,transform:{position:{x:e.x,y:e.y,z:e.z},eulerHint:{x:i.x,y:i.y,z:i.z},size:{x:s.x,y:s.y},scale:{x:r.x,y:r.y,z:r.z},anchor:{x:0,y:0}},content:void 0},h={id:o,item:{id:t},dataType:g.DataType.SpriteComponent,options:{startColor:[1,1,1,1]},renderer:{renderMode:g.RenderMode.MESH}};n&&(h.renderer.texture={id:n});const l={id:b(),dataType:g.DataType.ActivationPlayableAsset},p={id:b(),dataType:g.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:l.id}}]},m={id:b(),dataType:g.DataType.SpriteColorPlayableAsset,startColor:[1,1,1,1]};return{item:c,components:[h],tracks:[p,{id:b(),dataType:g.DataType.SpriteColorTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:m.id}}]}],playableAssets:[l,m]}}function ee(t,e,i,s,r,a){const n=b(),o={id:t,name:e,dataType:g.DataType.VFXItemData,components:[{id:n}],delay:0,duration:999,endBehavior:g.EndBehavior.restart,renderLevel:g.RenderLevel.BPlus,type:g.ItemType.sprite,visible:!0,transform:{position:{x:i.x,y:i.y,z:i.z},eulerHint:{x:s.x,y:s.y,z:s.z},size:{x:r.x,y:r.y},scale:{x:1,y:1,z:1},anchor:{x:0,y:0}},content:void 0},c={id:n,item:{id:t},dataType:g.DataType.TextComponent,options:a,renderer:{renderMode:1}},h={id:b(),dataType:g.DataType.ActivationPlayableAsset};return{item:o,components:[c],tracks:[{id:b(),dataType:g.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:h.id}}]}],playableAssets:[h]}}function ie(t,e){t.items.push(e.item),t.miscs.push(...e.tracks,...e.playableAssets),t.components.push(...e.components);const i=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0],s=t.components.find(t=>t.id===i.components[0]?.id);if(s){s.items.push({id:e.item.id});const i={id:b(),dataType:g.DataType.ObjectBindingTrack,children:[],clips:[]};for(const t of e.tracks)i.children.push({id:t.id});t.miscs.find(t=>t.id===s.timelineAsset.id).tracks.push({id:i.id}),s.sceneBindings.push({key:{id:i.id},value:{id:e.item.id}}),t.miscs.push(i)}}function se(t,e,i){var s;const r=t.items.findIndex(t=>t.id===e);if(r<0)return;!function(t,e){var i;const s=t.items.findIndex(t=>t.id===e);if(!t.items[s]?.parentId)return;const r=t.items.find(e=>e.id===t.items[s].parentId);if(!r)return void delete t.items[s].parentId;const{position:a={x:0,y:0,z:0},eulerHint:n=new N,scale:o=new N(1,1,1)}=r.transform;(i=t.items[s]).transform??(i.transform={position:{x:0,y:0,z:0},eulerHint:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},size:{x:1,y:1}}),t.items[s].transform.position.x+=a.x,t.items[s].transform.position.y+=a.y,t.items[s].transform.position.z+=a.z,t.items[s].transform.eulerHint.x+=n.x,t.items[s].transform.eulerHint.y+=n.y,t.items[s].transform.eulerHint.z+=n.z,t.items[s].transform.scale.x*=0===o.x?1:o.x,t.items[s].transform.scale.y*=0===o.y?1:o.y,t.items[s].transform.scale.z*=0===o.z?1:o.z}(t,e);const a=t.items.find(t=>t.id===i);if(!a)return;t.items[r].parentId=i;const{position:n={x:0,y:0,z:0},eulerHint:o=new N,scale:c=new N(1,1,1)}=a.transform;(s=t.items[r]).transform??(s.transform={position:{x:0,y:0,z:0},eulerHint:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},size:{x:1,y:1}}),t.items[r].transform.position.x-=n.x,t.items[r].transform.position.y-=n.y,t.items[r].transform.position.z-=n.z,t.items[r].transform.eulerHint.x-=o.x,t.items[r].transform.eulerHint.y-=o.y,t.items[r].transform.eulerHint.z-=o.z,t.items[r].transform.scale.x/=0===c.x?1:c.x,t.items[r].transform.scale.y/=0===c.y?1:c.y,t.items[r].transform.scale.z/=0===c.z?1:c.z}function re(t,e){let i;return t.components.forEach(s=>{if(s.dataType===g.DataType.SpriteComponent&&s.item.id===e&&s.renderer.texture){const e=t.textures?.find(t=>t.id===s.renderer.texture?.id);e&&(i=t.images.find(t=>t.id===e.source.id)?.url)}}),i}import{VFXItem as ae,SpriteComponent as ne,spec as oe,TextComponent as ce}from"@galacean/effects";import{VideoComponent as he}from"@galacean/effects-plugin-multimedia";var le=class{static createEmpty(t,e=null,i="NewVFXItem"){const s=pe.createVFXItem(t,e,i);return s.type=oe.ItemType.null,s}static createSprite(t,e=null,i="NewSpite"){const s=pe.createVFXItem(t,e,i,ne);return s.type=oe.ItemType.sprite,s}static createText(t,e=null,i="NewText"){const s=pe.createVFXItem(t,e,i,ce);return s.type=oe.ItemType.text,s}static createVideo(t,e=null,i="NewVideo"){const s=pe.createVFXItem(t,e,i,he);return s.type=oe.ItemType.video,s}},pe=class{static createVFXItem(t,e=null,i="NewVFXItem",...s){const r=new ae(t.getEngine());r.name=i;for(const t of s)r.addComponent(t);return t.addItem(r),t.rootComposition.items.push(r),e&&r.setParent(e),r}};import{AssetManager as me}from"@galacean/effects";var de=class{constructor(t,e,i,s){c(this,"sdk"),c(this,"player"),c(this,"container"),c(this,"emitter"),c(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new Kt(this)}getPageData(){return this.sdk.pageData}getCurrentComposition(){return this.player.getCompositions()[0]}isItemSelected(t){return!!this.sdk.pageData?.activeData.selectedItems?.find(e=>e===t)}getItemEditEnable(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData||this.getViewProperty()?.ignoreInteraction)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart)}getItemShow(t){const e=this.getViewItemById(t);if(!this.sdk.pageData||!e?.property.visible)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart||a===g.EndBehavior.freeze)}addSelectedItems(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.selectedItems??[];t.forEach(t=>{Z(e,t)}),this.emitter.emit("selectedItemChange",e)}removeSelectedItems(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.selectedItems??[];for(const i of t){const t=e.findIndex(t=>t===i);t>=0&&e.splice(t,1)}this.emitter.emit("selectedItemChange",e)}clearSelectedItems(t=!1){this.sdk.pageData&&(t?this.emitter.emit("selectedItemChange",[]):this.sdk.pageData.activeData.selectedItems=[])}getSelectedItems(){const t=this.sdk.pageData?.activeData.selectedItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}addPreSelectedItem(t){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=void 0,this.emitter.emit("preSelectedItemChange",void 0)}getPreSelectedItem(){const t=this.getPageData();v(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}addLoadingItems(t){var e;v(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.activeData).loadingItems??(e.loadingItems=[]);const i=this.sdk.pageData.activeData.loadingItems;t.forEach(t=>{Z(i,t)}),this.emitter.emit("loadingItemChange",i)}removeLoadingItems(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.loadingItems??[];for(const i of t){const t=e.findIndex(t=>t===i);t>=0&&e.splice(t,1)}this.emitter.emit("loadingItemChange",e)}clearLoadingItems(){this.sdk.pageData&&(this.sdk.pageData.activeData.loadingItems=[],this.emitter.emit("loadingItemChange",[]))}getLoadingItems(){const t=this.sdk.pageData?.activeData.loadingItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}getViewItemById(t){return this.sdk.pageData?.items.find(e=>e.id===t)}getPlayerSizeByParent(t,e){const[i,s]=t,[r=1624,a=750]=e;let n=s,o=n/a*r;return o>i&&(n=i/o*s,o=i),[o,n]}async loadScene(t){qt(this.player);const e=this.getViewProperty(t);if(!e||!this.sdk.pageData)return void console.warn(`This page does not have ${t} view property.`);const{scene:i,size:s}=e,r=this.container.parentElement?.offsetWidth??300,a=this.container.parentElement?.offsetHeight??300,[n,o]=this.getPlayerSizeByParent([r,a],s);this.container.style.width=`${n}px`,this.container.style.height=`${o}px`,this.sdk.pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},this.player.resize();const c=JSON.parse(JSON.stringify(i)),h=await this.player.loadScene(c,{autoplay:!1});this.player.gotoAndStop(this.sdk.pageData.time),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,h.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshPageTime(t){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t,e,i){var s;v(this.sdk.pageData,"You must call SDK#run() first"),(s=this.sdk.pageData.property).zoom??(s.zoom=1);const{zoom:r,translation:[a=0,n=0]}=this.sdk.pageData.property,{width:o,height:c,scale:h}=this.interactionUtils.viewportParam,l=i?t:k(t,-.1,.1),p=V(k(r+l,ci.config.pageConfig.minZoom,ci.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=p,ci.config.mode){case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new F(a,n)),i=e??new F(o/2,c/2),s=this.interactionUtils.getNDCPositionByScreenPosition(i),r=(s.x-t.x)/h,l=(s.y-t.y)/h,m=new F(s.x-r*p,s.y-l*p),d=(new O).compose(new N(m.x,m.y,0),new H,new N(p,p,1));this.sdk.pageData.property.translation=this.interactionUtils.getPixelSizeByNDCSize(m).toArray(),this.setCurrenCameraViewportMatrix(d);break}case"template":this.container.style.scale=`${p}`}this.refreshInteractionParam(),this.sdk.pageData.items=[];const m=this.getCurrentComposition();this.addViewItemsByItems(this.sdk.pageData.items,m.items),this.emitter.emit("zoomChange",p),this.emitter.emit("viewportTransform",{zoom:p,translatoion:[a,n]}),this.emitter.emit("pageDataChange",this.sdk.pageData)}setPageZoom(t){v(this.sdk.pageData,"You must call SDK#run() first");const{translation:[e=0,i=0]}=this.sdk.pageData.property,s=V(k(t,ci.config.pageConfig.minZoom,ci.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=s,ci.config.mode){case"template":this.container.style.scale=`${s}`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new F(e,i)),r=(new O).compose(new N(t.x,t.y,0),new H,new N(s,s,1));this.setCurrenCameraViewportMatrix(r);break}}this.emitter.emit("zoomChange",s),this.emitter.emit("viewportTransform",{zoom:s,translatoion:[e,i]}),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){v(this.sdk.pageData,"You must call SDK#run() first");const{translation:[e=0,i=0],zoom:s}=this.sdk.pageData.property,r=e+t.x,a=i+t.y;switch(this.sdk.pageData.property.translation=[r,a],ci.config.mode){case"template":this.container.style.translate=`${r}px ${a}px`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new F(r,a)),e=(new O).compose(new N(t.x,t.y,0),new H,new N(s,s,1));this.setCurrenCameraViewportMatrix(e);break}}this.refreshInteractionParam(),this.sdk.pageData.items=[];const n=this.getCurrentComposition();this.addViewItemsByItems(this.sdk.pageData.items,n.items),this.emitter.emit("viewportTransform",{zoom:s,translatoion:[r,a]}),this.emitter.emit("pageDataChange",this.sdk.pageData)}setCurrenCameraViewportMatrix(t){const e=this.getCurrentComposition();if(!e)return;const{camera:i}=e;i.setViewportMatrix(t)}rotateItem(t,e){const i=this.getPlayerItemById(t);i&&(i.rotate(...e.toArray()),this.transformSceneItem(t,"rotation",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"rotation"}))}moveItem(t,e){const i=this.getPlayerItemById(t);if(i){const s=(new O).copyFrom(i.transform.getParentMatrix()??new O);s.setPosition(new N);const r=e.clone().applyMatrix(s.invert());i.translate(...r.toArray()),i.transform.updateLocalMatrix(),this.transformSceneItem(t,"position",r.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"translation"})}}scaleItem(t,e){const i=this.getPlayerItemById(t);i&&(i.scale(...e.toArray()),this.transformSceneItem(t,"scale",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"size"}))}scaleTextItem(t,e){const i=this.getViewItemById(t);if(i?.type===g.ItemType.text){const{textWidth:t}=i.property;this.changeItemProperty({itemId:i.id,type:g.ItemType.text,propertyName:"textWidth",propertyValue:t*e})}}getItemTransformById(t){const e={matrix:new O,parentMatrix:new O},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=O.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(O.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(O.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new O).toArray()))}return e}addViewItemsByItems(t,e,i){const s=e=>{e.forEach(e=>{t.find(t=>t.id===e.getInstanceId())||t.push(this.createViewItemByPlayerItem(e,i))})};for(const i of e)ci.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){v(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s,isVisible:r}=t,a={position:[0,0],rotation:[0,0,0],size:[0,0],visible:r,keyPropertyEditing:!1},{scale:n,translation:o,width:c,height:h}=this.interactionUtils.viewportParam,l="editor"===ci.config.mode?1:n,p=this.getViewportLeftTopPosition();if(t.type!==g.ItemType.null){i.updateLocalMatrix();const e=(new O).copyFrom(s?.transform.getWorldMatrix()??(new O).identity()).invert().multiply(i.getWorldMatrix()),r=new N,n=new H,o=new N;e.decompose(r,n,o);const c=(new K).setFromQuaternion(n);c.x=Number.isNaN(c.x)?0:c.x,c.y=Number.isNaN(c.y)?0:c.y,c.z=Number.isNaN(c.z)?0:c.z;const{scale:h,translation:l,width:p,height:m}=this.interactionUtils.viewportParam;this.interactionUtils.initInteractionPlane(r,c);const d=this.interactionUtils.projectPoint(r),g="editor"===ci.config.mode?d.subtract(l.clone().multiply(h)).scaleByCenter(new F(1/h,1/h),new F(p/2,m/2)).toArray().map(t=>V(t,2)):d.divide(h).toArray().map(t=>V(t,2)),u=c.toArray().map(t=>V(t,2)),f=o.toArray().map(t=>V(t,2)),y=i.size.toArray(),x=this.getPixelSizeByWorldSize([f[0]*y[0],f[1]*y[1],f[2]],t).map(t=>V(t,2));a.position=g,a.rotation=u,a.size=x}else{const e=this.getViewBoxByPlayerItem(t,t.children),i=this.interactionUtils.getViewPositionWWithOutTransform(e.getCenter().subtract(p)),s="editor"===ci.config.mode?i.subtract(o.clone().multiply(n)).scaleByCenter(new F(1/n,1/n),new F(c/2,h/2)).toArray().map(t=>V(t,2)):i.toArray();a.position=s,a.size=e.getSize().divide(l).toArray()}switch(t.type){case g.ItemType.sprite:{const e=this.getViewProperty()?.scene;if(e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(a.keyPropertyEditing||!("renderer"in t)||!("texture"in t.renderer)||!t.renderer.texture)return;const i=e.textures?.find(e=>e.id===t.renderer.texture.id);if(i&&"source"in i&&i.source){const t=e?.images.find(t=>t.id===i.source.id);a.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(a,{image:s})}})}break}case g.ItemType.text:case g.ItemType.richtext:{const e=this.getViewProperty()?.scene;if(a.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:n,fontSize:o,fontStyle:c,outline:h,textWidth:l,lineHeight:p}=t.options,m=h?.outlineColor?h.outlineColor.map((t,e)=>e>2?t:V(255*t,0)):void 0,d=i.map((t,e)=>e>2?t:V(255*t,0)),u=h?.outlineWidth;Object.assign(a,{textAlign:e,textColor:d,fontWeight:r,text:s,fontFamily:n,fontSize:o,fontStyle:c,outlineColor:m,outlineWidth:u,textWidth:l,lineHeight:p})})}break}}return{id:t.getInstanceId(),name:t.name,parentId:t.parentId??e,children:[],type:t.type,duration:t.duration,delay:t.defination.delay,endBehavior:t.endBehavior,property:a}}getViewBoxById(t){const e=new W,i=this.getPlayerItemById(t),s=this.getChildrenPlayerItems(i);return i&&s?this.getViewBoxByPlayerItem(i,s):e}getItemViewAnchor(t){const e=this.getPlayerItemById(t);if(e?.transform?.anchor){const t=(new N).copyFrom(e.transform.anchor).applyMatrix((new O).copyFrom(e.transform.getWorldMatrix())),i=this.getViewportLeftTopPosition();return this.interactionUtils.projectPoint(t).add(i).round(2)}}getChildrenPlayerItems(t){const e=[];return t?(e.push(...this.player.getCompositions()[0].items.filter(e=>e.parentId===t.getInstanceId())),e.push(...e.flatMap(t=>this.getChildrenPlayerItems(t))),e):[]}getChildrenSceneItemIds(t,e){const i=[];return i.push(...e.items.filter(e=>e.parentId===t).map(t=>t.id)),i.push(...i.flatMap(t=>this.getChildrenSceneItemIds(t,e))),i}getViewBoxByPlayerItem(t,e){const i=new W;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,n=(new O).copyFrom(r?.transform.getWorldMatrix()??new O).invert().multiply(s.getWorldMatrix()),{x:o,y:c}=a.clone().divide(2),h=new N(o,c,0).applyMatrix(n),l=new N(o,-c,0).applyMatrix(n),p=new N(-o,-c,0).applyMatrix(n),m=new N(-o,c,0).applyMatrix(n),d=this.getViewportLeftTopPosition(),g=this.interactionUtils.projectPoint(h).add(d).round(2),u=this.interactionUtils.projectPoint(l).add(d).round(2),f=this.interactionUtils.projectPoint(p).add(d).round(2),y=this.interactionUtils.projectPoint(m).add(d).round(2);i.setFromVec2Array([g,u,f,y]);const x=e?.map(t=>this.getViewBoxById(t.getInstanceId()));x&&x.map(t=>i.union(t));break}case g.ItemType.null:{const t=e?.map(t=>this.getViewBoxById(t.getInstanceId()));t&&t.map(t=>i.union(t));break}}return i}getViewportLeftTopPosition(){if(!this.sdk.pageData||"editor"===ci.config.mode)return new F;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,n=new F(i,s),o=new F(r,a).multiply(t);return n.clone().divide(2).subtract(o.clone().divide(2)).add(e)}getContainerPosition(){const{offsetWidth:t,offsetHeight:e}=this.container.parentElement;return new F(t/2,e/2).add(new F(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,i="editor"===ci.config.mode?1:e,{width:s,height:r}=this.interactionUtils.viewportParam,a=new F(s,r).multiply(i),n=this.getViewportLeftTopPosition(),o=t.clone().subtract(n);return new F(o.x/a.x*2-1,1-o.y/a.y*2)}async changeItemProperty(t){v(this.sdk.pageData,"You must call SDK#run() first"),v(t,"Param is not exsited.");const e=this.getViewItemById(t.itemId),i=this.getPlayerItemById(t.itemId);if(!e||!i)return void console.warn(`Id ${t.itemId} is not a item id.`);if(!(t.propertyName in e.property))return void console.warn(`Item does not have property ${t.propertyName}.`);const s="editor"===ci.config.mode?this.interactionUtils.viewportParam.scale:1;switch(t.propertyName){case"textAlign":[g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(P).setTextAlign(t.propertyValue);break;case"textColor":if(Array.isArray(t.propertyValue)&&4===t.propertyValue.length){const e=t.propertyValue.map((t,e)=>e>2?t:V(t/255,5));i.getComponent(P).setTextColor(e)}break;case"fontFamily":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0];await me.loadFontFamily([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(P).setFontFamily(s)}break;case"text":if("string"==typeof t.propertyValue){const e=i.getComponent(P);e.setText(t.propertyValue);const r=e.getLineCount(t.propertyValue),a=Math.ceil(e.textLayout.lineHeight*r);e.setTextHeight(a);const n=e.textLayout.width,o=new F(n,a).multiply(s),c=this.interactionUtils.getWorldSizeByViewSize(o);i.transform.setSize(Math.abs(c.x),Math.abs(c.y))}break;case"fontWeight":[g.TextWeight.normal,g.TextWeight.bold,g.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(P).setFontWeight(t.propertyValue);break;case"textWidth":{const e=i.getComponent(P);e.setTextWidth(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new F(a,r).multiply(s),o=this.interactionUtils.getWorldSizeByViewSize(n);i.transform.setSize(Math.abs(o.x),Math.abs(o.y));break}case"lineHeight":{const e=i.getComponent(P);e.setLineHeight(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new F(a,r).multiply(s),o=this.interactionUtils.getWorldSizeByViewSize(n);i.transform.setSize(Math.abs(o.x),Math.abs(o.y));break}case"outlineColor":if(Array.isArray(t.propertyValue)&&4===t.propertyValue.length){const e=i.getComponent(P);if("function"==typeof e.setOutlineColor){const i=t.propertyValue.map((t,e)=>e>2?t:V(t/255,5));e.setOutlineColor(i)}}break;case"outlineWidth":if("number"==typeof t.propertyValue){const e=i.getComponent(P);"function"==typeof e.setOutlineWidth&&e.setOutlineWidth(t.propertyValue)}break;case"fontSize":if("number"==typeof t.propertyValue&&i.type===g.ItemType.text){const e=i.getComponent(P);e.setFontSize(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new F(a,r).multiply(s),o=this.interactionUtils.getWorldSizeByViewSize(n);i.transform.setSize(Math.abs(o.x),Math.abs(o.y))}break;case"image":"string"==typeof t.propertyValue&&i.getComponent(I).setTexture(await C.fromImage(t.propertyValue,this.player.renderer.engine));break;case"position":if(Array.isArray(t.propertyValue)&&(3===t.propertyValue.length||2===t.propertyValue.length)){const i=t.propertyValue.map((t,i)=>t-(e.property.position[i]??0)),s=this.interactionUtils.getWorldSizeByViewSize(new F(...i),!0,t.itemId);this.moveItem(t.itemId,s)}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.rotation[i]??0));this.rotateItem(t.itemId,new N(...i).negate())}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const i=t.propertyValue.map(t=>0===t||null===t?1:t),s=e.property.size.map(t=>t||1),r=i.map((t,e)=>t/s[e]);this.scaleItem(t.itemId,new N(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),ci.config.pageConfig.groupVisible)){this.getChildrenPlayerItems(i).forEach(e=>{e.setVisible(t.propertyValue)})}}["position","rotation","size"].includes(t.propertyName)||this.player.gotoAndStop(this.sdk.pageData.time),this.changeViewItemProperty(t),this.refreshViewItem(t.itemId)}changeViewItemProperty(t){v(this.sdk.pageData,"You must call SDK#run() first"),v(t,"Param is not exsited."),this.sdk.pageData.viewProperties.forEach(e=>{if(!this.sdk.pageData?.property.asyncMode&&e.id!==this.sdk.pageData?.activeData.view)return;const{scene:i}=e;switch(t.propertyName){case"position":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),s=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(s?.[e]??0)),a=this.interactionUtils.getWorldSizeByViewSize(new F(...r),!0,t.itemId);this.changeSceneItemProperty(i,{...t,propertyValue:a.toArray()})}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),s=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(s?.[e]??0));this.changeSceneItemProperty(i,{...t,propertyValue:r})}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),s=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t/(s?.[e]??0));this.changeSceneItemProperty(i,{...t,propertyValue:r})}break;default:this.changeSceneItemProperty(i,t)}})}changeSceneItemProperty(t,e){var i,s,r,a,n,o;switch(v(e,"Param is not exsited."),e.propertyName){case"textAlign":if([g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&"textAlign"in i.options&&(i.options.textAlign=e.propertyValue)}break;case"textColor":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(i?.options){const t=e.propertyValue.map((t,e)=>e>2?t:V(t/255,5));i.options.textColor=[...t]}}break;case"fontFamily":if("string"==typeof e.propertyValue){const i=e.propertyValue.split("/"),s=i[i.length-1]?.split(".")[0],r=t.fonts?.find(t=>"family"in t&&t.family===s||"fontFamily"in t&&t.fontFamily===s);!r&&t.fonts&&s&&t.fonts.push({fontFamily:s,fontURL:e.propertyValue});const a=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));a&&(a.options.fontFamily=s)}break;case"lineHeight":if("number"==typeof e.propertyValue){const s=t.items.find(t=>t.id===e.itemId),r=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(s&&r?.options){r.options.lineHeight=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const e=t.getComponent(P),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a,n],c=this.interactionUtils.getWorldSizeByViewSize(new F(...o));(i=s.transform).size??(i.size={x:1,y:1}),s.transform.size={x:Math.abs(c.x),y:Math.abs(c.y)}}}}break;case"textWidth":if("number"==typeof e.propertyValue){const i=t.items.find(t=>t.id===e.itemId),r=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(r?.options&&i){r.options.textWidth=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const e=t.getComponent(P),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a,n],c=this.interactionUtils.getWorldSizeByViewSize(new F(...o));(s=i.transform).size??(s.size={x:1,y:1}),i.transform.size={x:Math.abs(c.x),y:Math.abs(c.y)}}}}break;case"text":if("string"==typeof e.propertyValue){const i=t.items.find(t=>t.id===e.itemId),s=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(s?.options&&i){s.options.text=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const a=t.getComponent(P),n=a.getLineCount(e.propertyValue),o=a.textLayout.lineHeight,c=a.textLayout.width,h=Math.ceil(o*n);s.options.textHeight=h;const l=[c,h],p=this.interactionUtils.getWorldSizeByViewSize(new F(...l));(r=i.transform).size??(r.size={x:1,y:1}),i.transform.size={x:Math.abs(p.x),y:Math.abs(p.y)}}}}break;case"fontWeight":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontWeight=e.propertyValue)}break;case"outlineColor":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&((a=i.options).outline??(a.outline={}),i.options.outline.outlineColor=[...e.propertyValue.map((t,e)=>e>2?t:V(t/255,5))])}break;case"outlineWidth":if("number"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&((n=i.options).outline??(n.outline={}),i.options.outline.outlineWidth=e.propertyValue)}break;case"fontSize":if("number"==typeof e.propertyValue){const i=t.items.find(t=>t.id===e.itemId),s=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(s?.options&&i){s.options.fontSize=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const e=t.getComponent(P),r=e.textLayout.width,a=Math.ceil(e.lineCount*e.lineCount);s.options.textHeight=a;const n=[r,a],c=this.interactionUtils.getWorldSizeByViewSize(new F(...n));(o=i.transform).size??(o.size={x:1,y:1}),i.transform.size={x:Math.abs(c.x),y:Math.abs(c.y)}}}}break;case"image":if("string"==typeof e.propertyValue){t.components.filter(t=>t.item.id===e.itemId).forEach(i=>{if(!("renderer"in i))return;const s=t.textures?.find(t=>t.id===i.renderer.texture.id);if(s&&"source"in s&&s.source){const i=t?.images.find(t=>t.id===s.source.id);i?.url&&(i.url=e.propertyValue,delete i.webp),i&&"template"in i&&i.template.background&&(i.template.background.url=e.propertyValue)}})}break;case"position":{const i=e.propertyValue;if(Array.isArray(e.propertyValue)&&3===i.length){const s=t.items.find(t=>t.id===e.itemId);s?.transform&&(s.transform.position.x+=i[0],s.transform.position.y+=i[1],s.transform.position.z+=i[2])}break}case"rotation":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.eulerHint.x+=e.propertyValue[0],i.transform.eulerHint.y+=e.propertyValue[1],i.transform.eulerHint.z+=e.propertyValue[2])}break;case"size":if(Array.isArray(e.propertyValue)&&2===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.scale.x*=e.propertyValue[0],i.transform.scale.y*=e.propertyValue[1])}break;case"visible":{const i=t.items.find(t=>t.id===e.itemId);if(i&&(i.visible=e.propertyValue,ci.config.pageConfig.groupVisible)){this.getChildrenSceneItemIds(e.itemId,t).forEach(i=>{const s=t.items.find(t=>t.id===i);s&&(s.visible=e.propertyValue)})}break}}}transformSceneItem(t,e,i){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach(s=>{if(!this.sdk.pageData?.property.asyncMode&&s.id!==this.sdk.pageData?.activeData.view)return;const{scene:r}=s;switch(e){case"position":if(Array.isArray(i)&&3===i.length){const e=r.items.find(e=>e.id===t);e?.transform&&(e.transform.position.x+=i[0],e.transform.position.y+=i[1],e.transform.position.z+=i[2])}break;case"rotation":if(Array.isArray(i)&&3===i.length){const e=r.items.find(e=>e.id===t);e?.transform&&(e.transform.eulerHint.x+=i[0],e.transform.eulerHint.y+=i[1],e.transform.eulerHint.z+=i[2])}break;case"scale":if(Array.isArray(i)&&3===i.length){const e=r.items.find(e=>e.id===t);e?.transform&&(e.transform.scale.x*=i[0],e.transform.scale.y*=i[1],e.transform.scale.z*=i[2])}}})}refreshViewItem(t){const e=this.sdk.pageData;v(e,"You must call SDK#run() first");const i=e.items.findIndex(e=>e.id===t);if(i<0)return void console.warn(`item ${t} is not existed.`);const s=e.items[i],r=this.getPlayerItemById(t);r&&s&&(e.items[i]=this.createViewItemByPlayerItem(r,s.parentId))}getPlayerItemById(t){return this.player.getCompositions()[0]?.items.find(e=>e.getInstanceId()===t)}getPixelSizeByWorldSize(t,e){v(this.sdk.pageData,"You must call SDK#run() first");const i=[0,0],s=e.composition?.camera,r=this.getViewProperty()?.size;if(s&&r){const{z:a}=e.transform.getWorldPosition(),{x:n,y:o}=s.getInverseVPRatio(a);i[0]=Math.abs(t[0]*r[0]/n/2),i[1]=Math.abs(t[1]*r[1]/o/-2)}else console.warn("camera is not existed.");return i}getActiveTargetScene(){const t=this.getViewProperty()?.scene;if(t)return t;console.warn("Target scene is not exsited.")}refreshSceneAndPageData(){v(this.sdk.pageData,"You must call SDK#run() first");const t=this.player.getCompositions()[0];this.refreshItemRenderOrder(t),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,t.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}async addSpriteItem(t){const e=this.getActiveTargetScene();if(!e)return;const{scale:i}=this.interactionUtils.viewportParam,{name:s="图层",size:r,scale:a=[1,1],url:n,rotation:o=0,position:c,parentId:h,id:l=b()}=t,p=this.interactionUtils.getWorldSizeByViewSize(new F(...r).multiply(i)),m=new N(...a??[1,1],1),d=new N(0,0,o),u=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new F(...c)))??new N,f=e.images.findIndex(t=>t.url===n);let y,x={};if(n)if(f<0){y=await C.fromImage(n,this.player.renderer.engine);const t={id:b(),url:n,renderLevel:g.RenderLevel.BPlus};x={id:y.guid,source:{id:t.id},flipY:!0,dataType:g.DataType.Texture},e.images.push(t),e.textures??(e.textures=[]),e.textures.push(x)}else{const t=e.textures?.find(t=>t.source.id===e.images[f].id);x={id:t?.id},y=this.player.renderer.engine.findObject({id:t.id})}const w=te(l,u,d,new F(Math.abs(p.x),Math.abs(p.y)),m,s,x?.id);e.items.find(t=>t.id===h)&&(w.item.parentId=h),ie(e,w);const v=this.player.getCompositions()[0],P=le.createSprite(v,null,s);if(P.setInstanceId(w.item.id),P.duration=999,P.defination.delay=0,P.endBehavior=g.EndBehavior.restart,P.transform.setSize(Math.abs(p.x),Math.abs(p.y)),P.transform.setPosition(...u.toArray()),P.transform.setRotation(...d.toArray()),P.transform.setScale(...m.toArray()),y){P.getComponent(I).setTexture(y)}return this.refreshSceneAndPageData(),w.item.id}addNullItem(t){const e=this.getActiveTargetScene();if(!e)return;const{name:i="空节点",position:s=[0,0],id:r=b(),children:a=[]}=t,n=a.filter(t=>!this.getPlayerItemById(t)),o=a.filter(t=>!!this.getPlayerItemById(t));if(n.length&&console.warn(`item ${n.join("、")} is not existed.`),0===o.length)return;this.interactionUtils.initInteractionPlane();const c=this.interactionUtils.getWorldSizeByViewSize(new F(...s))??new N,h=function(t,e,i){const s=JSON.parse(JSON.stringify(i)),r={id:t,name:e,duration:999,type:g.ItemType.null,visible:!0,endBehavior:g.EndBehavior.restart,delay:0,renderLevel:g.RenderLevel.BPlus,content:{options:{startColor:[1,1,1,1]}},components:[],transform:{position:s,eulerHint:{x:0,y:0,z:0},size:{x:1,y:1},scale:{x:1,y:1,z:1}},dataType:g.DataType.VFXItemData},a={id:b(),dataType:g.DataType.ActivationPlayableAsset};return{item:r,components:[],tracks:[{id:b(),dataType:g.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:a.id}}]}],playableAssets:[a]}}(r,i,c);ie(e,h),o.forEach(t=>{se(e,t,r)});const l=this.player.getCompositions()[0],p=le.createEmpty(l,null,i);return p.setInstanceId(h.item.id),p.duration=999,p.defination.delay=0,p.endBehavior=g.EndBehavior.restart,p.transform.setPosition(...c.toArray()),o.forEach(t=>{const e=this.getPlayerItemById(t);e.setParent(p),e.parentId=h.item.id,e.translate(...c.clone().negate().toArray())}),this.refreshSceneAndPageData(),h.item.id}async addTextItem(t){const e=this.getActiveTargetScene();if(!e)return;const{id:i=b(),parentId:s,name:r="文本",lineHeight:a,textWidth:n,fontFamily:o,position:c=[0,0],fontSize:h,fontWeight:l=g.TextWeight.normal,fontStyle:p=g.FontStyle.normal,textAlign:m=g.TextAlignment.left,text:d,textColor:u,textHeight:f=a,outlineColor:y=[.8,.8,.8,1],outlineWidth:x=0,rotation:w=0,url:I}=t;I&&!e.fonts?.find(t=>t.fontFamily===o)&&(e.fonts??(e.fonts=[]),e.fonts.push({fontFamily:o,fontURL:I}));const C={text:d,fontFamily:o,fontSize:h,textColor:u,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:n,textHeight:f,lineHeight:a,textBaseline:g.TextBaseline.top,textOverflow:g.TextOverflow.visible,outline:{outlineColor:y,outlineWidth:x}},D=this.player.getCompositions()[0],z=le.createText(D,null,r);z.setInstanceId(i),z.duration=999,z.defination.delay=0,z.endBehavior=g.EndBehavior.restart;const S=z.getComponent(P),A={options:C,renderer:{renderMode:1},dataType:g.DataType.TextComponent,item:{id:z.getInstanceId()},id:S.getInstanceId()};S.fromData(A),A.options.textHeight=Math.ceil(a*S.lineCount),S.fromData(A),await me.loadFontFamily([{fontURL:I,fontFamily:o}]),S.setFontFamily(o);const T=new F(n,C.textHeight).multiply(this.interactionUtils.viewportParam.scale),k=this.interactionUtils.getWorldSizeByViewSize(T),_=new N(0,0,w),E=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new F(...c)))??new N,B=ee(i,r,E,_,new F(Math.abs(k.x),Math.abs(k.y)),C);e.items.find(t=>t.id===s)&&(B.item.parentId=s),ie(e,B),z.transform.setSize(Math.abs(k.x),Math.abs(k.y)),z.transform.setPosition(...E.toArray()),z.transform.setRotation(..._.toArray()),v(this.sdk.pageData,"You must call SDK#run() first"),this.player.gotoAndStop(this.sdk.pageData.time),this.refreshSceneAndPageData()}deleteItem(t){const e=this.getActiveTargetScene();if(!e)return;!function(t,e){const i=t.items.find(t=>t.id===e);if(!i)return void console.warn(`item ${e} is not exsited.`);t.items=t.items.filter(t=>t.id!==e),t.items.forEach(t=>{t.parentId===e&&(t.transform??(t.transform={position:{x:0,y:0,z:0},eulerHint:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},size:{x:1,y:1}}),t.transform.position.x+=i.transform.position.x,t.transform.position.y+=i.transform.position.y,t.transform.position.z+=i.transform.position.z,t.transform.eulerHint.x+=i.transform.eulerHint.x,t.transform.eulerHint.y+=i.transform.eulerHint.y,t.transform.eulerHint.z+=i.transform.eulerHint.z,t.transform.scale.x*=0!==i.transform.scale.x?i.transform.scale.x:1,t.transform.scale.y*=0!==i.transform.scale.y?i.transform.scale.y:1,t.transform.scale.z*=0!==i.transform.scale.z?i.transform.scale.z:1),delete t.parentId});const s=t.components.filter(t=>t.item.id===e);t.components=t.components.filter(t=>!s.map(t=>t.id).includes(t.id)),s.forEach(e=>{if(e.dataType===g.DataType.SpriteComponent&&e.renderer.texture&&!t.components.find(t=>t.renderer?.texture?.id===e.renderer.texture.id)){const i=t.textures?.find(t=>t.id===e.renderer.texture?.id);i&&(t.textures=t.textures?.filter(t=>t.id!==i.id),t.images=t.images.filter(t=>t.id!==i.source.id))}});const r=[];let a,n;const o=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(+t.version>=3.3){const i=t.components.find(t=>t.id===o.components[0].id);i.items=i.items.filter(t=>t.id!==e),n=i.timelineAsset.id,a=i.sceneBindings.find(t=>t.value.id===e)?.key.id,i.sceneBindings=i.sceneBindings.filter(t=>t.value.id!==e),a&&r.push(a)}else o.items=o.items.filter(t=>t.id!==e),n=o.timelineAsset.id,a=o.sceneBindings.find(t=>t.value.id===e)?.key.id,o.sceneBindings=o.sceneBindings.filter(t=>t.value.id!==e),a&&r.push(a);const c=t.miscs.findIndex(t=>t.id===n);c>=0&&(t.miscs[c].tracks=t.miscs[c].tracks.filter(t=>t.id!==a));const h=t.miscs.find(t=>t.id===a);h&&(h.children.forEach(e=>{r.push(e.id);const i=t.miscs.find(t=>t.id===e.id);i&&r.push(...i.clips.map(t=>t.asset.id))}),r.push(...h.children.map(t=>t.id))),t.miscs=t.miscs.filter(t=>!r.includes(t.id))}(e,t);const i=this.player.getCompositions()[0].items.find(e=>e.getInstanceId()===t);if(i){const t=i.getWorldTransform(),e=t.getWorldPosition(),s=t.getRotation(),r=t.getWorldScale();i.children.forEach(t=>{t.scale(...r.toArray()),t.rotate(...s.toArray()),t.translate(...e.toArray()),t.parent=void 0,t.parentId=void 0}),i.dispose()}}getCanvasUndoRedo(){return this.sdk.canvasUndoRedo}getItemCreateInfo(t,e=!1){v(this.sdk.pageData,"You must call SDK#run() first");const i=this.getPlayerItemById(t),s=this.getViewProperty()?.scene;if(!i||!s)return void console.warn(`item ${t} is not exsited.`);const{transform:r}=i,a=(new N).copyFrom(r.getWorldPosition()),n=r.getRotation(),o=r.getWorldScale();if(e&&i.parent){const t=i.parent.transform;a.subtract(t.getWorldPosition()),o.divide(t.getWorldScale())}this.interactionUtils.initInteractionPlane(a);const c=this.interactionUtils.projectPoint(a);switch(i.type){case g.ItemType.sprite:{const{size:a}=r,h=this.interactionUtils.projectPoint(new N),l=this.interactionUtils.projectPoint(new N(a.x,a.y,0)),p=[Math.abs(l.x-h.x),Math.abs(l.y-h.y)];return{type:"sprite",name:i.name,parentId:e?i.parent?.getInstanceId():void 0,id:i.getInstanceId(),url:re(s,t),size:p,scale:[o.x,o.y],rotation:n.z,position:[c.x,c.y]}}case g.ItemType.null:{const t=i.children.map(t=>t.getInstanceId());return{type:"null",parentId:e?i.parent?.getInstanceId():void 0,children:t,name:i.name,scale:[o.x,o.y],rotation:n.z,position:[c.x,c.y]}}case g.ItemType.text:{const r=s.components.find(e=>e.item.id===t),a=s.fonts?.find(t=>t.fontFamily===r.options.fontFamily)?.fontURL;return{type:"text",id:t,parentId:e?i.parent?.getInstanceId():void 0,name:i.name,lineHeight:r.options.lineHeight,textWidth:r.options.textWidth,fontFamily:r.options.fontFamily,position:[c.x,c.y],rotation:n.z,textHeight:r.options.textHeight,fontSize:r.options.fontSize,fontWeight:r.options.fontWeight,fontStyle:r.options.fontStyle,textAlign:r.options.fontStyle,text:r.options.text,textColor:r.options.textColor,outlineColor:r.options.outline?.outlineColor,url:a}}}}getChildrenIds(t){return this.getPageData()?.items.filter(e=>e.parentId===t)?.map(t=>t.id)??[]}createScreenShotSceneByIds(t){const e=new W;let i;const s=(t,e,s)=>{const{id:r=b(),url:a,name:n="图层",scale:o=[1,1]}=t,c=new F(e.x/o[0],e.y/o[1]),h=i.images.findIndex(t=>t.url===a);let l={};if(a)if(h<0){const t={id:b(),url:a,renderLevel:g.RenderLevel.BPlus};l={id:b(),source:{id:t.id},flipY:!0,dataType:g.DataType.Texture},i.images.push(t),i.textures??(i.textures=[]),i.textures.push(l)}else{const t=i.textures?.find(t=>t.source.id===i.images[h].id);l={id:t?.id}}const p=te(r,new N(s.x,s.y,0),new N(0,0,t.rotation??0),c,new N(t.scale?.[0]??1,t.scale?.[1]??1,1),n,l.id);ie(i,p)},r=(t,e,s)=>{const{id:r=b(),name:a="文本",lineHeight:n,textWidth:o,fontFamily:c,fontSize:h,fontWeight:l=g.TextWeight.normal,fontStyle:p=g.FontStyle.normal,textAlign:m=g.TextAlignment.left,text:d,textColor:u,rotation:f=0,url:y,textHeight:x}=t;y&&!i.fonts?.find(t=>t.fontFamily===c)&&(i.fonts??(i.fonts=[]),i.fonts.push({fontFamily:c,fontURL:y}));const w={text:d,fontFamily:c,fontSize:h,textColor:u,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:o,textHeight:x??n,lineHeight:n},v=ee(r,a,new N(...s.toArray(),0),new N(0,0,f),new F(e.x,e.y),w);ie(i,v)};if(Array.isArray(t)){t.map(t=>this.getViewBoxById(t)).map(t=>e.union(t));const a=e.getSize();i=Qt(a.toArray());const n=(new O).compose(new N(0,0,8),new H,new N(1,1,1)).invert(),o=(new O).perspective(60*_,a.x/a.y,.1,40,!0),c=(new O).multiplyMatrices(o,n),h=c.clone().invert(),l=c.projectPoint(new N).z,p=new N(0,0,l).applyMatrix(h),m=new N(2,2,l).applyMatrix(h),d=Math.abs(m.x-p.x)/a.x,g=Math.abs(m.y-p.y)/a.y;t.forEach(t=>{const i=this.getItemCreateInfo(t,!1);if(!i||"null"===i.type)return;const a=this.getViewBoxById(t),n=a.getSize().multiply(new F(d,g)).abs(),o=a.getCenter().subtract(e.getCenter()).multiply(new F(d,-g));switch(i.type){case"sprite":s(i,n,o);break;case"text":r(i,n,o)}})}else{const a=this.getViewBoxById(t),n=this.getItemCreateInfo(t,!1);e.copyFrom(a);const o=e.getSize();i=Qt(o.toArray());const c=(new O).compose(new N(0,0,8),new H,new N(1,1,1)).invert(),h=(new O).perspective(60*_,o.x/o.y,.1,40,!0),l=(new O).multiplyMatrices(h,c),p=l.clone().invert(),m=l.projectPoint(new N).z,d=new N(0,0,m).applyMatrix(p),g=new N(2,2,m).applyMatrix(p),u=(new N).subtractVectors(g,d);if(n)switch(n.type){case"sprite":s(n,new F(u.x,u.y),new F);break;case"text":r(n,new F(u.x,u.y),new F)}}return i}updateItemOrder(t,e){v(this.sdk.pageData,"You must call SDK#run() first");const i=this.getCurrentComposition();if(!i)return void console.warn("Composition not found.");const s=i.items.find(e=>e.getInstanceId()===t);if(!s)return void console.warn(`Item with id ${t} not found.`);const r=s.parent,a=r.children.filter(t=>!this.isPluginItem(t)),n=r.children.filter(t=>this.isPluginItem(t)),o=a.findIndex(e=>e.getInstanceId()===t);if(-1===o)return void console.warn(`Item with id ${t} not found in siblings.`);let c=o;switch(e){case 0:c=a.length-1;break;case 1:c=0;break;case 2:c=Math.min(o+1,a.length-1);break;case 3:c=Math.max(o-1,0)}if(c===o)return;const[h]=a.splice(o,1);h&&a.splice(c,0,h),r.children=[...n,...a],this.refreshItemRenderOrder(i),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,i.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}isPluginItem(t){return"ModelPluginItem"===t.name}refreshItemRenderOrder(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=(()=>{const e=[],i=t=>{for(const s of t)this.isPluginItem(s)||(e.push(s),s.children.length>0&&i(s.children))},s=[...t.rootItem.children];return i(s),e})();t.items.length=0,t.items.push(...e);for(let e=0;e<t.items.length;e++){const i=t.items[e];i.renderOrder=e,i.setActive(!1),i.setActive(!0)}const i=this.getViewProperty();if(i){const{scene:e}=i,s=e.compositions.find(t=>t.id===e.compositionId)??e.compositions[0];if(s){const i=s.components.map(t=>e.components.find(e=>e.id===t.id)).find(t=>t?.dataType===g.DataType.CompositionComponent);i&&(i.items=t.items.map(t=>({id:t.getInstanceId()})))}}}getViewProperty(t){return v(this.sdk.pageData,"You must call SDK#run() first"),t??(t=this.sdk.pageData.activeData.view),this.sdk.pageData.viewProperties.find(e=>e.id===t)}viewportFit(){v(this.sdk.pageData,"You must call SDK#run() first");const t=new W;this.sdk.pageData.items.forEach(e=>{const i=this.getViewBoxById(e.id);t.union(i)});const{width:e,height:i,scale:s,translation:r}=this.interactionUtils.viewportParam;if(t.isEmpty())this.pageMove(r.clone().negate()),this.pageZoom(-s,void 0,!0);else{const r=t.getCenter(),a=t.getSize(),n=a.x/e*i>a.y?1/(a.x/e):1/(a.y/i),o=(new F).subtractVectors(new F(e/2,i/2),r);this.pageMove(o),this.pageZoom(n*s-s,void 0,!0)}}};import ge from"jszip";import ue from"jszip";var fe,ye,xe,we,ve,Ie,Pe,Ce,be,De,ze,Se,Ae,Te,ke,_e,Ee,Be,Me,Ve="ready",Ge="executable",Ue="dispose",Fe={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},Re="idle",We="convertImage",Le="transcoding",He="audio",Ne="jpeg",Oe="webp",Ke="png",je=(Fe.MP4,Fe.WebP,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo,Fe.Images,Fe.MP4,Fe.WebP,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo,Fe.Images,"default"),Ye="exporting",$e="success",Je="error",Xe={highest:"flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=256[p];[s1][p]paletteuse",high:"flags=bicubic,split[s0][s1];[s0]palettegen=max_colors=200[p];[s1][p]paletteuse",medium:"flags=bilinear,split[s0][s1];[s0]palettegen=max_colors=64[p];[s1][p]paletteuse=dither=bayer",low:"flags=neighbor,split[s0][s1];[s0]palettegen=max_colors=32[p];[s1][p]paletteuse=dither=none"},Ze={highest:"1",high:"3",medium:"6",low:"9"},qe=class{constructor(t){c(this,"sampleRate"),c(this,"duration"),c(this,"channels");const{sampleRate:e=44100,duration:i=1,channels:s=2}=t??{};this.sampleRate=e,this.duration=i,this.channels=s}getBuffer(){const t=this.sampleRate*this.duration*this.channels*2,e=44+t,i=new ArrayBuffer(e),s=new DataView(i);let r=0;const a=t=>{for(let e=0;e<t.length;e++)s.setUint8(r++,t.charCodeAt(e))},n=t=>{s.setUint32(r,t,!0),r+=4},o=t=>{s.setUint16(r,t,!0),r+=2};a("RIFF"),n(e-8),a("WAVE"),a("fmt "),n(16),o(1),o(this.channels),n(this.sampleRate),n(this.sampleRate*this.channels*2),o(2*this.channels),o(16),a("data"),n(t);for(let e=0;e<t;e++)s.setUint8(r++,0);return new Uint8Array(i)}},Qe=["@vvfx/sdk","exporter"],ti=class extends w{constructor(t){super(),c(this,"status",Ve),c(this,"stage",Re),c(this,"mediaType"),c(this,"loggerInTranscoding"),c(this,"multiThreading"),c(this,"extraCanvas"),c(this,"player"),p(this,fe,0),p(this,ye),p(this,xe),p(this,we),p(this,ve),p(this,Ie,[]),p(this,Pe),p(this,Ce),p(this,be,[]),p(this,De,0),p(this,ze),p(this,Se,[]),p(this,Ae,0),p(this,Te,0),p(this,ke,0),p(this,_e,0),p(this,Ee,[]),p(this,Be,[]),p(this,Me,!0);const{mediaType:e,extraCanvas:i,loggerInTranscoding:s,multiThreading:r}=t;this.mediaType=e,this.loggerInTranscoding=s??!1,this.multiThreading=r??!1,this.extraCanvas=i??void 0,this.onInit()}get canceled(){return this.status===Ue}get config(){const t=this.player?.getCompositions()??[],e=t?.[0],i=e?.name??(new Date).getTime().toString(),s=e?.getDuration()??0,r=e?.startTime??0,a=l(this,ze)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:l(this,ze)?.fps??30,backgroundColor:l(this,ze)?.backgroundColor??"#000000",loop:l(this,ze)?.loop??!0,audioEnable:l(this,ze)?.audioEnable??!1}}get gifConfig(){return l(this,ze)?.gifConfig}get apngConfig(){return l(this,ze)?.apngConfig}get progress(){const t=l(this,Te)||1,e=l(this,ke)||1,i=Math.min(t/e,1),s=Math.min(l(this,Ae),t)/t*.4,r=Math.min(l(this,_e),t)/t*.6,a=Math.min(s+r,1);l(this,Se)[l(this,De)]=i;const n=l(this,Se).reduce((t,e,i)=>i<l(this,De)?t+(e||0):t,0)+a*i;return Math.min((o=n,Math.round(100*o)/100),1);var o}get transImageType(){return this.mediaType===Fe.MP4?Ne:this.mediaType===Fe.WebP?Oe:Ke}async onInit(){try{Et("log",[...Qe,"ready"],"starting"),this.status=Ve,await this.loadHelper(this.mediaType),this.status=Ge,Et("log",[...Qe,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=Ue,this.onError(t)}finally{return this.status}}onReset(){this.stage=Re,window.cancelAnimationFrame(l(this,fe)),m(this,fe,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){Et("log",[...Qe,"error"],t),this.onFinish(!1,l(this,Ee),l(this,Be)),this.emit("error",t),this.dispose()}onFinish(t,e,i){Et("log",[...Qe,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("finish",t,e,i)}async loadHelper(t){const e="WebP"===t&&!l(this,we),i=[Fe.MP4,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo].includes(t)&&!l(this,xe);e&&m(this,we,await Zt()),i&&(m(this,xe,await async function(t){const{multiThreading:e}=t??{},i=new jt,s=!!e,r={classWorkerURL:await Yt(Jt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await Yt(Jt.MT.CORE,"text/javascript"),r.wasmURL=await Yt(Jt.MT.WASM,"application/wasm"),r.workerURL=await Yt(Jt.MT.WORKER,"text/javascript")):(r.coreURL=await Yt(Jt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await Yt(Jt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),l(this,xe).on("log",({message:t})=>{if(this.loggerInTranscoding&&Et("log",[...Qe,"transcoding log"],t),this.canceled||this.stage!==Le)return;const e=/frame=\s*(\d+)/.exec(t);if(e?.[1]){const t=Number(e[1]);this.setProgress({currentTaskInTranscodingFrameIndex:t})}}))}getAllTaskFrames(t){return t.reduce((t,e)=>{const{scene:i,fps:s}=e,r=i.compositions?.[0]?.duration??0;return t+Math.round(r*(s??30))},0)}setProgress(t){void 0!==t?.completedTaskPercentArray&&m(this,Se,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&m(this,Ae,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&m(this,Te,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&m(this,_e,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&m(this,ke,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){v(this.player);const{oldTotalTime:i,startTime:s}=this.config;v(i);const r=1e3*i-1e3*i%15;return t=Math.min(t,r/1e3),e?this.player.gotoAndPlay(t-s):this.player.gotoAndStop(t-s),t}getWavAudio(t){m(this,Pe,new qe),l(this,xe)?l(this,xe).writeFile(t,l(this,Pe).getBuffer()):Et("log",[...Qe,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new ue,s=i.folder(t);return v(s),l(this,be).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){v(l(this,we));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${l(this,be).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=l(this,we).cwrap("main","string",["number","number"]),[r,a]=function(t,e){const i=t._malloc(e.length*Uint32Array.BYTES_PER_ELEMENT);return e.forEach((e,s)=>{const r=t._malloc(e.length+1);t.writeAsciiToMemory(e,r),t.setValue(i+Uint32Array.BYTES_PER_ELEMENT*s,r,"i32")}),[e.length,i]}(l(this,we),i);_t(r&&a,"getWebP has error"),s(r,a);const n=l(this,we).FS.readFile(e);return l(this,be).forEach(t=>{l(this,we)?.FS.unlink(t)}),n}async getAPNG(){v(l(this,xe));this.stage=Le;const t="export.apng",{fps:e,scale:i="-1:-1",quality:s="highest"}=this.apngConfig??{},r=[`scale=${i}:force_original_aspect_ratio=decrease:flags=lanczos`];e&&r.push(`fps=${e}`);if(0!==await l(this,xe).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-vf",r.join(","),"-plays",this.config.loop?"0":"1","-compression_level",Ze[s],"-y",t]))throw new Error("the command executed by ffmpeg to generate a apng failed.");return t}async getGIF(){v(l(this,xe));this.stage=Le;const t="export.gif",{fps:e,scale:i="-1:-1",quality:s="highest"}=this.gifConfig??{},r=[`scale=${i}:${Xe[s]}`];e&&r.unshift(`fps=${e}`);if(0!==await l(this,xe).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-loop",this.config.loop?"0":"-1","-vf",r.join(","),"-y",t]))throw new Error("the command executed by ffmpeg to generate a gif failed.");return t}async getMP4(t,e){v(l(this,xe));this.stage=Le;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;this.config.audioEnable&&!l(this,Pe)&&(m(this,Ce,"audio.wav"),this.getWavAudio(l(this,Ce)));if(0!==await l(this,xe).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${r}`,"-y",i]))throw new Error("the command executed by ffmpeg to generate a mp4 failed.");if(l(this,Ce)&&l(this,Pe)){this.stage=He,s="export-with-audio.mp4";if(0!==await l(this,xe).exec(["-i",i,"-i",l(this,Ce),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s]))throw new Error("the command executed by ffmpeg to generate a audio of video failed.")}return s&&l(this,xe).deleteFile(i).catch(()=>{Et("log",[...Qe,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){v(l(this,xe));this.stage=Le;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await l(this,xe).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${s}`,"-y",i]),i}async getVideoByType(t,e){v(l(this,xe));const i=this.mediaType===Fe.APNG,s=this.mediaType===Fe.GIF,r=this.mediaType===Fe.AlphaMaskVideo,a=this.mediaType===Fe.MP4;let n="";try{i&&(n=await this.getAPNG()),s&&(n=await this.getGIF()),a&&(n=await this.getMP4(t,e)),r&&(n=await this.getAlphaMaskVideo(t,e)),this.stage=Re}catch(t){throw t}finally{for(const t of l(this,be))t&&l(this,xe).deleteFile(t)}let o=null;try{v(n);const t=await l(this,xe).readFile(n);o="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{l(this,xe).deleteFile(n).catch(()=>{Et("log",[...Qe,"ffmpeg delete file error"])})}return o}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});m(this,ve,e),l(this,ve).start(0);const i=[];l(this,ve).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},m(this,Ie,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o}=t;v(this.player),v(l(this,ye));const c=l(this,Ae)+1;this.stage=We,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&&Et("log",[...Qe,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),Xt(l(this,ye),s,this.config.backgroundColor);let h=s;this.mediaType===Fe.AlphaMaskVideo&&(v(this.extraCanvas),function(t,e){e.width=2*t.width,e.height=t.height;const i=t.getContext("2d");if(!i)throw new Error("inputCtx is null");const s=e.getContext("2d");if(!s)throw new Error("ctx is null");s.clearRect(0,0,e.width,e.height);const r=i.getImageData(0,0,t.width,t.height),a=i.getImageData(0,0,t.width,t.height),n=r.data;for(let t=0;t<n.length;t+=4){const e=Math.max(0,(n[t+3]??0)-5)/250*255;e<=0?(n[t]=0,n[t+1]=0,n[t+2]=0,n[t+3]=255):(n[t]=(n[t]??0)*e/255,n[t+1]=(n[t+1]??0)*e/255,n[t+2]=(n[t+2]??0)*e/255,n[t+3]=255)}s.putImageData(r,0,0);const o=a.data;for(let t=0;t<o.length;t+=4){const e=Math.max(0,(o[t+3]??0)-5)/250*255;o[t]=e,o[t+1]=e,o[t+2]=e,o[t+3]=255}s.putImageData(a,t.width,0)}(s,this.extraCanvas),h=this.extraCanvas);const p=await async function(t,e,i){return new Promise((s,r)=>{t.toBlob(t=>{t?s(t.arrayBuffer()):r("toBlob failed")},e,i)})}(h,`image/${this.transImageType}`,1),d=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===Fe.Images?r.push(p):this.mediaType===Fe.WebP?(v(l(this,we)),l(this,we).FS.writeFile(d,new Uint8Array(p))):(v(l(this,xe)),await l(this,xe).writeFile(d,new Uint8Array(p))),l(this,be).push(d);if(c===l(this,Te)){this.player?.pause(),await new Promise(t=>{window.requestAnimationFrame(t)});let t=null;"Images"===this.mediaType?t=await this.getImagesZip(this.config.name,r):"WebP"===this.mediaType?t=this.getWebP():[Fe.MP4,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(n,o)??null),t&&(Et("log",[...Qe,"done"],"success"),this.emit("done",l(this,ze),!0,t))}else m(this,fe,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o})}))}catch(t){Et("log",[...Qe,"onExportImageFrame","failed"],t),this.emit("done",l(this,ze),!1)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;v(this.player),v(l(this,ye));const e=l(this,Ae)+1;if(this.stage=We,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&Et("log",[...Qe,"converting log"],`converting ${e} frame image`),Xt(l(this,ye),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<l(this,Te))m(this,fe,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),l(this,ve)?.stop();const t=new Blob(l(this,Ie),{type:"video/webm"}),e=await t.arrayBuffer();Et("log",[...Qe,"done"],"success"),this.emit("done",l(this,ze),!0,e)}}catch(t){Et("log",[...Qe,"done"],"failed",t),this.emit("done",l(this,ze),!1)}}async runTask(t){try{if(this.canceled)return;v(this.player),v(l(this,ye));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[n,o]=e;if(l(this,ye).width=n,l(this,ye).height=o,s.width=n,s.height=o,this.player.resize(),m(this,be,[]),[Fe.MP4,Fe.APNG,Fe.Images,Fe.WebP,Fe.GIF,Fe.AlphaMaskVideo].includes(this.mediaType)){const t={canvas:s,imageBuffers:[],startTime:i,oldTotalTime:r,newTotalTime:a};await this.onExportImageFrame(t)}else"WebM"===this.mediaType&&await this.onExportWebMFrame(s)}catch(t){Et("log",[...Qe,"run task error"],t),this.emit("done",l(this,ze),!1)}}clearTaskInfo(){m(this,De,0),m(this,ze,void 0),m(this,Se,[]),m(this,Ae,0),m(this,Te,0),m(this,ke,0),m(this,_e,0),m(this,Ee,[]),m(this,Be,[]),m(this,Me,!0)}clearFFMpegCore(){if(l(this,xe)){for(const t of l(this,be))t&&l(this,xe).deleteFile(t);m(this,be,[]),l(this,xe).terminate(),m(this,xe,void 0)}}clearImage2WebPCore(){l(this,we)&&(l(this,we).FS.quit(),m(this,we,void 0))}clearMediaRecorder(){l(this,ve)&&(l(this,ve).stop(),m(this,ve,void 0)),m(this,Ie,[])}clearAllListeners(){for(const t of this.getListeners("ready"))this.off("ready",t);for(const t of this.getListeners("progress"))this.off("progress",t);for(const t of this.getListeners("done"))this.off("done",t);for(const t of this.getListeners("finish"))this.off("finish",t);for(const t of this.getListeners("error"))this.off("error",t)}onCancel(){this.canceled||(this.onFinish(!1,l(this,Ee),l(this,Be)),this.status=Ue,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),Et("log",Qe,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===Ve)return Et("log",[...Qe],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===Ue){if(await this.onInit()===Ue)throw new Error("init environment failed")}if(this.clearTaskInfo(),!l(this,ye)){const t=document.createElement("canvas");t.dataset.key="player-canvas",m(this,ye,t)}this.player||(this.player=new f({canvas:l(this,ye),pixelRatio:1,transparentBackground:!0,renderOptions:{willCaptureImage:!0}}),this.player.on("rendererror",t=>{this.onError(t)}),this.player.on("webglcontextlost",t=>{this.onError(t)}));let e=null;e??(e=document.querySelector('canvas[data-key="container-canvas"]')),e??(e=document.createElement("canvas")),e.dataset.key="container-canvas",e.style.display="none",this.setProgress({allTaskFrames:this.getAllTaskFrames(t)});const i=[],s=[];let r=!0;for(const[a,n]of t.entries()){if(this.canceled){r=!1;break}m(this,De,a),m(this,ze,n);const{size:t,scene:o}=n;await new Promise(async c=>{try{if(!this.player)throw new Error("player not found");Et("log",[...Qe,"export"],"start",n),qt(this.player),await this.player.loadScene(o,{env:"editor",autoplay:!1});const h=this.config.oldTotalTime,l=0;this.player.pause(),this.setProgress({currentTaskFrameIndex:0,currentTaskTotalFrames:Math.round(h*this.config.fps)});const p=(t,e,o)=>{this.off("done",p),i[a]=n,e&&o?s[a]=o:r=!1,c()};this.on("done",p);const m={size:t,startTime:l,containerCanvas:e};await this.runTask(m)}catch(t){Et("log",[...Qe,"export error"],t),r=!1,c()}})}m(this,Ee,i),m(this,Be,s),m(this,Me,r)}catch(t){this.onError(t),m(this,Me,!1)}e>=1&&l(this,Me)?this.onFinish(!0,l(this,Ee),l(this,Be)):this.onFinish(!1,l(this,Ee),l(this,Be))}dispose(){this.status=Ue,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,l(this,ye)?.remove(),m(this,ye,void 0),m(this,Ce,void 0),m(this,Pe,void 0)}};fe=new WeakMap,ye=new WeakMap,xe=new WeakMap,we=new WeakMap,ve=new WeakMap,Ie=new WeakMap,Pe=new WeakMap,Ce=new WeakMap,be=new WeakMap,De=new WeakMap,ze=new WeakMap,Se=new WeakMap,Ae=new WeakMap,Te=new WeakMap,ke=new WeakMap,_e=new WeakMap,Ee=new WeakMap,Be=new WeakMap,Me=new WeakMap;var ei={[Fe.MP4]:{suffix:"mp4",error:"export mp4 is error"},[Fe.GIF]:{suffix:"gif",error:"export gif is error"},[Fe.Images]:{suffix:"zip",error:"export Images is error"},[Fe.APNG]:{suffix:"apng",error:"export APNG is error"},[Fe.WebP]:{suffix:"webp",error:"export WebP is error"},[Fe.AlphaMaskVideo]:{suffix:"mp4",error:"export AlphaMaskVideo is error"},[Fe.WebM]:{suffix:"webm",error:"export WebM is error"}},ii=class extends w{constructor(t){super(),c(this,"_config"),c(this,"_status",je),c(this,"_exportMedia"),this._config=t,this._exportMedia=new ti(t)}get status(){return this._status}onExportMedia(t,e,i,s){if(!e.length||!i)return void Et("info",["@vvfx/sdk","export media is error","result or suffix is empty"]);const r=t[0]?.folderName,a=new ge;e.forEach((e,s)=>{if(!e)return;const{name:r}=t[s]??{};r&&a.file(`${r}.${i}`,e)}),a.generateAsync({type:"blob"}).then(t=>{!function(t,e,i="application/octet-stream"){const s=new Blob(Array.isArray(t)?t:[t],{type:i}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}(t,`${r}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],s??"export media is error",t)})}onExportProgress(t){this.emit("progress",t)}onExportDone(t,e,i){this.emit("done",t,e,i)}onExportError(t){this._status=Je,Et("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=Ye,this._exportMedia.onExport(t),this._exportMedia.on("progress",this.onExportProgress.bind(this)),this._exportMedia.on("done",this.onExportDone.bind(this)),this._exportMedia.once("finish",(e,i,s)=>{if(this._status=e?$e:Je,this.emit("complete",e,i,s),this._config.isOutputBuffer||!s||0===s.length)return;const{suffix:r,error:a}=ei[this._config.mediaType];r&&this.onExportMedia(t,s,r,a)}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=Je,this._exportMedia.onCancel(),this.emit("complete",!1,[],[])}dispose(){this._exportMedia.dispose()}},si=class{constructor(){c(this,"enabled",!0),c(this,"_player"),c(this,"_container"),this._container=document.createElement("canvas"),this._player=new f({canvas:this._container,manualRender:!0,renderOptions:{willCaptureImage:!0}})}async generate(t,e,i,s,r){if(!this.enabled)return void console.warn("Screen shot is not opened, use #SDK.setConfig() open this feature.");qt(this._player);const[a,n]=e;this._container.width=a,this._container.height=n,this._player.resize();const o=JSON.parse(JSON.stringify(t));await this._player.loadScene(o,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(s);const[c,h]=i,l=document.createElement("canvas");l.width=c,l.height=h;const p=l.getContext("2d");r??(r=[255,255,255,1]),p&&(p.fillStyle=`rgba(${r.join(",")})`,p.fillRect(0,0,c,h),this.drawImageCover(p,this._player.canvas,0,0,c,h,.5,.5));const m=l.toDataURL("image/png");return qt(this._player),m}dispose(){this._player.dispose()}drawImageCover(t,e,i,s,r,a,n,o,c){2===arguments.length&&(i=s=0,r=t.canvas.width,a=t.canvas.height),n="number"==typeof n?k(n,0,1):.5,o="number"==typeof o?k(o,0,1):.5,c??(c={left:0,top:0,width:e instanceof HTMLVideoElement?e.videoWidth:e.width,height:e instanceof HTMLVideoElement?e.videoHeight:e.height});const h=c.width,l=c.height,p=Math.min(r/h,a/l);let m=h*p,d=l*p,g=1;m<r&&(g=r/m),Math.abs(g-1)<1e-14&&d<a&&(g=a/d),m*=g,d*=g;const u=Math.max(h/(m/r),0),f=Math.max(l/(d/a),0),y=Math.min((h-u)*n,h),x=Math.min((l-f)*o,l);t.drawImage(e,y+c.left,x+c.top,u,f,i,s,r,a)}},ri={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},ai=class{constructor(t){c(this,"_player"),c(this,"_container"),c(this,"size",[0,0]),c(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new f({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r,a){if(!ci.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new f({canvas:this._container,manualRender:!0})),r??(r=[0,0,0,0]),a??(a=i[0]<i[1]?"y":"x"),this.size=[...s],this._container.width=this.size[0],this._container.height=this.size[1],qt(this._player),this._player.resize();const n=JSON.parse(JSON.stringify(t));await this._player.loadScene(n,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(e);const o=this._player.getCompositions()[0];if(o){const[e,n]=s,c=i[0]/i[1],h=e/n;c>h&&this.keepDistribute(t,o,h/c,s);const[l,p,m,d]=r,g=e-m-d,u=n-l-p,f=[(m-d)/2,(l-p)/2],y=(new W).setFromCenterAndSize(new F(e,n).divide(2),new F(e,n)),x=(new W).setFromCenterAndSize(new F(e,n).divide(2).add(new F(...f)),new F(g,u));this.keepAdsorption("topAdsorption",t,o,f,y,x,a),this.keepAdsorption("bottomAdsorption",t,o,f,y,x,a),this.keepAdsorption("leftAdsorption",t,o,f,y,x,a),this.keepAdsorption("rightAdsorption",t,o,f,y,x,a),this.keepAdsorption("centerAdsorption",t,o,f,y,x,a),this.keepDoubleAdsorption("bottomCenterAdsorption",t,o,f,y,x)}return t}keepDistribute(t,e,i,s){const r=t=>{const i=(new O).copyFrom(e.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===ri[a]&&!t.parentId).forEach(a=>{const n=e.items.filter(t=>t.parentId===a.getInstanceId()),o=n.find(t=>"check-area"===t.name),c=o?this.getViewBoxByHeadlessPlayerItem(o,[],r):this.getViewBoxByHeadlessPlayerItem(a,n,r),h=a.transform.position.clone(),l=c.getCenter(),p=new F(...s.map(t=>t/2)),m=l.y-p.y;((t,i,r)=>{const{z:a}=t.transform.getWorldPosition(),{x:n,y:o}=e.camera.getInverseVPRatio(a);t.transform.translate(2*i*n/s[0],-2*r*o/s[1],0)})(a,0,m/i-m),a.transform.updateLocalMatrix();const d=a.transform.position.clone().subtract(h).toArray();this._pageDataUtils.changeSceneItemProperty(t,{itemId:a.getInstanceId(),type:a.type,propertyName:"position",propertyValue:d})})})}keepAdsorption(t,e,i,s,r,a,n){const{x:o,y:c}=r.getSize(),h=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:n}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/o,-2*s*n/c,0)},l=t=>{const e=(new O).copyFrom(i.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,c)},p=ri[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===p&&!t.parentId).forEach(r=>{const o=i.items.filter(t=>t.parentId===r.getInstanceId()),c=o.find(t=>"check-area"===t.name),p=r.transform.position.clone(),m=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",d=["leftAdsorption","topAdsorption"].includes(t)?1:-1,g=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",u=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",f=3===r.name.split("-").length,y=Number(r.name.split("-")[1]),x=new F,w=[1,1],v=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l);h(r,...s),v.getSize().x>a.getSize().x&&(w[0]=a.getSize().x/v.getSize().x,w[1]=a.getSize().x/v.getSize().x,r.scale(...w,1)),r.transform.updateLocalMatrix();const I=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l),P=new F;if(!a.containsBox(I)){const{min:t,max:e}=I,{min:i,max:s}=a;P.x+=t.x<i.x?i.x-t.x:0,P.x+=e.x>s.x?s.x-e.x:0,P.y+=t.y<i.y?i.y-t.y:0,P.y+=e.y>s.y?s.y-e.y:0,h(r,...P.toArray()),r.transform.updateLocalMatrix()}const C=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l);if(!Number.isNaN(y)&&f)if("centerAdsorption"!==t){const t=Math.abs(C[u][m]-a[g][m]),e=a.getSize()[m]*y;t>e&&(x[m]=(e-t)*d,h(r,...x.toArray()),r.transform.updateLocalMatrix())}else{const t=C.getSize()[n],e=a.getSize()[n];if(t/e>y){const i=e*y/t;r.scale(i,i,1),w[0]*=i,w[1]*=i}}const b=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l),D=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),z=new W;if(D.forEach(t=>{const e=i.items.filter(e=>e.parentId===t.getInstanceId()),s=e.find(t=>"check-area"===t.name),r=s?this.getViewBoxByHeadlessPlayerItem(s,[],l):this.getViewBoxByHeadlessPlayerItem(t,e,l);z.union(r)}),!z.isEmpty()&&z.max.y>b.min.y)if("centerAdsorption"===t){const t=z.max.y-b.min.y;h(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=b.getSize().y,e=a.getSize().y-(z.max.y-a.min.y);let i=z.max.y-b.min.y;if(t>e){const s=e/t;w[0]*=s,w[1]*=s,r.scale(s,s,1),r.transform.updateLocalMatrix(),i-=(t-e)/2}h(r,0,i),r.transform.updateLocalMatrix()}const S=r.transform.position.clone().subtract(p).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"position",propertyValue:S}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"size",propertyValue:w})})}keepDoubleAdsorption(t,e,i,s,r,a){const{x:n,y:o}=r.getSize(),c=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:c}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/n,-2*s*c/o,0)},h=t=>{const e=(new O).copyFrom(i.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(n,o)},l=ri[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===l&&!t.parentId).forEach(t=>{const r=i.items.filter(e=>e.parentId===t.getInstanceId()),n=r.find(t=>"check-area"===t.name),o=t.transform.position.clone(),l=3===t.name.split("-").length,p=Number(t.name.split("-")[1]),m=[1,1],d=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);c(t,...s),d.getSize().x>a.getSize().x&&(m[0]=a.getSize().x/d.getSize().x,m[1]=a.getSize().x/d.getSize().x,t.scale(...m,1)),t.transform.updateLocalMatrix();const g=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);if(!Number.isNaN(p)&&l){const e=g.getSize().y,i=a.getSize().y;if(e/i>p){const s=i*p/e;t.scale(s,s,1),m[0]*=s,m[1]*=s}}const u=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h),f=new F;if(!a.containsBox(u)){const{min:e,max:i}=u,{min:s,max:r}=a;f.x+=e.x<s.x?s.x-e.x:0,f.x+=i.x>r.x?r.x-i.x:0,f.y+=e.y<s.y?s.y-e.y:0,f.y+=i.y>r.y?r.y-i.y:0,c(t,...f.toArray()),t.transform.updateLocalMatrix()}const y=t.transform.position.clone().subtract(o).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"position",propertyValue:y}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"size",propertyValue:m})})}getViewBoxByHeadlessPlayerItem(t,e,i){const s=new W,{transform:r,composition:a}=t;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,n=(new O).copyFrom(a?.transform.getWorldMatrix()??new O).invert().multiply(r.getWorldMatrix()),{x:o,y:c}=t.clone().divide(2),h=new N(o,c,0).applyMatrix(n),l=new N(o,-c,0).applyMatrix(n),p=new N(-o,-c,0).applyMatrix(n),m=new N(-o,c,0).applyMatrix(n),d=i(h).round(2),g=i(l).round(2),u=i(p).round(2),f=i(m).round(2);s.setFromVec2Array([d,g,u,f]);const y=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});y&&y.map(t=>s.union(t));break}case g.ItemType.null:{const t=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});t&&t.map(t=>s.union(t));break}}return s}dispose(){this._player?.dispose()}},ni=class{constructor(){c(this,"index",0),c(this,"operations",[])}push(t){this.operations.push(t)}undo(){const t=Math.max(0,this.index-1);if(t!==this.index)return this.index=t,this.operations[t]}redo(){const t=Math.min(this.index+1,this.operations.length-1);if(t!==this.index)return this.index=t,this.operations[t]}clear(){this.operations=[]}},oi=class t{constructor(e){c(this,"_eventEmitter",new w),c(this,"_pageData"),c(this,"_screenShot"),c(this,"_exporter"),c(this,"_pageDataUtils"),c(this,"_sizeAdapt"),c(this,"_gestureHandler"),c(this,"disposables",[]),c(this,"_isSwitchScene",!1),c(this,"_canvasUndoRedo",new ni),c(this,"player"),c(this,"_container"),c(this,"_playerContainer"),c(this,"on",this._eventEmitter.on),this._container=e;const[i,s]=[e.offsetWidth,e.offsetHeight],r=document.createElement("div");r.id="player-container",r.style.width=`${i}px`,r.style.height=`${s}px`,r.style.position="absolute",r.style.backgroundRepeat="no-repeat",r.style.backgroundPosition="center center",e.appendChild(r),this._playerContainer=r,this.player=new f({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if(v(this._pageData,"You must call SDK#run() first"),this._isSwitchScene)return;const t=this.player.getCompositions()[0]?.time;if(this._pageData.playing)if(void 0!==t)this._pageData.time===t&&this.player.pause(),this._pageData.time=t,this._pageDataUtils.refreshPageTime(t);else{this._pageData.playing=!1,this.setPlayProgress(100);const t=this.getViewProperty(this._pageData.activeData.view??0)?.scene,e=t?.compositions.find(e=>e.id===t.compositionId);this._pageData.time=e?.duration??2,this._pageDataUtils.refreshPageTime(this._pageData.time)}this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}),this._eventEmitter.on("pageDataChange",t=>{this._pageData=t,this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.view=t;const e=this.getViewProperty(t);this._gestureHandler.ignoreInteraction=!!e?.ignoreInteraction}),this._eventEmitter.on("sdkConfigChange",(t,e)=>{this.checkExporter(t.exportConfig,e.exportConfig)}),this._pageDataUtils=new de(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportConfig),this._gestureHandler=new Nt(e),this._screenShot=new si,this._sizeAdapt=new ai(this._pageDataUtils);const a=new ResizeObserver(()=>{if(!this._pageData)return;const i=[e.offsetWidth,e.offsetHeight],s=this.getViewProperty(this._pageData.activeData.view??0);if(!s)return;const{size:r}=s,[a,n]="template"===t.config.mode?this._pageDataUtils.getPlayerSizeByParent(i,r):i;this._playerContainer.style.width=`${a}px`,this._playerContainer.style.height=`${n}px`,this.player.resize(),this._pageDataUtils.refreshInteractionParam(),this._gestureHandler.resize()});a.observe(e),this.disposables.push(()=>{a.disconnect()})}get container(){return this._container}get pageData(){return this._pageData}get exportStatus(){return this?._exporter?.status}get canvasUndoRedo(){return this._canvasUndoRedo}get exportOptions(){if(!this.pageData)return[];const t=this.pageData.viewProperties.filter(t=>!t.ignoreInteraction),e=t[0]?.scene?.compositions?.[0]?.name??"videos",i=[];return t.map((t,s)=>{const{size:r,scene:a,export:{name:n,...o}}=t,c=r?.[0]&&r?.[1]?` (${s+1})_${r[0]}×${r[1]}`:` (${s+1})`;let h="";return h=n?function(t,e){if(!e.includes(t))return t;let i=1,s=`${t} (${i})`;for(;e.includes(s);)i++,s=`${t} (${i})`;return s}(n,i):`${e}${c}`,i.push(h),{folderName:e,name:h,size:r,scene:JSON.parse(JSON.stringify(a)),...o}})}dispose(){this.player?.dispose(),this._screenShot?.dispose(),this._pageData=void 0,this._playerContainer.remove(),this?._exporter?.dispose(),this._screenShot.dispose(),this._gestureHandler.dispose(),this.disposables.forEach(t=>{t()})}async getInitParam(t){const e=JSON.parse(JSON.stringify(t));if("editor"===e.mode){const t=[this._container.offsetWidth,this._container.offsetHeight];return{scene:Qt(t),viewParams:[{size:t,export:{audioEnable:!1}}],options:{asyncMode:!1,safeAreaPreview:!1,adsorption:!0}}}{if("string"==typeof e.scene)try{const t=await fetch(e.scene,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);const i=await t.json(),s=i.compositions.find(t=>t.id===i.compositionId)??i.compositions[0],r=e.viewParams?.length?e.viewParams:[{size:s.previewSize??[750,1624],export:{audioEnable:!1}}];return{...e,scene:i,viewParams:r}}catch(t){throw new Error(`Failed to fetch scene data from ${e.scene}: ${t instanceof Error?t.message:String(t)}`)}const t=e.scene.compositions.find(t=>t.id===e.scene.compositionId)??e.scene.compositions[0],i=e.viewParams?.length?e.viewParams:[{size:t.previewSize??[750,1624],export:{audioEnable:!1}}];return{...e,scene:e.scene,viewParams:i}}}checkExporter(t,e){this._exporter&&!Bt(t,e)&&(this._exporter.dispose(),this.initExporter(e))}initExporter(t){this._exporter=new ii(t),this._exporter.on("progress",t=>{this._eventEmitter.emit("exportProgress",t)}),this._exporter.on("done",(t,e,i)=>{this._eventEmitter.emit("exportDone",t,e,i)}),this._exporter.on("complete",(t,e,i)=>{this._eventEmitter.emit("exportComplete",t,e,i)})}async initSDK(e){var i;const{scene:s,viewParams:r,options:a}=e,n=[];if(t.config.pageConfig.staticPreview){const t=JSON.parse(JSON.stringify(s)),e=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(e){const[i,s]=e.previewSize??[1080,1920],r=e.duration??0;n.push({size:[i,s],safeArea:[0,0,0,0],previewSafeAreas:[],id:0,scene:t,ignoreInteraction:!0,export:{time:r,audioEnable:!1}})}}for(let e=0;e<r.length;e++){const a=r[e];if(!a)continue;let o=JSON.parse(JSON.stringify(s));const c=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0];v(c);const h=c.previewSize??[750,1624],l=h,p=a.size??h;c.previewSize=p;const m=c.duration??0,d=a.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(o=await this._sizeAdapt.adjustment(o,m,l,p,d,a.adaptionDirection)),(i=a.export).time??(i.time=m),n.push({...a,size:p,safeArea:d,previewSafeAreas:[...a.previewSafeAreas??[]],id:e+1,scene:o,ignoreInteraction:!1})}const o=n[0]?.scene;if(!o)return void console.warn("SDK need one view property at least.");const c=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0],h={...a,zoom:1,translation:[0,0],asyncMode:a.asyncMode??!1},l=(c?.duration??0)-.1,p=t.config.pageConfig.staticPreview?1:0;this._pageData={scene:JSON.parse(JSON.stringify(s)),time:l,property:h,activeData:{view:n[p].id,selectedItems:[]},items:[],viewProperties:n,playing:!1},this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),this._gestureHandler.ignoreInteraction=!!n[1]?.ignoreInteraction,t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=h.safeAreaPreview,this._eventEmitter.emit("progress",{duration:l,time:l,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing}),await this._pageDataUtils.loadScene(this._pageData.activeData.view),this._pageDataUtils.refreshPageTime(l)}async run(e){t.config.mode=e.mode,t.config.pageConfig.staticPreview="template"===e.mode&&t.config.pageConfig.staticPreview;const i=await this.getInitParam(e);await this.initSDK(i),this._eventEmitter.emit("pageDataChange",this.getPageData())}getPageData(){return JSON.parse(JSON.stringify(this._pageData))}getActiveItems(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem??""}setSelectedItems(t){this._pageDataUtils.clearPreSelectedItem(),this._pageDataUtils.clearSelectedItems(),this._pageDataUtils.addSelectedItems([...t])}getItemProperty(t){v(this._pageData,"You must call SDK#run() first");const e=this._pageData.items.find(e=>e.id===t.itemId);if(e&&e.type===t.type)return{type:e.type,property:e.property}}getItemPropertyValue(t){v(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){v(this._pageData,"You must call SDK#run() first");const e=this.getViewProperty(this._pageData.activeData.view??0)?.ignoreInteraction;e?console.warn("Static scene cannot change."):(await this._pageDataUtils.changeItemProperty(t),this._gestureHandler.render(),this._eventEmitter.emit("pageDataChange",this.getPageData()))}async generateScreenShot(t,e=[300,400],i,s){v(this._pageData,"You must call SDK#run() first");const r=this.getViewProperty(t);if(!r)return"";const{scene:a,size:[n,o]}=r,c=a.compositionId,h=a.compositions.find(t=>t.id===c);i??(i=h?.duration??0);const l=JSON.parse(JSON.stringify(a));return await this._screenShot.generate(l,[n,o],e,i,s)}async switchScene(t){if(v(this._pageData,"You must call SDK#run() first"),t===this._pageData.activeData.view)return;this._isSwitchScene=!0;const e=this._pageData.viewProperties[t];if(e){const t=this._pageData.playing;this._pageData.activeData={view:e.id,selectedItems:[],preSelectedItem:void 0},await this._pageDataUtils.loadScene(e.id),t&&(this._pageData.playing=t,this.player.gotoAndPlay(this._pageData.time))}else console.warn("target scene does not exist.");this._eventEmitter.emit("selectedViewChange",t),this._eventEmitter.emit("pageDataChange",this.getPageData()),this._isSwitchScene=!1}getPageConfig(){return v(this._pageData,"You must call SDK#run() first"),{safeAreaPreview:this._pageData.property.safeAreaPreview,zoom:this._pageData.property.zoom,adsorption:this._pageData.property.adsorption,asyncMode:this._pageData.property.asyncMode}}setPageConfig(e){v(this._pageData,"You must call SDK#run() first");const{adsorption:i,safeAreaPreview:s,zoom:r}=this._pageData.property;this._pageData.property={...this._pageData.property,...e},this._pageData.property.zoom!==r&&this._pageDataUtils.setPageZoom(this._pageData.property.zoom),i!==e.adsorption&&(t.config.gestureHandlerConfig.adsorptionGizmoEnabled=e.adsorption),s!==e.safeAreaPreview&&(t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=e.safeAreaPreview),this._gestureHandler.render()}async setPlayProgress(t){v(this._pageData,"You must call SDK#run() first");const e=(this.player.getCompositions()[0]?.getDuration()??2)*t/100;this._pageData.time=e;!this.player.getCompositions().length&&(qt(this.player),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0));this._pageData.playing?this.player.gotoAndPlay(e):(this.player.gotoAndStop(e),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:e,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!0})),this._pageDataUtils.refreshPageTime(e)}getViewItems(){return this.getPageData()?.items??[]}async setPlayState(t){v(this._pageData,"You must call SDK#run() first");const e="play"===t;if(this._pageData.playing!==e){if(this._pageData.playing=e,this._gestureHandler.ignoreInteraction=e,e){const t=this.player.getCompositions(),e=this.getViewProperty(this._pageData.activeData.view??0);await this.player.loadScene(e.scene,{autoplay:!1}),this.player.gotoAndPlay(this._pageData.time),this.destroyCompositions(t)}else this.player.gotoAndStop(this._pageData.time);this._gestureHandler.render()}}getViewThumbnail(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(async t=>({id:t.id,thumbnail:await this.generateScreenShot(t.id)}))}getViewScene(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:t.scene}))}destroyCompositions(t){t.forEach(t=>{t.dispose();const e=this.player.getCompositions(),i=e.indexOf(t);i>-1&&e.splice(i,1)})}onExport(){t.config.exportConfig.enabled&&(v(this.pageData,"You must call SDK#run() first"),v(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){v(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData={view:this._pageData.viewProperties[this._pageData.viewProperties.length-1].id,selectedItems:[],preSelectedItem:void 0},this._pageData.viewProperties.push(...t.viewProperties),this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}async runByPageData(t){const e=JSON.parse(JSON.stringify(t));e.property.zoom=1,e.property.translation=[0,0],this._pageData=e,this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._pageDataUtils.refreshPageTime(this._pageData.time),this._eventEmitter.emit("pageDataChange",this.getPageData())}async reloadPageDataByScene(t){v(this._pageData,"You must call SDK#run() first");let e=JSON.parse(JSON.stringify(t));if("string"==typeof e)try{const t=await fetch(e,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);e=await t.json()}catch(t){throw new Error(`Failed to fetch scene data from ${e}: ${t instanceof Error?t.message:String(t)}`)}this._pageData.time=e.compositions.find(t=>t.id===e.compositionId)?.duration??2,this._pageData.viewProperties.forEach(t=>{t.scene=JSON.parse(JSON.stringify(e))}),this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}async addViewParams(e){var i;v(this._pageData);const s=[],r=this._pageData.viewProperties[this._pageData.viewProperties.length-1]?.id??this._pageData.viewProperties.length-1;for(let a=0;a<e.length;a++){const n=e[a];if(!n)continue;let o=JSON.parse(JSON.stringify(this._pageData.scene));const c=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0];v(c);const{previewSize:h=[750,1624]}=c,l=h,p=n.size??h;c.previewSize=p;const m=c.duration??0,d=n.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(o=await this._sizeAdapt.adjustment(o,m,l,p,d,n.adaptionDirection)),(i=n.export).time??(i.time=m),s.push({...n,size:p,safeArea:d,previewSafeAreas:[...n.previewSafeAreas??[]],id:r+1+a,scene:o,ignoreInteraction:!1})}this._pageData.viewProperties.push(...s),this._eventEmitter.emit("pageDataChange",this.getPageData())}async deleteViewParams(t){t.sort((t,e)=>t-e);for(let e=0;e<t.length;e++){const i=t[e];v(this._pageData);const s=i-e,r=this._pageData.viewProperties.findIndex(t=>t.id===s);if(!0===this._pageData.viewProperties[r]?.ignoreInteraction){console.warn("target view ignore interaction, it can not be deleted.");continue}if(r<0){console.warn("Target view is not existed.");continue}this._pageData.viewProperties.splice(r,1);const a=this._pageData.activeData.view??0;s===a?(this._pageData.activeData.view=0,await this._pageDataUtils.loadScene(0)):s<a&&(this._pageData.activeData.view=a-1),this._pageData.viewProperties.forEach(t=>{t.id>s&&(t.id-=1)})}this._eventEmitter.emit("selectedViewChange",this._pageData?.activeData?.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}setExportParam(t,e){v(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||Object.assign(i.export,t)})}setPageZoom(t){v(this._pageData),this._pageData.property.zoom=t,this._pageDataUtils.setPageZoom(this._pageData.property.zoom),this._gestureHandler.render()}setStaticPreviewEnabled(e){t.config.pageConfig.staticPreview=e}setStaticPreviewName(e){t.config.pageConfig.staticPreviewName=e}setAsyncEnabled(e){t.config.pageConfig.asncMode=e}setGroupVisibleEnabled(e){t.config.pageConfig.groupVisible=e}addFilterItemNames(e){"string"==typeof e?Z(t.config.pageConfig.filterItemNames,e):e.forEach(e=>{Z(t.config.pageConfig.filterItemNames,e)})}setPreferenceBackgroundColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.markColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.markAlpha=e[3]??.3,this._gestureHandler.render()}setSafeAreaColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxAlpha=e[3]??.3,this._gestureHandler.render()}setSizeAdaptEnabled(e){t.config.sizeAdaptConfig.enabled=e}setScreenShotEnabled(e){t.config.screenShotConfig.enabled=e}setExportConfig(e){const i=Object.assign({},t.config.exportConfig,e);this.checkExporter(t.config.exportConfig,i),t.config.exportConfig=i}setSelectorGizmoPreSelectConfig(e,i){void 0!==e&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedColor=e),void 0!==i&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedWidth=i),this._gestureHandler.render()}setTranformGizmoWireframeConfig(e){void 0!==e.wireframeAlpha&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeAlpha=e.wireframeAlpha),void 0!==e.wireframeColor&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeColor=e.wireframeColor),void 0!==e.wireframeWidth&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeWidth=e.wireframeWidth),this._gestureHandler.render()}getSDKConfig(){return t.config}setSDKConfig(e){const i=Object.assign({},t.config);this._eventEmitter.emit("sdkConfigChange",i,e),t.config=e}setSDKBackground(t,e){switch(t){case"color":this._container.style.removeProperty("background-color"),this._container.style.removeProperty("background-image"),this._container.style.removeProperty("background-repeat"),this._container.style.removeProperty("background-position"),this._container.style.removeProperty("background-size"),e&&(this._container.style.backgroundColor=e);break;case"image":this._container.style.removeProperty("background-color"),this._container.style.removeProperty("background-image"),this._container.style.removeProperty("background-repeat"),this._container.style.removeProperty("background-position"),this._container.style.removeProperty("background-size"),e&&(this._container.style.backgroundImage=`url(${e})`);break;case"chess-board":e??(e="#CCCCCC"),this._container.style.backgroundColor=e,this._container.style.backgroundImage="linear-gradient(45deg, #FFFFFF 25%, transparent 25%, transparent 75%, #FFFFFF 75%),linear-gradient(45deg, #FFFFFF 25%, transparent 25%, transparent 75%, #FFFFFF 75%)",this._container.style.backgroundRepeat="repeat",this._container.style.backgroundPosition="0 0, 10px 10px",this._container.style.backgroundSize="20px 20px"}}async addSpriteItem(t){return await this._pageDataUtils.addSpriteItem(t)}openPictureCutGizmo(){this._gestureHandler.openPictureCutGizmo()}closePictureCutGizmo(){this._gestureHandler.closePictureCutGizmo()}getCutInfo(){return this._gestureHandler.getCutInfo()}setCutBox(t,e){return this._gestureHandler.setCutBox(t,e)}openPictureExpandGizmo(){this._gestureHandler.openPictureExpandGizmo()}closePictureExpandGizmo(){this._gestureHandler.closePictureExpandGizmo()}getExpandInfo(){return this._gestureHandler.getExpandInfo()}setExpandBox(t,e){return this._gestureHandler.setExpandBox(t,e)}openMaskGizmo(t){this._gestureHandler.openMaskGizmo(t)}clearMaskGizmo(){this._gestureHandler.clearMaskGizmo()}closeMaskGizmo(){this._gestureHandler.closeMaskGizmo()}getMask(){return this._gestureHandler.getMask()}openLoadingGizmo(t){this._gestureHandler.openLoadingGizmo(t)}closeLoadingGizmo(t){this._gestureHandler.closeLoadingGizmo(t)}groupItems(t){return this._pageDataUtils.addNullItem(t)}async addTextItem(t){await this._pageDataUtils.addTextItem(t)}deleteItems(t){if(v(this._pageData,"You must call SDK#run() first"),Array.isArray(t)){t.forEach(t=>{this._pageDataUtils.deleteItem(t)});const e=this._pageData.activeData.selectedItems.filter(e=>!t.includes(e));this._eventEmitter.emit("selectedItemChange",e)}else{this._pageDataUtils.deleteItem(t);const e=this._pageData.activeData.selectedItems.filter(e=>e!==t);this._eventEmitter.emit("selectedItemChange",e)}this._pageDataUtils.interactionUtils.refreshViewParam(),this._pageDataUtils.interactionUtils.refreshCameraParam(),this._pageData.items=[];const e=this._pageDataUtils.getCurrentComposition();this._pageDataUtils.addViewItemsByItems(this._pageData.items,e.items),this._eventEmitter.emit("pageDataChange",this._pageData)}getItemCreateInfo(t){v(this._pageData,"You must call SDK#run() first");const e=[];if(Array.isArray(t))t.forEach(i=>{const s=this._pageDataUtils.getViewItemById(i),r=this._pageDataUtils.getItemCreateInfo(i,!(!s?.parentId||!t.includes(s?.parentId)));r&&e.push(r)});else{const i=this._pageDataUtils.getItemCreateInfo(t,!1);i&&e.push(i)}return e}async createScreenShotSceneByIds(t,e=0){const i=this._pageDataUtils.createScreenShotSceneByIds(t);if(!i)return;const s=i?.compositions[0]?.previewSize??[750,1624];console.log(i);const r=await this._screenShot.generate(i,s,s,e);return console.log(r),r}getChildrenIds(t){return this._pageDataUtils.getChildrenIds(t)}updateItemOrder(t,e){v(this._pageData,"You must call SDK#run() first");const i=this.getViewProperty(this._pageData.activeData.view??0)?.ignoreInteraction;i?console.warn("Static scene cannot change."):(this._pageDataUtils.updateItemOrder(t,e),this._gestureHandler.render())}exportJSON(t){v(this._pageData,"You must call SDK#run() first");const e=[];if(Array.isArray(t))t.forEach(t=>{const i=this.getViewProperty(t);i?e.push(i.scene):console.warn(`view id ${t} is not exsited.`)});else if(void 0!==t){const i=this.getViewProperty(t);i?e.push(i.scene):console.warn(`view id ${t} is not exsited.`)}else e.push(...this._pageData.viewProperties.map(t=>t.scene));return e}getViewBoxById(t){return this._pageDataUtils.getViewBoxById(t)}getViewItemById(t){return this._pageDataUtils.getViewItemById(t)}getViewProperty(t){return this._pageDataUtils.getViewProperty(t)}pageMove(t){this._pageDataUtils.pageMove(new F(...t))}pageZoom(t,e){this._pageDataUtils.pageZoom(t,e?new F(...e):void 0)}setPictureCutGizmoLockScale(t){this._gestureHandler.setPictureCutGizmoLockScale(t)}setPictureExpandGizmoLockScale(t){this._gestureHandler.setPictureExpandGizmoLockScale(t)}viewportFit(){this._pageDataUtils.viewportFit()}};c(oi,"config",{mode:"template",pageConfig:{asncMode:!1,minZoom:.01,maxZoom:20,staticPreview:!0,staticPreviewName:"标准模板",filterItemNames:["check-area","ModelPluginItem"],groupVisible:!0},screenShotConfig:{enabled:!0},exportConfig:{enabled:!0,mediaType:"MP4",loggerInTranscoding:!1},sizeAdaptConfig:{enabled:!0},gestureHandlerConfig:{enabled:!0,adsorptionGizmoEnabled:!0,adsorptionGizmoConfig:{lineWidth:2,lineColor:37375,distance:6},controlGizmoEnabled:!0,controlGizmoConfig:{zoomStep:.01},preferenceGizmoEnabled:!0,preferenceGizmoConfig:{boxColor:16711680,boxWidth:1,markColor:0,markAlpha:.17,safeAreaEnabled:!0,safeAreaBoxColor:65280,safeAreaBoxAlpha:.3},selectorGizmoEnabled:!0,selectorGizmoConfig:{preSelectedWidth:3,preSelectedColor:15425024,regionBoxColor:16777215,regionBoxAlpha:.17,regionWireframeColor:16777215,regionWireframeAlpha:.78,regionWireframeWidth:1},transformGizmoEnabled:!0,transformGizmoConfig:{wireframeColor:16711680,wireframeAlpha:1,wireframeWidth:1.5,cornerFillColor:16777215,cornerLineColor:0,cornerLineWidth:1,cornerLineAlpha:.3,scaleCircleSize:4,rotationCircleSize:8,pictureLogoUrl:"https://mdn.alipayobjects.com/huamei_ppzin5/afts/img/EMCfRoZQj8cAAAAAOmAAAAgADjdkAQFr/original",nullLogoUrl:"https://mdn.alipayobjects.com/huamei_ppzin5/afts/img/Yo69Sr7boqYAAAAAH3AAAAgADjdkAQFr/original",sizeTextColor:6710886,nameTextColor:6710886},pictureCutGizmoEnabled:!1,pictureCutGizmoConfig:{maskColor:16777215,maskAlpha:.5,cutBoxLineWidth:2,cutBoxLineColor:6960383,cutBoxLineAlpha:1,itemBoxLineWidth:1,itemBoxLineColor:6960383,itemBoxLineAlpha:1,cutBoxCornerRadius:5,cutBoxCornerLineWidth:2,cutBoxCornerLineColor:6960383,cutBoxCornerLineAlpha:1,cutBoxCornerFillColor:16777215,scaleInteractionDistance:8,directionScaleInteractionDistance:5},pictureExpandGizmoEnabled:!1,pictureExpandGizmoConfig:{maskColor:6960383,maskAlpha:.2,expandBoxLineWidth:2,expandBoxLineColor:6960383,expandBoxLineAlpha:1,expandBoxCornerRadius:5,expandBoxCornerLineWidth:2,expandBoxCornerLineColor:6960383,expandBoxCornerLineAlpha:1,expandBoxCornerFillColor:16777215,scaleInteractionDistance:8,directionScaleInteractionDistance:5},textGizmoEnbaled:!0,textGizmoConfig:{boxLineWidth:2,boxLineColor:7026175,scaleCornerRadius:5,rotationCornerWidth:30,rotationCornerTexture:"https://mdn.alipayobjects.com/huamei_ppzin5/afts/img/Zc9ZSqNEjnQAAAAAQBAAAAgADjdkAQFr/original",scaleCornerFillColor:16777215,scaleCornerStrokeWidth:2,scaleCornerStrokeColor:7026175},maskGizmoEnabled:!1,maskGizmoConfig:{brushSize:20,brushColor:6960383,brushAlpha:.5,maskColor:65280,maskAlpha:1,boxLineWidth:1,boxLineColor:6960383,boxLineAlpha:1}}});var ci=oi;export{W as Box2,d as ItemOrderAction,ci as SDK,F as Vector2,b as generateGUID,g as spec};
1
+ var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,r=t=>{throw TypeError(t)},a=(e,i)=>{for(var s in i)t(e,s,{get:i[s],enumerable:!0})},n=(r,a,n,o)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let c of i(a))s.call(r,c)||c===n||t(r,c,{get:()=>a[c],enumerable:!(o=e(a,c))||o.enumerable});return r},o=(t,e,i)=>(n(t,e,"default"),i&&n(i,e,"default")),c=(e,i,s)=>((e,i,s)=>i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s)(e,"symbol"!=typeof i?i+"":i,s),h=(t,e,i)=>e.has(t)||r("Cannot "+i),l=(t,e,i)=>(h(t,e,"read from private field"),i?i.call(t):e.get(t)),p=(t,e,i)=>e.has(t)?r("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),m=(t,e,i,s)=>(h(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i),d=(t=>(t[t.BringToFront=0]="BringToFront",t[t.SendToBack=1]="SendToBack",t[t.BringForward=2]="BringForward",t[t.SendBackward=3]="SendBackward",t))(d||{});import"@galacean/effects";import{spec as g,VFXItem as u,Player as f,math as y,Composition as x,EventEmitter as w,assertExist as v,SpriteComponent as I,TextComponent as P,Texture as C,generateGUID as b}from"@galacean/effects";import"@galacean/effects-plugin-rich-text";import{RichTextComponent as D}from"@galacean/effects-plugin-rich-text";import"@galacean/effects-plugin-model";import"@galacean/effects-plugin-multimedia";import{VideoComponent as z}from"@galacean/effects-plugin-multimedia";import"@galacean/effects-plugin-spine";import{Application as S}from"@pixi/app";var A=class{constructor(){c(this,"type"),c(this,"active"),this.type="null",this.active=!1}get interactive(){return this.active}set interactive(t){this.active=t}},T=1e-6;function k(t,e,i){const s=isNaN(e)?-1/0:e,r=isNaN(i)?1/0:i,a=Math.min(s,r),n=Math.max(s,r);return Math.min(Math.max(t,a),n)}var _=Math.PI/180,E=180/Math.PI;function B(t){return Math.atan2(-t.y,-t.x)+Math.PI}function M(t,e){const i=Math.min(Math.max(t.dot(e)/t.length()/e.length(),-1),1);let s=Math.acos(i);return s=t.x*e.y-t.y*e.x>0?s:-s,s}function V(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function G(t,e){return Math.abs(t-e)<T||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function U(t){return isNaN(t)||Math.abs(t)<T}var F=class t extends y.Vector2{subtract(t){return this.x-=t.x,this.y-=t.y,this}toViewCoordinate(t,e){return this.x=(this.x+1)/2*t,this.y=(1-(this.y+1)/2)*e,this}clone(){return new t(this.x,this.y)}distanceTo(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}scaleByCenter(e,i=new t){const s=(new t).subtractVectors(i,this).multiply(e);return this.subtractVectors(i,s)}round(t=0){const e=Math.pow(10,t);return this.x=Math.round(this.x*e)/e,this.y=Math.round(this.y*e)/e,this}distanceToLine(e){const i=Math.pow(e.length(),2),{start:s,end:r}=e;if(0===i)return{d:(new t).subtractVectors(this,s).length(),t:0};const a=k(((this.x-s.x)*(r.x-s.x)+(this.y-s.y)*(r.y-s.y))/i,0,1);return{d:(new t).subtractVectors(this,e.at(a)).length(),t:a}}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),r=this.x-t.x,a=this.y-t.y;return this.x=r*i-a*s+t.x,this.y=r*s+a*i+t.y,this}},R=class t{constructor(t=new F,e=new F){c(this,"start",new F),c(this,"end",new F),this.start.copyFrom(t),this.end.copyFrom(e)}set(t,e){return this.start.copyFrom(t),this.end.copyFrom(e),this}copyFrom(t){return this.start.copyFrom(t.start),this.end.copyFrom(t.end),this}direction(){return(new F).subtractVectors(this.end,this.start).normalize()}getCenter(t=new F){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new F){return t.subtractVectors(this.end,this.start)}distanceSq(){return this.start.distanceSquared(this.end)}distance(){return this.start.distance(this.end)}at(t,e=new F){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new F,s=new F;i.subtractVectors(t,this.start),s.subtractVectors(this.end,this.start);const r=s.dot(s);let a=s.dot(i)/r;return e&&(a=k(a,0,1)),a}closestPointToPoint(t,e,i=new F){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiply(s).add(this.start)}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new t).copyFrom(this)}length(){return(new F).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new F).subtractVectors(t.start,this.start),r=(new F).subtractVectors(t.end,this.start),a=(new F).subtractVectors(this.start,t.start),n=(new F).subtractVectors(this.end,t.start),o=s.cross(e),c=r.cross(e),h=a.cross(i),l=n.cross(i);return o*c<0&&h*l<0}},W=class t{constructor(t=new F(1/0,1/0),e=new F(-1/0,-1/0)){c(this,"corners",[]),c(this,"min",new F(1/0,1/0)),c(this,"max",new F(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[new F(e.x,t.y),e.clone(),new F(t.x,e.y),t.clone()]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[new F(e.x,t.y),e.clone(),new F(t.x,e.y),t.clone()],this}setFromVec2Array(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min.min(t),this.max.max(t),this.corners.push(t.clone())}),this}setFromVec2ArrayWithOutCorners(t){return this.min=(new F).copyFrom(t[0]),this.max=(new F).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new F(this.max.x,this.min.y)),this.corners.push(new F(this.max.x,this.max.y)),this.corners.push(new F(this.min.x,this.max.y)),this.corners.push(new F(this.min.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new F).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y),this.min.clone()],this}clone(){return(new t).copyFrom(this)}copyFrom(t){return this.corners=[],this.min.copyFrom(t.min),this.max.copyFrom(t.max),t.corners.forEach(t=>{this.corners.push(t.clone())}),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this.corners=[],this}isEmpty(){return this.max.x<=this.min.x||this.max.y<=this.min.y}getCorners(){const t=[];return this.corners.forEach(e=>{t.push(e.clone())}),t}getCenter(t=new F){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new F){return this.isEmpty()?t.set(0,0):t.subtractVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.subtract(t),this.max.add(t),this}expandByScalar(t){return this.min.add(-t),this.max.add(t),this}containsPoint(t,e=!0){if(e)return!(t.x<this.min.x||t.x>this.max.x||t.y<this.min.y||t.y>this.max.y);if(this.isEmpty())return!1;for(let e=0;e<this.corners.length;e++){const i=this.corners[e],s=this.corners[(e+1)%4],r=new F(s.x-i.x,s.y-i.y),a=new F(t.x-i.x,t.y-i.y);if(r.cross(a)<0)return!1}return!0}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e=new F){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}clampPoint(t,e=new F){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new F).copyFrom(t).clamp(this.min,this.max).subtract(t).length()}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.min.x>this.max.x||this.min.y>this.max.y?this.makeEmpty():this}union(t){return this.min.min(t.min),this.max.max(t.max),this.corners=[new F(this.max.x,this.min.y),this.max.clone(),new F(this.min.x,this.max.y),this.min.clone()],this}translate(t){return this.min.add(t),this.max.add(t),this.corners.forEach(e=>{e.add(t)}),this}scaleByCenter(t,e){e??(e=this.getCenter());const i="number"==typeof t?new F(t,t):new F(t.x,t.y);return this.min.scaleByCenter(i,e),this.max.scaleByCenter(i,e),this.corners.forEach(t=>{t.scaleByCenter(i,e)}),this}scale(t,e){e??(e=this.getCenter());const i=i=>{const s=i.clone().add(e);i.add(s.multiply(t-1))};return i(this.min),i(this.max),this.corners.forEach(t=>{i(t)}),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}intersectsBox(t,e=!0){if(e)return!(t.max.x<this.min.x||t.min.x>this.max.x||t.max.y<this.min.y||t.min.y>this.max.y);if(!this.isEmpty())for(let e=0;e<this.corners.length;e++){const i=new R(this.corners[e],this.corners[(e+1)%4]);if(t.containsPoint(this.corners[e],!1))return!0;for(let e=0;e<t.corners.length;e++){const s=new R(t.corners[e],t.corners[(e+1)%4]);if(this.containsPoint(t.corners[e],!1))return!0;if(i.crossWithLine(s))return!0}}for(let e=0;e<t.corners.length;e++){const i=this.containsPoint(t.corners[e],!1),s=t.containsPoint(this.corners[e],!1);if(i||s)return!0}return!1}rotate(t,e){e??(e=this.getCenter());const i=this.corners.map(i=>i.rotateAround(e,t));return this.makeEmpty(),this.setFromVec2Array(i),this}},L=class t{constructor(t=new F,e=0){c(this,"center"),c(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new F).copyFrom(t),this.radius=e,this}clone(){return(new t).copy(this)}copy(t){return this.center.copyFrom(t.center),this.radius=t.radius,this}makeEmpty(){return this.center=new F,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new F){return t.copyFrom(this.center),t}getRadius(){return this.radius}expandByPoint(t){return this.radius=this.center.distanceTo(t),this}expandByScalar(t){return this.radius+=t,this}containsPoint(t){return this.center.distanceTo(t)<this.radius}containsBox(t){for(let e=0;e<4;e++)if(!this.containsPoint(t.corners[e]))return!1;return!0}intersectsBox(t){for(let e=0;e<4;e++)if(this.containsPoint(t.corners[e]))return!0;return!1}distanceToPoint(t){return this.center.distanceTo(t)-this.radius}},H=class extends y.Quaternion{},N=class t extends y.Vector3{clone(){return new t(this.x,this.y,this.z)}setFromMatrixColumn(t,e){return this.set(...t.elements.slice(4*e))}applyEuler(t,e){return this.applyQuaternion((new H).setFromEuler(t))}applyQuaternion(e,i=new t){const{x:s,y:r,z:a,w:n}=e,{x:o,y:c,z:h}=this.subtract(i),l=n*o+r*h-a*c,p=n*c+a*o-s*h,m=n*h+s*c-r*o,d=-s*o-r*c-a*h;return this.x=l*n+d*-s+p*-a-m*-r+i.x,this.y=p*n+d*-r+m*-s-l*-a+i.y,this.z=m*n+d*-a+l*-r-p*-s+i.z,this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}applyMatrix(e,i=new t){const s=e.elements,{x:r,y:a,z:n}=this.subtract(i);let o=1/(s[3]*r+s[7]*a+s[11]*n+s[15]);return o=isNaN(o)?1:o,this.x=(s[0]*r+s[4]*a+s[8]*n+s[12])*o+i.x,this.y=(s[1]*r+s[5]*a+s[9]*n+s[13])*o+i.y,this.z=(s[2]*r+s[6]*a+s[10]*n+s[14])*o+i.z,this}},O=class t extends y.Matrix4{static fromArray(e,i=0){return(new t).setFromArray(e,i)}clone(){const e=this.elements;return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}compose(t,e,i,s=N.ZERO){const r=this.elements,{x:a,y:n,z:o,w:c}=e,h=-s.x,l=-s.y,p=-s.z,m=a+a,d=n+n,g=o+o,u=a*m,f=a*d,y=a*g,x=n*d,w=n*g,v=o*g,I=c*m,P=c*d,C=c*g,{x:b,y:D,z:z}=i;return r[0]=(1-(x+v))*b,r[1]=(f+C)*b,r[2]=(y-P)*b,r[3]=0,r[4]=(f-C)*D,r[5]=(1-(u+v))*D,r[6]=(w+I)*D,r[7]=0,r[8]=(y+P)*z,r[9]=(w-I)*z,r[10]=(1-(u+x))*z,r[11]=0,r[12]=h*r[0]+l*r[4]+p*r[8]-h+t.x,r[13]=h*r[1]+l*r[5]+p*r[9]-l+t.y,r[14]=h*r[2]+l*r[6]+p*r[10]-p+t.z,this}extractRotation(t){const e=new N,i=t.elements,s=this.elements,r=1/e.setFromMatrixColumn(t,0).length(),a=1/e.setFromMatrixColumn(t,1).length(),n=1/e.setFromMatrixColumn(t,2).length();return s[0]=i[0]*r,s[1]=i[1]*r,s[2]=i[2]*r,s[3]=0,s[4]=i[4]*a,s[5]=i[5]*a,s[6]=i[6]*a,s[7]=0,s[8]=i[8]*n,s[9]=i[9]*n,s[10]=i[10]*n,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,r=t.z,a=Math.cos(i),n=Math.sin(i),o=Math.cos(s),c=Math.sin(s),h=Math.cos(r),l=Math.sin(r);if(t.order===y.EulerOrder.XYZ){const t=a*h,i=a*l,s=n*h,r=n*l;e[0]=o*h,e[4]=-o*l,e[8]=c,e[1]=i+s*c,e[5]=t-r*c,e[9]=-n*o,e[2]=r-t*c,e[6]=s+i*c,e[10]=a*o}else if(t.order===y.EulerOrder.YXZ){const t=o*h,i=o*l,s=c*h,r=c*l;e[0]=t+r*n,e[4]=s*n-i,e[8]=a*c,e[1]=a*l,e[5]=a*h,e[9]=-n,e[2]=i*n-s,e[6]=r+t*n,e[10]=a*o}else if(t.order===y.EulerOrder.ZXY){const t=o*h,i=o*l,s=c*h,r=c*l;e[0]=t-r*n,e[4]=-a*l,e[8]=s+i*n,e[1]=i+s*n,e[5]=a*h,e[9]=r-t*n,e[2]=-a*c,e[6]=n,e[10]=a*o}else if(t.order===y.EulerOrder.ZYX){const t=a*h,i=a*l,s=n*h,r=n*l;e[0]=o*h,e[4]=s*c-i,e[8]=t*c+r,e[1]=o*l,e[5]=r*c+t,e[9]=i*c-s,e[2]=-c,e[6]=n*o,e[10]=a*o}else if(t.order===y.EulerOrder.YZX){const t=a*o,i=a*c,s=n*o,r=n*c;e[0]=o*h,e[4]=r-t*l,e[8]=s*l+i,e[1]=l,e[5]=a*h,e[9]=-n*h,e[2]=-c*h,e[6]=i*l+s,e[10]=t-r*l}else if(t.order===y.EulerOrder.XZY){const t=a*o,i=a*c,s=n*o,r=n*c;e[0]=o*h,e[4]=-l,e[8]=c*h,e[1]=t*l+r,e[5]=a*h,e[9]=i*l-s,e[2]=s*l-i,e[6]=n*h,e[10]=r*l+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setPosition(t){return this.elements[12]=t.x,this.elements[13]=t.y,this.elements[14]=t.z,this}},K=class extends y.Euler{constructor(t=0,e=0,i=0,s=y.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new O).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*E,this.y*E,this.z*E):new N(this.x*E,this.y*E,this.z*E)}setFromDegreeVector3(t,e){return this.set(t.x*_,t.y*_,t.z*_,e??this.order)}},j=class t{constructor(t=0,e=new N(0,0,1)){c(this,"distance"),c(this,"normal");const i=e.length();0===i&&(this.normal=new N(0,0,1)),this.distance=t/(i??1),this.normal=e.normalize()}static set(e,i){return new t(e,i)}set(t,e){const i=e.length();return 0===i&&(this.normal=new N(0,0,1)),this.distance=t/i,this.normal=e.normalize(),this}static copy(e){return new t(e.distance,e.normal.clone())}copy(t){return this.distance=t.distance,this.normal.copyFrom(t.normal),this}static setFromNormalAndCoplanarPoint(e,i){const s=-e.dot(i);return new t(s,i)}setFromNormalAndCoplanarPoint(t,e){return this.normal.copyFrom(e),this.distance=-t.dot(this.normal),this}clone(){return new t(this.distance,this.normal.clone())}distanceToPoint(t){return this.normal.dot(t)+this.distance}},Y=class t extends y.Ray{constructor(t=new N,e=new N(1,0,0)){super(t,e),c(this,"origin"),c(this,"direction"),this.origin=t.clone(),this.direction=e.clone()}clone(){return new t(this.origin,this.direction)}rayCastPlane(t,e){const i=this.distanceToPlane(t);return isNaN(i)||this.at(i),i}at(t){return this.direction.clone().normalize().multiply(t).add(this.origin)}distanceToPlane(t){const e=t.normal.dot(this.direction);if(U(e))return U(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},$=class{constructor(t=new Y){c(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new N(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new N,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},J=class extends A{constructor(t){super(),c(this,"defaultInteractive",!0),c(this,"type","control"),c(this,"_interactionType","mouse"),c(this,"active",!1),c(this,"lastPoint",new F),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"SDKUtils"),this.SDKUtils=t}get interactive(){return ci.config.gestureHandlerConfig.controlGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.controlGizmoEnabled=!0}get interactionType(){return this._interactionType}set interactionType(t){t===this._interactionType&&(this._interactionType=t,this.refreshCursorResult())}get useCameraControl(){return"editor"===ci.config.mode}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(t){return"mouse"===this.interactionType&&(this.active=!0,this.lastPoint=new F(t.clientX,t.clientY)),this.refreshCursorResult(),"mouse"===this.interactionType?this.type:void 0}action(t){if(!ci.config.gestureHandlerConfig.controlGizmoEnabled)return void console.warn("Control gizmo is not opened, use #SDK.setControlConfig() open this feature.");const{metaKey:e,ctrlKey:i,shiftKey:s}=t;if(0===t.buttons){const{deltaX:r,deltaY:a,offsetX:n,offsetY:o}=t,c=new F(r,a);if(e||i){const t=this.useCameraControl?new F(n,o):new F,e=-c.y*ci.config.gestureHandlerConfig.controlGizmoConfig.zoomStep;this.SDKUtils.pageZoom(e,t)}else c.x=s&&0!==c.y?Math.sqrt(c.x**2+c.y**2)*c.y/Math.abs(c.y):c.x,c.y=s?0:c.y,this.SDKUtils.pageMove(c.negate())}else if(this.active&&t instanceof MouseEvent&&[1,4].includes(t.buttons)){const{clientX:e,clientY:i}=t,r=new F(e,i),a=(new F).subtractVectors(r,this.lastPoint);a.x=s&&0!==a.y?Math.sqrt(a.x**2+a.y**2)*a.y/Math.abs(a.y):a.x,a.y=s?0:a.y,this.SDKUtils.pageMove(a),this.lastPoint.copyFrom(r)}}endAction(){return this.active=!1,this.refreshCursorResult(),"mouse"===this.interactionType?this.type:void 0}interruption(){return this.type}actionKey(){}endActionKey(){}refreshCursorResult(){"mouse"===this.interactionType?this.cursorResult={type:this.active?"active-hand":"hand",angle:0}:this.cursorResult={type:"normal",angle:0}}getRenderObjects(){return[]}};import{Graphics as X}from"@pixi/graphics";function Z(t,e){t.includes(e)||t.push(e)}var q=class extends A{constructor(t){super(),c(this,"result",{type:"null",box:new W}),c(this,"selectedItemIds",[]),c(this,"activeParentIds",[]),c(this,"cursorPoint",new F),c(this,"startPoint",new F),c(this,"firstClickPoint",new F),c(this,"graphics",new X),c(this,"pageDataUtils"),c(this,"clearResult",!1),c(this,"type","selector"),this.pageDataUtils=t}get interactive(){return ci.config.gestureHandlerConfig.selectorGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.selectorGizmoEnabled=!0}actionKey(){}endActionKey(){}getRenderObjects(){return this.interactive?this.clearResult?(this.result={type:"null",box:new W},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t,e){if(this.result.box=new W,!this.interactive)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const i=new F(t.offsetX,t.offsetY),s=this.hitTest(i);this.selectedItemIds=this.filterSelectedItems(s);const r=this.selectedItemIds[0]??"",a=this.pageDataUtils.getPageData().activeData.selectedItems.flatMap(t=>this.pageDataUtils.getChildrenIds(t));return r.length&&e&&!a.includes(r)||!e?(!r.length||this.pageDataUtils.isItemSelected(r)||a.includes(r)?this.pageDataUtils.clearPreSelectedItem():this.pageDataUtils.addPreSelectedItem(r),this.type):(this.pageDataUtils.clearPreSelectedItem(),e)}preAction(t,e=!1,i){switch(this.pageDataUtils.clearPreSelectedItem(),t.buttons){case 1:{const s=new F(t.offsetX,t.offsetY);if(i??(i=this.firstClickPoint),e&&s.distanceTo(i)<4){const e=new F(t.offsetX,t.offsetY),i=this.hitTest(e);this.selectedItemIds=this.filterSelectedItems(i)}if(e||this.firstClickPoint.set(t.offsetX,t.offsetY),t.shiftKey){if(e){const t=this.pageDataUtils.getViewItemById(this.selectedItemIds[0]);t?.parentId&&this.pageDataUtils.removeSelectedItems([t.parentId])}}else this.pageDataUtils.clearSelectedItems(0===this.selectedItemIds.length);if(0===this.selectedItemIds.length)return this.startPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),this.activeParentIds=[],this.active=!0,this.type;{this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]);const t=this.pageDataUtils.getPageData()?.activeData?.selectedItems;return this.addActiveParentIds(t),this.clearResult=!0,1===t?.length&&this.pageDataUtils.getViewItemById(t[0])?.type===g.ItemType.text?"text":"transform"}}case 2:{const e=[...this.pageDataUtils.getPageData().activeData.selectedItems,...this.pageDataUtils.getPageData().activeData.selectedItems.flatMap(t=>this.pageDataUtils.getChildrenIds(t))];return void(this.selectedItemIds.length&&!e.includes(this.selectedItemIds[0])&&(t.shiftKey||this.pageDataUtils.clearSelectedItems(),this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0))}default:return}}action(t){const e=(new F).addVectors(this.cursorPoint,(new F).subtractVectors(new F(t.clientX,t.clientY),this.startPoint)),i=(new F).subtractVectors(this.cursorPoint,e),s=(new F).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new W).setFromCenterAndSize(s,i);this.result.type="region",this.result.box=r,this.pageDataUtils.clearSelectedItems();const a=this.pageDataUtils.getPageData().items?.filter(t=>this.pageDataUtils.getItemEditEnable(t.id)),n=[];a?.forEach(t=>{r.intersectsBox(this.pageDataUtils.getViewBoxById(t.id),!1)&&n.push(t.id)});const o=this.filterSelectedItems(n);this.pageDataUtils.addSelectedItems(o)}endAction(){this.active=!1,this.result.type="null"}interruption(){this.active=!1,this.result.type="null"}hitTest(t){const e=this.pageDataUtils.getCurrentComposition();if(!e?.items)return[];const{x:i,y:s}=this.pageDataUtils.getViewportByViewPoint(t),r={ray:new Y,regions:[]};try{r.regions=e.hitTest(i,s,!0),r.ray=e.getHitTestRay(i,s)}catch(t){console.warn(t)}return this.reorderHitTestResult(r,e).filter(t=>"extra-camera"!==t&&this.pageDataUtils.getItemEditEnable(t))}reorderHitTestResult(t,e){if(0===t.regions.length||!e)return[];const{ray:i}=t,s=t.regions.reverse(),r=[];return s.forEach(t=>{let s;const a=(t,e)=>{for(const i of t){if(i.getInstanceId()===e&&(s=i),s)return;a(i.children,e)}};if(a(e.items,t.item.getInstanceId()),void 0===s)return;const n="rootItem"===t.compContent?.name?s.getInstanceId():t.compContent.getInstanceId(),o=i.origin.clone().distance(t.position.clone());if((s.type===g.ItemType.mesh||s.getComponent(I)?.renderer?.occlusion||s.getComponent(P)?.renderer?.occlusion||s.getComponent(z)?.renderer?.occlusion||s.getComponent(D)?.renderer?.occlusion)&&r.length>0){let t=!0;r.forEach((e,i)=>{if(t)return o<=e[1]?(r.splice(i,0,[n,o]),void(t=!1)):void(i===r.length-1&&r.push([n,o]))})}else r.push([n,o])}),r.map(t=>t[0])}filterSelectedItems(t){const e=[],i=t=>{const e=this.pageDataUtils.getViewItemById(t);return!e.parentId||this.activeParentIds.includes(e.parentId)?e.id:i(e.parentId)},s=this.pageDataUtils.getPageData()?.activeData.loadingItems??[];return t.forEach(t=>{const r=i(t);s.includes(r)||Z(e,r)}),e}addActiveParentIds(t){this.activeParentIds=[],t?.forEach(t=>{if(!this.pageDataUtils.getViewItemById(t))return;const e=t=>{this.activeParentIds.push(t);const i=this.pageDataUtils.getViewItemById(t);i.parentId&&e(i.parentId)};e(t)})}resetActiveParentIds(t){const e=this.pageDataUtils.getViewItemById(t);e&&(this.activeParentIds=this.activeParentIds.filter(t=>t===e.parentId))}refreshResults(){const{box:t}=this.result;this.graphics.clear();const e=this.pageDataUtils.getPreSelectedItem(),i=this.pageDataUtils.getViewBoxById(e?.id??""),{regionBoxColor:s,regionBoxAlpha:r,preSelectedWidth:a,preSelectedColor:n,regionWireframeWidth:o,regionWireframeColor:c,regionWireframeAlpha:h}=ci.config.gestureHandlerConfig.selectorGizmoConfig;if(i?.isEmpty()||(this.graphics.lineStyle(a,n),this.graphics.drawBox(i)),!t.isEmpty()&&"region"===this.result.type)this.graphics.lineStyle(o,c,h),this.graphics.drawBox(t),this.graphics.beginFill(s,r),this.graphics.fillBox(t),this.graphics.endFill()}};import{Graphics as Q}from"@pixi/graphics";import{assertExist as tt}from"@galacean/effects";import{Text as et}from"@pixi/text";import{Sprite as it}from"@pixi/sprite";var st=class extends A{constructor(t,e,i){super(),c(this,"type","transform"),c(this,"wireframe"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"cursorPoint",new F),c(this,"lastPoint",new F),c(this,"rotationAngle",0),c(this,"active",!1),c(this,"enableAdsorption",!0),c(this,"scaleParam"),c(this,"activeType","null"),c(this,"lastWorldPosition",new N),c(this,"firstClickPoint",new F),c(this,"pageDataUtils"),c(this,"adsorptionGizmo"),c(this,"selectorGizmo"),c(this,"graphics",new Q),c(this,"nameText",new et("",{fontSize:14,fill:ci.config.gestureHandlerConfig.transformGizmoConfig.sizeTextColor,align:"left"})),c(this,"imageSprite"),c(this,"nullSprite"),this.pageDataUtils=t,this.selectorGizmo=i,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new F,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,rotationEnabled:!0,scaleEnabled:!0,box:new W,totalBox:new W,childrenBoxes:[],activeType:"null",interactiveDirection:new F,scaleCorner:new F,scaleEdgeCorners:[]},this.imageSprite=it.from(ci.config.gestureHandlerConfig.transformGizmoConfig.pictureLogoUrl),this.imageSprite._width=15,this.imageSprite._height=15,this.nullSprite=it.from(ci.config.gestureHandlerConfig.transformGizmoConfig.nullLogoUrl),this.nullSprite._width=15,this.nullSprite._height=15}get interactive(){return ci.config.gestureHandlerConfig.transformGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.transformGizmoEnabled=t}get infoType(){const t=this.pageDataUtils.getSelectedItems();return 1===t.length?t[0].type:g.ItemType.base}actionKey(){}endActionKey(){}getRenderObjects(){const t=[];if(!this.interactive)return t;if(this.refreshRenderObject(),t.push(this.graphics),this.infoType!==g.ItemType.base)switch(t.push(this.nameText),this.infoType){case g.ItemType.sprite:t.push(this.imageSprite);break;case g.ItemType.null:t.push(this.nullSprite)}return t}cancelPreparation(){this.active=!1,this.wireframe.activeType="null"}preparationAction(t){if(!this.interactive)return void console.warn("Transform gizmo is not opened, use #SDK.openTransformGizmo() open this feature.");const e=new F(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;this.refreshCursorResult(this.activeType,B(s));const r="translation"===this.activeType?this.selectorGizmo.preparationAction(t,"transform"):this.type;return this.active="transform"===r&&"null"!==this.activeType,this.active&&r?r:void 0}preAction(t,e=!1){if(this.active=1===t.buttons,this.lastPoint=new F(t.clientX,t.clientY),this.cursorPoint=new F(t.offsetX,t.offsetY),1!==t.buttons)return;if(e)return this.selectorGizmo.preAction(t,e,new F(t.offsetX,t.offsetY));this.active=!0,"null"===this.wireframe.activeType&&(this.wireframe.activeType="translation");const i=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());return this.initInteractionPlane(i),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(i)??new N,this.activeType=e?"null":this.activeType,this.type}action(t){if(!this.interactive)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(!this.active){this.active=!0,this.refreshWireframeBySelectedItems(),this.wireframe.activeType="translation",this.lastPoint.set(t.clientX,t.clientY),this.cursorPoint.set(t.offsetX,t.offsetY);const e=this.cursorPoint.clone().subtract(this.pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.lastWorldPosition=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new N}const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);if(!this.wireframe.interactive)return;const s=this.pageDataUtils.getSelectedItems(),{anchor:r,activeType:a,interactiveDirection:n}=this.wireframe,o=this.pageDataUtils.getPageData();tt(o);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new N,a=V(M((new F).subtractVectors(this.cursorPoint,t),(new F).subtractVectors(this.cursorPoint.add(i),t))*E,3);e.z=a,this.rotationAngle+=a,c=B(n)+this.rotationAngle*_,s.forEach(t=>{this.pageDataUtils.rotateItem(t.id,e)});break}case"translation":{const t=i.clone();if(this.enableAdsorption){const e=o.items.map(t=>s.find(e=>e.id===t.id)||0!==s.filter(e=>t.parentId&&t.parentId===e.id).length||!this.pageDataUtils.getItemEditEnable(t.id)||s.find(e=>e.parentId===t.id)?new W:this.pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),i=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new F(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);t.add(i).subtract(r)}const e=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(t).clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(e){const t=e.clone().subtract(this.lastWorldPosition);s.forEach(e=>{e.type!==g.ItemType.camera&&(t.x=V(t.x,5),t.y=V(t.y,5),t.z=V(t.z,5),this.pageDataUtils.moveItem(e.id,t))}),this.lastWorldPosition.copyFrom(e)}break}case"scale":{const t=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(this.cursorPoint.add(i).clone().subtract(this.pageDataUtils.getViewportLeftTopPosition()));if(i.length()&&t&&this.scaleParam){const{corner:e,center:i,shift:r,lastScalar:a}=this.scaleParam,n=this.pageDataUtils.getSelectedItems()[0]??void 0,o=this.pageDataUtils.getItemTransformById(n?.id??""),c=(new O).extractRotation(o.matrix).invert(),h=(new N).subtractVectors(e,i).applyMatrix(c),l=h.clone().multiply(a),p=t.clone().subtract(r).subtract(i).applyMatrix(c),m=new N(1,1,1),d=function(t){let e,i=0;return t.forEach((t,s)=>{if(0===s)e=Math.abs(t);else{const r=Math.abs(t);e<r&&(e=r,i=s)}}),i}([G(h.x,0)?1:Math.abs(p.x/h.x),G(h.y,0)?1:Math.abs(p.y/h.y)]),g=p.toArray()[d],u=l.toArray()[d];if(G(a.x,a.y)&&G(a.z,a.x)){const t=G(u,0)?1:Math.abs(g/u);m.set(t,t,t)}else if(0===d){m.x=G(u,0)?1:Math.abs(g/u);const t=h.y*g/h.x;m.y=G(l.y,0)?1:t/l.y;const e=h.z*g/h.x;m.z=G(l.z,0)?1:e/l.z}else if(1===d){m.y=G(u,0)?1:Math.abs(g/u);const t=h.x*g/h.y;m.x=G(l.x,0)?1:t/l.x;const e=h.z*g/h.y;m.z=G(l.z,0)?1:e/l.z}else{m.z=G(u,0)?1:Math.abs(g/u);const t=h.x*g/h.z;m.x=G(l.x,0)?1:t/l.x;const e=h.y*g/h.z;m.y=G(l.y,0)?1:e/l.y}const f=m.clone().subtract(new N(1,1,0)).divide(2).add(new N(1,1,.5)),y=i.clone().add((new N).subtractVectors(e,i).multiply(a.x));this.scaleParam.lastScalar.multiply(f);const x=i.clone().add((new N).subtractVectors(e,i).multiply(this.scaleParam.lastScalar.x)),w=(new N).subtractVectors(x,y);w.x=V(w.x,5),w.y=V(w.y,5),w.z=V(w.z,5),this.scaleParam.center.add(w),this.scaleParam.corner.add(w),s.forEach(t=>{this.pageDataUtils.scaleItem(t.id,f),this.pageDataUtils.moveItem(t.id,w)}),this.lastWorldPosition.copyFrom(t)}c=B(n);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new F(t.clientX,t.clientY),i=(new F).subtractVectors(e,this.lastPoint);this.cursorPoint.add(i);const s=this.wireframe;this.refreshTransformType(this.cursorPoint);const{activeType:r,interactiveDirection:a}=s;this.refreshCursorResult(r,B(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new F,this.lastPoint=new F}interruption(){this.active=!1,this.cursorResult.type="normal",this.adsorptionGizmo.clearAbsorptionResult()}refreshCursorResult(t,e=0){switch(t){case"scale":this.cursorResult={type:"scale",angle:(e+Math.PI/4)*E};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*E};break;case"translation":case"null":this.cursorResult={type:"normal",angle:0}}}refreshResults(){const t=this.wireframe.activeType;this.refreshWireframeBySelectedItems(),t!==this.wireframe.activeType&&this.refreshCursorResult(this.wireframe.activeType)}initInteractionPlane(t){const e=this.pageDataUtils.getSelectedItems();switch(this.wireframe.activeType){case"scale":{const i=1==e.length?e[0]:void 0;let s,r,a;if(i){const t=this.pageDataUtils.getItemTransformById(i.id);s=(new N).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new N).setFromMatrixPosition(t.matrix),a=(new K).setFromQuaternion((new H).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new N,center:new N,corner:new N,lastScalar:new N(1,1,1)},this.scaleParam.center=s??r;const n=this.pageDataUtils.getViewportLeftTopPosition();if(["scale"].includes(this.wireframe.activeType)&&this.wireframe.scaleCorner){const t=this.wireframe.scaleCorner.clone().subtract(n);this.scaleParam.corner=this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new N}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new N).subtract(this.scaleParam.corner);break}case"translation":case"rotation":this.pageDataUtils.interactionUtils.initInteractionPlane()}}refreshRenderObject(){this.graphics.clear(),this.nameText.text="";const{wireframeAlpha:t,wireframeColor:e,wireframeWidth:i,cornerFillColor:s,cornerLineWidth:r,cornerLineColor:a,cornerLineAlpha:n}=ci.config.gestureHandlerConfig.transformGizmoConfig;if(!this.wireframe.box.isEmpty()){this.graphics.lineStyle(i,e,t),this.wireframe.edges.forEach(t=>{this.graphics.drawLine(t)});const o=t=>{t.corners.forEach((e,i)=>{const s=new R(e,t.corners[(i+1)%4]);this.graphics.drawLine(s)})};if(this.wireframe.childrenBoxes.forEach(t=>{o(t)}),this.wireframe.cornerEnable&&(this.graphics.beginFill(s),this.graphics.lineStyle(r,a,n),this.wireframe.scaleCorners.forEach(t=>{this.graphics.drawCircle(t.center.x,t.center.y,t.radius)}),this.graphics.endFill()),this.infoType!==g.ItemType.base){const t=this.pageDataUtils.getSelectedItems()[0],e=t.type===g.ItemType.null?"编组":"图片",{size:i,rotation:s}=t.property,r=this.infoType===g.ItemType.sprite?this.imageSprite:this.nullSprite,a=this.wireframe.box.corners[3],n=s[2]*_;r.anchor.set(0,1),r.x=a.x,r.y=a.y-5,r.rotation=-n;const o=a.clone().add(new F(20,0)).rotateAround(a,-n),c=new F(0,4).rotateAround(new F,n);this.nameText.text=` ${e} ${i.map(t=>V(t,0)).join(" * ")}`,this.nameText.anchor.set(0,1),this.nameText.x=o.x+c.x,this.nameText.y=o.y-c.y,this.nameText.rotation=-n}}}refreshTransformType(t){this.activeType="null";let e=!0;if(this.wireframe.interactiveDirection=new F,this.wireframe.scaleCorner=void 0,this.wireframe.scaleEdgeCorners=void 0,e&&this.wireframe.totalBox.containsPoint(t)){if(this.wireframe.scaleEnabled)for(let i=0,s=this.wireframe.scaleCorners.length;i<s;i++){if(this.wireframe.scaleCorners[i].containsPoint(t)){e=!1,this.activeType="scale",this.wireframe.activeType="scale",this.wireframe.scaleCorner=this.wireframe.scaleCorners[i].center.clone(),this.wireframe.interactiveDirection.copyFrom(this.wireframe.scaleCorners[i].center).subtract(this.wireframe.box.getCenter());break}}if(e&&this.wireframe.box.containsPoint(t,!1)&&(e=!1,this.activeType="translation",this.wireframe.activeType="translation"),this.wireframe.rotationEnabled)for(let i=0,s=this.wireframe.scaleCorners.length;i<s;i++){if(this.wireframe.rotationCorners[i].containsPoint(t)&&e){e=!1,this.activeType="rotation",this.wireframe.activeType="rotation",this.wireframe.interactiveDirection.copyFrom(this.wireframe.rotationCorners[i].center).subtract(this.wireframe.box.getCenter());break}}}}refreshWireframeBySelectedItems(){const t=this.pageDataUtils.getSelectedItems(),e=new W;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],this.wireframe.rotationEnabled=1===t.length&&t[0].type!==g.ItemType.null,this.wireframe.scaleEnabled=1===t.length&&t[0].type!==g.ItemType.null,this.wireframe.cornerEnable=1===t.length&&t[0].type!==g.ItemType.null,t.length>1)t.forEach(t=>{if(this.pageDataUtils.getItemShow(t.id)){const i=this.pageDataUtils.getViewBoxById(t.id);e.union(i),this.wireframe.childrenBoxes.push((new W).copyFrom(i).expandByScalar(1))}}),this.wireframe.anchor=e.getCenter(),this.wireframe.interactive=!0;else if(1===t.length){const i=t[0];if(i.type!==g.ItemType.text&&this.pageDataUtils.getItemShow(i.id)){const t=this.pageDataUtils.getViewBoxById(i.id);e.copyFrom(t),this.wireframe.anchor=this.pageDataUtils.getItemViewAnchor(i.id)??e.getCenter(),this.wireframe.interactive=i.type!==g.ItemType.mesh&&this.pageDataUtils.getItemEditEnable(i.id)}}const i=e.isEmpty(),s=i?0:1,r=i?0:16;this.wireframe.activeType=t.length?this.wireframe.activeType:"null",this.wireframe.box.copyFrom(e).expandByScalar(s),this.wireframe.totalBox.copyFrom(e).expandByScalar(r);const a=this.wireframe.box.corners;a.forEach((t,e)=>{this.wireframe.edges.push(new R((new F).copyFrom(t),(new F).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:n,rotationCircleSize:o}=ci.config.gestureHandlerConfig.transformGizmoConfig;1===t.length&&this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new L(t,n));const e=(new F).subtractVectors(t,this.wireframe.box.getCenter()),i=(new F).copyFrom(this.wireframe.box.getCenter()).add((new F).copyFrom(e).normalize().multiply(e.length()+o-n));this.wireframe.rotationCorners.push(new L(i,o))})}setAdsorptionEnabled(t){this.enableAdsorption=t}};import{Graphics as rt}from"@pixi/graphics";var at=class extends A{constructor(){super(...arguments),c(this,"results",[]),c(this,"graphics",new rt),c(this,"absorptionResult",{}),c(this,"type","adsorption")}get interactive(){return ci.config.gestureHandlerConfig.adsorptionGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.adsorptionGizmoEnabled=t}preparationAction(){}getCursorState(){}preAction(){}action(){}cancelPreparation(){}actionKey(){}endActionKey(){}endAction(){}interruption(){}boxTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!this.interactive)return void console.warn("Adsorption gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if(e.isEmpty())return;const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),n=e.clone().translate(a),o=n.getCenter();this.absorptionResult={},i.forEach(t=>{if(t.isEmpty())return;t.corners.forEach(t=>{n.corners.forEach(e=>{this.getPointAbsorption(e,t,s,r)}),this.getPointAbsorption(o,t,s,r)});const e=t.getCenter();this.getPointAbsorption(o,e,s,r),n.corners.forEach(t=>{this.getPointAbsorption(t,e,s,r)})})}pointTranslationAdsorption(t,e,i,s=!0,r=!0){if(this.results=[],!this.interactive)return void console.warn("Adsorption is not opened, use #SDK.setAdsorptionConfig() open this feature.");const a=new F(this.absorptionResult?.x??0,this.absorptionResult?.y??0).add(t),n=e.clone().add(a);this.absorptionResult={},i.forEach(t=>{this.getPointAbsorption(n,t,s,r)})}getPointAbsorption(t,e,i=!0,s=!0){i&&Math.abs(t.x-e.x)<ci.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<ci.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"y")}refreshPointAbsorptionResult(t,e,i){const s=t[i]-e[i],r="x"===i?"xPoints":"yPoints";if(this.absorptionResult&&void 0===this.absorptionResult[i])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else if(Math.abs(s)-Math.abs(this.absorptionResult[i]??0)<=.005)if(Math.abs(Math.abs(s)-Math.abs(this.absorptionResult[i]??0))<.05&&s*(this.absorptionResult[i]??0)>0)if(void 0===this.absorptionResult[r])this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}];else{const i=this.absorptionResult[r].filter(e=>e.point.equals(t));void 0===i||0===i.length?this.absorptionResult[r]?.push({point:t,targets:[e]}):i[0]?.targets.push(e)}else this.absorptionResult[i]=s,this.absorptionResult[r]=[{point:t,targets:[e]}]}refreshResults(){if(void 0===this.absorptionResult)return;const{x:t,y:e,xPoints:i,yPoints:s}=this.absorptionResult,r=new F(t??0,e??0);void 0!==t&&void 0!==i&&i.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.x=t.x,i.y=Math.min(i.y,t.y),s.x=t.x,s.y=Math.max(s.y,t.y)}),this.results.push(new R(i,s))}),void 0!==e&&void 0!==s&&s.forEach(t=>{const e=t.point.clone().subtract(r),i=e.clone(),s=e.clone();t.targets.forEach(t=>{i.y=t.y,i.x=Math.min(i.x,t.x),s.y=t.y,s.x=Math.max(s.x,t.x)}),this.results.push(new R(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=ci.config.gestureHandlerConfig.adsorptionGizmoConfig;this.results.forEach(i=>{this.graphics.lineStyle(t,e),this.graphics.drawLine(i)})}getRenderObjects(){return this.interactive?(this.refreshResults(),this.refreshRenderObject(),[this.graphics]):[]}clearAbsorptionResult(){this.results=[],this.absorptionResult={}}},nt={};a(nt,{Application:()=>lt,utils:()=>ct});var ot={};a(ot,{Application:()=>lt,utils:()=>ct}),o(ot,ut),o(ot,ft),o(ot,yt),o(ot,xt),o(ot,wt),o(ot,vt),o(ot,It),o(ot,Pt),o(ot,Ct),o(ot,bt),o(ot,Dt),o(ot,zt);import"@pixi/polyfill";import*as ct from"@pixi/utils";import{InteractionManager as ht}from"@pixi/interaction";import{Application as lt}from"@pixi/app";import{Renderer as pt,BatchRenderer as mt}from"@pixi/core";import{AppLoaderPlugin as dt}from"@pixi/loaders";import{TickerPlugin as gt}from"@pixi/ticker";import*as ut from"@pixi/constants";import*as ft from"@pixi/core";import*as yt from"@pixi/display";import*as xt from"@pixi/graphics";import*as wt from"@pixi/loaders";import*as vt from"@pixi/interaction";import*as It from"@pixi/math";import*as Pt from"@pixi/runner";import*as Ct from"@pixi/sprite";import*as bt from"@pixi/text";import*as Dt from"@pixi/ticker";import*as zt from"@pixi/settings";ct.skipHello(),pt.registerPlugin("interaction",ht),pt.registerPlugin("batch",mt),lt.registerPlugin(gt),lt.registerPlugin(dt),ot.Graphics.prototype.drawBox=function(t){const e=t.getCorners();this.beginFill();for(let t=0;t<4;t++)this.moveTo(e[t].x,e[t].y),this.lineTo(e[(t+1)%4].x,e[(t+1)%4].y);this.endFill()},ot.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},ot.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof R)this.moveTo(t.start.x,t.start.y),this.lineTo(t.end.x,t.end.y);else for(let e=0;e<t.length-1;e++)this.moveTo(t[e].x,t[e].y),this.lineTo(t[e+1].x,t[e+1].y);this.endFill()},o(nt,ot);var St=class extends A{constructor(t){super(),c(this,"box",new W),c(this,"graphics",new nt.Graphics),c(this,"PageDataUtils"),c(this,"type","preference"),this.PageDataUtils=t}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.box=new W,!this.interactive)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if("editor"===ci.config.mode)return;const t=this.PageDataUtils.getPageData();v(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new F(s,r).multiply(i),n=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new W).setFromCenterAndSize(n,a)}}refreshRenderObjects(){if("editor"===ci.config.mode)return;const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:n}=ci.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new nt.Graphics;const{offsetWidth:o,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new W(new F(0,0),new F(o,this.box.min.y)),l=new W(new F(0,this.box.min.y),new F(this.box.min.x,c)),p=new W(new F(this.box.min.x,this.box.max.y),new F(o,c)),m=new W(new F(this.box.max.x,this.box.min.y),new F(o,this.box.max.y));if(this.graphics.beginFill(i,s),this.graphics.fillBox(h),this.graphics.fillBox(l),this.graphics.fillBox(p),this.graphics.fillBox(m),this.graphics.endFill(),r){const t=this.PageDataUtils.getViewProperty();if(t){const{size:e,safeArea:i,previewSafeAreas:s}=t,[r,o,c,h]=i,l=this.box.getSize(),p=r/e[1]*l.y,m=c/e[0]*l.x,d=h/e[0]*l.x,g=o/e[1]*l.y,{min:u,max:f}=this.box;this.graphics.beginFill(a,n);const y=new W(u,new F(f.x,u.y+p)),x=new W(new F(u.x,u.y+p),new F(u.x+m,f.y)),w=new W(new F(f.x-d,u.y+p),new F(f.x,f.y)),v=new W(new F(u.x+m,f.y-g),new F(f.x-d,f.y));this.graphics.fillBox(y),this.graphics.fillBox(x),this.graphics.fillBox(w),this.graphics.fillBox(v),this.graphics.endFill(),s.forEach(t=>{const{box:[i,s,r,a],color:n}=t,o=this.box.getSize(),c=new F(r/e[0]*o.x,a/e[1]*o.y),h=new F(i/e[0]*o.x+c.x/2,s/e[1]*o.y+c.y/2).add(u),l=(new W).setFromCenterAndSize(h,c),p=n?.[3]??.3,m=n?.slice(0,3)??[255,0,0],d=m[0]<<16|m[1]<<8|m[2];this.graphics.beginFill(d,p),this.graphics.fillBox(l),this.graphics.endFill()})}}this.graphics.lineStyle(t,e),this.graphics.drawBox(this.box)}getRenderObjects(){return ci.config.gestureHandlerConfig.preferenceGizmoEnabled&&"editor"!==ci.config.mode?(this.refreshRenderObjects(),[this.graphics]):[]}get interactive(){return ci.config.gestureHandlerConfig.preferenceGizmoEnabled}set interactive(t){ci.config.gestureHandlerConfig.preferenceGizmoEnabled=t}},At="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",Tt={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${At}/icons/cursor-rotate-32.svg`},circle:{type:"svg",content:"default",url:`${At}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${At}/icons/cursor-scale-32.svg`},hand:{type:"preset",content:"grab"},"active-hand":{type:"preset",content:"grabbing"},"text-rotation":{type:"svg",content:"default",url:"https://mdn.alipayobjects.com/huamei_ixsp8m/afts/img/A*R722QoloC44AAAAAKkAAAAgAev-aAQ/original"}};function kt(t,e="item doesn't exist"){if(null==t)throw new Error(e)}function _t(t,e="asserts failed"){if(!t)throw new Error(e)}function Et(t,e,...i){const s=e.reduce((t,e)=>t?`${t} ${e}`:e,""),r="color: #108ee9;";switch(t){case"error":console.error(`%c[${s}]`,r,...i);break;case"info":console.info(`%c[${s}]`,r,...i);break;case"debug":console.debug(`%c[${s}]`,r,...i);break;case"warn":console.warn(`%c[${s}]`,r,...i);break;default:console.log(`%c[${s}]`,r,...i)}}function Bt(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||"object"!=typeof t)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.toString()===e.toString();if(Array.isArray(t)!==Array.isArray(e))return!1;const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!Object.prototype.hasOwnProperty.call(e,s))return!1;if(!Bt(t[s],e[s]))return!1}return!0}var Mt=class extends A{constructor(t,e){super(),c(this,"result",{type:"invalid"}),c(this,"interactionParam",{type:"none"}),c(this,"graphics",new nt.Graphics),c(this,"isShiftDown",!1),c(this,"_isLockScale",!1),c(this,"_pageDataUtils"),c(this,"_eventEmitter"),c(this,"type","picture-cut"),c(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return ci.config.gestureHandlerConfig.pictureCutGizmoEnabled}set interactive(t){t!==ci.config.gestureHandlerConfig.pictureCutGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture cut gizmo can not open."):ci.config.gestureHandlerConfig.pictureCutGizmoEnabled=t)}get isLockScale(){return this._isLockScale}set isLockScale(t){t!==this.isLockScale&&(this._isLockScale=t)}preparationAction(t){if(!this.interactive)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),"picture-cut"}preAction(t,e){if(this.interactive&&"none"!==this.interactionParam.type)return"picture-cut"}action(t){var e;if(!this.interactive||"none"===this.interactionParam.type||"invalid"===this.result.type)return;const i=new F(t.clientX,t.clientY),{startMouse:s,box:r}=this.interactionParam,a=(new F).subtractVectors(i,s),{itemBox:{min:n,max:o}}=this.result;switch(this.interactionParam.type){case"move":{const{min:t,max:e}=r,i=n.x-t.x,s=o.x-e.x,c=n.y-t.y,h=o.y-e.y;a.x=Math.min(Math.max(a.x,i),s),a.y=Math.min(Math.max(a.y,c),h);const l=r.clone().translate(a);this.result.cutBox.copyFrom(l),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}case"scale":{const{startCorner:t,anchor:i}=this.interactionParam,s=new F;if(s.x=Math.min(Math.max(t.x+a.x,n.x),o.x),s.y=Math.min(Math.max(t.y+a.y,n.y),o.y),this.isShiftDown||this.isLockScale){const{x:a,y:c}=this.result.cutBox.getSize(),{x:h,y:l}=r.getSize();if((e=this.interactionParam).lockedAspect??(e.lockedAspect=a/c),Math.abs(s.x-i.x)/h>Math.abs(s.y-i.y)/l){const e=Math.abs(s.x-i.x)/this.interactionParam.lockedAspect;s.y=(t.y-i.y)/Math.abs(t.y-i.y)*e+i.y,s.y=Math.min(Math.max(s.y,n.y),o.y)}else{const e=Math.abs(s.y-i.y)*this.interactionParam.lockedAspect;s.x=(t.x-i.x)/Math.abs(t.x-i.x)*e+i.x,s.x=Math.min(Math.max(s.x,n.x),o.x)}}const c=(s.x-i.x)/(t.x-i.x),h=(s.y-i.y)/(t.y-i.y),l=new F(c,h);this.result.cutBox.copyFrom(r.clone().scaleByCenter(l,i)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}case"direction-scale":{const{index:t}=this.interactionParam,e=r.corners[t].clone();t%2==0?(a.x=Math.min(Math.max(e.x+a.x,n.x),o.x)-e.x,a.y=0):(a.x=0,a.y=Math.min(Math.max(e.y+a.y,n.y),o.y)-e.y);const i=r.corners.map((e,i)=>[t,(t+1)%4].includes(i)?e.clone().add(a):e.clone());this.result.cutBox.copyFrom((new W).setFromVec2Array(i)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),"picture-cut"}interruption(){this.interactionParam={type:"none"}}actionKey(t){this.isShiftDown=t.shiftKey}endActionKey(t){this.isShiftDown=t.shiftKey,"lockedAspect"in this.interactionParam&&delete this.interactionParam.lockedAspect}cancelPreparation(){this.interactionParam={type:"none"}}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(kt(t,"You must call SDK#run() first"),1!==t.activeData.selectedItems.length)console.warn("Picture Cut Gizmo can edit one picture at a time.");else if("invalid"===this.result.type){const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]);this.result={type:"valid",itemBox:e.clone(),cutBox:e.clone()}}else{const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]),i=e.getCenter().subtract(this.result.itemBox.getCenter()),s=e.getSize().x/this.result.itemBox.getSize().x;this.result.itemBox.scale(s),this.result.cutBox.scale(s),this.result.itemBox.translate(i),this.result.cutBox.translate(i)}}else this.result={type:"invalid"}}refreshRenderObjects(){if(this.graphics.clear(),!this.interactive||"invalid"===this.result.type)return;const{maskColor:t,maskAlpha:e,cutBoxLineWidth:i,cutBoxLineColor:s,cutBoxLineAlpha:r,itemBoxLineWidth:a,itemBoxLineColor:n,itemBoxLineAlpha:o,cutBoxCornerRadius:c,cutBoxCornerFillColor:h,cutBoxCornerLineWidth:l,cutBoxCornerLineColor:p,cutBoxCornerLineAlpha:m}=ci.config.gestureHandlerConfig.pictureCutGizmoConfig,{cutBox:d,itemBox:g}=this.result,{min:u,max:f}=d,{min:y,max:x}=g,w=new W(y.clone(),new F(x.x,u.y)),v=new W(new F(y.x,u.y),new F(u.x,x.y)),I=new W(new F(f.x,u.y),new F(x.x,f.y)),P=new W(new F(u.x,f.y),x.clone());this.graphics.beginFill(t,e),this.graphics.fillBox(w),this.graphics.fillBox(v),this.graphics.fillBox(I),this.graphics.fillBox(P),this.graphics.endFill(),this.graphics.lineStyle(a,n,o),this.graphics.drawBox(g),this.graphics.lineStyle(i,s,r),this.graphics.drawBox(d),this.graphics.beginFill(h),this.graphics.lineStyle(l,p,m),d.corners.forEach(t=>{this.graphics.drawCircle(t.x,t.y,c)}),this.graphics.endFill()}refreshCursorResult(t,e=0){switch(t){case"scale":case"direction-scale":this.cursorResult={type:"scale",angle:e};break;case"move":case"none":this.cursorResult={type:"normal",angle:0}}}getRenderObjects(){return this.interactive?(this.refreshRenderObjects(),[this.graphics]):[]}refreshInteractionType(t,e){if(this.interactionParam={type:"none"},!this.interactive||"invalid"===this.result.type)return;const{cutBox:i}=this.result;let s=!1,r=0;i.corners.forEach((a,n)=>{s||a.distanceTo(t)<ci.config.gestureHandlerConfig.pictureCutGizmoConfig.scaleInteractionDistance&&(s=!0,this.interactionParam={type:"scale",box:i.clone(),startMouse:e,startCorner:a.clone(),anchor:i.corners[(n+2)%4]},r=Math.PI/2*n)}),i.corners.forEach((a,n)=>{if(s)return;const o=new R(a.clone(),i.corners[(n+1)%4]),c=t.distanceToLine(o);if(c.d>=0&&c.d<=8&&c.t>=0&&c.t<=1){s=!0;const t=o.at(c.t);this.interactionParam={type:"direction-scale",index:n,point:t,box:i.clone(),startMouse:e},r=Math.PI/2*n+Math.PI/4}}),i.containsPoint(t)&&!s&&(this.interactionParam={type:"move",point:t.clone(),box:i.clone(),startMouse:e},s=!0),this.refreshCursorResult(this.interactionParam.type,r*E)}getCutInfo(){if(this.interactive&&"invalid"!==this.result.type)return{cutBox:this.result.cutBox,itemBox:this.result.itemBox}}setCutBox(t,e){if(!this.interactive||"invalid"===this.result.type)return;const{itemBox:{min:i,max:s}}=this.result;return this.result.cutBox.set(new F(Math.max(i.x,t.x),Math.max(i.y,t.y)),new F(Math.min(s.x,e.x),Math.min(s.y,e.y))),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone()),this.result.cutBox.clone()}};import{Graphics as Vt}from"@pixi/graphics";import{Sprite as Gt}from"@pixi/sprite";import{DEG2RAD as Ut}from"@galacean/effects-plugin-model";var Ft=class extends A{constructor(t,e,i,s,r){super(),c(this,"type","text"),c(this,"_eventEmitter"),c(this,"textAreaElement"),c(this,"graphics",new Vt),c(this,"_pageDataUtils"),c(this,"result"),c(this,"interactionParam"),c(this,"_adsorptionGizmo"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"rotationSprite",new Gt),c(this,"_selectorGizmo"),c(this,"handleInput",async t=>{const e=t.target;await this._pageDataUtils.changeItemProperty({itemId:this._pageDataUtils.getSelectedItems()[0].id,type:g.ItemType.text,propertyName:"text",propertyValue:e.value}),this._eventEmitter.emit("textInput",{text:e.value,fontFamily:e.style.fontFamily})}),c(this,"handleBlur",()=>{this.interactionParam.type="scale",this.textAreaElement.style.display="none",this.textAreaElement.removeEventListener("input",this.handleInput),this.textAreaElement.removeEventListener("blur",this.handleBlur)}),this._pageDataUtils=t,this._adsorptionGizmo=e,this._selectorGizmo=i,this._eventEmitter=s,this.textAreaElement=document.createElement("textarea"),this.textAreaElement.style.display="none",r?.appendChild(this.textAreaElement),function(t,e,i){const s=i.replace(/&/g,`.${e}`),r=document.createElement("style");r.textContent=`\n .${e} {\n ${s}\n }\n `,document.head.appendChild(r),t.classList.add(e)}(this.textAreaElement,"text-gizmo-custom-style","\n word-break: break-all;\n position: absolute;\n border: none;\n margin: 0;\n padding: 0;\n outline: none !important;\n overflow: hidden;\n resize: none;\n display: none;\n background: transparent;\n opacity: .8;\n field-sizing: content;\n &::selection {\n background: rgba(221, 63, 23, .5);\n }\n -webkit-text-fill-color: transparent;\n text-fill-color: transparent;\n"),this.result={type:"empty"},this.interactionParam={active:!1,type:"none",anchor:new F,lastPoint:new F,startPoint:new F,lastWorldPosition:new N}}get interactive(){return ci.config.gestureHandlerConfig.textGizmoEnbaled}set interactive(t){ci.config.gestureHandlerConfig.textGizmoEnbaled=t}preparationAction(t){if(!this.interactive)return void console.warn("Text gizmo is not opened, use #SDK.openTextGizmo() open this feature.");if("empty"===this.result.type)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);if(this.refreshInteractionParam(e,i),this.refreshCursorResult(),"none"!==this.interactionParam.type){const e="translation"===this.interactionParam.type?this._selectorGizmo.preparationAction(t,"text"):this.type;return this.interactionParam.active="text"===e,this.interactionParam.active?e:void 0}}preAction(t,e){if(1!==t.buttons)return this.type;const{offsetX:i,offsetY:s}=t,r=new F(i,s);if(e){if("empty"===this.result.type||this.result.box.containsPoint(r))this.interactionParam.type="edit";else if("none"===this.interactionParam.type)return this.result={type:"empty"},void this._pageDataUtils.clearSelectedItems(!0)}else if("empty"===this.result.type||this.result.box.containsPoint(r)){const t=r.subtract(this._pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(t),this.interactionParam.lastWorldPosition=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new N,this.refreshCursorResult()}else if("edit"===this.interactionParam.type)this.interactionParam.type="none";else if("none"===this.interactionParam.type)return void(this.result={type:"empty"});return this.type}action(t){if(!this.interactive)return void console.warn("Text gizmo is not opened, use #SDK.setTextConfig() open this feature.");if("edit"===this.interactionParam.type||"empty"===this.result.type)return;if(!this.interactionParam.active){this.interactionParam.active=!0,this.interactionParam.type="translation",this.interactionParam.lastPoint=new F(t.clientX,t.clientY),this.interactionParam.startPoint=new F(t.offsetX,t.offsetY);const e=new F(t.offsetX,t.offsetY).subtract(this._pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.interactionParam.lastWorldPosition=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new N}const e=new F(t.clientX,t.clientY),{type:i,lastPoint:s,startPoint:r,anchor:a}=this.interactionParam,n=(new F).subtractVectors(e,s),o=this._pageDataUtils.getSelectedItems();switch(i){case"rotation":{const t=new N,e=V(M((new F).subtractVectors(r,a),(new F).subtractVectors(r.add(n),a))*E,3);t.z=e,o.forEach(e=>{this._pageDataUtils.rotateItem(e.id,t)});break}case"translation":{const t=n.clone();if(this._adsorptionGizmo.interactive){const e=this._pageDataUtils.getPageData();v(e);const i=e.items.map(t=>o.find(e=>e.id===t.id)||0!==o.filter(e=>t.parentId&&t.parentId===e.id).length||!this._pageDataUtils.getItemEditEnable(t.id)||o.find(e=>e.parentId===t.id)?new W:this._pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),s=new F(this._adsorptionGizmo.absorptionResult.x??0,this._adsorptionGizmo.absorptionResult.y??0);this._adsorptionGizmo.boxTranslationAdsorption(t,this.result.box,i);const r=new F(this._adsorptionGizmo.absorptionResult.x??0,this._adsorptionGizmo.absorptionResult.y??0);t.add(s).subtract(r)}const e=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(r.add(t).clone().subtract(this._pageDataUtils.getViewportLeftTopPosition()));if(e){const t=e.clone().subtract(this.interactionParam.lastWorldPosition);o.forEach(e=>{e.type!==g.ItemType.camera&&(t.x=V(t.x,5),t.y=V(t.y,5),t.z=V(t.z,5),this._pageDataUtils.moveItem(e.id,t))}),this.interactionParam.lastWorldPosition.copyFrom(e)}break}case"scale":{const t=r.clone(),e=r.clone().add(n);if(n.length()){const i=(new F).subtractVectors(t,a),s=(new F).subtractVectors(e,a),n=Math.max(s.dot(i)/i.length(),1),c=i.length(),h=(n/c-1)/2+1,l=a.clone().add(i.clone().normalize().scale(c*h)),p=(new F).subtractVectors(l,t);r.add(p);const m=this._pageDataUtils.interactionUtils.getWorldSizeByViewSize(p);m.x=V(m.x,5),m.y=V(m.y,5),m.z=V(m.z,5),o.forEach(t=>{this._pageDataUtils.moveItem(t.id,m)}),o.forEach(t=>{this._pageDataUtils.scaleTextItem(t.id,h)})}break}}this.refreshCursorResult(),this.interactionParam.lastPoint.copyFrom(e)}endAction(t){const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this._adsorptionGizmo.clearAbsorptionResult(),this.refreshInteractionParam(e,i),this.refreshCursorResult(),this.type}interruption(){return this.interactionParam.type="none",this._adsorptionGizmo.clearAbsorptionResult(),this.type}actionKey(t){}endActionKey(t){}cancelPreparation(){}refreshResults(){if(!this.interactive)return;const t=this._pageDataUtils.getPageData()?.activeData?.selectedItems,e=this._pageDataUtils.getViewItemById(t?.[0]);if(!t||1!==t.length||e?.type!==g.ItemType.text)return void(this.result={type:"empty"});const i=this._pageDataUtils.getViewBoxById(t[0]);if(i.isEmpty())this.result={type:"empty"};else{const t=[new R(i.corners[0],i.corners[1]).at(.5),new R(i.corners[2],i.corners[3]).at(.5)],s=new R(i.getCenter(),new R(i.corners[0],i.corners[3]).at(.5)),r=s.at((s.length()+22)/s.length());this.result={type:"valid",box:i.clone(),scaleCorners:t,rotationCorner:r,rotation:-e.property.rotation[2]*Ut}}}refreshInteractionParam(t,e){if("empty"===this.result.type)return this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new F,this.interactionParam.startPoint=new F,void(this.interactionParam.lastWorldPosition=new N);if("edit"===this.interactionParam.type)return;const i=this.result.box.getCenter();if(t.distanceTo(this.result.rotationCorner)<14)return this.interactionParam.active=!0,this.interactionParam.type="rotation",this.interactionParam.anchor=i,this.interactionParam.lastPoint=e.clone(),this.interactionParam.startPoint=this.result.rotationCorner.clone(),void(this.interactionParam.lastWorldPosition=new N);const s=this.result.scaleCorners.find(e=>e.distanceTo(t)<10);return s?(this.interactionParam.active=!0,this.interactionParam.type="scale",this.interactionParam.anchor=i,this.interactionParam.lastPoint=e.clone(),this.interactionParam.startPoint=s.clone(),void(this.interactionParam.lastWorldPosition=new N)):this.result.box.containsPoint(t,!1)?(this.interactionParam.active=!0,this.interactionParam.type="translation",this.interactionParam.lastPoint=e.clone(),this.interactionParam.startPoint=t.clone(),void(this.interactionParam.lastWorldPosition=new N)):(this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new F,this.interactionParam.startPoint=new F,void(this.interactionParam.lastWorldPosition=new N))}refreshCursorResult(){const t=(new F).subtractVectors(this.interactionParam.startPoint,this.interactionParam.anchor).angle();switch(this.interactionParam.type){case"edit":case"none":case"translation":this.cursorResult={type:"normal",angle:0};break;case"scale":this.cursorResult={type:"scale",angle:(t+Math.PI/4)*E};break;case"rotation":this.cursorResult={type:"rotation",angle:(t+Math.PI/4)*E}}}getRenderObjects(){const t=[];if(!this.interactive||"empty"===this.result.type)return[];this.graphics.clear();const{box:e,scaleCorners:i,rotationCorner:s,rotation:r}=this.result,{boxLineWidth:a,boxLineColor:n,scaleCornerRadius:o,rotationCornerWidth:c,scaleCornerFillColor:h,scaleCornerStrokeWidth:l,scaleCornerStrokeColor:p}=ci.config.gestureHandlerConfig.textGizmoConfig;if(this.graphics.lineStyle(a,n),this.graphics.drawBox(e),"edit"!==this.interactionParam.type)i.forEach(t=>{this.graphics.lineStyle(l,p),this.graphics.beginFill(h),this.graphics.drawCircle(t.x,t.y,o),this.graphics.endFill()}),this.rotationSprite.width=c,this.rotationSprite.height=c,this.rotationSprite.anchor.set(.5,.5),this.rotationSprite.x=s.x,this.rotationSprite.y=s.y,this.rotationSprite.rotation=r,t.push(this.rotationSprite);else if("edit"===this.interactionParam.type&&"none"===this.textAreaElement.style.display){const t=this._pageDataUtils.getSelectedItems(),i=this._pageDataUtils.interactionUtils.viewportParam,s=t[0],r=s?.property,a=e.clone().rotate(r.rotation[2]*Ut),n=a.min.clone(),o=a.getSize();this.textAreaElement.value=r.text??"",this.textAreaElement.style.fontFamily=r.fontFamily,this.textAreaElement.style.fontSize=r.fontSize*i.scale+"px",this.textAreaElement.style.fontWeight=r.fontWeight,this.textAreaElement.style.color=`rgba(${r.textColor.join(",")})`,this.textAreaElement.style.display="block",this.textAreaElement.style.wordBreak="break-all",this.textAreaElement.style.whiteSpace="pre-wrap",this.textAreaElement.style.overflowWrap="break-word",this.textAreaElement.style.left=`${n.x}px`,this.textAreaElement.style.top=`${n.y}px`,this.textAreaElement.style.width=`${o.x}px`,this.textAreaElement.style.height="auto",this.textAreaElement.style.lineHeight=`${r.lineHeight}px`,this.textAreaElement.style.transformOrigin="center center",this.textAreaElement.style.paintOrder="stroke fill",void 0!==r.rotation[2]&&(this.textAreaElement.style.transform=`\n rotateZ(${-r.rotation[2]}deg)\n `),this.textAreaElement.addEventListener("input",this.handleInput),this.textAreaElement.addEventListener("blur",this.handleBlur),window.setTimeout(()=>{this.textAreaElement.focus()},50)}else if("edit"===this.interactionParam.type&&"block"===this.textAreaElement.style.display){const t=this._pageDataUtils.getSelectedItems(),i=this._pageDataUtils.interactionUtils.viewportParam,s=t[0],r=s?.property,a=e.clone().rotate(r.rotation[2]*Ut),n=a.min.clone(),o=a.getSize();this.textAreaElement.style.left=`${n.x}px`,this.textAreaElement.style.top=`${n.y}px`,this.textAreaElement.style.width=`${o.x}px`,this.textAreaElement.style.fontSize=r.fontSize*i.scale+"px",r.rotation[2]&&(this.textAreaElement.style.transform=`\n rotateZ(${-r.rotation[2]}deg)\n `)}return t.push(this.graphics),t}initInteractionPlane(t){switch(this.interactionParam.type){case"scale":case"translation":case"rotation":this._pageDataUtils.interactionUtils.initInteractionPlane()}}};import{Texture as Rt}from"@pixi/core";var Wt=class extends A{constructor(t){super(),c(this,"_pageDataUtils"),c(this,"_config",{}),c(this,"type","mask"),c(this,"cursorResult",{type:"normal",angle:0}),c(this,"result",{status:"init",lines:[]}),c(this,"graphics",new nt.Graphics),c(this,"linesMaskGraphics",new nt.Graphics),c(this,"rectMaskGraphics",new nt.Graphics),this._pageDataUtils=t}get interactive(){return ci.config.gestureHandlerConfig.maskGizmoEnabled}set interactive(t){t!==ci.config.gestureHandlerConfig.maskGizmoEnabled&&(t||(this.result.status="init"),ci.config.gestureHandlerConfig.maskGizmoEnabled=t)}get config(){return{...ci.config.gestureHandlerConfig.maskGizmoConfig,...this._config}}set config(t){this._config={...this._config,...t}}initialize(){}preparationAction(t){if(this.interactive)return this.result.point=new F(t.offsetX,t.offsetY),this.type}preAction(t){if(this.interactive)return this.result.point=new F(t.offsetX,t.offsetY),this.result.lines.push([]),this.type}action(t){if(!this.interactive||"init"===this.result.status)return;const e=new F(t.offsetX,t.offsetY);this.result.point=e,this.result.lines[this.result.lines.length-1]?.push(e)}endAction(){if(this.interactive)return this.type}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(kt(t,"You must call SDK#run() first"),1!==t.activeData.selectedItems.length)console.warn("Mask Gizmo can edit one picture at a time.");else{if("init"===this.result.status){const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]);this.result={status:"done",box:e.clone(),lines:[]}}else{const e=this.result.box,i=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]),s=i.getCenter().subtract(e.getCenter()),r=i.getSize().x/e.getSize().x;e.scale(r),e.translate(s)}this.refreshCursorResult()}}else this.result={status:"init",lines:[]}}getRenderObjects(){return this.interactive?this.refreshRenderObjects():[]}refreshRenderObjects(){if(this.graphics.clear(),this.linesMaskGraphics.clear(),this.rectMaskGraphics.clear(),!this.interactive||"init"===this.result.status)return[];const{brushColor:t,brushAlpha:e,boxLineWidth:i,boxLineColor:s,boxLineAlpha:r}=this.config,a=this.result.box,{min:n,max:o}=a,c=new W(new F(n.x,n.y),new F(o.x,n.y)),h=new W(new F(n.x,n.y),new F(n.x,o.y)),l=new W(new F(o.x,n.y),new F(o.x,n.y)),p=new W(new F(n.x,o.y),new F(o.x,o.y));this.graphics.fillBox(c),this.graphics.fillBox(h),this.graphics.fillBox(l),this.graphics.fillBox(p),this.graphics.lineStyle(i,s,r),this.graphics.drawBox(a),this.graphics.endFill();for(let t=0;t<this.result.lines.length;t++){0===t&&this.linesMaskGraphics.lineStyle({width:this.config.brushSize,color:0,cap:nt.LINE_CAP.ROUND,join:nt.LINE_JOIN.ROUND,alignment:.5});const e=this.result.lines[t];if(e)for(let t=0;t<e.length;t++){const i=e[t];i&&(0===t?this.linesMaskGraphics.moveTo(i.x,i.y):this.linesMaskGraphics.lineTo(i.x,i.y))}}return this.linesMaskGraphics.endFill(),this.rectMaskGraphics.beginFill(t,e),this.rectMaskGraphics.drawRect(a.min.x,a.min.y,a.max.x-a.min.x,a.max.y-a.min.y),this.rectMaskGraphics.endFill(),this.rectMaskGraphics.mask=this.linesMaskGraphics,[this.graphics,this.linesMaskGraphics,this.rectMaskGraphics]}refreshCursorResult(){const{point:t,box:e}=this.result;this.cursorResult={type:"normal",angle:0},t&&e&&t.x>=e.min.x&&t.x<=e.max.x&&t.y>=e.min.y&&t.y<=e.max.y&&(this.cursorResult={type:"circle",angle:0})}clearMask(){this.result.lines=[]}getMask(){if(0===this.result.lines.length)return null;const t=this.rectMaskGraphics.getBounds(),e=new nt.Renderer({width:Math.ceil(t.width),height:Math.ceil(t.height),backgroundColor:16777215}),i=new nt.Container,s=this.rectMaskGraphics.clone();s.beginFill(this.config.maskColor),s.position.set(-t.x,-t.y),s.drawRect(t.x,t.y,t.width,t.height),s.endFill(),i.addChild(s);const r=this.linesMaskGraphics.clone();s.mask=r,r.position.set(-t.x,-t.y),i.addChild(r),e.render(i);const a=e.view.toDataURL("image/png");return e.destroy(!0),a}},Lt=class extends A{constructor(t){super(),c(this,"type","loading"),c(this,"_pageDataUtils"),c(this,"_idMap",new Map),c(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t}addId(t){const e=this._pageDataUtils.getViewBoxById(t);"string"==typeof t&&(this._idMap.set(t,{status:"init",box:e,graphics:new nt.Graphics,ticker:new nt.Ticker}),this._pageDataUtils.addLoadingItems([t]),this._pageDataUtils.removeSelectedItems([t]))}deleteId(t){const e=this._idMap.get(t);if(e){const{graphics:i,ticker:s}=e;i.clear(),s.destroy(),this._idMap.delete(t),this._pageDataUtils.removeLoadingItems([t])}}initialize(){}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(0!==this._idMap.size)for(const t of this._idMap.keys()){const e=this._idMap.get(t);if(e){const{box:i}=e,s=this._pageDataUtils.getViewBoxById(t),r=s.getCenter().subtract(i.getCenter()),a=s.getSize().x/i.getSize().x;i.scale(a),i.translate(r)}}}getRenderObjects(){return 0===this._idMap.size?[]:this.refreshRenderObjects()}refreshRenderObjects(){if(0===this._idMap.size)return[];const t=[];for(const e of this._idMap.keys()){const i=this._idMap.get(e);if(!i)continue;if(t.push(i.graphics),"done"===i.status){i.ticker.update();continue}i.status="done";const{min:s,max:r}=i.box;let a=.006,n=.5;i.ticker.add(()=>{n>.6?a=-.003:n<.4&&(a=.006),n+=a,i.graphics.clear(),i.graphics.beginFill(0,n),i.graphics.drawRect(s.x,s.y,r.x-s.x,r.y-s.y),i.graphics.endFill()}),i.ticker.start()}return t}},Ht=class extends A{constructor(t,e){super(),c(this,"result",{type:"invalid"}),c(this,"interactionParam",{type:"none"}),c(this,"graphics",new nt.Graphics),c(this,"isShiftDown",!1),c(this,"_isLockScale",!1),c(this,"_pageDataUtils"),c(this,"_eventEmitter"),c(this,"type","picture-expand"),c(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return ci.config.gestureHandlerConfig.pictureExpandGizmoEnabled}set interactive(t){t!==ci.config.gestureHandlerConfig.pictureExpandGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture expand gizmo can not open."):ci.config.gestureHandlerConfig.pictureExpandGizmoEnabled=t)}get isLockScale(){return this._isLockScale}set isLockScale(t){t!==this.isLockScale&&(this._isLockScale=t)}preparationAction(t){if(!this.interactive)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),this.type}preAction(t,e){if(this.interactive&&"none"!==this.interactionParam.type)return this.type}action(t){var e;if(!this.interactive||"none"===this.interactionParam.type||"invalid"===this.result.type)return;const i=new F(t.clientX,t.clientY),{startMouse:s,box:r}=this.interactionParam,a=(new F).subtractVectors(i,s),{itemBox:{min:n,max:o}}=this.result;switch(this.interactionParam.type){case"move":{const{min:t,max:e}=r,i=o.x-e.x,s=n.x-t.x,c=o.y-e.y,h=n.y-t.y;a.x=Math.min(Math.max(a.x,i),s),a.y=Math.min(Math.max(a.y,c),h);const l=r.clone().translate(a);this.result.expandBox.copyFrom(l),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}case"scale":{const{index:t}=this.interactionParam,{min:i,max:s}=r,c=r.corners[t],h=r.corners[(t+2)%4],l=new F(c.x+a.x,c.y+a.y);if(c.x>=s.x?l.x=Math.max(l.x,o.x):c.x<=i.x?l.x=Math.min(l.x,n.x):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.x=Math.abs(l.x-i.x)>Math.abs(l.x-s.x)?s.x:i.x),c.y>=s.y?l.y=Math.max(l.y,o.y):c.y<=i.y?l.y=Math.min(l.y,n.y):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.y=Math.abs(l.y-i.y)>Math.abs(l.y-s.y)?s.y:i.y),this.isShiftDown||this.isLockScale){const{x:t,y:a}=this.result.expandBox.getSize(),{x:p,y:m}=r.getSize();if((e=this.interactionParam).lockedAspect??(e.lockedAspect=t/a),Math.abs(l.x-h.x)/p>Math.abs(l.y-h.y)/m){const t=Math.abs(l.x-h.x)/this.interactionParam.lockedAspect;l.y=(c.y-h.y)/Math.abs(c.y-h.y)*t+h.y,c.y>=s.y?l.y=Math.max(l.y,o.y):c.y<=i.y?l.y=Math.min(l.y,n.y):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.y=Math.abs(l.y-i.y)>Math.abs(l.y-s.y)?s.y:i.y)}else{const t=Math.abs(l.y-h.y)*this.interactionParam.lockedAspect;console.log("result width is ",t),l.x=(c.x-h.x)/Math.abs(c.x-h.x)*t+h.x,c.x>=s.x?l.x=Math.max(l.x,o.x):c.x<=i.x?l.x=Math.min(l.x,n.x):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),l.x=Math.abs(l.x-i.x)>Math.abs(l.x-s.x)?s.x:i.x)}}this.result.expandBox.copyFrom((new W).setFromVec2ArrayWithOutCorners([l,h])),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}case"direction-scale":{const{index:t,point:e}=this.interactionParam,i=r.corners[t].clone();e.x>=o.x?(a.x=Math.max(r.corners[t].x+a.x,o.x)-i.x,a.y=0):e.x<=n.x&&(a.x=Math.min(r.corners[t].x+a.x,n.x)-i.x,a.y=0),e.y>=o.y?(a.y=Math.max(r.corners[t].y+a.y,o.y)-i.y,a.x=0):e.y<=n.y&&(a.y=Math.min(r.corners[t].y+a.y,n.y)-i.y,a.x=0);const s=r.corners.map((e,i)=>[t,(t+1)%4].includes(i)?e.clone().add(a):e.clone());this.result.expandBox.copyFrom((new W).setFromVec2Array(s)),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new F(t.offsetX,t.offsetY),i=new F(t.clientX,t.clientY);return this.refreshInteractionType(e,i),this.type}interruption(){this.interactionParam={type:"none"}}actionKey(t){this.isShiftDown=t.shiftKey}endActionKey(t){this.isShiftDown=t.shiftKey,"lockedAspect"in this.interactionParam&&delete this.interactionParam.lockedAspect}cancelPreparation(){this.interactionParam={type:"none"}}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(kt(t,"You must call SDK#run() first"),1!==t.activeData.selectedItems.length)console.warn("Picture Expand Gizmo can edit one picture at a time.");else if("invalid"===this.result.type){const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]);this.result={type:"valid",itemBox:e.clone(),expandBox:e.clone()}}else{const e=this._pageDataUtils.getViewBoxById(t.activeData.selectedItems[0]),i=e.getCenter().subtract(this.result.itemBox.getCenter()),s=e.getSize().x/this.result.itemBox.getSize().x;this.result.itemBox.scale(s),this.result.expandBox.scale(s),this.result.itemBox.translate(i),this.result.expandBox.translate(i)}}else this.result={type:"invalid"}}refreshRenderObjects(){if(this.graphics.clear(),!this.interactive||"invalid"===this.result.type)return;const{maskColor:t,maskAlpha:e,expandBoxLineWidth:i,expandBoxLineColor:s,expandBoxLineAlpha:r,expandBoxCornerRadius:a,expandBoxCornerFillColor:n,expandBoxCornerLineWidth:o,expandBoxCornerLineColor:c,expandBoxCornerLineAlpha:h}=ci.config.gestureHandlerConfig.pictureExpandGizmoConfig,{expandBox:l}=this.result;this.graphics.beginFill(t,e),this.graphics.fillBox(l),this.graphics.endFill(),this.graphics.lineStyle(i,s,r),this.graphics.drawBox(l),this.graphics.beginFill(n),this.graphics.lineStyle(o,c,h),l.corners.forEach(t=>{this.graphics.drawCircle(t.x,t.y,a)}),this.graphics.endFill()}refreshCursorResult(t,e=0){switch(t){case"scale":case"direction-scale":this.cursorResult={type:"scale",angle:e};break;case"move":case"none":this.cursorResult={type:"normal",angle:0}}}getRenderObjects(){return this.interactive?(this.refreshRenderObjects(),[this.graphics]):[]}refreshInteractionType(t,e){if(this.interactionParam.type="none",!this.interactive||"invalid"===this.result.type)return;const{expandBox:i}=this.result;let s=!1,r=0;i.corners.forEach((a,n)=>{s||a.distanceTo(t)<ci.config.gestureHandlerConfig.pictureExpandGizmoConfig.scaleInteractionDistance&&(s=!0,this.interactionParam={type:"scale",index:n,box:i.clone(),startMouse:e},r=Math.PI/2*n)}),i.corners.forEach((a,n)=>{if(s)return;const o=new R(a.clone(),i.corners[(n+1)%4]),c=t.distanceToLine(o);if(c.d>=0&&c.d<=8&&c.t>=0&&c.t<=1){s=!0;const t=o.at(c.t);this.interactionParam={type:"direction-scale",index:n,point:t,box:i.clone(),startMouse:e},r=Math.PI/2*n+Math.PI/4}}),i.containsPoint(t)&&!s&&(this.interactionParam={type:"move",point:t.clone(),box:i.clone(),startMouse:e},s=!0),this.refreshCursorResult(this.interactionParam.type,r*E)}getExpandInfo(){if(this.interactive&&"invalid"!==this.result.type)return{expandBox:this.result.expandBox,itemBox:this.result.itemBox}}setExpandBox(t,e){if(!this.interactive||"invalid"===this.result.type)return;const{itemBox:{min:i,max:s}}=this.result;return this.result.expandBox.set(new F(Math.min(i.x,t.x),Math.min(i.y,t.y)),new F(Math.max(s.x,e.x),Math.max(s.y,e.y))),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone()),this.result.expandBox.clone()}},Nt=class{constructor(t){c(this,"wireframeApplication"),c(this,"gizmos",[]),c(this,"activeGizmo"),c(this,"selectorGizmo"),c(this,"transformGizmo"),c(this,"controlGizmo"),c(this,"preferenceGizmo"),c(this,"pictureCutGizmo"),c(this,"pictureExpandGizmo"),c(this,"textGizmo"),c(this,"maskGizmo"),c(this,"loadingGizmo"),c(this,"_ignoreInteraction",!1),c(this,"clickButtons",0),c(this,"container"),c(this,"_emitter"),c(this,"clickTime",0),c(this,"firstClick",!0),c(this,"dblclickTimeSpan",500),c(this,"spaceEmit",!1),c(this,"interactType","select"),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new S({backgroundAlpha:0,width:e,height:i,resolution:1,antialias:!0}),this.container=t,this.wireframeApplication.view.style.position="absolute",this.wireframeApplication.view.id="wireframeApplicationCanvas",t.appendChild(this.wireframeApplication.view),this.wireframeApplication.stage.sortableChildren=!0,async function(){await Promise.all(Object.entries(Tt).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>Tt[t]={...e,content:i})})).catch(t=>{console.error(t)})}()}set ignoreInteraction(t){t!==this._ignoreInteraction&&(this._ignoreInteraction=t,t&&(this.activeGizmo?.cancelPreparation(),this.activeGizmo=void 0))}get ignoreInteraction(){return this._ignoreInteraction}resize(){this.wireframeApplication&&(this.wireframeApplication.resizeTo=this.container,this.render())}refresh(){this.gizmos.forEach(t=>{t.refreshResults()})}render(){if(this.refresh(),!this.wireframeApplication?.stage)return;this.wireframeApplication?.stage?.removeChildren();const t=(this.ignoreInteraction?[this.preferenceGizmo]:this.gizmos).flatMap(t=>t.getRenderObjects());this.wireframeApplication?.stage?.addChild(...t),this.wireframeApplication?.render();const e=this.activeGizmo instanceof st||this.activeGizmo instanceof Mt||this.activeGizmo instanceof Ht||this.activeGizmo instanceof Wt||this.activeGizmo instanceof Ft||this.activeGizmo instanceof J?this.activeGizmo.cursorResult:void 0;this.setCursor(e)}async init(t,e){if(null===this.wireframeApplication)return void setTimeout(async()=>{await this.init(t,e)},50);this.gizmos=[],this.controlGizmo=new J(t),this.selectorGizmo=new q(t);const i=new at;this.transformGizmo=new st(t,i,this.selectorGizmo),this.preferenceGizmo=new St(t),this.pictureCutGizmo=new Mt(t,e),this.pictureExpandGizmo=new Ht(t,e),this.textGizmo=new Ft(t,i,this.selectorGizmo,e,this.wireframeApplication?.view.parentElement),this.textGizmo.rotationSprite.texture=await Rt.fromURL(ci.config.gestureHandlerConfig.textGizmoConfig.rotationCornerTexture),this.maskGizmo=new Wt(t),this.loadingGizmo=new Lt(t),this.gizmos.push(this.maskGizmo,this.pictureCutGizmo,this.pictureExpandGizmo,this.loadingGizmo,this.transformGizmo,this.textGizmo,this.selectorGizmo,this.controlGizmo,this.preferenceGizmo,i),this._emitter=e,this.initEvents(),this.registerViewEvent()}initEvents(){this.onMouseMove=this.onMouseMove.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp)}registerViewEvent(){this.wireframeApplication.view.onmousedown=t=>{this.onMouseDown(t)},this.wireframeApplication.view.onmousemove=t=>{0===t.buttons&&this.onMouseMove(t)},this.wireframeApplication.view.onmouseout=()=>{this.selectorGizmo?.cancelPreparation(),this.render()},this.wireframeApplication.view.onwheel=t=>{this.onWheel(t)},this.wireframeApplication.view.oncontextmenu=t=>{t.stopPropagation(),t.preventDefault()}}onMouseDown(t){if(!this.ignoreInteraction){switch(this.clickButtons=t.buttons,this.interactType){case"select":if(4===this.clickButtons&&(this.activeGizmo=this.controlGizmo,this.controlGizmo.preAction(t)),this.firstClick=!!this.firstClick&&Date.now()-this.clickTime<this.dblclickTimeSpan,this.firstClick){if(this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.activeGizmo&&["transform","text"].includes(this.activeGizmo.type)){const e=this.activeGizmo.preAction(t,!0);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null"))}else{this.activeGizmo=void 0;const e=this.selectorGizmo?.preAction(t,!0);this.activeGizmo=this.gizmos.find(t=>t.type===(e??"null"))}this.firstClick=!1}else{void 0===this.activeGizmo&&this.gizmos.forEach(e=>{if(!e.interactive||this.activeGizmo)return;const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)});const e=this.activeGizmo?.preAction(t);"selector"!==e&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===e),this.clickTime=Date.now(),this.firstClick=!0}break;case"hand":this.activeGizmo=this.controlGizmo,this.activeGizmo.preAction(t)}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}}onMouseMove(t){if(!this.ignoreInteraction){if(0!==t.buttons)this.activeGizmo?.action(t);else switch(this.interactType){case"select":this.activeGizmo=void 0,this.spaceEmit?(this.activeGizmo=this.controlGizmo,this.controlGizmo.interactionType="mouse"):this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);"selector"!==i&&this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()});break;case"hand":this.activeGizmo=this.controlGizmo,this.activeGizmo.preparationAction(t)}this.render()}}onWheel(t){this.ignoreInteraction||(t.preventDefault(),this.selectorGizmo&&(this.selectorGizmo.clearResult=!0),this.controlGizmo?.action(t))}onMouseUp(t){if(this.ignoreInteraction)return;const e=this.activeGizmo?.endAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===e),void 0===this.activeGizmo&&1===this.clickButtons&&this.gizmos.forEach(e=>{if(e.interactive)if(void 0===this.activeGizmo){const i=e.preparationAction(t);this.activeGizmo=this.gizmos.find(t=>t.type===i)}else e.cancelPreparation()}),this.clickButtons=0,this.render(),document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}onKeyDown(t){this.ignoreInteraction||("escape"===t.code.toLocaleLowerCase()&&"select"!==this.interactType&&this.setInteractType("select"),"space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active?this.gizmos.forEach(e=>{e.actionKey(t)}):(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.controlGizmo.interactionType="hand"===this.interactType||this.spaceEmit?"mouse":"wheel"),this.render())}onKeyUp(t){this.ignoreInteraction||(this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceEmit=!1,this.controlGizmo.interactionType="hand"===this.interactType||this.spaceEmit?"mouse":"wheel"),this.render())}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}setCursor(t){let e="default";if(t?.type&&["scale","rotation","circle","hand","active-hand"].includes(t.type)){const i=Tt[t.type];if("svg"===i.type){const s=16;e=encodeURIComponent(i.content.replace("rotate(0.00)",`rotate(${t.angle??0})`)),e=`url("data:image/svg+xml,${e}") ${s} ${s}, auto`}else e=i.content}this.wireframeApplication.view.style.cursor=e}openPictureCutGizmo(){if(!this.pictureCutGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureCutGizmo.interactive=!0,this.pictureCutGizmo.interactive&&(this.pictureExpandGizmo.interactive=!1,this.maskGizmo.interactive=!1,this.selectorGizmo.interactive=!1,this.transformGizmo.interactive=!1,this.textGizmo.interactive=!1);const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureCutGizmo(){if(!this.pictureCutGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureCutGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}setInteractType(t){t!==this.interactType&&(this.interactType=t,this.controlGizmo.interactionType="hand"===this.interactType||this.spaceEmit?"mouse":"wheel")}getCutInfo(){return this.pictureCutGizmo?.getCutInfo()}setCutBox(t,e){const i=this.pictureCutGizmo?.setCutBox(t,e);return this.render(),i}openPictureExpandGizmo(){if(!this.pictureExpandGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureExpandGizmo.interactive=!0,this.pictureExpandGizmo.interactive&&(this.pictureCutGizmo.interactive=!1,this.maskGizmo.interactive=!1,this.selectorGizmo.interactive=!1,this.transformGizmo.interactive=!1,this.textGizmo.interactive=!1);const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureExpandGizmo(){if(!this.pictureExpandGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.pictureExpandGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}getExpandInfo(){return this.pictureExpandGizmo?.getExpandInfo()}setExpandBox(t,e){const i=this.pictureExpandGizmo?.setExpandBox(t,e);return this.render(),i}openMaskGizmo(t){if(!this.maskGizmo)return;const e=JSON.parse(JSON.stringify(ci.config));this.maskGizmo.interactive=!0,this.maskGizmo.config={brushSize:t},this.maskGizmo.interactive&&(this.pictureCutGizmo.interactive=!1,this.pictureExpandGizmo.interactive=!1,this.transformGizmo.interactive=!1,this.selectorGizmo.interactive=!1);const i=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}clearMaskGizmo(){this.maskGizmo&&(this.maskGizmo.clearMask(),this.render())}closeMaskGizmo(){if(!this.maskGizmo)return;const t=JSON.parse(JSON.stringify(ci.config));this.maskGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}setMaskGizmoConfig(t){this.maskGizmo&&(this.maskGizmo.config=t)}getMask(){if(this.maskGizmo)return this.maskGizmo.getMask()}openLoadingGizmo(t){if(!this.loadingGizmo)return;const e=JSON.parse(JSON.stringify(ci.config));this.loadingGizmo.addId(t),this.loadingGizmo.interactive&&(this.maskGizmo.interactive=!1,this.pictureCutGizmo.interactive=!1);const i=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}closeLoadingGizmo(t){if(!this.loadingGizmo)return;const e=JSON.parse(JSON.stringify(ci.config));this.loadingGizmo.deleteId(t);const i=JSON.parse(JSON.stringify(ci.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}setPictureCutGizmoLockScale(t){this.pictureCutGizmo.isLockScale=t}setPictureExpandGizmoLockScale(t){this.pictureExpandGizmo.isLockScale=t}};import{assertExist as Ot}from"@galacean/effects";var Kt=class{constructor(t){c(this,"plane",new j),c(this,"ray",new Y),c(this,"viewportParam",{width:0,height:0,scale:1,translation:new F,rulerWidth:0}),c(this,"cameraParam",{position:new N,rotation:new N,focusPosition:new N,focusRotation:new N,viewProjectionMatrix:new O,inverseViewProjectionMatrix:new O}),c(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();Ot(t,"You must run SDK first");const e=new F(this.pageDataUtils.container.offsetWidth,this.pageDataUtils.container.offsetHeight),{zoom:i,translation:s}=t.property;this.viewportParam.width=e.x,this.viewportParam.height=e.y,this.viewportParam.scale=i,this.viewportParam.translation=new F(...s),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=O.fromArray(e.getViewProjectionMatrix().toArray()),i=O.fromArray(e.getViewMatrix().toArray()).invert(),s=new H;i.decompose(this.cameraParam.position,s,new N),this.cameraParam.rotation=(new K).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new N(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new K).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new K).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=O.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new K).setFromDegreeVector3(this.cameraParam.rotation));const i=new N(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new K).setFromDegreeVector3(this.cameraParam.rotation):(new K).setFromQuaternion((new H).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i).matrix)),r=i?(new N).setFromMatrixPosition(this.pageDataUtils.getItemTransformById(i).matrix):this.cameraParam.focusPosition,a="editor"===ci.config.mode?1:this.viewportParam.scale;t.multiply(a);const n=this.projectPoint(r.clone()),o=this.getWorldPositionByViewPoint(n.add(t));if(!o)return console.warn("size is out of bounds."),new N(0,0,0);const c=(new K).setFromQuaternion((new H).setFromEuler(s).invert());return(e||!i?o.applyEuler(c,r):o).subtract(r)}projectPoint(t){const{width:e,height:i,scale:s}=this.viewportParam,{viewProjectionMatrix:r}=this.cameraParam,a="editor"===ci.config.mode?1:s;return(new F).copyFrom(t.applyMatrix(r).toVector2()).toViewCoordinate(e*a,i*a)}getWorldPositionByViewPoint(t){const{position:e,inverseViewProjectionMatrix:i}=this.cameraParam,s=this.getNDCPositionByScreenPosition(t),r=(new $).setFromCamera(s,{position:e,inverseViewProjectMatrix:i}).rayCastPlane(this.plane);return r?.point}getNDCPositionByScreenPosition(t){const{width:e,height:i,scale:s}=this.viewportParam,r="editor"===ci.config.mode?1:s;return new F(t.x/(e*r)*2-1,1-t.y/(i*r)*2)}getNDCSizeByPixelSize(t){const{width:e,height:i}=this.viewportParam;return new F(t.x/e*2,-t.y/i*2)}getPixelSizeByNDCSize(t){const{width:e,height:i}=this.viewportParam;return new F(t.x/2*e,-t.y/2*i)}getViewPositionWWithOutTransform(t){const{scale:e}=this.viewportParam,i="editor"===ci.config.mode?1:e;return t.divide(i)}getViewPositionByPixelPoint(t){if("template"===ci.config.mode)return t.clone();const{width:e,height:i,scale:s,translation:r}=this.viewportParam;return t.clone().scaleByCenter(new F(s,s),new F(e/2,i/2)).add(r)}};import{FFmpeg as jt}from"@ffmpeg/ffmpeg";import{toBlobURL as Yt}from"@ffmpeg/util";var $t={SCRIPT:"https://gw.alipayobjects.com/os/gltf-asset/99531561844014/img2webp.js",WASM:"https://mdn.alipayobjects.com/mars/uri/file/as/0.0.4/wasm/img2webp/img2webp.wasm"},Jt={CLASSWORKER:"https://mdn.alipayobjects.com/rms/uri/file/as/ffmpeg/core/0.12.10/dist/worker.js",DEFAULT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core/0.12.10/dist/esm/ffmpeg-core.wasm"},MT:{CORE:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.js",WASM:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.wasm",WORKER:"https://gw.alipayobjects.com/os/lib/ffmpeg/core-mt/0.12.10/dist/esm/ffmpeg-core.worker.js"}};function Xt(t,e,i,s){const r=e.getContext("2d");_t(r),r.clearRect(0,0,e.width,e.height),i&&(r.save(),r.fillStyle=i,r.fillRect(0,0,e.width,e.height),r.restore()),s&&r.drawImage(s,0,0,s.width,s.height,0,0,e.width,e.height),r.drawImage(t,0,0,t.width,t.height,0,0,e.width,e.height)}async function Zt(){return new Promise(async(t,e)=>{try{await function(t,e={}){return new Promise((i,s)=>{const r=document.querySelector(`script[src="${t}"]`);if(r)return"true"===r.dataset.loaded?void i(r):(r.addEventListener("load",()=>{i(r)}),void r.addEventListener("error",()=>{s(new Error(`Script already failed: ${t}`))}));const a=document.createElement("script");a.src=t,a.async=!0,Object.keys(e).forEach(t=>{a.setAttribute(t,e[t]??"")}),a.onload=()=>{a.dataset.loaded="true",i(a)},a.onerror=()=>{s(new Error(`Failed to load script: ${t}`))},document.head.appendChild(a)})}($t.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?$t.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function qt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.disposed||t.destroyCurrentCompositions()}function Qt(t=[750,750]){const e=b(),i={id:b(),dataType:g.DataType.TimelineAsset,tracks:[]},s={id:b(),item:{id:e},dataType:g.DataType.CompositionComponent,items:[],timelineAsset:{id:i.id},sceneBindings:[]},r={id:e,name:"AI 设计师画布",duration:999,startTime:0,endBehavior:g.EndBehavior.forward,previewSize:[...t],camera:{fov:60,far:40,near:.1,clipMode:1,position:[0,0,8],rotation:[0,0,0],aspect:t[0]/t[1]},components:[{id:s.id}]},a={version:g.JSONSceneVersion.LATEST,playerVersion:{web:"2.7.3",native:"10.7.6"},type:"ge",compositionId:e,compositions:[],images:[],plugins:[],bins:[],textures:[],items:[],components:[],materials:[],shaders:[],geometries:[],animations:[],miscs:[]};return a.miscs.push(i),a.compositions.push(r),a.components.push(s),a}function te(t,e,i,s,r,a,n){const o=b(),c={id:t,name:a,dataType:g.DataType.VFXItemData,components:[{id:o}],delay:0,duration:999,endBehavior:g.EndBehavior.restart,renderLevel:g.RenderLevel.BPlus,type:g.ItemType.sprite,visible:!0,transform:{position:{x:e.x,y:e.y,z:e.z},eulerHint:{x:i.x,y:i.y,z:i.z},size:{x:s.x,y:s.y},scale:{x:r.x,y:r.y,z:r.z},anchor:{x:0,y:0}},content:void 0},h={id:o,item:{id:t},dataType:g.DataType.SpriteComponent,options:{startColor:[1,1,1,1]},renderer:{renderMode:g.RenderMode.MESH}};n&&(h.renderer.texture={id:n});const l={id:b(),dataType:g.DataType.ActivationPlayableAsset},p={id:b(),dataType:g.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:l.id}}]},m={id:b(),dataType:g.DataType.SpriteColorPlayableAsset,startColor:[1,1,1,1]};return{item:c,components:[h],tracks:[p,{id:b(),dataType:g.DataType.SpriteColorTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:m.id}}]}],playableAssets:[l,m]}}function ee(t,e,i,s,r,a){const n=b(),o={id:t,name:e,dataType:g.DataType.VFXItemData,components:[{id:n}],delay:0,duration:999,endBehavior:g.EndBehavior.restart,renderLevel:g.RenderLevel.BPlus,type:g.ItemType.sprite,visible:!0,transform:{position:{x:i.x,y:i.y,z:i.z},eulerHint:{x:s.x,y:s.y,z:s.z},size:{x:r.x,y:r.y},scale:{x:1,y:1,z:1},anchor:{x:0,y:0}},content:void 0},c={id:n,item:{id:t},dataType:g.DataType.TextComponent,options:a,renderer:{renderMode:1}},h={id:b(),dataType:g.DataType.ActivationPlayableAsset};return{item:o,components:[c],tracks:[{id:b(),dataType:g.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:h.id}}]}],playableAssets:[h]}}function ie(t,e){t.items.push(e.item),t.miscs.push(...e.tracks,...e.playableAssets),t.components.push(...e.components);const i=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0],s=t.components.find(t=>t.id===i.components[0]?.id);if(s){s.items.push({id:e.item.id});const i={id:b(),dataType:g.DataType.ObjectBindingTrack,children:[],clips:[]};for(const t of e.tracks)i.children.push({id:t.id});t.miscs.find(t=>t.id===s.timelineAsset.id).tracks.push({id:i.id}),s.sceneBindings.push({key:{id:i.id},value:{id:e.item.id}}),t.miscs.push(i)}}function se(t,e,i){var s;const r=t.items.findIndex(t=>t.id===e);if(r<0)return;!function(t,e){var i;const s=t.items.findIndex(t=>t.id===e);if(!t.items[s]?.parentId)return;const r=t.items.find(e=>e.id===t.items[s].parentId);if(!r)return void delete t.items[s].parentId;const{position:a={x:0,y:0,z:0},eulerHint:n=new N,scale:o=new N(1,1,1)}=r.transform;(i=t.items[s]).transform??(i.transform={position:{x:0,y:0,z:0},eulerHint:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},size:{x:1,y:1}}),t.items[s].transform.position.x+=a.x,t.items[s].transform.position.y+=a.y,t.items[s].transform.position.z+=a.z,t.items[s].transform.eulerHint.x+=n.x,t.items[s].transform.eulerHint.y+=n.y,t.items[s].transform.eulerHint.z+=n.z,t.items[s].transform.scale.x*=0===o.x?1:o.x,t.items[s].transform.scale.y*=0===o.y?1:o.y,t.items[s].transform.scale.z*=0===o.z?1:o.z}(t,e);const a=t.items.find(t=>t.id===i);if(!a)return;t.items[r].parentId=i;const{position:n={x:0,y:0,z:0},eulerHint:o=new N,scale:c=new N(1,1,1)}=a.transform;(s=t.items[r]).transform??(s.transform={position:{x:0,y:0,z:0},eulerHint:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},size:{x:1,y:1}}),t.items[r].transform.position.x-=n.x,t.items[r].transform.position.y-=n.y,t.items[r].transform.position.z-=n.z,t.items[r].transform.eulerHint.x-=o.x,t.items[r].transform.eulerHint.y-=o.y,t.items[r].transform.eulerHint.z-=o.z,t.items[r].transform.scale.x/=0===c.x?1:c.x,t.items[r].transform.scale.y/=0===c.y?1:c.y,t.items[r].transform.scale.z/=0===c.z?1:c.z}function re(t,e){let i;return t.components.forEach(s=>{if(s.dataType===g.DataType.SpriteComponent&&s.item.id===e&&s.renderer.texture){const e=t.textures?.find(t=>t.id===s.renderer.texture?.id);e&&(i=t.images.find(t=>t.id===e.source.id)?.url)}}),i}import{VFXItem as ae,SpriteComponent as ne,spec as oe,TextComponent as ce}from"@galacean/effects";import{VideoComponent as he}from"@galacean/effects-plugin-multimedia";var le=class{static createEmpty(t,e=null,i="NewVFXItem"){const s=pe.createVFXItem(t,e,i);return s.type=oe.ItemType.null,s}static createSprite(t,e=null,i="NewSpite"){const s=pe.createVFXItem(t,e,i,ne);return s.type=oe.ItemType.sprite,s}static createText(t,e=null,i="NewText"){const s=pe.createVFXItem(t,e,i,ce);return s.type=oe.ItemType.text,s}static createVideo(t,e=null,i="NewVideo"){const s=pe.createVFXItem(t,e,i,he);return s.type=oe.ItemType.video,s}},pe=class{static createVFXItem(t,e=null,i="NewVFXItem",...s){const r=new ae(t.getEngine());r.name=i;for(const t of s)r.addComponent(t);return t.addItem(r),t.rootComposition.items.push(r),e&&r.setParent(e),r}};import{AssetManager as me}from"@galacean/effects";var de=class{constructor(t,e,i,s){c(this,"sdk"),c(this,"player"),c(this,"container"),c(this,"emitter"),c(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new Kt(this)}getPageData(){return this.sdk.pageData}getCurrentComposition(){return this.player.getCompositions()[0]}isItemSelected(t){return!!this.sdk.pageData?.activeData.selectedItems?.find(e=>e===t)}getItemEditEnable(t){const e=this.getViewItemById(t);if(!e||!this.sdk.pageData||this.getViewProperty()?.ignoreInteraction)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart)}getItemShow(t){const e=this.getViewItemById(t);if(!this.sdk.pageData||!e?.property.visible)return!1;const i=this.sdk.pageData.time,{duration:s,delay:r,endBehavior:a}=e;return i>=r&&(i<r+s||a===g.EndBehavior.restart||a===g.EndBehavior.freeze)}addSelectedItems(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.selectedItems??[];t.forEach(t=>{Z(e,t)}),this.emitter.emit("selectedItemChange",e)}removeSelectedItems(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.selectedItems??[];for(const i of t){const t=e.findIndex(t=>t===i);t>=0&&e.splice(t,1)}this.emitter.emit("selectedItemChange",e)}clearSelectedItems(t=!1){this.sdk.pageData&&(t?this.emitter.emit("selectedItemChange",[]):this.sdk.pageData.activeData.selectedItems=[])}getSelectedItems(){const t=this.sdk.pageData?.activeData.selectedItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}addPreSelectedItem(t){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=void 0,this.emitter.emit("preSelectedItemChange",void 0)}getPreSelectedItem(){const t=this.getPageData();v(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}addLoadingItems(t){var e;v(this.sdk.pageData,"You must call SDK#run() first"),(e=this.sdk.pageData.activeData).loadingItems??(e.loadingItems=[]);const i=this.sdk.pageData.activeData.loadingItems;t.forEach(t=>{Z(i,t)}),this.emitter.emit("loadingItemChange",i)}removeLoadingItems(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.loadingItems??[];for(const i of t){const t=e.findIndex(t=>t===i);t>=0&&e.splice(t,1)}this.emitter.emit("loadingItemChange",e)}clearLoadingItems(){this.sdk.pageData&&(this.sdk.pageData.activeData.loadingItems=[],this.emitter.emit("loadingItemChange",[]))}getLoadingItems(){const t=this.sdk.pageData?.activeData.loadingItems;return this.sdk.pageData?.items.filter(e=>t?.find(t=>t===e.id))??[]}getViewItemById(t){return this.sdk.pageData?.items.find(e=>e.id===t)}getPlayerSizeByParent(t,e){const[i,s]=t,[r=1624,a=750]=e;let n=s,o=n/a*r;return o>i&&(n=i/o*s,o=i),[o,n]}async loadScene(t){qt(this.player);const e=this.getViewProperty(t);if(!e||!this.sdk.pageData)return void console.warn(`This page does not have ${t} view property.`);const{scene:i,size:s}=e,r=this.container.parentElement?.offsetWidth??300,a=this.container.parentElement?.offsetHeight??300,[n,o]=this.getPlayerSizeByParent([r,a],s);this.container.style.width=`${n}px`,this.container.style.height=`${o}px`,this.sdk.pageData.activeData={view:t,selectedItems:[],preSelectedItem:void 0},this.player.resize();const c=JSON.parse(JSON.stringify(i)),h=await this.player.loadScene(c,{autoplay:!1});this.player.gotoAndStop(this.sdk.pageData.time),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,h.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshPageTime(t){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t,e,i){var s;v(this.sdk.pageData,"You must call SDK#run() first"),(s=this.sdk.pageData.property).zoom??(s.zoom=1);const{zoom:r,translation:[a=0,n=0]}=this.sdk.pageData.property,{width:o,height:c,scale:h}=this.interactionUtils.viewportParam,l=i?t:k(t,-.1,.1),p=V(k(r+l,ci.config.pageConfig.minZoom,ci.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=p,ci.config.mode){case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new F(a,n)),i=e??new F(o/2,c/2),s=this.interactionUtils.getNDCPositionByScreenPosition(i),r=(s.x-t.x)/h,l=(s.y-t.y)/h,m=new F(s.x-r*p,s.y-l*p),d=(new O).compose(new N(m.x,m.y,0),new H,new N(p,p,1));this.sdk.pageData.property.translation=this.interactionUtils.getPixelSizeByNDCSize(m).toArray(),this.setCurrenCameraViewportMatrix(d);break}case"template":this.container.style.scale=`${p}`}this.refreshInteractionParam(),this.sdk.pageData.items=[];const m=this.getCurrentComposition();this.addViewItemsByItems(this.sdk.pageData.items,m.items),this.emitter.emit("zoomChange",p),this.emitter.emit("viewportTransform",{zoom:p,translatoion:[a,n]}),this.emitter.emit("pageDataChange",this.sdk.pageData)}setPageZoom(t){v(this.sdk.pageData,"You must call SDK#run() first");const{translation:[e=0,i=0]}=this.sdk.pageData.property,s=V(k(t,ci.config.pageConfig.minZoom,ci.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=s,ci.config.mode){case"template":this.container.style.scale=`${s}`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new F(e,i)),r=(new O).compose(new N(t.x,t.y,0),new H,new N(s,s,1));this.setCurrenCameraViewportMatrix(r);break}}this.emitter.emit("zoomChange",s),this.emitter.emit("viewportTransform",{zoom:s,translatoion:[e,i]}),this.emitter.emit("pageDataChange",this.sdk.pageData)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){v(this.sdk.pageData,"You must call SDK#run() first");const{translation:[e=0,i=0],zoom:s}=this.sdk.pageData.property,r=e+t.x,a=i+t.y;switch(this.sdk.pageData.property.translation=[r,a],ci.config.mode){case"template":this.container.style.translate=`${r}px ${a}px`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new F(r,a)),e=(new O).compose(new N(t.x,t.y,0),new H,new N(s,s,1));this.setCurrenCameraViewportMatrix(e);break}}this.refreshInteractionParam(),this.sdk.pageData.items=[];const n=this.getCurrentComposition();this.addViewItemsByItems(this.sdk.pageData.items,n.items),this.emitter.emit("viewportTransform",{zoom:s,translatoion:[r,a]}),this.emitter.emit("pageDataChange",this.sdk.pageData)}setCurrenCameraViewportMatrix(t){const e=this.getCurrentComposition();if(!e)return;const{camera:i}=e;i.setViewportMatrix(t)}rotateItem(t,e){const i=this.getPlayerItemById(t);i&&(i.rotate(...e.toArray()),this.transformSceneItem(t,"rotation",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"rotation"}))}moveItem(t,e){const i=this.getPlayerItemById(t);if(i){const s=(new O).copyFrom(i.transform.getParentMatrix()??new O);s.setPosition(new N);const r=e.clone().applyMatrix(s.invert());i.translate(...r.toArray()),i.transform.updateLocalMatrix(),this.transformSceneItem(t,"position",r.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"translation"})}}scaleItem(t,e){const i=this.getPlayerItemById(t);i&&(i.scale(...e.toArray()),this.transformSceneItem(t,"scale",e.toArray()),this.refreshViewItem(t),this.emitter.emit("itemPropertyChange",{id:t,property:"size"}))}scaleTextItem(t,e){const i=this.getViewItemById(t);if(i?.type===g.ItemType.text){const{textWidth:t}=i.property;this.changeItemProperty({itemId:i.id,type:g.ItemType.text,propertyName:"textWidth",propertyValue:t*e})}}getItemTransformById(t){const e={matrix:new O,parentMatrix:new O},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=O.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(O.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(O.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new O).toArray()))}return e}addViewItemsByItems(t,e,i){const s=e=>{e.forEach(e=>{t.find(t=>t.id===e.getInstanceId())||t.push(this.createViewItemByPlayerItem(e,i))})};for(const i of e)ci.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){v(this.sdk.pageData,"You must call SDK#run() first");const{transform:i,composition:s,isVisible:r}=t,a={position:[0,0],rotation:[0,0,0],size:[0,0],visible:r,keyPropertyEditing:!1},{scale:n,translation:o,width:c,height:h}=this.interactionUtils.viewportParam,l="editor"===ci.config.mode?1:n,p=this.getViewportLeftTopPosition();if(t.type!==g.ItemType.null){i.updateLocalMatrix();const e=(new O).copyFrom(s?.transform.getWorldMatrix()??(new O).identity()).invert().multiply(i.getWorldMatrix()),r=new N,n=new H,o=new N;e.decompose(r,n,o);const c=(new K).setFromQuaternion(n);c.x=Number.isNaN(c.x)?0:c.x,c.y=Number.isNaN(c.y)?0:c.y,c.z=Number.isNaN(c.z)?0:c.z;const{scale:h,translation:l,width:p,height:m}=this.interactionUtils.viewportParam;this.interactionUtils.initInteractionPlane(r,c);const d=this.interactionUtils.projectPoint(r),g="editor"===ci.config.mode?d.subtract(l.clone().multiply(h)).scaleByCenter(new F(1/h,1/h),new F(p/2,m/2)).toArray().map(t=>V(t,2)):d.divide(h).toArray().map(t=>V(t,2)),u=c.toArray().map(t=>V(t,2)),f=o.toArray().map(t=>V(t,2)),y=i.size.toArray(),x=this.getPixelSizeByWorldSize([f[0]*y[0],f[1]*y[1],f[2]],t).map(t=>V(t,2));a.position=g,a.rotation=u,a.size=x}else{const e=this.getViewBoxByPlayerItem(t,t.children),i=this.interactionUtils.getViewPositionWWithOutTransform(e.getCenter().subtract(p)),s="editor"===ci.config.mode?i.subtract(o.clone().multiply(n)).scaleByCenter(new F(1/n,1/n),new F(c/2,h/2)).toArray().map(t=>V(t,2)):i.toArray();a.position=s,a.size=e.getSize().divide(l).toArray()}switch(t.type){case g.ItemType.sprite:{const e=this.getViewProperty()?.scene;if(e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(a.keyPropertyEditing||!("renderer"in t)||!("texture"in t.renderer)||!t.renderer.texture)return;const i=e.textures?.find(e=>e.id===t.renderer.texture.id);if(i&&"source"in i&&i.source){const t=e?.images.find(t=>t.id===i.source.id);a.keyPropertyEditing=!!t?.template;const s=t?.url??"";s&&Object.assign(a,{image:s})}})}break}case g.ItemType.text:case g.ItemType.richtext:{const e=this.getViewProperty()?.scene;if(a.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType))return;const{textAlign:e,textColor:i,text:s,fontWeight:r,fontFamily:n,fontSize:o,fontStyle:c,outline:h,textWidth:l,lineHeight:p}=t.options,m=h?.outlineColor?h.outlineColor.map((t,e)=>e>2?t:V(255*t,0)):void 0,d=i.map((t,e)=>e>2?t:V(255*t,0)),u=h?.outlineWidth;Object.assign(a,{textAlign:e,textColor:d,fontWeight:r,text:s,fontFamily:n,fontSize:o,fontStyle:c,outlineColor:m,outlineWidth:u,textWidth:l,lineHeight:p})})}break}}return{id:t.getInstanceId(),name:t.name,parentId:t.parentId??e,children:[],type:t.type,duration:t.duration,delay:t.defination.delay,endBehavior:t.endBehavior,property:a}}getViewBoxById(t){const e=new W,i=this.getPlayerItemById(t),s=this.getChildrenPlayerItems(i);return i&&s?this.getViewBoxByPlayerItem(i,s):e}getItemViewAnchor(t){const e=this.getPlayerItemById(t);if(e?.transform?.anchor){const t=(new N).copyFrom(e.transform.anchor).applyMatrix((new O).copyFrom(e.transform.getWorldMatrix())),i=this.getViewportLeftTopPosition();return this.interactionUtils.projectPoint(t).add(i).round(2)}}getChildrenPlayerItems(t){const e=[];return t?(e.push(...this.player.getCompositions()[0].items.filter(e=>e.parentId===t.getInstanceId())),e.push(...e.flatMap(t=>this.getChildrenPlayerItems(t))),e):[]}getChildrenSceneItemIds(t,e){const i=[];return i.push(...e.items.filter(e=>e.parentId===t).map(t=>t.id)),i.push(...i.flatMap(t=>this.getChildrenSceneItemIds(t,e))),i}getViewBoxByPlayerItem(t,e){const i=new W;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,n=(new O).copyFrom(r?.transform.getWorldMatrix()??new O).invert().multiply(s.getWorldMatrix()),{x:o,y:c}=a.clone().divide(2),h=new N(o,c,0).applyMatrix(n),l=new N(o,-c,0).applyMatrix(n),p=new N(-o,-c,0).applyMatrix(n),m=new N(-o,c,0).applyMatrix(n),d=this.getViewportLeftTopPosition(),g=this.interactionUtils.projectPoint(h).add(d).round(2),u=this.interactionUtils.projectPoint(l).add(d).round(2),f=this.interactionUtils.projectPoint(p).add(d).round(2),y=this.interactionUtils.projectPoint(m).add(d).round(2);i.setFromVec2Array([g,u,f,y]);const x=e?.map(t=>this.getViewBoxById(t.getInstanceId()));x&&x.map(t=>i.union(t));break}case g.ItemType.null:{const t=e?.map(t=>this.getViewBoxById(t.getInstanceId()));t&&t.map(t=>i.union(t));break}}return i}getViewportLeftTopPosition(){if(!this.sdk.pageData||"editor"===ci.config.mode)return new F;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,n=new F(i,s),o=new F(r,a).multiply(t);return n.clone().divide(2).subtract(o.clone().divide(2)).add(e)}getContainerPosition(){const{offsetWidth:t,offsetHeight:e}=this.container.parentElement;return new F(t/2,e/2).add(new F(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,i="editor"===ci.config.mode?1:e,{width:s,height:r}=this.interactionUtils.viewportParam,a=new F(s,r).multiply(i),n=this.getViewportLeftTopPosition(),o=t.clone().subtract(n);return new F(o.x/a.x*2-1,1-o.y/a.y*2)}async changeItemProperty(t){v(this.sdk.pageData,"You must call SDK#run() first"),v(t,"Param is not exsited.");const e=this.getViewItemById(t.itemId),i=this.getPlayerItemById(t.itemId);if(!e||!i)return void console.warn(`Id ${t.itemId} is not a item id.`);if(!(t.propertyName in e.property))return void console.warn(`Item does not have property ${t.propertyName}.`);const s="editor"===ci.config.mode?this.interactionUtils.viewportParam.scale:1;switch(t.propertyName){case"textAlign":[g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(P).setTextAlign(t.propertyValue);break;case"textColor":if(Array.isArray(t.propertyValue)&&4===t.propertyValue.length){const e=t.propertyValue.map((t,e)=>e>2?t:V(t/255,5));i.getComponent(P).setTextColor(e)}break;case"fontFamily":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0];await me.loadFontFamily([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(P).setFontFamily(s)}break;case"text":if("string"==typeof t.propertyValue){const e=i.getComponent(P);e.setText(t.propertyValue);const r=e.getLineCount(t.propertyValue),a=Math.ceil(e.textLayout.lineHeight*r);e.setTextHeight(a);const n=e.textLayout.width,o=new F(n,a).multiply(s),c=this.interactionUtils.getWorldSizeByViewSize(o);i.transform.setSize(Math.abs(c.x),Math.abs(c.y))}break;case"fontWeight":[g.TextWeight.normal,g.TextWeight.bold,g.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(P).setFontWeight(t.propertyValue);break;case"textWidth":{const e=i.getComponent(P);e.setTextWidth(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new F(a,r).multiply(s),o=this.interactionUtils.getWorldSizeByViewSize(n);i.transform.setSize(Math.abs(o.x),Math.abs(o.y));break}case"lineHeight":{const e=i.getComponent(P);e.setLineHeight(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new F(a,r).multiply(s),o=this.interactionUtils.getWorldSizeByViewSize(n);i.transform.setSize(Math.abs(o.x),Math.abs(o.y));break}case"outlineColor":if(Array.isArray(t.propertyValue)&&4===t.propertyValue.length){const e=i.getComponent(P);if("function"==typeof e.setOutlineColor){const i=t.propertyValue.map((t,e)=>e>2?t:V(t/255,5));e.setOutlineColor(i)}}break;case"outlineWidth":if("number"==typeof t.propertyValue){const e=i.getComponent(P);"function"==typeof e.setOutlineWidth&&e.setOutlineWidth(t.propertyValue)}break;case"fontSize":if("number"==typeof t.propertyValue&&i.type===g.ItemType.text){const e=i.getComponent(P),r=e.textStyle.fontSize;e.setFontSize(t.propertyValue),e.setLineHeight(e.textLayout.lineHeight*t.propertyValue/r);const a=e.getLineCount(e.text),n=Math.ceil(e.textLayout.lineHeight*a);e.setTextHeight(n);const o=e.textLayout.width,c=new F(o,n).multiply(s),h=this.interactionUtils.getWorldSizeByViewSize(c);i.transform.setSize(Math.abs(h.x),Math.abs(h.y))}break;case"image":"string"==typeof t.propertyValue&&i.getComponent(I).setTexture(await C.fromImage(t.propertyValue,this.player.renderer.engine));break;case"position":if(Array.isArray(t.propertyValue)&&(3===t.propertyValue.length||2===t.propertyValue.length)){const i=t.propertyValue.map((t,i)=>t-(e.property.position[i]??0)),s=this.interactionUtils.getWorldSizeByViewSize(new F(...i),!0,t.itemId);this.moveItem(t.itemId,s)}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const i=t.propertyValue.map((t,i)=>t-(e.property.rotation[i]??0));this.rotateItem(t.itemId,new N(...i).negate())}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const i=t.propertyValue.map(t=>0===t||null===t?1:t),s=e.property.size.map(t=>t||1),r=i.map((t,e)=>t/s[e]);this.scaleItem(t.itemId,new N(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),ci.config.pageConfig.groupVisible)){this.getChildrenPlayerItems(i).forEach(e=>{e.setVisible(t.propertyValue)})}}["position","rotation","size"].includes(t.propertyName)||this.player.gotoAndStop(this.sdk.pageData.time),this.changeViewItemProperty(t),this.refreshViewItem(t.itemId)}changeViewItemProperty(t){v(this.sdk.pageData,"You must call SDK#run() first"),v(t,"Param is not exsited."),this.sdk.pageData.viewProperties.forEach(e=>{if(!this.sdk.pageData?.property.asyncMode&&e.id!==this.sdk.pageData?.activeData.view)return;const{scene:i}=e;switch(t.propertyName){case"position":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),s=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(s?.[e]??0)),a=this.interactionUtils.getWorldSizeByViewSize(new F(...r),!0,t.itemId);this.changeSceneItemProperty(i,{...t,propertyValue:a.toArray()})}break;case"rotation":if(Array.isArray(t.propertyValue)&&3===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),s=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t-(s?.[e]??0));this.changeSceneItemProperty(i,{...t,propertyValue:r})}break;case"size":if(Array.isArray(t.propertyValue)&&2===t.propertyValue.length){const e=this.sdk.pageData.items.find(e=>e.id===t.itemId),s=e?.property[t.propertyName],r=t.propertyValue.map((t,e)=>t/(s?.[e]??0));this.changeSceneItemProperty(i,{...t,propertyValue:r})}break;default:this.changeSceneItemProperty(i,t)}})}changeSceneItemProperty(t,e){var i,s,r,a,n,o;v(e,"Param is not exsited.");const c="editor"===ci.config.mode?this.interactionUtils.viewportParam.scale:1;switch(e.propertyName){case"textAlign":if([g.TextAlignment.left,g.TextAlignment.middle,g.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&"textAlign"in i.options&&(i.options.textAlign=e.propertyValue)}break;case"textColor":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(i?.options){const t=e.propertyValue.map((t,e)=>e>2?t:V(t/255,5));i.options.textColor=[...t]}}break;case"fontFamily":if("string"==typeof e.propertyValue){const i=e.propertyValue.split("/"),s=i[i.length-1]?.split(".")[0],r=t.fonts?.find(t=>"family"in t&&t.family===s||"fontFamily"in t&&t.fontFamily===s);!r&&t.fonts&&s&&t.fonts.push({fontFamily:s,fontURL:e.propertyValue});const a=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));a&&(a.options.fontFamily=s)}break;case"lineHeight":if("number"==typeof e.propertyValue){const s=t.items.find(t=>t.id===e.itemId),r=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(s&&r?.options){r.options.lineHeight=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const e=t.getComponent(P),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a*c,n*c],h=this.interactionUtils.getWorldSizeByViewSize(new F(...o));(i=s.transform).size??(i.size={x:1,y:1}),s.transform.size={x:Math.abs(h.x),y:Math.abs(h.y)}}}}break;case"textWidth":if("number"==typeof e.propertyValue){const i=t.items.find(t=>t.id===e.itemId),r=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(r?.options&&i){r.options.textWidth=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const e=t.getComponent(P),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a*c,n*c],h=this.interactionUtils.getWorldSizeByViewSize(new F(...o));(s=i.transform).size??(s.size={x:1,y:1}),i.transform.size={x:Math.abs(h.x),y:Math.abs(h.y)}}}}break;case"text":if("string"==typeof e.propertyValue){const i=t.items.find(t=>t.id===e.itemId),s=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(s?.options&&i){s.options.text=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const a=t.getComponent(P),n=a.getLineCount(e.propertyValue),o=a.textLayout.lineHeight,h=a.textLayout.width,l=Math.ceil(o*n);s.options.textHeight=l;const p=[h*c,l*c],m=this.interactionUtils.getWorldSizeByViewSize(new F(...p));(r=i.transform).size??(r.size={x:1,y:1}),i.transform.size={x:Math.abs(m.x),y:Math.abs(m.y)}}}}break;case"fontWeight":if("string"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontWeight=e.propertyValue)}break;case"outlineColor":if(Array.isArray(e.propertyValue)&&4===e.propertyValue.length){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&((a=i.options).outline??(a.outline={}),i.options.outline.outlineColor=[...e.propertyValue.map((t,e)=>e>2?t:V(t/255,5))])}break;case"outlineWidth":if("number"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));i?.options&&((n=i.options).outline??(n.outline={}),i.options.outline.outlineWidth=e.propertyValue)}break;case"fontSize":if("number"==typeof e.propertyValue){const i=t.items.find(t=>t.id===e.itemId),s=t.components.find(t=>t.item.id===e.itemId&&[g.DataType.TextComponent,g.DataType.RichTextComponent].includes(t.dataType));if(s?.options&&i){s.options.fontSize=e.propertyValue;const t=this.getPlayerItemById(e.itemId);if(t){const s=t.getComponent(P),r=s.textStyle.fontSize;s.setFontSize(e.propertyValue),s.setLineHeight(s.textLayout.lineHeight*e.propertyValue/r);const a=s.getLineCount(s.text),n=Math.ceil(s.textLayout.lineHeight*a);s.setTextHeight(n);const h=s.textLayout.width,l=new F(h,n).multiply(c),p=this.interactionUtils.getWorldSizeByViewSize(l);(o=i.transform).size??(o.size={x:1,y:1}),i.transform.size={x:Math.abs(p.x),y:Math.abs(p.y)}}}}break;case"image":if("string"==typeof e.propertyValue){t.components.filter(t=>t.item.id===e.itemId).forEach(i=>{if(!("renderer"in i))return;const s=t.textures?.find(t=>t.id===i.renderer.texture.id);if(s&&"source"in s&&s.source){const i=t?.images.find(t=>t.id===s.source.id);i?.url&&(i.url=e.propertyValue,delete i.webp),i&&"template"in i&&i.template.background&&(i.template.background.url=e.propertyValue)}})}break;case"position":{const i=e.propertyValue;if(Array.isArray(e.propertyValue)&&3===i.length){const s=t.items.find(t=>t.id===e.itemId);s?.transform&&(s.transform.position.x+=i[0],s.transform.position.y+=i[1],s.transform.position.z+=i[2])}break}case"rotation":if(Array.isArray(e.propertyValue)&&3===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.eulerHint.x+=e.propertyValue[0],i.transform.eulerHint.y+=e.propertyValue[1],i.transform.eulerHint.z+=e.propertyValue[2])}break;case"size":if(Array.isArray(e.propertyValue)&&2===e.propertyValue.length){const i=t.items.find(t=>t.id===e.itemId);i?.transform&&(i.transform.scale.x*=e.propertyValue[0],i.transform.scale.y*=e.propertyValue[1])}break;case"visible":{const i=t.items.find(t=>t.id===e.itemId);if(i&&(i.visible=e.propertyValue,ci.config.pageConfig.groupVisible)){this.getChildrenSceneItemIds(e.itemId,t).forEach(i=>{const s=t.items.find(t=>t.id===i);s&&(s.visible=e.propertyValue)})}break}}}transformSceneItem(t,e,i){v(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.viewProperties.forEach(s=>{if(!this.sdk.pageData?.property.asyncMode&&s.id!==this.sdk.pageData?.activeData.view)return;const{scene:r}=s;switch(e){case"position":if(Array.isArray(i)&&3===i.length){const e=r.items.find(e=>e.id===t);e?.transform&&(e.transform.position.x+=i[0],e.transform.position.y+=i[1],e.transform.position.z+=i[2])}break;case"rotation":if(Array.isArray(i)&&3===i.length){const e=r.items.find(e=>e.id===t);e?.transform&&(e.transform.eulerHint.x+=i[0],e.transform.eulerHint.y+=i[1],e.transform.eulerHint.z+=i[2])}break;case"scale":if(Array.isArray(i)&&3===i.length){const e=r.items.find(e=>e.id===t);e?.transform&&(e.transform.scale.x*=i[0],e.transform.scale.y*=i[1],e.transform.scale.z*=i[2])}}})}refreshViewItem(t){const e=this.sdk.pageData;v(e,"You must call SDK#run() first");const i=e.items.findIndex(e=>e.id===t);if(i<0)return void console.warn(`item ${t} is not existed.`);const s=e.items[i],r=this.getPlayerItemById(t);r&&s&&(e.items[i]=this.createViewItemByPlayerItem(r,s.parentId))}getPlayerItemById(t){return this.player.getCompositions()[0]?.items.find(e=>e.getInstanceId()===t)}getPixelSizeByWorldSize(t,e){v(this.sdk.pageData,"You must call SDK#run() first");const i=[0,0],s=e.composition?.camera,r=this.getViewProperty()?.size;if(s&&r){const{z:a}=e.transform.getWorldPosition(),{x:n,y:o}=s.getInverseVPRatio(a);i[0]=Math.abs(t[0]*r[0]/n/2),i[1]=Math.abs(t[1]*r[1]/o/-2)}else console.warn("camera is not existed.");return i}getActiveTargetScene(){const t=this.getViewProperty()?.scene;if(t)return t;console.warn("Target scene is not exsited.")}refreshSceneAndPageData(){v(this.sdk.pageData,"You must call SDK#run() first");const t=this.player.getCompositions()[0];this.refreshItemRenderOrder(t),this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam(),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,t.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}async addSpriteItem(t){const e=this.getActiveTargetScene();if(!e)return;const{scale:i}=this.interactionUtils.viewportParam,{name:s="图层",size:r,scale:a=[1,1],url:n,rotation:o=0,position:c,parentId:h,id:l=b()}=t,p=this.interactionUtils.getWorldSizeByViewSize(new F(...r).multiply(i)),m=new N(...a??[1,1],1),d=new N(0,0,o),u=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new F(...c)))??new N,f=e.images.findIndex(t=>t.url===n);let y,x={};if(n)if(f<0){y=await C.fromImage(n,this.player.renderer.engine);const t={id:b(),url:n,renderLevel:g.RenderLevel.BPlus};x={id:y.guid,source:{id:t.id},flipY:!0,dataType:g.DataType.Texture},e.images.push(t),e.textures??(e.textures=[]),e.textures.push(x)}else{const t=e.textures?.find(t=>t.source.id===e.images[f].id);x={id:t?.id},y=this.player.renderer.engine.findObject({id:t.id})}const w=te(l,u,d,new F(Math.abs(p.x),Math.abs(p.y)),m,s,x?.id);e.items.find(t=>t.id===h)&&(w.item.parentId=h),ie(e,w);const v=this.player.getCompositions()[0],P=le.createSprite(v,null,s);if(P.setInstanceId(w.item.id),P.duration=999,P.defination.delay=0,P.endBehavior=g.EndBehavior.restart,P.transform.setSize(Math.abs(p.x),Math.abs(p.y)),P.transform.setPosition(...u.toArray()),P.transform.setRotation(...d.toArray()),P.transform.setScale(...m.toArray()),y){P.getComponent(I).setTexture(y)}return this.refreshSceneAndPageData(),w.item.id}addNullItem(t){const e=this.getActiveTargetScene();if(!e)return;const{name:i="空节点",position:s=[0,0],id:r=b(),children:a=[]}=t,n=a.filter(t=>!this.getPlayerItemById(t)),o=a.filter(t=>!!this.getPlayerItemById(t));if(n.length&&console.warn(`item ${n.join("、")} is not existed.`),0===o.length)return;this.interactionUtils.initInteractionPlane();const c=this.interactionUtils.getWorldSizeByViewSize(new F(...s))??new N,h=function(t,e,i){const s=JSON.parse(JSON.stringify(i)),r={id:t,name:e,duration:999,type:g.ItemType.null,visible:!0,endBehavior:g.EndBehavior.restart,delay:0,renderLevel:g.RenderLevel.BPlus,content:{options:{startColor:[1,1,1,1]}},components:[],transform:{position:s,eulerHint:{x:0,y:0,z:0},size:{x:1,y:1},scale:{x:1,y:1,z:1}},dataType:g.DataType.VFXItemData},a={id:b(),dataType:g.DataType.ActivationPlayableAsset};return{item:r,components:[],tracks:[{id:b(),dataType:g.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:g.EndBehavior.restart,asset:{id:a.id}}]}],playableAssets:[a]}}(r,i,c);ie(e,h),o.forEach(t=>{se(e,t,r)});const l=this.player.getCompositions()[0],p=le.createEmpty(l,null,i);return p.setInstanceId(h.item.id),p.duration=999,p.defination.delay=0,p.endBehavior=g.EndBehavior.restart,p.transform.setPosition(...c.toArray()),o.forEach(t=>{const e=this.getPlayerItemById(t);e.setParent(p),e.parentId=h.item.id,e.translate(...c.clone().negate().toArray())}),this.refreshSceneAndPageData(),h.item.id}async addTextItem(t){const e=this.getActiveTargetScene();if(!e)return;const{id:i=b(),parentId:s,name:r="文本",lineHeight:a,textWidth:n,fontFamily:o,position:c=[0,0],fontSize:h,fontWeight:l=g.TextWeight.normal,fontStyle:p=g.FontStyle.normal,textAlign:m=g.TextAlignment.left,text:d,textColor:u,textHeight:f=a,outlineColor:y=[.8,.8,.8,1],outlineWidth:x=0,rotation:w=0,url:I}=t;I&&!e.fonts?.find(t=>t.fontFamily===o)&&(e.fonts??(e.fonts=[]),e.fonts.push({fontFamily:o,fontURL:I}));const C={text:d,fontFamily:o,fontSize:h,textColor:u,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:n,textHeight:f,lineHeight:a,textBaseline:g.TextBaseline.top,textOverflow:g.TextOverflow.visible,outline:{outlineColor:y,outlineWidth:x}},D=this.player.getCompositions()[0],z=le.createText(D,null,r);z.setInstanceId(i),z.duration=999,z.defination.delay=0,z.endBehavior=g.EndBehavior.restart;const S=z.getComponent(P),A={options:C,renderer:{renderMode:1},dataType:g.DataType.TextComponent,item:{id:z.getInstanceId()},id:S.getInstanceId()};S.fromData(A),A.options.textHeight=Math.ceil(a*S.lineCount),S.fromData(A),await me.loadFontFamily([{fontURL:I,fontFamily:o}]),S.setFontFamily(o);const T=new F(n,C.textHeight).multiply(this.interactionUtils.viewportParam.scale),k=this.interactionUtils.getWorldSizeByViewSize(T),_=new N(0,0,w),E=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new F(...c)))??new N,B=ee(i,r,E,_,new F(Math.abs(k.x),Math.abs(k.y)),C);e.items.find(t=>t.id===s)&&(B.item.parentId=s),ie(e,B),z.transform.setSize(Math.abs(k.x),Math.abs(k.y)),z.transform.setPosition(...E.toArray()),z.transform.setRotation(..._.toArray()),v(this.sdk.pageData,"You must call SDK#run() first"),this.player.gotoAndStop(this.sdk.pageData.time),this.refreshSceneAndPageData()}deleteItem(t){const e=this.getActiveTargetScene();if(!e)return;!function(t,e){const i=t.items.find(t=>t.id===e);if(!i)return void console.warn(`item ${e} is not exsited.`);t.items=t.items.filter(t=>t.id!==e),t.items.forEach(t=>{t.parentId===e&&(t.transform??(t.transform={position:{x:0,y:0,z:0},eulerHint:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},size:{x:1,y:1}}),t.transform.position.x+=i.transform.position.x,t.transform.position.y+=i.transform.position.y,t.transform.position.z+=i.transform.position.z,t.transform.eulerHint.x+=i.transform.eulerHint.x,t.transform.eulerHint.y+=i.transform.eulerHint.y,t.transform.eulerHint.z+=i.transform.eulerHint.z,t.transform.scale.x*=0!==i.transform.scale.x?i.transform.scale.x:1,t.transform.scale.y*=0!==i.transform.scale.y?i.transform.scale.y:1,t.transform.scale.z*=0!==i.transform.scale.z?i.transform.scale.z:1),delete t.parentId});const s=t.components.filter(t=>t.item.id===e);t.components=t.components.filter(t=>!s.map(t=>t.id).includes(t.id)),s.forEach(e=>{if(e.dataType===g.DataType.SpriteComponent&&e.renderer.texture&&!t.components.find(t=>t.renderer?.texture?.id===e.renderer.texture.id)){const i=t.textures?.find(t=>t.id===e.renderer.texture?.id);i&&(t.textures=t.textures?.filter(t=>t.id!==i.id),t.images=t.images.filter(t=>t.id!==i.source.id))}});const r=[];let a,n;const o=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(+t.version>=3.3){const i=t.components.find(t=>t.id===o.components[0].id);i.items=i.items.filter(t=>t.id!==e),n=i.timelineAsset.id,a=i.sceneBindings.find(t=>t.value.id===e)?.key.id,i.sceneBindings=i.sceneBindings.filter(t=>t.value.id!==e),a&&r.push(a)}else o.items=o.items.filter(t=>t.id!==e),n=o.timelineAsset.id,a=o.sceneBindings.find(t=>t.value.id===e)?.key.id,o.sceneBindings=o.sceneBindings.filter(t=>t.value.id!==e),a&&r.push(a);const c=t.miscs.findIndex(t=>t.id===n);c>=0&&(t.miscs[c].tracks=t.miscs[c].tracks.filter(t=>t.id!==a));const h=t.miscs.find(t=>t.id===a);h&&(h.children.forEach(e=>{r.push(e.id);const i=t.miscs.find(t=>t.id===e.id);i&&r.push(...i.clips.map(t=>t.asset.id))}),r.push(...h.children.map(t=>t.id))),t.miscs=t.miscs.filter(t=>!r.includes(t.id))}(e,t);const i=this.player.getCompositions()[0].items.find(e=>e.getInstanceId()===t);if(i){const t=i.getWorldTransform(),e=t.getWorldPosition(),s=t.getRotation(),r=t.getWorldScale();i.children.forEach(t=>{t.scale(...r.toArray()),t.rotate(...s.toArray()),t.translate(...e.toArray()),t.parent=void 0,t.parentId=void 0}),i.dispose()}}getCanvasUndoRedo(){return this.sdk.canvasUndoRedo}getItemCreateInfo(t,e=!1){v(this.sdk.pageData,"You must call SDK#run() first");const i=this.getPlayerItemById(t),s=this.getViewProperty()?.scene;if(!i||!s)return void console.warn(`item ${t} is not exsited.`);const{transform:r}=i,a=(new N).copyFrom(r.getWorldPosition()),n=r.getRotation(),o=r.getWorldScale();if(e&&i.parent){const t=i.parent.transform;a.subtract(t.getWorldPosition()),o.divide(t.getWorldScale())}this.interactionUtils.initInteractionPlane(a);const c=this.interactionUtils.projectPoint(a);switch(i.type){case g.ItemType.sprite:{const{size:a}=r,h=this.interactionUtils.projectPoint(new N),l=this.interactionUtils.projectPoint(new N(a.x,a.y,0)),p=[Math.abs(l.x-h.x),Math.abs(l.y-h.y)];return{type:"sprite",name:i.name,parentId:e?i.parent?.getInstanceId():void 0,id:i.getInstanceId(),url:re(s,t),size:p,scale:[o.x,o.y],rotation:n.z,position:[c.x,c.y]}}case g.ItemType.null:{const t=i.children.map(t=>t.getInstanceId());return{type:"null",parentId:e?i.parent?.getInstanceId():void 0,children:t,name:i.name,scale:[o.x,o.y],rotation:n.z,position:[c.x,c.y]}}case g.ItemType.text:{const r=s.components.find(e=>e.item.id===t),a=s.fonts?.find(t=>t.fontFamily===r.options.fontFamily)?.fontURL;return{type:"text",id:t,parentId:e?i.parent?.getInstanceId():void 0,name:i.name,lineHeight:r.options.lineHeight,textWidth:r.options.textWidth,fontFamily:r.options.fontFamily,position:[c.x,c.y],rotation:n.z,textHeight:r.options.textHeight,fontSize:r.options.fontSize,fontWeight:r.options.fontWeight,fontStyle:r.options.fontStyle,textAlign:r.options.fontStyle,text:r.options.text,textColor:r.options.textColor,outlineColor:r.options.outline?.outlineColor,url:a}}}}getChildrenIds(t){return this.getPageData()?.items.filter(e=>e.parentId===t)?.map(t=>t.id)??[]}createScreenShotSceneByIds(t){const e=new W;let i;const s=(t,e,s)=>{const{id:r=b(),url:a,name:n="图层",scale:o=[1,1]}=t,c=new F(e.x/o[0],e.y/o[1]),h=i.images.findIndex(t=>t.url===a);let l={};if(a)if(h<0){const t={id:b(),url:a,renderLevel:g.RenderLevel.BPlus};l={id:b(),source:{id:t.id},flipY:!0,dataType:g.DataType.Texture},i.images.push(t),i.textures??(i.textures=[]),i.textures.push(l)}else{const t=i.textures?.find(t=>t.source.id===i.images[h].id);l={id:t?.id}}const p=te(r,new N(s.x,s.y,0),new N(0,0,t.rotation??0),c,new N(t.scale?.[0]??1,t.scale?.[1]??1,1),n,l.id);ie(i,p)},r=(t,e,s)=>{const{id:r=b(),name:a="文本",lineHeight:n,textWidth:o,fontFamily:c,fontSize:h,fontWeight:l=g.TextWeight.normal,fontStyle:p=g.FontStyle.normal,textAlign:m=g.TextAlignment.left,text:d,textColor:u,rotation:f=0,url:y,textHeight:x}=t;y&&!i.fonts?.find(t=>t.fontFamily===c)&&(i.fonts??(i.fonts=[]),i.fonts.push({fontFamily:c,fontURL:y}));const w={text:d,fontFamily:c,fontSize:h,textColor:u,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:o,textHeight:x??n,lineHeight:n},v=ee(r,a,new N(...s.toArray(),0),new N(0,0,f),new F(e.x,e.y),w);ie(i,v)};if(Array.isArray(t)){t.map(t=>this.getViewBoxById(t)).map(t=>e.union(t));const a=e.getSize();i=Qt(a.toArray());const n=(new O).compose(new N(0,0,8),new H,new N(1,1,1)).invert(),o=(new O).perspective(60*_,a.x/a.y,.1,40,!0),c=(new O).multiplyMatrices(o,n),h=c.clone().invert(),l=c.projectPoint(new N).z,p=new N(0,0,l).applyMatrix(h),m=new N(2,2,l).applyMatrix(h),d=Math.abs(m.x-p.x)/a.x,g=Math.abs(m.y-p.y)/a.y;t.forEach(t=>{const i=this.getItemCreateInfo(t,!1);if(!i||"null"===i.type)return;const a=this.getViewBoxById(t),n=a.getSize().multiply(new F(d,g)).abs(),o=a.getCenter().subtract(e.getCenter()).multiply(new F(d,-g));switch(i.type){case"sprite":s(i,n,o);break;case"text":r(i,n,o)}})}else{const a=this.getViewBoxById(t),n=this.getItemCreateInfo(t,!1);e.copyFrom(a);const o=e.getSize();i=Qt(o.toArray());const c=(new O).compose(new N(0,0,8),new H,new N(1,1,1)).invert(),h=(new O).perspective(60*_,o.x/o.y,.1,40,!0),l=(new O).multiplyMatrices(h,c),p=l.clone().invert(),m=l.projectPoint(new N).z,d=new N(0,0,m).applyMatrix(p),g=new N(2,2,m).applyMatrix(p),u=(new N).subtractVectors(g,d);if(n)switch(n.type){case"sprite":s(n,new F(u.x,u.y),new F);break;case"text":r(n,new F(u.x,u.y),new F)}}return i}updateItemOrder(t,e){v(this.sdk.pageData,"You must call SDK#run() first");const i=this.getCurrentComposition();if(!i)return void console.warn("Composition not found.");const s=i.items.find(e=>e.getInstanceId()===t);if(!s)return void console.warn(`Item with id ${t} not found.`);const r=s.parent,a=r.children.filter(t=>!this.isPluginItem(t)),n=r.children.filter(t=>this.isPluginItem(t)),o=a.findIndex(e=>e.getInstanceId()===t);if(-1===o)return void console.warn(`Item with id ${t} not found in siblings.`);let c=o;switch(e){case 0:c=a.length-1;break;case 1:c=0;break;case 2:c=Math.min(o+1,a.length-1);break;case 3:c=Math.max(o-1,0)}if(c===o)return;const[h]=a.splice(o,1);h&&a.splice(c,0,h),r.children=[...n,...a],this.refreshItemRenderOrder(i),this.sdk.pageData.items=[],this.addViewItemsByItems(this.sdk.pageData.items,i.items),this.emitter.emit("pageDataChange",this.sdk.pageData)}isPluginItem(t){return"ModelPluginItem"===t.name}refreshItemRenderOrder(t){v(this.sdk.pageData,"You must call SDK#run() first");const e=(()=>{const e=[],i=t=>{for(const s of t)this.isPluginItem(s)||(e.push(s),s.children.length>0&&i(s.children))},s=[...t.rootItem.children];return i(s),e})();t.items.length=0,t.items.push(...e);for(let e=0;e<t.items.length;e++){const i=t.items[e];i.renderOrder=e,i.setActive(!1),i.setActive(!0)}const i=this.getViewProperty();if(i){const{scene:e}=i,s=e.compositions.find(t=>t.id===e.compositionId)??e.compositions[0];if(s){const i=s.components.map(t=>e.components.find(e=>e.id===t.id)).find(t=>t?.dataType===g.DataType.CompositionComponent);i&&(i.items=t.items.map(t=>({id:t.getInstanceId()})))}}}getViewProperty(t){return v(this.sdk.pageData,"You must call SDK#run() first"),t??(t=this.sdk.pageData.activeData.view),this.sdk.pageData.viewProperties.find(e=>e.id===t)}viewportFit(){v(this.sdk.pageData,"You must call SDK#run() first");const t=new W;this.sdk.pageData.items.forEach(e=>{const i=this.getViewBoxById(e.id);t.union(i)});const{width:e,height:i,scale:s,translation:r}=this.interactionUtils.viewportParam;if(t.isEmpty())this.pageMove(r.clone().negate()),this.pageZoom(-s,void 0,!0);else{const r=t.getCenter(),a=t.getSize(),n=a.x/e*i>a.y?1/(a.x/e):1/(a.y/i),o=(new F).subtractVectors(new F(e/2,i/2),r);this.pageMove(o),this.pageZoom(n*s-s,void 0,!0)}}};import ge from"jszip";import ue from"jszip";var fe,ye,xe,we,ve,Ie,Pe,Ce,be,De,ze,Se,Ae,Te,ke,_e,Ee,Be,Me,Ve="ready",Ge="executable",Ue="dispose",Fe={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},Re="idle",We="convertImage",Le="transcoding",He="audio",Ne="jpeg",Oe="webp",Ke="png",je=(Fe.MP4,Fe.WebP,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo,Fe.Images,Fe.MP4,Fe.WebP,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo,Fe.Images,"default"),Ye="exporting",$e="success",Je="error",Xe={highest:"flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=256[p];[s1][p]paletteuse",high:"flags=bicubic,split[s0][s1];[s0]palettegen=max_colors=200[p];[s1][p]paletteuse",medium:"flags=bilinear,split[s0][s1];[s0]palettegen=max_colors=64[p];[s1][p]paletteuse=dither=bayer",low:"flags=neighbor,split[s0][s1];[s0]palettegen=max_colors=32[p];[s1][p]paletteuse=dither=none"},Ze={highest:"1",high:"3",medium:"6",low:"9"},qe=class{constructor(t){c(this,"sampleRate"),c(this,"duration"),c(this,"channels");const{sampleRate:e=44100,duration:i=1,channels:s=2}=t??{};this.sampleRate=e,this.duration=i,this.channels=s}getBuffer(){const t=this.sampleRate*this.duration*this.channels*2,e=44+t,i=new ArrayBuffer(e),s=new DataView(i);let r=0;const a=t=>{for(let e=0;e<t.length;e++)s.setUint8(r++,t.charCodeAt(e))},n=t=>{s.setUint32(r,t,!0),r+=4},o=t=>{s.setUint16(r,t,!0),r+=2};a("RIFF"),n(e-8),a("WAVE"),a("fmt "),n(16),o(1),o(this.channels),n(this.sampleRate),n(this.sampleRate*this.channels*2),o(2*this.channels),o(16),a("data"),n(t);for(let e=0;e<t;e++)s.setUint8(r++,0);return new Uint8Array(i)}},Qe=["@vvfx/sdk","exporter"],ti=class extends w{constructor(t){super(),c(this,"status",Ve),c(this,"stage",Re),c(this,"mediaType"),c(this,"loggerInTranscoding"),c(this,"multiThreading"),c(this,"extraCanvas"),c(this,"player"),p(this,fe,0),p(this,ye),p(this,xe),p(this,we),p(this,ve),p(this,Ie,[]),p(this,Pe),p(this,Ce),p(this,be,[]),p(this,De,0),p(this,ze),p(this,Se,[]),p(this,Ae,0),p(this,Te,0),p(this,ke,0),p(this,_e,0),p(this,Ee,[]),p(this,Be,[]),p(this,Me,!0);const{mediaType:e,extraCanvas:i,loggerInTranscoding:s,multiThreading:r}=t;this.mediaType=e,this.loggerInTranscoding=s??!1,this.multiThreading=r??!1,this.extraCanvas=i??void 0,this.onInit()}get canceled(){return this.status===Ue}get config(){const t=this.player?.getCompositions()??[],e=t?.[0],i=e?.name??(new Date).getTime().toString(),s=e?.getDuration()??0,r=e?.startTime??0,a=l(this,ze)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:l(this,ze)?.fps??30,backgroundColor:l(this,ze)?.backgroundColor??"#000000",loop:l(this,ze)?.loop??!0,audioEnable:l(this,ze)?.audioEnable??!1}}get gifConfig(){return l(this,ze)?.gifConfig}get apngConfig(){return l(this,ze)?.apngConfig}get progress(){const t=l(this,Te)||1,e=l(this,ke)||1,i=Math.min(t/e,1),s=Math.min(l(this,Ae),t)/t*.4,r=Math.min(l(this,_e),t)/t*.6,a=Math.min(s+r,1);l(this,Se)[l(this,De)]=i;const n=l(this,Se).reduce((t,e,i)=>i<l(this,De)?t+(e||0):t,0)+a*i;return Math.min((o=n,Math.round(100*o)/100),1);var o}get transImageType(){return this.mediaType===Fe.MP4?Ne:this.mediaType===Fe.WebP?Oe:Ke}async onInit(){try{Et("log",[...Qe,"ready"],"starting"),this.status=Ve,await this.loadHelper(this.mediaType),this.status=Ge,Et("log",[...Qe,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=Ue,this.onError(t)}finally{return this.status}}onReset(){this.stage=Re,window.cancelAnimationFrame(l(this,fe)),m(this,fe,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){Et("log",[...Qe,"error"],t),this.onFinish(!1,l(this,Ee),l(this,Be)),this.emit("error",t),this.dispose()}onFinish(t,e,i){Et("log",[...Qe,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("finish",t,e,i)}async loadHelper(t){const e="WebP"===t&&!l(this,we),i=[Fe.MP4,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo].includes(t)&&!l(this,xe);e&&m(this,we,await Zt()),i&&(m(this,xe,await async function(t){const{multiThreading:e}=t??{},i=new jt,s=!!e,r={classWorkerURL:await Yt(Jt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await Yt(Jt.MT.CORE,"text/javascript"),r.wasmURL=await Yt(Jt.MT.WASM,"application/wasm"),r.workerURL=await Yt(Jt.MT.WORKER,"text/javascript")):(r.coreURL=await Yt(Jt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await Yt(Jt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),l(this,xe).on("log",({message:t})=>{if(this.loggerInTranscoding&&Et("log",[...Qe,"transcoding log"],t),this.canceled||this.stage!==Le)return;const e=/frame=\s*(\d+)/.exec(t);if(e?.[1]){const t=Number(e[1]);this.setProgress({currentTaskInTranscodingFrameIndex:t})}}))}getAllTaskFrames(t){return t.reduce((t,e)=>{const{scene:i,fps:s}=e,r=i.compositions?.[0]?.duration??0;return t+Math.round(r*(s??30))},0)}setProgress(t){void 0!==t?.completedTaskPercentArray&&m(this,Se,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&m(this,Ae,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&m(this,Te,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&m(this,_e,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&m(this,ke,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){v(this.player);const{oldTotalTime:i,startTime:s}=this.config;v(i);const r=1e3*i-1e3*i%15;return t=Math.min(t,r/1e3),e?this.player.gotoAndPlay(t-s):this.player.gotoAndStop(t-s),t}getWavAudio(t){m(this,Pe,new qe),l(this,xe)?l(this,xe).writeFile(t,l(this,Pe).getBuffer()):Et("log",[...Qe,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new ue,s=i.folder(t);return v(s),l(this,be).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){v(l(this,we));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${l(this,be).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=l(this,we).cwrap("main","string",["number","number"]),[r,a]=function(t,e){const i=t._malloc(e.length*Uint32Array.BYTES_PER_ELEMENT);return e.forEach((e,s)=>{const r=t._malloc(e.length+1);t.writeAsciiToMemory(e,r),t.setValue(i+Uint32Array.BYTES_PER_ELEMENT*s,r,"i32")}),[e.length,i]}(l(this,we),i);_t(r&&a,"getWebP has error"),s(r,a);const n=l(this,we).FS.readFile(e);return l(this,be).forEach(t=>{l(this,we)?.FS.unlink(t)}),n}async getAPNG(){v(l(this,xe));this.stage=Le;const t="export.apng",{fps:e,scale:i="-1:-1",quality:s="highest"}=this.apngConfig??{},r=[`scale=${i}:force_original_aspect_ratio=decrease:flags=lanczos`];e&&r.push(`fps=${e}`);if(0!==await l(this,xe).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-vf",r.join(","),"-plays",this.config.loop?"0":"1","-compression_level",Ze[s],"-y",t]))throw new Error("the command executed by ffmpeg to generate a apng failed.");return t}async getGIF(){v(l(this,xe));this.stage=Le;const t="export.gif",{fps:e,scale:i="-1:-1",quality:s="highest"}=this.gifConfig??{},r=[`scale=${i}:${Xe[s]}`];e&&r.unshift(`fps=${e}`);if(0!==await l(this,xe).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-loop",this.config.loop?"0":"-1","-vf",r.join(","),"-y",t]))throw new Error("the command executed by ffmpeg to generate a gif failed.");return t}async getMP4(t,e){v(l(this,xe));this.stage=Le;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;this.config.audioEnable&&!l(this,Pe)&&(m(this,Ce,"audio.wav"),this.getWavAudio(l(this,Ce)));if(0!==await l(this,xe).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${r}`,"-y",i]))throw new Error("the command executed by ffmpeg to generate a mp4 failed.");if(l(this,Ce)&&l(this,Pe)){this.stage=He,s="export-with-audio.mp4";if(0!==await l(this,xe).exec(["-i",i,"-i",l(this,Ce),"-c:v","copy","-c:a","aac","-t",`${a}`,"-y",s]))throw new Error("the command executed by ffmpeg to generate a audio of video failed.")}return s&&l(this,xe).deleteFile(i).catch(()=>{Et("log",[...Qe,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){v(l(this,xe));this.stage=Le;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await l(this,xe).exec(["-framerate",String(this.config.fps),"-start_number",String(1),"-i",`image-%4d.${this.transImageType}`,"-c:v","libx264","-crf","23","-pix_fmt","yuv420p","-vf",`pad=ceil(iw/2)*2:ceil(ih/2)*2${s}`,"-y",i]),i}async getVideoByType(t,e){v(l(this,xe));const i=this.mediaType===Fe.APNG,s=this.mediaType===Fe.GIF,r=this.mediaType===Fe.AlphaMaskVideo,a=this.mediaType===Fe.MP4;let n="";try{i&&(n=await this.getAPNG()),s&&(n=await this.getGIF()),a&&(n=await this.getMP4(t,e)),r&&(n=await this.getAlphaMaskVideo(t,e)),this.stage=Re}catch(t){throw t}finally{for(const t of l(this,be))t&&l(this,xe).deleteFile(t)}let o=null;try{v(n);const t=await l(this,xe).readFile(n);o="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{l(this,xe).deleteFile(n).catch(()=>{Et("log",[...Qe,"ffmpeg delete file error"])})}return o}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});m(this,ve,e),l(this,ve).start(0);const i=[];l(this,ve).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},m(this,Ie,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o}=t;v(this.player),v(l(this,ye));const c=l(this,Ae)+1;this.stage=We,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&&Et("log",[...Qe,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),Xt(l(this,ye),s,this.config.backgroundColor);let h=s;this.mediaType===Fe.AlphaMaskVideo&&(v(this.extraCanvas),function(t,e){e.width=2*t.width,e.height=t.height;const i=t.getContext("2d");if(!i)throw new Error("inputCtx is null");const s=e.getContext("2d");if(!s)throw new Error("ctx is null");s.clearRect(0,0,e.width,e.height);const r=i.getImageData(0,0,t.width,t.height),a=i.getImageData(0,0,t.width,t.height),n=r.data;for(let t=0;t<n.length;t+=4){const e=Math.max(0,(n[t+3]??0)-5)/250*255;e<=0?(n[t]=0,n[t+1]=0,n[t+2]=0,n[t+3]=255):(n[t]=(n[t]??0)*e/255,n[t+1]=(n[t+1]??0)*e/255,n[t+2]=(n[t+2]??0)*e/255,n[t+3]=255)}s.putImageData(r,0,0);const o=a.data;for(let t=0;t<o.length;t+=4){const e=Math.max(0,(o[t+3]??0)-5)/250*255;o[t]=e,o[t+1]=e,o[t+2]=e,o[t+3]=255}s.putImageData(a,t.width,0)}(s,this.extraCanvas),h=this.extraCanvas);const p=await async function(t,e,i){return new Promise((s,r)=>{t.toBlob(t=>{t?s(t.arrayBuffer()):r("toBlob failed")},e,i)})}(h,`image/${this.transImageType}`,1),d=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===Fe.Images?r.push(p):this.mediaType===Fe.WebP?(v(l(this,we)),l(this,we).FS.writeFile(d,new Uint8Array(p))):(v(l(this,xe)),await l(this,xe).writeFile(d,new Uint8Array(p))),l(this,be).push(d);if(c===l(this,Te)){this.player?.pause(),await new Promise(t=>{window.requestAnimationFrame(t)});let t=null;"Images"===this.mediaType?t=await this.getImagesZip(this.config.name,r):"WebP"===this.mediaType?t=this.getWebP():[Fe.MP4,Fe.APNG,Fe.GIF,Fe.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(n,o)??null),t&&(Et("log",[...Qe,"done"],"success"),this.emit("done",l(this,ze),!0,t))}else m(this,fe,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o})}))}catch(t){Et("log",[...Qe,"onExportImageFrame","failed"],t),this.emit("done",l(this,ze),!1)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;v(this.player),v(l(this,ye));const e=l(this,Ae)+1;if(this.stage=We,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&&Et("log",[...Qe,"converting log"],`converting ${e} frame image`),Xt(l(this,ye),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<l(this,Te))m(this,fe,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),l(this,ve)?.stop();const t=new Blob(l(this,Ie),{type:"video/webm"}),e=await t.arrayBuffer();Et("log",[...Qe,"done"],"success"),this.emit("done",l(this,ze),!0,e)}}catch(t){Et("log",[...Qe,"done"],"failed",t),this.emit("done",l(this,ze),!1)}}async runTask(t){try{if(this.canceled)return;v(this.player),v(l(this,ye));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[n,o]=e;if(l(this,ye).width=n,l(this,ye).height=o,s.width=n,s.height=o,this.player.resize(),m(this,be,[]),[Fe.MP4,Fe.APNG,Fe.Images,Fe.WebP,Fe.GIF,Fe.AlphaMaskVideo].includes(this.mediaType)){const t={canvas:s,imageBuffers:[],startTime:i,oldTotalTime:r,newTotalTime:a};await this.onExportImageFrame(t)}else"WebM"===this.mediaType&&await this.onExportWebMFrame(s)}catch(t){Et("log",[...Qe,"run task error"],t),this.emit("done",l(this,ze),!1)}}clearTaskInfo(){m(this,De,0),m(this,ze,void 0),m(this,Se,[]),m(this,Ae,0),m(this,Te,0),m(this,ke,0),m(this,_e,0),m(this,Ee,[]),m(this,Be,[]),m(this,Me,!0)}clearFFMpegCore(){if(l(this,xe)){for(const t of l(this,be))t&&l(this,xe).deleteFile(t);m(this,be,[]),l(this,xe).terminate(),m(this,xe,void 0)}}clearImage2WebPCore(){l(this,we)&&(l(this,we).FS.quit(),m(this,we,void 0))}clearMediaRecorder(){l(this,ve)&&(l(this,ve).stop(),m(this,ve,void 0)),m(this,Ie,[])}clearAllListeners(){for(const t of this.getListeners("ready"))this.off("ready",t);for(const t of this.getListeners("progress"))this.off("progress",t);for(const t of this.getListeners("done"))this.off("done",t);for(const t of this.getListeners("finish"))this.off("finish",t);for(const t of this.getListeners("error"))this.off("error",t)}onCancel(){this.canceled||(this.onFinish(!1,l(this,Ee),l(this,Be)),this.status=Ue,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),Et("log",Qe,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===Ve)return Et("log",[...Qe],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===Ue){if(await this.onInit()===Ue)throw new Error("init environment failed")}if(this.clearTaskInfo(),!l(this,ye)){const t=document.createElement("canvas");t.dataset.key="player-canvas",m(this,ye,t)}this.player||(this.player=new f({canvas:l(this,ye),pixelRatio:1,transparentBackground:!0,renderOptions:{willCaptureImage:!0}}),this.player.on("rendererror",t=>{this.onError(t)}),this.player.on("webglcontextlost",t=>{this.onError(t)}));let e=null;e??(e=document.querySelector('canvas[data-key="container-canvas"]')),e??(e=document.createElement("canvas")),e.dataset.key="container-canvas",e.style.display="none",this.setProgress({allTaskFrames:this.getAllTaskFrames(t)});const i=[],s=[];let r=!0;for(const[a,n]of t.entries()){if(this.canceled){r=!1;break}m(this,De,a),m(this,ze,n);const{size:t,scene:o}=n;await new Promise(async c=>{try{if(!this.player)throw new Error("player not found");Et("log",[...Qe,"export"],"start",n),qt(this.player),await this.player.loadScene(o,{env:"editor",autoplay:!1});const h=this.config.oldTotalTime,l=0;this.player.pause(),this.setProgress({currentTaskFrameIndex:0,currentTaskTotalFrames:Math.round(h*this.config.fps)});const p=(t,e,o)=>{this.off("done",p),i[a]=n,e&&o?s[a]=o:r=!1,c()};this.on("done",p);const m={size:t,startTime:l,containerCanvas:e};await this.runTask(m)}catch(t){Et("log",[...Qe,"export error"],t),r=!1,c()}})}m(this,Ee,i),m(this,Be,s),m(this,Me,r)}catch(t){this.onError(t),m(this,Me,!1)}e>=1&&l(this,Me)?this.onFinish(!0,l(this,Ee),l(this,Be)):this.onFinish(!1,l(this,Ee),l(this,Be))}dispose(){this.status=Ue,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,l(this,ye)?.remove(),m(this,ye,void 0),m(this,Ce,void 0),m(this,Pe,void 0)}};fe=new WeakMap,ye=new WeakMap,xe=new WeakMap,we=new WeakMap,ve=new WeakMap,Ie=new WeakMap,Pe=new WeakMap,Ce=new WeakMap,be=new WeakMap,De=new WeakMap,ze=new WeakMap,Se=new WeakMap,Ae=new WeakMap,Te=new WeakMap,ke=new WeakMap,_e=new WeakMap,Ee=new WeakMap,Be=new WeakMap,Me=new WeakMap;var ei={[Fe.MP4]:{suffix:"mp4",error:"export mp4 is error"},[Fe.GIF]:{suffix:"gif",error:"export gif is error"},[Fe.Images]:{suffix:"zip",error:"export Images is error"},[Fe.APNG]:{suffix:"apng",error:"export APNG is error"},[Fe.WebP]:{suffix:"webp",error:"export WebP is error"},[Fe.AlphaMaskVideo]:{suffix:"mp4",error:"export AlphaMaskVideo is error"},[Fe.WebM]:{suffix:"webm",error:"export WebM is error"}},ii=class extends w{constructor(t){super(),c(this,"_config"),c(this,"_status",je),c(this,"_exportMedia"),this._config=t,this._exportMedia=new ti(t)}get status(){return this._status}onExportMedia(t,e,i,s){if(!e.length||!i)return void Et("info",["@vvfx/sdk","export media is error","result or suffix is empty"]);const r=t[0]?.folderName,a=new ge;e.forEach((e,s)=>{if(!e)return;const{name:r}=t[s]??{};r&&a.file(`${r}.${i}`,e)}),a.generateAsync({type:"blob"}).then(t=>{!function(t,e,i="application/octet-stream"){const s=new Blob(Array.isArray(t)?t:[t],{type:i}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}(t,`${r}.zip`,"application/zip")}).catch(t=>{Et("error",["@vvfx/sdk"],s??"export media is error",t)})}onExportProgress(t){this.emit("progress",t)}onExportDone(t,e,i){this.emit("done",t,e,i)}onExportError(t){this._status=Je,Et("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=Ye,this._exportMedia.onExport(t),this._exportMedia.on("progress",this.onExportProgress.bind(this)),this._exportMedia.on("done",this.onExportDone.bind(this)),this._exportMedia.once("finish",(e,i,s)=>{if(this._status=e?$e:Je,this.emit("complete",e,i,s),this._config.isOutputBuffer||!s||0===s.length)return;const{suffix:r,error:a}=ei[this._config.mediaType];r&&this.onExportMedia(t,s,r,a)}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=Je,this._exportMedia.onCancel(),this.emit("complete",!1,[],[])}dispose(){this._exportMedia.dispose()}},si=class{constructor(){c(this,"enabled",!0),c(this,"_player"),c(this,"_container"),this._container=document.createElement("canvas"),this._player=new f({canvas:this._container,manualRender:!0,renderOptions:{willCaptureImage:!0}})}async generate(t,e,i,s,r){if(!this.enabled)return void console.warn("Screen shot is not opened, use #SDK.setConfig() open this feature.");qt(this._player);const[a,n]=e;this._container.width=a,this._container.height=n,this._player.resize();const o=JSON.parse(JSON.stringify(t));await this._player.loadScene(o,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(s);const[c,h]=i,l=document.createElement("canvas");l.width=c,l.height=h;const p=l.getContext("2d");r??(r=[255,255,255,1]),p&&(p.fillStyle=`rgba(${r.join(",")})`,p.fillRect(0,0,c,h),this.drawImageCover(p,this._player.canvas,0,0,c,h,.5,.5));const m=l.toDataURL("image/png");return qt(this._player),m}dispose(){this._player.dispose()}drawImageCover(t,e,i,s,r,a,n,o,c){2===arguments.length&&(i=s=0,r=t.canvas.width,a=t.canvas.height),n="number"==typeof n?k(n,0,1):.5,o="number"==typeof o?k(o,0,1):.5,c??(c={left:0,top:0,width:e instanceof HTMLVideoElement?e.videoWidth:e.width,height:e instanceof HTMLVideoElement?e.videoHeight:e.height});const h=c.width,l=c.height,p=Math.min(r/h,a/l);let m=h*p,d=l*p,g=1;m<r&&(g=r/m),Math.abs(g-1)<1e-14&&d<a&&(g=a/d),m*=g,d*=g;const u=Math.max(h/(m/r),0),f=Math.max(l/(d/a),0),y=Math.min((h-u)*n,h),x=Math.min((l-f)*o,l);t.drawImage(e,y+c.left,x+c.top,u,f,i,s,r,a)}},ri={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},ai=class{constructor(t){c(this,"_player"),c(this,"_container"),c(this,"size",[0,0]),c(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new f({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r,a){if(!ci.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new f({canvas:this._container,manualRender:!0})),r??(r=[0,0,0,0]),a??(a=i[0]<i[1]?"y":"x"),this.size=[...s],this._container.width=this.size[0],this._container.height=this.size[1],qt(this._player),this._player.resize();const n=JSON.parse(JSON.stringify(t));await this._player.loadScene(n,{reusable:!0,autoplay:!1}),this._player.gotoAndStop(e);const o=this._player.getCompositions()[0];if(o){const[e,n]=s,c=i[0]/i[1],h=e/n;c>h&&this.keepDistribute(t,o,h/c,s);const[l,p,m,d]=r,g=e-m-d,u=n-l-p,f=[(m-d)/2,(l-p)/2],y=(new W).setFromCenterAndSize(new F(e,n).divide(2),new F(e,n)),x=(new W).setFromCenterAndSize(new F(e,n).divide(2).add(new F(...f)),new F(g,u));this.keepAdsorption("topAdsorption",t,o,f,y,x,a),this.keepAdsorption("bottomAdsorption",t,o,f,y,x,a),this.keepAdsorption("leftAdsorption",t,o,f,y,x,a),this.keepAdsorption("rightAdsorption",t,o,f,y,x,a),this.keepAdsorption("centerAdsorption",t,o,f,y,x,a),this.keepDoubleAdsorption("bottomCenterAdsorption",t,o,f,y,x)}return t}keepDistribute(t,e,i,s){const r=t=>{const i=(new O).copyFrom(e.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===ri[a]&&!t.parentId).forEach(a=>{const n=e.items.filter(t=>t.parentId===a.getInstanceId()),o=n.find(t=>"check-area"===t.name),c=o?this.getViewBoxByHeadlessPlayerItem(o,[],r):this.getViewBoxByHeadlessPlayerItem(a,n,r),h=a.transform.position.clone(),l=c.getCenter(),p=new F(...s.map(t=>t/2)),m=l.y-p.y;((t,i,r)=>{const{z:a}=t.transform.getWorldPosition(),{x:n,y:o}=e.camera.getInverseVPRatio(a);t.transform.translate(2*i*n/s[0],-2*r*o/s[1],0)})(a,0,m/i-m),a.transform.updateLocalMatrix();const d=a.transform.position.clone().subtract(h).toArray();this._pageDataUtils.changeSceneItemProperty(t,{itemId:a.getInstanceId(),type:a.type,propertyName:"position",propertyValue:d})})})}keepAdsorption(t,e,i,s,r,a,n){const{x:o,y:c}=r.getSize(),h=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:n}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/o,-2*s*n/c,0)},l=t=>{const e=(new O).copyFrom(i.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,c)},p=ri[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===p&&!t.parentId).forEach(r=>{const o=i.items.filter(t=>t.parentId===r.getInstanceId()),c=o.find(t=>"check-area"===t.name),p=r.transform.position.clone(),m=["leftAdsorption","rightAdsorption"].includes(t)?"x":"y",d=["leftAdsorption","topAdsorption"].includes(t)?1:-1,g=["leftAdsorption","topAdsorption"].includes(t)?"min":"max",u=["leftAdsorption","topAdsorption"].includes(t)?"max":"min",f=3===r.name.split("-").length,y=Number(r.name.split("-")[1]),x=new F,w=[1,1],v=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l);h(r,...s),v.getSize().x>a.getSize().x&&(w[0]=a.getSize().x/v.getSize().x,w[1]=a.getSize().x/v.getSize().x,r.scale(...w,1)),r.transform.updateLocalMatrix();const I=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l),P=new F;if(!a.containsBox(I)){const{min:t,max:e}=I,{min:i,max:s}=a;P.x+=t.x<i.x?i.x-t.x:0,P.x+=e.x>s.x?s.x-e.x:0,P.y+=t.y<i.y?i.y-t.y:0,P.y+=e.y>s.y?s.y-e.y:0,h(r,...P.toArray()),r.transform.updateLocalMatrix()}const C=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l);if(!Number.isNaN(y)&&f)if("centerAdsorption"!==t){const t=Math.abs(C[u][m]-a[g][m]),e=a.getSize()[m]*y;t>e&&(x[m]=(e-t)*d,h(r,...x.toArray()),r.transform.updateLocalMatrix())}else{const t=C.getSize()[n],e=a.getSize()[n];if(t/e>y){const i=e*y/t;r.scale(i,i,1),w[0]*=i,w[1]*=i}}const b=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l),D=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),z=new W;if(D.forEach(t=>{const e=i.items.filter(e=>e.parentId===t.getInstanceId()),s=e.find(t=>"check-area"===t.name),r=s?this.getViewBoxByHeadlessPlayerItem(s,[],l):this.getViewBoxByHeadlessPlayerItem(t,e,l);z.union(r)}),!z.isEmpty()&&z.max.y>b.min.y)if("centerAdsorption"===t){const t=z.max.y-b.min.y;h(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=b.getSize().y,e=a.getSize().y-(z.max.y-a.min.y);let i=z.max.y-b.min.y;if(t>e){const s=e/t;w[0]*=s,w[1]*=s,r.scale(s,s,1),r.transform.updateLocalMatrix(),i-=(t-e)/2}h(r,0,i),r.transform.updateLocalMatrix()}const S=r.transform.position.clone().subtract(p).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"position",propertyValue:S}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:r.getInstanceId(),type:r.type,propertyName:"size",propertyValue:w})})}keepDoubleAdsorption(t,e,i,s,r,a){const{x:n,y:o}=r.getSize(),c=(t,e,s)=>{const{z:r}=t.transform.getWorldPosition(),{x:a,y:c}=i.camera.getInverseVPRatio(r);t.transform.translate(2*e*a/n,-2*s*c/o,0)},h=t=>{const e=(new O).copyFrom(i.camera.getViewProjectionMatrix());return(new F).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(n,o)},l=ri[t];i.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===l&&!t.parentId).forEach(t=>{const r=i.items.filter(e=>e.parentId===t.getInstanceId()),n=r.find(t=>"check-area"===t.name),o=t.transform.position.clone(),l=3===t.name.split("-").length,p=Number(t.name.split("-")[1]),m=[1,1],d=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);c(t,...s),d.getSize().x>a.getSize().x&&(m[0]=a.getSize().x/d.getSize().x,m[1]=a.getSize().x/d.getSize().x,t.scale(...m,1)),t.transform.updateLocalMatrix();const g=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h);if(!Number.isNaN(p)&&l){const e=g.getSize().y,i=a.getSize().y;if(e/i>p){const s=i*p/e;t.scale(s,s,1),m[0]*=s,m[1]*=s}}const u=n?this.getViewBoxByHeadlessPlayerItem(n,[],h):this.getViewBoxByHeadlessPlayerItem(t,r,h),f=new F;if(!a.containsBox(u)){const{min:e,max:i}=u,{min:s,max:r}=a;f.x+=e.x<s.x?s.x-e.x:0,f.x+=i.x>r.x?r.x-i.x:0,f.y+=e.y<s.y?s.y-e.y:0,f.y+=i.y>r.y?r.y-i.y:0,c(t,...f.toArray()),t.transform.updateLocalMatrix()}const y=t.transform.position.clone().subtract(o).toArray();this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"position",propertyValue:y}),this._pageDataUtils.changeSceneItemProperty(e,{itemId:t.getInstanceId(),type:t.type,propertyName:"size",propertyValue:m})})}getViewBoxByHeadlessPlayerItem(t,e,i){const s=new W,{transform:r,composition:a}=t;switch(t.type){case g.ItemType.sprite:case g.ItemType.plugin:case g.ItemType.video:case g.ItemType.richtext:case g.ItemType.text:case g.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,n=(new O).copyFrom(a?.transform.getWorldMatrix()??new O).invert().multiply(r.getWorldMatrix()),{x:o,y:c}=t.clone().divide(2),h=new N(o,c,0).applyMatrix(n),l=new N(o,-c,0).applyMatrix(n),p=new N(-o,-c,0).applyMatrix(n),m=new N(-o,c,0).applyMatrix(n),d=i(h).round(2),g=i(l).round(2),u=i(p).round(2),f=i(m).round(2);s.setFromVec2Array([d,g,u,f]);const y=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});y&&y.map(t=>s.union(t));break}case g.ItemType.null:{const t=e?.map(t=>{const e=a?.items.filter(e=>e.parentId===t.getInstanceId())??[];return this.getViewBoxByHeadlessPlayerItem(t,e,i)});t&&t.map(t=>s.union(t));break}}return s}dispose(){this._player?.dispose()}},ni=class{constructor(){c(this,"index",0),c(this,"operations",[])}push(t){this.operations.push(t)}undo(){const t=Math.max(0,this.index-1);if(t!==this.index)return this.index=t,this.operations[t]}redo(){const t=Math.min(this.index+1,this.operations.length-1);if(t!==this.index)return this.index=t,this.operations[t]}clear(){this.operations=[]}},oi=class t{constructor(e){c(this,"_eventEmitter",new w),c(this,"_pageData"),c(this,"_screenShot"),c(this,"_exporter"),c(this,"_pageDataUtils"),c(this,"_sizeAdapt"),c(this,"_gestureHandler"),c(this,"disposables",[]),c(this,"_isSwitchScene",!1),c(this,"_canvasUndoRedo",new ni),c(this,"player"),c(this,"_container"),c(this,"_playerContainer"),c(this,"on",this._eventEmitter.on),this._container=e;const[i,s]=[e.offsetWidth,e.offsetHeight],r=document.createElement("div");r.id="player-container",r.style.width=`${i}px`,r.style.height=`${s}px`,r.style.position="absolute",r.style.backgroundRepeat="no-repeat",r.style.backgroundPosition="center center",e.appendChild(r),this._playerContainer=r,this.player=new f({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if(v(this._pageData,"You must call SDK#run() first"),this._isSwitchScene)return;const t=this.player.getCompositions()[0]?.time;if(this._pageData.playing)if(void 0!==t)this._pageData.time===t&&this.player.pause(),this._pageData.time=t,this._pageDataUtils.refreshPageTime(t);else{this._pageData.playing=!1,this.setPlayProgress(100);const t=this.getViewProperty(this._pageData.activeData.view??0)?.scene,e=t?.compositions.find(e=>e.id===t.compositionId);this._pageData.time=e?.duration??2,this._pageDataUtils.refreshPageTime(this._pageData.time)}this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}),this._eventEmitter.on("pageDataChange",t=>{this._pageData=t,this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.view=t;const e=this.getViewProperty(t);this._gestureHandler.ignoreInteraction=!!e?.ignoreInteraction}),this._eventEmitter.on("sdkConfigChange",(t,e)=>{this.checkExporter(t.exportConfig,e.exportConfig)}),this._pageDataUtils=new de(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportConfig),this._gestureHandler=new Nt(e),this._screenShot=new si,this._sizeAdapt=new ai(this._pageDataUtils);const a=new ResizeObserver(()=>{if(!this._pageData)return;const i=[e.offsetWidth,e.offsetHeight],s=this.getViewProperty(this._pageData.activeData.view??0);if(!s)return;const{size:r}=s,[a,n]="template"===t.config.mode?this._pageDataUtils.getPlayerSizeByParent(i,r):i;this._playerContainer.style.width=`${a}px`,this._playerContainer.style.height=`${n}px`,this.player.resize(),this._pageDataUtils.refreshInteractionParam(),this._gestureHandler.resize()});a.observe(e),this.disposables.push(()=>{a.disconnect()})}get container(){return this._container}get pageData(){return this._pageData}get exportStatus(){return this?._exporter?.status}get canvasUndoRedo(){return this._canvasUndoRedo}get exportOptions(){if(!this.pageData)return[];const t=this.pageData.viewProperties.filter(t=>!t.ignoreInteraction),e=t[0]?.scene?.compositions?.[0]?.name??"videos",i=[];return t.map((t,s)=>{const{size:r,scene:a,export:{name:n,...o}}=t,c=r?.[0]&&r?.[1]?` (${s+1})_${r[0]}×${r[1]}`:` (${s+1})`;let h="";return h=n?function(t,e){if(!e.includes(t))return t;let i=1,s=`${t} (${i})`;for(;e.includes(s);)i++,s=`${t} (${i})`;return s}(n,i):`${e}${c}`,i.push(h),{folderName:e,name:h,size:r,scene:JSON.parse(JSON.stringify(a)),...o}})}dispose(){this.player?.dispose(),this._screenShot?.dispose(),this._pageData=void 0,this._playerContainer.remove(),this?._exporter?.dispose(),this._screenShot.dispose(),this._gestureHandler.dispose(),this.disposables.forEach(t=>{t()})}async getInitParam(t){const e=JSON.parse(JSON.stringify(t));if("editor"===e.mode){const t=[this._container.offsetWidth,this._container.offsetHeight];return{scene:Qt(t),viewParams:[{size:t,export:{audioEnable:!1}}],options:{asyncMode:!1,safeAreaPreview:!1,adsorption:!0}}}{if("string"==typeof e.scene)try{const t=await fetch(e.scene,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);const i=await t.json(),s=i.compositions.find(t=>t.id===i.compositionId)??i.compositions[0],r=e.viewParams?.length?e.viewParams:[{size:s.previewSize??[750,1624],export:{audioEnable:!1}}];return{...e,scene:i,viewParams:r}}catch(t){throw new Error(`Failed to fetch scene data from ${e.scene}: ${t instanceof Error?t.message:String(t)}`)}const t=e.scene.compositions.find(t=>t.id===e.scene.compositionId)??e.scene.compositions[0],i=e.viewParams?.length?e.viewParams:[{size:t.previewSize??[750,1624],export:{audioEnable:!1}}];return{...e,scene:e.scene,viewParams:i}}}checkExporter(t,e){this._exporter&&!Bt(t,e)&&(this._exporter.dispose(),this.initExporter(e))}initExporter(t){this._exporter=new ii(t),this._exporter.on("progress",t=>{this._eventEmitter.emit("exportProgress",t)}),this._exporter.on("done",(t,e,i)=>{this._eventEmitter.emit("exportDone",t,e,i)}),this._exporter.on("complete",(t,e,i)=>{this._eventEmitter.emit("exportComplete",t,e,i)})}async initSDK(e){var i;const{scene:s,viewParams:r,options:a}=e,n=[];if(t.config.pageConfig.staticPreview){const t=JSON.parse(JSON.stringify(s)),e=t.compositions.find(e=>e.id===t.compositionId)??t.compositions[0];if(e){const[i,s]=e.previewSize??[1080,1920],r=e.duration??0;n.push({size:[i,s],safeArea:[0,0,0,0],previewSafeAreas:[],id:0,scene:t,ignoreInteraction:!0,export:{time:r,audioEnable:!1}})}}for(let e=0;e<r.length;e++){const a=r[e];if(!a)continue;let o=JSON.parse(JSON.stringify(s));const c=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0];v(c);const h=c.previewSize??[750,1624],l=h,p=a.size??h;c.previewSize=p;const m=c.duration??0,d=a.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(o=await this._sizeAdapt.adjustment(o,m,l,p,d,a.adaptionDirection)),(i=a.export).time??(i.time=m),n.push({...a,size:p,safeArea:d,previewSafeAreas:[...a.previewSafeAreas??[]],id:e+1,scene:o,ignoreInteraction:!1})}const o=n[0]?.scene;if(!o)return void console.warn("SDK need one view property at least.");const c=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0],h={...a,zoom:1,translation:[0,0],asyncMode:a.asyncMode??!1},l=(c?.duration??0)-.1,p=t.config.pageConfig.staticPreview?1:0;this._pageData={scene:JSON.parse(JSON.stringify(s)),time:l,property:h,activeData:{view:n[p].id,selectedItems:[]},items:[],viewProperties:n,playing:!1},this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),this._gestureHandler.ignoreInteraction=!!n[1]?.ignoreInteraction,t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=h.safeAreaPreview,this._eventEmitter.emit("progress",{duration:l,time:l,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing}),await this._pageDataUtils.loadScene(this._pageData.activeData.view),this._pageDataUtils.refreshPageTime(l)}async run(e){t.config.mode=e.mode,t.config.pageConfig.staticPreview="template"===e.mode&&t.config.pageConfig.staticPreview;const i=await this.getInitParam(e);await this.initSDK(i),this._eventEmitter.emit("pageDataChange",this.getPageData())}getPageData(){return JSON.parse(JSON.stringify(this._pageData))}getActiveItems(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem??""}setSelectedItems(t){this._pageDataUtils.clearPreSelectedItem(),this._pageDataUtils.clearSelectedItems(),this._pageDataUtils.addSelectedItems([...t])}getItemProperty(t){v(this._pageData,"You must call SDK#run() first");const e=this._pageData.items.find(e=>e.id===t.itemId);if(e&&e.type===t.type)return{type:e.type,property:e.property}}getItemPropertyValue(t){v(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){v(this._pageData,"You must call SDK#run() first");const e=this.getViewProperty(this._pageData.activeData.view??0)?.ignoreInteraction;e?console.warn("Static scene cannot change."):(await this._pageDataUtils.changeItemProperty(t),this._gestureHandler.render(),this._eventEmitter.emit("pageDataChange",this.getPageData()))}async generateScreenShot(t,e=[300,400],i,s){v(this._pageData,"You must call SDK#run() first");const r=this.getViewProperty(t);if(!r)return"";const{scene:a,size:[n,o]}=r,c=a.compositionId,h=a.compositions.find(t=>t.id===c);i??(i=h?.duration??0);const l=JSON.parse(JSON.stringify(a));return await this._screenShot.generate(l,[n,o],e,i,s)}async switchScene(t){if(v(this._pageData,"You must call SDK#run() first"),t===this._pageData.activeData.view)return;this._isSwitchScene=!0;const e=this._pageData.viewProperties[t];if(e){const t=this._pageData.playing;this._pageData.activeData={view:e.id,selectedItems:[],preSelectedItem:void 0},await this._pageDataUtils.loadScene(e.id),t&&(this._pageData.playing=t,this.player.gotoAndPlay(this._pageData.time))}else console.warn("target scene does not exist.");this._eventEmitter.emit("selectedViewChange",t),this._eventEmitter.emit("pageDataChange",this.getPageData()),this._isSwitchScene=!1}getPageConfig(){return v(this._pageData,"You must call SDK#run() first"),{safeAreaPreview:this._pageData.property.safeAreaPreview,zoom:this._pageData.property.zoom,adsorption:this._pageData.property.adsorption,asyncMode:this._pageData.property.asyncMode}}setPageConfig(e){v(this._pageData,"You must call SDK#run() first");const{adsorption:i,safeAreaPreview:s,zoom:r}=this._pageData.property;this._pageData.property={...this._pageData.property,...e},this._pageData.property.zoom!==r&&this._pageDataUtils.setPageZoom(this._pageData.property.zoom),i!==e.adsorption&&(t.config.gestureHandlerConfig.adsorptionGizmoEnabled=e.adsorption),s!==e.safeAreaPreview&&(t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaEnabled=e.safeAreaPreview),this._gestureHandler.render()}async setPlayProgress(t){v(this._pageData,"You must call SDK#run() first");const e=(this.player.getCompositions()[0]?.getDuration()??2)*t/100;this._pageData.time=e;!this.player.getCompositions().length&&(qt(this.player),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0));this._pageData.playing?this.player.gotoAndPlay(e):(this.player.gotoAndStop(e),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:e,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!0})),this._pageDataUtils.refreshPageTime(e)}getViewItems(){return this.getPageData()?.items??[]}async setPlayState(t){v(this._pageData,"You must call SDK#run() first");const e="play"===t;if(this._pageData.playing!==e){if(this._pageData.playing=e,this._gestureHandler.ignoreInteraction=e,e){const t=this.player.getCompositions(),e=this.getViewProperty(this._pageData.activeData.view??0);await this.player.loadScene(e.scene,{autoplay:!1}),this.player.gotoAndPlay(this._pageData.time),this.destroyCompositions(t)}else this.player.gotoAndStop(this._pageData.time);this._gestureHandler.render()}}getViewThumbnail(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(async t=>({id:t.id,thumbnail:await this.generateScreenShot(t.id)}))}getViewScene(){return v(this._pageData,"You must call SDK#run() first"),this._pageData.viewProperties.map(t=>({id:t.id,thumbnail:t.scene}))}destroyCompositions(t){t.forEach(t=>{t.dispose();const e=this.player.getCompositions(),i=e.indexOf(t);i>-1&&e.splice(i,1)})}onExport(){t.config.exportConfig.enabled&&(v(this.pageData,"You must call SDK#run() first"),v(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){v(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){v(this._pageData,"You must call SDK#run() first"),this._pageData.activeData={view:this._pageData.viewProperties[this._pageData.viewProperties.length-1].id,selectedItems:[],preSelectedItem:void 0},this._pageData.viewProperties.push(...t.viewProperties),this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}async runByPageData(t){const e=JSON.parse(JSON.stringify(t));e.property.zoom=1,e.property.translation=[0,0],this._pageData=e,this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),await this._pageDataUtils.loadScene(this.pageData?.activeData.view??0),this._pageDataUtils.refreshPageTime(this._pageData.time),this._eventEmitter.emit("pageDataChange",this.getPageData())}async reloadPageDataByScene(t){v(this._pageData,"You must call SDK#run() first");let e=JSON.parse(JSON.stringify(t));if("string"==typeof e)try{const t=await fetch(e,{mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}, statusText: ${t.statusText}`);e=await t.json()}catch(t){throw new Error(`Failed to fetch scene data from ${e}: ${t instanceof Error?t.message:String(t)}`)}this._pageData.time=e.compositions.find(t=>t.id===e.compositionId)?.duration??2,this._pageData.viewProperties.forEach(t=>{t.scene=JSON.parse(JSON.stringify(e))}),this._pageDataUtils.init(),await this._gestureHandler.init(this._pageDataUtils,this._eventEmitter),await this._pageDataUtils.loadScene(this._pageData.activeData.view??0),this._eventEmitter.emit("progress",{duration:this.player.getCompositions()[0]?.getDuration()??2,time:this._pageData.time,end:this.player.getCompositions()[0]?.isDestroyed??!1,paused:!this._pageData.playing})}async addViewParams(e){var i;v(this._pageData);const s=[],r=this._pageData.viewProperties[this._pageData.viewProperties.length-1]?.id??this._pageData.viewProperties.length-1;for(let a=0;a<e.length;a++){const n=e[a];if(!n)continue;let o=JSON.parse(JSON.stringify(this._pageData.scene));const c=o.compositions.find(t=>t.id===o.compositionId)??o.compositions[0];v(c);const{previewSize:h=[750,1624]}=c,l=h,p=n.size??h;c.previewSize=p;const m=c.duration??0,d=n.safeArea??[0,0,0,0];t.config.sizeAdaptConfig.enabled&&(o=await this._sizeAdapt.adjustment(o,m,l,p,d,n.adaptionDirection)),(i=n.export).time??(i.time=m),s.push({...n,size:p,safeArea:d,previewSafeAreas:[...n.previewSafeAreas??[]],id:r+1+a,scene:o,ignoreInteraction:!1})}this._pageData.viewProperties.push(...s),this._eventEmitter.emit("pageDataChange",this.getPageData())}async deleteViewParams(t){t.sort((t,e)=>t-e);for(let e=0;e<t.length;e++){const i=t[e];v(this._pageData);const s=i-e,r=this._pageData.viewProperties.findIndex(t=>t.id===s);if(!0===this._pageData.viewProperties[r]?.ignoreInteraction){console.warn("target view ignore interaction, it can not be deleted.");continue}if(r<0){console.warn("Target view is not existed.");continue}this._pageData.viewProperties.splice(r,1);const a=this._pageData.activeData.view??0;s===a?(this._pageData.activeData.view=0,await this._pageDataUtils.loadScene(0)):s<a&&(this._pageData.activeData.view=a-1),this._pageData.viewProperties.forEach(t=>{t.id>s&&(t.id-=1)})}this._eventEmitter.emit("selectedViewChange",this._pageData?.activeData?.view??0),this._eventEmitter.emit("pageDataChange",this.getPageData())}setExportParam(t,e){v(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||Object.assign(i.export,t)})}setPageZoom(t){v(this._pageData),this._pageData.property.zoom=t,this._pageDataUtils.setPageZoom(this._pageData.property.zoom),this._gestureHandler.render()}setStaticPreviewEnabled(e){t.config.pageConfig.staticPreview=e}setStaticPreviewName(e){t.config.pageConfig.staticPreviewName=e}setAsyncEnabled(e){t.config.pageConfig.asncMode=e}setGroupVisibleEnabled(e){t.config.pageConfig.groupVisible=e}addFilterItemNames(e){"string"==typeof e?Z(t.config.pageConfig.filterItemNames,e):e.forEach(e=>{Z(t.config.pageConfig.filterItemNames,e)})}setPreferenceBackgroundColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.markColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.markAlpha=e[3]??.3,this._gestureHandler.render()}setSafeAreaColor(e){t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxColor=e[0]<<16|e[1]<<8|e[2],t.config.gestureHandlerConfig.preferenceGizmoConfig.safeAreaBoxAlpha=e[3]??.3,this._gestureHandler.render()}setSizeAdaptEnabled(e){t.config.sizeAdaptConfig.enabled=e}setScreenShotEnabled(e){t.config.screenShotConfig.enabled=e}setExportConfig(e){const i=Object.assign({},t.config.exportConfig,e);this.checkExporter(t.config.exportConfig,i),t.config.exportConfig=i}setSelectorGizmoPreSelectConfig(e,i){void 0!==e&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedColor=e),void 0!==i&&(t.config.gestureHandlerConfig.selectorGizmoConfig.preSelectedWidth=i),this._gestureHandler.render()}setTranformGizmoWireframeConfig(e){void 0!==e.wireframeAlpha&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeAlpha=e.wireframeAlpha),void 0!==e.wireframeColor&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeColor=e.wireframeColor),void 0!==e.wireframeWidth&&(t.config.gestureHandlerConfig.transformGizmoConfig.wireframeWidth=e.wireframeWidth),this._gestureHandler.render()}getSDKConfig(){return t.config}setSDKConfig(e){const i=Object.assign({},t.config);this._eventEmitter.emit("sdkConfigChange",i,e),t.config=e}setSDKBackground(t,e){switch(t){case"color":this._container.style.removeProperty("background-color"),this._container.style.removeProperty("background-image"),this._container.style.removeProperty("background-repeat"),this._container.style.removeProperty("background-position"),this._container.style.removeProperty("background-size"),e&&(this._container.style.backgroundColor=e);break;case"image":this._container.style.removeProperty("background-color"),this._container.style.removeProperty("background-image"),this._container.style.removeProperty("background-repeat"),this._container.style.removeProperty("background-position"),this._container.style.removeProperty("background-size"),e&&(this._container.style.backgroundImage=`url(${e})`);break;case"chess-board":e??(e="#CCCCCC"),this._container.style.backgroundColor=e,this._container.style.backgroundImage="linear-gradient(45deg, #FFFFFF 25%, transparent 25%, transparent 75%, #FFFFFF 75%),linear-gradient(45deg, #FFFFFF 25%, transparent 25%, transparent 75%, #FFFFFF 75%)",this._container.style.backgroundRepeat="repeat",this._container.style.backgroundPosition="0 0, 10px 10px",this._container.style.backgroundSize="20px 20px"}}async addSpriteItem(t){return await this._pageDataUtils.addSpriteItem(t)}openPictureCutGizmo(){this._gestureHandler.openPictureCutGizmo()}closePictureCutGizmo(){this._gestureHandler.closePictureCutGizmo()}getCutInfo(){return this._gestureHandler.getCutInfo()}setCutBox(t,e){return this._gestureHandler.setCutBox(t,e)}openPictureExpandGizmo(){this._gestureHandler.openPictureExpandGizmo()}closePictureExpandGizmo(){this._gestureHandler.closePictureExpandGizmo()}getExpandInfo(){return this._gestureHandler.getExpandInfo()}setExpandBox(t,e){return this._gestureHandler.setExpandBox(t,e)}openMaskGizmo(t){this._gestureHandler.openMaskGizmo(t)}clearMaskGizmo(){this._gestureHandler.clearMaskGizmo()}closeMaskGizmo(){this._gestureHandler.closeMaskGizmo()}getMask(){return this._gestureHandler.getMask()}openLoadingGizmo(t){this._gestureHandler.openLoadingGizmo(t)}closeLoadingGizmo(t){this._gestureHandler.closeLoadingGizmo(t)}groupItems(t){return this._pageDataUtils.addNullItem(t)}async addTextItem(t){await this._pageDataUtils.addTextItem(t)}deleteItems(t){if(v(this._pageData,"You must call SDK#run() first"),Array.isArray(t)){t.forEach(t=>{this._pageDataUtils.deleteItem(t)});const e=this._pageData.activeData.selectedItems.filter(e=>!t.includes(e));this._eventEmitter.emit("selectedItemChange",e)}else{this._pageDataUtils.deleteItem(t);const e=this._pageData.activeData.selectedItems.filter(e=>e!==t);this._eventEmitter.emit("selectedItemChange",e)}this._pageDataUtils.interactionUtils.refreshViewParam(),this._pageDataUtils.interactionUtils.refreshCameraParam(),this._pageData.items=[];const e=this._pageDataUtils.getCurrentComposition();this._pageDataUtils.addViewItemsByItems(this._pageData.items,e.items),this._eventEmitter.emit("pageDataChange",this._pageData)}getItemCreateInfo(t){v(this._pageData,"You must call SDK#run() first");const e=[];if(Array.isArray(t))t.forEach(i=>{const s=this._pageDataUtils.getViewItemById(i),r=this._pageDataUtils.getItemCreateInfo(i,!(!s?.parentId||!t.includes(s?.parentId)));r&&e.push(r)});else{const i=this._pageDataUtils.getItemCreateInfo(t,!1);i&&e.push(i)}return e}async createScreenShotSceneByIds(t,e=0){const i=this._pageDataUtils.createScreenShotSceneByIds(t);if(!i)return;const s=i?.compositions[0]?.previewSize??[750,1624];console.log(i);const r=await this._screenShot.generate(i,s,s,e);return console.log(r),r}getChildrenIds(t){return this._pageDataUtils.getChildrenIds(t)}updateItemOrder(t,e){v(this._pageData,"You must call SDK#run() first");const i=this.getViewProperty(this._pageData.activeData.view??0)?.ignoreInteraction;i?console.warn("Static scene cannot change."):(this._pageDataUtils.updateItemOrder(t,e),this._gestureHandler.render())}exportJSON(t){v(this._pageData,"You must call SDK#run() first");const e=[];if(Array.isArray(t))t.forEach(t=>{const i=this.getViewProperty(t);i?e.push(i.scene):console.warn(`view id ${t} is not exsited.`)});else if(void 0!==t){const i=this.getViewProperty(t);i?e.push(i.scene):console.warn(`view id ${t} is not exsited.`)}else e.push(...this._pageData.viewProperties.map(t=>t.scene));return e}getViewBoxById(t){return this._pageDataUtils.getViewBoxById(t)}getViewItemById(t){return this._pageDataUtils.getViewItemById(t)}getViewProperty(t){return this._pageDataUtils.getViewProperty(t)}pageMove(t){this._pageDataUtils.pageMove(new F(...t))}pageZoom(t,e){this._pageDataUtils.pageZoom(t,e?new F(...e):void 0)}setPictureCutGizmoLockScale(t){this._gestureHandler.setPictureCutGizmoLockScale(t)}setPictureExpandGizmoLockScale(t){this._gestureHandler.setPictureExpandGizmoLockScale(t)}viewportFit(){this._pageDataUtils.viewportFit()}};c(oi,"config",{mode:"template",pageConfig:{asncMode:!1,minZoom:.01,maxZoom:20,staticPreview:!0,staticPreviewName:"标准模板",filterItemNames:["check-area","ModelPluginItem"],groupVisible:!0},screenShotConfig:{enabled:!0},exportConfig:{enabled:!0,mediaType:"MP4",loggerInTranscoding:!1},sizeAdaptConfig:{enabled:!0},gestureHandlerConfig:{enabled:!0,adsorptionGizmoEnabled:!0,adsorptionGizmoConfig:{lineWidth:2,lineColor:37375,distance:6},controlGizmoEnabled:!0,controlGizmoConfig:{zoomStep:.01},preferenceGizmoEnabled:!0,preferenceGizmoConfig:{boxColor:16711680,boxWidth:1,markColor:0,markAlpha:.17,safeAreaEnabled:!0,safeAreaBoxColor:65280,safeAreaBoxAlpha:.3},selectorGizmoEnabled:!0,selectorGizmoConfig:{preSelectedWidth:3,preSelectedColor:15425024,regionBoxColor:16777215,regionBoxAlpha:.17,regionWireframeColor:16777215,regionWireframeAlpha:.78,regionWireframeWidth:1},transformGizmoEnabled:!0,transformGizmoConfig:{wireframeColor:16711680,wireframeAlpha:1,wireframeWidth:1.5,cornerFillColor:16777215,cornerLineColor:0,cornerLineWidth:1,cornerLineAlpha:.3,scaleCircleSize:4,rotationCircleSize:8,pictureLogoUrl:"https://mdn.alipayobjects.com/huamei_ppzin5/afts/img/EMCfRoZQj8cAAAAAOmAAAAgADjdkAQFr/original",nullLogoUrl:"https://mdn.alipayobjects.com/huamei_ppzin5/afts/img/Yo69Sr7boqYAAAAAH3AAAAgADjdkAQFr/original",sizeTextColor:6710886,nameTextColor:6710886},pictureCutGizmoEnabled:!1,pictureCutGizmoConfig:{maskColor:16777215,maskAlpha:.5,cutBoxLineWidth:2,cutBoxLineColor:6960383,cutBoxLineAlpha:1,itemBoxLineWidth:1,itemBoxLineColor:6960383,itemBoxLineAlpha:1,cutBoxCornerRadius:5,cutBoxCornerLineWidth:2,cutBoxCornerLineColor:6960383,cutBoxCornerLineAlpha:1,cutBoxCornerFillColor:16777215,scaleInteractionDistance:8,directionScaleInteractionDistance:5},pictureExpandGizmoEnabled:!1,pictureExpandGizmoConfig:{maskColor:6960383,maskAlpha:.2,expandBoxLineWidth:2,expandBoxLineColor:6960383,expandBoxLineAlpha:1,expandBoxCornerRadius:5,expandBoxCornerLineWidth:2,expandBoxCornerLineColor:6960383,expandBoxCornerLineAlpha:1,expandBoxCornerFillColor:16777215,scaleInteractionDistance:8,directionScaleInteractionDistance:5},textGizmoEnbaled:!0,textGizmoConfig:{boxLineWidth:2,boxLineColor:7026175,scaleCornerRadius:5,rotationCornerWidth:30,rotationCornerTexture:"https://mdn.alipayobjects.com/huamei_ppzin5/afts/img/Zc9ZSqNEjnQAAAAAQBAAAAgADjdkAQFr/original",scaleCornerFillColor:16777215,scaleCornerStrokeWidth:2,scaleCornerStrokeColor:7026175},maskGizmoEnabled:!1,maskGizmoConfig:{brushSize:20,brushColor:6960383,brushAlpha:.5,maskColor:65280,maskAlpha:1,boxLineWidth:1,boxLineColor:6960383,boxLineAlpha:1}}});var ci=oi;export{W as Box2,d as ItemOrderAction,ci as SDK,F as Vector2,b as generateGUID,g as spec};