@vvfx/sdk 0.0.0-alpha.46 → 0.0.0-alpha.48
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.cjs +1 -1
- package/dist/index.d.cts +37 -2
- package/dist/index.d.ts +37 -2
- package/dist/index.global.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t,e=Object.create,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.getPrototypeOf,n=Object.prototype.hasOwnProperty,o=t=>{throw TypeError(t)},c=(t,e)=>{for(var s in e)i(t,s,{get:e[s],enumerable:!0})},h=(t,e,a,o)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of r(e))n.call(t,c)||c===a||i(t,c,{get:()=>e[c],enumerable:!(o=s(e,c))||o.enumerable});return t},l=(t,e,i)=>(h(t,e,"default"),i&&h(i,e,"default")),p=(t,s,r)=>(r=null!=t?e(a(t)):{},h(!s&&t&&t.__esModule?r:i(r,"default",{value:t,enumerable:!0}),t)),m=(t,e,s)=>((t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s)(t,"symbol"!=typeof e?e+"":e,s),d=(t,e,i)=>e.has(t)||o("Cannot "+i),g=(t,e,i)=>(d(t,e,"read from private field"),i?i.call(t):e.get(t)),u=(t,e,i)=>e.has(t)?o("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,s)=>(d(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i),y={};c(y,{Box2:()=>V,ItemOrderAction:()=>x,SDK:()=>We,Vector2:()=>B,generateGUID:()=>w.generateGUID,spec:()=>w.spec}),module.exports=(t=y,h(i({},"__esModule",{value:!0}),t));var x=(t=>(t[t.BringToFront=0]="BringToFront",t[t.SendToBack=1]="SendToBack",t[t.BringForward=2]="BringForward",t[t.SendBackward=3]="SendBackward",t))(x||{}),w=(require("@galacean/effects"),require("@galacean/effects")),v=(require("@galacean/effects-plugin-rich-text"),require("@galacean/effects-plugin-rich-text")),I=(require("@galacean/effects-plugin-model"),require("@galacean/effects-plugin-multimedia"),require("@galacean/effects-plugin-multimedia")),P=(require("@galacean/effects-plugin-spine"),require("@pixi/app")),C=class{constructor(){m(this,"type"),m(this,"active"),this.type="null",this.active=!1}get interactive(){return this.active}set interactive(t){this.active=t}},D=1e-6;function b(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 z=Math.PI/180,S=180/Math.PI;function A(t){return Math.atan2(-t.y,-t.x)+Math.PI}function E(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 T(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function _(t,e){return Math.abs(t-e)<D||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function k(t){return isNaN(t)||Math.abs(t)<D}var B=class t extends w.math.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=b(((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}},M=class t{constructor(t=new B,e=new B){m(this,"start",new B),m(this,"end",new B),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 B).subtractVectors(this.end,this.start).normalize()}getCenter(t=new B){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new B){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 B){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new B,s=new B;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=b(a,0,1)),a}closestPointToPoint(t,e,i=new B){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 B).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new B).subtractVectors(t.start,this.start),r=(new B).subtractVectors(t.end,this.start),a=(new B).subtractVectors(this.start,t.start),n=(new B).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}},V=class t{constructor(t=new B(1/0,1/0),e=new B(-1/0,-1/0)){m(this,"corners",[]),m(this,"min",new B(1/0,1/0)),m(this,"max",new B(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[new B(e.x,t.y),e.clone(),new B(t.x,e.y),t.clone()]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[new B(e.x,t.y),e.clone(),new B(t.x,e.y),t.clone()],this}setFromVec2Array(t){return this.min=(new B).copyFrom(t[0]),this.max=(new B).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 B).copyFrom(t[0]),this.max=(new B).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new B(this.max.x,this.min.y)),this.corners.push(new B(this.max.x,this.max.y)),this.corners.push(new B(this.min.x,this.max.y)),this.corners.push(new B(this.min.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new B).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[new B(this.max.x,this.min.y),this.max.clone(),new B(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 B){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new B){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 B(s.x-i.x,s.y-i.y),a=new B(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 B){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 B){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new B).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 B(this.max.x,this.min.y),this.max.clone(),new B(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 B(t,t):new B(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 M(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 M(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}},G=class t{constructor(t=new B,e=0){m(this,"center"),m(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new B).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 B,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new B){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}},U=class extends w.math.Quaternion{},F=class t extends w.math.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 U).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}},R=class t extends w.math.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=F.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:D,y:b,z:z}=i;return r[0]=(1-(x+v))*D,r[1]=(f+C)*D,r[2]=(y-P)*D,r[3]=0,r[4]=(f-C)*b,r[5]=(1-(u+v))*b,r[6]=(w+I)*b,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 F,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===w.math.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===w.math.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===w.math.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===w.math.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===w.math.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===w.math.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}},W=class extends w.math.Euler{constructor(t=0,e=0,i=0,s=w.math.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new R).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*S,this.y*S,this.z*S):new F(this.x*S,this.y*S,this.z*S)}setFromDegreeVector3(t,e){return this.set(t.x*z,t.y*z,t.z*z,e??this.order)}},H=class t{constructor(t=0,e=new F(0,0,1)){m(this,"distance"),m(this,"normal");const i=e.length();0===i&&(this.normal=new F(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 F(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}},L=class t extends w.math.Ray{constructor(t=new F,e=new F(1,0,0)){super(t,e),m(this,"origin"),m(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(k(e))return k(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},N=class{constructor(t=new L){m(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new F(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new F,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},O=class extends C{constructor(t){super(),m(this,"defaultInteractive",!0),m(this,"type","control"),m(this,"lastPoint",new B),m(this,"SDKUtils"),this.SDKUtils=t}get interactive(){return We.config.gestureHandlerConfig.controlGizmoEnabled}set interactive(t){We.config.gestureHandlerConfig.controlGizmoEnabled=!0}get useCameraControl(){return"editor"===We.config.mode}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(t){}action(t){if(!We.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 B(r,a);if(e||i){const t=this.useCameraControl?new B(n,o):new B,e=-a*We.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())}}endAction(){}interruption(){return this.type}actionKey(){}endActionKey(){}getRenderObjects(){return[]}},j=require("@pixi/graphics");function K(t,e){t.includes(e)||t.push(e)}var Y=class extends C{constructor(t){super(),m(this,"result",{type:"null",box:new V}),m(this,"selectedItemIds",[]),m(this,"activeParentIds",[]),m(this,"cursorPoint",new B),m(this,"startPoint",new B),m(this,"firstClickPoint",new B),m(this,"graphics",new j.Graphics),m(this,"pageDataUtils"),m(this,"clearResult",!1),m(this,"type","selector"),this.pageDataUtils=t}get interactive(){return We.config.gestureHandlerConfig.selectorGizmoEnabled}set interactive(t){We.config.gestureHandlerConfig.selectorGizmoEnabled=!0}actionKey(){}endActionKey(){}getRenderObjects(){return this.interactive?this.clearResult?(this.result={type:"null",box:new V},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t,e){if(this.result.box=new V,!this.interactive)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const i=new B(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 B(t.offsetX,t.offsetY);if(i??(i=this.firstClickPoint),e&&s.distanceTo(i)<4){const e=new B(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 B(t.clientX,t.clientY),this.cursorPoint=new B(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===w.spec.ItemType.text?"text":"transform"}}case 2:return void(this.selectedItemIds.length&&(t.shiftKey||this.pageDataUtils.clearSelectedItems(),this.pageDataUtils.addSelectedItems([this.selectedItemIds[0]]),this.clearResult=!0));default:return}}action(t){const e=(new B).addVectors(this.cursorPoint,(new B).subtractVectors(new B(t.clientX,t.clientY),this.startPoint)),i=(new B).subtractVectors(this.cursorPoint,e),s=(new B).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new V).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 L,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===w.spec.ItemType.mesh||s.getComponent(w.SpriteComponent)?.renderer?.occlusion||s.getComponent(w.TextComponent)?.renderer?.occlusion||s.getComponent(I.VideoComponent)?.renderer?.occlusion||s.getComponent(v.RichTextComponent)?.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)||K(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}=We.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()}},$=require("@pixi/graphics"),q=require("@galacean/effects"),J=require("@pixi/text"),X=require("@pixi/sprite"),Z=class extends C{constructor(t,e,i){super(),m(this,"type","transform"),m(this,"wireframe"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"cursorPoint",new B),m(this,"lastPoint",new B),m(this,"rotationAngle",0),m(this,"active",!1),m(this,"enableAdsorption",!0),m(this,"scaleParam"),m(this,"activeType","null"),m(this,"lastWorldPosition",new F),m(this,"firstClickPoint",new B),m(this,"pageDataUtils"),m(this,"adsorptionGizmo"),m(this,"selectorGizmo"),m(this,"graphics",new $.Graphics),m(this,"nameText",new J.Text("",{fontSize:14,fill:We.config.gestureHandlerConfig.transformGizmoConfig.sizeTextColor,align:"left"})),m(this,"imageSprite"),m(this,"nullSprite"),this.pageDataUtils=t,this.selectorGizmo=i,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new B,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,rotationEnabled:!0,scaleEnabled:!0,box:new V,totalBox:new V,childrenBoxes:[],activeType:"null",interactiveDirection:new B,scaleCorner:new B,scaleEdgeCorners:[]},this.imageSprite=X.Sprite.from(We.config.gestureHandlerConfig.transformGizmoConfig.pictureLogoUrl),this.imageSprite._width=15,this.imageSprite._height=15,this.nullSprite=X.Sprite.from(We.config.gestureHandlerConfig.transformGizmoConfig.nullLogoUrl),this.nullSprite._width=15,this.nullSprite._height=15}get interactive(){return We.config.gestureHandlerConfig.transformGizmoEnabled}set interactive(t){We.config.gestureHandlerConfig.transformGizmoEnabled=t}get infoType(){const t=this.pageDataUtils.getSelectedItems();return 1===t.length?t[0].type:w.spec.ItemType.base}actionKey(){}endActionKey(){}getRenderObjects(){const t=[];if(!this.interactive)return t;if(this.refreshRenderObject(),t.push(this.graphics),this.infoType!==w.spec.ItemType.base)switch(t.push(this.nameText),this.infoType){case w.spec.ItemType.sprite:t.push(this.imageSprite);break;case w.spec.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 B(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;this.refreshCursorResult(this.activeType,A(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 B(t.clientX,t.clientY),this.cursorPoint=new B(t.offsetX,t.offsetY),1!==t.buttons)return;if(e)return this.selectorGizmo.preAction(t,e,new B(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 F,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 F}const e=new B(t.clientX,t.clientY),i=(new B).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();(0,q.assertExist)(o);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new F,a=T(E((new B).subtractVectors(this.cursorPoint,t),(new B).subtractVectors(this.cursorPoint.add(i),t))*S,3);e.z=a,this.rotationAngle+=a,c=A(n)+this.rotationAngle*z,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 V:this.pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),i=new B(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new B(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!==w.spec.ItemType.camera&&(t.x=T(t.x,5),t.y=T(t.y,5),t.z=T(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 R).extractRotation(o.matrix).invert(),h=(new F).subtractVectors(e,i).applyMatrix(c),l=h.clone().multiply(a),p=t.clone().subtract(r).subtract(i).applyMatrix(c),m=new F(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}([_(h.x,0)?1:Math.abs(p.x/h.x),_(h.y,0)?1:Math.abs(p.y/h.y)]),g=p.toArray()[d],u=l.toArray()[d];if(_(a.x,a.y)&&_(a.z,a.x)){const t=_(u,0)?1:Math.abs(g/u);m.set(t,t,t)}else if(0===d){m.x=_(u,0)?1:Math.abs(g/u);const t=h.y*g/h.x;m.y=_(l.y,0)?1:t/l.y;const e=h.z*g/h.x;m.z=_(l.z,0)?1:e/l.z}else if(1===d){m.y=_(u,0)?1:Math.abs(g/u);const t=h.x*g/h.y;m.x=_(l.x,0)?1:t/l.x;const e=h.z*g/h.y;m.z=_(l.z,0)?1:e/l.z}else{m.z=_(u,0)?1:Math.abs(g/u);const t=h.x*g/h.z;m.x=_(l.x,0)?1:t/l.x;const e=h.y*g/h.z;m.y=_(l.y,0)?1:e/l.y}const f=m.clone().subtract(new F(1,1,0)).divide(2).add(new F(1,1,.5)),y=i.clone().add((new F).subtractVectors(e,i).multiply(a.x));this.scaleParam.lastScalar.multiply(f);const x=i.clone().add((new F).subtractVectors(e,i).multiply(this.scaleParam.lastScalar.x)),w=(new F).subtractVectors(x,y);w.x=T(w.x,5),w.y=T(w.y,5),w.z=T(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=A(n);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new B(t.clientX,t.clientY),i=(new B).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,A(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new B,this.lastPoint=new B}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)*S};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*S};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 F).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new F).setFromMatrixPosition(t.matrix),a=(new W).setFromQuaternion((new U).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new F,center:new F,corner:new F,lastScalar:new F(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 F}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new F).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}=We.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 M(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!==w.spec.ItemType.base){const t=this.pageDataUtils.getSelectedItems()[0],e=t.type===w.spec.ItemType.null?"编组":t.name,{size:i,rotation:s}=t.property,r=this.infoType===w.spec.ItemType.sprite?this.imageSprite:this.nullSprite,a=this.wireframe.box.corners[3],n=s[2]*z;r.anchor.set(0,1),r.x=a.x,r.y=a.y-5,r.rotation=-n;const o=a.clone().add(new B(20,0)).rotateAround(a,-n),c=new B(0,4).rotateAround(new B,n);this.nameText.text=` ${e} ${i.map(t=>T(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 B,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 V;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],this.wireframe.rotationEnabled=1===t.length&&t[0].type!==w.spec.ItemType.null,this.wireframe.scaleEnabled=1===t.length&&t[0].type!==w.spec.ItemType.null,this.wireframe.cornerEnable=1===t.length&&t[0].type!==w.spec.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 V).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!==w.spec.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!==w.spec.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 M((new B).copyFrom(t),(new B).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:n,rotationCircleSize:o}=We.config.gestureHandlerConfig.transformGizmoConfig;1===t.length&&this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new G(t,n));const e=(new B).subtractVectors(t,this.wireframe.box.getCenter()),i=(new B).copyFrom(this.wireframe.box.getCenter()).add((new B).copyFrom(e).normalize().multiply(e.length()+o-n));this.wireframe.rotationCorners.push(new G(i,o))})}setAdsorptionEnabled(t){this.enableAdsorption=t}},Q=require("@pixi/graphics"),tt=class extends C{constructor(){super(...arguments),m(this,"results",[]),m(this,"graphics",new Q.Graphics),m(this,"absorptionResult",{}),m(this,"type","adsorption")}get interactive(){return We.config.gestureHandlerConfig.adsorptionGizmoEnabled}set interactive(t){We.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 B(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 B(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)<We.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<We.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 B(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 M(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 M(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=We.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={}}},et={};c(et,{Application:()=>at.Application,utils:()=>st});var it={};c(it,{Application:()=>at.Application,utils:()=>st});require("@pixi/polyfill");var st=p(require("@pixi/utils"),1),rt=require("@pixi/interaction"),at=require("@pixi/app"),nt=require("@pixi/core"),ot=require("@pixi/loaders"),ct=require("@pixi/ticker");l(it,require("@pixi/constants")),l(it,require("@pixi/core")),l(it,require("@pixi/display")),l(it,require("@pixi/graphics")),l(it,require("@pixi/loaders")),l(it,require("@pixi/interaction")),l(it,require("@pixi/math")),l(it,require("@pixi/runner")),l(it,require("@pixi/sprite")),l(it,require("@pixi/text")),l(it,require("@pixi/ticker")),l(it,require("@pixi/settings")),st.skipHello(),nt.Renderer.registerPlugin("interaction",rt.InteractionManager),nt.Renderer.registerPlugin("batch",nt.BatchRenderer),at.Application.registerPlugin(ct.TickerPlugin),at.Application.registerPlugin(ot.AppLoaderPlugin),it.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()},it.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},it.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof M)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()},l(et,it);var ht=class extends C{constructor(t){super(),m(this,"box",new V),m(this,"graphics",new et.Graphics),m(this,"PageDataUtils"),m(this,"type","preference"),this.PageDataUtils=t}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.box=new V,!this.interactive)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if("editor"===We.config.mode)return;const t=this.PageDataUtils.getPageData();(0,w.assertExist)(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new B(s,r).multiply(i),n=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new V).setFromCenterAndSize(n,a)}}refreshRenderObjects(){if("editor"===We.config.mode)return;const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:n}=We.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new et.Graphics;const{offsetWidth:o,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new V(new B(0,0),new B(o,this.box.min.y)),l=new V(new B(0,this.box.min.y),new B(this.box.min.x,c)),p=new V(new B(this.box.min.x,this.box.max.y),new B(o,c)),m=new V(new B(this.box.max.x,this.box.min.y),new B(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 V(u,new B(f.x,u.y+p)),x=new V(new B(u.x,u.y+p),new B(u.x+m,f.y)),w=new V(new B(f.x-d,u.y+p),new B(f.x,f.y)),v=new V(new B(u.x+m,f.y-g),new B(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 B(r/e[0]*o.x,a/e[1]*o.y),h=new B(i/e[0]*o.x+c.x/2,s/e[1]*o.y+c.y/2).add(u),l=(new V).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 We.config.gestureHandlerConfig.preferenceGizmoEnabled&&"editor"!==We.config.mode?(this.refreshRenderObjects(),[this.graphics]):[]}get interactive(){return We.config.gestureHandlerConfig.preferenceGizmoEnabled}set interactive(t){We.config.gestureHandlerConfig.preferenceGizmoEnabled=t}},lt="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",pt={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${lt}/icons/cursor-rotate-32.svg`},circle:{type:"svg",content:"default",url:`${lt}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${lt}/icons/cursor-scale-32.svg`},"text-rotation":{type:"svg",content:"default",url:"https://mdn.alipayobjects.com/huamei_ixsp8m/afts/img/A*R722QoloC44AAAAAKkAAAAgAev-aAQ/original"}};function mt(t,e="item doesn't exist"){if(null==t)throw new Error(e)}function dt(t,e="asserts failed"){if(!t)throw new Error(e)}function gt(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 ut(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(!ut(t[s],e[s]))return!1}return!0}var ft=class extends C{constructor(t,e){super(),m(this,"result",{type:"invalid"}),m(this,"interactionParam",{type:"none"}),m(this,"graphics",new et.Graphics),m(this,"isShiftDown",!1),m(this,"_pageDataUtils"),m(this,"_eventEmitter"),m(this,"type","picture-cut"),m(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return We.config.gestureHandlerConfig.pictureCutGizmoEnabled}set interactive(t){t!==We.config.gestureHandlerConfig.pictureCutGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture cut gizmo can not open."):We.config.gestureHandlerConfig.pictureCutGizmoEnabled=t)}preparationAction(t){if(!this.interactive)return;const e=new B(t.offsetX,t.offsetY),i=new B(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){if(!this.interactive||"none"===this.interactionParam.type||"invalid"===this.result.type)return;const e=new B(t.clientX,t.clientY),{startMouse:i,box:s}=this.interactionParam,r=(new B).subtractVectors(e,i),{itemBox:{min:a,max:n}}=this.result;switch(this.interactionParam.type){case"move":{const{min:t,max:e}=s,i=a.x-t.x,o=n.x-e.x,c=a.y-t.y,h=n.y-e.y;r.x=Math.min(Math.max(r.x,i),o),r.y=Math.min(Math.max(r.y,c),h);const l=s.clone().translate(r);this.result.cutBox.copyFrom(l),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}case"scale":{const{startCorner:t,anchor:e}=this.interactionParam,i=new B;i.x=Math.min(Math.max(t.x+r.x,a.x),n.x),i.y=Math.min(Math.max(t.y+r.y,a.y),n.y);const o=new B((i.x-e.x)/(t.x-e.x),(i.y-e.y)/(t.y-e.y));this.result.cutBox.copyFrom(s.clone().scaleByCenter(o,e)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}case"direction-scale":{const{index:t}=this.interactionParam,e=s.corners[t].clone();t%2==0?(r.x=Math.min(Math.max(e.x+r.x,a.x),n.x)-e.x,r.y=0):(r.x=0,r.y=Math.min(Math.max(e.y+r.y,a.y),n.y)-e.y);const i=s.corners.map((e,i)=>[t,(t+1)%4].includes(i)?e.clone().add(r):e.clone());this.result.cutBox.copyFrom((new V).setFromVec2Array(i)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new B(t.offsetX,t.offsetY),i=new B(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(mt(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}=We.config.gestureHandlerConfig.pictureCutGizmoConfig,{cutBox:d,itemBox:g}=this.result,{min:u,max:f}=d,{min:y,max:x}=g,w=new V(y.clone(),new B(x.x,u.y)),v=new V(new B(y.x,u.y),new B(u.x,x.y)),I=new V(new B(f.x,u.y),new B(x.x,f.y)),P=new V(new B(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)<We.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 M(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*S)}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 B(Math.max(i.x,t.x),Math.max(i.y,t.y)),new B(Math.min(s.x,e.x),Math.min(s.y,e.y))),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone()),this.result.cutBox.clone()}},yt=require("@pixi/graphics"),xt=require("@pixi/sprite"),wt=require("@galacean/effects-plugin-model");var vt=class extends C{constructor(t,e,i,s,r){super(),m(this,"type","text"),m(this,"_eventEmitter"),m(this,"textAreaElement"),m(this,"graphics",new yt.Graphics),m(this,"_pageDataUtils"),m(this,"result"),m(this,"interactionParam"),m(this,"_adsorptionGizmo"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"rotationSprite",new xt.Sprite),m(this,"_selectorGizmo"),m(this,"handleInput",async t=>{const e=t.target;this.textAreaElement.style.height="auto",this.textAreaElement.style.height=`${this.textAreaElement.scrollHeight}px`,await this._pageDataUtils.changeItemProperty({itemId:this._pageDataUtils.getSelectedItems()[0].id,type:w.spec.ItemType.text,propertyName:"text",propertyValue:e.value}),this._eventEmitter.emit("textInput",{text:e.value,fontFamily:e.style.fontFamily})}),m(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 &::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 B,lastPoint:new B,startPoint:new B,lastWorldPosition:new F}}get interactive(){return We.config.gestureHandlerConfig.textGizmoEnbaled}set interactive(t){We.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 B(t.offsetX,t.offsetY),i=new B(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 B(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 F,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 B(t.clientX,t.clientY),this.interactionParam.startPoint=new B(t.offsetX,t.offsetY);const e=new B(t.offsetX,t.offsetY).subtract(this._pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.interactionParam.lastWorldPosition=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new F}const e=new B(t.clientX,t.clientY),{type:i,lastPoint:s,startPoint:r,anchor:a}=this.interactionParam,n=(new B).subtractVectors(e,s),o=this._pageDataUtils.getSelectedItems();switch(i){case"rotation":{const t=new F,e=T(E((new B).subtractVectors(r,a),(new B).subtractVectors(r.add(n),a))*S,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();(0,w.assertExist)(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 V:this._pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),s=new B(this._adsorptionGizmo.absorptionResult.x??0,this._adsorptionGizmo.absorptionResult.y??0);this._adsorptionGizmo.boxTranslationAdsorption(t,this.result.box,i);const r=new B(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!==w.spec.ItemType.camera&&(t.x=T(t.x,5),t.y=T(t.y,5),t.z=T(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 B).subtractVectors(t,a),s=(new B).subtractVectors(e,a).dot(i)/i.length(),n=i.length(),c=(s/n-1)/2+1,h=a.clone().add(i.clone().normalize().scale(n*c)),l=(new B).subtractVectors(h,t);r.add(l);const p=this._pageDataUtils.interactionUtils.getWorldSizeByViewSize(l);p.x=T(p.x,5),p.y=T(p.y,5),p.z=T(p.z,5),o.forEach(t=>{this._pageDataUtils.moveItem(t.id,p)}),o.forEach(t=>{this._pageDataUtils.scaleTextItem(t.id,c)})}break}}this.refreshCursorResult(),this.interactionParam.lastPoint.copyFrom(e)}endAction(t){const e=new B(t.offsetX,t.offsetY),i=new B(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!==w.spec.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 M(i.corners[0],i.corners[1]).at(.5),new M(i.corners[2],i.corners[3]).at(.5)],s=new M(i.getCenter(),new M(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]*wt.DEG2RAD}}}refreshInteractionParam(t,e){if("empty"===this.result.type)return this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new B,this.interactionParam.startPoint=new B,void(this.interactionParam.lastWorldPosition=new F);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 F);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 F)):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 F)):(this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new B,this.interactionParam.startPoint=new B,void(this.interactionParam.lastWorldPosition=new F))}refreshCursorResult(){const t=(new B).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)*S};break;case"rotation":this.cursorResult={type:"rotation",angle:(t+Math.PI/4)*S}}}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}=We.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]*wt.DEG2RAD),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.height=`${this.textAreaElement.scrollHeight}px`,this.textAreaElement.style.lineHeight=`${r.lineHeight}px`,this.textAreaElement.style.transformOrigin="center center",this.textAreaElement.style.paintOrder="stroke fill",r.outlineColor&&(this.textAreaElement.style.webkitTextStroke=`${r.outlineWidth??0}px rgba(${r.outlineColor.join(",")})`),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]*wt.DEG2RAD),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()}}},It=require("@pixi/core"),Pt=class extends C{constructor(t){super(),m(this,"_pageDataUtils"),m(this,"_config",{}),m(this,"type","mask"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"result",{status:"init",lines:[]}),m(this,"graphics",new et.Graphics),m(this,"linesMaskGraphics",new et.Graphics),m(this,"rectMaskGraphics",new et.Graphics),this._pageDataUtils=t}get interactive(){return We.config.gestureHandlerConfig.maskGizmoEnabled}set interactive(t){t!==We.config.gestureHandlerConfig.maskGizmoEnabled&&(t||(this.result.status="init"),We.config.gestureHandlerConfig.maskGizmoEnabled=t)}get config(){return{...We.config.gestureHandlerConfig.maskGizmoConfig,...this._config}}set config(t){this._config={...this._config,...t}}initialize(){}preparationAction(t){if(this.interactive)return this.result.point=new B(t.offsetX,t.offsetY),this.type}preAction(t){if(this.interactive)return this.result.point=new B(t.offsetX,t.offsetY),this.result.lines.push([]),this.type}action(t){if(!this.interactive||"init"===this.result.status)return;const e=new B(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(mt(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 V(new B(n.x,n.y),new B(o.x,n.y)),h=new V(new B(n.x,n.y),new B(n.x,o.y)),l=new V(new B(o.x,n.y),new B(o.x,n.y)),p=new V(new B(n.x,o.y),new B(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:et.LINE_CAP.ROUND,join:et.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 et.Renderer({width:Math.ceil(t.width),height:Math.ceil(t.height),backgroundColor:16777215}),i=new et.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}},Ct=class extends C{constructor(t){super(),m(this,"type","loading"),m(this,"_pageDataUtils"),m(this,"_idMap",new Map),m(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 et.Graphics,ticker:new et.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}},Dt=class extends C{constructor(t,e){super(),m(this,"result",{type:"invalid"}),m(this,"interactionParam",{type:"none"}),m(this,"graphics",new et.Graphics),m(this,"_pageDataUtils"),m(this,"_eventEmitter"),m(this,"type","picture-expand"),m(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return We.config.gestureHandlerConfig.pictureExpandGizmoEnabled}set interactive(t){t!==We.config.gestureHandlerConfig.pictureExpandGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture expand gizmo can not open."):We.config.gestureHandlerConfig.pictureExpandGizmoEnabled=t)}preparationAction(t){if(!this.interactive)return;const e=new B(t.offsetX,t.offsetY),i=new B(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){if(!this.interactive||"none"===this.interactionParam.type||"invalid"===this.result.type)return;const e=new B(t.clientX,t.clientY),{startMouse:i,box:s}=this.interactionParam,r=(new B).subtractVectors(e,i),{itemBox:{min:a,max:n}}=this.result;switch(this.interactionParam.type){case"move":{const{min:t,max:e}=s,i=n.x-e.x,o=a.x-t.x,c=n.y-e.y,h=a.y-t.y;r.x=Math.min(Math.max(r.x,i),o),r.y=Math.min(Math.max(r.y,c),h);const l=s.clone().translate(r);this.result.expandBox.copyFrom(l),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}case"scale":{const{index:t}=this.interactionParam,e=new B,{min:i,max:o}=s,c=s.corners[t];c.x>=o.x?e.x=Math.max(c.x+r.x,n.x):c.x<=i.x?e.x=Math.min(c.x+r.x,a.x):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),e.x=Math.abs(e.x-i.x)>Math.abs(e.x-o.x)?o.x:i.x),c.y>=o.y?e.y=Math.max(c.y+r.y,n.y):c.y<=i.y?e.y=Math.min(c.y+r.y,a.y):(console.warn("resultCorner has wrong, we have move it to the nearest corner"),e.y=Math.abs(e.y-i.y)>Math.abs(e.y-o.y)?o.y:i.y);const h=s.corners[(t+2)%4];this.result.expandBox.copyFrom((new V).setFromVec2ArrayWithOutCorners([e,h])),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}case"direction-scale":{const{index:t,point:e}=this.interactionParam,i=s.corners[t].clone();e.x>=n.x?(r.x=Math.max(s.corners[t].x+r.x,n.x)-i.x,r.y=0):e.x<=a.x&&(r.x=Math.min(s.corners[t].x+r.x,a.x)-i.x,r.y=0),e.y>=n.y?(r.y=Math.max(s.corners[t].y+r.y,n.y)-i.y,r.x=0):e.y<=a.y&&(r.y=Math.min(s.corners[t].y+r.y,a.y)-i.y,r.x=0);const o=s.corners.map((e,i)=>[t,(t+1)%4].includes(i)?e.clone().add(r):e.clone());this.result.expandBox.copyFrom((new V).setFromVec2Array(o)),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new B(t.offsetX,t.offsetY),i=new B(t.clientX,t.clientY);return this.refreshInteractionType(e,i),this.type}interruption(){this.interactionParam={type:"none"}}actionKey(){}endActionKey(){}cancelPreparation(){this.interactionParam={type:"none"}}refreshResults(){if(this.interactive){const t=this._pageDataUtils.getPageData();if(mt(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}=We.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)<We.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 M(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*S)}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 B(Math.min(i.x,t.x),Math.min(i.y,t.y)),new B(Math.max(s.x,e.x),Math.max(s.y,e.y))),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone()),this.result.expandBox.clone()}},bt=class{constructor(t){m(this,"wireframeApplication"),m(this,"gizmos",[]),m(this,"activeGizmo"),m(this,"selectorGizmo"),m(this,"transformGizmo"),m(this,"controlGizmo"),m(this,"preferenceGizmo"),m(this,"pictureCutGizmo"),m(this,"pictureExpandGizmo"),m(this,"textGizmo"),m(this,"maskGizmo"),m(this,"loadingGizmo"),m(this,"spaceClickTime"),m(this,"spaceEmit",!1),m(this,"_ignoreInteraction",!1),m(this,"clickButtons",0),m(this,"container"),m(this,"_emitter"),m(this,"clickTime",0),m(this,"firstClick",!0),m(this,"dblclickTimeSpan",500),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new P.Application({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(pt).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>pt[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 Z||this.activeGizmo instanceof ft||this.activeGizmo instanceof Dt||this.activeGizmo instanceof Pt||this.activeGizmo instanceof vt?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 O(t),this.selectorGizmo=new Y(t);const i=new tt;this.transformGizmo=new Z(t,i,this.selectorGizmo),this.preferenceGizmo=new ht(t),this.pictureCutGizmo=new ft(t,e),this.pictureExpandGizmo=new Dt(t,e),this.textGizmo=new vt(t,i,this.selectorGizmo,e,this.wireframeApplication?.view.parentElement),this.textGizmo.rotationSprite.texture=await It.Texture.fromURL(We.config.gestureHandlerConfig.textGizmoConfig.rotationCornerTexture),this.maskGizmo=new Pt(t),this.loadingGizmo=new Ct(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){if(this.clickButtons=t.buttons,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}this.render(),document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}}onMouseMove(t){this.ignoreInteraction||(0!==t.buttons?this.activeGizmo?.action(t):this.spaceEmit||(this.activeGizmo=void 0,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()})),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){if(!this.ignoreInteraction){if("space"!==t.code.toLocaleLowerCase()||this.activeGizmo?.active)this.gizmos.forEach(e=>{e.actionKey(t)});else{if(this.spaceEmit)return;void 0===this.spaceClickTime?this.spaceClickTime=Date.now():Date.now()-this.spaceClickTime>300&&(this.spaceEmit=!0,this.activeGizmo=this.controlGizmo,this.activeGizmo?.actionKey(t))}this.render()}}onKeyUp(t){this.ignoreInteraction||(this.gizmos.forEach(e=>{e.endActionKey(t)}),"space"===t.code.toLocaleLowerCase()&&(this.spaceClickTime=void 0,this.spaceEmit=!1),this.render())}dispose(){this.wireframeApplication.destroy(),this.gizmos=[],this.activeGizmo=void 0}setCursor(t){let e="default";if(t?.type&&["scale","rotation","circle"].includes(t.type)){const i=pt[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(We.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(We.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureCutGizmo(){if(!this.pictureCutGizmo)return;const t=JSON.parse(JSON.stringify(We.config));this.pictureCutGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(We.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}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(We.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(We.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureExpandGizmo(){if(!this.pictureExpandGizmo)return;const t=JSON.parse(JSON.stringify(We.config));this.pictureExpandGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(We.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(We.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(We.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(We.config));this.maskGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(We.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(We.config));this.loadingGizmo.addId(t),this.loadingGizmo.interactive&&(this.maskGizmo.interactive=!1,this.pictureCutGizmo.interactive=!1);const i=JSON.parse(JSON.stringify(We.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}closeLoadingGizmo(t){if(!this.loadingGizmo)return;const e=JSON.parse(JSON.stringify(We.config));this.loadingGizmo.deleteId(t);const i=JSON.parse(JSON.stringify(We.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}},zt=require("@galacean/effects"),St=class{constructor(t){m(this,"plane",new H),m(this,"ray",new L),m(this,"viewportParam",{width:0,height:0,scale:1,translation:new B,rulerWidth:0}),m(this,"cameraParam",{position:new F,rotation:new F,focusPosition:new F,focusRotation:new F,viewProjectionMatrix:new R,inverseViewProjectionMatrix:new R}),m(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();(0,zt.assertExist)(t,"You must run SDK first");const e=new B(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 B(...s.map(t=>t/i)),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=R.fromArray(e.getViewProjectionMatrix().toArray()),i=R.fromArray(e.getViewMatrix().toArray()).invert(),s=new U;i.decompose(this.cameraParam.position,s,new F),this.cameraParam.rotation=(new W).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new F(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new W).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new W).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=R.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new W).setFromDegreeVector3(this.cameraParam.rotation));const i=new F(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new W).setFromDegreeVector3(this.cameraParam.rotation):(new W).setFromQuaternion((new U).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i).matrix)),r=i?(new F).setFromMatrixPosition(this.pageDataUtils.getItemTransformById(i).matrix):this.cameraParam.focusPosition,a="editor"===We.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 F(0,0,0);const c=(new W).setFromQuaternion((new U).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"===We.config.mode?1:s;return(new B).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 N).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"===We.config.mode?1:s;return new B(t.x/(e*r)*2-1,1-t.y/(i*r)*2)}getNDCSizeByPixelSize(t){const{width:e,height:i}=this.viewportParam;return new B(t.x/e*2,-t.y/i*2)}getPixelSizeByNDCSize(t){const{width:e,height:i}=this.viewportParam;return new B(t.x/2*e,-t.y/2*i)}getViewPositionWWithOutTransform(t){const{scale:e}=this.viewportParam,i="editor"===We.config.mode?1:e;return t.divide(i)}getViewPositionByPixelPoint(t){if("template"===We.config.mode)return t.clone();const{width:e,height:i,scale:s,translation:r}=this.viewportParam;return t.clone().scaleByCenter(new B(s,s),new B(e/2,i/2)).add(r.multiply(s))}},At=require("@ffmpeg/ffmpeg"),Et=require("@ffmpeg/util"),Tt={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"},_t={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 kt(t,e,i,s){const r=e.getContext("2d");dt(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 Bt(){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)})}(Tt.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?Tt.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function Mt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.disposed||t.destroyCurrentCompositions()}function Vt(t=[750,750]){const e=(0,w.generateGUID)(),i={id:(0,w.generateGUID)(),dataType:w.spec.DataType.TimelineAsset,tracks:[]},s={id:(0,w.generateGUID)(),item:{id:e},dataType:w.spec.DataType.CompositionComponent,items:[],timelineAsset:{id:i.id},sceneBindings:[]},r={id:e,name:"AI 设计师画布",duration:999,startTime:0,endBehavior:w.spec.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:w.spec.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 Gt(t,e,i,s,r,a,n){const o=(0,w.generateGUID)(),c={id:t,name:a,dataType:w.spec.DataType.VFXItemData,components:[{id:o}],delay:0,duration:999,endBehavior:w.spec.EndBehavior.restart,renderLevel:w.spec.RenderLevel.BPlus,type:w.spec.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:w.spec.DataType.SpriteComponent,options:{startColor:[1,1,1,1]},renderer:{renderMode:w.spec.RenderMode.MESH}};n&&(h.renderer.texture={id:n});const l={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationPlayableAsset},p={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:l.id}}]},m={id:(0,w.generateGUID)(),dataType:w.spec.DataType.SpriteColorPlayableAsset,startColor:[1,1,1,1]};return{item:c,components:[h],tracks:[p,{id:(0,w.generateGUID)(),dataType:w.spec.DataType.SpriteColorTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:m.id}}]}],playableAssets:[l,m]}}function Ut(t,e,i,s,r,a){const n=(0,w.generateGUID)(),o={id:t,name:e,dataType:w.spec.DataType.VFXItemData,components:[{id:n}],delay:0,duration:999,endBehavior:w.spec.EndBehavior.restart,renderLevel:w.spec.RenderLevel.BPlus,type:w.spec.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:w.spec.DataType.TextComponent,options:a,renderer:{renderMode:1}},h={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationPlayableAsset};return{item:o,components:[c],tracks:[{id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:h.id}}]}],playableAssets:[h]}}function Ft(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:(0,w.generateGUID)(),dataType:w.spec.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 Rt(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 F,scale:o=new F(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 F,scale:c=new F(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 Wt(t,e){let i;return t.components.forEach(s=>{if(s.dataType===w.spec.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}var Ht,Lt,Nt,Ot,jt,Kt,Yt,$t,qt,Jt,Xt,Zt,Qt,te,ee,ie,se,re,ae,ne=require("@galacean/effects"),oe=require("@galacean/effects-plugin-multimedia"),ce=class{static createEmpty(t,e=null,i="NewVFXItem"){const s=he.createVFXItem(t,e,i);return s.type=ne.spec.ItemType.null,s}static createSprite(t,e=null,i="NewSpite"){const s=he.createVFXItem(t,e,i,ne.SpriteComponent);return s.type=ne.spec.ItemType.sprite,s}static createText(t,e=null,i="NewText"){const s=he.createVFXItem(t,e,i,ne.TextComponent);return s.type=ne.spec.ItemType.text,s}static createVideo(t,e=null,i="NewVideo"){const s=he.createVFXItem(t,e,i,oe.VideoComponent);return s.type=ne.spec.ItemType.video,s}},he=class{static createVFXItem(t,e=null,i="NewVFXItem",...s){const r=new ne.VFXItem(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}},le=require("@galacean/effects"),pe=class{constructor(t,e,i,s){m(this,"sdk"),m(this,"player"),m(this,"container"),m(this,"emitter"),m(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new St(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===w.spec.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===w.spec.EndBehavior.restart||a===w.spec.EndBehavior.freeze)}addSelectedItems(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.selectedItems??[];t.forEach(t=>{K(e,t)}),this.emitter.emit("selectedItemChange",e)}removeSelectedItems(t){(0,w.assertExist)(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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){(0,w.assertExist)(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();(0,w.assertExist)(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}addLoadingItems(t){var e;(0,w.assertExist)(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=>{K(i,t)}),this.emitter.emit("loadingItemChange",i)}removeLoadingItems(t){(0,w.assertExist)(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){Mt(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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t,e){var i;(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(i=this.sdk.pageData.property).zoom??(i.zoom=1);const{zoom:s,translation:[r=0,a=0]}=this.sdk.pageData.property,{width:n,height:o,scale:c}=this.interactionUtils.viewportParam,h=b(t,-.1,.1),l=T(b(s+h,We.config.pageConfig.minZoom,We.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=l,We.config.mode){case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new B(r,a)),i=e??new B(n/2,o/2),s=this.interactionUtils.getNDCPositionByScreenPosition(i),h=(s.x-t.x)/c,p=(s.y-t.y)/c,m=new B(s.x-h*l,s.y-p*l),d=(new R).compose(new F(m.x,m.y,0),new U,new F(l,l,1));this.sdk.pageData.property.translation=this.interactionUtils.getPixelSizeByNDCSize(m).toArray(),this.setCurrenCameraViewportMatrix(d);break}case"template":this.container.style.scale=`${l}`}this.refreshInteractionParam(),this.sdk.pageData.items=[];const p=this.getCurrentComposition();this.addViewItemsByItems(this.sdk.pageData.items,p.items),this.emitter.emit("zoomChange",l)}setPageZoom(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const{translation:[e=0,i=0]}=this.sdk.pageData.property,s=T(b(t,We.config.pageConfig.minZoom,We.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=s,We.config.mode){case"template":this.container.style.scale=`${s}`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new B(e,i)),r=(new R).compose(new F(t.x,t.y,0),new U,new F(s,s,1));this.setCurrenCameraViewportMatrix(r);break}}this.emitter.emit("zoomChange",s)}refreshInteractionParam(){this.interactionUtils.refreshViewParam(),this.interactionUtils.refreshCameraParam()}pageMove(t){(0,w.assertExist)(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],We.config.mode){case"template":this.container.style.translate=`${r}px ${a}px`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new B(r,a)),e=(new R).compose(new F(t.x,t.y,0),new U,new F(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("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 R).copyFrom(i.transform.getParentMatrix()??new R);s.setPosition(new F);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===w.spec.ItemType.text){const{textWidth:t}=i.property;this.changeItemProperty({itemId:i.id,type:w.spec.ItemType.text,propertyName:"textWidth",propertyValue:t*e})}}getItemTransformById(t){const e={matrix:new R,parentMatrix:new R},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=R.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(R.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(R.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new R).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)We.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){(0,w.assertExist)(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"===We.config.mode?1:n,p=this.getViewportLeftTopPosition();if(t.type!==w.spec.ItemType.null){i.updateLocalMatrix();const e=(new R).copyFrom(s?.transform.getWorldMatrix()??(new R).identity()).invert().multiply(i.getWorldMatrix()),r=new F,n=new U,o=new F;e.decompose(r,n,o);const c=(new W).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"===We.config.mode?d.subtract(l.clone().multiply(h)).scaleByCenter(new B(1/h,1/h),new B(p/2,m/2)).toArray().map(t=>T(t,2)):d.divide(h).toArray().map(t=>T(t,2)),u=c.toArray().map(t=>T(t,2)),f=o.toArray().map(t=>T(t,2)),y=i.size.toArray(),x=this.getPixelSizeByWorldSize([f[0]*y[0],f[1]*y[1],f[2]],t).map(t=>T(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"===We.config.mode?i.subtract(o.clone().multiply(n)).scaleByCenter(new B(1/n,1/n),new B(c/2,h/2)).toArray().map(t=>T(t,2)):i.toArray();a.position=s,a.size=e.getSize().divide(l).toArray()}switch(t.type){case w.spec.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 w.spec.ItemType.text:case w.spec.ItemType.richtext:{const e=this.getViewProperty()?.scene;if(a.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![w.spec.DataType.TextComponent,w.spec.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:T(255*t,0)):void 0,d=i.map((t,e)=>e>2?t:T(255*t,0)),g=h?.outlineWidth;Object.assign(a,{textAlign:e,textColor:d,fontWeight:r,text:s,fontFamily:n,fontSize:o,fontStyle:c,outlineColor:m,outlineWidth:g,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 V,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 F).copyFrom(e.transform.anchor).applyMatrix((new R).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 V;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,n=(new R).copyFrom(r?.transform.getWorldMatrix()??new R).invert().multiply(s.getWorldMatrix()),{x:o,y:c}=a.clone().divide(2),h=new F(o,c,0).applyMatrix(n),l=new F(o,-c,0).applyMatrix(n),p=new F(-o,-c,0).applyMatrix(n),m=new F(-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 w.spec.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"===We.config.mode)return new B;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,n=new B(i,s),o=new B(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 B(t/2,e/2).add(new B(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,i="editor"===We.config.mode?1:e,{offsetWidth:s,offsetHeight:r}=this.container,a=new B(s,r).multiply(i),n=this.getViewportLeftTopPosition(),o=t.clone().subtract(n);return new B(o.x/a.x*2-1,1-o.y/a.y*2)}async changeItemProperty(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(0,w.assertExist)(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"===We.config.mode?this.interactionUtils.viewportParam.scale:1;switch(t.propertyName){case"textAlign":[w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(w.TextComponent).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:T(255*t,0));i.getComponent(w.TextComponent).setTextColor(e)}break;case"fontFamily":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0];await le.AssetManager.loadFontFamily([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(w.TextComponent).setFontFamily(s)}break;case"text":if("string"==typeof t.propertyValue){const e=i.getComponent(w.TextComponent);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 B(n,a).multiply(s),c=this.interactionUtils.getWorldSizeByViewSize(o);i.transform.setSize(Math.abs(c.x),Math.abs(c.y))}break;case"fontWeight":[w.spec.TextWeight.normal,w.spec.TextWeight.bold,w.spec.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(w.TextComponent).setFontWeight(t.propertyValue);break;case"textWidth":{const e=i.getComponent(w.TextComponent);e.setTextWidth(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new B(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(w.TextComponent);e.setLineHeight(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new B(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(w.TextComponent);if("function"==typeof e.setOutlineColor){const i=t.propertyValue.map((t,e)=>e>2?t:T(t/255,5));e.setOutlineColor(i)}}break;case"outlineWidth":if("number"==typeof t.propertyValue){const e=i.getComponent(w.TextComponent);"function"==typeof e.setOutlineWidth&&e.setOutlineWidth(t.propertyValue)}break;case"fontSize":if("number"==typeof t.propertyValue&&i.type===w.spec.ItemType.text){i.getComponent(w.TextComponent).setFontSize(t.propertyValue)}break;case"image":"string"==typeof t.propertyValue&&i.getComponent(w.SpriteComponent).setTexture(await w.Texture.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 B(...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 F(...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 F(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),We.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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(0,w.assertExist)(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 B(...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;switch((0,w.assertExist)(e,"Param is not exsited."),e.propertyName){case"textAlign":if([w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));if(i?.options){const t=e.propertyValue.map((t,e)=>e>2?t:T(255*t,0));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&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a,n],c=this.interactionUtils.getWorldSizeByViewSize(new B(...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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a,n],c=this.interactionUtils.getWorldSizeByViewSize(new B(...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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),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 B(...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&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.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:T(t/255,5))])}break;case"outlineWidth":if("number"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.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.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));i?.options&&(i.options.fontSize=e.propertyValue)}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,We.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){(0,w.assertExist)(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;(0,w.assertExist)(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){(0,w.assertExist)(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(){(0,w.assertExist)(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=(0,w.generateGUID)()}=t,p=this.interactionUtils.getWorldSizeByViewSize(new B(...r).multiply(i)),m=new F(...a??[1,1],1),d=new F(0,0,o),g=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new B(...c)))??new F,u=e.images.findIndex(t=>t.url===n);let f,y={};if(n)if(u<0){f=await w.Texture.fromImage(n,this.player.renderer.engine);const t={id:(0,w.generateGUID)(),url:n,renderLevel:w.spec.RenderLevel.BPlus};y={id:f.guid,source:{id:t.id},flipY:!0,dataType:w.spec.DataType.Texture},e.images.push(t),e.textures??(e.textures=[]),e.textures.push(y)}else{const t=e.textures?.find(t=>t.source.id===e.images[u].id);y={id:t?.id},f=this.player.renderer.engine.findObject({id:t.id})}const x=Gt(l,g,d,new B(Math.abs(p.x),Math.abs(p.y)),m,s,y?.id);e.items.find(t=>t.id===h)&&(x.item.parentId=h),Ft(e,x);const v=this.player.getCompositions()[0],I=ce.createSprite(v,null,s);if(I.setInstanceId(x.item.id),I.duration=999,I.defination.delay=0,I.endBehavior=w.spec.EndBehavior.restart,I.transform.setSize(Math.abs(p.x),Math.abs(p.y)),I.transform.setPosition(...g.toArray()),I.transform.setRotation(...d.toArray()),I.transform.setScale(...m.toArray()),f){I.getComponent(w.SpriteComponent).setTexture(f)}return this.refreshSceneAndPageData(),x.item.id}addNullItem(t){const e=this.getActiveTargetScene();if(!e)return;const{name:i="空节点",position:s=[0,0],id:r=(0,w.generateGUID)(),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 B(...s))??new F,h=function(t,e,i){const s=JSON.parse(JSON.stringify(i)),r={id:t,name:e,duration:999,type:w.spec.ItemType.null,visible:!0,endBehavior:w.spec.EndBehavior.restart,delay:0,renderLevel:w.spec.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:w.spec.DataType.VFXItemData},a={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationPlayableAsset};return{item:r,components:[],tracks:[{id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:a.id}}]}],playableAssets:[a]}}(r,i,c);Ft(e,h),o.forEach(t=>{Rt(e,t,r)});const l=this.player.getCompositions()[0],p=ce.createEmpty(l,null,i);return p.setInstanceId(h.item.id),p.duration=999,p.defination.delay=0,p.endBehavior=w.spec.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=(0,w.generateGUID)(),parentId:s,name:r="文本",lineHeight:a,textWidth:n,fontFamily:o,position:c=[0,0],fontSize:h,fontWeight:l=w.spec.TextWeight.normal,fontStyle:p=w.spec.FontStyle.normal,textAlign:m=w.spec.TextAlignment.left,text:d,textColor:g,textHeight:u=a,outlineColor:f=[.8,.8,.8,1],outlineWidth:y=0,rotation:x=0,url:v}=t;v&&!e.fonts?.find(t=>t.fontFamily===o)&&(e.fonts??(e.fonts=[]),e.fonts.push({fontFamily:o,fontURL:v}));const I={text:d,fontFamily:o,fontSize:h,textColor:g,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:n,textHeight:u,lineHeight:a,textBaseline:w.spec.TextBaseline.top,textOverflow:w.spec.TextOverflow.visible,outline:{outlineColor:f,outlineWidth:y}},P=this.player.getCompositions()[0],C=ce.createText(P,null,r);C.setInstanceId(i),C.duration=999,C.defination.delay=0,C.endBehavior=w.spec.EndBehavior.restart;const D=C.getComponent(w.TextComponent),b={options:I,renderer:{renderMode:1},dataType:w.spec.DataType.TextComponent,item:{id:C.getInstanceId()},id:D.getInstanceId()};D.fromData(b),b.options.textHeight=Math.ceil(a*D.lineCount),D.fromData(b),await le.AssetManager.loadFontFamily([{fontURL:v,fontFamily:o}]),D.setFontFamily(o);const z=new B(n,I.textHeight).multiply(this.interactionUtils.viewportParam.scale),S=this.interactionUtils.getWorldSizeByViewSize(z),A=new F(0,0,x),E=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new B(...c)))??new F,T=Ut(i,r,E,A,new B(Math.abs(S.x),Math.abs(S.y)),I);e.items.find(t=>t.id===s)&&(T.item.parentId=s),Ft(e,T),C.transform.setSize(Math.abs(S.x),Math.abs(S.y)),C.transform.setPosition(...E.toArray()),C.transform.setRotation(...A.toArray()),(0,w.assertExist)(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===w.spec.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()}}getItemCreateInfo(t,e=!1){(0,w.assertExist)(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 F).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 w.spec.ItemType.sprite:{const{size:a}=r,h=this.interactionUtils.projectPoint(new F),l=this.interactionUtils.projectPoint(new F(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:Wt(s,t),size:p,scale:[o.x,o.y],rotation:n.z,position:[c.x,c.y]}}case w.spec.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 w.spec.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 V;let i;const s=(t,e,s)=>{const{id:r=(0,w.generateGUID)(),url:a,name:n="图层",scale:o=[1,1]}=t,c=new B(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:(0,w.generateGUID)(),url:a,renderLevel:w.spec.RenderLevel.BPlus};l={id:(0,w.generateGUID)(),source:{id:t.id},flipY:!0,dataType:w.spec.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=Gt(r,new F(s.x,s.y,0),new F(0,0,t.rotation??0),c,new F(t.scale?.[0]??1,t.scale?.[1]??1,1),n,l.id);Ft(i,p)},r=(t,e,s)=>{const{id:r=(0,w.generateGUID)(),name:a="文本",lineHeight:n,textWidth:o,fontFamily:c,fontSize:h,fontWeight:l=w.spec.TextWeight.normal,fontStyle:p=w.spec.FontStyle.normal,textAlign:m=w.spec.TextAlignment.left,text:d,textColor:g,rotation:u=0,url:f,textHeight:y}=t;f&&!i.fonts?.find(t=>t.fontFamily===c)&&(i.fonts??(i.fonts=[]),i.fonts.push({fontFamily:c,fontURL:f}));const x={text:d,fontFamily:c,fontSize:h,textColor:g,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:o,textHeight:y??n,lineHeight:n},v=Ut(r,a,new F(...s.toArray(),0),new F(0,0,u),new B(e.x,e.y),x);Ft(i,v)};if(Array.isArray(t)){t.map(t=>this.getViewBoxById(t)).map(t=>e.union(t));const a=e.getSize();i=Vt(a.toArray());const n=(new R).compose(new F(0,0,8),new U,new F(1,1,1)).invert(),o=(new R).perspective(60*z,a.x/a.y,.1,40,!0),c=(new R).multiplyMatrices(o,n),h=c.clone().invert(),l=c.projectPoint(new F).z,p=new F(0,0,l).applyMatrix(h),m=new F(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 B(d,g)).abs(),o=a.getCenter().subtract(e.getCenter()).multiply(new B(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=Vt(o.toArray());const c=(new R).compose(new F(0,0,8),new U,new F(1,1,1)).invert(),h=(new R).perspective(60*z,o.x/o.y,.1,40,!0),l=(new R).multiplyMatrices(h,c),p=l.clone().invert(),m=l.projectPoint(new F).z,d=new F(0,0,m).applyMatrix(p),g=new F(2,2,m).applyMatrix(p),u=(new F).subtractVectors(g,d);if(n)switch(n.type){case"sprite":s(n,new B(u.x,u.y),new B);break;case"text":r(n,new B(u.x,u.y),new B)}}return i}updateItemOrder(t,e){(0,w.assertExist)(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){(0,w.assertExist)(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===w.spec.DataType.CompositionComponent);i&&(i.items=t.items.map(t=>({id:t.getInstanceId()})))}}}getViewProperty(t){return(0,w.assertExist)(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)}},me=p(require("jszip"),1),de=p(require("jszip"),1),ge="ready",ue="executable",fe="dispose",ye={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},xe="idle",we="convertImage",ve="transcoding",Ie="audio",Pe="jpeg",Ce="webp",De="png",be=(ye.MP4,ye.WebP,ye.APNG,ye.GIF,ye.AlphaMaskVideo,ye.Images,ye.MP4,ye.WebP,ye.APNG,ye.GIF,ye.AlphaMaskVideo,ye.Images,"default"),ze="exporting",Se="success",Ae="error",Ee={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"},Te={highest:"1",high:"3",medium:"6",low:"9"},_e=class{constructor(t){m(this,"sampleRate"),m(this,"duration"),m(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)}},ke=["@vvfx/sdk","exporter"],Be=class extends w.EventEmitter{constructor(t){super(),m(this,"status",ge),m(this,"stage",xe),m(this,"mediaType"),m(this,"loggerInTranscoding"),m(this,"multiThreading"),m(this,"extraCanvas"),m(this,"player"),u(this,Ht,0),u(this,Lt),u(this,Nt),u(this,Ot),u(this,jt),u(this,Kt,[]),u(this,Yt),u(this,$t),u(this,qt,[]),u(this,Jt,0),u(this,Xt),u(this,Zt,[]),u(this,Qt,0),u(this,te,0),u(this,ee,0),u(this,ie,0),u(this,se,[]),u(this,re,[]),u(this,ae,!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===fe}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=g(this,Xt)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:g(this,Xt)?.fps??30,backgroundColor:g(this,Xt)?.backgroundColor??"#000000",loop:g(this,Xt)?.loop??!0,audioEnable:g(this,Xt)?.audioEnable??!1}}get gifConfig(){return g(this,Xt)?.gifConfig}get apngConfig(){return g(this,Xt)?.apngConfig}get progress(){const t=g(this,te)||1,e=g(this,ee)||1,i=Math.min(t/e,1),s=Math.min(g(this,Qt),t)/t*.4,r=Math.min(g(this,ie),t)/t*.6,a=Math.min(s+r,1);g(this,Zt)[g(this,Jt)]=i;const n=g(this,Zt).reduce((t,e,i)=>i<g(this,Jt)?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===ye.MP4?Pe:this.mediaType===ye.WebP?Ce:De}async onInit(){try{gt("log",[...ke,"ready"],"starting"),this.status=ge,await this.loadHelper(this.mediaType),this.status=ue,gt("log",[...ke,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=fe,this.onError(t)}finally{return this.status}}onReset(){this.stage=xe,window.cancelAnimationFrame(g(this,Ht)),f(this,Ht,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){gt("log",[...ke,"error"],t),this.onFinish(!1,g(this,se),g(this,re)),this.emit("error",t),this.dispose()}onFinish(t,e,i){gt("log",[...ke,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("finish",t,e,i)}async loadHelper(t){const e="WebP"===t&&!g(this,Ot),i=[ye.MP4,ye.APNG,ye.GIF,ye.AlphaMaskVideo].includes(t)&&!g(this,Nt);e&&f(this,Ot,await Bt()),i&&(f(this,Nt,await async function(t){const{multiThreading:e}=t??{},i=new At.FFmpeg,s=!!e,r={classWorkerURL:await(0,Et.toBlobURL)(_t.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await(0,Et.toBlobURL)(_t.MT.CORE,"text/javascript"),r.wasmURL=await(0,Et.toBlobURL)(_t.MT.WASM,"application/wasm"),r.workerURL=await(0,Et.toBlobURL)(_t.MT.WORKER,"text/javascript")):(r.coreURL=await(0,Et.toBlobURL)(_t.DEFAULT.CORE,"text/javascript"),r.wasmURL=await(0,Et.toBlobURL)(_t.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),g(this,Nt).on("log",({message:t})=>{if(this.loggerInTranscoding&>("log",[...ke,"transcoding log"],t),this.canceled||this.stage!==ve)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&&f(this,Zt,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&f(this,Qt,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&f(this,te,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&f(this,ie,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&f(this,ee,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){(0,w.assertExist)(this.player);const{oldTotalTime:i,startTime:s}=this.config;(0,w.assertExist)(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){f(this,Yt,new _e),g(this,Nt)?g(this,Nt).writeFile(t,g(this,Yt).getBuffer()):gt("log",[...ke,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new de.default,s=i.folder(t);return(0,w.assertExist)(s),g(this,qt).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){(0,w.assertExist)(g(this,Ot));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${g(this,qt).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=g(this,Ot).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]}(g(this,Ot),i);dt(r&&a,"getWebP has error"),s(r,a);const n=g(this,Ot).FS.readFile(e);return g(this,qt).forEach(t=>{g(this,Ot)?.FS.unlink(t)}),n}async getAPNG(){(0,w.assertExist)(g(this,Nt));this.stage=ve;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 g(this,Nt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-vf",r.join(","),"-plays",this.config.loop?"0":"1","-compression_level",Te[s],"-y",t]))throw new Error("the command executed by ffmpeg to generate a apng failed.");return t}async getGIF(){(0,w.assertExist)(g(this,Nt));this.stage=ve;const t="export.gif",{fps:e,scale:i="-1:-1",quality:s="highest"}=this.gifConfig??{},r=[`scale=${i}:${Ee[s]}`];e&&r.unshift(`fps=${e}`);if(0!==await g(this,Nt).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){(0,w.assertExist)(g(this,Nt));this.stage=ve;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;this.config.audioEnable&&!g(this,Yt)&&(f(this,$t,"audio.wav"),this.getWavAudio(g(this,$t)));if(0!==await g(this,Nt).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(g(this,$t)&&g(this,Yt)){this.stage=Ie,s="export-with-audio.mp4";if(0!==await g(this,Nt).exec(["-i",i,"-i",g(this,$t),"-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&&g(this,Nt).deleteFile(i).catch(()=>{gt("log",[...ke,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){(0,w.assertExist)(g(this,Nt));this.stage=ve;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await g(this,Nt).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){(0,w.assertExist)(g(this,Nt));const i=this.mediaType===ye.APNG,s=this.mediaType===ye.GIF,r=this.mediaType===ye.AlphaMaskVideo,a=this.mediaType===ye.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=xe}catch(t){throw t}finally{for(const t of g(this,qt))t&&g(this,Nt).deleteFile(t)}let o=null;try{(0,w.assertExist)(n);const t=await g(this,Nt).readFile(n);o="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{g(this,Nt).deleteFile(n).catch(()=>{gt("log",[...ke,"ffmpeg delete file error"])})}return o}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});f(this,jt,e),g(this,jt).start(0);const i=[];g(this,jt).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},f(this,Kt,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o}=t;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,Lt));const c=g(this,Qt)+1;this.stage=we,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&>("log",[...ke,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),kt(g(this,Lt),s,this.config.backgroundColor);let h=s;this.mediaType===ye.AlphaMaskVideo&&((0,w.assertExist)(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 l=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),p=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===ye.Images?r.push(l):this.mediaType===ye.WebP?((0,w.assertExist)(g(this,Ot)),g(this,Ot).FS.writeFile(p,new Uint8Array(l))):((0,w.assertExist)(g(this,Nt)),await g(this,Nt).writeFile(p,new Uint8Array(l))),g(this,qt).push(p);if(c===g(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():[ye.MP4,ye.APNG,ye.GIF,ye.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(n,o)??null),t&&(gt("log",[...ke,"done"],"success"),this.emit("done",g(this,Xt),!0,t))}else f(this,Ht,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o})}))}catch(t){gt("log",[...ke,"onExportImageFrame","failed"],t),this.emit("done",g(this,Xt),!1)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,Lt));const e=g(this,Qt)+1;if(this.stage=we,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&>("log",[...ke,"converting log"],`converting ${e} frame image`),kt(g(this,Lt),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<g(this,te))f(this,Ht,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),g(this,jt)?.stop();const t=new Blob(g(this,Kt),{type:"video/webm"}),e=await t.arrayBuffer();gt("log",[...ke,"done"],"success"),this.emit("done",g(this,Xt),!0,e)}}catch(t){gt("log",[...ke,"done"],"failed",t),this.emit("done",g(this,Xt),!1)}}async runTask(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,Lt));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[n,o]=e;if(g(this,Lt).width=n,g(this,Lt).height=o,s.width=n,s.height=o,this.player.resize(),f(this,qt,[]),[ye.MP4,ye.APNG,ye.Images,ye.WebP,ye.GIF,ye.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){gt("log",[...ke,"run task error"],t),this.emit("done",g(this,Xt),!1)}}clearTaskInfo(){f(this,Jt,0),f(this,Xt,void 0),f(this,Zt,[]),f(this,Qt,0),f(this,te,0),f(this,ee,0),f(this,ie,0),f(this,se,[]),f(this,re,[]),f(this,ae,!0)}clearFFMpegCore(){if(g(this,Nt)){for(const t of g(this,qt))t&&g(this,Nt).deleteFile(t);f(this,qt,[]),g(this,Nt).terminate(),f(this,Nt,void 0)}}clearImage2WebPCore(){g(this,Ot)&&(g(this,Ot).FS.quit(),f(this,Ot,void 0))}clearMediaRecorder(){g(this,jt)&&(g(this,jt).stop(),f(this,jt,void 0)),f(this,Kt,[])}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,g(this,se),g(this,re)),this.status=fe,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),gt("log",ke,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===ge)return gt("log",[...ke],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===fe){if(await this.onInit()===fe)throw new Error("init environment failed")}if(this.clearTaskInfo(),!g(this,Lt)){const t=document.createElement("canvas");t.dataset.key="player-canvas",f(this,Lt,t)}this.player||(this.player=new w.Player({canvas:g(this,Lt),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}f(this,Jt,a),f(this,Xt,n);const{size:t,scene:o}=n;await new Promise(async c=>{try{if(!this.player)throw new Error("player not found");gt("log",[...ke,"export"],"start",n),Mt(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){gt("log",[...ke,"export error"],t),r=!1,c()}})}f(this,se,i),f(this,re,s),f(this,ae,r)}catch(t){this.onError(t),f(this,ae,!1)}e>=1&&g(this,ae)?this.onFinish(!0,g(this,se),g(this,re)):this.onFinish(!1,g(this,se),g(this,re))}dispose(){this.status=fe,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,g(this,Lt)?.remove(),f(this,Lt,void 0),f(this,$t,void 0),f(this,Yt,void 0)}};Ht=new WeakMap,Lt=new WeakMap,Nt=new WeakMap,Ot=new WeakMap,jt=new WeakMap,Kt=new WeakMap,Yt=new WeakMap,$t=new WeakMap,qt=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,te=new WeakMap,ee=new WeakMap,ie=new WeakMap,se=new WeakMap,re=new WeakMap,ae=new WeakMap;var Me={[ye.MP4]:{suffix:"mp4",error:"export mp4 is error"},[ye.GIF]:{suffix:"gif",error:"export gif is error"},[ye.Images]:{suffix:"zip",error:"export Images is error"},[ye.APNG]:{suffix:"apng",error:"export APNG is error"},[ye.WebP]:{suffix:"webp",error:"export WebP is error"},[ye.AlphaMaskVideo]:{suffix:"mp4",error:"export AlphaMaskVideo is error"},[ye.WebM]:{suffix:"webm",error:"export WebM is error"}},Ve=class extends w.EventEmitter{constructor(t){super(),m(this,"_config"),m(this,"_status",be),m(this,"_exportMedia"),this._config=t,this._exportMedia=new Be(t)}get status(){return this._status}onExportMedia(t,e,i,s){if(!e.length||!i)return void gt("info",["@vvfx/sdk","export media is error","result or suffix is empty"]);const r=t[0]?.folderName,a=new me.default;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=>{gt("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=Ae,gt("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=ze,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?Se:Ae,this.emit("complete",e,i,s),this._config.isOutputBuffer||!s||0===s.length)return;const{suffix:r,error:a}=Me[this._config.mediaType];r&&this.onExportMedia(t,s,r,a)}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=Ae,this._exportMedia.onCancel(),this.emit("complete",!1,[],[])}dispose(){this._exportMedia.dispose()}},Ge=class{constructor(){m(this,"enabled",!0),m(this,"_player"),m(this,"_container"),this._container=document.createElement("canvas"),this._player=new w.Player({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.");Mt(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 Mt(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?b(n,0,1):.5,o="number"==typeof o?b(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)}},Ue={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},Fe=class{constructor(t){m(this,"_player"),m(this,"_container"),m(this,"size",[0,0]),m(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new w.Player({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r,a){if(!We.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new w.Player({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],Mt(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 V).setFromCenterAndSize(new B(e,n).divide(2),new B(e,n)),x=(new V).setFromCenterAndSize(new B(e,n).divide(2).add(new B(...f)),new B(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 R).copyFrom(e.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===Ue[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 B(...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 R).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,c)},p=Ue[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 B,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 B;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 D=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l),b=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),z=new V;if(b.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>D.min.y)if("centerAdsorption"===t){const t=z.max.y-D.min.y;h(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=D.getSize().y,e=a.getSize().y-(z.max.y-a.min.y);let i=z.max.y-D.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 R).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(n,o)},l=Ue[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 B;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 V,{transform:r,composition:a}=t;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,n=(new R).copyFrom(a?.transform.getWorldMatrix()??new R).invert().multiply(r.getWorldMatrix()),{x:o,y:c}=t.clone().divide(2),h=new F(o,c,0).applyMatrix(n),l=new F(o,-c,0).applyMatrix(n),p=new F(-o,-c,0).applyMatrix(n),m=new F(-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 w.spec.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()}},Re=class t{constructor(e){m(this,"_eventEmitter",new w.EventEmitter),m(this,"_pageData"),m(this,"_screenShot"),m(this,"_exporter"),m(this,"_pageDataUtils"),m(this,"_sizeAdapt"),m(this,"_gestureHandler"),m(this,"disposables",[]),m(this,"_isSwitchScene",!1),m(this,"player"),m(this,"_container"),m(this,"_playerContainer"),m(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 w.Player({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if((0,w.assertExist)(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("zoomChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._gestureHandler.render()}),this._eventEmitter.on("selectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{(0,w.assertExist)(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 pe(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportConfig),this._gestureHandler=new bt(e),this._screenShot=new Ge,this._sizeAdapt=new Fe(this._pageDataUtils);const a=new ResizeObserver(()=>{if(!this._pageData)return;const t=[e.offsetWidth,e.offsetHeight],i=this.getViewProperty(this._pageData.activeData.view??0);if(!i)return;const{size:s}=i,[r,a]=this._pageDataUtils.getPlayerSizeByParent(t,s);this._playerContainer.style.width=`${r}px`,this._playerContainer.style.height=`${a}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 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:Vt(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&&!ut(t,e)&&(this._exporter.dispose(),this.initExporter(e))}initExporter(t){this._exporter=new Ve(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];(0,w.assertExist)(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(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return(0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){(0,w.assertExist)(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){(0,w.assertExist)(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((0,w.assertExist)(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(0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(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&&(Mt(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){(0,w.assertExist)(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(0,w.assertExist)(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(0,w.assertExist)(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&&((0,w.assertExist)(this.pageData,"You must call SDK#run() first"),(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){(0,w.assertExist)(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){(0,w.assertExist)(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;(0,w.assertExist)(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];(0,w.assertExist)(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];(0,w.assertExist)(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){(0,w.assertExist)(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||Object.assign(i.export,t)})}setPageZoom(t){(0,w.assertExist)(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?K(t.config.pageConfig.filterItemNames,e):e.forEach(e=>{K(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((0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(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)}};m(Re,"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 We=Re;
|
|
1
|
+
"use strict";var t,e=Object.create,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,a=Object.getPrototypeOf,n=Object.prototype.hasOwnProperty,o=t=>{throw TypeError(t)},c=(t,e)=>{for(var s in e)i(t,s,{get:e[s],enumerable:!0})},h=(t,e,a,o)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of r(e))n.call(t,c)||c===a||i(t,c,{get:()=>e[c],enumerable:!(o=s(e,c))||o.enumerable});return t},l=(t,e,i)=>(h(t,e,"default"),i&&h(i,e,"default")),p=(t,s,r)=>(r=null!=t?e(a(t)):{},h(!s&&t&&t.__esModule?r:i(r,"default",{value:t,enumerable:!0}),t)),m=(t,e,s)=>((t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s)(t,"symbol"!=typeof e?e+"":e,s),d=(t,e,i)=>e.has(t)||o("Cannot "+i),g=(t,e,i)=>(d(t,e,"read from private field"),i?i.call(t):e.get(t)),u=(t,e,i)=>e.has(t)?o("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),f=(t,e,i,s)=>(d(t,e,"write to private field"),s?s.call(t,i):e.set(t,i),i),y={};c(y,{Box2:()=>V,ItemOrderAction:()=>x,SDK:()=>Le,Vector2:()=>B,generateGUID:()=>w.generateGUID,spec:()=>w.spec}),module.exports=(t=y,h(i({},"__esModule",{value:!0}),t));var x=(t=>(t[t.BringToFront=0]="BringToFront",t[t.SendToBack=1]="SendToBack",t[t.BringForward=2]="BringForward",t[t.SendBackward=3]="SendBackward",t))(x||{}),w=(require("@galacean/effects"),require("@galacean/effects")),v=(require("@galacean/effects-plugin-rich-text"),require("@galacean/effects-plugin-rich-text")),I=(require("@galacean/effects-plugin-model"),require("@galacean/effects-plugin-multimedia"),require("@galacean/effects-plugin-multimedia")),P=(require("@galacean/effects-plugin-spine"),require("@pixi/app")),C=class{constructor(){m(this,"type"),m(this,"active"),this.type="null",this.active=!1}get interactive(){return this.active}set interactive(t){this.active=t}},D=1e-6;function b(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 z=Math.PI/180,S=180/Math.PI;function A(t){return Math.atan2(-t.y,-t.x)+Math.PI}function E(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 T(t,e,i=Math.round){if(Number.isInteger(t))return t;const s=Math.pow(10,e);return i(t*s)/s}function k(t,e){return Math.abs(t-e)<D||t===1/0&&e===1/0||t===-1/0&&e===-1/0}function _(t){return isNaN(t)||Math.abs(t)<D}var B=class t extends w.math.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=b(((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}},M=class t{constructor(t=new B,e=new B){m(this,"start",new B),m(this,"end",new B),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 B).subtractVectors(this.end,this.start).normalize()}getCenter(t=new B){return t.addVectors(this.start,this.end).multiply(.5)}delta(t=new B){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 B){return this.delta(e).multiply(t).add(this.start)}closestPointToPointParameter(t,e){const i=new B,s=new B;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=b(a,0,1)),a}closestPointToPoint(t,e,i=new B){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 B).subtractVectors(this.end,this.start).length()}crossWithLine(t){const e=this.delta(),i=t.delta(),s=(new B).subtractVectors(t.start,this.start),r=(new B).subtractVectors(t.end,this.start),a=(new B).subtractVectors(this.start,t.start),n=(new B).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}},V=class t{constructor(t=new B(1/0,1/0),e=new B(-1/0,-1/0)){m(this,"corners",[]),m(this,"min",new B(1/0,1/0)),m(this,"max",new B(-1/0,-1/0)),this.min=t.clone(),this.max=e.clone(),this.isEmpty()?this.corners=[]:this.corners=[new B(e.x,t.y),e.clone(),new B(t.x,e.y),t.clone()]}set(t,e){return this.min.copyFrom(t),this.max.copyFrom(e),this.corners=[new B(e.x,t.y),e.clone(),new B(t.x,e.y),t.clone()],this}setFromVec2Array(t){return this.min=(new B).copyFrom(t[0]),this.max=(new B).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 B).copyFrom(t[0]),this.max=(new B).copyFrom(t[0]),t.forEach(t=>{this.min=this.min.min(t),this.max=this.max.max(t)}),this.corners.push(new B(this.max.x,this.min.y)),this.corners.push(new B(this.max.x,this.max.y)),this.corners.push(new B(this.min.x,this.max.y)),this.corners.push(new B(this.min.x,this.min.y)),this}setFromCenterAndSize(t,e){const i=(new B).copyFrom(e).multiply(.5);return this.min.copyFrom(t).subtract(i),this.max.copyFrom(t).add(i),this.corners=[new B(this.max.x,this.min.y),this.max.clone(),new B(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 B){return this.isEmpty()?t.set(0,0):t.addVectors(this.min,this.max).multiply(.5)}getSize(t=new B){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 B(s.x-i.x,s.y-i.y),a=new B(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 B){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 B){return e.copyFrom(t).clamp(this.min,this.max)}distanceToPoint(t){return(new B).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 B(this.max.x,this.min.y),this.max.clone(),new B(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 B(t,t):new B(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 M(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 M(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}},G=class t{constructor(t=new B,e=0){m(this,"center"),m(this,"radius"),this.center=t.clone(),this.radius=e}set(t,e){return this.center=(new B).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 B,this.radius=0,this}isEmpty(){return 0===this.radius}getCenter(t=new B){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}},U=class extends w.math.Quaternion{},F=class t extends w.math.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 U).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}},R=class t extends w.math.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=F.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:D,y:b,z:z}=i;return r[0]=(1-(x+v))*D,r[1]=(f+C)*D,r[2]=(y-P)*D,r[3]=0,r[4]=(f-C)*b,r[5]=(1-(u+v))*b,r[6]=(w+I)*b,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 F,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===w.math.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===w.math.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===w.math.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===w.math.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===w.math.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===w.math.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}},W=class extends w.math.Euler{constructor(t=0,e=0,i=0,s=w.math.EulerOrder.XYZ){super(t,e,i,s)}getInvertMatrixByEuler(){return(new R).makeRotationFromEuler(this).invert()}toDegreeVector3(t){return t?t.set(this.x*S,this.y*S,this.z*S):new F(this.x*S,this.y*S,this.z*S)}setFromDegreeVector3(t,e){return this.set(t.x*z,t.y*z,t.z*z,e??this.order)}},L=class t{constructor(t=0,e=new F(0,0,1)){m(this,"distance"),m(this,"normal");const i=e.length();0===i&&(this.normal=new F(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 F(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}},H=class t extends w.math.Ray{constructor(t=new F,e=new F(1,0,0)){super(t,e),m(this,"origin"),m(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(_(e))return _(t.distanceToPoint(this.origin))?0:NaN;const i=(-this.origin.dot(t.normal)-t.distance)/e;return i>0?i:NaN}},N=class{constructor(t=new H){m(this,"ray"),this.ray=t.clone()}setFromCamera(t,e){const i=e.position,s=new F(t.x,t.y,.5).applyMatrix(e.inverseViewProjectMatrix).subtract(i).normalize();return this.ray.set(i,s),this}rayCastPlane(t){const e=new F,i=this.ray.rayCastPlane(t,e);if(!isNaN(i))return{distance:i,point:this.ray.at(i)}}},O=class extends C{constructor(t){super(),m(this,"defaultInteractive",!0),m(this,"type","control"),m(this,"_interactionType","mouse"),m(this,"active",!1),m(this,"lastPoint",new B),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"SDKUtils"),this.SDKUtils=t}get interactive(){return Le.config.gestureHandlerConfig.controlGizmoEnabled}set interactive(t){Le.config.gestureHandlerConfig.controlGizmoEnabled=!0}get interactionType(){return this._interactionType}set interactionType(t){t===this._interactionType&&(this._interactionType=t,this.refreshCursorResult())}get useCameraControl(){return"editor"===Le.config.mode}preparationAction(){}cancelPreparation(){}refreshResults(){}preAction(t){return"mouse"===this.interactionType&&(this.active=!0,this.lastPoint=new B(t.clientX,t.clientY)),this.refreshCursorResult(),"mouse"===this.interactionType?this.type:void 0}action(t){if(!Le.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 B(r,a);if(e||i){const t=this.useCameraControl?new B(n,o):new B,e=-c.y*Le.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 B(e,i),a=(new B).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[]}},K=require("@pixi/graphics");function j(t,e){t.includes(e)||t.push(e)}var Y=class extends C{constructor(t){super(),m(this,"result",{type:"null",box:new V}),m(this,"selectedItemIds",[]),m(this,"activeParentIds",[]),m(this,"cursorPoint",new B),m(this,"startPoint",new B),m(this,"firstClickPoint",new B),m(this,"graphics",new K.Graphics),m(this,"pageDataUtils"),m(this,"clearResult",!1),m(this,"type","selector"),this.pageDataUtils=t}get interactive(){return Le.config.gestureHandlerConfig.selectorGizmoEnabled}set interactive(t){Le.config.gestureHandlerConfig.selectorGizmoEnabled=!0}actionKey(){}endActionKey(){}getRenderObjects(){return this.interactive?this.clearResult?(this.result={type:"null",box:new V},this.clearResult=!1,[]):(this.refreshResults(),[this.graphics]):[]}cancelPreparation(){this.result.type="null",this.pageDataUtils.clearPreSelectedItem()}preparationAction(t,e){if(this.result.box=new V,!this.interactive)return void console.warn("Selector gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");const i=new B(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 B(t.offsetX,t.offsetY);if(i??(i=this.firstClickPoint),e&&s.distanceTo(i)<4){const e=new B(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 B(t.clientX,t.clientY),this.cursorPoint=new B(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===w.spec.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 B).addVectors(this.cursorPoint,(new B).subtractVectors(new B(t.clientX,t.clientY),this.startPoint)),i=(new B).subtractVectors(this.cursorPoint,e),s=(new B).addVectors(this.cursorPoint,e).multiply(.5);i.x=Math.abs(i.x),i.y=Math.abs(i.y);const r=(new V).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 H,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===w.spec.ItemType.mesh||s.getComponent(w.SpriteComponent)?.renderer?.occlusion||s.getComponent(w.TextComponent)?.renderer?.occlusion||s.getComponent(I.VideoComponent)?.renderer?.occlusion||s.getComponent(v.RichTextComponent)?.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)||j(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}=Le.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()}},$=require("@pixi/graphics"),q=require("@galacean/effects"),J=require("@pixi/text"),X=require("@pixi/sprite"),Z=class extends C{constructor(t,e,i){super(),m(this,"type","transform"),m(this,"wireframe"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"cursorPoint",new B),m(this,"lastPoint",new B),m(this,"rotationAngle",0),m(this,"active",!1),m(this,"enableAdsorption",!0),m(this,"scaleParam"),m(this,"activeType","null"),m(this,"lastWorldPosition",new F),m(this,"firstClickPoint",new B),m(this,"pageDataUtils"),m(this,"adsorptionGizmo"),m(this,"selectorGizmo"),m(this,"graphics",new $.Graphics),m(this,"nameText",new J.Text("",{fontSize:14,fill:Le.config.gestureHandlerConfig.transformGizmoConfig.sizeTextColor,align:"left"})),m(this,"imageSprite"),m(this,"nullSprite"),this.pageDataUtils=t,this.selectorGizmo=i,this.adsorptionGizmo=e,this.wireframe={edges:[],anchor:new B,scaleCorners:[],rotationCorners:[],interactive:!0,cornerEnable:!0,directionEnable:!0,rotationEnabled:!0,scaleEnabled:!0,box:new V,totalBox:new V,childrenBoxes:[],activeType:"null",interactiveDirection:new B,scaleCorner:new B,scaleEdgeCorners:[]},this.imageSprite=X.Sprite.from(Le.config.gestureHandlerConfig.transformGizmoConfig.pictureLogoUrl),this.imageSprite._width=15,this.imageSprite._height=15,this.nullSprite=X.Sprite.from(Le.config.gestureHandlerConfig.transformGizmoConfig.nullLogoUrl),this.nullSprite._width=15,this.nullSprite._height=15}get interactive(){return Le.config.gestureHandlerConfig.transformGizmoEnabled}set interactive(t){Le.config.gestureHandlerConfig.transformGizmoEnabled=t}get infoType(){const t=this.pageDataUtils.getSelectedItems();return 1===t.length?t[0].type:w.spec.ItemType.base}actionKey(){}endActionKey(){}getRenderObjects(){const t=[];if(!this.interactive)return t;if(this.refreshRenderObject(),t.push(this.graphics),this.infoType!==w.spec.ItemType.base)switch(t.push(this.nameText),this.infoType){case w.spec.ItemType.sprite:t.push(this.imageSprite);break;case w.spec.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 B(t.offsetX,t.offsetY),i=this.wireframe;this.refreshTransformType(e);const{interactiveDirection:s}=i;this.refreshCursorResult(this.activeType,A(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 B(t.clientX,t.clientY),this.cursorPoint=new B(t.offsetX,t.offsetY),1!==t.buttons)return;if(e)return this.selectorGizmo.preAction(t,e,new B(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 F,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 F}const e=new B(t.clientX,t.clientY),i=(new B).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();(0,q.assertExist)(o);let c=0;switch(a){case"rotation":{const t=r.clone(),e=new F,a=T(E((new B).subtractVectors(this.cursorPoint,t),(new B).subtractVectors(this.cursorPoint.add(i),t))*S,3);e.z=a,this.rotationAngle+=a,c=A(n)+this.rotationAngle*z,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 V:this.pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),i=new B(this.adsorptionGizmo.absorptionResult.x??0,this.adsorptionGizmo.absorptionResult.y??0);this.adsorptionGizmo.boxTranslationAdsorption(t,this.wireframe.box,e);const r=new B(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!==w.spec.ItemType.camera&&(t.x=T(t.x,5),t.y=T(t.y,5),t.z=T(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 R).extractRotation(o.matrix).invert(),h=(new F).subtractVectors(e,i).applyMatrix(c),l=h.clone().multiply(a),p=t.clone().subtract(r).subtract(i).applyMatrix(c),m=new F(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}([k(h.x,0)?1:Math.abs(p.x/h.x),k(h.y,0)?1:Math.abs(p.y/h.y)]),g=p.toArray()[d],u=l.toArray()[d];if(k(a.x,a.y)&&k(a.z,a.x)){const t=k(u,0)?1:Math.abs(g/u);m.set(t,t,t)}else if(0===d){m.x=k(u,0)?1:Math.abs(g/u);const t=h.y*g/h.x;m.y=k(l.y,0)?1:t/l.y;const e=h.z*g/h.x;m.z=k(l.z,0)?1:e/l.z}else if(1===d){m.y=k(u,0)?1:Math.abs(g/u);const t=h.x*g/h.y;m.x=k(l.x,0)?1:t/l.x;const e=h.z*g/h.y;m.z=k(l.z,0)?1:e/l.z}else{m.z=k(u,0)?1:Math.abs(g/u);const t=h.x*g/h.z;m.x=k(l.x,0)?1:t/l.x;const e=h.y*g/h.z;m.y=k(l.y,0)?1:e/l.y}const f=m.clone().subtract(new F(1,1,0)).divide(2).add(new F(1,1,.5)),y=i.clone().add((new F).subtractVectors(e,i).multiply(a.x));this.scaleParam.lastScalar.multiply(f);const x=i.clone().add((new F).subtractVectors(e,i).multiply(this.scaleParam.lastScalar.x)),w=(new F).subtractVectors(x,y);w.x=T(w.x,5),w.y=T(w.y,5),w.z=T(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=A(n);break}}this.refreshCursorResult(a,c),this.lastPoint.copyFrom(e)}endAction(t){this.active=!1;const e=new B(t.clientX,t.clientY),i=(new B).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,A(a)),this.adsorptionGizmo.clearAbsorptionResult(),this.rotationAngle=0,this.cursorPoint=new B,this.lastPoint=new B}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)*S};break;case"rotation":this.cursorResult={type:"rotation",angle:(e+Math.PI/4)*S};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 F).copyFrom(this.pageDataUtils.getPlayerItemById(i.id).transform.anchor).applyMatrix(t.matrix),r=(new F).setFromMatrixPosition(t.matrix),a=(new W).setFromQuaternion((new U).setFromRotationMatrix(t.matrix))}this.pageDataUtils.interactionUtils.initInteractionPlane(r,a),this.scaleParam={shift:new F,center:new F,corner:new F,lastScalar:new F(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 F}this.scaleParam.shift=(this.pageDataUtils.interactionUtils.getWorldPositionByViewPoint(t)??new F).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}=Le.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 M(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!==w.spec.ItemType.base){const t=this.pageDataUtils.getSelectedItems()[0],e=t.type===w.spec.ItemType.null?"编组":"图片",{size:i,rotation:s}=t.property,r=this.infoType===w.spec.ItemType.sprite?this.imageSprite:this.nullSprite,a=this.wireframe.box.corners[3],n=s[2]*z;r.anchor.set(0,1),r.x=a.x,r.y=a.y-5,r.rotation=-n;const o=a.clone().add(new B(20,0)).rotateAround(a,-n),c=new B(0,4).rotateAround(new B,n);this.nameText.text=` ${e} ${i.map(t=>T(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 B,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 V;if(this.wireframe.edges=[],this.wireframe.scaleCorners=[],this.wireframe.childrenBoxes=[],this.wireframe.rotationCorners=[],this.wireframe.rotationEnabled=1===t.length&&t[0].type!==w.spec.ItemType.null,this.wireframe.scaleEnabled=1===t.length&&t[0].type!==w.spec.ItemType.null,this.wireframe.cornerEnable=1===t.length&&t[0].type!==w.spec.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 V).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!==w.spec.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!==w.spec.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 M((new B).copyFrom(t),(new B).copyFrom(a[(e+1)%4])))});const{scaleCircleSize:n,rotationCircleSize:o}=Le.config.gestureHandlerConfig.transformGizmoConfig;1===t.length&&this.wireframe.box.corners.forEach(t=>{this.wireframe.scaleCorners.push(new G(t,n));const e=(new B).subtractVectors(t,this.wireframe.box.getCenter()),i=(new B).copyFrom(this.wireframe.box.getCenter()).add((new B).copyFrom(e).normalize().multiply(e.length()+o-n));this.wireframe.rotationCorners.push(new G(i,o))})}setAdsorptionEnabled(t){this.enableAdsorption=t}},Q=require("@pixi/graphics"),tt=class extends C{constructor(){super(...arguments),m(this,"results",[]),m(this,"graphics",new Q.Graphics),m(this,"absorptionResult",{}),m(this,"type","adsorption")}get interactive(){return Le.config.gestureHandlerConfig.adsorptionGizmoEnabled}set interactive(t){Le.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 B(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 B(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)<Le.config.gestureHandlerConfig.adsorptionGizmoConfig.distance&&this.refreshPointAbsorptionResult(t,e,"x"),s&&Math.abs(t.y-e.y)<Le.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 B(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 M(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 M(i,s))})}refreshRenderObject(){this.graphics.clear();const{lineWidth:t,lineColor:e}=Le.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={}}},et={};c(et,{Application:()=>at.Application,utils:()=>st});var it={};c(it,{Application:()=>at.Application,utils:()=>st});require("@pixi/polyfill");var st=p(require("@pixi/utils"),1),rt=require("@pixi/interaction"),at=require("@pixi/app"),nt=require("@pixi/core"),ot=require("@pixi/loaders"),ct=require("@pixi/ticker");l(it,require("@pixi/constants")),l(it,require("@pixi/core")),l(it,require("@pixi/display")),l(it,require("@pixi/graphics")),l(it,require("@pixi/loaders")),l(it,require("@pixi/interaction")),l(it,require("@pixi/math")),l(it,require("@pixi/runner")),l(it,require("@pixi/sprite")),l(it,require("@pixi/text")),l(it,require("@pixi/ticker")),l(it,require("@pixi/settings")),st.skipHello(),nt.Renderer.registerPlugin("interaction",rt.InteractionManager),nt.Renderer.registerPlugin("batch",nt.BatchRenderer),at.Application.registerPlugin(ct.TickerPlugin),at.Application.registerPlugin(ot.AppLoaderPlugin),it.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()},it.Graphics.prototype.fillBox=function(t){const e=t.getSize();this.drawRect(t.min.x,t.min.y,e.x,e.y)},it.Graphics.prototype.drawLine=function(t){if(this.beginFill(),t instanceof M)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()},l(et,it);var ht=class extends C{constructor(t){super(),m(this,"box",new V),m(this,"graphics",new et.Graphics),m(this,"PageDataUtils"),m(this,"type","preference"),this.PageDataUtils=t}preparationAction(){}preAction(){}action(){}endAction(){}interruption(){}actionKey(){}endActionKey(){}cancelPreparation(){}refreshResults(){if(this.box=new V,!this.interactive)return void console.warn("Preference gizmo is not opened, use #SDK.setAdsorptionConfig() open this feature.");if("editor"===Le.config.mode)return;const t=this.PageDataUtils.getPageData();(0,w.assertExist)(t);const{container:e}=this.PageDataUtils;if(e){const{zoom:i}=t.property,{offsetWidth:s,offsetHeight:r}=e,a=new B(s,r).multiply(i),n=this.PageDataUtils.getViewportLeftTopPosition().add(a.clone().divide(2));this.box=(new V).setFromCenterAndSize(n,a)}}refreshRenderObjects(){if("editor"===Le.config.mode)return;const{boxWidth:t,boxColor:e,markColor:i,markAlpha:s,safeAreaEnabled:r,safeAreaBoxColor:a,safeAreaBoxAlpha:n}=Le.config.gestureHandlerConfig.preferenceGizmoConfig;this.graphics=new et.Graphics;const{offsetWidth:o,offsetHeight:c}=this.PageDataUtils.container.parentElement,h=new V(new B(0,0),new B(o,this.box.min.y)),l=new V(new B(0,this.box.min.y),new B(this.box.min.x,c)),p=new V(new B(this.box.min.x,this.box.max.y),new B(o,c)),m=new V(new B(this.box.max.x,this.box.min.y),new B(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 V(u,new B(f.x,u.y+p)),x=new V(new B(u.x,u.y+p),new B(u.x+m,f.y)),w=new V(new B(f.x-d,u.y+p),new B(f.x,f.y)),v=new V(new B(u.x+m,f.y-g),new B(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 B(r/e[0]*o.x,a/e[1]*o.y),h=new B(i/e[0]*o.x+c.x/2,s/e[1]*o.y+c.y/2).add(u),l=(new V).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 Le.config.gestureHandlerConfig.preferenceGizmoEnabled&&"editor"!==Le.config.mode?(this.refreshRenderObjects(),[this.graphics]):[]}get interactive(){return Le.config.gestureHandlerConfig.preferenceGizmoEnabled}set interactive(t){Le.config.gestureHandlerConfig.preferenceGizmoEnabled=t}},lt="https://mdn.alipayobjects.com/rms/uri/file/as/0.0.6",pt={normal:{type:"preset",content:"default"},rotation:{type:"svg",content:"default",url:`${lt}/icons/cursor-rotate-32.svg`},circle:{type:"svg",content:"default",url:`${lt}/icons/cursor-rotate-32.svg`},scale:{type:"svg",content:"default",url:`${lt}/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 mt(t,e="item doesn't exist"){if(null==t)throw new Error(e)}function dt(t,e="asserts failed"){if(!t)throw new Error(e)}function gt(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 ut(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(!ut(t[s],e[s]))return!1}return!0}var ft=class extends C{constructor(t,e){super(),m(this,"result",{type:"invalid"}),m(this,"interactionParam",{type:"none"}),m(this,"graphics",new et.Graphics),m(this,"isShiftDown",!1),m(this,"_isLockScale",!1),m(this,"_pageDataUtils"),m(this,"_eventEmitter"),m(this,"type","picture-cut"),m(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return Le.config.gestureHandlerConfig.pictureCutGizmoEnabled}set interactive(t){t!==Le.config.gestureHandlerConfig.pictureCutGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture cut gizmo can not open."):Le.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 B(t.offsetX,t.offsetY),i=new B(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 B(t.clientX,t.clientY),{startMouse:s,box:r}=this.interactionParam,a=(new B).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 B;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 B(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 V).setFromVec2Array(i)),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new B(t.offsetX,t.offsetY),i=new B(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(mt(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}=Le.config.gestureHandlerConfig.pictureCutGizmoConfig,{cutBox:d,itemBox:g}=this.result,{min:u,max:f}=d,{min:y,max:x}=g,w=new V(y.clone(),new B(x.x,u.y)),v=new V(new B(y.x,u.y),new B(u.x,x.y)),I=new V(new B(f.x,u.y),new B(x.x,f.y)),P=new V(new B(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)<Le.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 M(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*S)}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 B(Math.max(i.x,t.x),Math.max(i.y,t.y)),new B(Math.min(s.x,e.x),Math.min(s.y,e.y))),this._eventEmitter.emit("cutBoxChange",this.result.cutBox.clone()),this.result.cutBox.clone()}},yt=require("@pixi/graphics"),xt=require("@pixi/sprite"),wt=require("@galacean/effects-plugin-model");var vt=class extends C{constructor(t,e,i,s,r){super(),m(this,"type","text"),m(this,"_eventEmitter"),m(this,"textAreaElement"),m(this,"graphics",new yt.Graphics),m(this,"_pageDataUtils"),m(this,"result"),m(this,"interactionParam"),m(this,"_adsorptionGizmo"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"rotationSprite",new xt.Sprite),m(this,"_selectorGizmo"),m(this,"handleInput",async t=>{const e=t.target;await this._pageDataUtils.changeItemProperty({itemId:this._pageDataUtils.getSelectedItems()[0].id,type:w.spec.ItemType.text,propertyName:"text",propertyValue:e.value}),this._eventEmitter.emit("textInput",{text:e.value,fontFamily:e.style.fontFamily})}),m(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 B,lastPoint:new B,startPoint:new B,lastWorldPosition:new F}}get interactive(){return Le.config.gestureHandlerConfig.textGizmoEnbaled}set interactive(t){Le.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 B(t.offsetX,t.offsetY),i=new B(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 B(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 F,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 B(t.clientX,t.clientY),this.interactionParam.startPoint=new B(t.offsetX,t.offsetY);const e=new B(t.offsetX,t.offsetY).subtract(this._pageDataUtils.getViewportLeftTopPosition());this.initInteractionPlane(e),this.interactionParam.lastWorldPosition=this._pageDataUtils.interactionUtils.getWorldPositionByViewPoint(e)??new F}const e=new B(t.clientX,t.clientY),{type:i,lastPoint:s,startPoint:r,anchor:a}=this.interactionParam,n=(new B).subtractVectors(e,s),o=this._pageDataUtils.getSelectedItems();switch(i){case"rotation":{const t=new F,e=T(E((new B).subtractVectors(r,a),(new B).subtractVectors(r.add(n),a))*S,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();(0,w.assertExist)(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 V:this._pageDataUtils.getViewBoxById(t.id)).filter(t=>!t.isEmpty()),s=new B(this._adsorptionGizmo.absorptionResult.x??0,this._adsorptionGizmo.absorptionResult.y??0);this._adsorptionGizmo.boxTranslationAdsorption(t,this.result.box,i);const r=new B(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!==w.spec.ItemType.camera&&(t.x=T(t.x,5),t.y=T(t.y,5),t.z=T(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 B).subtractVectors(t,a),s=(new B).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 B).subtractVectors(l,t);r.add(p);const m=this._pageDataUtils.interactionUtils.getWorldSizeByViewSize(p);m.x=T(m.x,5),m.y=T(m.y,5),m.z=T(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 B(t.offsetX,t.offsetY),i=new B(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!==w.spec.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 M(i.corners[0],i.corners[1]).at(.5),new M(i.corners[2],i.corners[3]).at(.5)],s=new M(i.getCenter(),new M(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]*wt.DEG2RAD}}}refreshInteractionParam(t,e){if("empty"===this.result.type)return this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new B,this.interactionParam.startPoint=new B,void(this.interactionParam.lastWorldPosition=new F);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 F);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 F)):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 F)):(this.interactionParam.active=!1,this.interactionParam.type="none",this.interactionParam.lastPoint=new B,this.interactionParam.startPoint=new B,void(this.interactionParam.lastWorldPosition=new F))}refreshCursorResult(){const t=(new B).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)*S};break;case"rotation":this.cursorResult={type:"rotation",angle:(t+Math.PI/4)*S}}}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}=Le.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]*wt.DEG2RAD),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]*wt.DEG2RAD),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()}}},It=require("@pixi/core"),Pt=class extends C{constructor(t){super(),m(this,"_pageDataUtils"),m(this,"_config",{}),m(this,"type","mask"),m(this,"cursorResult",{type:"normal",angle:0}),m(this,"result",{status:"init",lines:[]}),m(this,"graphics",new et.Graphics),m(this,"linesMaskGraphics",new et.Graphics),m(this,"rectMaskGraphics",new et.Graphics),this._pageDataUtils=t}get interactive(){return Le.config.gestureHandlerConfig.maskGizmoEnabled}set interactive(t){t!==Le.config.gestureHandlerConfig.maskGizmoEnabled&&(t||(this.result.status="init"),Le.config.gestureHandlerConfig.maskGizmoEnabled=t)}get config(){return{...Le.config.gestureHandlerConfig.maskGizmoConfig,...this._config}}set config(t){this._config={...this._config,...t}}initialize(){}preparationAction(t){if(this.interactive)return this.result.point=new B(t.offsetX,t.offsetY),this.type}preAction(t){if(this.interactive)return this.result.point=new B(t.offsetX,t.offsetY),this.result.lines.push([]),this.type}action(t){if(!this.interactive||"init"===this.result.status)return;const e=new B(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(mt(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 V(new B(n.x,n.y),new B(o.x,n.y)),h=new V(new B(n.x,n.y),new B(n.x,o.y)),l=new V(new B(o.x,n.y),new B(o.x,n.y)),p=new V(new B(n.x,o.y),new B(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:et.LINE_CAP.ROUND,join:et.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 et.Renderer({width:Math.ceil(t.width),height:Math.ceil(t.height),backgroundColor:16777215}),i=new et.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}},Ct=class extends C{constructor(t){super(),m(this,"type","loading"),m(this,"_pageDataUtils"),m(this,"_idMap",new Map),m(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 et.Graphics,ticker:new et.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}},Dt=class extends C{constructor(t,e){super(),m(this,"result",{type:"invalid"}),m(this,"interactionParam",{type:"none"}),m(this,"graphics",new et.Graphics),m(this,"isShiftDown",!1),m(this,"_isLockScale",!1),m(this,"_pageDataUtils"),m(this,"_eventEmitter"),m(this,"type","picture-expand"),m(this,"cursorResult",{type:"normal",angle:0}),this._pageDataUtils=t,this._eventEmitter=e}get interactive(){return Le.config.gestureHandlerConfig.pictureExpandGizmoEnabled}set interactive(t){t!==Le.config.gestureHandlerConfig.pictureExpandGizmoEnabled&&(1!==this._pageDataUtils.getPageData()?.activeData.selectedItems?.length?console.warn("Selected items` length is not one, Picture expand gizmo can not open."):Le.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 B(t.offsetX,t.offsetY),i=new B(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 B(t.clientX,t.clientY),{startMouse:s,box:r}=this.interactionParam,a=(new B).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 B(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 V).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 V).setFromVec2Array(s)),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone());break}}}endAction(t){if(!this.interactive||"none"===this.interactionParam.type)return;const e=new B(t.offsetX,t.offsetY),i=new B(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(mt(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}=Le.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)<Le.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 M(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*S)}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 B(Math.min(i.x,t.x),Math.min(i.y,t.y)),new B(Math.max(s.x,e.x),Math.max(s.y,e.y))),this._eventEmitter.emit("expandBoxChange",this.result.expandBox.clone()),this.result.expandBox.clone()}},bt=class{constructor(t){m(this,"wireframeApplication"),m(this,"gizmos",[]),m(this,"activeGizmo"),m(this,"selectorGizmo"),m(this,"transformGizmo"),m(this,"controlGizmo"),m(this,"preferenceGizmo"),m(this,"pictureCutGizmo"),m(this,"pictureExpandGizmo"),m(this,"textGizmo"),m(this,"maskGizmo"),m(this,"loadingGizmo"),m(this,"_ignoreInteraction",!1),m(this,"clickButtons",0),m(this,"container"),m(this,"_emitter"),m(this,"clickTime",0),m(this,"firstClick",!0),m(this,"dblclickTimeSpan",500),m(this,"spaceEmit",!1),m(this,"interactType","select"),this.gizmos=[];const{width:e,height:i}=t.getBoundingClientRect();this.wireframeApplication=new P.Application({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(pt).map(([t,e])=>{const{url:i}=e;if(i)return fetch(i).then(t=>t.text()).then(i=>pt[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 Z||this.activeGizmo instanceof ft||this.activeGizmo instanceof Dt||this.activeGizmo instanceof Pt||this.activeGizmo instanceof vt||this.activeGizmo instanceof O?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 O(t),this.selectorGizmo=new Y(t);const i=new tt;this.transformGizmo=new Z(t,i,this.selectorGizmo),this.preferenceGizmo=new ht(t),this.pictureCutGizmo=new ft(t,e),this.pictureExpandGizmo=new Dt(t,e),this.textGizmo=new vt(t,i,this.selectorGizmo,e,this.wireframeApplication?.view.parentElement),this.textGizmo.rotationSprite.texture=await It.Texture.fromURL(Le.config.gestureHandlerConfig.textGizmoConfig.rotationCornerTexture),this.maskGizmo=new Pt(t),this.loadingGizmo=new Ct(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=pt[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(Le.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(Le.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureCutGizmo(){if(!this.pictureCutGizmo)return;const t=JSON.parse(JSON.stringify(Le.config));this.pictureCutGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(Le.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(Le.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(Le.config));this.render(),this._emitter?.emit("sdkConfigChange",t,e)}closePictureExpandGizmo(){if(!this.pictureExpandGizmo)return;const t=JSON.parse(JSON.stringify(Le.config));this.pictureExpandGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0,this.textGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(Le.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(Le.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(Le.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(Le.config));this.maskGizmo.interactive=!1,this.transformGizmo.interactive=!0,this.selectorGizmo.interactive=!0;const e=JSON.parse(JSON.stringify(Le.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(Le.config));this.loadingGizmo.addId(t),this.loadingGizmo.interactive&&(this.maskGizmo.interactive=!1,this.pictureCutGizmo.interactive=!1);const i=JSON.parse(JSON.stringify(Le.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}closeLoadingGizmo(t){if(!this.loadingGizmo)return;const e=JSON.parse(JSON.stringify(Le.config));this.loadingGizmo.deleteId(t);const i=JSON.parse(JSON.stringify(Le.config));this.render(),this._emitter?.emit("sdkConfigChange",e,i)}setPictureCutGizmoLockScale(t){this.pictureCutGizmo.isLockScale=t}setPictureExpandGizmoLockScale(t){this.pictureExpandGizmo.isLockScale=t}},zt=require("@galacean/effects"),St=class{constructor(t){m(this,"plane",new L),m(this,"ray",new H),m(this,"viewportParam",{width:0,height:0,scale:1,translation:new B,rulerWidth:0}),m(this,"cameraParam",{position:new F,rotation:new F,focusPosition:new F,focusRotation:new F,viewProjectionMatrix:new R,inverseViewProjectionMatrix:new R}),m(this,"pageDataUtils"),this.pageDataUtils=t}refreshViewParam(){const t=this.pageDataUtils.getPageData();(0,zt.assertExist)(t,"You must run SDK first");const e=new B(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 B(...s),this.viewportParam.rulerWidth=0}refreshCameraParam(){const{player:t}=this.pageDataUtils,e=t?.getCompositions()?.[0]?.camera;if(e){const t=R.fromArray(e.getViewProjectionMatrix().toArray()),i=R.fromArray(e.getViewMatrix().toArray()).invert(),s=new U;i.decompose(this.cameraParam.position,s,new F),this.cameraParam.rotation=(new W).setFromQuaternion(s).toDegreeVector3(),this.cameraParam.focusPosition=new F(...this.cameraParam.position.toVector2().toArray(),this.cameraParam.position.z>0?0:2*this.cameraParam.position.z),this.cameraParam.focusPosition.applyEuler((new W).setFromDegreeVector3(this.cameraParam.rotation.clone()),this.cameraParam.position),this.cameraParam.focusRotation=(new W).setFromQuaternion(s.invert()).toDegreeVector3(),this.cameraParam.viewProjectionMatrix=t,this.cameraParam.inverseViewProjectionMatrix=R.fromArray(e.getInverseViewProjectionMatrix().toArray())}}initInteractionPlane(t,e){t??(t=this.cameraParam.focusPosition),e??(e=(new W).setFromDegreeVector3(this.cameraParam.rotation));const i=new F(0,0,1).applyEuler(e);this.plane.setFromNormalAndCoplanarPoint(t,i)}getWorldSizeByViewSize(t,e=!0,i){const s=e||!i?(new W).setFromDegreeVector3(this.cameraParam.rotation):(new W).setFromQuaternion((new U).setFromRotationMatrix(this.pageDataUtils.getItemTransformById(i).matrix)),r=i?(new F).setFromMatrixPosition(this.pageDataUtils.getItemTransformById(i).matrix):this.cameraParam.focusPosition,a="editor"===Le.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 F(0,0,0);const c=(new W).setFromQuaternion((new U).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"===Le.config.mode?1:s;return(new B).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 N).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"===Le.config.mode?1:s;return new B(t.x/(e*r)*2-1,1-t.y/(i*r)*2)}getNDCSizeByPixelSize(t){const{width:e,height:i}=this.viewportParam;return new B(t.x/e*2,-t.y/i*2)}getPixelSizeByNDCSize(t){const{width:e,height:i}=this.viewportParam;return new B(t.x/2*e,-t.y/2*i)}getViewPositionWWithOutTransform(t){const{scale:e}=this.viewportParam,i="editor"===Le.config.mode?1:e;return t.divide(i)}getViewPositionByPixelPoint(t){if("template"===Le.config.mode)return t.clone();const{width:e,height:i,scale:s,translation:r}=this.viewportParam;return t.clone().scaleByCenter(new B(s,s),new B(e/2,i/2)).add(r)}},At=require("@ffmpeg/ffmpeg"),Et=require("@ffmpeg/util"),Tt={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"},kt={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 _t(t,e,i,s){const r=e.getContext("2d");dt(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 Bt(){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)})}(Tt.SCRIPT,{crossOrigin:"anonymous"});const e={locateFile:(t,e)=>t.endsWith("createWebPCore.wasm")?Tt.WASM:e+t};t(await window.createWebPCore(e))}catch(t){e(t)}})}function Mt(t){for(const e of t.getCompositions())for(const t of e.textures)t.isDestroyed||t.dispose();t.disposed||t.destroyCurrentCompositions()}function Vt(t=[750,750]){const e=(0,w.generateGUID)(),i={id:(0,w.generateGUID)(),dataType:w.spec.DataType.TimelineAsset,tracks:[]},s={id:(0,w.generateGUID)(),item:{id:e},dataType:w.spec.DataType.CompositionComponent,items:[],timelineAsset:{id:i.id},sceneBindings:[]},r={id:e,name:"AI 设计师画布",duration:999,startTime:0,endBehavior:w.spec.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:w.spec.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 Gt(t,e,i,s,r,a,n){const o=(0,w.generateGUID)(),c={id:t,name:a,dataType:w.spec.DataType.VFXItemData,components:[{id:o}],delay:0,duration:999,endBehavior:w.spec.EndBehavior.restart,renderLevel:w.spec.RenderLevel.BPlus,type:w.spec.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:w.spec.DataType.SpriteComponent,options:{startColor:[1,1,1,1]},renderer:{renderMode:w.spec.RenderMode.MESH}};n&&(h.renderer.texture={id:n});const l={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationPlayableAsset},p={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:l.id}}]},m={id:(0,w.generateGUID)(),dataType:w.spec.DataType.SpriteColorPlayableAsset,startColor:[1,1,1,1]};return{item:c,components:[h],tracks:[p,{id:(0,w.generateGUID)(),dataType:w.spec.DataType.SpriteColorTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:m.id}}]}],playableAssets:[l,m]}}function Ut(t,e,i,s,r,a){const n=(0,w.generateGUID)(),o={id:t,name:e,dataType:w.spec.DataType.VFXItemData,components:[{id:n}],delay:0,duration:999,endBehavior:w.spec.EndBehavior.restart,renderLevel:w.spec.RenderLevel.BPlus,type:w.spec.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:w.spec.DataType.TextComponent,options:a,renderer:{renderMode:1}},h={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationPlayableAsset};return{item:o,components:[c],tracks:[{id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:h.id}}]}],playableAssets:[h]}}function Ft(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:(0,w.generateGUID)(),dataType:w.spec.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 Rt(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 F,scale:o=new F(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 F,scale:c=new F(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 Wt(t,e){let i;return t.components.forEach(s=>{if(s.dataType===w.spec.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}var Lt,Ht,Nt,Ot,Kt,jt,Yt,$t,qt,Jt,Xt,Zt,Qt,te,ee,ie,se,re,ae,ne=require("@galacean/effects"),oe=require("@galacean/effects-plugin-multimedia"),ce=class{static createEmpty(t,e=null,i="NewVFXItem"){const s=he.createVFXItem(t,e,i);return s.type=ne.spec.ItemType.null,s}static createSprite(t,e=null,i="NewSpite"){const s=he.createVFXItem(t,e,i,ne.SpriteComponent);return s.type=ne.spec.ItemType.sprite,s}static createText(t,e=null,i="NewText"){const s=he.createVFXItem(t,e,i,ne.TextComponent);return s.type=ne.spec.ItemType.text,s}static createVideo(t,e=null,i="NewVideo"){const s=he.createVFXItem(t,e,i,oe.VideoComponent);return s.type=ne.spec.ItemType.video,s}},he=class{static createVFXItem(t,e=null,i="NewVFXItem",...s){const r=new ne.VFXItem(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}},le=require("@galacean/effects"),pe=class{constructor(t,e,i,s){m(this,"sdk"),m(this,"player"),m(this,"container"),m(this,"emitter"),m(this,"interactionUtils"),this.player=t,this.sdk=s,this.container=e,this.emitter=i}init(){this.interactionUtils=new St(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===w.spec.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===w.spec.EndBehavior.restart||a===w.spec.EndBehavior.freeze)}addSelectedItems(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const e=this.sdk.pageData.activeData.selectedItems??[];t.forEach(t=>{j(e,t)}),this.emitter.emit("selectedItemChange",e)}removeSelectedItems(t){(0,w.assertExist)(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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.activeData.preSelectedItem=t,this.emitter.emit("preSelectedItemChange",t)}clearPreSelectedItem(){(0,w.assertExist)(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();(0,w.assertExist)(t,"You must call SDK#run() first");const e=t.activeData.preSelectedItem;return e?this.getViewItemById(e):void 0}addLoadingItems(t){var e;(0,w.assertExist)(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=>{j(i,t)}),this.emitter.emit("loadingItemChange",i)}removeLoadingItems(t){(0,w.assertExist)(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){Mt(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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),this.sdk.pageData.time=t}pageZoom(t,e,i){var s;(0,w.assertExist)(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:b(t,-.1,.1),p=T(b(r+l,Le.config.pageConfig.minZoom,Le.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=p,Le.config.mode){case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new B(a,n)),i=e??new B(o/2,c/2),s=this.interactionUtils.getNDCPositionByScreenPosition(i),r=(s.x-t.x)/h,l=(s.y-t.y)/h,m=new B(s.x-r*p,s.y-l*p),d=(new R).compose(new F(m.x,m.y,0),new U,new F(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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const{translation:[e=0,i=0]}=this.sdk.pageData.property,s=T(b(t,Le.config.pageConfig.minZoom,Le.config.pageConfig.maxZoom),2);switch(this.sdk.pageData.property.zoom=s,Le.config.mode){case"template":this.container.style.scale=`${s}`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new B(e,i)),r=(new R).compose(new F(t.x,t.y,0),new U,new F(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){(0,w.assertExist)(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],Le.config.mode){case"template":this.container.style.translate=`${r}px ${a}px`;break;case"editor":{const t=this.interactionUtils.getNDCSizeByPixelSize(new B(r,a)),e=(new R).compose(new F(t.x,t.y,0),new U,new F(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 R).copyFrom(i.transform.getParentMatrix()??new R);s.setPosition(new F);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===w.spec.ItemType.text){const{textWidth:t}=i.property;this.changeItemProperty({itemId:i.id,type:w.spec.ItemType.text,propertyName:"textWidth",propertyValue:t*e})}}getItemTransformById(t){const e={matrix:new R,parentMatrix:new R},i=this.getPlayerItemById(t);if(void 0!==i?.transform){i.transform.updateLocalMatrix();const t=R.fromArray(i.composition?.transform.getWorldMatrix().elements??[]).invert();e.matrix=t.clone().multiply(R.fromArray(i.transform.getWorldMatrix().elements)),e.parentMatrix=t.clone().multiply(R.fromArray(i.transform.parentTransform?.getWorldMatrix().elements??(new R).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)Le.config.pageConfig.filterItemNames.includes(i.name)||(s([i]),this.addViewItemsByItems(t,i.children,i.getInstanceId()))}createViewItemByPlayerItem(t,e){(0,w.assertExist)(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"===Le.config.mode?1:n,p=this.getViewportLeftTopPosition();if(t.type!==w.spec.ItemType.null){i.updateLocalMatrix();const e=(new R).copyFrom(s?.transform.getWorldMatrix()??(new R).identity()).invert().multiply(i.getWorldMatrix()),r=new F,n=new U,o=new F;e.decompose(r,n,o);const c=(new W).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"===Le.config.mode?d.subtract(l.clone().multiply(h)).scaleByCenter(new B(1/h,1/h),new B(p/2,m/2)).toArray().map(t=>T(t,2)):d.divide(h).toArray().map(t=>T(t,2)),u=c.toArray().map(t=>T(t,2)),f=o.toArray().map(t=>T(t,2)),y=i.size.toArray(),x=this.getPixelSizeByWorldSize([f[0]*y[0],f[1]*y[1],f[2]],t).map(t=>T(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"===Le.config.mode?i.subtract(o.clone().multiply(n)).scaleByCenter(new B(1/n,1/n),new B(c/2,h/2)).toArray().map(t=>T(t,2)):i.toArray();a.position=s,a.size=e.getSize().divide(l).toArray()}switch(t.type){case w.spec.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 w.spec.ItemType.text:case w.spec.ItemType.richtext:{const e=this.getViewProperty()?.scene;if(a.keyPropertyEditing=!0,e){e.components.filter(e=>e.item.id===t.getInstanceId()).forEach(t=>{if(![w.spec.DataType.TextComponent,w.spec.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:T(255*t,0)):void 0,d=i.map((t,e)=>e>2?t:T(255*t,0)),g=h?.outlineWidth;Object.assign(a,{textAlign:e,textColor:d,fontWeight:r,text:s,fontFamily:n,fontSize:o,fontStyle:c,outlineColor:m,outlineWidth:g,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 V,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 F).copyFrom(e.transform.anchor).applyMatrix((new R).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 V;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{const{transform:s,composition:r}=t;s.updateLocalMatrix();const{size:a}=s,n=(new R).copyFrom(r?.transform.getWorldMatrix()??new R).invert().multiply(s.getWorldMatrix()),{x:o,y:c}=a.clone().divide(2),h=new F(o,c,0).applyMatrix(n),l=new F(o,-c,0).applyMatrix(n),p=new F(-o,-c,0).applyMatrix(n),m=new F(-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 w.spec.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"===Le.config.mode)return new B;const{zoom:t,translation:e}=this.sdk.pageData.property,{offsetWidth:i,offsetHeight:s}=this.container.parentElement,{offsetWidth:r,offsetHeight:a}=this.container,n=new B(i,s),o=new B(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 B(t/2,e/2).add(new B(...this.sdk.pageData?.property.translation??[0,0]))}getViewportByViewPoint(t){if(!this.sdk.pageData)return t;const{zoom:e}=this.sdk.pageData.property,i="editor"===Le.config.mode?1:e,{width:s,height:r}=this.interactionUtils.viewportParam,a=new B(s,r).multiply(i),n=this.getViewportLeftTopPosition(),o=t.clone().subtract(n);return new B(o.x/a.x*2-1,1-o.y/a.y*2)}async changeItemProperty(t){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(0,w.assertExist)(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"===Le.config.mode?this.interactionUtils.viewportParam.scale:1;switch(t.propertyName){case"textAlign":[w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(t.propertyValue)&&i.getComponent(w.TextComponent).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:T(t/255,5));i.getComponent(w.TextComponent).setTextColor(e)}break;case"fontFamily":if("string"==typeof t.propertyValue){const e=t.propertyValue.split("/"),s=e[e.length-1]?.split(".")[0];await le.AssetManager.loadFontFamily([{fontURL:t.propertyValue,fontFamily:s}]),s&&i.getComponent(w.TextComponent).setFontFamily(s)}break;case"text":if("string"==typeof t.propertyValue){const e=i.getComponent(w.TextComponent);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 B(n,a).multiply(s),c=this.interactionUtils.getWorldSizeByViewSize(o);i.transform.setSize(Math.abs(c.x),Math.abs(c.y))}break;case"fontWeight":[w.spec.TextWeight.normal,w.spec.TextWeight.bold,w.spec.TextWeight.lighter].includes(t.propertyValue)&&i.getComponent(w.TextComponent).setFontWeight(t.propertyValue);break;case"textWidth":{const e=i.getComponent(w.TextComponent);e.setTextWidth(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new B(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(w.TextComponent);e.setLineHeight(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new B(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(w.TextComponent);if("function"==typeof e.setOutlineColor){const i=t.propertyValue.map((t,e)=>e>2?t:T(t/255,5));e.setOutlineColor(i)}}break;case"outlineWidth":if("number"==typeof t.propertyValue){const e=i.getComponent(w.TextComponent);"function"==typeof e.setOutlineWidth&&e.setOutlineWidth(t.propertyValue)}break;case"fontSize":if("number"==typeof t.propertyValue&&i.type===w.spec.ItemType.text){const e=i.getComponent(w.TextComponent);e.setFontSize(t.propertyValue);const r=Math.ceil(e.textLayout.lineHeight*e.lineCount);e.setTextHeight(r);const a=e.textLayout.width,n=new B(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(w.SpriteComponent).setTexture(await w.Texture.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 B(...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 F(...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 F(...r,1))}break;case"visible":if("boolean"==typeof t.propertyValue&&(i.setVisible(t.propertyValue),Le.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){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first"),(0,w.assertExist)(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 B(...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((0,w.assertExist)(e,"Param is not exsited."),e.propertyName){case"textAlign":if([w.spec.TextAlignment.left,w.spec.TextAlignment.middle,w.spec.TextAlignment.right].includes(e.propertyValue)){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.DataType.RichTextComponent].includes(t.dataType));if(i?.options){const t=e.propertyValue.map((t,e)=>e>2?t:T(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&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a,n],c=this.interactionUtils.getWorldSizeByViewSize(new B(...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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),a=e.textLayout.width,n=Math.ceil(e.lineCount*e.lineCount);r.options.textHeight=n;const o=[a,n],c=this.interactionUtils.getWorldSizeByViewSize(new B(...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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),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 B(...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&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.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:T(t/255,5))])}break;case"outlineWidth":if("number"==typeof e.propertyValue){const i=t.components.find(t=>t.item.id===e.itemId&&[w.spec.DataType.TextComponent,w.spec.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&&[w.spec.DataType.TextComponent,w.spec.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(w.TextComponent),r=e.textLayout.width,a=Math.ceil(e.lineCount*e.lineCount);s.options.textHeight=a;const n=[r,a],c=this.interactionUtils.getWorldSizeByViewSize(new B(...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,Le.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){(0,w.assertExist)(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;(0,w.assertExist)(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){(0,w.assertExist)(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(){(0,w.assertExist)(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=(0,w.generateGUID)()}=t,p=this.interactionUtils.getWorldSizeByViewSize(new B(...r).multiply(i)),m=new F(...a??[1,1],1),d=new F(0,0,o),g=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new B(...c)))??new F,u=e.images.findIndex(t=>t.url===n);let f,y={};if(n)if(u<0){f=await w.Texture.fromImage(n,this.player.renderer.engine);const t={id:(0,w.generateGUID)(),url:n,renderLevel:w.spec.RenderLevel.BPlus};y={id:f.guid,source:{id:t.id},flipY:!0,dataType:w.spec.DataType.Texture},e.images.push(t),e.textures??(e.textures=[]),e.textures.push(y)}else{const t=e.textures?.find(t=>t.source.id===e.images[u].id);y={id:t?.id},f=this.player.renderer.engine.findObject({id:t.id})}const x=Gt(l,g,d,new B(Math.abs(p.x),Math.abs(p.y)),m,s,y?.id);e.items.find(t=>t.id===h)&&(x.item.parentId=h),Ft(e,x);const v=this.player.getCompositions()[0],I=ce.createSprite(v,null,s);if(I.setInstanceId(x.item.id),I.duration=999,I.defination.delay=0,I.endBehavior=w.spec.EndBehavior.restart,I.transform.setSize(Math.abs(p.x),Math.abs(p.y)),I.transform.setPosition(...g.toArray()),I.transform.setRotation(...d.toArray()),I.transform.setScale(...m.toArray()),f){I.getComponent(w.SpriteComponent).setTexture(f)}return this.refreshSceneAndPageData(),x.item.id}addNullItem(t){const e=this.getActiveTargetScene();if(!e)return;const{name:i="空节点",position:s=[0,0],id:r=(0,w.generateGUID)(),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 B(...s))??new F,h=function(t,e,i){const s=JSON.parse(JSON.stringify(i)),r={id:t,name:e,duration:999,type:w.spec.ItemType.null,visible:!0,endBehavior:w.spec.EndBehavior.restart,delay:0,renderLevel:w.spec.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:w.spec.DataType.VFXItemData},a={id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationPlayableAsset};return{item:r,components:[],tracks:[{id:(0,w.generateGUID)(),dataType:w.spec.DataType.ActivationTrack,children:[],clips:[{start:0,duration:999,endBehavior:w.spec.EndBehavior.restart,asset:{id:a.id}}]}],playableAssets:[a]}}(r,i,c);Ft(e,h),o.forEach(t=>{Rt(e,t,r)});const l=this.player.getCompositions()[0],p=ce.createEmpty(l,null,i);return p.setInstanceId(h.item.id),p.duration=999,p.defination.delay=0,p.endBehavior=w.spec.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=(0,w.generateGUID)(),parentId:s,name:r="文本",lineHeight:a,textWidth:n,fontFamily:o,position:c=[0,0],fontSize:h,fontWeight:l=w.spec.TextWeight.normal,fontStyle:p=w.spec.FontStyle.normal,textAlign:m=w.spec.TextAlignment.left,text:d,textColor:g,textHeight:u=a,outlineColor:f=[.8,.8,.8,1],outlineWidth:y=0,rotation:x=0,url:v}=t;v&&!e.fonts?.find(t=>t.fontFamily===o)&&(e.fonts??(e.fonts=[]),e.fonts.push({fontFamily:o,fontURL:v}));const I={text:d,fontFamily:o,fontSize:h,textColor:g,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:n,textHeight:u,lineHeight:a,textBaseline:w.spec.TextBaseline.top,textOverflow:w.spec.TextOverflow.visible,outline:{outlineColor:f,outlineWidth:y}},P=this.player.getCompositions()[0],C=ce.createText(P,null,r);C.setInstanceId(i),C.duration=999,C.defination.delay=0,C.endBehavior=w.spec.EndBehavior.restart;const D=C.getComponent(w.TextComponent),b={options:I,renderer:{renderMode:1},dataType:w.spec.DataType.TextComponent,item:{id:C.getInstanceId()},id:D.getInstanceId()};D.fromData(b),b.options.textHeight=Math.ceil(a*D.lineCount),D.fromData(b),await le.AssetManager.loadFontFamily([{fontURL:v,fontFamily:o}]),D.setFontFamily(o);const z=new B(n,I.textHeight).multiply(this.interactionUtils.viewportParam.scale),S=this.interactionUtils.getWorldSizeByViewSize(z),A=new F(0,0,x),E=this.interactionUtils.getWorldPositionByViewPoint(this.interactionUtils.getViewPositionByPixelPoint(new B(...c)))??new F,T=Ut(i,r,E,A,new B(Math.abs(S.x),Math.abs(S.y)),I);e.items.find(t=>t.id===s)&&(T.item.parentId=s),Ft(e,T),C.transform.setSize(Math.abs(S.x),Math.abs(S.y)),C.transform.setPosition(...E.toArray()),C.transform.setRotation(...A.toArray()),(0,w.assertExist)(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===w.spec.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){(0,w.assertExist)(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 F).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 w.spec.ItemType.sprite:{const{size:a}=r,h=this.interactionUtils.projectPoint(new F),l=this.interactionUtils.projectPoint(new F(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:Wt(s,t),size:p,scale:[o.x,o.y],rotation:n.z,position:[c.x,c.y]}}case w.spec.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 w.spec.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 V;let i;const s=(t,e,s)=>{const{id:r=(0,w.generateGUID)(),url:a,name:n="图层",scale:o=[1,1]}=t,c=new B(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:(0,w.generateGUID)(),url:a,renderLevel:w.spec.RenderLevel.BPlus};l={id:(0,w.generateGUID)(),source:{id:t.id},flipY:!0,dataType:w.spec.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=Gt(r,new F(s.x,s.y,0),new F(0,0,t.rotation??0),c,new F(t.scale?.[0]??1,t.scale?.[1]??1,1),n,l.id);Ft(i,p)},r=(t,e,s)=>{const{id:r=(0,w.generateGUID)(),name:a="文本",lineHeight:n,textWidth:o,fontFamily:c,fontSize:h,fontWeight:l=w.spec.TextWeight.normal,fontStyle:p=w.spec.FontStyle.normal,textAlign:m=w.spec.TextAlignment.left,text:d,textColor:g,rotation:u=0,url:f,textHeight:y}=t;f&&!i.fonts?.find(t=>t.fontFamily===c)&&(i.fonts??(i.fonts=[]),i.fonts.push({fontFamily:c,fontURL:f}));const x={text:d,fontFamily:c,fontSize:h,textColor:g,fontWeight:l,letterSpace:0,textAlign:m,fontStyle:p,textWidth:o,textHeight:y??n,lineHeight:n},v=Ut(r,a,new F(...s.toArray(),0),new F(0,0,u),new B(e.x,e.y),x);Ft(i,v)};if(Array.isArray(t)){t.map(t=>this.getViewBoxById(t)).map(t=>e.union(t));const a=e.getSize();i=Vt(a.toArray());const n=(new R).compose(new F(0,0,8),new U,new F(1,1,1)).invert(),o=(new R).perspective(60*z,a.x/a.y,.1,40,!0),c=(new R).multiplyMatrices(o,n),h=c.clone().invert(),l=c.projectPoint(new F).z,p=new F(0,0,l).applyMatrix(h),m=new F(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 B(d,g)).abs(),o=a.getCenter().subtract(e.getCenter()).multiply(new B(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=Vt(o.toArray());const c=(new R).compose(new F(0,0,8),new U,new F(1,1,1)).invert(),h=(new R).perspective(60*z,o.x/o.y,.1,40,!0),l=(new R).multiplyMatrices(h,c),p=l.clone().invert(),m=l.projectPoint(new F).z,d=new F(0,0,m).applyMatrix(p),g=new F(2,2,m).applyMatrix(p),u=(new F).subtractVectors(g,d);if(n)switch(n.type){case"sprite":s(n,new B(u.x,u.y),new B);break;case"text":r(n,new B(u.x,u.y),new B)}}return i}updateItemOrder(t,e){(0,w.assertExist)(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){(0,w.assertExist)(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===w.spec.DataType.CompositionComponent);i&&(i.items=t.items.map(t=>({id:t.getInstanceId()})))}}}getViewProperty(t){return(0,w.assertExist)(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(){(0,w.assertExist)(this.sdk.pageData,"You must call SDK#run() first");const t=new V;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 B).subtractVectors(new B(e/2,i/2),r);this.pageMove(o),this.pageZoom(n*s-s,void 0,!0)}}},me=p(require("jszip"),1),de=p(require("jszip"),1),ge="ready",ue="executable",fe="dispose",ye={APNG:"APNG",MP4:"MP4",WebM:"WebM",Images:"Images",WebP:"WebP",GIF:"GIF",AlphaMaskVideo:"AlphaMaskVideo"},xe="idle",we="convertImage",ve="transcoding",Ie="audio",Pe="jpeg",Ce="webp",De="png",be=(ye.MP4,ye.WebP,ye.APNG,ye.GIF,ye.AlphaMaskVideo,ye.Images,ye.MP4,ye.WebP,ye.APNG,ye.GIF,ye.AlphaMaskVideo,ye.Images,"default"),ze="exporting",Se="success",Ae="error",Ee={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"},Te={highest:"1",high:"3",medium:"6",low:"9"},ke=class{constructor(t){m(this,"sampleRate"),m(this,"duration"),m(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)}},_e=["@vvfx/sdk","exporter"],Be=class extends w.EventEmitter{constructor(t){super(),m(this,"status",ge),m(this,"stage",xe),m(this,"mediaType"),m(this,"loggerInTranscoding"),m(this,"multiThreading"),m(this,"extraCanvas"),m(this,"player"),u(this,Lt,0),u(this,Ht),u(this,Nt),u(this,Ot),u(this,Kt),u(this,jt,[]),u(this,Yt),u(this,$t),u(this,qt,[]),u(this,Jt,0),u(this,Xt),u(this,Zt,[]),u(this,Qt,0),u(this,te,0),u(this,ee,0),u(this,ie,0),u(this,se,[]),u(this,re,[]),u(this,ae,!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===fe}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=g(this,Xt)?.time;return{name:i,startTime:r,oldTotalTime:s,newTotalTime:a,fps:g(this,Xt)?.fps??30,backgroundColor:g(this,Xt)?.backgroundColor??"#000000",loop:g(this,Xt)?.loop??!0,audioEnable:g(this,Xt)?.audioEnable??!1}}get gifConfig(){return g(this,Xt)?.gifConfig}get apngConfig(){return g(this,Xt)?.apngConfig}get progress(){const t=g(this,te)||1,e=g(this,ee)||1,i=Math.min(t/e,1),s=Math.min(g(this,Qt),t)/t*.4,r=Math.min(g(this,ie),t)/t*.6,a=Math.min(s+r,1);g(this,Zt)[g(this,Jt)]=i;const n=g(this,Zt).reduce((t,e,i)=>i<g(this,Jt)?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===ye.MP4?Pe:this.mediaType===ye.WebP?Ce:De}async onInit(){try{gt("log",[..._e,"ready"],"starting"),this.status=ge,await this.loadHelper(this.mediaType),this.status=ue,gt("log",[..._e,"ready"],"success"),this.emit("ready",this.mediaType)}catch(t){this.status=fe,this.onError(t)}finally{return this.status}}onReset(){this.stage=xe,window.cancelAnimationFrame(g(this,Lt)),f(this,Lt,0),this.player?.pause(),this.clearTaskInfo(),this.setProgress()}onError(t){gt("log",[..._e,"error"],t),this.onFinish(!1,g(this,se),g(this,re)),this.emit("error",t),this.dispose()}onFinish(t,e,i){gt("log",[..._e,"finish"],t?"success":"failed"),this.emit("progress",1),this.emit("finish",t,e,i)}async loadHelper(t){const e="WebP"===t&&!g(this,Ot),i=[ye.MP4,ye.APNG,ye.GIF,ye.AlphaMaskVideo].includes(t)&&!g(this,Nt);e&&f(this,Ot,await Bt()),i&&(f(this,Nt,await async function(t){const{multiThreading:e}=t??{},i=new At.FFmpeg,s=!!e,r={classWorkerURL:await(0,Et.toBlobURL)(kt.CLASSWORKER,"text/javascript"),coreURL:"",wasmURL:""};return s?(r.coreURL=await(0,Et.toBlobURL)(kt.MT.CORE,"text/javascript"),r.wasmURL=await(0,Et.toBlobURL)(kt.MT.WASM,"application/wasm"),r.workerURL=await(0,Et.toBlobURL)(kt.MT.WORKER,"text/javascript")):(r.coreURL=await(0,Et.toBlobURL)(kt.DEFAULT.CORE,"text/javascript"),r.wasmURL=await(0,Et.toBlobURL)(kt.DEFAULT.WASM,"application/wasm")),await i.load(r),i}({multiThreading:this.multiThreading})),g(this,Nt).on("log",({message:t})=>{if(this.loggerInTranscoding&>("log",[..._e,"transcoding log"],t),this.canceled||this.stage!==ve)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&&f(this,Zt,t.completedTaskPercentArray),void 0!==t?.currentTaskFrameIndex&&f(this,Qt,t.currentTaskFrameIndex),void 0!==t?.currentTaskTotalFrames&&f(this,te,t.currentTaskTotalFrames),void 0!==t?.currentTaskInTranscodingFrameIndex&&f(this,ie,t.currentTaskInTranscodingFrameIndex),void 0!==t?.allTaskFrames&&f(this,ee,t.allTaskFrames),this.emit("progress",this.progress)}forwardPlayerTime(t,e=!1){(0,w.assertExist)(this.player);const{oldTotalTime:i,startTime:s}=this.config;(0,w.assertExist)(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){f(this,Yt,new ke),g(this,Nt)?g(this,Nt).writeFile(t,g(this,Yt).getBuffer()):gt("log",[..._e,"getWavAudio"],"ffmpegCore is not ready")}async getImagesZip(t,e){const i=new de.default,s=i.folder(t);return(0,w.assertExist)(s),g(this,qt).forEach((t,i)=>{s.file(t,e[i])}),i.generateAsync({type:"arraybuffer"})}getWebP(){(0,w.assertExist)(g(this,Ot));const t=Math.round(1e3/this.config.fps/1),e="out.webp",i=`${g(this,qt).join(` -d ${t} `)} -d ${t} -o ${e} -loop ${this.config.loop?0:1}`.split(" "),s=g(this,Ot).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]}(g(this,Ot),i);dt(r&&a,"getWebP has error"),s(r,a);const n=g(this,Ot).FS.readFile(e);return g(this,qt).forEach(t=>{g(this,Ot)?.FS.unlink(t)}),n}async getAPNG(){(0,w.assertExist)(g(this,Nt));this.stage=ve;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 g(this,Nt).exec(["-framerate",`${this.config.fps}`,"-start_number","1","-i",`image-%4d.${this.transImageType}`,"-vf",r.join(","),"-plays",this.config.loop?"0":"1","-compression_level",Te[s],"-y",t]))throw new Error("the command executed by ffmpeg to generate a apng failed.");return t}async getGIF(){(0,w.assertExist)(g(this,Nt));this.stage=ve;const t="export.gif",{fps:e,scale:i="-1:-1",quality:s="highest"}=this.gifConfig??{},r=[`scale=${i}:${Ee[s]}`];e&&r.unshift(`fps=${e}`);if(0!==await g(this,Nt).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){(0,w.assertExist)(g(this,Nt));this.stage=ve;const i="export.mp4";let s;const r=e?",setpts=PTS/"+Math.round(t/e*100)/100:"",a=e??t;this.config.audioEnable&&!g(this,Yt)&&(f(this,$t,"audio.wav"),this.getWavAudio(g(this,$t)));if(0!==await g(this,Nt).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(g(this,$t)&&g(this,Yt)){this.stage=Ie,s="export-with-audio.mp4";if(0!==await g(this,Nt).exec(["-i",i,"-i",g(this,$t),"-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&&g(this,Nt).deleteFile(i).catch(()=>{gt("log",[..._e,"ffmpeg delete file error"])}),s??i}async getAlphaMaskVideo(t,e){(0,w.assertExist)(g(this,Nt));this.stage=ve;const i="export.mp4",s=e?",setpts=PTS/"+Math.round(t/e*100)/100:"";return await g(this,Nt).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){(0,w.assertExist)(g(this,Nt));const i=this.mediaType===ye.APNG,s=this.mediaType===ye.GIF,r=this.mediaType===ye.AlphaMaskVideo,a=this.mediaType===ye.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=xe}catch(t){throw t}finally{for(const t of g(this,qt))t&&g(this,Nt).deleteFile(t)}let o=null;try{(0,w.assertExist)(n);const t=await g(this,Nt).readFile(n);o="string"==typeof t?(new TextEncoder).encode(t):new Uint8Array(t)}finally{g(this,Nt).deleteFile(n).catch(()=>{gt("log",[..._e,"ffmpeg delete file error"])})}return o}onRecordWebM(t){const e=new MediaRecorder(t.captureStream(this.config.fps),{mimeType:"video/webm;codecs=vp9"});f(this,Kt,e),g(this,Kt).start(0);const i=[];g(this,Kt).ondataavailable=t=>{t.data.size>0&&i.push(t.data)},f(this,jt,i)}async onExportImageFrame(t){try{if(this.canceled)return;const{canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o}=t;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,Ht));const c=g(this,Qt)+1;this.stage=we,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:c}),this.loggerInTranscoding&>("log",[..._e,"converting log"],`converting ${c} frame image`),c>=1&&this.forwardPlayerTime(c/this.config.fps+a),_t(g(this,Ht),s,this.config.backgroundColor);let h=s;this.mediaType===ye.AlphaMaskVideo&&((0,w.assertExist)(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 l=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),p=`image-${e=c,i=4,String(e).padStart(i,"0")}.${this.transImageType}`;this.mediaType===ye.Images?r.push(l):this.mediaType===ye.WebP?((0,w.assertExist)(g(this,Ot)),g(this,Ot).FS.writeFile(p,new Uint8Array(l))):((0,w.assertExist)(g(this,Nt)),await g(this,Nt).writeFile(p,new Uint8Array(l))),g(this,qt).push(p);if(c===g(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():[ye.MP4,ye.APNG,ye.GIF,ye.AlphaMaskVideo].includes(this.mediaType)&&(t=await this.getVideoByType(n,o)??null),t&&(gt("log",[..._e,"done"],"success"),this.emit("done",g(this,Xt),!0,t))}else f(this,Lt,window.requestAnimationFrame(()=>{this.canceled||this.onExportImageFrame({canvas:s,imageBuffers:r,startTime:a,oldTotalTime:n,newTotalTime:o})}))}catch(t){gt("log",[..._e,"onExportImageFrame","failed"],t),this.emit("done",g(this,Xt),!1)}var e,i}async onExportWebMFrame(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,Ht));const e=g(this,Qt)+1;if(this.stage=we,this.setProgress({currentTaskInTranscodingFrameIndex:0,currentTaskFrameIndex:e}),this.loggerInTranscoding&>("log",[..._e,"converting log"],`converting ${e} frame image`),_t(g(this,Ht),t,this.config.backgroundColor),1===e&&(this.player.play(),this.onRecordWebM(t)),e<g(this,te))f(this,Lt,window.requestAnimationFrame(()=>{this.canceled||this.onExportWebMFrame(t)}));else{this.player?.pause(),g(this,Kt)?.stop();const t=new Blob(g(this,jt),{type:"video/webm"}),e=await t.arrayBuffer();gt("log",[..._e,"done"],"success"),this.emit("done",g(this,Xt),!0,e)}}catch(t){gt("log",[..._e,"done"],"failed",t),this.emit("done",g(this,Xt),!1)}}async runTask(t){try{if(this.canceled)return;(0,w.assertExist)(this.player),(0,w.assertExist)(g(this,Ht));const{size:e,startTime:i,containerCanvas:s}=t,{oldTotalTime:r,newTotalTime:a}=this.config,[n,o]=e;if(g(this,Ht).width=n,g(this,Ht).height=o,s.width=n,s.height=o,this.player.resize(),f(this,qt,[]),[ye.MP4,ye.APNG,ye.Images,ye.WebP,ye.GIF,ye.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){gt("log",[..._e,"run task error"],t),this.emit("done",g(this,Xt),!1)}}clearTaskInfo(){f(this,Jt,0),f(this,Xt,void 0),f(this,Zt,[]),f(this,Qt,0),f(this,te,0),f(this,ee,0),f(this,ie,0),f(this,se,[]),f(this,re,[]),f(this,ae,!0)}clearFFMpegCore(){if(g(this,Nt)){for(const t of g(this,qt))t&&g(this,Nt).deleteFile(t);f(this,qt,[]),g(this,Nt).terminate(),f(this,Nt,void 0)}}clearImage2WebPCore(){g(this,Ot)&&(g(this,Ot).FS.quit(),f(this,Ot,void 0))}clearMediaRecorder(){g(this,Kt)&&(g(this,Kt).stop(),f(this,Kt,void 0)),f(this,jt,[])}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,g(this,se),g(this,re)),this.status=fe,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),gt("log",_e,"canceled"))}async onExport(t){const e=t.length;try{if(this.status===ge)return gt("log",[..._e],"readying"),void this.on("ready",()=>{this.onExport(t)});if(this.status===fe){if(await this.onInit()===fe)throw new Error("init environment failed")}if(this.clearTaskInfo(),!g(this,Ht)){const t=document.createElement("canvas");t.dataset.key="player-canvas",f(this,Ht,t)}this.player||(this.player=new w.Player({canvas:g(this,Ht),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}f(this,Jt,a),f(this,Xt,n);const{size:t,scene:o}=n;await new Promise(async c=>{try{if(!this.player)throw new Error("player not found");gt("log",[..._e,"export"],"start",n),Mt(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){gt("log",[..._e,"export error"],t),r=!1,c()}})}f(this,se,i),f(this,re,s),f(this,ae,r)}catch(t){this.onError(t),f(this,ae,!1)}e>=1&&g(this,ae)?this.onFinish(!0,g(this,se),g(this,re)):this.onFinish(!1,g(this,se),g(this,re))}dispose(){this.status=fe,this.onReset(),this.clearMediaRecorder(),this.clearFFMpegCore(),this.clearImage2WebPCore(),this.clearAllListeners(),this.player?.dispose(),this.player=void 0,g(this,Ht)?.remove(),f(this,Ht,void 0),f(this,$t,void 0),f(this,Yt,void 0)}};Lt=new WeakMap,Ht=new WeakMap,Nt=new WeakMap,Ot=new WeakMap,Kt=new WeakMap,jt=new WeakMap,Yt=new WeakMap,$t=new WeakMap,qt=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,te=new WeakMap,ee=new WeakMap,ie=new WeakMap,se=new WeakMap,re=new WeakMap,ae=new WeakMap;var Me={[ye.MP4]:{suffix:"mp4",error:"export mp4 is error"},[ye.GIF]:{suffix:"gif",error:"export gif is error"},[ye.Images]:{suffix:"zip",error:"export Images is error"},[ye.APNG]:{suffix:"apng",error:"export APNG is error"},[ye.WebP]:{suffix:"webp",error:"export WebP is error"},[ye.AlphaMaskVideo]:{suffix:"mp4",error:"export AlphaMaskVideo is error"},[ye.WebM]:{suffix:"webm",error:"export WebM is error"}},Ve=class extends w.EventEmitter{constructor(t){super(),m(this,"_config"),m(this,"_status",be),m(this,"_exportMedia"),this._config=t,this._exportMedia=new Be(t)}get status(){return this._status}onExportMedia(t,e,i,s){if(!e.length||!i)return void gt("info",["@vvfx/sdk","export media is error","result or suffix is empty"]);const r=t[0]?.folderName,a=new me.default;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=>{gt("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=Ae,gt("error",["@vvfx/sdk"],"export is error",t)}onExport(t){this._status=ze,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?Se:Ae,this.emit("complete",e,i,s),this._config.isOutputBuffer||!s||0===s.length)return;const{suffix:r,error:a}=Me[this._config.mediaType];r&&this.onExportMedia(t,s,r,a)}),this._exportMedia.on("error",this.onExportError.bind(this))}onCancel(){this._status=Ae,this._exportMedia.onCancel(),this.emit("complete",!1,[],[])}dispose(){this._exportMedia.dispose()}},Ge=class{constructor(){m(this,"enabled",!0),m(this,"_player"),m(this,"_container"),this._container=document.createElement("canvas"),this._player=new w.Player({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.");Mt(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 Mt(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?b(n,0,1):.5,o="number"==typeof o?b(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)}},Ue={topAdsorption:"T",leftAdsorption:"L",rightAdsorption:"R",bottomAdsorption:"B",centerAdsorption:"C",bottomCenterAdsorption:"BC"},Fe=class{constructor(t){m(this,"_player"),m(this,"_container"),m(this,"size",[0,0]),m(this,"_pageDataUtils"),this._container=document.createElement("canvas"),this._player=new w.Player({canvas:this._container,manualRender:!0}),this._pageDataUtils=t}async adjustment(t,e,i,s,r,a){if(!Le.config.sizeAdaptConfig.enabled)return console.warn("Size adapt is not opened, use #SDK.setConfig() open this feature."),t;this._player??(this._player=new w.Player({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],Mt(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 V).setFromCenterAndSize(new B(e,n).divide(2),new B(e,n)),x=(new V).setFromCenterAndSize(new B(e,n).divide(2).add(new B(...f)),new B(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 R).copyFrom(e.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(i).toVector2()).toViewCoordinate(s[0],s[1])};["topAdsorption","centerAdsorption","bottomAdsorption"].forEach(a=>{e.items.filter(t=>t.name.split("-")[0]?.toLocaleUpperCase()===Ue[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 B(...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 R).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(o,c)},p=Ue[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 B,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 B;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 D=c?this.getViewBoxByHeadlessPlayerItem(c,[],l):this.getViewBoxByHeadlessPlayerItem(r,o,l),b=i.items.filter(t=>"T"===t.name.split("-")[0]?.toLocaleUpperCase()&&!t.parentId),z=new V;if(b.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>D.min.y)if("centerAdsorption"===t){const t=z.max.y-D.min.y;h(r,0,t),r.transform.updateLocalMatrix()}else if(["leftAdsorption","rightAdsorption"].includes(t)){const t=D.getSize().y,e=a.getSize().y-(z.max.y-a.min.y);let i=z.max.y-D.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 R).copyFrom(i.camera.getViewProjectionMatrix());return(new B).copyFrom(t.applyMatrix(e).toVector2()).toViewCoordinate(n,o)},l=Ue[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 B;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 V,{transform:r,composition:a}=t;switch(t.type){case w.spec.ItemType.sprite:case w.spec.ItemType.plugin:case w.spec.ItemType.video:case w.spec.ItemType.richtext:case w.spec.ItemType.text:case w.spec.ItemType.shape:{r.setValid(!0),r.updateLocalMatrix();const{size:t}=r,n=(new R).copyFrom(a?.transform.getWorldMatrix()??new R).invert().multiply(r.getWorldMatrix()),{x:o,y:c}=t.clone().divide(2),h=new F(o,c,0).applyMatrix(n),l=new F(o,-c,0).applyMatrix(n),p=new F(-o,-c,0).applyMatrix(n),m=new F(-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 w.spec.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()}},Re=class{constructor(){m(this,"index",0),m(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=[]}},We=class t{constructor(e){m(this,"_eventEmitter",new w.EventEmitter),m(this,"_pageData"),m(this,"_screenShot"),m(this,"_exporter"),m(this,"_pageDataUtils"),m(this,"_sizeAdapt"),m(this,"_gestureHandler"),m(this,"disposables",[]),m(this,"_isSwitchScene",!1),m(this,"_canvasUndoRedo",new Re),m(this,"player"),m(this,"_container"),m(this,"_playerContainer"),m(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 w.Player({container:r,interactive:!0,pixelRatio:window.devicePixelRatio||1}),this.player.on("update",()=>{if((0,w.assertExist)(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=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems=[...t],this._gestureHandler.render()}),this._eventEmitter.on("preSelectedItemChange",t=>{(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t,this._gestureHandler.render()}),this._eventEmitter.on("selectedViewChange",t=>{(0,w.assertExist)(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 pe(this.player,r,this._eventEmitter,this),this.initExporter(t.config.exportConfig),this._gestureHandler=new bt(e),this._screenShot=new Ge,this._sizeAdapt=new Fe(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:Vt(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&&!ut(t,e)&&(this._exporter.dispose(),this.initExporter(e))}initExporter(t){this._exporter=new Ve(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];(0,w.assertExist)(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(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.selectedItems}setPreSelectedItem(t){(0,w.assertExist)(this._pageData,"You must call SDK#run() first"),this._pageData.activeData.preSelectedItem=t}getPreSelectedItem(){return(0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(this._pageData,"You must call SDK#run() first");const e=this.getItemProperty(t)?.property?.[t.propertyName];return e}async setItemPropertyValue(t){(0,w.assertExist)(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){(0,w.assertExist)(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((0,w.assertExist)(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(0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(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&&(Mt(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){(0,w.assertExist)(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(0,w.assertExist)(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(0,w.assertExist)(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&&((0,w.assertExist)(this.pageData,"You must call SDK#run() first"),(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onExport(this.exportOptions))}cancelExport(){(0,w.assertExist)(this._exporter,"You must init exporter first"),this._exporter.onCancel()}async loadPageData(t){(0,w.assertExist)(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){(0,w.assertExist)(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;(0,w.assertExist)(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];(0,w.assertExist)(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];(0,w.assertExist)(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){(0,w.assertExist)(this._pageData),this._pageData.viewProperties.forEach(i=>{void 0!==e&&i.id!==e||Object.assign(i.export,t)})}setPageZoom(t){(0,w.assertExist)(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?j(t.config.pageConfig.filterItemNames,e):e.forEach(e=>{j(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((0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(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){(0,w.assertExist)(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 B(...t))}pageZoom(t,e){this._pageDataUtils.pageZoom(t,e?new B(...e):void 0)}setPictureCutGizmoLockScale(t){this._gestureHandler.setPictureCutGizmoLockScale(t)}setPictureExpandGizmoLockScale(t){this._gestureHandler.setPictureExpandGizmoLockScale(t)}viewportFit(){this._pageDataUtils.viewportFit()}};m(We,"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 Le=We;
|