@hatiolab/things-scene 10.0.0-beta.30 → 10.0.0-beta.32

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.
@@ -1,6 +1,6 @@
1
1
  !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("dompurify"),require("three"),require("three/examples/jsm/lines/Line2.js"),require("three/examples/jsm/lines/LineMaterial.js"),require("three/examples/jsm/lines/LineGeometry.js"),require("three/examples/jsm/renderers/CSS3DRenderer.js"),require("tinycolor2"),require("three/examples/jsm/postprocessing/EffectComposer.js"),require("three/examples/jsm/postprocessing/RenderPass.js"),require("three/examples/jsm/postprocessing/OutlinePass.js"),require("three/examples/jsm/postprocessing/OutputPass.js"),require("three/examples/jsm/postprocessing/SMAAPass.js"),require("three/examples/jsm/controls/TransformControls.js"),require("three/examples/jsm/loaders/GLTFLoader.js"),require("three/examples/jsm/loaders/DRACOLoader.js"),require("three/examples/jsm/loaders/KTX2Loader.js"),require("three/examples/jsm/libs/meshopt_decoder.module.js"),require("three/examples/jsm/geometries/RoundedBoxGeometry.js")):"function"==typeof define&&define.amd?define(["exports","dompurify","three","three/examples/jsm/lines/Line2.js","three/examples/jsm/lines/LineMaterial.js","three/examples/jsm/lines/LineGeometry.js","three/examples/jsm/renderers/CSS3DRenderer.js","tinycolor2","three/examples/jsm/postprocessing/EffectComposer.js","three/examples/jsm/postprocessing/RenderPass.js","three/examples/jsm/postprocessing/OutlinePass.js","three/examples/jsm/postprocessing/OutputPass.js","three/examples/jsm/postprocessing/SMAAPass.js","three/examples/jsm/controls/TransformControls.js","three/examples/jsm/loaders/GLTFLoader.js","three/examples/jsm/loaders/DRACOLoader.js","three/examples/jsm/loaders/KTX2Loader.js","three/examples/jsm/libs/meshopt_decoder.module.js","three/examples/jsm/geometries/RoundedBoxGeometry.js"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).scene={},t.DOMPurify,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.tinycolor,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE,t.THREE)}(this,function(t,e,n,r,i,s,o,a,c,l,h,d,u,p,f,g,m,y,b){"use strict";function v(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}),e.default=t,Object.freeze(e)}var _=v(n);function x(t,e){return t===e||t!=t&&e!=e}function w(t,e){for(var n=t.length;n--;)if(x(t[n][0],e))return n;return-1}var M=Array.prototype.splice;function S(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}S.prototype.clear=function(){this.__data__=[],this.size=0},S.prototype.delete=function(t){var e=this.__data__,n=w(e,t);return!(n<0)&&(n==e.length-1?e.pop():M.call(e,n,1),--this.size,!0)},S.prototype.get=function(t){var e=this.__data__,n=w(e,t);return n<0?void 0:e[n][1]},S.prototype.has=function(t){return w(this.__data__,t)>-1},S.prototype.set=function(t,e){var n=this.__data__,r=w(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this};var A="object"==typeof global&&global&&global.Object===Object&&global,E="object"==typeof self&&self&&self.Object===Object&&self,k=A||E||Function("return this")(),C=k.Symbol,P=Object.prototype,T=P.hasOwnProperty,D=P.toString,O=C?C.toStringTag:void 0;var z=Object.prototype.toString;var I=C?C.toStringTag:void 0;function L(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":I&&I in Object(t)?function(t){var e=T.call(t,O),n=t[O];try{t[O]=void 0;var r=!0}catch(t){}var i=D.call(t);return r&&(e?t[O]=n:delete t[O]),i}(t):function(t){return z.call(t)}(t)}function j(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function R(t){if(!j(t))return!1;var e=L(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var F,B=k["__core-js_shared__"],N=(F=/[^.]+$/.exec(B&&B.keys&&B.keys.IE_PROTO||""))?"Symbol(src)_1."+F:"";var H=Function.prototype.toString;function V(t){if(null!=t){try{return H.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var G=/^\[object .+?Constructor\]$/,Y=Function.prototype,U=Object.prototype,$=Y.toString,W=U.hasOwnProperty,X=RegExp("^"+$.call(W).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function q(t){return!(!j(t)||(e=t,N&&N in e))&&(R(t)?X:G).test(V(t));var e}function K(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return q(n)?n:void 0}var Q=K(k,"Map"),Z=K(Object,"create");var J=Object.prototype.hasOwnProperty;var tt=Object.prototype.hasOwnProperty;function et(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function nt(t,e){var n=t.__data__;return function(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}(e)?n["string"==typeof e?"string":"hash"]:n.map}function rt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}et.prototype.clear=function(){this.__data__=Z?Z(null):{},this.size=0},et.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},et.prototype.get=function(t){var e=this.__data__;if(Z){var n=e[t];return"__lodash_hash_undefined__"===n?void 0:n}return J.call(e,t)?e[t]:void 0},et.prototype.has=function(t){var e=this.__data__;return Z?void 0!==e[t]:tt.call(e,t)},et.prototype.set=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=Z&&void 0===e?"__lodash_hash_undefined__":e,this},rt.prototype.clear=function(){this.size=0,this.__data__={hash:new et,map:new(Q||S),string:new et}},rt.prototype.delete=function(t){var e=nt(this,t).delete(t);return this.size-=e?1:0,e},rt.prototype.get=function(t){return nt(this,t).get(t)},rt.prototype.has=function(t){return nt(this,t).has(t)},rt.prototype.set=function(t,e){var n=nt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this};function it(t){var e=this.__data__=new S(t);this.size=e.size}it.prototype.clear=function(){this.__data__=new S,this.size=0},it.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},it.prototype.get=function(t){return this.__data__.get(t)},it.prototype.has=function(t){return this.__data__.has(t)},it.prototype.set=function(t,e){var n=this.__data__;if(n instanceof S){var r=n.__data__;if(!Q||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new rt(r)}return n.set(t,e),this.size=n.size,this};function st(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new rt;++e<n;)this.add(t[e])}function ot(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}st.prototype.add=st.prototype.push=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this},st.prototype.has=function(t){return this.__data__.has(t)};function at(t,e,n,r,i,s){var o=1&n,a=t.length,c=e.length;if(a!=c&&!(o&&c>a))return!1;var l=s.get(t),h=s.get(e);if(l&&h)return l==e&&h==t;var d=-1,u=!0,p=2&n?new st:void 0;for(s.set(t,e),s.set(e,t);++d<a;){var f=t[d],g=e[d];if(r)var m=o?r(g,f,d,e,t,s):r(f,g,d,t,e,s);if(void 0!==m){if(m)continue;u=!1;break}if(p){if(!ot(e,function(t,e){if(o=e,!p.has(o)&&(f===t||i(f,t,n,r,s)))return p.push(e);var o})){u=!1;break}}else if(f!==g&&!i(f,g,n,r,s)){u=!1;break}}return s.delete(t),s.delete(e),u}var ct=k.Uint8Array;function lt(t){var e=-1,n=Array(t.size);return t.forEach(function(t,r){n[++e]=[r,t]}),n}function ht(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=t}),n}var dt=C?C.prototype:void 0,ut=dt?dt.valueOf:void 0;function pt(t,e){for(var n=-1,r=e.length,i=t.length;++n<r;)t[i+n]=e[n];return t}var ft=Array.isArray;function gt(){return[]}var mt=Object.prototype.propertyIsEnumerable,yt=Object.getOwnPropertySymbols,bt=yt?function(t){return null==t?[]:(t=Object(t),function(t,e){for(var n=-1,r=null==t?0:t.length,i=0,s=[];++n<r;){var o=t[n];e(o,n,t)&&(s[i++]=o)}return s}(yt(t),function(e){return mt.call(t,e)}))}:gt;function vt(t){return null!=t&&"object"==typeof t}function _t(t){return vt(t)&&"[object Arguments]"==L(t)}var xt=Object.prototype,wt=xt.hasOwnProperty,Mt=xt.propertyIsEnumerable,St=_t(function(){return arguments}())?_t:function(t){return vt(t)&&wt.call(t,"callee")&&!Mt.call(t,"callee")};var At="object"==typeof t&&t&&!t.nodeType&&t,Et=At&&"object"==typeof module&&module&&!module.nodeType&&module,kt=Et&&Et.exports===At?k.Buffer:void 0,Ct=(kt?kt.isBuffer:void 0)||function(){return!1},Pt=/^(?:0|[1-9]\d*)$/;function Tt(t,e){var n=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==n||"symbol"!=n&&Pt.test(t))&&t>-1&&t%1==0&&t<e}function Dt(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}var Ot={};function zt(t){return function(e){return t(e)}}Ot["[object Float32Array]"]=Ot["[object Float64Array]"]=Ot["[object Int8Array]"]=Ot["[object Int16Array]"]=Ot["[object Int32Array]"]=Ot["[object Uint8Array]"]=Ot["[object Uint8ClampedArray]"]=Ot["[object Uint16Array]"]=Ot["[object Uint32Array]"]=!0,Ot["[object Arguments]"]=Ot["[object Array]"]=Ot["[object ArrayBuffer]"]=Ot["[object Boolean]"]=Ot["[object DataView]"]=Ot["[object Date]"]=Ot["[object Error]"]=Ot["[object Function]"]=Ot["[object Map]"]=Ot["[object Number]"]=Ot["[object Object]"]=Ot["[object RegExp]"]=Ot["[object Set]"]=Ot["[object String]"]=Ot["[object WeakMap]"]=!1;var It="object"==typeof t&&t&&!t.nodeType&&t,Lt=It&&"object"==typeof module&&module&&!module.nodeType&&module,jt=Lt&&Lt.exports===It&&A.process,Rt=function(){try{var t=Lt&&Lt.require&&Lt.require("util").types;return t||jt&&jt.binding&&jt.binding("util")}catch(t){}}(),Ft=Rt&&Rt.isTypedArray,Bt=Ft?zt(Ft):function(t){return vt(t)&&Dt(t.length)&&!!Ot[L(t)]},Nt=Object.prototype.hasOwnProperty;function Ht(t,e){var n=ft(t),r=!n&&St(t),i=!n&&!r&&Ct(t),s=!n&&!r&&!i&&Bt(t),o=n||r||i||s,a=o?function(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}(t.length,String):[],c=a.length;for(var l in t)!e&&!Nt.call(t,l)||o&&("length"==l||i&&("offset"==l||"parent"==l)||s&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||Tt(l,c))||a.push(l);return a}var Vt=Object.prototype;function Gt(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||Vt)}function Yt(t,e){return function(n){return t(e(n))}}var Ut=Yt(Object.keys,Object),$t=Object.prototype.hasOwnProperty;function Wt(t){if(!Gt(t))return Ut(t);var e=[];for(var n in Object(t))$t.call(t,n)&&"constructor"!=n&&e.push(n);return e}function Xt(t){return null!=t&&Dt(t.length)&&!R(t)}function qt(t){return Xt(t)?Ht(t):Wt(t)}function Kt(t){return function(t,e,n){var r=e(t);return ft(t)?r:pt(r,n(t))}(t,qt,bt)}var Qt=Object.prototype.hasOwnProperty;var Zt=K(k,"DataView"),Jt=K(k,"Promise"),te=K(k,"Set"),ee=K(k,"WeakMap"),ne="[object Map]",re="[object Promise]",ie="[object Set]",se="[object WeakMap]",oe="[object DataView]",ae=V(Zt),ce=V(Q),le=V(Jt),he=V(te),de=V(ee),ue=L;(Zt&&ue(new Zt(new ArrayBuffer(1)))!=oe||Q&&ue(new Q)!=ne||Jt&&ue(Jt.resolve())!=re||te&&ue(new te)!=ie||ee&&ue(new ee)!=se)&&(ue=function(t){var e=L(t),n="[object Object]"==e?t.constructor:void 0,r=n?V(n):"";if(r)switch(r){case ae:return oe;case ce:return ne;case le:return re;case he:return ie;case de:return se}return e});var pe="[object Arguments]",fe="[object Array]",ge="[object Object]",me=Object.prototype.hasOwnProperty;function ye(t,e,n,r,i,s){var o=ft(t),a=ft(e),c=o?fe:ue(t),l=a?fe:ue(e),h=(c=c==pe?ge:c)==ge,d=(l=l==pe?ge:l)==ge,u=c==l;if(u&&Ct(t)){if(!Ct(e))return!1;o=!0,h=!1}if(u&&!h)return s||(s=new it),o||Bt(t)?at(t,e,n,r,i,s):function(t,e,n,r,i,s,o){switch(n){case"[object DataView]":if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case"[object ArrayBuffer]":return!(t.byteLength!=e.byteLength||!s(new ct(t),new ct(e)));case"[object Boolean]":case"[object Date]":case"[object Number]":return x(+t,+e);case"[object Error]":return t.name==e.name&&t.message==e.message;case"[object RegExp]":case"[object String]":return t==e+"";case"[object Map]":var a=lt;case"[object Set]":var c=1&r;if(a||(a=ht),t.size!=e.size&&!c)return!1;var l=o.get(t);if(l)return l==e;r|=2,o.set(t,e);var h=at(a(t),a(e),r,i,s,o);return o.delete(t),h;case"[object Symbol]":if(ut)return ut.call(t)==ut.call(e)}return!1}(t,e,c,n,r,i,s);if(!(1&n)){var p=h&&me.call(t,"__wrapped__"),f=d&&me.call(e,"__wrapped__");if(p||f){var g=p?t.value():t,m=f?e.value():e;return s||(s=new it),i(g,m,n,r,s)}}return!!u&&(s||(s=new it),function(t,e,n,r,i,s){var o=1&n,a=Kt(t),c=a.length;if(c!=Kt(e).length&&!o)return!1;for(var l=c;l--;){var h=a[l];if(!(o?h in e:Qt.call(e,h)))return!1}var d=s.get(t),u=s.get(e);if(d&&u)return d==e&&u==t;var p=!0;s.set(t,e),s.set(e,t);for(var f=o;++l<c;){var g=t[h=a[l]],m=e[h];if(r)var y=o?r(m,g,h,e,t,s):r(g,m,h,t,e,s);if(!(void 0===y?g===m||i(g,m,n,r,s):y)){p=!1;break}f||(f="constructor"==h)}if(p&&!f){var b=t.constructor,v=e.constructor;b==v||!("constructor"in t)||!("constructor"in e)||"function"==typeof b&&b instanceof b&&"function"==typeof v&&v instanceof v||(p=!1)}return s.delete(t),s.delete(e),p}(t,e,n,r,i,s))}function be(t,e,n,r,i){return t===e||(null==t||null==e||!vt(t)&&!vt(e)?t!=t&&e!=e:ye(t,e,n,r,be,i))}var ve=function(){try{var t=K(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();function _e(t,e,n){"__proto__"==e&&ve?ve(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}var xe=Object.prototype.hasOwnProperty;function we(t,e,n){var r=t[e];xe.call(t,e)&&x(r,n)&&(void 0!==n||e in t)||_e(t,e,n)}function Me(t,e,n,r){var i=!n;n||(n={});for(var s=-1,o=e.length;++s<o;){var a=e[s],c=r?r(n[a],t[a],a,n,t):void 0;void 0===c&&(c=t[a]),i?_e(n,a,c):we(n,a,c)}return n}function Se(t){return t}function Ae(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}var Ee=Math.max;function ke(t){return function(){return t}}var Ce=ve?function(t,e){return ve(t,"toString",{configurable:!0,enumerable:!1,value:ke(e),writable:!0})}:Se,Pe=Date.now;var Te=function(t){var e=0,n=0;return function(){var r=Pe(),i=16-(r-n);if(n=r,i>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Ce);function De(t,e){return Te(function(t,e,n){return e=Ee(void 0===e?t.length-1:e,0),function(){for(var r=arguments,i=-1,s=Ee(r.length-e,0),o=Array(s);++i<s;)o[i]=r[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=r[i];return a[e]=n(o),Ae(t,this,a)}}(t,e,Se),t+"")}function Oe(t,e,n){if(!j(n))return!1;var r=typeof e;return!!("number"==r?Xt(n)&&Tt(e,n.length):"string"==r&&e in n)&&x(n[e],t)}var ze=Object.prototype.hasOwnProperty;function Ie(t){if(!j(t))return function(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e}(t);var e=Gt(t),n=[];for(var r in t)("constructor"!=r||!e&&ze.call(t,r))&&n.push(r);return n}function Le(t){return Xt(t)?Ht(t,!0):Ie(t)}var je,Re=(je=function(t,e,n,r){Me(e,Le(e),t,r)},De(function(t,e){var n=-1,r=e.length,i=r>1?e[r-1]:void 0,s=r>2?e[2]:void 0;for(i=je.length>3&&"function"==typeof i?(r--,i):void 0,s&&Oe(e[0],e[1],s)&&(i=r<3?void 0:i,r=1),t=Object(t);++n<r;){var o=e[n];o&&je(t,o,n,i)}return t})),Fe=Yt(Object.getPrototypeOf,Object),Be=Function.prototype,Ne=Object.prototype,He=Be.toString,Ve=Ne.hasOwnProperty,Ge=He.call(Object);function Ye(t){if(!vt(t))return!1;var e=L(t);return"[object Error]"==e||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!function(t){if(!vt(t)||"[object Object]"!=L(t))return!1;var e=Fe(t);if(null===e)return!0;var n=Ve.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&He.call(n)==Ge}(t)}var Ue=De(function(t,e){try{return Ae(t,void 0,e)}catch(t){return Ye(t)?t:new Error(t)}});function $e(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}var We=Object.prototype,Xe=We.hasOwnProperty;function qe(t,e,n,r){return void 0===t||x(t,We[n])&&!Xe.call(r,n)?e:t}var Ke={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"};function Qe(t){return"\\"+Ke[t]}var Ze=/<%=([\s\S]+?)%>/g;var Je,tn=(Je={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},function(t){return null==Je?void 0:Je[t]});function en(t){return"symbol"==typeof t||vt(t)&&"[object Symbol]"==L(t)}var nn=C?C.prototype:void 0,rn=nn?nn.toString:void 0;function sn(t){if("string"==typeof t)return t;if(ft(t))return $e(t,sn)+"";if(en(t))return rn?rn.call(t):"";var e=t+"";return"0"==e&&1/t==-1/0?"-0":e}function on(t){return null==t?"":sn(t)}var an=/[&<>"']/g,cn=RegExp(an.source);var ln={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:Ze,variable:"",imports:{_:{escape:function(t){return(t=on(t))&&cn.test(t)?t.replace(an,tn):t}}}},hn=/\b__p \+= '';/g,dn=/\b(__p \+=) '' \+/g,un=/(__e\(.*?\)|\b__t\)) \+\n'';/g,pn=/[()=,{}\[\]\/\s]/,fn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,gn=/($^)/,mn=/['\n\r\u2028\u2029\\]/g,yn=Object.prototype.hasOwnProperty;var bn="object"==typeof t&&t&&!t.nodeType&&t,vn=bn&&"object"==typeof module&&module&&!module.nodeType&&module,_n=vn&&vn.exports===bn?k.Buffer:void 0,xn=_n?_n.allocUnsafe:void 0;var wn=Object.getOwnPropertySymbols?function(t){for(var e=[];t;)pt(e,bt(t)),t=Fe(t);return e}:gt;var Mn=Object.prototype.hasOwnProperty;var Sn=/\w*$/;var An=C?C.prototype:void 0,En=An?An.valueOf:void 0;function kn(t,e,n){var r,i,s,o,a,c=t.constructor;switch(e){case"[object ArrayBuffer]":return a=new(o=t).constructor(o.byteLength),new ct(a).set(new ct(o)),a;case"[object Boolean]":case"[object Date]":return new c(+t);case"[object DataView]":return s=(i=t).buffer,new i.constructor(s,i.byteOffset,i.byteLength);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return function(t){var e=t.buffer;return new t.constructor(e,t.byteOffset,t.length)}(t);case"[object Map]":case"[object Set]":return new c;case"[object Number]":case"[object String]":return new c(t);case"[object RegExp]":return function(t){var e=new t.constructor(t.source,Sn.exec(t));return e.lastIndex=t.lastIndex,e}(t);case"[object Symbol]":return r=t,En?Object(En.call(r)):{}}}var Cn=Object.create,Pn=function(){function t(){}return function(e){if(!j(e))return{};if(Cn)return Cn(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();var Tn=Rt&&Rt.isMap,Dn=Tn?zt(Tn):function(t){return vt(t)&&"[object Map]"==ue(t)};var On=Rt&&Rt.isSet,zn=On?zt(On):function(t){return vt(t)&&"[object Set]"==ue(t)},In="[object Arguments]",Ln="[object Function]",jn="[object Object]",Rn={};function Fn(t,e,n,r,i,s){var o,a=2&e;if(void 0!==o)return o;if(!j(t))return t;var c=ft(t);if(c)return o=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&Mn.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n<r;)e[n]=t[n];return e}(t,o);var l=ue(t),h=l==Ln||"[object GeneratorFunction]"==l;if(Ct(t))return function(t){var e=t.length,n=xn?xn(e):new t.constructor(e);return t.copy(n),n}(t);if(l==jn||l==In||h&&!i)return o=h?{}:function(t){return"function"!=typeof t.constructor||Gt(t)?{}:Pn(Fe(t))}(t),a?function(t,e){return Me(t,wn(t),e)}(t,function(t,e){return t&&Me(e,Le(e),t)}(o,t)):function(t,e){return Me(t,bt(t),e)}(t,function(t,e){return t&&Me(e,qt(e),t)}(o,t));if(!Rn[l])return i?t:{};o=kn(t,l),s||(s=new it);var d=s.get(t);if(d)return d;s.set(t,o),zn(t)?t.forEach(function(r){o.add(Fn(r,e,n,r,t,s))}):Dn(t)&&t.forEach(function(r,i){o.set(i,Fn(r,e,n,i,t,s))});var u=c?void 0:Kt(t);return function(t,e){for(var n=-1,r=null==t?0:t.length;++n<r&&!1!==e(t[n],n,t););}(u||t,function(r,i){u&&(r=t[i=r]),we(o,i,Fn(r,e,n,i,t,s))}),o}Rn[In]=Rn["[object Array]"]=Rn["[object ArrayBuffer]"]=Rn["[object DataView]"]=Rn["[object Boolean]"]=Rn["[object Date]"]=Rn["[object Float32Array]"]=Rn["[object Float64Array]"]=Rn["[object Int8Array]"]=Rn["[object Int16Array]"]=Rn["[object Int32Array]"]=Rn["[object Map]"]=Rn["[object Number]"]=Rn[jn]=Rn["[object RegExp]"]=Rn["[object Set]"]=Rn["[object String]"]=Rn["[object Symbol]"]=Rn["[object Uint8Array]"]=Rn["[object Uint8ClampedArray]"]=Rn["[object Uint16Array]"]=Rn["[object Uint32Array]"]=!0,Rn["[object Error]"]=Rn[Ln]=Rn["[object WeakMap]"]=!1;function Bn(t){return Fn(t,4)}var Nn=function(){return k.Date.now()},Hn=/\s/;var Vn=/^\s+/;function Gn(t){return t?t.slice(0,function(t){for(var e=t.length;e--&&Hn.test(t.charAt(e)););return e}(t)+1).replace(Vn,""):t}var Yn=/^[-+]0x[0-9a-f]+$/i,Un=/^0b[01]+$/i,$n=/^0o[0-7]+$/i,Wn=parseInt;function Xn(t){if("number"==typeof t)return t;if(en(t))return NaN;if(j(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=j(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=Gn(t);var n=Un.test(t);return n||$n.test(t)?Wn(t.slice(2),n?2:8):Yn.test(t)?NaN:+t}var qn=Math.max,Kn=Math.min;function Qn(t,e,n){var r,i,s,o,a,c,l=0,h=!1,d=!1,u=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function p(e){var n=r,s=i;return r=i=void 0,l=e,o=t.apply(s,n)}function f(t){var n=t-c;return void 0===c||n>=e||n<0||d&&t-l>=s}function g(){var t=Nn();if(f(t))return m(t);a=setTimeout(g,function(t){var n=e-(t-c);return d?Kn(n,s-(t-l)):n}(t))}function m(t){return a=void 0,u&&r?p(t):(r=i=void 0,o)}function y(){var t=Nn(),n=f(t);if(r=arguments,i=this,c=t,n){if(void 0===a)return function(t){return l=t,a=setTimeout(g,e),h?p(t):o}(c);if(d)return clearTimeout(a),a=setTimeout(g,e),p(c)}return void 0===a&&(a=setTimeout(g,e)),o}return e=Xn(e)||0,j(n)&&(h=!!n.leading,s=(d="maxWait"in n)?qn(Xn(n.maxWait)||0,e):s,u="trailing"in n?!!n.trailing:u),y.cancel=function(){void 0!==a&&clearTimeout(a),l=0,r=c=i=a=void 0},y.flush=function(){return void 0===a?o:m(Nn())},y}function Zn(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return j(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),Qn(t,e,{leading:r,maxWait:e,trailing:i})}var Jn=1/0;function tr(t){var e=function(t){return t?(t=Xn(t))===Jn||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}(t),n=e%1;return e==e?n?e-n:e:0}function er(t){return function(t,e){var n;if("function"!=typeof e)throw new TypeError("Expected a function");return t=tr(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=void 0),n}}(2,t)}var nr=Object.prototype.hasOwnProperty;function rr(t){if(null==t)return!0;if(Xt(t)&&(ft(t)||"string"==typeof t||"function"==typeof t.splice||Ct(t)||Bt(t)||St(t)))return!t.length;var e=ue(t);if("[object Map]"==e||"[object Set]"==e)return!t.size;if(Gt(t))return!Wt(t).length;for(var n in t)if(nr.call(t,n))return!1;return!0}let ir=0;function sr(t={},...e){return"object"!=typeof t&&(t={}),e.forEach(e=>{for(const n in e)"object"!=typeof e[n]?t[n]=e[n]:e[n].length>0?t[n]=e[n].map(t=>{let r;return r="object"!=typeof e[n]?t:sr({},t),r}):t[n]=sr(t[n],e[n])}),t}function or(t){for(;t&&"object"==typeof t;){const e=t;for(const e in t){t=t[e];break}if(t===e){t=void 0;break}}return t}function ar(t,e){if(!this.__collection__)return this;return-1==this.__collection__.indexOf(e)&&this.__collection__.splice(t,0,e),this}function cr(t){return this.__collection__||(this.__collection__=[]),-1==this.__collection__.indexOf(t)&&this.__collection__.push(t),this}function lr(t){return this.__collection__||(this.__collection__=[]),-1==this.__collection__.indexOf(t)&&this.__collection__.unshift(t),this}function hr(t){if(!this.__collection__)return this;const e=this.__collection__.indexOf(t);return e>=0&&this.__collection__.splice(e,1),this}function dr(t){if(this.__collection__)return this.__collection__[t]}function ur(t,e){this.__collection__&&this.__collection__.forEach(t,e)}function pr(t){return this.__collection__?this.__collection__.indexOf(t):-1}function fr(){return this.__collection__?this.__collection__.length:0}function gr(){this.__collection__=[]}function mr(t){const e=this.indexOf(t);-1!=e&&0!=e&&(this.__collection__[e]=this.__collection__[e-1],this.__collection__[e-1]=t)}function yr(t){const e=this.indexOf(t);-1!=e&&e!=this.size()-1&&(this.__collection__[e]=this.__collection__[e+1],this.__collection__[e+1]=t)}function br(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this.__collection__.splice(0,e),r=this.__collection__.splice(1);this.__collection__=this.__collection__.concat(n,r)}function vr(t){const e=this.indexOf(t);if(-1==e||e==this.size()-1)return;const n=this.__collection__.splice(0,e),r=this.__collection__.splice(1);this.__collection__=n.concat(r,this.__collection__)}class _r{constructor(){this.__collection__=[],this.insertAt=ar,this.append=cr,this.prepend=lr,this.remove=hr,this.getAt=dr,this.forEach=ur,this.indexOf=pr,this.size=fr,this.clear=gr,this.moveForward=mr,this.moveBackward=yr,this.moveToHead=br,this.moveToTail=vr}}const xr=new class{constructor(){this.drawCount=0,this.drawTimeSum=0,this.drawTimeLast=0,this.invalidateCount=0,this.triggerCount=0,this.cacheHit=0,this.cacheMiss=0,this._lastSnapshotTime=0,this._frameCount=0,this._getResidents=null}registerResidents(t){this._getResidents=t}countFrame(){this._frameCount++}snapshot(){const t=performance.now(),e=this.drawCount,n=this.cacheHit+this.cacheMiss,r=this._getResidents?.()??null;let i=0;if(this._lastSnapshotTime>0){const e=t-this._lastSnapshotTime;e>0&&(i=Math.round(1e3*this._frameCount/e))}this._lastSnapshotTime=t,this._frameCount=0;const s={fps:i,drawCount:e,drawTimeAvg:e>0?Math.round(this.drawTimeSum/e*100)/100:0,drawTimeLast:Math.round(100*this.drawTimeLast)/100,invalidateCount:this.invalidateCount,triggerCount:this.triggerCount,cacheHitRate:n>0?Math.round(this.cacheHit/n*1e3)/10:0,...r??{}};return this.drawCount=0,this.drawTimeSum=0,this.invalidateCount=0,this.triggerCount=0,this.cacheHit=0,this.cacheMiss=0,s}},wr=/\s+/;function Mr(t,e,n,r){if(!n)return!0;if("object"==typeof n){for(const r in n){const i=n[r];t[e].apply(t,[r,i])}return!1}if(wr.test(n)){return n.split(wr).forEach(n=>t[e].apply(t,[n].concat(r))),!1}return!0}const Sr=["on","off","once","delegate_on","delegate_off","trigger","listenTo"],Ar={withEvent(){Sr.forEach(t=>this[t]=Ar[t])},on(t,e,n){if(!Mr(this,"on",t,[e,n])||!e)return this;this._listeners||(this._listeners={});return(this._listeners[t]||(this._listeners[t]=[])).push({callback:e,context:n,ctx:n||this}),this},once(t,e,n){if(!Mr(this,"once",t,[e,n])||!e)return this;const r=this,i=er(function(){r.off(t,i,n),e.apply(r,arguments)});return i._callback=e,this.on(t,i,n),this},off(t,e,n){if(!this._listeners||!Mr(this,"off",t,[e,n]))return this;if(!t&&!e&&!n)return this._listeners=void 0,this;let r;r=t&&"string"==typeof t?[t]:Object.keys(this._listeners||{});for(let t=0;t<r.length;t++){const i=r[t],s=this._listeners?.[i];if(s){const t=[];if(this._listeners[i]=t,e||n)for(let r=0;r<s.length;r++){const i=s[r];(e&&e!==i.callback&&e!==i.callback._callback||n&&n!==i.context)&&t.push(i)}t.length||delete this._listeners[i]}}return this},delegate_on(t){return this._delegators||(this._delegators=new _r),this._delegators.append(t),this},delegate_off(t){return this._delegators?(this._delegators.remove(t),this):this},delegate(){if(this._delegators&&this._delegators.size()>0&&kr(this._delegators,arguments),!this._listeners)return this;const t=arguments.length-1,e=arguments[t];arguments[t]={origin:e.origin,name:e.name,deliverer:this};const n=this._listeners[e.name],r=this._listeners["(all)"];return n&&Er(n,arguments),r&&Er(r,arguments),this},trigger(t){xr.triggerCount++;const e=[].slice.call(arguments,1);if(e.push({origin:this,name:t,deliverer:this}),this._delegators&&this._delegators.size()>0&&kr(this._delegators,e),!this._listeners)return this;if(!Mr(this,"trigger",t,e))return this;const n=this._listeners[t],r=this._listeners["(all)"];return n&&Er(n,e),r&&Er(r,e),this},stopListening(t,e,n){let r=this._listeningTo;if(!r)return this;const i=!e&&!n;n||"object"!=typeof e||(n=this),t&&(r={},r[t._listenId]=t);for(const t in r){const s=r[t];s.off(e,n,this),(i||rr(s._events))&&delete this._listeningTo[t]}return this}};function Er(t,e){t.forEach(t=>t.callback.apply(t.ctx,e))}function kr(t,e){t.forEach(t=>Ar.delegate.apply(t,e))}const Cr={listenTo:"on",listenToOnce:"once"};for(const t in Cr){const e=Cr[t];Ar[t]=function(t,n,r){this._listeningTo||(this._listeningTo={});const i=this._listeningTo;t._listenId||(t._listenId=`${"l"}${++ir}`);return i[t._listenId]=t,r||"object"!=typeof n||(r=this),t[e](n,r,this),this}}const Pr=Ar.on,Tr=Ar.off,Dr=Ar.once,Or=Ar.trigger,zr=Ar.delegate_on,Ir=Ar.delegate_off;function Lr(t,e){if(e instanceof Array)e.forEach(e=>Lr(t,e));else{if(t.mixedIn=t.hasOwnProperty("mixedIn")?t.mixedIn:[],t.mixingIn=t.hasOwnProperty("mixingIn")?t.mixingIn:[],t.mixedIn.indexOf(e)>=0)return t;if(t.mixingIn.indexOf(e)>=0)throw new Error(`found cyclic dependencies between ${t.mixingIn}`);t.mixingIn.push(e),e.call(t),t.mixingIn.pop(),t.mixedIn.push(e)}return t}const jr=(...t)=>{const e=[];t.forEach(t=>t&&t.stack&&e.push(t.stack)),console.error("[ERROR]",...t,e.join(" "))},Rr=(...t)=>{const e=[];t.forEach(t=>t&&t.stack&&e.push(t.stack)),console.warn("[WARN]",...t,e.join(" "))},Fr=(...t)=>console.log("[DEBUG]",...t);function Br(t,e,n){const r=function(t,e){let n=t;for(;n;){const t=Object.getOwnPropertyDescriptor(n,e);if(t?.get)return t;n=Object.getPrototypeOf(n)}}(t,e);if(!r?.get)return void jr(`${String(e)} is not defined in ${t.constructor.name}`);const i=r.get,s={get:n?function(){return e in this.__cache__?xr.cacheHit++:(xr.cacheMiss++,this.__cache__[e]=Object.freeze(i.call(this))),this.__cache__[e]}:function(){return e in this.__cache__?xr.cacheHit++:(xr.cacheMiss++,this.__cache__[e]=i.call(this)),this.__cache__[e]},configurable:!0};r.set&&(s.set=r.set),Object.defineProperty(t,e,s)}var Nr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Hr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Vr(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Gr,Yr={exports:{}};var Ur=(Gr||(Gr=1,function(t){var e=function(t){var e,n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(t,e,n){t[e]=n.value},s="function"==typeof Symbol?Symbol:{},o=s.iterator||"@@iterator",a=s.asyncIterator||"@@asyncIterator",c=s.toStringTag||"@@toStringTag";function l(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,n){return t[e]=n}}function h(t,e,n,r){var s=e&&e.prototype instanceof y?e:y,o=Object.create(s.prototype),a=new T(r||[]);return i(o,"_invoke",{value:E(t,n,a)}),o}function d(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var u="suspendedStart",p="suspendedYield",f="executing",g="completed",m={};function y(){}function b(){}function v(){}var _={};l(_,o,function(){return this});var x=Object.getPrototypeOf,w=x&&x(x(D([])));w&&w!==n&&r.call(w,o)&&(_=w);var M=v.prototype=y.prototype=Object.create(_);function S(t){["next","throw","return"].forEach(function(e){l(t,e,function(t){return this._invoke(e,t)})})}function A(t,e){function n(i,s,o,a){var c=d(t[i],t,s);if("throw"!==c.type){var l=c.arg,h=l.value;return h&&"object"==typeof h&&r.call(h,"__await")?e.resolve(h.__await).then(function(t){n("next",t,o,a)},function(t){n("throw",t,o,a)}):e.resolve(h).then(function(t){l.value=t,o(l)},function(t){return n("throw",t,o,a)})}a(c.arg)}var s;i(this,"_invoke",{value:function(t,r){function i(){return new e(function(e,i){n(t,r,e,i)})}return s=s?s.then(i,i):i()}})}function E(t,n,r){var i=u;return function(s,o){if(i===f)throw new Error("Generator is already running");if(i===g){if("throw"===s)throw o;return{value:e,done:!0}}for(r.method=s,r.arg=o;;){var a=r.delegate;if(a){var c=k(a,r);if(c){if(c===m)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===u)throw i=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=f;var l=d(t,n,r);if("normal"===l.type){if(i=r.done?g:p,l.arg===m)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(i=g,r.method="throw",r.arg=l.arg)}}}function k(t,n){var r=n.method,i=t.iterator[r];if(i===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,k(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),m;var s=d(i,t.iterator,n.arg);if("throw"===s.type)return n.method="throw",n.arg=s.arg,n.delegate=null,m;var o=s.arg;return o?o.done?(n[t.resultName]=o.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,m):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,m)}function C(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function P(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(C,this),this.reset(!0)}function D(t){if(null!=t){var n=t[o];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return s.next=s}}throw new TypeError(typeof t+" is not iterable")}return b.prototype=v,i(M,"constructor",{value:v,configurable:!0}),i(v,"constructor",{value:b,configurable:!0}),b.displayName=l(v,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,v):(t.__proto__=v,l(t,c,"GeneratorFunction")),t.prototype=Object.create(M),t},t.awrap=function(t){return{__await:t}},S(A.prototype),l(A.prototype,a,function(){return this}),t.AsyncIterator=A,t.async=function(e,n,r,i,s){void 0===s&&(s=Promise);var o=new A(h(e,n,r,i),s);return t.isGeneratorFunction(n)?o:o.next().then(function(t){return t.done?t.value:o.next()})},S(M),l(M,c,"Generator"),l(M,o,function(){return this}),l(M,"toString",function(){return"[object Generator]"}),t.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},t.values=D,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(P),!t)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function i(r,i){return a.type="throw",a.arg=t,n.next=r,i&&(n.method="next",n.arg=e),!!i}for(var s=this.tryEntries.length-1;s>=0;--s){var o=this.tryEntries[s],a=o.completion;if("root"===o.tryLoc)return i("end");if(o.tryLoc<=this.prev){var c=r.call(o,"catchLoc"),l=r.call(o,"finallyLoc");if(c&&l){if(this.prev<o.catchLoc)return i(o.catchLoc,!0);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return i(o.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return i(o.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var s=i;break}}s&&("break"===t||"continue"===t)&&s.tryLoc<=e&&e<=s.finallyLoc&&(s=null);var o=s?s.completion:{};return o.type=t,o.arg=e,s?(this.method="next",this.next=s.finallyLoc,m):this.complete(o)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),m},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),P(n),m}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;P(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:D(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),m}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}Number.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},String.fromCodePoint||function(t){var e=function(e){for(var n=[],r=0,i="",s=0,o=arguments.length;s!==o;++s){var a=+arguments[s];if(!(a<1114111&&a>>>0===a))throw RangeError("Invalid code point: "+a);a<=65535?r=n.push(a):(a-=65536,r=n.push(55296+(a>>10),a%1024+56320)),r>=16383&&(i+=t.apply(null,n),n.length=0)}return i+t.apply(null,n)};try{Object.defineProperty(String,"fromCodePoint",{value:e,configurable:!0,writable:!0})}catch(t){String.fromCodePoint=e}}(String.fromCharCode),Object.is||(Object.is=function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e})
2
2
  /*! https://mths.be/codepointat v0.2.0 by @mathias */,String.prototype.codePointAt||function(){var t=function(){try{var t={},e=Object.defineProperty,n=e(t,t,t)&&e}catch(t){}return n}(),e=function(t){if(null==this)throw TypeError();var e=String(this),n=e.length,r=t?Number(t):0;if(r!=r&&(r=0),!(r<0||r>=n)){var i,s=e.charCodeAt(r);return s>=55296&&s<=56319&&n>r+1&&(i=e.charCodeAt(r+1))>=56320&&i<=57343?1024*(s-55296)+i-56320+65536:s}};t?t(String.prototype,"codePointAt",{value:e,configurable:!0,writable:!0}):String.prototype.codePointAt=e}(),Math.log10=Math.log10||function(t){return Math.log(t)*Math.LOG10E},t.exports=function(){function t(e,n,r){function i(o,a){if(!n[o]){if(!e[o]){if(!a&&Vr)return Vr(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};e[o][0].call(l.exports,function(t){return i(e[o][1][t]||t)},l,l.exports,t,e,n,r)}return n[o].exports}for(var s=Vr,o=0;o<r.length;o++)i(r[o]);return i}return t}()({1:[function(t,e,n){var r=t("./utils"),i=function(){var t=r.stringToArray,e=["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],n=["Zeroth","First","Second","Third","Fourth","Fifth","Sixth","Seventh","Eighth","Ninth","Tenth","Eleventh","Twelfth","Thirteenth","Fourteenth","Fifteenth","Sixteenth","Seventeenth","Eighteenth","Nineteenth"],i=["Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"],s=["Thousand","Million","Billion","Trillion"];function o(t,r){var o=function t(r,o,a){var c="";if(r<=19)c=(o?" and ":"")+(a?n[r]:e[r]);else if(r<100){var l=Math.floor(r/10),h=r%10;c=(o?" and ":"")+i[l-2],h>0?c+="-"+t(h,!1,a):a&&(c=c.substring(0,c.length-1)+"ieth")}else if(r<1e3){var d=Math.floor(r/100),u=r%100;c=(o?", ":"")+e[d]+" Hundred",u>0?c+=t(u,!0,a):a&&(c+="th")}else{var p=Math.floor(Math.log10(r)/3);p>s.length&&(p=s.length);var f=Math.pow(10,3*p),g=Math.floor(r/f),m=r-g*f;c=(o?", ":"")+t(g,!1,!1)+" "+s[p-1],m>0?c+=t(m,!0,a):a&&(c+="th")}return c};return o(t,!1,r)}var a={};function c(t){var e=t.split(/,\s|\sand\s|[\s\\-]/).map(function(t){return a[t]}),n=[0];e.forEach(function(t){if(t<100){var e=n.pop();e>=1e3&&(n.push(e),e=0),n.push(e+t)}else n.push(n.pop()*t)});var r=n.reduce(function(t,e){return t+e},0);return r}e.forEach(function(t,e){a[t.toLowerCase()]=e}),n.forEach(function(t,e){a[t.toLowerCase()]=e}),i.forEach(function(t,e){var n=t.toLowerCase();a[n]=10*(e+2),a[n.substring(0,t.length-1)+"ieth"]=a[n]}),a.hundredth=100,s.forEach(function(t,e){var n=t.toLowerCase(),r=Math.pow(10,3*(e+1));a[n]=r,a[n+"th"]=r});var l=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],h={M:1e3,D:500,C:100,L:50,X:10,V:5,I:1};function d(t){for(var e=0;e<l.length;e++){var n=l[e];if(t>=n[0])return n[1]+d(t-n[0])}return""}function u(t){for(var e=0,n=1,r=t.length-1;r>=0;r--){var i=t[r],s=h[i];s<n?e-=s:(n=s,e+=s)}return e}function p(t,e){for(var n=[],r=e.charCodeAt(0);t>0;)n.unshift(String.fromCharCode((t-1)%26+r)),t=Math.floor((t-1)/26);return n.join("")}function f(t,e){for(var n=e.charCodeAt(0),r=0,i=0;i<t.length;i++)r+=(t.charCodeAt(t.length-i-1)-n+1)*Math.pow(26,i);return r}function g(t,e){if(void 0!==t)return b(t=Math.floor(t),_(e))}var m={DECIMAL:"decimal",LETTERS:"letters",ROMAN:"roman",WORDS:"words",SEQUENCE:"sequence"},y={UPPER:"upper",LOWER:"lower",TITLE:"title"};function b(e,n){var r,i=e<0;switch(e=Math.abs(e),n.primary){case m.LETTERS:r=p(e,n.case===y.UPPER?"A":"a");break;case m.ROMAN:r=d(e),n.case===y.UPPER&&(r=r.toUpperCase());break;case m.WORDS:r=o(e,n.ordinal),n.case===y.UPPER?r=r.toUpperCase():n.case===y.LOWER&&(r=r.toLowerCase());break;case m.DECIMAL:r=""+e;var s=n.mandatoryDigits-r.length;if(s>0){var a=new Array(s+1).join("0");r=a+r}if(48!==n.zeroCode&&(r=t(r).map(function(t){return String.fromCodePoint(t.codePointAt(0)+n.zeroCode-48)}).join("")),n.regular)for(var c=Math.floor((r.length-1)/n.groupingSeparators.position);c>0;c--){var l=r.length-c*n.groupingSeparators.position;r=r.substr(0,l)+n.groupingSeparators.character+r.substr(l)}else n.groupingSeparators.reverse().forEach(function(t){var e=r.length-t.position;r=r.substr(0,e)+t.character+r.substr(e)});if(n.ordinal){var h={1:"st",2:"nd",3:"rd"}[r[r.length-1]];(!h||r.length>1&&"1"===r[r.length-2])&&(h="th"),r+=h}break;case m.SEQUENCE:throw{code:"D3130",value:n.token}}return i&&(r="-"+r),r}var v=[48,1632,1776,1984,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,42528,43216,43264,43472,43504,43600,44016,65296];function _(e){var n,r={type:"integer",primary:m.DECIMAL,case:y.LOWER,ordinal:!1},i=e.lastIndexOf(";");switch(-1===i?n=e:(n=e.substring(0,i),"o"===e.substring(i+1)[0]&&(r.ordinal=!0)),n){case"A":r.case=y.UPPER;case"a":r.primary=m.LETTERS;break;case"I":r.case=y.UPPER;case"i":r.primary=m.ROMAN;break;case"W":r.case=y.UPPER,r.primary=m.WORDS;break;case"Ww":r.case=y.TITLE,r.primary=m.WORDS;break;case"w":r.primary=m.WORDS;break;default:var s=null,o=0,a=0,c=[],l=0,h=t(n).map(function(t){return t.codePointAt(0)}).reverse();if(h.forEach(function(t){for(var e=!1,n=0;n<v.length;n++){var r=v[n];if(t>=r&&t<=r+9){if(e=!0,o++,l++,null===s)s=r;else if(r!==s)throw{code:"D3131"};break}}e||(35===t?(l++,a++):c.push({position:l,character:String.fromCodePoint(t)}))}),o>0){r.primary=m.DECIMAL,r.zeroCode=s,r.mandatoryDigits=o,r.optionalDigits=a;var d=function(t){if(0===t.length)return 0;for(var e=t[0].character,n=1;n<t.length;n++)if(t[n].character!==e)return 0;for(var r=t.map(function(t){return t.position}),i=function t(e,n){return 0===n?e:t(n,e%n)},s=r.reduce(i),o=1;o<=r.length;o++)if(-1===r.indexOf(o*s))return 0;return s},u=d(c);u>0?(r.regular=!0,r.groupingSeparators={position:u,character:c[0].character}):(r.regular=!1,r.groupingSeparators=c)}else r.primary=m.SEQUENCE,r.token=n}return r}var x={Y:"1",M:"1",D:"1",d:"1",F:"n",W:"1",w:"1",X:"1",x:"1",H:"1",h:"1",P:"n",m:"01",s:"01",f:"1",Z:"01:01",z:"01:01",C:"n",E:"n"};function w(t){for(var e=[],n={type:"datetime",parts:e},r=function(n,r){if(r>n){var i=t.substring(n,r);i=i.split("]]").join("]"),e.push({type:"literal",value:i})}},i=0,s=0;s<t.length;){if("["===t.charAt(s)){if("["===t.charAt(s+1)){r(i,s),e.push({type:"literal",value:"["}),i=s+=2;continue}if(r(i,s),i=s,-1===(s=t.indexOf("]",i)))throw{code:"D3135"};var o,a=t.substring(i+1,s),c={type:"marker",component:(a=a.split(/\s+/).join("")).charAt(0)},l=a.lastIndexOf(",");if(-1!==l){var h=a.substring(l+1),d=h.indexOf("-"),u=void 0,p=void 0,f=function(t){return void 0===t||"*"===t?void 0:parseInt(t)};-1===d?u=h:(u=h.substring(0,d),p=h.substring(d+1));var g={min:f(u),max:f(p)};c.width=g,o=a.substring(1,l)}else o=a.substring(1);if(1===o.length)c.presentation1=o;else if(o.length>1){var m=o.charAt(o.length-1);-1!=="atco".indexOf(m)?(c.presentation2=m,"o"===m&&(c.ordinal=!0),c.presentation1=o.substring(0,o.length-1)):c.presentation1=o}else c.presentation1=x[c.component];if(void 0===c.presentation1)throw{code:"D3132",value:c.component};if("n"===c.presentation1[0])c.names=y.LOWER;else if("N"===c.presentation1[0])"n"===c.presentation1[1]?c.names=y.TITLE:c.names=y.UPPER;else if(-1!=="YMDdFWwXxHhmsf".indexOf(c.component)){var b=c.presentation1;if(c.presentation2&&(b+=";"+c.presentation2),c.integerFormat=_(b),c.width&&void 0!==c.width.min&&c.integerFormat.mandatoryDigits<c.width.min&&(c.integerFormat.mandatoryDigits=c.width.min),-1!=="YMD".indexOf(c.component))if(c.n=-1,c.width&&void 0!==c.width.max)c.n=c.width.max,c.integerFormat.mandatoryDigits=c.n;else{var v=c.integerFormat.mandatoryDigits+c.integerFormat.optionalDigits;v>=2&&(c.n=v)}}"Z"!==c.component&&"z"!==c.component||(c.integerFormat=_(c.presentation1)),e.push(c),i=s+1}s++}return r(i,s),n}var M=["","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],S=["January","February","March","April","May","June","July","August","September","October","November","December"],A=864e5,E=function(t){var e=Date.UTC(t.year,t.month),n=new Date(e).getUTCDay();return 0===n&&(n=7),n>4?e+(8-n)*A:e-(n-1)*A},k=function t(e,n){return{year:e,month:n,nextMonth:function(){return 11===n?t(e+1,0):t(e,n+1)},previousMonth:function(){return 0===n?t(e-1,11):t(e,n-1)},nextYear:function(){return t(e+1,n)},previousYear:function(){return t(e-1,n)}}},C=function(t,e){return(e-t)/(7*A)+1},P=function(t,e){var n;switch(e){case"Y":n=t.getUTCFullYear();break;case"M":n=t.getUTCMonth()+1;break;case"D":n=t.getUTCDate();break;case"d":n=(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-Date.UTC(t.getUTCFullYear(),0))/A+1;break;case"F":0===(n=t.getUTCDay())&&(n=7);break;case"W":var r=k(t.getUTCFullYear(),0),i=E(r),s=Date.UTC(r.year,t.getUTCMonth(),t.getUTCDate()),o=C(i,s);if(o>52)s>=E(r.nextYear())&&(o=1);else if(o<1){var a=E(r.previousYear());o=C(a,s)}n=Math.floor(o);break;case"w":var c=k(t.getUTCFullYear(),t.getUTCMonth()),l=E(c),h=Date.UTC(c.year,c.month,t.getUTCDate()),d=C(l,h);if(d>4)h>=E(c.nextMonth())&&(d=1);else if(d<1){var u=E(c.previousMonth());d=C(u,h)}n=Math.floor(d);break;case"X":var p=k(t.getUTCFullYear(),0),f=E(p),g=E(p.nextYear()),m=t.getTime();n=m<f?p.year-1:m>=g?p.year+1:p.year;break;case"x":var y=k(t.getUTCFullYear(),t.getUTCMonth()),b=E(y),v=y.nextMonth(),_=E(v),x=t.getTime();n=x<b?y.previousMonth().month+1:x>=_?v.month+1:y.month+1;break;case"H":n=t.getUTCHours();break;case"h":n=t.getUTCHours(),0==(n%=12)&&(n=12);break;case"P":n=t.getUTCHours()>=12?"pm":"am";break;case"m":n=t.getUTCMinutes();break;case"s":n=t.getUTCSeconds();break;case"f":n=t.getUTCMilliseconds();break;case"Z":case"z":break;case"C":case"E":n="ISO"}return n},T=null;function D(t,e,n){var r=0,i=0;if(void 0!==n){var s=parseInt(n);r=Math.floor(s/100),i=s%100}var o,a=function(t,e){var n=P(t,e.component);if(-1!=="YMDdFWwXxHhms".indexOf(e.component))if("Y"===e.component&&-1!==e.n&&(n%=Math.pow(10,e.n)),e.names){if("M"===e.component||"x"===e.component)n=S[n-1];else{if("F"!==e.component)throw{code:"D3133",value:e.component};n=M[n]}e.names===y.UPPER?n=n.toUpperCase():e.names===y.LOWER&&(n=n.toLowerCase()),e.width&&n.length>e.width.max&&(n=n.substring(0,e.width.max))}else n=b(n,e.integerFormat);else if("f"===e.component)n=b(n,e.integerFormat);else if("Z"===e.component||"z"===e.component){var s=100*r+i;if(e.integerFormat.regular)n=b(s,e.integerFormat);else{var o=e.integerFormat.mandatoryDigits;if(1===o||2===o)n=b(r,e.integerFormat),0!==i&&(n+=":"+g(i,"00"));else{if(3!==o&&4!==o)throw{code:"D3134",value:o};n=b(s,e.integerFormat)}}s>=0&&(n="+"+n),"z"===e.component&&(n="GMT"+n),0===s&&"t"===e.presentation2&&(n="Z")}return n};void 0===e?(null===T&&(T=w("[Y0001]-[M01]-[D01]T[H01]:[m01]:[s01].[f001][Z01:01t]")),o=T):o=w(e);var c=new Date(t+60*(60*r+i)*1e3),l="";return o.parts.forEach(function(t){"literal"===t.type?l+=t.value:l+=a(c,t)}),l}function O(t){var e={};if("datetime"===t.type)e.type="datetime",e.parts=t.parts.map(function(t){var e={};if("literal"===t.type)e.regex=t.value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");else if("Z"===t.component||"z"===t.component){var n;Array.isArray(t.integerFormat.groupingSeparators)||(n=t.integerFormat.groupingSeparators),e.regex="","z"===t.component&&(e.regex="GMT"),e.regex+="[-+][0-9]+",n&&(e.regex+=n.character+"[0-9]+"),e.parse=function(e){"z"===t.component&&(e=e.substring(3));var r=0,i=0;return n?(r=Number.parseInt(e.substring(0,e.indexOf(n.character))),i=Number.parseInt(e.substring(e.indexOf(n.character)+1))):e.length-1<=2?r=Number.parseInt(e):(r=Number.parseInt(e.substring(0,3)),i=Number.parseInt(e.substring(3))),60*r+i}}else if(t.integerFormat)t.integerFormat.n=t.n,e=O(t.integerFormat);else{e.regex="[a-zA-Z]+";var r={};if("M"===t.component||"x"===t.component)S.forEach(function(e,n){t.width&&t.width.max?r[e.substring(0,t.width.max)]=n+1:r[e]=n+1});else if("F"===t.component)M.forEach(function(e,n){n>0&&(t.width&&t.width.max?r[e.substring(0,t.width.max)]=n:r[e]=n)});else{if("P"!==t.component)throw{code:"D3133",value:t.component};r={am:0,AM:0,pm:1,PM:1}}e.parse=function(t){return r[t]}}return e.component=t.component,e});else{e.type="integer";var n,r=t.case===y.UPPER;switch(n=t.n&&t.n>0?0===t.optionalDigits?"{".concat(t.n,"}"):"{".concat(t.n-t.optionalDigits,",").concat(t.n,"}"):"+",t.primary){case m.LETTERS:e.regex=r?"[A-Z]+":"[a-z]+",e.parse=function(t){return f(t,r?"A":"a")};break;case m.ROMAN:e.regex=r?"[MDCLXVI]+":"[mdclxvi]+",e.parse=function(t){return u(r?t:t.toUpperCase())};break;case m.WORDS:e.regex="(?:"+Object.keys(a).concat("and","[\\-, ]").join("|")+")+",e.parse=function(t){return c(t.toLowerCase())};break;case m.DECIMAL:e.regex="[0-9]".concat(n),t.ordinal&&(e.regex+="(?:th|st|nd|rd)"),e.parse=function(e){var n=e;return t.ordinal&&(n=e.substring(0,e.length-2)),t.regular?n=n.split(",").join(""):t.groupingSeparators.forEach(function(t){n=n.split(t.character).join("")}),48!==t.zeroCode&&(n=n.split("").map(function(e){return String.fromCodePoint(e.codePointAt(0)-t.zeroCode+48)}).join("")),parseInt(n)};break;case m.SEQUENCE:throw{code:"D3130",value:t.token}}}return e}function z(t,e){if(void 0!==t)return O(_(e)).parse(t)}function I(t,e){var n=O(w(e)),r="^"+n.parts.map(function(t){return"("+t.regex+")"}).join("")+"$",i=new RegExp(r,"i").exec(t);if(null!==i){for(var s=161,o=130,a=84,c=72,l=23,h=47,d={},u=1;u<i.length;u++){var p=n.parts[u-1];p.parse&&(d[p.component]=p.parse(i[u]))}if(0===Object.getOwnPropertyNames(d).length)return;var f=0,g=function(t){f<<=1,f+=t?1:0},m=function(t){return!(~t&f||!(t&f))};"YXMxWwdD".split("").forEach(function(t){return g(d[t])});var y=!m(s)&&m(o),b=m(a),v=!b&&m(c);f=0,"PHhmsf".split("").forEach(function(t){return g(d[t])});var _=!m(l)&&m(h),x=(y?"YD":b?"XxwF":v?"XWF":"YMD")+(_?"Phmsf":"Hmsf"),M=this.environment.timestamp,S=!1,A=!1;if(x.split("").forEach(function(t){if(void 0===d[t])S?(d[t]=-1!=="MDd".indexOf(t)?1:0,A=!0):d[t]=P(M,t);else if(S=!0,A)throw{code:"D3136"}}),d.M>0?d.M-=1:d.M=0,y){var E=Date.UTC(d.Y,0),k=1e3*(d.d-1)*60*60*24,C=new Date(E+k);d.M=C.getUTCMonth(),d.D=C.getUTCDate()}if(b)throw{code:"D3136"};if(v)throw{code:"D3136"};_&&(d.H=12===d.h?0:d.h,1===d.P&&(d.H+=12));var T=Date.UTC(d.Y,d.M,d.D,d.H,d.m,d.s,d.f);return(d.Z||d.z)&&(T-=60*(d.Z||d.z)*1e3),T}}var L=new RegExp("^\\d{4}(-[01]\\d)*(-[0-3]\\d)*(T[0-2]\\d:[0-5]\\d:[0-5]\\d)*(\\.\\d+)?([+-][0-2]\\d:?[0-5]\\d|Z)?$");function j(t,e){if(void 0!==t){if(void 0===e){if(!L.test(t))throw{stack:(new Error).stack,code:"D3110",value:t};return Date.parse(t)}return I.call(this,t,e)}}function R(t,e,n){if(void 0!==t)return D.call(this,t,e,n)}return{formatInteger:g,parseInteger:z,fromMillis:R,toMillis:j}}();e.exports=i},{"./utils":6}],2:[function(t,e,n){(function(n){(function(){function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */i=function(){return e};var t,e={},n=Object.prototype,s=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},a="function"==typeof Symbol?Symbol:{},c=a.iterator||"@@iterator",l=a.asyncIterator||"@@asyncIterator",h=a.toStringTag||"@@toStringTag";function d(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{d({},"")}catch(t){d=function(t,e,n){return t[e]=n}}function u(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,s=Object.create(i.prototype),a=new O(r||[]);return o(s,"_invoke",{value:C(t,n,a)}),s}function p(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=u;var f="suspendedStart",g="suspendedYield",m="executing",y="completed",b={};function v(){}function _(){}function x(){}var w={};d(w,c,function(){return this});var M=Object.getPrototypeOf,S=M&&M(M(z([])));S&&S!==n&&s.call(S,c)&&(w=S);var A=x.prototype=v.prototype=Object.create(w);function E(t){["next","throw","return"].forEach(function(e){d(t,e,function(t){return this._invoke(e,t)})})}function k(t,e){function n(i,o,a,c){var l=p(t[i],t,o);if("throw"!==l.type){var h=l.arg,d=h.value;return d&&"object"==r(d)&&s.call(d,"__await")?e.resolve(d.__await).then(function(t){n("next",t,a,c)},function(t){n("throw",t,a,c)}):e.resolve(d).then(function(t){h.value=t,a(h)},function(t){return n("throw",t,a,c)})}c(l.arg)}var i;o(this,"_invoke",{value:function(t,r){function s(){return new e(function(e,i){n(t,r,e,i)})}return i=i?i.then(s,s):s()}})}function C(e,n,r){var i=f;return function(s,o){if(i===m)throw new Error("Generator is already running");if(i===y){if("throw"===s)throw o;return{value:t,done:!0}}for(r.method=s,r.arg=o;;){var a=r.delegate;if(a){var c=P(a,r);if(c){if(c===b)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===f)throw i=y,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=m;var l=p(e,n,r);if("normal"===l.type){if(i=r.done?y:g,l.arg===b)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(i=y,r.method="throw",r.arg=l.arg)}}}function P(e,n){var r=n.method,i=e.iterator[r];if(i===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,P(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),b;var s=p(i,e.iterator,n.arg);if("throw"===s.type)return n.method="throw",n.arg=s.arg,n.delegate=null,b;var o=s.arg;return o?o.done?(n[e.resultName]=o.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,b):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,b)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function D(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function z(e){if(e||""===e){var n=e[c];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,o=function n(){for(;++i<e.length;)if(s.call(e,i))return n.value=e[i],n.done=!1,n;return n.value=t,n.done=!0,n};return o.next=o}}throw new TypeError(r(e)+" is not iterable")}return _.prototype=x,o(A,"constructor",{value:x,configurable:!0}),o(x,"constructor",{value:_,configurable:!0}),_.displayName=d(x,h,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===_||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,d(t,h,"GeneratorFunction")),t.prototype=Object.create(A),t},e.awrap=function(t){return{__await:t}},E(k.prototype),d(k.prototype,l,function(){return this}),e.AsyncIterator=k,e.async=function(t,n,r,i,s){void 0===s&&(s=Promise);var o=new k(u(t,n,r,i),s);return e.isGeneratorFunction(n)?o:o.next().then(function(t){return t.done?t.value:o.next()})},E(A),d(A,h,"Generator"),d(A,c,function(){return this}),d(A,"toString",function(){return"[object Generator]"}),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=z,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(D),!e)for(var n in this)"t"===n.charAt(0)&&s.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function r(r,i){return a.type="throw",a.arg=e,n.next=r,i&&(n.method="next",n.arg=t),!!i}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var c=s.call(o,"catchLoc"),l=s.call(o,"finallyLoc");if(c&&l){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&s.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=t,o.arg=e,i?(this.method="next",this.next=i.finallyLoc,b):this.complete(o)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),b},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),D(n),b}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;D(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:z(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),b}},e}var s=t("./utils"),o=function(){var t=i().mark(H),e=i().mark(V),o=i().mark(G),a=i().mark(Y),c=i().mark(Q),l=i().mark(ut),h=i().mark(pt),d=i().mark(ft),u=i().mark(mt),p=i().mark(St),f=i().mark(Ct),g=i().mark(Dt),m=s.isNumeric,y=s.isArrayOfStrings,b=s.isArrayOfNumbers,v=s.createSequence,_=s.isSequence,x=s.isFunction,w=s.isLambda,M=s.isIterable,S=s.getFunctionArity,A=s.isDeepEqual,E=s.stringToArray;function k(t){if(void 0!==t){var e=0;return t.forEach(function(t){e+=t}),e}}function C(t){return void 0===t?0:t.length}function P(t){if(void 0!==t&&0!==t.length)return Math.max.apply(Math,t)}function T(t){if(void 0!==t&&0!==t.length)return Math.min.apply(Math,t)}function D(t){if(void 0!==t&&0!==t.length){var e=0;return t.forEach(function(t){e+=t}),e/t.length}}function O(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(void 0!==t){var n;if("string"==typeof t)n=t;else if(x(t))n="";else{if("number"==typeof t&&!isFinite(t))throw{code:"D3001",value:t,stack:(new Error).stack};var r=e?2:0;Array.isArray(t)&&t.outerWrapper&&(t=t[0]),n=JSON.stringify(t,function(t,e){return null!=e&&e.toPrecision&&m(e)?Number(e.toPrecision(15)):e&&x(e)?"":e},r)}return n}}function z(t,e,n){if(void 0!==t){var r=E(t),i=r.length;if(i+e<0&&(e=0),void 0!==n){if(n<=0)return"";var s=e>=0?e+n:i+e+n;return r.slice(e,s).join("")}return r.slice(e).join("")}}function I(t,e){if(void 0!==t){var n=t.indexOf(e);return n>-1?t.substr(0,n):t}}function L(t,e){if(void 0!==t){var n=t.indexOf(e);return n>-1?t.substr(n+e.length):t}}function j(t){if(void 0!==t)return t.toLowerCase()}function R(t){if(void 0!==t)return t.toUpperCase()}function F(t){if(void 0!==t)return E(t).length}function B(t){if(void 0!==t){var e=t.replace(/[ \t\n\r]+/gm," ");return" "===e.charAt(0)&&(e=e.substring(1))," "===e.charAt(e.length-1)&&(e=e.substring(0,e.length-1)),e}}function N(t,e,n){if(void 0!==t){var r;void 0!==n&&0!==n.length||(n=" ");var i=Math.abs(e)-F(t);if(i>0){var s=new Array(i+1).join(n);n.length>1&&(s=z(s,0,i)),r=e>0?t+s:s+t}else r=t;return r}}function H(e,n){var r;return i().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(r=e.apply(this,[n]),!M(r)){t.next=4;break}return t.delegateYield(r,"t0",3);case 3:r=t.t0;case 4:if(!r||"number"==typeof r.start||"number"===r.end||Array.isArray(r.groups)||x(r.next)){t.next=6;break}throw{code:"T1010",stack:(new Error).stack};case 6:return t.abrupt("return",r);case 7:case"end":return t.stop()}},t,this)}function V(t,n){var r,s;return i().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==t){e.next=2;break}return e.abrupt("return",void 0);case 2:if("string"!=typeof n){e.next=6;break}r=-1!==t.indexOf(n),e.next=9;break;case 6:return e.delegateYield(H(n,t),"t0",7);case 7:s=e.t0,r=void 0!==s;case 9:return e.abrupt("return",r);case 10:case"end":return e.stop()}},e)}function G(t,e,n){var r,s,a;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:if(!(n<0)){i.next=4;break}throw{stack:(new Error).stack,value:n,code:"D3040",index:3};case 4:if(r=v(),!(void 0===n||n>0)){i.next=17;break}return s=0,i.delegateYield(H(e,t),"t0",8);case 8:if(void 0===(a=i.t0)){i.next=17;break}case 10:if(void 0===a||!(void 0===n||s<n)){i.next=17;break}return r.push({match:a.match,index:a.start,groups:a.groups}),i.delegateYield(H(a.next),"t1",13);case 13:a=i.t1,s++,i.next=10;break;case 17:return i.abrupt("return",r);case 18:case"end":return i.stop()}},o)}function Y(t,e,n,r){var s,o,c,l,h,d,u,p;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:if(s=this,""!==e){i.next=5;break}throw{code:"D3010",stack:(new Error).stack,value:e,index:2};case 5:if(!(r<0)){i.next=7;break}throw{code:"D3011",stack:(new Error).stack,value:r,index:4};case 7:if(o="string"==typeof n?function(t){for(var e="",r=0,i=n.indexOf("$",r);-1!==i&&r<n.length;){e+=n.substring(r,i),r=i+1;var s=n.charAt(r);if("$"===s)e+="$",r++;else if("0"===s)e+=t.match,r++;else{var o;if(o=0===t.groups.length?1:Math.floor(Math.log(t.groups.length)*Math.LOG10E)+1,i=parseInt(n.substring(r,r+o),10),o>1&&i>t.groups.length&&(i=parseInt(n.substring(r,r+o-1),10)),isNaN(i))e+="$";else{if(t.groups.length>0){var a=t.groups[i-1];void 0!==a&&(e+=a)}r+=i.toString().length}}i=n.indexOf("$",r)}return e+=n.substring(r)}:n,c="",l=0,!(void 0===r||r>0)){i.next=44;break}if(h=0,"string"!=typeof e){i.next=18;break}for(d=t.indexOf(e,l);-1!==d&&(void 0===r||h<r);)c+=t.substring(l,d),c+=n,l=d+e.length,h++,d=t.indexOf(e,l);c+=t.substring(l),i.next=42;break;case 18:return i.delegateYield(H(e,t),"t0",19);case 19:if(void 0===(u=i.t0)){i.next=41;break}case 21:if(void 0===u||!(void 0===r||h<r)){i.next=38;break}if(c+=t.substring(l,u.start),p=o.apply(s,[u]),!M(p)){i.next=27;break}return i.delegateYield(p,"t1",26);case 26:p=i.t1;case 27:if("string"!=typeof p){i.next=31;break}c+=p,i.next=32;break;case 31:throw{code:"D3012",stack:(new Error).stack,value:p};case 32:return l=u.start+u.match.length,h++,i.delegateYield(H(u.next),"t2",35);case 35:u=i.t2,i.next=21;break;case 38:c+=t.substring(l),i.next=42;break;case 41:c=t;case 42:i.next=45;break;case 44:c=t;case 45:return i.abrupt("return",c);case 46:case"end":return i.stop()}},a,this)}function U(t){if(void 0!==t){var e="undefined"!=typeof window?window.btoa:function(t){return new n.Buffer.from(t,"binary").toString("base64")};return e(t)}}function $(t){if(void 0!==t){var e="undefined"!=typeof window?window.atob:function(t){return new n.Buffer.from(t,"base64").toString("binary")};return e(t)}}function W(t){if(void 0!==t){var e;try{e=encodeURIComponent(t)}catch(e){throw{code:"D3140",stack:(new Error).stack,value:t,functionName:"encodeUrlComponent"}}return e}}function X(t){if(void 0!==t){var e;try{e=encodeURI(t)}catch(e){throw{code:"D3140",stack:(new Error).stack,value:t,functionName:"encodeUrl"}}return e}}function q(t){if(void 0!==t){var e;try{e=decodeURIComponent(t)}catch(e){throw{code:"D3140",stack:(new Error).stack,value:t,functionName:"decodeUrlComponent"}}return e}}function K(t){if(void 0!==t){var e;try{e=decodeURI(t)}catch(e){throw{code:"D3140",stack:(new Error).stack,value:t,functionName:"decodeUrl"}}return e}}function Q(t,e,n){var r,s,o,a;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:if(!(n<0)){i.next=4;break}throw{code:"D3020",stack:(new Error).stack,value:n,index:3};case 4:if(r=[],!(void 0===n||n>0)){i.next=27;break}if("string"!=typeof e){i.next=10;break}r=t.split(e,n),i.next=27;break;case 10:return s=0,i.delegateYield(H(e,t),"t0",12);case 12:if(void 0===(o=i.t0)){i.next=26;break}a=0;case 15:if(void 0===o||!(void 0===n||s<n)){i.next=23;break}return r.push(t.substring(a,o.start)),a=o.end,i.delegateYield(H(o.next),"t1",19);case 19:o=i.t1,s++,i.next=15;break;case 23:(void 0===n||s<n)&&r.push(t.substring(a)),i.next=27;break;case 26:r.push(t);case 27:return i.abrupt("return",r);case 28:case"end":return i.stop()}},c)}function Z(t,e){if(void 0!==t)return void 0===e&&(e=""),t.join(e)}function J(t,e,n){if(void 0!==t){var r={"decimal-separator":".","grouping-separator":",","exponent-separator":"e",infinity:"Infinity","minus-sign":"-",NaN:"NaN",percent:"%","per-mille":"‰","zero-digit":"0",digit:"#","pattern-separator":";"};void 0!==n&&Object.keys(n).forEach(function(t){r[t]=n[t]});for(var i=[],s=r["zero-digit"].charCodeAt(0),o=s;o<s+10;o++)i.push(String.fromCharCode(o));var a=i.concat([r["decimal-separator"],r["exponent-separator"],r["grouping-separator"],r.digit,r["pattern-separator"]]),c=e.split(r["pattern-separator"]);if(c.length>2)throw{code:"D3080",stack:(new Error).stack};var l=function(t){var e,n,i,s,o=function(){for(var e,n=0;n<t.length;n++)if(e=t.charAt(n),-1!==a.indexOf(e)&&e!==r["exponent-separator"])return t.substring(0,n)}(),c=function(){for(var e,n=t.length-1;n>=0;n--)if(e=t.charAt(n),-1!==a.indexOf(e)&&e!==r["exponent-separator"])return t.substring(n+1)}(),l=t.substring(o.length,t.length-c.length),h=t.indexOf(r["exponent-separator"],o.length);-1===h||h>t.length-c.length?(e=l,n=void 0):(e=l.substring(0,h),n=l.substring(h+1));var d=e.indexOf(r["decimal-separator"]);return-1===d?(i=e,s=c):(i=e.substring(0,d),s=e.substring(d+1)),{prefix:o,suffix:c,activePart:l,mantissaPart:e,exponentPart:n,integerPart:i,fractionalPart:s,subpicture:t}},h=function(t){var e,n,s=t.subpicture,o=s.indexOf(r["decimal-separator"]);o!==s.lastIndexOf(r["decimal-separator"])&&(e="D3081"),s.indexOf(r.percent)!==s.lastIndexOf(r.percent)&&(e="D3082"),s.indexOf(r["per-mille"])!==s.lastIndexOf(r["per-mille"])&&(e="D3083"),-1!==s.indexOf(r.percent)&&-1!==s.indexOf(r["per-mille"])&&(e="D3084");var c=!1;for(n=0;n<t.mantissaPart.length;n++){var l=t.mantissaPart.charAt(n);if(-1!==i.indexOf(l)||l===r.digit){c=!0;break}}c||(e="D3085"),-1!==t.activePart.split("").map(function(t){return-1===a.indexOf(t)?"p":"a"}).join("").indexOf("p")&&(e="D3086"),-1!==o?s.charAt(o-1)!==r["grouping-separator"]&&s.charAt(o+1)!==r["grouping-separator"]||(e="D3087"):t.integerPart.charAt(t.integerPart.length-1)===r["grouping-separator"]&&(e="D3088"),-1!==s.indexOf(r["grouping-separator"]+r["grouping-separator"])&&(e="D3089");var h=t.integerPart.indexOf(r.digit);-1!==h&&t.integerPart.substring(0,h).split("").filter(function(t){return i.indexOf(t)>-1}).length>0&&(e="D3090"),-1!==(h=t.fractionalPart.lastIndexOf(r.digit))&&t.fractionalPart.substring(h).split("").filter(function(t){return i.indexOf(t)>-1}).length>0&&(e="D3091");var d="string"==typeof t.exponentPart;if(d&&t.exponentPart.length>0&&(-1!==s.indexOf(r.percent)||-1!==s.indexOf(r["per-mille"]))&&(e="D3092"),d&&(0===t.exponentPart.length||t.exponentPart.split("").filter(function(t){return-1===i.indexOf(t)}).length>0)&&(e="D3093"),e)throw{code:e,stack:(new Error).stack}},d=function(t){var e=function(e,n){for(var s=[],o=e.indexOf(r["grouping-separator"]);-1!==o;){var a=(n?e.substring(0,o):e.substring(o)).split("").filter(function(t){return-1!==i.indexOf(t)||t===r.digit}).length;s.push(a),o=t.integerPart.indexOf(r["grouping-separator"],o+1)}return s},n=e(t.integerPart),s=function(t){if(0===t.length)return 0;for(var e=function t(e,n){return 0===n?e:t(n,e%n)},n=t.reduce(e),r=1;r<=t.length;r++)if(-1===t.indexOf(r*n))return 0;return n},o=s(n),a=e(t.fractionalPart,!0),c=t.integerPart.split("").filter(function(t){return-1!==i.indexOf(t)}).length,l=c,h=t.fractionalPart.split(""),d=h.filter(function(t){return-1!==i.indexOf(t)}).length,u=h.filter(function(t){return-1!==i.indexOf(t)||t===r.digit}).length,p="string"==typeof t.exponentPart;0===c&&0===u&&(p?(d=1,u=1):c=1),p&&0===c&&-1!==t.integerPart.indexOf(r.digit)&&(c=1),0===c&&0===d&&(d=1);var f=0;return p&&(f=t.exponentPart.split("").filter(function(t){return-1!==i.indexOf(t)}).length),{integerPartGroupingPositions:n,regularGrouping:o,minimumIntegerPartSize:c,scalingFactor:l,prefix:t.prefix,fractionalPartGroupingPositions:a,minimumFactionalPartSize:d,maximumFactionalPartSize:u,minimumExponentSize:f,suffix:t.suffix,picture:t.subpicture}},u=c.map(l);u.forEach(h);var p,f,g,m,y=u.map(d),b=r["minus-sign"],v=r["zero-digit"],_=r["decimal-separator"],x=r["grouping-separator"];if(1===y.length&&(y.push(JSON.parse(JSON.stringify(y[0]))),y[1].prefix=b+y[1].prefix),f=-1!==(p=t>=0?y[0]:y[1]).picture.indexOf(r.percent)?100*t:-1!==p.picture.indexOf(r["per-mille"])?1e3*t:t,0===p.minimumExponentSize)g=f;else{var w=Math.pow(10,p.scalingFactor),M=Math.pow(10,p.scalingFactor-1);for(g=f,m=0;g<M;)g*=10,m-=1;for(;g>w;)g/=10,m+=1}var S=function(t,e){var n=Math.abs(t).toFixed(e);return"0"!==v&&(n=n.split("").map(function(t){return t>="0"&&t<="9"?i[t.charCodeAt(0)-48]:t}).join("")),n},A=S(st(g,p.maximumFactionalPartSize),p.maximumFactionalPartSize),E=A.indexOf(".");for(-1===E?A+=_:A=A.replace(".",_);A.charAt(0)===v;)A=A.substring(1);for(;A.charAt(A.length-1)===v;)A=A.substring(0,A.length-1);E=A.indexOf(_);var k=p.minimumIntegerPartSize-E,C=p.minimumFactionalPartSize-(A.length-E-1);if(A=(k>0?new Array(k+1).join(v):"")+A,A+=C>0?new Array(C+1).join(v):"",E=A.indexOf(_),p.regularGrouping>0)for(var P=Math.floor((E-1)/p.regularGrouping),T=1;T<=P;T++)A=[A.slice(0,E-T*p.regularGrouping),x,A.slice(E-T*p.regularGrouping)].join("");else p.integerPartGroupingPositions.forEach(function(t){A=[A.slice(0,E-t),x,A.slice(E-t)].join(""),E++});if(E=A.indexOf(_),p.fractionalPartGroupingPositions.forEach(function(t){A=[A.slice(0,t+E+1),x,A.slice(t+E+1)].join("")}),E=A.indexOf(_),-1!==p.picture.indexOf(_)&&E!==A.length-1||(A=A.substring(0,A.length-1)),void 0!==m){var D=S(m,0);(k=p.minimumExponentSize-D.length)>0&&(D=new Array(k+1).join(v)+D),A=A+r["exponent-separator"]+(m<0?b:"")+D}return A=p.prefix+A+p.suffix}}function tt(t,e){if(void 0!==t){if(t=st(t),(e=void 0===e?10:st(e))<2||e>36)throw{code:"D3100",stack:(new Error).stack,value:e};return t.toString(e)}}function et(t){var e;if(void 0!==t){if("number"==typeof t)e=t;else if("string"==typeof t&&/^-?[0-9]+(\.[0-9]+)?([Ee][-+]?[0-9]+)?$/.test(t)&&!isNaN(parseFloat(t))&&isFinite(t))e=parseFloat(t);else if(!0===t)e=1;else{if(!1!==t)throw{code:"D3030",value:t,stack:(new Error).stack,index:1};e=0}return e}}function nt(t){if(void 0!==t)return Math.abs(t)}function rt(t){if(void 0!==t)return Math.floor(t)}function it(t){if(void 0!==t)return Math.ceil(t)}function st(t,e){var n;if(void 0!==t){if(e){var r=t.toString().split("e");t=+(r[0]+"e"+(r[1]?+r[1]+e:e))}var i=(n=Math.round(t))-t;return.5===Math.abs(i)&&1===Math.abs(n%2)&&(n-=1),e&&(r=n.toString().split("e"),n=+(r[0]+"e"+(r[1]?+r[1]-e:-e))),Object.is(n,-0)&&(n=0),n}}function ot(t){if(void 0!==t){if(t<0)throw{stack:(new Error).stack,code:"D3060",index:1,value:t};return Math.sqrt(t)}}function at(t,e){var n;if(void 0!==t){if(n=Math.pow(t,e),!isFinite(n))throw{stack:(new Error).stack,code:"D3061",index:1,value:t,exp:e};return n}}function ct(){return Math.random()}function lt(t){if(void 0!==t){var e=!1;return Array.isArray(t)?1===t.length?e=lt(t[0]):t.length>1&&(e=t.filter(function(t){return lt(t)}).length>0):"string"==typeof t?t.length>0&&(e=!0):m(t)?0!==t&&(e=!0):null!==t&&"object"===r(t)?Object.keys(t).length>0&&(e=!0):"boolean"==typeof t&&!0===t&&(e=!0),e}}function ht(t){if(void 0!==t)return!lt(t)}function dt(t,e,n,r){var i=[e],s=S(t);return s>=2&&i.push(n),s>=3&&i.push(r),i}function ut(t,e){var n,r,s,o;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:n=v(),r=0;case 4:if(!(r<t.length)){i.next=12;break}return s=dt(e,t[r],r,t),i.delegateYield(e.apply(this,s),"t0",7);case 7:void 0!==(o=i.t0)&&n.push(o);case 9:r++,i.next=4;break;case 12:return i.abrupt("return",n);case 13:case"end":return i.stop()}},l,this)}function pt(t,e){var n,r,s,o;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:n=v(),r=0;case 4:if(!(r<t.length)){i.next=13;break}return s=t[r],o=dt(e,s,r,t),i.delegateYield(e.apply(this,o),"t0",8);case 8:lt(i.t0)&&n.push(s);case 10:r++,i.next=4;break;case 13:return i.abrupt("return",n);case 14:case"end":return i.stop()}},h,this)}function ft(t,e){var n,r,s,o,a,c,l;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:n=!1,s=0;case 4:if(!(s<t.length)){i.next=22;break}if(o=t[s],a=!0,void 0===e){i.next=12;break}return c=dt(e,o,s,t),i.delegateYield(e.apply(this,c),"t0",10);case 10:l=i.t0,a=lt(l);case 12:if(!a){i.next=19;break}if(n){i.next=18;break}r=o,n=!0,i.next=19;break;case 18:throw{stack:(new Error).stack,code:"D3138",index:s};case 19:s++,i.next=4;break;case 22:if(n){i.next=24;break}throw{stack:(new Error).stack,code:"D3139"};case 24:return i.abrupt("return",r);case 25:case"end":return i.stop()}},d,this)}function gt(){for(var t=[],e=Array.prototype.slice.call(arguments),n=Math.min.apply(Math,e.map(function(t){return Array.isArray(t)?t.length:0})),r=0;r<n;r++){var i=e.map(function(t){return t[r]});t.push(i)}return t}function mt(t,e,n){var r,s,o,a;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:if(!((s=S(e))<2)){i.next=5;break}throw{stack:(new Error).stack,code:"D3050",index:1};case 5:void 0===n&&t.length>0?(r=t[0],o=1):(r=n,o=0);case 6:if(!(o<t.length)){i.next=15;break}return a=[r,t[o]],s>=3&&a.push(o),s>=4&&a.push(t),i.delegateYield(e.apply(this,a),"t0",11);case 11:r=i.t0,o++,i.next=6;break;case 15:return i.abrupt("return",r);case 16:case"end":return i.stop()}},u,this)}function yt(t){var e=v();if(Array.isArray(t)){var n={};t.forEach(function(t){yt(t).forEach(function(t){n[t]=!0})}),e=yt(n)}else null===t||"object"!==r(t)||w(t)||Object.keys(t).forEach(function(t){return e.push(t)});return e}function bt(t,e){var n;if(Array.isArray(t)){n=v();for(var i=0;i<t.length;i++){var s=bt(t[i],e);void 0!==s&&(Array.isArray(s)?s.forEach(function(t){return n.push(t)}):n.push(s))}}else null!==t&&"object"===r(t)&&(n=t[e]);return n}function vt(t,e){return void 0===t?e:void 0===e?t:(Array.isArray(t)||(t=v(t)),Array.isArray(e)||(e=[e]),t.concat(e))}function _t(t){return void 0!==t}function xt(t){var e=v();if(Array.isArray(t))t.forEach(function(t){e=vt(e,xt(t))});else if(null===t||"object"!==r(t)||w(t))e=t;else for(var n in t){var i={};i[n]=t[n],e.push(i)}return e}function wt(t){if(void 0!==t){var e={};return t.forEach(function(t){for(var n in t)e[n]=t[n]}),e}}function Mt(t){if(void 0!==t){if(t.length<=1)return t;for(var e=t.length,n=new Array(e),r=0;r<e;r++)n[e-r-1]=t[r];return n}}function St(t,e){var n,r,s,o;return i().wrap(function(a){for(;;)switch(a.prev=a.next){case 0:n=v(),a.t0=i().keys(t);case 2:if((a.t1=a.t0()).done){a.next=10;break}return r=a.t1.value,s=dt(e,t[r],r,t),a.delegateYield(e.apply(this,s),"t2",6);case 6:void 0!==(o=a.t2)&&n.push(o),a.next=2;break;case 10:return a.abrupt("return",n);case 11:case"end":return a.stop()}},p,this)}function At(t){throw{code:"D3137",stack:(new Error).stack,message:t||"$error() function evaluated"}}function Et(t,e){if(!t)throw{code:"D3141",stack:(new Error).stack,message:e||"$assert() statement failed"}}function kt(t){if(void 0!==t)return null===t?"null":m(t)?"number":"string"==typeof t?"string":"boolean"==typeof t?"boolean":Array.isArray(t)?"array":x(t)?"function":"object"}function Ct(t,e){var n,r,s,o;return i().wrap(function(a){for(;;)switch(a.prev=a.next){case 0:if(void 0!==t){a.next=2;break}return a.abrupt("return",void 0);case 2:if(!(t.length<=1)){a.next=4;break}return a.abrupt("return",t);case 4:if(void 0!==e){a.next=10;break}if(b(t)||y(t)){a.next=7;break}throw{stack:(new Error).stack,code:"D3070",index:1};case 7:n=i().mark(function t(e,n){return i().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",e>n);case 1:case"end":return t.stop()}},t)}),a.next=11;break;case 10:n=e;case 11:return r=i().mark(function t(e,r){var s,o;return i().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return s=i().mark(function t(e,r,s){return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(0!==r.length){i.next=4;break}Array.prototype.push.apply(e,s),i.next=16;break;case 4:if(0!==s.length){i.next=8;break}Array.prototype.push.apply(e,r),i.next=16;break;case 8:return i.delegateYield(n(r[0],s[0]),"t0",9);case 9:if(!i.t0){i.next=14;break}return e.push(s[0]),i.delegateYield(t(e,r,s.slice(1)),"t1",12);case 12:i.next=16;break;case 14:return e.push(r[0]),i.delegateYield(t(e,r.slice(1),s),"t2",16);case 16:case"end":return i.stop()}},t)}),o=[],t.delegateYield(s(o,e,r),"t0",3);case 3:return t.abrupt("return",o);case 4:case"end":return t.stop()}},t)}),s=i().mark(function t(e){var n,s,o;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(Array.isArray(e)&&!(e.length<=1)){i.next=4;break}return i.abrupt("return",e);case 4:return n=Math.floor(e.length/2),s=e.slice(0,n),o=e.slice(n),i.delegateYield(t(s),"t0",8);case 8:return s=i.t0,i.delegateYield(t(o),"t1",10);case 10:return o=i.t1,i.delegateYield(r(s,o),"t2",12);case 12:return i.abrupt("return",i.t2);case 13:case"end":return i.stop()}},t)}),a.delegateYield(s(t),"t0",14);case 14:return o=a.t0,a.abrupt("return",o);case 16:case"end":return a.stop()}},f)}function Pt(t){if(void 0!==t){if(t.length<=1)return t;for(var e=new Array(t.length),n=0;n<t.length;n++){var r=Math.floor(Math.random()*(n+1));n!==r&&(e[n]=e[r]),e[r]=t[n]}return e}}function Tt(t){if(void 0!==t){if(!Array.isArray(t)||t.length<=1)return t;for(var e=_(t)?v():[],n=0;n<t.length;n++){for(var r=t[n],i=!1,s=0;s<e.length;s++)if(A(r,e[s])){i=!0;break}i||e.push(r)}return e}}function Dt(t,e){var n,r,s,o;return i().wrap(function(a){for(;;)switch(a.prev=a.next){case 0:n={},a.t0=i().keys(t);case 2:if((a.t1=a.t0()).done){a.next=11;break}return r=a.t1.value,s=t[r],o=dt(e,s,r,t),a.delegateYield(e.apply(this,o),"t2",7);case 7:lt(a.t2)&&(n[r]=s),a.next=2;break;case 11:return 0===Object.keys(n).length&&(n=void 0),a.abrupt("return",n);case 13:case"end":return a.stop()}},g,this)}return{sum:k,count:C,max:P,min:T,average:D,string:O,substring:z,substringBefore:I,substringAfter:L,lowercase:j,uppercase:R,length:F,trim:B,pad:N,match:G,contains:V,replace:Y,split:Q,join:Z,formatNumber:J,formatBase:tt,number:et,floor:rt,ceil:it,round:st,abs:nt,sqrt:ot,power:at,random:ct,boolean:lt,not:ht,map:ut,zip:gt,filter:pt,single:ft,foldLeft:mt,sift:Dt,keys:yt,lookup:bt,append:vt,exists:_t,spread:xt,merge:wt,reverse:Mt,each:St,error:At,assert:Et,type:kt,sort:Ct,shuffle:Pt,distinct:Tt,base64encode:U,base64decode:$,encodeUrlComponent:W,encodeUrl:X,decodeUrlComponent:q,decodeUrl:K}}();e.exports=o}).call(this)}).call(this,void 0!==Nr?Nr:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./utils":6}],3:[function(t,e,n){function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */i=function(){return e};var t,e={},n=Object.prototype,s=n.hasOwnProperty,o=Object.defineProperty||function(t,e,n){t[e]=n.value},a="function"==typeof Symbol?Symbol:{},c=a.iterator||"@@iterator",l=a.asyncIterator||"@@asyncIterator",h=a.toStringTag||"@@toStringTag";function d(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{d({},"")}catch(t){d=function(t,e,n){return t[e]=n}}function u(t,e,n,r){var i=e&&e.prototype instanceof v?e:v,s=Object.create(i.prototype),a=new O(r||[]);return o(s,"_invoke",{value:C(t,n,a)}),s}function p(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}e.wrap=u;var f="suspendedStart",g="suspendedYield",m="executing",y="completed",b={};function v(){}function _(){}function x(){}var w={};d(w,c,function(){return this});var M=Object.getPrototypeOf,S=M&&M(M(z([])));S&&S!==n&&s.call(S,c)&&(w=S);var A=x.prototype=v.prototype=Object.create(w);function E(t){["next","throw","return"].forEach(function(e){d(t,e,function(t){return this._invoke(e,t)})})}function k(t,e){function n(i,o,a,c){var l=p(t[i],t,o);if("throw"!==l.type){var h=l.arg,d=h.value;return d&&"object"==r(d)&&s.call(d,"__await")?e.resolve(d.__await).then(function(t){n("next",t,a,c)},function(t){n("throw",t,a,c)}):e.resolve(d).then(function(t){h.value=t,a(h)},function(t){return n("throw",t,a,c)})}c(l.arg)}var i;o(this,"_invoke",{value:function(t,r){function s(){return new e(function(e,i){n(t,r,e,i)})}return i=i?i.then(s,s):s()}})}function C(e,n,r){var i=f;return function(s,o){if(i===m)throw new Error("Generator is already running");if(i===y){if("throw"===s)throw o;return{value:t,done:!0}}for(r.method=s,r.arg=o;;){var a=r.delegate;if(a){var c=P(a,r);if(c){if(c===b)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===f)throw i=y,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=m;var l=p(e,n,r);if("normal"===l.type){if(i=r.done?y:g,l.arg===b)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(i=y,r.method="throw",r.arg=l.arg)}}}function P(e,n){var r=n.method,i=e.iterator[r];if(i===t)return n.delegate=null,"throw"===r&&e.iterator.return&&(n.method="return",n.arg=t,P(e,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),b;var s=p(i,e.iterator,n.arg);if("throw"===s.type)return n.method="throw",n.arg=s.arg,n.delegate=null,b;var o=s.arg;return o?o.done?(n[e.resultName]=o.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=t),n.delegate=null,b):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,b)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function D(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function z(e){if(e||""===e){var n=e[c];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,o=function n(){for(;++i<e.length;)if(s.call(e,i))return n.value=e[i],n.done=!1,n;return n.value=t,n.done=!0,n};return o.next=o}}throw new TypeError(r(e)+" is not iterable")}return _.prototype=x,o(A,"constructor",{value:x,configurable:!0}),o(x,"constructor",{value:_,configurable:!0}),_.displayName=d(x,h,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===_||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,d(t,h,"GeneratorFunction")),t.prototype=Object.create(A),t},e.awrap=function(t){return{__await:t}},E(k.prototype),d(k.prototype,l,function(){return this}),e.AsyncIterator=k,e.async=function(t,n,r,i,s){void 0===s&&(s=Promise);var o=new k(u(t,n,r,i),s);return e.isGeneratorFunction(n)?o:o.next().then(function(t){return t.done?t.value:o.next()})},E(A),d(A,h,"Generator"),d(A,c,function(){return this}),d(A,"toString",function(){return"[object Generator]"}),e.keys=function(t){var e=Object(t),n=[];for(var r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},e.values=z,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(D),!e)for(var n in this)"t"===n.charAt(0)&&s.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function r(r,i){return a.type="throw",a.arg=e,n.next=r,i&&(n.method="next",n.arg=t),!!i}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var c=s.call(o,"catchLoc"),l=s.call(o,"finallyLoc");if(c&&l){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&s.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=t,o.arg=e,i?(this.method="next",this.next=i.finallyLoc,b):this.complete(o)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),b},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),D(n),b}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;D(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,r){return this.delegate={iterator:z(e),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=t),b}},e}var s=t("./datetime"),o=t("./functions"),a=t("./utils"),c=t("./parser"),l=t("./signature"),h=function(){var t=i().mark(N),e=i().mark(H),n=i().mark(G),h=i().mark(Y),d=i().mark(U),u=i().mark($),p=i().mark(W),f=i().mark(X),g=i().mark(st),m=i().mark(ct),y=i().mark(dt),b=i().mark(ut),v=i().mark(pt),_=i().mark(mt),x=i().mark(vt),w=i().mark(_t),M=i().mark(xt),S=i().mark(wt),A=i().mark(St),E=i().mark(Et),k=i().mark(Pt),C=i().mark(Ot),P=a.isNumeric,T=a.isArrayOfStrings,D=a.isArrayOfNumbers,O=a.createSequence,z=a.isSequence,I=a.isFunction,L=a.isLambda,j=a.isIterable,R=a.getFunctionArity,F=a.isDeepEqual,B=It(null);function N(e,n,r){var s,o,a,c;return i().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:(o=r.lookup("__evaluate_entry"))&&o(e,n,r),t.t0=e.type,t.next="path"===t.t0?5:"binary"===t.t0?8:"unary"===t.t0?11:"name"===t.t0?14:"string"===t.t0||"number"===t.t0||"value"===t.t0?16:"wildcard"===t.t0?18:"descendant"===t.t0?20:"parent"===t.t0?22:"condition"===t.t0?24:"block"===t.t0?27:"bind"===t.t0?30:"regex"===t.t0?33:"function"===t.t0?35:"variable"===t.t0?38:"lambda"===t.t0?40:"partial"===t.t0?42:"apply"===t.t0?45:"transform"===t.t0?48:50;break;case 5:return t.delegateYield(H(e,n,r),"t1",6);case 6:return s=t.t1,t.abrupt("break",50);case 8:return t.delegateYield(W(e,n,r),"t2",9);case 9:return s=t.t2,t.abrupt("break",50);case 11:return t.delegateYield(X(e,n,r),"t3",12);case 12:return s=t.t3,t.abrupt("break",50);case 14:return s=q(e,n),t.abrupt("break",50);case 16:return s=K(e),t.abrupt("break",50);case 18:return s=Q(e,n),t.abrupt("break",50);case 20:return s=J(e,n),t.abrupt("break",50);case 22:return s=r.lookup(e.slot.label),t.abrupt("break",50);case 24:return t.delegateYield(ut(e,n,r),"t4",25);case 25:return s=t.t4,t.abrupt("break",50);case 27:return t.delegateYield(pt(e,n,r),"t5",28);case 28:return s=t.t5,t.abrupt("break",50);case 30:return t.delegateYield(dt(e,n,r),"t6",31);case 31:return s=t.t6,t.abrupt("break",50);case 33:return s=ft(e),t.abrupt("break",50);case 35:return t.delegateYield(_t(e,n,r),"t7",36);case 36:return s=t.t7,t.abrupt("break",50);case 38:return s=gt(e,n,r),t.abrupt("break",50);case 40:return s=Mt(e,n,r),t.abrupt("break",50);case 42:return t.delegateYield(St(e,n,r),"t8",43);case 43:return s=t.t8,t.abrupt("break",50);case 45:return t.delegateYield(vt(e,n,r),"t9",46);case 46:return s=t.t9,t.abrupt("break",50);case 48:return s=yt(e,n,r),t.abrupt("break",50);case 50:if(!r.async||null!=s&&"function"==typeof s.then||(s=Promise.resolve(s)),!r.async||"function"!=typeof s.then||!e.nextFunction||"function"!=typeof s[e.nextFunction]){t.next=54;break}t.next=57;break;case 54:return t.next=56,s;case 56:s=t.sent;case 57:if(!Object.prototype.hasOwnProperty.call(e,"predicate")){t.next=65;break}a=0;case 59:if(!(a<e.predicate.length)){t.next=65;break}return t.delegateYield($(e.predicate[a].expr,s,r),"t10",61);case 61:s=t.t10;case 62:a++,t.next=59;break;case 65:if("path"===e.type||!Object.prototype.hasOwnProperty.call(e,"group")){t.next=68;break}return t.delegateYield(ct(e.group,s,r),"t11",67);case 67:s=t.t11;case 68:return(c=r.lookup("__evaluate_exit"))&&c(e,n,r,s),s&&z(s)&&!s.tupleStream&&(e.keepArray&&(s.keepSingleton=!0),0===s.length?s=void 0:1===s.length&&(s=s.keepSingleton?s:s[0])),t.abrupt("return",s);case 72:case"end":return t.stop()}},t)}function H(t,n,r){var s,o,a,c,l,h;return i().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:s=Array.isArray(n)&&"variable"!==t.steps[0].type?n:O(n),a=!1,c=void 0,l=0;case 4:if(!(l<t.steps.length)){e.next=25;break}if((h=t.steps[l]).tuple&&(a=!0),0!==l||!h.consarray){e.next=12;break}return e.delegateYield(N(h,s,r),"t0",9);case 9:o=e.t0,e.next=19;break;case 12:if(!a){e.next=17;break}return e.delegateYield(U(h,s,c,r),"t1",14);case 14:c=e.t1,e.next=19;break;case 17:return e.delegateYield(G(h,s,r,l===t.steps.length-1),"t2",18);case 18:o=e.t2;case 19:if(a||void 0!==o&&0!==o.length){e.next=21;break}return e.abrupt("break",25);case 21:void 0===h.focus&&(s=o);case 22:l++,e.next=4;break;case 25:if(a)if(t.tuple)o=c;else for(o=O(),l=0;l<c.length;l++)o.push(c[l]["@"]);if(t.keepSingletonArray&&(Array.isArray(o)&&o.cons&&!o.sequence&&(o=O(o)),o.keepSingleton=!0),!t.hasOwnProperty("group")){e.next=30;break}return e.delegateYield(ct(t.group,a?c:o,r),"t3",29);case 29:o=e.t3;case 30:return e.abrupt("return",o);case 31:case"end":return e.stop()}},e)}function V(t,e){var n=It(t);for(var r in e)n.bind(r,e[r]);return n}function G(t,e,r,s){var o,a,c,l,h;return i().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if("sort"!==t.type){n.next=7;break}return n.delegateYield(mt(t,e,r),"t0",2);case 2:if(o=n.t0,!t.stages){n.next=6;break}return n.delegateYield(Y(t.stages,o,r),"t1",5);case 5:o=n.t1;case 6:return n.abrupt("return",o);case 7:o=O(),a=0;case 9:if(!(a<e.length)){n.next=24;break}return n.delegateYield(N(t,e[a],r),"t2",11);case 11:if(c=n.t2,!t.stages){n.next=20;break}l=0;case 14:if(!(l<t.stages.length)){n.next=20;break}return n.delegateYield($(t.stages[l].expr,c,r),"t3",16);case 16:c=n.t3;case 17:l++,n.next=14;break;case 20:void 0!==c&&o.push(c);case 21:a++,n.next=9;break;case 24:return h=O(),s&&1===o.length&&Array.isArray(o[0])&&!z(o[0])?h=o[0]:o.forEach(function(t){!Array.isArray(t)||t.cons?h.push(t):t.forEach(function(t){return h.push(t)})}),n.abrupt("return",h);case 27:case"end":return n.stop()}},n)}function Y(t,e,n){var r,s,o,a;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:r=e,s=0;case 2:if(!(s<t.length)){i.next=15;break}o=t[s],i.t0=o.type,i.next="filter"===i.t0?7:"index"===i.t0?10:12;break;case 7:return i.delegateYield($(o.expr,r,n),"t1",8);case 8:return r=i.t1,i.abrupt("break",12);case 10:for(a=0;a<r.length;a++)r[a][o.value]=a;return i.abrupt("break",12);case 12:s++,i.next=2;break;case 15:return i.abrupt("return",r);case 16:case"end":return i.stop()}},h)}function U(t,e,n,r){var s,o,a,c,l,h,u,p;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if("sort"!==t.type){i.next=15;break}if(!n){i.next=6;break}return i.delegateYield(mt(t,n,r),"t0",3);case 3:s=i.t0,i.next=11;break;case 6:return i.delegateYield(mt(t,e,r),"t1",7);case 7:for(o=i.t1,(s=O()).tupleStream=!0,a=0;a<o.length;a++)(c={"@":o[a]})[t.index]=a,s.push(c);case 11:if(!t.stages){i.next=14;break}return i.delegateYield(Y(t.stages,s,r),"t2",13);case 13:s=i.t2;case 14:return i.abrupt("return",s);case 15:(s=O()).tupleStream=!0,l=r,void 0===n&&(n=e.map(function(t){return{"@":t}})),h=0;case 20:if(!(h<n.length)){i.next=28;break}return l=V(r,n[h]),i.delegateYield(N(t,n[h]["@"],l),"t3",23);case 23:if(void 0!==(u=i.t3))for(Array.isArray(u)||(u=[u]),p=0;p<u.length;p++)c={},Object.assign(c,n[h]),u.tupleStream?Object.assign(c,u[p]):(t.focus?(c[t.focus]=u[p],c["@"]=n[h]["@"]):c["@"]=u[p],t.index&&(c[t.index]=p),t.ancestor&&(c[t.ancestor.label]=n[h]["@"])),s.push(c);case 25:h++,i.next=20;break;case 28:if(!t.stages){i.next=31;break}return i.delegateYield(Y(t.stages,s,r),"t4",30);case 30:s=i.t4;case 31:return i.abrupt("return",s);case 32:case"end":return i.stop()}},d)}function $(t,e,n){var r,s,a,c,l,h;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(r=O(),e&&e.tupleStream&&(r.tupleStream=!0),Array.isArray(e)||(e=O(e)),"number"!==t.type){i.next=10;break}(s=Math.floor(t.value))<0&&(s=e.length+s),void 0!==(a=e[s])&&(Array.isArray(a)?r=a:r.push(a)),i.next=23;break;case 10:s=0;case 11:if(!(s<e.length)){i.next=23;break}return a=e[s],c=a,l=n,e.tupleStream&&(c=a["@"],l=V(n,a)),i.delegateYield(N(t,c,l),"t0",17);case 17:h=i.t0,P(h)&&(h=[h]),D(h)?h.forEach(function(t){var n=Math.floor(t);n<0&&(n=e.length+n),n===s&&r.push(a)}):o.boolean(h)&&r.push(a);case 20:s++,i.next=11;break;case 23:return i.abrupt("return",r);case 24:case"end":return i.stop()}},u)}function W(t,e,n){var r,s,o,a,c;return i().wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return l.delegateYield(N(t.lhs,e,n),"t0",1);case 1:if(s=l.t0,o=t.value,a=i().mark(function r(){return i().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.delegateYield(N(t.rhs,e,n),"t0",1);case 1:return r.abrupt("return",r.t0);case 2:case"end":return r.stop()}},r)}),"and"!==o&&"or"!==o){l.next=15;break}return l.prev=5,l.delegateYield(st(s,a,o),"t1",7);case 7:return l.abrupt("return",l.t1);case 10:throw l.prev=10,l.t2=l.catch(5),l.t2.position=t.position,l.t2.token=o,l.t2;case 15:return l.delegateYield(a(),"t3",16);case 16:c=l.t3,l.prev=17,l.t4=o,l.next="+"===l.t4||"-"===l.t4||"*"===l.t4||"/"===l.t4||"%"===l.t4?21:"="===l.t4||"!="===l.t4?23:"<"===l.t4||"<="===l.t4||">"===l.t4||">="===l.t4?25:"&"===l.t4?27:".."===l.t4?29:"in"===l.t4?31:33;break;case 21:return r=et(s,c,o),l.abrupt("break",33);case 23:return r=nt(s,c,o),l.abrupt("break",33);case 25:return r=rt(s,c,o),l.abrupt("break",33);case 27:return r=at(s,c),l.abrupt("break",33);case 29:return r=ht(s,c),l.abrupt("break",33);case 31:return r=it(s,c),l.abrupt("break",33);case 33:l.next=40;break;case 35:throw l.prev=35,l.t5=l.catch(17),l.t5.position=t.position,l.t5.token=o,l.t5;case 40:return l.abrupt("return",r);case 41:case"end":return l.stop()}},p,null,[[5,10],[17,35]])}function X(t,e,n){var r,s,a,c;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:i.t0=t.value,i.next="-"===i.t0?3:"["===i.t0?15:"{"===i.t0?27:30;break;case 3:return i.delegateYield(N(t.expression,e,n),"t1",4);case 4:if(void 0!==(r=i.t1)){i.next=9;break}r=void 0,i.next=14;break;case 9:if(!P(r)){i.next=13;break}r=-r,i.next=14;break;case 13:throw{code:"D1002",stack:(new Error).stack,position:t.position,token:t.value,value:r};case 14:return i.abrupt("break",30);case 15:r=[],s=0;case 17:if(!(s<t.expressions.length)){i.next=25;break}return a=t.expressions[s],i.delegateYield(N(a,e,n),"t2",20);case 20:void 0!==(c=i.t2)&&("["===a.value?r.push(c):r=o.append(r,c));case 22:s++,i.next=17;break;case 25:return t.consarray&&Object.defineProperty(r,"cons",{enumerable:!1,configurable:!1,value:!0}),i.abrupt("break",30);case 27:return i.delegateYield(ct(t,e,n),"t3",28);case 28:return r=i.t3,i.abrupt("break",30);case 30:return i.abrupt("return",r);case 31:case"end":return i.stop()}},f)}function q(t,e,n){return o.lookup(e,t.value)}function K(t){return t.value}function Q(t,e){var n=O();return Array.isArray(e)&&e.outerWrapper&&e.length>0&&(e=e[0]),null!==e&&"object"===r(e)&&Object.keys(e).forEach(function(t){var r=e[t];Array.isArray(r)?(r=Z(r),n=o.append(n,r)):n.push(r)}),n}function Z(t,e){return void 0===e&&(e=[]),Array.isArray(t)?t.forEach(function(t){Z(t,e)}):e.push(t),e}function J(t,e){var n,r=O();return void 0!==e&&(tt(e,r),n=1===r.length?r[0]:r),n}function tt(t,e){Array.isArray(t)||e.push(t),Array.isArray(t)?t.forEach(function(t){tt(t,e)}):null!==t&&"object"===r(t)&&Object.keys(t).forEach(function(n){tt(t[n],e)})}function et(t,e,n){var r;if(void 0!==t&&!P(t))throw{code:"T2001",stack:(new Error).stack,value:t};if(void 0!==e&&!P(e))throw{code:"T2002",stack:(new Error).stack,value:e};if(void 0===t||void 0===e)return r;switch(n){case"+":r=t+e;break;case"-":r=t-e;break;case"*":r=t*e;break;case"/":r=t/e;break;case"%":r=t%e}return r}function nt(t,e,n){var i,s=r(t),o=r(e);if("undefined"===s||"undefined"===o)return!1;switch(n){case"=":i=F(t,e);break;case"!=":i=!F(t,e)}return i}function rt(t,e,n){var i,s=r(t),o=r(e);if("undefined"!==s&&"string"!==s&&"number"!==s||"undefined"!==o&&"string"!==o&&"number"!==o)throw{code:"T2010",stack:(new Error).stack,value:"string"!==s&&"number"!==s?t:e};if("undefined"!==s&&"undefined"!==o){if(s!==o)throw{code:"T2009",stack:(new Error).stack,value:t,value2:e};switch(n){case"<":i=t<e;break;case"<=":i=t<=e;break;case">":i=t>e;break;case">=":i=t>=e}return i}}function it(t,e){var n=!1;if(void 0===t||void 0===e)return!1;Array.isArray(e)||(e=[e]);for(var r=0;r<e.length;r++)if(e[r]===t){n=!0;break}return n}function st(t,e,n){var r,s;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:s=ot(t),i.t0=n,i.next="and"===i.t0?4:"or"===i.t0?12:20;break;case 4:if(i.t1=s,!i.t1){i.next=10;break}return i.t2=ot,i.delegateYield(e(),"t3",8);case 8:i.t4=i.t3,i.t1=(0,i.t2)(i.t4);case 10:return r=i.t1,i.abrupt("break",20);case 12:if(i.t5=s,i.t5){i.next=18;break}return i.t6=ot,i.delegateYield(e(),"t7",16);case 16:i.t8=i.t7,i.t5=(0,i.t6)(i.t8);case 18:return r=i.t5,i.abrupt("break",20);case 20:return i.abrupt("return",r);case 21:case"end":return i.stop()}},g)}function ot(t){var e=o.boolean(t);return void 0!==e&&e}function at(t,e){var n="",r="";return void 0!==t&&(n=o.string(t)),void 0!==e&&(r=o.string(e)),n.concat(r)}function ct(t,e,n){var r,s,a,c,l,h,d,u,p,f,g,y,b;return i().wrap(function(m){for(;;)switch(m.prev=m.next){case 0:r={},s={},a=!(!e||!e.tupleStream),Array.isArray(e)||(e=O(e)),0===e.length&&e.push(void 0),c=0;case 6:if(!(c<e.length)){m.next=31;break}l=e[c],h=a?V(n,l):n,d=0;case 10:if(!(d<t.lhs.length)){m.next=28;break}return u=t.lhs[d],m.delegateYield(N(u[0],a?l["@"]:l,h),"t0",13);case 13:if("string"==typeof(p=m.t0)||void 0===p){m.next=16;break}throw{code:"T1003",stack:(new Error).stack,position:t.position,value:p};case 16:if(void 0===p){m.next=25;break}if(f={data:l,exprIndex:d},!s.hasOwnProperty(p)){m.next=24;break}if(s[p].exprIndex===d){m.next=21;break}throw{code:"D1009",stack:(new Error).stack,position:t.position,value:p};case 21:s[p].data=o.append(s[p].data,l),m.next=25;break;case 24:s[p]=f;case 25:d++,m.next=10;break;case 28:c++,m.next=6;break;case 31:m.t1=i().keys(s);case 32:if((m.t2=m.t1()).done){m.next=43;break}return p=m.t2.value,f=s[p],g=f.data,h=n,a&&(y=lt(f.data),g=y["@"],delete y["@"],h=V(n,y)),m.delegateYield(N(t.lhs[f.exprIndex][1],g,h),"t3",39);case 39:void 0!==(b=m.t3)&&(r[p]=b),m.next=32;break;case 43:return m.abrupt("return",r);case 44:case"end":return m.stop()}},m)}function lt(t){if(!Array.isArray(t))return t;var e={};Object.assign(e,t[0]);for(var n=1;n<t.length;n++)for(var r in t[n])e[r]=o.append(e[r],t[n][r]);return e}function ht(t,e){var n;if(void 0!==t&&!Number.isInteger(t))throw{code:"T2003",stack:(new Error).stack,value:t};if(void 0!==e&&!Number.isInteger(e))throw{code:"T2004",stack:(new Error).stack,value:e};if(void 0===t||void 0===e)return n;if(t>e)return n;var r=e-t+1;if(r>1e7)throw{code:"D2014",stack:(new Error).stack,value:r};n=new Array(r);for(var i=t,s=0;i<=e;i++,s++)n[s]=i;return n.sequence=!0,n}function dt(t,e,n){var r;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return i.delegateYield(N(t.rhs,e,n),"t0",1);case 1:return r=i.t0,n.bind(t.lhs.value,r),i.abrupt("return",r);case 4:case"end":return i.stop()}},y)}function ut(t,e,n){var r,s;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return i.delegateYield(N(t.condition,e,n),"t0",1);case 1:if(s=i.t0,!o.boolean(s)){i.next=7;break}return i.delegateYield(N(t.then,e,n),"t1",4);case 4:r=i.t1,i.next=10;break;case 7:if(void 0===t.else){i.next=10;break}return i.delegateYield(N(t.else,e,n),"t2",9);case 9:r=i.t2;case 10:return i.abrupt("return",r);case 11:case"end":return i.stop()}},b)}function pt(t,e,n){var r,s,o;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:s=It(n),o=0;case 2:if(!(o<t.expressions.length)){i.next=8;break}return i.delegateYield(N(t.expressions[o],e,s),"t0",4);case 4:r=i.t0;case 5:o++,i.next=2;break;case 8:return i.abrupt("return",r);case 9:case"end":return i.stop()}},v)}function ft(t){var e=new Rt.RegexEngine(t.value),n=function n(r,i){var s;e.lastIndex=i||0;var o=e.exec(r);if(null!==o){if(s={match:o[0],start:o.index,end:o.index+o[0].length,groups:[]},o.length>1)for(var a=1;a<o.length;a++)s.groups.push(o[a]);s.next=function(){if(!(e.lastIndex>=r.length)){var i=n(r,e.lastIndex);if(i&&""===i.match)throw{code:"D1004",stack:(new Error).stack,position:t.position,value:t.value.source};return i}}}return s};return n}function gt(t,e,n){return""===t.value?e&&e.outerWrapper?e[0]:e:n.lookup(t.value)}function mt(t,e,n){var s,a,c,l,h;return i().wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return a=e,c=!!e.tupleStream,l=i().mark(function e(s,o){var a,l,h,d,u,p,f,g,m;return i().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:a=0,l=0;case 2:if(!(0===a&&l<t.terms.length)){e.next=35;break}return h=t.terms[l],d=s,u=n,c&&(d=s["@"],u=V(n,s)),e.delegateYield(N(h.expression,d,u),"t0",8);case 8:return p=e.t0,d=o,u=n,c&&(d=o["@"],u=V(n,o)),e.delegateYield(N(h.expression,d,u),"t1",13);case 13:if(f=e.t1,g=r(p),m=r(f),"undefined"!==g){e.next=19;break}return a="undefined"===m?0:1,e.abrupt("continue",32);case 19:if("undefined"!==m){e.next=22;break}return a=-1,e.abrupt("continue",32);case 22:if(!("string"!==g&&"number"!==g||"string"!==m&&"number"!==m)){e.next=24;break}throw{code:"T2008",stack:(new Error).stack,position:t.position,value:"string"!==g&&"number"!==g?p:f};case 24:if(g===m){e.next=26;break}throw{code:"T2007",stack:(new Error).stack,position:t.position,value:p,value2:f};case 26:if(p!==f){e.next=30;break}return e.abrupt("continue",32);case 30:a=p<f?-1:1;case 31:!0===h.descending&&(a=-a);case 32:l++,e.next=2;break;case 35:return e.abrupt("return",1===a);case 36:case"end":return e.stop()}},e)}),h={environment:n,input:e},d.delegateYield(o.sort.apply(h,[a,l]),"t0",5);case 5:return s=d.t0,d.abrupt("return",s);case 7:case"end":return d.stop()}},_)}function yt(t,e,n){var s=i().mark(function e(s){var o,a,c,l,h,d,u,p,f,g,m;return i().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==s){e.next=2;break}return e.abrupt("return",void 0);case 2:if(o=n.lookup("clone"),I(o)){e.next=5;break}throw{code:"T2013",stack:(new Error).stack,position:t.position};case 5:return e.delegateYield(xt(o,[s],null,n),"t0",6);case 6:return a=e.t0,e.delegateYield(N(t.pattern,a,n),"t1",8);case 8:if(void 0===(c=e.t1)){e.next=35;break}Array.isArray(c)||(c=[c]),l=0;case 12:if(!(l<c.length)){e.next=35;break}if(!(h=c[l])||!(h.isPrototypeOf(a)||h instanceof Object.constructor)){e.next=16;break}throw{code:"D1010",stack:(new Error).stack,position:t.position};case 16:return e.delegateYield(N(t.update,h,n),"t2",17);case 17:if(d=e.t2,"undefined"===(u=r(d))){e.next=23;break}if("object"===u&&null!==d&&!Array.isArray(d)){e.next=22;break}throw{code:"T2011",stack:(new Error).stack,position:t.update.position,value:d};case 22:for(p in d)h[p]=d[p];case 23:if(void 0===t.delete){e.next=32;break}return e.delegateYield(N(t.delete,h,n),"t3",25);case 25:if(void 0===(f=e.t3)){e.next=32;break}if(g=f,Array.isArray(f)||(f=[f]),T(f)){e.next=31;break}throw{code:"T2012",stack:(new Error).stack,position:t.delete.position,value:g};case 31:for(m=0;m<f.length;m++)"object"===r(h)&&null!==h&&delete h[f[m]];case 32:l++,e.next=12;break;case 35:return e.abrupt("return",a);case 36:case"end":return e.stop()}},e)});return Dt(s,"<(oa):o>")}var bt=c("function($f, $g) { function($x){ $g($f($x)) } }");function vt(t,e,n){var r,s,o,a;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return i.delegateYield(N(t.lhs,e,n),"t0",1);case 1:if(s=i.t0,"function"!==t.rhs.type){i.next=7;break}return i.delegateYield(_t(t.rhs,e,n,{context:s}),"t1",4);case 4:r=i.t1,i.next=20;break;case 7:return i.delegateYield(N(t.rhs,e,n),"t2",8);case 8:if(o=i.t2,I(o)){i.next=11;break}throw{code:"T2006",stack:(new Error).stack,position:t.position,value:o};case 11:if(!I(s)){i.next=18;break}return i.delegateYield(N(bt,null,n),"t3",13);case 13:return a=i.t3,i.delegateYield(xt(a,[s,o],null,n),"t4",15);case 15:r=i.t4,i.next=20;break;case 18:return i.delegateYield(xt(o,[s],null,n),"t5",19);case 19:r=i.t5;case 20:return i.abrupt("return",r);case 21:case"end":return i.stop()}},x)}function _t(t,e,n,s){var o,a,c,l,h,d;return i().wrap(function(u){for(;;)switch(u.prev=u.next){case 0:return u.delegateYield(N(t.procedure,e,n),"t0",1);case 1:if(void 0!==(a=u.t0)||"path"!==t.procedure.type||!n.lookup(t.procedure.steps[0].value)){u.next=4;break}throw{code:"T1005",stack:(new Error).stack,position:t.position,token:t.procedure.steps[0].value};case 4:c=[],void 0!==s&&c.push(s.context),l=i().mark(function r(){var s,o;return i().wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return r.delegateYield(N(t.arguments[h],e,n),"t0",1);case 1:s=r.t0,I(s)?(o=i().mark(function t(){var e,r,o,a=arguments;return i().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:for(e=a.length,r=new Array(e),o=0;o<e;o++)r[o]=a[o];return t.delegateYield(xt(s,r,null,n),"t0",2);case 2:return t.abrupt("return",t.t0);case 3:case"end":return t.stop()}},t)}),o.arity=R(s),c.push(o)):c.push(s);case 3:case"end":return r.stop()}},r)}),h=0;case 8:if(!(h<t.arguments.length)){u.next=13;break}return u.delegateYield(l(),"t1",10);case 10:h++,u.next=8;break;case 13:return d="path"===t.procedure.type?t.procedure.steps[0].value:t.procedure.value,u.prev=14,"object"===r(a)&&(a.token=d,a.position=t.position),u.delegateYield(xt(a,c,e,n),"t2",17);case 17:o=u.t2,u.next=25;break;case 20:throw u.prev=20,u.t3=u.catch(14),u.t3.position||(u.t3.position=t.position),u.t3.token||(u.t3.token=d),u.t3;case 25:return u.abrupt("return",o);case 26:case"end":return u.stop()}},w,null,[[14,20]])}function xt(t,e,n,r){var s,o,a,c;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return i.delegateYield(wt(t,e,n,r),"t0",1);case 1:s=i.t0;case 2:if(!L(s)||!0!==s.thunk){i.next=21;break}return i.delegateYield(N(s.body.procedure,s.input,s.environment),"t1",4);case 4:o=i.t1,"variable"===s.body.procedure.type&&(o.token=s.body.procedure.value),o.position=s.body.procedure.position,a=[],c=0;case 9:if(!(c<s.body.arguments.length)){i.next=17;break}return i.t2=a,i.delegateYield(N(s.body.arguments[c],s.input,s.environment),"t3",12);case 12:i.t4=i.t3,i.t2.push.call(i.t2,i.t4);case 14:c++,i.next=9;break;case 17:return i.delegateYield(wt(o,a,n,r),"t5",18);case 18:s=i.t5,i.next=2;break;case 21:return i.abrupt("return",s);case 22:case"end":return i.stop()}},M)}function wt(t,e,n,r){var s,o,a;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(i.prev=0,o=e,t&&(o=At(t.signature,e,n)),!L(t)){i.next=8;break}return i.delegateYield(Et(t,o),"t0",5);case 5:s=i.t0,i.next=24;break;case 8:if(!t||!0!==t._jsonata_function){i.next=16;break}if(a={environment:r,input:n},s=t.implementation.apply(a,o),!j(s)){i.next=14;break}return i.delegateYield(s,"t1",13);case 13:s=i.t1;case 14:i.next=24;break;case 16:if("function"!=typeof t){i.next=23;break}if(s=t.apply(n,o),!j(s)){i.next=21;break}return i.delegateYield(s,"t2",20);case 20:s=i.t2;case 21:i.next=24;break;case 23:throw{code:"T1006",stack:(new Error).stack};case 24:i.next=30;break;case 26:throw i.prev=26,i.t3=i.catch(0),t&&(void 0===i.t3.token&&void 0!==t.token&&(i.t3.token=t.token),i.t3.position=t.position||i.t3.position),i.t3;case 30:return i.abrupt("return",s);case 31:case"end":return i.stop()}},S,null,[[0,26]])}function Mt(t,e,n){var r={_jsonata_lambda:!0,input:e,environment:n,arguments:t.arguments,signature:t.signature,body:t.body};return!0===t.thunk&&(r.thunk=!0),r.apply=i().mark(function t(n,s){return i().wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.delegateYield(xt(r,s,e,n.environment),"t0",1);case 1:return t.abrupt("return",t.t0);case 2:case"end":return t.stop()}},t)}),r}function St(t,e,n){var r,s,o,a,c;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:s=[],o=0;case 2:if(!(o<t.arguments.length)){i.next=15;break}if("operator"!==(a=t.arguments[o]).type||"?"!==a.value){i.next=8;break}s.push(a),i.next=12;break;case 8:return i.t0=s,i.delegateYield(N(a,e,n),"t1",10);case 10:i.t2=i.t1,i.t0.push.call(i.t0,i.t2);case 12:o++,i.next=2;break;case 15:return i.delegateYield(N(t.procedure,e,n),"t3",16);case 16:if(void 0!==(c=i.t3)||"path"!==t.procedure.type||!n.lookup(t.procedure.steps[0].value)){i.next=19;break}throw{code:"T1007",stack:(new Error).stack,position:t.position,token:t.procedure.steps[0].value};case 19:if(!L(c)){i.next=23;break}r=kt(c,s),i.next=32;break;case 23:if(!c||!0!==c._jsonata_function){i.next=27;break}r=Ct(c.implementation,s),i.next=32;break;case 27:if("function"!=typeof c){i.next=31;break}r=Ct(c,s),i.next=32;break;case 31:throw{code:"T1008",stack:(new Error).stack,position:t.position,token:"path"===t.procedure.type?t.procedure.steps[0].value:t.procedure.value};case 32:return i.abrupt("return",r);case 33:case"end":return i.stop()}},A)}function At(t,e,n){return void 0===t?e:t.validate(e,n)}function Et(t,e){var n,r;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(r=It(t.environment),t.arguments.forEach(function(t,n){r.bind(t.value,e[n])}),"function"!=typeof t.body){i.next=7;break}return i.delegateYield(Pt(t.body,r),"t0",4);case 4:n=i.t0,i.next=9;break;case 7:return i.delegateYield(N(t.body,t.input,r),"t1",8);case 8:n=i.t1;case 9:return i.abrupt("return",n);case 10:case"end":return i.stop()}},E)}function kt(t,e){var n=It(t.environment),r=[];return t.arguments.forEach(function(t,i){var s=e[i];s&&"operator"===s.type&&"?"===s.value?r.push(t):n.bind(t.value,s)}),{_jsonata_lambda:!0,input:t.input,environment:n,arguments:r,body:t.body}}function Ct(t,e){var n=Tt(t),r="function("+(n=n.map(function(t){return"$"+t.trim()})).join(", ")+"){ _ }",i=c(r);return i.body=t,kt(i,e)}function Pt(t,e){var n,r,s,o;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(n=Tt(t),r=n.map(function(t){return e.lookup(t.trim())}),s={environment:e},o=t.apply(s,r),!j(o)){i.next=7;break}return i.delegateYield(o,"t0",6);case 6:o=i.t0;case 7:return i.abrupt("return",o);case 8:case"end":return i.stop()}},k)}function Tt(t){var e=t.toString();return/\(([^)]*)\)/.exec(e)[1].split(",")}function Dt(t,e){var n={_jsonata_function:!0,implementation:t};return void 0!==e&&(n.signature=l(e)),n}function Ot(t,e){var n,r,s;return i().wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(void 0!==t){i.next=2;break}return i.abrupt("return",void 0);case 2:n=this.input,void 0!==e&&(n=e,Array.isArray(n)&&!z(n)&&((n=O(n)).outerWrapper=!0)),i.prev=4,r=c(t,!1),i.next=12;break;case 8:throw i.prev=8,i.t0=i.catch(4),jt(i.t0),{stack:(new Error).stack,code:"D3120",value:i.t0.message,error:i.t0};case 12:return i.prev=12,i.delegateYield(N(r,n,this.environment),"t1",14);case 14:s=i.t1,i.next=21;break;case 17:throw i.prev=17,i.t2=i.catch(12),jt(i.t2),{stack:(new Error).stack,code:"D3121",value:i.t2.message,error:i.t2};case 21:return i.abrupt("return",s);case 22:case"end":return i.stop()}},C,this,[[4,8],[12,17]])}function zt(t){if(void 0!==t)return JSON.parse(o.string(t))}function It(t){var e={};return{bind:function(t,n){e[t]=n},lookup:function(n){var r;return e.hasOwnProperty(n)?r=e[n]:t&&(r=t.lookup(n)),r},timestamp:t?t.timestamp:null,async:!!t&&t.async,global:t?t.global:{ancestry:[null]}}}B.bind("sum",Dt(o.sum,"<a<n>:n>")),B.bind("count",Dt(o.count,"<a:n>")),B.bind("max",Dt(o.max,"<a<n>:n>")),B.bind("min",Dt(o.min,"<a<n>:n>")),B.bind("average",Dt(o.average,"<a<n>:n>")),B.bind("string",Dt(o.string,"<x-b?:s>")),B.bind("substring",Dt(o.substring,"<s-nn?:s>")),B.bind("substringBefore",Dt(o.substringBefore,"<s-s:s>")),B.bind("substringAfter",Dt(o.substringAfter,"<s-s:s>")),B.bind("lowercase",Dt(o.lowercase,"<s-:s>")),B.bind("uppercase",Dt(o.uppercase,"<s-:s>")),B.bind("length",Dt(o.length,"<s-:n>")),B.bind("trim",Dt(o.trim,"<s-:s>")),B.bind("pad",Dt(o.pad,"<s-ns?:s>")),B.bind("match",Dt(o.match,"<s-f<s:o>n?:a<o>>")),B.bind("contains",Dt(o.contains,"<s-(sf):b>")),B.bind("replace",Dt(o.replace,"<s-(sf)(sf)n?:s>")),B.bind("split",Dt(o.split,"<s-(sf)n?:a<s>>")),B.bind("join",Dt(o.join,"<a<s>s?:s>")),B.bind("formatNumber",Dt(o.formatNumber,"<n-so?:s>")),B.bind("formatBase",Dt(o.formatBase,"<n-n?:s>")),B.bind("formatInteger",Dt(s.formatInteger,"<n-s:s>")),B.bind("parseInteger",Dt(s.parseInteger,"<s-s:n>")),B.bind("number",Dt(o.number,"<(nsb)-:n>")),B.bind("floor",Dt(o.floor,"<n-:n>")),B.bind("ceil",Dt(o.ceil,"<n-:n>")),B.bind("round",Dt(o.round,"<n-n?:n>")),B.bind("abs",Dt(o.abs,"<n-:n>")),B.bind("sqrt",Dt(o.sqrt,"<n-:n>")),B.bind("power",Dt(o.power,"<n-n:n>")),B.bind("random",Dt(o.random,"<:n>")),B.bind("boolean",Dt(o.boolean,"<x-:b>")),B.bind("not",Dt(o.not,"<x-:b>")),B.bind("map",Dt(o.map,"<af>")),B.bind("zip",Dt(o.zip,"<a+>")),B.bind("filter",Dt(o.filter,"<af>")),B.bind("single",Dt(o.single,"<af?>")),B.bind("reduce",Dt(o.foldLeft,"<afj?:j>")),B.bind("sift",Dt(o.sift,"<o-f?:o>")),B.bind("keys",Dt(o.keys,"<x-:a<s>>")),B.bind("lookup",Dt(o.lookup,"<x-s:x>")),B.bind("append",Dt(o.append,"<xx:a>")),B.bind("exists",Dt(o.exists,"<x:b>")),B.bind("spread",Dt(o.spread,"<x-:a<o>>")),B.bind("merge",Dt(o.merge,"<a<o>:o>")),B.bind("reverse",Dt(o.reverse,"<a:a>")),B.bind("each",Dt(o.each,"<o-f:a>")),B.bind("error",Dt(o.error,"<s?:x>")),B.bind("assert",Dt(o.assert,"<bs?:x>")),B.bind("type",Dt(o.type,"<x:s>")),B.bind("sort",Dt(o.sort,"<af?:a>")),B.bind("shuffle",Dt(o.shuffle,"<a:a>")),B.bind("distinct",Dt(o.distinct,"<x:x>")),B.bind("base64encode",Dt(o.base64encode,"<s-:s>")),B.bind("base64decode",Dt(o.base64decode,"<s-:s>")),B.bind("encodeUrlComponent",Dt(o.encodeUrlComponent,"<s-:s>")),B.bind("encodeUrl",Dt(o.encodeUrl,"<s-:s>")),B.bind("decodeUrlComponent",Dt(o.decodeUrlComponent,"<s-:s>")),B.bind("decodeUrl",Dt(o.decodeUrl,"<s-:s>")),B.bind("eval",Dt(Ot,"<sx?:x>")),B.bind("toMillis",Dt(s.toMillis,"<s-s?:n>")),B.bind("fromMillis",Dt(s.fromMillis,"<n-s?s?:s>")),B.bind("clone",Dt(zt,"<(oa)-:o>"));var Lt={S0101:"String literal must be terminated by a matching quote",S0102:"Number out of range: {{token}}",S0103:"Unsupported escape sequence: \\{{token}}",S0104:"The escape sequence \\u must be followed by 4 hex digits",S0105:"Quoted property name must be terminated with a backquote (`)",S0106:"Comment has no closing tag",S0201:"Syntax error: {{token}}",S0202:"Expected {{value}}, got {{token}}",S0203:"Expected {{value}} before end of expression",S0204:"Unknown operator: {{token}}",S0205:"Unexpected token: {{token}}",S0206:"Unknown expression type: {{token}}",S0207:"Unexpected end of expression",S0208:"Parameter {{value}} of function definition must be a variable name (start with $)",S0209:"A predicate cannot follow a grouping expression in a step",S0210:"Each step can only have one grouping expression",S0211:"The symbol {{token}} cannot be used as a unary operator",S0212:"The left side of := must be a variable name (start with $)",S0213:"The literal value {{value}} cannot be used as a step within a path expression",S0214:"The right side of {{token}} must be a variable name (start with $)",S0215:"A context variable binding must precede any predicates on a step",S0216:"A context variable binding must precede the 'order-by' clause on a step",S0217:"The object representing the 'parent' cannot be derived from this expression",S0301:"Empty regular expressions are not allowed",S0302:"No terminating / in regular expression",S0402:"Choice groups containing parameterized types are not supported",S0401:"Type parameters can only be applied to functions and arrays",S0500:"Attempted to evaluate an expression containing syntax error(s)",T0410:"Argument {{index}} of function {{token}} does not match function signature",T0411:"Context value is not a compatible type with argument {{index}} of function {{token}}",T0412:"Argument {{index}} of function {{token}} must be an array of {{type}}",D1001:"Number out of range: {{value}}",D1002:"Cannot negate a non-numeric value: {{value}}",T1003:"Key in object structure must evaluate to a string; got: {{value}}",D1004:"Regular expression matches zero length string",T1005:"Attempted to invoke a non-function. Did you mean ${{{token}}}?",T1006:"Attempted to invoke a non-function",T1007:"Attempted to partially apply a non-function. Did you mean ${{{token}}}?",T1008:"Attempted to partially apply a non-function",D1009:"Multiple key definitions evaluate to same key: {{value}}",D1010:"Attempted to access the Javascript object prototype",T1010:"The matcher function argument passed to function {{token}} does not return the correct object structure",T2001:"The left side of the {{token}} operator must evaluate to a number",T2002:"The right side of the {{token}} operator must evaluate to a number",T2003:"The left side of the range operator (..) must evaluate to an integer",T2004:"The right side of the range operator (..) must evaluate to an integer",D2005:"The left side of := must be a variable name (start with $)",T2006:"The right side of the function application operator ~> must be a function",T2007:"Type mismatch when comparing values {{value}} and {{value2}} in order-by clause",T2008:"The expressions within an order-by clause must evaluate to numeric or string values",T2009:"The values {{value}} and {{value2}} either side of operator {{token}} must be of the same data type",T2010:"The expressions either side of operator {{token}} must evaluate to numeric or string values",T2011:"The insert/update clause of the transform expression must evaluate to an object: {{value}}",T2012:"The delete clause of the transform expression must evaluate to a string or array of strings: {{value}}",T2013:"The transform expression clones the input object using the $clone() function. This has been overridden in the current scope by a non-function.",D2014:"The size of the sequence allocated by the range operator (..) must not exceed 1e6. Attempted to allocate {{value}}.",D3001:"Attempting to invoke string function on Infinity or NaN",D3010:"Second argument of replace function cannot be an empty string",D3011:"Fourth argument of replace function must evaluate to a positive number",D3012:"Attempted to replace a matched string with a non-string value",D3020:"Third argument of split function must evaluate to a positive number",D3030:"Unable to cast value to a number: {{value}}",D3040:"Third argument of match function must evaluate to a positive number",D3050:"The second argument of reduce function must be a function with at least two arguments",D3060:"The sqrt function cannot be applied to a negative number: {{value}}",D3061:"The power function has resulted in a value that cannot be represented as a JSON number: base={{value}}, exponent={{exp}}",D3070:"The single argument form of the sort function can only be applied to an array of strings or an array of numbers. Use the second argument to specify a comparison function",D3080:"The picture string must only contain a maximum of two sub-pictures",D3081:"The sub-picture must not contain more than one instance of the 'decimal-separator' character",D3082:"The sub-picture must not contain more than one instance of the 'percent' character",D3083:"The sub-picture must not contain more than one instance of the 'per-mille' character",D3084:"The sub-picture must not contain both a 'percent' and a 'per-mille' character",D3085:"The mantissa part of a sub-picture must contain at least one character that is either an 'optional digit character' or a member of the 'decimal digit family'",D3086:"The sub-picture must not contain a passive character that is preceded by an active character and that is followed by another active character",D3087:"The sub-picture must not contain a 'grouping-separator' character that appears adjacent to a 'decimal-separator' character",D3088:"The sub-picture must not contain a 'grouping-separator' at the end of the integer part",D3089:"The sub-picture must not contain two adjacent instances of the 'grouping-separator' character",D3090:"The integer part of the sub-picture must not contain a member of the 'decimal digit family' that is followed by an instance of the 'optional digit character'",D3091:"The fractional part of the sub-picture must not contain an instance of the 'optional digit character' that is followed by a member of the 'decimal digit family'",D3092:"A sub-picture that contains a 'percent' or 'per-mille' character must not contain a character treated as an 'exponent-separator'",D3093:"The exponent part of the sub-picture must comprise only of one or more characters that are members of the 'decimal digit family'",D3100:"The radix of the formatBase function must be between 2 and 36. It was given {{value}}",D3110:"The argument of the toMillis function must be an ISO 8601 formatted timestamp. Given {{value}}",D3120:"Syntax error in expression passed to function eval: {{value}}",D3121:"Dynamic error evaluating the expression passed to function eval: {{value}}",D3130:"Formatting or parsing an integer as a sequence starting with {{value}} is not supported by this implementation",D3131:"In a decimal digit pattern, all digits must be from the same decimal group",D3132:"Unknown component specifier {{value}} in date/time picture string",D3133:"The 'name' modifier can only be applied to months and days in the date/time picture string, not {{value}}",D3134:"The timezone integer format specifier cannot have more than four digits",D3135:"No matching closing bracket ']' in date/time picture string",D3136:"The date/time picture string is missing specifiers required to parse the timestamp",D3137:"{{{message}}}",D3138:"The $single() function expected exactly 1 matching result. Instead it matched more.",D3139:"The $single() function expected exactly 1 matching result. Instead it matched 0.",D3140:"Malformed URL passed to ${{{functionName}}}(): {{value}}",D3141:"{{{message}}}"};function jt(t){var e=Lt[t.code];if(void 0!==e){var n=e.replace(/\{\{\{([^}]+)}}}/g,function(){return t[arguments[1]]});n=n.replace(/\{\{([^}]+)}}/g,function(){return JSON.stringify(t[arguments[1]])}),t.message=n}}function Rt(t,e){var n,r;try{n=c(t,e&&e.recover),r=n.errors,delete n.errors}catch(t){throw jt(t),t}var i=It(B),o=new Date;return i.bind("now",Dt(function(t,e){return s.fromMillis(o.getTime(),t,e)},"<s?s?:s>")),i.bind("millis",Dt(function(){return o.getTime()},"<:n>")),e&&e.RegexEngine?Rt.RegexEngine=e.RegexEngine:Rt.RegexEngine=RegExp,{evaluate:function(t,e,s){if(void 0!==r){var a={code:"S0500",position:0};throw jt(a),a}var c,l,h;if(void 0!==e)for(var d in c=It(i),e)c.bind(d,e[d]);else c=i;if(c.bind("$",t),o=new Date,c.timestamp=o,Array.isArray(t)&&!z(t)&&((t=O(t)).outerWrapper=!0),"function"==typeof s){c.async=!0;var u=function(t){jt(t),s(t,null)},p=function t(e){(l=h.next(e)).done?s(null,l.value):l.value.then(t).catch(u)};h=N(n,t,c),(l=h.next()).value.then(p).catch(u)}else try{for(h=N(n,t,c),l=h.next();!l.done;)l=h.next(l.value);return l.value}catch(a){throw jt(a),a}},assign:function(t,e){i.bind(t,e)},registerFunction:function(t,e,n){var r=Dt(e,n);i.bind(t,r)},ast:function(){return n},errors:function(){return r}}}return Rt.parser=c,Rt}();e.exports=h},{"./datetime":1,"./functions":2,"./parser":4,"./signature":5,"./utils":6}],4:[function(t,e,n){var r=t("./signature"),i=function(){var t={".":75,"[":80,"]":0,"{":70,"}":0,"(":80,")":0,",":0,"@":80,"#":80,";":80,":":80,"?":20,"+":50,"-":50,"*":60,"/":60,"%":60,"|":20,"=":40,"<":40,">":40,"^":40,"**":60,"..":20,":=":10,"!=":40,"<=":40,">=":40,"~>":40,and:30,or:25,in:40,"&":50,"!":0,"~":0},e={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},n=function(n){var r=0,i=n.length,s=function(t,e){return{type:t,value:e,position:r}},o=function(){for(var t,e,s=r,o=0;r<i;){var a=n.charAt(r);if("/"===a&&"\\"!==n.charAt(r-1)&&0===o){if(""===(t=n.substring(s,r)))throw{code:"S0301",stack:(new Error).stack,position:r};for(r++,a=n.charAt(r),s=r;"i"===a||"m"===a;)r++,a=n.charAt(r);return e=n.substring(s,r)+"g",new RegExp(t,e)}"("!==a&&"["!==a&&"{"!==a||"\\"===n.charAt(r-1)||o++,")"!==a&&"]"!==a&&"}"!==a||"\\"===n.charAt(r-1)||o--,r++}throw{code:"S0302",stack:(new Error).stack,position:r}},a=function a(c){if(r>=i)return null;for(var l=n.charAt(r);r<i&&" \t\n\r\v".indexOf(l)>-1;)r++,l=n.charAt(r);if("/"===l&&"*"===n.charAt(r+1)){var h=r;for(r+=2,l=n.charAt(r);"*"!==l||"/"!==n.charAt(r+1);)if(l=n.charAt(++r),r>=i)throw{code:"S0106",stack:(new Error).stack,position:h};return r+=2,l=n.charAt(r),a(c)}if(!0!==c&&"/"===l)return r++,s("regex",o());if("."===l&&"."===n.charAt(r+1))return r+=2,s("operator","..");if(":"===l&&"="===n.charAt(r+1))return r+=2,s("operator",":=");if("!"===l&&"="===n.charAt(r+1))return r+=2,s("operator","!=");if(">"===l&&"="===n.charAt(r+1))return r+=2,s("operator",">=");if("<"===l&&"="===n.charAt(r+1))return r+=2,s("operator","<=");if("*"===l&&"*"===n.charAt(r+1))return r+=2,s("operator","**");if("~"===l&&">"===n.charAt(r+1))return r+=2,s("operator","~>");if(Object.prototype.hasOwnProperty.call(t,l))return r++,s("operator",l);if('"'===l||"'"===l){var d=l;r++;for(var u="";r<i;){if("\\"===(l=n.charAt(r)))if(r++,l=n.charAt(r),Object.prototype.hasOwnProperty.call(e,l))u+=e[l];else{if("u"!==l)throw{code:"S0103",stack:(new Error).stack,position:r,token:l};var p=n.substr(r+1,4);if(!/^[0-9a-fA-F]+$/.test(p))throw{code:"S0104",stack:(new Error).stack,position:r};var f=parseInt(p,16);u+=String.fromCharCode(f),r+=4}else{if(l===d)return r++,s("string",u);u+=l}r++}throw{code:"S0101",stack:(new Error).stack,position:r}}var g,m=/^-?(0|([1-9][0-9]*))(\.[0-9]+)?([Ee][-+]?[0-9]+)?/.exec(n.substring(r));if(null!==m){var y=parseFloat(m[0]);if(!isNaN(y)&&isFinite(y))return r+=m[0].length,s("number",y);throw{code:"S0102",stack:(new Error).stack,position:r,token:m[0]}}if("`"===l){r++;var b=n.indexOf("`",r);if(-1!==b)return g=n.substring(r,b),r=b+1,s("name",g);throw r=i,{code:"S0105",stack:(new Error).stack,position:r}}for(var v,_=r;;)if(v=n.charAt(_),_===i||" \t\n\r\v".indexOf(v)>-1||Object.prototype.hasOwnProperty.call(t,v)){if("$"===n.charAt(r))return g=n.substring(r+1,_),r=_,s("variable",g);switch(g=n.substring(r,_),r=_,g){case"or":case"in":case"and":return s("operator",g);case"true":return s("value",!0);case"false":return s("value",!1);case"null":return s("value",null);default:return r===i&&""===g?null:s("name",g)}}else _++};return a},i=function(e,i){var s,o,a={},c=[],l=function(){var t=[];"(end)"!==s.id&&t.push({type:s.type,value:s.value,position:s.position});for(var e=o();null!==e;)t.push(e),e=o();return t},h={nud:function(){var t={code:"S0211",token:this.value,position:this.position};if(i)return t.remaining=l(),t.type="error",c.push(t),t;throw t.stack=(new Error).stack,t}},d=function(t,e){var n=a[t];return e=e||0,n?e>=n.lbp&&(n.lbp=e):((n=Object.create(h)).id=n.value=t,n.lbp=e,a[t]=n),n},u=function(t){if(i){t.remaining=l(),c.push(t);var e=a["(error)"];return(s=Object.create(e)).error=t,s.type="(error)",s}throw t.stack=(new Error).stack,t},p=function(t,n){if(t&&s.id!==t){var r={code:"(end)"===s.id?"S0203":"S0202",position:s.position,token:s.value,value:t};return u(r)}var i=o(n);if(null===i)return(s=a["(end)"]).position=e.length,s;var c,l=i.value,h=i.type;switch(h){case"name":case"variable":c=a["(name)"];break;case"operator":if(!(c=a[l]))return u({code:"S0204",stack:(new Error).stack,position:i.position,token:l});break;case"string":case"number":case"value":c=a["(literal)"];break;case"regex":h="regex",c=a["(regex)"];break;default:return u({code:"S0205",stack:(new Error).stack,position:i.position,token:l})}return(s=Object.create(c)).value=l,s.type=h,s.position=i.position,s},f=function(t){var e,n=s;for(p(null,!0),e=n.nud();t<s.lbp;)n=s,p(),e=n.led(e);return e},g=function(t){d(t,0).nud=function(){return this}},m=function(e,n,r){var i=n||t[e],s=d(e,i);return s.led=r||function(t){return this.lhs=t,this.rhs=f(i),this.type="binary",this},s},y=function(t,e,n){var r=d(t,e);return r.led=n,r},b=function(t,e){var n=d(t);return n.nud=e||function(){return this.expression=f(70),this.type="unary",this},n};g("(end)"),g("(name)"),g("(literal)"),g("(regex)"),d(":"),d(";"),d(","),d(")"),d("]"),d("}"),d(".."),m("."),m("+"),m("-"),m("*"),m("/"),m("%"),m("="),m("<"),m(">"),m("!="),m("<="),m(">="),m("&"),m("and"),m("or"),m("in"),g("and"),g("or"),g("in"),b("-"),m("~>"),y("(error)",10,function(t){return this.lhs=t,this.error=s.error,this.remaining=l(),this.type="error",this}),b("*",function(){return this.type="wildcard",this}),b("**",function(){return this.type="descendant",this}),b("%",function(){return this.type="parent",this}),m("(",t["("],function(t){if(this.procedure=t,this.type="function",this.arguments=[],")"!==s.id)for(;"operator"===s.type&&"?"===s.id?(this.type="partial",this.arguments.push(s),p("?")):this.arguments.push(f(0)),","===s.id;)p(",");if(p(")",!0),"name"===t.type&&("function"===t.value||"λ"===t.value)){if(this.arguments.forEach(function(t,e){if("variable"!==t.type)return u({code:"S0208",stack:(new Error).stack,position:t.position,token:t.value,value:e+1})}),this.type="lambda","<"===s.id){for(var e=s.position,n=1,i="<";n>0&&"{"!==s.id&&"(end)"!==s.id;){var o=p();">"===o.id?n--:"<"===o.id&&n++,i+=o.value}p(">");try{this.signature=r(i)}catch(t){return t.position=e+t.offset,u(t)}}p("{"),this.body=f(0),p("}")}return this}),b("(",function(){for(var t=[];")"!==s.id&&(t.push(f(0)),";"===s.id);)p(";");return p(")",!0),this.type="block",this.expressions=t,this}),b("[",function(){var t=[];if("]"!==s.id)for(;;){var e=f(0);if(".."===s.id){var n={type:"binary",value:"..",position:s.position,lhs:e};p(".."),n.rhs=f(0),e=n}if(t.push(e),","!==s.id)break;p(",")}return p("]",!0),this.expressions=t,this.type="unary",this}),m("[",t["["],function(e){if("]"===s.id){for(var n=e;n&&"binary"===n.type&&"["===n.value;)n=n.lhs;return n.keepArray=!0,p("]"),e}return this.lhs=e,this.rhs=f(t["]"]),this.type="binary",p("]",!0),this}),m("^",t["^"],function(t){p("(");for(var e=[];;){var n={descending:!1};if("<"===s.id?p("<"):">"===s.id&&(n.descending=!0,p(">")),n.expression=f(0),e.push(n),","!==s.id)break;p(",")}return p(")"),this.lhs=t,this.rhs=e,this.type="binary",this});var v=function(t){var e=[];if("}"!==s.id)for(;;){var n=f(0);p(":");var r=f(0);if(e.push([n,r]),","!==s.id)break;p(",")}return p("}",!0),void 0===t?(this.lhs=e,this.type="unary"):(this.lhs=t,this.rhs=e,this.type="binary"),this};b("{",v),m("{",t["{"],v),y(":=",t[":="],function(e){return"variable"!==e.type?u({code:"S0212",stack:(new Error).stack,position:e.position,token:e.value}):(this.lhs=e,this.rhs=f(t[":="]-1),this.type="binary",this)}),m("@",t["@"],function(e){return this.lhs=e,this.rhs=f(t["@"]),"variable"!==this.rhs.type?u({code:"S0214",stack:(new Error).stack,position:this.rhs.position,token:"@"}):(this.type="binary",this)}),m("#",t["#"],function(e){return this.lhs=e,this.rhs=f(t["#"]),"variable"!==this.rhs.type?u({code:"S0214",stack:(new Error).stack,position:this.rhs.position,token:"#"}):(this.type="binary",this)}),m("?",t["?"],function(t){return this.type="condition",this.condition=t,this.then=f(0),":"===s.id&&(p(":"),this.else=f(0)),this}),b("|",function(){return this.type="transform",this.pattern=f(0),p("|"),this.update=f(0),","===s.id&&(p(","),this.delete=f(0)),p("|"),this});var _=function t(e){var n;if("function"!==e.type||e.predicate)if("condition"===e.type)e.then=t(e.then),void 0!==e.else&&(e.else=t(e.else)),n=e;else if("block"===e.type){var r=e.expressions.length;r>0&&(e.expressions[r-1]=t(e.expressions[r-1])),n=e}else n=e;else{var i={type:"lambda",thunk:!0,arguments:[],position:e.position};i.body=e,n=i}return n},x=0,w=0,M=[],S=function t(e,n){switch(e.type){case"name":case"wildcard":n.level--,0===n.level&&(void 0===e.ancestor||(M[n.index].slot.label=e.ancestor.label),e.ancestor=n,e.tuple=!0);break;case"parent":n.level++;break;case"block":e.expressions.length>0&&(e.tuple=!0,n=t(e.expressions[e.expressions.length-1],n));break;case"path":e.tuple=!0;var r=e.steps.length-1;for(n=t(e.steps[r--],n);n.level>0&&r>=0;)n=t(e.steps[r--],n);break;default:throw{code:"S0217",token:e.type,position:e.position}}return n},A=function(t,e){if(void 0!==e.seekingParent||"parent"===e.type){var n=void 0!==e.seekingParent?e.seekingParent:[];"parent"===e.type&&n.push(e.slot),void 0===t.seekingParent?t.seekingParent=n:Array.prototype.push.apply(t.seekingParent,n)}},E=function(t){var e=t.steps.length-1,n=t.steps[e],r=void 0!==n.seekingParent?n.seekingParent:[];"parent"===n.type&&r.push(n.slot);for(var i=0;i<r.length;i++){var s=r[i];for(e=t.steps.length-2;s.level>0;){if(e<0){void 0===t.seekingParent?t.seekingParent=[s]:t.seekingParent.push(s);break}for(var o=t.steps[e--];e>=0&&o.focus&&t.steps[e].focus;)o=t.steps[e--];s=S(o,s)}}},k=function t(e){var n;switch(e.type){case"binary":switch(e.value){case".":var r=t(e.lhs);n="path"===r.type?r:{type:"path",steps:[r]},"parent"===r.type&&(n.seekingParent=[r.slot]);var s=t(e.rhs);"function"===s.type&&"path"===s.procedure.type&&1===s.procedure.steps.length&&"name"===s.procedure.steps[0].type&&"function"===n.steps[n.steps.length-1].type&&(n.steps[n.steps.length-1].nextFunction=s.procedure.steps[0].value),"path"===s.type?Array.prototype.push.apply(n.steps,s.steps):(void 0!==s.predicate&&(s.stages=s.predicate,delete s.predicate),n.steps.push(s)),n.steps.filter(function(t){if("number"===t.type||"value"===t.type)throw{code:"S0213",stack:(new Error).stack,position:t.position,value:t.value};return"string"===t.type}).forEach(function(t){t.type="name"}),n.steps.filter(function(t){return!0===t.keepArray}).length>0&&(n.keepSingletonArray=!0);var o=n.steps[0];"unary"===o.type&&"["===o.value&&(o.consarray=!0);var a=n.steps[n.steps.length-1];"unary"===a.type&&"["===a.value&&(a.consarray=!0),E(n);break;case"[":var l=n=t(e.lhs),h="predicate";if("path"===n.type&&(l=n.steps[n.steps.length-1],h="stages"),void 0!==l.group)throw{code:"S0209",stack:(new Error).stack,position:e.position};void 0===l[h]&&(l[h]=[]);var d=t(e.rhs);void 0!==d.seekingParent&&(d.seekingParent.forEach(function(t){1===t.level?S(l,t):t.level--}),A(l,d)),l[h].push({type:"filter",expr:d,position:e.position});break;case"{":if(void 0!==(n=t(e.lhs)).group)throw{code:"S0210",stack:(new Error).stack,position:e.position};n.group={lhs:e.rhs.map(function(e){return[t(e[0]),t(e[1])]}),position:e.position};break;case"^":"path"!==(n=t(e.lhs)).type&&(n={type:"path",steps:[n]});var u={type:"sort",position:e.position};u.terms=e.rhs.map(function(e){var n=t(e.expression);return A(u,n),{descending:e.descending,expression:n}}),n.steps.push(u),E(n);break;case":=":(n={type:"bind",value:e.value,position:e.position}).lhs=t(e.lhs),n.rhs=t(e.rhs),A(n,n.rhs);break;case"@":if(n=t(e.lhs),l=n,"path"===n.type&&(l=n.steps[n.steps.length-1]),void 0!==l.stages||void 0!==l.predicate)throw{code:"S0215",stack:(new Error).stack,position:e.position};if("sort"===l.type)throw{code:"S0216",stack:(new Error).stack,position:e.position};e.keepArray&&(l.keepArray=!0),l.focus=e.rhs.value,l.tuple=!0;break;case"#":n=t(e.lhs),l=n,"path"===n.type?l=n.steps[n.steps.length-1]:(n={type:"path",steps:[n]},void 0!==l.predicate&&(l.stages=l.predicate,delete l.predicate)),void 0===l.stages?l.index=e.rhs.value:l.stages.push({type:"index",value:e.rhs.value,position:e.position}),l.tuple=!0;break;case"~>":(n={type:"apply",value:e.value,position:e.position}).lhs=t(e.lhs),n.rhs=t(e.rhs);break;default:(n={type:e.type,value:e.value,position:e.position}).lhs=t(e.lhs),n.rhs=t(e.rhs),A(n,n.lhs),A(n,n.rhs)}break;case"unary":n={type:e.type,value:e.value,position:e.position},"["===e.value?n.expressions=e.expressions.map(function(e){var r=t(e);return A(n,r),r}):"{"===e.value?n.lhs=e.lhs.map(function(e){var r=t(e[0]);A(n,r);var i=t(e[1]);return A(n,i),[r,i]}):(n.expression=t(e.expression),"-"===e.value&&"number"===n.expression.type?(n=n.expression).value=-n.value:A(n,n.expression));break;case"function":case"partial":(n={type:e.type,name:e.name,value:e.value,position:e.position}).arguments=e.arguments.map(function(e){var r=t(e);return A(n,r),r}),n.procedure=t(e.procedure);break;case"lambda":n={type:e.type,arguments:e.arguments,signature:e.signature,position:e.position};var p=t(e.body);n.body=_(p);break;case"condition":(n={type:e.type,position:e.position}).condition=t(e.condition),A(n,n.condition),n.then=t(e.then),A(n,n.then),void 0!==e.else&&(n.else=t(e.else),A(n,n.else));break;case"transform":(n={type:e.type,position:e.position}).pattern=t(e.pattern),n.update=t(e.update),void 0!==e.delete&&(n.delete=t(e.delete));break;case"block":(n={type:e.type,position:e.position}).expressions=e.expressions.map(function(e){var r=t(e);return A(n,r),(r.consarray||"path"===r.type&&r.steps[0].consarray)&&(n.consarray=!0),r});break;case"name":n={type:"path",steps:[e]},e.keepArray&&(n.keepSingletonArray=!0);break;case"parent":n={type:"parent",slot:{label:"!"+x++,level:1,index:w++}},M.push(n);break;case"string":case"number":case"value":case"wildcard":case"descendant":case"variable":case"regex":n=e;break;case"operator":if("and"===e.value||"or"===e.value||"in"===e.value)e.type="name",n=t(e);else{if("?"!==e.value)throw{code:"S0201",stack:(new Error).stack,position:e.position,token:e.value};n=e}break;case"error":n=e,e.lhs&&(n=t(e.lhs));break;default:var f="S0206";"(end)"===e.id&&(f="S0207");var g={code:f,position:e.position,token:e.value};if(i)return c.push(g),{type:"error",error:g};throw g.stack=(new Error).stack,g}return e.keepArray&&(n.keepArray=!0),n};o=n(e),p();var C=f(0);if("(end)"!==s.id){var P={code:"S0201",position:s.position,token:s.value};u(P)}if("parent"===(C=k(C)).type||void 0!==C.seekingParent)throw{code:"S0217",token:C.type,position:C.position};return c.length>0&&(C.errors=c),C};return i}();e.exports=i},{"./signature":5}],5:[function(t,e,n){function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}var i=t("./utils"),s=function(){var t={a:"arrays",b:"booleans",f:"functions",n:"numbers",o:"objects",s:"strings"};function e(e){for(var n=1,s=[],o={},a=o;n<e.length;){var c=e.charAt(n);if(":"===c)break;var l=function(){s.push(o),a=o,o={}},h=function(t,e,n,r){for(var i=1,s=e;s<t.length;)if(s++,(c=t.charAt(s))===r){if(0===--i)break}else c===n&&i++;return s};switch(c){case"s":case"n":case"b":case"l":case"o":o.regex="["+c+"m]",o.type=c,l();break;case"a":o.regex="[asnblfom]",o.type=c,o.array=!0,l();break;case"f":o.regex="f",o.type=c,l();break;case"j":o.regex="[asnblom]",o.type=c,l();break;case"x":o.regex="[asnblfom]",o.type=c,l();break;case"-":a.context=!0,a.contextRegex=new RegExp(a.regex),a.regex+="?";break;case"?":case"+":a.regex+=c;break;case"(":var d=h(e,n,"(",")"),u=e.substring(n+1,d);if(-1!==u.indexOf("<"))throw{code:"S0402",stack:(new Error).stack,value:u,offset:n};o.regex="["+u+"m]",o.type="("+u+")",n=d,l();break;case"<":if("a"!==a.type&&"f"!==a.type)throw{code:"S0401",stack:(new Error).stack,value:a.type,offset:n};var p=h(e,n,"<",">");a.subtype=e.substring(n+1,p),n=p}n++}var f="^"+s.map(function(t){return"("+t.regex+")"}).join("")+"$",g=new RegExp(f),m=function(t){var e;if(i.isFunction(t))e="f";else switch(r(t)){case"string":e="s";break;case"number":e="n";break;case"boolean":e="b";break;case"object":e=null===t?"l":Array.isArray(t)?"a":"o";break;default:e="m"}return e},y=function(t,e){for(var n="^",r=0,i=0;i<s.length;i++){n+=s[i].regex;var o=e.match(n);if(null===o)throw{code:"T0410",stack:(new Error).stack,value:t[r],index:r+1};r=o[0].length}throw{code:"T0410",stack:(new Error).stack,value:t[r],index:r+1}};return{definition:e,validate:function(e,n){var r="";e.forEach(function(t){r+=m(t)});var i=g.exec(r);if(i){var o=[],a=0;return s.forEach(function(r,s){var c=e[a],l=i[s+1];if(""===l)if(r.context&&r.contextRegex){var h=m(n);if(!r.contextRegex.test(h))throw{code:"T0411",stack:(new Error).stack,value:n,index:a+1};o.push(n)}else o.push(c),a++;else l.split("").forEach(function(n){if("a"===r.type){if("m"===n)c=void 0;else{c=e[a];var i=!0;if(void 0!==r.subtype)if("a"!==n&&l!==r.subtype)i=!1;else if("a"===n&&c.length>0){var s=m(c[0]);i=s===r.subtype.charAt(0)&&0===c.filter(function(t){return m(t)!==s}).length}if(!i)throw{code:"T0412",stack:(new Error).stack,value:c,index:a+1,type:t[r.subtype]};"a"!==n&&(c=[c])}o.push(c),a++}else o.push(c),a++})}),o}y(e,r)}}}return e}();e.exports=s},{"./utils":6}],6:[function(t,e,n){function r(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=i(t))||e){n&&(t=n);var r=0,s=function(){};return{s:s,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,c=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){c=!0,o=t},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw o}}}}function i(t,e){if(t){if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(t,e):void 0}}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}var a=function(){function t(t){var e=!1;if("number"==typeof t&&(e=!isNaN(t))&&!isFinite(t))throw{code:"D1001",value:t,stack:(new Error).stack};return e}function e(t){var e=!1;return Array.isArray(t)&&(e=0===t.filter(function(t){return"string"!=typeof t}).length),e}function n(e){var n=!1;return Array.isArray(e)&&(n=0===e.filter(function(e){return!t(e)}).length),n}function i(){var t=[];return t.sequence=!0,1===arguments.length&&t.push(arguments[0]),t}function s(t){return!0===t.sequence&&Array.isArray(t)}function a(t){return t&&(!0===t._jsonata_function||!0===t._jsonata_lambda)||"function"==typeof t}function c(t){return"number"==typeof t.arity?t.arity:"function"==typeof t.implementation?t.implementation.length:"number"==typeof t.length?t.length:t.arguments.length}function l(t){return t&&!0===t._jsonata_lambda}var h=("function"==typeof Symbol?Symbol:{}).iterator||"@@iterator";function d(t){return"object"===o(t)&&null!==t&&h in t&&"next"in t&&"function"==typeof t.next}function u(t,e){if(t===e)return!0;if("object"===o(t)&&"object"===o(e)&&null!==t&&null!==e){if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(!u(t[n],e[n]))return!1;return!0}var r=Object.getOwnPropertyNames(t),i=Object.getOwnPropertyNames(e);if(r.length!==i.length)return!1;for(r=r.sort(),i=i.sort(),n=0;n<r.length;n++)if(r[n]!==i[n])return!1;for(n=0;n<r.length;n++){var s=r[n];if(!u(t[s],e[s]))return!1}return!0}return!1}function p(t){var e,n=[],i=r(t);try{for(i.s();!(e=i.n()).done;){var s=e.value;n.push(s)}}catch(t){i.e(t)}finally{i.f()}return n}return{isNumeric:t,isArrayOfStrings:e,isArrayOfNumbers:n,createSequence:i,isSequence:s,isFunction:a,isLambda:l,isIterable:d,getFunctionArity:c,isDeepEqual:u,stringToArray:p}}();e.exports=a},{}]},{},[3])(3)}(Yr)),Yr.exports),$r=Hr(Ur);const Wr=function(t){return t};function Xr(t){if(!t)return Wr;try{const e=$r(function(t){return t.replace(/(?<=^|\.|\[)([a-zA-Z_][\w]*-[\w-]*)(?=\.|$|\[|])/g,"`$1`")}(t));return function(t){return e.evaluate(t)}}catch(t){return jr(t),Wr}}function qr(t){const e=or(t);return null==e?"":String(e)}function Kr(t){return Number(or(t))}function Qr(t){return t}function Zr(t){return qr(t)}function Jr(t){return Kr(t)}function ti(t){if(this.param)return t=qr(t),this.param.hasOwnProperty(t)?this.param[t]:this.param.default}function ei(t){const{param:e}=this;if(e){for(const n in e){let[r,i]=n.split("~");const s=!!r,o=!!i,a=parseFloat(r),c=parseFloat(i);if(t=Kr(t),s&&!o&&t>=a)return e[n];if(!s&&o&&t<a)return e[n];if(t>=a&&t<c)return e[n]}return e.default}}function ni(t){return Kr(t)*Math.PI/180}function ri(){}const ii=[/\bimport\b/,/\brequire\b/,/\b__proto__\b/,/\bconstructor\s*\[/,/\bprototype\b/];const si=["globalThis","self","top","parent","frames","fetch","XMLHttpRequest","eval","Function","require","importScripts","process"],oi=new Array(si.length).fill(void 0);function ai(t){try{!function(t){for(const e of ii)if(e.test(t))throw new Error(`Blocked pattern detected: ${e}`)}(t);const e=new Function("value","targets","scene",...si,t);return function(t,n){try{return e.call(this,t,n,globalThis.scene,...oi)}catch(t){return void jr(t)}}}catch(t){return jr(t),ri}}function ci(t,e,n,r,i){switch(n){case"value":return"text"===i||"string"===i?Zr.bind(t):"number"===i?Jr.bind(t):Qr.bind(e);case"map":return ti.bind(t);case"range":return ei.bind(t);case"radian":return ni.bind(t);case"eval":return ai(r).bind(e);default:return Qr.bind(e)}}class li{constructor(t,e){this.owner=e,this.model=t}dispose(){this._model=null,this.owner=null,this.evaluator=null,this.accessor=null}get model(){return this._model}set model(t){const{target:e,property:n,rule:r,param:i,accessor:s}=t;this._model=t,this.evaluator=ci(this,this.owner,r,i,function(t){switch(t){case"ref":case"fillStyle":case"strokeStyle":return"string";default:return}}(n)),this.accessor=Xr(s);const o=e.match(/\[(.*?)\]/);if(o){const[t,e]=o[1].split(":");this.propAccessor=Xr(t),this.partAccessor=Xr(e)}}get target(){return this.model.target}get property(){return this.model.property}get source(){return this.model.source}get param(){return this.model.param}get ndnsp(){return!!this.model.ndnsp}get partial(){return!!this.model.partial}}function hi(t,e,n,r){r?t.forEach(t=>t[e]={...t[e],...n}):t.forEach(t=>t[e]=n)}function di(t=!1){(t||void 0!==this.data)&&this.mappings&&this.mappings.forEach(t=>{try{let e,{source:n,target:r,property:i,accessor:s,propAccessor:o,partAccessor:a,ndnsp:c=!1,partial:l=!1}=t;n&&"(self)"!=n?(n.startsWith("#")&&(n=n.substring(1)),e=this.root.findById(n)?.data||{}):e=this.data;const h=s(e);if(r=r.trim(),"(root)"==r||"(key)"==r){if(null==h)return;const e=Object.keys(h||{}).map(t=>this.root.findOrCreate(t)).filter(Boolean).flat();e.length>0&&e.forEach(e=>{const n=t.evaluator(h[e.get("id")],[e]);!i||"(action)"===i||c&&!n&&0!==n&&!1!==n||(e[i]=l?{...e[i],...n}:n)})}else if(r.startsWith("[")){if(null==h)return;if(h instanceof Array)h.forEach(e=>{const n=o(e);if(n){const r=this.root.findOrCreate(n);if(r){const n=t.evaluator(a(e),r);!i||"(action)"===i||c&&!n&&0!==n&&!1!==n||hi(r,i,n,l)}}});else{if(!(h instanceof Object))throw String("mapping data should be an object to target property-id.("+h+")");{const e=o(h);if(e){const n=this.root.findOrCreate(e);if(n){const e=t.evaluator(a(h),n);!i||"(action)"===i||c&&!e&&0!==e&&!1!==e||hi(n,i,e,l)}}}}}else{const e=this.root.findAll(r,this);if(e.length>0){const n=t.evaluator(h,e);!i||"(action)"===i||c&&!n&&0!==n&&!1!==n||hi(e,i,n,l)}}}catch(e){jr(e,this,t)}})}function ui(t,e){this.state.persistent&&this.app?.isViewMode&&this.app?.dataStorage.save(this,t.data),di.call(this,!0)}function pi(){if(this._model.mappings)return this._model.mappings instanceof Array?void(this._mappings=(this._model.mappings||[]).filter(t=>t.rule&&t.target).map(t=>new li(t,this))):(jr("Mappings model is invalid (should be a Array) ..",this._model.mappings),void(this._mappings=[]));this._mappings=[]}function fi(){this._mappings&&this._mappings.forEach(t=>t.dispose()),delete this._mappings}function gi(t,e){this.disposeMappings(),di.call(this)}function mi(t,e,n,r,i,s){e.complete?t.drawImage(e,n,r,i,s):e.addEventListener("load",()=>{this.invalidate()})}function yi(t){const{effects:e}=this.state;(e||[]).forEach(e=>{this.effect(t,e)})}const bi={},vi={VIEW:0,EDIT:1,SHIFT:2,ADD:3},_i="undefined"==typeof window?1:window.devicePixelRatio||(window.matchMedia&&window.matchMedia("(min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 1.5),(-moz-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5)").matches?2:1),xi=["mousemove","mouseup","mousedown","mouseout","wheel","touchstart","touchmove","touchend","dblclick"],wi=["keydown","keyup"],Mi={ALPHA:1,FONT_SIZE:15,FONT_FAMILY:"Roboto, sans-serif",FONT_COLOR:"black",TEXT_ALIGN:"center",TEXT_BASELINE:"middle",TEXT_WRAP:!1,BOLD:!1,ITALIC:!1,STROKE_STYLE:"#999",LINE_DASH:"solid",LETTER_SPACING:0},Si=()=>{if("undefined"==typeof document||"function"!=typeof getComputedStyle||!document.documentElement)return;const t=getComputedStyle(document.documentElement);if(!t)return;const e=t.getPropertyValue?.("--scene-theme-font-family")?.trim(),n=t.fontFamily||"sans-serif";Mi.FONT_FAMILY=e||n},Ai=()=>{if("undefined"!=typeof window&&"undefined"!=typeof document&&(window.addEventListener("load",()=>{Si()}),"fonts"in document&&"ready"in document.fonts&&document.fonts.ready.then(Si),"undefined"!=typeof MutationObserver&&document.documentElement)){new MutationObserver(()=>{Si()}).observe(document.documentElement,{attributes:!0,attributeFilter:["style","class"]})}};let Ei;function ki(t,e,n,r,i){const{alpha:s=1}=r,o=i.fillStyle;if(t.globalAlpha*=s,o)if("string"==typeof o)t.fillStyle=o,t.fill();else if("object"==typeof o)if("gradient"==o.type){t.translate(n.x,n.y);let r,{width:i,height:s}=e;if("linear"==o.gradientType){const e=3.141592653589793,n=o.rotation;if(n>=.436332&&n<=1.13446||n>=2.00713&&n<=2.70526||n>=3.57792&&n<=4.27606||n>=5.14872&&n<=5.84685){let o=Math.sqrt(Math.pow((i-4)/2,2)+Math.pow((s-4)/2,2));o-=o-(i+s)/3,r=t.createLinearGradient(o*Math.cos(n+e),o*Math.sin(n+e),o*Math.cos(n),o*Math.sin(n))}else r=t.createLinearGradient((i-4)/2*Math.cos(n+e),(s-4)/2*Math.sin(n+e),(i-4)/2*Math.cos(n),(s-4)/2*Math.sin(n))}else if("radial"==o.gradientType){const e=.95*Math.sqrt(Math.pow((i-4)/2,2)+Math.pow((s-4)/2,2));switch(o.center){case"center":default:r=t.createRadialGradient(0,0,0,0,0,e);break;case"left-top":r=t.createRadialGradient(-i/2,-s/2,0,-i/2,-s/2,2*e);break;case"right-top":r=t.createRadialGradient(i/2,-s/2,0,i/2,-s/2,2*e);break;case"left-bottom":r=t.createRadialGradient(-i/2,s/2,0,-i/2,s/2,2*e);break;case"right-bottom":r=t.createRadialGradient(i/2,s/2,0,i/2,s/2,2*e)}}o.colorStops.forEach(t=>{if(t.position>=0&&t.position<=1)try{r.addColorStop(t.position,t.color)}catch(e){Rr("Invalid Color for colorstop : ",t.color),r.addColorStop(t.position,"#fff")}}),t.fillStyle=r,t.fill(),t.translate(-n.x,-n.y)}else if("pattern"==o.type&&o.image)if(o.guideOnly&&1!=i.app.mode)o.color&&(t.fillStyle=o.color,t.fill());else{i.prepareFillIf(!i._pattern_image_origin);const n=i._pattern_image;if(!n||!n.width||!n.height)return;let r=0,s=0,a=0,c=0,l=e.left,h=e.top;if(!o.fitPattern){r=o.offsetX,s=o.offsetY;const t=o.width?o.width:n.width,i=o.height?o.height:n.height;switch(o.align){case"center":a=e.width/2-t/2,c=e.height/2-i/2;break;case"left-top":a=0,c=0;break;case"left-bottom":a=0,c=e.height-i;break;case"right-top":a=e.width-t,c=0;break;case"right-bottom":a=e.width-t,c=e.height-i;break;case"left":a=0,c=e.height/2-i/2;break;case"right":a=e.width-t,c=e.height/2-i/2;break;case"top":a=e.width/2-t/2,c=0;break;case"bottom":a=e.width/2-t/2,c=e.height-i}l+=r+a,h+=s+c}t.translate(l,h),o.color&&(t.fillStyle=o.color,t.fill()),o.fitPattern?Math.abs((n.width-e.width)*(n.height-e.height))>1?(delete i._pattern_image,delete i._pattern_image_origin):t.fillStyle=t.createPattern(n,"no-repeat"):t.fillStyle=t.createPattern(n,o.noRepeat?"no-repeat":"repeat"),t.fill(),t.translate(-l,-h)}}function Ci(t,e){const n=this.fillStyle;if(!n||"pattern"!=n.type||!n.image)return void t(this);if("string"!=typeof n.image)return this._pattern_image_origin=this._pattern_image=n.image,void t(this);this._pattern_image=null,this._pattern_image_origin=new Image;const r=this;this._pattern_image_origin.onload=function(){if(!n.fitPattern&&!n.width&&!n.height)return r._pattern_image=r._pattern_image_origin,void t(this);let e=n.width||this.width,i=n.height||this.height;n.fitPattern&&(e=r.bounds.width,i=r.bounds.height);const s=Ei(e,i);s.getContext("2d").drawImage(this,0,0,this.width,this.height,0,0,e,i),r._pattern_image=s,t(this)},this._pattern_image_origin.onerror=function(t){e(t)};try{"data"!==String(n.image).substring(0,4)?this._pattern_image_origin.crossOrigin="use-credentials":this._pattern_image_origin.crossOrigin=null,this._pattern_image_origin.src=this.app.url(n.image)}catch(t){e(t)}}function Pi(t){t&&this.prepareFill(t=>{this.invalidate()},t=>{jr(t)})}function Ti(t,e){const n=this.fillStyle;n&&"pattern"!==n.type?this._pattern_image&&(this._pattern_image=null,this._pattern_image_origin=null):n?.image&&this.prepareFillIf(n.image)}function Di(t,e,n){let{strokeStyle:r,lineDash:i,lineWidth:s,lineCap:o,lineJoin:a,alpha:c}=e;if(r&&0!=s){if(o&&(t.lineCap=o),i){const e="round"==o;switch(i){case"solid":i=[0,0];break;case"round-dot":i=e?[0,2*s]:[s,s];break;case"square-dot":i=e?[s,2*s]:[2*s,s];break;case"dash":i=e?[3*s,2.5*s]:[4*s,1.5*s];break;case"dash-dot":i=e?[3*s,3*s,0,3*s]:[4*s,2*s,s,2*s];break;case"long-dash":i=e?[5*s,4*s]:[6*s,3*s];break;case"long-dash-dot":i=e?[5*s,3*s,0,3*s]:[6*s,2*s,s,2*s];break;case"long-dash-dot-dot":i=e?[5*s,2*s,0,2*s,0,2*s]:[6*s,s,s,s,s,s]}t.setLineDash(i)}t.globalAlpha*=c,t.strokeStyle=r,t.lineWidth=s,t.lineJoin=a,t.stroke()}}function Oi(t){const e=/(\*\*|__)(.*?)\1|(\*|_)(.*?)\3|([^\*_]+)/g,n=[];let r;for(;null!==(r=e.exec(t));)r[1]?n.push({text:r[2],bold:!0,italic:!1}):r[3]?n.push({text:r[4],bold:!1,italic:!0}):r[5]&&n.push({text:r[5],bold:!1,italic:!1});return n}function zi(t,e,n,r=0){if(e.text.length<2)return e;let i=2;for(;i<e.text.length;i++){const s=e.text.substring(0,i);if(!(t.measureText(s).width+(i-1)*r<n))break}return{...e,text:e.text.substring(0,i-1)}}function Ii(t,e,n,r,i,s=0){const o=String(e).split("\n");return r?[].concat(...o.map(e=>function(t,e,n,r=0){const i=[];let s=[],o=0;return e.forEach(e=>{let a=e.text;for(;a.length>0;){const c=n-o,l=t.measureText(a).width+(a.length-1)*r;if(l<=c)s.push({...e,text:a}),o+=l,a="";else{const n=zi(t,{...e,text:a},c,r);s.push(n),i.push(s),s=[],o=0,a=a.substring(n.text.length)}}}),s.length>0&&i.push(s),i}(t,i?Oi(e):[{text:e,bold:!1,italic:!1}],n,s))):o.map(t=>i?Oi(t):[{text:t,bold:!1,italic:!1}])}function Li(t,e,n,r,i,s,o=0){if(!r)return[];t.save(),t.font=n;const a=Ii(t,r,e,!!i,s,o);return t.restore(),a}function ji(t){const{fontFamily:e=Mi.FONT_FAMILY,bold:n=Mi.BOLD,italic:r=Mi.ITALIC,fontSize:i=Mi.FONT_SIZE}=t,s=[];return n&&s.push("bold"),r&&s.push("italic"),s.push(i+"px"),s.push(e),s.join(" ")}function Ri(t,e){const n=t.bold||e.bold,r=t.italic||e.italic;return ji({...t,bold:n,italic:r})}function Fi(t,e,n,r){let{alpha:i,rotation:s,keepTextAngle:o=!1,fontColor:a=Mi.FONT_COLOR,textAlign:c=Mi.TEXT_ALIGN,textBaseline:l=Mi.TEXT_BASELINE,textBackgroundStyle:h,fontSize:d,lineHeight:u,textWrap:p,textOverflow:f,letterSpacing:g=0}=r;i=void 0!==i?i:1,d||=Mi.FONT_SIZE,u||=1.2*d,t.save();const{left:m,top:y,width:b,height:v}=e;if(s&&o&&(t.translate(m+b/2,y+v/2),t.rotate(-s),t.translate(-(m+b/2),-(y+v/2))),t.beginPath(),t.font=ji(r),!p&&f){const e=function(t,e,n,r){const i="ellipsis"===t?"…":"",s=e.measureText(i).width,o=[];let a=0;for(const i of n){const n=[];for(const c of i){const i=e.measureText(c.text).width;if(!(a+i<=r-("ellipsis"===t?s:0))){const i=Bi(e,c,r-a-("ellipsis"===t?s:0),t);return n.push(i),o.push(n),o}n.push(c),a+=i}o.push(n),a=0}return o}(f,t,n,b);n=e}const _=n.length*u;let x;switch(l){case"top":x=y,t.textBaseline="top";break;case"bottom":x=y+v-_+u,t.textBaseline="bottom";break;default:x=y+v/2-_/2+u/2,t.textBaseline="middle"}t.globalAlpha*=i,t.fillStyle=a,n.forEach((e,i)=>{const s=x+i*u,o=function(t,e,n,r=0){return e.reduce((e,i)=>(t.font=Ri(n,i),e+t.measureText(i.text).width+r*(i.text.length-1)),0)}(t,e,r,g);let l=m;switch(c){case"left":case"justify":l=m;break;case"right":l=m+b-o;break;case"center":l=m+(b-o)/2}if(h&&(t.fillStyle=h,function(t,e,n,r,i,s=0,o=!1,a=!0){s="number"==typeof s?{tl:s,tr:s,br:s,bl:s}:{tl:0,tr:0,br:0,bl:0,...s},t.beginPath(),t.moveTo(e+s.tl,n),t.lineTo(e+r-s.tr,n),t.quadraticCurveTo(e+r,n,e+r,n+s.tr),t.lineTo(e+r,n+i-s.br),t.quadraticCurveTo(e+r,n+i,e+r-s.br,n+i),t.lineTo(e+s.bl,n+i),t.quadraticCurveTo(e,n+i,e,n+i-s.bl),t.lineTo(e,n+s.tl),t.quadraticCurveTo(e,n,e+s.tl,n),t.closePath(),o&&t.fill(),a&&t.stroke()}(t,l-4,s-d/2-4,o+8,d+8,4,!0,!1),t.fillStyle=a),"justify"===c&&i<n.length-1&&e.length>1){const n=b-o,i=e.length-1,a=n/i;e.forEach((e,n)=>{t.font=Ri(r,e),t.fillText(e.text,l,s),l+=t.measureText(e.text).width+(n<i?a:0)})}else e.forEach(e=>{t.font=Ri(r,e),[...e.text].forEach(e=>{t.fillText(e,l,s),l+=t.measureText(e).width+g})})}),t.restore()}function Bi(t,e,n,r){let i="";for(let r=0;r<e.text.length;r++){const s=i+e.text[r];if(t.measureText(s).width>n)break;i=s}return{...e,text:i+("ellipsis"===r?"…":"")}}function Ni(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("image/"))return void this.set("fillStyle",{type:"pattern",image:e[n],fitPattern:!0})}Ai(),Si(),Ei="undefined"==typeof document?function(t,e){return new Canvas(t,e)}:function(t,e){const n=document.createElement("canvas");return n.width=t,n.height=e,n};const Hi=[];function Vi(t,e,n={x:0,y:0},r=0,i={x:1,y:1}){if(1!==i.x||1!==i.y?(t=(t-n.x)/i.x,e=(e-n.y)/i.y):(t-=n.x,e-=n.y),0!==r){const n=Math.cos(-r),i=Math.sin(-r),s=t*i+e*n;t=t*n-e*i,e=s}return{x:t+n.x,y:e+n.y}}function Gi(t,e,n={x:0,y:0},r=0,i={x:1,y:1}){if(t-=n.x,e-=n.y,0!==r){const n=Math.cos(r),i=Math.sin(r),s=t*i+e*n;t=t*n-e*i,e=s}return 1!==i.x||1!==i.y?{x:t*i.x+n.x,y:e*i.y+n.y}:{x:t+n.x,y:e+n.y}}function Yi(t,e,n){if(!this.parent)return{x:t,y:e};const{rotation:r=0,scale:i={x:1,y:1}}=this.state;if(this.isLayer()){const n=this.state.translate,s=Vi(t,e,n,r,i);return n&&(s.x-=n.x,s.y-=n.y),s}return Vi(t,e,n=n||this.rotatePoint,r,i)}function Ui(t,e,n){if(!this.parent)return{x:t,y:e};let{rotation:r=0,scale:i={x:1,y:1}}=this.state;if(this.isLayer()){const n=this.state.translate,s=Gi(t,e,void 0,r+(this._delta?.theta??0),i);return n&&(s.x+=n.x,s.y+=n.y),s}n=n||this.rotatePoint;const{theta:s=0,tx:o=0,ty:a=0,sx:c=1,sy:l=1}=this._delta||{};if(0===s&&0===o&&0===a&&1===c&&1===l)return Gi(t,e,n,r,i);return Gi(t+o,e+a,{x:n.x+o,y:n.y+a},r+s,{x:i.x*c,y:i.y*l})}function $i(t,e,n){n=n||this.rootModel;const r=this.transcoordS2T(t,e,n);return Gi(r.x,r.y,void 0,(n.get("rotation")||0)+n._delta.theta)}function Wi(t,e,n){n=n||this.rootModel,Hi.length=0;for(let t=this.parent;t&&t!==n;t=t.parent)Hi.push(t);let r=this.transcoordS2P(t,e);for(let t=0;t<Hi.length;t++){const e=Hi[t],n=e.bounds;r.x+=n.left,r.y+=n.top,r=e.transcoordS2P(r.x,r.y)}return r}function Xi(t,e,n){n=n||this.rootModel,Hi.length=0;for(let t=this.parent;t&&t!==n;t=t.parent)Hi.push(t);let r={x:t,y:e};for(let t=Hi.length-1;t>=0;t--){const e=Hi[t];r=e.transcoordP2S(r.x,r.y);const n=e.bounds;r.x-=n.left,r.y-=n.top}return r}function qi(t,e,n){const r=this.transcoordT2P(t,e,n);return this.transcoordP2S(r.x,r.y)}function Ki(t,e,n){const r=this.rootModel,i=this.transcoordS2T(t,e,r);return n.transcoordT2S(i.x,i.y,r)}function Qi(t,e,n){if(!n)for(n=this;n&&!n.isLayer();)n=n.parent;const{translate:r={x:0,y:0},scale:i={x:1,y:1},rotation:s=0}=n.model,o=Vi(t,e,r,s,i);return r&&(o.x-=r.x,o.y-=r.y),n===this?o:this.transcoordT2S(o.x,o.y,n)}function Zi(t,e,n){if(!n)for(n=this;n&&!n.isLayer();)n=n.parent;let r;if(r=n!==this?this.transcoordS2T(t,e,n):{x:t,y:e},!this.scalable)return r;const{translate:i={x:0,y:0},rotation:s=0,scale:o={x:1,y:1}}=n.model;return r=Gi(r.x,r.y,void 0,s+n._delta.theta,o),i&&(r.x+=i.x,r.y+=i.y),r}function Ji(t){let e=0,n=0,r=0,i=0,s=!1;return t.forEach(t=>{s?(e=Math.min(t.left,e),n=Math.min(t.top,n),r=Math.max(t.left+t.width,r),i=Math.max(t.top+t.height,i)):(e=t.left,n=t.top,r=t.left+t.width,i=t.top+t.height,s=!0)}),{left:e,top:n,width:r-e,height:i-n}}function ts(t){const e=t.element,n=t.fillStyle,r=e.style;if(n)if("string"==typeof n)r.backgroundColor=n;else switch(n.type){case"pattern":if(r.backgroundImage="url("+n.image+")",r.backgroundColor="transparent",n.fitPattern?r.backgroundSize="100% 100%":n.width||n.height?r.backgroundSize=`${n.width?n.width+"px":"auto"} ${n.height?n.height+"px":"auto"}`:r.backgroundSize="contain",n.fitPattern)r.backgroundRepeat="no-repeat";else{const{offsetX:t,offsetY:e,noRepeat:i,align:s,color:o}=n;if(i&&(r.backgroundRepeat="no-repeat"),o&&(r.backgroundColor=o),s)switch(s){case"center":r.backgroundPosition="center center";break;case"left-top":r.backgroundPosition="left top";break;case"left-bottom":r.backgroundPosition="left bottom";break;case"right-top":r.backgroundPosition="right top";break;case"right-bottom":r.backgroundPosition="right bottom";break;case"left":r.backgroundPosition="left center";break;case"right":r.backgroundPosition="right center";break;case"top":r.backgroundPosition="center top";break;case"bottom":r.backgroundPosition="center bottom"}else t||e?r.backgroundPosition=`${Number(t)||0}px ${Number(e)||0}px`:delete r.backgroundPosition}break;case"gradient":r.background=function(t,e){const n=e.colorStops,r=e.gradientType;if(n instanceof Array&&n.length>0)switch(r){case"radial":return"radial-gradient(farthest-corner at "+function(t,e){const{width:n,height:r}=t.bounds;switch(e){case"center":return[n/2,r/2];case"left-top":return[0,0];case"right-top":return[n,0];case"left-bottom":return[0,r];default:return[n,r]}}(t,e.center||"center").map(t=>t+"px").join(" ")+","+n.map(t=>`${t.color} ${100*t.position}%`).join(",")+")";case"linear":return"linear-gradient("+(180*(e.rotation||0)/3.141592653589793+90+"deg")+", "+n.map(t=>`${t.color} ${100*t.position}%`).join(",")+")"}return""}(t,n)}else r.background="transparent"}const es={x:1,y:1},ns={boxSizing:"border-box",margin:"0px",position:"absolute",outline:"none"};function rs(t){let{id:e,scale:n=es,bold:r,italic:i,fontFamily:s="",textAlign:o,textBaseline:a,textOverflow:c,paddingTop:l,paddingBottom:h,paddingLeft:d,paddingRight:u,fontSize:p=Mi.FONT_SIZE,lineWidth:f=0,lineHeight:g,lineDash:m}=t.state;h||=0,l||=0,d||=0,u||=0;const y=t.state.class,{strokeStyle:b,rotation:v=0,fontColor:_,hidden:x}=t,{left:w,top:M,width:S,height:A}=t.bounds,E=t.element;if(E.hidden=x,e&&(E.id=e),y&&(E.className=y),Object.assign(E.style,ns,{fontFamily:s,fontSize:p+"px",width:S+"px",height:A+"px",paddingTop:l+"px",paddingRight:u+"px",paddingBottom:h+"px",paddingLeft:d+"px",border:f+"px",borderColor:b,borderStyle:f>0?m||Mi.LINE_DASH:"",color:_,fontWeight:r?"bold":"",fontStyle:i?"italic":"",textAlign:"end"==o?"right":"start"==o?"left":o,verticalAlign:a,lineHeight:void 0===g?"":g+"px",whiteSpace:c?"nowrap":"",overflow:c?"hidden":"",textOverflow:c||""},t.isIn3DSpace()?{}:{left:w+"px",top:M+"px"}),ts(t),function(t){if(!t.isShadowable()||!t.state.shadow)return;const e=t.element,{left:n=0,top:r=0,blurSize:i=0,color:s="transparent"}=t.state.shadow;e.style.boxShadow=`${n}px ${r}px ${i}px ${s}`}(t),t.isIn3DSpace())return;const k=t.delta(),C=(n&&n.x||1)*k.sx,P=(n&&n.y||1)*k.sy,T=(v||0)+k.theta,D=k.tx||0,O=k.ty||0;E.style.transform=`rotate(${T}rad) translate(${D}px, ${O}px) scale(${C}, ${P}) perspective(1px)`}function is(t,e){let n=this.bounds,r=this.rotatePoint;const i=this.get("rotation"),s=this.get("scale");if(t){const r=t.call(e,n);r&&(n=r)}const{left:o,top:a,width:c,height:l}=n;let h=[{x:o,y:a},{x:o+c,y:a+l}];h=h.map(t=>Gi(t.x,t.y,r,i,s));let d=h[0],u=h[1];r={x:(d.x+u.x)/2,y:(d.y+u.y)/2},h=h.map(t=>Vi(t.x,t.y,r,i,s)),d=h[0],u=h[1],this.bounds={left:d.x,top:d.y,width:u.x-d.x,height:u.y-d.y}}function ss(t,e,n){let r=this.path,i=this.rotatePoint;this.get("rotation"),this.get("scale"),t&&(r=t.call(n,r));let s=r.map(t=>{const e=this.toParent(t.x,t.y);return void 0!==t.z&&(e.z=t.z),e});if(e){const t=e.call(n,s);t&&(s=t)}const o={x:0,y:0};let a,c,l,h;r=s.map(t=>this.fromParent(t.x,t.y,o)),a=c=r[0].x,l=h=r[0].y;for(let t=1;t<r.length;t++){const e=r[t];e.x<a?a=e.x:e.x>c&&(c=e.x),e.y<l?l=e.y:e.y>h&&(h=e.y)}i={x:(a+c)/2,y:(l+h)/2},i=this.toParent(i.x,i.y,o),this.path=s.map(t=>{const e=this.fromParent(t.x,t.y,i);return void 0!==t.z&&(e.z=t.z),e})}let os,as=[];function cs(){os=null;const t=performance.now();as=as.filter(t=>ls(t));const e=as.reduce((e,n)=>{const r=t-n.updatedAt;return r>=n.retention?e.kills.push(n):e.next=0==e.next?n.retention-r:Math.min(e.next,n.retention-r),e},{next:0,kills:[]});e.kills.forEach(t=>{const e=as.indexOf(t);-1!=e?(as.splice(e,1),t.removeSelf(!0)):jr("Should not be here. Maybe reentrance problem.")}),e.next>0&&(os=setTimeout(hs,Math.max(e.next,500)))}function ls(t){return!t.disposed&&t.retention>0&&!t.isTemplate()&&t.app&&t.app.isViewMode}const hs=Zn(function(){requestAnimationFrame(cs)},500);var ds=new class{add(t){ls(t)&&-1==as.indexOf(t)&&(as.push(t),t.touch()),this.touch()}remove(t){const e=as.indexOf(t);e>0&&as.splice(e,1),this.touch()}touch(){null!==os&&(clearTimeout(os),os=null),hs()}dispose(){hs.cancel(),null!==os&&(clearTimeout(os),os=null),as=[]}get length(){return as.length}};const us=function(t){return t};function ps(t){const e=t.indexOf("||");let n="",r="";-1!=e&&(n=t,r=t.substring(e+2,t.length-1).trim(),t=t.replace(t.substring(e,t.length-1),"").trim());const i=t.substr(2,t.length-3).trim().replace(/\[(\w+)\]/g,".$1").replace(/^\./,"").split(".").filter(t=>!!t.trim()),s=i.slice(1);return{defaultValue:r,match:t,originText:n||t,target:i[0],accessor:s.length>0?function(t){return s.reduce((t,e)=>t?t[e]:void 0,t)}:us}}function fs(t){if(!t)return;const e=String(t),n=(e.match(/#{(\S*)}/)||[]).map(t=>ps(t))[0];if(n)return n.accessor(this.getState(n.target));const r=(e.match(/\${[^}]*}/)||[]).map(t=>ps(t))[0];if(r){const t=this.root.findById(r.target);return r.accessor(this.getState(t))}return t}function gs(t,e){if(!t)return;const n=String(t),r=e||or,i=(n.match(/#{(\S*)}/gi)||[]).map(t=>ps(t)),s=(n.match(/\${[^}]*}/gi)||[]).map(t=>ps(t));if(0==i.length&&0==s.length)return n;let o=n;return i.forEach(t=>{const e=r(t.accessor(this.getState(t.target)));o=o.replace(t.match,void 0===e?"":e)}),s.forEach(t=>{const e=this.root.findById(t.target),n=r(t.accessor(e&&e.data));o=o.replace(t.match,void 0===n?"":n)}),o}function ms(t,e,n){if(!t)return;const r=n||or,i=String(t),s=(i.match(/#{[^}]*}/gi)||[]).map(t=>ps(t)),o=(i.match(/\${[^}]*}/gi)||[]).map(t=>ps(t));return 0!=s.length||0!=o.length?function(){let t=i;return s.forEach(n=>{const i=r(n.accessor(e.getState(n.target)));t=t.replace(n.originText,void 0===i?n.defaultValue||"":i)}),o.forEach(n=>{const i=e.root.findById(n.target),s=r(n.accessor(i&&i.data));t=t.replace(n.originText,void 0===s?n.defaultValue||"":s)}),t}:void 0}class ys{constructor(){}static registerDecorator(t,e){ys.constructors.set(t,e)}static create(t,e,n={},r){const i=ys.constructors.get(t);if(!i)throw new Error(`unknown decorator type: ${t}`);return new i(r,e,n)}}ys.constructors=new Map;class bs{constructor(){this.overlays=new WeakMap}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}addOverlay(t){if(this.overlays.has(t))return!1;const e={element:t,registry:new Map};return this.overlays.set(t,e),!0}removeOverlay(t){if(!this.overlays.has(t))return!1;const e=this.overlays.get(t);for(const[n]of e.registry)this.removeFromOverlay(t,n);return this.overlays.delete(t),!0}addToOverlay(t,e,n,r={}){this.overlays.has(t)||this.addOverlay(t);const i=this.overlays.get(t);i.registry.has(e)||i.registry.set(e,new Map);const s=i.registry.get(e);s.has(n)&&s.get(n).stop();const o=ys.create(n,e,r,t);return s.set(n,o),o.start(),o}removeFromOverlay(t,e,n){if(!this.overlays.has(t))return;const r=this.overlays.get(t);if(!r.registry.has(e))return;const i=r.registry.get(e);let s=null;if(n){if(i.has(n))try{const t=i.get(n);s=n,t&&"function"==typeof t.stop&&t.stop(),i.delete(n)}catch(t){jr(`데코레이터(${n}) 제거 중 오류:`,t)}}else{const t=Array.from(i.keys());for(const e of t)try{const t=i.get(e);t&&"function"==typeof t.stop&&t.stop(),i.delete(e)}catch(t){jr(`데코레이터(${e}) 제거 중 오류:`,t)}s="_all_"}0===i.size&&r.registry.delete(e),!s||"data-spread"!==s&&"_all_"!==s||this.restartBorderAnimations(t,e)}restartBorderAnimations(t,e){if(!this.overlays.has(t))return;const n=this.overlays.get(t);for(const[t,r]of n.registry.entries()){if(e&&t===e)continue;const n=r.get("border-highlighting");if(n)try{"function"==typeof n.invalidate&&n.invalidate();const t=n;"function"==typeof t.startAnimations&&t.options&&t.options.animation&&t.startAnimations()}catch(t){jr("애니메이션 재시작 중 오류:",t)}}}removeAllFromOverlay(t,e){if(!this.overlays.has(t))return;const n=this.overlays.get(t);if(e)for(const[r]of n.registry)this.removeFromOverlay(t,r,e);else{for(const[t,e]of n.registry)for(const t of e.values())t.stop();n.registry.clear()}}getDecoratorFromOverlay(t,e,n){const r=this.overlays.get(t);return r?.registry.get(e)?.get(n)}getDecoratorsFromOverlay(t,e){const n=this.overlays.get(t);return n&&n.registry.has(e)?Array.from(n.registry.get(e).values()):[]}getTargetsWithType(t,e){const n=this.overlays.get(t);if(!n)return[];const r=[];for(const[t,i]of n.registry)i.has(e)&&r.push(t);return r}updateInOverlay(t,e,n,r){const i=this.getDecoratorFromOverlay(t,e,n);i&&i.update(r)}invalidateOverlay(t){if(!this.overlays.has(t))return;const e=this.overlays.get(t),n=Array.from(e.registry.entries());for(const[e,r]of n){if(e.disposed){this.removeFromOverlay(t,e);continue}this.getDecoratorsFromOverlay(t,e).forEach(t=>{t.invalidate()})}}}function vs(t,e){return!1}function _s({x:t,y:e},...n){const r=this.path,i=t,s=e;this.path=r.map(t=>({x:t.x+i,y:t.y+s}))}function xs(t){const e=t??this.center.x,{rotation:n}=this.state,r=this.fillStyle;if(this.set("rotation",2*Math.PI-n),r&&"gradient"===r.type&&"linear"===r.gradientType){const t=Bn(r);t.rotation=(Math.PI-parseFloat(r.rotation||0))%(2*Math.PI),this.set("fillStyle",t)}this.path=this.path.map(t=>({x:2*e-t.x,y:t.y}))}function ws(t){this.symmetryX(),this.set("rotation",(Math.PI+this.model.rotation)%(2*Math.PI)),t&&this.move({x:0,y:2*(t-this.center.y)},!1)}function Ms(t,e,n){if(n){const e=this.bounds,n=e.height/e.width;let r=t.width-e.width,i=t.height-e.height;r*n>i?i=r*n:r=i/n;let s=t.left-e.left,o=t.top-e.top;return 0!=s&&0!=o?(o=-i,s=-r):0!=s?s=-r:0!=o&&(o=-i),{left:e.left+s,top:e.top+o,width:e.width+r,height:e.height+i}}return t}function Ss(t,e){if(e||this.app.rotateStepForced){const e=this.app.rotateStep;return Math.floor((t+e/2)/e)*e}return t}function As(t){return function(t,e){const n=t.path.slice();if(!n||!n.length)return void jr("path should not be empty");let r=1;const i=[];if(t.isLine()||n.push(n[0]),e<=0)return t.toScene(n[0].x,n[0].y);if(e>=1)return t.toScene(n[n.length-1].x,n[n.length-1].y);for(;n[r];){const t=n[r-1],e=n[r],s=e.x-t.x,o=e.y-t.y;i.push(Math.sqrt(s*s+o*o)),r++}const s=i.reduce(function(t,e){return t+e},0);r=0;let o=0;do{o+=i[r++]}while(o/s<e);o-=i[--r],e=(e-o/s)*(s/i[r]);const a=n[r%n.length],c=n[(r+1)%n.length],l=a.x+Math.round((c.x-a.x)*e),h=a.y+Math.round((c.y-a.y)*e);return t.toScene(l,h)}(this,t||0)}function Es(){const t=this.path;let e,n,r,i;e=n=t[0].x,r=i=t[0].y;for(let s=1;s<t.length;s++){const o=t[s];o.x<e?e=o.x:o.x>n&&(n=o.x),o.y<r?r=o.y:o.y>i&&(i=o.y)}return{left:e,top:r,width:n-e,height:i-r}}function ks(t){const e=this.bounds;if(Math.round(100*t.width)/100==Math.round(100*e.width)/100&&Math.round(100*t.height)/100==Math.round(100*e.height)/100&&Math.round(100*t.left)/100==Math.round(100*e.left)/100&&Math.round(100*t.top)/100==Math.round(100*e.top)/100)return;const n=0==e.width?1:t.width/e.width,r=0==e.height?1:t.height/e.height;this.path=this.path.map(i=>({x:t.left+(i.x-e.left)*n,y:t.top+(i.y-e.top)*r}))}function Cs(){const t=this.bounds;return{x:t.left+t.width/2,y:t.top+t.height/2}}function Ps(t){if(!t||isNaN(t.x)||isNaN(t.y))return;const e=this.center;if(Math.round(100*t.x)/100==Math.round(100*e.x)/100&&Math.round(100*t.y)/100==Math.round(100*e.y)/100)return;const n=t.x-e.x,r=t.y-e.y;this.path=this.path.map(t=>({x:t.x+n,y:t.y+r}))}function Ts(){const{x:t,y:e}=this.center;return{x:t,y:e,z:this.state.zPos}}function Ds(t){const{x:e,y:n,z:r}=t||{};this.center={x:e,y:n},isNaN(r)||this.setState("zPos",Number(r))}function Os(){const{rotationX:t,rotationY:e,rotation:n}=this.state;return{x:t,y:e,z:-n}}function zs(t){const{x:e,y:n,z:r}=t;this.setState({rotationX:e,rotationY:n,rotation:-r})}function Is(){const{width:t,height:e}=this.bounds,{depth:n}=this.state;return{width:t,height:e,depth:n}}function Ls(t){const{width:e,height:n,depth:r}=t,{top:i,left:s}=this.bounds;this.bounds={top:i,left:s,width:e,height:n},this.setState("depth",r)}function js(){return jr("이 컴포넌트에 get path 가 구현되어있지 않음.",this),[]}function Rs(t){jr("이 컴포넌트에 get path 가 구현되어있지 않음.",this)}function Fs(){return this.path}function Bs(){return this.center}function Ns(){return this.nature.mutable}function Hs(){return this.nature.resizable&&!this.stuck}function Vs(){return this.nature.rotatable&&!this.stuck}const Gs={x:1,y:1};function Ys(t,e,n){const{left:r=0,top:i=0,blurSize:s=0,color:o="transparent"}=e,a=n.rootModel.get("scale")||Gs;t.shadowOffsetX=r*a.x*_i,t.shadowOffsetY=i*a.y*_i,t.shadowBlur=s*a.x*_i,t.shadowColor=o}function Us(t){t.save(),this.prerender(t),this.render(t),this.postrender(t),t.restore()}function $s(t){const e=this.rotatePoint,{scale:n,rotation:r,shadow:i,alpha:s}=this.state,o=(n&&n.x||1)*this._delta.sx,a=(n&&n.y||1)*this._delta.sy,c=(r||0)+this._delta.theta,{tx:l=0,ty:h=0}=this._delta,d=(s||1)-this._delta.fade;(l||h)&&t.translate(l,h),(1!=o||1!=a||c)&&(t.translate(e.x,e.y),1==o&&1==a||t.scale(o,a),c&&t.rotate(c),t.translate(-e.x,-e.y)),d&&(t.globalAlpha=d),i&&Ys(t,i,this),this.app.isEditMode&&this.hidden&&(t.globalAlpha*=.5)}function Ws(t){}function Xs(t){this.drawText(t)}function qs(t,e){t(this)}function Ks(t){t&&this.prepare&&this.prepare(t=>{this.invalidate()},t=>{jr(t)})}function Qs(t){!this.textHidden&&this.text&&this.hasTextProperty&&Fi(t,this.textBounds,this.textLines(t),this.state)}function Zs(t,e){Di(t,e?{...this.state,...e}:this.state)}function Js(t,e){this.fillStyle&&"transparent"!=this.fillStyle&&(ki(t,this.bounds,this.center,e?{...this.state,...e}:this.state,this),function(t){t.shadowColor="transparent"}(t))}function to(){return this.get("strokeStyle")}function eo(t){this.set("strokeStyle",t)}function no(){return this.getState("fillStyle")}function ro(t){this.setState("fillStyle",t)}function io(){return this.get("fontColor")}function so(t){this.set("fontColor",String(or(t)))}function oo(){return this.getState("rotation")}function ao(t){this.setState("rotation",Number(or(t)))}function co(){return this.app.isEditMode?["decotag","data-spread"]:[]}function lo(){const{id:t,tag:e}=this.state;return(t?`#${t}`:"")+(e?`@${e}`:"")}function ho(){return this.getState("hidden")||!this.data&&0!==this.data&&this.getState("ndns")||this.isTemplate()}function uo(t){this.setState("hidden",t)}function po(){return this.state.tag}function fo(t){this.setState("tag",t)}function go(){}function mo(t){this.data instanceof Array?this.data=this.data.concat(t):this.data instanceof Object?this.data={...this.data,...t}:this.data??=t}function yo(){const t=this.getState("text");return null==t?"":String(t)}function bo(t){const{textWrap:e,supportMarkdown:n}=this.state;return Li(t||this.getContext(),this.textBounds.width,this.font,this.text,e,n)}function vo(){return ji(this.model)}function _o(){const t=this.get("lineHeight");return t||1.2*this.fontSize}function xo(){return this._text_substitutor||(this._text_substitutor=ms(this.getState("text"),this,void 0)||this.defaultTextSubstitutor),this._text_substitutor}function wo(){const t=this.get("textFormat");return t?function(t,e){if(!t||isNaN(+e))return e;let n,r,i,s,o,a,c,l,h,d,u,p=t.length,f=t.search(/[0-9\-\+#]/),g=f>0?t.substring(0,f):"",m=t.split("").reverse().join(""),y=m.search(/[0-9\-\+#]/),b=p-y,v=t.substring(b,b+1),_=b+("."===v||","===v?1:0),x=y>0?t.substring(_,p):"";if(n=(e="-"===(t=t.substring(f,_)).charAt(0)?-e:+e)<0?e=-e:0,r=t.match(/[^\d\-\+#]/g),i=".",s=r&&r[1]&&r[0]||",",t=t.split("."),e=+(e=e.toFixed(t[1]&&t[1].length))+"",a=t[1]&&t[1].lastIndexOf("0"),l=e.split("."),(!l[1]||l[1]&&l[1].length<=a)&&(e=(+e).toFixed(a+1)),h=t[0].split(s),t[0]=h.join(""),o=t[0]&&t[0].indexOf("0"),o>-1)for(;l[0].length<t[0].length-o;)l[0]="0"+l[0];else 0===+l[0]&&(l[0]="");if((e=e.split("."))[0]=l[0],c=h[1]&&h[h.length-1].length,c){for(d=e[0],m="",b=d.length%c,p=d.length,_=0;_<p;_++)m+=d.charAt(_),!((_-b+1)%c)&&_<p-c&&(m+=s);e[0]=m}return e[1]=t[1]&&e[1]?"."+e[1]:"",r=e.join(""),"0"!==r&&""!==r||(n=!1),u="+"==t[0].substring(0,1)?n?"-":"+":n?"-":"",g+(u+r)+x}(t,this.textSubstitutor()):this.textSubstitutor()}function Mo(t){delete this._text_substitutor;const e=or(t);this.setState("text",null==e?"":String(e))}function So(){let{paddingTop:t,paddingLeft:e,paddingRight:n,paddingBottom:r}=this.state;r||=0,t||=0,e||=0,n||=0;const{left:i,top:s,width:o,height:a}=this.bounds;return{left:i+e,top:s+t,width:Math.max(o-e-n,0),height:Math.max(a-t-r,0)}}function Ao(){return 0}function Eo(){return!!this._textHidden}function ko(t){this._textHidden=!!t,this.invalidate()}function Co(){return!0}function Po(t){return t}function To(t){return Math.pow(t,2)}function Do(t){return 1-Math.sin(Math.acos(t))}function Oo(t,e={x:1.5}){return Math.pow(t,2)*((e.x+1)*t-e.x)}function zo(t){for(let e=0,n=1;;e+=n,n/=2)if(t>=(7-4*e)/11)return-Math.pow((11-6*e-11*t)/4,2)+Math.pow(n,2)}function Io(t,e={x:1.5}){return Math.pow(2,10*(t-1))*Math.cos(20*Math.PI*e.x/3*t)}var Lo={linear:Po,quad:To,circ:Do,back:Oo,bounce:zo,elastic:Io},jo=Object.freeze({__proto__:null,back:Oo,bounce:zo,circ:Do,default:Lo,elastic:Io,linear:Po,quad:To});function Ro(t){const{duration:e=1e3,easing:n,step:r=()=>{},onStart:i,onProgress:s,onComplete:o,options:a,repeat:c=!1,delta:l}=t;let h;h="string"==typeof l?jo[l]:l||Po,"out"===n?h=function(t,e){return function(n){return 1-t(1-n,e)}}(h,a):"inout"===n&&(h=function(t,e){return function(n){return n<.5?t(2*n,e)/2:(2-t(2*(1-n),e))/2}}(h,a));let d=!1,u=null;return{start:function(){if(d)return this;d=!0,i&&i();let t=0;const n=()=>{if(!d)return;0===t&&(t=performance.now());const i=(performance.now()-t)/e,o=c?i%1:Math.min(i,1);r(h(o,a)),s&&s(o),!(i>=1)||c&&d||(this.stop(),t=0),d&&(u=requestAnimationFrame(n))};return u=requestAnimationFrame(n),this},stop:function(){return d=!1,null!==u&&(cancelAnimationFrame(u),u=null),o&&o(),this}}}class Fo{constructor(t,e){this._started=!1,this._raf=null,this._timeout=null,this.client=t,this.config=e,this._started=!1;const{delta:n="linear",options:r,ease:i}=this.config;let s;s="string"==typeof n?Lo[n]:n,this.delta="out"===i?function(t,e){return function(n){return 1-t(1-n,e)}}(s,r):"inout"===i?function(t,e){return function(n){return n<.5?t(2*n,e)/2:(2-t(2*(1-n),e))/2}}(s,r):s,this.init()}dispose(){this.stop(),delete this.client}init(){}start(){if(this._started)return;const{duration:t=2e3,delay:e=0,repeat:n=!1,interval:r=0,onComplete:i}=this.config;this._started=!0;let s=0,o=0;const a=()=>{if(this._raf=null,this._timeout=null,!this._started)return;0==s&&(s=performance.now(),this.client?.touch?.());const c=performance.now()-s,l=Math.max((c-e)%(t+r),0)/t,h=r<=0&&o>l;if(o=l,l>=1||h){if(this.step(1),this.client&&this.client.invalidate?.(),!n||!this._started)return this.stop(i),void(s=0);if(r>0)return void(this._timeout=setTimeout(()=>{this.step(0),this.client&&this.client.invalidate?.(),this._timeout=setTimeout(a,r/2)},r/2))}else this.step(this.delta(l)),this.client&&this.client.invalidate?.();this._raf=requestAnimationFrame(a)};this._raf=requestAnimationFrame(a)}stop(t){this._raf&&cancelAnimationFrame(this._raf),this._timeout&&clearTimeout(this._timeout),this._raf=null,this._timeout=null,this._started=!1,t?.()}step(t){}get started(){return this._started}set started(t){this.started!=!!t&&(t?this.start():this.stop())}}const Bo={rotation:class extends Fo{step(t){const{theta:e=6.28}=this.config;this.client.delta?.("theta",t*e)}},vibration:class extends Fo{step(t){const{theta:e=.2617993877991494}=this.config,n=4*e;let r=t*n;t<1/4?r*=-1:t<3/4?r-=2*e:r=n-r,this.client.delta?.("theta",r)}},heartbeat:class extends Fo{step(t){const{scale:e=1.3}=this.config,n=2*(e-1);let r;r=t<.5?1+n*t:1+(1-t)*n,this.client.delta?.({sx:r,sy:r})}},moving:class extends Fo{step(t){const{x:e=0,y:n=0}=this.config;this.client.delta?.({tx:t*e,ty:t*n})}},outline:class extends Fo{step(t){const{rideOn:e}=this.config;if(!e||!this.client)return;const n=this.client.root.findById(e);if(!n)return;let r={tx:0,ty:0};const i=this.client.delta("");i&&"object"==typeof i&&"tx"in i&&"ty"in i&&(r=i);const{tx:s,ty:o}=r,a=n.outline(t),{x:c,y:l}=this.client.center,h=this.client.toScene(c,l);this.client.delta({tx:a.x-h.x+s,ty:a.y-h.y+o})}},fade:class extends Fo{step(t){const{startAlpha:e=1,endAlpha:n=0}=this.config,r=Math.max(Math.min(e,n,1),0),i=2*(Math.min(Math.max(e,n,1),1)-r);let s;s=t<.5?i*t:(1-t)*i,this.client.delta?.("fade",s)}},waypoint:class extends Fo{start(){let{toComponent:t,fromComponent:e}=this.config;e||(e=t);const n=e.center,r=t.center,{x:i,y:s}=e.toScene(n.x,n.y),{x:o,y:a}=t.toScene(r.x,r.y),c=Math.atan2(a-s,o-i)+Math.PI/2;this.client.location={x:i,y:s},this.client.setState("rotation",c),super.start()}stop(){const{toComponent:t}=this.config;super.stop();const e=t.center,n=t.toScene(e.x,e.y);this.client.delta({tx:0,ty:0}),this.client.location=n}step(t){let{toComponent:e,fromComponent:n}=this.config;n||(n=e);const r=n.center,i=e.center,{x:s,y:o}=n.toScene(r.x,r.y),{x:a,y:c}=e.toScene(i.x,i.y),l=(a-s)*t,h=(c-o)*t;this.client.location={x:s+l,y:o+h}}}};function No(t,e){const n=e.type?Bo[e.type]:void 0;return n?new n(t,e):null}const Ho={gradation:function(t,e,n){const{subType:r,from:i,to:s,colors:o}=n;let a;switch(r){case"linear":default:a=e.createLinearGradient(i.x,i.y,s.x,s.y);break;case"radial":a=e.createRadialGradient(i.x,i.y,i.r,s.x,s.y,s.r)}o&&(o.forEach(function(t){a.addColorStop(t.endPoint,t.color)}),e.fillStyle=a,e.fill())},shadow:Ys};function Vo(t){return this._animate&&this._animate.stop(),this._animate=Ro(t),this._animate}function Go(t,e){return function(t,e,n){const r=Ho[n.type];r&&r(t,e,n)}(this,t,e)}function Yo(...t){return JSON.stringify(this.hierarchy,...t)}function Uo(){delete this._model[""],"chartjs"!==this._model.type&&delete this._model.chart}function $o(t){this.rootModel.closeScene(t)}function Wo(t,e){return t?"object"==typeof t?(this._delta={...this._delta,...t},this._delta):void 0!==e?(this._delta[t]=e,this._delta[t]):void 0:this._delta}function Xo(){this.parent&&this.parent.invalidate()}function qo(){const t=this.nature["value-property"]||"text";return"value"==t?this.getState("value"):this[t]}function Ko(t){const e=this.nature["value-property"]||"text";"value"==e?this.setState("value",t):this[e]=t}function Qo(){return this.getState("data")}function Zo(t){this.setState("data",t),this.touch()}function Jo(t){const e=this.model.event?.tap;if(e){const{x:t,y:n}=this.center;this.rootModel?._doEventAction(e,this,!0,new MouseEvent("click",{clientX:t,clientY:n}))}}function ta(){return!this._mappings&&this.parent&&this.buildMappings(),this._mappings}function ea(){return Number(this.get("retention"))||0}function na(){if(this.app.isViewMode&&!this.isTemplate()){if(!this._animation){const t=this.state.animation;t&&t.oncreate&&(this._animation=No(this,t.oncreate))}return this._animation}}function ra(){return!!this.animation?.started}function ia(t){this.animation&&(this.animation.started=t)}function sa(){}function oa(t,e,n,r){const i=e.get("class");if(!i)return!1;return(i.split(" ")||[]).indexOf(t.substr(1))>=0}function aa(t,e,n,r){return t==e.get("type")}function ca(t,e,n,r){if("(all)"==t)return!0;switch(t.charAt(0)){case"#":return function(t,e){return t.substring(1)==e.get("id")}(t,e);case".":return oa(t,e);case"(":return function(t,e,n,r){switch(t){case"(all)":return!0;case"(self)":return r===e;case"(root)":return!r.parent&&r===e;case"(descendant)":return r!==e;case"(child)":return r===e.parent;default:return!1}}(t,e,0,r);default:return aa(t,e)}}function la(t,e,n,r,i,s){return t(e,n,r,i)&&s.push(n),n.components&&n.components.forEach(n=>{la(t,e,n,r,i,s)}),s}function ha(t,e,n,r){switch(t){case"(all)":return!0;case"(parent)":return n&&n.parent===e;case"(child)":case"(children)":return n&&n===e.parent;case"(sibling)":case"(siblings)":return n&&n.parent===e.parent&&n!==e;default:return!1}}function da(t,e,n){if("(root)"==t)return[e];if("(self)"==t)return n?[n]:[];let r;switch(t.charAt(0)){case"#":const n=e.root.findAllById?.(t.substring(1));return n||[];case".":r=oa;break;case"(":r=ha;break;default:r=aa}return la(r,t,e,n,e,[])}function ua(t,...e){if(t(this,...e))return this}function pa(t,...e){return"string"==typeof t?da(t,this,e[0]||this):"function"==typeof t&&t(this,...e)?[this]:void 0}function fa(t,e,n){if(!this.capturable||n?.(this))return!1;const r=this.fromParent(t,e);return this.contains(r.x,r.y)?this:void 0}function ga(t){return this.anchors.find(e=>e.name===t)}function ma(t){return!0}function ya(t){return this._parent.getContext(t??this)}function ba(){return this.isRoot()?this:this.parent&&this.parent.root}function va(){return this.isRootModel()?this:this.parent&&this.parent.rootModel}function _a(){return this._parent}function xa(t){this._parent=t}function wa(){return this.nature.anchors||[]}function Ma(){let t=this.position,e=this;for(;"static"===t&&e.parent;)e=e.parent,t=e.position;return"static"==t}function Sa(){return!!(this.parent&&this.parent.layout.isStuck(this)||this.get("locked"))}function Aa(){return!1!==this.get("capturable")&&(this.app.isEditMode||!this.hidden)}function Ea(){return this.app?.isViewMode&&this.isPositionable()?this.state.position??"static":"static"}function ka(){return this.app&&this.app.isViewMode&&this.state.origin||""}function Ca(){const{offsetX:t=0,offsetY:e=0}=this.state;return{x:t,y:e}}function Pa(){return!this._app&&this.parent&&(this._app=this.parent.app),this._app}const Ta={},Da={mutable:!1,resizable:!0,rotatable:!0,properties:[],"value-property":"text"},Oa=[],za=new Set(["data","text","value","source","accessor","mappings","variables","fillStyle","strokeStyle","fontColor","alpha","opacity","hidden","locked","hatched","started","animation","sensitive","event","src","href","url","class","templatePrefix"]),Ia={theta:0,tx:0,ty:0,sx:1,sy:1,fade:0};let La=0;const ja={};const Ra=new FinalizationRegistry(t=>{!function(t){La--;let e=ja[t];e||(e=ja[t]={up:0,down:0}),e.down++}(t)});class Fa{static get nature(){return Da}static register(t,e){if(!e)return Ta[t];Ta[t]=e}static get residents(){return ja}static get residentsCount(){return La}static registerDecorator(t,e){ys.registerDecorator(t,e)}constructor(t,e){this._app=e,this._model=t||{},this._state={},this._delta=Bn(Ia),e&&this.animation?.config&&(1==this.animation.config.autoplay||(this.animation.config.autoplay??1))&&(this.animation.started=!0),this.clearCache(),ds.add(this),function(t){La++;let e=ja[t];e||(e=ja[t]={up:0,down:0}),e.up++}(this._model.type),Ra.register(this,this._model.type)}created(){}added(t){}removed(t){}async ready(){if(this.state.persistent){const{isViewMode:t,dataStorage:e}=this.app;t&&(this.data=await e.load(this))}}touch(){this.updatedAt=performance.now()}clearCache(...t){this._cachedState=null,function(t,...e){0==e.length?t.__cache__={}:e.forEach(e=>delete t.__cache__[e])}(this,...t)}removeSelf(t){t?this.dispose():this.parent?.removeComponent?.(this)}resetAnimation(){this._animation&&(this._animation.dispose(),this._animation=null,this._delta=Bn(Ia))}dispose(){this.resetAnimation(),this.disposeMappings(),this.parent?.removeComponent?.(this),delete this._text_substitutor,delete this._value_substitutor,this._disposed=!0,this._realObject&&(this._realObject.dispose(),this._realObject=void 0),this.retention&&ds.touch(),this.clearCache(),delete this._app}get nature(){return this.constructor.nature}get disposed(){return!!this._disposed}isLayer(){return!1}isGroup(){return!1}isContainer(){return!1}isLine(){return!1}isRoot(){return!1}isRootModel(){return!1}is3dish(){return!1}get is3dMode(){return!1}isIn3DSpace(){return!!this._realObject}isTemplate(){return!!this.get("templatePrefix")}isHTMLElement(){return!1}isConnectable(){return!1}isIdentifiable(){return!0}isPositionable(){return this.parent?.isRootModel()}replaceRefids(t){}get(t){return this._model[t]}set(t,e){if("string"==typeof t)return this.set({[t]:e});const n=this;return this._applyProps(this._model,t,{getBeforeVal:function(t){return n._model[t]},clearState:!0,sensitive:!1,beforeFillStyle:function(t,e){t.hasOwnProperty("retention")&&ds.add(n)},afterFillStyle:function(t,e){t.hasOwnProperty("mappings")&&n.onchangeMappings(t,e)}})}getState(t){return this._state.hasOwnProperty(t)?this._state[t]:this.get(t)}setState(t,e){if("string"==typeof t)return this.setState({[t]:e});const n=this;return this._applyProps(this._state,t,{getBeforeVal:function(t){return n.getState(t)},clearState:!1,sensitive:this.getState("sensitive")})}get model(){return this._model}get state(){return this._cachedState||(this._cachedState=Object.freeze(Object.assign({},this._model,this._state))),this._cachedState}get hierarchy(){const t=Bn(this._model);return this.volatile.forEach(e=>{delete t[e]}),t}get volatile(){return Oa}_applyProps(t,e,n){const r={},i={};let s=!1;const o=Bn(e),a=this;if(Object.getOwnPropertyNames(o).forEach(function(e){const c=n.getBeforeVal(e),l=o[e];!n.sensitive&&function(t,e){return be(t,e)}(c,l)||(i[e]=c,r[e]=l,t[e]=l,n.clearState&&delete a._state[e],s=!0)}),s){this._cachedState=null;Object.keys(r).some(t=>!za.has(t))&&this.clearCache(),r.hasOwnProperty("text")&&delete this._text_substitutor,n.beforeFillStyle&&n.beforeFillStyle(r,i),r.hasOwnProperty("fillStyle")&&this.onchangeFill(r,i),n.afterFillStyle&&n.afterFillStyle(r,i),r.hasOwnProperty("data")&&this.onchangeData(r,i),this.onchange&&this.onchange(r,i),this.trigger("change",r,i)}return this}contains(t,e){return vs.call(this,t,e)}move(t,...e){_s.call(this,t,...e)}symmetryX(t){xs.call(this,t)}symmetryY(t){ws.call(this,t)}adjustResize(t,e,n){return Ms.call(this,t,e,n)}adjustRotation(t,e){return Ss.call(this,t,e)}outline(t){return As.call(this,t)}get bounds(){return Es.call(this)}set bounds(t){ks.call(this,t)}get center(){return Cs.call(this)}set center(t){Ps.call(this,t)}get location(){return Ts.call(this)}set location(t){Ds.call(this,t)}get rotate(){return Os.call(this)}set rotate(t){zs.call(this,t)}get dimension(){return Is.call(this)}set dimension(t){Ls.call(this,t)}get path(){return js.call(this)}set path(t){Rs.call(this,t)}get drawPath(){return Fs.call(this)}get rotatePoint(){return Bs.call(this)}get mutable(){return Ns.call(this)}get resizable(){return Hs.call(this)}get rotatable(){return Vs.call(this)}buildRealObject(){}get realObject(){return this.disposed||this._realObject||(this._realObject=this.buildRealObject(),this._realObject&&(this._realObject.update(),this._realObject.updateTransform())),this._realObject}draw(t){t&&Us.call(this,t)}prerender(t){$s.call(this,t)}render(t){Ws.call(this,t)}postrender(t){Xs.call(this,t)}prepare(t,e){qs.call(this,t,e)}prepareIf(t){Ks.call(this,t)}drawText(t){Qs.call(this,t)}drawStroke(t,e){Zs.call(this,t,e)}drawFill(t,e){Js.call(this,t,e)}get strokeStyle(){return to.call(this)}set strokeStyle(t){eo.call(this,t)}get fillStyle(){return no.call(this)}set fillStyle(t){ro.call(this,t)}get fontColor(){return io.call(this)}set fontColor(t){so.call(this,t)}get rotation(){return oo.call(this)}set rotation(t){ao.call(this,t)}get decorators(){return co.call(this)}get decotag(){return lo.call(this)}get hidden(){return ho.call(this)}set hidden(t){uo.call(this,t)}get tag(){return po.call(this)}set tag(t){fo.call(this,t)}get appendum(){return go.call(this)}set appendum(t){mo.call(this,t)}defaultTextSubstitutor(){return yo.call(this)}textLines(t){return bo.call(this,t)}get font(){return vo.call(this)}get lineHeight(){return _o.call(this)}get textSubstitutor(){return xo.call(this)}get text(){return wo.call(this)}set text(t){Mo.call(this,t)}get textBounds(){return So.call(this)}get textRotation(){return Ao.call(this)}get textHidden(){return Eo.call(this)}set textHidden(t){ko.call(this,t)}get hasTextProperty(){return Co.call(this)}animate(t){return Vo.call(this,t)}effect(t,e){return Go.call(this,t,e)}serialize(...t){return Yo.call(this,...t)}trim(){Uo.call(this)}closeScene(t){$o.call(this,t)}delta(t,e){return Wo.call(this,t,e)}invalidate(){Xo.call(this)}get value(){return qo.call(this)}set value(t){Ko.call(this,t)}get data(){return Qo.call(this)}set data(t){Zo.call(this,t)}set tap(t){Jo.call(this,t)}get mappings(){return ta.call(this)}get retention(){return ea.call(this)}get animation(){return na.call(this)}get started(){return ra.call(this)}set started(t){ia.call(this,t)}get controls(){return sa.call(this)}findFirst(t,...e){return ua.call(this,t,...e)}findAll(t,...e){return pa.call(this,t,...e)}capture(t,e,n){return fa.call(this,t,e,n)}findAnchor(t){return ga.call(this,t)}isDescendible(t){return ma.call(this,t)}getContext(t){return ya.call(this,t)}get root(){return ba.call(this)}get rootModel(){return va.call(this)}get parent(){return _a.call(this)}set parent(t){xa.call(this,t)}get anchors(){return wa.call(this)}get scalable(){return Ma.call(this)}get stuck(){return Sa.call(this)}get capturable(){return Aa.call(this)}get position(){return Ea.call(this)}get origin(){return ka.call(this)}get offset(){return Ca.call(this)}get app(){return Pa.call(this)}drawEffect(t){yi.call(this,t)}prepareFill(t,e){Ci.call(this,t,e)}prepareFillIf(t){Pi.call(this,t)}onchangeFill(t,e){Ti.call(this,t,e)}drawImage(t,e,n,r,i,s){mi.call(this,t,e,n,r,i,s)}mutateBounds(t,e){is.call(this,t,e)}mutatePath(t,e,n){ss.call(this,t,e,n)}access(t){return fs.call(this,t)}substitute(t,e){return gs.call(this,t,e)}onchangeMappings(t,e){gi.call(this,t,e)}onchangeData(t,e){ui.call(this,t,e)}buildMappings(){pi.call(this)}executeMappings(t){di.call(this,t)}disposeMappings(){fi.call(this)}ondropfile(t,e){Ni.call(this,t,e)}transcoordS2P(t,e,n){return Ui.call(this,t,e,n)}transcoordP2S(t,e,n){return Yi.call(this,t,e,n)}transcoordS2T(t,e,n){return Wi.call(this,t,e,n)}transcoordT2P(t,e,n){return Xi.call(this,t,e,n)}transcoordT2S(t,e,n){return qi.call(this,t,e,n)}transcoordS2TR(t,e,n){return $i.call(this,t,e,n)}transcoordS2O(t,e,n){return Ki.call(this,t,e,n)}transcoordC2S(t,e,n){return Qi.call(this,t,e,n)}transcoordS2C(t,e,n){return Zi.call(this,t,e,n)}toParent(t,e,n){return Ui.call(this,t,e,n)}fromParent(t,e,n){return Yi.call(this,t,e,n)}toScene(t,e,n){return Wi.call(this,t,e,n)}fromScene(t,e,n){return qi.call(this,t,e,n)}toLocal(t,e,n){return Qi.call(this,t,e,n)}toGlobal(t,e,n){return Zi.call(this,t,e,n)}toOther(t,e,n){return Ki.call(this,t,e,n)}on(t,e,n){return Pr.call(this,t,e,n)}off(t,e,n){return Tr.call(this,t,e,n)}once(t,e,n){return Dr.call(this,t,e,n)}trigger(t,...e){return Or.call(this,t,...e)}delegate_on(t){return zr.call(this,t)}delegate_off(t){return Ir.call(this,t)}onchange(t,e){}removeComponent(t,e){}addComponent(t,e){}insertComponentAt(t,e,n){}getOverlay(t){}findById(t){}findByRefid(t){}findAllById(t){return[]}resize(){}fit(t){}get components(){}get layout(){}get auxOverlay(){}get isReady(){return!1}get unitScale(){return 1}get selected(){return[]}set selected(t){}get focused(){return null}set focused(t){}get hasSameParentForAllSelected(){return!1}set hasSameParentForAllSelected(t){}get fitMode(){}set fitMode(t){}get element(){return null}set element(t){}}Fa.union=Ji,Fa.transcoordR=Vi,Fa.transcoordRR=Gi,Fa.createCanvas=Ei,Fa.memoize=Br,Fa.mixin=Lr,Fa.drawText=Fi,Fa.font=ji,Fa.textLines=Li,Fa.drawStroke=Di,Fa.drawFill=ki,Fa.reposition=rs,Fa.RetentionManager=ds,Fa.template=function(t,e,n){var r=ln.imports._.templateSettings||ln;n&&Oe(t,e,n)&&(e=void 0),t=on(t),e=Re({},e,r,qe);var i,s,o=Re({},e.imports,r.imports,qe),a=qt(o),c=function(t,e){return $e(e,function(e){return t[e]})}(o,a),l=0,h=e.interpolate||gn,d="__p += '",u=RegExp((e.escape||gn).source+"|"+h.source+"|"+(h===Ze?fn:gn).source+"|"+(e.evaluate||gn).source+"|$","g"),p=yn.call(e,"sourceURL")?"//# sourceURL="+(e.sourceURL+"").replace(/\s/g," ")+"\n":"";t.replace(u,function(e,n,r,o,a,c){return r||(r=o),d+=t.slice(l,c).replace(mn,Qe),n&&(i=!0,d+="' +\n__e("+n+") +\n'"),a&&(s=!0,d+="';\n"+a+";\n__p += '"),r&&(d+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),l=c+e.length,e}),d+="';\n";var f=yn.call(e,"variable")&&e.variable;if(f){if(pn.test(f))throw new Error("Invalid `variable` option passed into `_.template`")}else d="with (obj) {\n"+d+"\n}\n";d=(s?d.replace(hn,""):d).replace(dn,"$1").replace(un,"$1;"),d="function("+(f||"obj")+") {\n"+(f?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(s?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+d+"return __p\n}";var g=Ue(function(){return Function(a,p+"return "+d).apply(void 0,c)});if(g.source=d,Ye(g))throw g;return g},Fa.buildSubstitutor=ms,["rotatePoint","font","lineHeight","retention"].forEach(t=>Fa.memoize(Fa.prototype,t,!1)),["bounds","center","textBounds"].forEach(t=>Fa.memoize(Fa.prototype,t,!0));class Ba extends Fa{set rotationX(t){this.setState("rotationX",t)}get rotationX(){return this.getState("rotationX")}set rotationY(t){this.setState("rotationY",t)}get rotationY(){return this.getState("rotationY")}set rotationZ(t){this.setState("rotation",t)}get rotationZ(){return this.getState("rotation")}set zPos(t){this.setState("zPos",t)}get zPos(){return this.getState("zPos")}set depth(t){this.setState("depth",t)}get depth(){return this.getState("depth")}postrender(t){this.drawFill(t,void 0),this.drawStroke(t,void 0),super.postrender(t)}render(t){const e=this.drawPath,{round:n=0}=this.state;if(!(e.length<=1)){t.beginPath();for(let r=0;r<e.length;r++){const i=e[(r-1+e.length)%e.length],s=e[(r+e.length)%e.length],o=e[(r+1)%e.length];if(i.x===s.x&&i.y===s.y)continue;let a=Math.sqrt((i.x-s.x)*(i.x-s.x)+(i.y-s.y)*(i.y-s.y)),c=0!==a?Math.atan2(i.x-s.x,i.y-s.y):0,l=Math.sin(c)*Math.min(n,a/2)+s.x,h=Math.cos(c)*Math.min(n,a/2)+s.y;const d=n>0||0!==a?{x:l,y:h}:s;a=Math.sqrt((o.x-s.x)*(o.x-s.x)+(o.y-s.y)*(o.y-s.y)),c=0!==a?Math.atan2(o.x-s.x,o.y-s.y):0,l=Math.sin(c)*Math.min(n,a/2)+s.x,h=Math.cos(c)*Math.min(n,a/2)+s.y;const u=n>0||0!==a?{x:l,y:h}:s;0==r?t.moveTo(d.x,d.y):t.lineTo(d.x,d.y),n>0&&t.quadraticCurveTo(s.x,s.y,u.x,u.y)}t.closePath()}}}function Na(t,e,n){return Math.max(0,Math.min(t,Math.min(n,e)/2))}function Ha(t){const e=class extends t{contains(t,e){const{left:n,top:r,width:i,height:s,lineWidth:o=0}=this.state,a=o/2;return t<Math.max(n+i,n)+a&&t>Math.min(n+i,n)-a&&e<Math.max(r+s,r)+a&&e>Math.min(r+s,r)-a}set path(t){const e=t[0],n=t[2];this.set({left:e.x,top:e.y,width:n.x-e.x,height:n.y-e.y})}get path(){const{left:t=0,top:e=0,width:n=0,height:r=0}=this.state;return[{x:t,y:e},{x:t+n,y:e},{x:t+n,y:e+r},{x:t,y:e+r}]}get anchors(){return function(t){const{left:e,top:n,width:r,height:i}=t.bounds,s=e+r/2,o=n+i/2;return[{name:"TOP",position:{x:s,y:n}},{name:"RIGHT",position:{x:e+r,y:o}},{name:"BOTTOM",position:{x:s,y:n+i}},{name:"LEFT",position:{x:e,y:o}}]}(this)}get bounds(){const{left:t=0,top:e=0,width:n=0,height:r=0}=this.state;return{left:t,top:e,width:n,height:r}}set bounds(t){this.set({left:0,top:0,width:0,height:0,...t})}render(t){let{round:e=0}=this.model;const{left:n,top:r,width:i,height:s}=this.bounds;t.translate(n,r),t.beginPath(),e=Na(e,i,s),e>0?t.roundRect(0,0,i,s,e):t.rect(0,0,i,s),t.translate(-n,-r)}};return Br(e.prototype,"path",!1),Br(e.prototype,"bounds",!0),e}const Va={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"textarea",label:"front-side-template",name:"frontSideTemplate",property:{language:"html"}},{type:"textarea",label:"back-side-template",name:"backSideTemplate",property:{language:"html"}},{type:"textarea",label:"style",name:"style",property:{language:"css"}}],help:"scene/component/info-window"};const Ga=20;function Ya(t,e){const n=t.split(/\s+/),r=n.indexOf(e);return-1!=r?n.splice(r,1):n.splice(-1,0,e),n.join(" ")}class Ua extends(Ha(Ba)){static get image(){return Ua._image||(Ua._image=new Image,Ua._image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAY1BMVEVHcEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADIAbxiAAAAIHRSTlMA+gPshCwwWFzYCeLRm7QRG6rLeDZI9JOJJDtjb1HAf1sAT80AAAQQSURBVHhe7MCBAAAAAMKw/KkzOMG2BAAAAKeu3lUohIEggO7jQi5qHqpgwML5/6+0F0y02z31FlvMMLKt86QMQ1ined2Evih1hFFjLfRWjgzDOGZ6JSiM00B9EuHALtQxJLiQBmqSBCeSUEuEGzs1BDjSaHxWOKK5Eyz/4SoMV/hp4+vtcPkdwZD/udwevNg7t1xXYRiKmkB7C+ENlPLq8fxHeX+RGjWQ1D45ldcIulBIvCvYJGBEadyTzxAcfY57NBjpLScOO/bzugcTHe7IMwiSLMcdHZhocMcMgTLjjgZM7F1bCJZ2v27ARGzYDwIk2Z+JYGJ/iiwQLMv+JAEThjkmRG64Q0Q+gIiIiIiIiIiIyFy0KRFt0bOJZAWSUigmkQaJaXhENiRnYBEpkZySRSRGcmIWEaQnYhHRSI5mESmQnIJFZIqQmGhiEYEbEnPjGlEGjYTogW/WUkOXENENSqZfEXmDiIiIiIiIiIiIiIiIiIiImq5ETIpRpBpjJCMeKy6Ri0ZS9MQjkmkkJs1YRDokp2MRyZGclkUkQnIiEQltaX3Lzb6yiGTpl2y/avqSAxGgelCOKI+Kc2isL0TUSsZ4EREREREREREREREREREREfnIQzXrNWSRTeNxnlOwIgueIr6AAyE+CpiqMEUK71IDO4E+LluEKYKnKcMUifEsTZgiJZ5lDVNkwJPcqzBFoPF/HplfxL/w6b4EPGv1h18Weya1TL8iIiIeiIiIiIiIiEjkPefxV+5YA9PPHylB+u5aqgZ39H+jKOxrqtu+pkzvr9YbzoZ6w2OFkzcrA3yE4WZlSSyFk54VoA/wR43+FaD+r9w32QdWvgvjp2ty2xq8qHPHmtyPFxfrK3hw1ejERlAlfR/Ame2OTow05d4rOLLSlHtDVhI0uRO01JeZ405op6zgNNXT+bIRfpIgn+AkU4pOxBscohojdCHu4RRzjC5EYwVHqRONDkSnEvK/CB3QSU32IRW3ZPnj9iEVoGCNTLVrh8ia1x+6wq8xvB5mz8pxu7oPwIn9lcR0AiuX1+1KX+BXqdvXzWsAC0NsGjzZsS/2Bd6yRA5RgIHkXNhSD3whASZ8rrB9mItuEAizac0fDlHxDMEwpQfD1tW4y3Hjfy5s9nOHH3uwWA+EqEJBWCjoTL/S5toBB/7hu6zer74NgqSP39zJU+qQX3ix763mHTqvIVRUVprCljlElRkEjBqNYevH8veBJ2xhiyhE8YctmhDFH7ZoQhR/2KIJUfxhiyRE8YctmhDFH7ZoQhR/2OIJUfxhC9Ppf/t1jgJACERRsHGyYRZB0Ujvf0xD8w6kP7y6RZmgf/oTFTtbbzJVxZWo2Nlqw6TVy5GowNl6ssm7v50obamfSxQAAAAAAAsKLM15fb3vpQAAAABJRU5ErkJggg=="),Ua._image}static toggle(t,e,n,r){if(!e)return void Rr("InfoWindow not defined.");const i=t.root.findById(e);i?i._findInfoWindowByComponent(t)?Ua.hide(t,e):Ua.show(t,e,n,r):Rr("InfoWindow Not Found.",e)}static hide(t,e){if(!e)return;const n=t.root.findById(e);n?n._removeInfoWindow(t):Rr("InfoWindow Not Found.",e)}static show(t,n,r,i){if(!n)return void Rr("InfoWindow not defined.");const s=t.root.findById(n);if(!s)return void Rr("InfoWindow Not Found.",n);if(s._findInfoWindowByComponent(t))return;const{frontSideTemplate:o="",backSideTemplate:a=""}=s.model;let c=[o,a].filter(t=>String(t).trim());if(c=c.map(t=>Fa.template(function(t,e,n){return(e||n?['<div class="info-window-btns">',e?'<button class="closable">&#88</button>':"",n?'<button class="flipable">&#8652</button>':"","</div>"]:[]).concat(['<div class="info-window-content">',t,"</div>"]).join("")}(t,!r,2==c.length))),0==c.length)return;const l='\n.flip {\n backface-visibility: hidden;\n border-radius: 7px;\n height: auto;\n font: normal 14px helvetica, arial, san serif;\n position: absolute;\n opacity: 0.9;\n transform-origin: 50% 50% 0px;\n transition: all 2s;\n min-width: 100px;\n min-height: 50px;\n background-color: #3e424e;\n box-shadow: 2px 3px 2px 0px rgba(0,0,0,0.15);\n}\n\n#side-1 {\n transform: rotateY(0deg);\n}\n\n.flip:after {\n content: "";\n display: block;\n position: absolute;\n opacity: 0.9;\n width: 0;\n height: 0;\n}\n\n.flip.arrow-top:after {\n left: 45%;\n top: -17px;\n border-left: 10px solid transparent;\n border-bottom: 18px solid #323b44;\n border-right: 10px solid transparent;\n}\n\n.flip.arrow-right:after {\n left: 100%;\n top: 48%;\n border-top: 10px solid transparent;\n border-left: 18px solid #323b44;\n border-bottom: 10px solid transparent;\n}\n\n.flip.arrow-bottom:after {\n left: 45%;\n top: 100%;\n border-left: 10px solid transparent;\n border-top: 18px solid #323b44;\n border-right: 10px solid transparent;\n}\n\n.flip.arrow-left:after {\n right: 100%;\n top: 48%;\n border-top: 10px solid transparent;\n border-right: 18px solid #323b44;\n border-bottom: 10px solid transparent;\n}\n\n#side-2 {\n transform: rotateY(180deg);\n}\n\n.flip-side-1 {\n transform: rotateY(0deg) !important;\n}\n\n.flip-side-2 {\n transform: rotateY(180deg) !important;\n}\n\n.info-window-btns {\n position: absolute;\n top: -18px;\n right: 5px;\n overflow: hidden;\n}\n\n.info-window-content {\n padding: 10px;\n color: #efefef;\n font-size: 13px;\n line-height: 1.4;\n}\n\n.info-window-btns button {\n width: 40px;\n height: 40px;\n float: right;\n border: 0;\n border-radius: 50%;\n background-color: #2a7da1;\n margin-right: 3px;\n text-align: center;\n cursor: pointer;\n font-size: 35px;\n color: #fff;\n line-height: 0;\n}\n\n.info-window-btns button:hover {\n background-color: #60bb23;\n}\n'+s.get("style");let{left:h,top:d}=t.bounds;const{x:u,y:p}=i?t.rootModel.toLocal(i.x,i.y):t.toScene(h,d);h=u,d=p;const f=document.createElement("span");f.style.position="absolute";const g=document.createElement("style");let m,y;g.type="text/css",g.appendChild(document.createTextNode(l)),f.appendChild(g),c[0]&&(m=document.createElement("div"),m.id="side-1",m.className="flip",m.style.display="inline-block",m.innerHTML=e.sanitize(c[0](t),{ADD_TAGS:["style"],ADD_ATTR:["class","id","style"]})),c[1]&&(y=document.createElement("div"),y.id="side-2",y.className="flip",y.style.display="inline-block",y.innerHTML=e.sanitize(c[1](t),{ADD_TAGS:["style"],ADD_ATTR:["class","id","style"]}));const b=t.rootModel.getOverlay(t);m&&f.appendChild(m),y&&f.appendChild(y),b.appendChild(f);const v=s._addInfoWindow(t,f,g).signal;if(xi.forEach(function(t){f.addEventListener(t,t=>t.stopPropagation(),{signal:v})}),wi.forEach(function(t){f.addEventListener(t,t=>t.stopPropagation(),{signal:v})}),m){const e=m.querySelector(".info-window-btns > .flipable");e&&e.addEventListener("click",function(t){t.preventDefault(),y.className=Ya(y.className,"flip-side-1"),m.className=Ya(m.className,"flip-side-2")},{signal:v});const r=m.querySelector(".info-window-btns > .closable");r&&r.addEventListener("click",function(e){e.preventDefault(),Ua.hide(t,n)},{signal:v})}if(y){const e=y.querySelector(".info-window-btns > .flipable");e&&e.addEventListener("click",function(t){t.preventDefault(),y.className=Ya(y.className,"flip-side-1"),m.className=Ya(m.className,"flip-side-2")},{signal:v});const r=y.querySelector(".info-window-btns > .closable");r&&r.addEventListener("click",function(e){e.preventDefault(),Ua.hide(t,n)},{signal:v})}const _=m.offsetWidth,x=m.offsetHeight,w=t.rootModel.target.getBoundingClientRect(),M=[];m&&M.push(m),y&&M.push(y);const S={x:h,y:d};let A=t.toGlobal(S.x,S.y);if(A.x+_/2+w.left<w.right&&A.x-_/2>w.left){if(x+Ga<A.y)return f.style.marginLeft=S.x-_/2+"px",f.style.marginTop=S.y-x-Ga+"px",void M.forEach(t=>t.className+=" arrow-bottom");if(A=t.toGlobal(S.x,S.y+x+Ga),w.bottom>A.y+w.top)return f.style.marginLeft=S.x-_/2+"px",f.style.marginTop=S.y+Ga+"px",void M.forEach(t=>t.className+=" arrow-top")}if(A=t.toGlobal(S.x,S.y),A.x-(_+Ga)>w.left)return f.style.marginLeft=S.x-_-Ga+"px",f.style.marginTop=S.y-x/2+"px",void M.forEach(t=>t.className+=" arrow-right");f.style.marginLeft=S.x+Ga+"px",f.style.marginTop=S.y-x/2+"px",M.forEach(t=>t.className+=" arrow-left")}dispose(){this.infoWindows.map(t=>t.component).forEach(t=>this._removeInfoWindow(t)),super.dispose()}get infoWindows(){return this._windows||(this._windows=[]),this._windows}_findInfoWindowByComponent(t){return this.infoWindows.find(e=>e.component===t)}_addInfoWindow(t,e,n){if(this._findInfoWindowByComponent(t))return;const r=new AbortController;return this._windows.push({component:t,window:e,styleElement:n,abortController:r}),r}_removeInfoWindow(t){const e=this._findInfoWindowByComponent(t);if(!e)return;e.abortController.abort();const n=e.window;n&&n.parentNode.removeChild(n);const r=this.infoWindows.lastIndexOf(e);this.infoWindows.splice(r,1)}render(t){const{left:e,top:n,width:r,height:i}=this.bounds;t.beginPath(),this.drawImage(t,Ua.image,e,n,r,i)}get hasTextProperty(){return!1}get nature(){return Va}}Fa.register("info-window",Ua);const $a={};var Wa={list:function(){return{...$a}},register:function(t,e){$a[t]=e},unregister:function(t){delete $a[t]},get:function(t){if(!t)return;const e=$a[t];return e||jr("Layout Not Found - ",t),e}};const Xa=new class{constructor(){this.ABSOLUTE=!0}reflow(t,e){this.drawables(t).filter(t=>t.isHTMLElement()).forEach(t=>t.reposition())}capturables(t){return t.components}drawables(t){return t.app&&!t.app.isViewMode?t.components:t.components.filter(t=>!t.hidden)}isStuck(t){return!1}};Wa.register("html-absolute",Xa);const qa=new class{constructor(){this.ABSOLUTE=!0}reflow(t,e){}capturables(t){return t.components}drawables(t){return t.app?.isViewMode?t.components.filter(t=>!t.hidden):t.components}isStuck(t){return!1}};function Ka(t){const e=t.components.filter(t=>!t.hidden),n=t.getState("layoutConfig")||{},r=e[n&&n.activeIndex||0];return r&&[r]||[]}Wa.register("absolute",qa);const Qa=new class{reflow(t){const e=t.bounds,n=t.getState("layoutConfig")||{},r={left:0,top:0,width:e.width,height:e.height};t.forEach((t,e)=>{const i=e!=(n.activeIndex||0);t.bounds=r,t.setState("rotation",0),"element"in t&&t.element&&(t.element.style.visibility=i?"hidden":"visible")})}capturables(t){return Ka(t)}drawables(t){return Ka(t)}isStuck(t){return!0}};function Za(t){const e=t.getState("layoutConfig");return e&&e.weight||1}Wa.register("card",Qa);const Ja=new class{reflow(t){const e=this.drawables(t),n=t.getState("padding")||{},r=e.reduce((t,e)=>t+Za(e),0),i=t.bounds,s=r>0?(i.width-((n.left||0)+(n.right||0)))/r:i.width,o=i.height-((n.top||0)+(n.bottom||0));let a=0;e.forEach(t=>{const e=Za(t),r=t.getState("margin")||{};t.bounds={left:s*a+(n.left||0)+(r.left||0),top:0+(n.top||0)+(r.top||0),width:e*s-((r.left||0)+(r.right||0)),height:o-((r.top||0)+(r.bottom||0))},t.setState("rotation",0),a+=e})}capturables(t){return t.components}drawables(t){return t.app?.isViewMode?t.components.filter(t=>!t.hidden):t.components}isStuck(t){return!0}};function tc(t){const e=t.getState("layoutConfig");return e&&e.weight||1}Wa.register("linear-horizontal",Ja);const ec=new class{reflow(t){const e=this.drawables(t),n=t.getState("padding")||{},r=e.reduce((t,e)=>t+tc(e),0),i=t.bounds,s=r>0?(i.height-((n.top||0)+(n.bottom||0)))/r:i.height,o=i.width-((n.left||0)+(n.right||0));let a=0;e.forEach(t=>{const e=tc(t),r=t.getState("margin")||{};t.bounds={left:0+(n.left||0)+(r.left||0),top:s*a+(n.top||0)+(r.top||0),width:o-((r.left||0)+(r.right||0)),height:e*s-((r.top||0)+(r.bottom||0))},t.setState("rotation",0),a+=e})}capturables(t){return t.components}drawables(t){return t.app?.isViewMode?t.components.filter(t=>!t.hidden):t.components}isStuck(t){return!0}};Wa.register("linear-vertical",ec);const nc=new class{constructor(){this.joinType=!0}reflow(t){const e=t.getState("layoutConfig"),n=e&&e.columns||t.getState("columns"),r=e&&e.rows||t.getState("rows"),i=e&&e.widths||t.getState("widths"),s=e&&e.heights||t.getState("heights"),o=i?i.filter((t,e)=>e<n).reduce((t,e)=>t+e,0):n,a=s?s.filter((t,e)=>e<r).reduce((t,e)=>t+e,0):r,c=t.textBounds,l=t.getState("paddingLeft")||0,h=t.getState("paddingTop")||0,d=c.width/o,u=c.height/a;let p=0,f=0;t.components.forEach((t,e)=>{const r=i?i[e%n]:1,o=s?s[Math.floor(e/n)]:1;let a=t.colspan||1,c=0;for(;--a>0;)c+=i?i[(e+a)%n]:1;let g=t.rowspan||1,m=0;for(;--g>0;)m+=s?s[Math.floor(e/n)+g]:1;t.bounds={left:l+p,top:h+f,width:d*(r+c),height:u*(o+m)},t.setState("rotation",0),e%n==n-1?(p=0,f+=o*u):p+=r*d})}capturables(t){return t.components.filter(t=>!t.merged)}drawables(t){return t.components.filter(t=>!t.merged&&!t.hidden)}isStuck(t){return!0}keyNavigate(t,e,n){const r=t.getState("layoutConfig"),i=r&&r.columns||t.getState("columns"),s=r&&r.rows||t.getState("rows"),{row:o,column:a}=t.getRowColumn(e);switch(n.code){case"ArrowUp":if(o>0)return t.getAt?.((o-1)*i+a);break;case"ArrowDown":if(o<s-1)return t.getAt?.((o+1)*i+a);break;case"ArrowRight":if(a<i-1)return t.getAt?.(o*i+a+1);break;case"ArrowLeft":if(a>0)return t.getAt?.(o*i+a-1);break;default:return e}}};Wa.register("table",nc);const rc=20;function ic(t,e="static",n,r,i,s,o={}){const{title:a="",gap:c=rc}=o;if("auto"===n){const{x:e,y:n}=function(t,e,n,r="",i=rc){const s=Math.max(e.width/4-n.width/2,i),o=Math.min(3*e.width/4+n.width/2,e.width-i)-n.width,a=Math.max(e.height/4-n.height/2,i),c=Math.min(3*e.height/4+n.height/2,e.height-i)-n.height+(r?-30:0);return{x:t.x<e.width/2?Math.min(o,t.x+20):Math.max(s,t.x-(n.width+20)),y:t.y<e.height/2?Math.min(c,t.y+20+(r?30:0)):Math.max(a,t.y-(n.height+20))}}(r,i,s,a,c);Object.assign(t.style,{position:"absolute",left:`${e}px`,top:`${n}px`})}else"static"===e?function(t,e,n,r,i){const s=t.style,o=e.includes("left")?i:e.includes("right")?n.width-r.width-i:n.width/2-r.width/2,a=e.includes("top")?i:e.includes("bottom")?n.height-r.height-i:n.height/2-r.height/2;Object.assign(s,{left:`${o}px`,top:`${a}px`})}(t,n,i,s,c):function(t,e,n=rc){const r=t.style;switch(Object.assign(r,{position:"absolute",left:"",right:"",top:"",bottom:"",transform:""}),e){case"center-middle":default:Object.assign(r,{left:"50%",top:"50%",transform:"translate(-50%, -50%)"});break;case"center-top":Object.assign(r,{left:"50%",top:`${n}px`,transform:"translateX(-50%)"});break;case"center-bottom":Object.assign(r,{left:"50%",bottom:`${n}px`,transform:"translateX(-50%)"});break;case"left-middle":Object.assign(r,{left:`${n}px`,top:"50%",transform:"translateY(-50%)"});break;case"right-middle":Object.assign(r,{right:`${n}px`,top:"50%",transform:"translateY(-50%)"});break;case"left-top":Object.assign(r,{left:`${n}px`,top:`${n}px`});break;case"right-top":Object.assign(r,{right:`${n}px`,top:`${n}px`});break;case"left-bottom":Object.assign(r,{left:`${n}px`,bottom:`${n}px`});break;case"right-bottom":Object.assign(r,{right:`${n}px`,bottom:`${n}px`})}}(t,n,c)}function sc(t,e,n={sx:1,sy:1}){let r,i,s=0,o=0,a=!1;const c=/translate\(([-\d.]+)px,\s*([-\d.]+)px\)/;function l(){const e=(t.style.transform||"").match(c);return{x:e?parseFloat(e[1]):0,y:e?parseFloat(e[2]):0}}function h(t,e){a=!0;const n=l();s=n.x,o=n.y,r=t,i=e}function d(e,c){if(!a)return;const l=e-r,h=c-i,{sx:d,sy:u}=n;!function(e,n){t.style.transform=`translate(${e}px, ${n}px)`}(s+l/d,o+h/u)}function u(){const t=l();s=t.x,o=t.y,a=!1}e?.addEventListener("mousedown",t=>{t.preventDefault(),t.stopPropagation(),h(t.clientX,t.clientY);const e=t=>{t.preventDefault(),d(t.clientX,t.clientY)},n=t=>{t.preventDefault(),u(),window.removeEventListener("mousemove",e,!0),window.removeEventListener("mouseup",n,!0)};window.addEventListener("mousemove",e,!0),window.addEventListener("mouseup",n,!0)}),e?.addEventListener("touchstart",t=>{if(1!==t.touches.length)return;t.preventDefault(),t.stopPropagation(),h(t.touches[0].clientX,t.touches[0].clientY);const e=t=>{1===t.touches.length&&(t.preventDefault(),d(t.touches[0].clientX,t.touches[0].clientY))},n=t=>{u(),window.removeEventListener("touchmove",e,!0),window.removeEventListener("touchend",n,!0),window.removeEventListener("touchcancel",n,!0)};window.addEventListener("touchmove",e,!0),window.addEventListener("touchend",n,!0),window.addEventListener("touchcancel",n,!0)})}const oc=["run","goto","goto-playlist","link-open","link-move","route-page","start-scenario","run-scenario","export-data","import-data"];function ac(t,e){const n=document.createElement("button");return n.className=t,n.textContent=e,n}const cc=new WeakMap;function lc(t){const e=t.root,n=cc.get(e);if(!n)return;if(e===t)return n.forEach(t=>lc(t[0])),void cc.delete(e);const r=n.findIndex(e=>e[0]===t);if(-1===r)return;const i=n[r][1];cancelAnimationFrame(i.rafId),i.ac.abort(),i.div.parentNode?.removeChild(i.div),i.scene.target=null,i.scene.release?.(),n.splice(r,1)}class hc{static hideAll(t){(cc.get(t)||[]).forEach(([t])=>lc(t))}static hide(t){const e=t.root,n=cc.get(e);if(!n)return;const r=n.findIndex(e=>e[0]===t);if(-1===r)return;const i=n[r][1];i.div.style.backgroundColor="transparent",i.rafId=function(t,e,n){t.style.opacity="1";const r=(t.style.transform||"").replace(/scale\([^)]+\)/,"").trim();t.style.transform=`${r} scale(1)`;let i=0;const s=Date.now(),o=()=>{if(n?.aborted)return;const a=Math.min((Date.now()-s)/200,1);t.style.opacity=String(1-a),t.style.transform=`${r} scale(${1-a})`.trim(),a<1?i=requestAnimationFrame(o):(t.style.display="none",e&&e())};return i=requestAnimationFrame(o),i}(i.div,()=>{lc(t)},i.ac.signal)}static show(t,e,n={}){const{data:r,modal:i=!1,closable:s=!0,minimizable:o=!1,draggable:a=!1,output:c=!0,popupPosition:l="static",origin:h="center-middle",title:d=""}=n,u=t.app?.refProvider,p=!l||"static"===l;u?.get(e,!0).then(e=>{const n=document.createElement("div");n.setAttribute("popup",""),"absolute"==l&&(n.style.zIndex="100");const u=n.style;if(i){const{width:e,height:n}=p?t.rootModel.bounds:t.rootModel.auxOverlay.getBoundingClientRect();Object.assign(u,{position:"absolute",zIndex:"100",left:0,top:0,width:p?`${e}px`:"100%",height:p?`${n}px`:"100%",overflow:"hidden",backgroundColor:"transparent"})}else Object.assign(u,{position:"absolute",display:"inline-block"});n.appendChild(function(t){const e=document.createDocumentFragment(),n=document.createElement("div");n.className="popup-wrap";const r=document.createElement("div");if(r.className="popup-translate",t){const t=document.createElement("div");t.className="popup-title-bar";const e=document.createElement("div");e.className="popup-title",t.appendChild(e);const n=document.createElement("div");n.className="popup-buttons-wrap",n.appendChild(ac("closable","close")),n.appendChild(ac("minimizable","minimize")),n.appendChild(ac("draggable","drag_pan")),t.appendChild(n),r.appendChild(t)}else{const t=document.createElement("div");t.className="popup-buttons-wrap float-right",t.appendChild(ac("closable","close")),t.appendChild(ac("minimizable","minimize")),t.appendChild(ac("draggable","drag_pan")),r.appendChild(t)}const i=document.createElement("div");return i.className="popup-content",r.appendChild(i),n.appendChild(r),e.appendChild(n),e}(!!d));const f=n.querySelector(".popup-content"),{width:g,height:m}=e.root.model;Object.assign(f.style,{width:`${g}px`,height:`${m}px`});const y=document.createElement("style");y.appendChild(document.createTextNode("\n\n.popup-wrap .popup-translate {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n min-width: 120px;\n overflow: hidden;\n transition: height 0.5s ease;\n}\n\n.popup-wrap .popup-translate > * {\n pointer-events: auto;\n}\n\n.popup-wrap .popup-content {\n background-color: var(--md-sys-color-surface, white);\n}\n\n.popup-wrap .popup-title-bar {\n display: flex;\n align-items: center;\n top: 0;\n left: 0;\n width: 100%;\n height: 30px;\n background-color: var(--md-sys-color-primary, #f1f1f1);\n color: var(--md-sys-color-on-primary, black);\n padding: 5px;\n box-sizing: border-box;\n border-bottom: 1px solid #ccc;\n}\n\n.popup-wrap .popup-title {\n flex: 1;\n text-align: center;\n}\n\n.popup-wrap .popup-buttons-wrap {\n position: relative;\n display: flex;\n flex-direction: row-reverse;\n gap: 4px;\n min-width: 100px;\n align-items: center;\n justify-items: center;\n margin: 0;\n padding: 0;\n}\n\n.popup-wrap .popup-buttons-wrap.float-right {\n position: absolute;\n right: 0;\n top: 0;\n height: 30px;\n margin-right: 5px;\n}\n\n.popup-wrap button.closable, \n.popup-wrap button.minimizable, \n.popup-wrap button.draggable {\n display: none;\n color: white; \n background-color: black; \n opacity: .3;\n width: 20px;\n height: 20px;\n top: 5px; \n z-index: 1;\n padding: 0;\n margin: 0;\n border: 0px;\n text-align: center;\n cursor: pointer;\n border-radius: 4px;\n font-family: Material Symbols Outlined;\n font-size: 16px;\n}\n\n.popup-wrap button.draggable {\n cursor: move;\n}\n\n.popup-wrap button.closable:hover, \n.popup-wrap button.minimizable:hover, \n.popup-wrap button.draggable:hover {\n opacity: .6; \n}\n")),n.appendChild(y),oc.forEach(n=>{e.on(n,(...e)=>{t.trigger(n,...e)})});const b=new AbortController,v=b.signal,_=n.querySelector(".draggable");[...xi,...wi].forEach(t=>{f.addEventListener(t,t=>t.stopPropagation(),{signal:v})}),[...xi,...wi].forEach(t=>{n.addEventListener(t,t=>t.stopPropagation(),{signal:v})}),i&&s&&n.addEventListener("click",e=>{e.target===n&&hc.hide(t)},{signal:v});const x=t.rootModel.getOverlay?.({...t,scalable:!l||"static"==l});x?.appendChild(n),function(t,e,n,r,i){const s=t.root;if(s===t)return;lc(t);let o=cc.get(s)||[];o=[...o,[t,{div:e,scene:n,ac:r,rafId:i}]],cc.set(s,o)}(t,n,e,b,0);const w=cc.get(t.root)?.find(e=>e[0]===t)?.[1];if(d){const t=n.querySelector(".popup-title-bar .popup-title");t&&(t.textContent=d)}const M=n.querySelector(".popup-translate");if(a&&(sc(M,d?n.querySelector(".popup-title-bar"):n.querySelector(".draggable"),function(t,e){if(!(e=e||t.position)||"static"===e){const e=(t.rootModel.getOverlay(t).style.transform||"").match(/scale\(([^,\s)]+)(?:,\s*([^)]+))?\)/),n=e?parseFloat(e[1]):1;return{sx:n,sy:e&&e[2]?parseFloat(e[2]):n}}return{sx:1,sy:1}}(t,l)),d?_&&(_.style.display="block"):(M?.addEventListener("mouseenter",()=>{_&&(_.style.display="block")},{signal:v}),M?.addEventListener("mouseleave",()=>{_&&(_.style.display="none")},{signal:v}))),o){const t=n.querySelector(".minimizable");let e=!1;t.addEventListener("click",t=>{t.preventDefault(),e=!e;const r=n.querySelector(".popup-wrap");!function(t,e,n){const r=e.querySelector(".minimizable"),i=e.querySelector(".popup-translate");i&&(n?(r.textContent="crop_square",i.style.height="30px"):(r.textContent="minimize",i.style.height="100%"))}(0,i?r:n,e)},{signal:v}),d?t&&(t.style.display="block"):(M?.addEventListener("mouseenter",()=>{t&&(t.style.display="block")},{signal:v}),M?.addEventListener("mouseleave",()=>{t&&(t.style.display="none")},{signal:v}))}if(s){const t=n.querySelector(".closable");d?t&&(t.style.display="block"):(M?.addEventListener("mouseenter",()=>{t&&(t.style.display="block")},{signal:v}),M?.addEventListener("mouseleave",()=>{t&&(t.style.display="none")},{signal:v}))}n.querySelector(".closable")?.addEventListener("click",e=>{e.preventDefault(),hc.hide(t)},{signal:v}),n.addEventListener("close-scene",e=>{e.preventDefault(),e.stopPropagation(),hc.hide(t),c&&(t.data=e.detail)},{signal:v}),e.target=f,e.data=r||t.data,e.fit("both");const{x:S,y:A}=t.center,E=t.toScene(S,A),k=i?n.querySelector(".popup-wrap"):n;ic(k,l,h,E,e.root.bounds,{width:g,height:m},{title:d}),i?Object.assign(k.style,{position:"absolute",pointerEvents:"none",width:`${g}px`,height:`${d?m+30:m}px`}):Object.assign(k.style,{pointerEvents:"none",width:`${g}px`,height:`${d?m+30:m}px`});const C=function(t,e,n){t.style.opacity="0";const r=(t.style.transform||"").replace(/scale\([^)]+\)/,"").trim();t.style.transform=`${r} scale(0)`,t.style.display="block";let i=0;const s=Date.now(),o=()=>{if(n?.aborted)return;const a=Math.min((Date.now()-s)/200,1);t.style.opacity=String(a),t.style.transform=`${r} scale(${a})`.trim(),a<1?i=requestAnimationFrame(o):e&&e()};return i=requestAnimationFrame(o),i}(n,()=>{i&&(n.style.backgroundColor="rgba(0,0,0,0.3)")},v);w&&(w.rafId=C)},t=>{jr("cannot fetch board: "+e,t)})}}const dc=new Image;function uc(t){return class extends t{get showMoveHandle(){return!1}postrender(t){super.postrender(t),this.app.isEditMode&&this._focused&&this.showMoveHandle&&this._draw_move_handle(t)}_draw_move_handle(t){const{left:e,top:n,width:r}=this.bounds;t.save(),t.beginPath(),t.globalAlpha=1,t.rect(e+r,n,25,25);t.fillStyle="rgba(235, 235, 235, 1)",t.fill(),t.drawImage(dc,e+r+3.75,n+3.75,17.5,17.5),t.closePath(),t.restore()}contains(t,e){let n=super.contains(t,e);if(this.app.isViewMode)return n;if(!n){const{left:r,top:i,width:s}=this.bounds,o=r+s,a=25;this.showMoveHandle&&(n=t<Math.max(o+25,o)&&t>Math.min(o+25,o)&&e<Math.max(i+a,i)&&e>Math.min(i+a,i))}return this._focused!==n&&(this._focused=n,this.invalidate()),n}}}dc.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAclBMVEVHcEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0BbqFAAAAJXRSTlMAgAP3VSI6/g9fBk5FavJsMrariSjzPnO1enRRL5SMhmOOWB9keFTE0wAAANxJREFUOMutk9kWgyAMRLFuiLjUtdp9yf//YglVsQXz1HniMPcEMgHGvpX2O0Ypi+EgCL+IAShC+wB7QfubRDT7AFcnUPoLMLiP4PyJbsb55i05AgnR5iaQDsICgtH0cotBWoAP1c7kC6kFxEseCfZfB6gEgbNeBrira2QmH1uVYCXlA3is8UmgUCPIyQJKEmu8QtQJN0e9DPXVpzG2G216c1CqRmcBOdxXk07sWUSPv07zo0amCNQycv+NzmR6cRcwmfbuI7p2nZ/z4be0P83Foz6vIkhfZXr82XgDlZsspIq4peUAAAAASUVORK5CYII=";const pc=[];class fc extends(uc(Ha(Fa))){constructor(t,e){super(t,e),this._components=[]}replaceRefids(t){this.components.forEach(e=>e.replaceRefids(t))}get showMoveHandle(){return!0}get showOverflow(){return!1}dispose(){this.components.slice().forEach(t=>t.dispose()),super.dispose()}isContainer(){return!0}containable(t){return t.isDescendible(this)}get hasTextProperty(){return!1}get components(){return this._components}get focusible(){return!0}get layout(){return Wa.get(this.get("layout"))||qa}reflow(){this.layout.reflow(this),this.components&&this.components.forEach(t=>{t.isContainer()&&t.reflow()})}get hierarchy(){const t=super.hierarchy;return this.components&&(t.components=this.components.map(t=>t.hierarchy)),t}addComponent(t,e=!1){const n=t.parent;if(n){if(this===n)return;n.removeComponent(t,e)}const r=this._components.push(t)-1;t.parent=this,t.added(this),e||this.trigger("add",this,t,r),t.delegate_on(this),e||t.trigger("added",this,t,r),this.root&&this.root.isReady&&t.ready()}removeComponent(t,e=!1){const n=this._components.indexOf(t);-1!=n&&(this._components.splice(n,1),t.parent=null,t.removed(this),e||(this.trigger("remove",this,t),t.trigger("removed",this,t)),t.delegate_off(this))}insertComponentAt(t,e,n=!1){const r=t.parent;r&&r.removeComponent(t,n);const i=this._components.splice(0,e);this._components=i.concat(t,this._components),e=this._components.indexOf(t),t.parent=this,t.added(this),n||this.trigger("add",this,t,e),t.delegate_on(this),n||t.trigger("added",this,t,e)}add(t,e=!1){return t instanceof Array?(t.forEach(t=>{-1==this._components.indexOf(t)&&this.addComponent(t,e)}),this):this.add.call(this,[t],e)}remove(t,e=!1){return t instanceof Array?this._components?(t.forEach(t=>{this.removeComponent(t,e)}),this):this:this.remove.call(this,[t],e)}getAt(t){if(this._components)return this._components[t]}forEach(t,e){this._components&&this._components.forEach(t,e)}traverse(t,e){t.call(e,this),this._components&&this._components.forEach(n=>{n.isContainer()?n.traverse(t,e):t.call(e,n)})}indexOf(t){return(this._components||pc).indexOf(t)}size(){return(this._components||pc).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let r=this._components.splice(0,n);const i=this._components.splice(1);this._components=r.concat(i),t=Math.max(0,t),t=Math.min(t,this._components.length),r=this._components.splice(0,t),this._components=r.concat(e,this._components)}moveChildForward(t){const e=this.indexOf(t);-1!=e&&e!=this.size()-1&&(this._components[e]=this._components[e+1],this._components[e+1]=t)}moveChildBackward(t){const e=this.indexOf(t);-1!=e&&0!=e&&(this._components[e]=this._components[e-1],this._components[e-1]=t)}moveChildToFront(t){const e=this.indexOf(t);if(-1==e||e==this.size()-1)return;const n=this._components.splice(0,e),r=this._components.splice(1);this._components=n.concat(r,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),r=this._components.splice(1);this._components=this._components.concat(n,r)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return da(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let r=this.components.length-1;r>=0;r--){const i=this.components[r].findAll(t,...e);i&&(n=n.concat(i))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return da(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const r=this.components[n].findFirst(t,...e);if(null!=r)return r}return t(this,...e)?this:void 0}}findById(t){return this.root.findAllById?.(t)?.[0]}findByRefid(t){return this.root.findByRefid?.(t)}contains(t,e){let n=super.contains(t,e);if(!n){const{left:r,top:i,width:s,height:o}=this.state;n=t<Math.max(r+s,r)&&t>Math.min(r+s,r)&&e<Math.max(i+o,i)&&e>Math.min(i+o,i)}return n}capture(t,e,n){if(!this.app.isEditMode&&this.hidden)return!1;const r=this.fromParent(t,e);if(!this.contains(r.x,r.y))return!1;const i=this.bounds;r.x-=i.left,r.y-=i.top;const s=this.layout.capturables(this);for(let i=s.length-1;i>=0;i--){const o=s[i];let a;if(a="static"==o.position?o.capture(r.x,r.y,n):o.capture(t,e,n),a)return a}return this.capturable&&!n?.(this)&&this}capturePath(t,e){if(e){if(e.indexOf(this)>-1)return!1;for(let t=0;t<e.length;t++)if(!this.containable(e[t]))return!1}const n=[],{left:r,top:i,width:s,height:o}=this.bounds;for(let e=0;e<t.length;e++){const a=this.fromParent(t[e].x,t[e].y);if(a.x<r||a.x>r+s||a.y<i||a.y>i+o)return!1;a.x-=r,a.y-=i,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const r=a[t];if(!r.isContainer())continue;const i=r.capturePath(n,e);if(i)return i}return this.focusible&&this}render(t){const{left:e=0,top:n=0,width:r,height:i}=this.bounds;t.beginPath(),t.rect(e,n,r,i),t.closePath(),this.drawFill(t),this.drawStroke(t)}postrender(t){const e=this.layout.drawables(this);if(e.length>0){let{left:n=0,top:r=0,width:i,height:s}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,r,i,s),t.clip(),t.closePath()),({top:r,left:n}=this.state),t.translate(n,r),e.forEach(e=>{e.draw(this.position&&"static"!==this.position?t:this.getContext(e))}),t.translate(-n,-r),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>Fa.memoize(fc.prototype,t,!1));class gc extends fc{constructor(t,e){super(t,e),this._element=null,t.translate=t.translate||{x:0,y:0},this._draw_reserved=!1,this.__draw__=()=>{this._draw_reserved=!1;const t=performance.now();this.trigger("redraw"),this.reflow(),this.draw();const e=performance.now()-t;xr.drawCount++,xr.drawTimeSum+=e,xr.drawTimeLast=e,xr.countFrame()},this.throttle_render=()=>{this._draw_reserved||requestAnimationFrame(this.__draw__),this._draw_reserved=!0}}get element(){return this._element}set element(t){this._element=t}fitSize(t,e,n,r){if(this.target){if(e){const t=getComputedStyle(this.target);n=n||(t?parseFloat(t.getPropertyValue("width")):this.target.clientWidth),r=r||(t?parseFloat(t.getPropertyValue("height")):this.target.clientHeight)}else n=this.model.width,r=this.model.height;"CANVAS"==t.tagName&&(t.setAttribute("width",n*_i),t.setAttribute("height",r*_i)),t.style.width=n+"px",t.style.height=r+"px"}}resize(){this.fitSize(this.element,!0)}isLayer(){return!0}get showOverflow(){return this.app.isEditMode}get anchors(){}createElement(){const t=Fa.createCanvas(1,1);return t.setAttribute("scene",this.state.type),t.style.position="absolute",t.style.pointerEvents=this.pointerEvents,t}get pointerEvents(){return"auto"}get target(){return this._target}set target(t){this._target&&this.element&&this._target.removeChild(this.element),this._target=t,this.element||(this.element=this.createElement()),this.resize(),t?.appendChild(this.element)}get canvas(){return this.element}dispose(){super.dispose(),this.target=null,this.element=null}get selected(){return this.root.selected||[]}set selected(t){this.root.selected=t}get hasSameParentForAllSelected(){return this.root.hasSameParentForAllSelected}get focused(){return this.root.focused}set focused(t){this.root.focused=t}get context2D(){if(!this._context2D&&(this._context2D=this.canvas&&this.canvas.getContext("2d"),this._context2D)){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--scene-theme-font-family")?.trim()||t.fontFamily||"sans-serif";this._context2D.font=["10px",e].join(" "),this._context2D.save()}return this._context2D}getContext(t){return this._context2D||this.context2D}draw(t){this.canvas&&(t=t||this.getContext(void 0))&&(t.save(),super.draw(t),t.restore())}prerender(t){const{translate:e,scale:n={x:1,y:1},rotation:r}=this.model;t.clearRect(0,0,t.canvas.width,t.canvas.height),e&&t.translate(e.x*_i,e.y*_i),t.scale(n.x*_i,n.y*_i),r&&t.rotate(r)}get rotatePoint(){return{x:0,y:0}}contains(t,e){return!1}invalidate(){xr.invalidateCount++,this.throttle_render()}move(t){const e=this.get("translate")||{x:0,y:0};this.set({translate:{x:e.x+t.x,y:e.y+t.y}})}centerTo(t,e){const n=t.rootModel.toLocal(this.canvas.clientWidth/2,this.canvas.clientHeight/2),{x:r,y:i}=t.center,{x:s,y:o}=t.fromParent(r,i),{x:a,y:c}=t.toScene(s,o),{x:l,y:h}=t.rootModel.get("translate"),{x:d,y:u}=t.rootModel.get("scale");e?Ro({step:function(e){t.rootModel.set({translate:{x:l+(n.x-a)*d*e,y:h+(n.y-c)*u*e}})},duration:1e3,delta:"circ"}).start():t.rootModel.set({translate:{x:l+(n.x-a)*d,y:h+(n.y-c)*u}})}}class mc extends gc{dispose(){super.dispose(),delete this._canvas,delete this._auxCanvas}createElement(){const t=document.createElement("div");return t.style.position="absolute",t.setAttribute("scene",`${this.state.type}-anchor`),t.style["user-select"]="none",t.style.overflow="hidden",this._canvas=Fa.createCanvas(1,1),this._canvas.style.position="absolute",this._canvas.style.pointerEvents="none",this._canvas.setAttribute("scene",`${this.state.type}-canvas`),t.appendChild(this._canvas),this._auxCanvas=Fa.createCanvas(1,1),this._auxCanvas.style.position="absolute",this._auxCanvas.style.pointerEvents="none",this._auxCanvas.style.zIndex="100",this._auxCanvas.setAttribute("scene",`${this.state.type}-aux-canvas`),t.appendChild(this._auxCanvas),t}resize(){if(!this.element)return;this.fitSize(this.element,!0);const t=this.element.clientWidth,e=this.element.clientHeight;this.fitSize(this.canvas,!0,t,e),this.fitSize(this.auxCanvas,!0,t,e)}get canvas(){return this._canvas}get auxCanvas(){return this._auxCanvas}get context2D(){if(!this._context2D){this._context2D=this.canvas&&this.canvas.getContext("2d");const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--scene-theme-font-family")?.trim()||t.fontFamily||"sans-serif";this._context2D.font=["10px",e].join(" "),this._context2D.save()}return this._context2D}get auxContext2D(){if(!this._auxContext2D){this._auxContext2D=this.auxCanvas&&this.auxCanvas.getContext("2d");const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--scene-theme-font-family")?.trim()||t.fontFamily||"sans-serif";this._auxContext2D.font=["10px",e].join(" "),this._auxContext2D.save()}return this._auxContext2D}getContext(t){/*!this.app.isViewMode || */
3
- return!t||t.scalable?this.context2D:this.auxContext2D}draw(t){this.canvas&&this.element&&(t=t||this.getContext(void 0))&&(this.auxContext2D.clearRect(0,0,this.auxCanvas.width,this.auxCanvas.height),this.auxContext2D.save(),this.auxContext2D.scale(_i,_i),super.draw(t),this.auxContext2D.restore())}}var yc,bc,vc,_c;!function(t){t.CANVAS="canvas",t.DOM="dom"}(yc||(yc={}));class xc{get overlay(){return this._overlay}constructor(t,e,n={}){if(this.element=null,this.isActive=!1,this._overlay=null,this.target=e,this.options={animation:!0,repeat:!0,duration:3e3,color:"#ff0000",opacity:1,fadeOut:!1,...n},this.mode=n.mode||this.determineOptimalMode(),t){this._overlay=t;bs.getInstance().addOverlay(t)}}determineOptimalMode(){return!1!==this.options.animation?yc.DOM:yc.CANVAS}start(){if(!this.isActive&&(this.isActive=!0,this.mode===yc.DOM)){this.overlay?(this.createDOMElements(),this.target.on("change",this.handleTargetChange,this),this.target.on("removed",this.handleTargetRemoved,this)):(Rr("오버레이가 설정되지 않아 DOM 모드 데코레이터를 시작할 수 없습니다."),this.isActive=!1)}}stop(){this.isActive&&(this.isActive=!1,this.mode===yc.DOM&&(this.target.off("change",this.handleTargetChange,this),this.target.off("removed",this.handleTargetRemoved,this),this.removeDOMElements()))}update(t){if(t&&(this.options={...this.options,...t},t.mode&&t.mode!==this.mode))return this.stop(),this.mode=t.mode,void this.start();this.mode===yc.DOM&&this.isActive&&this.updateDOMElements()}render(t,e){return!(this.mode!==yc.CANVAS||!this.isActive)&&this.renderCanvas(t,e)}removeDOMElements(){this.element&&this.element.parentNode&&(this.element.parentNode.removeChild(this.element),this.element=null)}updateDOMElements(){this.removeDOMElements(),this.createDOMElements()}getComponentPosition(){const{left:t,top:e,width:n,height:r}=this.target.bounds;if("function"==typeof this.target.toGlobal)try{const{x:i,y:s}=this.target.toGlobal(t,e,this.target.rootModel);return{x:i,y:s,width:n,height:r}}catch(t){Rr("좌표 변환 실패, 기본값 사용:",t)}return{x:t,y:e,width:n,height:r}}handleTargetChange(t,e){this.target.disposed?this.stop():this.invalidate()}handleTargetRemoved(){this.stop()}invalidate(){}}function wc(t,e,n){const r=t.rootModel;if(r?.is3dMode){const e=t._realObject?.object3d,n=r.activeCamera3d,i=r.renderer3d;if(e&&n&&i){const t=new _.Vector3;e.getWorldPosition(t);const r=t.clone().project(n),s=i.domElement;return{x:(.5*r.x+.5)*s.clientWidth,y:(.5*-r.y+.5)*s.clientHeight}}return null}const i=t.toGlobal(e,n,r);return isNaN(i.x)||isNaN(i.y)?null:i}class Mc extends xc{constructor(t,e,n={}){super(t,e,{strokeWidth:2,strokeColor:"#FF0000",strokeOpacity:1,fillColor:"none",fillOpacity:.5,scale:1,rotation:0,x:0,y:0,zIndex:0,mode:yc.DOM,...n}),this.vectorElement=null,this.animationElements=[],this.svgContainer=null,this.animationElement=null}getDecoratorType(){return this.constructor.DECORATOR_TYPE}dispose(){this.removeDOMElements()}determineOptimalMode(){return yc.DOM}renderCanvas(t,e){return Rr("VectorDecorator는 Canvas 렌더링을 지원하지 않습니다. DOM 모드를 사용하세요."),!1}getSvgContainer(){if(!this.overlay)throw new Error("오버레이 요소가 없습니다.");if(!Mc.svgContainerCache.has(this.overlay)){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","vector-decorator-container"),t.setAttribute("pointer-events","none"),t.style.overflow="visible",t.style.position="absolute",t.style.top="0",t.style.left="0",this.overlay.appendChild(t),Mc.svgContainerCache.set(this.overlay,t)}return Mc.svgContainerCache.get(this.overlay)}getOrCreateDecoratorGroup(t=!1){const e=this.getSvgContainer(),n=this.getVectorGroupId(),r=this.getDecoratorType();let i=e.querySelector(`g[data-decorator-type-container="${r}"]`);if(!i){i=document.createElementNS("http://www.w3.org/2000/svg","g"),i.setAttribute("data-decorator-type-container",r),i.setAttribute("class",`${r}-container`),e.appendChild(i);const t=document.createElementNS("http://www.w3.org/2000/svg","defs");t.setAttribute("data-defs-for",r),i.appendChild(t)}let s=i.querySelector(`g[data-decorator-group-id="${n}"]`);if(!s){const{id:t}=this.target.state;return s=document.createElementNS("http://www.w3.org/2000/svg","g"),s.setAttribute("data-decorator-group-id",n),s.setAttribute("data-decorator-type",r),t&&s.setAttribute("data-component-id",t),i.appendChild(s),s}if(t)for(;s.firstChild;)s.removeChild(s.firstChild);return s}getDefsForType(){const t=this.getSvgContainer(),e=this.getDecoratorType();let n=t.querySelector(`g[data-decorator-type-container="${e}"]`);n||(this.getOrCreateDecoratorGroup(),n=t.querySelector(`g[data-decorator-type-container="${e}"]`));let r=n.querySelector(`defs[data-defs-for="${e}"]`);return r||(r=document.createElementNS("http://www.w3.org/2000/svg","defs"),r.setAttribute("data-defs-for",e),n.appendChild(r)),r}getDecoratorGroup(){const t=this.getSvgContainer(),e=this.getVectorGroupId(),n=t.querySelector(`g[data-decorator-group-id="${e}"]`);if(n)return n}createFadeAnimation(t=0,e=1,n=1e3,r={}){const i=document.createElementNS("http://www.w3.org/2000/svg","animate");return i.setAttribute("attributeName","opacity"),i.setAttribute("from",t.toString()),i.setAttribute("to",e.toString()),i.setAttribute("dur",`${n}ms`),r.delay&&i.setAttribute("begin",`${r.delay}ms`),i.setAttribute("fill","freeze"),r.repeat?i.setAttribute("repeatCount","indefinite"):i.setAttribute("repeatCount","1"),i}createTranslateAnimation(t,e=[],n=1e3,r={}){const i=document.createElementNS("http://www.w3.org/2000/svg","animateTransform");return i.setAttribute("attributeName","transform"),i.setAttribute("type","translate"),i.setAttribute("values",t.join(";")),e.length>0&&i.setAttribute("keyTimes",e.join(";")),i.setAttribute("dur",`${n}ms`),r.delay&&i.setAttribute("begin",`${r.delay}ms`),r.repeat?i.setAttribute("repeatCount","indefinite"):i.setAttribute("repeatCount","1"),i}createRotateAnimation(t=0,e=360,n=0,r=0,i=1e3,s={}){const o=document.createElementNS("http://www.w3.org/2000/svg","animateTransform");return o.setAttribute("attributeName","transform"),o.setAttribute("type","rotate"),o.setAttribute("from",`${t} ${n} ${r}`),o.setAttribute("to",`${e} ${n} ${r}`),o.setAttribute("dur",`${i}ms`),s.delay&&o.setAttribute("begin",`${s.delay}ms`),s.repeat?o.setAttribute("repeatCount","indefinite"):o.setAttribute("repeatCount","1"),o}addAnimations(t,e){e.forEach(e=>{t.appendChild(e),this.animationElements.push(e)})}projectComponentPoint(t,e,n){return wc(t,e,n)}updatePosition(){if(!this.vectorElement)return;const t=this.options,{left:e,top:n}=this.target.bounds,r=this.projectComponentPoint(this.target,e,n);if(!r)return;const i=r.x+(t.x??0),s=r.y+(t.y??0);this.vectorElement.setAttribute("transform",`translate(${i}, ${s})`)}updateDOMElements(){this.createDOMElements()}getVectorGroupId(){const t=this.getDecoratorType(),{refid:e="unknown"}=this.target.state;return`decorator-${t}-${e}`}removeVectorElements(){if(this.overlay)try{const t=Mc.svgContainerCache.get(this.overlay);if(!t)return;const e=this.getVectorGroupId(),n=this.getDecoratorType(),r=t.querySelector(`g[data-decorator-type-container="${n}"]`);if(r){const t=r.querySelector(`g[data-decorator-group-id="${e}"]`);if(t&&(this.vectorElement&&(this.vectorElement===t||t.contains(this.vectorElement))&&(this.vectorElement=null),this.animationElements=this.animationElements.filter(e=>!t.contains(e)),t.remove()),!r.querySelector("g[data-decorator-group-id]")){const t=r.querySelector(`defs[data-defs-for="${n}"]`);t&&t.remove(),r.remove()}}0===t.children.length&&(t.remove(),Mc.svgContainerCache.delete(this.overlay))}catch(t){jr("벡터 요소 제거 실패:",t)}}removeDOMElements(){this.removeVectorElements()}delta(t,e){if("string"==typeof t)return"fade"===t?this.applyFadeValue(e):"theta"===t&&this.applyRotationValue(e),{tx:0,ty:0};if("object"==typeof t){const e=t;("tx"in e||"ty"in e)&&this.applyTranslateValues(e.tx||0,e.ty||0),("sx"in e||"sy"in e)&&this.applyScaleValues(e.sx||1,e.sy||1)}return null}invalidate(){this.mode===yc.DOM&&this.isActive&&this.updateDOMElements()}touch(){}applyFadeValue(t){if(this.vectorElement){const e=t.toFixed(2);this.vectorElement.setAttribute("opacity",e)}}applyRotationValue(t){if(this.vectorElement){const e=this.getComponentBounds(),n=e.width/2,r=e.height/2,i=(180*t/Math.PI).toFixed(1);this.vectorElement.setAttribute("transform",`rotate(${i} ${n} ${r})`)}}applyTranslateValues(t,e){if(this.vectorElement){const n=this.vectorElement.getAttribute("transform")||"";if(n.includes("translate")){const r=n.replace(/translate\([^)]+\)/,`translate(${t}, ${e})`);this.vectorElement.setAttribute("transform",r)}else this.vectorElement.setAttribute("transform",`${n} translate(${t}, ${e})`.trim())}}applyScaleValues(t,e){if(this.vectorElement){const n=this.vectorElement.getAttribute("transform")||"";if(n.includes("scale")){const r=n.replace(/scale\([^)]+\)/,`scale(${t}, ${e})`);this.vectorElement.setAttribute("transform",r)}else this.vectorElement.setAttribute("transform",`${n} scale(${t}, ${e})`.trim())}}getComponentBounds(){return this.target&&this.target.bounds?this.target.bounds:{top:0,left:0,width:100,height:100}}}Mc.svgContainerCache=new WeakMap,Mc.DECORATOR_TYPE="vector";class Sc extends xc{constructor(t,e,n={}){super(t,e,{scale:1,strokeColor:"#000000",strokeWidth:1,rotation:0,shadow:!1,shadowColor:"rgba(0,0,0,0.5)",shadowBlur:5,shadowOffsetX:2,shadowOffsetY:2,...n}),this.animationId=null,this.canvasElement=null,this.context=null,this.animationFrame=null,this.deltaValue=0}determineOptimalMode(){return yc.CANVAS}createDOMElements(){Rr("RasterDecorator는 DOM 렌더링을 지원하지 않습니다. Canvas 모드를 사용하세요.")}setAnimationState(t=3e3,e=!1){Sc.animationStateMap.set(this.target,{startTime:Date.now(),duration:t,repeat:e})}getAnimationState(){const t=Sc.animationStateMap.get(this.target);if(!t)return{delta:0,finished:!0};const{startTime:e,duration:n,repeat:r}=t,i=Date.now()-e;let s=Math.min(1,i/n),o=s>=1;return r&&o&&(Sc.animationStateMap.set(this.target,{startTime:Date.now(),duration:n,repeat:r}),s=0,o=!1),{delta:s,finished:o}}bounceEffect(t,e=10){const n=Math.min(1,4*t);return Math.sin(n*Math.PI*10)*e*(1-n)}fadeEffect(t,e=!1){return e?t:1-t}pulseEffect(t,e=.8,n=1.2){return e+(.5*Math.sin(t*Math.PI*2)+.5)*(n-e)}rotateEffect(t,e=360){return t*e}applyShadowEffect(t){if(this.options.shadow){const e=this.options;t.shadowColor=e.shadowColor||"rgba(0,0,0,0.5)",t.shadowBlur=e.shadowBlur||5,t.shadowOffsetX=e.shadowOffsetX||2,t.shadowOffsetY=e.shadowOffsetY||2}}removeShadowEffect(t){t.shadowColor="transparent",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0}start(){super.start(),this.isActive&&this.options.animation&&this.setAnimationState(this.options.duration||3e3,this.options.repeat||!1)}stop(){null!==this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null),super.stop(),Sc.animationStateMap.delete(this.target)}applyTransform(t,e,n){const r=this.options,i=r.scale||1,s=r.rotation||0;if(1!==i||0!==s){if(t.translate(e,n),0!==s){const e=s*Math.PI/180;t.rotate(e)}1!==i&&t.scale(i,i),t.translate(-e,-n)}}delta(t,e){return"string"==typeof t?("fade"===t?(this.deltaValue=e,this.context&&(this.context.globalAlpha=e)):"theta"===t&&(this.deltaValue=e),{tx:0,ty:0}):null}invalidate(){this.context&&this.isActive&&(this.animationFrame||(this.animationFrame=requestAnimationFrame(()=>{this.animationFrame=null,this.renderCanvas(this.context,this.deltaValue)})))}touch(){this.deltaValue=0}}Sc.animationStateMap=new WeakMap;class Ac extends Mc{constructor(t,e,n={}){super(t,e,{size:1,showId:!1,animation:!1,...n}),this.arrowElement=null,this.labelElement=null,this.decoratorGroup=null}createDOMElements(){if(this.overlay)try{const t=this.getOrCreateDecoratorGroup(!0);this.decoratorGroup=t,t.setAttribute("transform","translate(0, 0)");const{size:e=1,showId:n=!1,duration:r=3e3,repeat:i=!0}=this.options,s=this.options.color||"#FF0000",o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d",this.createArrowPath(0,0,e)),o.setAttribute("fill",s),o.setAttribute("stroke",s),o.setAttribute("stroke-width","1"),o.setAttribute("class","bouncing-arrow");const a=[];if(this.options.animation){const t=this.createBounceAnimation(r,i);if(a.push(t),this.options.fadeOut){const t=this.createFadeAnimation(1,0,r,{repeat:i});a.push(t)}}if(this.addAnimations(o,a),t.appendChild(o),this.arrowElement=o,n&&this.target.state?.id){const n=this.createArrowLabel(0,0,s,this.target.state.id,e);if(this.options.animation){const t=[],e=this.createBounceAnimation(r,i);if(t.push(e),this.options.fadeOut){const e=this.createFadeAnimation(1,0,r,{repeat:i});t.push(e)}this.addAnimations(n,t)}t.appendChild(n),this.labelElement=n}this.vectorElement=t,this.updatePosition(),this.options.animation&&this.startAnimations()}catch(t){jr("화살표 SVG 요소 생성 실패:",t)}}createArrowPath(t,e,n=1){const r=n/this.getScale();return`\n M${t-10*r},${e-16*r} \n L${t+10*r},${e-16*r} \n L${t+10*r},${e-8*r} \n L${t+16*r},${e-8*r} \n L${t},${e} \n L${t-16*r},${e-8*r} \n L${t-10*r},${e-8*r} \n Z\n `}getScale(){try{if(this.target.rootModel&&"number"==typeof this.target.rootModel.scale)return this.target.rootModel.scale||1}catch(t){Rr("스케일 계산 실패, 기본값 사용",t)}return 1}createBounceAnimation(t,e){const n=["0,-10"],r=["0"];for(let t=1;t<=20;t++){const e=t/20;let i=Math.pow(e,.5).toFixed(3);parseFloat(r[r.length-1])>=parseFloat(i)&&(i=(parseFloat(r[r.length-1])+.01).toFixed(3)),n.push("0,0"),n.push("0,-10"),r.push(i),r.push((parseFloat(i)+.01).toFixed(3))}return r[r.length-1]="1.000",this.createTranslateAnimation(n,r,t,{repeat:e})}createArrowLabel(t,e,n,r,i=1){const s=document.createElementNS("http://www.w3.org/2000/svg","g");s.setAttribute("class","bouncing-arrow-label");const o=document.createElementNS("http://www.w3.org/2000/svg","rect");o.setAttribute("x",`${t+20*i}`),o.setAttribute("y",""+(e-20*i)),o.setAttribute("width",""+40*i),o.setAttribute("height",""+20*i),o.setAttribute("rx","3"),o.setAttribute("fill",n);const a=document.createElementNS("http://www.w3.org/2000/svg","text");return a.setAttribute("x",`${t+40*i}`),a.setAttribute("y",""+(e-6*i)),a.setAttribute("fill","white"),a.setAttribute("font-size",12*i+"px"),a.setAttribute("text-anchor","middle"),a.textContent=r,s.appendChild(o),s.appendChild(a),s}startAnimations(){setTimeout(()=>{this.animationElements.forEach(t=>{try{t instanceof SVGElement&&"beginElement"in t&&t.beginElement()}catch(t){jr("애니메이션 시작 오류:",t)}})},10)}invalidate(){this.updatePosition()}updatePosition(){if(!this.vectorElement)return;const{left:t,top:e,width:n}=this.target.bounds,r=this.projectComponentPoint(this.target,t+n/2,e);if(!r)return;const i=Math.max(r.x,20),s=Math.max(r.y,20);this.vectorElement.setAttribute("transform",`translate(${i}, ${s})`)}}Ac.DECORATOR_TYPE="bouncing-arrow",function(t){t.ROTATE="rotate",t.TRANSLATE_X="translateX",t.TRANSLATE_Y="translateY",t.SCALE="scale",t.FADE="fade"}(bc||(bc={})),function(t){t.VIBRATION="vibration",t.ROTATION="rotation",t.HEARTBEAT="heartbeat",t.MOVING="moving",t.OUTLINE="outline",t.FADE="fade",t.WAYPOINT="waypoint"}(vc||(vc={})),function(t){t.CENTER="center",t.TOP="top",t.RIGHT="right",t.BOTTOM="bottom",t.LEFT="left",t.TOP_RIGHT="top-right",t.BOTTOM_RIGHT="bottom-right",t.BOTTOM_LEFT="bottom-left",t.TOP_LEFT="top-left",t.TOP_LEFT_CORNER="top-left-corner",t.TOP_RIGHT_CORNER="top-right-corner",t.BOTTOM_LEFT_CORNER="bottom-left-corner",t.BOTTOM_RIGHT_CORNER="bottom-right-corner",t.LEFT_TOP="left-top",t.LEFT_BOTTOM="left-bottom",t.RIGHT_TOP="right-top",t.RIGHT_BOTTOM="right-bottom"}(_c||(_c={}));class Ec extends Mc{constructor(t,e,n={}){const{animations:r,...i}=n;super(t,e,{icon:"arrow_forward",size:24,color:"#FF0000",deltaX:0,deltaY:0,...i}),this.animations=[],this._location=null,this.element=null,this._delta={theta:0,tx:0,ty:0,sx:1,sy:1,fade:0},this.animations=this.createAnimations(r)}delta(t,e){if(!t)return this._delta;switch(typeof t){case"object":this._delta={...this._delta,...t};break;case"string":if(void 0===e)return this._delta[t];this._delta[t]=e}const{tx:n,ty:r,sx:i,sy:s,theta:o,fade:a}=this._delta;return this.element&&Object.assign(this._getElement().style,{opacity:1-a,transform:`rotate(${o}rad) translate(${n}px, ${r}px) scale(${i}, ${s}) perspective(1px)`}),this._delta}getScaledSize(){const t=this.options.size||24,{x:e}=this.target.rootModel?.state.scale||{x:1},{x:n}=this.target.state.scale||{x:1};return t*e*n}get location(){if(this._location)return this._location;const{location:t,position:e,size:n}=this.options,{bounds:r}=this.target,{left:i,top:s,width:o,height:a}=r,c=n/2;let l;switch(e||t||_c.CENTER){case _c.TOP_LEFT:case"top-left":l={x:i,y:s-n};break;case _c.TOP:case"top":l={x:i+(o-n)/2,y:s-n};break;case _c.TOP_RIGHT:case"top-right":l={x:i+o-n,y:s-n};break;case _c.BOTTOM_LEFT:case"bottom-left":l={x:i,y:s+a};break;case _c.BOTTOM:case"bottom":l={x:i+(o-n)/2,y:s+a};break;case _c.BOTTOM_RIGHT:case"bottom-right":l={x:i+o-n,y:s+a};break;case _c.LEFT_TOP:case"left-top":l={x:i-n,y:s};break;case _c.LEFT:case"left":l={x:i-n,y:s+(a-n)/2};break;case _c.LEFT_BOTTOM:case"left-bottom":l={x:i-n,y:s+(a-n)};break;case _c.RIGHT_TOP:case"right-top":l={x:i+o,y:s};break;case _c.RIGHT:case"right":l={x:i+o,y:s+(a-n)/2};break;case _c.RIGHT_BOTTOM:case"right-bottom":l={x:i+o,y:s+(a-n)};break;case _c.TOP_LEFT_CORNER:case"top-left-corner":l={x:i-c,y:s-c};break;case _c.TOP_RIGHT_CORNER:case"top-right-corner":l={x:i+o-c,y:s-c};break;case _c.BOTTOM_LEFT_CORNER:case"bottom-left-corner":l={x:i-c,y:s+a-c};break;case _c.BOTTOM_RIGHT_CORNER:case"bottom-right-corner":l={x:i+o-c,y:s+a-c};break;case _c.CENTER:default:l={x:i+o/2-n/2,y:s+a/2-n/2}}return this._location=this.toGlobal(l.x,l.y),this._location}_getElement(){return this.element||this._createElementIfNeeded(),this.element}_createElementIfNeeded(){if(this.element)return;const{icon:t="arrow_forward",color:e="#FF0000"}=this.options,n=this.getScaledSize(),{x:r,y:i}=this.location,s=document.createElement("div");s.setAttribute("scene","animated-icon"),Object.assign(s.style,{position:"absolute",fontVariationSettings:"'FILL' 1",fontFamily:"Material Symbols Outlined",fontSize:n+"px",width:n+"px",height:n+"px",lineHeight:n+"px",padding:0,margin:0,color:e,textAlign:"center",verticalAlign:"middle",left:r+"px",top:i+"px",pointerEvents:"none"}),s.textContent=t,this.element=s}updateIconSizeAndPosition(){if(!this.element)return;this._location=null;const t=this.getScaledSize(),{x:e,y:n}=this.location;Object.assign(this.element.style,{fontSize:t+"px",width:t+"px",height:t+"px",lineHeight:t+"px",left:e+"px",top:n+"px"})}touch(){}invalidate(){this.updateIconSizeAndPosition()}start(){super.start(),this.isActive&&(this.overlay&&this._getElement().parentNode!==this.overlay&&this.overlay.appendChild(this._getElement()),this.animations.forEach(t=>t.start()))}stop(){this.animations.forEach(t=>t.stop()),this.element&&this._getElement().parentNode&&this._getElement().parentNode.removeChild(this._getElement()),this._location=null,super.stop()}get center(){const t=this.getScaledSize(),{x:e,y:n}=this.location;return{x:e+t/2,y:n+t/2}}toGlobal(t,e){const{tx:n,ty:r}=this._delta;return this.projectComponentPoint(this.target,t+n,e+r)??this.target.toGlobal(t+n,e+r)}get root(){return this.target.root}createDOMElements(){this._getElement()}updateDOMElements(){this.element?this.updateIconSizeAndPosition():this._getElement()}updatePosition(){this.updateIconSizeAndPosition()}createAnimations(t){if(Array.isArray(t))return t.map(t=>("theta"in t&&(t={...t,theta:t.theta*(Math.PI/180)}),No(this,t)));if(t){const e={...t};return"theta"in e&&(e.theta=e.theta*(Math.PI/180)),[No(this,e)]}return[]}}Ec.DECORATOR_TYPE="animated-icon";class kc extends Mc{constructor(t,e,n={}){super(t,e,{distance:10,lineWidth:2,fillStyle:"rgba(0, 0, 0, 0.5)",animation:!1,...n}),this.pathElement=null,this.decoratorGroup=null,this.elementId=""}createDOMElements(){if(this.overlay)try{this.getSvgContainer();const t=this.getOrCreateDecoratorGroup(!0);this.decoratorGroup=t;const e=this.getDefsForType(),n=this.getVectorGroupId();this.elementId=`${n}-border`;const{color:r="#FF0000",animation:i=!1}=this.options,{fillStyle:s}=this.target.state||{},o=this.createFilter(this.elementId,this.options.fillStyle||s||"rgba(0, 0, 0, 0.5)");if(e.appendChild(o),i){const t=this.createGradient(this.elementId,r);e.appendChild(t)}const a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("fill","none"),a.setAttribute("stroke-width",(this.options.lineWidth||2).toString()),a.setAttribute("stroke-linejoin","round"),a.setAttribute("pointer-events","none"),a.setAttribute("class","border-highlighting-path"),a.setAttribute("filter",`url(#${this.elementId}-filter)`),i?a.setAttribute("stroke",`url(#${this.elementId})`):a.setAttribute("stroke",r),t.appendChild(a),this.pathElement=a,this.vectorElement=t,this.updatePathData(),this.options.animation&&this.startAnimations()}catch(t){jr("테두리 하이라이팅 요소 생성 실패:",t)}}updatePathData(){if(!this.pathElement)return;this.pathElement.setAttribute("visibility","visible"),this.pathElement.setAttribute("opacity","1"),this.decoratorGroup&&(this.decoratorGroup.setAttribute("visibility","visible"),this.decoratorGroup.setAttribute("opacity","1"));const t=this.getPathPoints(),e=this.createOffsetPath(t,this.options.distance),{round:n=0}=this.target.state||{},r=this.pointsToPathData(e,n);this.pathElement.setAttribute("d",r)}invalidate(){this.updatePathData()}startAnimations(){if(!this.isActive||!this.options.animation||!this.pathElement)return;this.pathElement.setAttribute("visibility","visible"),this.pathElement.setAttribute("opacity","1"),this.decoratorGroup&&(this.decoratorGroup.setAttribute("visibility","visible"),this.decoratorGroup.setAttribute("opacity","1")),this.elementId&&(this.pathElement.setAttribute("stroke",`url(#${this.elementId})`),this.pathElement.setAttribute("filter",`url(#${this.elementId}-filter)`));const t=this.getDefsForType();if(t){const e=t.querySelector(`#${this.elementId}`);if(e){e.querySelectorAll("animate").forEach(t=>{try{t instanceof SVGElement&&"beginElement"in t&&(t.setAttribute("restart","always"),t.beginElement())}catch(t){jr("애니메이션 시작 오류:",t)}})}}}createDefsElement(t){const e=document.createElementNS("http://www.w3.org/2000/svg","defs");return t.appendChild(e),e}getPathPoints(){if(!this.target.path||!Array.isArray(this.target.path)){const{left:t,top:e,width:n,height:r}=this.target.bounds;return[{x:t,y:e},{x:t+n,y:e},{x:t+n,y:e+r},{x:t,y:e+r}]}return this.target.path.map(t=>this.target.toGlobal(t.x,t.y))}createOffsetPath(t,e){const n=[],r=t.length;for(let i=0;i<r;i++){const s=t[(i-1+r)%r],o=t[i],a=t[(i+1)%r],c=o.x-s.x,l=o.y-s.y,h=a.x-o.x,d=a.y-o.y,u=this.normalize({x:l,y:-c}),p=this.normalize({x:d,y:-h}),f=this.normalize({x:(u.x+p.x)/2,y:(u.y+p.y)/2}),g={x:o.x+f.x*e,y:o.y+f.y*e};n.push(g)}return n}normalize(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return{x:t.x/e||0,y:t.y/e||0}}pointsToPathData(t,e=0){if(t.length<2)return"";let n="";const r=t.length,i=(t,e,n)=>{const r=e.x-t.x,i=e.y-t.y,s=Math.sqrt(r*r+i*i);return{x:t.x+r/s*n,y:t.y+i/s*n}};for(let s=0;s<r;s++){const o=t[s],a=t[(s+1)%r],c=t[(s-1+r)%r],l=Math.sqrt((o.x-c.x)**2+(o.y-c.y)**2),h=Math.sqrt((o.x-a.x)**2+(o.y-a.y)**2),d=Math.min(e,l/2,h/2),u=i(o,c,d),p=i(o,a,d);n+=0===s?`M${u.x},${u.y}`:` L${u.x},${u.y}`,n+=` Q${o.x},${o.y} ${p.x},${p.y}`}return n+=" Z",n}createFilter(t,e){const n=document.createElementNS("http://www.w3.org/2000/svg","filter");n.setAttribute("id",`${t}-filter`);const r=document.createElementNS("http://www.w3.org/2000/svg","feFlood");r.setAttribute("flood-color",e),r.setAttribute("result","flood");const i=document.createElementNS("http://www.w3.org/2000/svg","feComposite");i.setAttribute("in","flood"),i.setAttribute("in2","SourceAlpha"),i.setAttribute("operator","in"),i.setAttribute("result","mask");const s=document.createElementNS("http://www.w3.org/2000/svg","feMerge"),o=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");o.setAttribute("in","mask");const a=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");return a.setAttribute("in","SourceGraphic"),s.appendChild(o),s.appendChild(a),n.appendChild(r),n.appendChild(i),n.appendChild(s),n}createGradient(t,e){const n=document.createElementNS("http://www.w3.org/2000/svg","linearGradient");n.setAttribute("id",t),n.setAttribute("x1","0%"),n.setAttribute("y1","0%"),n.setAttribute("x2","100%"),n.setAttribute("y2","0%");const r=this.alterColor(e,120),i=this.alterColor(e,240),s=document.createElementNS("http://www.w3.org/2000/svg","stop");s.setAttribute("offset","0%"),s.setAttribute("stop-color",e);const o=document.createElementNS("http://www.w3.org/2000/svg","animate");o.setAttribute("attributeName","stop-color"),o.setAttribute("values",`${e};${r};${i};${e}`),o.setAttribute("dur","5s"),o.setAttribute("repeatCount","indefinite");const a=document.createElementNS("http://www.w3.org/2000/svg","stop");a.setAttribute("offset","100%"),a.setAttribute("stop-color",i);const c=document.createElementNS("http://www.w3.org/2000/svg","animate");return c.setAttribute("attributeName","stop-color"),c.setAttribute("values",`${i};${e};${r};${i}`),c.setAttribute("dur","5s"),c.setAttribute("repeatCount","indefinite"),s.appendChild(o),a.appendChild(c),n.appendChild(s),n.appendChild(a),n}alterColor(t,e){const n=this.convertToHex(t),r=parseInt(n.substring(1,3),16),i=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),o=this.rgbToHsl(r,i,s);o[0]=(o[0]+e/360)%1;const a=this.hslToRgb(o[0],o[1],o[2]);return`#${a[0].toString(16).padStart(2,"0")}${a[1].toString(16).padStart(2,"0")}${a[2].toString(16).padStart(2,"0")}`}rgbToHsl(t,e,n){t/=255,e/=255,n/=255;const r=Math.max(t,e,n),i=Math.min(t,e,n);let s=0,o=0;const a=(r+i)/2;if(r!==i){const c=r-i;switch(o=a>.5?c/(2-r-i):c/(r+i),r){case t:s=(e-n)/c+(e<n?6:0);break;case e:s=(n-t)/c+2;break;case n:s=(t-e)/c+4}s/=6}return[s,o,a]}hslToRgb(t,e,n){let r,i,s;if(0===e)r=i=s=n;else{const o=(t,e,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t),a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=o(c,a,t+1/3),i=o(c,a,t),s=o(c,a,t-1/3)}return[Math.round(255*r),Math.round(255*i),Math.round(255*s)]}convertToHex(t){if(/^#([0-9A-F]{6})$/i.test(t))return t;const e=document.createElement("canvas");e.width=1,e.height=1;const n=e.getContext("2d");if(!n)return"#FF0000";n.fillStyle=t,n.fillRect(0,0,1,1);const r=n.getImageData(0,0,1,1).data;return`#${r[0].toString(16).padStart(2,"0")}${r[1].toString(16).padStart(2,"0")}${r[2].toString(16).padStart(2,"0")}`}start(){super.start(),this.isActive&&this.options.animation&&this.startAnimations()}removeDOMElements(){try{if(this.pathElement&&this.pathElement.parentNode&&this.pathElement.parentNode.removeChild(this.pathElement),this.pathElement=null,this.overlay){const t=this.getDefsForType();if(t&&this.elementId){const e=t.querySelector(`#${this.elementId}-filter`);e&&e.remove();const n=t.querySelector(`#${this.elementId}`);n&&n.remove()}}super.removeDOMElements()}catch(t){jr("테두리 하이라이팅 요소 제거 중 오류:",t)}}}kc.DECORATOR_TYPE="border-highlighting";class Cc extends Mc{constructor(t,e,n={}){super(t,e,{bgColor:"#FF0000",textColor:"white",cornerRadius:3,padding:3,fontSize:"12px",fontFamily:"Arial",...n}),this.textElements=[],this.rectElements=[]}updateDOMElements(){if(!this.target.anchors||!this.target.anchors.length)return void this.removeDOMElements();const t=this.options,e=this.target.anchors,n=this.getOrCreateDecoratorGroup(!0);this.textElements=[],this.rectElements=[];const r=this.getComponentBounds();e.forEach(e=>{const{name:i,position:s}=e;let{x:o,y:a}=s||{};if(!i)return;let c=this.calculateOffsetX(o,r),l=this.calculateOffsetY(a,r);const h=this.projectComponentPoint(this.target,o,a);if(!h)return;o=h.x,a=h.y;const d=document.createElementNS("http://www.w3.org/2000/svg","text");d.setAttribute("fill",t.textColor),d.setAttribute("font-family",t.fontFamily),d.setAttribute("font-size",t.fontSize),d.textContent=i,n.appendChild(d);const u=d.getBBox();n.removeChild(d);const p=u.width,f=u.height;c=-1==c?-p-9:3,l=-1==l?-f-9:3,d.setAttribute("x",(o+c+3).toString()),d.setAttribute("y",(a+l+f).toString());const g=document.createElementNS("http://www.w3.org/2000/svg","rect");g.setAttribute("x",(o+c).toString()),g.setAttribute("y",(a+l).toString()),g.setAttribute("width",(p+6).toString()),g.setAttribute("height",(f+6).toString()),g.setAttribute("rx",t.cornerRadius.toString()),g.setAttribute("ry",t.cornerRadius.toString()),g.setAttribute("fill",t.bgColor),n.appendChild(g),n.appendChild(d),this.rectElements.push(g),this.textElements.push(d)})}calculateOffsetX(t,e){return t<e.left+1?-1:1}calculateOffsetY(t,e){return t<e.top+1?-1:1}updatePosition(){super.updatePosition(),this.updateDOMElements()}invalidate(){this.updatePosition()}createDOMElements(){this.updateDOMElements()}}Cc.DECORATOR_TYPE="anchors";class Pc extends Mc{constructor(t,e,n={}){super(t,e,{bgColor:"#FF0000",textColor:"white",cornerRadius:3,padding:3,fontSize:"12px",fontFamily:"Arial",offsetX:3,offsetY:-8,animation:!1,...n}),this.textElement=null,this.backgroundElement=null,this.currentTag=""}createDOMElements(){const t=this.target.decotag;if(!t)return;this.currentTag=t;const{fontFamily:e,fontSize:n,textColor:r,padding:i,cornerRadius:s,bgColor:o,animation:a,repeat:c,duration:l}=this.options,h=this.getOrCreateDecoratorGroup(!0);h.setAttribute("transform","translate(0, 0)"),this.textElement=document.createElementNS("http://www.w3.org/2000/svg","text"),this.textElement.textContent=t,this.textElement.setAttribute("x",`${i}`),this.textElement.setAttribute("y",`-${n}`),this.textElement.setAttribute("font-family",e),this.textElement.setAttribute("font-size",n),this.textElement.setAttribute("fill",r),this.textElement.setAttribute("dominant-baseline","middle"),h.appendChild(this.textElement);const d=this.textElement.getBBox();if(this.backgroundElement=document.createElementNS("http://www.w3.org/2000/svg","rect"),this.backgroundElement.setAttribute("x",(d.x-i).toString()),this.backgroundElement.setAttribute("y",(d.y-i).toString()),this.backgroundElement.setAttribute("width",(d.width+2*i).toString()),this.backgroundElement.setAttribute("height",(d.height+2*i).toString()),this.backgroundElement.setAttribute("rx",s.toString()),this.backgroundElement.setAttribute("ry",s.toString()),this.backgroundElement.setAttribute("fill",o),h.replaceChildren(),h.appendChild(this.backgroundElement),h.appendChild(this.textElement),a){const t=this.createFadeAnimation(.3,1,l,{repeat:c});this.addAnimations(h,[t])}this.vectorElement=h,this.updatePosition()}updateDOMElements(){const t=this.target.decotag;t&&t===this.currentTag?this.vectorElement&&this.updatePosition():(this.removeDOMElements(),this.createDOMElements())}updatePosition(){super.updatePosition()}invalidate(){this.updatePosition()}}Pc.DECORATOR_TYPE="decotag";class Tc extends Mc{constructor(t,e,n={}){super(t,e,{arrowColor:"#FFA500",arrowHeadLength:12,lineWidth:1.5,startAlpha:.6,endAlpha:1,animated:!0,animationDuration:5e3,repeat:!1,...n}),this.currentMappings=null}createDOMElements(){if(this.removeDOMElements(),!this.target.mappings||!this.target.mappings.length)return;this.currentMappings=this.target.mappings;const t=this.options,e=this.getOrCreateDecoratorGroup(!0),n=this.getDefsForType(),r=`data-spread-style-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,i=document.createElementNS("http://www.w3.org/2000/svg","style");i.setAttribute("id",r),i.textContent=`\n @keyframes fadeOut {\n from { opacity: 1; }\n to { opacity: ${t.repeat?"0.2":"0"}; }\n }\n .arrow-animated {\n animation: fadeOut ${t.animationDuration||2e3}ms linear ${t.repeat?"infinite":"1"} forwards;\n }\n `,n.appendChild(i);const s=`arrow-gradient-${Date.now()}-${Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}`,o=document.createElementNS("http://www.w3.org/2000/svg","linearGradient");o.setAttribute("id",s),o.setAttribute("gradientUnits","userSpaceOnUse");const a=document.createElementNS("http://www.w3.org/2000/svg","stop");a.setAttribute("offset","0%"),a.setAttribute("stop-color",t.arrowColor||"#FFA500"),a.setAttribute("stop-opacity",(t.startAlpha||.5).toString());const c=document.createElementNS("http://www.w3.org/2000/svg","stop");c.setAttribute("offset","100%"),c.setAttribute("stop-color",t.arrowColor||"#FFA500"),c.setAttribute("stop-opacity",(t.endAlpha||1).toString()),o.appendChild(a),o.appendChild(c),n.appendChild(o);const l=document.createElementNS("http://www.w3.org/2000/svg","g");l.setAttribute("class",t.animated?"arrow-animated":""),e.appendChild(l);this.target.mappings.forEach(e=>{const n=this.target.root.findAll(e.target,this.target);n&&n.length&&n.forEach(e=>{const n=this.target.center,r=e.center,i=this.projectComponentPoint(this.target,n.x,n.y),a=this.projectComponentPoint(e,r.x,r.y);if(!i||!a)return;o.setAttribute("x1",i.x.toString()),o.setAttribute("y1",i.y.toString()),o.setAttribute("x2",a.x.toString()),o.setAttribute("y2",a.y.toString());const{linePath:c,headPath:h}=this.createArrowPaths(i,a,t.arrowHeadLength),d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d",c),d.setAttribute("stroke",`url(#${s})`),d.setAttribute("stroke-width",String(t.lineWidth||2)),d.setAttribute("fill","none"),d.setAttribute("data-target-id",e.state?.id||""),d.setAttribute("data-source-id",this.target.state?.id||"");const u=document.createElementNS("http://www.w3.org/2000/svg","path");u.setAttribute("d",h),u.setAttribute("fill",t.arrowColor||"#FFA500"),u.setAttribute("stroke","none"),l.appendChild(d),l.appendChild(u)})}),this.vectorElement=e}createArrowPaths(t,e,n){const r=e.x-t.x,i=e.y-t.y,s=Math.atan2(i,r),o=e.x+n*Math.cos(s+Tc.ARROW_ANGLE_1),a=e.y+n*Math.sin(s+Tc.ARROW_ANGLE_1),c=e.x+n*Math.cos(s+Tc.ARROW_ANGLE_2),l=e.y+n*Math.sin(s+Tc.ARROW_ANGLE_2);return{linePath:`M ${t.x} ${t.y} L ${e.x} ${e.y}`,headPath:`M ${e.x} ${e.y} L ${o} ${a} L ${c} ${l} Z`}}updateDOMElements(){if(!this.target.app?.isEditMode)return void this.removeDOMElements();const t=this.target.mappings;t&&t===this.currentMappings?this.vectorElement&&this.updatePosition():(this.removeDOMElements(),requestAnimationFrame(()=>{this.createDOMElements()}))}updatePosition(){const t=this.getDecoratorType(),e=this.getSvgContainer().querySelector(`g[data-decorator-type-container="${t}"]`);if(!e)return;const n=this.getVectorGroupId(),r=e.querySelector(`g[data-decorator-group-id="${n}"]`);if(!r)return;const i=this.options;if(!this.target.mappings||!this.target.mappings.length)return;const s=r.querySelector("g.arrow-animated")||r,o=Array.from(s.querySelectorAll('path[fill="none"]')),a=Array.from(s.querySelectorAll('path[stroke="none"]'));if(0===o.length)return;const c=e.querySelector(`defs[data-defs-for="${t}"]`);if(!c)return;const l=c.querySelector("linearGradient");if(!l)return;const h=this.target.mappings;let d=[];h.forEach(t=>{const e=this.target.root.findAll(t.target,this.target);e&&e.length&&(d=[...d,...e])});for(let t=0;t<Math.min(o.length,a.length,d.length);t++){const e=o[t],n=a[t],r=d[t],s=this.target.center,c=r.center,h=this.projectComponentPoint(this.target,s.x,s.y),u=this.projectComponentPoint(r,c.x,c.y);if(!h||!u)continue;const{linePath:p,headPath:f}=this.createArrowPaths(h,u,i.arrowHeadLength);e.setAttribute("d",p),n.setAttribute("d",f),0===t&&l&&(l.setAttribute("x1",h.x.toString()),l.setAttribute("y1",h.y.toString()),l.setAttribute("x2",u.x.toString()),l.setAttribute("y2",u.y.toString()))}}removeDOMElements(){this.currentMappings=null;try{if(this.overlay){const t=this.getSvgContainer();if(t){const e=this.getDecoratorType(),n=t.querySelector(`g[data-decorator-type-container="${e}"]`);if(n){const t=n.querySelector(`defs[data-defs-for="${e}"]`);if(t){t.querySelectorAll("style").forEach(t=>t.remove());t.querySelectorAll("linearGradient").forEach(t=>t.remove())}}}}this.animationElements=[],super.removeDOMElements()}catch(t){jr("데이터 스프레드 데코레이터 요소 제거 중 오류:",t)}}invalidate(){this.updatePosition()}}Tc.DECORATOR_TYPE="data-spread",Tc.ARROW_ANGLE_1=160*Math.PI/180,Tc.ARROW_ANGLE_2=200*Math.PI/180;class Dc extends Mc{constructor(t,e,n={}){super(t,e,{bgColor:"#FF0000",textColor:"white",cornerRadius:2,padding:2,fontSize:"12px",fontFamily:"Arial",offsetX:4,offsetY:4,...n}),this.textElements=[],this.rectElements=[]}createDOMElements(){this.updateDOMElements()}updateDOMElements(){if(!this.target.isLine||!this.target.isLine())return void this.removeDOMElements();const{offsetX:t,offsetY:e,padding:n,textColor:r,bgColor:i,cornerRadius:s,fontSize:o,fontFamily:a}=this.options,c=this.getOrCreateDecoratorGroup(!0);this.textElements=[],this.rectElements=[];const{fromEnd:l,toEnd:h}=this.target;[l,h].filter(Boolean).forEach(l=>{const{component:h,anchor:d}=l;if(!d)return;const{name:u,position:p}=d||{};if(!h.rootModel||!u||!p)return;const f=this.projectComponentPoint(h,p.x,p.y);if(!f)return;let{x:g,y:m}=f;const y=document.createElementNS("http://www.w3.org/2000/svg","g"),b=document.createElementNS("http://www.w3.org/2000/svg","text");b.setAttribute("text-anchor","middle"),b.setAttribute("dominant-baseline","middle"),b.setAttribute("x","0"),b.setAttribute("y","0"),b.setAttribute("fill",r),b.setAttribute("font-family",a),b.setAttribute("font-size",o),b.textContent=u,c.appendChild(b);const v=b.getBBox();c.removeChild(b);const _=document.createElementNS("http://www.w3.org/2000/svg","rect"),x=v.width+2*(n??0),w=v.height+2*(n??0);g+=(t??0)+x/2,m+=(e??0)+w/2,_.setAttribute("x",(-x/2).toString()),_.setAttribute("y",(-w/2).toString()),_.setAttribute("width",x.toString()),_.setAttribute("height",w.toString()),_.setAttribute("rx",(s??0).toString()),_.setAttribute("ry",(s??0).toString()),_.setAttribute("fill",i),y.appendChild(_),y.appendChild(b),y.setAttribute("transform",`translate(${g}, ${m})`),c.appendChild(y),this.rectElements.push(_),this.textElements.push(b)})}updatePosition(){super.updatePosition(),this.updateDOMElements()}invalidate(){this.updatePosition()}}Dc.DECORATOR_TYPE="link",ys.registerDecorator("bouncing-arrow",Ac),ys.registerDecorator("animated-icon",Ec),ys.registerDecorator("border-highlighting",kc),ys.registerDecorator("anchors",Cc),ys.registerDecorator("decotag",Pc),ys.registerDecorator("data-spread",Tc),ys.registerDecorator("link",Dc);class Oc{constructor(t){this.params=Object.assign({},t)}excute(){}}class zc extends Oc{execute(){this.params.changes.forEach(t=>t.component.set(t.after))}static before(t){return t.map(t=>({component:t}))}static after(t,e){e.execute(null,!1)}static around(t,e,n){e.call(n),t.execute(null,!1)}}const Ic="left",Lc="right",jc="center",Rc="bottom",Fc="middle",Bc="z-front",Nc="z-back",Hc="z-middle",Vc=[Ic,Lc,jc,"top",Fc,Rc,Bc,Nc,Hc];function Gc(t){if(!this.hasSameParentForAllSelected||-1===Vc.indexOf(t))return;const e=this.selected.filter(t=>!t.stuck);if(e.length<=1)return;const n=this.app.commander;zc.around(n,function(){!function(t,e){const n=JSON.parse(JSON.stringify(e[0].bounds));let r=n.left+n.width,i=n.top+n.height;for(let t=0;t<e.length;t++){const s=e[t].bounds;n.left=s.left>n.left?n.left:s.left,n.top=s.top>n.top?n.top:s.top,r=s.left+s.width>r?s.left+s.width:r,i=s.top+s.height>i?s.top+s.height:i}switch(n.width=r-n.left,n.height=i-n.top,t){case Ic:for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:n.left,top:r.top,width:r.width,height:r.height}}break;case jc:for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:n.left+n.width/2-r.width/2,top:r.top,width:r.width,height:r.height}}break;case Lc:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={left:r-n.width,top:n.top,width:n.width,height:n.height}}break;case"top":for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:r.left,top:n.top,width:r.width,height:r.height}}break;case Fc:for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:r.left,top:n.top+n.height/2-r.height/2,width:r.width,height:r.height}}break;case Rc:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={left:n.left,top:i-n.height,width:n.width,height:n.height}}break;case Bc:{let t=1/0;for(let n=0;n<e.length;n++){const r=e[n].state.zPos||0;r<t&&(t=r)}for(let n=0;n<e.length;n++)e[n].set({zPos:t});break}case Nc:{let t=-1/0;for(let n=0;n<e.length;n++){const r=(e[n].state.zPos||0)+(e[n].state.depth||0);r>t&&(t=r)}for(let n=0;n<e.length;n++){const r=e[n].state.depth||0;e[n].set({zPos:t-r})}break}case Hc:{let t=1/0,n=-1/0;for(let r=0;r<e.length;r++){const i=e[r].state.zPos||0,s=e[r].state.depth||0;i<t&&(t=i),i+s>n&&(n=i+s)}const r=(t+n)/2;for(let t=0;t<e.length;t++){const n=e[t].state.depth||0;e[t].set({zPos:r-n/2})}break}default:;}}(t,e)})}const Yc="VERTICAL",Uc=[Yc,"HORIZONTAL","Z"];function $c(t){if(!this.hasSameParentForAllSelected||-1===Uc.indexOf(t))return;const e=this.selected;if(e.length<=1)return;const n=this.app.commander;zc.around(n,function(){!function(t,e){if("Z"===t)return void function(t){const e=t.filter(t=>!t.stuck).slice(0);e.sort((t,e)=>(t.state.zPos||0)+(t.state.depth||0)/2-((e.state.zPos||0)+(e.state.depth||0)/2));const n=e.reduce((t,e)=>t+(e.state.depth||0),0),r=e[0].state.zPos||0,i=((e[e.length-1].state.zPos||0)+(e[e.length-1].state.depth||0)-r-n)/(e.length-1);let s=r+(e[0].state.depth||0);for(let t=1;t<e.length-1;t++){const n=e[t],r=n.state.depth||0;s+=i,n.set({zPos:s}),s+=r}}(e);const n=e.filter(t=>!t.stuck).slice(0);n.sort(function(e,n){const r=e.center,i=n.center;return t===Yc?r.y-i.y:r.x-i.x});const r=n.reduce((e,n)=>e+(t===Yc?n.bounds.height:n.bounds.width),0),i=n[0].bounds,s=n[n.length-1].bounds,o=((t===Yc?s.top+s.height-i.top:s.left+s.width-i.left)-r)/(n.length-1);let a=t===Yc?i.top+i.height:i.left+i.width;for(let e=1;e<n.length-1;e++){const r=n[e],i=r.bounds;a+=o,t===Yc?(r.bounds={left:i.left,top:a,width:i.width,height:i.height},a+=i.height):(r.bounds={left:a,top:i.top,width:i.width,height:i.height},a+=i.width)}}(t,e)})}function Wc(t){let e=0;for(;t&&!t.isRootModel();)e+=t.get("rotation")||0,t=t.parent;return e%(2*Math.PI)}class Xc extends Oc{execute(){this.params.changes.forEach(t=>{const{component:e,to_container:n,to_index:r,to_left:i,to_top:s}=t,o=function(t){if(t.isRootModel())return t.bounds;const{bounds:e,rotatePoint:n}=t;let r=n;return r=t.toScene(r.x,r.y),{left:r.x-(n.x-e.left),top:r.y-(n.y-e.top),width:e.width,height:e.height}}(e),a=Wc(e);if(e.removeSelf(!n),e.bounds=o,e.set("rotation",a),n){e.set("rotation",function(t,e){return((t.get("rotation")||0)-Wc(e))%(2*Math.PI)}(e,n));const o=function(t,e){if(e.isRootModel())return t.bounds;const{bounds:n,rotatePoint:r}=t,i=e.fromScene(r.x,r.y),s=e.bounds;return{left:i.x-(r.x-n.left)-s.left,top:i.y-(r.y-n.top)-s.top,width:n.width,height:n.height}}(e,n);t.to_left=void 0!==i?i:o.left,t.to_top=void 0!==s?s:o.top,e.bounds={left:t.to_left,top:t.to_top,width:o.width,height:o.height},void 0===r?n.addComponent(e):n.insertComponentAt(e,r)}})}}function qc(t,e,n){this.app.commander.execute(new Xc({changes:[{component:t,to_container:e,to_index:n}]}))}function Kc(t){const e=this.selected.filter(t=>!t.stuck);if(0===e.length||e[0].isRootModel())return;if(e.length>1&&("forward"===t||"backward"===t))return;const n=e[0].parent;let r;if("forward"===t){const t=n.indexOf(e[0]);r=[{component:e[0],from_container:n,to_container:n,from_index:t,to_index:t+1}]}else if("backward"===t){const t=n.indexOf(e[0]);r=[{component:e[0],from_container:n,to_container:n,from_index:t,to_index:t-1}]}else r=e.filter(t=>t.parent===n).sort((e,r)=>{const i=n.indexOf(e)<n.indexOf(r);return"front"===t?i:!i}).map((e,r)=>(n.indexOf(e),{component:e,to_container:n,to_index:"front"===t?n.components.length-r-1:r}));const i=new Xc({changes:r});this.app.commander.execute(i)}function Qc(t,e,n,r){const i=Fa.register(t.type);if(!i)return Rr("Class not found",t.type),null;n&&(t.refid=n(t.refid)),t.id&&r&&r(t.id)&&delete t.id;const s=new i(t,e);return t.components&&s.isContainer()&&(t.components.forEach(t=>{const i=Qc(t,e,n,r);i&&s.addComponent(i)}),delete t.components),s.created(),s}function Zc(t,e){const n=Bn(t.hierarchy);return delete n.id,Qc(n,t.app,e)}function Jc(t,e,n){t instanceof Array||(t=[t]),n||(n=this.model_layer);const r=[],i=new Map;this.selected=t.map(t=>{try{return Qc(t,n.app,t=>{const e=this.getNewRefid();return void 0!==t&&i.set(t,e),e},t=>(this.indexMap[t]||[])[0])}catch(t){return Rr(t),!1}}).filter(Boolean).map(t=>{const{left:s,top:o,width:a,height:c,x:l,y:h,cx:d,cy:u}=e;return t.replaceRefids(i),isNaN(s)||isNaN(o)||isNaN(a)||isNaN(c)||(t.bounds={left:s,top:o,width:a,height:c}),isNaN(l)||isNaN(h)||t.move({x:l,y:h},!1),isNaN(d)||isNaN(u)||(t.center={x:d,y:u}),r.push({component:t,to_container:n}),t}),this.app.commander.execute(new Xc({changes:r}))}function tl(){const t=[],e=new Map;if(this.selected=this.selected.filter(t=>!t.isRootModel()).map(n=>{const r=Zc(n,t=>{const n=this.getNewRefid();return void 0!==t&&e.set(t,n),n});return r.move({x:20,y:20},!1),t.push({component:r,to_container:n.parent}),r}).map(t=>(t.replaceRefids(e),t)),0===t.length)return;const n=new Xc({changes:t});this.app.commander.execute(n)}function el(){const t=this.selected;this.selected=[];let e=null;const n=t.filter(t=>!t.isRootModel()&&(t.parent.focusible||t.parent.isGroup())).map(t=>(e||(e=t.parent),{component:t,to_container:null}));for(;e&&e.isGroup();){const t=[];if(e.components.filter(t=>!n.find(e=>e.component===t)).forEach(e=>t.push(e)),t.length>1)break;const r=e.parent;t.forEach(t=>n.push({component:t,to_container:r})),n.push({component:e,to_container:null}),e=r}n.length>0&&this.app.commander.execute(new Xc({changes:n})),e&&e.calculateBounds&&e.calculateBounds()}const nl=new Set(["execute","redo","undo","command-reset"]);function rl(t,e,n,r){const i=function(t,e){return nl.has(e)?t.app?.commander:"mode"===e?t.app:t}(this,e);i?.[t](e,n,r)}function il(t,e,n){rl.call(this,"on",t,e,n)}function sl(t,e,n){rl.call(this,"once",t,e,n)}function ol(t,e,n){rl.call(this,"off",t,e,n)}function al(t){const e=this.target_element,n=t||this.fitMode,r=this;function i(){r.fit(n),document.fullscreenElement||document.removeEventListener("fullscreenchange",i)}document.addEventListener("fullscreenchange",i),e.requestFullscreen().catch(()=>{document.removeEventListener("fullscreenchange",i)})}let cl=0;function ll(){const t=this.selected.filter(t=>!t.isRootModel()).map(t=>t.hierarchy);if(0!==t.length)return cl=0,JSON.stringify(t,null,2)}function hl(){cl=0;const t=ll.call(this);return el.call(this),t}function dl(t){if(t)try{cl++,Jc.call(this,JSON.parse(t),{x:15*cl,y:15*cl})}catch(e){jr(e,t)}}const ul=function(){return{escape:function(t){return t.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")},parseExtension:t,mimeType:function(e){const n=t(e).toLowerCase();return function(){const t="application/font-woff",e="image/jpeg";return{woff:t,woff2:t,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:e,jpeg:e,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml"}}()[n]||""},dataAsUrl:function(t,e){return"data:"+e+";base64,"+t},isDataUrl:function(t){return-1!==t.search(/^(data:)/)},canvasToBlob:function(t){return t.toBlob?new Promise(function(e){t.toBlob(e)}):function(t){return new Promise(function(e){const n=window.atob(t.toDataURL().split(",")[1]),r=n.length,i=new Uint8Array(r);for(let t=0;t<r;t++)i[t]=n.charCodeAt(t);e(new Blob([i],{type:"image/png"}))})}(t)},resolveUrl:function(t,e){const n=document.implementation.createHTMLDocument(),r=n.createElement("base");n.head.appendChild(r);const i=n.createElement("a");return n.body.appendChild(i),r.href=e,i.href=t,i.href},getAndEncode:function(t){const e=3e4;_l.impl.options.cacheBust&&(t+=(/\?/.test(t)?"&":"?")+(new Date).getTime());return new Promise(function(n){const r=new XMLHttpRequest;let i;if(r.onreadystatechange=s,r.ontimeout=o,r.responseType="blob",r.timeout=e,r.open("GET",t,!0),r.send(),_l.impl.options.imagePlaceholder){const t=_l.impl.options.imagePlaceholder.split(/,/);t&&t[1]&&(i=t[1])}function s(){if(4!==r.readyState)return;if(200!==r.status)return void(i?n(i):a("cannot fetch resource: "+t+", status: "+r.status));const e=new FileReader;e.onloadend=function(){const t=e.result.split(/,/)[1];n(t)},e.readAsDataURL(r.response)}function o(){i?n(i):a("timeout of "+e+"ms occured while fetching resource: "+t)}function a(t){jr(t),n("")}})},uid:function(){let t=0;return function(){return"u"+e()+t++;function e(){return("0000"+(Math.random()*Math.pow(36,4)|0).toString(36)).slice(-4)}}}(),delay:function(t){return function(e){return new Promise(function(n){setTimeout(function(){n(e)},t)})}},asArray:function(t){const e=[],n=t.length;for(let r=0;r<n;r++)e.push(t[r]);return e},escapeXhtml:function(t){return t.replace(/#/g,"%23").replace(/\n/g,"%0A")},makeImage:function(t){return new Promise(function(e,n){const r=new Image;r.onload=function(){e(r)},r.onerror=n,r.src=t})},width:function(t){const n=e(t,"border-left-width"),r=e(t,"border-right-width");return t.scrollWidth+n+r},height:function(t){const n=e(t,"border-top-width"),r=e(t,"border-bottom-width");return t.scrollHeight+n+r}};function t(t){const e=/\.([^\.\/]*?)$/g.exec(t);return e?e[1]:""}function e(t,e){const n=window.getComputedStyle(t).getPropertyValue(e);return parseFloat(n.replace("px",""))}}(),pl=function(){const t=/url\(['"]?([^'"]+?)['"]?\)/g;return{inlineAll:function(t,i,s){return o()?Promise.resolve(t):Promise.resolve(t).then(n).then(function(e){let n=Promise.resolve(t);return e.forEach(function(t){n=n.then(function(e){return r(e,t,i,s)})}),n});function o(){return!e(t)}},shouldProcess:e,impl:{readUrls:n,inline:r}};function e(e){return-1!==e.search(t)}function n(e){const n=[];let r;for(;null!==(r=t.exec(e));)n.push(r[1]);return n.filter(function(t){return!ul.isDataUrl(t)})}function r(t,e,n,r){return Promise.resolve(e).then(function(t){return n?ul.resolveUrl(t,n):t}).then(r||ul.getAndEncode).then(function(t){return ul.dataAsUrl(t,ul.mimeType(e))}).then(function(n){return t.replace(function(t){return new RegExp("(url\\(['\"]?)("+ul.escape(t)+")(['\"]?\\))","g")}(e),"$1"+n+"$3")})}}(),fl=function(){return{resolveAll:function(){return t().then(function(t){return Promise.all(t.map(function(t){return t.resolve()}))}).then(function(t){return t.join("\n")})},impl:{readAll:t}};function t(){return Promise.resolve(ul.asArray(document.styleSheets)).then(function(t){const e=[];return t.forEach(function(t){try{ul.asArray(t.cssRules||[]).forEach(t=>e.push(t))}catch(e){Rr("Error while reading CSS rules from "+t.href,e instanceof Error?e.message:String(e))}}),e}).then(function(t){return t.filter(function(t){return t.type===CSSRule.FONT_FACE_RULE}).filter(function(t){return pl.shouldProcess(t.style.getPropertyValue("src"))})}).then(function(e){return e.map(t)});function t(t){return{resolve:function(){const e=(t.parentStyleSheet||{}).href;return pl.inlineAll(t.cssText,e)},src:function(){return t.style.getPropertyValue("src")}}}}}(),gl=function(){return{inlineAll:function e(n){return n instanceof Element?r(n).then(function(){return n instanceof HTMLImageElement?t(n).inline().then(()=>n):Promise.all(ul.asArray(n.childNodes).map(function(t){return e(t)})).then(()=>n)}):Promise.resolve(n);function r(t){const e=t.style.getPropertyValue("background");return e?pl.inlineAll(e).then(function(e){t.style.setProperty("background",e,t.style.getPropertyPriority("background"))}).then(function(){return t}):Promise.resolve(t)}},impl:{newImage:t}};function t(t){return{inline:function(e){return ul.isDataUrl(t.src)?Promise.resolve():Promise.resolve(t.src).then(e||ul.getAndEncode).then(function(e){return ul.dataAsUrl(e,ul.mimeType(t.src))}).then(function(e){return new Promise(function(n,r){t.onload=n,t.onerror=r,t.src=e})})}}}}(),ml={imagePlaceholder:void 0,cacheBust:!1};function yl(t,e){return function(t){void 0===t.imagePlaceholder?_l.impl.options.imagePlaceholder=ml.imagePlaceholder:_l.impl.options.imagePlaceholder=t.imagePlaceholder;void 0===t.cacheBust?_l.impl.options.cacheBust=ml.cacheBust:_l.impl.options.cacheBust=t.cacheBust}(e=e||{}),Promise.resolve(t).then(function(t){return vl(t,e.filter,!0)}).then(function(t){return function(t){return gl.inlineAll(t).then(function(){return t})}(t)}).then(function(t){const{bgcolor:n,width:r,height:i,style:s,sx:o=1,sy:a=1}=e||{},c=t.style;n&&(c.backgroundColor=n);r&&(c.width=r+"px");i&&(c.height=i+"px");c["margin-left"]="0px",c["margin-top"]="0px",c.transform=`rotate(0rad) translate(0px, 0px) scale(${o}, ${a}) perspective(1px)`,s&&Object.keys(s).forEach(function(t){c[t]=s[t]});return t}).then(function(n){return function(t,e,n){return Promise.resolve(t).then(function(t){return t.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),(new XMLSerializer).serializeToString(t)}).then(ul.escapeXhtml).then(function(t){return'<foreignObject x="0" y="0" width="100%" height="100%">'+t+"</foreignObject>"}).then(function(t){return'<svg xmlns="http://www.w3.org/2000/svg" width="'+e+'" height="'+n+'">'+t+"</svg>"}).then(function(t){return"data:image/svg+xml;charset=utf-8,"+t})}(n,e.width||ul.width(t),e.height||ul.height(t))})}function bl(t,e){return yl(t,e).then(ul.makeImage).then(ul.delay(100)).then(function(n){const r=function(t){const n=document.createElement("canvas");if(n.width=e.width||ul.width(t),n.height=e.height||ul.height(t),e.bgcolor){const t=n.getContext("2d");t.fillStyle=e.bgcolor,t.fillRect(0,0,n.width,n.height)}return n}(t);return r.getContext("2d").drawImage(n,0,0),r})}function vl(t,e,n){return n||!e||e(t)?Promise.resolve(t).then(function(t){if(t instanceof HTMLCanvasElement)try{return ul.makeImage(t.toDataURL()).then(t=>t)}catch(t){Rr(t)}return t.cloneNode(!1)}).then(function(n){return function(t,e,n){const r=t.childNodes;return 0===r.length?Promise.resolve(e):i(e,ul.asArray(r),n).then(function(){return e});function i(t,e,n){let r=Promise.resolve();return e.forEach(function(e){r=r.then(function(){return vl(e,n,!1)}).then(function(e){e&&t.appendChild(e)})}),r}}(t,n,e)}).then(function(e){return function(t,e){return e instanceof Element?Promise.resolve().then(n).then(r).then(i).then(s).then(function(){return e}):e;function n(){function n(t,e){function n(t,e){ul.asArray(t).forEach(function(n){e.setProperty(n,t.getPropertyValue(n),t.getPropertyPriority(n))})}t.cssText?e.cssText=t.cssText:n(t,e)}n(window.getComputedStyle(t),e.style)}function r(){function n(n){const r=window.getComputedStyle(t,n),i=r.getPropertyValue("content");if(""===i||"none"===i)return;const s=ul.uid(),o=e;o.className=o.className+" "+s;const a=document.createElement("style");function c(t,e,n){const r="."+t+":"+e,i=n.cssText?s(n):o(n);return document.createTextNode(r+"{"+i+"}");function s(t){const e=t.getPropertyValue("content");return t.cssText+" content: "+e+";"}function o(t){return ul.asArray(t).map(e).join("; ")+";";function e(e){return e+": "+t.getPropertyValue(e)+(t.getPropertyPriority(e)?" !important":"")}}}a.appendChild(c(s,n,r)),e.appendChild(a)}[":before",":after"].forEach(function(t){n(t)})}function i(){t instanceof HTMLTextAreaElement&&e instanceof HTMLTextAreaElement&&(e.textContent=t.value),t instanceof HTMLInputElement&&e instanceof HTMLInputElement&&e.setAttribute("value",t.value)}function s(){e instanceof SVGElement&&(e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e instanceof SVGRectElement&&["width","height"].forEach(function(t){const n=e.getAttribute(t);n&&e.style.setProperty(t,n)}))}}(t,e)}):Promise.resolve(void 0)}const _l={toSvg:yl,toPng:function(t,e){return bl(t,e||{}).then(function(t){return t.toDataURL()})},toJpeg:function(t,e){return bl(t,e=e||{}).then(function(t){return t.toDataURL("image/jpeg",e.quality||1)})},toBlob:function(t,e){return bl(t,e||{}).then(t=>ul.canvasToBlob(t))},toPixelData:function(t,e){return bl(t,e||{}).then(function(e){return e.getContext("2d").getImageData(0,0,ul.width(t),ul.height(t)).data})},impl:{fontFaces:fl,images:gl,util:ul,inliner:pl,options:{}}};function xl(t,e,n,r){const i=this.model_layer,s=i._overlay;return new Promise(function(o,a){if(i){const a=i.get("width"),c=i.get("height");n=n||a,r=r||c;const l=i.get("translate"),h=i.get("scale"),d=Math.min(n/a,r/c);n=a*d,r=c*d,i.set("translate",{x:0,y:0}),i.set("scale",{x:d/_i,y:d/_i});let u=Fa.createCanvas(n,r);const p=u.getContext("2d");if(i.draw(p),i.set("translate",l),i.set("scale",h),!s)return o(u.toDataURL(t,e)),void(u=null);_l.toPng(s,{sx:d,sy:d,width:n,height:r}).then(function(i){const s=new Image;s.onload=function(){p.drawImage(s,0,0,n,r),o(u.toDataURL(t,e)),u=null},s.src=i},function(n){jr(n),o(u.toDataURL(t,e)),u=null})}else a("No target model")})}function wl(){if(!this.hasSameParentForAllSelected)return;const t=this.selected.filter(t=>!!t.parent&&!t.stuck);if(t.length<2)return;const e=t[0].parent,n=[],r=t.sort((t,n)=>e.components.indexOf(t)-e.components.indexOf(n));r.forEach(t=>{n.push(t.bounds)});const i=Fa.union(n);let s=t[0].fromParent(i.left,i.top);s=t[0].toScene(s.x,s.y);const o=new Map,a=Qc({type:"group",left:s.x,top:s.y,width:i.width,height:i.height},e.app,t=>{const e=this.getNewRefid();return void 0!==t&&o.set(t,e),e});a.replaceRefids(o);const c=[{component:a,to_container:e}];r.forEach(t=>{c.push({component:t,to_container:a})}),this.app.commander.execute(new Xc({changes:c})),this.selected=[a]}function Ml(){if(0===this.selected.length)return;const t=[],e=[];this.selected.forEach(n=>{if(!n.isGroup())return;const r=n.parent;n.components.forEach(n=>{t.push(n),e.push({component:n,to_container:r})}),e.push({component:n,to_container:null})}),this.app.commander.execute(new Xc({changes:e})),this.selected=t}function Sl(){const t=this.selected;if(0===t.length)return;const e=t.map(t=>t.bounds),n=Fa.union(e),r=n.left+n.width/2;t.map(t=>{t.symmetryX(r)})}function Al(){const t=this.selected;if(0===t.length)return;const e=t.map(t=>t.bounds),n=Fa.union(e),r=n.top+n.height/2;t.map(t=>{t.symmetryY(r)})}function El(){zc.around(this.app.commander,Sl,this)}function kl(){zc.around(this.app.commander,Al,this)}function Cl(t,e,n){const r=this.findAll(t,n);return r.forEach(t=>{t.set(e)}),r}function Pl(t){zc.around(this.app.commander,t)}function Tl(){return Object.values(this.indexMap).map(t=>t.map(t=>{const{id:e,data:n}=t.model;return{key:e,value:n}})).flat().sort((t,e)=>t.key>e.key?1:-1)}const Dl="left",Ol="right",zl="center",Il="bottom",Ll="middle",jl=[Dl,Ol,zl,"top",Ll,Il];function Rl(t){if(!this.hasSameParentForAllSelected||-1===jl.indexOf(t))return;const e=this.selected.filter(t=>!t.stuck);if(0===e.length)return;const n=this.app.commander;zc.around(n,function(){!function(t,e){const n=e[0].parent,{width:r,height:i}=n.bounds;switch(t){case Dl:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,left:0}}break;case zl:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,left:r/2-n.width/2}}break;case Ol:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,left:r-n.width}}break;case"top":for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,top:0}}break;case Ll:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,top:i/2-n.height/2}}break;case Il:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,top:i-n.height}}break;default:;}}(t,e)})}function Fl(t){t instanceof Array||(t=[t]),this.trigger("addstart",t)}function Bl(){this.trigger("stylepastestart")}function Nl(){this.trigger("stylepastestop")}function Hl(){this.trigger("databindpastestart")}function Vl(){this.trigger("databindpastestop")}let Gl=0,Yl=0,Ul=0,$l=null;function Wl(){Ul++;const t=performance.now(),e=t-Yl;e>=1e3&&(Gl=Math.round(1e3*Ul/e),Yl=t,Ul=0),$l=requestAnimationFrame(Wl)}function Xl(){null!==$l&&(cancelAnimationFrame($l),$l=null)}function ql(){return null===$l&&(Yl=performance.now(),Ul=0,$l=requestAnimationFrame(Wl)),Gl}const Kl=function(){const t=document.createElement("canvas").getContext("2d");return(window.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)}();function Ql(t,e){const n=document.createElement("canvas");return n.width=t,n.height=e,n.style.width=t+"px",n.style.height=e+"px",n}const Zl=Math.sqrt(3);function Jl(t,e){const n=1.2*e;switch(t){case"size1":return{X:n,Y:n};case"size2":return{X:1.5*n,Y:n};case"size3":return{X:2*n,Y:n};case"size4":return{X:n,Y:1.5*n};case"size5":default:return{X:1.5*n,Y:1.5*n};case"size6":return{X:2*n,Y:1.5*n};case"size7":return{X:n,Y:2*n};case"size8":return{X:1.5*n,Y:2*n};case"size9":return{X:2*n,Y:2*n}}}function th(t,e,n){switch(t){case"none":default:return null;case"arrow":{const t=Zl*e.X,n=e.Y,r=new _.ConeGeometry(n,t,16);return r.rotateZ(-Math.PI/2),r.translate(-t/2,0,0),{mesh:new _.Mesh(r,new _.MeshBasicMaterial)}}case"sharp-arrow":{const t=Zl*e.X*1.3,n=.65*e.Y,r=new _.ConeGeometry(n,t,16);return r.rotateZ(-Math.PI/2),r.translate(-t/2,0,0),{mesh:new _.Mesh(r,new _.MeshBasicMaterial)}}case"open-arrow":{const t=Zl*e.X,n=e.Y,r=new _.ConeGeometry(n,t,6);return r.rotateZ(-Math.PI/2),r.translate(-t/2,0,0),{mesh:new _.Mesh(r,new _.MeshBasicMaterial({wireframe:!0}))}}case"diamond":{const t=new _.OctahedronGeometry(1);return t.scale(e.X,e.Y,e.Y),{mesh:new _.Mesh(t,new _.MeshBasicMaterial)}}case"oval":{const t=new _.SphereGeometry(1,16,12);return t.scale(e.X,e.Y,e.Y),{mesh:new _.Mesh(t,new _.MeshBasicMaterial)}}case"cross":{const t=Math.max(e.X,e.Y),n=.9*t,r=.25*t,i=.15*t,s=new _.Group,o=[new _.Vector3(1,1,1).normalize(),new _.Vector3(1,-1,-1).normalize(),new _.Vector3(-1,1,-1).normalize(),new _.Vector3(-1,-1,1).normalize()];for(const t of o){const e=new _.CylinderGeometry(r,i,n,6),o=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,1,0),t);e.applyQuaternion(o),e.translate(t.x*n/2,t.y*n/2,t.z*n/2),s.add(new _.Mesh(e,new _.MeshBasicMaterial))}return{group:s}}}}function eh(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function nh(t,e,n,o){const{strokeStyle:a,alpha:c=1,lineWidth:l=2,begin:h="none",beginSize:d="size2",end:u="arrow",endSize:p="size2",label:f}=n,g=(new _.Vector3).subVectors(e,t),m=g.length(),y=new _.Group;if(m<.01)return y;const b=g.clone().normalize(),v=eh(h,l),x=eh(u,l),w=t.clone().add(b.clone().multiplyScalar(v)),M=e.clone().sub(b.clone().multiplyScalar(x));let S;if(Array.isArray(a)&&a.length>=2){const t=a[1];S=new _.Color(t.length>7?t.slice(0,7):t)}else S=new _.Color("string"==typeof a?a:"#00B050");const A=function(t,e,n,o){const{strokeStyle:a,alpha:c=1,lineWidth:l=2,lineDash:h="solid"}=n,d=new s.LineGeometry;let u;d.setPositions([t.x,t.y,t.z,e.x,e.y,e.z]);let p=!1;if(Array.isArray(a)&&a.length>=2){const t=new _.Color(a[0].length>7?a[0].slice(0,7):a[0]),e=new _.Color(a[1].length>7?a[1].slice(0,7):a[1]);d.setColors([t.r,t.g,t.b,e.r,e.g,e.b]),p=!0,u=e}else u=new _.Color("string"==typeof a?a:"#00B050");const{dashed:f,dashSize:g,gapSize:m}=function(t,e){switch(t){case"solid":default:return{dashed:!1,dashSize:1,gapSize:0};case"round-dot":return{dashed:!0,dashSize:e,gapSize:2*e};case"square-dot":return{dashed:!0,dashSize:2*e,gapSize:e};case"dash":return{dashed:!0,dashSize:4*e,gapSize:1.5*e};case"dash-dot":return{dashed:!0,dashSize:2.5*e,gapSize:1.5*e};case"long-dash":return{dashed:!0,dashSize:6*e,gapSize:3*e};case"long-dash-dot":return{dashed:!0,dashSize:3.5*e,gapSize:2*e};case"long-dash-dot-dot":return{dashed:!0,dashSize:3*e,gapSize:1.5*e}}}(h,l),y=new i.LineMaterial({color:p?16777215:u.getHex(),linewidth:l,worldUnits:!0,vertexColors:p,dashed:f,dashSize:g,gapSize:m,transparent:c<1||Array.isArray(a)&&a.some(t=>t.length>7),opacity:c,resolution:o}),b=new r.Line2(d,y);return b.computeLineDistances(),b}(w,M,n,o);y.add(A);const E=(new _.Quaternion).setFromUnitVectors(new _.Vector3(1,0,0),b),k=(new _.Quaternion).setFromUnitVectors(new _.Vector3(1,0,0),b.clone().negate()),C=(t,e,n)=>{if(!t)return;const r=t.mesh||t.line2||t.group;if(r){if(r.position.copy(e),r.setRotationFromQuaternion(n),t.mesh){const e=t.mesh.material;e.color.copy(S),e.transparent=c<1,e.opacity=c}else if(t.line2){const e=t.line2.material;e.color.copy(S),e.transparent=c<1,e.opacity=c,e.resolution.copy(o)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color.copy(S),e.transparent=c<1,e.opacity=c,e.resolution&&e.resolution.copy(o)}});y.add(r)}};C(th(u,Jl(p,l)),e,E);if(C(th(h,Jl(d,l)),t,k),f){const n=(new _.Vector3).addVectors(t,e).multiplyScalar(.5);n.y+=3;const r=function(t,e,n){const r="Arial",i=Ql(256,64),s=i.getContext("2d");s.font=`bold 28px ${r}`;const o=s.measureText(t).width;s.fillStyle=e,s.fillRect(0,0,o+12,40),s.fillStyle="white",s.font=`bold 28px ${r}`,s.textBaseline="top",s.fillText(t,6,6);const a=new _.CanvasTexture(i);a.needsUpdate=!0,a.minFilter=_.LinearFilter,a.colorSpace=_.SRGBColorSpace;const c=new _.SpriteMaterial({map:a,transparent:!0}),l=new _.Sprite(c);l.position.copy(n);const h=(o+12)/40;return l.scale.set(4*h,4,1),l}(f,"string"==typeof a?a:Array.isArray(a)&&a[1]||"#00B050",n);y.add(r)}return y}const rh=.001;function ih(t,e,n){let r=1;if(n&&"none"!=n&&"transparent"!=n){r=e*("string"==typeof n?a(n).getAlpha():1)}else r=0;t.opacity=r,t.transparent=r<1}function sh(t){const e=a(t);return e.isValid()?e.toHexString():t}const oh={width:1,height:1,depth:1},ah={x:1,y:1,z:1},ch={x:0,y:0,z:0},lh={x:0,y:0,z:0},hh={default:{metalness:0,roughness:.4},metal:{metalness:1,roughness:.3,envMapIntensity:1},glass:{metalness:0,roughness:.1,opacity:.3,envMapIntensity:1.5},plastic:{metalness:0,roughness:.4},wood:{metalness:0,roughness:.8,envMapIntensity:.3},ceramic:{metalness:.1,roughness:.2,envMapIntensity:.3},rubber:{metalness:0,roughness:.9,envMapIntensity:.3}};function dh(t){if(!t)return{metalness:0,roughness:.4,emissive:"#000000",emissiveIntensity:0,opacity:1,envMapIntensity:.5,side:"double",castShadow:!0,receiveShadow:!1};const e=hh[t.preset??"default"]??hh.default;return{metalness:t.metalness??e.metalness,roughness:t.roughness??e.roughness,emissive:t.emissive??"#000000",emissiveIntensity:t.emissiveIntensity??0,opacity:t.opacity??e.opacity??1,envMapIntensity:t.envMapIntensity??e.envMapIntensity??.5,side:t.side??"double",castShadow:t.castShadow??!0,receiveShadow:t.receiveShadow??!1}}const uh={double:_.DoubleSide,front:_.FrontSide,back:_.BackSide};function ph(t){return uh[t]??_.DoubleSide}function fh(t,e){t.metalness=e.metalness,t.roughness=e.roughness,t.emissive.set(e.emissive),t.emissiveIntensity=e.emissiveIntensity,t.opacity=e.opacity,t.transparent=e.opacity<1,t.envMapIntensity=e.envMapIntensity,t.side=ph(e.side)}const gh=["map","normalMap","roughnessMap","metalnessMap","aoMap","emissiveMap","bumpMap","displacementMap","alphaMap","envMap","lightMap"];function mh(t){for(const e of gh){const n=t[e];n?.dispose()}t.dispose()}function yh(t){t.traverse(t=>{if(t.geometry?.dispose(),t.material){const e=Array.isArray(t.material)?t.material:[t.material];for(const t of e)mh(t)}})}function bh(t,e,n){const r=document.createElement("canvas");r.width=e,r.height=n;const i=r.getContext("2d");if(!i)return null;let s;if("radial"===t.gradientType){const r=e/2,o=n/2,a=Math.max(e,n)/2;switch(t.center){case"left-top":s=i.createRadialGradient(0,0,0,0,0,2*a);break;case"right-top":s=i.createRadialGradient(e,0,0,e,0,2*a);break;case"left-bottom":s=i.createRadialGradient(0,n,0,0,n,2*a);break;case"right-bottom":s=i.createRadialGradient(e,n,0,e,n,2*a);break;default:s=i.createRadialGradient(r,o,0,r,o,a)}}else{const r=t.rotation??0,o=e/2,a=n/2,c=Math.cos(r)*o,l=Math.sin(r)*a;s=i.createLinearGradient(o-c,a-l,o+c,a+l)}for(const e of t.colorStops)if(e.position>=0&&e.position<=1)try{s.addColorStop(e.position,e.color)}catch{s.addColorStop(e.position,"#fff")}return i.fillStyle=s,i.fillRect(0,0,e,n),r}function vh(t){const{fillStyle:e}=t.state;if("object"==typeof e)return"pattern"===e.type&&e.image?function(t,e){const{width:n,height:r}=t.state,i=Math.abs(n)||1,s=Math.abs(r)||1,o=new _.Texture;o.colorSpace=_.SRGBColorSpace;const a=new Image;return"data"!==String(e.image).substring(0,4)&&(a.crossOrigin="anonymous"),a.onload=()=>{const n=2*i,r=2*s,c=document.createElement("canvas");c.width=n,c.height=r;const l=c.getContext("2d");if(l){if(e.color&&(l.fillStyle=e.color,l.fillRect(0,0,n,r)),e.fitPattern)l.drawImage(a,0,0,n,r);else{const t=2*(e.width||a.naturalWidth),i=2*(e.height||a.naturalHeight),s=2*(e.offsetX||0),o=2*(e.offsetY||0);let c=0,h=0;switch(e.align){case"center":c=(n-t)/2,h=(r-i)/2;break;case"left-top":break;case"left-bottom":h=r-i;break;case"right-top":c=n-t;break;case"right-bottom":c=n-t,h=r-i;break;case"left":h=(r-i)/2;break;case"right":c=n-t,h=(r-i)/2;break;case"top":c=(n-t)/2;break;case"bottom":c=(n-t)/2,h=r-i}const d=s+c,u=o+h;if(e.noRepeat)l.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,d,u,t,i);else{l.save(),l.rect(0,0,n,r),l.clip();const e=d>0?d-Math.ceil(d/t)*t:d;for(let s=u>0?u-Math.ceil(u/i)*i:u;s<r;s+=i)for(let r=e;r<n;r+=t)l.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,r,s,t,i);l.restore()}}o.image=c,o.minFilter=_.LinearFilter,o.needsUpdate=!0,t.invalidate()}},a.onerror=t=>{jr("Pattern texture load error:",t)},a.src=t.app.url(e.image),o}(t,e):"gradient"===e.type&&e.colorStops?.length?function(t){const e=bh(t,256,256);if(!e)return;const n=new _.CanvasTexture(e);return n.colorSpace=_.SRGBColorSpace,n.needsUpdate=!0,n}(e):void 0}function _h(t,e){return-1!==t.findIndex(t=>t in e)}class xh{static buildFillStyleTexture(t){return vh(t)}constructor(t){this._focused=!1,this._suppressOnchange=!1,this._onchangeWrapper=(t,e)=>{this._suppressOnchange||this.onchange(t,e)},this._component=t,this.object3d=this.getObject3dInstance(),this.component.on("change",this._onchangeWrapper)}update(){this.clear(),this.build(),this.updateTransform(),this.updateFillStyle(),this.updateStrokeStyle(),this.updateAlpha(),this.updateHidden(),this.updateText()}getObject3dInstance(){return new _.Object3D}build(){this.object3d.userData.context=this;const t=dh(this.component.state.material3d);this._applyShadow(t.castShadow,t.receiveShadow),this.object3d.name=this.component.state.id}updateMaterial3d(){const t=dh(this.component.state.material3d);this._applyShadow(t.castShadow,t.receiveShadow)}_applyShadow(t,e){this.object3d.castShadow=t,this.object3d.receiveShadow=e,this.object3d.traverse(n=>{n!==this.object3d&&(n.castShadow=t,n.receiveShadow=e)})}get gizmoTransformable(){return!0}get component(){return this._component}get threeContainer(){let t=this.component;for(;t;){if("is3dContainer"in t&&t.is3dContainer())return t;t=t.parent}}get focused(){return this._focused}set focused(t){this._focused=t,t&&(this._focusedAt=performance.now())}dispose(){this.component.off("change",this._onchangeWrapper),this.clear()}clear(){for(const t of this.object3d.children)yh(t);return this.object3d.userData={},this.object3d.clear()}updateTransform(){if(this.component.state.screenFixed&&this.component.isHTMLElement()){const{x:t=0,y:e=0}=this.component.center,{width:n=0,height:r=0}=this.component.parent?.bounds??{};return this.object3d.position.set(t-n/2,-(e-r/2),0),void this.object3d.rotation.set(0,0,0)}const{x:t,y:e,z:n}=this.position,{x:r,y:i,z:s}=this.rotation,{x:o,y:a,z:c}=this.scale;this.object3d.position.set(t,e,n),this.object3d.rotation.set(r,i,s),this.object3d.scale.set(Math.max(o,rh),Math.max(a,rh),Math.max(c,rh))}get position(){const{x:t,y:e,z:n}=this.center;return{x:t,y:n,z:e}}get rotation(){const{rotationX:t=0,rotationY:e=0,rotation:n=0}=this.component.state;return{x:t,y:-n,z:e}}get scale(){const{scale:t}=this.component.state,e="number"==typeof t?t:t?.x??1;return{x:e,y:e,z:e}}get cx(){const{x:t=0}=this.component.center,{width:e=0}=this.component.parent?.bounds??{},{tx:n=0}=this.component.delta();return t+n-e/2}get cy(){const{y:t=0}=this.component.center,{height:e=0}=this.component.parent?.bounds??{},{ty:n=0}=this.component.delta();return t+n-e/2}get cz(){const{zPos:t=0}=this.component.state,{tz:e=0}=this.component.delta();return t+e+this.syncZPosOffset}get center(){const{x:t=0,y:e=0}=this.component.center,{width:n=0,height:r=0}=this.component.parent?.bounds??{},{tx:i=0,ty:s=0}=this.component.delta();return{x:t+i-n/2,y:e+s-r/2,z:this.cz}}get dimension(){const{width:t,height:e}=this.component.bounds;return{width:Math.abs(t)||1,height:Math.abs(e)||1,depth:this.effectiveDepth}}get effectiveDepth(){return this.component.state.depth||1}updatePosition(){const{x:t=0,y:e=0,z:n=0}=this.position;this.object3d.position.set(t,e,n)}updateRotate(){const{x:t=0,y:e=0,z:n=0}=this.rotation;this.object3d.rotation.set(t,e,n)}updateScale(){const{x:t=1,y:e=1,z:n=1}=this.scale;this.object3d.scale.set(Math.max(t,rh),Math.max(e,rh),Math.max(n,rh))}syncAnimationDelta(){const t=this.component.delta();this.updatePosition();const{rotationX:e=0,rotationY:n=0,rotation:r=0}=this.component.state,i=t.theta||0;this.object3d.rotation.set(e,-(r+i),n);const{scale:s}=this.component.state,o="number"==typeof s?s:s?.x??1,a=t.sx??1,c=t.sy??1;this.object3d.scale.set(Math.max(o*a,rh),Math.max(o*c,rh),Math.max(o,rh));const l=t.fade||0;if(0!==l){const t=(this.component.state.alpha??1)*(1-l);this.object3d.traverse(e=>{if(e.isMesh&&e.material){const n=Array.isArray(e.material)?e.material:[e.material];for(const e of n)e.opacity=t,e.transparent=e.opacity<1}})}}updateDimension(){this.clear(),this.build()}updateAlpha(){let{alpha:t}=this.component.state;t=null==t?1:t,this.object3d.traverse(e=>{let n=e.material;e.material&&(Array.isArray(n)||(n=[n]),n.forEach(e=>{e.opacity*=t,e.transparent=t<1}))})}updateHidden(){this.object3d.visible=!this.component.state.hidden}updateStrokeStyle(){}updateFillStyle(){}updateText(){}get syncZPosOffset(){return this.effectiveDepth/2}get textSurfaceYOffset(){return this.effectiveDepth-this.syncZPosOffset}syncFromObject3D(){const t=this.object3d,e=this._component,{width:n=0,height:r=0}=e.parent?.bounds??{},i=e.bounds,{tx:s=0,ty:o=0,tz:a=0}=e.delta();this._suppressOnchange=!0,e.bounds={left:t.position.x-s+n/2-i.width/2,top:t.position.z-o+r/2-i.height/2,width:i.width,height:i.height},e.set({zPos:t.position.y-a-this.syncZPosOffset,rotationX:t.rotation.x,rotation:-t.rotation.y,rotationY:t.rotation.z}),this._suppressOnchange=!1}onGizmoDragEnd(t){}applyDimensionFromGizmo(t){this._suppressOnchange=!0,this._component.set(t),this._suppressOnchange=!1}onchange(t,e){"screenFixed"in t&&this.updateTransform(),_h(["cx","cy","cz","zPos","left","top"],t)&&this.updatePosition(),_h(["width","height","depth","lineWidth"],t)&&this.updateDimension(),_h(["rotationX","rotationY","rotation"],t)&&this.updateRotate(),"scale"in t&&this.updateScale(),"hidden"in t&&this.updateHidden(),"alpha"in t&&this.updateAlpha(),"strokeStyle"in t&&this.updateStrokeStyle(),"fillStyle"in t&&this.updateFillStyle(),_h(["text","fontColor","fontSize","fontFamily","bold","italic","textAlign","textBaseline"],t)&&this.updateText(),"material3d"in t&&this.updateMaterial3d()}}class wh extends xh{get syncZPosOffset(){return this.effectiveDepth}getObject3dInstance(){return new o.CSS3DObject(this.component.element)}get rotation(){const{rotationX:t=0,rotationY:e=0,rotation:n=0}=this.component.state;return{x:t-Math.PI/2,y:e,z:-n}}syncFromObject3D(){const t=this.object3d,e=this._component,{width:n=0,height:r=0}=e.parent?.bounds??{},i=e.bounds,{tx:s=0,ty:o=0,tz:a=0}=e.delta();this._suppressOnchange=!0;const c=t.scale.x;e.bounds={left:t.position.x-s+n/2-i.width/2,top:t.position.z-o+r/2-i.height/2,width:i.width,height:i.height},e.set({zPos:t.position.y-a-this.syncZPosOffset,rotationX:t.rotation.x+Math.PI/2,rotation:-t.rotation.z,rotationY:t.rotation.y,scale:{x:c,y:c}}),this._suppressOnchange=!1}build(){super.build();const t=this.component.element;if(!t)return;const{width:e,height:n}=this.component.bounds;t.style.width=e+"px",t.style.height=n+"px",t.style.left="",t.style.top=""}updateDimension(){super.updateDimension();const t=this.dimension,e=this.component.element;e&&(e.style.width=t.width+"px",e.style.height=t.height+"px")}updateAlpha(){super.updateAlpha();const{alpha:t=1}=this.component.state,e=this.component.element;e&&(e.style.opacity=String(t))}}const Mh=new Map;let Sh;function Ah(t,e){Mh.set(t,e)}function Eh(t){Sh=t}function kh(t){const e=t.buildRealObject();if(e)return e;const n=t.model?.type,r=n?Mh.get(n):void 0;if(r)return r(t);if(t.isHTMLElement()){const e=Mh.get("html-overlay-element");if(e)return e(t)}return Sh?.(t)}function Ch(t,e,n){if(!t.hasTextProperty||t.textHidden)return;const r=t._realObject;if(!r?.object3d)return;const{text:i="",bold:s=Mi.BOLD,italic:a=Mi.ITALIC,fontFamily:c=Mi.FONT_FAMILY,fontColor:l=Mi.FONT_COLOR,fontSize:h=Mi.FONT_SIZE,textAlign:d=Mi.TEXT_ALIGN,textBaseline:u=Mi.TEXT_BASELINE,width:p,height:f}=t.model,g=Math.abs(p)||1,m=Math.abs(f)||1,y=document.createElement("textarea"),b=new AbortController;xi.forEach(t=>{y.addEventListener(t,t=>t.stopPropagation(),{capture:!0,signal:b.signal})}),y.value=i;const v="right"===d||"end"===d?"right":"left"===d||"start"===d?"left":"justify"===d?"justify":"center";let x="0";if("bottom"===u||"alphabetic"===u){const t=1.2*h*Math.max(1,(i.match(/\n/g)||[]).length+1);x=Math.max(0,m-t)+"px"}else if("middle"===u){const t=1.2*h*Math.max(1,(i.match(/\n/g)||[]).length+1);x=Math.max(0,(m-t)/2)+"px"}y.style.cssText=[`width: ${g}px`,`height: ${m}px`,`padding: ${x} 0 0 0`,"margin: 0",`font-family: ${c}`,`font-size: ${h}px`,`line-height: ${1.2*h}px`,"overflow: hidden","resize: none","outline: 1px solid #f26522","border: 0","background-color: rgba(255, 255, 255, 0.85)","display: block",`color: ${l}`,"box-sizing: border-box","font-weight: "+(s?"bold":"normal"),"font-style: "+(a?"italic":"normal"),`text-align: ${v}`].join("; ");const w=new o.CSS3DObject(y),M=r.object3d;M.updateWorldMatrix(!0,!1);const S=new _.Vector3,A=new _.Quaternion,E=new _.Vector3;M.matrixWorld.decompose(S,A,E);const k=new _.Vector3(0,r.textSurfaceYOffset,0);k.multiply(E),k.applyQuaternion(A),w.position.copy(S).add(k);const C=(new _.Quaternion).setFromAxisAngle(new _.Vector3(1,0,0),-Math.PI/2);w.quaternion.copy(A).multiply(C),w.scale.copy(E),e.css3DScene.add(w),n();const P=e.css3DRenderer.domElement,T=P.style.getPropertyValue("pointer-events"),D=P.style.getPropertyPriority("pointer-events"),O=[];let z=y;for(;z&&z!==P.parentElement;)O.push({el:z,saved:z.style.pointerEvents}),z.style.setProperty("pointer-events","auto","important"),z=z.parentElement;y.focus(),y.select();let I=!1;const L=t.root?.selected;y.addEventListener("keydown",t=>{t.stopPropagation(),"Escape"!==t.code&&(t.shiftKey||"Enter"!==t.code&&"NumpadEnter"!==t.code)||(I="Escape"===t.code,y.blur())},{signal:b.signal});const j=()=>{e.css3DScene.remove(w);for(const{el:t,saved:e}of O)e?t.style.pointerEvents=e:t.style.removeProperty("pointer-events");D?P.style.setProperty("pointer-events",T,D):T&&P.style.setProperty("pointer-events",T),b.abort(),y.removeEventListener("blur",j),L&&t.root&&(t.root.selected=L),I||y.value===i||t.app.commander.execute(new zc({changes:[{component:t,before:{text:i},after:{text:y.value}}]})),n()};y.addEventListener("blur",j)}class Ph extends n.Scene{dispose(){const t=new Set;this.traverse(e=>{if(e.isMesh){t.add(e.geometry);const n=e.material;Array.isArray(n)?n.forEach(e=>t.add(e)):t.add(n)}});for(const e of t)e.dispose()}}function Th(t,e){t.metalness=e.metalness,t.roughness=e.roughness,t.opacity=e.opacity,t.transparent=e.opacity<1,t.envMapIntensity=e.envMapIntensity}function Dh(t){const{fillStyle:e,floorMaterial3d:n}=t.state,r=dh(n);if("none"===e)return;const i=new _.BoxGeometry(1,1,1);let s;if(e){const n=xh.buildFillStyleTexture(t);if(n){const t="#424b57",e=[new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({map:n}),new _.MeshStandardMaterial({color:t})];e.forEach(t=>Th(t,r)),s=e}else if("string"==typeof e){const t=new _.MeshStandardMaterial({color:e});Th(t,r),s=t}}if(!s){const t=new _.MeshStandardMaterial({color:"#e0e0e0"});Th(t,r),s=t}const o=new _.Mesh(i,s),{width:a,height:c}=t.state;return o.scale.set(a,c,5),o.rotation.x=-Math.PI/2,o.position.y=-3.5,o.name="floor",o.receiveShadow=!1!==n?.receiveShadow,o.castShadow=!0===n?.castShadow,o}const Oh={studio:class extends Ph{constructor(){super(),this.name="StudioEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:13421772}),r=new n.Mesh(t,e);r.position.set(0,13,0),r.scale.set(40,30,35),this.add(r);const i=new n.MeshStandardMaterial({color:11184810,roughness:.8}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(40,.5,35),this.add(s);const o=new n.PointLight(16777215,500,40,2);o.position.set(0,24,0),this.add(o);const a=new n.PointLight(16777215,200,30,2);a.position.set(-10,22,-8),this.add(a);const c=new n.PointLight(16777215,200,30,2);c.position.set(10,22,8),this.add(c);const l=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:16777215,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,26,r),o.scale.set(6,.1,6),o};this.add(l(-8,-6,60)),this.add(l(8,-6,60)),this.add(l(-8,6,60)),this.add(l(8,6,60)),this.add(l(0,0,50))}},warehouse:class extends Ph{constructor(){super(),this.name="WarehouseEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:8425632}),r=new n.Mesh(t,e);r.position.set(0,18,0),r.scale.set(50,40,40),this.add(r);const i=new n.MeshStandardMaterial({color:9474192,roughness:.9}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(50,.5,40),this.add(s);const o=new n.PointLight(15266047,600,50,2);o.position.set(-10,30,0),this.add(o);const a=new n.PointLight(15266047,600,50,2);a.position.set(10,30,0),this.add(a);const c=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:15266047,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,35,r),o.scale.set(8,.1,2),o};this.add(c(-12,-6,80)),this.add(c(-12,6,80)),this.add(c(0,0,60)),this.add(c(12,-6,80)),this.add(c(12,6,80));const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:16772829,emissiveIntensity:15}));l.position.set(0,10,-19),l.scale.set(12,8,.1),this.add(l)}},factory:class extends Ph{constructor(){super(),this.name="FactoryEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:6318192,metalness:.1,roughness:.8}),r=new n.Mesh(t,e);r.position.set(0,20,0),r.scale.set(60,44,45),this.add(r);const i=new n.MeshStandardMaterial({color:8028272,roughness:.7,metalness:.05}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(60,.5,45),this.add(s);const o=(t,e)=>{const r=new n.PointLight(15791615,800,55,2);return r.position.set(t,35,e),r};this.add(o(-15,-10)),this.add(o(-15,10)),this.add(o(0,0)),this.add(o(15,-10)),this.add(o(15,10));const a=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:15791615,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,38,r),o.scale.set(6,.1,3),o};this.add(a(-18,-10,90)),this.add(a(-18,10,90)),this.add(a(0,-10,70)),this.add(a(0,10,70)),this.add(a(18,-10,90)),this.add(a(18,10,90));const c=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:11206570,emissiveIntensity:10}));c.position.set(28,14,-21),c.scale.set(1,2,.1),this.add(c);const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:16772829,emissiveIntensity:25}));l.position.set(0,8,-22),l.scale.set(10,10,.1),this.add(l)}},office:class extends Ph{constructor(){super(),this.name="OfficeEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:14209224}),r=new n.Mesh(t,e);r.position.set(0,10,0),r.scale.set(35,22,30),this.add(r);const i=new n.MeshStandardMaterial({color:10524808,roughness:.85}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(35,.5,30),this.add(s);const o=new n.PointLight(16774374,400,30,2);o.position.set(0,17,0),this.add(o);const a=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:16775408,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,19.5,r),o.scale.set(4,.1,4),o};this.add(a(-8,-6,60)),this.add(a(-8,6,60)),this.add(a(8,-6,60)),this.add(a(8,6,60)),this.add(a(0,0,50));const c=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:30}));c.position.set(17,10,0),c.scale.set(.1,6,12),this.add(c);const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:20}));l.position.set(-17,10,0),l.scale.set(.1,4,8),this.add(l)}},home:class extends Ph{constructor(){super(),this.name="HomeEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:15261136}),r=new n.Mesh(t,e);r.position.set(0,8,0),r.scale.set(28,18,24),this.add(r);const i=new n.MeshStandardMaterial({color:11571312,roughness:.7}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(28,.5,24),this.add(s);const o=new n.PointLight(16770244,300,25,2);o.position.set(0,14,0),this.add(o);const a=new n.PointLight(16767152,100,20,2);a.position.set(-8,12,-6),this.add(a);const c=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:16771280,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,15.5,r),o.scale.set(3,.1,3),o};this.add(c(0,0,40)),this.add(c(-6,-4,25)),this.add(c(6,4,25));const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:35}));l.position.set(13.5,8,0),l.scale.set(.1,8,10),this.add(l);const h=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:15}));h.position.set(-13.5,9,3),h.scale.set(.1,5,6),this.add(h)}}};class zh{get scene(){return this._scene}get mixer(){return this._mixer}setup(){return this._scene=new _.Scene,this._scene}setupMixer(){return this._timer=new _.Timer,this._timer.connect(document),this._mixer=new _.AnimationMixer(this._scene),this._mixer}setupEnvironment(t){this._renderer=t,this._applyEnvironment("studio")}_applyEnvironment(t){this._envTexture&&this._envTexture.dispose();const e=new(0,Oh[t]),n=new _.PMREMGenerator(this._renderer);this._envTexture=n.fromScene(e).texture,this._scene.environment=this._envTexture,e.dispose(),n.dispose()}setSky(t,e){if(!this._scene||!this._renderer)return;const n=t;n&&n in Oh?(this._applyEnvironment(n),this._scene.background=this._envTexture):this._scene.background="color"===t&&e?new _.Color(e):null}addFloor(t){const e=Dh(t);e&&this._scene.add(e)}updateFloor(t){if(!this._scene)return;const e=this._scene.children.find(t=>"floor"===t.name);e&&(yh(e),this._scene.remove(e)),this.addFloor(t)}addObject(t){this._scene.add(t)}updateAnimation(){this._mixer&&this._timer&&(this._timer.update(),this._mixer.update(this._timer.getDelta()))}destroy(){this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this._scene)),this._envTexture&&(this._envTexture.dispose(),delete this._envTexture),this._scene&&(this._scene.environment=null,yh(this._scene),this._scene.clear()),delete this._scene,delete this._mixer,delete this._renderer,this._timer&&this._timer.disconnect(),delete this._timer}}class Ih{constructor(){this._activeView="perspective",this._cameraZPos=0}get camera(){return this._perspCamera}get activeCamera(){return"perspective"!==this._activeView&&this._orthoCamera?this._orthoCamera:this._perspCamera}get activeView(){return this._activeView}get cameraZPos(){return this._cameraZPos}setup(t,e,n){const{fov:r,near:i,far:s,cameraX:o,cameraY:a,cameraZ:c}=n,l=t/e;this._perspCamera=new _.PerspectiveCamera(r,l,i,s);let h=.4*e,d=.4*t;return this._cameraZPos=Math.min(250,Math.floor(.5*Math.min(t,e))),null!=o&&(h=o*t),null!=a&&(d=a*e),null!=c&&(this._cameraZPos=c*Math.floor(Math.min(t,e))),this._perspCamera.position.set(h,this._cameraZPos,d),this._activeView="perspective",this._perspCamera}addToScene(t){t.add(this._perspCamera),this._perspCamera.lookAt(t.position)}updateAspect(t,e){if(this._perspCamera&&(this._perspCamera.aspect=t/e,this._perspCamera.updateProjectionMatrix()),this._orthoCamera){const n=this._orthoCamera,r=(n.top-n.bottom)/2,i=t/e;n.left=-r*i,n.right=r*i,n.updateProjectionMatrix()}}updateProperties(t){this._perspCamera&&(void 0!==t.fov&&(this._perspCamera.fov=t.fov),void 0!==t.near&&(this._perspCamera.near=t.near),void 0!==t.far&&(this._perspCamera.far=t.far),this._perspCamera.updateProjectionMatrix())}setOrthoView(t,e,n,r,i){this._orthoCamera||(this._orthoCamera=new _.OrthographicCamera(-1,1,1,-1,.1,5e4)),this.updateOrthoFrustum(e,n,r,i);const s=this._orthoCamera;s.zoom=1;const o=2*Math.max(e,n);switch(t){case"top":s.position.set(0,o,0),s.up.set(0,0,-1);break;case"front":s.position.set(0,0,o),s.up.set(0,1,0);break;case"back":s.position.set(0,0,-o),s.up.set(0,1,0);break;case"right":s.position.set(o,0,0),s.up.set(0,1,0);break;case"left":s.position.set(-o,0,0),s.up.set(0,1,0)}return s.lookAt(0,0,0),s.updateProjectionMatrix(),this._activeView=t,s}restorePerspective(){return this._activeView="perspective",this._perspCamera}updateOrthoFrustum(t,e,n,r){if(!this._orthoCamera)return;const i=(n||t)/(r||e),s=Math.max(t,e)/2;i>=1?(this._orthoCamera.left=-s*i,this._orthoCamera.right=s*i,this._orthoCamera.top=s,this._orthoCamera.bottom=-s):(this._orthoCamera.left=-s,this._orthoCamera.right=s,this._orthoCamera.top=s/i,this._orthoCamera.bottom=-s/i),this._orthoCamera.updateProjectionMatrix()}destroy(){delete this._perspCamera,delete this._orthoCamera,this._activeView="perspective"}}class Lh{constructor(){this._noSupportWebgl=!1}get renderer(){return this._renderer}get css3DRenderer(){return this._css3DRenderer||(this._css3DRenderer=this.createCSS3DRenderer()),this._css3DRenderer}get css3DScene(){return this._css3DScene||(this._css3DScene=new _.Scene),this._css3DScene}get composer(){return this._composer}get noSupportWebgl(){return this._noSupportWebgl}get domElement(){return this._renderer?.domElement}get hudScene(){return this._hudScene||(this._hudScene=new _.Scene),this._hudScene}get hudCSS3DScene(){return this._hudCSS3DScene||(this._hudCSS3DScene=new _.Scene),this._hudCSS3DScene}get hudCamera(){return this._hudCamera}setupHUD(t,e){this._hudCamera=new _.OrthographicCamera(-t/2,t/2,e/2,-e/2,.1,1e4),this._hudCamera.position.set(0,5e3,0),this._hudCamera.lookAt(0,0,0),this._hudCSS3DCamera=new _.OrthographicCamera(-t/2,t/2,e/2,-e/2,.1,1e4),this._hudCSS3DCamera.position.set(0,0,1e3),this._hudCSS3DCamera.lookAt(0,0,0),this._hudCSS3DRenderer=new o.CSS3DRenderer,this._hudCSS3DRenderer.setSize(t,e);const n=this._hudCSS3DRenderer.domElement;n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.pointerEvents="none",n.style.zIndex="10";const r=new _.AmbientLight(16777215,3);this.hudScene.add(r);const i=new Float32Array(64).fill(1),s=new _.DataTexture(i,4,4,_.RGBAFormat,_.FloatType);s.mapping=_.EquirectangularReflectionMapping,s.needsUpdate=!0,this.hudScene.environment=s}resizeHUD(t,e){this._hudCamera&&(this._hudCamera.right=t,this._hudCamera.bottom=-e,this._hudCamera.updateProjectionMatrix())}setupWebGL(t,e,n){try{const r=document.createElement("canvas"),i=r.getContext("webgl2");if(!i)return this._noSupportWebgl=!0,!1;const s=new _.WebGLRenderer({canvas:r,context:i,precision:n.precision,alpha:!0,antialias:n.antialias,logarithmicDepthBuffer:!1!==n.postprocessing,premultipliedAlpha:!1});return s.autoClear=!0,s.outputColorSpace=_.SRGBColorSpace,s.toneMapping=_.NoToneMapping,s.toneMappingExposure=n.exposure,s.shadowMap.enabled=!0,s.shadowMap.type=_.PCFShadowMap,s.setClearColor(16777215,1),s.setPixelRatio(window.devicePixelRatio),s.setSize(t,e,!1),r.style.width="100%",r.style.height="100%",this._renderer=s,this._noSupportWebgl=!1,!0}catch(t){return this._noSupportWebgl=!0,!1}}setupCSS3D(t,e){const n=this.css3DRenderer.domElement;n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.pointerEvents="none",e&&n.setAttribute("scene",e),n.style.setProperty("pointer-events","none","important")}createCSS3DRenderer(){return new o.CSS3DRenderer}setupComposer(t,e,n,r,i){const s=new _.WebGLRenderTarget(n,r,{samples:4});this._composer=new c.EffectComposer(this._renderer,s),this._composer.setSize(n,r);const o=new l.RenderPass(t,e);this._composer.addPass(o);const a=new h.OutlinePass(new _.Vector2(n,r),t,e);if(a.visibleEdgeColor.set(15885602),a.hiddenEdgeColor.set(15885602),a.edgeStrength=3,a.edgeThickness=1.5,a.edgeGlow=.5,a.pulsePeriod=0,i){const t=a.render.bind(a);a.render=(e,n,r,s,o)=>{const a=i.visible;i.visible=!1,t(e,n,r,s,o),i.visible=a}}return this._outlinePass=a,this._composer.addPass(a),this._composer.addPass(new u.SMAAPass),this._composer.addPass(new d.OutputPass),this._composer}updateRenderPassCamera(t){this._composer&&this._composer.passes.length>0&&(this._composer.passes[0].camera=t),this._outlinePass&&(this._outlinePass.renderCamera=t),this._camera&&(this._camera=t)}setOutlineObjects(t){this._outlinePass&&(this._outlinePass.selectedObjects=t)}resize(t,e){if(this._renderer?.setSize(t,e,!1),this._css3DRenderer?.setSize(t,e),this._composer?.setSize(t,e),this._hudCSS3DRenderer&&this._hudCSS3DCamera){const n=t/(this._hudCSS3DCamera.right-this._hudCSS3DCamera.left),r=e/(this._hudCSS3DCamera.top-this._hudCSS3DCamera.bottom),i=this._hudCSS3DRenderer.domElement;i.style.transformOrigin="0 0",i.style.transform=`scale(${n}, ${r})`}}setDirectRenderTargets(t,e){this._scene=t,this._camera=e}render(){if(this._composer){if(this._composer.render(),this._renderer){const t=this._renderer.getContext();t.colorMask(!1,!1,!1,!0),t.clearColor(0,0,0,1),t.clear(t.COLOR_BUFFER_BIT),t.colorMask(!0,!0,!0,!0)}}else this._renderer&&this._scene&&this._camera&&this._renderer.render(this._scene,this._camera);this.renderHUD()}renderHUD(){if(!this._renderer||!this._hudScene||!this._hudCamera)return;if(0===this._hudScene.children.length)return;const t=this._renderer.autoClear;this._renderer.autoClear=!1,this._renderer.setRenderTarget(null),this._renderer.clearDepth(),this._renderer.render(this._hudScene,this._hudCamera),this._renderer.autoClear=t}renderCSS3D(t){if(this._css3DRenderer?.render(this.css3DScene,t),this._hudCSS3DRenderer&&this._hudCSS3DCamera&&this._hudCSS3DScene){const t=this._hudCSS3DRenderer.domElement;this._hudCSS3DScene.children.length>0?(t.style.display="",this._hudCSS3DRenderer.render(this._hudCSS3DScene,this._hudCSS3DCamera)):t.style.display="none"}}get hudCSS3DRenderer(){return this._hudCSS3DRenderer}getSize(){const t=new _.Vector2;return this._renderer?.getSize(t),{width:t.x,height:t.y}}destroy(){this._outlinePass=void 0,this._composer?.dispose(),this._renderer?.dispose(),delete this._composer,delete this._renderer,this.disposeHUD()}disposeHUD(){if(this._hudScene){[...this._hudScene.children].forEach(t=>{if(this._hudScene.remove(t),t.geometry&&t.geometry.dispose(),t.material){const e=t.material;e.map&&e.map.dispose(),e.dispose()}}),this._hudScene.environment&&(this._hudScene.environment.dispose(),this._hudScene.environment=null),this._hudScene=void 0}if(this._hudCamera=void 0,this._hudCSS3DScene){[...this._hudCSS3DScene.children].forEach(t=>this._hudCSS3DScene.remove(t)),this._hudCSS3DScene=void 0}this._hudCSS3DRenderer&&(this._hudCSS3DRenderer.domElement.remove(),this._hudCSS3DRenderer=void 0),this._hudCSS3DCamera=void 0}disposeCSS3DScene(){if(this._css3DScene){[...this._css3DScene.children].forEach(t=>this._css3DScene.remove(t))}}}class jh{constructor(){this.lights=[]}get hemiLight(){return this._hemiLight}get dirLight(){return this._dirLight}setup(t,e,n){this._scene=t,this._camera=e;const{hemisphere:r,directional:i,point:s}=n;if(this._hemiLight=new _.HemisphereLight(r.skyColor,r.groundColor,r.intensity),t.add(this._hemiLight),this.lights.push(this._hemiLight),i){if(this._dirLight=new _.DirectionalLight(i.color,i.intensity),i.position&&this._dirLight.position.set(...i.position),!1!==i.castShadow){this._dirLight.castShadow=!0;const t=i.shadowMapSize??2048;this._dirLight.shadow.mapSize.set(t,t),this._dirLight.shadow.bias=i.shadowBias??-5e-4;const e=this._dirLight.shadow.camera;e.near=.1,e.far=5e3,e.left=-1500,e.right=1500,e.top=1500,e.bottom=-1500}i.attachToCamera?e.add(this._dirLight):t.add(this._dirLight),this.lights.push(this._dirLight)}if(s){const e=new _.PointLight(s.color,s.intensity,void 0,s.decay);e.power=s.power,e.castShadow=s.castShadow,e.position.set(...s.position),e.shadow.camera.near=s.shadowNear,e.shadow.camera.far=s.shadowFar,t.add(e),this.lights.push(e)}}updateHemisphere(t){this._hemiLight&&(void 0!==t.skyColor&&this._hemiLight.color.set(t.skyColor),void 0!==t.groundColor&&this._hemiLight.groundColor.set(t.groundColor),void 0!==t.intensity&&(this._hemiLight.intensity=t.intensity))}updateDirectional(t){this._dirLight&&(void 0!==t.color&&this._dirLight.color.set(t.color),void 0!==t.intensity&&(this._dirLight.intensity=t.intensity))}setDirectionalEnabled(t,e){if(t&&!this._dirLight&&this._camera){const t=e?.color??16777215,n=e?.intensity??.8;this._dirLight=new _.DirectionalLight(t,n),this._camera.add(this._dirLight),this.lights.push(this._dirLight)}else!t&&this._dirLight&&(this._dirLight.removeFromParent(),this._dirLight.dispose(),this.lights=this.lights.filter(t=>t!==this._dirLight),this._dirLight=void 0)}destroy(){this.lights.forEach(t=>t.dispose()),this.lights=[],this._hemiLight=void 0,this._dirLight=void 0,this._scene=void 0,this._camera=void 0}}const Rh=1e-6;class Fh{constructor(){this._enabled=!0,this._state=0,this._autoRotate=!1,this._autoRotateSpeed=2,this._dampingFactor=.15,this._rotateSpeed=.1,this._panSpeed=1,this._lastScale=1,this._spherical=new _.Spherical,this._sphericalDelta=new _.Spherical,this._panOffset=new _.Vector3,this._target=new _.Vector3,this._target0=new _.Vector3,this._position0=new _.Vector3,this._rotateStart=new _.Vector2,this._rotateEnd=new _.Vector2,this._rotateDelta=new _.Vector2,this._panStart=new _.Vector2,this._panEnd=new _.Vector2,this._panDelta=new _.Vector2,this._offset=new _.Vector3,this._lastPosition=new _.Vector3,this._lastQuaternion=new _.Quaternion,this._panLeftV=new _.Vector3,this._panUpV=new _.Vector3,this._panCalcOffset=new _.Vector3}get isActive(){return!!this._camera}get target(){return this._target.clone()}restoreTarget(t){this._target.copy(t),this.update()}get _isOrthoLocked(){return!!this._camera?.isOrthographicCamera}setup(t,e){this._camera=t,this._host=e,this._target.set(0,0,0),this._target0.copy(this._target),this._position0.copy(t.position),this._quat=(new _.Quaternion).setFromUnitVectors(t.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert();const n=e.state;this._autoRotate=!e.app?.isEditMode&&(n.autoRotate||"orbit"===n.cameraAutoPlay)||!1,this._autoRotateSpeed=n.rotationSpeed||2,this.update()}setEnabled(t){this._enabled=t}setOnUserInteraction(t){this._onUserInteraction=t}onDragStart(t){this._enabled&&(this._onUserInteraction?.(),this._isOrthoLocked?(this._state=2,this._panStart.set(t.offsetX,t.offsetY)):(this._state=t.altKey?2:1,1===this._state?this._rotateStart.set(t.offsetX,t.offsetY):this._panStart.set(t.offsetX,t.offsetY)))}onDragMove(t){this._enabled&&(this._isOrthoLocked?(this._state=2,this._handlePanMove(t.offsetX,t.offsetY)):(this._state=t.altKey?2:1,1===this._state?this._handleRotateMove(t.offsetX,t.offsetY):this._handlePanMove(t.offsetX,t.offsetY)))}onDragEnd(t){this._state=0,this._host?.invalidate()}onTouchStart(t){this._onUserInteraction?.();const e=t.touches[0],n=e.offsetX??e.pageX,r=e.offsetY??e.pageY;if(this._isOrthoLocked)return this._panStart.set(n,r),void(this._state=4);switch(t.touches.length){case 1:this._rotateStart.set(n,r),this._state=3;break;case 2:this._lastScale=t.scale||1,this._panStart.set(n,r),this._state=4;break;default:this._state=0}}onTouchMove(t){const e=t.touches[0],n=e.offsetX??e.pageX,r=e.offsetY??e.pageY;if(this._isOrthoLocked)this._handlePanMove(n,r);else switch(t.touches.length){case 1:if(3!==this._state)return;this._handleRotateMove(n,r);break;case 2:if(Math.abs(this._lastScale-(t.scale||1))>.05)return;if(4!==this._state)return;this._handlePanMove(n,r);break;default:this._state=0}}onTouchEnd(t){this._lastScale=1,this._state=0}onKeyDown(t){switch(t.code){case"ArrowUp":this._pan(0,7);break;case"ArrowDown":this._pan(0,-7);break;case"ArrowLeft":this._pan(7,0);break;case"ArrowRight":this._pan(-7,0);break;default:return}this.update()}update(){const t=this._camera,e=t.position;if(this._isOrthoLocked)return this._panOffset.lengthSq()>0&&(this._target.add(this._panOffset),e.add(this._panOffset),this._panOffset.set(0,0,0)),(this._lastPosition.distanceToSquared(e)>Rh||8*(1-this._lastQuaternion.dot(t.quaternion))>Rh)&&(this._lastPosition.copy(e),this._lastQuaternion.copy(t.quaternion),this._host?.invalidate(),!0);if(this._offset.copy(e).sub(this._target),this._offset.applyQuaternion(this._quat),this._spherical.setFromVector3(this._offset),this._spherical.theta+=this._sphericalDelta.theta,this._autoRotate&&0===this._state){const t=2*Math.PI/60*(this._autoRotateSpeed/60);this._spherical.theta-=t}this._spherical.phi+=this._sphericalDelta.phi,this._spherical.phi=Math.max(0,Math.min(Math.PI,this._spherical.phi)),this._spherical.makeSafe(),this._target.add(this._panOffset),this._offset.setFromSpherical(this._spherical),this._offset.applyQuaternion(this._quatInverse),e.copy(this._target).add(this._offset),t.lookAt(this._target);const n=1-this._dampingFactor;return this._sphericalDelta.theta*=n,this._sphericalDelta.phi*=n,this._panOffset.set(0,0,0),(this._lastPosition.distanceToSquared(e)>Rh||8*(1-this._lastQuaternion.dot(t.quaternion))>Rh)&&(this._lastPosition.copy(e),this._lastQuaternion.copy(t.quaternion),this._host?.invalidate(),!0)}reset(){this._target.copy(this._target0),this._camera.position.copy(this._position0),this._camera.updateProjectionMatrix(),this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0),this._state=0,this.update()}pinResetPosition(){this._camera&&(this._position0.copy(this._camera.position),this._target0.copy(this._target))}setCamera(t){this._camera=t,this._target.set(0,0,0),this._position0.copy(t.position),this._quat=(new _.Quaternion).setFromUnitVectors(t.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0),this._lastPosition.copy(t.position),this._lastQuaternion.copy(t.quaternion),this._state=0,t.updateMatrixWorld(!0)}isAutoRotating(){return this._autoRotate}setAutoRotate(t){this._autoRotate=t,this._host?.invalidate()}markCameraChanged(){this._host?.invalidate()}dollyAtCursor(t,e,n){this._onUserInteraction?.();const r=this._camera,i=r.position.distanceTo(this._target),s=Math.max(1,Math.min(5e4,i*t));if(Math.abs(s-i)<Rh)return;const o=Math.tan(r.fov/2*Math.PI/180)/r.zoom,a=i-s,c=e*a*o*r.aspect,l=n*a*o;this._panLeftV.setFromMatrixColumn(r.matrix,0).multiplyScalar(c),this._panUpV.setFromMatrixColumn(r.matrix,1).multiplyScalar(l),this._target.add(this._panLeftV).add(this._panUpV),r.position.add(this._panLeftV).add(this._panUpV),this._panCalcOffset.subVectors(r.position,this._target).normalize().multiplyScalar(s),r.position.copy(this._target).add(this._panCalcOffset),this._host?.invalidate()}zoomOrthoAtCursor(t,e,n){this._onUserInteraction?.();const r=this._camera,i=r.zoom,s=Math.max(.1,Math.min(20,i*t)),o=e*(r.right-r.left)/2*(1/i-1/s),a=n*(r.top-r.bottom)/2*(1/i-1/s);this._panLeftV.setFromMatrixColumn(r.matrix,0).multiplyScalar(o),this._panUpV.setFromMatrixColumn(r.matrix,1).multiplyScalar(a),this._target.add(this._panLeftV).add(this._panUpV),r.position.add(this._panLeftV).add(this._panUpV),r.zoom=s,r.updateProjectionMatrix(),this._host?.invalidate()}destroy(){delete this._camera,delete this._host}_getViewportSize(){const t=this._host?.element;if(t){const e=t.getBoundingClientRect();if(e.width>0&&e.height>0)return{width:e.width,height:e.height}}const{width:e,height:n}=this._host.bounds;return{width:Math.abs(e)||1,height:Math.abs(n)||1}}_handleRotateMove(t,e){this._rotateEnd.set(t,e),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart);const{width:n,height:r}=this._getViewportSize();this._sphericalDelta.theta-=2*Math.PI*this._rotateDelta.x/n*this._rotateSpeed,this._sphericalDelta.phi-=2*Math.PI*this._rotateDelta.y/r*this._rotateSpeed,this._rotateStart.copy(this._rotateEnd),this._host?.invalidate()}_handlePanMove(t,e){this._panEnd.set(t,e),this._panDelta.subVectors(this._panEnd,this._panStart),this._isOrthoLocked?this._panOrtho(this._panDelta.x,this._panDelta.y):this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this._host?.invalidate()}_panOrtho(t,e){const n=this._camera,{width:r,height:i}=this._getViewportSize();this._panLeftV.setFromMatrixColumn(n.matrix,0),this._panLeftV.multiplyScalar(-t*(n.right-n.left)/n.zoom/r),this._panUpV.setFromMatrixColumn(n.matrix,1),this._panUpV.multiplyScalar(e*(n.top-n.bottom)/n.zoom/i),this._target.add(this._panLeftV).add(this._panUpV),n.position.add(this._panLeftV).add(this._panUpV)}_pan(t,e){t*=this._panSpeed,e*=this._panSpeed;const{width:n,height:r}=this._getViewportSize(),i=this._camera;if(i.isPerspectiveCamera){this._panCalcOffset.copy(i.position).sub(this._target);let n=this._panCalcOffset.length();n*=Math.tan(i.fov/2*Math.PI/180),this._panLeftV.setFromMatrixColumn(i.matrix,0),this._panLeftV.multiplyScalar(-2*t*n/r),this._panOffset.add(this._panLeftV),this._panUpV.setFromMatrixColumn(i.matrix,1),this._panUpV.multiplyScalar(2*e*n/r),this._panOffset.add(this._panUpV)}else i.isOrthographicCamera&&(this._panLeftV.setFromMatrixColumn(i.matrix,0),this._panLeftV.multiplyScalar(-t*(i.right-i.left)/i.zoom/n),this._panOffset.add(this._panLeftV),this._panUpV.setFromMatrixColumn(i.matrix,1),this._panUpV.multiplyScalar(e*(i.top-i.bottom)/i.zoom/r),this._panOffset.add(this._panUpV))}}class Bh{constructor(){this._mouse=new _.Vector2,this._raycaster=new _.Raycaster}get mouse(){return this._mouse}get lastFocused(){return this._lastFocused}set lastFocused(t){this._lastFocused=t}get lastHovered(){return this._lastHovered}set lastHovered(t){this._lastHovered=t}updateMouseNDC(t,e,n,r,i,s){this._mouse.x=(t-n)/i*2-1,this._mouse.y=-(e-r)/s*2+1}getObjectByRaycast(t,e){const n=this.getObjectsByRaycast(t,e);if(n&&n.length>0)for(const t of n){if(!this._isWorldVisible(t.object))continue;let e=t.object;for(;e;){if(e.userData.context)return e;e=e.parent}}}_isWorldVisible(t){let e=t;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}getObjectsByRaycast(t,e){return this._raycaster.setFromCamera(this._mouse,t),this._raycaster.intersectObjects(e.children,!0)}setHUD(t,e){this._hudScene=t,this._hudCamera=e}handleClick(t,e,n){let r;this._lastFocused&&(this._lastFocused.focused=!1),this._hudScene&&this._hudCamera&&(r=this.getObjectByRaycast(this._hudCamera,this._hudScene)),r||(r=this.getObjectByRaycast(t,e));const i=r?.userData.context;return i&&(i.focused=!0,this._lastFocused=i,i.component?.trigger("click",n)),i}handleHover(t,e,n){let r;this._hudScene&&this._hudCamera&&(r=this.getObjectByRaycast(this._hudCamera,this._hudScene)),r||(r=this.getObjectByRaycast(t,e));const i=r?.userData.context;i!==this._lastHovered&&(this._lastHovered&&(this._lastHovered.component?.trigger("mouseleave",n),this._lastHovered=void 0),i&&(this._lastHovered=i,this._lastHovered.component?.trigger("mouseenter",n)))}destroy(){this._lastFocused=void 0,this._lastHovered=void 0,this._hudScene=void 0,this._hudCamera=void 0}}class Nh{constructor(){this._mode="translate",this._isDragging=!1}get controls(){return this._controls}get mode(){return this._mode}get attached(){return this._attached}get isAttached(){return!!this._attached}get isDragging(){return this._isDragging}setup(t,e,n){this.destroy(),this._scene=n;const r=document.createElement("div");r.style.cssText="position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none",r.setPointerCapture=()=>{},r.releasePointerCapture=()=>{},e.appendChild(r),this._proxyElement=r,this._controls=new p.TransformControls(t,r),this._controls.setMode(this._mode),n.add(this._controls.getHelper()),this._controls.addEventListener("dragging-changed",t=>{this._isDragging=t.value,this.onDraggingChanged?.(t.value)}),this._controls.addEventListener("change",()=>{this._attached&&this.onObjectChange?.(this._attached)})}forwardEvent(t,e){if(!this._proxyElement||!this._controls)return;const n=new PointerEvent(e,{clientX:t.clientX,clientY:t.clientY,button:"pointermove"===e?-1:t.button??0,pointerId:1,pointerType:"mouse",bubbles:!0});this._proxyElement.dispatchEvent(n)}setMode(t){this._mode=t,this._controls?.setMode(t)}attach(t){this._attached=t,this._controls?.attach(t),this._controls?.getHelper().updateMatrixWorld(!0),this.onAttachChanged?.(!0)}detach(){this._controls?.detach(),this._attached=void 0,this.onAttachChanged?.(!1)}updateCamera(t){this._controls&&(this._controls.camera=t)}destroy(){this._controls&&(this._controls.detach(),this._controls.dispose(),this._scene&&this._scene.remove(this._controls.getHelper()),this._controls=void 0),this._proxyElement?.parentNode&&this._proxyElement.parentNode.removeChild(this._proxyElement),this._proxyElement=void 0,this._attached=void 0,this._isDragging=!1}}class Hh{constructor(){this._mouseDownAltKey=!1}captureAltKey(t){this._mouseDownAltKey=t}setupCallbacks(t,e,n,r){t.onDraggingChanged=i=>{e.setEnabled(!i);const s=n();s&&(r?.onDraggingChanged?.(i),i?this._onDragStart(t,s):this._onDragEnd(t,s),s.app?.commander?.execute(null),s.invalidate())},t.onObjectChange=e=>{this._syncFromGizmo(t,e),n()?.invalidate()},t.onAttachChanged=t=>{r?.onAttachChanged?.(t)}}_onDragStart(t,e){this._mouseDownAltKey&&"translate"===t.mode&&this._performAltDragDuplicate(e);const n=e.root?.selected||[];n.length>1&&this._captureMultiSelectState(t,n),"scale"===t.mode&&this._captureScalePreDrag(t)}_performAltDragDuplicate(t){const e=t.root?.selected||[];if(0===e.length||!t.root)return;const n=t.root,r=[];for(const t of e){const e=t.parent,i=new Map,s=Zc(t,t=>{const e=n.getNewRefid();return void 0!==t&&i.set(t,e),e});s.replaceRefids(i),e.addComponent(s),r.push({component:s,to_container:e})}this._altDragDuplicates=r}_captureMultiSelectState(t,e){const n=t.attached;if(n)if("translate"===t.mode){const t=new Map,r=n.position;for(let n=1;n<e.length;n++){const i=e[n]._realObject;i?.object3d&&i.gizmoTransformable&&t.set(i,i.object3d.position.clone().sub(r))}this._multiSelectOffsets=t}else if("rotate"===t.mode){this._gizmoInitialRotation=n.rotation.clone();const t=new Map;for(let n=1;n<e.length;n++){const r=e[n]._realObject;r?.object3d&&r.gizmoTransformable&&t.set(r,r.object3d.rotation.clone())}this._multiSelectInitialRotations=t}else if("scale"===t.mode){const t=new Map;for(let n=1;n<e.length;n++){const r=e[n],i=r._realObject;if(i?.object3d&&i.gizmoTransformable){const{left:e,top:n,width:s,height:o}=r.bounds,{zPos:a=0}=r.state,c=r.state.depth;t.set(i,{left:e,top:n,width:s,height:o,depth:c,zPos:a,scaleX:i.object3d.scale.x,scaleY:i.object3d.scale.y,scaleZ:i.object3d.scale.z})}}this._multiSelectPreDragDimensions=t}}_captureScalePreDrag(t){const e=t.attached,n=e?.userData.context;if(!n||!e)return;const{left:r,top:i,width:s,height:o}=n.component.bounds,{zPos:a=0}=n.component.state,c=n.component.state.depth;this._preDragDimension={left:r,top:i,width:s,height:o,depth:c,zPos:a},this._preDragScale={x:e.scale.x,y:e.scale.y,z:e.scale.z},this._preDragEffectiveDepth=void 0===c?n.effectiveDepth:void 0}_onDragEnd(t,e){if(this._altDragDuplicates&&this._altDragDuplicates.length>0&&(e.app?.commander.execute(new Xc({changes:this._altDragDuplicates})),this._altDragDuplicates=void 0),this._multiSelectOffsets=void 0,this._gizmoInitialRotation=void 0,this._multiSelectInitialRotations=void 0,this._preDragDimension){const e=t.attached,n=e?.userData.context;if(n&&(void 0!==this._preDragEffectiveDepth&&n.applyDimensionFromGizmo({depth:this._preDragEffectiveDepth}),n.update()),this._multiSelectPreDragDimensions)for(const[t]of this._multiSelectPreDragDimensions)t.update()}const n=e.root?.selected||[];for(const e of n){const n=e._realObject;n?.onGizmoDragEnd(t.mode)}this._preDragDimension=void 0,this._preDragScale=void 0,this._preDragEffectiveDepth=void 0,this._multiSelectPreDragDimensions=void 0}_syncFromGizmo(t,e){const n=e.userData.context;if(n)if("scale"===t.mode&&this._preDragDimension&&this._preDragScale){if(this._syncDimensionFromGizmo(n,e),this._multiSelectPreDragDimensions&&this._preDragScale){const t=e.scale.x/this._preDragScale.x,n=e.scale.y/this._preDragScale.y,r=e.scale.z/this._preDragScale.z;for(const[e,i]of this._multiSelectPreDragDimensions){const s=i.width*t,o=i.height*r,a={left:i.left+(i.width-s)/2,top:i.top+(i.height-o)/2,width:s,height:o};if(void 0!==i.depth){const t=i.depth*n;a.depth=t,a.zPos=i.zPos+(i.depth-t)/2}e.applyDimensionFromGizmo(a)}}}else{if(n.syncFromObject3D(),"translate"===t.mode&&this._applyGroundSnap(e,n),this._multiSelectOffsets){const n=e.position;for(const[e,r]of this._multiSelectOffsets)e.object3d&&(e.object3d.position.copy(n).add(r),"translate"===t.mode&&this._applyGroundSnap(e.object3d,e),e.syncFromObject3D())}if(this._multiSelectInitialRotations&&this._gizmoInitialRotation){const t=e.rotation.x-this._gizmoInitialRotation.x,n=e.rotation.y-this._gizmoInitialRotation.y,r=e.rotation.z-this._gizmoInitialRotation.z;for(const[e,i]of this._multiSelectInitialRotations)e.object3d&&(e.object3d.rotation.set(i.x+t,i.y+n,i.z+r),e.syncFromObject3D())}}}_applyGroundSnap(t,e){const n=e.effectiveDepth/2,r=t.position.y-n,i=Math.abs(r);if(i<2)t.position.y=n,e.syncFromObject3D();else if(i<10){const s=(i-2)/8,o=1-s*s;t.position.y=n+r*(1-o),e.syncFromObject3D()}}_syncDimensionFromGizmo(t,e){const n=this._preDragDimension,r=this._preDragScale,i=n.width*(e.scale.x/r.x),s=n.height*(e.scale.z/r.z),o={left:n.left+(n.width-i)/2,top:n.top+(n.height-s)/2,width:i,height:s};if(void 0!==n.depth){const t=n.depth*(e.scale.y/r.y);o.depth=t,o.zPos=n.zPos+(n.depth-t)/2}t.applyDimensionFromGizmo(o)}}class Vh{constructor(){this._mouseIsDown=!1,this._isDragging=!1,this._mouseDownPos={x:0,y:0}}get hostElement(){return this._hostElement}setup(t,e,n){this.cleanup(),this._hostElement=t,this._gizmo=e.gizmo,this._controls=e.controls,this._camera=e.camera,this._scene=e.scene,this._event=e.event,this._delegate=n,t.hasAttribute("tabindex")||t.setAttribute("tabindex","0"),t.style.outline="none";const r={mousedown:t=>this._onMouseDown(t),mousemove:t=>this._onMouseMove(t),wheel:t=>{t.stopPropagation(),this._delegate.handleWheel(t)},dblclick:t=>{t.stopPropagation(),this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleDblClick(t)},contextmenu:t=>{t.preventDefault()},touchstart:t=>{t.stopPropagation(),this._delegate.handleTouchStart(t)},touchmove:t=>{t.stopPropagation(),this._delegate.handleTouchMove(t)},touchend:t=>{t.stopPropagation(),this._delegate.handleTouchEnd(t)},keydown:t=>{this._delegate.handleKeyDown(t)&&t.stopPropagation()},keyup:t=>{(this._delegate.handleKeyUp?.(t)??!1)&&t.stopPropagation()}};t.addEventListener("mousedown",r.mousedown),t.addEventListener("mousemove",r.mousemove),t.addEventListener("wheel",r.wheel),t.addEventListener("dblclick",r.dblclick),t.addEventListener("contextmenu",r.contextmenu),t.addEventListener("touchstart",r.touchstart,{passive:!1}),t.addEventListener("touchmove",r.touchmove,{passive:!1}),t.addEventListener("touchend",r.touchend),t.addEventListener("keydown",r.keydown),t.addEventListener("keyup",r.keyup),this._boundHandlers=r}cleanup(){this._removeDocCapture();const t=this._hostElement,e=this._boundHandlers;t&&e&&(t.removeEventListener("mousedown",e.mousedown),t.removeEventListener("mousemove",e.mousemove),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.dblclick),t.removeEventListener("contextmenu",e.contextmenu),t.removeEventListener("touchstart",e.touchstart),t.removeEventListener("touchmove",e.touchmove),t.removeEventListener("touchend",e.touchend),t.removeEventListener("keydown",e.keydown),t.removeEventListener("keyup",e.keyup),t.removeAttribute("tabindex"),t.style.outline=""),this._boundHandlers=void 0,this._hostElement=void 0,this._mouseIsDown=!1,this._isDragging=!1}forceCleanupDragState(){this._removeDocCapture(),this._mouseIsDown=!1,this._isDragging=!1}clientToElementCoords(t,e){const n=this._hostElement;if(!n)return{x:t,y:e};const r=n.getBoundingClientRect();return{x:t-r.left,y:e-r.top}}updateMouseNDCFromClient(t,e){const n=this._hostElement?.getBoundingClientRect();if(!n||0===n.width||0===n.height)return;const r=t-n.left,i=e-n.top;this._event.updateMouseNDC(r,i,0,0,n.width,n.height)}_onMouseDown(t){if(t.stopPropagation(),this._hostElement.focus(),this._delegate.isPlacementMode())return void this._delegate.handlePlacementClick(t);if(this._delegate.isSpacePanning?.()??!1)return this._mouseIsDown=!0,this._isDragging=!1,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{t.stopPropagation();const e=t.clientX-this._mouseDownPos.x,n=t.clientY-this._mouseDownPos.y;if(!this._isDragging){if(e*e+n*n<Vh.DRAG_THRESHOLD)return;this._isDragging=!0;const t=this.clientToElementCoords(this._mouseDownPos.x,this._mouseDownPos.y);this._controls.onDragStart({offsetX:t.x,offsetY:t.y,altKey:!0})}const r=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragMove({offsetX:r.x,offsetY:r.y,altKey:!0})},this._docUpHandler=t=>{if(t.stopPropagation(),this._removeDocCapture(),this._isDragging){const e=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragEnd({offsetX:e.x,offsetY:e.y})}this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),void document.addEventListener("mouseup",this._docUpHandler,!0);if(t.shiftKey&&!t.altKey&&!t.metaKey&&!t.ctrlKey){const e=this.clientToElementCoords(t.clientX,t.clientY);return this._mouseIsDown=!0,this._isDragging=!1,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{t.stopPropagation();const n=t.clientX-this._mouseDownPos.x,r=t.clientY-this._mouseDownPos.y;if(!this._isDragging){if(n*n+r*r<Vh.DRAG_THRESHOLD)return;this._isDragging=!0,this._delegate.handleBoxSelectionStart?.(e.x,e.y)}const i=this.clientToElementCoords(t.clientX,t.clientY);this._delegate.handleBoxSelectionUpdate?.(i.x,i.y)},this._docUpHandler=t=>{if(t.stopPropagation(),this._removeDocCapture(),this._isDragging)this._delegate.handleBoxSelectionEnd?.(t.shiftKey);else{const e=this.clientToElementCoords(t.clientX,t.clientY);this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleClickAt(e.x,e.y,t)}this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),void document.addEventListener("mouseup",this._docUpHandler,!0)}if(this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.tryVertexDragStart?.(t))return this._mouseIsDown=!0,this._isDragging=!0,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{t.stopPropagation(),this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleVertexDragMove?.(t)},this._docUpHandler=t=>{t.stopPropagation(),this._removeDocCapture(),this._delegate.handleVertexDragEnd?.(t),this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),void document.addEventListener("mouseup",this._docUpHandler,!0);this._delegate.captureMouseDownAltKey(t.altKey),this._gizmo.forwardEvent(t,"pointermove"),this._gizmo.forwardEvent(t,"pointerdown");let e=this._gizmo.isDragging;!e&&t.altKey&&this._delegate.tryAltClickSelect(t)&&(this._gizmo.forwardEvent(t,"pointermove"),this._gizmo.forwardEvent(t,"pointerdown"),e=this._gizmo.isDragging),this._mouseIsDown=!0,this._isDragging=!1,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{if(t.stopPropagation(),e)return void this._gizmo.forwardEvent(t,"pointermove");const n=t.clientX-this._mouseDownPos.x,r=t.clientY-this._mouseDownPos.y;if(!this._isDragging){if(n*n+r*r<Vh.DRAG_THRESHOLD)return;this._isDragging=!0;const e=this.clientToElementCoords(this._mouseDownPos.x,this._mouseDownPos.y);this._controls.onDragStart({offsetX:e.x,offsetY:e.y,altKey:t.altKey})}const i=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragMove({offsetX:i.x,offsetY:i.y,altKey:t.altKey})},this._docUpHandler=t=>{if(t.stopPropagation(),this._removeDocCapture(),e)return this._gizmo.forwardEvent(t,"pointerup"),this._mouseIsDown=!1,void(this._isDragging=!1);if(this._isDragging){const e=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragEnd({offsetX:e.x,offsetY:e.y})}else{const e=this.clientToElementCoords(t.clientX,t.clientY);this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleClickAt(e.x,e.y,t)}this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),document.addEventListener("mouseup",this._docUpHandler,!0)}_onMouseMove(t){if(t.stopPropagation(),this._mouseIsDown)return;if(this._delegate.isPlacementMode())return void this._delegate.handlePlacementHover(t);this.updateMouseNDCFromClient(t.clientX,t.clientY);const e=this._camera.activeCamera;e&&this._scene.scene&&this._event.handleHover(e,this._scene.scene,t),this._gizmo.forwardEvent(t,"pointermove")}_removeDocCapture(){this._docMoveHandler&&(document.removeEventListener("mousemove",this._docMoveHandler,!0),this._docMoveHandler=void 0),this._docUpHandler&&(document.removeEventListener("mouseup",this._docUpHandler,!0),this._docUpHandler=void 0)}}Vh.DRAG_THRESHOLD=16;class Gh{constructor(){this._groundPlane=new _.Plane(new _.Vector3(0,1,0),0)}get isActive(){return!!this._pendingModels}get pendingModels(){return this._pendingModels}setup(t,e){this._camera=t.camera,this._event=t.event,this._scene=t.scene,this._delegate=e}start(t){this._pendingModels=t}stop(){this._pendingModels=void 0,this._removeIndicator()}destroy(){this._removeIndicator(),this._pendingModels=void 0}raycastGroundPlane(t){this._delegate.updateMouseNDCFromClient(t.clientX,t.clientY);const e=this._camera.activeCamera;if(!e)return null;e.updateMatrixWorld(!0);const n=new _.Raycaster;n.setFromCamera(this._event.mouse,e);const r=new _.Vector3;return n.ray.intersectPlane(this._groundPlane,r)}updateIndicator(t){if(!t)return void(this._placementIndicator&&(this._placementIndicator.visible=!1));if(!this._placementIndicator){const t=this._scene?.scene;if(!t)return;const e=new _.RingGeometry(.8,1,32);e.rotateX(-Math.PI/2);const n=new _.MeshBasicMaterial({color:48340,opacity:.6,transparent:!0,side:_.DoubleSide,depthTest:!1});this._placementIndicator=new _.Mesh(e,n),this._placementIndicator.renderOrder=999,t.add(this._placementIndicator)}const e=this._pendingModels?.[0],n=e?.rx??e?.width??50,r=e?.ry??e?.height??50;this._placementIndicator.scale.set(n,1,r),this._placementIndicator.position.copy(t),this._placementIndicator.position.y=1,this._placementIndicator.visible=!0}_removeIndicator(){if(this._placementIndicator){const t=this._placementIndicator;this._scene?.scene?.remove(t),t.geometry.dispose(),t.material.dispose(),this._placementIndicator=void 0}}}const Yh={linear:t=>t,"ease-in":t=>t*t,"ease-out":t=>1-(1-t)*(1-t),"ease-in-out":t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2};function Uh(t,e,n,r,i,s=new _.Vector3){const o=t*t,a=o*t;return s.set(.5*(2*n.x+(-e.x+r.x)*t+(2*e.x-5*n.x+4*r.x-i.x)*o+(-e.x+3*n.x-3*r.x+i.x)*a),.5*(2*n.y+(-e.y+r.y)*t+(2*e.y-5*n.y+4*r.y-i.y)*o+(-e.y+3*n.y-3*r.y+i.y)*a),.5*(2*n.z+(-e.z+r.z)*t+(2*e.z-5*n.z+4*r.z-i.z)*o+(-e.z+3*n.z-3*r.z+i.z)*a))}class $h{constructor(){this._slots=new Array(10),this._animating=!1,this._animationProgress=0,this._playStartOffset=0,this._lastPlayProgress=-1,this._playIndex=-1,this._playing=!1,this._orbitRotating=!1,this._orbitPaused=!1}get isAnimating(){return this._animating}get isPlaying(){return this._playing}get isOrbitRotating(){return this._orbitRotating}get isOrbitPaused(){return this._orbitPaused}get playIndex(){return this._playIndex}get lastPlayProgress(){return this._lastPlayProgress}get playProgress(){if(!this._playing||this._playIndex<0)return 0;const t=this.getPlayableSlots().length;if(t<2)return 0;const e=(this._playIndex-1+t)%t;let n=this._animating?this._animationProgress:1;return this._playStartOffset>0&&(n=this._playStartOffset+n*(1-this._playStartOffset)),(e+n)%t/t}setCallbacks(t,e){this._onInvalidate=t,this._onAnimationComplete=e}saveSlot(t,e){if(t<0||t>9)return;const n=this._slots[t];this._slots[t]={...e,name:"name"in e?e.name:n?.name}}renameSlot(t,e){if(t<0||t>9)return;const n=this._slots[t];n&&(n.name=e||void 0)}clearSlot(t){t<0||t>9||(this._slots[t]=void 0)}getSlot(t){return this._slots[t]}exportSlots(){return this._slots.map(t=>t?{...t}:null)}importSlots(t){if(Array.isArray(t))for(let e=0;e<10;e++){const n=t[e];this._slots[e]=n?{...n}:void 0}}resetAll(){this._slots=new Array(10)}getPlayableSlots(){return this._slots.map((t,e)=>t&&!t.excludeFromPlay?e:-1).filter(t=>t>=0)}swapSlots(t,e){if(t<0||t>9||e<0||e>9||t===e)return;const n=this._slots[t];this._slots[t]=this._slots[e],this._slots[e]=n}moveSlot(t,e){if(t<1||t>9||e<1||e>9||t===e)return;const n=this._slots[t];this._slots.splice(t,1),this._slots.splice(e,0,n)}animateToSlot(t,e,n,r=800,i){const s=this._slots[t];if(!s)return!1;this.stopAnimation(),this._animating=!0,this._animationProgress=0;const o=e.position.clone(),a=n.target.clone(),c=new _.Vector3(s.position.x,s.position.y,s.position.z),l=new _.Vector3(s.target.x,s.target.y,s.target.z),h=.01,d=Math.max(o.distanceTo(a),h),u=Math.max(c.distanceTo(l),h),p=(new _.Vector3).subVectors(a,o),f=(new _.Vector3).subVectors(l,c),g=p.lengthSq()>1e-4?p.normalize():new _.Vector3(0,0,-1).applyQuaternion(e.quaternion),m=f.lengthSq()>1e-4?f.normalize():g.clone(),y=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),g),b=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),m),v=Yh[s.easing??"ease-in-out"];return this._runAnimation(r,v,t=>{i?Uh(t,i.prevPos,o,c,i.nextPos,e.position):e.position.lerpVectors(o,c,t);const r=y.clone().slerp(b,t),s=new _.Vector3(0,0,-1).applyQuaternion(r),a=d+(u-d)*t,l=e.position.clone().add(s.multiplyScalar(a));n.restoreTarget(l)}),!0}_animatePathSegment(t,e,n,r,i,s){const o=Yh[r];this._runAnimation(n,o,n=>{const r=t+(e-t)*n,o=this.evaluatePath(r<=1?r:r-1);o&&(i.position.copy(o.position),s.restoreTarget(o.target))})}_runAnimation(t,e,n){this.stopAnimation(),this._animating=!0,this._animationProgress=0;const r=performance.now(),i=()=>{const s=performance.now()-r,o=Math.min(s/t,1),a=e(o);this._animationProgress=a,n(a),this._onInvalidate?.(),o<1?this._animationId=requestAnimationFrame(i):(this._animating=!1,this._animationId=void 0,this._onAnimationComplete?.())};this._animationId=requestAnimationFrame(i)}_initFromProgress(t,e){const n=t*e,r=Math.min(Math.floor(n),e-1);this._playStartOffset=n-r,this._playIndex=(r+1)%e}startPlay(t,e,n=2e3,r=1200,i=-1,s=!1){if(this._playing)return void this.stopPlay();const o=this.getPlayableSlots();if(o.length<2)return;this._playing=!0;let a=!0,c=-1;const l=i>=0&&i<=1?i:this._lastPlayProgress>0&&this._lastPlayProgress<1?this._lastPlayProgress:-1;s?this._playIndex=0:l>=0?(this._initFromProgress(l,o.length),c=l,a=!1):this._playIndex=0;const h=t=>new _.Vector3(t.x,t.y,t.z),d=t=>{this._onAnimationComplete=()=>{this._playing&&(this._playStartOffset=0,setTimeout(()=>{this._playing&&(this._playIndex=(this._playIndex+1)%o.length,u())},t))}},u=()=>{if(!this._playing)return;const i=o[this._playIndex],s=this._slots[i],l=s?.holdDuration??n,u=s?.transitionDuration??r;if(c>=0){const n=c;let r=this._playIndex/o.length;r<=n&&(r+=1),c=-1;const i=this._playStartOffset,a=Math.max(Math.round(u*(1-i)),100);return d(l),void this._animatePathSegment(n,r,a,s?.easing??"ease-in-out",t,e)}const p=this._buildSplineContext(o,a,t,e,h);a=!1,d(l),this.animateToSlot(i,t,e,u,p)};u()}_buildSplineContext(t,e,n,r,i){if(t.length<3)return;const s=t.length,o=t[(this._playIndex+1)%s],a=this._slots[o];if(!a)return;if(e)return{prevPos:n.position.clone(),nextPos:i(a.position)};const c=t[(this._playIndex-2+s)%s],l=this._slots[c];return l?{prevPos:i(l.position),nextPos:i(a.position)}:void 0}setProgressForSlot(t){const e=this.getPlayableSlots(),n=e.indexOf(t);n<0||e.length<2?this._lastPlayProgress=-1:this._lastPlayProgress=n/e.length}stopPlay(){this._lastPlayProgress=this.playProgress,this._playing=!1,this._playIndex=-1,this._playStartOffset=0,this._onAnimationComplete=void 0,this.stopAnimation()}resetPlay(){this.stopPlay(),this._lastPlayProgress=-1}toggleOrbitRotation(t){const e=t.isAutoRotating();this._orbitRotating=!e,this._orbitPaused=!this._orbitRotating,t.setAutoRotate(this._orbitRotating)}stopOrbitRotation(t){this._orbitRotating=!1,this._orbitPaused=!1,t.setAutoRotate(!1)}evaluatePath(t){const e=this.getPlayableSlots();if(e.length<2)return null;const n=e.length,r=Math.max(0,Math.min(1,t)),i=t=>{const r=this._slots[e[(t%n+n)%n]];return r?new _.Vector3(r.position.x,r.position.y,r.position.z):new _.Vector3},s=t=>{const r=this._slots[e[(t%n+n)%n]];return r?new _.Vector3(r.target.x,r.target.y,r.target.z):new _.Vector3};if(2===n){const t=r<.5?2*r:2*(1-r);return{position:i(0).lerp(i(1),t),target:s(0).lerp(s(1),t)}}const o=r*n,a=Math.min(Math.floor(o),n-1),c=o-a,l=Uh(c,i(a-1),i(a),i(a+1),i(a+2)),h=i(a),d=i(a+1),u=s(a),p=s(a+1),f=.01,g=Math.max(h.distanceTo(u),f),m=Math.max(d.distanceTo(p),f),y=(new _.Vector3).subVectors(u,h),b=(new _.Vector3).subVectors(p,d),v=y.lengthSq()>1e-4?y.normalize():new _.Vector3(0,0,-1),x=b.lengthSq()>1e-4?b.normalize():v.clone(),w=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),v),M=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),x),S=w.clone().slerp(M,c),A=new _.Vector3(0,0,-1).applyQuaternion(S),E=g+(m-g)*c,k=l.clone().add(A.multiplyScalar(E));return{position:l,target:k}}stopAnimation(){void 0!==this._animationId&&(cancelAnimationFrame(this._animationId),this._animationId=void 0),this._animating=!1}destroy(){this.stopPlay(),this.stopAnimation(),this._orbitPaused=!1,this._slots=new Array(10),this._onInvalidate=void 0,this._onAnimationComplete=void 0}}class Wh{constructor(){this._overlay=null,this._hostElement=null,this._startX=0,this._startY=0,this._currentX=0,this._currentY=0,this._active=!1}get isActive(){return this._active}setup(t){this._hostElement=t}startSelection(t,e){this._hostElement&&(this._startX=t,this._startY=e,this._currentX=t,this._currentY=e,this._active=!0,this._overlay=document.createElement("div"),this._overlay.style.cssText="\n position: absolute;\n border: 1px solid #4a9eff;\n background: rgba(74, 158, 255, 0.1);\n pointer-events: none;\n z-index: 1000;\n ",this._hostElement.appendChild(this._overlay),this._updateOverlay())}updateSelection(t,e){this._active&&(this._currentX=t,this._currentY=e,this._updateOverlay())}endSelection(t,e,n){if(!this._active||!this._hostElement)return this.cancelSelection(),[];const r=this._hostElement.getBoundingClientRect(),i=r.width,s=r.height,o=Math.min(this._startX,this._currentX),a=Math.max(this._startX,this._currentX),c=Math.min(this._startY,this._currentY),l=Math.max(this._startY,this._currentY);if(a-o<5&&l-c<5)return this.cancelSelection(),[];const h=o/i*2-1,d=a/i*2-1,u=-l/s*2+1,p=-c/s*2+1,f=[],g=new _.Vector3;for(const e of n){const n=e._realObject;n?.object3d&&(g.copy(n.object3d.position),g.project(t),g.z>1||g.x>=h&&g.x<=d&&g.y>=u&&g.y<=p&&f.push(e))}return this.cancelSelection(),f}cancelSelection(){this._active=!1,this._overlay&&this._hostElement&&this._hostElement.removeChild(this._overlay),this._overlay=null}destroy(){this.cancelSelection(),this._hostElement=null}_updateOverlay(){if(!this._overlay)return;const t=Math.min(this._startX,this._currentX),e=Math.min(this._startY,this._currentY),n=Math.abs(this._currentX-this._startX),r=Math.abs(this._currentY-this._startY);this._overlay.style.left=`${t}px`,this._overlay.style.top=`${e}px`,this._overlay.style.width=`${n}px`,this._overlay.style.height=`${r}px`}}const Xh=4890367,qh=16750592;class Kh{constructor(){this._componentHandles=[],this._activeVertexHandles=[],this._activeHandleIndex=-1,this._isDragging=!1,this._isExtending=!1,this._dragPlane=new _.Plane,this._dragOffset=new _.Vector3,this._raycaster=new _.Raycaster,this._intersection=new _.Vector3}get isDragging(){return this._isDragging}get isAttached(){return this._componentHandles.length>0}setVisible(t){this._handleGroup&&(this._handleGroup.visible=t)}attachMultiple(t,e,n){this.detach();const r=t.filter(t=>t.mutable&&t.path&&t.path.length>=2);if(0!==r.length){this._scene3d=e,this._commander=n,this._handleGroup=new _.Group,this._handleGroup.name="__vertexHandles__",this._handleGroup.renderOrder=1e4;for(const t of r){const e=this._buildComponentHandles(t);this._componentHandles.push(e)}e.add(this._handleGroup)}}attach(t,e,n){this.attachMultiple([t],e,n)}detach(){this._handleGroup&&this._scene3d&&(this._scene3d.remove(this._handleGroup),yh(this._handleGroup)),this._componentHandles=[],this._handleGroup=void 0,this._scene3d=void 0,this._commander=void 0,this._activeComponent=void 0,this._activeVertexHandles=[],this._activeHandleIndex=-1,this._isDragging=!1,this._isExtending=!1}_buildComponentHandles(t){const e=[],n=[],r=t.path;if(!r||!this._handleGroup)return{component:t,vertexHandles:e,midpointHandles:n};const{width:i=0,height:s=0}=t.parent?.bounds??{},o=t._realObject,a=o?o.object3d.position.y:0;for(let n=0;n<r.length;n++){const o=r[n],c=new _.Vector3(o.x-i/2,(o.z||0)+a,o.y-s/2),l=this._createVertexHandle(c,n,t);e.push(l),this._handleGroup.add(l)}if(t.pathExtendable)for(let e=0;e<r.length-1;e++){const o=r[e],c=r[e+1],l=new _.Vector3((o.x+c.x)/2-i/2,((o.z||0)+(c.z||0))/2+a,(o.y+c.y)/2-s/2),h=this._createMidpointHandle(l,e,t);n.push(h),this._handleGroup.add(h)}return{component:t,vertexHandles:e,midpointHandles:n}}_rebuildComponentHandles(t){const e=this._componentHandles.findIndex(e=>e.component===t);if(e<0||!this._handleGroup)return;const n=this._componentHandles[e];for(const t of[...n.vertexHandles,...n.midpointHandles])this._handleGroup.remove(t),t.geometry.dispose(),t.material.dispose();this._componentHandles[e]=this._buildComponentHandles(t),this._activeComponent===t&&(this._activeVertexHandles=this._componentHandles[e].vertexHandles)}_createVertexHandle(t,e,n){const r=new _.SphereGeometry(1,16,12),i=new _.MeshBasicMaterial({color:Xh,transparent:!0,opacity:.8,depthTest:!1}),s=new _.Mesh(r,i);return s.position.copy(t),s.userData.vertexIndex=e,s.userData.handleType="vertex",s.userData.component=n,s.renderOrder=10001,s}_createMidpointHandle(t,e,n){const r=new _.OctahedronGeometry(.7,0),i=new _.MeshBasicMaterial({color:16735602,transparent:!0,opacity:.7,depthTest:!1}),s=new _.Mesh(r,i);return s.position.copy(t),s.userData.segmentIndex=e,s.userData.handleType="midpoint",s.userData.component=n,s.renderOrder=10001,s}_handlePosToPoint(t,e){const{width:n=0,height:r=0}=e.parent?.bounds??{},i=e._realObject,s=i?i.object3d.position.y:0,o={x:t.x+n/2,y:t.z+r/2},a=t.y-s;return Math.abs(a)>.001&&(o.z=a),o}_execMutatePath(t,e){const n=this._commander;n?zc.around(n,()=>{t.mutatePath(null,e)}):t.mutatePath(null,e)}_getAllHandles(){const t=[];for(const e of this._componentHandles)t.push(...e.vertexHandles,...e.midpointHandles);return t}_findComponentHandles(t){return this._componentHandles.find(e=>e.component===t)}onPointerDown(t,e,n){if(!this._handleGroup)return!1;const r=this._getAllHandles();if(0===r.length)return!1;this._raycaster.setFromCamera(t,e);const i=this._raycaster.intersectObjects(r,!1);if(0===i.length)return!1;const s=i[0].object,o=s.userData.handleType,a=s.userData.component,c=this._findComponentHandles(a);if(!c)return!1;if(this._activeComponent=a,this._activeVertexHandles=c.vertexHandles,"midpoint"===o)return this._startMidpointDrag(s,a,e);const l=s.userData.vertexIndex,h=a.path;if(!h)return!1;const d=0===l||l===h.length-1;return n.altKey&&d&&a.pathExtendable?this._startEndpointExtend(s,l,a,e):(this._activeHandleIndex=l,this._isDragging=!0,this._isExtending=!1,s.material.color.setHex(qh),this._setupDragPlane(e,s.position),!0)}_startMidpointDrag(t,e,n){const r=t.userData.segmentIndex+1,i=this._handlePosToPoint(t.position,e);this._execMutatePath(e,t=>{t.splice(r,0,i)}),this._rebuildComponentHandles(e);const s=this._activeVertexHandles[r];return!!s&&(this._activeHandleIndex=r,this._isDragging=!0,this._isExtending=!1,s.material.color.setHex(qh),this._setupDragPlane(n,s.position),!0)}_startEndpointExtend(t,e,n,r){const i=n.path;if(!i)return!1;const s=this._handlePosToPoint(t.position,n),o=0===e?0:i.length;this._execMutatePath(n,t=>{t.splice(o,0,s)}),this._rebuildComponentHandles(n);const a=this._activeVertexHandles[o];return!!a&&(this._activeHandleIndex=o,this._isDragging=!0,this._isExtending=!0,a.material.color.setHex(qh),this._setupDragPlane(r,a.position),!0)}_setupDragPlane(t,e){const n=new _.Vector3;t.getWorldDirection(n),this._dragPlane.setFromNormalAndCoplanarPoint(n,e),this._raycaster.ray.intersectPlane(this._dragPlane,this._intersection),this._dragOffset.copy(e).sub(this._intersection)}onPointerMove(t,e,n){if(!this._isDragging||this._activeHandleIndex<0)return!1;this._raycaster.setFromCamera(t,e),this._raycaster.ray.intersectPlane(this._dragPlane,this._intersection);const r=this._intersection.add(this._dragOffset);if(n.shiftKey){const t=this._activeVertexHandles[this._activeHandleIndex];t&&(r.x=t.position.x,r.z=t.position.z)}const i=this._activeVertexHandles[this._activeHandleIndex];return i&&i.position.copy(r),this._updateLinePreview(),!0}_updateLinePreview(){if(!this._activeComponent)return;const t=this._activeComponent._realObject;if(!t?._line2)return;const{width:e=0,height:n=0}=this._activeComponent.parent?.bounds??{},{x:r,y:i}=this._activeComponent.center,s=t.object3d?t.object3d.position.y:0,o=[];for(const t of this._activeVertexHandles){const a=t.position.x+e/2-r,c=t.position.y-s,l=t.position.z+n/2-i;o.push(a,c,l)}if(o.length<6)return;t._line2.geometry.setPositions(o),t._line2.computeLineDistances()}onPointerUp(){if(!this._isDragging||this._activeHandleIndex<0||!this._activeComponent)return!1;const t=this._activeHandleIndex,e=this._activeVertexHandles[t],n=this._activeComponent;if(!e)return this._isDragging=!1,this._activeHandleIndex=-1,this._isExtending=!1,!0;e.material.color.setHex(Xh);const r=this._handlePosToPoint(e.position,n);return this._execMutatePath(n,e=>{e[t]=r}),this._isDragging=!1,this._activeHandleIndex=-1,this._isExtending=!1,this._rebuildComponentHandles(n),!0}onDblClick(t,e){if(!this._handleGroup)return!1;const n=[];for(const t of this._componentHandles)n.push(...t.vertexHandles);this._raycaster.setFromCamera(t,e);const r=this._raycaster.intersectObjects(n,!1);if(0===r.length)return!1;const i=r[0].object,s=i.userData.component;if(!s.pathExtendable)return!1;const o=s.path;if(!o||o.length<=2)return!1;const a=i.userData.vertexIndex;return this._execMutatePath(s,t=>{t.splice(a,1)}),this._rebuildComponentHandles(s),!0}syncHandles(){for(const t of this._componentHandles)this._rebuildComponentHandles(t.component)}updateHandleScales(t){const e=this._getAllHandles();if(0!==e.length)for(const n of e){const e=t.position.distanceTo(n.position),r="midpoint"===n.userData.handleType?5:8;let i;if(t.isPerspectiveCamera){const n=t.fov,s=2*Math.tan(n*Math.PI/360)*e;i=r/window.innerHeight*s}else{const e=t,n=(e.top-e.bottom)/e.zoom;i=r/window.innerHeight*n}n.scale.setScalar(Math.max(i,.1))}}destroy(){this.detach()}}class Qh{constructor(){this.sceneManager=new zh,this.cameraManager=new Ih,this.rendererManager=new Lh,this.lightManager=new jh,this.controlsManager=new Fh,this.eventManager=new Bh,this.gizmoManager=new Nh,this.interactionManager=new Vh,this.placementManager=new Gh,this.gizmoOperationManager=new Hh,this.bookmarkManager=new $h,this.boxSelectionManager=new Wh,this.vertexGizmoManager=new Kh,this._isSpacePanning=!1,this._initialized=!1,this._decoratorOutlines=new Set,this._selectionOutlineObjects=[],this._highlightedMarkerIndex=-1,this._arrows=new Map,this._pathVisible=!1}get isInitialized(){return this._initialized}get host(){return this._host}get scene3d(){return this.sceneManager.scene}get renderer3d(){return this.rendererManager.renderer}get mixer(){return this.sceneManager.mixer}get camera(){return this.cameraManager.camera}get activeCamera(){return this.cameraManager.activeCamera}get css3DScene(){return this.rendererManager.css3DScene}get css3DRenderer(){return this.rendererManager.css3DRenderer}get noSupportWebgl(){return this.rendererManager.noSupportWebgl}get isActive(){return this.controlsManager.isActive}setGizmoMode(t){if(this.gizmoManager.mode===t&&this.gizmoManager.attached)return this.gizmoManager.detach(),void this._host?.invalidate();this.gizmoManager.setMode(t),this.onGizmoModeChanged?.(t);const e=this._host?.root?.selected,n=e?.filter(t=>t!==this._host&&t._realObject)||[];if(n.length>=1){const t=n[0]._realObject;t?.object3d&&t.gizmoTransformable&&this.gizmoManager.attach(t.object3d),this._host?.invalidate()}}get gizmoMode(){return this.gizmoManager.mode}init(t,e){this.interactionManager.cleanup(),this._cleanupEventHandlers(),this._host=t,this.sceneManager.scene&&this.destroy(),this._redrawHandler=()=>this.animate(),t.root.on("redraw",this._redrawHandler),this._initialized=!0,this._setupScene(e),this._onComponentAdd=(t,e)=>this.addObject(e),this._onComponentRemove=(t,e)=>this.removeObject(e),t.on&&(t.on("add",this._onComponentAdd),t.on("remove",this._onComponentRemove)),t.app?.isEditMode&&t.root?.on&&(this._onSelectionChanged=t=>this._handleSelectionChanged(t),t.root.on("selected",this._onSelectionChanged)),t.app?.isEditMode&&t.root?.on&&(this._onAddStart=t=>{this.placementManager.start(t),this._host?.element&&(this._host.element.style.cursor="crosshair",this._host.element.focus())},this._onAddStop=()=>{this.placementManager.stop(),this._host?.element&&(this._host.element.style.cursor="")},t.root.on("addstart",this._onAddStart),t.root.on("addstop",this._onAddStop))}_cleanupEventHandlers(){const t=this._host;t&&(this._redrawHandler&&(t.root.off("redraw",this._redrawHandler),this._redrawHandler=void 0),t.off&&(this._onComponentAdd&&(t.off("add",this._onComponentAdd),this._onComponentAdd=void 0),this._onComponentRemove&&(t.off("remove",this._onComponentRemove),this._onComponentRemove=void 0)),this._onSelectionChanged&&t.root?.off&&(t.root.off("selected",this._onSelectionChanged),this._onSelectionChanged=void 0),this._onAddStart&&t.root?.off&&(t.root.off("addstart",this._onAddStart),this._onAddStart=void 0),this._onAddStop&&t.root?.off&&(t.root.off("addstop",this._onAddStop),this._onAddStop=void 0))}_setupScene(t){const e=this._host;let{width:n,height:r}=e.bounds;n=Math.abs(n)||1,r=Math.abs(r)||1;const{fov:i=45,near:s=.1,far:o=2e4,antialias:a=!0,precision:c="highp",cameraX:l,cameraY:h,cameraZ:d,exposure:u=1}=e.state,p=e.components||[],f=t?.lightingConfig??{hemisphere:{skyColor:16777215,groundColor:4473924,intensity:.4}},g=t?.css3DSceneAttribute??"three-container:css3d-renderer",m=this.sceneManager.setup(),y=this.cameraManager.setup(n,r,{fov:i,near:s,far:o,cameraX:l,cameraY:h,cameraZ:d});this.cameraManager.addToScene(m);const b=e.app?.postprocessing;if(this.rendererManager.setupWebGL(n,r,{precision:c,antialias:a,exposure:u,postprocessing:b})){if(t?.skipEnvironment||this.sceneManager.setupEnvironment(this.rendererManager.renderer),this.controlsManager.setup(y,e),this.controlsManager.setOnUserInteraction(()=>{this.bookmarkManager.isPlaying&&(this.bookmarkManager.stopPlay(),this._pathVisible&&this.showBookmarkPath()),this.bookmarkManager.isOrbitRotating&&this.bookmarkManager.stopOrbitRotation(this.controlsManager)}),e.app?.isEditMode&&e.element&&(this.gizmoManager.setup(y,e.element,m),this._setupGizmoCallbacks()),this.placementManager.setup({camera:this.cameraManager,event:this.eventManager,scene:this.sceneManager},{updateMouseNDCFromClient:(t,e)=>this._updateMouseNDCFromClient(t,e)}),this.lightManager.setup(m,y,f),this.sceneManager.setupMixer(),this.createObjects(p),y.updateProjectionMatrix(),t?.skipFloor||this.sceneManager.addFloor(e),this.sceneManager.setSky(e.state.sky,e.state.skyColor),t?.skipPostprocessing||!1===e.app?.postprocessing)this.rendererManager.setDirectRenderTargets(m,y);else{const t=this.gizmoManager.controls?.getHelper();this.rendererManager.setupComposer(m,y,n,r,t)}this.rendererManager.setupHUD(n,r),this.rendererManager.hudCamera&&this.eventManager.setHUD(this.rendererManager.hudScene,this.rendererManager.hudCamera),this.rendererManager.setupCSS3D(e.app.isViewMode,g),this._onFocus=()=>this.renderThreeD(),window.addEventListener("focus",this._onFocus),e.element&&(this.interactionManager.setup(e.element,{gizmo:this.gizmoManager,controls:this.controlsManager,camera:this.cameraManager,scene:this.sceneManager,event:this.eventManager},this._buildInteractionDelegate()),e.app?.isEditMode&&this.boxSelectionManager.setup(e.element))}}_setupGizmoCallbacks(){this.gizmoOperationManager.setupCallbacks(this.gizmoManager,this.controlsManager,()=>this._host,{onAttachChanged:t=>this.onGizmoAttachChanged?.(t),onDraggingChanged:t=>{t?this.vertexGizmoManager.setVisible(!1):(this.vertexGizmoManager.syncHandles(),this.vertexGizmoManager.setVisible(!0))}})}createObjects(t){for(const e of t)this.addObject(e)}addObject(t){if(!t._realObject&&!t.is3dContainer?.()){try{const{width:e,height:n}=t.bounds;if(!e||!n)return;if(t.isHTMLElement()&&!t.element)return;const r=kh(t);if(r){if(t._realObject=r,r.update(),r.updateTransform(),t.state.screenFixed)r instanceof wh?this.rendererManager.hudCSS3DScene.add(r.object3d):this.rendererManager.hudScene.add(r.object3d);else if(r instanceof wh)this.rendererManager.css3DScene.add(r.object3d);else{const e=t.parent?._realObject?.object3d;e&&e!==this.sceneManager.scene?e.add(r.object3d):this.sceneManager.scene.add(r.object3d)}const e=this._host?.root?.selected;e&&e.length>0&&e[0]===t&&r.object3d&&r.gizmoTransformable&&this.gizmoManager.attached&&this.gizmoManager.attach(r.object3d)}}catch(t){jr(t)}if(t.isContainer()){const e=t,n=e.components||[];this.createObjects(n),e.on&&(e.on("add",this._onComponentAdd),e.on("remove",this._onComponentRemove))}}}removeObject(t){if(t.is3dContainer?.())return;if(t.isContainer()){const e=t,n=e.components||[];for(const t of n)this.removeObject(t);e.off&&(e.off("add",this._onComponentAdd),e.off("remove",this._onComponentRemove))}const e=t._realObject;if(e)try{const n=e.object3d;n&&this.gizmoManager.attached===n&&this.gizmoManager.detach(),n&&(e instanceof wh?this.rendererManager.css3DScene.remove(n):n.removeFromParent()),e.dispose?.(),t._realObject=void 0}catch(t){jr(t)}}resize(t,e,n=!1){const r=this._host;if(!r)return;if(void 0===t||void 0===e){const n=r.bounds;t=n.width,e=n.height}if(t=Math.abs(t)||1,e=Math.abs(e)||1,n)return void this._applyResize(t,e);this.rendererManager.css3DRenderer?.setSize(t,e);const i=t,s=e;clearTimeout(this._resizeDebouncer),this._resizeDebouncer=window.setTimeout(()=>{this._resizeDebouncer=void 0,this._applyResize(i,s)},100)}_applyResize(t,e){this.cameraManager.updateAspect(t,e),this.rendererManager.resize(t,e);const n=new _.Vector2(t,e);for(const t of this._arrows.values())t.traverse(t=>{t instanceof r.Line2&&t.material.resolution.copy(n)});this._initialized&&(this.renderThreeD(),this.renderCSS3D())}animate(){if(!this._initialized||!this.controlsManager.isActive)return;this.sceneManager.updateAnimation();let t=!1;const e=n=>{for(const r of n)r._animation?.started&&r._realObject&&(r._realObject.syncAnimationDelta(),t=!0),r.components&&e(r.components)};e(this._host?.components||[]),this.controlsManager.update(),this.renderThreeD(),t&&this._host?.invalidate()}renderThreeD(){this._initialized&&(this.vertexGizmoManager?.isAttached&&this.vertexGizmoManager.updateHandleScales(this.cameraManager.activeCamera),this.rendererManager.render())}setCameraView(t,e){const n=this._host;if(!n)return;const{width:r,height:i}=n.bounds,s=n.element,o=s?.clientWidth||r,a=s?.clientHeight||i;let c;c="perspective"===t?this.cameraManager.restorePerspective():this.cameraManager.setOrthoView(t,r,i,o,a),this.controlsManager.setCamera(c),this.gizmoManager.updateCamera(c),this.rendererManager.updateRenderPassCamera(c),!1!==e?.render&&this.renderThreeD(),this.onCameraViewChanged?.(t)}renderCSS3D(){const t=this.cameraManager.activeCamera;t&&this.rendererManager.renderCSS3D(t)}buildOverlays(){const t=this._host;if(!t?.element)return;t.element.appendChild(this.css3DRenderer.domElement);const e=this.rendererManager.hudCSS3DRenderer?.domElement;e&&t.element.appendChild(e)}destroy(){this.interactionManager.cleanup(),this._resizeDebouncer&&(clearTimeout(this._resizeDebouncer),this._resizeDebouncer=void 0),this._onFocus&&(window.removeEventListener("focus",this._onFocus),this._onFocus=void 0),this.vertexGizmoManager.destroy(),this.boxSelectionManager.destroy(),this.bookmarkManager.destroy(),this.gizmoManager.destroy(),this.controlsManager.destroy(),this.lightManager.destroy(),this.rendererManager.destroy(),this.cameraManager.destroy(),this.sceneManager.destroy(),this.eventManager.destroy(),this._initialized=!1}forceCleanupDragState(){this.interactionManager.forceCleanupDragState(),this.boxSelectionManager.isActive&&(this.boxSelectionManager.cancelSelection(),this.controlsManager.setEnabled(!0)),this._isSpacePanning&&(this._isSpacePanning=!1,void 0!==this._beforeSpaceMode&&this._host?.app&&(this._host.app.mode=this._beforeSpaceMode,this._beforeSpaceMode=void 0)),this._host?.element&&(this._host.element.style.cursor="")}clearAllObjects(){this.gizmoManager.detach();const t=this._host?.components||[];for(const e of t)e._realObject&&this.removeObject(e)}rebuildForHost(t,e){this.interactionManager.cleanup();try{this._cleanupEventHandlers()}catch(t){}this._host=t,this._redrawHandler=()=>this.animate(),t.root.on("redraw",this._redrawHandler),this._onComponentAdd=(t,e)=>this.addObject(e),this._onComponentRemove=(t,e)=>this.removeObject(e),t.on&&(t.on("add",this._onComponentAdd),t.on("remove",this._onComponentRemove)),t.app?.isEditMode&&t.root?.on&&(this._onSelectionChanged=t=>this._handleSelectionChanged(t),t.root.on("selected",this._onSelectionChanged),this._onAddStart=t=>{this.placementManager.start(t),this._host?.element&&(this._host.element.style.cursor="crosshair",this._host.element.focus())},this._onAddStop=()=>{this.placementManager.stop(),this._host?.element&&(this._host.element.style.cursor="")},t.root.on("addstart",this._onAddStart),t.root.on("addstop",this._onAddStop)),this.createObjects(t.components||[]),t.element&&this.interactionManager.setup(t.element,{gizmo:this.gizmoManager,controls:this.controlsManager,camera:this.cameraManager,scene:this.sceneManager,event:this.eventManager},this._buildInteractionDelegate()),this.controlsManager.setup(this.cameraManager.camera,t),t.app?.isEditMode&&t.element&&this.boxSelectionManager.setup(t.element),t.app?.isEditMode&&t.element&&this.sceneManager.scene&&(this.gizmoManager.setup(this.cameraManager.camera,t.element,this.sceneManager.scene),this._setupGizmoCallbacks()),this._onFocus||(this._onFocus=()=>this.renderThreeD(),window.addEventListener("focus",this._onFocus)),this.renderThreeD()}dispose(){const t=e=>{for(const n of e)if(!n.is3dContainer?.()){if(n.isContainer()){const e=n.components||[];t(e)}n._realObject&&(n._realObject.dispose?.(),n._realObject=void 0)}};t(this._host?.components||[]),this._decoratorOutlines.clear(),this._selectionOutlineObjects=[],this.clearArrows(),this.placementManager.destroy(),this._cleanupEventHandlers(),this.rendererManager.disposeCSS3DScene(),this.destroy(),this._host=void 0}_buildInteractionDelegate(){return{isPlacementMode:()=>this.placementManager.isActive,handlePlacementClick:t=>{if(!this._host?.root)return;const e=this.placementManager.raycastGroundPlane(t);if(e){const t=this._host,n=t.bounds.width||800,r=t.bounds.height||600,i=e.x+n/2,s=e.z+r/2;Jc.call(t.root,this.placementManager.pendingModels,{cx:i,cy:s}),t.root.trigger("addstop")}},handlePlacementHover:t=>{const e=this.placementManager.raycastGroundPlane(t);this.placementManager.updateIndicator(e),this.renderThreeD()},tryAltClickSelect:t=>{if(!this._host?.app?.isEditMode||!this._host.root)return!1;this._updateMouseNDCFromClient(t.clientX,t.clientY);const e=this.cameraManager.activeCamera;if(e&&this.sceneManager.scene){const n=this.eventManager.handleClick(e,this.sceneManager.scene,t);if(n?.component)return this._host.root.selected=[n.component],!0}return!1},captureMouseDownAltKey:t=>{this.gizmoOperationManager.captureAltKey(t)},handleClickAt:(t,e,n)=>{this._handleClickAt(n)},handleWheel:t=>this.onWheel(t),handleDblClick:t=>this.onDblClick(t),handleTouchStart:t=>this.onTouchStart(t),handleTouchMove:t=>this.onPan(t),handleTouchEnd:t=>this.onTouchEnd(t),handleKeyDown:t=>this.onKeyDown(t),handleKeyUp:t=>this._onKeyUp(t),isSpacePanning:()=>this._isSpacePanning,handleBoxSelectionStart:(t,e)=>{this.controlsManager.setEnabled(!1),this._host?.element&&(this._host.element.style.cursor="crosshair"),this.boxSelectionManager.startSelection(t,e)},handleBoxSelectionUpdate:(t,e)=>{this.boxSelectionManager.updateSelection(t,e)},tryVertexDragStart:t=>{if(!this.vertexGizmoManager.isAttached)return!1;const e=this.cameraManager.activeCamera;if(!e)return!1;const n=this.eventManager.mouse,r=this.vertexGizmoManager.onPointerDown(n,e,t);return r&&this.controlsManager.setEnabled(!1),r},handleVertexDragMove:t=>{const e=this.cameraManager.activeCamera;if(!e)return;const n=this.eventManager.mouse;this.vertexGizmoManager.onPointerMove(n,e,t),this._host?.invalidate()},handleVertexDragEnd:t=>{this.vertexGizmoManager.onPointerUp(),this.controlsManager.setEnabled(!0),this._host?.invalidate()},handleBoxSelectionEnd:t=>{this.controlsManager.setEnabled(!0),this._host?.element&&(this._host.element.style.cursor="");const e=this.cameraManager.activeCamera,n=this.sceneManager.scene,r=this._host?.components||[];if(e&&n){const i=this.boxSelectionManager.endSelection(e,n,r);if(i.length>0&&this._host?.root)if(t){const t=this._host,e=(this._host.root.selected||[]).filter(e=>e!==t);for(const t of i)e.includes(t)||e.push(t);this._host.root.selected=e}else this._host.root.selected=i}else this.boxSelectionManager.cancelSelection()}}}_handleClickAt(t){const e=this._host,n=this.cameraManager.activeCamera;if(!n||!this.sceneManager.scene)return;if(this._pathMarkers&&this._pathMarkers.children.length>0){const t=new _.Raycaster,e=this.eventManager.mouse;t.setFromCamera(e,n);const r=t.intersectObjects(this._pathMarkers.children,!0);if(r.length>0){let t=r[0].object;for(;t&&void 0===t.userData.bookmarkSlotIndex;)t=t.parent;if(t&&void 0!==t.userData.bookmarkSlotIndex)return void this.animateToSlot(t.userData.bookmarkSlotIndex)}}if(this.vertexGizmoManager?.isDragging)return this.vertexGizmoManager.onPointerUp(),this.controlsManager.setEnabled(!0),void this._host?.invalidate();const r=this.gizmoManager.isDragging;if(this.gizmoManager.forwardEvent(t,"pointerup"),r)return;const i=this.eventManager.handleClick(n,this.sceneManager.scene,t);if(e.root){const t=e.app?.mode;if(4===t||5===t){if(!i?.component){const n=4===t?"stylepastestop":"databindpastestop";e.root.trigger(n)}return}}e.app?.isEditMode&&e.root&&this._applySelection(e.root,i?.component,t.shiftKey)}_applySelection(t,e,n){if(e)if(n){const n=(t.selected||[]).slice(),r=n.indexOf(e);-1===r?n.push(e):n.splice(r,1),t.selected=n}else t.selected=[e];else n||(t.selected=[])}getObjectByRaycast(){if(!this.sceneManager.scene)return;const t=this.cameraManager.activeCamera;return t?this.eventManager.getObjectByRaycast(t,this.sceneManager.scene):void 0}getObjectsByRaycast(){if(!this.sceneManager.scene)return;const t=this.cameraManager.activeCamera;return t?this.eventManager.getObjectsByRaycast(t,this.sceneManager.scene):void 0}_updateMouseNDCFromClient(t,e){const n=this._host?.element;if(n){const r=n.getBoundingClientRect();if(r.width>0&&r.height>0){const n=t-r.left,i=e-r.top;return void this.eventManager.updateMouseNDC(n,i,0,0,r.width,r.height)}}const r=this._host;if(r){const{left:n,top:i,width:s,height:o}=r.bounds;s>0&&o>0&&this.eventManager.updateMouseNDC(t,e,n,i,Math.abs(s),Math.abs(o))}}_eventToNDC(t){const e=this._host?.element;if(e){const n=e.getBoundingClientRect();if(n.width>0&&n.height>0)return{ndcX:(t.clientX-n.left)/n.width*2-1,ndcY:-(t.clientY-n.top)/n.height*2+1}}const n=this._host;if(n?.transcoordC2S){const{width:e,height:r}=n.bounds;if(Math.abs(e)>0&&Math.abs(r)>0){const i=n.transcoordC2S(t.offsetX,t.offsetY);return{ndcX:i.x/Math.abs(e)*2-1,ndcY:-(i.y/Math.abs(r)*2-1)}}}return{ndcX:0,ndcY:0}}_updateMouseNDC(t){const e=this._host?.element;if(e){const n=e.getBoundingClientRect();if(n.width>0&&n.height>0){const e=t.clientX-n.left,r=t.clientY-n.top;return void this.eventManager.updateMouseNDC(e,r,0,0,n.width,n.height)}}const n=this._host;if(n?.transcoordC2S){const{width:e,height:r}=n.bounds;if(Math.abs(e)>0&&Math.abs(r)>0){const i=n.transcoordC2S(t.offsetX,t.offsetY);this.eventManager.updateMouseNDC(i.x,i.y,0,0,Math.abs(e),Math.abs(r))}}}onMouseUp(t){if(this.controlsManager.isActive){const e=this.gizmoManager.isDragging;if(this.gizmoManager.forwardEvent(t,"pointerup"),e)return t.stopPropagation(),!0;const n=this.cameraManager.activeCamera;this._updateMouseNDC(t);const r=this.eventManager.handleClick(n,this.sceneManager.scene,t),i=this._host;return i?.app?.isEditMode&&i.root&&this._applySelection(i.root,r?.component,t.shiftKey),t.stopPropagation(),!0}return!1}onMouseMove(t){if(this.controlsManager.isActive){this.gizmoManager.forwardEvent(t,"pointermove");const e=this.cameraManager.activeCamera;return this._updateMouseNDC(t),this.eventManager.handleHover(e,this.sceneManager.scene,t),t.stopPropagation(),!0}return!1}onMouseDown(t){return!(!this.controlsManager.isActive||(this.gizmoManager.forwardEvent(t,"pointerdown"),!this.gizmoManager.isDragging))&&(t.stopPropagation(),!0)}onMouseLeave(t){return!1}onWheel(t){if(this.controlsManager.isActive){const{ndcX:e,ndcY:n}=this._eventToNDC(t);if("perspective"!==this.cameraManager.activeView){const r=t.deltaY>0?.9:1.1;this.controlsManager.zoomOrthoAtCursor(r,e,n),this.renderThreeD()}else{const r=Math.pow(.999,-t.deltaY);this.controlsManager.dollyAtCursor(r,e,n),this.renderThreeD()}return t.stopPropagation(),!0}return!1}onDblClick(t){if(!this.controlsManager.isActive)return!1;const e=this._host,n=this.cameraManager.activeCamera;if(!n||!this.sceneManager.scene)return this.controlsManager.reset(),!0;if(e?.app?.isEditMode&&e.root){if(this.vertexGizmoManager.isAttached){const t=this.eventManager.mouse;if(this.vertexGizmoManager.onDblClick(t,n))return this._host?.invalidate(),!0}const t=this.eventManager.getObjectByRaycast(n,this.sceneManager.scene),e=t?.userData?.context?.component;if(e?.hasTextProperty)return Ch(e,this.rendererManager,()=>{this.renderThreeD(),this.renderCSS3D()}),!0}return this.controlsManager.reset(),t.stopPropagation(),!0}pinResetPosition(){this.controlsManager.pinResetPosition()}onDragStart(t){return!!this.controlsManager.isActive&&(this.gizmoManager.isDragging?(t.stopPropagation(),!0):(this.bookmarkManager.stopOrbitRotation(this.controlsManager),this.bookmarkManager.stopPlay(),this.controlsManager.onDragStart(t),t.stopPropagation(),!0))}onDragMove(t){return!!this.controlsManager.isActive&&(this.gizmoManager.isDragging?(this.gizmoManager.forwardEvent(t,"pointermove"),t.stopPropagation(),!0):(this.controlsManager.onDragMove(t),t.stopPropagation(),!0))}onDragEnd(t){return!!this.controlsManager.isActive&&(this.gizmoManager.isDragging?(this.gizmoManager.forwardEvent(t,"pointerup"),t.stopPropagation(),!0):(this.controlsManager.onDragEnd(t),t.stopPropagation(),!0))}onTouchStart(t){return!!this.controlsManager.isActive&&(this.controlsManager.onTouchStart(t),t.stopPropagation(),!0)}onPan(t){return!!this.controlsManager.isActive&&(this.controlsManager.onTouchMove(t),t.stopPropagation(),!0)}onTouchEnd(t){return!!this.controlsManager.isActive&&(this.controlsManager.onTouchEnd(t),t.stopPropagation(),!0)}onKeyDown(t){return!t.isComposing&&229!==t.keyCode&&(!!this.controlsManager.isActive&&(!!this._handleEscapeKey(t)||(!(!this._host?.app?.isEditMode||!this._handleEditModeKey(t))||(!!this._handleCursorHintKey(t)||(!!this._handleCameraAndViewKey(t)||(!!this._handlePlaybackKey(t)||(!t.shiftKey||t.ctrlKey||t.metaKey||t.altKey||"KeyB"!==t.code||!this._host?.app?.isEditMode?(this.controlsManager.onKeyDown(t),t.stopPropagation(),!0):(this.onBookmarkEditToggle?.(),t.preventDefault(),!0))))))))}_handleEscapeKey(t){if("Escape"!==t.key&&"Escape"!==t.code)return!1;if(this.placementManager.isActive&&this._host?.root)return this._host.root.trigger("addstop"),t.stopPropagation(),!0;const e=this._host?.app,n=this._host?.root;return e&&4===e.mode?(n?.trigger("stylepastestop"),!0):e&&5===e.mode?(n?.trigger("databindpastestop"),!0):!(!e?.isEditMode||!n)&&(this.gizmoManager.detach(),n.selected=[],!0)}_handleEditModeKey(t){const e=this._host.root;if(t.metaKey||t.ctrlKey)switch(t.code){case"KeyZ":{const n=this._host?.app?.commander,r=(e?.selected||[]).filter(t=>t!==this._host).map(t=>t.state?.id).filter(Boolean);if(t.shiftKey?n?.redo():n?.undo(),e&&r.length>0){const t=r.map(t=>e.findById(t)).filter(Boolean);t.length>0&&(e.selected=t)}return t.preventDefault(),!0}case"KeyC":return e&&(this._clipboard=ll.call(e)),t.preventDefault(),!0;case"KeyX":return e&&(this._clipboard=hl.call(e)),t.preventDefault(),!0;case"KeyV":return e&&this._clipboard&&dl.call(e,this._clipboard),t.preventDefault(),!0;case"KeyD":return e&&(this._clipboard=ll.call(e),this._clipboard&&dl.call(e,this._clipboard)),t.preventDefault(),!0;default:return!1}if("Enter"===t.code||"NumpadEnter"===t.code){const n=e?.selected;if(1===n?.length&&n[0].hasTextProperty)return Ch(n[0],this.rendererManager,()=>{this.renderThreeD(),this.renderCSS3D()}),t.preventDefault(),!0}switch(t.code){case"KeyW":return this.setGizmoMode("translate"),!0;case"KeyE":return this.setGizmoMode("rotate"),!0;case"KeyR":return this.setGizmoMode("scale"),!0;case"Delete":case"Backspace":return e&&el.call(e),!0}return this._handleArrowKeyMove(t,e)}_handleArrowKeyMove(t,e){const n=e?.selected;if(!n||0===n.length)return!1;const r=t.shiftKey?this._host.MPP||10:1;let i;switch(t.code){case"ArrowLeft":i={x:-r,y:0};break;case"ArrowRight":i={x:r,y:0};break;case"ArrowUp":i={x:0,y:-r};break;case"ArrowDown":i={x:0,y:r}}return!!i&&(zc.around(this._host.app.commander,()=>{n.forEach(t=>{t.stuck||t.move(i,!1)})}),t.preventDefault(),t.stopPropagation(),!0)}_handleCursorHintKey(t){return!(t.repeat||!this._host?.app?.isEditMode)&&("AltLeft"===t.code||"AltRight"===t.code?(this._host?.element&&(this._host.element.style.cursor="grab"),!0):("ShiftLeft"===t.code||"ShiftRight"===t.code)&&(this._host?.element&&(this._host.element.style.cursor="crosshair"),!0))}_handleCameraAndViewKey(t){if(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)return!1;switch(t.code){case"KeyQ":case"Digit0":return this._host?.set?.("threed",!1),t.preventDefault(),!0;case"Digit1":return this.setCameraView("perspective"),t.preventDefault(),!0;case"Digit2":return this.setCameraView("top"),t.preventDefault(),!0;case"Digit3":return this.setCameraView("front"),t.preventDefault(),!0;case"Digit4":return this.setCameraView("back"),t.preventDefault(),!0;case"Digit5":return this.setCameraView("right"),t.preventDefault(),!0;case"Digit6":return this.setCameraView("left"),t.preventDefault(),!0;case"KeyH":return this.onHelpToggle?.(),t.preventDefault(),!0;case"KeyB":return this.onBookmarkNavToggle?.(),t.preventDefault(),!0;case"KeyF":return this.onSearchToggle?.(),t.preventDefault(),!0}return!1}_handlePlaybackKey(t){return!(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)&&("KeyP"!==t.code||this._host?.app?.isEditMode?"Space"===t.code&&this._host?.app?.isEditMode?(this._isSpacePanning=!0,this._beforeSpaceMode=this._host.app.mode,this._host.app.mode=2,this._host?.element&&(this._host.element.style.cursor="grab"),t.preventDefault(),!0):"Space"!==t.code||this._host?.app?.isEditMode?"KeyO"===t.code&&!this._host?.app?.isEditMode&&(this.bookmarkManager.resetPlay(),this.bookmarkManager.toggleOrbitRotation(this.controlsManager),t.preventDefault(),!0):(this.bookmarkManager.isOrbitRotating||this.bookmarkManager.isOrbitPaused?this.bookmarkManager.toggleOrbitRotation(this.controlsManager):(this.bookmarkManager.isPlaying||this.bookmarkManager.lastPlayProgress>=0)&&this.togglePlay(),t.preventDefault(),!0):(this.bookmarkManager.stopOrbitRotation(this.controlsManager),this.restartPlay(),t.preventDefault(),!0))}_onKeyUp(t){return"AltLeft"===t.code||"AltRight"===t.code||"ShiftLeft"===t.code||"ShiftRight"===t.code?(this._host?.element&&!this._isSpacePanning&&(this._host.element.style.cursor=""),!0):!("Space"!==t.code||!this._isSpacePanning)&&(this._isSpacePanning=!1,void 0!==this._beforeSpaceMode&&this._host?.app&&(this._host.app.mode=this._beforeSpaceMode,this._beforeSpaceMode=void 0),this._host?.element&&(this._host.element.style.cursor=""),t.preventDefault(),!0)}onPinch(t){if(this.controlsManager.isActive){if("perspective"!==this.cameraManager.activeView){const e=this.cameraManager.activeCamera,n=t.scale||1;e.zoom=Math.max(.1,Math.min(20,e.zoom*n)),e.updateProjectionMatrix(),this.controlsManager.markCameraChanged(),this.renderThreeD()}else{const e=t.scale||1;Math.abs(e-1)>.01&&(this.controlsManager.dollyAtCursor(1/e,0,0),this.renderThreeD())}return t.stopPropagation(),!0}return!1}onDoubleTap(){this.controlsManager.reset()}getCameraState(){const t=this._host;if(!t)return null;const e=this.cameraManager.camera;if(!e)return null;const{width:n,height:r}=t.bounds,i=Math.floor(Math.min(n,r))||1;return{view:this.cameraManager.activeView,cameraX:e.position.x/(n||1),cameraY:e.position.z/(r||1),cameraZ:e.position.y/i}}getCameraWorldState(){const t=this.cameraManager.camera;if(!t)return null;const e=this.controlsManager.target;return{position:{x:t.position.x,y:t.position.y,z:t.position.z},target:{x:e.x,y:e.y,z:e.z}}}captureSessionState(){const t=this.cameraManager.activeView,e=this.cameraManager.camera,n=this.controlsManager.target,r={view:t};return e&&(r.perspPosition={x:e.position.x,y:e.position.y,z:e.position.z}),r.orbitTarget={x:n.x,y:n.y,z:n.z},r}captureViewportInfo(){const t=this.cameraManager.activeCamera,e=this.controlsManager.target.clone();let n=0,r=0;if(t?.fov){r=2*t.position.distanceTo(e)*Math.tan(t.fov*Math.PI/180/2),n=r*(t.aspect||1)}return{target:e,visibleWidth:n,visibleHeight:r}}restoreSessionState(t){"perspective"!==t.view&&this.setCameraView(t.view,{render:!1});const e=this.cameraManager.camera;e&&t.perspPosition&&e.position.set(t.perspPosition.x,t.perspPosition.y,t.perspPosition.z),t.orbitTarget&&this.controlsManager.restoreTarget(new _.Vector3(t.orbitTarget.x,t.orbitTarget.y,t.orbitTarget.z))}saveCameraToSlot(t){if(!this._host?.app?.isEditMode)return;const e=this.cameraManager.camera;if(!e)return;if("perspective"!==this.cameraManager.activeView)return;const n=this.controlsManager.target,r=e.position;let i=n.x,s=n.y,o=n.z;if(r.distanceTo(n)<1){const t=new _.Vector3(0,0,-1).applyQuaternion(e.quaternion);i=r.x+1*t.x,s=r.y+1*t.y,o=r.z+1*t.z}const a={position:{x:r.x,y:r.y,z:r.z},target:{x:i,y:s,z:o}};this.bookmarkManager.saveSlot(t,a),this._host?.app?.isEditMode&&this._host?.set?.("cameraBookmarks",this.bookmarkManager.exportSlots()),this.onBookmarkChanged?.()}positionCameraForViewport(t,e,n,r,i){const s=this.cameraManager.activeCamera;if(!s?.position)return;const o=(s.fov||45)*Math.PI/180,a=s.aspect||1,c=r/2/Math.tan(o/2),l=n/2/(a*Math.tan(o/2)),h=Math.max(c,l),d=i?.orbitTarget?.y??0,u=new _.Vector3(t,d,e);let p;if(i?.perspPosition&&i?.orbitTarget){const t=new _.Vector3(i.perspPosition.x,i.perspPosition.y,i.perspPosition.z),e=new _.Vector3(i.orbitTarget.x,i.orbitTarget.y,i.orbitTarget.z);p=t.sub(e).normalize()}else p=s.position.clone().normalize();s.position.copy(u.clone().add(p.multiplyScalar(h)));try{this.controlsManager.restoreTarget(u)}catch{s.lookAt(u)}this._host?.invalidate()}centerToComponent(t,e){const n=this.cameraManager.activeCamera;if(!n)return;const r=new _.Vector3,i=t._realObject;if(i?.object3d)i.object3d.getWorldPosition(r);else{const{x:e=0,y:n=0}=t.center,{width:i=0,height:s=0}=t.parent?.bounds??{};r.set(e-i/2,0,n-s/2)}const s=this.controlsManager.target,o=n.position.clone().sub(s),a=r.clone().add(o);if(!e)return n.position.copy(a),this.controlsManager.restoreTarget(r),void this._host?.invalidate();const c=n.position.clone(),l=s.clone(),h=performance.now(),d=()=>{const t=performance.now()-h,e=Math.min(t/800,1),i=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;n.position.lerpVectors(c,a,i);const s=l.clone().lerp(r,i);this.controlsManager.restoreTarget(s),this._host?.invalidate(),e<1&&requestAnimationFrame(d)};requestAnimationFrame(d)}animateToSlot(t){const e=this.cameraManager.camera;e&&(this.bookmarkManager.isPlaying&&this.bookmarkManager.stopPlay(),"perspective"!==this.cameraManager.activeView&&this.setCameraView("perspective",{render:!1}),this.bookmarkManager.animateToSlot(t,e,this.controlsManager),this.bookmarkManager.setProgressForSlot(t))}scrubPath(t){const e=this.cameraManager.camera;if(!e)return;const n=this.bookmarkManager.evaluatePath(t);n&&(e.position.copy(n.position),this.controlsManager.restoreTarget(n.target),this._host?.invalidate())}togglePlay(t=-1){const e=this.cameraManager.camera;if(e){if("perspective"!==this.cameraManager.activeView&&this.setCameraView("perspective",{render:!1}),this.bookmarkManager.isPlaying)return this.bookmarkManager.stopPlay(),void(this._pathVisible&&this.showBookmarkPath());this.hideBookmarkPath(),this.bookmarkManager.startPlay(e,this.controlsManager,2e3,1200,t)}}restartPlay(){const t=this.cameraManager.camera;t&&("perspective"!==this.cameraManager.activeView&&this.setCameraView("perspective",{render:!1}),this.bookmarkManager.stopPlay(),this.hideBookmarkPath(),this.bookmarkManager.startPlay(t,this.controlsManager,2e3,1200,-1,!0))}startAutoPlay(t){"orbit"===t?this.bookmarkManager.toggleOrbitRotation(this.controlsManager):"play"===t&&this.togglePlay()}showBookmarkPath(){this._pathVisible=!0,this.hideBookmarkPath();const t=this.sceneManager.scene;if(!t)return;const e=this.bookmarkManager.getPlayableSlots();if(0===e.length)return;const n=[];for(const t of e){const e=this.bookmarkManager.getSlot(t);e&&n.push(new _.Vector3(e.position.x,e.position.y,e.position.z))}if(n.length>=2){let e=0;for(let t=1;t<n.length;t++)e+=n[t].distanceTo(n[t-1]);const r=e/(n.length-1),i=n.length>=3?new _.CatmullRomCurve3(n,!0,"centripetal").getPoints(30*n.length):n,s=(new _.BufferGeometry).setFromPoints(i),o=new _.LineDashedMaterial({color:4890367,dashSize:.06*r,gapSize:.03*r,opacity:.5,transparent:!0,depthTest:!1});this._pathLine=new _.Line(s,o),this._pathLine.computeLineDistances(),this._pathLine.renderOrder=9999,t.add(this._pathLine)}let r;if(n.length>=2){let t=0;for(let e=1;e<n.length;e++)t+=n[e].distanceTo(n[e-1]);r=t/(n.length-1)*.08}else{const t=this.bookmarkManager.getSlot(e[0]);r=.08*(t?new _.Vector3(t.position.x,t.position.y,t.position.z).distanceTo(new _.Vector3(t.target.x,t.target.y,t.target.z)):10)}this._pathMarkers=new _.Group,this._pathMarkers.renderOrder=9999;const i=new _.MeshBasicMaterial({color:4890367,opacity:.6,transparent:!0,depthTest:!1}),s=new _.MeshBasicMaterial({color:4890367,opacity:.15,transparent:!0,depthTest:!1,side:_.DoubleSide});for(const t of e){const e=this.bookmarkManager.getSlot(t);if(!e)continue;const n=new _.Vector3(e.position.x,e.position.y,e.position.z),o=new _.Vector3(e.target.x,e.target.y,e.target.z),a=(new _.Vector3).subVectors(o,n).normalize(),c=new _.Group;c.position.copy(n);const l=(new _.Matrix4).lookAt(new _.Vector3(0,0,0),a,new _.Vector3(0,1,0));c.quaternion.setFromRotationMatrix(l);const h=.2*r,d=new _.BoxGeometry(1.2*h,.8*h,h),u=new _.Mesh(d,i);u.renderOrder=9999,c.add(u);const p=Math.max(.06*n.distanceTo(o),.5*h),f=.35*p,g=9*f/16,m=new _.BufferGeometry,y=[0,0,0,-f,g,-p,f,g,-p,f,-g,-p,-f,-g,-p],b=[0,1,2,0,2,3,0,3,4,0,4,1];m.setAttribute("position",new _.Float32BufferAttribute(y,3)),m.setIndex(b),m.computeVertexNormals();const v=new _.Mesh(m,s);v.position.z=.5*-h,v.renderOrder=9999,c.add(v);const x=new Float32Array([0,0,0,-f,g,-p,0,0,0,f,g,-p,0,0,0,f,-g,-p,0,0,0,-f,-g,-p,-f,g,-p,f,g,-p,f,g,-p,f,-g,-p,f,-g,-p,-f,-g,-p,-f,-g,-p,-f,g,-p]),w=new _.BufferGeometry;w.setAttribute("position",new _.BufferAttribute(x,3));const M=new _.LineSegments(w,new _.LineBasicMaterial({color:4890367,opacity:.5,transparent:!0,depthTest:!1}));M.position.z=.5*-h,M.renderOrder=9999,c.add(M),c.userData.bookmarkSlotIndex=t,this._pathMarkers.add(c)}t.add(this._pathMarkers),this._host?.invalidate()}hideBookmarkPath(t=!1){t&&(this._pathVisible=!1);const e=this.sceneManager.scene;if(this._pathLine&&(e?.remove(this._pathLine),this._pathLine.geometry.dispose(),this._pathLine.material.dispose(),this._pathLine=void 0),this._pathMarkers){e?.remove(this._pathMarkers);const t=new Set;this._pathMarkers.traverse(e=>{e.geometry&&e.geometry.dispose();const n=e.material;n&&!t.has(n)&&(n.dispose(),t.add(n))}),this._pathMarkers=void 0}this._host?.invalidate()}initBookmarks(){const t=this._host;if(!t)return;const e=t.state.cameraBookmarks;Array.isArray(e)&&this.bookmarkManager.importSlots(e),this.bookmarkManager.setCallbacks(()=>this._host?.invalidate())}onchange(t){if(t.hasOwnProperty("autoRotate")&&this.controlsManager.setAutoRotate(t.autoRotate),t.hasOwnProperty("fov")||t.hasOwnProperty("near")||t.hasOwnProperty("far")){const t=this._host;if(t){const{near:e,far:n,fov:r}=t.state;this.cameraManager.updateProperties({near:e,far:n,fov:r}),this.controlsManager.markCameraChanged()}}let e=!1;if(t.hasOwnProperty("hemiIntensity")&&(this.lightManager.updateHemisphere({intensity:t.hemiIntensity}),e=!0),t.hasOwnProperty("dirLightEnabled")){const n=this._host;n&&this.lightManager.setDirectionalEnabled(t.dirLightEnabled,{color:n.state.dirLightColor,intensity:n.state.dirLightIntensity}),e=!0}(t.hasOwnProperty("dirLightColor")||t.hasOwnProperty("dirLightIntensity"))&&(this.lightManager.updateDirectional({color:t.dirLightColor,intensity:t.dirLightIntensity}),e=!0),e&&this.renderThreeD(),(t.hasOwnProperty("fillStyle")||t.hasOwnProperty("floorMaterial3d"))&&(this.sceneManager.updateFloor(this._host),this.renderThreeD()),(t.hasOwnProperty("sky")||t.hasOwnProperty("skyColor"))&&(this.sceneManager.setSky(this._host.state.sky,this._host.state.skyColor),this.renderThreeD())}get domElement(){return this.rendererManager.domElement}getRendererSize(){return this.rendererManager.getSize()}showWebglNoSupportText(t,e,n){t.save(),t.font=e/20+"px Arial",t.textAlign="center",t.fillText("WebGL no support",e/2-e/40,n/2),t.restore()}showDebugFPS(t){t.font="100px Arial",t.textAlign="center",t.fillStyle="black",t.globalAlpha=.5,t.fillText(String(ql()),100,100)}get decoratorOutlines(){return this._decoratorOutlines}addOutline(t){this._decoratorOutlines.add(t),this._syncOutlinePass(),this._host?.invalidate()}removeOutline(t){this._decoratorOutlines.delete(t),this._syncOutlinePass(),this._host?.invalidate()}clearOutlines(){this._decoratorOutlines.clear(),this._syncOutlinePass(),this._host?.invalidate()}addArrow(t,e,n,r={}){this.removeArrow(t);const i=e._realObject,s=n._realObject;if(!i?.object3d||!s?.object3d)return;const o=new _.Vector3,a=new _.Vector3;i.object3d.getWorldPosition(o),s.object3d.getWorldPosition(a),o.y+=1,a.y+=1;const c=this.rendererManager.getSize(),l=nh(o,a,r,new _.Vector2(c.width,c.height));l.name=`arrow-${t}`,l.userData._arrowStyle=r,this.sceneManager.scene?.add(l),this._arrows.set(t,l),this._host?.invalidate()}removeArrow(t){const e=this._arrows.get(t);e&&(e.traverse(t=>{if(t instanceof r.Line2)return t.geometry.dispose(),void t.material.dispose();if(t instanceof _.Sprite){const e=t.material.map;if(e){e.dispose();const t=e.source?.data;t instanceof HTMLCanvasElement&&(t.width=0,t.height=0)}return void t.material.dispose()}(t instanceof _.Mesh||t instanceof _.Line)&&(t.geometry.dispose(),t.material instanceof _.Material&&t.material.dispose())}),e.removeFromParent(),this._arrows.delete(t),this._host?.invalidate())}clearArrows(){for(const t of this._arrows.keys())this.removeArrow(t)}updateArrow(t,e,n){const r=this._getArrowStyle(t);r&&this.addArrow(t,e,n,r)}_getArrowStyle(t){const e=this._arrows.get(t);return e?e.userData._arrowStyle??null:null}highlightBookmarkMarker(t){this._highlightedMarkerIndex!==t&&(this._highlightedMarkerIndex=t,this._syncOutlinePass(),this._host?.invalidate())}clearBookmarkMarkerHighlight(){-1!==this._highlightedMarkerIndex&&(this._highlightedMarkerIndex=-1,this._syncOutlinePass(),this._host?.invalidate())}_syncOutlinePass(){const t=[...this._selectionOutlineObjects];for(const e of this._decoratorOutlines){const n=e._realObject;n?.object3d&&!t.includes(n.object3d)&&t.push(n.object3d)}if(this._highlightedMarkerIndex>=0&&this._pathMarkers)for(const e of this._pathMarkers.children)if(e.userData.bookmarkSlotIndex===this._highlightedMarkerIndex){e.traverse(e=>{e.isMesh&&t.push(e)});break}this.rendererManager.setOutlineObjects(t)}_handleSelectionChanged(t){const e=t.filter(t=>t!==this._host&&t._realObject);if(e.length>=1){const t=e[0]._realObject;t?.object3d&&t.gizmoTransformable?this.gizmoManager.attached&&this.gizmoManager.attach(t.object3d):this.gizmoManager.detach()}else this.gizmoManager.detach();const n=e.filter(t=>t.mutable&&t.path);n.length>0&&this.sceneManager.scene?this.vertexGizmoManager.attachMultiple(n,this.sceneManager.scene,this._host?.app?.commander):this.vertexGizmoManager.detach(),this._updateSelectionOutline(e),this._host?.invalidate()}_updateSelectionOutline(t){this._selectionOutlineObjects=[];for(const e of t){const t=e._realObject;t?.object3d&&this._selectionOutlineObjects.push(t.object3d)}this._syncOutlinePass()}}Wa.register("three",{reflow:function(t){},capturables:function(t){return t.state.threed?[]:t.components},drawables:function(t){return t.state.threed?[]:t.components},isStuck:function(t){return!1}});const Zh={x:1,y:1},Jh={x:0,y:0},td='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M4 5l12-1v12l-12-1z"/>\n <circle cx="10" cy="10" r="1.5"/>\n</svg>',ed='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <rect x="4" y="4" width="12" height="12" rx="1"/>\n <path d="M10 2v2M10 16v2"/>\n <path d="M10 7v3l2-1.5" opacity="0.5"/>\n</svg>',nd='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M4 14l2-10h8l2 10z"/>\n <path d="M6 4h8" stroke-width="2"/>\n</svg>',rd='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M4 6l2 10h8l2-10z"/>\n <path d="M6 16h8" stroke-width="2"/>\n</svg>',id='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M6 4l10 2v8l-10 2z"/>\n <path d="M16 6v8" stroke-width="2"/>\n</svg>',sd='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M14 4L4 6v8l10 2z"/>\n <path d="M4 6v8" stroke-width="2"/>\n</svg>',od={mutable:!1,resizable:!0,rotatable:!1,properties:[{type:"number",label:"width",name:"width"},{type:"number",label:"height",name:"height"},{type:"select",label:"fit-mode",name:"fitMode",property:{options:["ratio","both","width","height","center","none"]}}]};class ad extends mc{get nature(){return od}get is3dMode(){return!!this._threeCapability?.isInitialized}is3dContainer(){return this.is3dMode}get gizmoMode(){return this._threeCapability?.gizmoMode}setGizmoMode(t){this._threeCapability?.setGizmoMode(t)}get scene3d(){return this._threeCapability?.scene3d}get renderer3d(){return this._threeCapability?.renderer3d}get activeCamera3d(){return this._threeCapability?.activeCamera}get mixer(){return this._threeCapability?.mixer}addArrow3D(t,e,n,r){this._threeCapability?.addArrow(t,e,n,r)}removeArrow3D(t){this._threeCapability?.removeArrow(t)}clearArrows3D(){this._threeCapability?.clearArrows()}_buildLightingConfig(){const t=this.state,e={hemisphere:{skyColor:16777215,groundColor:4473924,intensity:t.hemiIntensity??1}};return!1!==t.dirLightEnabled&&(e.directional={color:t.dirLightColor||"#ffffff",intensity:t.dirLightIntensity??.8,attachToCamera:!0,castShadow:!1!==t.dirShadowEnabled,shadowMapSize:t.dirShadowMapSize??2048,shadowBias:t.dirShadowBias??-5e-4}),e}_hide2DLayers(){this.canvas&&(this.canvas.style.display="none"),this._overlay&&(this._overlay.style.display="none"),this._auxCanvas&&(this._auxCanvas.style.display="none"),this._decoratorAuxOverlay&&(this._decoratorAuxOverlay.style.display="none");for(const t of this.root?.assist_layers||[])t.element&&(t.element.style.display="none")}get _hasZoomHandler(){return(this.root?.model?.handlers||[]).includes("zoom-handler")}get _needsViewportSync(){return!!this.app?.isEditMode||this._hasZoomHandler}_activateThreeD(t=!1){this._threeCapability&&this._deactivateThreeD(),t&&!this._needsViewportSync&&(this._saved2DViewport={scale:{...this.get("scale")||{x:1,y:1}},translate:{...this.get("translate")||{x:0,y:0}}}),this._threeCapability=new Qh,this._threeCapability.init(this,{lightingConfig:this._buildLightingConfig(),css3DSceneAttribute:"model-layer:css3d-renderer"}),this._hide2DLayers();const e=bs.getInstance(),n=[];this.decoratorOverlay&&(n.push(...e.getTargetsWithType(this.decoratorOverlay,"border-highlighting")),e.removeAllFromOverlay(this.decoratorOverlay,"border-highlighting")),this.decoratorAuxOverlay&&(n.push(...e.getTargetsWithType(this.decoratorAuxOverlay,"border-highlighting")),e.removeAllFromOverlay(this.decoratorAuxOverlay,"border-highlighting"));for(const t of n)this._threeCapability.addOutline(t);if(this._threeCapability.domElement&&this.element){const t=this._threeCapability.domElement;t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.pointerEvents="none",t.setAttribute("scene","model-layer-webgl");const e=this._decoratorOverlay||this.element.firstChild;this.element.insertBefore(t,e)}if(this._threeCapability.buildOverlays(),t&&this._needsViewportSync)this._initCameraFrom2DViewport();else if(this._lastCameraState)this._threeCapability.restoreSessionState(this._lastCameraState);else{const t=this.model.initialCameraView;t&&"perspective"!==t&&this._threeCapability.setCameraView(t,{render:!1})}if(this._pendingCameraView&&(this._threeCapability.setCameraView(this._pendingCameraView,{render:!1}),delete this._pendingCameraView),this._threeCapability.initBookmarks(),!this.app?.isEditMode){const t=this.model?.cameraAutoPlay;"orbit"!==t&&"play"!==t||this._threeCapability.startAutoPlay(t)}this.app?.isEditMode&&this._createToolbar(),this._registerPopupCallbacks();const r=this.root;r?.selected?.length>0&&this._threeCapability._handleSelectionChanged(r.selected),this._resizeThreeD(!0),this.element&&"function"==typeof this.element.focus&&this.element.focus()}_createToolbar(){if(!this.element)return;this._removeToolbar();const t=!!this._threeCapability,e=document.createElement("div");e.setAttribute("scene","threed-toolbar"),e.style.cssText=["position:absolute","top:12px","left:12px","display:flex","flex-direction:column","gap:1px","padding:4px","background:rgba(30,30,30,0.92)","border:1px solid rgba(255,255,255,0.08)","border-radius:8px","pointer-events:auto","backdrop-filter:blur(8px)","-webkit-backdrop-filter:blur(8px)","box-shadow:0 4px 16px rgba(0,0,0,0.4),inset 0 1px 0 rgba(255,255,255,0.05)","user-select:none"].join(";");const n=["width:32px","height:32px","display:flex","align-items:center","justify-content:center","border-radius:5px","cursor:pointer","transition:all 0.12s ease","position:relative"].join(";"),r=(t,e)=>{const r=document.createElement("div");return r.innerHTML=t,r.title=e,r.style.cssText=n,this._applyButtonStyle(r,!1),r.addEventListener("mouseenter",()=>{r.dataset.active||(r.style.background="rgba(255,255,255,0.1)")}),r.addEventListener("mouseleave",()=>{this._applyButtonStyle(r,!!r.dataset.active)}),r},i=()=>{const t=document.createElement("div");return t.style.cssText="height:1px;margin:3px 4px;background:rgba(255,255,255,0.1)",t},s=r(t?'<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <rect x="3" y="3" width="14" height="14" rx="1.5"/>\n <line x1="3" y1="10" x2="17" y2="10" opacity="0.4"/>\n <line x1="10" y1="3" x2="10" y2="17" opacity="0.4"/>\n </svg>':'<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M10 2l7 4v8l-7 4-7-4V6l7-4z"/>\n <path d="M10 10l7-4M10 10v8M10 10L3 6"/>\n </svg>',t?"2D Mode":"3D Mode");if(this._applyToggleStyle(s,t),s.addEventListener("mouseenter",()=>{s.style.background=t?"rgba(255,160,60,0.35)":"rgba(255,160,60,0.25)"}),s.addEventListener("mouseleave",()=>{this._applyToggleStyle(s,t)}),s.addEventListener("click",()=>{this.set("threed",!this.model.threed)}),e.appendChild(s),!t)return e.addEventListener("mousedown",t=>t.stopPropagation()),e.addEventListener("mouseup",t=>t.stopPropagation()),this.target.appendChild(e),void(this._toolbar=e);e.appendChild(i());const o=this._threeCapability,a=document.createElement("div");a.style.cssText="display:flex;flex-direction:column;gap:1px";const c=o.getCameraState()?.view??"perspective",l=[{view:"perspective",icon:td,title:"Perspective"},{view:"top",icon:ed,title:"Top"},{view:"front",icon:nd,title:"Front"},{view:"back",icon:rd,title:"Back"},{view:"right",icon:id,title:"Right"},{view:"left",icon:sd,title:"Left"}],h=[];for(const{view:t,icon:e,title:n}of l){const i=r(e,n);i.dataset.view=t,t===c&&(this._applyButtonStyle(i,!0),i.dataset.active="1"),i.addEventListener("click",()=>{this._threeCapability?.setCameraView(t)}),h.push(i),a.appendChild(i)}a.appendChild(i());const d=r('<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M10 2 L13 5 L12 10 L15 13 L5 13 L8 10 L7 5 Z"/>\n <line x1="10" y1="13" x2="10" y2="18"/>\n </svg>',"Pin Camera View");d.addEventListener("click",()=>{const t=this._threeCapability?.getCameraState();t&&(this.set("cameraX",t.cameraX),this.set("cameraY",t.cameraY),this.set("cameraZ",t.cameraZ),this._threeCapability?.pinResetPosition())}),a.appendChild(d),e.appendChild(a),this._cameraButtons=h,o.onGizmoAttachChanged=t=>{this.root?.trigger("gizmoattach",t)},o.onCameraViewChanged=t=>{this._updateCameraButtons(t)},o.onGizmoModeChanged=t=>{this.root?.trigger("gizmomode",t)},e.addEventListener("mousedown",t=>{t.stopPropagation(),t.preventDefault()}),e.addEventListener("mouseup",t=>t.stopPropagation()),this.target.appendChild(e),this._toolbar=e}_applyToggleStyle(t,e){e?(t.style.background="rgba(255,140,40,0.3)",t.style.color="#ffaa44",t.style.boxShadow="inset 0 0 0 1.5px rgba(255,140,40,0.5)"):(t.style.background="rgba(255,140,40,0.15)",t.style.color="#cc8833",t.style.boxShadow="inset 0 0 0 1.5px rgba(255,140,40,0.3)")}_applyButtonStyle(t,e){e?(t.style.background="rgba(74,158,255,0.25)",t.style.color="#4a9eff",t.style.boxShadow="inset 0 0 0 1.5px rgba(74,158,255,0.5)",t.dataset.active="1"):(t.style.background="transparent",t.style.color="rgba(255,255,255,0.55)",t.style.boxShadow="none",delete t.dataset.active)}_updateCameraButtons(t){this._cameraButtons?.forEach(e=>{this._applyButtonStyle(e,e.dataset.view===t)})}_registerPopupCallbacks(){const t=this._threeCapability;t&&(t.onHelpToggle=()=>this._toggleHelpPanel(),t.onSearchToggle=()=>this.onSearchToggle?.(),t.onBookmarkNavToggle=()=>this._toggleBookmarkNav(),t.onBookmarkEditToggle=()=>this._toggleBookmarkEdit())}_closeFloatingPopup(){this._floatingPopupCloseHandler&&(this.target?.removeEventListener("mousedown",this._floatingPopupCloseHandler,!0),this._floatingPopupCloseHandler=void 0),this._floatingPopup?.parentNode&&this._floatingPopup.parentNode.removeChild(this._floatingPopup),this._floatingPopup=void 0}_showFloatingPopup(t,e=!1){this._closeFloatingPopup(),this._floatingPopup=t,e||(this._floatingPopupCloseHandler=e=>{t.contains(e.target)||this._closeFloatingPopup()},setTimeout(()=>{this.target?.addEventListener("mousedown",this._floatingPopupCloseHandler,!0)},0)),t.addEventListener("mousedown",t=>{t.stopPropagation();const e=t.target?.tagName;"INPUT"!==e&&"TEXTAREA"!==e&&"SELECT"!==e&&t.preventDefault()}),t.addEventListener("mouseup",t=>t.stopPropagation()),this._makePopupDraggable(t),this.target.appendChild(t)}_makePopupDraggable(t){let e=0,n=0,r=0,i=0;const s=s=>{const o=s.clientX-e,a=s.clientY-n;t.style.left=r+o+"px",t.style.top=i+a+"px"},o=e=>{t.releasePointerCapture(e.pointerId),t.removeEventListener("pointermove",s),t.removeEventListener("pointerup",o),t.style.cursor=""};t.addEventListener("pointerdown",a=>{const c=a.target,l=c.tagName?.toLowerCase();if("button"===l||"input"===l||"select"===l||"pointer"===c.style.cursor)return;if(c.closest("[data-drag-handle]"))return;const h=t.getBoundingClientRect(),d=t.parentElement.getBoundingClientRect();r=h.left-d.left,i=h.top-d.top,t.style.left=r+"px",t.style.top=i+"px",t.style.right="auto",t.style.bottom="auto",t.style.transform="none",e=a.clientX,n=a.clientY,t.style.cursor="grabbing",t.setPointerCapture(a.pointerId),t.addEventListener("pointermove",s),t.addEventListener("pointerup",o)})}_toggleHelpPanel(){if("help"===this._floatingPopup?.dataset.popupType)return void this._closeFloatingPopup();const t=!!this.app?.isEditMode,e=document.createElement("div");e.dataset.popupType="help",e.style.cssText=["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)","max-width:min(560px, calc(100% - 40px))","max-height:calc(100% - 40px)","overflow-y:auto","padding:16px 20px","background:rgba(30,30,30,0.94)","border:1px solid rgba(255,255,255,0.08)","border-radius:10px","pointer-events:auto","backdrop-filter:blur(8px)","-webkit-backdrop-filter:blur(8px)","box-shadow:0 4px 20px rgba(0,0,0,0.5)","user-select:none","color:rgba(255,255,255,0.85)","font:12px/1.6 -apple-system,BlinkMacSystemFont,sans-serif","z-index:200"].join(";");const n=document.createElement("div");n.textContent="×",n.style.cssText="position:absolute;top:8px;right:12px;cursor:pointer;font-size:18px;color:rgba(255,255,255,0.4);line-height:1",n.addEventListener("click",()=>this._closeFloatingPopup()),n.addEventListener("mouseenter",()=>{n.style.color="#fff"}),n.addEventListener("mouseleave",()=>{n.style.color="rgba(255,255,255,0.4)"}),e.appendChild(n);const r=document.createElement("div");r.textContent="Help",r.style.cssText="font-size:13px;font-weight:600;color:#4a9eff;margin-bottom:12px",e.appendChild(r);const i=document.createElement("div");i.style.cssText="display:grid;grid-template-columns:1fr 1fr;gap:0 24px",e.appendChild(i);const s=[{label:"Camera",items:[{key:"1",desc:"Perspective",icon:td},{key:"2",desc:"Top",icon:ed},{key:"3",desc:"Front",icon:nd},{key:"4",desc:"Back",icon:rd},{key:"5",desc:"Right",icon:id},{key:"6",desc:"Left",icon:sd},{key:"0 / Q",desc:"Exit 3D"}]},{label:"Bookmarks",items:[{key:"B",desc:"Bookmark navigator"},{key:"Shift+B",desc:"Bookmark editor",editOnly:!0},{key:"P",desc:"Play tour",viewOnly:!0},{key:"O",desc:"Orbit rotation",viewOnly:!0},{key:"Space",desc:"Pan mode (edit) / Pause (view)"}]},{label:"Navigation",items:[{key:"Drag",desc:"Rotate camera"},{key:"Alt+Drag",desc:"Pan camera"},{key:"Space+Drag",desc:"Pan camera (no select)",editOnly:!0},{key:"Shift+Drag",desc:"Box select",editOnly:!0},{key:"Scroll",desc:"Dolly zoom"},{key:"DblClick",desc:"Reset camera"},{key:"Arrows",desc:"Pan camera"}]},{label:"Edit",items:[{key:"W",desc:"Move gizmo",editOnly:!0},{key:"E",desc:"Rotate gizmo",editOnly:!0},{key:"R",desc:"Scale gizmo",editOnly:!0},{key:"Ctrl+Z",desc:"Undo",editOnly:!0},{key:"Ctrl+Shift+Z",desc:"Redo",editOnly:!0},{key:"Ctrl+C/X/V",desc:"Copy / Cut / Paste",editOnly:!0},{key:"Del",desc:"Delete selected",editOnly:!0},{key:"Esc",desc:"Deselect all",editOnly:!0}]},{label:"Misc",items:[{key:"H",desc:"This help"},{key:"F",desc:"Search"}]}].map(e=>({...e,items:e.items.filter(e=>!(e.editOnly&&!t)&&(!e.viewOnly||!t))})).filter(t=>t.items.length>0),o=s.reduce((t,e)=>t+e.items.length+1,0);let a=0,c=s.length;for(let t=0;t<s.length;t++)if(a+=s[t].items.length+1,a>=o/2){c=t+1;break}const l=[s.slice(0,c),s.slice(c)];for(const t of l){const e=document.createElement("div");let n=!0;for(const r of t){if(!n){const t=document.createElement("div");t.style.cssText="height:1px;margin:8px 0;background:rgba(255,255,255,0.08)",e.appendChild(t)}n=!1;const t=document.createElement("div");t.textContent=r.label,t.style.cssText="font-size:10px;font-weight:700;text-transform:uppercase;color:rgba(255,255,255,0.45);margin:0 0 5px;letter-spacing:0.8px",e.appendChild(t);for(const t of r.items){const n=document.createElement("div");n.style.cssText="display:flex;justify-content:space-between;align-items:center;padding:2px 0;gap:12px";const r=document.createElement("span");r.style.cssText="display:inline-flex;gap:2px;flex-shrink:0";for(const e of t.key.split("+")){const n=document.createElement("kbd");if(n.textContent=e.trim(),n.style.cssText="font-size:10px;font-family:monospace;padding:1px 5px;border-radius:3px;background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.12);color:rgba(255,255,255,0.65);line-height:1.4",r.appendChild(n),e!==t.key.split("+").at(-1)){const t=document.createElement("span");t.textContent="+",t.style.cssText="color:rgba(255,255,255,0.2);font-size:10px;margin:0 1px",r.appendChild(t)}}const i=document.createElement("span");if(i.style.cssText="font-size:11px;color:rgba(255,255,255,0.7);text-align:right;white-space:nowrap;display:inline-flex;align-items:center;gap:4px",i.appendChild(document.createTextNode(t.desc)),t.icon){const e=document.createElement("span");e.innerHTML=t.icon,e.style.cssText="display:inline-flex;opacity:0.6",i.appendChild(e)}n.appendChild(r),n.appendChild(i),e.appendChild(n)}}i.appendChild(e)}this._showFloatingPopup(e)}_toggleBookmarkNav(){"bookmark-nav"!==this._floatingPopup?.dataset.popupType?this._buildBookmarkPopup("bookmark-nav"):this._closeFloatingPopup()}_toggleBookmarkEdit(){"bookmark-edit"!==this._floatingPopup?.dataset.popupType?this._buildBookmarkPopup("bookmark-edit"):this._closeFloatingPopup()}_buildBookmarkPopup(t){const e=this._threeCapability;if(!e)return;const n="bookmark-nav"===t,r=!!this.app?.isEditMode,i=document.createElement("div");i.dataset.popupType=t,i.tabIndex=-1,i.style.cssText=["position:absolute",n?"bottom:12px":"top:12px","right:12px","min-width:"+(n?"140px":"200px"),"padding:10px 12px","background:rgba(30,30,30,0.94)","border:1px solid rgba(255,255,255,0.08)","border-radius:10px","pointer-events:auto","backdrop-filter:blur(8px)","-webkit-backdrop-filter:blur(8px)","box-shadow:0 4px 20px rgba(0,0,0,0.5)","user-select:none","color:rgba(255,255,255,0.85)","font:12px/1.5 -apple-system,BlinkMacSystemFont,sans-serif","z-index:200"].join(";");const s=document.createElement("div");s.textContent="×",s.style.cssText="position:absolute;top:6px;right:10px;cursor:pointer;font-size:18px;color:rgba(255,255,255,0.4);line-height:1",s.addEventListener("click",()=>this._closeFloatingPopup()),s.addEventListener("mouseenter",()=>{s.style.color="#fff"}),s.addEventListener("mouseleave",()=>{s.style.color="rgba(255,255,255,0.4)"}),i.appendChild(s);const o=document.createElement("div");o.textContent="Bookmarks",o.style.cssText="font-size:13px;font-weight:600;color:#4a9eff;margin-bottom:8px;cursor:grab",i.appendChild(o);const a=document.createElement("div");a.style.cssText="display:flex;flex-direction:column;gap:2px",i.appendChild(a);const c=e.bookmarkManager,l=()=>{r&&this.set?.("cameraBookmarks",c.exportSlots()),e.onBookmarkChanged?.()},h="border:none;background:transparent;color:inherit;cursor:pointer;padding:2px 4px;border-radius:4px;font-size:13px;line-height:1;display:flex;align-items:center;justify-content:center;width:24px;height:24px",d=t=>{const e=28,n=window.devicePixelRatio||1,r=document.createElement("canvas");r.width=e*n,r.height=e*n,r.style.cssText="width:28px;height:28px;flex-shrink:0;border-radius:50%;background:rgba(0,0,0,0.3)";const i=r.getContext("2d");i.scale(n,n);const s=14,o=14,a=12,c=t.position.x-t.target.x,l=t.position.z-t.target.z,h=t.position.y-t.target.y,d=Math.sqrt(c*c+l*l),u=Math.sqrt(c*c+h*h+l*l),p=u>.001?Math.max(0,h/u):0;let f=0,g=0;d>.001&&(f=c/d,g=l/d);const m=1-.6*p,y=s+f*a*.7*m,b=o+g*a*.7*m;i.strokeStyle="rgba(255,255,255,0.12)",i.lineWidth=1,i.beginPath(),i.arc(s,o,a,0,2*Math.PI),i.stroke(),i.strokeStyle="rgba(255,255,255,0.06)",i.beginPath(),i.moveTo(s,2),i.lineTo(s,26),i.moveTo(2,o),i.lineTo(26,o),i.stroke(),i.fillStyle="rgba(255,255,255,0.25)",i.beginPath(),i.arc(s,o,1.5,0,2*Math.PI),i.fill(),i.strokeStyle=`rgba(74,158,255,${.2+.2*p})`,i.lineWidth=1,i.beginPath(),i.moveTo(y,b),i.lineTo(s,o),i.stroke();const v=.6+.4*p;i.fillStyle=`rgba(74,158,255,${v})`,i.beginPath(),i.arc(y,b,3,0,2*Math.PI),i.fill();const _=Math.atan2(g,f),x=Math.PI/8;return i.fillStyle="rgba(74,158,255,0.08)",i.beginPath(),i.moveTo(y,b),i.arc(y,b,.6*a,_+Math.PI-x,_+Math.PI+x),i.closePath(),i.fill(),r},u=()=>{const t=e.getCameraWorldState();if(!t)return-1;const n=.01;for(let e=1;e<=9;e++){const r=c.getSlot(e);if(r&&(Math.abs(t.position.x-r.position.x)<n&&Math.abs(t.position.y-r.position.y)<n&&Math.abs(t.position.z-r.position.z)<n&&Math.abs(t.target.x-r.target.x)<n&&Math.abs(t.target.y-r.target.y)<n&&Math.abs(t.target.z-r.target.z)<n))return e}return-1};let p,f,g=-1;const m=()=>{a.innerHTML="";let t=!1;const r=u(),i=Array.from({length:9},(t,e)=>e+1);for(const s of i){const i=c.getSlot(s),o=!!i,u=s===r;if(n&&!o)continue;t=t||o;const p=document.createElement("div"),f=u?"rgba(74,158,255,0.1)":"transparent";if(p.style.cssText=`display:flex;align-items:center;gap:6px;padding:${n?"6px 8px":"3px 4px"};border-radius:6px;transition:background 0.15s;background:${f}${u?";box-shadow:inset 0 0 0 1px rgba(74,158,255,0.25)":""}`,p.dataset.active=u?"1":"",p.addEventListener("mouseenter",()=>{p.style.background=p.dataset.active?"rgba(74,158,255,0.15)":"rgba(255,255,255,0.06)",!n&&o&&e.highlightBookmarkMarker(s)}),p.addEventListener("mouseleave",()=>{const t=p.dataset.active;p.style.background=t?"rgba(74,158,255,0.1)":"transparent",n||e.clearBookmarkMarkerHighlight()}),n){if(o&&i){const t=d(i);t.style.pointerEvents="none",p.appendChild(t)}const t=document.createElement("span");t.textContent=i?.name||"noname",t.style.cssText=`flex:1;color:${i?.name?"rgba(255,255,255,0.8)":"rgba(255,255,255,0.35)"};font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none;${i?.name?"":"font-style:italic"}`,p.appendChild(t),p.style.cursor="pointer",p.addEventListener("click",()=>{e.animateToSlot(s)})}else{const t=document.createElement("div");t.textContent="⠿";const n=o,r=o?"color:rgba(255,255,255,0.3)":"color:rgba(255,255,255,0.12)";if(t.style.cssText=`width:16px;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;user-select:none;${r}${n?";cursor:grab":""}`,n&&(t.dataset.dragHandle="1",t.addEventListener("mouseenter",()=>{t.style.color="rgba(255,255,255,0.6)"}),t.addEventListener("mouseleave",()=>{t.style.color="rgba(255,255,255,0.3)"})),p.appendChild(t),o&&i){const t=d(i);t.style.pointerEvents="none",p.appendChild(t)}o&&(p.style.cursor="pointer",p.addEventListener("click",t=>{const n=t.target.tagName;"INPUT"!==n&&"BUTTON"!==n&&e.animateToSlot(s)}));const a=document.createElement("input");a.type="text",a.value=i?.name||"",a.placeholder=o?"noname":"Empty",a.style.cssText=`width:80px;font-size:12px;color:${o?"rgba(255,255,255,0.7)":"rgba(255,255,255,0.3)"};background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,0.1);outline:none;padding:2px 0;min-width:0`,a.addEventListener("focus",()=>{a.style.borderBottomColor="rgba(74,158,255,0.5)",a.style.color="rgba(255,255,255,0.9)"}),a.addEventListener("blur",()=>{a.style.borderBottomColor="rgba(255,255,255,0.1)",a.style.color=o?"rgba(255,255,255,0.7)":"rgba(255,255,255,0.3)",o&&(c.renameSlot(s,a.value.trim()),l())}),a.addEventListener("keydown",t=>{t.stopPropagation(),t.isComposing||"Enter"!==t.key||a.blur()}),p.appendChild(a);const u=document.createElement("div");if(u.style.cssText="display:flex;gap:2px;flex-shrink:0",o){const t=document.createElement("button");t.textContent="📌",t.title="Overwrite with current view",t.style.cssText=h+";color:#ffaa44",t.addEventListener("mouseenter",()=>{t.style.background="rgba(255,170,68,0.15)"}),t.addEventListener("mouseleave",()=>{t.style.background="transparent"}),t.addEventListener("click",()=>{e.saveCameraToSlot(s),m()}),u.appendChild(t);const n=document.createElement("button");n.textContent="🗑",n.title="Delete this slot",n.style.cssText=h+";color:#ff6b6b",n.addEventListener("mouseenter",()=>{n.style.background="rgba(255,107,107,0.15)"}),n.addEventListener("mouseleave",()=>{n.style.background="transparent"}),n.addEventListener("click",()=>{c.clearSlot(s),l(),m()}),u.appendChild(n);const r=document.createElement("button");r.textContent="⋮",r.title="Playlist settings",r.style.cssText=h+";color:rgba(255,255,255,0.35);font-size:14px",r.addEventListener("mouseenter",()=>{r.style.background="rgba(255,255,255,0.08)"}),r.addEventListener("mouseleave",()=>{r.style.background="transparent"}),u.appendChild(r)}else{const t=document.createElement("button");t.textContent="📌",t.title="Save current view here",t.style.cssText=h+";color:#4ade80",t.addEventListener("mouseenter",()=>{t.style.background="rgba(74,222,128,0.15)"}),t.addEventListener("mouseleave",()=>{t.style.background="transparent"}),t.addEventListener("click",()=>{e.saveCameraToSlot(s),m()}),u.appendChild(t)}p.appendChild(u)}const y=document.createElement("div");if(y.dataset.slotIndex=String(s),y.dataset.filled=o?"1":"",y.appendChild(p),!n&&o){const t=p.querySelector("[data-drag-handle]");t&&t.addEventListener("pointerdown",e=>{e.preventDefault(),e.stopPropagation(),y.style.opacity="0.3",y.style.pointerEvents="none",y.style.outline="1px dashed rgba(74,158,255,0.4)",y.style.borderRadius="4px",t.style.cursor="grabbing";const n=document.createElement("div");n.style.cssText="height:2px;background:#4a9eff;border-radius:1px;margin:1px 0",t.setPointerCapture(e.pointerId);const r=t=>{const e=Array.from(a.querySelectorAll('[data-slot-index][data-filled="1"]'));n.parentNode&&n.parentNode.removeChild(n);let r=null;for(const n of e){if(n===y)continue;const e=n.getBoundingClientRect();if(t.clientY<e.top+e.height/2){r=n;break}}if(r)a.insertBefore(n,r);else{const t=e[e.length-1];t&&t.after(n)}},i=e=>{t.releasePointerCapture(e.pointerId),t.removeEventListener("pointermove",r),t.removeEventListener("pointerup",i),y.style.cssText="",t.style.cursor="grab";const s=Array.from(a.querySelectorAll('[data-slot-index][data-filled="1"]'));n.parentNode&&(a.insertBefore(y,n),n.parentNode.removeChild(n));const o=Array.from(a.querySelectorAll('[data-slot-index][data-filled="1"]')).map(t=>parseInt(t.dataset.slotIndex)).map(t=>{const e=c.getSlot(t);return e?{...e,name:e.name}:void 0}),h=s.map(t=>parseInt(t.dataset.slotIndex)).sort((t,e)=>t-e);o.forEach((t,e)=>{const n=h[e];t?c.saveSlot(n,t):c.clearSlot(n)}),l(),m()};t.addEventListener("pointermove",r),t.addEventListener("pointerup",i)})}if(!n&&o&&i){const t=document.createElement("div");t.dataset.slotDetail="1";const e=g===s;t.style.cssText=`display:${e?"block":"none"};margin:2px 0 4px 26px;padding:6px 8px;background:rgba(255,255,255,0.03);border-radius:4px;border:1px solid rgba(255,255,255,0.06)`;const n="width:50px;font-size:11px;color:rgba(255,255,255,0.7);background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.12);border-radius:3px;padding:2px 4px;outline:none;text-align:right",r="font-size:10px;color:rgba(255,255,255,0.45);white-space:nowrap",o="display:flex;align-items:center;gap:6px;margin-bottom:4px",c=document.createElement("div");c.style.cssText=o;const h=document.createElement("span");h.textContent="Hold",h.style.cssText=r+";width:55px";const d=document.createElement("input");d.type="number",d.min="0",d.step="500",d.value=String(i.holdDuration??2e3),d.style.cssText=n;const u=document.createElement("span");u.textContent="ms",u.style.cssText=r,d.addEventListener("change",()=>{const t=parseInt(d.value);i.holdDuration=isNaN(t)?void 0:Math.max(0,t),l()}),d.addEventListener("keydown",t=>t.stopPropagation()),c.appendChild(h),c.appendChild(d),c.appendChild(u),t.appendChild(c);const f=document.createElement("div");f.style.cssText=o;const m=document.createElement("span");m.textContent="Transition",m.style.cssText=r+";width:55px";const b=document.createElement("input");b.type="number",b.min="0",b.step="200",b.value=String(i.transitionDuration??1200),b.style.cssText=n;const v=document.createElement("span");v.textContent="ms",v.style.cssText=r,b.addEventListener("change",()=>{const t=parseInt(b.value);i.transitionDuration=isNaN(t)?void 0:Math.max(0,t),l()}),b.addEventListener("keydown",t=>t.stopPropagation()),f.appendChild(m),f.appendChild(b),f.appendChild(v),t.appendChild(f);const _=document.createElement("div");_.style.cssText=o;const x=document.createElement("span");x.textContent="Easing",x.style.cssText=r+";width:55px";const w=document.createElement("select");w.style.cssText="font-size:11px;color:rgba(255,255,255,0.7);background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.12);border-radius:3px;padding:2px 4px;outline:none";for(const t of["ease-in-out","ease-in","ease-out","linear"]){const e=document.createElement("option");e.value=t,e.textContent=t,e.style.cssText="background:#2a2a2a;color:#ccc",(i.easing??"ease-in-out")===t&&(e.selected=!0),w.appendChild(e)}w.addEventListener("change",()=>{i.easing="ease-in-out"===w.value?void 0:w.value,l()}),_.appendChild(x),_.appendChild(w),t.appendChild(_);const M=document.createElement("div");M.style.cssText=o+";margin-bottom:0";const S=document.createElement("span");S.textContent="Skip in play",S.style.cssText=r+";width:55px";const A=document.createElement("input");A.type="checkbox",A.checked=!!i.excludeFromPlay,A.style.cssText="accent-color:#4a9eff;cursor:pointer",A.addEventListener("change",()=>{i.excludeFromPlay=A.checked||void 0,l()}),M.appendChild(S),M.appendChild(A),t.appendChild(M),y.appendChild(t);const E=p.querySelector("button:last-child");E&&(e&&(E.style.color="#4a9eff"),E.addEventListener("click",()=>{const e="none"!==t.style.display;a.querySelectorAll("[data-slot-detail]").forEach(e=>{if(e!==t&&"none"!==e.style.display){e.style.display="none";const t=e.parentElement?.firstElementChild?.querySelector("button:last-child");t&&(t.style.color="rgba(255,255,255,0.35)")}}),t.style.display=e?"none":"block",E.style.color=e?"rgba(255,255,255,0.35)":"#4a9eff",g=e?-1:s}))}a.appendChild(y)}if(!t){const t=document.createElement("div");if(t.textContent=n?"No bookmarks defined":"No bookmarks saved",t.style.cssText="color:rgba(255,255,255,0.3);font-size:12px;text-align:center;padding:12px 0",a.appendChild(t),!n){const t=document.createElement("div");t.textContent="Use 📌 to save camera positions",t.style.cssText="color:rgba(255,255,255,0.2);font-size:11px;text-align:center;padding:0 0 4px",a.appendChild(t)}}p&&(p.style.display=c.getPlayableSlots().length>=2?"block":"none")};if(m(),!n){p=document.createElement("div"),p.style.cssText="display:none;margin-top:6px;padding:4px 8px;border-top:1px solid rgba(255,255,255,0.06)";const t=document.createElement("div");t.style.cssText="display:flex;align-items:center;gap:6px";const n=document.createElement("input");n.type="range",n.min="0",n.max="1000",n.value="0",n.tabIndex=-1,n.style.cssText="flex:1;min-width:0;margin:0;height:14px;cursor:grab;accent-color:#4a9eff;outline:none";const r=document.createElement("button");r.textContent="▶",r.title="Play / Stop",r.style.cssText="border:none;background:rgba(255,255,255,0.06);color:rgba(255,255,255,0.5);cursor:pointer;font-size:12px;padding:3px 6px;border-radius:4px;line-height:1;flex-shrink:0",r.addEventListener("mouseenter",()=>{r.style.background="rgba(74,158,255,0.15)",r.style.color="#4a9eff"}),r.addEventListener("mouseleave",()=>{r.style.background="rgba(255,255,255,0.06)",r.style.color=c.isPlaying?"#4a9eff":"rgba(255,255,255,0.5)"}),r.addEventListener("click",()=>{const t=c.isPlaying?-1:parseInt(n.value)/1e3;e.togglePlay(t),a()}),n.addEventListener("focus",()=>n.blur());let s=!1;n.addEventListener("mousedown",()=>{s=!0,n.style.cursor="grabbing",c.isPlaying&&(e.togglePlay(),a())}),n.addEventListener("input",()=>{const t=parseInt(n.value)/1e3;e.scrubPath(t)});const o=()=>{s&&(s=!1,n.style.cursor="grab")};n.addEventListener("mouseup",o),n.addEventListener("mouseleave",o),i.addEventListener("keydown",t=>{if("Space"===t.code&&"none"!==p.style.display){t.preventDefault(),t.stopPropagation();const r=c.isPlaying?-1:parseInt(n.value)/1e3;e.togglePlay(r),a()}}),t.appendChild(n),t.appendChild(r),p.appendChild(t),i.appendChild(p);const a=()=>{const t=c.isPlaying;r.textContent=t?"⏹":"▶",r.style.color=t?"#4a9eff":"rgba(255,255,255,0.5)"};let l=-1;const h=()=>{if(this._floatingPopup===i){if(c.isPlaying){const t=c.playProgress;n.value=String(Math.round(1e3*t)),l=-1}else{"⏹"===r.textContent&&a();const t=c.lastPlayProgress;t>=0&&t!==l&&(n.value=String(Math.round(1e3*t)),l=t)}f=requestAnimationFrame(h)}};f=requestAnimationFrame(h);(()=>{const t=c.getPlayableSlots().length;p.style.display=t>=2?"block":"none"})()}if(!n){const t=document.createElement("button"),e="display:block;width:100%;margin-top:8px;padding:5px 0;border:1px solid rgba(255,255,255,0.12);border-radius:6px;background:transparent;color:rgba(255,255,255,0.45);font-size:11px;cursor:pointer;transition:all 0.15s";r&&(t.textContent="Clear All",t.style.cssText=e,t.addEventListener("mouseenter",()=>{t.style.borderColor="rgba(255,107,107,0.4)",t.style.color="#ff6b6b"}),t.addEventListener("mouseleave",()=>{t.style.borderColor="rgba(255,255,255,0.12)",t.style.color="rgba(255,255,255,0.45)"}),t.addEventListener("click",()=>{c.resetAll(),l(),m()})),i.appendChild(t)}const y=e.onBookmarkChanged;e.onBookmarkChanged=()=>{y?.(),this._floatingPopup===i&&(m(),v=-2,n||e.showBookmarkPath())},this._showFloatingPopup(i,!0),n||e.showBookmarkPath();let b,v=u();const _=()=>{if(this._floatingPopup!==i)return;const t=u();if(t!==v){v=t;a.querySelectorAll("[data-slot-index]").forEach(e=>{const n=parseInt(e.dataset.slotIndex||"-1"),r=e.firstElementChild;if(!r)return;const i=n===t,s=i?"rgba(74,158,255,0.1)":"transparent";r.style.background=s,r.style.boxShadow=i?"inset 0 0 0 1px rgba(74,158,255,0.25)":"none",r.dataset.active=i?"1":""})}b=requestAnimationFrame(_)};b=requestAnimationFrame(_);const x=this._closeFloatingPopup.bind(this);this._closeFloatingPopup=()=>{void 0!==b&&cancelAnimationFrame(b),void 0!==f&&cancelAnimationFrame(f),c.isPlaying&&e.togglePlay(),e.clearBookmarkMarkerHighlight(),e.hideBookmarkPath(!0),this._closeFloatingPopup=x,x()}}_removeToolbar(){this._closeFloatingPopup(),this._threeCapability&&(this._threeCapability.onGizmoModeChanged=void 0,this._threeCapability.onGizmoAttachChanged=void 0,this._threeCapability.onCameraViewChanged=void 0,this._threeCapability.onBookmarkChanged=void 0,this._threeCapability.onHelpToggle=void 0,this._threeCapability.onSearchToggle=void 0,this._threeCapability.onBookmarkNavToggle=void 0,this._threeCapability.onBookmarkEditToggle=void 0),this._toolbar?.parentNode&&this._toolbar.parentNode.removeChild(this._toolbar),this._toolbar=void 0,this._cameraButtons=void 0}_resizeThreeD(t=!1){if(!this._threeCapability||!this.element)return;const e=this.canvas?.clientWidth??0,n=this.canvas?.clientHeight??0,r=e>0?e:this.element.clientWidth,i=n>0?n:this.element.clientHeight;r>0&&i>0&&this._threeCapability.resize(r,i,t)}detachThreeCapability(){const t=this._threeCapability;if(t)return t.forceCleanupDragState(),t.clearAllObjects(),this._threeCapability=void 0,t}adoptThreeCapability(t){this._threeCapability=t,this._hide2DLayers();const e=t.domElement;if(e&&this.element){e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.pointerEvents="none",e.setAttribute("scene","model-layer-webgl");const t=this._decoratorOverlay||this.element.firstChild;this.element.insertBefore(e,t)}t.buildOverlays(),t.rebuildForHost(this,{lightingConfig:this._buildLightingConfig(),css3DSceneAttribute:"model-layer:css3d-renderer"}),this.app?.isEditMode&&this._createToolbar(),this._registerPopupCallbacks(),this._resizeThreeD(!0)}_deactivateThreeD(){if(!this._threeCapability)return;this._removeToolbar(),this._lastCameraState=this._threeCapability.captureSessionState();const{target:t,visibleWidth:e,visibleHeight:n}=this._threeCapability.captureViewportInfo();this._threeCapability.forceCleanupDragState();const r=this._threeCapability.domElement,i=this._threeCapability.css3DRenderer?.domElement,s=[...this._threeCapability.decoratorOutlines];this._threeCapability.dispose(),this._threeCapability=void 0,i?.parentNode&&i.parentNode.removeChild(i);for(const t of this.components)if(t.isHTMLElement()&&t.element){const e=t.element,n=this.getOverlay(t);n?.appendChild(e)}r?.parentNode&&r.parentNode.removeChild(r),this.canvas&&(this.canvas.style.display=""),this._overlay&&(this._overlay.style.display=""),this._auxCanvas&&(this._auxCanvas.style.display=""),this._decoratorOverlay&&(this._decoratorOverlay.style.display=""),this._decoratorAuxOverlay&&(this._decoratorAuxOverlay.style.display="");for(const t of this.root?.assist_layers||[])t.element&&(t.element.style.display="");for(const t of this.components)t.isHTMLElement()&&t.element&&t.reposition();this.app?.isEditMode&&this._createToolbar();for(const t of s)t.disposed||this.applyDecorator(t,"border-highlighting",{distance:8,lineWidth:4,color:"#f007"});this._saved2DViewport?(this.set({scale:this._saved2DViewport.scale,translate:this._saved2DViewport.translate}),this._saved2DViewport=void 0):this._needsViewportSync&&this._init2DViewportFrom3DCamera(t,e,n),this.root.target_element?.focus()}_getViewportSize(){const t=this.target;return{w:t?.clientWidth||this.canvas?.clientWidth||this.state.width||800,h:t?.clientHeight||this.canvas?.clientHeight||this.state.height||600}}_initCameraFrom2DViewport(){if(!this._threeCapability)return;const{w:t,h:e}=this._getViewportSize(),n=this.get("translate")||{x:0,y:0},r=this.get("scale")||{x:1,y:1},i=r.x||1,s=r.y||1,{width:o=800,height:a=600}=this.state,c=(t/2-n.x)/i-o/2,l=(e/2-n.y)/s-a/2,h=t/i,d=e/s;this._threeCapability.positionCameraForViewport(c,l,h,d,this._lastCameraState)}_init2DViewportFrom3DCamera(t,e,n){if(!e&&!n)return;const{w:r,h:i}=this._getViewportSize(),{width:s=800,height:o=600}=this.state,a=t.x+s/2,c=t.z+o/2,l=e>0?r/e:1/0,h=n>0?i/n:1/0,d=Math.max(.1,Math.min(Math.min(l,h),10)),u=r/2-a*d,p=i/2-c*d;this.set({translate:{x:u,y:p},scale:{x:d,y:d}})}centerTo(t,e){this.is3dMode&&this._threeCapability?this._threeCapability.centerToComponent(t,e):super.centerTo(t,e)}async ready(){await super.ready(),this.model.threed?this._threeCapability||(await new Promise(t=>setTimeout(t,0)),this._activateThreeD()):this.app?.isEditMode&&this._createToolbar(),this.root?.trigger("dimension",this.model.threed?"3d":"2d")}dispose(){this._deactivateThreeD(),this._removeToolbar(),super.dispose(),this._overlay=null,this._decoratorOverlay&&(bs.getInstance().removeOverlay(this._decoratorOverlay),this._decoratorOverlay.parentNode&&this._decoratorOverlay.parentNode.removeChild(this._decoratorOverlay),this._decoratorOverlay=null),this._decoratorAuxOverlay&&(bs.getInstance().removeOverlay(this._decoratorAuxOverlay),this._decoratorAuxOverlay.parentNode&&this._decoratorAuxOverlay.parentNode.removeChild(this._decoratorAuxOverlay),this._decoratorAuxOverlay=null)}contains(t,e){return!0}isRootModel(){return!0}get stuck(){return!0}get layout(){return this.is3dMode?Wa.get("three"):Xa}get overlay(){if(!this._overlay){const t=document.createElement("div");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.margin="0",t.style.padding="0",t.style.overflow="initial",t.style["user-select"]="none",t.style["transform-origin"]="top left",t.setAttribute("scene","model-layer-overlay"),this.element.insertBefore(t,this.auxCanvas),this._overlay=t,this._repositionOverlay()}return this._overlay}get auxOverlay(){return this.element??void 0}get decoratorOverlay(){if(!this._decoratorOverlay){const t=document.createElement("div");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.margin="0",t.style.padding="0",t.style.overflow="initial",t.style["user-select"]="none",t.style["transform-origin"]="top left",t.setAttribute("scene","decorator-overlay"),t.id=`decorator-overlay-${Date.now()}`,this.element.insertBefore(t,this.overlay),this._decoratorOverlay=t,bs.getInstance().addOverlay(t)}return this._decoratorOverlay}get decoratorAuxOverlay(){if(!this._decoratorAuxOverlay){const t=document.createElement("div");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.margin="0",t.style.padding="0",t.style.overflow="initial",t.style.zIndex="100",t.style["user-select"]="none",t.style["transform-origin"]="top left",t.setAttribute("scene","decorator-aux-overlay"),t.id=`decorator-overlay-${Date.now()}`,this.element.appendChild(t),this._decoratorAuxOverlay=t,bs.getInstance().addOverlay(t)}return this._decoratorAuxOverlay}createElement(){const t=super.createElement();return this._overlay&&t.appendChild(this._overlay),t}resize(){if(!this.target||!this.element)return;let{width:t,height:e,fitMode:n}=this.model;this.root.fitMode?n=this.root.fitMode:n||(n="ratio");let r=null;try{r=getComputedStyle(this.target)}catch(t){return void jr(t,this.target)}let i=r?parseFloat(r.getPropertyValue("width")):this.target.clientWidth,s=r?parseFloat(r.getPropertyValue("height")):this.target.clientHeight;switch(n){case"both":case"ratio":break;case"width":s=e*i/t,this.element.style.overflowX="hidden",this.element.style.overflowY="auto";break;case"height":i=t*s/e,this.element.style.overflowX="auto",this.element.style.overflowY="hidden";break;default:i=Math.max(t,i),s=Math.max(e,s),this.element.style.overflowX=i>t?"hidden":"auto",this.element.style.overflowY=s>e?"hidden":"auto"}this.fitSize(this.element,!0),this.fitSize(this.canvas,!0,i,s),this.fitSize(this.auxCanvas,!0,i,s),this.is3dMode&&this._threeCapability.resize(i,s)}draw(t){if(this.is3dMode){if(!this.element)return;this._threeCapability.renderCSS3D()}else this.model.threed||super.draw(t)}get MPP(){const{scale:t={x:1,y:1},unit:e}=this.model;switch(e){case"mm":case"cm":return 1/this.app.PPM/t.x;case"in":return 1/this.app.PPI/t.x;default:return 1/t.x}}capturePath(t,e){const n=this.layout.capturables(this);for(let r=n.length-1;r>=0;r--){const i=n[r];if(!i.isContainer())continue;const s=i.capturePath(t,e);if(s)return s}return!1}getOverlay(t){return t&&!t.scalable?this.auxOverlay:this.overlay}getDecoratorOverlay(t){return t&&!t.scalable?this.decoratorAuxOverlay:this.decoratorOverlay}_onkeydown_root(t){if(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)return;const e=this.rootModel;if(!e)return;if("KeyF"===t.code)return this.onSearchToggle?.(),void t.preventDefault();if("KeyH"===t.code)return this._toggleHelpPanel(),void t.preventDefault();if(e.is3dMode)return;if("KeyQ"===t.code)return e.set("threed",!0),void t.preventDefault();const n={Digit1:"perspective",Digit2:"top",Digit3:"front",Digit4:"back",Digit5:"right",Digit6:"left"}[t.code];n&&(e._pendingCameraView=n,e.set("threed",!0),t.preventDefault())}get eventMap(){return{"(self)":{"(all)":{change:this._onchanged_all,mouseenter:this._onmouseenter_all,mouseleave:this._onmouseleave_all,click:this._onclick,mousedown:this._onmousedownup,mouseup:this._onmousedownup,touchstart:this._onmousedownup,touchend:this._onmousedownup,"deco-reset":t=>this.resetDecorator(void 0,t.origin)},"(descendant)":{"deco-anchors":(t,e)=>this.applyDecorator(e.origin,"anchors",t),"deco-anchors-off":t=>this.offdecorator(t.origin,"anchors"),"deco-anchors-reset":t=>this.resetDecorator("anchors"),"deco-dataspread":(t,e)=>this.applyDecorator(e.origin,"data-spread",t),"deco-dataspread-off":t=>this.offdecorator(t.origin,"data-spread"),"deco-dataspread-reset":t=>this.resetDecorator("data-spread"),"deco-link":(t,e)=>this.applyDecorator(e.origin,"link",t),"deco-link-off":t=>this.offdecorator(t.origin,"link"),"deco-link-reset":t=>this.resetDecorator("link"),"deco-arrow":(t,e)=>this.applyDecorator(e.origin,"bouncing-arrow",t),"deco-arrow-off":t=>this.offdecorator(t.origin,"bouncing-arrow"),"deco-arrow-reset":t=>this.resetDecorator("bouncing-arrow"),"deco-icon":(t,e)=>this.applyDecorator(e.origin,"animated-icon",t),"deco-icon-off":t=>this.offdecorator(t.origin,"animated-icon"),"deco-icon-reset":t=>this.resetDecorator("animated-icon"),"deco-border":(t,e)=>{this.app.isEditMode||(this._threeCapability?this._threeCapability.addOutline(e.origin):this.applyDecorator(e.origin,"border-highlighting",t))},"deco-border-off":t=>{this.app.isEditMode||(this._threeCapability?this._threeCapability.removeOutline(t.origin):this.offdecorator(t.origin,"border-highlighting"))},"deco-border-reset":t=>{this.app.isEditMode||(this._threeCapability?this._threeCapability.clearOutlines():this.resetDecorator("border-highlighting"))},"deco-tag":(t,e)=>this.applyDecorator(e.origin,"decotag",t),"deco-tag-off":t=>this.offdecorator(t.origin,"decotag"),"deco-tag-reset":t=>this.resetDecorator("decotag",t.origin),"deco-off":t=>{this.offdecorator(t.origin),this._threeCapability?.removeOutline(t.origin)},mouseenter:this.onmouseenterForDecorator,mouseleave:this.onmouseleaveForDecorator},"(self)":{change:this.onChangeForDecorator,redraw:this.onRedrawForDecorator}},"(root)":{"(self)":{selected:this._onRootSelected,keydown:this._onkeydown_root}}}}onRedrawForDecorator(){this.is3dMode||(bs.getInstance().invalidateOverlay(this.decoratorOverlay),bs.getInstance().invalidateOverlay(this.decoratorAuxOverlay))}closeScene(t){requestAnimationFrame(()=>this.overlay.dispatchEvent(new CustomEvent("close-scene",{bubbles:!0,composed:!0,detail:t})))}_repositionOverlay(){const t=this._overlay;if(!t)return;const{translate:e=Jh,scale:n=Zh,rotation:r=0}=this.model,{left:i,top:s}=this.bounds;t.style.left=i+"px",t.style.top=s+"px",t.style.transform=`rotate(${r}rad) scale(${n.x}, ${n.y}) perspective(1px)`,t.style.marginLeft=`${e.x}px`,t.style.marginTop=`${e.y}px`}onchange(t){const e=this._model;delete e.id,delete e.text,delete e.class,this._repositionOverlay(),t.hasOwnProperty("threed")&&(t.threed?this._activateThreeD(!0):this._deactivateThreeD(),this.root?.trigger("dimension",t.threed?"3d":"2d")),this.is3dMode&&((t.hasOwnProperty("width")||t.hasOwnProperty("height"))&&this._resizeThreeD(),this._threeCapability.onchange(t))}_onRootSelected(t){const e=1===t?.length?t[0]:t&&0!==t.length?null:this;e&&globalThis.dispatchEvent?.(new CustomEvent("clickComponent",{detail:e}))}_onchanged_all(t,e,n){this.invalidate()}_onmouseenter_all(t,e){if(t.stopPropagation(),!this.app||this.app.isEditMode)return;if(!e)return;const n=e.origin;if(n instanceof ad||!n.model.event||!n.model.event.hover)return;if(n.hidden)return;const r=n.model.event.hover;r&&this._doEventAction(r,n,!0,t)}_onmouseleave_all(t,e){if(t.stopPropagation(),!e)return;const n=e.origin;if(!this.app||this.app.isEditMode)return;const r=n.model.event&&n.model.event.hover;r&&this._doEventAction(r,n,!1,t)}_onclick(t,e){if(t.stopPropagation(),this.app.isEditMode)return;if(!e)return;const n=e.origin,r=n.model.event?.tap;r&&this._doEventAction(r,n,!0,t)}_onmousedownup(t,e){if(t.stopPropagation(),this.app.isEditMode)return;if(!e)return;const n=e.origin,r=n.model.event?.tap;r&&r.pressed&&this._doMouseDownUpEventAction(r,n,"mousedown"==t.type||"touchstart"==t.type,t)}_doMouseDownUpEventAction(t,e,n,r){const{pressed:i=!1}=t;i&&(n?function(t){if(t.hasOwnProperty("_backupShadow"))return;const e=t.get("shadow");t._backupShadow=e;const{left:n=0,top:r=0}=e||{};t.delta("tx",n),t.delta("ty",r),t.set("shadow",{})}(e):function(t){t.hasOwnProperty("_backupShadow")&&(t.delta("tx",0),t.delta("ty",0),t.set("shadow",t._backupShadow),delete t._backupShadow)}(e))}_doEventAction(t,e,n,r){let{action:i,target:s,value:o,emphasize:a=!1,restore:c=!1,options:l}=t;if(s&&(s=e.access(s)),o&&(o=e.access(o)),a&&(n?function(t){const{hover:e}=t.state.event||{},{emphasize:n}=e||{};if(t.hasOwnProperty("_backupStrokeStyle"))return;if("__backup_emphasize"in t)return;const{strokeStyle:r,lineWidth:i,fillStyle:s}=t.state;t.__backup_emphasize={strokeStyle:r,lineWidth:i,fillStyle:s},t.setState(n)}(e):c&&function(t){"__backup_emphasize"in t&&(t.setState(t.__backup_emphasize),delete t.__backup_emphasize)}(e)),i)switch(i){case"data-toggle":if(!s)return;(n||c)&&this.root.findAll(s,e)?.forEach(t=>{t.data=!t.data});break;case"data-tristate":if(!s)return;(n||c)&&this.root.findAll(s,e)?.forEach(t=>{const e=Math.round(Math.max(Number(t.data)||0,0));t.data=(e+(n?1:2))%3});break;case"data-spreading":if(!s)return;n&&(e.access(o),this.root.findAll(s,e)?.forEach(t=>{t.executeMappings(!0)}));break;case"data-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.data=t})}break;case"partial-data-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.data={...e.data,...t}})}break;case"value-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.value=t})}break;case"partial-value-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.value={...e.value,...t}})}break;case"infoWindow":case"info-window":if(!s)return;"click"==r.type||n?Ua.show(e,s,c,{x:r.offsetX,y:r.offsetY}):c&&Ua.hide(e,s);break;case"toggle-info-window":if(!s)return;Ua.toggle(e,s,!1,{x:r.offsetX,y:r.offsetY});break;case"popup":case"modal-popup":if(!s)return;const t=l&&"input"in l?l.input:"(self)",a=!l||(!("output"in l)||l.output);hc.show(e,s,{data:t&&this.root.findFirst(t,e)?.data,output:a,modal:"modal-popup"===i,closable:!0,draggable:!0,origin:"auto"});break;case"close-scene":this.closeScene(e.data);break;case"goto":case"goto-playlist":this.trigger(i,s,l,e);break;case"mouse-cursor":n?this.target.style.cursor=s||"auto":c&&(this.target.style.cursor="auto");break;default:this.trigger(i,s,o,e)}}applyDecorator(t,e,n={}){const r=this.getDecoratorOverlay(t);if(r){bs.getInstance().addToOverlay(r,t,e,n)}}offdecorator(t,e){const n=this.getDecoratorOverlay(t);if(n){bs.getInstance().removeFromOverlay(n,t,e)}}resetDecorator(t,e){const n=this.getDecoratorOverlay(e);n&&bs.getInstance().removeAllFromOverlay(n,t)}onChangeForDecorator(t,e,n){const{origin:r}=n,i=this.getDecoratorOverlay(r);bs.getInstance().invalidateOverlay(i)}onmouseenterForDecorator(t,e){const{origin:n}=e;n.decorators&&n.decorators.forEach(t=>{this.applyDecorator(n,t)})}onmouseleaveForDecorator(t,e){const{origin:n}=e;n.decorators&&n.decorators.forEach(t=>{this.offdecorator(n,t)})}}function cd(t,e){const n=t.state.refid;return t.root.findAll(t=>t.isLine()&&t.from?.component===n&&(!e||t.from.anchor===e))}function ld(t,e){const n=t.state.refid;return t.root.findAll(t=>t.isLine()&&t.to?.component===n&&(!e||t.to.anchor===e))}function hd(t){return class extends t{isConnectable(){return!0}postrender(t){super.postrender(t),this._draw_anchors(t)}_draw_anchors(t){const e=this.anchors||[];t.save(),e.forEach(e=>{const{draw:n}=e;if(n){t.beginPath();try{n.call(e,t,this)}catch(t){jr(t)}t.closePath()}}),t.restore()}contains(t,e){let n=super.contains(t,e);if(n)return n;const r=this.anchors||[];for(const i of r){const r=i.bounds;if(!r)continue;const{left:s,top:o,width:a,height:c}=r;if(n=t<Math.max(s+a,s)&&t>Math.min(s+a,s)&&e<Math.max(o+c,o)&&e>Math.min(o+c,o),n)return n}return!1}findInOutLines(t){return function(t,e){const n=t.state.refid;return t.root.findAll(t=>!(!t.isLine()||(t.from?.component!==n||e&&t.from.anchor!==e)&&(t.to?.component!==n||e&&t.to.anchor!==e)))}(this,t)}findOutletLines(t){return cd(this,t)}findOutletEnds(t){return function(t,e){return cd(t,e).map(t=>t.toEnd?.component).filter(Boolean)}(this,t)}findInletLines(t){return ld(this,t)}findInletEnds(t){return function(t,e){return ld(t,e).map(t=>t.fromEnd?.component).filter(Boolean)}(this,t)}}}ad.Popup=hc,Fa.register("model-layer",ad);const dd={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"round",name:"round",property:{min:0}}],help:"scene/component/rect"},ud={ondragmove:function(t,e,n){const{left:r,width:i,height:s}=n.model;let o=(n.fromParent(t.x,t.y).x-r)/(i/2)*100;o=Na(o,i,s),n.set({round:o})}};class pd extends(hd(Ha(Ba))){is3dish(){return!0}get controls(){let{left:t,top:e,width:n,round:r,height:i}=this.state;return r=null==r?0:Na(r,n,i),[{x:t+n/2*(r/100),y:e,handler:ud}]}get nature(){return dd}}Fa.register("rect",pd);const fd=[1,2,10,20,50,50,50,50,50,50];class gd extends(Ha(Ba)){render(t){const{lineWidth:e=1,fillStyle:n="lightgray",font:r="15px Arial",left:i,top:s,origin:o,width:a,height:c,side:l="bottom",strokeStyle:h="#000000",scale:d=1}=this.state;t.translate(i,s),t.beginPath();const u=Math.round(e/2);t.rect(-u,-u,a+2*u,c+2*u),t.clip(),t.beginPath(),t.rect(0,0,a,c),n&&(t.fillStyle=n,t.fill()),t.lineWidth=e,t.strokeStyle=h,t.stroke(),t.beginPath(),t.font=r;const p="bottom"!==l,f=p?0:c;let g=4*c/5,m=2*c/3,y=1*c/2,b=3*c/5;p&&(g=c-g,m=c-m,y=c-y,b=c-1.5*c/5);const v=d*this.app.PPM/this.root.unitScale;let _=Math.ceil(o/v);const x=this.app.PPM/v,w=x<=1.1?1:fd[Math.round(x)]||100;1!=w&&(_+=(w-_%w)%w);let M=Math.ceil(_*v);const S=o+a;for(t.fillStyle=h;M<S;){if(_%10==0){t.moveTo(M-o,y),t.lineTo(M-o,f);const e=(_/10).toString(),n=t.measureText(e);t.fillText(e,M-o-n.width-6,b)}else _%5==0?(t.moveTo(M-o,m),t.lineTo(M-o,f)):(t.moveTo(M-o,g),t.lineTo(M-o,f));_+=w,M=Math.ceil(_*v)}}}Fa.register("ruler",gd);const md=20,yd=20,bd=90*Math.PI/180,vd="9px Verdana",_d=20,xd="#f4f4f4",wd="#999";function Md(t,e,n){return{left:-t.x,top:-t.y,width:md,height:_d}}function Sd(t,e,n,r){return{left:md-t.x,top:0-t.y,origin:20-t.x,width:e-md,height:_d}}function Ad(t,e,n,r){const i={x:0-t.x+10,y:-t.y+yd+(n-yd)/2},s=Fa.transcoordRR(0-t.x,-t.y+yd,i,bd);return{left:s.x-(n-yd),top:s.y,origin:20-t.y,width:n-yd,height:_d}}function Ed(t){const e=t.get("translate");return{left:-e.x,top:-e.y,width:t.canvas.width/_i,height:t.canvas.height/_i}}Fa.register("guide-layer",class extends gc{constructor(t,e){super(t,e),this.appScale={x:1,y:1},"disabled"!==t.ruler&&(this.hruler=new gd({left:md,top:0,origin:20,margin:0,height:_d,unit:"m",rotation:0,font:vd,fillStyle:xd,strokeStyle:wd,capturable:!1}),this.vruler=new gd({left:0,top:0,origin:20,margin:0,height:_d,unit:"m",rotation:bd,font:vd,side:"top",fillStyle:xd,strokeStyle:wd,capturable:!1}),this.origin_rect=new pd({left:-20,top:-20,width:20,height:20,fillStyle:xd,strokeStyle:wd,lineWidth:1}),this.addComponent(this.hruler),this.addComponent(this.vruler),this.addComponent(this.origin_rect)),this.invalidate()}get capturable(){return!1}async ready(){if(await super.ready(),!this.hruler)return void(this.screen_coord=Ed(this));const t=this.rootModel,e=Object.assign({},t.get("translate"));e.x<md&&(e.x+=md),e.y<yd&&(e.y+=yd);const n=t.get("scale")||{x:1,y:1};this.appScale=n,this.hruler.set("scale",n.x),this.vruler.set("scale",n.y),t.set("translate",e),this.set("translate",e),this.screen_coord=Ed(this);const{width:r,height:i}=this.screen_coord;this.hruler.set(Sd(e,r)),this.vruler.set(Ad(e,0,i)),this.origin_rect.set(Md(e))}resize(){super.resize(),this.screen_coord=Ed(this);const{width:t,height:e}=this.screen_coord;this.hruler&&(this.hruler.set(Sd(this.model.translate,t)),this.vruler.set(Ad(this.model.translate,0,e)),this.origin_rect.set(Md(this.model.translate)))}render(t){if(this.rootModel?.is3dMode)return;if(!this.guide)return;t.save();const{x:e,y:n}=this.guide,{top:r,left:i,width:s,height:o}=this.screen_coord;t.beginPath(),t.moveTo(e,r),t.lineTo(e,r+o),t.moveTo(i,n),t.lineTo(i+s,n),t.lineWidth=1,t.strokeStyle="tomato",t.setLineDash([2,3]),t.font="10px tahoma",t.fillStyle="#333";const a=this.toGlobal(e,n,this.rootModel);t.textBaseline=a.y>200?"bottom":"top",t.textAlign=a.x>200?"right":"left";const c=a.y>200?-5:5,l=a.x>200?-5:5,h=Math.round(e/this.appScale.x),d=Math.round(n/this.appScale.y);t.fillText(` ${h}, ${d} `,e+l,n+c),t.stroke(),t.restore()}get guide(){return this._guide}set guide(t){this._guide=t,this.invalidate()}contains(t,e){return!0}get eventMap(){return{"(root)":{"(descendant)":{mousemove:this.onmousemove_child,mouseout:this.onmouseout_child,dragmove:this.onmousemove_child},"model-layer":{change:this.onchange_root_model}},"(self)":{"(descendant)":{mousedown:this.onmousedown_origin}}}}onmousedown_origin(t,e){this.rootModel.set("translate",{x:20,y:20})}onchange_root_model(t,e,n){if(t.scale&&(this.appScale=t.scale,this.hruler&&(this.hruler.set("scale",t.scale.x),this.vruler.set("scale",t.scale.y))),t.translate&&this.set({translate:{x:t.translate.x,y:t.translate.y}}),t.scale||t.translate){if(this.screen_coord=Ed(this),this.hruler){const{translate:t}=this.model,{width:e,height:n}=this.screen_coord;this.hruler.set(Sd(t,e)),this.vruler.set(Ad(t,0,n)),this.origin_rect.set(Md(t))}this._guide=null}this.invalidate()}onmouseout_child(t){this._guide=null,this.invalidate()}onmousemove_child(t,e){t.target&&"CANVAS"!==t.target.tagName?this.guide=null:this.guide=this.toLocal(t.offsetX,t.offsetY)}});Fa.register("shift-layer",class extends gc{async ready(){await super.ready();const t=this.rootModel.get("translate");this.set("translate",t)}render(t){}get pointerEvents(){return"none"}contains(t,e){return!(2!=this.app.mode)}get eventMap(){return{"(root)":{"(self)":{keydown:this.onkeydown,keyup:this.onkeyup}}}}onkeydown(t){"Space"===t.code&&void 0===this.before_mode&&(this.before_mode=this.app.mode,this.app.mode=2)}onkeyup(t){"Space"===t.code&&(void 0!==this.before_mode&&(this.app.mode=this.before_mode),delete this.before_mode)}ondragstart(t){this.last_position=this.toLocal(t.offsetX,t.offsetY)}ondragmove(t){const{x:e,y:n}=this.toLocal(t.offsetX,t.offsetY);this.rootModel.move({x:e-this.last_position.x,y:n-this.last_position.y},!1),this.last_position=this.toLocal(t.offsetX,t.offsetY)}});function kd(t,e,n,r){const i=t.selected;let s=r?i.slice(0):[];e.isContainer()||(e=e.parent);const o=e.layout.capturables(e),a=!!e.layout.joinType;if(r&&n.selected.forEach(t=>{s.splice(s.indexOf(t),1)}),n.selected=[],o.forEach(t=>{t.capturable&&function(t,e,n){const{sx:r,sy:i,ex:s,ey:o}=e;let a,c,l,h;if(r>s?(a=s,c=r):(a=r,c=s),i>o?(l=o,h=i):(l=i,h=o),n){const e=t.bounds,n=t.transcoordS2TR(e.left,e.top),r=t.transcoordS2TR(e.left+e.width,e.top+e.height),i=n.x,s=r.x,o=n.y,d=r.y,u=Math.min(a,i,c,s),p=Math.max(a,i,c,s),f=Math.min(l,o,h,d),g=Math.max(l,o,h,d);return!(p-u>Math.abs(c-a)+Math.abs(s-i)||g-f>Math.abs(h-l)+Math.abs(d-o))}{const e=t.path;if(!e)return jr("컴포넌트에 get path가 잘못 구현되어있음.",t),!1;for(let n=0;n<e.length;n++){const r=t.transcoordS2TR(e[n].x,e[n].y);if(a>r.x||c<r.x||l>r.y||h<r.y)return!1}return!0}}(t,n,a)&&-1==s.indexOf(t)&&n.selected.push(t)}),s=s.concat(n.selected),i.length!==s.length)t.selected=s;else for(let e=0;e<s.length;e++)if(i[e]!=s[e]){t.selected=s;break}}function Cd(t,e,n,r,i){i||kd(t,e,n,r)}function Pd(t,e){const n=t.components||[];for(const t of n){Pd(t,e);const n=e.indexOf(t);-1!=n&&e.splice(n,1)}}Fa.register("add-layer",class extends gc{async ready(){await super.ready();const t=this.rootModel,e=t.get("translate"),n=t.get("scale");this.set("translate",e),this.set("scale",n)}get pointerEvents(){return"none"}render(t){const e=this.addbox;if(e){const{sx:n,sy:r,ex:i,ey:s}=e,o=this.get("scale")||{x:1,y:1};t.beginPath(),t.rect(n,r,i-n,s-r),t.setLineDash([2/o.x,4/o.y]),t.lineWidth=1/o.x,t.strokeStyle="black",t.stroke()}}contains(t,e){return!(3!=this.app.mode)}get eventMap(){return{"(root)":{"(self)":{addstart:this.onaddstart,addstop:this.onaddstop,keydown:this.onkeydown,dragstart:this.ondragstart,dragmove:this.ondragmove,dragend:this.ondragend,mousedown:this.onmousedown,mouseup:this.onmouseup}},"model-layer":{"(self)":{change:this.onchange_root_model}}}}onchange_root_model(t,e,n){t.translate&&this.set("translate",t.translate),t.scale&&this.set("scale",t.scale)}onaddstart(t,e){void 0===this.before_mode&&(this.before_mode=this.app.mode,this.models=t,this.app.mode=3,this.root.target_element?.focus())}onaddstop(){void 0!==this.before_mode&&(this.app.mode=this.before_mode),delete this.before_mode,delete this.addbox,this.invalidate()}onkeydown(t){3!==this.app.mode||"Esc"!=t.code&&"Escape"!=t.code||this.root.trigger("addstop")}ondragstart(t){const{x:e,y:n}=this.toLocal(t.offsetX,t.offsetY);this.addbox={sx:e,sy:n}}ondragmove(t){if(3!==this.app.mode)return;const{x:e,y:n}=this.toLocal(t.offsetX,t.offsetY);this.addbox&&(this.addbox.ex=e,this.addbox.ey=n,this.invalidate())}ondragend(t,e){if(3!==this.app.mode)return;const{sx:n,sy:r,ex:i,ey:s}=this.addbox;Jc.call(this.root,this.models,{left:Math.min(n,i),top:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}),this.root.trigger("addstop")}onmousedown(t,e){3===this.app.mode&&(this.downpoint={x:t.offsetX,y:t.offsetY})}onmouseup(t,e){if(this.downpoint.x!==t.offsetX||this.downpoint.y!==t.offsetY)return;const{x:n,y:r}=this.toLocal(t.offsetX,t.offsetY);Jc.call(this.root,this.models,{cx:n,cy:r}),this.root.trigger("addstop")}});Fa.register("selection-layer",class extends gc{async ready(){await super.ready();const t=this.rootModel,e=t.get("translate"),n=t.get("scale");this.set("translate",e),this.set("scale",n)}contains(t,e){return!1}render(t){const e=this.selbox;if(e){const{sx:n,sy:r,ex:i,ey:s}=e,o=this.get("scale")||{x:1,y:1};t.beginPath(),t.rect(n,r,i-n,s-r),t.setLineDash([2/o.x,4/o.y]),t.lineWidth=1/o.x,t.strokeStyle="black",t.stroke()}}get eventMap(){return{"(root)":{"(self)":{keydown:this.onkeydown}},"model-layer":{"(self)":{change:this.onchange_root_model},"(all)":{dragstart:this.ondragstart_selbox,dragmove:this.ondragmove_selbox,dragend:this.ondragend_selbox,mousedown:this.onmousedown_comp,mouseup:this.onmouseup_comp}}}}onkeydown(t,e){const{deliverer:n}=e,r=n.selected;if(1!==r.length)return!1;let i=r[0];const s=i.parent;if(!s||s===n)return!1;if("Tab"===t.code){const e=s.layout.capturables(s);let n=e.indexOf(i);if(-1==n){if(!s.indexOf(i))return Rr("Container not contains [",i,"] as a component"),!1;n=0}const r=e.length;t.shiftKey?n--:n++,i=e[(n+r)%r]}else{if(!s.layout.keyNavigate)return!1;i=s.layout.keyNavigate(s,i,t)||i}n.selected=[i],t.preventDefault()}onchange_root_model(t,e,n){t.translate&&this.set("translate",t.translate),t.scale&&this.set("scale",t.scale)}_pendingDecision(t){this.downpoint={x:t.offsetX,y:t.offsetY}}_selectGroupItem(t,e){const n=this.selected.indexOf(t);let r=t.parent;for(;r.parent.isGroup();)r=r.parent;let i=[],s=!1,o=!1;if(this.selected.forEach(t=>{let e=t.parent;if(t!==r){for(;e.parent&&e.parent.isGroup();)e=e.parent;e===r&&(i.push(t),s=!0)}else o=!0}),s)if(e.shiftKey){if(-1!=n)return void this._pendingDecision(e);i.push(t)}else{if(-1!=n)return void this._pendingDecision(e);i=[t]}else{if(o)return void this._pendingDecision(e);if(e.shiftKey)if(this.selected.length>0){if(-1!=this.selected.indexOf(r))return;i=[...this.selected,r]}else i=[r];else i=[r]}this.selected=i}onmousedown_comp(t,e){const{origin:n}=e;if(this.downpoint=null,t.shiftKey){if(n.stuck)return;if(n.parent.isGroup())return void this._selectGroupItem(n,t);this._pendingDecision(t)}else{if(n.parent.isGroup())return void this._selectGroupItem(n,t);if(n.stuck)this.selected.length>0&&(this.selected=[]);else{if(-1!=this.selected.indexOf(n))return;this.selected=[n],this.sameParent=!0}}}onmouseup_comp(t,e){if(!this.downpoint)return;if(this.downpoint.x!==t.offsetX||this.downpoint.y!==t.offsetY)return;const{origin:n}=e;if(t.shiftKey){let t=this.selected.indexOf(n);if(-1==t&&n.parent.isGroup()&&(t=this.selected.indexOf(n.parent)),-1!==t){const e=this.selected.slice();e.splice(t,1),this.selected=e}else{const t=this.selected.filter(t=>!t.isRootModel()&&!!t.parent),e=t.length>0&&t[0].parent;e&&e!==n.parent&&(!function(t,e){let n=t.parent;for(;n;){const t=e.indexOf(n);-1!=t&&e.splice(t,1),n=n.parent}}(n,t),Pd(n,t)),t.push(n),this.selected=t}}else if(n.parent.isGroup())return void(this.selected=[n])}ondragstart_selbox(t,e){const{origin:n}=e;if(!n.stuck)return;const{x:r,y:i}=this.toLocal(t.offsetX,t.offsetY);this.selbox={sx:r,sy:i,selected:[]}}ondragmove_selbox(t,e){const{origin:n}=e;if(!n.stuck)return;const{x:r,y:i}=this.toLocal(t.offsetX,t.offsetY);this.selbox&&(this.selbox.ex=r,this.selbox.ey=i,Cd(this,n,this.selbox,t.shiftKey,!1),this.invalidate())}ondragend_selbox(t,e){const{origin:n}=e;n.stuck&&(this.last_pos=null,this.selbox=null,Cd(this,null,null,!1,!0),this.invalidate())}});class Td{constructor(t){this.layer=t}draw(t,e,n){const{left:r,top:i,width:s,height:o}=e.bounds;0!=s&&0!=o&&(t.beginPath(),t.rect(r,i,s,o),t.clip(),t.beginPath(),t.strokeStyle="#f26522",t.lineWidth=4,t.shadowBlur=10,t.shadowColor="black",t.shadowOffsetX=0,t.shadowOffsetY=0,t.rect(r,i,s,o),t.stroke(),t.closePath())}}class Dd{constructor(t){this.layer=t}draw(t,e,n){const r=e.bounds;t.beginPath(),t.rect(r.left-4/n.x,r.top-4/n.y,r.width+8/n.x,r.height+8/n.y),t.setLineDash([3/n.x,4/n.y]),t.lineWidth=1/n.x,t.strokeStyle="black",t.stroke(),t.setLineDash([]),t.closePath()}}class Od{constructor(t){this.layer=t}reset(){this.active=null}get selected(){return this.layer.selected}contains(t,e,n,r){const i=n.controls;return!!i&&(i.every((i,s)=>(Math.abs(t-i.x)<=4/r.x&&Math.abs(e-i.y)<=4/r.y&&(this.active={component:n,index:s,handler:i.handler}),!this.active)),!!this.active)}draw(t,e,n){const r=e.controls;r&&r.forEach((e,r)=>{t.beginPath(),t.lineWidth=1/n.x,t.ellipse(e.x,e.y,4/n.x,4/n.y,0,0,2*Math.PI,!0),t.fillStyle="#ff5d72",t.fill(),t.strokeStyle="#fff",t.stroke()})}onevent(t,e){const{handler:n,component:r,index:i}=this.active;let s=r.toLocal(e.offsetX,e.offsetY);s=r.toParent(s.x,s.y),n&&"function"==typeof n[t]&&n[t](s,i,r)}onmousedown(t){this.onevent("onmousedown",t)}ondragstart(t){const e=this.active;e.changes=zc.before([e.component]),this.onevent("ondragstart",t)}ondragmove(t){this.onevent("ondragmove",t)}ondragend(t){this.onevent("ondragend",t);const{component:e,changes:n}=this.active;zc.after(n,e.app.commander),e.parent&&e.parent.calculateBounds&&e.parent.calculateBounds()}}function zd(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}const Id=15*Math.PI/180;class Ld{constructor(t){this.layer=t}reset(){this.active=null,this.created=null}get selected(){return this.layer.selected}contains(t,e,n,r){return!!n.mutable&&(n.path.every((i,s)=>(Math.abs(t-i.x)<=4/r.x&&Math.abs(e-i.y)<=4/r.y&&(this.active={component:n,index:s}),!this.active)),!!this.active)}startLinkProcess(t,e,n){try{const r=Qc(e,t.app,void 0);return t.rootModel.addComponent(r),this.layer.selected=[r],this.active={component:r,index:1},this.ondragstart(n),r}catch(t){Rr(t)}}draw(t,e,n){if(!e.mutable||e.stuck)return;const r=e.path,i=this.active;r.forEach((r,s)=>{t.beginPath(),t.ellipse(r.x,r.y,4/n.x,4/n.y,0,0,2*Math.PI,!0),t.lineWidth=1/n.x,t.strokeStyle="#656565",t.fillStyle="#fff",i&&i.component===e&&i.index===s&&(t.strokeStyle="#fa7703",i.toFill&&(t.fillStyle="#ffb80c")),t.fill(),t.stroke()})}ondblclick(t){const e=this.active.component;if(!e.pathExtendable)return;const n=e.path.slice();n.length<3||(n.splice(this.active.index,1),e.path=n)}onmousedown(t){this.active.toFill=!0}ondragstart(t){const{index:e,component:n}=this.active;this.created||(this.active.changes=zc.before([n])),0!==e&&e!==n.path.length-1||(this.layer.counterEnd=0===e?n.toEnd||{fromto:"to"}:n.fromEnd||{fromto:"from"})}ondragmove(t){const{component:e,index:n}=this.active||{},{offsetX:r,offsetY:i}=t;let s=e.toLocal(r,i);if(s=e.toParent(s.x,s.y),t.shiftKey){const t=e.path.length;let r=e.isLine()&&0==n?e.path[1]:e.path[(n-1+t)%t];r=e.toParent(r.x,r.y);let i=0;if(t>2){let s;e.isLine()?0==n?s=e.path[2]:1!=n&&(s=e.path[n-2]):s=e.path[(n-2+t)%t],s&&(s=e.toParent(s.x,s.y),i=zd(s,r))}const c=Math.round((zd(r,s)-i)/Id)*Id+i;s=function(t,e,n){return{x:Math.cos(e)*n+t.x,y:Math.sin(e)*n+t.y}}(r,c,(o=r,a=s,Math.sqrt((a.x-o.x)*(a.x-o.x)+(a.y-o.y)*(a.y-o.y))))}var o,a;if(0===n||n===e.path.length-1){const t=this.layer.anchorTarget=e.rootModel.capture(r,i,t=>!t.isConnectable());if(t){const{x:o,y:a}=t.toLocal(r,i),c=this.layer.get("scale")||{x:1,y:1},l=this.layer.counterEnd,h=(t.anchors||[]).find(n=>{const{name:r,inout:i,multiplicity:s=1/0,position:h,filter:d}=n;if(l){const{anchor:t,fromto:e}=l;if(t&&("out"===t.inout&&"out"===i||"in"===t.inout&&"in"===i))return!1;if("from"===e&&"out"===i||"to"===e&&"in"===i)return!1}else jr("should not be here.");if(Math.abs(o-h.x)>8/c.x||Math.abs(a-h.y)>8/c.y)return!1;const u=t.findInOutLines(r);return!!u.includes(e)||!(s!==1/0&&u.length>=s)&&(!l||!d||!!d.call(n,l))});h?0==n?e.from={component:t.get("refid"),anchor:h.name,position:s}:e.to={component:t.get("refid"),anchor:h.name,position:s}:0==n?e.from={position:s}:e.to={position:s}}else 0==n?e.from={position:s}:e.to={position:s}}e.mutatePath(null,function(t){const e=t[n]?.z;t[n]=s,void 0!==e&&(s.z=e)})}ondragend(t){const{component:e,index:n,changes:r}=this.active;if(0===n||n===e.path.length-1){const{offsetX:r,offsetY:i}=t,s=e.rootModel.capture(r,i,t=>t===e||t.isLine()),{x:o,y:a}=s.toLocal(r,i),c=this.layer.get("scale")||{x:1,y:1},l=(s.anchors||[]).find(t=>t&&Math.abs(o-t.position.x)<=8/c.x&&Math.abs(a-t.position.y)<=8/c.y);l&&(0==n?e.from={component:s.get("refid"),anchor:l.name}:e.to={component:s.get("refid"),anchor:l.name}),this.layer.endLinkProcess()}if(this.created){const t=new Xc({changes:[{component:this.created,to_container:this.created.parent}]});this.created.app.commander.execute(t)}else zc.after(r,e.app.commander);e.parent&&e.parent.calculateBounds&&e.parent.calculateBounds()}}function jd(t,e,n){return t.filter(t=>{const{name:r,inout:i,multiplicity:s=1/0,filter:o}=t;if(n){const{anchor:t,fromto:e}=n;if(t&&("out"===t.inout&&"out"===i||"in"===t.inout&&"in"===i))return!1;if("from"===e&&"out"===i||"to"===e&&"in"===i)return!1}else if("in"===i)return!1;return!(s!==1/0&&e.findInOutLines(r).length>=s)&&(!o||!n||!!o.call(t,n))})}class Rd{constructor(t){this.layer=t}get active(){return this._active?.component.disposed&&(this._active=null),this._active}set active(t){this._active=t}reset(){this.active=null}contains(t,e,n,r){const i=this.active?.component===n&&this.active?.anchor;this.active=null;const s=this.layer.counterEnd;return jd(n.isConnectable()&&!n.disposed&&this.getAnchorHandles(n,r)||[],n,s).every(s=>{const o=i===s.name?2:1;return s&&s.position&&Math.abs(t-s.position.x)<=4*o/r.x&&Math.abs(e-s.position.y)<=4*o/r.y&&(this.active={component:n,anchor:s.name,template:s.template}),!this.active}),!!this.active}getAnchorHandles(t,e){const{width:n,height:r}=t.bounds;return n*e.x<30||r*e.y<30?[]:t.anchors}draw(t,e,n){if(!e.get("refid")||e.isLine())return;const r=this.active,i=this.active?.component===e&&this.active?.anchor,s=this.layer.counterEnd;jd(e.isConnectable()&&!e.disposed&&this.getAnchorHandles(e,n)||[],e,s).forEach(s=>{const{name:o,position:a}=s,c=i===o?2:1;a&&(t.beginPath(),t.ellipse(a.x,a.y,4*c/n.x,4*c/n.y,0,0,2*Math.PI),t.setLineDash([0,0]),t.lineWidth=1/n.x,t.strokeStyle="#656565",t.stroke(),t.fillStyle="#fff",r&&r.component===e&&r.anchor===o&&(t.strokeStyle="#fa7703",r.focus&&(t.fillStyle="#ffb80c")),t.fill(),t.stroke())})}onmousedown(t){this.active.focus=!0}ondragstart(t){const{component:e,anchor:n,template:r}=this.active,i=this.layer.toLocal(t.offsetX,t.offsetY);this.layer.startLinkProcess(e,{type:"ortholine",lineWidth:1,strokeStyle:"black",begin:"oval",beginSize:"size9",end:"arrow",endSize:"size9",lineDash:"solid",lineCap:"butt",round:10,...r,from:{component:e.get("refid"),anchor:n,position:i},to:{position:i}},t)}ondragmove(t){}ondragend(t){}}function Fd(t,e){const{left:n,top:r,width:i,height:s}=t,o=n+i/2,a=r+s/2,c=n+i,l=r+s,h=i*e.x>50,d=s*e.y>50;return[{x:n,y:r},h?{x:o,y:r}:{x:null,y:null},{x:c,y:r},d?{x:c,y:a}:{x:null,y:null},{x:c,y:l},h?{x:o,y:l}:{x:null,y:null},{x:n,y:l},d?{x:n,y:a}:{x:null,y:null}]}class Bd{constructor(t){this.layer=t}reset(){this.active=null}get selected(){return this.layer.selected}contains(t,e,n,r){if(!n.resizable)return!1;const i=Fd(n.bounds,r);for(let s=0;s<i.length;s++){const o=i[s];if(null!=o.x&&null!=o.y&&Math.abs(t-o.x)<=4/r.x&&Math.abs(e-o.y)<=4/r.y)return this.active={component:n,index:s},!0}return!1}draw(t,e,n){if(e.isLine())return;const{left:r,top:i,width:s,height:o}=e.bounds;if(t.beginPath(),t.rect(r-4/n.x,i-4/n.y,s+8/n.x,o+8/n.y),t.setLineDash([3/n.x,4/n.y]),t.lineWidth=1/n.x,t.strokeStyle="black",t.stroke(),t.setLineDash([]),!e.resizable)return;const a=this.active;Fd(e.bounds,n).forEach((r,i)=>{null!=r.x&&null!=r.y&&(t.beginPath(),t.rect(r.x-4/n.x,r.y-4/n.y,8/n.x,8/n.y),t.setLineDash([]),t.strokeStyle="#656565",t.stroke(),t.fillStyle="#fff",a&&a.component===e&&a.index===i&&(t.strokeStyle="#fa7703",a.focus&&(t.fillStyle="#ffb80c")),t.fill(),t.stroke())})}onmousedown(t){this.active.focus=!0}ondragstart(t){const{component:e}=this.active;this.active.bounds=e.bounds,this.active.boundsList=this.layer.selected.filter(t=>t.resizable).map(t=>t.bounds)}_resizeAll(t,e){const{component:n,index:r,boundsList:i,bounds:s}=this.active,o=n.scalable?this.layer.toLocal(t.offsetX,t.offsetY):{x:t.offsetX,y:t.offsetY};n.bounds=s;const a=function(t,e,n){const{left:r,top:i,width:s,height:o}=t.bounds;let a,c;switch(e){case 0:a=r,c=i;break;case 1:a=r+s/2,c=i;break;case 2:a=r+s,c=i;break;case 3:a=r+s,c=i+o/2;break;case 4:a=r+s,c=i+o;break;case 5:a=r+s/2,c=i+o;break;case 6:a=r,c=i+o;break;case 7:a=r,c=i+o/2}const l=a,h=c,d=t.fromScene(n.x,n.y);return{dx:d.x-l,dy:d.y-h}}(n,r,o);this.layer.selected.filter(t=>t.resizable).forEach((n,s)=>{n.bounds=i[s],function(t,e,n,r,i,s){let{left:o,top:a,width:c,height:l}=t.bounds;const h={left:o,top:a,width:c,height:l};switch(e){case 0:o+=r,a+=i,c-=r,l-=i;break;case 1:a+=i,l-=i;break;case 2:a+=i,c+=r,l-=i;break;case 3:c+=r;break;case 4:c+=r,l+=i;break;case 5:l+=i;break;case 6:o+=r,c-=r,l+=i;break;case 7:o+=r,c-=r}if(t.mutateBounds(function(e){return Math.abs(c)<=.001&&(c=.001),Math.abs(l)<=.001&&(l=.001),t.adjustResize({left:o,top:a,width:c,height:l},h,n)},this),t.isContainer()&&t.layout.ABSOLUTE&&!t.isGroup()){const e=h.left-o,n=h.top-a;return void(s?t.components.forEach(t=>{t.delta("tx",0),t.delta("ty",0),t.move({x:e,y:n},!1)}):t.components.forEach(t=>{t.delta("tx",e),t.delta("ty",n)}))}const d=s&&t.parent;d&&d.isGroup()&&d.calculateBounds()}(n,r,t.shiftKey,a.dx,a.dy,e)})}ondragmove(t){this._resizeAll(t,!1)}ondragend(t){this._resizeAll(t,!0),this.active.component.app.commander.execute(null,!1)}}const Nd=2*Math.PI,Hd=Math.PI/2;function Vd(t,e){const n=t.bounds;return{x:n.left+n.width/2,y:n.top-20/e.y}}class Gd{constructor(t){this.layer=t}reset(){this.active=null}get selected(){return this.layer.selected}contains(t,e,n,r){if(!n.rotatable)return!1;const i=Vd(n,r);return Math.abs(t-i.x)<=4/r.x&&Math.abs(e-i.y)<=4/r.y&&(this.active={component:n},!0)}draw(t,e,n){if(!e.rotatable)return;t.beginPath();const r=Vd(e,n);t.lineWidth=1.5/n.x,t.moveTo(r.x,r.y+20/n.y),t.lineTo(r.x,r.y),t.strokeStyle="#656565",t.stroke(),t.beginPath(),t.ellipse(r.x,r.y,4/n.x,4/n.y,0,0,Nd,!0),t.stroke(),t.fillStyle="#fff",t.fill();const i=this.active;i&&i.component===e&&(t.strokeStyle="#fa7703",t.stroke(),i.toFill&&(t.fillStyle="#ffb80c",t.fill()))}onmousedown(t){this.active.toFill=!0}ondragstart(t){const e=this.active;e.start_rotation=e.component.get("rotation"),e.rotations=this.layer.selected.filter(t=>t.rotatable).map(t=>t.get("rotation"))}ondragmove(t){const{component:e}=this.active;let n;e.scalable?(n=e.toLocal(t.offsetX,t.offsetY),n=e.toParent(n.x,n.y)):(n={x:t.offsetX,y:t.offsetY},e.parent?.isRootModel()||(n=e.toParent(n.x,n.y)));const r=e.rotatePoint,i=e.get("rotation")||0;let s=Math.atan((r.y-n.y)/(r.x-n.x));s=r.x>=n.x?s-Hd:Hd+s;const o=s-i;this.layer.selected.filter(t=>t.rotatable).forEach((e,n)=>{const r=((e.get("rotation")||0)+o)%Nd;e.set("rotation",e.adjustRotation(r,t.shiftKey))})}ondragend(t){const{component:e}=this.active;e.app.commander.execute(null,!1)}}Fa.register("modeling-layer",class extends mc{constructor(t,e){super(t,e),this.pathHandler=new Ld(this);const n=this.pathHandler,r=new Od(this),i=new Bd(this),s=new Gd(this);this._modelers=[n,r,i,s],this._control_mode_modelers=[r,n,i,s],this.focusOutline=new Td(this),this.groupOutline=new Dd(this),this.anchorHandler=new Rd(this),this._reversed_modelers=this._modelers.slice().reverse(),this._control_mode_reverse_modelers=this._control_mode_modelers.slice().reverse(),this.hovered=null,this.hoveredDest=null}get modelers(){return this._control_mode?this._control_mode_modelers:this._modelers}get reversedModelers(){return this._control_mode?this._control_mode_reverse_modelers:this._reversed_modelers}async ready(){await super.ready();const t=this.rootModel,e=t.get("translate"),n=t.get("scale");this.set("translate",e),this.set("scale",n)}capture(t,e,n){return!!this.contains(t,e)&&this}contains(t,e){let n=this.selected.filter(t=>!!t.parent);const r=this.fromParent(t,e),i=this.get("scale")||{x:1,y:1};let s;if(this._state_dragging){if(this._counter_end){let n=i;if(this.anchorTarget.scalable?s=this.anchorTarget.fromScene(r.x,r.y):(s=this.anchorTarget.fromScene(t,e),n={x:1,y:1}),this.anchorHandler.contains(s.x,s.y,this.anchorTarget,n))return!0}return!0}this.modelers.forEach(t=>t.reset()),n=this.selected.filter(t=>!!t.parent);for(let o=0;o<n.length;o++){const a=n[o];let c=i;a.scalable?s=a.fromScene(r.x,r.y):(s=a.fromScene(t,e),c={x:1,y:1});for(let t=0;t<this.modelers.length;t++){const e=this.modelers[t];if(e.contains(s.x,s.y,a,c))return this.currentModeler=e,!0}}if(this.anchorTarget){let n=i;if(this.anchorTarget.scalable?s=this.anchorTarget.fromScene(r.x,r.y):(s=this.anchorTarget.fromScene(t,e),n={x:1,y:1}),this.anchorHandler.contains(s.x,s.y,this.anchorTarget,n))return this.currentModeler=this.anchorHandler,!0}else this.anchorHandler.reset();return this.currentModeler=null,!1}_componentDrawer(t,e,n,r){const i=[];let s=e.parent;if(e.isRootModel())return t.save(),r(t,e,n),void t.restore();for((t=this.getContext(e))==this.auxContext2D&&(n={x:1,y:1});s&&!s.isRootModel();)i.push(s),s=s.parent;t.save(),i.reverse().forEach(function(e){const n=e.rotatePoint;t.translate(n.x,n.y);const r=e.get("scale");r&&t.scale(r.x,r.y),t.rotate(e.get("rotation")),t.translate(-n.x,-n.y);const i=e.bounds;t.translate(i.left,i.top)});const o=e.rotatePoint;t.translate(o.x,o.y);const a=e.get("scale");a&&t.scale(a.x,a.y),t.rotate(e.get("rotation")),t.translate(-o.x,-o.y),r(t,e,n),t.restore()}prerender(t){const{translate:e,scale:n={x:1,y:1},rotation:r}=this.model;t.save(),t.beginPath(),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.rect(0,0,t.canvas.width,t.canvas.height),t.fillStyle="black",t.globalAlpha=.5,t.fill(),t.restore(),e&&t.translate(e.x*_i,e.y*_i),t.scale(n.x*_i,n.y*_i),r&&t.rotate(r),t.clearRect(0,0,this.rootModel.get("width"),this.rootModel.get("height"))}render(t){if(this.rootModel?.is3dMode)return;t.beginPath();const e=this.get("scale")||{x:1,y:1},n=this.selected.filter(t=>!!t.parent);if(this.anchorTarget&&this._componentDrawer(t,this.anchorTarget,e,(t,e,n)=>{this.anchorHandler.draw(t,e,n)}),this.focused&&this._componentDrawer(t,this.focused,e,(t,e,n)=>{this.focusOutline.draw(t,e,n)}),n.length>0&&n[0].parent.isGroup()){let r=n[0].parent;for(;r.parent.isGroup();)r=r.parent;this._componentDrawer(t,r,e,(t,e,n)=>{this.groupOutline.draw(t,e,n)})}n.forEach(n=>{this._componentDrawer(t,n,e,(t,e,n)=>{this.reversedModelers.forEach(r=>r.draw(t,e,n))})})}get anchorTarget(){return this.currentModeler===this.anchorHandler||this.currentModeler===this.pathHandler||this.hovered?.isLine()||(this._anchorTarget=this.hovered),this._anchorTarget}set anchorTarget(t){this._anchorTarget=t}get hovered(){return this._hovered}set hovered(t){this._hovered=t,this.invalidate()}startLinkProcess(t,e,n){this.currentModeler=this.pathHandler,this.processingLink=this.pathHandler.startLinkProcess(t,e,n),this.counterEnd=this.processingLink.fromEnd,this.processingLink.trigger("tag")}set counterEnd(t){this.currentModeler=this.pathHandler,this._counter_end=t}get counterEnd(){return this._counter_end}endLinkProcess(){this.processingLink?.trigger("tagreset"),this.processingLink=null,this._counter_end=null}get eventMap(){return{"model-layer":{"(all)":{change:this.onchange_model,wheel:this.onwheel_scale,drop:this.ondrop},"(descendant)":{mouseenter:this.onmouseenter,mouseleave:this.onmouseleave},"(self)":{dblclick:this.ondblclick_model}},"(root)":{"(self)":{selected:this.onselected,keydown:this.onkeydown,keyup:this.onkeyup}}}}onmouseenter(t,e){this.hovered=e?.origin}onmouseleave(t,e){this.hovered=null}onkeydown(t){"Alt"==t.key&&(this._control_mode=!0,this.invalidate())}onkeyup(t){"Alt"==t.key&&(this._control_mode=!1,this.invalidate())}onselected(t,e){this.invalidate()}onchange_model(t,e,n){const{origin:r,deliverer:i}=n;r===i&&(t.translate&&this.set("translate",t.translate),void 0!==t.rotation&&this.set("rotation",t.rotation),t.scale&&this.set("scale",t.scale)),this.invalidate()}ondblclick_model(t,e){const n=e.origin;n?.root.fit()}ondblclick(t){"function"==typeof this.currentModeler.ondblclick&&this.currentModeler.ondblclick(t),this.invalidate()}onmousedown(t){this.currentModeler.onmousedown(t),this.invalidate()}onmouseup(t){"function"==typeof this.currentModeler.onmouseup&&this.currentModeler.onmouseup(t),this.invalidate()}ondragstart(t){this.currentModeler.ondragstart(t),this._state_dragging=!0}ondragmove(t){this.currentModeler.ondragmove(t),this.invalidate()}ondragend(t){this._state_dragging=!1,this.currentModeler.ondragend(t),this.invalidate()}ondrop(t,e){const{origin:n}=e,r=t.dataTransfer.files;if(r.length<1)return;const i=this.rootModel.toLocal(t.offsetX,t.offsetY),s=this.rootModel;Promise.all(Array.from(r).map(t=>new Promise((e,n)=>{const r=new FileReader;r.addEventListener("loadend",t=>{e(r.result)}),["error","abort"].forEach(t=>r.addEventListener(t,t=>{n(t)})),r.readAsDataURL(t)}))).then(e=>{if(t.altKey)return zc.around(this.app.commander,()=>{n.ondropfile(r,e)}),void(this.selected=[n]);const o=[],a=e.map((t,e)=>{let n;const a=r[e].type,c=r[e].name;return a.startsWith("image/")?(n=Qc({type:a.startsWith("image/gif")?"gif-view":"image-view",top:0,left:0,width:200,height:200,src:t},s.app),o.push(new Promise((e,r)=>{const i=new Image;i.src=t,i.onload=()=>{n.set({width:i.width,height:i.height}),e()},i.onerror=t=>{r(t)}}))):a.startsWith("audio/")?n=Qc({type:"audio",top:0,left:0,width:100,height:100,src:t},s.app):a.startsWith("vnd.ms-excel/")||/\.xlsx?$/.test(c)?n=Qc({type:"excel",top:0,left:0,width:100,height:100,src:t},s.app):Fr("dropped file",r[e]),n&&(n.center=i,i.x+=50,i.y+=50),n}).filter(Boolean).map(t=>({component:t,to_container:s}));a.length>0&&Promise.all(o).then(()=>{this.app.commander.execute(new Xc({changes:a})),this.selected=a.map(t=>t.component)},t=>{jr(t)})},t=>{jr(t)})}onwheel_scale(t,e){if(0==t.deltaY&&0==t.deltaX)return;const n=e.deliverer;let r;if(t.shiftKey)r=-1!=navigator.userAgent.indexOf("Win")?t.deltaY<0?1:-1:t.deltaX<0?1:-1,t.altKey?zc.around(this.app.commander,()=>{n.selected.forEach(t=>{let e=t.get("letterSpacing")||Mi.LETTER_SPACING;e+=r,t.set("letterSpacing",e)})}):zc.around(this.app.commander,()=>{n.selected.forEach(t=>{let e=t.get("fontSize")||Mi.FONT_SIZE;e<1&&(e=1),e+=r,t.set("fontSize",e)})});else{r=t.deltaY<0?1:-1;const e=n.get("scale")||{x:1,y:1},i=n.get("translate"),s=t.offsetX,o=t.offsetY,a=n.toLocal(s,o),c=.1*r,l={x:e.x+c,y:e.y+c};if(r<0&&e.x<.2||r>0&&e.x>10)return;n.set("scale",l);const h=n.toLocal(s,o);n.set("translate",{x:i.x+(h.x-a.x)*l.x,y:i.y+(h.y-a.y)*l.y})}}});Fa.register("scroll-layer",class extends gc{get capturable(){return!0}get pointerEvents(){return"none"}render(t){const{scrolling:e}=this.state;if(t.save(),t.beginPath(),t.fillStyle="#777",this.vscroller){const{left:n,top:r,width:i,height:s}=this.vscroller;t.globalAlpha="v"==e?1:.3,t.fillRect(n,r,i,s)}if(this.hscroller){const{left:n,top:r,width:i,height:s}=this.hscroller;t.globalAlpha="h"==e?1:.3,t.fillRect(n,r,i,s)}t.stroke(),t.restore()}resize(){super.resize(),this.calcScrollerBounds()}contains(t,e){const n=this.vscroller,r=this.hscroller;return this.setState("scrolling",n&&t>=n.left&&t<=n.left+n.width&&e>=n.top&&e<=n.top+n.height?"v":r&&t>=r.left&&t<=r.left+r.width&&e>=r.top&&e<=r.top+r.height?"h":null),!!this.getState("scrolling")}get eventMap(){return{"(root)":{"model-layer":{change:this.onchangeModelLayer}}}}onchange(t){"scrolling"in t&&this.invalidate()}ondragstart(t,e){this.lastPosition={x:t.offsetX,y:t.offsetY}}ondragmove(t,e){const n=this.root,{clientWidth:r,clientHeight:i}=this.canvas,{width:s,height:o}=this.rootModel.model,{x:a,y:c}={x:t.offsetX,y:t.offsetY},{x:l,y:h}=this._scale,{scrolling:d}=this.state,u=s/r,p=o/i;d&&n.rootModel.move({x:"h"==d?(-a+this.lastPosition.x)*l*u:0,y:"v"==d?(-c+this.lastPosition.y)*h*p:0},!1),this.lastPosition={x:t.offsetX,y:t.offsetY}}ondragend(){delete this.lastPosition,this.setState({scrolling:null})}calcScrollerBounds(){if(!this.rootModel)return;const{clientWidth:t,clientHeight:e}=this.canvas,{width:n,height:r}=this.rootModel.model,{x:i=1,y:s=1}=this._scale||{},{x:o=0,y:a=0}=this._translate||{},c=n/t,l=r/e;let h={left:-o/i/c,top:e-10,width:t/i/c,height:10};this.hscroller=h.left>1||h.width+h.left<t-1?h:null,h={left:t-10,top:-a/s/l,width:10,height:e/s/l},this.vscroller=h.top>1||h.height+h.top<e-1?h:null,this.invalidate()}onchangeModelLayer(t,e,n){if(t.scale){const{x:e=1,y:n=1}=t?.scale||{};this._scale={x:e,y:n},this.calcScrollerBounds()}if(t.translate){const{x:e=0,y:n=0}=t.translate||{};this._translate={x:e,y:n},this.calcScrollerBounds()}}});const Yd="#ff3366",Ud=[3,3];function $d(){const t=arguments,e=t[t.length-1],n=this.event_pump;n.listeners.forEach(r=>{!function(t,e,n,r,i){for(const s in n){const o=n[s];if(ca(s,r.origin,0,t))for(const t in o){const n=o[t];t==r.name&&(r.listener=e,n.apply(e,i))}}}(n.deliverer,r.listener,r.cloned_handlers,e,t)})}Fa.register("snap-guide-layer",class extends gc{constructor(){super(...arguments),this._snapResult=null}get pointerEvents(){return"none"}get capturable(){return!1}contains(t,e){return!1}get snapResult(){return this._snapResult}set snapResult(t){this._snapResult=t,this.invalidate()}clear(){this._snapResult&&(this._snapResult=null,this.invalidate())}get eventMap(){return{"(root)":{"model-layer":{change:this.onchange_root_model}}}}onchange_root_model(t){(t.translate||t.scale)&&this.syncTransform()}syncTransform(){const t=this.rootModel;if(!t)return;const e=t.get("translate")||{x:0,y:0},n=t.get("scale")||{x:1,y:1};this.set({translate:e,scale:n})}async ready(){await super.ready(),this.syncTransform()}render(t){const e=this._snapResult;if(e&&0!==e.guides.length){t.save(),t.strokeStyle=Yd,t.fillStyle=Yd,t.lineWidth=1,t.setLineDash(Ud);for(let n=0,r=e.guides.length;n<r;n++){const r=e.guides[n];t.beginPath(),"x"===r.axis?(t.moveTo(r.position,r.from),t.lineTo(r.position,r.to)):(t.moveTo(r.from,r.position),t.lineTo(r.to,r.position)),t.stroke()}t.restore()}}});class Wd{constructor(t){if(void 0===t.on)throw new Error("Deliverer should be a event handlable object.");this.deliverer=t,this.listeners=[]}start(){this.deliverer.on("(all)",$d,{event_pump:this})}stop(){this.deliverer.off("(all)",$d)}on(t,e){const n=Object.assign({},e);Object.keys(n).forEach(e=>{if(0==e.indexOf("?")){const r=n[e],i=e.substr(1),s=t.get(i);delete n[e],s?n[s]=r:Rr("EventPump#on","variable #{selector} is not evaluated on listener")}}),this.listeners.push({listener:t,handlers:e,cloned_handlers:n})}off(t,e){for(let n=0;n<this.listeners.length;n++){const r=this.listeners[n];r.listener!==t||e&&r.handlers!==e||this.listeners.splice(n,1)}}clear(){this.listeners=[]}dispose(){this.stop(),this.clear()}}class Xd{constructor(t){this.eventMaps=[],this.root=t,t.eventMap&&this.add(t,t.eventMap)}set root(t){this._root=t}get root(){return this._root}stop(){this.eventMaps.forEach(t=>t.eventPump.stop())}add(t,e){if(this.root)for(const n in e){const r=e[n];if("(self)"===n&&void 0===t.on)throw new Error("(self) selector not available when deliverer is not a event handlable object.");da(n,this.root,t).forEach(n=>{const i=new Wd(n);i.on(t,r),i.start(),this.eventMaps.push({eventPump:i,listener:t,handlerMap:e,deliverer:n})})}}remove(t,e){const n=this.eventMaps.slice(0);for(let r=0;r<n.length;r++){const i=n[r];i.listener!==t||e&&i.handlerMap!==e||(this.eventMaps.splice(r,1),i.eventPump.dispose())}}clear(){this.eventMaps.slice(0).forEach(t=>t.eventPump.dispose()),this.eventMaps=[]}dispose(){this.stop(),this.clear()}}const qd=0,Kd=1,Qd=2,Zd=0,Jd=1,tu=2;let eu={},nu=0;class ru{constructor(t,e){this._type=e||t.type,this._ctrlKey=t.ctrlKey,this._altKey=t.altKey,this._shiftKey=t.shiftKey,this._metaKey=t.metaKey;const n=function(t){if(t.touches){const e=t.touches[0];if(!e)return eu;const n=e.target.getBoundingClientRect();return eu={x:t.offsetX||e.clientX-n.left,y:t.offsetY||e.clientY-n.top},eu}return{x:t.offsetX,y:t.offsetY}}(t);if(this._offsetX=n.x,this._offsetY=n.y,t.touches&&t.touches[0]?(this._clientX=t.touches[0].clientX,this._clientY=t.touches[0].clientY):(this._clientX=t.clientX,this._clientY=t.clientY),"wheel"==t.type)this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ;else if("drop"==t.type)this.dataTransfer=t.dataTransfer;else if(t.type.match(/^touch/)&&(this._scale=t.scale,this._touches=t.touches,this._changedTouches=t.changedTouches,null==this._scale)){const e=function(t){let e,n,r=0,i=0,s=0;if(1===t.touches.length)return s;Array.from(t.touches).forEach(t=>{e=null!=e?Math.min(t.screenX,e):t.screenX,r=Math.max(t.screenX,r),n=null!=n?Math.min(t.screenY,n):t.screenY,i=Math.max(t.screenY,i)});const o=r-e||0,a=i-n||0;return s=Math.sqrt(Math.pow(o,2)+Math.pow(a,2))||0,s}(t);nu>0&&(this._scale=e/nu),nu=e}}get type(){return this._type}set type(t){this._type=t}get offsetX(){return this._offsetX}get offsetY(){return this._offsetY}get altKey(){return this._altKey}get ctrlKey(){return this._ctrlKey}get shiftKey(){return this._shiftKey}get metaKey(){return this._metaKey}get clientX(){return this._clientX}get clientY(){return this._clientY}get touches(){return this._touches}get changedTouches(){return this._changedTouches}get scale(){return this._scale}stopPropagation(){this._stop_=!0,this.originalEvent?.stopPropagation()}isPropagationStopped(){return this._stop_}preventDefault(){this._prevented=!0}isDefaultPrevented(){return this._prevented}}function iu(t,e,n){if(!t||!t.app)return;if(t.app.isViewMode&&t.hidden)return;n instanceof ru&&e===n.type||(n=new ru(n,e));const r="on"+e;t[r]&&t[r](n),n.isPropagationStopped()||t.trigger(e,n)}class su{constructor(t,e){this.gestureHandlerBuilder=t=>{const e=this[`on${t}`];return t=>{const n=new ru(t),r=this.getChildScrollOffset();return n._offsetX+=this.html_element.scrollLeft+r.scrollLeft,n._offsetY+=this.html_element.scrollTop+r.scrollTop,e(n),n.isDefaultPrevented()&&t.preventDefault(),!1}},this.keyeventHandlerBuilder=t=>this[`on${t}`],this.ondragover=t=>(iu(this.findTarget(t),t.type,t),!1),this.ondrop=t=>(iu(this.findTarget(t),t.type,t),!1),this.ondblclick=t=>(iu(this.findTarget(t),t.type,t),this.last_target=null,!1),this.onkeydown=t=>(this.container.trigger(t.type,t),!1),this.onkeyup=t=>(this.container.trigger(t.type,t),!1),this.onmousemove=t=>{switch(this.status){case Kd:const e=t.offsetX-this.__dragstart_e.offsetX,n=t.offsetY-this.__dragstart_e.offsetY;if(e*e+n*n<16)break;this.status=Qd,iu(this.last_target,"dragstart",this.__dragstart_e),this.__dragmove_e=t,iu(this.last_target,"dragmove",t);break;case Qd:this.__dragmove_e=t,iu(this.last_target,"dragmove",t);break;default:{const e=this.findTarget(t);this.last_enter_target!==e&&(this.last_enter_target&&iu(this.last_enter_target,"mouseleave",t),e&&iu(e,"mouseenter",t),this.last_enter_target=e),iu(e,t.type,t),this.last_target=e}}return!1},this.onmousedown=t=>{if(this.status===Qd)iu(this.last_target,"dragend",t),this.last_target=null,this.status=qd;else{const e=this.findTarget(t);this.last_target=e,this.status=Kd,this.__dragstart_e=t,iu(e,t.type,t)}return!1},this.onmouseup=t=>{if(this.status===Qd)iu(this.last_target,"dragend",t);else{const e=this.findTarget(t);iu(e,t.type,t),this.last_target===e&&iu(e,"click",t)}return this.last_target=null,this.status=qd,!1},this.onmouseout=t=>{const e=this.findTarget(t);if(this.status===Qd)iu(this.last_target,"dragend",t);else{if(this.last_target&&this.last_target===e)return;this.last_enter_target&&(iu(this.last_enter_target,"mouseleave",t),delete this.last_enter_target)}return this.last_target=null,this.status=qd,!1},this.ontouchstart=t=>{const e=this.findTarget(t);return this.last_target=e,this.status=Jd,this.touchPoints||(this.touchPoints=[]),this.touchPoints.push(t.changedTouches[0]),this.holdTimer=setTimeout(()=>{this.status=Zd,iu(this.last_target,"hold",t),delete this.holdTimer},500),iu(e,t.type,t),!1},this.ontouchmove=t=>{if(!t.touches||!t.changedTouches)return iu(this.last_target,"dragstart",t),iu(this.last_target,"dragmove",t),!1;let e=this.findTarget(t);switch(this.status){case Jd:Array.from(t.changedTouches).forEach(t=>{const e=this.touchPoints.find(e=>e.identifier===t.identifier);if(!e)return;const n=e.clientX-t.clientX,r=e.clientY-t.clientY;return Math.sqrt(Math.pow(n,2)+Math.pow(r,2))>=16?(this.status=tu,void(this.holdTimer&&(clearTimeout(this.holdTimer),delete this.holdTimer))):void 0});break;case tu:if(this.holdTimer&&(clearTimeout(this.holdTimer),delete this.holdTimer),2===t.changedTouches.length&&null!=t.scale&&1!==t.scale&&(t.scale<.9||t.scale>1.1))return iu(this.last_target,"pinch",t),!1;iu(this.last_target,"pan",t),e=this.last_target;break;default:this.last_enter_target!==e&&(this.last_enter_target&&iu(this.last_enter_target,"mouseleave",t),e&&iu(e,"mouseenter",t),this.last_enter_target=e),this.last_target=e}return iu(e,"touchmove",t),!1},this.ontouchend=t=>{let e=this.findTarget(t);switch(this.status){case tu:e=this.last_target;break;case Jd:{const n=performance.now(),r=n-this.touchedAt;this.holdTimer&&(clearTimeout(this.holdTimer),delete this.holdTimer,iu(e,r<500?"doubletap":"tap",t),this.touchedAt=n);break}}iu(e,"touchend",t);const n=this.touchPoints.findIndex(e=>e.identifier===t.changedTouches[0].identifier);return this.touchPoints.splice(n,1),this.last_target=null,this.status=Zd,!1},this.onwheel=t=>(iu(this.findTarget(t),t.type,t),!1),this.container=t,this.html_element=e,this.status=qd,this.last_target=null,this.gesture_handlers=xi.map(t=>this.gestureHandlerBuilder(t)),this.keyevent_handlers=wi.map(t=>this.keyeventHandlerBuilder(t)),xi.forEach((t,n)=>e.addEventListener(t,this.gesture_handlers[n]),{passive:!1}),wi.forEach((t,n)=>e.addEventListener(t,this.keyevent_handlers[n])),e.ondragover=this.gestureHandlerBuilder("dragover"),e.ondrop=this.gestureHandlerBuilder("drop"),e.tabIndex=1}dispose(){this.last_enter_target&&iu(this.last_enter_target,"mouseleave",new CustomEvent("mouseleave")),xi.forEach((t,e)=>this.html_element.removeEventListener(t,this.gesture_handlers[e])),wi.forEach((t,e)=>this.html_element.removeEventListener(t,this.keyevent_handlers[e])),delete this.gesture_handlers,delete this.keyevent_handlers,delete this.last_target}getChildScrollOffset(){for(const t of this.html_element.children)if(t.scrollTop>0||t.scrollLeft>0)return{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop};return{scrollLeft:0,scrollTop:0}}findTarget(t){const e=this.container.rootModel;if(e?.is3dMode)return e;const n=this.html_element.getBoundingClientRect(),r=this.getChildScrollOffset(),i=t.clientX-n.left+this.html_element.scrollLeft+r.scrollLeft,s=t.clientY-n.top+this.html_element.scrollTop+r.scrollTop;return this.container.capture(i,s)}}function ou(t,e,n,r=0){if(e.length<2)return e;let i=2;for(;i<e.length;i++){const s=e.substring(0,i);if(!(t.measureText(s).width+(s.length-1)*r<n))break}return e.substring(0,i-1)}function au(t,e,n,r,i=0){const s=String(e).split("\n");return r?[].concat.apply([],s.map(e=>function(t,e,n,r=0){const i=e.split(" "),s=[];let o,a,c=[];for(o=0,a=1;a<=i.length;a++)if(c=i.slice(o,a),t.measureText(c.join(" ")).width+(c.join("").length-1)*r>n){if(a-o==1){const e=ou(t,c[0],n,r);s.push([e]),i.splice(o,1,e,c[0].substring(e.length))}else{for(;""==i[a-1];)a++;s.push(i.slice(o,--a))}o=a}return a-o>1&&s.push(c),0==s.length&&s.push([""]),s}(t,e,n,i))):s.map(t=>t.split(" "))}const cu={},lu={},hu=()=>{};var du={register:function(t,e,n){cu[t]=e,n&&(lu[t]=n)},unregister:function(t){delete cu[t],delete lu[t]},get:function(t){return cu[t]},getDisposer:function(t){return lu[t]||hu}};function uu(t){if(!t.hasTextProperty||t.textHidden)return;let{text:e="",bold:n=Mi.BOLD,italic:r=Mi.ITALIC,textWrap:i=Mi.TEXT_WRAP,letterSpacing:s=0,fontFamily:o=Mi.FONT_FAMILY,fontColor:a=Mi.FONT_COLOR,textAlign:c=Mi.TEXT_ALIGN,textBaseline:l=Mi.TEXT_BASELINE,fontSize:h=Mi.FONT_SIZE,lineHeight:d=1.2*h}=t.model;const{left:u,top:p,width:f,height:g}=t.textBounds;h||=Mi.FONT_SIZE,d||=1.2*h,t.textHidden=!0;const m=document.createElement("textarea"),y=new AbortController;xi.forEach(function(t){m.addEventListener(t,t=>t.stopPropagation(),{capture:!0,signal:y.signal})});const b=t.toGlobal(u,p),{rotation:v,scale:_}=function(t){let e=0,n=1,r=t;for(;r;){e+=r.get("rotation")||0;const{x:t,y:i}=r.get("scale")||{x:1,y:1};n*=Math.max(t,i)||1,r=r.parent}return{rotation:e,scale:n}}(t);m.value=e;const x={position:"absolute",width:f+"px",height:g+"px",padding:"0",fontFamily:o,fontSize:h+"px",lineHeight:d+"px",overflow:"hidden",resize:"none",outline:"none",border:"0",backgroundColor:"transparent",display:"inline-block",color:a};switch(n&&(x.fontWeight="bold"),r&&(x.fontStyle="italic"),c){case"right":case"end":x.textAlign="right";break;case"justify":x.textAlign="justify";break;case"left":case"start":x.textAlign="left";break;default:x.textAlign="center"}const w=[n,r,h+"px",o].filter(Boolean).join(" ");function M(e){const n={left:0,top:0},r=d*function(t,e,n,r,i=0){const s=t.getContext();let o;return s.save(),s.font=n,o=au(s,e,r,t.get("textWrap"),i).length,s.restore(),o}(t,e,w,f,s);switch(x.height=r+"px",l){case"top":case"hanging":break;case"bottom":case"alphabetic":n.top=g-r;break;default:n.top=g/2-r/2}if(!i){const r=function(t,e,n,r){const i=e.split("\n");let s=r;const o=t.getContext();return o.save(),o.font=n,i.forEach(t=>{const e=o.measureText(t).width;e>s&&(s=e)}),o.restore(),s}(t,e,w,f);switch(x.width=r+"px",c){case"right":case"end":n.left=f-r;break;case"left":case"start":break;default:n.left=(f-r)/2}}x.marginLeft=n.left+"px",x.marginTop=n.top+"px",x.transform=`translate(${b.x}px, ${b.y}px) scale(${_}) rotate(${v}rad)`,x.transformOrigin=`${-n.left}px ${-n.top}px`,Object.assign(m.style,x)}M(e);const S=t.root.target_element;S.appendChild(m),m.select();let A,E=!1;m.addEventListener("keydown",function(t){t.stopPropagation(),"Escape"!=t.code&&(t.shiftKey||"Enter"!=t.code&&"NumpadEnter"!=t.code)?setTimeout(()=>{M(m.value)}):(E=A.skipUpdate="Escape"==t.code,"function"==typeof document.createEvent?m.dispatchEvent(A):m.fireEvent(A.eventType,A))},{signal:y.signal}),document.createEvent?(A=document.createEvent("HTMLEvents"),A.initEvent("blur",!0,!1)):(A=document.createEventObject(),A.eventType="blur");const k=t.root.selected,C=function(n){t.root.selected=k,t.textHidden=!1,y.abort(),m.removeEventListener("blur",C,!1),m.parentElement&&m.parentElement.removeChild(m),S.focus(),n.skipUpdate||E||t.app.commander.execute(new zc({changes:[{component:t,before:{text:e},after:{text:m.value}}]}))};m.addEventListener("blur",C,!1)}du.register("text-editor",{"(root)":{"(self)":{keydown:function(t,e){const{deliverer:n}=e,r=n.selected;return!(1!==r.length||!r[0].hasTextProperty)&&(("Enter"==t.code||"NumpadEnter"==t.code)&&(uu(r[0]),t.preventDefault(),!0))}}},"model-layer":{"(descendant)":{dblclick:function(t,e){uu(e.origin)}}}});class pu{constructor(t){const e=[],n=[];for(let r=0,i=t.length;r<i;r++){const i=t[r],s=i.left,o=i.left+i.width,a=s+i.width/2,c=i.top,l=i.top+i.height,h=c+i.height/2;e.push({value:s,perpMin:c,perpMax:l},{value:a,perpMin:c,perpMax:l},{value:o,perpMin:c,perpMax:l}),n.push({value:c,perpMin:s,perpMax:o},{value:h,perpMin:s,perpMax:o},{value:l,perpMin:s,perpMax:o})}e.sort((t,e)=>t.value-e.value),n.sort((t,e)=>t.value-e.value),this.xEdges=e,this.yEdges=n}get empty(){return 0===this.xEdges.length&&0===this.yEdges.length}calculateSnap(t,e,n,r){if(0===this.xEdges.length&&0===this.yEdges.length)return{dx:e,dy:n,guides:[]};const i={left:t.left+e,top:t.top+n,width:t.width,height:t.height},s=i.left,o=s+i.width,a=s+i.width/2,c=i.top,l=c+i.height,h=c+i.height/2,d=this.findBestSnap(this.xEdges,[s,a,o],r),u=this.findBestSnap(this.yEdges,[c,h,l],r),p=d?e+d.correction:e,f=u?n+u.correction:n;if(!d&&!u)return{dx:e,dy:n,guides:[]};const g=[];if(d){const e=t.top+f,n=e+t.height;for(const t of d.matches)g.push({axis:"x",position:t.value,from:Math.min(e,t.perpMin),to:Math.max(n,t.perpMax)})}if(u){const e=t.left+p,n=e+t.width;for(const t of u.matches)g.push({axis:"y",position:t.value,from:Math.min(e,t.perpMin),to:Math.max(n,t.perpMax)})}return{dx:p,dy:f,guides:g}}findBestSnap(t,e,n){let r=n+1,i=0,s=[];for(let o=0;o<3;o++){const a=e[o],c=this.searchNearest(t,a,n);if(!c)continue;const l=Math.abs(c.correction);if(l<r)r=l,i=c.correction,s=c.matches;else if(l===r&&c.correction===i)for(const t of c.matches)s.push(t)}return r<=n?{correction:i,matches:s}:null}searchNearest(t,e,n){const r=t.length;if(0===r)return null;let i=0,s=r;for(;i<s;){const n=i+s>>1;t[n].value<e?i=n+1:s=n}let o=-1,a=n+1;if(i<r){const r=t[i].value-e;r<=n&&(o=i,a=r)}if(i>0){const n=e-t[i-1].value;n<a&&(o=i-1,a=n)}if(o<0||a>n)return null;const c=t[o].value,l=c-e,h=[t[o]];for(let e=o-1;e>=0&&t[e].value===c;e--)h.push(t[e]);for(let e=o+1;e<r&&t[e].value===c;e++)h.push(t[e]);return{correction:l,matches:h}}}function fu(t){const e=t.root;if(!e||!e.assist_layers)return null;for(const t of e.assist_layers)if("snap-guide-layer"===t.state?.type)return t;return null}const gu=Qn(function(t,e,n){if(!t.hasSameParentForAllSelected||n)return void(t.focused=null);const r=[];e[0].parent.isGroup()?t.focused=e[0].parent:(e.forEach(t=>{t.path.forEach(e=>{r.push(t.toScene(e.x,e.y))})}),t.focused=t.capturePath(r,e))},300);let mu,yu,bu;du.register("move-handler",{"model-layer":{"(descendant)":{dragstart:function(t,e){const{origin:n,deliverer:r}=e;if(n.stuck)return;let i=r.selected;const s=r.selected.filter(t=>!t.stuck);if(i.length!==s.length&&(i=r.selected=s),0==i.length)return;let o;if(i[0].scalable?(o=i[0].toLocal(t.offsetX,t.offsetY),o=i[0].toParent(o.x,o.y)):o={x:t.offsetX,y:t.offsetY},this.last_pos=o,this.direction=0,r.focused=i[0].parent,t.altKey){const t=[],e=new Map;r.selected=r.selected.filter(t=>!t.isRootModel()).map(n=>{const i=Zc(n,t=>{const n=r.root.getNewRefid();return void 0!==t&&e.set(t,n),n});return t.push({component:i,to_container:n.parent}),i}).map(t=>(t.replaceRefids(e),t)),t.forEach(({component:t,to_container:e})=>{e.addComponent(t)}),this.duplicates=r.selected.map(t=>({component:t}))}else this.changes=zc.before(i);this.snapIndex=function(t){if(0===t.length)return null;const e=t[0].parent;if(!e||!e.components)return null;const n=new Set(t),r=[];for(const t of e.components)t.isLayer?.()||t.stuck||n.has(t)||r.push(t.bounds);return 0===r.length?null:new pu(r)}(i);const a=n.rootModel?.get("scale"),c=a?(Math.abs(a.x)+Math.abs(a.y))/2:1;this.snapThreshold=5/(c||1)},dragmove:function(t,e){const{origin:n,deliverer:r}=e;if(n.stuck)return;const i=r.selected;if(0==i.length)return;let s;i[0].scalable?(s=i[0].toLocal(t.offsetX,t.offsetY),s=i[0].toParent(s.x,s.y)):s={x:t.offsetX,y:t.offsetY},t.shiftKey?2==this.direction&&(this.direction=0):this.direction=2;let o=s.x-this.last_pos.x,a=s.y-this.last_pos.y;if(0==this.direction){if(o*o+a*a<25)return;Math.abs(o)>Math.abs(a)?this.direction=3:this.direction=4}3==this.direction?a=0:4==this.direction&&(o=0);const c=this.snapIndex,l=c&&!t.metaKey&&!t.ctrlKey,h=o,d=a;if(l){const t=function(t){return 0===t.length?null:1===t.length?t[0].bounds:Ji(t.map(t=>t.bounds))}(i);if(t){const e=c.calculateSnap(t,o,a,this.snapThreshold);o=e.dx,a=e.dy;const n=fu(r);n&&(n.snapResult=e.guides.length>0?e:null)}}else{const t=fu(r);t&&(t.snapResult=null)}i.forEach(t=>{t.move({x:o,y:a},1===i.length)}),this.last_pos={x:s.x-(h-o),y:s.y-(d-a)},gu(r,i)},dragend:function(t,e){const{origin:n,deliverer:r}=e;if(n.stuck)return;const i=r.selected;if(0==i.length)return;const s=i[0].parent,o=r.focused||e.deliverer;if(this.changes&&!o.isGroup())if(r.hasSameParentForAllSelected&&o&&o!==s){const t=this.changes.map(t=>{const{component:e}=t;return{component:e,to_container:o}});r.app.commander.execute(new Xc({changes:t}))}else zc.after(this.changes,r.app.commander);else if(this.duplicates){this.duplicates=this.duplicates.map(t=>(t.to_container=o,t));const t=new Xc({changes:this.duplicates});r.app.commander.execute(t)}i.forEach(t=>{t.parent&&t.parent.calculateBounds&&t.parent.calculateBounds()}),this.last_pos=null,this.changes=null,this.duplicates=null,this.snapIndex=null,this.snapThreshold=5;const a=fu(r);a&&a.clear(),gu(r,i,!0)}}},"(root)":{"(self)":{keydown:function(t,e){const{origin:n,deliverer:r}=e,i={},s=t.shiftKey?n.rootModel.MPP:1;switch(t.which){case 37:i.x=-s,i.y=0;break;case 38:i.x=0,i.y=-s;break;case 39:i.x=s,i.y=0;break;case 40:i.x=0,i.y=s;break;default:return}const o=r.selected;zc.around(r.app.commander,function(){o.forEach(t=>{!t.stuck&&t.move(i,!1)})})}}}});const vu=Zn(()=>{const{x:t,y:e}=bu,n=yu.deref();n&&(n.rootModel.move({x:t-mu.x,y:e-mu.y},!1),mu={x:t,y:e})},60,{leading:!0,trailing:!0});du.register("shift-handler",{"model-layer":{"(all)":{dragstart:function(t,e){mu={x:t.offsetX,y:t.offsetY}},dragmove:function(t,e){yu=new WeakRef(e.deliverer),bu={x:t.offsetX,y:t.offsetY},vu()}}}}),du.register("zoom-handler",{"model-layer":{"(all)":{wheel:function(t,e){if(0==t.deltaY&&0==t.deltaX)return;const n=e.deliverer,r=t.deltaY<0?1:-1,i=n.get("scale")||{x:1,y:1},s=n.get("translate"),o=t.offsetX,a=t.offsetY,c=n.toLocal(o,a),l=.1*r,h={x:i.x+l,y:i.y+l};if(r<0&&i.x<.2||r>0&&i.x>10)return;n.set("scale",h);const d=n.toLocal(o,a);n.set("translate",{x:s.x+(d.x-c.x)*h.x,y:s.y+(d.y-c.y)*h.y})}},"(self)":{dblclick:function(t,e){const n=e.origin;n?.root.fit()}}}});let _u={},xu={};function wu(t){const e={};for(const n in t)t.hasOwnProperty(n)&&void 0!==t[n]&&(e[n]=t[n]);return e}du.register("paste-handler",{"(root)":{"(self)":{stylepastestart:function(t){const{deliverer:e}=t,n=e.app,r=e.selected;if(r&&r[0]&&r!==e.rootModel){const t=r[0],{fillStyle:e,strokeStyle:i,alpha:s,lineWidth:o,lineDash:a,lineCap:c,lineJoin:l,fontColor:h,fontSize:d,fontFamily:u,bold:p,italic:f,textAlign:g,textBaseline:m,textOverflow:y,paddingTop:b,paddingBottom:v,paddingLeft:_,paddingRight:x}=t.state;_u=Bn({fillStyle:e,strokeStyle:i,alpha:s,lineWidth:o,lineDash:a,lineCap:c,lineJoin:l,fontColor:h,fontSize:d,fontFamily:u,bold:p,italic:f,textAlign:g,textBaseline:m,textOverflow:y,paddingTop:b,paddingBottom:v,paddingLeft:_,paddingRight:x}),n.mode=4}},stylepastestop:function(t){const{deliverer:e}=t,n=e.app;_u={},4==n.mode&&(n.mode=1)},databindpastestart:function(t){const{deliverer:e}=t,n=e.app,r=e.selected;if(r&&r[0]&&r!==e.rootModel){const t=r[0],{mappings:e}=t.state;xu=Bn({mappings:e}),n.mode=5}},databindpastestop:function(t){const{deliverer:e}=t,n=e.app;xu={},5==n.mode&&(n.mode=1)},pasteapply:function(t,e){const{deliverer:n}=e,r=n.app;t&&(4==r.mode?zc.around(r.commander,()=>{t.set(wu({...t.model,..._u}))}):5==r.mode&&zc.around(r.commander,()=>{t.set(wu({...t.model,...xu}))}))},keydown:function(t,e){const{deliverer:n}=e;"Esc"!=t.code&&"Escape"!=t.code||(4==n.app.mode?n.trigger("stylepastestop"):5==n.app.mode&&n.trigger("databindpastestop"))}}},"model-layer":{"(all)":{click:function(t,e){const{deliverer:n}=e,r=n.app;if(4!=r.mode&&5!=r.mode)return;const i=e.origin;4==r.mode?i===n?n.root.trigger("stylepastestop"):i&&zc.around(r.commander,()=>{const t=wu({...i.model,..._u});i?.set(t)}):i===n?n.root.trigger("databindpastestop"):i&&zc.around(r.commander,()=>{const t=wu({...i.model,...xu});i?.set(t)})}}}});class Mu{constructor(){this.animatorMap=new Map}waypoint(t,e){this.animatorMap.has(t)&&this.off(t);let{from:n,to:r}=e;if("string"==typeof n&&(n=t.root?.findById(n)),"string"==typeof r&&(r=t.root.findById(r)),!r)return void Rr("WaypointAnimation: Source or target component not found");const i=No(t,{type:"waypoint",fromComponent:n,toComponent:r,...e,onComplete:()=>{this.off(t)}});i&&(this.animatorMap.set(t,i),i.start())}off(t){const e=this.animatorMap.get(t);e&&(e.stop(),this.animatorMap.delete(t))}reset(t){if(this.animatorMap.size>0){for(const t of this.animatorMap.values())t.stop();this.animatorMap.clear()}}dispose(){this.reset(null),this.animatorMap=null}}function Su(t){const{origin:e}=t,n=e.root,{waypointHandler:r}=n;r?.reset()}du.register("waypoint-handler",{"model-layer":{"(descendant)":{waypoint:function(t,e){const{origin:n}=e,r=n.root;let{waypointHandler:i}=r;i||(i=new Mu,r.waypointHandler=i),i.waypoint(n,t)},waypointoff:function(t){const{origin:e}=t,n=e.root,{waypointHandler:r}=n;r?r.off(e):Rr("waypoint-handler not found")},waypointreset:Su},"(self)":{waypointreset:Su}}},function(t){const{waypointHandler:e}=t;e&&(e.dispose(),delete t.waypointHandler)});const Au=[],Eu=Qn(function(){Au.forEach(t=>{t.resize()})},100);"undefined"!=typeof window&&window.addEventListener("resize",Eu);class ku extends fc{constructor(t,e){super(Object.assign({type:"root",scale:{x:1,y:1}},t||{}),e),this._hasSameParentForAllSelected=!1,this._maxRefid=e?.isViewMode?1e6:0,t=t||{},this.fitMode=t.model&&t.model.fitMode,this._app=e,this.style=t.style,this.indexMap=new Map,this.refidIndexMap=new Map,this.templateMap={},this._serviceMap=new Map,this.target_element=t.target_element,this.rebuildContentModel(this.model.model),Au.push(this)}registerService(t,e){this._serviceMap.set(t,e)}getService(t){return this._serviceMap.get(t)}unregisterService(t){this._serviceMap.delete(t)}dispose(){hc.hideAll(this),this._app&&this._app.dispose(),super.dispose(),this._disposeAllResources(),this.target_element=null,this._refresh_mapping_debouncer&&"function"==typeof this._refresh_mapping_debouncer.cancel&&this._refresh_mapping_debouncer.cancel(),delete this._refresh_mapping_debouncer;const t=Au.indexOf(this);t>=0&&Au.splice(t,1),this.refidIndexMap.clear(),this.indexMap.clear(),this._serviceMap.clear(),this._maxRefid=0}isRoot(){return!0}get app(){return this._app}get target_element(){return this._target_element}set target_element(t){this._ua_event_handler&&(this._ua_event_handler.dispose(),delete this._ua_event_handler),t&&(t.style.position="absolute",t.style.cursor="default",t.style.overflow="hidden",t.setAttribute("scene","root-container"),this._ua_event_handler=new su(this,t)),this.forEach(e=>e.target=t),this._target_element=t}get fitMode(){return this._fitMode}set fitMode(t){this._fitMode=t}get hasSameParentForAllSelected(){return this._hasSameParentForAllSelected}set hasSameParentForAllSelected(t){this._hasSameParentForAllSelected=t}get unitScale(){switch(this.model_layer&&this.model_layer.get("unit")){case"mm":case"cm":case"in":return this.app.PPM/10;default:return 1}}addTemplate(t,e){const n=this.templateMap[t];n&&jr("Template replaced (duplicated)",t,e,n),this.templateMap[t]=e,delete this.templatePrefixes}removeTemplate(t,e){const n=this.templateMap[t];n!==e?Rr("Removing template failed (different)",t,e,n):delete this.templateMap[t],delete this.templatePrefixes}findTemplateFor(t){this.templatePrefixes||(this.templatePrefixes=Object.keys(this.templateMap).sort().reverse());const e=this.templatePrefixes.find(e=>t.startsWith(e));if(e)return this.templateMap[e]}addIndex(t,e){if(!t)return;const n=t.toString().replace(/^#/,""),r=this.indexMap.get(n)||[];r.push(e),this.indexMap.set(n,r)}removeIndex(t,e){if(!t)return;const n=t.toString().replace(/^#/,""),r=this.indexMap.get(n)||[],i=r.indexOf(e);-1===i?Rr("Removing index failed (not found)",t,e):(r.splice(i,1),0===r.length?this.indexMap.delete(n):this.indexMap.set(n,r))}addRefidIndex(t,e){null==t&&(t=this.getNewRefid(),e.set("refid",t)),this._maxRefid=Math.max(t,this._maxRefid);const n=this.refidIndexMap.get(t);n&&jr("Refid Index replaced (has not to be)",t,e,n),this.refidIndexMap.set(t,e)}removeRefidIndex(t,e){if(null==t)return;const n=this.refidIndexMap.get(t);n!==e?jr("Refid Removing index failed (has not to be)",t,e,n):this.refidIndexMap.delete(t)}getNewRefid(){return this._maxRefid=(this._maxRefid||0)+1,this._maxRefid}async subscribe(t,e){this._app.isViewMode&&t&&this._app&&(e._subscription=await this._app.subscribe(t,e))}async unsubscribe(t,e){e._subscription&&(await e._subscription.unsubscribe(),delete e._subscription)}findById(t){if(!t)return null;const e=t.toString().replace(/^#/,"");return(this.indexMap.get(e)||[])[0]}findAllById(t){if(!t)return[];const e=t.toString().replace(/^#/,"");return this.indexMap.get(e)||[]}findByRefid(t){return this.refidIndexMap.get(t)}findOrCreate(t){const e=this.findAllById(t);if(!e||0===e.length){if(this.app&&!this.app.isEditMode){const e=this.findTemplateFor(t);if(e){const n=Qc(Object.assign(Bn(e.hierarchy),{id:t,templatePrefix:""}),this.app);return this.model_layer.addComponent(n),[n]}}return[]}return e}resize(){this.components.forEach(t=>{t.resize&&t.resize()}),this.invalidate()}fit(t){const{width:e,height:n,fitMode:r}=this.model_layer.model,i=this.target_element,s=this.model_layer;if(this.fitMode=t||this.fitMode||r||"ratio",e&&n&&i&&i.clientWidth&&i.clientHeight){switch(this.fitMode){case"center":!function(t,e,n){const r=t.unitScale,{width:i,height:s}=e.model;e.set("scale",{x:r,y:r}),e.set("translate",{x:Math.max((n.clientWidth-i*r)/2,0),y:Math.max((n.clientHeight-s*r)/2,0)})}(this,s,i);break;case"both":!function(t,e,n){const{width:r,height:i}=e.model,s=n.clientWidth,o=n.clientHeight;e.set("scale",{x:s/r,y:o/i}),e.set("translate",{x:0,y:0})}(0,s,i);break;case"width":!function(t,e,n){const r=n.clientWidth/e.get("width");e.set("scale",{x:r,y:r}),e.set("translate",{x:0,y:0})}(0,s,i);break;case"height":!function(t,e,n){const r=n.clientHeight/e.get("height");e.set("scale",{x:r,y:r}),e.set("translate",{x:0,y:0})}(0,s,i);break;case"ratio":!function(t,e,n){const{width:r,height:i}=e.model,s=n.clientWidth,o=n.clientHeight,a=s/r,c=o/i,l=Math.min(a,c);e.set("scale",{x:l,y:l}),e.set("translate",{x:(s-r*l)/2,y:(o-i*l)/2})}(0,s,i);break;default:!function(t,e){const n=t.unitScale;e.set("scale",{x:n,y:n}),e.set("translate",{x:0,y:0})}(this,s)}this.resize()}}_disposeAllResources(){this.selected=[],this._focused=null,this._ready=!1,this.eventEngine&&(this.assist_handlers&&this.assist_handlers.forEach(t=>{this.eventEngine.remove(t)}),this.eventEngine.dispose(),delete this.eventEngine),(this.model.handlers||[]).map(t=>{du.getDisposer(t).call(null,this)}),this.assist_layers&&this.assist_layers.forEach(t=>{t.dispose(),this.removeComponent(t)}),delete this.assist_layers,this.model_layer&&this.model_layer.dispose(),this.model_layer&&this.removeComponent(this.model_layer),delete this.model_layer,this.indexMap=new Map,this.refidIndexMap=new Map,this.templateMap={}}rebuildContentModel(t,e){let n;e?.preserveThreeD&&this.model_layer?.is3dMode&&(n=this.model_layer.detachThreeCapability()),this._disposeAllResources(),this.eventEngine=new Xd(this),(t=t||{}).type="model-layer",this.model_layer=Qc(t,this.app),this.addComponent(this.model_layer),this.model_layer.target=this.target_element,this.assist_layers=(this.model.layers||[]).map(t=>{const e=Qc(t,this.app);if(e)return this.addComponent(e),e.target=this.target_element,e;jr("Layer compile failed",t)}).filter(Boolean),this.assist_handlers=(this.model.handlers||[]).map(t=>{const e={};return this.eventEngine.add(e,du.get(t)),e}),n&&(this.model_layer?.model?.threed?this.model_layer.adoptThreeCapability(n):n.dispose()),this._ready=!0,this.traverse(t=>t.ready())}get root(){return this}get anchors(){return[]}get isReady(){return this._ready}get rootModel(){return this.model_layer}get threed(){return this.model_layer?.model?.threed||!1}set threed(t){this.model_layer&&this.model_layer.set("threed",t)}get stuck(){return!0}get data(){const t={};for(const[e,n]of this.indexMap.entries())n.length>0&&(t[e]=n[0].data);return t}set data(t){for(const e in t){const n=this.findOrCreate(e);n&&0!==n.length&&n.forEach(n=>n.data=t[e])}}get dataByRefid(){const t={};for(const[e,n]of this.refidIndexMap.entries())t[e]=n.data;return t}set dataByRefid(t){for(const e in t){const n=this.findByRefid(Number(e));n&&(n.data=t[e])}}get values(){const t={};for(const[e,n]of this.indexMap.entries())n.length>0&&(t[e]=n[0].value);return t}set values(t){for(const e in t){const n=this.findOrCreate(e);n&&0!==n.length&&n.forEach(n=>n.value=t[e])}}get valuesByRefid(){const t={};for(const[e,n]of this.refidIndexMap.entries())t[e]=n.value;return t}set valuesByRefid(t){for(const e in t){const n=this.findByRefid(Number(e));n&&(n.value=t[e])}}get selected(){return(this._selected||[]).filter(t=>t.parent)}set selected(t){const e=this._selected;if(this._selected=t,!t||t.length<=1)this.hasSameParentForAllSelected=!0;else{const e=t[0].parent;this.hasSameParentForAllSelected=!t.find(t=>t.parent!=e)}this.trigger("selected",t,e)}get focused(){return this._focused}set focused(t){this._focused!==t&&(this._focused=t,this.invalidate())}get style(){return this._style}set style(t){this._style=t,this._compiled_style=t}get hasTextProperty(){return!1}render(){this.components.forEach(t=>t.draw())}contains(t,e){return!0}capturePath(t,e){return this.model_layer.capturePath(t,e)}invalidate(){this.components.forEach(t=>t.invalidate())}_areAliasesEqual(t,e){if(!Array.isArray(t)&&!Array.isArray(e))return!0;if(!Array.isArray(t)||!Array.isArray(e))return!1;if(t.length!==e.length)return!1;const n=[...t].sort(),r=[...e].sort();return n.every((t,e)=>t===r[e])}get eventMap(){return{"(root)":{"(descendant)":{added:this.onadded,removed:this.onremoved,change:this.onchanged}}}}refreshMappings(){if(!this._refresh_mapping_debouncer){if(this.disposed)return;this._refresh_mapping_debouncer=Qn(function t(e){e.executeMappings(),e.components&&e.components.forEach(e=>t(e))},1e3)}this._refresh_mapping_debouncer(this.model_layer)}_addTraverse(t){t.components&&t.components.forEach(t=>this._addTraverse(t));const{id:e,alias:n,refid:r,tag:i,templatePrefix:s}=t.model;this.addRefidIndex(r,t),e&&this.addIndex(e,t),Array.isArray(n)&&n.forEach(e=>{e&&this.addIndex(e,t)}),i&&this.subscribe(i,t),s&&this.addTemplate(s,t);const o=sr({},t.eventMap,t.model.eventMap);this.eventEngine.add(t,o)}_removeTraverse(t){t.components&&t.components.forEach(t=>this._removeTraverse(t));const{id:e,alias:n,refid:r,tag:i,templatePrefix:s}=t.model;this.removeRefidIndex(r,t),e&&this.removeIndex(e,t),Array.isArray(n)&&n.forEach(e=>{e&&this.removeIndex(e,t)}),i&&this.unsubscribe(i,t),s&&this.removeTemplate(s,t),this.eventEngine.remove(t)}onadded(t,e){this._addTraverse(e),this.refreshMappings(),this.invalidate()}onremoved(t,e){this._removeTraverse(e),this.invalidate()}onchanged(t,e,n){e.templatePrefix&&this.removeTemplate(e.templatePrefix,n.origin),t.templatePrefix&&this.addTemplate(t.templatePrefix,n.origin),e.id&&this.removeIndex(e.id,n.origin),t.id&&this.addIndex(t.id,n.origin),Array.isArray(e.alias)&&e.alias.forEach(t=>{t&&this.removeIndex(t,n.origin)}),Array.isArray(t.alias)&&t.alias.forEach(t=>{t&&this.addIndex(t,n.origin)}),e.tag&&this.unsubscribe(e.tag,n.origin),t.tag&&this.subscribe(t.tag,n.origin),e.id==t.id&&e.class==t.class&&this._areAliasesEqual(e.alias,t.alias)||this.refreshMappings()}}Fa.memoize(ku.prototype,"unitScale",!1);let Cu=13.3;var Pu=function(t){return void 0!==t&&(Cu=t),Cu};const Tu="$base_url";const Du=Math.PI/12;class Ou{constructor(t,e){this._postprocessing=!0,this._mode=t,this.screen=Pu(),this._baseUrl="undefined"!=typeof window?window.location.origin:null,this._refProvider=e,this.isEditMode&&(this._rotateStep=Du,this._rotateStepForced=!1)}dispose(){this._dataSubscriptionProvider?.dispose?.(),delete this._dataStorage}_calcScreen(){const t={width:screen.width,height:screen.height};this._PPI=function(t,e,n,r="d"){t<=0&&(t=1),e<=0&&(e=1);const i=("d"===r?Math.sqrt(t*t+e*e):"w"===r?t:e)/n;return i>0?Math.round(i):0}(t.width,t.height,this.screen),this._PPM=this._PPI/25.4}subscribe(t,e){return this._dataSubscriptionProvider?.subscribe?.(t,e)}get refProvider(){return this._refProvider}set dataSubscriptionProvider(t){this._dataSubscriptionProvider=t}get dataSubscriptionProvider(){return this._dataSubscriptionProvider}set commander(t){this._commander=t}get commander(){return this._commander}get screen(){return this._screen}set screen(t){this._screen=t,this._calcScreen()}get DPPX(){return _i}get PPI(){return this._PPI}get PPM(){return this._PPM}get mode(){return this._mode}set mode(t){const e=this._mode;e!==t&&(this._mode=t,this.trigger("mode",t,e))}get isViewMode(){return 0===this._mode}get isEditMode(){return 1===this._mode}get baseUrl(){return this._baseUrl}set baseUrl(t){t&&this._baseUrl!==t&&(this._baseUrl=t)}url(t){try{let e;return e=t.includes(Tu)?new URL(t.replace(Tu,this.baseUrl??""),this.baseUrl??void 0):new URL(t,location.origin),e.href}catch(e){Rr(e,t)}}get rotateStep(){return this._rotateStep}set rotateStep(t){this._rotateStep=Number(t)||Du}get rotateStepForced(){return this._rotateStepForced}set rotateStepForced(t){this._rotateStepForced=!!t}get dataStorage(){return this._dataStorage}set dataStorage(t){this._dataStorage=t}get postprocessing(){return this._postprocessing}set postprocessing(t){this._postprocessing=t}}Lr(Ou.prototype,Ar.withEvent);class zu{constructor(t,e){!(t=Number(t))||t<=0?(jr("TimeCapsule maxsize should be greater than 0.",t),this.maxsize=10):this.maxsize=t,this.reset(),e&&(this.snapshot(e),this.preserve())}preserve(){this.checkPoint=this.pos}hasUnpreservedChanges(){return this.checkPoint!=this.pos}dispose(){this.reset()}snapshot(t){if(this.q.splice(this.pos+1,this.q.length-(this.pos+1),t),this.q.length>this.maxsize){const t=this.q.splice(0,this.q.length-this.maxsize);this.checkPoint=Math.max(-1,this.checkPoint-t.length)}this.pos=this.q.length-1}forward(){if(this.snapshot_taker&&this.snapshot_taker.take(),this.forwardable)return this.q[++this.pos];Rr("Not forwardable.")}backward(){if(this.snapshot_taker&&this.snapshot_taker.take(),this.backwardable)return this.q[--this.pos];Rr("Not backwardable.")}get current(){if(-1!==this.pos)return this.q[this.pos];Rr("Non state has been recorded.")}get length(){return this.q.length}get forwardable(){return this.pos<this.q.length-1}get backwardable(){return this.pos>0}get snapshot_taker(){return this._snapshot_taker}set snapshot_taker(t){this._snapshot_taker=t}reset(){this.q=[],this.pos=-1,this.checkPoint=-1}}const Iu=Qn(t=>{t.brake||t.take()},1e3,{leading:!0,trailing:!1});function Lu(t){!t.brake&&t.dirty&&Iu(t)}class ju{constructor(t,e){this._brake=!1,this.dirty=!1,this.brake=!1,this.dirty=!1,this.state_holder=t,this.timecapsule=e,this.timecapsule.snapshot_taker=this}dispose(){Iu.cancel(),this.state_holder=null,this.timecapsule=null}touch(){this.dirty=!0,Lu(this)}take(t=!1){(this.dirty||t)&&(this.timecapsule.snapshot(this.state_holder.state),this.dirty=!1)}get brake(){return this._brake}set brake(t){this._brake=!!t,Lu(this)}}function Ru(t,e){const n=e.model_layer.get("scale"),r=e.model_layer.get("translate"),i=e.model_layer.get("threed");if(t){const s=JSON.parse(t);s.scale=n,s.translate=r,s.threed=i,e.rebuildContentModel(s,{preserveThreeD:!0})}}class Fu{constructor(t){this.container=t,this.timecapsule=new zu(20);const e=this;this.snapshot_taker=new ju({get state(){const t=e.container.model_layer.hierarchy;return JSON.stringify(t)}},this.timecapsule),this.snapshot_taker.take(!0),this.timecapsule.preserve()}dispose(){this.reset(),this.timecapsule&&this.timecapsule.dispose(),this.snapshot_taker&&this.snapshot_taker.dispose(),delete this.container,delete this.timecapsule,delete this.snapshot_taker}preserve(){this.timecapsule.preserve()}hasUnpreservedChanges(){return this.timecapsule.hasUnpreservedChanges()}execute(t,e){!1!==e&&t&&t.execute(),this.snapshot_taker.touch(),this.trigger("execute",t,!0,!1)}undo(){this.timecapsule.backwardable&&(Ru(this.timecapsule.backward(),this.container),this.trigger("undo",this.undoable(),this.redoable()))}redo(){this.timecapsule.forwardable&&(Ru(this.timecapsule.forward(),this.container),this.trigger("redo",this.undoable(),this.redoable()))}undoable(){return this.timecapsule.backwardable}redoable(){return this.timecapsule.forwardable}reset(){this.timecapsule&&this.timecapsule.reset(),this.trigger("command-reset")}}Lr(Fu.prototype,Ar.withEvent);const Bu=new class{constructor(){this._scenes=[],this.onSceneChange=null}register(t){this._cleanup(),this._scenes.push(new WeakRef(t)),this.onSceneChange?.(this._scenes.length)}unregister(t){this._scenes=this._scenes.filter(e=>{const n=e.deref();return n&&n!==t}),this.onSceneChange?.(this._scenes.length)}getScenes(){return this._cleanup(),this._scenes.map((t,e)=>{const n=t.deref();if(!n)return null;const r=n.root,i=r?.model||{};return{index:e,model:{width:i.width||0,height:i.height||0,type:i.type||"unknown"}}}).filter(Boolean)}getComponentTree(t=0){const e=this._getScene(t);if(!e)return[];const n=e.rootContainer;if(!n)return[];const r=n.model_layer;return r?this._childrenOf(r):[]}getChildTree(t,e=0){const n=this._getScene(e);if(!n)return[];const r=n.rootContainer;if(!r)return[];let i;return i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t),i?this._childrenOf(i):[]}getComponentInfo(t,e=0){const n=this._getScene(e);if(!n)return null;const r=n.rootContainer;if(!r)return null;let i;if(i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t),!i)return null;const s=this._safeBounds(i),o={model:this._safeClone(i.model),state:this._safeClone(i.state),nature:i.nature||{},data:this._safeValue(i.data),value:this._safeValue(i.value),bounds:s,type:i.model?.type||"unknown",isContainer:!!i.isContainer?.(),hidden:!!i.model?.hidden};return"model-layer"===i.model?.type&&(o.is3dMode=!!i.model?.threed),o}selectComponent(t,e=0){const n=this._getScene(e);if(!n)return!1;const r=n.rootContainer;if(!r)return!1;if(!t||"root"===t||"__root__"===t)return r.selected=[],!0;const i=this._findComponent(r,t);return!!i&&(r.selected=[i],!0)}setComponentProperty(t,e,n,r=0){const i=this._getScene(r);if(!i)return!1;const s=i.rootContainer;if(!s)return!1;let o;if(o="root"===t||"__root__"===t?s.model_layer:this._findComponent(s,t),!o)return!1;try{return o.set(e,n),!0}catch{return!1}}setCameraView(t,e=0){const n=this._getScene(e);if(!n)return!1;const r=n.rootContainer;if(!r)return!1;const i=r.model_layer;if(!i||!i._threeCapability)return!1;try{return i._threeCapability.setCameraView(t),!0}catch{return!1}}getCameraState(t=0){const e=this._getScene(t);if(!e)return null;const n=e.rootContainer;if(!n)return null;const r=n.model_layer;if(!r||!r._threeCapability)return null;try{return r._threeCapability.getCameraState()}catch{return null}}toggleHidden(t,e=0){const n=this._getScene(e);if(!n)return!1;const r=n.rootContainer;if(!r)return!1;const i=this._findComponent(r,t);if(!i)return!1;try{return i.set("hidden",!i.model?.hidden),!i.model?.hidden}catch{return!1}}evaluateData(t,e=0){const n=this._getScene(e);if(!n)return;const r=n.rootContainer;if(!r)return;const i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t);return i?this._safeValue(i.data):void 0}evaluateValue(t,e=0){const n=this._getScene(e);if(!n)return;const r=n.rootContainer;if(!r)return;const i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t);return i?this._safeValue(i.value):void 0}searchComponents(t,e=0){const n=this._getScene(e);if(!n)return[];const r=n.rootContainer;if(!r)return[];const i=r.model_layer;if(!i)return[];const s=[],o=t.toLowerCase();return this._traverseComponent(i,t=>{const e=t.state||t.model||{};[e.type||"",e.name||"",e.id||"",e.tag||"",e.class||"",String(e.refid||"")].join(" ").toLowerCase().includes(o)&&s.push(this._toTreeNode(t))}),s}getComponentPath(t,e=0){const n=this._getScene(e);if(!n)return[];const r=n.rootContainer;if(!r)return[];const i=r.model_layer;if(!i)return[];const s=[];return this._findPath(i,t,s)?s:[]}getThreedInfo(t,e=0){const n=this._getScene(e);if(!n)return null;const r=n.rootContainer;if(!r)return null;let i;if(i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t),!i)return null;const s=i.model||{},o=s.type||"unknown",a=s.material3d,c={is3dish:"function"==typeof i.is3dish&&i.is3dish(),type:o};if(a&&(c.material3d=this._safeClone(a)),c.resolved=dh(a),"gltf-object"===o)try{c.nodeNames=i.nodeNames??[],c.animationNames=i.animationNames??[],c.autoPlay=!1!==i.autoPlay,c.nodes=this._safeClone(i.nodes),c.animations=this._safeClone(i.animations),c.fillStyleTargets=i.fillStyleTargets}catch{}return a?.spriteMode&&(c.spriteMode=a.spriteMode),a?.renderMode&&(c.renderMode=a.renderMode),c}_getScene(t){this._cleanup();const e=this._scenes[t];return e?.deref()??null}_cleanup(){this._scenes=this._scenes.filter(t=>void 0!==t.deref())}_findComponent(t,e){const n=Number(e);if(!isNaN(n)){const e=t.findByRefid(n);if(e)return e}const r=t.findById(e);return r||null}_childrenOf(t){const e=t.components;return e?e.map(t=>this._toTreeNode(t)):[]}_toTreeNode(t){const e=t.components,n=!!e&&e.length>0,r=t.state||t.model||{};return{id:String(r.refid??r.id??""),type:r.type||"unknown",model_id:r.id,hasChildren:n,childCount:n?e.length:0,refid:r.refid,tag:r.tag,name:r.name,hidden:!!r.hidden,clazz:r.class}}_componentId(t){const e=t.state||t.model||{};return String(e.refid??e.id??"")}_findPath(t,e,n){const r=this._componentId(t);if(r===e)return!0;const i=t.components;if(!i)return!1;for(const s of i)if(this._findPath(s,e,n))return n.unshift("model-layer"===t.model?.type?"__root__":r),!0;return!1}_traverseComponent(t,e){e(t);const n=t.components;if(n)for(const t of n)this._traverseComponent(t,e)}_safeBounds(t){try{const e=t.bounds;return e?{left:e.left??0,top:e.top??0,width:e.width??0,height:e.height??0}:null}catch{return null}}_safeClone(t){if(!t||"object"!=typeof t)return t??{};try{return JSON.parse(JSON.stringify(t))}catch{const e={};for(const n of Object.keys(t))try{const r=t[n];if("function"==typeof r)continue;e[n]="object"==typeof r?String(r):r}catch{e[n]="[error]"}return e}}_safeValue(t){if(null==t)return t;try{return JSON.parse(JSON.stringify(t))}catch{return String(t)}}},Nu="KHR_materials_pbrSpecularGlossiness";class Hu{constructor(t){this.name=Nu,this.parser=t}extendMaterialParams(t,e){const r=this.parser.json.materials?.[t],i=r?.extensions?.[Nu];if(!i)return Promise.resolve();const s=[];if(Array.isArray(i.diffuseFactor)){const[t,r,s,o]=i.diffuseFactor;e.color||(e.color=new n.Color),e.color.setRGB(t,r,s,n.LinearSRGBColorSpace),e.opacity=o}null!=i.diffuseTexture&&s.push(this.parser.assignTexture(e,"map",i.diffuseTexture,n.SRGBColorSpace));const o=i.glossinessFactor??1;e.roughness=1-o;const a=i.specularFactor??[1,1,1],c=Math.max(a[0],a[1],a[2]);return e.metalness=c>.5?c:0,Promise.all(s)}}const Vu={once:_.LoopOnce,repeat:_.LoopRepeat,pingpong:_.LoopPingPong};class Gu extends xh{constructor(){super(...arguments),this.objectSize=new _.Vector3,this._nodeIndex=new Map,this._originals=new Map,this._animationActions=new Map,this._fillStyleOriginals=new Map,this._clonedMaterials=new WeakSet,this._loadGen=0}static getSharedLoader(t){if(!Gu._sharedLoader){const t=new f.GLTFLoader;!function(t){t.register(t=>new Hu(t))}(t);const e=new g.DRACOLoader;e.setDecoderPath("/node_modules/three/examples/jsm/libs/draco/"),t.setDRACOLoader(e);const n=new m.KTX2Loader;n.setTranscoderPath("/node_modules/three/examples/jsm/libs/basis/"),t.setKTX2Loader(n),t.setMeshoptDecoder(y.MeshoptDecoder),t.setCrossOrigin("anonymous"),Gu._sharedLoader=t}return t&&Gu._sharedLoader.ktx2Loader?.detectSupport(t),Gu._sharedLoader}static loadGLTF(t,e){let n=Gu._gltfCache.get(t);if(!n){const r=Gu.getSharedLoader(e);n=new Promise((e,n)=>{r.load(t,e,void 0,n)}).catch(e=>{throw Gu._gltfCache.delete(t),e}),Gu._gltfCache.set(t,n)}return n}_ensureOwnMaterial(t){let e=t.material;return this._clonedMaterials.has(e)||(e=e.clone(),t.material=e,this._clonedMaterials.add(e)),e}build(){super.build();const{src:t}=this.component.state;if(!t)return void this.clear();const e=++this._loadGen,n=this.component.app.url(t);Gu.loadGLTF(n,this.threeContainer?.renderer3d).then(t=>{e===this._loadGen&&this.gltfLoaded(t)},t=>{e===this._loadGen&&(jr("GLTFLoader.load",t),this.clear(),this._showErrorPlaceholder(),this.component.setState({loadError:String(t)}))})}gltfLoaded(t){this.component.state.loadError&&this.component.setState({loadError:void 0});const e=t.scene,n=t.animations,r=e.clone();r.userData.context=this,r.traverse(t=>{t.isMesh&&(t.castShadow=!0)});const i=(new _.Box3).setFromObject(r),s=i.getCenter(r.position),o=i.getSize(new _.Vector3);s.multiplyScalar(-1);const a=this.component.state.src;if(a){const t=Gu._topViewCache.get(a);t?this.component._topViewSnapshot=t:this._renderTopViewSnapshot(a,r)}this.clear(),this.object3d.userData.context=this,this.objectSize=o,this.pivot=new _.Object3D,this.object3d.add(this.pivot),this.pivot.add(r),this._buildNodeIndex(r),this.updateDimension(),n&&n.length&&this._setupAnimations(n);const c=this.component.state.nodes;c&&this._applyNodeStates(c),this.updateFillStyle()}_renderTopViewSnapshot(t,e){const n=Gu.renderTopView(e);Gu._topViewCache.set(t,n),this.component._topViewSnapshot=n,this.component.invalidate()}static renderTopView(t){const e=256,n=new _.Scene,r=t.parent;n.add(t);const i=new _.AmbientLight(16777215,.8);n.add(i);const s=new _.DirectionalLight(16777215,1);s.position.set(0,10,0),n.add(s);const o=(new _.Box3).setFromObject(t),a=o.getSize(new _.Vector3),c=o.getCenter(new _.Vector3),l=(a.x||1)/2*1.02,h=(a.z||1)/2*1.02,d=new _.OrthographicCamera(-l,l,h,-h,.01,10*a.y+1);d.position.set(c.x,o.max.y+a.y,c.z),d.lookAt(c.x,c.y,c.z);const u=l/h,p=u>=1?e:Math.round(e*u),f=u>=1?Math.round(e/u):e;let g;try{g=new _.WebGLRenderer({antialias:!0,alpha:!0});const t=g.getContext();t&&!t.isContextLost()||(g.dispose(),g=void 0)}catch{g=void 0}if(!g){r?r.add(t):n.remove(t);const e=document.createElement("canvas");return e.width=p,e.height=f,e}g.setClearColor(0,0),g.setSize(p,f),g.render(n,d),r?r.add(t):n.remove(t);const m=document.createElement("canvas");m.width=p,m.height=f;const y=m.getContext("2d");return y&&y.drawImage(g.domElement,0,0),g.dispose(),m}static getTopViewCache(t){return Gu._topViewCache.get(t)}static setTopViewCache(t,e){Gu._topViewCache.set(t,e)}static flushCache(){Gu._gltfCache.clear(),Gu._topViewCache.clear()}_buildNodeIndex(t){this._nodeIndex.clear(),this._originals.clear(),t.traverse(t=>{if(!t.name)return;this._nodeIndex.set(t.name,t);const e={visible:t.visible,scale:t.scale.clone()};if(t.isMesh){const n=t.material;n&&(e.color=n.color.clone(),e.opacity=n.opacity,e.transparent=n.transparent,e.emissive=n.emissive.clone(),e.emissiveIntensity=n.emissiveIntensity)}this._originals.set(t.name,e)})}getNode(t){return this._nodeIndex.get(t)}get nodeNames(){return Array.from(this._nodeIndex.keys())}_applyNodeStates(t){for(const[e,n]of Object.entries(t)){const t=this._nodeIndex.get(e);if(t&&(void 0!==n.visible&&(t.visible=n.visible),void 0!==n.scale&&t.scale.setScalar(n.scale),t.isMesh)){const e=t;if(!(void 0!==n.color||void 0!==n.opacity||void 0!==n.emissive||void 0!==n.emissiveIntensity))continue;const r=this._ensureOwnMaterial(e);void 0!==n.color&&r.color.set(n.color),void 0!==n.opacity&&(r.opacity=n.opacity,r.transparent=n.opacity<1),void 0!==n.emissive&&r.emissive.set(n.emissive),void 0!==n.emissiveIntensity&&(r.emissiveIntensity=n.emissiveIntensity)}}}_resetNode(t){const e=this._nodeIndex.get(t),n=this._originals.get(t);if(e&&n&&(e.visible=n.visible,e.scale.copy(n.scale),e.isMesh)){const t=e.material;t&&n.color&&(t.color.copy(n.color),t.opacity=n.opacity,t.transparent=n.transparent,t.emissive.copy(n.emissive),t.emissiveIntensity=n.emissiveIntensity)}}_resetAllNodes(){for(const t of this._originals.keys())this._resetNode(t)}_setupAnimations(t){const e=this.threeContainer.mixer;this._animationActions.clear();for(const n of t){const t=e.clipAction(n);this._animationActions.set(n.name,t)}!1!==this.component.state.autoPlay&&this._animationActions.forEach(t=>t.play());const n=this.component.state.animations;n&&this._applyAnimationStates(n)}_applyAnimationStates(t){for(const[e,n]of Object.entries(t)){const t=this._animationActions.get(e);t&&(void 0!==n.loop&&(t.loop=Vu[n.loop]??_.LoopRepeat,"once"===n.loop&&(t.clampWhenFinished=!0)),void 0!==n.speed&&(t.timeScale=n.speed),void 0!==n.weight&&(t.weight=n.weight),void 0!==n.play&&(n.play?t.play():t.stop()))}}get animationNames(){return Array.from(this._animationActions.keys())}_showErrorPlaceholder(){const t=new _.BoxGeometry(1,1,1),e=new _.MeshStandardMaterial({color:13369344,wireframe:!0}),n=new _.Mesh(t,e);n.name="__error_placeholder__",this.object3d.add(n)}updateFillStyle(){const t=this.component.state.fillStyleTargets;if(!t||0===t.length)return;const{fillStyle:e}=this.component.state;if(!e)return;const n=xh.buildFillStyleTexture(this.component);for(const r of t){const t=this._nodeIndex.get(r);if(!t||!t.isMesh)continue;const i=this._ensureOwnMaterial(t);i&&(this._fillStyleOriginals.has(r)||this._fillStyleOriginals.set(r,{color:i.color.clone(),map:i.map,opacity:i.opacity,transparent:i.transparent}),n?(i.map&&i.map!==this._fillStyleOriginals.get(r)?.map&&i.map.dispose(),n.needsUpdate=!0,i.map=n):"string"==typeof e&&("transparent"!==e?i.color.set(e):(i.opacity=0,i.transparent=!0)))}}_restoreFillStyleTargets(t){for(const e of t){const t=this._fillStyleOriginals.get(e);if(!t)continue;const n=this._nodeIndex.get(e);if(!n||!n.isMesh)continue;const r=n.material;r&&(r.map&&r.map!==t.map&&r.map.dispose(),r.color.copy(t.color),r.map=t.map,r.opacity=t.opacity,r.transparent=t.transparent,this._fillStyleOriginals.delete(e))}}clear(){return this._animationActions.forEach(t=>t.stop()),this._animationActions.clear(),this._nodeIndex.clear(),this._originals.clear(),this._fillStyleOriginals.clear(),this.pivot&&yh(this.pivot),this.pivot=void 0,this.objectSize=void 0,super.clear()}updateDimension(){const{width:t=1,height:e=1,depth:n=1}=this.component.state,{x:r=1,y:i=1,z:s=1}=this.objectSize||{};this.pivot&&this.pivot.scale.set(t/r,n/i,e/s),this.component.invalidate()}updateSource(){this.build()}onchange(t,e){if(super.onchange(t,e),"src"in t&&this.updateSource(),"nodes"in t){this._resetAllNodes();const e=t.nodes;e&&Object.keys(e).length>0&&this._applyNodeStates(e)}if("animations"in t){const e=t.animations;e&&this._applyAnimationStates(e)}if("fillStyleTargets"in t){const t=e.fillStyleTargets??[];t.length>0&&this._restoreFillStyleTargets(t),this.updateFillStyle()}"autoPlay"in t&&(!1!==t.autoPlay?this._animationActions.forEach(t=>t.play()):this._animationActions.forEach(t=>t.stop()))}}Gu._topViewCache=new Map,Gu._gltfCache=new Map,Gu._sharedLoader=null;const Yu=["id","name","tag","type","class","text","data","property"];class Uu{constructor(){this._results=[],this._currentIndex=-1,this._lastQuery=""}get results(){return this._results}get currentIndex(){return this._currentIndex}get currentResult(){return this._results[this._currentIndex]}get resultCount(){return this._results.length}search(t,e,n){if(this._lastQuery=e,this._results=[],this._currentIndex=-1,!e||!t)return this._results;const r=n?.fields||Yu,i=n?.caseSensitive??!1,s=n?.includeHidden??!1,o=n?.maxResults??1/0,a=i?e:e.toLowerCase(),c=new Set;return this._traverse(t,t=>{if(c.has(t))return;if(this._results.length>=o)return;if(!s&&t.state.hidden)return;const e=this._matchComponent(t,a,r,i);e&&(c.add(t),this._results.push(e))}),this._results.length>0&&(this._currentIndex=0),this._results}navigateNext(){if(0!==this._results.length)return this._currentIndex=(this._currentIndex+1)%this._results.length,this._results[this._currentIndex]}navigatePrev(){if(0!==this._results.length)return this._currentIndex=(this._currentIndex-1+this._results.length)%this._results.length,this._results[this._currentIndex]}navigateTo(t){if(!(t<0||t>=this._results.length))return this._currentIndex=t,this._results[this._currentIndex]}clear(){this._results=[],this._currentIndex=-1,this._lastQuery=""}_traverse(t,e){e(t);const n=t.components;if(n)for(const t of n)this._traverse(t,e)}_matchComponent(t,e,n,r){const i=t.state,s=t=>{if(!t)return!1;return(r?t:t.toLowerCase()).includes(e)};for(const o of n)switch(o){case"id":if(s(i.id))return{component:t,matchType:"id",matchField:"id",matchValue:i.id};break;case"name":if(s(i.name))return{component:t,matchType:"name",matchField:"name",matchValue:i.name};break;case"tag":if(s(i.tag))return{component:t,matchType:"tag",matchField:"tag",matchValue:i.tag};break;case"type":if(s(i.type))return{component:t,matchType:"type",matchField:"type",matchValue:i.type};break;case"class":if(s(i.class))return{component:t,matchType:"class",matchField:"class",matchValue:i.class};break;case"text":if(s(i.text))return{component:t,matchType:"text",matchField:"text",matchValue:i.text};break;case"data":{const n=this._matchDataBinding(t,e,r);if(n)return n;break}case"property":{const n=this._matchProperties(t,e,r);if(n)return n;break}}return null}_matchDataBinding(t,e,n){const r=t._model,i=r?.mappings;if(!i||!Array.isArray(i))return null;const s=t=>{if(!t)return!1;return(n?t:t.toLowerCase()).includes(e)};for(const e of i){if(s(e.accessor))return{component:t,matchType:"data",matchField:"accessor",matchValue:e.accessor};if(s(e.target))return{component:t,matchType:"data",matchField:"target",matchValue:e.target};if(s(e.property))return{component:t,matchType:"data",matchField:"property",matchValue:e.property};if(s(e.source))return{component:t,matchType:"data",matchField:"source",matchValue:e.source}}return null}_matchProperties(t,e,n){const r=t.state,i=t=>{if(!t)return!1;return(n?t:t.toLowerCase()).includes(e)},s=["ref","src","value","action"];for(const e of s){const n=r[e];if("string"==typeof n&&i(n))return{component:t,matchType:"property",matchField:e,matchValue:n}}return null}}const $u={id:"ID",name:"Name",tag:"Tag",type:"Type",class:"Class",text:"Text",data:"Data",property:"Prop"};class Wu{constructor(){this._engine=new Uu,this._visible=!1,this._queryHistory=[],this._historyIndex=-1,this._savedInput="",this._keyboardNav=!1}get isVisible(){return this._visible}get engine(){return this._engine}setup(t){this.destroy(),this._host=t}toggle(){this._visible?this._input&&document.activeElement!==this._input?(this._input.focus(),this._input.select()):this.hide():this.show()}show(){this._host?.element&&(this._container||this._buildDOM(),this._container&&!this._container.parentElement&&this._host.element.appendChild(this._container),this._container.style.display="flex",this._visible=!0,requestAnimationFrame(()=>{this._input?.focus(),this._input?.select()}))}hide(){this._container&&(this._container.style.display="none"),this._visible=!1,this._historyIndex=-1,this._clearHighlight(),this._engine.clear(),this._updateStatus(),this._hideResultList()}destroy(){this._container?.parentElement&&this._container.parentElement.removeChild(this._container),this._container=void 0,this._input=void 0,this._statusEl=void 0,this._resultListEl=void 0,this._host=void 0,this._visible=!1,this._engine.clear()}_buildDOM(){const t=this._host,e=document.createElement("div");e.setAttribute("scene","search-overlay"),e.style.cssText=["position:absolute","top:8px","right:8px","display:flex","flex-direction:column","background:rgba(30,30,30,0.94)","border:1px solid rgba(255,255,255,0.12)","border-radius:8px","backdrop-filter:blur(12px)","pointer-events:auto","user-select:none","z-index:10000",'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',"font-size:13px","color:rgba(255,255,255,0.9)","box-shadow:0 4px 16px rgba(0,0,0,0.3)","min-width:280px","max-width:400px"].join(";");const n=document.createElement("div");n.style.cssText="display:flex;align-items:center;padding:6px 8px;gap:6px";const r=document.createElement("span");r.textContent="🔍",r.style.cssText="font-size:14px;flex-shrink:0;opacity:0.6",n.appendChild(r);const i=document.createElement("input");i.type="text",i.placeholder="Search: type, id, tag, text, data...",i.style.cssText=["flex:1","background:rgba(255,255,255,0.08)","border:1px solid rgba(255,255,255,0.15)","border-radius:4px","color:white","padding:4px 8px","font-size:13px","outline:none","min-width:0"].join(";"),i.addEventListener("focus",()=>{i.style.borderColor="rgba(74,158,255,0.6)"}),i.addEventListener("blur",()=>{i.style.borderColor="rgba(255,255,255,0.15)"}),n.appendChild(i);const s=document.createElement("span");s.style.cssText="font-size:11px;color:rgba(255,255,255,0.5);white-space:nowrap;flex-shrink:0",n.appendChild(s);const o=document.createElement("button");o.textContent="✕",o.title="Close (Esc)",o.style.cssText=this._buttonStyle(),o.addEventListener("click",()=>this.hide()),n.appendChild(o),e.appendChild(n);const a=document.createElement("div");a.style.cssText=["max-height:240px","overflow-y:auto","border-top:1px solid rgba(255,255,255,0.08)","display:none"].join(";"),e.appendChild(a),i.addEventListener("input",()=>{this._historyIndex=-1,this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._doSearch(i.value),150)}),i.addEventListener("keydown",e=>{if(e.stopPropagation(),"Escape"===e.key)return this.hide(),void t.element?.focus();if("ArrowDown"===e.key||"Tab"===e.key){if("Tab"===e.key&&e.shiftKey)return;return this._isHistoryMode()||!this._input?.value&&"ArrowDown"===e.key?this._navigateHistory(1):this._engine.resultCount>0&&this._focusResult(0),void e.preventDefault()}if("ArrowUp"===e.key)return this._navigateHistory(-1),void e.preventDefault();if("Enter"===e.key){const t=this._engine.currentIndex>=0?this._engine.currentIndex:0;return this._selectResult(t),void e.preventDefault()}}),this._container=e,this._input=i,this._statusEl=s,this._resultListEl=a}_buttonStyle(){return["background:none","border:none","color:rgba(255,255,255,0.6)","cursor:pointer","font-size:12px","padding:2px 4px","border-radius:3px","line-height:1"].join(";")}_doSearch(t){if(!this._host?.root)return;const e=t.trim();if(!e)return this._engine.clear(),this._clearHighlight(),this._updateStatus(),void this._hideResultList();this._engine.search(this._host.root,e),this._updateStatus(),this._renderResultList()}_addToHistory(t){const e=t.trim();if(!e)return;const n=this._queryHistory.indexOf(e);n>=0&&this._queryHistory.splice(n,1),this._queryHistory.unshift(e),this._queryHistory.length>Wu.MAX_HISTORY&&this._queryHistory.pop()}_navigateHistory(t){if(0===this._queryHistory.length)return;if(!this._input)return;-1===this._historyIndex&&-1===t&&(this._savedInput=this._input.value);const e=this._historyIndex+(-1===t?1:-1);e<-1||e>=this._queryHistory.length||(this._historyIndex=e,-1===this._historyIndex?this._input.value=this._savedInput:this._input.value=this._queryHistory[this._historyIndex],this._debounceTimer&&clearTimeout(this._debounceTimer),this._doSearch(this._input.value))}_isHistoryMode(){return this._historyIndex>=0}_focusResult(t){if(t<0||t>=this._engine.resultCount)return;if(t>=50)return;this._engine.navigateTo(t),this._keyboardNav=!0,this._updateStatus(),this._updateResultListSelection();const e=this._resultListEl?.querySelector(`[data-index="${t}"]`);e?.focus()}_selectResult(t){if(!this._host)return;if(0===this._engine.resultCount)return;if(t<0||t>=this._engine.resultCount)return;this._engine.navigateTo(t);const e=this._engine.currentResult;if(!e)return;this._addToHistory(this._input?.value||""),this._host.setSelected([e.component]),this._host.centerTo(e.component,!0);const n=this._engine.results.map(t=>t.component);this._host.highlightSearchResults?.(n),this._host.invalidate?.(),this._updateStatus(),this._updateResultListSelection()}_clearHighlight(){this._host?.highlightSearchResults?.([]),this._host?.invalidate?.()}_updateStatus(){if(!this._statusEl)return;const t=this._engine.resultCount,e=this._engine.currentIndex;0===t&&this._input?.value?.trim()?(this._statusEl.textContent="No results",this._statusEl.style.color="rgba(255,120,120,0.8)"):t>0?(this._statusEl.textContent=`${e+1}/${t}`,this._statusEl.style.color="rgba(255,255,255,0.5)"):this._statusEl.textContent=""}_renderResultList(){if(!this._resultListEl)return;const t=this._engine.results;if(this._resultListEl.innerHTML="",0===t.length)return void(this._resultListEl.style.display="none");const e=t.slice(0,50);for(let t=0;t<e.length;t++){const n=e[t],r=document.createElement("div");r.dataset.index=String(t),r.tabIndex=-1,r.style.cssText=["padding:4px 10px","cursor:pointer","display:flex","align-items:center","gap:6px","font-size:12px","border-bottom:1px solid rgba(255,255,255,0.04)","transition:background 0.1s","outline:none"].join(";"),r.addEventListener("mouseenter",()=>{this._keyboardNav=!1,r.style.background="rgba(255,255,255,0.08)"}),r.addEventListener("mouseleave",()=>{this._engine.currentIndex!==t?r.style.background="none":r.style.background="rgba(74,158,255,0.15)"}),r.addEventListener("click",()=>{this._selectResult(t)}),r.addEventListener("keydown",e=>{e.stopPropagation(),"ArrowDown"===e.key?(this._focusResult(t+1),e.preventDefault()):"ArrowUp"===e.key?(0===t?(this._input?.focus(),this._input?.select()):this._focusResult(t-1),e.preventDefault()):"Enter"===e.key?(this._selectResult(t),e.preventDefault()):"Escape"===e.key?(this.hide(),this._host?.element?.focus(),e.preventDefault()):e.shiftKey&&"Tab"===e.key?(this._input?.focus(),e.preventDefault()):1!==e.key.length||e.metaKey||e.ctrlKey||e.altKey||this._input?.focus()});const i=document.createElement("span");i.textContent=$u[n.matchType]||n.matchType,i.style.cssText=["font-size:9px","padding:1px 4px","border-radius:3px","background:rgba(74,158,255,0.2)","color:rgba(74,158,255,0.9)","flex-shrink:0","text-transform:uppercase","letter-spacing:0.5px"].join(";"),r.appendChild(i);const s=document.createElement("span");s.textContent=n.component.state.type||"?",s.style.cssText="color:rgba(255,255,255,0.7);flex-shrink:0",r.appendChild(s);const o=document.createElement("span");if(o.textContent=this._truncate(n.matchValue,30),o.style.cssText="color:rgba(255,200,100,0.8);overflow:hidden;text-overflow:ellipsis;white-space:nowrap",r.appendChild(o),"id"!==n.matchType&&n.component.state.id){const t=document.createElement("span");t.textContent=`#${n.component.state.id}`,t.style.cssText="color:rgba(255,255,255,0.3);font-size:11px;margin-left:auto;flex-shrink:0",r.appendChild(t)}this._resultListEl.appendChild(r)}if(t.length>50){const e=document.createElement("div");e.style.cssText="padding:4px 10px;font-size:11px;color:rgba(255,255,255,0.3);text-align:center",e.textContent=`... and ${t.length-50} more`,this._resultListEl.appendChild(e)}this._resultListEl.style.display="block",this._updateResultListSelection()}_updateResultListSelection(){if(!this._resultListEl)return;const t=this._engine.currentIndex;for(const e of Array.from(this._resultListEl.children)){const n=e,r=parseInt(n.dataset.index||"-1",10);n.style.background=r===t?"rgba(74,158,255,0.15)":"none"}const e=this._resultListEl.querySelector(`[data-index="${t}"]`);e?.scrollIntoView({block:"nearest"})}_hideResultList(){this._resultListEl&&(this._resultListEl.style.display="none",this._resultListEl.innerHTML="")}_truncate(t,e){return t.length>e?t.slice(0,e)+"...":t}}Wu.MAX_HISTORY=20;let Xu=0;const qu=new FinalizationRegistry(t=>{Xu--});class Ku{static get residents(){return Xu}static get residentsCount(){return Xu}constructor(t){this._searchOverlay=new Wu,this._container=t,this.app=t.app,this._commander=new Fu(this._container),this.app.commander=this._commander,Xu++,qu.register(this,Xu),Bu.register(this),this._container.target_element&&this._setupSearchOverlay()}add(t,e,n){return Jc.call(this._container,t,e,n)}duplicate(){return tl.call(this._container)}remove(){return el.call(this._container)}animate(t){return Ro.call(this,t)}fullscreen(t){return al.call(this._container,t)}get target(){return this._container.target_element}set target(t){let e;if("string"==typeof t){if(e=document.getElementById(t),!e)throw new Error(`target element '${t}' does not exist`);if(e.firstChild)throw new Error(`target element '${t}' already has children`)}else e=t;e&&e.style&&(e.style.cursor="default"),this._container.target_element=e,this._setupSearchOverlay(),this._container.invalidate()}get scale(){return this.root.get("scale")}set scale(t){this.root.set("scale",t)}get translate(){return this.root.get("translate")}set translate(t){this.root.set("translate",t)}get unit(){return this.root.get("unit")||"px"}get PPM(){return this.app.PPM}get PPI(){return this.app.PPI}get DPPX(){return this.app.DPPX}static get DPPX(){return _i}get unitScale(){return this._container.unitScale}get screen(){return this.app.screen}set screen(t){this.app.screen=t,this._container.resize()}resize(){this._container.resize()}release(){this.dispose()}dispose(){this._searchOverlay.destroy(),Bu.unregister(this),this._commander&&this._commander.dispose(),this._container&&this._container.dispose(),Gu.flushCache()}get selected(){return this._container.selected.slice()}set selected(t){this._container.selected=t}select(t,...e){return this._container.selected=this.root?.findAll(t,...e),this.selected}get commander(){return this._commander}undo(){this.commander.undo()}undoable(){return this.commander.undoable()}redo(){this.commander.redo()}redoable(){return this.commander.redoable()}preserve(){this.commander.preserve()}hasUnpreservedChanges(){return this.commander.hasUnpreservedChanges()}cut(){return hl.call(this._container)}copy(){return ll.call(this._container)}paste(t){return dl.call(this._container,t)}undoableChange(t){return Pl.call(this._container,t)}change(t,e,n){return Cl.call(this.root,t,e,n)}get model(){return this.root.hierarchy}set model(t){this._container.rebuildContentModel(t)}get rootContainer(){return this._container}get root(){return this._container?.model_layer}findAll(t,...e){return this.root.findAll(t,...e)}findFirst(t,...e){return this.root.findFirst(t,...e)}findById(t){return this._container.findById(t)}findAllById(t){return this._container.findAllById(t)}serialize(){return this.root.trim(),this.root.serialize()}align(t){return Gc.call(this._container,t)}place(t){return Rl.call(this._container,t)}distribute(t){return $c.call(this._container,t)}move(t,e,n){return qc.call(this._container,t,e,n)}zorder(t){return Kc.call(this._container,t)}symmetryX(){return El.call(this._container)}symmetryY(){return kl.call(this._container)}on(t,e,n){return il.call(this._container,t,e,n)}once(t,e,n){return sl.call(this._container,t,e,n)}off(t,e,n){return this._container&&ol.call(this._container,t,e,n)}centerTo(t,e){return this.root.centerTo(t,e)}get mode(){return this.app.mode}set mode(t){void 0!==t&&(this.app.mode=t)}toDataURL(t,e,n,r){return xl.call(this._container,t,e,n,r)}group(){return wl.call(this._container)}ungroup(){return Ml.call(this._container)}fit(t){this._container.once("redraw",()=>this._container.fit(t)),this._container.invalidate()}get fitMode(){return this._container.fitMode}get ids(){return Tl.call(this._container)}get data(){return this._container.data}set data(t){this._container.data=t}get dataByRefid(){return this._container.dataByRefid}set dataByRefid(t){this._container.dataByRefid=t}get values(){return this._container.values}set values(t){this._container.values=t}get valuesByRefid(){return this._container.valuesByRefid}set valuesByRefid(t){this._container.valuesByRefid=t}get baseUrl(){return this.app.baseUrl}set baseUrl(t){this.app.baseUrl=t}startAddMode(t){return Fl.call(this._container,t)}startStylePasteMode(){return Bl.call(this._container)}stopStylePasteMode(){return Nl.call(this._container)}startDatabindPasteMode(){return Hl.call(this._container)}stopDatabindPasteMode(){return Vl.call(this._container)}get searchOverlay(){return this._searchOverlay}_setupSearchOverlay(){const t=this;this._searchOverlay.setup({get root(){return t.root},get element(){return t.target},centerTo(e,n){t.centerTo(e,n)},setSelected(e){t.selected=e},invalidate(){t._container?.invalidate()}});const e=this._container.model_layer;e&&(e.onSearchToggle=()=>this._searchOverlay.toggle())}}const Qu=new class{async load(t){}async save(t,e){}async clear(t){}};function Zu({target:t,model:e,style:n,layers:r=[],handlers:i=[],mode:s=0,refProvider:o,dataSubscriptionProvider:a,dataStorage:c=Qu,baseUrl:l,fitMode:h,postprocessing:d=!0}){let u=null;if("string"==typeof t){if(u=document.getElementById(t),!u)throw new Error(`target element '${t}' does not exist`);if(u.firstChild)throw new Error(`target element '${t}' is not empty`)}else u=t??null;u&&u.style&&(u.style.position="absolute",u.style.cursor="default",u.style.overflow="hidden");const p=new Ou(s,o);return l&&(p.baseUrl=l),p.postprocessing=d,p.dataSubscriptionProvider=a,p.dataStorage=c,new Ku(new ku({target_element:u,model:e,style:n,layers:r,handlers:i,fitMode:h},p))}function Ju(t,e,n,r){var i,s=arguments.length,o=s<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,n,o):i(e,n))||o);return s>3&&o&&Object.defineProperty(e,n,o),o}function tp(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)}function ep(t,e,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(t,n):i?i.value=n:e.set(t,n),n}"function"==typeof SuppressedError&&SuppressedError;
3
+ return!t||t.scalable?this.context2D:this.auxContext2D}draw(t){this.canvas&&this.element&&(t=t||this.getContext(void 0))&&(this.auxContext2D.clearRect(0,0,this.auxCanvas.width,this.auxCanvas.height),this.auxContext2D.save(),this.auxContext2D.scale(_i,_i),super.draw(t),this.auxContext2D.restore())}}var yc,bc,vc,_c;!function(t){t.CANVAS="canvas",t.DOM="dom"}(yc||(yc={}));class xc{get overlay(){return this._overlay}constructor(t,e,n={}){if(this.element=null,this.isActive=!1,this._overlay=null,this.target=e,this.options={animation:!0,repeat:!0,duration:3e3,color:"#ff0000",opacity:1,fadeOut:!1,...n},this.mode=n.mode||this.determineOptimalMode(),t){this._overlay=t;bs.getInstance().addOverlay(t)}}determineOptimalMode(){return!1!==this.options.animation?yc.DOM:yc.CANVAS}start(){if(!this.isActive&&(this.isActive=!0,this.mode===yc.DOM)){this.overlay?(this.createDOMElements(),this.target.on("change",this.handleTargetChange,this),this.target.on("removed",this.handleTargetRemoved,this)):(Rr("오버레이가 설정되지 않아 DOM 모드 데코레이터를 시작할 수 없습니다."),this.isActive=!1)}}stop(){this.isActive&&(this.isActive=!1,this.mode===yc.DOM&&(this.target.off("change",this.handleTargetChange,this),this.target.off("removed",this.handleTargetRemoved,this),this.removeDOMElements()))}update(t){if(t&&(this.options={...this.options,...t},t.mode&&t.mode!==this.mode))return this.stop(),this.mode=t.mode,void this.start();this.mode===yc.DOM&&this.isActive&&this.updateDOMElements()}render(t,e){return!(this.mode!==yc.CANVAS||!this.isActive)&&this.renderCanvas(t,e)}removeDOMElements(){this.element&&this.element.parentNode&&(this.element.parentNode.removeChild(this.element),this.element=null)}updateDOMElements(){this.removeDOMElements(),this.createDOMElements()}getComponentPosition(){const{left:t,top:e,width:n,height:r}=this.target.bounds;if("function"==typeof this.target.toGlobal)try{const{x:i,y:s}=this.target.toGlobal(t,e,this.target.rootModel);return{x:i,y:s,width:n,height:r}}catch(t){Rr("좌표 변환 실패, 기본값 사용:",t)}return{x:t,y:e,width:n,height:r}}handleTargetChange(t,e){this.target.disposed?this.stop():this.invalidate()}handleTargetRemoved(){this.stop()}invalidate(){}}function wc(t,e,n){const r=t.rootModel;if(r?.is3dMode){const e=t._realObject?.object3d,n=r.activeCamera3d,i=r.renderer3d;if(e&&n&&i){const t=new _.Vector3;e.getWorldPosition(t);const r=t.clone().project(n),s=i.domElement;return{x:(.5*r.x+.5)*s.clientWidth,y:(.5*-r.y+.5)*s.clientHeight}}return null}const i=t.toGlobal(e,n,r);return isNaN(i.x)||isNaN(i.y)?null:i}class Mc extends xc{constructor(t,e,n={}){super(t,e,{strokeWidth:2,strokeColor:"#FF0000",strokeOpacity:1,fillColor:"none",fillOpacity:.5,scale:1,rotation:0,x:0,y:0,zIndex:0,mode:yc.DOM,...n}),this.vectorElement=null,this.animationElements=[],this.svgContainer=null,this.animationElement=null}getDecoratorType(){return this.constructor.DECORATOR_TYPE}dispose(){this.removeDOMElements()}determineOptimalMode(){return yc.DOM}renderCanvas(t,e){return Rr("VectorDecorator는 Canvas 렌더링을 지원하지 않습니다. DOM 모드를 사용하세요."),!1}getSvgContainer(){if(!this.overlay)throw new Error("오버레이 요소가 없습니다.");if(!Mc.svgContainerCache.has(this.overlay)){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","vector-decorator-container"),t.setAttribute("pointer-events","none"),t.style.overflow="visible",t.style.position="absolute",t.style.top="0",t.style.left="0",this.overlay.appendChild(t),Mc.svgContainerCache.set(this.overlay,t)}return Mc.svgContainerCache.get(this.overlay)}getOrCreateDecoratorGroup(t=!1){const e=this.getSvgContainer(),n=this.getVectorGroupId(),r=this.getDecoratorType();let i=e.querySelector(`g[data-decorator-type-container="${r}"]`);if(!i){i=document.createElementNS("http://www.w3.org/2000/svg","g"),i.setAttribute("data-decorator-type-container",r),i.setAttribute("class",`${r}-container`),e.appendChild(i);const t=document.createElementNS("http://www.w3.org/2000/svg","defs");t.setAttribute("data-defs-for",r),i.appendChild(t)}let s=i.querySelector(`g[data-decorator-group-id="${n}"]`);if(!s){const{id:t}=this.target.state;return s=document.createElementNS("http://www.w3.org/2000/svg","g"),s.setAttribute("data-decorator-group-id",n),s.setAttribute("data-decorator-type",r),t&&s.setAttribute("data-component-id",t),i.appendChild(s),s}if(t)for(;s.firstChild;)s.removeChild(s.firstChild);return s}getDefsForType(){const t=this.getSvgContainer(),e=this.getDecoratorType();let n=t.querySelector(`g[data-decorator-type-container="${e}"]`);n||(this.getOrCreateDecoratorGroup(),n=t.querySelector(`g[data-decorator-type-container="${e}"]`));let r=n.querySelector(`defs[data-defs-for="${e}"]`);return r||(r=document.createElementNS("http://www.w3.org/2000/svg","defs"),r.setAttribute("data-defs-for",e),n.appendChild(r)),r}getDecoratorGroup(){const t=this.getSvgContainer(),e=this.getVectorGroupId(),n=t.querySelector(`g[data-decorator-group-id="${e}"]`);if(n)return n}createFadeAnimation(t=0,e=1,n=1e3,r={}){const i=document.createElementNS("http://www.w3.org/2000/svg","animate");return i.setAttribute("attributeName","opacity"),i.setAttribute("from",t.toString()),i.setAttribute("to",e.toString()),i.setAttribute("dur",`${n}ms`),r.delay&&i.setAttribute("begin",`${r.delay}ms`),i.setAttribute("fill","freeze"),r.repeat?i.setAttribute("repeatCount","indefinite"):i.setAttribute("repeatCount","1"),i}createTranslateAnimation(t,e=[],n=1e3,r={}){const i=document.createElementNS("http://www.w3.org/2000/svg","animateTransform");return i.setAttribute("attributeName","transform"),i.setAttribute("type","translate"),i.setAttribute("values",t.join(";")),e.length>0&&i.setAttribute("keyTimes",e.join(";")),i.setAttribute("dur",`${n}ms`),r.delay&&i.setAttribute("begin",`${r.delay}ms`),r.repeat?i.setAttribute("repeatCount","indefinite"):i.setAttribute("repeatCount","1"),i}createRotateAnimation(t=0,e=360,n=0,r=0,i=1e3,s={}){const o=document.createElementNS("http://www.w3.org/2000/svg","animateTransform");return o.setAttribute("attributeName","transform"),o.setAttribute("type","rotate"),o.setAttribute("from",`${t} ${n} ${r}`),o.setAttribute("to",`${e} ${n} ${r}`),o.setAttribute("dur",`${i}ms`),s.delay&&o.setAttribute("begin",`${s.delay}ms`),s.repeat?o.setAttribute("repeatCount","indefinite"):o.setAttribute("repeatCount","1"),o}addAnimations(t,e){e.forEach(e=>{t.appendChild(e),this.animationElements.push(e)})}projectComponentPoint(t,e,n){return wc(t,e,n)}updatePosition(){if(!this.vectorElement)return;const t=this.options,{left:e,top:n}=this.target.bounds,r=this.projectComponentPoint(this.target,e,n);if(!r)return;const i=r.x+(t.x??0),s=r.y+(t.y??0);this.vectorElement.setAttribute("transform",`translate(${i}, ${s})`)}updateDOMElements(){this.createDOMElements()}getVectorGroupId(){const t=this.getDecoratorType(),{refid:e="unknown"}=this.target.state;return`decorator-${t}-${e}`}removeVectorElements(){if(this.overlay)try{const t=Mc.svgContainerCache.get(this.overlay);if(!t)return;const e=this.getVectorGroupId(),n=this.getDecoratorType(),r=t.querySelector(`g[data-decorator-type-container="${n}"]`);if(r){const t=r.querySelector(`g[data-decorator-group-id="${e}"]`);if(t&&(this.vectorElement&&(this.vectorElement===t||t.contains(this.vectorElement))&&(this.vectorElement=null),this.animationElements=this.animationElements.filter(e=>!t.contains(e)),t.remove()),!r.querySelector("g[data-decorator-group-id]")){const t=r.querySelector(`defs[data-defs-for="${n}"]`);t&&t.remove(),r.remove()}}0===t.children.length&&(t.remove(),Mc.svgContainerCache.delete(this.overlay))}catch(t){jr("벡터 요소 제거 실패:",t)}}removeDOMElements(){this.removeVectorElements()}delta(t,e){if("string"==typeof t)return"fade"===t?this.applyFadeValue(e):"theta"===t&&this.applyRotationValue(e),{tx:0,ty:0};if("object"==typeof t){const e=t;("tx"in e||"ty"in e)&&this.applyTranslateValues(e.tx||0,e.ty||0),("sx"in e||"sy"in e)&&this.applyScaleValues(e.sx||1,e.sy||1)}return null}invalidate(){this.mode===yc.DOM&&this.isActive&&this.updateDOMElements()}touch(){}applyFadeValue(t){if(this.vectorElement){const e=t.toFixed(2);this.vectorElement.setAttribute("opacity",e)}}applyRotationValue(t){if(this.vectorElement){const e=this.getComponentBounds(),n=e.width/2,r=e.height/2,i=(180*t/Math.PI).toFixed(1);this.vectorElement.setAttribute("transform",`rotate(${i} ${n} ${r})`)}}applyTranslateValues(t,e){if(this.vectorElement){const n=this.vectorElement.getAttribute("transform")||"";if(n.includes("translate")){const r=n.replace(/translate\([^)]+\)/,`translate(${t}, ${e})`);this.vectorElement.setAttribute("transform",r)}else this.vectorElement.setAttribute("transform",`${n} translate(${t}, ${e})`.trim())}}applyScaleValues(t,e){if(this.vectorElement){const n=this.vectorElement.getAttribute("transform")||"";if(n.includes("scale")){const r=n.replace(/scale\([^)]+\)/,`scale(${t}, ${e})`);this.vectorElement.setAttribute("transform",r)}else this.vectorElement.setAttribute("transform",`${n} scale(${t}, ${e})`.trim())}}getComponentBounds(){return this.target&&this.target.bounds?this.target.bounds:{top:0,left:0,width:100,height:100}}}Mc.svgContainerCache=new WeakMap,Mc.DECORATOR_TYPE="vector";class Sc extends xc{constructor(t,e,n={}){super(t,e,{scale:1,strokeColor:"#000000",strokeWidth:1,rotation:0,shadow:!1,shadowColor:"rgba(0,0,0,0.5)",shadowBlur:5,shadowOffsetX:2,shadowOffsetY:2,...n}),this.animationId=null,this.canvasElement=null,this.context=null,this.animationFrame=null,this.deltaValue=0}determineOptimalMode(){return yc.CANVAS}createDOMElements(){Rr("RasterDecorator는 DOM 렌더링을 지원하지 않습니다. Canvas 모드를 사용하세요.")}setAnimationState(t=3e3,e=!1){Sc.animationStateMap.set(this.target,{startTime:Date.now(),duration:t,repeat:e})}getAnimationState(){const t=Sc.animationStateMap.get(this.target);if(!t)return{delta:0,finished:!0};const{startTime:e,duration:n,repeat:r}=t,i=Date.now()-e;let s=Math.min(1,i/n),o=s>=1;return r&&o&&(Sc.animationStateMap.set(this.target,{startTime:Date.now(),duration:n,repeat:r}),s=0,o=!1),{delta:s,finished:o}}bounceEffect(t,e=10){const n=Math.min(1,4*t);return Math.sin(n*Math.PI*10)*e*(1-n)}fadeEffect(t,e=!1){return e?t:1-t}pulseEffect(t,e=.8,n=1.2){return e+(.5*Math.sin(t*Math.PI*2)+.5)*(n-e)}rotateEffect(t,e=360){return t*e}applyShadowEffect(t){if(this.options.shadow){const e=this.options;t.shadowColor=e.shadowColor||"rgba(0,0,0,0.5)",t.shadowBlur=e.shadowBlur||5,t.shadowOffsetX=e.shadowOffsetX||2,t.shadowOffsetY=e.shadowOffsetY||2}}removeShadowEffect(t){t.shadowColor="transparent",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0}start(){super.start(),this.isActive&&this.options.animation&&this.setAnimationState(this.options.duration||3e3,this.options.repeat||!1)}stop(){null!==this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null),super.stop(),Sc.animationStateMap.delete(this.target)}applyTransform(t,e,n){const r=this.options,i=r.scale||1,s=r.rotation||0;if(1!==i||0!==s){if(t.translate(e,n),0!==s){const e=s*Math.PI/180;t.rotate(e)}1!==i&&t.scale(i,i),t.translate(-e,-n)}}delta(t,e){return"string"==typeof t?("fade"===t?(this.deltaValue=e,this.context&&(this.context.globalAlpha=e)):"theta"===t&&(this.deltaValue=e),{tx:0,ty:0}):null}invalidate(){this.context&&this.isActive&&(this.animationFrame||(this.animationFrame=requestAnimationFrame(()=>{this.animationFrame=null,this.renderCanvas(this.context,this.deltaValue)})))}touch(){this.deltaValue=0}}Sc.animationStateMap=new WeakMap;class Ac extends Mc{constructor(t,e,n={}){super(t,e,{size:1,showId:!1,animation:!1,...n}),this.arrowElement=null,this.labelElement=null,this.decoratorGroup=null}createDOMElements(){if(this.overlay)try{const t=this.getOrCreateDecoratorGroup(!0);this.decoratorGroup=t,t.setAttribute("transform","translate(0, 0)");const{size:e=1,showId:n=!1,duration:r=3e3,repeat:i=!0}=this.options,s=this.options.color||"#FF0000",o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d",this.createArrowPath(0,0,e)),o.setAttribute("fill",s),o.setAttribute("stroke",s),o.setAttribute("stroke-width","1"),o.setAttribute("class","bouncing-arrow");const a=[];if(this.options.animation){const t=this.createBounceAnimation(r,i);if(a.push(t),this.options.fadeOut){const t=this.createFadeAnimation(1,0,r,{repeat:i});a.push(t)}}if(this.addAnimations(o,a),t.appendChild(o),this.arrowElement=o,n&&this.target.state?.id){const n=this.createArrowLabel(0,0,s,this.target.state.id,e);if(this.options.animation){const t=[],e=this.createBounceAnimation(r,i);if(t.push(e),this.options.fadeOut){const e=this.createFadeAnimation(1,0,r,{repeat:i});t.push(e)}this.addAnimations(n,t)}t.appendChild(n),this.labelElement=n}this.vectorElement=t,this.updatePosition(),this.options.animation&&this.startAnimations()}catch(t){jr("화살표 SVG 요소 생성 실패:",t)}}createArrowPath(t,e,n=1){const r=n/this.getScale();return`\n M${t-10*r},${e-16*r} \n L${t+10*r},${e-16*r} \n L${t+10*r},${e-8*r} \n L${t+16*r},${e-8*r} \n L${t},${e} \n L${t-16*r},${e-8*r} \n L${t-10*r},${e-8*r} \n Z\n `}getScale(){try{if(this.target.rootModel&&"number"==typeof this.target.rootModel.scale)return this.target.rootModel.scale||1}catch(t){Rr("스케일 계산 실패, 기본값 사용",t)}return 1}createBounceAnimation(t,e){const n=["0,-10"],r=["0"];for(let t=1;t<=20;t++){const e=t/20;let i=Math.pow(e,.5).toFixed(3);parseFloat(r[r.length-1])>=parseFloat(i)&&(i=(parseFloat(r[r.length-1])+.01).toFixed(3)),n.push("0,0"),n.push("0,-10"),r.push(i),r.push((parseFloat(i)+.01).toFixed(3))}return r[r.length-1]="1.000",this.createTranslateAnimation(n,r,t,{repeat:e})}createArrowLabel(t,e,n,r,i=1){const s=document.createElementNS("http://www.w3.org/2000/svg","g");s.setAttribute("class","bouncing-arrow-label");const o=document.createElementNS("http://www.w3.org/2000/svg","rect");o.setAttribute("x",`${t+20*i}`),o.setAttribute("y",""+(e-20*i)),o.setAttribute("width",""+40*i),o.setAttribute("height",""+20*i),o.setAttribute("rx","3"),o.setAttribute("fill",n);const a=document.createElementNS("http://www.w3.org/2000/svg","text");return a.setAttribute("x",`${t+40*i}`),a.setAttribute("y",""+(e-6*i)),a.setAttribute("fill","white"),a.setAttribute("font-size",12*i+"px"),a.setAttribute("text-anchor","middle"),a.textContent=r,s.appendChild(o),s.appendChild(a),s}startAnimations(){setTimeout(()=>{this.animationElements.forEach(t=>{try{t instanceof SVGElement&&"beginElement"in t&&t.beginElement()}catch(t){jr("애니메이션 시작 오류:",t)}})},10)}invalidate(){this.updatePosition()}updatePosition(){if(!this.vectorElement)return;const{left:t,top:e,width:n}=this.target.bounds,r=this.projectComponentPoint(this.target,t+n/2,e);if(!r)return;const i=Math.max(r.x,20),s=Math.max(r.y,20);this.vectorElement.setAttribute("transform",`translate(${i}, ${s})`)}}Ac.DECORATOR_TYPE="bouncing-arrow",function(t){t.ROTATE="rotate",t.TRANSLATE_X="translateX",t.TRANSLATE_Y="translateY",t.SCALE="scale",t.FADE="fade"}(bc||(bc={})),function(t){t.VIBRATION="vibration",t.ROTATION="rotation",t.HEARTBEAT="heartbeat",t.MOVING="moving",t.OUTLINE="outline",t.FADE="fade",t.WAYPOINT="waypoint"}(vc||(vc={})),function(t){t.CENTER="center",t.TOP="top",t.RIGHT="right",t.BOTTOM="bottom",t.LEFT="left",t.TOP_RIGHT="top-right",t.BOTTOM_RIGHT="bottom-right",t.BOTTOM_LEFT="bottom-left",t.TOP_LEFT="top-left",t.TOP_LEFT_CORNER="top-left-corner",t.TOP_RIGHT_CORNER="top-right-corner",t.BOTTOM_LEFT_CORNER="bottom-left-corner",t.BOTTOM_RIGHT_CORNER="bottom-right-corner",t.LEFT_TOP="left-top",t.LEFT_BOTTOM="left-bottom",t.RIGHT_TOP="right-top",t.RIGHT_BOTTOM="right-bottom"}(_c||(_c={}));class Ec extends Mc{constructor(t,e,n={}){const{animations:r,...i}=n;super(t,e,{icon:"arrow_forward",size:24,color:"#FF0000",deltaX:0,deltaY:0,...i}),this.animations=[],this._location=null,this.element=null,this._delta={theta:0,tx:0,ty:0,sx:1,sy:1,fade:0},this.animations=this.createAnimations(r)}delta(t,e){if(!t)return this._delta;switch(typeof t){case"object":this._delta={...this._delta,...t};break;case"string":if(void 0===e)return this._delta[t];this._delta[t]=e}const{tx:n,ty:r,sx:i,sy:s,theta:o,fade:a}=this._delta;return this.element&&Object.assign(this._getElement().style,{opacity:1-a,transform:`rotate(${o}rad) translate(${n}px, ${r}px) scale(${i}, ${s}) perspective(1px)`}),this._delta}getScaledSize(){const t=this.options.size||24,{x:e}=this.target.rootModel?.state.scale||{x:1},{x:n}=this.target.state.scale||{x:1};return t*e*n}get location(){if(this._location)return this._location;const{location:t,position:e,size:n}=this.options,{bounds:r}=this.target,{left:i,top:s,width:o,height:a}=r,c=n/2;let l;switch(e||t||_c.CENTER){case _c.TOP_LEFT:case"top-left":l={x:i,y:s-n};break;case _c.TOP:case"top":l={x:i+(o-n)/2,y:s-n};break;case _c.TOP_RIGHT:case"top-right":l={x:i+o-n,y:s-n};break;case _c.BOTTOM_LEFT:case"bottom-left":l={x:i,y:s+a};break;case _c.BOTTOM:case"bottom":l={x:i+(o-n)/2,y:s+a};break;case _c.BOTTOM_RIGHT:case"bottom-right":l={x:i+o-n,y:s+a};break;case _c.LEFT_TOP:case"left-top":l={x:i-n,y:s};break;case _c.LEFT:case"left":l={x:i-n,y:s+(a-n)/2};break;case _c.LEFT_BOTTOM:case"left-bottom":l={x:i-n,y:s+(a-n)};break;case _c.RIGHT_TOP:case"right-top":l={x:i+o,y:s};break;case _c.RIGHT:case"right":l={x:i+o,y:s+(a-n)/2};break;case _c.RIGHT_BOTTOM:case"right-bottom":l={x:i+o,y:s+(a-n)};break;case _c.TOP_LEFT_CORNER:case"top-left-corner":l={x:i-c,y:s-c};break;case _c.TOP_RIGHT_CORNER:case"top-right-corner":l={x:i+o-c,y:s-c};break;case _c.BOTTOM_LEFT_CORNER:case"bottom-left-corner":l={x:i-c,y:s+a-c};break;case _c.BOTTOM_RIGHT_CORNER:case"bottom-right-corner":l={x:i+o-c,y:s+a-c};break;case _c.CENTER:default:l={x:i+o/2-n/2,y:s+a/2-n/2}}return this._location=this.toGlobal(l.x,l.y),this._location}_getElement(){return this.element||this._createElementIfNeeded(),this.element}_createElementIfNeeded(){if(this.element)return;const{icon:t="arrow_forward",color:e="#FF0000"}=this.options,n=this.getScaledSize(),{x:r,y:i}=this.location,s=document.createElement("div");s.setAttribute("scene","animated-icon"),Object.assign(s.style,{position:"absolute",fontVariationSettings:"'FILL' 1",fontFamily:"Material Symbols Outlined",fontSize:n+"px",width:n+"px",height:n+"px",lineHeight:n+"px",padding:0,margin:0,color:e,textAlign:"center",verticalAlign:"middle",left:r+"px",top:i+"px",pointerEvents:"none"}),s.textContent=t,this.element=s}updateIconSizeAndPosition(){if(!this.element)return;this._location=null;const t=this.getScaledSize(),{x:e,y:n}=this.location;Object.assign(this.element.style,{fontSize:t+"px",width:t+"px",height:t+"px",lineHeight:t+"px",left:e+"px",top:n+"px"})}touch(){}invalidate(){this.updateIconSizeAndPosition()}start(){super.start(),this.isActive&&(this.overlay&&this._getElement().parentNode!==this.overlay&&this.overlay.appendChild(this._getElement()),this.animations.forEach(t=>t.start()))}stop(){this.animations.forEach(t=>t.stop()),this.element&&this._getElement().parentNode&&this._getElement().parentNode.removeChild(this._getElement()),this._location=null,super.stop()}get center(){const t=this.getScaledSize(),{x:e,y:n}=this.location;return{x:e+t/2,y:n+t/2}}toGlobal(t,e){const{tx:n,ty:r}=this._delta;return this.projectComponentPoint(this.target,t+n,e+r)??this.target.toGlobal(t+n,e+r)}get root(){return this.target.root}createDOMElements(){this._getElement()}updateDOMElements(){this.element?this.updateIconSizeAndPosition():this._getElement()}updatePosition(){this.updateIconSizeAndPosition()}createAnimations(t){if(Array.isArray(t))return t.map(t=>("theta"in t&&(t={...t,theta:t.theta*(Math.PI/180)}),No(this,t)));if(t){const e={...t};return"theta"in e&&(e.theta=e.theta*(Math.PI/180)),[No(this,e)]}return[]}}Ec.DECORATOR_TYPE="animated-icon";class kc extends Mc{constructor(t,e,n={}){super(t,e,{distance:10,lineWidth:2,fillStyle:"rgba(0, 0, 0, 0.5)",animation:!1,...n}),this.pathElement=null,this.decoratorGroup=null,this.elementId=""}createDOMElements(){if(this.overlay)try{this.getSvgContainer();const t=this.getOrCreateDecoratorGroup(!0);this.decoratorGroup=t;const e=this.getDefsForType(),n=this.getVectorGroupId();this.elementId=`${n}-border`;const{color:r="#FF0000",animation:i=!1}=this.options,{fillStyle:s}=this.target.state||{},o=this.createFilter(this.elementId,this.options.fillStyle||s||"rgba(0, 0, 0, 0.5)");if(e.appendChild(o),i){const t=this.createGradient(this.elementId,r);e.appendChild(t)}const a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("fill","none"),a.setAttribute("stroke-width",(this.options.lineWidth||2).toString()),a.setAttribute("stroke-linejoin","round"),a.setAttribute("pointer-events","none"),a.setAttribute("class","border-highlighting-path"),a.setAttribute("filter",`url(#${this.elementId}-filter)`),i?a.setAttribute("stroke",`url(#${this.elementId})`):a.setAttribute("stroke",r),t.appendChild(a),this.pathElement=a,this.vectorElement=t,this.updatePathData(),this.options.animation&&this.startAnimations()}catch(t){jr("테두리 하이라이팅 요소 생성 실패:",t)}}updatePathData(){if(!this.pathElement)return;this.pathElement.setAttribute("visibility","visible"),this.pathElement.setAttribute("opacity","1"),this.decoratorGroup&&(this.decoratorGroup.setAttribute("visibility","visible"),this.decoratorGroup.setAttribute("opacity","1"));const t=this.getPathPoints(),e=this.createOffsetPath(t,this.options.distance),{round:n=0}=this.target.state||{},r=this.pointsToPathData(e,n);this.pathElement.setAttribute("d",r)}invalidate(){this.updatePathData()}startAnimations(){if(!this.isActive||!this.options.animation||!this.pathElement)return;this.pathElement.setAttribute("visibility","visible"),this.pathElement.setAttribute("opacity","1"),this.decoratorGroup&&(this.decoratorGroup.setAttribute("visibility","visible"),this.decoratorGroup.setAttribute("opacity","1")),this.elementId&&(this.pathElement.setAttribute("stroke",`url(#${this.elementId})`),this.pathElement.setAttribute("filter",`url(#${this.elementId}-filter)`));const t=this.getDefsForType();if(t){const e=t.querySelector(`#${this.elementId}`);if(e){e.querySelectorAll("animate").forEach(t=>{try{t instanceof SVGElement&&"beginElement"in t&&(t.setAttribute("restart","always"),t.beginElement())}catch(t){jr("애니메이션 시작 오류:",t)}})}}}createDefsElement(t){const e=document.createElementNS("http://www.w3.org/2000/svg","defs");return t.appendChild(e),e}getPathPoints(){if(!this.target.path||!Array.isArray(this.target.path)){const{left:t,top:e,width:n,height:r}=this.target.bounds;return[{x:t,y:e},{x:t+n,y:e},{x:t+n,y:e+r},{x:t,y:e+r}]}return this.target.path.map(t=>this.target.toGlobal(t.x,t.y))}createOffsetPath(t,e){const n=[],r=t.length;for(let i=0;i<r;i++){const s=t[(i-1+r)%r],o=t[i],a=t[(i+1)%r],c=o.x-s.x,l=o.y-s.y,h=a.x-o.x,d=a.y-o.y,u=this.normalize({x:l,y:-c}),p=this.normalize({x:d,y:-h}),f=this.normalize({x:(u.x+p.x)/2,y:(u.y+p.y)/2}),g={x:o.x+f.x*e,y:o.y+f.y*e};n.push(g)}return n}normalize(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return{x:t.x/e||0,y:t.y/e||0}}pointsToPathData(t,e=0){if(t.length<2)return"";let n="";const r=t.length,i=(t,e,n)=>{const r=e.x-t.x,i=e.y-t.y,s=Math.sqrt(r*r+i*i);return{x:t.x+r/s*n,y:t.y+i/s*n}};for(let s=0;s<r;s++){const o=t[s],a=t[(s+1)%r],c=t[(s-1+r)%r],l=Math.sqrt((o.x-c.x)**2+(o.y-c.y)**2),h=Math.sqrt((o.x-a.x)**2+(o.y-a.y)**2),d=Math.min(e,l/2,h/2),u=i(o,c,d),p=i(o,a,d);n+=0===s?`M${u.x},${u.y}`:` L${u.x},${u.y}`,n+=` Q${o.x},${o.y} ${p.x},${p.y}`}return n+=" Z",n}createFilter(t,e){const n=document.createElementNS("http://www.w3.org/2000/svg","filter");n.setAttribute("id",`${t}-filter`);const r=document.createElementNS("http://www.w3.org/2000/svg","feFlood");r.setAttribute("flood-color",e),r.setAttribute("result","flood");const i=document.createElementNS("http://www.w3.org/2000/svg","feComposite");i.setAttribute("in","flood"),i.setAttribute("in2","SourceAlpha"),i.setAttribute("operator","in"),i.setAttribute("result","mask");const s=document.createElementNS("http://www.w3.org/2000/svg","feMerge"),o=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");o.setAttribute("in","mask");const a=document.createElementNS("http://www.w3.org/2000/svg","feMergeNode");return a.setAttribute("in","SourceGraphic"),s.appendChild(o),s.appendChild(a),n.appendChild(r),n.appendChild(i),n.appendChild(s),n}createGradient(t,e){const n=document.createElementNS("http://www.w3.org/2000/svg","linearGradient");n.setAttribute("id",t),n.setAttribute("x1","0%"),n.setAttribute("y1","0%"),n.setAttribute("x2","100%"),n.setAttribute("y2","0%");const r=this.alterColor(e,120),i=this.alterColor(e,240),s=document.createElementNS("http://www.w3.org/2000/svg","stop");s.setAttribute("offset","0%"),s.setAttribute("stop-color",e);const o=document.createElementNS("http://www.w3.org/2000/svg","animate");o.setAttribute("attributeName","stop-color"),o.setAttribute("values",`${e};${r};${i};${e}`),o.setAttribute("dur","5s"),o.setAttribute("repeatCount","indefinite");const a=document.createElementNS("http://www.w3.org/2000/svg","stop");a.setAttribute("offset","100%"),a.setAttribute("stop-color",i);const c=document.createElementNS("http://www.w3.org/2000/svg","animate");return c.setAttribute("attributeName","stop-color"),c.setAttribute("values",`${i};${e};${r};${i}`),c.setAttribute("dur","5s"),c.setAttribute("repeatCount","indefinite"),s.appendChild(o),a.appendChild(c),n.appendChild(s),n.appendChild(a),n}alterColor(t,e){const n=this.convertToHex(t),r=parseInt(n.substring(1,3),16),i=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),o=this.rgbToHsl(r,i,s);o[0]=(o[0]+e/360)%1;const a=this.hslToRgb(o[0],o[1],o[2]);return`#${a[0].toString(16).padStart(2,"0")}${a[1].toString(16).padStart(2,"0")}${a[2].toString(16).padStart(2,"0")}`}rgbToHsl(t,e,n){t/=255,e/=255,n/=255;const r=Math.max(t,e,n),i=Math.min(t,e,n);let s=0,o=0;const a=(r+i)/2;if(r!==i){const c=r-i;switch(o=a>.5?c/(2-r-i):c/(r+i),r){case t:s=(e-n)/c+(e<n?6:0);break;case e:s=(n-t)/c+2;break;case n:s=(t-e)/c+4}s/=6}return[s,o,a]}hslToRgb(t,e,n){let r,i,s;if(0===e)r=i=s=n;else{const o=(t,e,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t),a=n<.5?n*(1+e):n+e-n*e,c=2*n-a;r=o(c,a,t+1/3),i=o(c,a,t),s=o(c,a,t-1/3)}return[Math.round(255*r),Math.round(255*i),Math.round(255*s)]}convertToHex(t){if(/^#([0-9A-F]{6})$/i.test(t))return t;const e=document.createElement("canvas");e.width=1,e.height=1;const n=e.getContext("2d");if(!n)return"#FF0000";n.fillStyle=t,n.fillRect(0,0,1,1);const r=n.getImageData(0,0,1,1).data;return`#${r[0].toString(16).padStart(2,"0")}${r[1].toString(16).padStart(2,"0")}${r[2].toString(16).padStart(2,"0")}`}start(){super.start(),this.isActive&&this.options.animation&&this.startAnimations()}removeDOMElements(){try{if(this.pathElement&&this.pathElement.parentNode&&this.pathElement.parentNode.removeChild(this.pathElement),this.pathElement=null,this.overlay){const t=this.getDefsForType();if(t&&this.elementId){const e=t.querySelector(`#${this.elementId}-filter`);e&&e.remove();const n=t.querySelector(`#${this.elementId}`);n&&n.remove()}}super.removeDOMElements()}catch(t){jr("테두리 하이라이팅 요소 제거 중 오류:",t)}}}kc.DECORATOR_TYPE="border-highlighting";class Cc extends Mc{constructor(t,e,n={}){super(t,e,{bgColor:"#FF0000",textColor:"white",cornerRadius:3,padding:3,fontSize:"12px",fontFamily:"Arial",...n}),this.textElements=[],this.rectElements=[]}updateDOMElements(){if(!this.target.anchors||!this.target.anchors.length)return void this.removeDOMElements();const t=this.options,e=this.target.anchors,n=this.getOrCreateDecoratorGroup(!0);this.textElements=[],this.rectElements=[];const r=this.getComponentBounds();e.forEach(e=>{const{name:i,position:s}=e;let{x:o,y:a}=s||{};if(!i)return;let c=this.calculateOffsetX(o,r),l=this.calculateOffsetY(a,r);const h=this.projectComponentPoint(this.target,o,a);if(!h)return;o=h.x,a=h.y;const d=document.createElementNS("http://www.w3.org/2000/svg","text");d.setAttribute("fill",t.textColor),d.setAttribute("font-family",t.fontFamily),d.setAttribute("font-size",t.fontSize),d.textContent=i,n.appendChild(d);const u=d.getBBox();n.removeChild(d);const p=u.width,f=u.height;c=-1==c?-p-9:3,l=-1==l?-f-9:3,d.setAttribute("x",(o+c+3).toString()),d.setAttribute("y",(a+l+f).toString());const g=document.createElementNS("http://www.w3.org/2000/svg","rect");g.setAttribute("x",(o+c).toString()),g.setAttribute("y",(a+l).toString()),g.setAttribute("width",(p+6).toString()),g.setAttribute("height",(f+6).toString()),g.setAttribute("rx",t.cornerRadius.toString()),g.setAttribute("ry",t.cornerRadius.toString()),g.setAttribute("fill",t.bgColor),n.appendChild(g),n.appendChild(d),this.rectElements.push(g),this.textElements.push(d)})}calculateOffsetX(t,e){return t<e.left+1?-1:1}calculateOffsetY(t,e){return t<e.top+1?-1:1}updatePosition(){super.updatePosition(),this.updateDOMElements()}invalidate(){this.updatePosition()}createDOMElements(){this.updateDOMElements()}}Cc.DECORATOR_TYPE="anchors";class Pc extends Mc{constructor(t,e,n={}){super(t,e,{bgColor:"#FF0000",textColor:"white",cornerRadius:3,padding:3,fontSize:"12px",fontFamily:"Arial",offsetX:3,offsetY:-8,animation:!1,...n}),this.textElement=null,this.backgroundElement=null,this.currentTag=""}createDOMElements(){const t=this.target.decotag;if(!t)return;this.currentTag=t;const{fontFamily:e,fontSize:n,textColor:r,padding:i,cornerRadius:s,bgColor:o,animation:a,repeat:c,duration:l}=this.options,h=this.getOrCreateDecoratorGroup(!0);h.setAttribute("transform","translate(0, 0)"),this.textElement=document.createElementNS("http://www.w3.org/2000/svg","text"),this.textElement.textContent=t,this.textElement.setAttribute("x",`${i}`),this.textElement.setAttribute("y",`-${n}`),this.textElement.setAttribute("font-family",e),this.textElement.setAttribute("font-size",n),this.textElement.setAttribute("fill",r),this.textElement.setAttribute("dominant-baseline","middle"),h.appendChild(this.textElement);const d=this.textElement.getBBox();if(this.backgroundElement=document.createElementNS("http://www.w3.org/2000/svg","rect"),this.backgroundElement.setAttribute("x",(d.x-i).toString()),this.backgroundElement.setAttribute("y",(d.y-i).toString()),this.backgroundElement.setAttribute("width",(d.width+2*i).toString()),this.backgroundElement.setAttribute("height",(d.height+2*i).toString()),this.backgroundElement.setAttribute("rx",s.toString()),this.backgroundElement.setAttribute("ry",s.toString()),this.backgroundElement.setAttribute("fill",o),h.replaceChildren(),h.appendChild(this.backgroundElement),h.appendChild(this.textElement),a){const t=this.createFadeAnimation(.3,1,l,{repeat:c});this.addAnimations(h,[t])}this.vectorElement=h,this.updatePosition()}updateDOMElements(){const t=this.target.decotag;t&&t===this.currentTag?this.vectorElement&&this.updatePosition():(this.removeDOMElements(),this.createDOMElements())}updatePosition(){super.updatePosition()}invalidate(){this.updatePosition()}}Pc.DECORATOR_TYPE="decotag";class Tc extends Mc{constructor(t,e,n={}){super(t,e,{arrowColor:"#FFA500",arrowHeadLength:12,lineWidth:1.5,startAlpha:.6,endAlpha:1,animated:!0,animationDuration:5e3,repeat:!1,...n}),this.currentMappings=null}createDOMElements(){if(this.removeDOMElements(),!this.target.mappings||!this.target.mappings.length)return;this.currentMappings=this.target.mappings;const t=this.options,e=this.getOrCreateDecoratorGroup(!0),n=this.getDefsForType(),r=`data-spread-style-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,i=document.createElementNS("http://www.w3.org/2000/svg","style");i.setAttribute("id",r),i.textContent=`\n @keyframes fadeOut {\n from { opacity: 1; }\n to { opacity: ${t.repeat?"0.2":"0"}; }\n }\n .arrow-animated {\n animation: fadeOut ${t.animationDuration||2e3}ms linear ${t.repeat?"infinite":"1"} forwards;\n }\n `,n.appendChild(i);const s=`arrow-gradient-${Date.now()}-${Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}`,o=document.createElementNS("http://www.w3.org/2000/svg","linearGradient");o.setAttribute("id",s),o.setAttribute("gradientUnits","userSpaceOnUse");const a=document.createElementNS("http://www.w3.org/2000/svg","stop");a.setAttribute("offset","0%"),a.setAttribute("stop-color",t.arrowColor||"#FFA500"),a.setAttribute("stop-opacity",(t.startAlpha||.5).toString());const c=document.createElementNS("http://www.w3.org/2000/svg","stop");c.setAttribute("offset","100%"),c.setAttribute("stop-color",t.arrowColor||"#FFA500"),c.setAttribute("stop-opacity",(t.endAlpha||1).toString()),o.appendChild(a),o.appendChild(c),n.appendChild(o);const l=document.createElementNS("http://www.w3.org/2000/svg","g");l.setAttribute("class",t.animated?"arrow-animated":""),e.appendChild(l);this.target.mappings.forEach(e=>{const n=this.target.root.findAll(e.target,this.target);n&&n.length&&n.forEach(e=>{const n=this.target.center,r=e.center,i=this.projectComponentPoint(this.target,n.x,n.y),a=this.projectComponentPoint(e,r.x,r.y);if(!i||!a)return;o.setAttribute("x1",i.x.toString()),o.setAttribute("y1",i.y.toString()),o.setAttribute("x2",a.x.toString()),o.setAttribute("y2",a.y.toString());const{linePath:c,headPath:h}=this.createArrowPaths(i,a,t.arrowHeadLength),d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d",c),d.setAttribute("stroke",`url(#${s})`),d.setAttribute("stroke-width",String(t.lineWidth||2)),d.setAttribute("fill","none"),d.setAttribute("data-target-id",e.state?.id||""),d.setAttribute("data-source-id",this.target.state?.id||"");const u=document.createElementNS("http://www.w3.org/2000/svg","path");u.setAttribute("d",h),u.setAttribute("fill",t.arrowColor||"#FFA500"),u.setAttribute("stroke","none"),l.appendChild(d),l.appendChild(u)})}),this.vectorElement=e}createArrowPaths(t,e,n){const r=e.x-t.x,i=e.y-t.y,s=Math.atan2(i,r),o=e.x+n*Math.cos(s+Tc.ARROW_ANGLE_1),a=e.y+n*Math.sin(s+Tc.ARROW_ANGLE_1),c=e.x+n*Math.cos(s+Tc.ARROW_ANGLE_2),l=e.y+n*Math.sin(s+Tc.ARROW_ANGLE_2);return{linePath:`M ${t.x} ${t.y} L ${e.x} ${e.y}`,headPath:`M ${e.x} ${e.y} L ${o} ${a} L ${c} ${l} Z`}}updateDOMElements(){if(!this.target.app?.isEditMode)return void this.removeDOMElements();const t=this.target.mappings;t&&t===this.currentMappings?this.vectorElement&&this.updatePosition():(this.removeDOMElements(),requestAnimationFrame(()=>{this.createDOMElements()}))}updatePosition(){const t=this.getDecoratorType(),e=this.getSvgContainer().querySelector(`g[data-decorator-type-container="${t}"]`);if(!e)return;const n=this.getVectorGroupId(),r=e.querySelector(`g[data-decorator-group-id="${n}"]`);if(!r)return;const i=this.options;if(!this.target.mappings||!this.target.mappings.length)return;const s=r.querySelector("g.arrow-animated")||r,o=Array.from(s.querySelectorAll('path[fill="none"]')),a=Array.from(s.querySelectorAll('path[stroke="none"]'));if(0===o.length)return;const c=e.querySelector(`defs[data-defs-for="${t}"]`);if(!c)return;const l=c.querySelector("linearGradient");if(!l)return;const h=this.target.mappings;let d=[];h.forEach(t=>{const e=this.target.root.findAll(t.target,this.target);e&&e.length&&(d=[...d,...e])});for(let t=0;t<Math.min(o.length,a.length,d.length);t++){const e=o[t],n=a[t],r=d[t],s=this.target.center,c=r.center,h=this.projectComponentPoint(this.target,s.x,s.y),u=this.projectComponentPoint(r,c.x,c.y);if(!h||!u)continue;const{linePath:p,headPath:f}=this.createArrowPaths(h,u,i.arrowHeadLength);e.setAttribute("d",p),n.setAttribute("d",f),0===t&&l&&(l.setAttribute("x1",h.x.toString()),l.setAttribute("y1",h.y.toString()),l.setAttribute("x2",u.x.toString()),l.setAttribute("y2",u.y.toString()))}}removeDOMElements(){this.currentMappings=null;try{if(this.overlay){const t=this.getSvgContainer();if(t){const e=this.getDecoratorType(),n=t.querySelector(`g[data-decorator-type-container="${e}"]`);if(n){const t=n.querySelector(`defs[data-defs-for="${e}"]`);if(t){t.querySelectorAll("style").forEach(t=>t.remove());t.querySelectorAll("linearGradient").forEach(t=>t.remove())}}}}this.animationElements=[],super.removeDOMElements()}catch(t){jr("데이터 스프레드 데코레이터 요소 제거 중 오류:",t)}}invalidate(){this.updatePosition()}}Tc.DECORATOR_TYPE="data-spread",Tc.ARROW_ANGLE_1=160*Math.PI/180,Tc.ARROW_ANGLE_2=200*Math.PI/180;class Dc extends Mc{constructor(t,e,n={}){super(t,e,{bgColor:"#FF0000",textColor:"white",cornerRadius:2,padding:2,fontSize:"12px",fontFamily:"Arial",offsetX:4,offsetY:4,...n}),this.textElements=[],this.rectElements=[]}createDOMElements(){this.updateDOMElements()}updateDOMElements(){if(!this.target.isLine||!this.target.isLine())return void this.removeDOMElements();const{offsetX:t,offsetY:e,padding:n,textColor:r,bgColor:i,cornerRadius:s,fontSize:o,fontFamily:a}=this.options,c=this.getOrCreateDecoratorGroup(!0);this.textElements=[],this.rectElements=[];const{fromEnd:l,toEnd:h}=this.target;[l,h].filter(Boolean).forEach(l=>{const{component:h,anchor:d}=l;if(!d)return;const{name:u,position:p}=d||{};if(!h.rootModel||!u||!p)return;const f=this.projectComponentPoint(h,p.x,p.y);if(!f)return;let{x:g,y:m}=f;const y=document.createElementNS("http://www.w3.org/2000/svg","g"),b=document.createElementNS("http://www.w3.org/2000/svg","text");b.setAttribute("text-anchor","middle"),b.setAttribute("dominant-baseline","middle"),b.setAttribute("x","0"),b.setAttribute("y","0"),b.setAttribute("fill",r),b.setAttribute("font-family",a),b.setAttribute("font-size",o),b.textContent=u,c.appendChild(b);const v=b.getBBox();c.removeChild(b);const _=document.createElementNS("http://www.w3.org/2000/svg","rect"),x=v.width+2*(n??0),w=v.height+2*(n??0);g+=(t??0)+x/2,m+=(e??0)+w/2,_.setAttribute("x",(-x/2).toString()),_.setAttribute("y",(-w/2).toString()),_.setAttribute("width",x.toString()),_.setAttribute("height",w.toString()),_.setAttribute("rx",(s??0).toString()),_.setAttribute("ry",(s??0).toString()),_.setAttribute("fill",i),y.appendChild(_),y.appendChild(b),y.setAttribute("transform",`translate(${g}, ${m})`),c.appendChild(y),this.rectElements.push(_),this.textElements.push(b)})}updatePosition(){super.updatePosition(),this.updateDOMElements()}invalidate(){this.updatePosition()}}Dc.DECORATOR_TYPE="link",ys.registerDecorator("bouncing-arrow",Ac),ys.registerDecorator("animated-icon",Ec),ys.registerDecorator("border-highlighting",kc),ys.registerDecorator("anchors",Cc),ys.registerDecorator("decotag",Pc),ys.registerDecorator("data-spread",Tc),ys.registerDecorator("link",Dc);class Oc{constructor(t){this.params=Object.assign({},t)}excute(){}}class zc extends Oc{execute(){this.params.changes.forEach(t=>t.component.set(t.after))}static before(t){return t.map(t=>({component:t}))}static after(t,e){e.execute(null,!1)}static around(t,e,n){e.call(n),t.execute(null,!1)}}const Ic="left",Lc="right",jc="center",Rc="bottom",Fc="middle",Bc="z-front",Nc="z-back",Hc="z-middle",Vc=[Ic,Lc,jc,"top",Fc,Rc,Bc,Nc,Hc];function Gc(t){if(!this.hasSameParentForAllSelected||-1===Vc.indexOf(t))return;const e=this.selected.filter(t=>!t.stuck);if(e.length<=1)return;const n=this.app.commander;zc.around(n,function(){!function(t,e){const n=JSON.parse(JSON.stringify(e[0].bounds));let r=n.left+n.width,i=n.top+n.height;for(let t=0;t<e.length;t++){const s=e[t].bounds;n.left=s.left>n.left?n.left:s.left,n.top=s.top>n.top?n.top:s.top,r=s.left+s.width>r?s.left+s.width:r,i=s.top+s.height>i?s.top+s.height:i}switch(n.width=r-n.left,n.height=i-n.top,t){case Ic:for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:n.left,top:r.top,width:r.width,height:r.height}}break;case jc:for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:n.left+n.width/2-r.width/2,top:r.top,width:r.width,height:r.height}}break;case Lc:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={left:r-n.width,top:n.top,width:n.width,height:n.height}}break;case"top":for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:r.left,top:n.top,width:r.width,height:r.height}}break;case Fc:for(let t=0;t<e.length;t++){const r=e[t].bounds;e[t].bounds={left:r.left,top:n.top+n.height/2-r.height/2,width:r.width,height:r.height}}break;case Rc:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={left:n.left,top:i-n.height,width:n.width,height:n.height}}break;case Bc:{let t=1/0;for(let n=0;n<e.length;n++){const r=e[n].state.zPos||0;r<t&&(t=r)}for(let n=0;n<e.length;n++)e[n].set({zPos:t});break}case Nc:{let t=-1/0;for(let n=0;n<e.length;n++){const r=(e[n].state.zPos||0)+(e[n].state.depth||0);r>t&&(t=r)}for(let n=0;n<e.length;n++){const r=e[n].state.depth||0;e[n].set({zPos:t-r})}break}case Hc:{let t=1/0,n=-1/0;for(let r=0;r<e.length;r++){const i=e[r].state.zPos||0,s=e[r].state.depth||0;i<t&&(t=i),i+s>n&&(n=i+s)}const r=(t+n)/2;for(let t=0;t<e.length;t++){const n=e[t].state.depth||0;e[t].set({zPos:r-n/2})}break}default:;}}(t,e)})}const Yc="VERTICAL",Uc=[Yc,"HORIZONTAL","Z"];function $c(t){if(!this.hasSameParentForAllSelected||-1===Uc.indexOf(t))return;const e=this.selected;if(e.length<=1)return;const n=this.app.commander;zc.around(n,function(){!function(t,e){if("Z"===t)return void function(t){const e=t.filter(t=>!t.stuck).slice(0);e.sort((t,e)=>(t.state.zPos||0)+(t.state.depth||0)/2-((e.state.zPos||0)+(e.state.depth||0)/2));const n=e.reduce((t,e)=>t+(e.state.depth||0),0),r=e[0].state.zPos||0,i=((e[e.length-1].state.zPos||0)+(e[e.length-1].state.depth||0)-r-n)/(e.length-1);let s=r+(e[0].state.depth||0);for(let t=1;t<e.length-1;t++){const n=e[t],r=n.state.depth||0;s+=i,n.set({zPos:s}),s+=r}}(e);const n=e.filter(t=>!t.stuck).slice(0);n.sort(function(e,n){const r=e.center,i=n.center;return t===Yc?r.y-i.y:r.x-i.x});const r=n.reduce((e,n)=>e+(t===Yc?n.bounds.height:n.bounds.width),0),i=n[0].bounds,s=n[n.length-1].bounds,o=((t===Yc?s.top+s.height-i.top:s.left+s.width-i.left)-r)/(n.length-1);let a=t===Yc?i.top+i.height:i.left+i.width;for(let e=1;e<n.length-1;e++){const r=n[e],i=r.bounds;a+=o,t===Yc?(r.bounds={left:i.left,top:a,width:i.width,height:i.height},a+=i.height):(r.bounds={left:a,top:i.top,width:i.width,height:i.height},a+=i.width)}}(t,e)})}function Wc(t){let e=0;for(;t&&!t.isRootModel();)e+=t.get("rotation")||0,t=t.parent;return e%(2*Math.PI)}class Xc extends Oc{execute(){this.params.changes.forEach(t=>{const{component:e,to_container:n,to_index:r,to_left:i,to_top:s}=t,o=function(t){if(t.isRootModel())return t.bounds;const{bounds:e,rotatePoint:n}=t;let r=n;return r=t.toScene(r.x,r.y),{left:r.x-(n.x-e.left),top:r.y-(n.y-e.top),width:e.width,height:e.height}}(e),a=Wc(e);if(e.removeSelf(!n),e.bounds=o,e.set("rotation",a),n){e.set("rotation",function(t,e){return((t.get("rotation")||0)-Wc(e))%(2*Math.PI)}(e,n));const o=function(t,e){if(e.isRootModel())return t.bounds;const{bounds:n,rotatePoint:r}=t,i=e.fromScene(r.x,r.y),s=e.bounds;return{left:i.x-(r.x-n.left)-s.left,top:i.y-(r.y-n.top)-s.top,width:n.width,height:n.height}}(e,n);t.to_left=void 0!==i?i:o.left,t.to_top=void 0!==s?s:o.top,e.bounds={left:t.to_left,top:t.to_top,width:o.width,height:o.height},void 0===r?n.addComponent(e):n.insertComponentAt(e,r)}})}}function qc(t,e,n){this.app.commander.execute(new Xc({changes:[{component:t,to_container:e,to_index:n}]}))}function Kc(t){const e=this.selected.filter(t=>!t.stuck);if(0===e.length||e[0].isRootModel())return;if(e.length>1&&("forward"===t||"backward"===t))return;const n=e[0].parent;let r;if("forward"===t){const t=n.indexOf(e[0]);r=[{component:e[0],from_container:n,to_container:n,from_index:t,to_index:t+1}]}else if("backward"===t){const t=n.indexOf(e[0]);r=[{component:e[0],from_container:n,to_container:n,from_index:t,to_index:t-1}]}else r=e.filter(t=>t.parent===n).sort((e,r)=>{const i=n.indexOf(e)<n.indexOf(r);return"front"===t?i:!i}).map((e,r)=>(n.indexOf(e),{component:e,to_container:n,to_index:"front"===t?n.components.length-r-1:r}));const i=new Xc({changes:r});this.app.commander.execute(i)}function Qc(t,e,n,r){const i=Fa.register(t.type);if(!i)return Rr("Class not found",t.type),null;n&&(t.refid=n(t.refid)),t.id&&r&&r(t.id)&&delete t.id;const s=new i(t,e);return t.components&&s.isContainer()&&(t.components.forEach(t=>{const i=Qc(t,e,n,r);i&&s.addComponent(i)}),delete t.components),s.created(),s}function Zc(t,e){const n=Bn(t.hierarchy);return delete n.id,Qc(n,t.app,e)}function Jc(t,e,n){t instanceof Array||(t=[t]),n||(n=this.model_layer);const r=[],i=new Map;this.selected=t.map(t=>{try{return Qc(t,n.app,t=>{const e=this.getNewRefid();return void 0!==t&&i.set(t,e),e},t=>(this.indexMap[t]||[])[0])}catch(t){return Rr(t),!1}}).filter(Boolean).map(t=>{const{left:s,top:o,width:a,height:c,x:l,y:h,cx:d,cy:u}=e;return t.replaceRefids(i),isNaN(s)||isNaN(o)||isNaN(a)||isNaN(c)||(t.bounds={left:s,top:o,width:a,height:c}),isNaN(l)||isNaN(h)||t.move({x:l,y:h},!1),isNaN(d)||isNaN(u)||(t.center={x:d,y:u}),r.push({component:t,to_container:n}),t}),this.app.commander.execute(new Xc({changes:r}))}function tl(){const t=[],e=new Map;if(this.selected=this.selected.filter(t=>!t.isRootModel()).map(n=>{const r=Zc(n,t=>{const n=this.getNewRefid();return void 0!==t&&e.set(t,n),n});return r.move({x:20,y:20},!1),t.push({component:r,to_container:n.parent}),r}).map(t=>(t.replaceRefids(e),t)),0===t.length)return;const n=new Xc({changes:t});this.app.commander.execute(n)}function el(){const t=this.selected;this.selected=[];let e=null;const n=t.filter(t=>!t.isRootModel()&&(t.parent.focusible||t.parent.isGroup())).map(t=>(e||(e=t.parent),{component:t,to_container:null}));for(;e&&e.isGroup();){const t=[];if(e.components.filter(t=>!n.find(e=>e.component===t)).forEach(e=>t.push(e)),t.length>1)break;const r=e.parent;t.forEach(t=>n.push({component:t,to_container:r})),n.push({component:e,to_container:null}),e=r}n.length>0&&this.app.commander.execute(new Xc({changes:n})),e&&e.calculateBounds&&e.calculateBounds()}const nl=new Set(["execute","redo","undo","command-reset"]);function rl(t,e,n,r){const i=function(t,e){return nl.has(e)?t.app?.commander:"mode"===e?t.app:t}(this,e);i?.[t](e,n,r)}function il(t,e,n){rl.call(this,"on",t,e,n)}function sl(t,e,n){rl.call(this,"once",t,e,n)}function ol(t,e,n){rl.call(this,"off",t,e,n)}function al(t){const e=this.target_element,n=t||this.fitMode,r=this;function i(){r.fit(n),document.fullscreenElement||document.removeEventListener("fullscreenchange",i)}document.addEventListener("fullscreenchange",i),e.requestFullscreen().catch(()=>{document.removeEventListener("fullscreenchange",i)})}let cl=0;function ll(){const t=this.selected.filter(t=>!t.isRootModel()).map(t=>t.hierarchy);if(0!==t.length)return cl=0,JSON.stringify(t,null,2)}function hl(){cl=0;const t=ll.call(this);return el.call(this),t}function dl(t){if(t)try{cl++,Jc.call(this,JSON.parse(t),{x:15*cl,y:15*cl})}catch(e){jr(e,t)}}const ul=function(){return{escape:function(t){return t.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")},parseExtension:t,mimeType:function(e){const n=t(e).toLowerCase();return function(){const t="application/font-woff",e="image/jpeg";return{woff:t,woff2:t,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:e,jpeg:e,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml"}}()[n]||""},dataAsUrl:function(t,e){return"data:"+e+";base64,"+t},isDataUrl:function(t){return-1!==t.search(/^(data:)/)},canvasToBlob:function(t){return t.toBlob?new Promise(function(e){t.toBlob(e)}):function(t){return new Promise(function(e){const n=window.atob(t.toDataURL().split(",")[1]),r=n.length,i=new Uint8Array(r);for(let t=0;t<r;t++)i[t]=n.charCodeAt(t);e(new Blob([i],{type:"image/png"}))})}(t)},resolveUrl:function(t,e){const n=document.implementation.createHTMLDocument(),r=n.createElement("base");n.head.appendChild(r);const i=n.createElement("a");return n.body.appendChild(i),r.href=e,i.href=t,i.href},getAndEncode:function(t){const e=3e4;_l.impl.options.cacheBust&&(t+=(/\?/.test(t)?"&":"?")+(new Date).getTime());return new Promise(function(n){const r=new XMLHttpRequest;let i;if(r.onreadystatechange=s,r.ontimeout=o,r.responseType="blob",r.timeout=e,r.open("GET",t,!0),r.send(),_l.impl.options.imagePlaceholder){const t=_l.impl.options.imagePlaceholder.split(/,/);t&&t[1]&&(i=t[1])}function s(){if(4!==r.readyState)return;if(200!==r.status)return void(i?n(i):a("cannot fetch resource: "+t+", status: "+r.status));const e=new FileReader;e.onloadend=function(){const t=e.result.split(/,/)[1];n(t)},e.readAsDataURL(r.response)}function o(){i?n(i):a("timeout of "+e+"ms occured while fetching resource: "+t)}function a(t){jr(t),n("")}})},uid:function(){let t=0;return function(){return"u"+e()+t++;function e(){return("0000"+(Math.random()*Math.pow(36,4)|0).toString(36)).slice(-4)}}}(),delay:function(t){return function(e){return new Promise(function(n){setTimeout(function(){n(e)},t)})}},asArray:function(t){const e=[],n=t.length;for(let r=0;r<n;r++)e.push(t[r]);return e},escapeXhtml:function(t){return t.replace(/#/g,"%23").replace(/\n/g,"%0A")},makeImage:function(t){return new Promise(function(e,n){const r=new Image;r.onload=function(){e(r)},r.onerror=n,r.src=t})},width:function(t){const n=e(t,"border-left-width"),r=e(t,"border-right-width");return t.scrollWidth+n+r},height:function(t){const n=e(t,"border-top-width"),r=e(t,"border-bottom-width");return t.scrollHeight+n+r}};function t(t){const e=/\.([^\.\/]*?)$/g.exec(t);return e?e[1]:""}function e(t,e){const n=window.getComputedStyle(t).getPropertyValue(e);return parseFloat(n.replace("px",""))}}(),pl=function(){const t=/url\(['"]?([^'"]+?)['"]?\)/g;return{inlineAll:function(t,i,s){return o()?Promise.resolve(t):Promise.resolve(t).then(n).then(function(e){let n=Promise.resolve(t);return e.forEach(function(t){n=n.then(function(e){return r(e,t,i,s)})}),n});function o(){return!e(t)}},shouldProcess:e,impl:{readUrls:n,inline:r}};function e(e){return-1!==e.search(t)}function n(e){const n=[];let r;for(;null!==(r=t.exec(e));)n.push(r[1]);return n.filter(function(t){return!ul.isDataUrl(t)})}function r(t,e,n,r){return Promise.resolve(e).then(function(t){return n?ul.resolveUrl(t,n):t}).then(r||ul.getAndEncode).then(function(t){return ul.dataAsUrl(t,ul.mimeType(e))}).then(function(n){return t.replace(function(t){return new RegExp("(url\\(['\"]?)("+ul.escape(t)+")(['\"]?\\))","g")}(e),"$1"+n+"$3")})}}(),fl=function(){return{resolveAll:function(){return t().then(function(t){return Promise.all(t.map(function(t){return t.resolve()}))}).then(function(t){return t.join("\n")})},impl:{readAll:t}};function t(){return Promise.resolve(ul.asArray(document.styleSheets)).then(function(t){const e=[];return t.forEach(function(t){try{ul.asArray(t.cssRules||[]).forEach(t=>e.push(t))}catch(e){Rr("Error while reading CSS rules from "+t.href,e instanceof Error?e.message:String(e))}}),e}).then(function(t){return t.filter(function(t){return t.type===CSSRule.FONT_FACE_RULE}).filter(function(t){return pl.shouldProcess(t.style.getPropertyValue("src"))})}).then(function(e){return e.map(t)});function t(t){return{resolve:function(){const e=(t.parentStyleSheet||{}).href;return pl.inlineAll(t.cssText,e)},src:function(){return t.style.getPropertyValue("src")}}}}}(),gl=function(){return{inlineAll:function e(n){return n instanceof Element?r(n).then(function(){return n instanceof HTMLImageElement?t(n).inline().then(()=>n):Promise.all(ul.asArray(n.childNodes).map(function(t){return e(t)})).then(()=>n)}):Promise.resolve(n);function r(t){const e=t.style.getPropertyValue("background");return e?pl.inlineAll(e).then(function(e){t.style.setProperty("background",e,t.style.getPropertyPriority("background"))}).then(function(){return t}):Promise.resolve(t)}},impl:{newImage:t}};function t(t){return{inline:function(e){return ul.isDataUrl(t.src)?Promise.resolve():Promise.resolve(t.src).then(e||ul.getAndEncode).then(function(e){return ul.dataAsUrl(e,ul.mimeType(t.src))}).then(function(e){return new Promise(function(n,r){t.onload=n,t.onerror=r,t.src=e})})}}}}(),ml={imagePlaceholder:void 0,cacheBust:!1};function yl(t,e){return function(t){void 0===t.imagePlaceholder?_l.impl.options.imagePlaceholder=ml.imagePlaceholder:_l.impl.options.imagePlaceholder=t.imagePlaceholder;void 0===t.cacheBust?_l.impl.options.cacheBust=ml.cacheBust:_l.impl.options.cacheBust=t.cacheBust}(e=e||{}),Promise.resolve(t).then(function(t){return vl(t,e.filter,!0)}).then(function(t){return function(t){return gl.inlineAll(t).then(function(){return t})}(t)}).then(function(t){const{bgcolor:n,width:r,height:i,style:s,sx:o=1,sy:a=1}=e||{},c=t.style;n&&(c.backgroundColor=n);r&&(c.width=r+"px");i&&(c.height=i+"px");c["margin-left"]="0px",c["margin-top"]="0px",c.transform=`rotate(0rad) translate(0px, 0px) scale(${o}, ${a}) perspective(1px)`,s&&Object.keys(s).forEach(function(t){c[t]=s[t]});return t}).then(function(n){return function(t,e,n){return Promise.resolve(t).then(function(t){return t.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),(new XMLSerializer).serializeToString(t)}).then(ul.escapeXhtml).then(function(t){return'<foreignObject x="0" y="0" width="100%" height="100%">'+t+"</foreignObject>"}).then(function(t){return'<svg xmlns="http://www.w3.org/2000/svg" width="'+e+'" height="'+n+'">'+t+"</svg>"}).then(function(t){return"data:image/svg+xml;charset=utf-8,"+t})}(n,e.width||ul.width(t),e.height||ul.height(t))})}function bl(t,e){return yl(t,e).then(ul.makeImage).then(ul.delay(100)).then(function(n){const r=function(t){const n=document.createElement("canvas");if(n.width=e.width||ul.width(t),n.height=e.height||ul.height(t),e.bgcolor){const t=n.getContext("2d");t.fillStyle=e.bgcolor,t.fillRect(0,0,n.width,n.height)}return n}(t);return r.getContext("2d").drawImage(n,0,0),r})}function vl(t,e,n){return n||!e||e(t)?Promise.resolve(t).then(function(t){if(t instanceof HTMLCanvasElement)try{return ul.makeImage(t.toDataURL()).then(t=>t)}catch(t){Rr(t)}return t.cloneNode(!1)}).then(function(n){return function(t,e,n){const r=t.childNodes;return 0===r.length?Promise.resolve(e):i(e,ul.asArray(r),n).then(function(){return e});function i(t,e,n){let r=Promise.resolve();return e.forEach(function(e){r=r.then(function(){return vl(e,n,!1)}).then(function(e){e&&t.appendChild(e)})}),r}}(t,n,e)}).then(function(e){return function(t,e){return e instanceof Element?Promise.resolve().then(n).then(r).then(i).then(s).then(function(){return e}):e;function n(){function n(t,e){function n(t,e){ul.asArray(t).forEach(function(n){e.setProperty(n,t.getPropertyValue(n),t.getPropertyPriority(n))})}t.cssText?e.cssText=t.cssText:n(t,e)}n(window.getComputedStyle(t),e.style)}function r(){function n(n){const r=window.getComputedStyle(t,n),i=r.getPropertyValue("content");if(""===i||"none"===i)return;const s=ul.uid(),o=e;o.className=o.className+" "+s;const a=document.createElement("style");function c(t,e,n){const r="."+t+":"+e,i=n.cssText?s(n):o(n);return document.createTextNode(r+"{"+i+"}");function s(t){const e=t.getPropertyValue("content");return t.cssText+" content: "+e+";"}function o(t){return ul.asArray(t).map(e).join("; ")+";";function e(e){return e+": "+t.getPropertyValue(e)+(t.getPropertyPriority(e)?" !important":"")}}}a.appendChild(c(s,n,r)),e.appendChild(a)}[":before",":after"].forEach(function(t){n(t)})}function i(){t instanceof HTMLTextAreaElement&&e instanceof HTMLTextAreaElement&&(e.textContent=t.value),t instanceof HTMLInputElement&&e instanceof HTMLInputElement&&e.setAttribute("value",t.value)}function s(){e instanceof SVGElement&&(e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e instanceof SVGRectElement&&["width","height"].forEach(function(t){const n=e.getAttribute(t);n&&e.style.setProperty(t,n)}))}}(t,e)}):Promise.resolve(void 0)}const _l={toSvg:yl,toPng:function(t,e){return bl(t,e||{}).then(function(t){return t.toDataURL()})},toJpeg:function(t,e){return bl(t,e=e||{}).then(function(t){return t.toDataURL("image/jpeg",e.quality||1)})},toBlob:function(t,e){return bl(t,e||{}).then(t=>ul.canvasToBlob(t))},toPixelData:function(t,e){return bl(t,e||{}).then(function(e){return e.getContext("2d").getImageData(0,0,ul.width(t),ul.height(t)).data})},impl:{fontFaces:fl,images:gl,util:ul,inliner:pl,options:{}}};function xl(t,e,n,r){const i=this.model_layer,s=i._overlay;return new Promise(function(o,a){if(i){const a=i.get("width"),c=i.get("height");n=n||a,r=r||c;const l=i.get("translate"),h=i.get("scale"),d=Math.min(n/a,r/c);n=a*d,r=c*d,i.set("translate",{x:0,y:0}),i.set("scale",{x:d/_i,y:d/_i});let u=Fa.createCanvas(n,r);const p=u.getContext("2d");if(i.draw(p),i.set("translate",l),i.set("scale",h),!s)return o(u.toDataURL(t,e)),void(u=null);_l.toPng(s,{sx:d,sy:d,width:n,height:r}).then(function(i){const s=new Image;s.onload=function(){p.drawImage(s,0,0,n,r),o(u.toDataURL(t,e)),u=null},s.src=i},function(n){jr(n),o(u.toDataURL(t,e)),u=null})}else a("No target model")})}function wl(){if(!this.hasSameParentForAllSelected)return;const t=this.selected.filter(t=>!!t.parent&&!t.stuck);if(t.length<2)return;const e=t[0].parent,n=[],r=t.sort((t,n)=>e.components.indexOf(t)-e.components.indexOf(n));r.forEach(t=>{n.push(t.bounds)});const i=Fa.union(n);let s=t[0].fromParent(i.left,i.top);s=t[0].toScene(s.x,s.y);const o=new Map,a=Qc({type:"group",left:s.x,top:s.y,width:i.width,height:i.height},e.app,t=>{const e=this.getNewRefid();return void 0!==t&&o.set(t,e),e});a.replaceRefids(o);const c=[{component:a,to_container:e}];r.forEach(t=>{c.push({component:t,to_container:a})}),this.app.commander.execute(new Xc({changes:c})),this.selected=[a]}function Ml(){if(0===this.selected.length)return;const t=[],e=[];this.selected.forEach(n=>{if(!n.isGroup())return;const r=n.parent;n.components.forEach(n=>{t.push(n),e.push({component:n,to_container:r})}),e.push({component:n,to_container:null})}),this.app.commander.execute(new Xc({changes:e})),this.selected=t}function Sl(){const t=this.selected;if(0===t.length)return;const e=t.map(t=>t.bounds),n=Fa.union(e),r=n.left+n.width/2;t.map(t=>{t.symmetryX(r)})}function Al(){const t=this.selected;if(0===t.length)return;const e=t.map(t=>t.bounds),n=Fa.union(e),r=n.top+n.height/2;t.map(t=>{t.symmetryY(r)})}function El(){zc.around(this.app.commander,Sl,this)}function kl(){zc.around(this.app.commander,Al,this)}function Cl(t,e,n){const r=this.findAll(t,n);return r.forEach(t=>{t.set(e)}),r}function Pl(t){zc.around(this.app.commander,t)}function Tl(){return Object.values(this.indexMap).map(t=>t.map(t=>{const{id:e,data:n}=t.model;return{key:e,value:n}})).flat().sort((t,e)=>t.key>e.key?1:-1)}const Dl="left",Ol="right",zl="center",Il="bottom",Ll="middle",jl=[Dl,Ol,zl,"top",Ll,Il];function Rl(t){if(!this.hasSameParentForAllSelected||-1===jl.indexOf(t))return;const e=this.selected.filter(t=>!t.stuck);if(0===e.length)return;const n=this.app.commander;zc.around(n,function(){!function(t,e){const n=e[0].parent,{width:r,height:i}=n.bounds;switch(t){case Dl:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,left:0}}break;case zl:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,left:r/2-n.width/2}}break;case Ol:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,left:r-n.width}}break;case"top":for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,top:0}}break;case Ll:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,top:i/2-n.height/2}}break;case Il:for(let t=0;t<e.length;t++){const n=e[t].bounds;e[t].bounds={...n,top:i-n.height}}break;default:;}}(t,e)})}function Fl(t){t instanceof Array||(t=[t]),this.trigger("addstart",t)}function Bl(){this.trigger("stylepastestart")}function Nl(){this.trigger("stylepastestop")}function Hl(){this.trigger("databindpastestart")}function Vl(){this.trigger("databindpastestop")}let Gl=0,Yl=0,Ul=0,$l=null;function Wl(){Ul++;const t=performance.now(),e=t-Yl;e>=1e3&&(Gl=Math.round(1e3*Ul/e),Yl=t,Ul=0),$l=requestAnimationFrame(Wl)}function Xl(){null!==$l&&(cancelAnimationFrame($l),$l=null)}function ql(){return null===$l&&(Yl=performance.now(),Ul=0,$l=requestAnimationFrame(Wl)),Gl}const Kl=function(){const t=document.createElement("canvas").getContext("2d");return(window.devicePixelRatio||1)/(t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1)}();function Ql(t,e){const n=document.createElement("canvas");return n.width=t,n.height=e,n.style.width=t+"px",n.style.height=e+"px",n}const Zl=Math.sqrt(3);function Jl(t,e){const n=1.2*e;switch(t){case"size1":return{X:n,Y:n};case"size2":return{X:1.5*n,Y:n};case"size3":return{X:2*n,Y:n};case"size4":return{X:n,Y:1.5*n};case"size5":default:return{X:1.5*n,Y:1.5*n};case"size6":return{X:2*n,Y:1.5*n};case"size7":return{X:n,Y:2*n};case"size8":return{X:1.5*n,Y:2*n};case"size9":return{X:2*n,Y:2*n}}}function th(t,e,n){switch(t){case"none":default:return null;case"arrow":{const t=Zl*e.X,n=e.Y,r=new _.ConeGeometry(n,t,16);return r.rotateZ(-Math.PI/2),r.translate(-t/2,0,0),{mesh:new _.Mesh(r,new _.MeshBasicMaterial)}}case"sharp-arrow":{const t=Zl*e.X*1.3,n=.65*e.Y,r=new _.ConeGeometry(n,t,16);return r.rotateZ(-Math.PI/2),r.translate(-t/2,0,0),{mesh:new _.Mesh(r,new _.MeshBasicMaterial)}}case"open-arrow":{const t=Zl*e.X,n=e.Y,r=new _.ConeGeometry(n,t,6);return r.rotateZ(-Math.PI/2),r.translate(-t/2,0,0),{mesh:new _.Mesh(r,new _.MeshBasicMaterial({wireframe:!0}))}}case"diamond":{const t=new _.OctahedronGeometry(1);return t.scale(e.X,e.Y,e.Y),{mesh:new _.Mesh(t,new _.MeshBasicMaterial)}}case"oval":{const t=new _.SphereGeometry(1,16,12);return t.scale(e.X,e.Y,e.Y),{mesh:new _.Mesh(t,new _.MeshBasicMaterial)}}case"cross":{const t=Math.max(e.X,e.Y),n=.9*t,r=.25*t,i=.15*t,s=new _.Group,o=[new _.Vector3(1,1,1).normalize(),new _.Vector3(1,-1,-1).normalize(),new _.Vector3(-1,1,-1).normalize(),new _.Vector3(-1,-1,1).normalize()];for(const t of o){const e=new _.CylinderGeometry(r,i,n,6),o=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,1,0),t);e.applyQuaternion(o),e.translate(t.x*n/2,t.y*n/2,t.z*n/2),s.add(new _.Mesh(e,new _.MeshBasicMaterial))}return{group:s}}}}function eh(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function nh(t,e,n,o){const{strokeStyle:a,alpha:c=1,lineWidth:l=2,begin:h="none",beginSize:d="size2",end:u="arrow",endSize:p="size2",label:f}=n,g=(new _.Vector3).subVectors(e,t),m=g.length(),y=new _.Group;if(m<.01)return y;const b=g.clone().normalize(),v=eh(h,l),x=eh(u,l),w=t.clone().add(b.clone().multiplyScalar(v)),M=e.clone().sub(b.clone().multiplyScalar(x));let S;if(Array.isArray(a)&&a.length>=2){const t=a[1];S=new _.Color(t.length>7?t.slice(0,7):t)}else S=new _.Color("string"==typeof a?a:"#00B050");const A=function(t,e,n,o){const{strokeStyle:a,alpha:c=1,lineWidth:l=2,lineDash:h="solid"}=n,d=new s.LineGeometry;let u;d.setPositions([t.x,t.y,t.z,e.x,e.y,e.z]);let p=!1;if(Array.isArray(a)&&a.length>=2){const t=new _.Color(a[0].length>7?a[0].slice(0,7):a[0]),e=new _.Color(a[1].length>7?a[1].slice(0,7):a[1]);d.setColors([t.r,t.g,t.b,e.r,e.g,e.b]),p=!0,u=e}else u=new _.Color("string"==typeof a?a:"#00B050");const{dashed:f,dashSize:g,gapSize:m}=function(t,e){switch(t){case"solid":default:return{dashed:!1,dashSize:1,gapSize:0};case"round-dot":return{dashed:!0,dashSize:e,gapSize:2*e};case"square-dot":return{dashed:!0,dashSize:2*e,gapSize:e};case"dash":return{dashed:!0,dashSize:4*e,gapSize:1.5*e};case"dash-dot":return{dashed:!0,dashSize:2.5*e,gapSize:1.5*e};case"long-dash":return{dashed:!0,dashSize:6*e,gapSize:3*e};case"long-dash-dot":return{dashed:!0,dashSize:3.5*e,gapSize:2*e};case"long-dash-dot-dot":return{dashed:!0,dashSize:3*e,gapSize:1.5*e}}}(h,l),y=new i.LineMaterial({color:p?16777215:u.getHex(),linewidth:l,worldUnits:!0,vertexColors:p,dashed:f,dashSize:g,gapSize:m,transparent:c<1||Array.isArray(a)&&a.some(t=>t.length>7),opacity:c,resolution:o}),b=new r.Line2(d,y);return b.computeLineDistances(),b}(w,M,n,o);y.add(A);const E=(new _.Quaternion).setFromUnitVectors(new _.Vector3(1,0,0),b),k=(new _.Quaternion).setFromUnitVectors(new _.Vector3(1,0,0),b.clone().negate()),C=(t,e,n)=>{if(!t)return;const r=t.mesh||t.line2||t.group;if(r){if(r.position.copy(e),r.setRotationFromQuaternion(n),t.mesh){const e=t.mesh.material;e.color.copy(S),e.transparent=c<1,e.opacity=c}else if(t.line2){const e=t.line2.material;e.color.copy(S),e.transparent=c<1,e.opacity=c,e.resolution.copy(o)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color.copy(S),e.transparent=c<1,e.opacity=c,e.resolution&&e.resolution.copy(o)}});y.add(r)}};C(th(u,Jl(p,l)),e,E);if(C(th(h,Jl(d,l)),t,k),f){const n=(new _.Vector3).addVectors(t,e).multiplyScalar(.5);n.y+=3;const r=function(t,e,n){const r="Arial",i=Ql(256,64),s=i.getContext("2d");s.font=`bold 28px ${r}`;const o=s.measureText(t).width;s.fillStyle=e,s.fillRect(0,0,o+12,40),s.fillStyle="white",s.font=`bold 28px ${r}`,s.textBaseline="top",s.fillText(t,6,6);const a=new _.CanvasTexture(i);a.needsUpdate=!0,a.minFilter=_.LinearFilter,a.colorSpace=_.SRGBColorSpace;const c=new _.SpriteMaterial({map:a,transparent:!0}),l=new _.Sprite(c);l.position.copy(n);const h=(o+12)/40;return l.scale.set(4*h,4,1),l}(f,"string"==typeof a?a:Array.isArray(a)&&a[1]||"#00B050",n);y.add(r)}return y}const rh=.001;function ih(t,e,n){let r=1;if(n&&"none"!=n&&"transparent"!=n){r=e*("string"==typeof n?a(n).getAlpha():1)}else r=0;t.opacity=r,t.transparent=r<1}function sh(t){const e=a(t);return e.isValid()?e.toHexString():t}const oh={width:1,height:1,depth:1},ah={x:1,y:1,z:1},ch={x:0,y:0,z:0},lh={x:0,y:0,z:0},hh={default:{metalness:0,roughness:.4},metal:{metalness:1,roughness:.3,envMapIntensity:1},glass:{metalness:0,roughness:.1,opacity:.3,envMapIntensity:1.5},plastic:{metalness:0,roughness:.4},wood:{metalness:0,roughness:.8,envMapIntensity:.3},ceramic:{metalness:.1,roughness:.2,envMapIntensity:.3},rubber:{metalness:0,roughness:.9,envMapIntensity:.3}};function dh(t){if(!t)return{metalness:0,roughness:.4,emissive:"#000000",emissiveIntensity:0,opacity:1,envMapIntensity:.5,side:"double",castShadow:!0,receiveShadow:!1};const e=hh[t.preset??"default"]??hh.default;return{metalness:t.metalness??e.metalness,roughness:t.roughness??e.roughness,emissive:t.emissive??"#000000",emissiveIntensity:t.emissiveIntensity??0,opacity:t.opacity??e.opacity??1,envMapIntensity:t.envMapIntensity??e.envMapIntensity??.5,side:t.side??"double",castShadow:t.castShadow??!0,receiveShadow:t.receiveShadow??!1}}const uh={double:_.DoubleSide,front:_.FrontSide,back:_.BackSide};function ph(t){return uh[t]??_.DoubleSide}function fh(t,e){t.metalness=e.metalness,t.roughness=e.roughness,t.emissive.set(e.emissive),t.emissiveIntensity=e.emissiveIntensity,t.opacity=e.opacity,t.transparent=e.opacity<1,t.envMapIntensity=e.envMapIntensity,t.side=ph(e.side)}const gh=["map","normalMap","roughnessMap","metalnessMap","aoMap","emissiveMap","bumpMap","displacementMap","alphaMap","envMap","lightMap"];function mh(t){for(const e of gh){const n=t[e];n?.dispose()}t.dispose()}function yh(t){t.traverse(t=>{if(t.geometry?.dispose(),t.material){const e=Array.isArray(t.material)?t.material:[t.material];for(const t of e)mh(t)}})}function bh(t,e,n){const r=document.createElement("canvas");r.width=e,r.height=n;const i=r.getContext("2d");if(!i)return null;let s;if("radial"===t.gradientType){const r=e/2,o=n/2,a=Math.max(e,n)/2;switch(t.center){case"left-top":s=i.createRadialGradient(0,0,0,0,0,2*a);break;case"right-top":s=i.createRadialGradient(e,0,0,e,0,2*a);break;case"left-bottom":s=i.createRadialGradient(0,n,0,0,n,2*a);break;case"right-bottom":s=i.createRadialGradient(e,n,0,e,n,2*a);break;default:s=i.createRadialGradient(r,o,0,r,o,a)}}else{const r=t.rotation??0,o=e/2,a=n/2,c=Math.cos(r)*o,l=Math.sin(r)*a;s=i.createLinearGradient(o-c,a-l,o+c,a+l)}for(const e of t.colorStops)if(e.position>=0&&e.position<=1)try{s.addColorStop(e.position,e.color)}catch{s.addColorStop(e.position,"#fff")}return i.fillStyle=s,i.fillRect(0,0,e,n),r}function vh(t){const{fillStyle:e}=t.state;if("object"==typeof e)return"pattern"===e.type&&e.image?function(t,e){const{width:n,height:r}=t.state,i=Math.abs(n)||1,s=Math.abs(r)||1,o=new _.Texture;o.colorSpace=_.SRGBColorSpace;const a=new Image;return"data"!==String(e.image).substring(0,4)&&(a.crossOrigin="anonymous"),a.onload=()=>{const n=2*i,r=2*s,c=document.createElement("canvas");c.width=n,c.height=r;const l=c.getContext("2d");if(l){if(e.color&&(l.fillStyle=e.color,l.fillRect(0,0,n,r)),e.fitPattern)l.drawImage(a,0,0,n,r);else{const t=2*(e.width||a.naturalWidth),i=2*(e.height||a.naturalHeight),s=2*(e.offsetX||0),o=2*(e.offsetY||0);let c=0,h=0;switch(e.align){case"center":c=(n-t)/2,h=(r-i)/2;break;case"left-top":break;case"left-bottom":h=r-i;break;case"right-top":c=n-t;break;case"right-bottom":c=n-t,h=r-i;break;case"left":h=(r-i)/2;break;case"right":c=n-t,h=(r-i)/2;break;case"top":c=(n-t)/2;break;case"bottom":c=(n-t)/2,h=r-i}const d=s+c,u=o+h;if(e.noRepeat)l.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,d,u,t,i);else{l.save(),l.rect(0,0,n,r),l.clip();const e=d>0?d-Math.ceil(d/t)*t:d;for(let s=u>0?u-Math.ceil(u/i)*i:u;s<r;s+=i)for(let r=e;r<n;r+=t)l.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,r,s,t,i);l.restore()}}o.image=c,o.minFilter=_.LinearFilter,o.needsUpdate=!0,t.invalidate()}},a.onerror=t=>{jr("Pattern texture load error:",t)},a.src=t.app.url(e.image),o}(t,e):"gradient"===e.type&&e.colorStops?.length?function(t){const e=bh(t,256,256);if(!e)return;const n=new _.CanvasTexture(e);return n.colorSpace=_.SRGBColorSpace,n.needsUpdate=!0,n}(e):void 0}function _h(t,e){return-1!==t.findIndex(t=>t in e)}class xh{static buildFillStyleTexture(t){return vh(t)}constructor(t){this._focused=!1,this._suppressOnchange=!1,this._onchangeWrapper=(t,e)=>{this._suppressOnchange||this.onchange(t,e)},this._component=t,this.object3d=this.getObject3dInstance(),this.component.on("change",this._onchangeWrapper)}update(){this.clear(),this.build(),this.updateTransform(),this.updateFillStyle(),this.updateStrokeStyle(),this.updateAlpha(),this.updateHidden(),this.updateText()}getObject3dInstance(){return new _.Object3D}build(){this.object3d.userData.context=this;const t=dh(this.component.state.material3d);this._applyShadow(t.castShadow,t.receiveShadow),this.object3d.name=this.component.state.id}updateMaterial3d(){const t=dh(this.component.state.material3d);this._applyShadow(t.castShadow,t.receiveShadow)}_applyShadow(t,e){this.object3d.castShadow=t,this.object3d.receiveShadow=e,this.object3d.traverse(n=>{n!==this.object3d&&(n.castShadow=t,n.receiveShadow=e)})}get gizmoTransformable(){return!0}get component(){return this._component}get threeContainer(){let t=this.component;for(;t;){if("is3dContainer"in t&&t.is3dContainer())return t;t=t.parent}}get focused(){return this._focused}set focused(t){this._focused=t,t&&(this._focusedAt=performance.now())}dispose(){this.component.off("change",this._onchangeWrapper),this.clear()}clear(){for(const t of this.object3d.children)yh(t);return this.object3d.userData={},this.object3d.clear()}updateTransform(){if(this.component.state.screenFixed&&this.component.isHTMLElement()){const{x:t=0,y:e=0}=this.component.center,{width:n=0,height:r=0}=this.component.parent?.bounds??{};return this.object3d.position.set(t-n/2,-(e-r/2),0),void this.object3d.rotation.set(0,0,0)}const{x:t,y:e,z:n}=this.position,{x:r,y:i,z:s}=this.rotation,{x:o,y:a,z:c}=this.scale;this.object3d.position.set(t,e,n),this.object3d.rotation.set(r,i,s),this.object3d.scale.set(Math.max(o,rh),Math.max(a,rh),Math.max(c,rh))}get position(){const{x:t,y:e,z:n}=this.center;return{x:t,y:n,z:e}}get rotation(){const{rotationX:t=0,rotationY:e=0,rotation:n=0}=this.component.state;return{x:t,y:-n,z:e}}get scale(){const{scale:t}=this.component.state,e="number"==typeof t?t:t?.x??1;return{x:e,y:e,z:e}}get cx(){const{x:t=0}=this.component.center,{width:e=0}=this.component.parent?.bounds??{},{tx:n=0}=this.component.delta();return t+n-e/2}get cy(){const{y:t=0}=this.component.center,{height:e=0}=this.component.parent?.bounds??{},{ty:n=0}=this.component.delta();return t+n-e/2}get cz(){const{zPos:t=0}=this.component.state,{tz:e=0}=this.component.delta();return t+e+this.syncZPosOffset}get center(){const{x:t=0,y:e=0}=this.component.center,{width:n=0,height:r=0}=this.component.parent?.bounds??{},{tx:i=0,ty:s=0}=this.component.delta();return{x:t+i-n/2,y:e+s-r/2,z:this.cz}}get dimension(){const{width:t,height:e}=this.component.bounds;return{width:Math.abs(t)||1,height:Math.abs(e)||1,depth:this.effectiveDepth}}get effectiveDepth(){return this.component.state.depth||1}updatePosition(){const{x:t=0,y:e=0,z:n=0}=this.position;this.object3d.position.set(t,e,n)}updateRotate(){const{x:t=0,y:e=0,z:n=0}=this.rotation;this.object3d.rotation.set(t,e,n)}updateScale(){const{x:t=1,y:e=1,z:n=1}=this.scale;this.object3d.scale.set(Math.max(t,rh),Math.max(e,rh),Math.max(n,rh))}syncAnimationDelta(){const t=this.component.delta();this.updatePosition();const{rotationX:e=0,rotationY:n=0,rotation:r=0}=this.component.state,i=t.theta||0;this.object3d.rotation.set(e,-(r+i),n);const{scale:s}=this.component.state,o="number"==typeof s?s:s?.x??1,a=t.sx??1,c=t.sy??1;this.object3d.scale.set(Math.max(o*a,rh),Math.max(o*c,rh),Math.max(o,rh));const l=t.fade||0;if(0!==l){const t=(this.component.state.alpha??1)*(1-l);this.object3d.traverse(e=>{if(e.isMesh&&e.material){const n=Array.isArray(e.material)?e.material:[e.material];for(const e of n)e.opacity=t,e.transparent=e.opacity<1}})}}updateDimension(){this.clear(),this.build()}updateAlpha(){let{alpha:t}=this.component.state;t=null==t?1:t,this.object3d.traverse(e=>{let n=e.material;e.material&&(Array.isArray(n)||(n=[n]),n.forEach(e=>{e.opacity*=t,e.transparent=t<1}))})}updateHidden(){this.object3d.visible=!this.component.state.hidden}updateStrokeStyle(){}updateFillStyle(){}updateText(){}get syncZPosOffset(){return this.effectiveDepth/2}get textSurfaceYOffset(){return this.effectiveDepth-this.syncZPosOffset}syncFromObject3D(){const t=this.object3d,e=this._component,{width:n=0,height:r=0}=e.parent?.bounds??{},i=e.bounds,{tx:s=0,ty:o=0,tz:a=0}=e.delta();this._suppressOnchange=!0,e.bounds={left:t.position.x-s+n/2-i.width/2,top:t.position.z-o+r/2-i.height/2,width:i.width,height:i.height},e.set({zPos:t.position.y-a-this.syncZPosOffset,rotationX:t.rotation.x,rotation:-t.rotation.y,rotationY:t.rotation.z}),this._suppressOnchange=!1}onGizmoDragEnd(t){}applyDimensionFromGizmo(t){this._suppressOnchange=!0,this._component.set(t),this._suppressOnchange=!1}onchange(t,e){"screenFixed"in t&&this.updateTransform(),_h(["cx","cy","cz","zPos","left","top"],t)&&this.updatePosition(),_h(["width","height","depth","lineWidth"],t)&&this.updateDimension(),_h(["rotationX","rotationY","rotation"],t)&&this.updateRotate(),"scale"in t&&this.updateScale(),"hidden"in t&&this.updateHidden(),"alpha"in t&&this.updateAlpha(),"strokeStyle"in t&&this.updateStrokeStyle(),"fillStyle"in t&&this.updateFillStyle(),_h(["text","fontColor","fontSize","fontFamily","bold","italic","textAlign","textBaseline"],t)&&this.updateText(),"material3d"in t&&this.updateMaterial3d()}}class wh extends xh{get syncZPosOffset(){return this.effectiveDepth}getObject3dInstance(){return new o.CSS3DObject(this.component.element)}get rotation(){const{rotationX:t=0,rotationY:e=0,rotation:n=0}=this.component.state;return{x:t-Math.PI/2,y:e,z:-n}}syncFromObject3D(){const t=this.object3d,e=this._component,{width:n=0,height:r=0}=e.parent?.bounds??{},i=e.bounds,{tx:s=0,ty:o=0,tz:a=0}=e.delta();this._suppressOnchange=!0;const c=t.scale.x;e.bounds={left:t.position.x-s+n/2-i.width/2,top:t.position.z-o+r/2-i.height/2,width:i.width,height:i.height},e.set({zPos:t.position.y-a-this.syncZPosOffset,rotationX:t.rotation.x+Math.PI/2,rotation:-t.rotation.z,rotationY:t.rotation.y,scale:{x:c,y:c}}),this._suppressOnchange=!1}build(){super.build();const t=this.component.element;if(!t)return;const{width:e,height:n}=this.component.bounds;t.style.width=e+"px",t.style.height=n+"px",t.style.left="",t.style.top=""}updateDimension(){super.updateDimension();const t=this.dimension,e=this.component.element;e&&(e.style.width=t.width+"px",e.style.height=t.height+"px")}updateAlpha(){super.updateAlpha();const{alpha:t=1}=this.component.state,e=this.component.element;e&&(e.style.opacity=String(t))}}const Mh=new Map;let Sh;function Ah(t,e){Mh.set(t,e)}function Eh(t){Sh=t}function kh(t){const e=t.buildRealObject();if(e)return e;const n=t.model?.type,r=n?Mh.get(n):void 0;if(r)return r(t);if(t.isHTMLElement()){const e=Mh.get("html-overlay-element");if(e)return e(t)}return Sh?.(t)}function Ch(t,e,n){if(!t.hasTextProperty||t.textHidden)return;const r=t._realObject;if(!r?.object3d)return;const{text:i="",bold:s=Mi.BOLD,italic:a=Mi.ITALIC,fontFamily:c=Mi.FONT_FAMILY,fontColor:l=Mi.FONT_COLOR,fontSize:h=Mi.FONT_SIZE,textAlign:d=Mi.TEXT_ALIGN,textBaseline:u=Mi.TEXT_BASELINE,width:p,height:f}=t.model,g=Math.abs(p)||1,m=Math.abs(f)||1,y=document.createElement("textarea"),b=new AbortController;xi.forEach(t=>{y.addEventListener(t,t=>t.stopPropagation(),{capture:!0,signal:b.signal})}),y.value=i;const v="right"===d||"end"===d?"right":"left"===d||"start"===d?"left":"justify"===d?"justify":"center";let x="0";if("bottom"===u||"alphabetic"===u){const t=1.2*h*Math.max(1,(i.match(/\n/g)||[]).length+1);x=Math.max(0,m-t)+"px"}else if("middle"===u){const t=1.2*h*Math.max(1,(i.match(/\n/g)||[]).length+1);x=Math.max(0,(m-t)/2)+"px"}y.style.cssText=[`width: ${g}px`,`height: ${m}px`,`padding: ${x} 0 0 0`,"margin: 0",`font-family: ${c}`,`font-size: ${h}px`,`line-height: ${1.2*h}px`,"overflow: hidden","resize: none","outline: 1px solid #f26522","border: 0","background-color: rgba(255, 255, 255, 0.85)","display: block",`color: ${l}`,"box-sizing: border-box","font-weight: "+(s?"bold":"normal"),"font-style: "+(a?"italic":"normal"),`text-align: ${v}`].join("; ");const w=new o.CSS3DObject(y),M=r.object3d;M.updateWorldMatrix(!0,!1);const S=new _.Vector3,A=new _.Quaternion,E=new _.Vector3;M.matrixWorld.decompose(S,A,E);const k=new _.Vector3(0,r.textSurfaceYOffset,0);k.multiply(E),k.applyQuaternion(A),w.position.copy(S).add(k);const C=(new _.Quaternion).setFromAxisAngle(new _.Vector3(1,0,0),-Math.PI/2);w.quaternion.copy(A).multiply(C),w.scale.copy(E),e.css3DScene.add(w),n();const P=e.css3DRenderer.domElement,T=P.style.getPropertyValue("pointer-events"),D=P.style.getPropertyPriority("pointer-events"),O=[];let z=y;for(;z&&z!==P.parentElement;)O.push({el:z,saved:z.style.pointerEvents}),z.style.setProperty("pointer-events","auto","important"),z=z.parentElement;y.focus(),y.select();let I=!1;const L=t.root?.selected;y.addEventListener("keydown",t=>{t.stopPropagation(),"Escape"!==t.code&&(t.shiftKey||"Enter"!==t.code&&"NumpadEnter"!==t.code)||(I="Escape"===t.code,y.blur())},{signal:b.signal});const j=()=>{e.css3DScene.remove(w);for(const{el:t,saved:e}of O)e?t.style.pointerEvents=e:t.style.removeProperty("pointer-events");D?P.style.setProperty("pointer-events",T,D):T&&P.style.setProperty("pointer-events",T),b.abort(),y.removeEventListener("blur",j),L&&t.root&&(t.root.selected=L),I||y.value===i||t.app.commander.execute(new zc({changes:[{component:t,before:{text:i},after:{text:y.value}}]})),n()};y.addEventListener("blur",j)}class Ph extends n.Scene{dispose(){const t=new Set;this.traverse(e=>{if(e.isMesh){t.add(e.geometry);const n=e.material;Array.isArray(n)?n.forEach(e=>t.add(e)):t.add(n)}});for(const e of t)e.dispose()}}function Th(t,e){t.metalness=e.metalness,t.roughness=e.roughness,t.opacity=e.opacity,t.transparent=e.opacity<1,t.envMapIntensity=e.envMapIntensity}function Dh(t){const{fillStyle:e,floorMaterial3d:n}=t.state,r=dh(n);if("none"===e)return;const i=new _.BoxGeometry(1,1,1);let s;if(e){const n=xh.buildFillStyleTexture(t);if(n){const t="#424b57",e=[new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({color:t}),new _.MeshStandardMaterial({map:n}),new _.MeshStandardMaterial({color:t})];e.forEach(t=>Th(t,r)),s=e}else if("string"==typeof e){const t=new _.MeshStandardMaterial({color:e});Th(t,r),s=t}}if(!s){const t=new _.MeshStandardMaterial({color:"#e0e0e0"});Th(t,r),s=t}const o=new _.Mesh(i,s),{width:a,height:c}=t.state;return o.scale.set(a,c,5),o.rotation.x=-Math.PI/2,o.position.y=-3.5,o.name="floor",o.receiveShadow=!1!==n?.receiveShadow,o.castShadow=!0===n?.castShadow,o}const Oh={studio:class extends Ph{constructor(){super(),this.name="StudioEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:13421772}),r=new n.Mesh(t,e);r.position.set(0,13,0),r.scale.set(40,30,35),this.add(r);const i=new n.MeshStandardMaterial({color:11184810,roughness:.8}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(40,.5,35),this.add(s);const o=new n.PointLight(16777215,500,40,2);o.position.set(0,24,0),this.add(o);const a=new n.PointLight(16777215,200,30,2);a.position.set(-10,22,-8),this.add(a);const c=new n.PointLight(16777215,200,30,2);c.position.set(10,22,8),this.add(c);const l=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:16777215,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,26,r),o.scale.set(6,.1,6),o};this.add(l(-8,-6,60)),this.add(l(8,-6,60)),this.add(l(-8,6,60)),this.add(l(8,6,60)),this.add(l(0,0,50))}},warehouse:class extends Ph{constructor(){super(),this.name="WarehouseEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:8425632}),r=new n.Mesh(t,e);r.position.set(0,18,0),r.scale.set(50,40,40),this.add(r);const i=new n.MeshStandardMaterial({color:9474192,roughness:.9}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(50,.5,40),this.add(s);const o=new n.PointLight(15266047,600,50,2);o.position.set(-10,30,0),this.add(o);const a=new n.PointLight(15266047,600,50,2);a.position.set(10,30,0),this.add(a);const c=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:15266047,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,35,r),o.scale.set(8,.1,2),o};this.add(c(-12,-6,80)),this.add(c(-12,6,80)),this.add(c(0,0,60)),this.add(c(12,-6,80)),this.add(c(12,6,80));const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:16772829,emissiveIntensity:15}));l.position.set(0,10,-19),l.scale.set(12,8,.1),this.add(l)}},factory:class extends Ph{constructor(){super(),this.name="FactoryEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:6318192,metalness:.1,roughness:.8}),r=new n.Mesh(t,e);r.position.set(0,20,0),r.scale.set(60,44,45),this.add(r);const i=new n.MeshStandardMaterial({color:8028272,roughness:.7,metalness:.05}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(60,.5,45),this.add(s);const o=(t,e)=>{const r=new n.PointLight(15791615,800,55,2);return r.position.set(t,35,e),r};this.add(o(-15,-10)),this.add(o(-15,10)),this.add(o(0,0)),this.add(o(15,-10)),this.add(o(15,10));const a=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:15791615,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,38,r),o.scale.set(6,.1,3),o};this.add(a(-18,-10,90)),this.add(a(-18,10,90)),this.add(a(0,-10,70)),this.add(a(0,10,70)),this.add(a(18,-10,90)),this.add(a(18,10,90));const c=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:11206570,emissiveIntensity:10}));c.position.set(28,14,-21),c.scale.set(1,2,.1),this.add(c);const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:16772829,emissiveIntensity:25}));l.position.set(0,8,-22),l.scale.set(10,10,.1),this.add(l)}},office:class extends Ph{constructor(){super(),this.name="OfficeEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:14209224}),r=new n.Mesh(t,e);r.position.set(0,10,0),r.scale.set(35,22,30),this.add(r);const i=new n.MeshStandardMaterial({color:10524808,roughness:.85}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(35,.5,30),this.add(s);const o=new n.PointLight(16774374,400,30,2);o.position.set(0,17,0),this.add(o);const a=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:16775408,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,19.5,r),o.scale.set(4,.1,4),o};this.add(a(-8,-6,60)),this.add(a(-8,6,60)),this.add(a(8,-6,60)),this.add(a(8,6,60)),this.add(a(0,0,50));const c=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:30}));c.position.set(17,10,0),c.scale.set(.1,6,12),this.add(c);const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:20}));l.position.set(-17,10,0),l.scale.set(.1,4,8),this.add(l)}},home:class extends Ph{constructor(){super(),this.name="HomeEnvironment",this.position.y=-3.5;const t=new n.BoxGeometry;t.deleteAttribute("uv");const e=new n.MeshStandardMaterial({side:n.BackSide,color:15261136}),r=new n.Mesh(t,e);r.position.set(0,8,0),r.scale.set(28,18,24),this.add(r);const i=new n.MeshStandardMaterial({color:11571312,roughness:.7}),s=new n.Mesh(t,i);s.position.set(0,-1.5,0),s.scale.set(28,.5,24),this.add(s);const o=new n.PointLight(16770244,300,25,2);o.position.set(0,14,0),this.add(o);const a=new n.PointLight(16767152,100,20,2);a.position.set(-8,12,-6),this.add(a);const c=(e,r,i)=>{const s=new n.MeshLambertMaterial({color:0,emissive:16771280,emissiveIntensity:i}),o=new n.Mesh(t,s);return o.position.set(e,15.5,r),o.scale.set(3,.1,3),o};this.add(c(0,0,40)),this.add(c(-6,-4,25)),this.add(c(6,4,25));const l=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:35}));l.position.set(13.5,8,0),l.scale.set(.1,8,10),this.add(l);const h=new n.Mesh(t,new n.MeshLambertMaterial({color:0,emissive:14544639,emissiveIntensity:15}));h.position.set(-13.5,9,3),h.scale.set(.1,5,6),this.add(h)}}};class zh{get scene(){return this._scene}get mixer(){return this._mixer}setup(){return this._scene=new _.Scene,this._scene}setupMixer(){return this._timer=new _.Timer,this._timer.connect(document),this._mixer=new _.AnimationMixer(this._scene),this._mixer}setupEnvironment(t){this._renderer=t,this._applyEnvironment("studio")}_applyEnvironment(t){this._envTexture&&this._envTexture.dispose();const e=new(0,Oh[t]),n=new _.PMREMGenerator(this._renderer);this._envTexture=n.fromScene(e).texture,this._scene.environment=this._envTexture,e.dispose(),n.dispose()}setSky(t,e){if(!this._scene||!this._renderer)return;const n=t;n&&n in Oh?(this._applyEnvironment(n),this._scene.background=this._envTexture):this._scene.background="color"===t&&e?new _.Color(e):null}addFloor(t){const e=Dh(t);e&&this._scene.add(e)}updateFloor(t){if(!this._scene)return;const e=this._scene.children.find(t=>"floor"===t.name);e&&(yh(e),this._scene.remove(e)),this.addFloor(t)}addObject(t){this._scene.add(t)}updateAnimation(){this._mixer&&this._timer&&(this._timer.update(),this._mixer.update(this._timer.getDelta()))}destroy(){this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this._scene)),this._envTexture&&(this._envTexture.dispose(),delete this._envTexture),this._scene&&(this._scene.environment=null,yh(this._scene),this._scene.clear()),delete this._scene,delete this._mixer,delete this._renderer,this._timer&&this._timer.disconnect(),delete this._timer}}class Ih{constructor(){this._activeView="perspective",this._cameraZPos=0}get camera(){return this._perspCamera}get activeCamera(){return"perspective"!==this._activeView&&this._orthoCamera?this._orthoCamera:this._perspCamera}get activeView(){return this._activeView}get cameraZPos(){return this._cameraZPos}setup(t,e,n){const{fov:r,near:i,far:s,cameraX:o,cameraY:a,cameraZ:c}=n,l=t/e;this._perspCamera=new _.PerspectiveCamera(r,l,i,s);let h=.4*e,d=.4*t;return this._cameraZPos=Math.min(250,Math.floor(.5*Math.min(t,e))),null!=o&&(h=o*t),null!=a&&(d=a*e),null!=c&&(this._cameraZPos=c*Math.floor(Math.min(t,e))),this._perspCamera.position.set(h,this._cameraZPos,d),this._activeView="perspective",this._perspCamera}addToScene(t){t.add(this._perspCamera),this._perspCamera.lookAt(t.position)}updateAspect(t,e){if(this._perspCamera&&(this._perspCamera.aspect=t/e,this._perspCamera.updateProjectionMatrix()),this._orthoCamera){const n=this._orthoCamera,r=(n.top-n.bottom)/2,i=t/e;n.left=-r*i,n.right=r*i,n.updateProjectionMatrix()}}updateProperties(t){this._perspCamera&&(void 0!==t.fov&&(this._perspCamera.fov=t.fov),void 0!==t.near&&(this._perspCamera.near=t.near),void 0!==t.far&&(this._perspCamera.far=t.far),this._perspCamera.updateProjectionMatrix())}setOrthoView(t,e,n,r,i){this._orthoCamera||(this._orthoCamera=new _.OrthographicCamera(-1,1,1,-1,.1,5e4)),this.updateOrthoFrustum(e,n,r,i);const s=this._orthoCamera;s.zoom=1;const o=2*Math.max(e,n);switch(t){case"top":s.position.set(0,o,0),s.up.set(0,0,-1);break;case"front":s.position.set(0,0,o),s.up.set(0,1,0);break;case"back":s.position.set(0,0,-o),s.up.set(0,1,0);break;case"right":s.position.set(o,0,0),s.up.set(0,1,0);break;case"left":s.position.set(-o,0,0),s.up.set(0,1,0)}return s.lookAt(0,0,0),s.updateProjectionMatrix(),this._activeView=t,s}restorePerspective(){return this._activeView="perspective",this._perspCamera}updateOrthoFrustum(t,e,n,r){if(!this._orthoCamera)return;const i=(n||t)/(r||e),s=Math.max(t,e)/2;i>=1?(this._orthoCamera.left=-s*i,this._orthoCamera.right=s*i,this._orthoCamera.top=s,this._orthoCamera.bottom=-s):(this._orthoCamera.left=-s,this._orthoCamera.right=s,this._orthoCamera.top=s/i,this._orthoCamera.bottom=-s/i),this._orthoCamera.updateProjectionMatrix()}destroy(){delete this._perspCamera,delete this._orthoCamera,this._activeView="perspective"}}class Lh{constructor(){this._noSupportWebgl=!1}get renderer(){return this._renderer}get css3DRenderer(){return this._css3DRenderer||(this._css3DRenderer=this.createCSS3DRenderer()),this._css3DRenderer}get css3DScene(){return this._css3DScene||(this._css3DScene=new _.Scene),this._css3DScene}get composer(){return this._composer}get noSupportWebgl(){return this._noSupportWebgl}get domElement(){return this._renderer?.domElement}get hudScene(){return this._hudScene||(this._hudScene=new _.Scene),this._hudScene}get hudCSS3DScene(){return this._hudCSS3DScene||(this._hudCSS3DScene=new _.Scene),this._hudCSS3DScene}get hudCamera(){return this._hudCamera}setupHUD(t,e){this._hudCamera=new _.OrthographicCamera(-t/2,t/2,e/2,-e/2,.1,1e4),this._hudCamera.position.set(0,5e3,0),this._hudCamera.lookAt(0,0,0),this._hudCSS3DCamera=new _.OrthographicCamera(-t/2,t/2,e/2,-e/2,.1,1e4),this._hudCSS3DCamera.position.set(0,0,1e3),this._hudCSS3DCamera.lookAt(0,0,0),this._hudCSS3DRenderer=new o.CSS3DRenderer,this._hudCSS3DRenderer.setSize(t,e);const n=this._hudCSS3DRenderer.domElement;n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.pointerEvents="none",n.style.zIndex="10";const r=new _.AmbientLight(16777215,3);this.hudScene.add(r);const i=new Float32Array(64).fill(1),s=new _.DataTexture(i,4,4,_.RGBAFormat,_.FloatType);s.mapping=_.EquirectangularReflectionMapping,s.needsUpdate=!0,this.hudScene.environment=s}resizeHUD(t,e){this._hudCamera&&(this._hudCamera.right=t,this._hudCamera.bottom=-e,this._hudCamera.updateProjectionMatrix())}setupWebGL(t,e,n){try{const r=document.createElement("canvas"),i=r.getContext("webgl2");if(!i)return this._noSupportWebgl=!0,!1;const s=new _.WebGLRenderer({canvas:r,context:i,precision:n.precision,alpha:!0,antialias:n.antialias,logarithmicDepthBuffer:!1!==n.postprocessing,premultipliedAlpha:!1});return s.autoClear=!0,s.outputColorSpace=_.SRGBColorSpace,s.toneMapping=_.NoToneMapping,s.toneMappingExposure=n.exposure,s.shadowMap.enabled=!0,s.shadowMap.type=_.PCFShadowMap,s.setClearColor(16777215,1),s.setPixelRatio(window.devicePixelRatio),s.setSize(t,e,!1),r.style.width="100%",r.style.height="100%",this._renderer=s,this._noSupportWebgl=!1,!0}catch(t){return this._noSupportWebgl=!0,!1}}setupCSS3D(t,e){const n=this.css3DRenderer.domElement;n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.pointerEvents="none",e&&n.setAttribute("scene",e),n.style.setProperty("pointer-events","none","important")}createCSS3DRenderer(){return new o.CSS3DRenderer}setupComposer(t,e,n,r,i){const s=new _.WebGLRenderTarget(n,r,{samples:4});this._composer=new c.EffectComposer(this._renderer,s),this._composer.setSize(n,r);const o=new l.RenderPass(t,e);this._composer.addPass(o);const a=new h.OutlinePass(new _.Vector2(n,r),t,e);if(a.visibleEdgeColor.set(15885602),a.hiddenEdgeColor.set(15885602),a.edgeStrength=3,a.edgeThickness=1.5,a.edgeGlow=.5,a.pulsePeriod=0,i){const t=a.render.bind(a);a.render=(e,n,r,s,o)=>{const a=i.visible;i.visible=!1,t(e,n,r,s,o),i.visible=a}}return this._outlinePass=a,this._composer.addPass(a),this._composer.addPass(new u.SMAAPass),this._composer.addPass(new d.OutputPass),this._composer}updateRenderPassCamera(t){this._composer&&this._composer.passes.length>0&&(this._composer.passes[0].camera=t),this._outlinePass&&(this._outlinePass.renderCamera=t),this._camera&&(this._camera=t)}setOutlineObjects(t){this._outlinePass&&(this._outlinePass.selectedObjects=t)}resize(t,e){if(this._renderer?.setSize(t,e,!1),this._css3DRenderer?.setSize(t,e),this._composer?.setSize(t,e),this._hudCSS3DRenderer&&this._hudCSS3DCamera){const n=t/(this._hudCSS3DCamera.right-this._hudCSS3DCamera.left),r=e/(this._hudCSS3DCamera.top-this._hudCSS3DCamera.bottom),i=this._hudCSS3DRenderer.domElement;i.style.transformOrigin="0 0",i.style.transform=`scale(${n}, ${r})`}}setDirectRenderTargets(t,e){this._scene=t,this._camera=e}render(){if(this._composer){if(this._composer.render(),this._renderer){const t=this._renderer.getContext();t.colorMask(!1,!1,!1,!0),t.clearColor(0,0,0,1),t.clear(t.COLOR_BUFFER_BIT),t.colorMask(!0,!0,!0,!0)}}else this._renderer&&this._scene&&this._camera&&this._renderer.render(this._scene,this._camera);this.renderHUD()}renderHUD(){if(!this._renderer||!this._hudScene||!this._hudCamera)return;if(0===this._hudScene.children.length)return;const t=this._renderer.autoClear;this._renderer.autoClear=!1,this._renderer.setRenderTarget(null),this._renderer.clearDepth(),this._renderer.render(this._hudScene,this._hudCamera),this._renderer.autoClear=t}renderCSS3D(t){if(this._css3DRenderer?.render(this.css3DScene,t),this._hudCSS3DRenderer&&this._hudCSS3DCamera&&this._hudCSS3DScene){const t=this._hudCSS3DRenderer.domElement;this._hudCSS3DScene.children.length>0?(t.style.display="",this._hudCSS3DRenderer.render(this._hudCSS3DScene,this._hudCSS3DCamera)):t.style.display="none"}}get hudCSS3DRenderer(){return this._hudCSS3DRenderer}getSize(){const t=new _.Vector2;return this._renderer?.getSize(t),{width:t.x,height:t.y}}destroy(){this._outlinePass=void 0,this._composer?.dispose(),this._renderer?.dispose(),delete this._composer,delete this._renderer,this.disposeHUD()}disposeHUD(){if(this._hudScene){[...this._hudScene.children].forEach(t=>{if(this._hudScene.remove(t),t.geometry&&t.geometry.dispose(),t.material){const e=t.material;e.map&&e.map.dispose(),e.dispose()}}),this._hudScene.environment&&(this._hudScene.environment.dispose(),this._hudScene.environment=null),this._hudScene=void 0}if(this._hudCamera=void 0,this._hudCSS3DScene){[...this._hudCSS3DScene.children].forEach(t=>this._hudCSS3DScene.remove(t)),this._hudCSS3DScene=void 0}this._hudCSS3DRenderer&&(this._hudCSS3DRenderer.domElement.remove(),this._hudCSS3DRenderer=void 0),this._hudCSS3DCamera=void 0}disposeCSS3DScene(){if(this._css3DScene){[...this._css3DScene.children].forEach(t=>this._css3DScene.remove(t))}}}class jh{constructor(){this.lights=[]}get hemiLight(){return this._hemiLight}get dirLight(){return this._dirLight}setup(t,e,n){this._scene=t,this._camera=e;const{hemisphere:r,directional:i,point:s}=n;if(this._hemiLight=new _.HemisphereLight(r.skyColor,r.groundColor,r.intensity),t.add(this._hemiLight),this.lights.push(this._hemiLight),i){if(this._dirLight=new _.DirectionalLight(i.color,i.intensity),i.position&&this._dirLight.position.set(...i.position),!1!==i.castShadow){this._dirLight.castShadow=!0;const t=i.shadowMapSize??2048;this._dirLight.shadow.mapSize.set(t,t),this._dirLight.shadow.bias=i.shadowBias??-5e-4;const e=this._dirLight.shadow.camera;e.near=.1,e.far=5e3,e.left=-1500,e.right=1500,e.top=1500,e.bottom=-1500}i.attachToCamera?e.add(this._dirLight):t.add(this._dirLight),this.lights.push(this._dirLight)}if(s){const e=new _.PointLight(s.color,s.intensity,void 0,s.decay);e.power=s.power,e.castShadow=s.castShadow,e.position.set(...s.position),e.shadow.camera.near=s.shadowNear,e.shadow.camera.far=s.shadowFar,t.add(e),this.lights.push(e)}}updateHemisphere(t){this._hemiLight&&(void 0!==t.skyColor&&this._hemiLight.color.set(t.skyColor),void 0!==t.groundColor&&this._hemiLight.groundColor.set(t.groundColor),void 0!==t.intensity&&(this._hemiLight.intensity=t.intensity))}updateDirectional(t){this._dirLight&&(void 0!==t.color&&this._dirLight.color.set(t.color),void 0!==t.intensity&&(this._dirLight.intensity=t.intensity))}setDirectionalEnabled(t,e){if(t&&!this._dirLight&&this._camera){const t=e?.color??16777215,n=e?.intensity??.8;this._dirLight=new _.DirectionalLight(t,n),this._camera.add(this._dirLight),this.lights.push(this._dirLight)}else!t&&this._dirLight&&(this._dirLight.removeFromParent(),this._dirLight.dispose(),this.lights=this.lights.filter(t=>t!==this._dirLight),this._dirLight=void 0)}destroy(){this.lights.forEach(t=>t.dispose()),this.lights=[],this._hemiLight=void 0,this._dirLight=void 0,this._scene=void 0,this._camera=void 0}}const Rh=1e-6;class Fh{constructor(){this._enabled=!0,this._state=0,this._autoRotate=!1,this._autoRotateSpeed=2,this._dampingFactor=.15,this._rotateSpeed=.1,this._panSpeed=1,this._lastScale=1,this._spherical=new _.Spherical,this._sphericalDelta=new _.Spherical,this._panOffset=new _.Vector3,this._target=new _.Vector3,this._target0=new _.Vector3,this._position0=new _.Vector3,this._rotateStart=new _.Vector2,this._rotateEnd=new _.Vector2,this._rotateDelta=new _.Vector2,this._panStart=new _.Vector2,this._panEnd=new _.Vector2,this._panDelta=new _.Vector2,this._offset=new _.Vector3,this._lastPosition=new _.Vector3,this._lastQuaternion=new _.Quaternion,this._panLeftV=new _.Vector3,this._panUpV=new _.Vector3,this._panCalcOffset=new _.Vector3}get isActive(){return!!this._camera}get target(){return this._target.clone()}restoreTarget(t){this._target.copy(t),this.update()}get _isOrthoLocked(){return!!this._camera?.isOrthographicCamera}setup(t,e){this._camera=t,this._host=e,this._target.set(0,0,0),this._target0.copy(this._target),this._position0.copy(t.position),this._quat=(new _.Quaternion).setFromUnitVectors(t.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert();const n=e.state;this._autoRotate=!e.app?.isEditMode&&(n.autoRotate||"orbit"===n.cameraAutoPlay)||!1,this._autoRotateSpeed=n.rotationSpeed||2,this.update()}setEnabled(t){this._enabled=t}setOnUserInteraction(t){this._onUserInteraction=t}onDragStart(t){this._enabled&&(this._onUserInteraction?.(),this._isOrthoLocked?(this._state=2,this._panStart.set(t.offsetX,t.offsetY)):(this._state=t.altKey?2:1,1===this._state?this._rotateStart.set(t.offsetX,t.offsetY):this._panStart.set(t.offsetX,t.offsetY)))}onDragMove(t){this._enabled&&(this._isOrthoLocked?(this._state=2,this._handlePanMove(t.offsetX,t.offsetY)):(this._state=t.altKey?2:1,1===this._state?this._handleRotateMove(t.offsetX,t.offsetY):this._handlePanMove(t.offsetX,t.offsetY)))}onDragEnd(t){this._state=0,this._host?.invalidate()}onTouchStart(t){this._onUserInteraction?.();const e=t.touches[0],n=e.offsetX??e.pageX,r=e.offsetY??e.pageY;if(this._isOrthoLocked)return this._panStart.set(n,r),void(this._state=4);switch(t.touches.length){case 1:this._rotateStart.set(n,r),this._state=3;break;case 2:this._lastScale=t.scale||1,this._panStart.set(n,r),this._state=4;break;default:this._state=0}}onTouchMove(t){const e=t.touches[0],n=e.offsetX??e.pageX,r=e.offsetY??e.pageY;if(this._isOrthoLocked)this._handlePanMove(n,r);else switch(t.touches.length){case 1:if(3!==this._state)return;this._handleRotateMove(n,r);break;case 2:if(Math.abs(this._lastScale-(t.scale||1))>.05)return;if(4!==this._state)return;this._handlePanMove(n,r);break;default:this._state=0}}onTouchEnd(t){this._lastScale=1,this._state=0}onKeyDown(t){switch(t.code){case"ArrowUp":this._pan(0,7);break;case"ArrowDown":this._pan(0,-7);break;case"ArrowLeft":this._pan(7,0);break;case"ArrowRight":this._pan(-7,0);break;default:return}this.update()}update(){const t=this._camera,e=t.position;if(this._isOrthoLocked)return this._panOffset.lengthSq()>0&&(this._target.add(this._panOffset),e.add(this._panOffset),this._panOffset.set(0,0,0)),(this._lastPosition.distanceToSquared(e)>Rh||8*(1-this._lastQuaternion.dot(t.quaternion))>Rh)&&(this._lastPosition.copy(e),this._lastQuaternion.copy(t.quaternion),this._host?.invalidate(),!0);if(this._offset.copy(e).sub(this._target),this._offset.applyQuaternion(this._quat),this._spherical.setFromVector3(this._offset),this._spherical.theta+=this._sphericalDelta.theta,this._autoRotate&&0===this._state){const t=2*Math.PI/60*(this._autoRotateSpeed/60);this._spherical.theta-=t}this._spherical.phi+=this._sphericalDelta.phi,this._spherical.phi=Math.max(0,Math.min(Math.PI,this._spherical.phi)),this._spherical.makeSafe(),this._target.add(this._panOffset),this._offset.setFromSpherical(this._spherical),this._offset.applyQuaternion(this._quatInverse),e.copy(this._target).add(this._offset),t.lookAt(this._target);const n=1-this._dampingFactor;return this._sphericalDelta.theta*=n,this._sphericalDelta.phi*=n,this._panOffset.set(0,0,0),(this._lastPosition.distanceToSquared(e)>Rh||8*(1-this._lastQuaternion.dot(t.quaternion))>Rh)&&(this._lastPosition.copy(e),this._lastQuaternion.copy(t.quaternion),this._host?.invalidate(),!0)}reset(){this._target.copy(this._target0),this._camera.position.copy(this._position0),this._camera.updateProjectionMatrix(),this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0),this._state=0,this.update()}pinResetPosition(){this._camera&&(this._position0.copy(this._camera.position),this._target0.copy(this._target))}setCamera(t){this._camera=t,this._target.set(0,0,0),this._position0.copy(t.position),this._quat=(new _.Quaternion).setFromUnitVectors(t.up,new _.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0),this._lastPosition.copy(t.position),this._lastQuaternion.copy(t.quaternion),this._state=0,t.updateMatrixWorld(!0)}isAutoRotating(){return this._autoRotate}setAutoRotate(t){this._autoRotate=t,this._host?.invalidate()}markCameraChanged(){this._host?.invalidate()}dollyAtCursor(t,e,n){this._onUserInteraction?.();const r=this._camera,i=r.position.distanceTo(this._target),s=Math.max(1,Math.min(5e4,i*t));if(Math.abs(s-i)<Rh)return;const o=Math.tan(r.fov/2*Math.PI/180)/r.zoom,a=i-s,c=e*a*o*r.aspect,l=n*a*o;this._panLeftV.setFromMatrixColumn(r.matrix,0).multiplyScalar(c),this._panUpV.setFromMatrixColumn(r.matrix,1).multiplyScalar(l),this._target.add(this._panLeftV).add(this._panUpV),r.position.add(this._panLeftV).add(this._panUpV),this._panCalcOffset.subVectors(r.position,this._target).normalize().multiplyScalar(s),r.position.copy(this._target).add(this._panCalcOffset),this._host?.invalidate()}zoomOrthoAtCursor(t,e,n){this._onUserInteraction?.();const r=this._camera,i=r.zoom,s=Math.max(.1,Math.min(20,i*t)),o=e*(r.right-r.left)/2*(1/i-1/s),a=n*(r.top-r.bottom)/2*(1/i-1/s);this._panLeftV.setFromMatrixColumn(r.matrix,0).multiplyScalar(o),this._panUpV.setFromMatrixColumn(r.matrix,1).multiplyScalar(a),this._target.add(this._panLeftV).add(this._panUpV),r.position.add(this._panLeftV).add(this._panUpV),r.zoom=s,r.updateProjectionMatrix(),this._host?.invalidate()}destroy(){delete this._camera,delete this._host}_getViewportSize(){const t=this._host?.element;if(t){const e=t.getBoundingClientRect();if(e.width>0&&e.height>0)return{width:e.width,height:e.height}}const{width:e,height:n}=this._host.bounds;return{width:Math.abs(e)||1,height:Math.abs(n)||1}}_handleRotateMove(t,e){this._rotateEnd.set(t,e),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart);const{width:n,height:r}=this._getViewportSize();this._sphericalDelta.theta-=2*Math.PI*this._rotateDelta.x/n*this._rotateSpeed,this._sphericalDelta.phi-=2*Math.PI*this._rotateDelta.y/r*this._rotateSpeed,this._rotateStart.copy(this._rotateEnd),this._host?.invalidate()}_handlePanMove(t,e){this._panEnd.set(t,e),this._panDelta.subVectors(this._panEnd,this._panStart),this._isOrthoLocked?this._panOrtho(this._panDelta.x,this._panDelta.y):this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this._host?.invalidate()}_panOrtho(t,e){const n=this._camera,{width:r,height:i}=this._getViewportSize();this._panLeftV.setFromMatrixColumn(n.matrix,0),this._panLeftV.multiplyScalar(-t*(n.right-n.left)/n.zoom/r),this._panUpV.setFromMatrixColumn(n.matrix,1),this._panUpV.multiplyScalar(e*(n.top-n.bottom)/n.zoom/i),this._target.add(this._panLeftV).add(this._panUpV),n.position.add(this._panLeftV).add(this._panUpV)}_pan(t,e){t*=this._panSpeed,e*=this._panSpeed;const{width:n,height:r}=this._getViewportSize(),i=this._camera;if(i.isPerspectiveCamera){this._panCalcOffset.copy(i.position).sub(this._target);let n=this._panCalcOffset.length();n*=Math.tan(i.fov/2*Math.PI/180),this._panLeftV.setFromMatrixColumn(i.matrix,0),this._panLeftV.multiplyScalar(-2*t*n/r),this._panOffset.add(this._panLeftV),this._panUpV.setFromMatrixColumn(i.matrix,1),this._panUpV.multiplyScalar(2*e*n/r),this._panOffset.add(this._panUpV)}else i.isOrthographicCamera&&(this._panLeftV.setFromMatrixColumn(i.matrix,0),this._panLeftV.multiplyScalar(-t*(i.right-i.left)/i.zoom/n),this._panOffset.add(this._panLeftV),this._panUpV.setFromMatrixColumn(i.matrix,1),this._panUpV.multiplyScalar(e*(i.top-i.bottom)/i.zoom/r),this._panOffset.add(this._panUpV))}}class Bh{constructor(){this._mouse=new _.Vector2,this._raycaster=new _.Raycaster}get mouse(){return this._mouse}get lastFocused(){return this._lastFocused}set lastFocused(t){this._lastFocused=t}get lastHovered(){return this._lastHovered}set lastHovered(t){this._lastHovered=t}updateMouseNDC(t,e,n,r,i,s){this._mouse.x=(t-n)/i*2-1,this._mouse.y=-(e-r)/s*2+1}getObjectByRaycast(t,e){const n=this.getObjectsByRaycast(t,e);if(n&&n.length>0)for(const t of n){if(!this._isWorldVisible(t.object))continue;let e=t.object;for(;e;){if(e.userData.context)return e;e=e.parent}}}_isWorldVisible(t){let e=t;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}getObjectsByRaycast(t,e){return this._raycaster.setFromCamera(this._mouse,t),this._raycaster.intersectObjects(e.children,!0)}setHUD(t,e){this._hudScene=t,this._hudCamera=e}handleClick(t,e,n){let r;this._lastFocused&&(this._lastFocused.focused=!1),this._hudScene&&this._hudCamera&&(r=this.getObjectByRaycast(this._hudCamera,this._hudScene)),r||(r=this.getObjectByRaycast(t,e));const i=r?.userData.context;return i&&(i.focused=!0,this._lastFocused=i,i.component?.trigger("click",n)),i}handleHover(t,e,n){let r;this._hudScene&&this._hudCamera&&(r=this.getObjectByRaycast(this._hudCamera,this._hudScene)),r||(r=this.getObjectByRaycast(t,e));const i=r?.userData.context;i!==this._lastHovered&&(this._lastHovered&&(this._lastHovered.component?.trigger("mouseleave",n),this._lastHovered=void 0),i&&(this._lastHovered=i,this._lastHovered.component?.trigger("mouseenter",n)))}destroy(){this._lastFocused=void 0,this._lastHovered=void 0,this._hudScene=void 0,this._hudCamera=void 0}}class Nh{constructor(){this._mode="translate",this._isDragging=!1}get controls(){return this._controls}get mode(){return this._mode}get attached(){return this._attached}get isAttached(){return!!this._attached}get isDragging(){return this._isDragging}setup(t,e,n){this.destroy(),this._scene=n;const r=document.createElement("div");r.style.cssText="position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none",r.setPointerCapture=()=>{},r.releasePointerCapture=()=>{},e.appendChild(r),this._proxyElement=r,this._controls=new p.TransformControls(t,r),this._controls.setMode(this._mode),n.add(this._controls.getHelper()),this._controls.addEventListener("dragging-changed",t=>{this._isDragging=t.value,this.onDraggingChanged?.(t.value)}),this._controls.addEventListener("change",()=>{this._attached&&this.onObjectChange?.(this._attached)})}forwardEvent(t,e){if(!this._proxyElement||!this._controls)return;const n=new PointerEvent(e,{clientX:t.clientX,clientY:t.clientY,button:"pointermove"===e?-1:t.button??0,pointerId:1,pointerType:"mouse",bubbles:!0});this._proxyElement.dispatchEvent(n)}setMode(t){this._mode=t,this._controls?.setMode(t)}attach(t){this._attached=t,this._controls?.attach(t),this._controls?.getHelper().updateMatrixWorld(!0),this.onAttachChanged?.(!0)}detach(){this._controls?.detach(),this._attached=void 0,this.onAttachChanged?.(!1)}updateCamera(t){this._controls&&(this._controls.camera=t)}destroy(){this._controls&&(this._controls.detach(),this._controls.dispose(),this._scene&&this._scene.remove(this._controls.getHelper()),this._controls=void 0),this._proxyElement?.parentNode&&this._proxyElement.parentNode.removeChild(this._proxyElement),this._proxyElement=void 0,this._attached=void 0,this._isDragging=!1}}class Hh{constructor(){this._mouseDownAltKey=!1}captureAltKey(t){this._mouseDownAltKey=t}setupCallbacks(t,e,n,r){t.onDraggingChanged=i=>{e.setEnabled(!i);const s=n();s&&(r?.onDraggingChanged?.(i),i?this._onDragStart(t,s):this._onDragEnd(t,s),s.app?.commander?.execute(null),s.invalidate())},t.onObjectChange=e=>{this._syncFromGizmo(t,e),n()?.invalidate()},t.onAttachChanged=t=>{r?.onAttachChanged?.(t)}}_onDragStart(t,e){this._mouseDownAltKey&&"translate"===t.mode&&this._performAltDragDuplicate(e);const n=e.root?.selected||[];n.length>1&&this._captureMultiSelectState(t,n),"scale"===t.mode&&this._captureScalePreDrag(t)}_performAltDragDuplicate(t){const e=t.root?.selected||[];if(0===e.length||!t.root)return;const n=t.root,r=[];for(const t of e){const e=t.parent,i=new Map,s=Zc(t,t=>{const e=n.getNewRefid();return void 0!==t&&i.set(t,e),e});s.replaceRefids(i),e.addComponent(s),r.push({component:s,to_container:e})}this._altDragDuplicates=r}_captureMultiSelectState(t,e){const n=t.attached;if(n)if("translate"===t.mode){const t=new Map,r=n.position;for(let n=1;n<e.length;n++){const i=e[n]._realObject;i?.object3d&&i.gizmoTransformable&&t.set(i,i.object3d.position.clone().sub(r))}this._multiSelectOffsets=t}else if("rotate"===t.mode){this._gizmoInitialRotation=n.rotation.clone();const t=new Map;for(let n=1;n<e.length;n++){const r=e[n]._realObject;r?.object3d&&r.gizmoTransformable&&t.set(r,r.object3d.rotation.clone())}this._multiSelectInitialRotations=t}else if("scale"===t.mode){const t=new Map;for(let n=1;n<e.length;n++){const r=e[n],i=r._realObject;if(i?.object3d&&i.gizmoTransformable){const{left:e,top:n,width:s,height:o}=r.bounds,{zPos:a=0}=r.state,c=r.state.depth;t.set(i,{left:e,top:n,width:s,height:o,depth:c,zPos:a,scaleX:i.object3d.scale.x,scaleY:i.object3d.scale.y,scaleZ:i.object3d.scale.z})}}this._multiSelectPreDragDimensions=t}}_captureScalePreDrag(t){const e=t.attached,n=e?.userData.context;if(!n||!e)return;const{left:r,top:i,width:s,height:o}=n.component.bounds,{zPos:a=0}=n.component.state,c=n.component.state.depth;this._preDragDimension={left:r,top:i,width:s,height:o,depth:c,zPos:a},this._preDragScale={x:e.scale.x,y:e.scale.y,z:e.scale.z},this._preDragEffectiveDepth=void 0===c?n.effectiveDepth:void 0}_onDragEnd(t,e){if(this._altDragDuplicates&&this._altDragDuplicates.length>0&&(e.app?.commander.execute(new Xc({changes:this._altDragDuplicates})),this._altDragDuplicates=void 0),this._multiSelectOffsets=void 0,this._gizmoInitialRotation=void 0,this._multiSelectInitialRotations=void 0,this._preDragDimension){const e=t.attached,n=e?.userData.context;if(n&&(void 0!==this._preDragEffectiveDepth&&n.applyDimensionFromGizmo({depth:this._preDragEffectiveDepth}),n.update()),this._multiSelectPreDragDimensions)for(const[t]of this._multiSelectPreDragDimensions)t.update()}const n=e.root?.selected||[];for(const e of n){const n=e._realObject;n?.onGizmoDragEnd(t.mode)}this._preDragDimension=void 0,this._preDragScale=void 0,this._preDragEffectiveDepth=void 0,this._multiSelectPreDragDimensions=void 0}_syncFromGizmo(t,e){const n=e.userData.context;if(n)if("scale"===t.mode&&this._preDragDimension&&this._preDragScale){if(this._syncDimensionFromGizmo(n,e),this._multiSelectPreDragDimensions&&this._preDragScale){const t=e.scale.x/this._preDragScale.x,n=e.scale.y/this._preDragScale.y,r=e.scale.z/this._preDragScale.z;for(const[e,i]of this._multiSelectPreDragDimensions){const s=i.width*t,o=i.height*r,a={left:i.left+(i.width-s)/2,top:i.top+(i.height-o)/2,width:s,height:o};if(void 0!==i.depth){const t=i.depth*n;a.depth=t,a.zPos=i.zPos+(i.depth-t)/2}e.applyDimensionFromGizmo(a)}}}else{if(n.syncFromObject3D(),"translate"===t.mode&&this._applyGroundSnap(e,n),this._multiSelectOffsets){const n=e.position;for(const[e,r]of this._multiSelectOffsets)e.object3d&&(e.object3d.position.copy(n).add(r),"translate"===t.mode&&this._applyGroundSnap(e.object3d,e),e.syncFromObject3D())}if(this._multiSelectInitialRotations&&this._gizmoInitialRotation){const t=e.rotation.x-this._gizmoInitialRotation.x,n=e.rotation.y-this._gizmoInitialRotation.y,r=e.rotation.z-this._gizmoInitialRotation.z;for(const[e,i]of this._multiSelectInitialRotations)e.object3d&&(e.object3d.rotation.set(i.x+t,i.y+n,i.z+r),e.syncFromObject3D())}}}_applyGroundSnap(t,e){const n=e.effectiveDepth/2,r=t.position.y-n,i=Math.abs(r);if(i<2)t.position.y=n,e.syncFromObject3D();else if(i<10){const s=(i-2)/8,o=1-s*s;t.position.y=n+r*(1-o),e.syncFromObject3D()}}_syncDimensionFromGizmo(t,e){const n=this._preDragDimension,r=this._preDragScale,i=n.width*(e.scale.x/r.x),s=n.height*(e.scale.z/r.z),o={left:n.left+(n.width-i)/2,top:n.top+(n.height-s)/2,width:i,height:s};if(void 0!==n.depth){const t=n.depth*(e.scale.y/r.y);o.depth=t,o.zPos=n.zPos+(n.depth-t)/2}t.applyDimensionFromGizmo(o)}}class Vh{constructor(){this._mouseIsDown=!1,this._isDragging=!1,this._mouseDownPos={x:0,y:0}}get hostElement(){return this._hostElement}setup(t,e,n){this.cleanup(),this._hostElement=t,this._gizmo=e.gizmo,this._controls=e.controls,this._camera=e.camera,this._scene=e.scene,this._event=e.event,this._delegate=n,t.hasAttribute("tabindex")||t.setAttribute("tabindex","0"),t.style.outline="none";const r={mousedown:t=>this._onMouseDown(t),mousemove:t=>this._onMouseMove(t),wheel:t=>{t.stopPropagation(),this._delegate.handleWheel(t)},dblclick:t=>{t.stopPropagation(),this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleDblClick(t)},contextmenu:t=>{t.preventDefault()},touchstart:t=>{t.stopPropagation(),this._delegate.handleTouchStart(t)},touchmove:t=>{t.stopPropagation(),this._delegate.handleTouchMove(t)},touchend:t=>{t.stopPropagation(),this._delegate.handleTouchEnd(t)},keydown:t=>{this._delegate.handleKeyDown(t)&&t.stopPropagation()},keyup:t=>{(this._delegate.handleKeyUp?.(t)??!1)&&t.stopPropagation()}};t.addEventListener("mousedown",r.mousedown),t.addEventListener("mousemove",r.mousemove),t.addEventListener("wheel",r.wheel),t.addEventListener("dblclick",r.dblclick),t.addEventListener("contextmenu",r.contextmenu),t.addEventListener("touchstart",r.touchstart,{passive:!1}),t.addEventListener("touchmove",r.touchmove,{passive:!1}),t.addEventListener("touchend",r.touchend),t.addEventListener("keydown",r.keydown),t.addEventListener("keyup",r.keyup),this._boundHandlers=r}cleanup(){this._removeDocCapture();const t=this._hostElement,e=this._boundHandlers;t&&e&&(t.removeEventListener("mousedown",e.mousedown),t.removeEventListener("mousemove",e.mousemove),t.removeEventListener("wheel",e.wheel),t.removeEventListener("dblclick",e.dblclick),t.removeEventListener("contextmenu",e.contextmenu),t.removeEventListener("touchstart",e.touchstart),t.removeEventListener("touchmove",e.touchmove),t.removeEventListener("touchend",e.touchend),t.removeEventListener("keydown",e.keydown),t.removeEventListener("keyup",e.keyup),t.removeAttribute("tabindex"),t.style.outline=""),this._boundHandlers=void 0,this._hostElement=void 0,this._mouseIsDown=!1,this._isDragging=!1}forceCleanupDragState(){this._removeDocCapture(),this._mouseIsDown=!1,this._isDragging=!1}clientToElementCoords(t,e){const n=this._hostElement;if(!n)return{x:t,y:e};const r=n.getBoundingClientRect();return{x:t-r.left,y:e-r.top}}updateMouseNDCFromClient(t,e){const n=this._hostElement?.getBoundingClientRect();if(!n||0===n.width||0===n.height)return;const r=t-n.left,i=e-n.top;this._event.updateMouseNDC(r,i,0,0,n.width,n.height)}_onMouseDown(t){if(t.stopPropagation(),this._hostElement.focus(),this._delegate.isPlacementMode())return void this._delegate.handlePlacementClick(t);if(this._delegate.isSpacePanning?.()??!1)return this._mouseIsDown=!0,this._isDragging=!1,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{t.stopPropagation();const e=t.clientX-this._mouseDownPos.x,n=t.clientY-this._mouseDownPos.y;if(!this._isDragging){if(e*e+n*n<Vh.DRAG_THRESHOLD)return;this._isDragging=!0;const t=this.clientToElementCoords(this._mouseDownPos.x,this._mouseDownPos.y);this._controls.onDragStart({offsetX:t.x,offsetY:t.y,altKey:!0})}const r=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragMove({offsetX:r.x,offsetY:r.y,altKey:!0})},this._docUpHandler=t=>{if(t.stopPropagation(),this._removeDocCapture(),this._isDragging){const e=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragEnd({offsetX:e.x,offsetY:e.y})}this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),void document.addEventListener("mouseup",this._docUpHandler,!0);if(t.shiftKey&&!t.altKey&&!t.metaKey&&!t.ctrlKey){const e=this.clientToElementCoords(t.clientX,t.clientY);return this._mouseIsDown=!0,this._isDragging=!1,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{t.stopPropagation();const n=t.clientX-this._mouseDownPos.x,r=t.clientY-this._mouseDownPos.y;if(!this._isDragging){if(n*n+r*r<Vh.DRAG_THRESHOLD)return;this._isDragging=!0,this._delegate.handleBoxSelectionStart?.(e.x,e.y)}const i=this.clientToElementCoords(t.clientX,t.clientY);this._delegate.handleBoxSelectionUpdate?.(i.x,i.y)},this._docUpHandler=t=>{if(t.stopPropagation(),this._removeDocCapture(),this._isDragging)this._delegate.handleBoxSelectionEnd?.(t.shiftKey);else{const e=this.clientToElementCoords(t.clientX,t.clientY);this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleClickAt(e.x,e.y,t)}this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),void document.addEventListener("mouseup",this._docUpHandler,!0)}if(this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.tryVertexDragStart?.(t))return this._mouseIsDown=!0,this._isDragging=!0,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{t.stopPropagation(),this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleVertexDragMove?.(t)},this._docUpHandler=t=>{t.stopPropagation(),this._removeDocCapture(),this._delegate.handleVertexDragEnd?.(t),this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),void document.addEventListener("mouseup",this._docUpHandler,!0);this._delegate.captureMouseDownAltKey(t.altKey),this._gizmo.forwardEvent(t,"pointermove"),this._gizmo.forwardEvent(t,"pointerdown");let e=this._gizmo.isDragging;!e&&t.altKey&&this._delegate.tryAltClickSelect(t)&&(this._gizmo.forwardEvent(t,"pointermove"),this._gizmo.forwardEvent(t,"pointerdown"),e=this._gizmo.isDragging),this._mouseIsDown=!0,this._isDragging=!1,this._mouseDownPos={x:t.clientX,y:t.clientY},this._docMoveHandler=t=>{if(t.stopPropagation(),e)return void this._gizmo.forwardEvent(t,"pointermove");const n=t.clientX-this._mouseDownPos.x,r=t.clientY-this._mouseDownPos.y;if(!this._isDragging){if(n*n+r*r<Vh.DRAG_THRESHOLD)return;this._isDragging=!0;const e=this.clientToElementCoords(this._mouseDownPos.x,this._mouseDownPos.y);this._controls.onDragStart({offsetX:e.x,offsetY:e.y,altKey:t.altKey})}const i=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragMove({offsetX:i.x,offsetY:i.y,altKey:t.altKey})},this._docUpHandler=t=>{if(t.stopPropagation(),this._removeDocCapture(),e)return this._gizmo.forwardEvent(t,"pointerup"),this._mouseIsDown=!1,void(this._isDragging=!1);if(this._isDragging){const e=this.clientToElementCoords(t.clientX,t.clientY);this._controls.onDragEnd({offsetX:e.x,offsetY:e.y})}else{const e=this.clientToElementCoords(t.clientX,t.clientY);this.updateMouseNDCFromClient(t.clientX,t.clientY),this._delegate.handleClickAt(e.x,e.y,t)}this._mouseIsDown=!1,this._isDragging=!1},document.addEventListener("mousemove",this._docMoveHandler,!0),document.addEventListener("mouseup",this._docUpHandler,!0)}_onMouseMove(t){if(t.stopPropagation(),this._mouseIsDown)return;if(this._delegate.isPlacementMode())return void this._delegate.handlePlacementHover(t);this.updateMouseNDCFromClient(t.clientX,t.clientY);const e=this._camera.activeCamera;e&&this._scene.scene&&this._event.handleHover(e,this._scene.scene,t),this._gizmo.forwardEvent(t,"pointermove")}_removeDocCapture(){this._docMoveHandler&&(document.removeEventListener("mousemove",this._docMoveHandler,!0),this._docMoveHandler=void 0),this._docUpHandler&&(document.removeEventListener("mouseup",this._docUpHandler,!0),this._docUpHandler=void 0)}}Vh.DRAG_THRESHOLD=16;class Gh{constructor(){this._groundPlane=new _.Plane(new _.Vector3(0,1,0),0)}get isActive(){return!!this._pendingModels}get pendingModels(){return this._pendingModels}setup(t,e){this._camera=t.camera,this._event=t.event,this._scene=t.scene,this._delegate=e}start(t){this._pendingModels=t}stop(){this._pendingModels=void 0,this._removeIndicator()}destroy(){this._removeIndicator(),this._pendingModels=void 0}raycastGroundPlane(t){this._delegate.updateMouseNDCFromClient(t.clientX,t.clientY);const e=this._camera.activeCamera;if(!e)return null;e.updateMatrixWorld(!0);const n=new _.Raycaster;n.setFromCamera(this._event.mouse,e);const r=new _.Vector3;return n.ray.intersectPlane(this._groundPlane,r)}updateIndicator(t){if(!t)return void(this._placementIndicator&&(this._placementIndicator.visible=!1));if(!this._placementIndicator){const t=this._scene?.scene;if(!t)return;const e=new _.RingGeometry(.8,1,32);e.rotateX(-Math.PI/2);const n=new _.MeshBasicMaterial({color:48340,opacity:.6,transparent:!0,side:_.DoubleSide,depthTest:!1});this._placementIndicator=new _.Mesh(e,n),this._placementIndicator.renderOrder=999,t.add(this._placementIndicator)}const e=this._pendingModels?.[0],n=e?.rx??e?.width??50,r=e?.ry??e?.height??50;this._placementIndicator.scale.set(n,1,r),this._placementIndicator.position.copy(t),this._placementIndicator.position.y=1,this._placementIndicator.visible=!0}_removeIndicator(){if(this._placementIndicator){const t=this._placementIndicator;this._scene?.scene?.remove(t),t.geometry.dispose(),t.material.dispose(),this._placementIndicator=void 0}}}const Yh={linear:t=>t,"ease-in":t=>t*t,"ease-out":t=>1-(1-t)*(1-t),"ease-in-out":t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2};function Uh(t,e,n,r,i,s=new _.Vector3){const o=t*t,a=o*t;return s.set(.5*(2*n.x+(-e.x+r.x)*t+(2*e.x-5*n.x+4*r.x-i.x)*o+(-e.x+3*n.x-3*r.x+i.x)*a),.5*(2*n.y+(-e.y+r.y)*t+(2*e.y-5*n.y+4*r.y-i.y)*o+(-e.y+3*n.y-3*r.y+i.y)*a),.5*(2*n.z+(-e.z+r.z)*t+(2*e.z-5*n.z+4*r.z-i.z)*o+(-e.z+3*n.z-3*r.z+i.z)*a))}class $h{constructor(){this._slots=new Array(10),this._animating=!1,this._animationProgress=0,this._playStartOffset=0,this._lastPlayProgress=-1,this._playIndex=-1,this._playing=!1,this._orbitRotating=!1,this._orbitPaused=!1}get isAnimating(){return this._animating}get isPlaying(){return this._playing}get isOrbitRotating(){return this._orbitRotating}get isOrbitPaused(){return this._orbitPaused}get playIndex(){return this._playIndex}get lastPlayProgress(){return this._lastPlayProgress}get playProgress(){if(!this._playing||this._playIndex<0)return 0;const t=this.getPlayableSlots().length;if(t<2)return 0;const e=(this._playIndex-1+t)%t;let n=this._animating?this._animationProgress:1;return this._playStartOffset>0&&(n=this._playStartOffset+n*(1-this._playStartOffset)),(e+n)%t/t}setCallbacks(t,e){this._onInvalidate=t,this._onAnimationComplete=e}saveSlot(t,e){if(t<0||t>9)return;const n=this._slots[t];this._slots[t]={...e,name:"name"in e?e.name:n?.name}}renameSlot(t,e){if(t<0||t>9)return;const n=this._slots[t];n&&(n.name=e||void 0)}clearSlot(t){t<0||t>9||(this._slots[t]=void 0)}getSlot(t){return this._slots[t]}exportSlots(){return this._slots.map(t=>t?{...t}:null)}importSlots(t){if(Array.isArray(t))for(let e=0;e<10;e++){const n=t[e];this._slots[e]=n?{...n}:void 0}}resetAll(){this._slots=new Array(10)}getPlayableSlots(){return this._slots.map((t,e)=>t&&!t.excludeFromPlay?e:-1).filter(t=>t>=0)}swapSlots(t,e){if(t<0||t>9||e<0||e>9||t===e)return;const n=this._slots[t];this._slots[t]=this._slots[e],this._slots[e]=n}moveSlot(t,e){if(t<1||t>9||e<1||e>9||t===e)return;const n=this._slots[t];this._slots.splice(t,1),this._slots.splice(e,0,n)}animateToSlot(t,e,n,r=800,i){const s=this._slots[t];if(!s)return!1;this.stopAnimation(),this._animating=!0,this._animationProgress=0;const o=e.position.clone(),a=n.target.clone(),c=new _.Vector3(s.position.x,s.position.y,s.position.z),l=new _.Vector3(s.target.x,s.target.y,s.target.z),h=.01,d=Math.max(o.distanceTo(a),h),u=Math.max(c.distanceTo(l),h),p=(new _.Vector3).subVectors(a,o),f=(new _.Vector3).subVectors(l,c),g=p.lengthSq()>1e-4?p.normalize():new _.Vector3(0,0,-1).applyQuaternion(e.quaternion),m=f.lengthSq()>1e-4?f.normalize():g.clone(),y=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),g),b=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),m),v=Yh[s.easing??"ease-in-out"];return this._runAnimation(r,v,t=>{i?Uh(t,i.prevPos,o,c,i.nextPos,e.position):e.position.lerpVectors(o,c,t);const r=y.clone().slerp(b,t),s=new _.Vector3(0,0,-1).applyQuaternion(r),a=d+(u-d)*t,l=e.position.clone().add(s.multiplyScalar(a));n.restoreTarget(l)}),!0}_animatePathSegment(t,e,n,r,i,s){const o=Yh[r];this._runAnimation(n,o,n=>{const r=t+(e-t)*n,o=this.evaluatePath(r<=1?r:r-1);o&&(i.position.copy(o.position),s.restoreTarget(o.target))})}_runAnimation(t,e,n){this.stopAnimation(),this._animating=!0,this._animationProgress=0;const r=performance.now(),i=()=>{const s=performance.now()-r,o=Math.min(s/t,1),a=e(o);this._animationProgress=a,n(a),this._onInvalidate?.(),o<1?this._animationId=requestAnimationFrame(i):(this._animating=!1,this._animationId=void 0,this._onAnimationComplete?.())};this._animationId=requestAnimationFrame(i)}_initFromProgress(t,e){const n=t*e,r=Math.min(Math.floor(n),e-1);this._playStartOffset=n-r,this._playIndex=(r+1)%e}startPlay(t,e,n=2e3,r=1200,i=-1,s=!1){if(this._playing)return void this.stopPlay();const o=this.getPlayableSlots();if(o.length<2)return;this._playing=!0;let a=!0,c=-1;const l=i>=0&&i<=1?i:this._lastPlayProgress>0&&this._lastPlayProgress<1?this._lastPlayProgress:-1;s?this._playIndex=0:l>=0?(this._initFromProgress(l,o.length),c=l,a=!1):this._playIndex=0;const h=t=>new _.Vector3(t.x,t.y,t.z),d=t=>{this._onAnimationComplete=()=>{this._playing&&(this._playStartOffset=0,setTimeout(()=>{this._playing&&(this._playIndex=(this._playIndex+1)%o.length,u())},t))}},u=()=>{if(!this._playing)return;const i=o[this._playIndex],s=this._slots[i],l=s?.holdDuration??n,u=s?.transitionDuration??r;if(c>=0){const n=c;let r=this._playIndex/o.length;r<=n&&(r+=1),c=-1;const i=this._playStartOffset,a=Math.max(Math.round(u*(1-i)),100);return d(l),void this._animatePathSegment(n,r,a,s?.easing??"ease-in-out",t,e)}const p=this._buildSplineContext(o,a,t,e,h);a=!1,d(l),this.animateToSlot(i,t,e,u,p)};u()}_buildSplineContext(t,e,n,r,i){if(t.length<3)return;const s=t.length,o=t[(this._playIndex+1)%s],a=this._slots[o];if(!a)return;if(e)return{prevPos:n.position.clone(),nextPos:i(a.position)};const c=t[(this._playIndex-2+s)%s],l=this._slots[c];return l?{prevPos:i(l.position),nextPos:i(a.position)}:void 0}setProgressForSlot(t){const e=this.getPlayableSlots(),n=e.indexOf(t);n<0||e.length<2?this._lastPlayProgress=-1:this._lastPlayProgress=n/e.length}stopPlay(){this._lastPlayProgress=this.playProgress,this._playing=!1,this._playIndex=-1,this._playStartOffset=0,this._onAnimationComplete=void 0,this.stopAnimation()}resetPlay(){this.stopPlay(),this._lastPlayProgress=-1}toggleOrbitRotation(t){const e=t.isAutoRotating();this._orbitRotating=!e,this._orbitPaused=!this._orbitRotating,t.setAutoRotate(this._orbitRotating)}stopOrbitRotation(t){this._orbitRotating=!1,this._orbitPaused=!1,t.setAutoRotate(!1)}evaluatePath(t){const e=this.getPlayableSlots();if(e.length<2)return null;const n=e.length,r=Math.max(0,Math.min(1,t)),i=t=>{const r=this._slots[e[(t%n+n)%n]];return r?new _.Vector3(r.position.x,r.position.y,r.position.z):new _.Vector3},s=t=>{const r=this._slots[e[(t%n+n)%n]];return r?new _.Vector3(r.target.x,r.target.y,r.target.z):new _.Vector3};if(2===n){const t=r<.5?2*r:2*(1-r);return{position:i(0).lerp(i(1),t),target:s(0).lerp(s(1),t)}}const o=r*n,a=Math.min(Math.floor(o),n-1),c=o-a,l=Uh(c,i(a-1),i(a),i(a+1),i(a+2)),h=i(a),d=i(a+1),u=s(a),p=s(a+1),f=.01,g=Math.max(h.distanceTo(u),f),m=Math.max(d.distanceTo(p),f),y=(new _.Vector3).subVectors(u,h),b=(new _.Vector3).subVectors(p,d),v=y.lengthSq()>1e-4?y.normalize():new _.Vector3(0,0,-1),x=b.lengthSq()>1e-4?b.normalize():v.clone(),w=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),v),M=(new _.Quaternion).setFromUnitVectors(new _.Vector3(0,0,-1),x),S=w.clone().slerp(M,c),A=new _.Vector3(0,0,-1).applyQuaternion(S),E=g+(m-g)*c,k=l.clone().add(A.multiplyScalar(E));return{position:l,target:k}}stopAnimation(){void 0!==this._animationId&&(cancelAnimationFrame(this._animationId),this._animationId=void 0),this._animating=!1}destroy(){this.stopPlay(),this.stopAnimation(),this._orbitPaused=!1,this._slots=new Array(10),this._onInvalidate=void 0,this._onAnimationComplete=void 0}}class Wh{constructor(){this._overlay=null,this._hostElement=null,this._startX=0,this._startY=0,this._currentX=0,this._currentY=0,this._active=!1}get isActive(){return this._active}setup(t){this._hostElement=t}startSelection(t,e){this._hostElement&&(this._startX=t,this._startY=e,this._currentX=t,this._currentY=e,this._active=!0,this._overlay=document.createElement("div"),this._overlay.style.cssText="\n position: absolute;\n border: 1px solid #4a9eff;\n background: rgba(74, 158, 255, 0.1);\n pointer-events: none;\n z-index: 1000;\n ",this._hostElement.appendChild(this._overlay),this._updateOverlay())}updateSelection(t,e){this._active&&(this._currentX=t,this._currentY=e,this._updateOverlay())}endSelection(t,e,n){if(!this._active||!this._hostElement)return this.cancelSelection(),[];const r=this._hostElement.getBoundingClientRect(),i=r.width,s=r.height,o=Math.min(this._startX,this._currentX),a=Math.max(this._startX,this._currentX),c=Math.min(this._startY,this._currentY),l=Math.max(this._startY,this._currentY);if(a-o<5&&l-c<5)return this.cancelSelection(),[];const h=o/i*2-1,d=a/i*2-1,u=-l/s*2+1,p=-c/s*2+1,f=[],g=new _.Vector3;for(const e of n){const n=e._realObject;n?.object3d&&(g.copy(n.object3d.position),g.project(t),g.z>1||g.x>=h&&g.x<=d&&g.y>=u&&g.y<=p&&f.push(e))}return this.cancelSelection(),f}cancelSelection(){this._active=!1,this._overlay&&this._hostElement&&this._hostElement.removeChild(this._overlay),this._overlay=null}destroy(){this.cancelSelection(),this._hostElement=null}_updateOverlay(){if(!this._overlay)return;const t=Math.min(this._startX,this._currentX),e=Math.min(this._startY,this._currentY),n=Math.abs(this._currentX-this._startX),r=Math.abs(this._currentY-this._startY);this._overlay.style.left=`${t}px`,this._overlay.style.top=`${e}px`,this._overlay.style.width=`${n}px`,this._overlay.style.height=`${r}px`}}const Xh=4890367,qh=16750592;class Kh{constructor(){this._componentHandles=[],this._activeVertexHandles=[],this._activeHandleIndex=-1,this._isDragging=!1,this._isExtending=!1,this._dragPlane=new _.Plane,this._dragOffset=new _.Vector3,this._raycaster=new _.Raycaster,this._intersection=new _.Vector3}get isDragging(){return this._isDragging}get isAttached(){return this._componentHandles.length>0}setVisible(t){this._handleGroup&&(this._handleGroup.visible=t)}attachMultiple(t,e,n){this.detach();const r=t.filter(t=>t.mutable&&t.path&&t.path.length>=2);if(0!==r.length){this._scene3d=e,this._commander=n,this._handleGroup=new _.Group,this._handleGroup.name="__vertexHandles__",this._handleGroup.renderOrder=1e4;for(const t of r){const e=this._buildComponentHandles(t);this._componentHandles.push(e)}e.add(this._handleGroup)}}attach(t,e,n){this.attachMultiple([t],e,n)}detach(){this._handleGroup&&this._scene3d&&(this._scene3d.remove(this._handleGroup),yh(this._handleGroup)),this._componentHandles=[],this._handleGroup=void 0,this._scene3d=void 0,this._commander=void 0,this._activeComponent=void 0,this._activeVertexHandles=[],this._activeHandleIndex=-1,this._isDragging=!1,this._isExtending=!1}_buildComponentHandles(t){const e=[],n=[],r=t.path;if(!r||!this._handleGroup)return{component:t,vertexHandles:e,midpointHandles:n};const{width:i=0,height:s=0}=t.parent?.bounds??{},o=t._realObject,a=o?o.object3d.position.y:0;for(let n=0;n<r.length;n++){const o=r[n],c=new _.Vector3(o.x-i/2,(o.z||0)+a,o.y-s/2),l=this._createVertexHandle(c,n,t);e.push(l),this._handleGroup.add(l)}if(t.pathExtendable)for(let e=0;e<r.length-1;e++){const o=r[e],c=r[e+1],l=new _.Vector3((o.x+c.x)/2-i/2,((o.z||0)+(c.z||0))/2+a,(o.y+c.y)/2-s/2),h=this._createMidpointHandle(l,e,t);n.push(h),this._handleGroup.add(h)}return{component:t,vertexHandles:e,midpointHandles:n}}_rebuildComponentHandles(t){const e=this._componentHandles.findIndex(e=>e.component===t);if(e<0||!this._handleGroup)return;const n=this._componentHandles[e];for(const t of[...n.vertexHandles,...n.midpointHandles])this._handleGroup.remove(t),t.geometry.dispose(),t.material.dispose();this._componentHandles[e]=this._buildComponentHandles(t),this._activeComponent===t&&(this._activeVertexHandles=this._componentHandles[e].vertexHandles)}_createVertexHandle(t,e,n){const r=new _.SphereGeometry(1,16,12),i=new _.MeshBasicMaterial({color:Xh,transparent:!0,opacity:.8,depthTest:!1}),s=new _.Mesh(r,i);return s.position.copy(t),s.userData.vertexIndex=e,s.userData.handleType="vertex",s.userData.component=n,s.renderOrder=10001,s}_createMidpointHandle(t,e,n){const r=new _.OctahedronGeometry(.7,0),i=new _.MeshBasicMaterial({color:16735602,transparent:!0,opacity:.7,depthTest:!1}),s=new _.Mesh(r,i);return s.position.copy(t),s.userData.segmentIndex=e,s.userData.handleType="midpoint",s.userData.component=n,s.renderOrder=10001,s}_handlePosToPoint(t,e){const{width:n=0,height:r=0}=e.parent?.bounds??{},i=e._realObject,s=i?i.object3d.position.y:0,o={x:t.x+n/2,y:t.z+r/2},a=t.y-s;return Math.abs(a)>.001&&(o.z=a),o}_execMutatePath(t,e){const n=this._commander;n?zc.around(n,()=>{t.mutatePath(null,e)}):t.mutatePath(null,e)}_getAllHandles(){const t=[];for(const e of this._componentHandles)t.push(...e.vertexHandles,...e.midpointHandles);return t}_findComponentHandles(t){return this._componentHandles.find(e=>e.component===t)}onPointerDown(t,e,n){if(!this._handleGroup)return!1;const r=this._getAllHandles();if(0===r.length)return!1;this._raycaster.setFromCamera(t,e);const i=this._raycaster.intersectObjects(r,!1);if(0===i.length)return!1;const s=i[0].object,o=s.userData.handleType,a=s.userData.component,c=this._findComponentHandles(a);if(!c)return!1;if(this._activeComponent=a,this._activeVertexHandles=c.vertexHandles,"midpoint"===o)return this._startMidpointDrag(s,a,e);const l=s.userData.vertexIndex,h=a.path;if(!h)return!1;const d=0===l||l===h.length-1;return n.altKey&&d&&a.pathExtendable?this._startEndpointExtend(s,l,a,e):(this._activeHandleIndex=l,this._isDragging=!0,this._isExtending=!1,s.material.color.setHex(qh),this._setupDragPlane(e,s.position),!0)}_startMidpointDrag(t,e,n){const r=t.userData.segmentIndex+1,i=this._handlePosToPoint(t.position,e);this._execMutatePath(e,t=>{t.splice(r,0,i)}),this._rebuildComponentHandles(e);const s=this._activeVertexHandles[r];return!!s&&(this._activeHandleIndex=r,this._isDragging=!0,this._isExtending=!1,s.material.color.setHex(qh),this._setupDragPlane(n,s.position),!0)}_startEndpointExtend(t,e,n,r){const i=n.path;if(!i)return!1;const s=this._handlePosToPoint(t.position,n),o=0===e?0:i.length;this._execMutatePath(n,t=>{t.splice(o,0,s)}),this._rebuildComponentHandles(n);const a=this._activeVertexHandles[o];return!!a&&(this._activeHandleIndex=o,this._isDragging=!0,this._isExtending=!0,a.material.color.setHex(qh),this._setupDragPlane(r,a.position),!0)}_setupDragPlane(t,e){const n=new _.Vector3;t.getWorldDirection(n),this._dragPlane.setFromNormalAndCoplanarPoint(n,e),this._raycaster.ray.intersectPlane(this._dragPlane,this._intersection),this._dragOffset.copy(e).sub(this._intersection)}onPointerMove(t,e,n){if(!this._isDragging||this._activeHandleIndex<0)return!1;this._raycaster.setFromCamera(t,e),this._raycaster.ray.intersectPlane(this._dragPlane,this._intersection);const r=this._intersection.add(this._dragOffset);if(n.shiftKey){const t=this._activeVertexHandles[this._activeHandleIndex];t&&(r.x=t.position.x,r.z=t.position.z)}const i=this._activeVertexHandles[this._activeHandleIndex];return i&&i.position.copy(r),this._updateLinePreview(),!0}_updateLinePreview(){if(!this._activeComponent)return;const t=this._activeComponent._realObject;if(!t?._line2)return;const{width:e=0,height:n=0}=this._activeComponent.parent?.bounds??{},{x:r,y:i}=this._activeComponent.center,s=t.object3d?t.object3d.position.y:0,o=[];for(const t of this._activeVertexHandles){const a=t.position.x+e/2-r,c=t.position.y-s,l=t.position.z+n/2-i;o.push(a,c,l)}if(o.length<6)return;t._line2.geometry.setPositions(o),t._line2.computeLineDistances()}onPointerUp(){if(!this._isDragging||this._activeHandleIndex<0||!this._activeComponent)return!1;const t=this._activeHandleIndex,e=this._activeVertexHandles[t],n=this._activeComponent;if(!e)return this._isDragging=!1,this._activeHandleIndex=-1,this._isExtending=!1,!0;e.material.color.setHex(Xh);const r=this._handlePosToPoint(e.position,n);return this._execMutatePath(n,e=>{e[t]=r}),this._isDragging=!1,this._activeHandleIndex=-1,this._isExtending=!1,this._rebuildComponentHandles(n),!0}onDblClick(t,e){if(!this._handleGroup)return!1;const n=[];for(const t of this._componentHandles)n.push(...t.vertexHandles);this._raycaster.setFromCamera(t,e);const r=this._raycaster.intersectObjects(n,!1);if(0===r.length)return!1;const i=r[0].object,s=i.userData.component;if(!s.pathExtendable)return!1;const o=s.path;if(!o||o.length<=2)return!1;const a=i.userData.vertexIndex;return this._execMutatePath(s,t=>{t.splice(a,1)}),this._rebuildComponentHandles(s),!0}syncHandles(){for(const t of this._componentHandles)this._rebuildComponentHandles(t.component)}updateHandleScales(t){const e=this._getAllHandles();if(0!==e.length)for(const n of e){const e=t.position.distanceTo(n.position),r="midpoint"===n.userData.handleType?5:8;let i;if(t.isPerspectiveCamera){const n=t.fov,s=2*Math.tan(n*Math.PI/360)*e;i=r/window.innerHeight*s}else{const e=t,n=(e.top-e.bottom)/e.zoom;i=r/window.innerHeight*n}n.scale.setScalar(Math.max(i,.1))}}destroy(){this.detach()}}class Qh{constructor(){this.sceneManager=new zh,this.cameraManager=new Ih,this.rendererManager=new Lh,this.lightManager=new jh,this.controlsManager=new Fh,this.eventManager=new Bh,this.gizmoManager=new Nh,this.interactionManager=new Vh,this.placementManager=new Gh,this.gizmoOperationManager=new Hh,this.bookmarkManager=new $h,this.boxSelectionManager=new Wh,this.vertexGizmoManager=new Kh,this._isSpacePanning=!1,this._initialized=!1,this._decoratorOutlines=new Set,this._selectionOutlineObjects=[],this._highlightedMarkerIndex=-1,this._arrows=new Map,this._pathVisible=!1}get isInitialized(){return this._initialized}get host(){return this._host}get scene3d(){return this.sceneManager.scene}get renderer3d(){return this.rendererManager.renderer}get mixer(){return this.sceneManager.mixer}get camera(){return this.cameraManager.camera}get activeCamera(){return this.cameraManager.activeCamera}get css3DScene(){return this.rendererManager.css3DScene}get css3DRenderer(){return this.rendererManager.css3DRenderer}get noSupportWebgl(){return this.rendererManager.noSupportWebgl}get isActive(){return this.controlsManager.isActive}setGizmoMode(t){if(this.gizmoManager.mode===t&&this.gizmoManager.attached)return this.gizmoManager.detach(),void this._host?.invalidate();this.gizmoManager.setMode(t),this.onGizmoModeChanged?.(t);const e=this._host?.root?.selected,n=e?.filter(t=>t!==this._host&&t._realObject)||[];if(n.length>=1){const t=n[0]._realObject;t?.object3d&&t.gizmoTransformable&&this.gizmoManager.attach(t.object3d),this._host?.invalidate()}}get gizmoMode(){return this.gizmoManager.mode}init(t,e){this.interactionManager.cleanup(),this._cleanupEventHandlers(),this._host=t,this.sceneManager.scene&&this.destroy(),this._redrawHandler=()=>this.animate(),t.root.on("redraw",this._redrawHandler),this._initialized=!0,this._setupScene(e),this._onComponentAdd=(t,e)=>this.addObject(e),this._onComponentRemove=(t,e)=>this.removeObject(e),t.on&&(t.on("add",this._onComponentAdd),t.on("remove",this._onComponentRemove)),t.app?.isEditMode&&t.root?.on&&(this._onSelectionChanged=t=>this._handleSelectionChanged(t),t.root.on("selected",this._onSelectionChanged)),t.app?.isEditMode&&t.root?.on&&(this._onAddStart=t=>{this.placementManager.start(t),this._host?.element&&(this._host.element.style.cursor="crosshair",this._host.element.focus())},this._onAddStop=()=>{this.placementManager.stop(),this._host?.element&&(this._host.element.style.cursor="")},t.root.on("addstart",this._onAddStart),t.root.on("addstop",this._onAddStop))}_cleanupEventHandlers(){const t=this._host;t&&(this._redrawHandler&&(t.root.off("redraw",this._redrawHandler),this._redrawHandler=void 0),t.off&&(this._onComponentAdd&&(t.off("add",this._onComponentAdd),this._onComponentAdd=void 0),this._onComponentRemove&&(t.off("remove",this._onComponentRemove),this._onComponentRemove=void 0)),this._onSelectionChanged&&t.root?.off&&(t.root.off("selected",this._onSelectionChanged),this._onSelectionChanged=void 0),this._onAddStart&&t.root?.off&&(t.root.off("addstart",this._onAddStart),this._onAddStart=void 0),this._onAddStop&&t.root?.off&&(t.root.off("addstop",this._onAddStop),this._onAddStop=void 0))}_setupScene(t){const e=this._host;let{width:n,height:r}=e.bounds;n=Math.abs(n)||1,r=Math.abs(r)||1;const{fov:i=45,near:s=.1,far:o=2e4,antialias:a=!0,precision:c="highp",cameraX:l,cameraY:h,cameraZ:d,exposure:u=1}=e.state,p=e.components||[],f=t?.lightingConfig??{hemisphere:{skyColor:16777215,groundColor:4473924,intensity:.4}},g=t?.css3DSceneAttribute??"three-container:css3d-renderer",m=this.sceneManager.setup(),y=this.cameraManager.setup(n,r,{fov:i,near:s,far:o,cameraX:l,cameraY:h,cameraZ:d});this.cameraManager.addToScene(m);const b=e.app?.postprocessing;if(this.rendererManager.setupWebGL(n,r,{precision:c,antialias:a,exposure:u,postprocessing:b})){if(t?.skipEnvironment||this.sceneManager.setupEnvironment(this.rendererManager.renderer),this.controlsManager.setup(y,e),this.controlsManager.setOnUserInteraction(()=>{this.bookmarkManager.isPlaying&&(this.bookmarkManager.stopPlay(),this._pathVisible&&this.showBookmarkPath()),this.bookmarkManager.isOrbitRotating&&this.bookmarkManager.stopOrbitRotation(this.controlsManager)}),e.app?.isEditMode&&e.element&&(this.gizmoManager.setup(y,e.element,m),this._setupGizmoCallbacks()),this.placementManager.setup({camera:this.cameraManager,event:this.eventManager,scene:this.sceneManager},{updateMouseNDCFromClient:(t,e)=>this._updateMouseNDCFromClient(t,e)}),this.lightManager.setup(m,y,f),this.sceneManager.setupMixer(),this.createObjects(p),y.updateProjectionMatrix(),t?.skipFloor||this.sceneManager.addFloor(e),this.sceneManager.setSky(e.state.sky,e.state.skyColor),t?.skipPostprocessing||!1===e.app?.postprocessing)this.rendererManager.setDirectRenderTargets(m,y);else{const t=this.gizmoManager.controls?.getHelper();this.rendererManager.setupComposer(m,y,n,r,t)}this.rendererManager.setupHUD(n,r),this.rendererManager.hudCamera&&this.eventManager.setHUD(this.rendererManager.hudScene,this.rendererManager.hudCamera),this.rendererManager.setupCSS3D(e.app.isViewMode,g),this._onFocus=()=>this.renderThreeD(),window.addEventListener("focus",this._onFocus),e.element&&(this.interactionManager.setup(e.element,{gizmo:this.gizmoManager,controls:this.controlsManager,camera:this.cameraManager,scene:this.sceneManager,event:this.eventManager},this._buildInteractionDelegate()),e.app?.isEditMode&&this.boxSelectionManager.setup(e.element))}}_setupGizmoCallbacks(){this.gizmoOperationManager.setupCallbacks(this.gizmoManager,this.controlsManager,()=>this._host,{onAttachChanged:t=>this.onGizmoAttachChanged?.(t),onDraggingChanged:t=>{t?this.vertexGizmoManager.setVisible(!1):(this.vertexGizmoManager.syncHandles(),this.vertexGizmoManager.setVisible(!0))}})}createObjects(t){for(const e of t)this.addObject(e)}addObject(t){if(!t._realObject&&!t.is3dContainer?.()){try{const{width:e,height:n}=t.bounds;if(!e||!n)return;if(t.isHTMLElement()&&!t.element)return;const r=kh(t);if(r){if(t._realObject=r,r.update(),r.updateTransform(),t.state.screenFixed)r instanceof wh?this.rendererManager.hudCSS3DScene.add(r.object3d):this.rendererManager.hudScene.add(r.object3d);else if(r instanceof wh)this.rendererManager.css3DScene.add(r.object3d);else{const e=t.parent?._realObject?.object3d;e&&e!==this.sceneManager.scene?e.add(r.object3d):this.sceneManager.scene.add(r.object3d)}const e=this._host?.root?.selected;e&&e.length>0&&e[0]===t&&r.object3d&&r.gizmoTransformable&&this.gizmoManager.attached&&this.gizmoManager.attach(r.object3d)}}catch(t){jr(t)}if(t.isContainer()){const e=t,n=e.components||[];this.createObjects(n),e.on&&(e.on("add",this._onComponentAdd),e.on("remove",this._onComponentRemove))}}}removeObject(t){if(t.is3dContainer?.())return;if(t.isContainer()){const e=t,n=e.components||[];for(const t of n)this.removeObject(t);e.off&&(e.off("add",this._onComponentAdd),e.off("remove",this._onComponentRemove))}const e=t._realObject;if(e)try{const n=e.object3d;n&&this.gizmoManager.attached===n&&this.gizmoManager.detach(),n&&(e instanceof wh?this.rendererManager.css3DScene.remove(n):n.removeFromParent()),e.dispose?.(),t._realObject=void 0}catch(t){jr(t)}}resize(t,e,n=!1){const r=this._host;if(!r)return;if(void 0===t||void 0===e){const n=r.bounds;t=n.width,e=n.height}if(t=Math.abs(t)||1,e=Math.abs(e)||1,n)return void this._applyResize(t,e);this.rendererManager.css3DRenderer?.setSize(t,e);const i=t,s=e;clearTimeout(this._resizeDebouncer),this._resizeDebouncer=window.setTimeout(()=>{this._resizeDebouncer=void 0,this._applyResize(i,s)},100)}_applyResize(t,e){this.cameraManager.updateAspect(t,e),this.rendererManager.resize(t,e);const n=new _.Vector2(t,e);for(const t of this._arrows.values())t.traverse(t=>{t instanceof r.Line2&&t.material.resolution.copy(n)});this._initialized&&this.renderThreeD()}animate(){if(!this._initialized||!this.controlsManager.isActive)return;this.sceneManager.updateAnimation();let t=!1;const e=n=>{for(const r of n)r._animation?.started&&r._realObject&&(r._realObject.syncAnimationDelta(),t=!0),r.components&&e(r.components)};e(this._host?.components||[]),this.controlsManager.update(),this.renderThreeD(),t&&this._host?.invalidate()}renderThreeD(){this._initialized&&(this.vertexGizmoManager?.isAttached&&this.vertexGizmoManager.updateHandleScales(this.cameraManager.activeCamera),this.rendererManager.render(),this.renderCSS3D())}setCameraView(t,e){const n=this._host;if(!n)return;const{width:r,height:i}=n.bounds,s=n.element,o=s?.clientWidth||r,a=s?.clientHeight||i;let c;c="perspective"===t?this.cameraManager.restorePerspective():this.cameraManager.setOrthoView(t,r,i,o,a),this.controlsManager.setCamera(c),this.gizmoManager.updateCamera(c),this.rendererManager.updateRenderPassCamera(c),!1!==e?.render&&this.renderThreeD(),this.onCameraViewChanged?.(t)}renderCSS3D(){const t=this.cameraManager.activeCamera;t&&this.rendererManager.renderCSS3D(t)}buildOverlays(){const t=this._host;if(!t?.element)return;t.element.appendChild(this.css3DRenderer.domElement);const e=this.rendererManager.hudCSS3DRenderer?.domElement;e&&t.element.appendChild(e)}destroy(){this.interactionManager.cleanup(),this._resizeDebouncer&&(clearTimeout(this._resizeDebouncer),this._resizeDebouncer=void 0),this._onFocus&&(window.removeEventListener("focus",this._onFocus),this._onFocus=void 0),this.vertexGizmoManager.destroy(),this.boxSelectionManager.destroy(),this.bookmarkManager.destroy(),this.gizmoManager.destroy(),this.controlsManager.destroy(),this.lightManager.destroy(),this.rendererManager.destroy(),this.cameraManager.destroy(),this.sceneManager.destroy(),this.eventManager.destroy(),this._initialized=!1}forceCleanupDragState(){this.interactionManager.forceCleanupDragState(),this.boxSelectionManager.isActive&&(this.boxSelectionManager.cancelSelection(),this.controlsManager.setEnabled(!0)),this._isSpacePanning&&(this._isSpacePanning=!1,void 0!==this._beforeSpaceMode&&this._host?.app&&(this._host.app.mode=this._beforeSpaceMode,this._beforeSpaceMode=void 0)),this._host?.element&&(this._host.element.style.cursor="")}clearAllObjects(){this.gizmoManager.detach();const t=this._host?.components||[];for(const e of t)e._realObject&&this.removeObject(e)}rebuildForHost(t,e){this.interactionManager.cleanup();try{this._cleanupEventHandlers()}catch(t){}this._host=t,this._redrawHandler=()=>this.animate(),t.root.on("redraw",this._redrawHandler),this._onComponentAdd=(t,e)=>this.addObject(e),this._onComponentRemove=(t,e)=>this.removeObject(e),t.on&&(t.on("add",this._onComponentAdd),t.on("remove",this._onComponentRemove)),t.app?.isEditMode&&t.root?.on&&(this._onSelectionChanged=t=>this._handleSelectionChanged(t),t.root.on("selected",this._onSelectionChanged),this._onAddStart=t=>{this.placementManager.start(t),this._host?.element&&(this._host.element.style.cursor="crosshair",this._host.element.focus())},this._onAddStop=()=>{this.placementManager.stop(),this._host?.element&&(this._host.element.style.cursor="")},t.root.on("addstart",this._onAddStart),t.root.on("addstop",this._onAddStop)),this.createObjects(t.components||[]),t.element&&this.interactionManager.setup(t.element,{gizmo:this.gizmoManager,controls:this.controlsManager,camera:this.cameraManager,scene:this.sceneManager,event:this.eventManager},this._buildInteractionDelegate()),this.controlsManager.setup(this.cameraManager.camera,t),t.app?.isEditMode&&t.element&&this.boxSelectionManager.setup(t.element),t.app?.isEditMode&&t.element&&this.sceneManager.scene&&(this.gizmoManager.setup(this.cameraManager.camera,t.element,this.sceneManager.scene),this._setupGizmoCallbacks()),this._onFocus||(this._onFocus=()=>this.renderThreeD(),window.addEventListener("focus",this._onFocus)),this.renderThreeD()}dispose(){const t=e=>{for(const n of e)if(!n.is3dContainer?.()){if(n.isContainer()){const e=n.components||[];t(e)}n._realObject&&(n._realObject.dispose?.(),n._realObject=void 0)}};t(this._host?.components||[]),this._decoratorOutlines.clear(),this._selectionOutlineObjects=[],this.clearArrows(),this.placementManager.destroy(),this._cleanupEventHandlers(),this.rendererManager.disposeCSS3DScene(),this.destroy(),this._host=void 0}_buildInteractionDelegate(){return{isPlacementMode:()=>this.placementManager.isActive,handlePlacementClick:t=>{if(!this._host?.root)return;const e=this.placementManager.raycastGroundPlane(t);if(e){const t=this._host,n=t.bounds.width||800,r=t.bounds.height||600,i=e.x+n/2,s=e.z+r/2;Jc.call(t.root,this.placementManager.pendingModels,{cx:i,cy:s}),t.root.trigger("addstop")}},handlePlacementHover:t=>{const e=this.placementManager.raycastGroundPlane(t);this.placementManager.updateIndicator(e),this.renderThreeD()},tryAltClickSelect:t=>{if(!this._host?.app?.isEditMode||!this._host.root)return!1;this._updateMouseNDCFromClient(t.clientX,t.clientY);const e=this.cameraManager.activeCamera;if(e&&this.sceneManager.scene){const n=this.eventManager.handleClick(e,this.sceneManager.scene,t);if(n?.component)return this._host.root.selected=[n.component],!0}return!1},captureMouseDownAltKey:t=>{this.gizmoOperationManager.captureAltKey(t)},handleClickAt:(t,e,n)=>{this._handleClickAt(n)},handleWheel:t=>this.onWheel(t),handleDblClick:t=>this.onDblClick(t),handleTouchStart:t=>this.onTouchStart(t),handleTouchMove:t=>this.onPan(t),handleTouchEnd:t=>this.onTouchEnd(t),handleKeyDown:t=>this.onKeyDown(t),handleKeyUp:t=>this._onKeyUp(t),isSpacePanning:()=>this._isSpacePanning,handleBoxSelectionStart:(t,e)=>{this.controlsManager.setEnabled(!1),this._host?.element&&(this._host.element.style.cursor="crosshair"),this.boxSelectionManager.startSelection(t,e)},handleBoxSelectionUpdate:(t,e)=>{this.boxSelectionManager.updateSelection(t,e)},tryVertexDragStart:t=>{if(!this.vertexGizmoManager.isAttached)return!1;const e=this.cameraManager.activeCamera;if(!e)return!1;const n=this.eventManager.mouse,r=this.vertexGizmoManager.onPointerDown(n,e,t);return r&&this.controlsManager.setEnabled(!1),r},handleVertexDragMove:t=>{const e=this.cameraManager.activeCamera;if(!e)return;const n=this.eventManager.mouse;this.vertexGizmoManager.onPointerMove(n,e,t),this._host?.invalidate()},handleVertexDragEnd:t=>{this.vertexGizmoManager.onPointerUp(),this.controlsManager.setEnabled(!0),this._host?.invalidate()},handleBoxSelectionEnd:t=>{this.controlsManager.setEnabled(!0),this._host?.element&&(this._host.element.style.cursor="");const e=this.cameraManager.activeCamera,n=this.sceneManager.scene,r=this._host?.components||[];if(e&&n){const i=this.boxSelectionManager.endSelection(e,n,r);if(i.length>0&&this._host?.root)if(t){const t=this._host,e=(this._host.root.selected||[]).filter(e=>e!==t);for(const t of i)e.includes(t)||e.push(t);this._host.root.selected=e}else this._host.root.selected=i}else this.boxSelectionManager.cancelSelection()}}}_handleClickAt(t){const e=this._host,n=this.cameraManager.activeCamera;if(!n||!this.sceneManager.scene)return;if(this._pathMarkers&&this._pathMarkers.children.length>0){const t=new _.Raycaster,e=this.eventManager.mouse;t.setFromCamera(e,n);const r=t.intersectObjects(this._pathMarkers.children,!0);if(r.length>0){let t=r[0].object;for(;t&&void 0===t.userData.bookmarkSlotIndex;)t=t.parent;if(t&&void 0!==t.userData.bookmarkSlotIndex)return void this.animateToSlot(t.userData.bookmarkSlotIndex)}}if(this.vertexGizmoManager?.isDragging)return this.vertexGizmoManager.onPointerUp(),this.controlsManager.setEnabled(!0),void this._host?.invalidate();const r=this.gizmoManager.isDragging;if(this.gizmoManager.forwardEvent(t,"pointerup"),r)return;const i=this.eventManager.handleClick(n,this.sceneManager.scene,t);if(e.root){const t=e.app?.mode;if(4===t||5===t){if(!i?.component){const n=4===t?"stylepastestop":"databindpastestop";e.root.trigger(n)}return}}e.app?.isEditMode&&e.root&&this._applySelection(e.root,i?.component,t.shiftKey)}_applySelection(t,e,n){if(e)if(n){const n=(t.selected||[]).slice(),r=n.indexOf(e);-1===r?n.push(e):n.splice(r,1),t.selected=n}else t.selected=[e];else n||(t.selected=[])}getObjectByRaycast(){if(!this.sceneManager.scene)return;const t=this.cameraManager.activeCamera;return t?this.eventManager.getObjectByRaycast(t,this.sceneManager.scene):void 0}getObjectsByRaycast(){if(!this.sceneManager.scene)return;const t=this.cameraManager.activeCamera;return t?this.eventManager.getObjectsByRaycast(t,this.sceneManager.scene):void 0}_updateMouseNDCFromClient(t,e){const n=this._host?.element;if(n){const r=n.getBoundingClientRect();if(r.width>0&&r.height>0){const n=t-r.left,i=e-r.top;return void this.eventManager.updateMouseNDC(n,i,0,0,r.width,r.height)}}const r=this._host;if(r){const{left:n,top:i,width:s,height:o}=r.bounds;s>0&&o>0&&this.eventManager.updateMouseNDC(t,e,n,i,Math.abs(s),Math.abs(o))}}_eventToNDC(t){const e=this._host?.element;if(e){const n=e.getBoundingClientRect();if(n.width>0&&n.height>0)return{ndcX:(t.clientX-n.left)/n.width*2-1,ndcY:-(t.clientY-n.top)/n.height*2+1}}const n=this._host;if(n?.transcoordC2S){const{width:e,height:r}=n.bounds;if(Math.abs(e)>0&&Math.abs(r)>0){const i=n.transcoordC2S(t.offsetX,t.offsetY);return{ndcX:i.x/Math.abs(e)*2-1,ndcY:-(i.y/Math.abs(r)*2-1)}}}return{ndcX:0,ndcY:0}}_updateMouseNDC(t){const e=this._host?.element;if(e){const n=e.getBoundingClientRect();if(n.width>0&&n.height>0){const e=t.clientX-n.left,r=t.clientY-n.top;return void this.eventManager.updateMouseNDC(e,r,0,0,n.width,n.height)}}const n=this._host;if(n?.transcoordC2S){const{width:e,height:r}=n.bounds;if(Math.abs(e)>0&&Math.abs(r)>0){const i=n.transcoordC2S(t.offsetX,t.offsetY);this.eventManager.updateMouseNDC(i.x,i.y,0,0,Math.abs(e),Math.abs(r))}}}onMouseUp(t){if(this.controlsManager.isActive){const e=this.gizmoManager.isDragging;if(this.gizmoManager.forwardEvent(t,"pointerup"),e)return t.stopPropagation(),!0;const n=this.cameraManager.activeCamera;this._updateMouseNDC(t);const r=this.eventManager.handleClick(n,this.sceneManager.scene,t),i=this._host;return i?.app?.isEditMode&&i.root&&this._applySelection(i.root,r?.component,t.shiftKey),t.stopPropagation(),!0}return!1}onMouseMove(t){if(this.controlsManager.isActive){this.gizmoManager.forwardEvent(t,"pointermove");const e=this.cameraManager.activeCamera;return this._updateMouseNDC(t),this.eventManager.handleHover(e,this.sceneManager.scene,t),t.stopPropagation(),!0}return!1}onMouseDown(t){return!(!this.controlsManager.isActive||(this.gizmoManager.forwardEvent(t,"pointerdown"),!this.gizmoManager.isDragging))&&(t.stopPropagation(),!0)}onMouseLeave(t){return!1}onWheel(t){if(this.controlsManager.isActive){const{ndcX:e,ndcY:n}=this._eventToNDC(t);if("perspective"!==this.cameraManager.activeView){const r=t.deltaY>0?.9:1.1;this.controlsManager.zoomOrthoAtCursor(r,e,n),this.renderThreeD()}else{const r=Math.pow(.999,-t.deltaY);this.controlsManager.dollyAtCursor(r,e,n),this.renderThreeD()}return t.stopPropagation(),!0}return!1}onDblClick(t){if(!this.controlsManager.isActive)return!1;const e=this._host,n=this.cameraManager.activeCamera;if(!n||!this.sceneManager.scene)return this.controlsManager.reset(),!0;if(e?.app?.isEditMode&&e.root){if(this.vertexGizmoManager.isAttached){const t=this.eventManager.mouse;if(this.vertexGizmoManager.onDblClick(t,n))return this._host?.invalidate(),!0}const t=this.eventManager.getObjectByRaycast(n,this.sceneManager.scene),e=t?.userData?.context?.component;if(e?.hasTextProperty)return Ch(e,this.rendererManager,()=>{this.renderThreeD()}),!0}return this.controlsManager.reset(),t.stopPropagation(),!0}pinResetPosition(){this.controlsManager.pinResetPosition()}onDragStart(t){return!!this.controlsManager.isActive&&(this.gizmoManager.isDragging?(t.stopPropagation(),!0):(this.bookmarkManager.stopOrbitRotation(this.controlsManager),this.bookmarkManager.stopPlay(),this.controlsManager.onDragStart(t),t.stopPropagation(),!0))}onDragMove(t){return!!this.controlsManager.isActive&&(this.gizmoManager.isDragging?(this.gizmoManager.forwardEvent(t,"pointermove"),t.stopPropagation(),!0):(this.controlsManager.onDragMove(t),t.stopPropagation(),!0))}onDragEnd(t){return!!this.controlsManager.isActive&&(this.gizmoManager.isDragging?(this.gizmoManager.forwardEvent(t,"pointerup"),t.stopPropagation(),!0):(this.controlsManager.onDragEnd(t),t.stopPropagation(),!0))}onTouchStart(t){return!!this.controlsManager.isActive&&(this.controlsManager.onTouchStart(t),t.stopPropagation(),!0)}onPan(t){return!!this.controlsManager.isActive&&(this.controlsManager.onTouchMove(t),t.stopPropagation(),!0)}onTouchEnd(t){return!!this.controlsManager.isActive&&(this.controlsManager.onTouchEnd(t),t.stopPropagation(),!0)}onKeyDown(t){return!t.isComposing&&229!==t.keyCode&&(!!this.controlsManager.isActive&&(!!this._handleEscapeKey(t)||(!(!this._host?.app?.isEditMode||!this._handleEditModeKey(t))||(!!this._handleCursorHintKey(t)||(!!this._handleCameraAndViewKey(t)||(!!this._handlePlaybackKey(t)||(!t.shiftKey||t.ctrlKey||t.metaKey||t.altKey||"KeyB"!==t.code||!this._host?.app?.isEditMode?(this.controlsManager.onKeyDown(t),t.stopPropagation(),!0):(this.onBookmarkEditToggle?.(),t.preventDefault(),!0))))))))}_handleEscapeKey(t){if("Escape"!==t.key&&"Escape"!==t.code)return!1;if(this.placementManager.isActive&&this._host?.root)return this._host.root.trigger("addstop"),t.stopPropagation(),!0;const e=this._host?.app,n=this._host?.root;return e&&4===e.mode?(n?.trigger("stylepastestop"),!0):e&&5===e.mode?(n?.trigger("databindpastestop"),!0):!(!e?.isEditMode||!n)&&(this.gizmoManager.detach(),n.selected=[],!0)}_handleEditModeKey(t){const e=this._host.root;if(t.metaKey||t.ctrlKey)switch(t.code){case"KeyZ":{const n=this._host?.app?.commander,r=(e?.selected||[]).filter(t=>t!==this._host).map(t=>t.state?.id).filter(Boolean);if(t.shiftKey?n?.redo():n?.undo(),e&&r.length>0){const t=r.map(t=>e.findById(t)).filter(Boolean);t.length>0&&(e.selected=t)}return t.preventDefault(),!0}case"KeyC":return e&&(this._clipboard=ll.call(e)),t.preventDefault(),!0;case"KeyX":return e&&(this._clipboard=hl.call(e)),t.preventDefault(),!0;case"KeyV":return e&&this._clipboard&&dl.call(e,this._clipboard),t.preventDefault(),!0;case"KeyD":return e&&(this._clipboard=ll.call(e),this._clipboard&&dl.call(e,this._clipboard)),t.preventDefault(),!0;default:return!1}if("Enter"===t.code||"NumpadEnter"===t.code){const n=e?.selected;if(1===n?.length&&n[0].hasTextProperty)return Ch(n[0],this.rendererManager,()=>{this.renderThreeD()}),t.preventDefault(),!0}switch(t.code){case"KeyW":return this.setGizmoMode("translate"),!0;case"KeyE":return this.setGizmoMode("rotate"),!0;case"KeyR":return this.setGizmoMode("scale"),!0;case"Delete":case"Backspace":return e&&el.call(e),!0}return this._handleArrowKeyMove(t,e)}_handleArrowKeyMove(t,e){const n=e?.selected;if(!n||0===n.length)return!1;const r=t.shiftKey?this._host.MPP||10:1;let i;switch(t.code){case"ArrowLeft":i={x:-r,y:0};break;case"ArrowRight":i={x:r,y:0};break;case"ArrowUp":i={x:0,y:-r};break;case"ArrowDown":i={x:0,y:r}}return!!i&&(zc.around(this._host.app.commander,()=>{n.forEach(t=>{t.stuck||t.move(i,!1)})}),t.preventDefault(),t.stopPropagation(),!0)}_handleCursorHintKey(t){return!(t.repeat||!this._host?.app?.isEditMode)&&("AltLeft"===t.code||"AltRight"===t.code?(this._host?.element&&(this._host.element.style.cursor="grab"),!0):("ShiftLeft"===t.code||"ShiftRight"===t.code)&&(this._host?.element&&(this._host.element.style.cursor="crosshair"),!0))}_handleCameraAndViewKey(t){if(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)return!1;switch(t.code){case"KeyQ":case"Digit0":return this._host?.set?.("threed",!1),t.preventDefault(),!0;case"Digit1":return this.setCameraView("perspective"),t.preventDefault(),!0;case"Digit2":return this.setCameraView("top"),t.preventDefault(),!0;case"Digit3":return this.setCameraView("front"),t.preventDefault(),!0;case"Digit4":return this.setCameraView("back"),t.preventDefault(),!0;case"Digit5":return this.setCameraView("right"),t.preventDefault(),!0;case"Digit6":return this.setCameraView("left"),t.preventDefault(),!0;case"KeyH":return this.onHelpToggle?.(),t.preventDefault(),!0;case"KeyB":return this.onBookmarkNavToggle?.(),t.preventDefault(),!0;case"KeyF":return this.onSearchToggle?.(),t.preventDefault(),!0}return!1}_handlePlaybackKey(t){return!(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)&&("KeyP"!==t.code||this._host?.app?.isEditMode?"Space"===t.code&&this._host?.app?.isEditMode?(this._isSpacePanning=!0,this._beforeSpaceMode=this._host.app.mode,this._host.app.mode=2,this._host?.element&&(this._host.element.style.cursor="grab"),t.preventDefault(),!0):"Space"!==t.code||this._host?.app?.isEditMode?"KeyO"===t.code&&!this._host?.app?.isEditMode&&(this.bookmarkManager.resetPlay(),this.bookmarkManager.toggleOrbitRotation(this.controlsManager),t.preventDefault(),!0):(this.bookmarkManager.isOrbitRotating||this.bookmarkManager.isOrbitPaused?this.bookmarkManager.toggleOrbitRotation(this.controlsManager):(this.bookmarkManager.isPlaying||this.bookmarkManager.lastPlayProgress>=0)&&this.togglePlay(),t.preventDefault(),!0):(this.bookmarkManager.stopOrbitRotation(this.controlsManager),this.restartPlay(),t.preventDefault(),!0))}_onKeyUp(t){return"AltLeft"===t.code||"AltRight"===t.code||"ShiftLeft"===t.code||"ShiftRight"===t.code?(this._host?.element&&!this._isSpacePanning&&(this._host.element.style.cursor=""),!0):!("Space"!==t.code||!this._isSpacePanning)&&(this._isSpacePanning=!1,void 0!==this._beforeSpaceMode&&this._host?.app&&(this._host.app.mode=this._beforeSpaceMode,this._beforeSpaceMode=void 0),this._host?.element&&(this._host.element.style.cursor=""),t.preventDefault(),!0)}onPinch(t){if(this.controlsManager.isActive){if("perspective"!==this.cameraManager.activeView){const e=this.cameraManager.activeCamera,n=t.scale||1;e.zoom=Math.max(.1,Math.min(20,e.zoom*n)),e.updateProjectionMatrix(),this.controlsManager.markCameraChanged(),this.renderThreeD()}else{const e=t.scale||1;Math.abs(e-1)>.01&&(this.controlsManager.dollyAtCursor(1/e,0,0),this.renderThreeD())}return t.stopPropagation(),!0}return!1}onDoubleTap(){this.controlsManager.reset()}getCameraState(){const t=this._host;if(!t)return null;const e=this.cameraManager.camera;if(!e)return null;const{width:n,height:r}=t.bounds,i=Math.floor(Math.min(n,r))||1;return{view:this.cameraManager.activeView,cameraX:e.position.x/(n||1),cameraY:e.position.z/(r||1),cameraZ:e.position.y/i}}getCameraWorldState(){const t=this.cameraManager.camera;if(!t)return null;const e=this.controlsManager.target;return{position:{x:t.position.x,y:t.position.y,z:t.position.z},target:{x:e.x,y:e.y,z:e.z}}}captureSessionState(){const t=this.cameraManager.activeView,e=this.cameraManager.camera,n=this.controlsManager.target,r={view:t};return e&&(r.perspPosition={x:e.position.x,y:e.position.y,z:e.position.z}),r.orbitTarget={x:n.x,y:n.y,z:n.z},r}captureViewportInfo(){const t=this.cameraManager.activeCamera,e=this.controlsManager.target.clone();let n=0,r=0;if(t?.fov){r=2*t.position.distanceTo(e)*Math.tan(t.fov*Math.PI/180/2),n=r*(t.aspect||1)}return{target:e,visibleWidth:n,visibleHeight:r}}restoreSessionState(t){"perspective"!==t.view&&this.setCameraView(t.view,{render:!1});const e=this.cameraManager.camera;e&&t.perspPosition&&e.position.set(t.perspPosition.x,t.perspPosition.y,t.perspPosition.z),t.orbitTarget&&this.controlsManager.restoreTarget(new _.Vector3(t.orbitTarget.x,t.orbitTarget.y,t.orbitTarget.z))}saveCameraToSlot(t){if(!this._host?.app?.isEditMode)return;const e=this.cameraManager.camera;if(!e)return;if("perspective"!==this.cameraManager.activeView)return;const n=this.controlsManager.target,r=e.position;let i=n.x,s=n.y,o=n.z;if(r.distanceTo(n)<1){const t=new _.Vector3(0,0,-1).applyQuaternion(e.quaternion);i=r.x+1*t.x,s=r.y+1*t.y,o=r.z+1*t.z}const a={position:{x:r.x,y:r.y,z:r.z},target:{x:i,y:s,z:o}};this.bookmarkManager.saveSlot(t,a),this._host?.app?.isEditMode&&this._host?.set?.("cameraBookmarks",this.bookmarkManager.exportSlots()),this.onBookmarkChanged?.()}positionCameraForViewport(t,e,n,r,i){const s=this.cameraManager.activeCamera;if(!s?.position)return;const o=(s.fov||45)*Math.PI/180,a=s.aspect||1,c=r/2/Math.tan(o/2),l=n/2/(a*Math.tan(o/2)),h=Math.max(c,l),d=i?.orbitTarget?.y??0,u=new _.Vector3(t,d,e);let p;if(i?.perspPosition&&i?.orbitTarget){const t=new _.Vector3(i.perspPosition.x,i.perspPosition.y,i.perspPosition.z),e=new _.Vector3(i.orbitTarget.x,i.orbitTarget.y,i.orbitTarget.z);p=t.sub(e).normalize()}else p=s.position.clone().normalize();s.position.copy(u.clone().add(p.multiplyScalar(h)));try{this.controlsManager.restoreTarget(u)}catch{s.lookAt(u)}this._host?.invalidate()}centerToComponent(t,e){const n=this.cameraManager.activeCamera;if(!n)return;const r=new _.Vector3,i=t._realObject;if(i?.object3d)i.object3d.getWorldPosition(r);else{const{x:e=0,y:n=0}=t.center,{width:i=0,height:s=0}=t.parent?.bounds??{};r.set(e-i/2,0,n-s/2)}const s=this.controlsManager.target,o=n.position.clone().sub(s),a=r.clone().add(o);if(!e)return n.position.copy(a),this.controlsManager.restoreTarget(r),void this._host?.invalidate();const c=n.position.clone(),l=s.clone(),h=performance.now(),d=()=>{const t=performance.now()-h,e=Math.min(t/800,1),i=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;n.position.lerpVectors(c,a,i);const s=l.clone().lerp(r,i);this.controlsManager.restoreTarget(s),this._host?.invalidate(),e<1&&requestAnimationFrame(d)};requestAnimationFrame(d)}animateToSlot(t){const e=this.cameraManager.camera;e&&(this.bookmarkManager.isPlaying&&this.bookmarkManager.stopPlay(),"perspective"!==this.cameraManager.activeView&&this.setCameraView("perspective",{render:!1}),this.bookmarkManager.animateToSlot(t,e,this.controlsManager),this.bookmarkManager.setProgressForSlot(t))}scrubPath(t){const e=this.cameraManager.camera;if(!e)return;const n=this.bookmarkManager.evaluatePath(t);n&&(e.position.copy(n.position),this.controlsManager.restoreTarget(n.target),this._host?.invalidate())}togglePlay(t=-1){const e=this.cameraManager.camera;if(e){if("perspective"!==this.cameraManager.activeView&&this.setCameraView("perspective",{render:!1}),this.bookmarkManager.isPlaying)return this.bookmarkManager.stopPlay(),void(this._pathVisible&&this.showBookmarkPath());this.hideBookmarkPath(),this.bookmarkManager.startPlay(e,this.controlsManager,2e3,1200,t)}}restartPlay(){const t=this.cameraManager.camera;t&&("perspective"!==this.cameraManager.activeView&&this.setCameraView("perspective",{render:!1}),this.bookmarkManager.stopPlay(),this.hideBookmarkPath(),this.bookmarkManager.startPlay(t,this.controlsManager,2e3,1200,-1,!0))}startAutoPlay(t){"orbit"===t?this.bookmarkManager.toggleOrbitRotation(this.controlsManager):"play"===t&&this.togglePlay()}showBookmarkPath(){this._pathVisible=!0,this.hideBookmarkPath();const t=this.sceneManager.scene;if(!t)return;const e=this.bookmarkManager.getPlayableSlots();if(0===e.length)return;const n=[];for(const t of e){const e=this.bookmarkManager.getSlot(t);e&&n.push(new _.Vector3(e.position.x,e.position.y,e.position.z))}if(n.length>=2){let e=0;for(let t=1;t<n.length;t++)e+=n[t].distanceTo(n[t-1]);const r=e/(n.length-1),i=n.length>=3?new _.CatmullRomCurve3(n,!0,"centripetal").getPoints(30*n.length):n,s=(new _.BufferGeometry).setFromPoints(i),o=new _.LineDashedMaterial({color:4890367,dashSize:.06*r,gapSize:.03*r,opacity:.5,transparent:!0,depthTest:!1});this._pathLine=new _.Line(s,o),this._pathLine.computeLineDistances(),this._pathLine.renderOrder=9999,t.add(this._pathLine)}let r;if(n.length>=2){let t=0;for(let e=1;e<n.length;e++)t+=n[e].distanceTo(n[e-1]);r=t/(n.length-1)*.08}else{const t=this.bookmarkManager.getSlot(e[0]);r=.08*(t?new _.Vector3(t.position.x,t.position.y,t.position.z).distanceTo(new _.Vector3(t.target.x,t.target.y,t.target.z)):10)}this._pathMarkers=new _.Group,this._pathMarkers.renderOrder=9999;const i=new _.MeshBasicMaterial({color:4890367,opacity:.6,transparent:!0,depthTest:!1}),s=new _.MeshBasicMaterial({color:4890367,opacity:.15,transparent:!0,depthTest:!1,side:_.DoubleSide});for(const t of e){const e=this.bookmarkManager.getSlot(t);if(!e)continue;const n=new _.Vector3(e.position.x,e.position.y,e.position.z),o=new _.Vector3(e.target.x,e.target.y,e.target.z),a=(new _.Vector3).subVectors(o,n).normalize(),c=new _.Group;c.position.copy(n);const l=(new _.Matrix4).lookAt(new _.Vector3(0,0,0),a,new _.Vector3(0,1,0));c.quaternion.setFromRotationMatrix(l);const h=.2*r,d=new _.BoxGeometry(1.2*h,.8*h,h),u=new _.Mesh(d,i);u.renderOrder=9999,c.add(u);const p=Math.max(.06*n.distanceTo(o),.5*h),f=.35*p,g=9*f/16,m=new _.BufferGeometry,y=[0,0,0,-f,g,-p,f,g,-p,f,-g,-p,-f,-g,-p],b=[0,1,2,0,2,3,0,3,4,0,4,1];m.setAttribute("position",new _.Float32BufferAttribute(y,3)),m.setIndex(b),m.computeVertexNormals();const v=new _.Mesh(m,s);v.position.z=.5*-h,v.renderOrder=9999,c.add(v);const x=new Float32Array([0,0,0,-f,g,-p,0,0,0,f,g,-p,0,0,0,f,-g,-p,0,0,0,-f,-g,-p,-f,g,-p,f,g,-p,f,g,-p,f,-g,-p,f,-g,-p,-f,-g,-p,-f,-g,-p,-f,g,-p]),w=new _.BufferGeometry;w.setAttribute("position",new _.BufferAttribute(x,3));const M=new _.LineSegments(w,new _.LineBasicMaterial({color:4890367,opacity:.5,transparent:!0,depthTest:!1}));M.position.z=.5*-h,M.renderOrder=9999,c.add(M),c.userData.bookmarkSlotIndex=t,this._pathMarkers.add(c)}t.add(this._pathMarkers),this._host?.invalidate()}hideBookmarkPath(t=!1){t&&(this._pathVisible=!1);const e=this.sceneManager.scene;if(this._pathLine&&(e?.remove(this._pathLine),this._pathLine.geometry.dispose(),this._pathLine.material.dispose(),this._pathLine=void 0),this._pathMarkers){e?.remove(this._pathMarkers);const t=new Set;this._pathMarkers.traverse(e=>{e.geometry&&e.geometry.dispose();const n=e.material;n&&!t.has(n)&&(n.dispose(),t.add(n))}),this._pathMarkers=void 0}this._host?.invalidate()}initBookmarks(){const t=this._host;if(!t)return;const e=t.state.cameraBookmarks;Array.isArray(e)&&this.bookmarkManager.importSlots(e),this.bookmarkManager.setCallbacks(()=>this._host?.invalidate())}onchange(t){if(t.hasOwnProperty("autoRotate")&&this.controlsManager.setAutoRotate(t.autoRotate),t.hasOwnProperty("fov")||t.hasOwnProperty("near")||t.hasOwnProperty("far")){const t=this._host;if(t){const{near:e,far:n,fov:r}=t.state;this.cameraManager.updateProperties({near:e,far:n,fov:r}),this.controlsManager.markCameraChanged()}}let e=!1;if(t.hasOwnProperty("hemiIntensity")&&(this.lightManager.updateHemisphere({intensity:t.hemiIntensity}),e=!0),t.hasOwnProperty("dirLightEnabled")){const n=this._host;n&&this.lightManager.setDirectionalEnabled(t.dirLightEnabled,{color:n.state.dirLightColor,intensity:n.state.dirLightIntensity}),e=!0}(t.hasOwnProperty("dirLightColor")||t.hasOwnProperty("dirLightIntensity"))&&(this.lightManager.updateDirectional({color:t.dirLightColor,intensity:t.dirLightIntensity}),e=!0),e&&this.renderThreeD(),(t.hasOwnProperty("fillStyle")||t.hasOwnProperty("floorMaterial3d"))&&(this.sceneManager.updateFloor(this._host),this.renderThreeD()),(t.hasOwnProperty("sky")||t.hasOwnProperty("skyColor"))&&(this.sceneManager.setSky(this._host.state.sky,this._host.state.skyColor),this.renderThreeD())}get domElement(){return this.rendererManager.domElement}getRendererSize(){return this.rendererManager.getSize()}showWebglNoSupportText(t,e,n){t.save(),t.font=e/20+"px Arial",t.textAlign="center",t.fillText("WebGL no support",e/2-e/40,n/2),t.restore()}showDebugFPS(t){t.font="100px Arial",t.textAlign="center",t.fillStyle="black",t.globalAlpha=.5,t.fillText(String(ql()),100,100)}get decoratorOutlines(){return this._decoratorOutlines}addOutline(t){this._decoratorOutlines.add(t),this._syncOutlinePass(),this._host?.invalidate()}removeOutline(t){this._decoratorOutlines.delete(t),this._syncOutlinePass(),this._host?.invalidate()}clearOutlines(){this._decoratorOutlines.clear(),this._syncOutlinePass(),this._host?.invalidate()}addArrow(t,e,n,r={}){this.removeArrow(t);const i=e._realObject,s=n._realObject;if(!i?.object3d||!s?.object3d)return;const o=new _.Vector3,a=new _.Vector3;i.object3d.getWorldPosition(o),s.object3d.getWorldPosition(a),o.y+=1,a.y+=1;const c=this.rendererManager.getSize(),l=nh(o,a,r,new _.Vector2(c.width,c.height));l.name=`arrow-${t}`,l.userData._arrowStyle=r,this.sceneManager.scene?.add(l),this._arrows.set(t,l),this._host?.invalidate()}removeArrow(t){const e=this._arrows.get(t);e&&(e.traverse(t=>{if(t instanceof r.Line2)return t.geometry.dispose(),void t.material.dispose();if(t instanceof _.Sprite){const e=t.material.map;if(e){e.dispose();const t=e.source?.data;t instanceof HTMLCanvasElement&&(t.width=0,t.height=0)}return void t.material.dispose()}(t instanceof _.Mesh||t instanceof _.Line)&&(t.geometry.dispose(),t.material instanceof _.Material&&t.material.dispose())}),e.removeFromParent(),this._arrows.delete(t),this._host?.invalidate())}clearArrows(){for(const t of this._arrows.keys())this.removeArrow(t)}updateArrow(t,e,n){const r=this._getArrowStyle(t);r&&this.addArrow(t,e,n,r)}_getArrowStyle(t){const e=this._arrows.get(t);return e?e.userData._arrowStyle??null:null}highlightBookmarkMarker(t){this._highlightedMarkerIndex!==t&&(this._highlightedMarkerIndex=t,this._syncOutlinePass(),this._host?.invalidate())}clearBookmarkMarkerHighlight(){-1!==this._highlightedMarkerIndex&&(this._highlightedMarkerIndex=-1,this._syncOutlinePass(),this._host?.invalidate())}_syncOutlinePass(){const t=[...this._selectionOutlineObjects];for(const e of this._decoratorOutlines){const n=e._realObject;n?.object3d&&!t.includes(n.object3d)&&t.push(n.object3d)}if(this._highlightedMarkerIndex>=0&&this._pathMarkers)for(const e of this._pathMarkers.children)if(e.userData.bookmarkSlotIndex===this._highlightedMarkerIndex){e.traverse(e=>{e.isMesh&&t.push(e)});break}this.rendererManager.setOutlineObjects(t)}_handleSelectionChanged(t){const e=t.filter(t=>t!==this._host&&t._realObject);if(e.length>=1){const t=e[0]._realObject;t?.object3d&&t.gizmoTransformable?this.gizmoManager.attached&&this.gizmoManager.attach(t.object3d):this.gizmoManager.detach()}else this.gizmoManager.detach();const n=e.filter(t=>t.mutable&&t.path);n.length>0&&this.sceneManager.scene?this.vertexGizmoManager.attachMultiple(n,this.sceneManager.scene,this._host?.app?.commander):this.vertexGizmoManager.detach(),this._updateSelectionOutline(e),this._host?.invalidate()}_updateSelectionOutline(t){this._selectionOutlineObjects=[];for(const e of t){const t=e._realObject;t?.object3d&&this._selectionOutlineObjects.push(t.object3d)}this._syncOutlinePass()}}Wa.register("three",{reflow:function(t){},capturables:function(t){return t.state.threed?[]:t.components},drawables:function(t){return t.state.threed?[]:t.components},isStuck:function(t){return!1}});const Zh={x:1,y:1},Jh={x:0,y:0},td='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M4 5l12-1v12l-12-1z"/>\n <circle cx="10" cy="10" r="1.5"/>\n</svg>',ed='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <rect x="4" y="4" width="12" height="12" rx="1"/>\n <path d="M10 2v2M10 16v2"/>\n <path d="M10 7v3l2-1.5" opacity="0.5"/>\n</svg>',nd='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M4 14l2-10h8l2 10z"/>\n <path d="M6 4h8" stroke-width="2"/>\n</svg>',rd='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M4 6l2 10h8l2-10z"/>\n <path d="M6 16h8" stroke-width="2"/>\n</svg>',id='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M6 4l10 2v8l-10 2z"/>\n <path d="M16 6v8" stroke-width="2"/>\n</svg>',sd='<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M14 4L4 6v8l10 2z"/>\n <path d="M4 6v8" stroke-width="2"/>\n</svg>',od={mutable:!1,resizable:!0,rotatable:!1,properties:[{type:"number",label:"width",name:"width"},{type:"number",label:"height",name:"height"},{type:"select",label:"fit-mode",name:"fitMode",property:{options:["ratio","both","width","height","center","none"]}}]};class ad extends mc{get nature(){return od}get is3dMode(){return!!this._threeCapability?.isInitialized}is3dContainer(){return this.is3dMode}get gizmoMode(){return this._threeCapability?.gizmoMode}setGizmoMode(t){this._threeCapability?.setGizmoMode(t)}get scene3d(){return this._threeCapability?.scene3d}get renderer3d(){return this._threeCapability?.renderer3d}get activeCamera3d(){return this._threeCapability?.activeCamera}get mixer(){return this._threeCapability?.mixer}addArrow3D(t,e,n,r){this._threeCapability?.addArrow(t,e,n,r)}removeArrow3D(t){this._threeCapability?.removeArrow(t)}clearArrows3D(){this._threeCapability?.clearArrows()}_buildLightingConfig(){const t=this.state,e={hemisphere:{skyColor:16777215,groundColor:4473924,intensity:t.hemiIntensity??1}};return!1!==t.dirLightEnabled&&(e.directional={color:t.dirLightColor||"#ffffff",intensity:t.dirLightIntensity??.8,attachToCamera:!0,castShadow:!1!==t.dirShadowEnabled,shadowMapSize:t.dirShadowMapSize??2048,shadowBias:t.dirShadowBias??-5e-4}),e}_hide2DLayers(){this.canvas&&(this.canvas.style.display="none"),this._overlay&&(this._overlay.style.display="none"),this._auxCanvas&&(this._auxCanvas.style.display="none"),this._decoratorAuxOverlay&&(this._decoratorAuxOverlay.style.display="none");for(const t of this.root?.assist_layers||[])t.element&&(t.element.style.display="none")}get _hasZoomHandler(){return(this.root?.model?.handlers||[]).includes("zoom-handler")}get _needsViewportSync(){return!!this.app?.isEditMode||this._hasZoomHandler}_activateThreeD(t=!1){this._threeCapability&&this._deactivateThreeD(),t&&!this._needsViewportSync&&(this._saved2DViewport={scale:{...this.get("scale")||{x:1,y:1}},translate:{...this.get("translate")||{x:0,y:0}}}),this._threeCapability=new Qh,this._threeCapability.init(this,{lightingConfig:this._buildLightingConfig(),css3DSceneAttribute:"model-layer:css3d-renderer"}),this._hide2DLayers();const e=bs.getInstance(),n=[];this.decoratorOverlay&&(n.push(...e.getTargetsWithType(this.decoratorOverlay,"border-highlighting")),e.removeAllFromOverlay(this.decoratorOverlay,"border-highlighting")),this.decoratorAuxOverlay&&(n.push(...e.getTargetsWithType(this.decoratorAuxOverlay,"border-highlighting")),e.removeAllFromOverlay(this.decoratorAuxOverlay,"border-highlighting"));for(const t of n)this._threeCapability.addOutline(t);if(this._threeCapability.domElement&&this.element){const t=this._threeCapability.domElement;t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.pointerEvents="none",t.setAttribute("scene","model-layer-webgl");const e=this._decoratorOverlay||this.element.firstChild;this.element.insertBefore(t,e)}if(this._threeCapability.buildOverlays(),t&&this._needsViewportSync)this._initCameraFrom2DViewport();else if(this._lastCameraState)this._threeCapability.restoreSessionState(this._lastCameraState);else{const t=this.model.initialCameraView;t&&"perspective"!==t&&this._threeCapability.setCameraView(t,{render:!1})}if(this._pendingCameraView&&(this._threeCapability.setCameraView(this._pendingCameraView,{render:!1}),delete this._pendingCameraView),this._threeCapability.initBookmarks(),!this.app?.isEditMode){const t=this.model?.cameraAutoPlay;"orbit"!==t&&"play"!==t||this._threeCapability.startAutoPlay(t)}this.app?.isEditMode&&this._createToolbar(),this._registerPopupCallbacks();const r=this.root;r?.selected?.length>0&&this._threeCapability._handleSelectionChanged(r.selected),this._resizeThreeD(!0),this.element&&"function"==typeof this.element.focus&&this.element.focus()}_createToolbar(){if(!this.element)return;this._removeToolbar();const t=!!this._threeCapability,e=document.createElement("div");e.setAttribute("scene","threed-toolbar"),e.style.cssText=["position:absolute","top:12px","left:12px","display:flex","flex-direction:column","gap:1px","padding:4px","background:rgba(30,30,30,0.92)","border:1px solid rgba(255,255,255,0.08)","border-radius:8px","pointer-events:auto","backdrop-filter:blur(8px)","-webkit-backdrop-filter:blur(8px)","box-shadow:0 4px 16px rgba(0,0,0,0.4),inset 0 1px 0 rgba(255,255,255,0.05)","user-select:none"].join(";");const n=["width:32px","height:32px","display:flex","align-items:center","justify-content:center","border-radius:5px","cursor:pointer","transition:all 0.12s ease","position:relative"].join(";"),r=(t,e)=>{const r=document.createElement("div");return r.innerHTML=t,r.title=e,r.style.cssText=n,this._applyButtonStyle(r,!1),r.addEventListener("mouseenter",()=>{r.dataset.active||(r.style.background="rgba(255,255,255,0.1)")}),r.addEventListener("mouseleave",()=>{this._applyButtonStyle(r,!!r.dataset.active)}),r},i=()=>{const t=document.createElement("div");return t.style.cssText="height:1px;margin:3px 4px;background:rgba(255,255,255,0.1)",t},s=r(t?'<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <rect x="3" y="3" width="14" height="14" rx="1.5"/>\n <line x1="3" y1="10" x2="17" y2="10" opacity="0.4"/>\n <line x1="10" y1="3" x2="10" y2="17" opacity="0.4"/>\n </svg>':'<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M10 2l7 4v8l-7 4-7-4V6l7-4z"/>\n <path d="M10 10l7-4M10 10v8M10 10L3 6"/>\n </svg>',t?"2D Mode":"3D Mode");if(this._applyToggleStyle(s,t),s.addEventListener("mouseenter",()=>{s.style.background=t?"rgba(255,160,60,0.35)":"rgba(255,160,60,0.25)"}),s.addEventListener("mouseleave",()=>{this._applyToggleStyle(s,t)}),s.addEventListener("click",()=>{this.set("threed",!this.model.threed)}),e.appendChild(s),!t)return e.addEventListener("mousedown",t=>t.stopPropagation()),e.addEventListener("mouseup",t=>t.stopPropagation()),this.target.appendChild(e),void(this._toolbar=e);e.appendChild(i());const o=this._threeCapability,a=document.createElement("div");a.style.cssText="display:flex;flex-direction:column;gap:1px";const c=o.getCameraState()?.view??"perspective",l=[{view:"perspective",icon:td,title:"Perspective"},{view:"top",icon:ed,title:"Top"},{view:"front",icon:nd,title:"Front"},{view:"back",icon:rd,title:"Back"},{view:"right",icon:id,title:"Right"},{view:"left",icon:sd,title:"Left"}],h=[];for(const{view:t,icon:e,title:n}of l){const i=r(e,n);i.dataset.view=t,t===c&&(this._applyButtonStyle(i,!0),i.dataset.active="1"),i.addEventListener("click",()=>{this._threeCapability?.setCameraView(t)}),h.push(i),a.appendChild(i)}a.appendChild(i());const d=r('<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <path d="M10 2 L13 5 L12 10 L15 13 L5 13 L8 10 L7 5 Z"/>\n <line x1="10" y1="13" x2="10" y2="18"/>\n </svg>',"Pin Camera View");d.addEventListener("click",()=>{const t=this._threeCapability?.getCameraState();t&&(this.set("cameraX",t.cameraX),this.set("cameraY",t.cameraY),this.set("cameraZ",t.cameraZ),this._threeCapability?.pinResetPosition())}),a.appendChild(d),e.appendChild(a),this._cameraButtons=h,o.onGizmoAttachChanged=t=>{this.root?.trigger("gizmoattach",t)},o.onCameraViewChanged=t=>{this._updateCameraButtons(t)},o.onGizmoModeChanged=t=>{this.root?.trigger("gizmomode",t)},e.addEventListener("mousedown",t=>{t.stopPropagation(),t.preventDefault()}),e.addEventListener("mouseup",t=>t.stopPropagation()),this.target.appendChild(e),this._toolbar=e}_applyToggleStyle(t,e){e?(t.style.background="rgba(255,140,40,0.3)",t.style.color="#ffaa44",t.style.boxShadow="inset 0 0 0 1.5px rgba(255,140,40,0.5)"):(t.style.background="rgba(255,140,40,0.15)",t.style.color="#cc8833",t.style.boxShadow="inset 0 0 0 1.5px rgba(255,140,40,0.3)")}_applyButtonStyle(t,e){e?(t.style.background="rgba(74,158,255,0.25)",t.style.color="#4a9eff",t.style.boxShadow="inset 0 0 0 1.5px rgba(74,158,255,0.5)",t.dataset.active="1"):(t.style.background="transparent",t.style.color="rgba(255,255,255,0.55)",t.style.boxShadow="none",delete t.dataset.active)}_updateCameraButtons(t){this._cameraButtons?.forEach(e=>{this._applyButtonStyle(e,e.dataset.view===t)})}_registerPopupCallbacks(){const t=this._threeCapability;t&&(t.onHelpToggle=()=>this._toggleHelpPanel(),t.onSearchToggle=()=>this.onSearchToggle?.(),t.onBookmarkNavToggle=()=>this._toggleBookmarkNav(),t.onBookmarkEditToggle=()=>this._toggleBookmarkEdit())}_closeFloatingPopup(){this._floatingPopupCloseHandler&&(this.target?.removeEventListener("mousedown",this._floatingPopupCloseHandler,!0),this._floatingPopupCloseHandler=void 0),this._floatingPopup?.parentNode&&this._floatingPopup.parentNode.removeChild(this._floatingPopup),this._floatingPopup=void 0}_showFloatingPopup(t,e=!1){this._closeFloatingPopup(),this._floatingPopup=t,e||(this._floatingPopupCloseHandler=e=>{t.contains(e.target)||this._closeFloatingPopup()},setTimeout(()=>{this.target?.addEventListener("mousedown",this._floatingPopupCloseHandler,!0)},0)),t.addEventListener("mousedown",t=>{t.stopPropagation();const e=t.target?.tagName;"INPUT"!==e&&"TEXTAREA"!==e&&"SELECT"!==e&&t.preventDefault()}),t.addEventListener("mouseup",t=>t.stopPropagation()),this._makePopupDraggable(t),this.target.appendChild(t)}_makePopupDraggable(t){let e=0,n=0,r=0,i=0;const s=s=>{const o=s.clientX-e,a=s.clientY-n;t.style.left=r+o+"px",t.style.top=i+a+"px"},o=e=>{t.releasePointerCapture(e.pointerId),t.removeEventListener("pointermove",s),t.removeEventListener("pointerup",o),t.style.cursor=""};t.addEventListener("pointerdown",a=>{const c=a.target,l=c.tagName?.toLowerCase();if("button"===l||"input"===l||"select"===l||"pointer"===c.style.cursor)return;if(c.closest("[data-drag-handle]"))return;const h=t.getBoundingClientRect(),d=t.parentElement.getBoundingClientRect();r=h.left-d.left,i=h.top-d.top,t.style.left=r+"px",t.style.top=i+"px",t.style.right="auto",t.style.bottom="auto",t.style.transform="none",e=a.clientX,n=a.clientY,t.style.cursor="grabbing",t.setPointerCapture(a.pointerId),t.addEventListener("pointermove",s),t.addEventListener("pointerup",o)})}_toggleHelpPanel(){if("help"===this._floatingPopup?.dataset.popupType)return void this._closeFloatingPopup();const t=!!this.app?.isEditMode,e=document.createElement("div");e.dataset.popupType="help",e.style.cssText=["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)","max-width:min(560px, calc(100% - 40px))","max-height:calc(100% - 40px)","overflow-y:auto","padding:16px 20px","background:rgba(30,30,30,0.94)","border:1px solid rgba(255,255,255,0.08)","border-radius:10px","pointer-events:auto","backdrop-filter:blur(8px)","-webkit-backdrop-filter:blur(8px)","box-shadow:0 4px 20px rgba(0,0,0,0.5)","user-select:none","color:rgba(255,255,255,0.85)","font:12px/1.6 -apple-system,BlinkMacSystemFont,sans-serif","z-index:200"].join(";");const n=document.createElement("div");n.textContent="×",n.style.cssText="position:absolute;top:8px;right:12px;cursor:pointer;font-size:18px;color:rgba(255,255,255,0.4);line-height:1",n.addEventListener("click",()=>this._closeFloatingPopup()),n.addEventListener("mouseenter",()=>{n.style.color="#fff"}),n.addEventListener("mouseleave",()=>{n.style.color="rgba(255,255,255,0.4)"}),e.appendChild(n);const r=document.createElement("div");r.textContent="Help",r.style.cssText="font-size:13px;font-weight:600;color:#4a9eff;margin-bottom:12px",e.appendChild(r);const i=document.createElement("div");i.style.cssText="display:grid;grid-template-columns:1fr 1fr;gap:0 24px",e.appendChild(i);const s=[{label:"Camera",items:[{key:"1",desc:"Perspective",icon:td},{key:"2",desc:"Top",icon:ed},{key:"3",desc:"Front",icon:nd},{key:"4",desc:"Back",icon:rd},{key:"5",desc:"Right",icon:id},{key:"6",desc:"Left",icon:sd},{key:"0 / Q",desc:"Exit 3D"}]},{label:"Bookmarks",items:[{key:"B",desc:"Bookmark navigator"},{key:"Shift+B",desc:"Bookmark editor",editOnly:!0},{key:"P",desc:"Play tour",viewOnly:!0},{key:"O",desc:"Orbit rotation",viewOnly:!0},{key:"Space",desc:"Pan mode (edit) / Pause (view)"}]},{label:"Navigation",items:[{key:"Drag",desc:"Rotate camera"},{key:"Alt+Drag",desc:"Pan camera"},{key:"Space+Drag",desc:"Pan camera (no select)",editOnly:!0},{key:"Shift+Drag",desc:"Box select",editOnly:!0},{key:"Scroll",desc:"Dolly zoom"},{key:"DblClick",desc:"Reset camera"},{key:"Arrows",desc:"Pan camera"}]},{label:"Edit",items:[{key:"W",desc:"Move gizmo",editOnly:!0},{key:"E",desc:"Rotate gizmo",editOnly:!0},{key:"R",desc:"Scale gizmo",editOnly:!0},{key:"Ctrl+Z",desc:"Undo",editOnly:!0},{key:"Ctrl+Shift+Z",desc:"Redo",editOnly:!0},{key:"Ctrl+C/X/V",desc:"Copy / Cut / Paste",editOnly:!0},{key:"Del",desc:"Delete selected",editOnly:!0},{key:"Esc",desc:"Deselect all",editOnly:!0}]},{label:"Misc",items:[{key:"H",desc:"This help"},{key:"F",desc:"Search"}]}].map(e=>({...e,items:e.items.filter(e=>!(e.editOnly&&!t)&&(!e.viewOnly||!t))})).filter(t=>t.items.length>0),o=s.reduce((t,e)=>t+e.items.length+1,0);let a=0,c=s.length;for(let t=0;t<s.length;t++)if(a+=s[t].items.length+1,a>=o/2){c=t+1;break}const l=[s.slice(0,c),s.slice(c)];for(const t of l){const e=document.createElement("div");let n=!0;for(const r of t){if(!n){const t=document.createElement("div");t.style.cssText="height:1px;margin:8px 0;background:rgba(255,255,255,0.08)",e.appendChild(t)}n=!1;const t=document.createElement("div");t.textContent=r.label,t.style.cssText="font-size:10px;font-weight:700;text-transform:uppercase;color:rgba(255,255,255,0.45);margin:0 0 5px;letter-spacing:0.8px",e.appendChild(t);for(const t of r.items){const n=document.createElement("div");n.style.cssText="display:flex;justify-content:space-between;align-items:center;padding:2px 0;gap:12px";const r=document.createElement("span");r.style.cssText="display:inline-flex;gap:2px;flex-shrink:0";for(const e of t.key.split("+")){const n=document.createElement("kbd");if(n.textContent=e.trim(),n.style.cssText="font-size:10px;font-family:monospace;padding:1px 5px;border-radius:3px;background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.12);color:rgba(255,255,255,0.65);line-height:1.4",r.appendChild(n),e!==t.key.split("+").at(-1)){const t=document.createElement("span");t.textContent="+",t.style.cssText="color:rgba(255,255,255,0.2);font-size:10px;margin:0 1px",r.appendChild(t)}}const i=document.createElement("span");if(i.style.cssText="font-size:11px;color:rgba(255,255,255,0.7);text-align:right;white-space:nowrap;display:inline-flex;align-items:center;gap:4px",i.appendChild(document.createTextNode(t.desc)),t.icon){const e=document.createElement("span");e.innerHTML=t.icon,e.style.cssText="display:inline-flex;opacity:0.6",i.appendChild(e)}n.appendChild(r),n.appendChild(i),e.appendChild(n)}}i.appendChild(e)}this._showFloatingPopup(e)}_toggleBookmarkNav(){"bookmark-nav"!==this._floatingPopup?.dataset.popupType?this._buildBookmarkPopup("bookmark-nav"):this._closeFloatingPopup()}_toggleBookmarkEdit(){"bookmark-edit"!==this._floatingPopup?.dataset.popupType?this._buildBookmarkPopup("bookmark-edit"):this._closeFloatingPopup()}_buildBookmarkPopup(t){const e=this._threeCapability;if(!e)return;const n="bookmark-nav"===t,r=!!this.app?.isEditMode,i=document.createElement("div");i.dataset.popupType=t,i.tabIndex=-1,i.style.cssText=["position:absolute",n?"bottom:12px":"top:12px","right:12px","min-width:"+(n?"140px":"200px"),"padding:10px 12px","background:rgba(30,30,30,0.94)","border:1px solid rgba(255,255,255,0.08)","border-radius:10px","pointer-events:auto","backdrop-filter:blur(8px)","-webkit-backdrop-filter:blur(8px)","box-shadow:0 4px 20px rgba(0,0,0,0.5)","user-select:none","color:rgba(255,255,255,0.85)","font:12px/1.5 -apple-system,BlinkMacSystemFont,sans-serif","z-index:200"].join(";");const s=document.createElement("div");s.textContent="×",s.style.cssText="position:absolute;top:6px;right:10px;cursor:pointer;font-size:18px;color:rgba(255,255,255,0.4);line-height:1",s.addEventListener("click",()=>this._closeFloatingPopup()),s.addEventListener("mouseenter",()=>{s.style.color="#fff"}),s.addEventListener("mouseleave",()=>{s.style.color="rgba(255,255,255,0.4)"}),i.appendChild(s);const o=document.createElement("div");o.textContent="Bookmarks",o.style.cssText="font-size:13px;font-weight:600;color:#4a9eff;margin-bottom:8px;cursor:grab",i.appendChild(o);const a=document.createElement("div");a.style.cssText="display:flex;flex-direction:column;gap:2px",i.appendChild(a);const c=e.bookmarkManager,l=()=>{r&&this.set?.("cameraBookmarks",c.exportSlots()),e.onBookmarkChanged?.()},h="border:none;background:transparent;color:inherit;cursor:pointer;padding:2px 4px;border-radius:4px;font-size:13px;line-height:1;display:flex;align-items:center;justify-content:center;width:24px;height:24px",d=t=>{const e=28,n=window.devicePixelRatio||1,r=document.createElement("canvas");r.width=e*n,r.height=e*n,r.style.cssText="width:28px;height:28px;flex-shrink:0;border-radius:50%;background:rgba(0,0,0,0.3)";const i=r.getContext("2d");i.scale(n,n);const s=14,o=14,a=12,c=t.position.x-t.target.x,l=t.position.z-t.target.z,h=t.position.y-t.target.y,d=Math.sqrt(c*c+l*l),u=Math.sqrt(c*c+h*h+l*l),p=u>.001?Math.max(0,h/u):0;let f=0,g=0;d>.001&&(f=c/d,g=l/d);const m=1-.6*p,y=s+f*a*.7*m,b=o+g*a*.7*m;i.strokeStyle="rgba(255,255,255,0.12)",i.lineWidth=1,i.beginPath(),i.arc(s,o,a,0,2*Math.PI),i.stroke(),i.strokeStyle="rgba(255,255,255,0.06)",i.beginPath(),i.moveTo(s,2),i.lineTo(s,26),i.moveTo(2,o),i.lineTo(26,o),i.stroke(),i.fillStyle="rgba(255,255,255,0.25)",i.beginPath(),i.arc(s,o,1.5,0,2*Math.PI),i.fill(),i.strokeStyle=`rgba(74,158,255,${.2+.2*p})`,i.lineWidth=1,i.beginPath(),i.moveTo(y,b),i.lineTo(s,o),i.stroke();const v=.6+.4*p;i.fillStyle=`rgba(74,158,255,${v})`,i.beginPath(),i.arc(y,b,3,0,2*Math.PI),i.fill();const _=Math.atan2(g,f),x=Math.PI/8;return i.fillStyle="rgba(74,158,255,0.08)",i.beginPath(),i.moveTo(y,b),i.arc(y,b,.6*a,_+Math.PI-x,_+Math.PI+x),i.closePath(),i.fill(),r},u=()=>{const t=e.getCameraWorldState();if(!t)return-1;const n=.01;for(let e=1;e<=9;e++){const r=c.getSlot(e);if(r&&(Math.abs(t.position.x-r.position.x)<n&&Math.abs(t.position.y-r.position.y)<n&&Math.abs(t.position.z-r.position.z)<n&&Math.abs(t.target.x-r.target.x)<n&&Math.abs(t.target.y-r.target.y)<n&&Math.abs(t.target.z-r.target.z)<n))return e}return-1};let p,f,g=-1;const m=()=>{a.innerHTML="";let t=!1;const r=u(),i=Array.from({length:9},(t,e)=>e+1);for(const s of i){const i=c.getSlot(s),o=!!i,u=s===r;if(n&&!o)continue;t=t||o;const p=document.createElement("div"),f=u?"rgba(74,158,255,0.1)":"transparent";if(p.style.cssText=`display:flex;align-items:center;gap:6px;padding:${n?"6px 8px":"3px 4px"};border-radius:6px;transition:background 0.15s;background:${f}${u?";box-shadow:inset 0 0 0 1px rgba(74,158,255,0.25)":""}`,p.dataset.active=u?"1":"",p.addEventListener("mouseenter",()=>{p.style.background=p.dataset.active?"rgba(74,158,255,0.15)":"rgba(255,255,255,0.06)",!n&&o&&e.highlightBookmarkMarker(s)}),p.addEventListener("mouseleave",()=>{const t=p.dataset.active;p.style.background=t?"rgba(74,158,255,0.1)":"transparent",n||e.clearBookmarkMarkerHighlight()}),n){if(o&&i){const t=d(i);t.style.pointerEvents="none",p.appendChild(t)}const t=document.createElement("span");t.textContent=i?.name||"noname",t.style.cssText=`flex:1;color:${i?.name?"rgba(255,255,255,0.8)":"rgba(255,255,255,0.35)"};font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none;${i?.name?"":"font-style:italic"}`,p.appendChild(t),p.style.cursor="pointer",p.addEventListener("click",()=>{e.animateToSlot(s)})}else{const t=document.createElement("div");t.textContent="⠿";const n=o,r=o?"color:rgba(255,255,255,0.3)":"color:rgba(255,255,255,0.12)";if(t.style.cssText=`width:16px;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;user-select:none;${r}${n?";cursor:grab":""}`,n&&(t.dataset.dragHandle="1",t.addEventListener("mouseenter",()=>{t.style.color="rgba(255,255,255,0.6)"}),t.addEventListener("mouseleave",()=>{t.style.color="rgba(255,255,255,0.3)"})),p.appendChild(t),o&&i){const t=d(i);t.style.pointerEvents="none",p.appendChild(t)}o&&(p.style.cursor="pointer",p.addEventListener("click",t=>{const n=t.target.tagName;"INPUT"!==n&&"BUTTON"!==n&&e.animateToSlot(s)}));const a=document.createElement("input");a.type="text",a.value=i?.name||"",a.placeholder=o?"noname":"Empty",a.style.cssText=`width:80px;font-size:12px;color:${o?"rgba(255,255,255,0.7)":"rgba(255,255,255,0.3)"};background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,0.1);outline:none;padding:2px 0;min-width:0`,a.addEventListener("focus",()=>{a.style.borderBottomColor="rgba(74,158,255,0.5)",a.style.color="rgba(255,255,255,0.9)"}),a.addEventListener("blur",()=>{a.style.borderBottomColor="rgba(255,255,255,0.1)",a.style.color=o?"rgba(255,255,255,0.7)":"rgba(255,255,255,0.3)",o&&(c.renameSlot(s,a.value.trim()),l())}),a.addEventListener("keydown",t=>{t.stopPropagation(),t.isComposing||"Enter"!==t.key||a.blur()}),p.appendChild(a);const u=document.createElement("div");if(u.style.cssText="display:flex;gap:2px;flex-shrink:0",o){const t=document.createElement("button");t.textContent="📌",t.title="Overwrite with current view",t.style.cssText=h+";color:#ffaa44",t.addEventListener("mouseenter",()=>{t.style.background="rgba(255,170,68,0.15)"}),t.addEventListener("mouseleave",()=>{t.style.background="transparent"}),t.addEventListener("click",()=>{e.saveCameraToSlot(s),m()}),u.appendChild(t);const n=document.createElement("button");n.textContent="🗑",n.title="Delete this slot",n.style.cssText=h+";color:#ff6b6b",n.addEventListener("mouseenter",()=>{n.style.background="rgba(255,107,107,0.15)"}),n.addEventListener("mouseleave",()=>{n.style.background="transparent"}),n.addEventListener("click",()=>{c.clearSlot(s),l(),m()}),u.appendChild(n);const r=document.createElement("button");r.textContent="⋮",r.title="Playlist settings",r.style.cssText=h+";color:rgba(255,255,255,0.35);font-size:14px",r.addEventListener("mouseenter",()=>{r.style.background="rgba(255,255,255,0.08)"}),r.addEventListener("mouseleave",()=>{r.style.background="transparent"}),u.appendChild(r)}else{const t=document.createElement("button");t.textContent="📌",t.title="Save current view here",t.style.cssText=h+";color:#4ade80",t.addEventListener("mouseenter",()=>{t.style.background="rgba(74,222,128,0.15)"}),t.addEventListener("mouseleave",()=>{t.style.background="transparent"}),t.addEventListener("click",()=>{e.saveCameraToSlot(s),m()}),u.appendChild(t)}p.appendChild(u)}const y=document.createElement("div");if(y.dataset.slotIndex=String(s),y.dataset.filled=o?"1":"",y.appendChild(p),!n&&o){const t=p.querySelector("[data-drag-handle]");t&&t.addEventListener("pointerdown",e=>{e.preventDefault(),e.stopPropagation(),y.style.opacity="0.3",y.style.pointerEvents="none",y.style.outline="1px dashed rgba(74,158,255,0.4)",y.style.borderRadius="4px",t.style.cursor="grabbing";const n=document.createElement("div");n.style.cssText="height:2px;background:#4a9eff;border-radius:1px;margin:1px 0",t.setPointerCapture(e.pointerId);const r=t=>{const e=Array.from(a.querySelectorAll('[data-slot-index][data-filled="1"]'));n.parentNode&&n.parentNode.removeChild(n);let r=null;for(const n of e){if(n===y)continue;const e=n.getBoundingClientRect();if(t.clientY<e.top+e.height/2){r=n;break}}if(r)a.insertBefore(n,r);else{const t=e[e.length-1];t&&t.after(n)}},i=e=>{t.releasePointerCapture(e.pointerId),t.removeEventListener("pointermove",r),t.removeEventListener("pointerup",i),y.style.cssText="",t.style.cursor="grab";const s=Array.from(a.querySelectorAll('[data-slot-index][data-filled="1"]'));n.parentNode&&(a.insertBefore(y,n),n.parentNode.removeChild(n));const o=Array.from(a.querySelectorAll('[data-slot-index][data-filled="1"]')).map(t=>parseInt(t.dataset.slotIndex)).map(t=>{const e=c.getSlot(t);return e?{...e,name:e.name}:void 0}),h=s.map(t=>parseInt(t.dataset.slotIndex)).sort((t,e)=>t-e);o.forEach((t,e)=>{const n=h[e];t?c.saveSlot(n,t):c.clearSlot(n)}),l(),m()};t.addEventListener("pointermove",r),t.addEventListener("pointerup",i)})}if(!n&&o&&i){const t=document.createElement("div");t.dataset.slotDetail="1";const e=g===s;t.style.cssText=`display:${e?"block":"none"};margin:2px 0 4px 26px;padding:6px 8px;background:rgba(255,255,255,0.03);border-radius:4px;border:1px solid rgba(255,255,255,0.06)`;const n="width:50px;font-size:11px;color:rgba(255,255,255,0.7);background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.12);border-radius:3px;padding:2px 4px;outline:none;text-align:right",r="font-size:10px;color:rgba(255,255,255,0.45);white-space:nowrap",o="display:flex;align-items:center;gap:6px;margin-bottom:4px",c=document.createElement("div");c.style.cssText=o;const h=document.createElement("span");h.textContent="Hold",h.style.cssText=r+";width:55px";const d=document.createElement("input");d.type="number",d.min="0",d.step="500",d.value=String(i.holdDuration??2e3),d.style.cssText=n;const u=document.createElement("span");u.textContent="ms",u.style.cssText=r,d.addEventListener("change",()=>{const t=parseInt(d.value);i.holdDuration=isNaN(t)?void 0:Math.max(0,t),l()}),d.addEventListener("keydown",t=>t.stopPropagation()),c.appendChild(h),c.appendChild(d),c.appendChild(u),t.appendChild(c);const f=document.createElement("div");f.style.cssText=o;const m=document.createElement("span");m.textContent="Transition",m.style.cssText=r+";width:55px";const b=document.createElement("input");b.type="number",b.min="0",b.step="200",b.value=String(i.transitionDuration??1200),b.style.cssText=n;const v=document.createElement("span");v.textContent="ms",v.style.cssText=r,b.addEventListener("change",()=>{const t=parseInt(b.value);i.transitionDuration=isNaN(t)?void 0:Math.max(0,t),l()}),b.addEventListener("keydown",t=>t.stopPropagation()),f.appendChild(m),f.appendChild(b),f.appendChild(v),t.appendChild(f);const _=document.createElement("div");_.style.cssText=o;const x=document.createElement("span");x.textContent="Easing",x.style.cssText=r+";width:55px";const w=document.createElement("select");w.style.cssText="font-size:11px;color:rgba(255,255,255,0.7);background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.12);border-radius:3px;padding:2px 4px;outline:none";for(const t of["ease-in-out","ease-in","ease-out","linear"]){const e=document.createElement("option");e.value=t,e.textContent=t,e.style.cssText="background:#2a2a2a;color:#ccc",(i.easing??"ease-in-out")===t&&(e.selected=!0),w.appendChild(e)}w.addEventListener("change",()=>{i.easing="ease-in-out"===w.value?void 0:w.value,l()}),_.appendChild(x),_.appendChild(w),t.appendChild(_);const M=document.createElement("div");M.style.cssText=o+";margin-bottom:0";const S=document.createElement("span");S.textContent="Skip in play",S.style.cssText=r+";width:55px";const A=document.createElement("input");A.type="checkbox",A.checked=!!i.excludeFromPlay,A.style.cssText="accent-color:#4a9eff;cursor:pointer",A.addEventListener("change",()=>{i.excludeFromPlay=A.checked||void 0,l()}),M.appendChild(S),M.appendChild(A),t.appendChild(M),y.appendChild(t);const E=p.querySelector("button:last-child");E&&(e&&(E.style.color="#4a9eff"),E.addEventListener("click",()=>{const e="none"!==t.style.display;a.querySelectorAll("[data-slot-detail]").forEach(e=>{if(e!==t&&"none"!==e.style.display){e.style.display="none";const t=e.parentElement?.firstElementChild?.querySelector("button:last-child");t&&(t.style.color="rgba(255,255,255,0.35)")}}),t.style.display=e?"none":"block",E.style.color=e?"rgba(255,255,255,0.35)":"#4a9eff",g=e?-1:s}))}a.appendChild(y)}if(!t){const t=document.createElement("div");if(t.textContent=n?"No bookmarks defined":"No bookmarks saved",t.style.cssText="color:rgba(255,255,255,0.3);font-size:12px;text-align:center;padding:12px 0",a.appendChild(t),!n){const t=document.createElement("div");t.textContent="Use 📌 to save camera positions",t.style.cssText="color:rgba(255,255,255,0.2);font-size:11px;text-align:center;padding:0 0 4px",a.appendChild(t)}}p&&(p.style.display=c.getPlayableSlots().length>=2?"block":"none")};if(m(),!n){p=document.createElement("div"),p.style.cssText="display:none;margin-top:6px;padding:4px 8px;border-top:1px solid rgba(255,255,255,0.06)";const t=document.createElement("div");t.style.cssText="display:flex;align-items:center;gap:6px";const n=document.createElement("input");n.type="range",n.min="0",n.max="1000",n.value="0",n.tabIndex=-1,n.style.cssText="flex:1;min-width:0;margin:0;height:14px;cursor:grab;accent-color:#4a9eff;outline:none";const r=document.createElement("button");r.textContent="▶",r.title="Play / Stop",r.style.cssText="border:none;background:rgba(255,255,255,0.06);color:rgba(255,255,255,0.5);cursor:pointer;font-size:12px;padding:3px 6px;border-radius:4px;line-height:1;flex-shrink:0",r.addEventListener("mouseenter",()=>{r.style.background="rgba(74,158,255,0.15)",r.style.color="#4a9eff"}),r.addEventListener("mouseleave",()=>{r.style.background="rgba(255,255,255,0.06)",r.style.color=c.isPlaying?"#4a9eff":"rgba(255,255,255,0.5)"}),r.addEventListener("click",()=>{const t=c.isPlaying?-1:parseInt(n.value)/1e3;e.togglePlay(t),a()}),n.addEventListener("focus",()=>n.blur());let s=!1;n.addEventListener("mousedown",()=>{s=!0,n.style.cursor="grabbing",c.isPlaying&&(e.togglePlay(),a())}),n.addEventListener("input",()=>{const t=parseInt(n.value)/1e3;e.scrubPath(t)});const o=()=>{s&&(s=!1,n.style.cursor="grab")};n.addEventListener("mouseup",o),n.addEventListener("mouseleave",o),i.addEventListener("keydown",t=>{if("Space"===t.code&&"none"!==p.style.display){t.preventDefault(),t.stopPropagation();const r=c.isPlaying?-1:parseInt(n.value)/1e3;e.togglePlay(r),a()}}),t.appendChild(n),t.appendChild(r),p.appendChild(t),i.appendChild(p);const a=()=>{const t=c.isPlaying;r.textContent=t?"⏹":"▶",r.style.color=t?"#4a9eff":"rgba(255,255,255,0.5)"};let l=-1;const h=()=>{if(this._floatingPopup===i){if(c.isPlaying){const t=c.playProgress;n.value=String(Math.round(1e3*t)),l=-1}else{"⏹"===r.textContent&&a();const t=c.lastPlayProgress;t>=0&&t!==l&&(n.value=String(Math.round(1e3*t)),l=t)}f=requestAnimationFrame(h)}};f=requestAnimationFrame(h);(()=>{const t=c.getPlayableSlots().length;p.style.display=t>=2?"block":"none"})()}if(!n){const t=document.createElement("button"),e="display:block;width:100%;margin-top:8px;padding:5px 0;border:1px solid rgba(255,255,255,0.12);border-radius:6px;background:transparent;color:rgba(255,255,255,0.45);font-size:11px;cursor:pointer;transition:all 0.15s";r&&(t.textContent="Clear All",t.style.cssText=e,t.addEventListener("mouseenter",()=>{t.style.borderColor="rgba(255,107,107,0.4)",t.style.color="#ff6b6b"}),t.addEventListener("mouseleave",()=>{t.style.borderColor="rgba(255,255,255,0.12)",t.style.color="rgba(255,255,255,0.45)"}),t.addEventListener("click",()=>{c.resetAll(),l(),m()})),i.appendChild(t)}const y=e.onBookmarkChanged;e.onBookmarkChanged=()=>{y?.(),this._floatingPopup===i&&(m(),v=-2,n||e.showBookmarkPath())},this._showFloatingPopup(i,!0),n||e.showBookmarkPath();let b,v=u();const _=()=>{if(this._floatingPopup!==i)return;const t=u();if(t!==v){v=t;a.querySelectorAll("[data-slot-index]").forEach(e=>{const n=parseInt(e.dataset.slotIndex||"-1"),r=e.firstElementChild;if(!r)return;const i=n===t,s=i?"rgba(74,158,255,0.1)":"transparent";r.style.background=s,r.style.boxShadow=i?"inset 0 0 0 1px rgba(74,158,255,0.25)":"none",r.dataset.active=i?"1":""})}b=requestAnimationFrame(_)};b=requestAnimationFrame(_);const x=this._closeFloatingPopup.bind(this);this._closeFloatingPopup=()=>{void 0!==b&&cancelAnimationFrame(b),void 0!==f&&cancelAnimationFrame(f),c.isPlaying&&e.togglePlay(),e.clearBookmarkMarkerHighlight(),e.hideBookmarkPath(!0),this._closeFloatingPopup=x,x()}}_removeToolbar(){this._closeFloatingPopup(),this._threeCapability&&(this._threeCapability.onGizmoModeChanged=void 0,this._threeCapability.onGizmoAttachChanged=void 0,this._threeCapability.onCameraViewChanged=void 0,this._threeCapability.onBookmarkChanged=void 0,this._threeCapability.onHelpToggle=void 0,this._threeCapability.onSearchToggle=void 0,this._threeCapability.onBookmarkNavToggle=void 0,this._threeCapability.onBookmarkEditToggle=void 0),this._toolbar?.parentNode&&this._toolbar.parentNode.removeChild(this._toolbar),this._toolbar=void 0,this._cameraButtons=void 0}_resizeThreeD(t=!1){if(!this._threeCapability||!this.element)return;const e=this.canvas?.clientWidth??0,n=this.canvas?.clientHeight??0,r=e>0?e:this.element.clientWidth,i=n>0?n:this.element.clientHeight;r>0&&i>0&&this._threeCapability.resize(r,i,t)}detachThreeCapability(){const t=this._threeCapability;if(t)return t.forceCleanupDragState(),t.clearAllObjects(),this._threeCapability=void 0,t}adoptThreeCapability(t){this._threeCapability=t,this._hide2DLayers();const e=t.domElement;if(e&&this.element){e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.pointerEvents="none",e.setAttribute("scene","model-layer-webgl");const t=this._decoratorOverlay||this.element.firstChild;this.element.insertBefore(e,t)}t.buildOverlays(),t.rebuildForHost(this,{lightingConfig:this._buildLightingConfig(),css3DSceneAttribute:"model-layer:css3d-renderer"}),this.app?.isEditMode&&this._createToolbar(),this._registerPopupCallbacks(),this._resizeThreeD(!0)}_deactivateThreeD(){if(!this._threeCapability)return;this._removeToolbar(),this._lastCameraState=this._threeCapability.captureSessionState();const{target:t,visibleWidth:e,visibleHeight:n}=this._threeCapability.captureViewportInfo();this._threeCapability.forceCleanupDragState();const r=this._threeCapability.domElement,i=this._threeCapability.css3DRenderer?.domElement,s=[...this._threeCapability.decoratorOutlines];this._threeCapability.dispose(),this._threeCapability=void 0,i?.parentNode&&i.parentNode.removeChild(i);for(const t of this.components)if(t.isHTMLElement()&&t.element){const e=t.element,n=this.getOverlay(t);n?.appendChild(e)}r?.parentNode&&r.parentNode.removeChild(r),this.canvas&&(this.canvas.style.display=""),this._overlay&&(this._overlay.style.display=""),this._auxCanvas&&(this._auxCanvas.style.display=""),this._decoratorOverlay&&(this._decoratorOverlay.style.display=""),this._decoratorAuxOverlay&&(this._decoratorAuxOverlay.style.display="");for(const t of this.root?.assist_layers||[])t.element&&(t.element.style.display="");for(const t of this.components)t.isHTMLElement()&&t.element&&t.reposition();this.app?.isEditMode&&this._createToolbar();for(const t of s)t.disposed||this.applyDecorator(t,"border-highlighting",{distance:8,lineWidth:4,color:"#f007"});this._saved2DViewport?(this.set({scale:this._saved2DViewport.scale,translate:this._saved2DViewport.translate}),this._saved2DViewport=void 0):this._needsViewportSync&&this._init2DViewportFrom3DCamera(t,e,n),this.root.target_element?.focus()}_getViewportSize(){const t=this.target;return{w:t?.clientWidth||this.canvas?.clientWidth||this.state.width||800,h:t?.clientHeight||this.canvas?.clientHeight||this.state.height||600}}_initCameraFrom2DViewport(){if(!this._threeCapability)return;const{w:t,h:e}=this._getViewportSize(),n=this.get("translate")||{x:0,y:0},r=this.get("scale")||{x:1,y:1},i=r.x||1,s=r.y||1,{width:o=800,height:a=600}=this.state,c=(t/2-n.x)/i-o/2,l=(e/2-n.y)/s-a/2,h=t/i,d=e/s;this._threeCapability.positionCameraForViewport(c,l,h,d,this._lastCameraState)}_init2DViewportFrom3DCamera(t,e,n){if(!e&&!n)return;const{w:r,h:i}=this._getViewportSize(),{width:s=800,height:o=600}=this.state,a=t.x+s/2,c=t.z+o/2,l=e>0?r/e:1/0,h=n>0?i/n:1/0,d=Math.max(.1,Math.min(Math.min(l,h),10)),u=r/2-a*d,p=i/2-c*d;this.set({translate:{x:u,y:p},scale:{x:d,y:d}})}centerTo(t,e){this.is3dMode&&this._threeCapability?this._threeCapability.centerToComponent(t,e):super.centerTo(t,e)}async ready(){await super.ready(),this.model.threed?this._threeCapability||(await new Promise(t=>setTimeout(t,0)),this._activateThreeD()):this.app?.isEditMode&&this._createToolbar(),this.root?.trigger("dimension",this.model.threed?"3d":"2d")}dispose(){this._deactivateThreeD(),this._removeToolbar(),super.dispose(),this._overlay=null,this._decoratorOverlay&&(bs.getInstance().removeOverlay(this._decoratorOverlay),this._decoratorOverlay.parentNode&&this._decoratorOverlay.parentNode.removeChild(this._decoratorOverlay),this._decoratorOverlay=null),this._decoratorAuxOverlay&&(bs.getInstance().removeOverlay(this._decoratorAuxOverlay),this._decoratorAuxOverlay.parentNode&&this._decoratorAuxOverlay.parentNode.removeChild(this._decoratorAuxOverlay),this._decoratorAuxOverlay=null)}contains(t,e){return!0}isRootModel(){return!0}get stuck(){return!0}get layout(){return this.is3dMode?Wa.get("three"):Xa}get overlay(){if(!this._overlay){const t=document.createElement("div");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.margin="0",t.style.padding="0",t.style.overflow="initial",t.style["user-select"]="none",t.style["transform-origin"]="top left",t.setAttribute("scene","model-layer-overlay"),this.element.insertBefore(t,this.auxCanvas),this._overlay=t,this._repositionOverlay()}return this._overlay}get auxOverlay(){return this.element??void 0}get decoratorOverlay(){if(!this._decoratorOverlay){const t=document.createElement("div");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.margin="0",t.style.padding="0",t.style.overflow="initial",t.style["user-select"]="none",t.style["transform-origin"]="top left",t.setAttribute("scene","decorator-overlay"),t.id=`decorator-overlay-${Date.now()}`,this.element.insertBefore(t,this.overlay),this._decoratorOverlay=t,bs.getInstance().addOverlay(t)}return this._decoratorOverlay}get decoratorAuxOverlay(){if(!this._decoratorAuxOverlay){const t=document.createElement("div");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.margin="0",t.style.padding="0",t.style.overflow="initial",t.style.zIndex="100",t.style["user-select"]="none",t.style["transform-origin"]="top left",t.setAttribute("scene","decorator-aux-overlay"),t.id=`decorator-overlay-${Date.now()}`,this.element.appendChild(t),this._decoratorAuxOverlay=t,bs.getInstance().addOverlay(t)}return this._decoratorAuxOverlay}createElement(){const t=super.createElement();return this._overlay&&t.appendChild(this._overlay),t}resize(){if(!this.target||!this.element)return;let{width:t,height:e,fitMode:n}=this.model;this.root.fitMode?n=this.root.fitMode:n||(n="ratio");let r=null;try{r=getComputedStyle(this.target)}catch(t){return void jr(t,this.target)}let i=r?parseFloat(r.getPropertyValue("width")):this.target.clientWidth,s=r?parseFloat(r.getPropertyValue("height")):this.target.clientHeight;switch(n){case"both":case"ratio":break;case"width":s=e*i/t,this.element.style.overflowX="hidden",this.element.style.overflowY="auto";break;case"height":i=t*s/e,this.element.style.overflowX="auto",this.element.style.overflowY="hidden";break;default:i=Math.max(t,i),s=Math.max(e,s),this.element.style.overflowX=i>t?"hidden":"auto",this.element.style.overflowY=s>e?"hidden":"auto"}this.fitSize(this.element,!0),this.fitSize(this.canvas,!0,i,s),this.fitSize(this.auxCanvas,!0,i,s),this.is3dMode&&this._threeCapability.resize(i,s)}draw(t){if(this.is3dMode){if(!this.element)return;this._threeCapability.renderCSS3D()}else this.model.threed||super.draw(t)}get MPP(){const{scale:t={x:1,y:1},unit:e}=this.model;switch(e){case"mm":case"cm":return 1/this.app.PPM/t.x;case"in":return 1/this.app.PPI/t.x;default:return 1/t.x}}capturePath(t,e){const n=this.layout.capturables(this);for(let r=n.length-1;r>=0;r--){const i=n[r];if(!i.isContainer())continue;const s=i.capturePath(t,e);if(s)return s}return!1}getOverlay(t){return t&&!t.scalable?this.auxOverlay:this.overlay}getDecoratorOverlay(t){return t&&!t.scalable?this.decoratorAuxOverlay:this.decoratorOverlay}_onkeydown_root(t){if(t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)return;const e=this.rootModel;if(!e)return;if("KeyF"===t.code)return this.onSearchToggle?.(),void t.preventDefault();if("KeyH"===t.code)return this._toggleHelpPanel(),void t.preventDefault();if(e.is3dMode)return;if("KeyQ"===t.code)return e.set("threed",!0),void t.preventDefault();const n={Digit1:"perspective",Digit2:"top",Digit3:"front",Digit4:"back",Digit5:"right",Digit6:"left"}[t.code];n&&(e._pendingCameraView=n,e.set("threed",!0),t.preventDefault())}get eventMap(){return{"(self)":{"(all)":{change:this._onchanged_all,mouseenter:this._onmouseenter_all,mouseleave:this._onmouseleave_all,click:this._onclick,mousedown:this._onmousedownup,mouseup:this._onmousedownup,touchstart:this._onmousedownup,touchend:this._onmousedownup,"deco-reset":t=>this.resetDecorator(void 0,t.origin)},"(descendant)":{"deco-anchors":(t,e)=>this.applyDecorator(e.origin,"anchors",t),"deco-anchors-off":t=>this.offdecorator(t.origin,"anchors"),"deco-anchors-reset":t=>this.resetDecorator("anchors"),"deco-dataspread":(t,e)=>this.applyDecorator(e.origin,"data-spread",t),"deco-dataspread-off":t=>this.offdecorator(t.origin,"data-spread"),"deco-dataspread-reset":t=>this.resetDecorator("data-spread"),"deco-link":(t,e)=>this.applyDecorator(e.origin,"link",t),"deco-link-off":t=>this.offdecorator(t.origin,"link"),"deco-link-reset":t=>this.resetDecorator("link"),"deco-arrow":(t,e)=>this.applyDecorator(e.origin,"bouncing-arrow",t),"deco-arrow-off":t=>this.offdecorator(t.origin,"bouncing-arrow"),"deco-arrow-reset":t=>this.resetDecorator("bouncing-arrow"),"deco-icon":(t,e)=>this.applyDecorator(e.origin,"animated-icon",t),"deco-icon-off":t=>this.offdecorator(t.origin,"animated-icon"),"deco-icon-reset":t=>this.resetDecorator("animated-icon"),"deco-border":(t,e)=>{this.app.isEditMode||(this._threeCapability?this._threeCapability.addOutline(e.origin):this.applyDecorator(e.origin,"border-highlighting",t))},"deco-border-off":t=>{this.app.isEditMode||(this._threeCapability?this._threeCapability.removeOutline(t.origin):this.offdecorator(t.origin,"border-highlighting"))},"deco-border-reset":t=>{this.app.isEditMode||(this._threeCapability?this._threeCapability.clearOutlines():this.resetDecorator("border-highlighting"))},"deco-tag":(t,e)=>this.applyDecorator(e.origin,"decotag",t),"deco-tag-off":t=>this.offdecorator(t.origin,"decotag"),"deco-tag-reset":t=>this.resetDecorator("decotag",t.origin),"deco-off":t=>{this.offdecorator(t.origin),this._threeCapability?.removeOutline(t.origin)},mouseenter:this.onmouseenterForDecorator,mouseleave:this.onmouseleaveForDecorator},"(self)":{change:this.onChangeForDecorator,redraw:this.onRedrawForDecorator}},"(root)":{"(self)":{selected:this._onRootSelected,keydown:this._onkeydown_root}}}}onRedrawForDecorator(){this.is3dMode||(bs.getInstance().invalidateOverlay(this.decoratorOverlay),bs.getInstance().invalidateOverlay(this.decoratorAuxOverlay))}closeScene(t){requestAnimationFrame(()=>this.overlay.dispatchEvent(new CustomEvent("close-scene",{bubbles:!0,composed:!0,detail:t})))}_repositionOverlay(){const t=this._overlay;if(!t)return;const{translate:e=Jh,scale:n=Zh,rotation:r=0}=this.model,{left:i,top:s}=this.bounds;t.style.left=i+"px",t.style.top=s+"px",t.style.transform=`rotate(${r}rad) scale(${n.x}, ${n.y}) perspective(1px)`,t.style.marginLeft=`${e.x}px`,t.style.marginTop=`${e.y}px`}onchange(t){const e=this._model;delete e.id,delete e.text,delete e.class,this._repositionOverlay(),t.hasOwnProperty("threed")&&(t.threed?this._activateThreeD(!0):this._deactivateThreeD(),this.root?.trigger("dimension",t.threed?"3d":"2d")),this.is3dMode&&((t.hasOwnProperty("width")||t.hasOwnProperty("height"))&&this._resizeThreeD(),this._threeCapability.onchange(t))}_onRootSelected(t){const e=1===t?.length?t[0]:t&&0!==t.length?null:this;e&&globalThis.dispatchEvent?.(new CustomEvent("clickComponent",{detail:e}))}_onchanged_all(t,e,n){this.invalidate()}_onmouseenter_all(t,e){if(t.stopPropagation(),!this.app||this.app.isEditMode)return;if(!e)return;const n=e.origin;if(n instanceof ad||!n.model.event||!n.model.event.hover)return;if(n.hidden)return;const r=n.model.event.hover;r&&this._doEventAction(r,n,!0,t)}_onmouseleave_all(t,e){if(t.stopPropagation(),!e)return;const n=e.origin;if(!this.app||this.app.isEditMode)return;const r=n.model.event&&n.model.event.hover;r&&this._doEventAction(r,n,!1,t)}_onclick(t,e){if(t.stopPropagation(),this.app.isEditMode)return;if(!e)return;const n=e.origin,r=n.model.event?.tap;r&&this._doEventAction(r,n,!0,t)}_onmousedownup(t,e){if(t.stopPropagation(),this.app.isEditMode)return;if(!e)return;const n=e.origin,r=n.model.event?.tap;r&&r.pressed&&this._doMouseDownUpEventAction(r,n,"mousedown"==t.type||"touchstart"==t.type,t)}_doMouseDownUpEventAction(t,e,n,r){const{pressed:i=!1}=t;i&&(n?function(t){if(t.hasOwnProperty("_backupShadow"))return;const e=t.get("shadow");t._backupShadow=e;const{left:n=0,top:r=0}=e||{};t.delta("tx",n),t.delta("ty",r),t.set("shadow",{})}(e):function(t){t.hasOwnProperty("_backupShadow")&&(t.delta("tx",0),t.delta("ty",0),t.set("shadow",t._backupShadow),delete t._backupShadow)}(e))}_doEventAction(t,e,n,r){let{action:i,target:s,value:o,emphasize:a=!1,restore:c=!1,options:l}=t;if(s&&(s=e.access(s)),o&&(o=e.access(o)),a&&(n?function(t){const{hover:e}=t.state.event||{},{emphasize:n}=e||{};if(t.hasOwnProperty("_backupStrokeStyle"))return;if("__backup_emphasize"in t)return;const{strokeStyle:r,lineWidth:i,fillStyle:s}=t.state;t.__backup_emphasize={strokeStyle:r,lineWidth:i,fillStyle:s},t.setState(n)}(e):c&&function(t){"__backup_emphasize"in t&&(t.setState(t.__backup_emphasize),delete t.__backup_emphasize)}(e)),i)switch(i){case"data-toggle":if(!s)return;(n||c)&&this.root.findAll(s,e)?.forEach(t=>{t.data=!t.data});break;case"data-tristate":if(!s)return;(n||c)&&this.root.findAll(s,e)?.forEach(t=>{const e=Math.round(Math.max(Number(t.data)||0,0));t.data=(e+(n?1:2))%3});break;case"data-spreading":if(!s)return;n&&(e.access(o),this.root.findAll(s,e)?.forEach(t=>{t.executeMappings(!0)}));break;case"data-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.data=t})}break;case"partial-data-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.data={...e.data,...t}})}break;case"value-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.value=t})}break;case"partial-value-set":if(!s)return;if(n){const t=e.access(o);this.root.findAll(s,e)?.forEach(e=>{e.value={...e.value,...t}})}break;case"infoWindow":case"info-window":if(!s)return;"click"==r.type||n?Ua.show(e,s,c,{x:r.offsetX,y:r.offsetY}):c&&Ua.hide(e,s);break;case"toggle-info-window":if(!s)return;Ua.toggle(e,s,!1,{x:r.offsetX,y:r.offsetY});break;case"popup":case"modal-popup":if(!s)return;const t=l&&"input"in l?l.input:"(self)",a=!l||(!("output"in l)||l.output);hc.show(e,s,{data:t&&this.root.findFirst(t,e)?.data,output:a,modal:"modal-popup"===i,closable:!0,draggable:!0,origin:"auto"});break;case"close-scene":this.closeScene(e.data);break;case"goto":case"goto-playlist":this.trigger(i,s,l,e);break;case"mouse-cursor":n?this.target.style.cursor=s||"auto":c&&(this.target.style.cursor="auto");break;default:this.trigger(i,s,o,e)}}applyDecorator(t,e,n={}){const r=this.getDecoratorOverlay(t);if(r){bs.getInstance().addToOverlay(r,t,e,n)}}offdecorator(t,e){const n=this.getDecoratorOverlay(t);if(n){bs.getInstance().removeFromOverlay(n,t,e)}}resetDecorator(t,e){const n=this.getDecoratorOverlay(e);n&&bs.getInstance().removeAllFromOverlay(n,t)}onChangeForDecorator(t,e,n){const{origin:r}=n,i=this.getDecoratorOverlay(r);bs.getInstance().invalidateOverlay(i)}onmouseenterForDecorator(t,e){const{origin:n}=e;n.decorators&&n.decorators.forEach(t=>{this.applyDecorator(n,t)})}onmouseleaveForDecorator(t,e){const{origin:n}=e;n.decorators&&n.decorators.forEach(t=>{this.offdecorator(n,t)})}}function cd(t,e){const n=t.state.refid;return t.root.findAll(t=>t.isLine()&&t.from?.component===n&&(!e||t.from.anchor===e))}function ld(t,e){const n=t.state.refid;return t.root.findAll(t=>t.isLine()&&t.to?.component===n&&(!e||t.to.anchor===e))}function hd(t){return class extends t{isConnectable(){return!0}postrender(t){super.postrender(t),this._draw_anchors(t)}_draw_anchors(t){const e=this.anchors||[];t.save(),e.forEach(e=>{const{draw:n}=e;if(n){t.beginPath();try{n.call(e,t,this)}catch(t){jr(t)}t.closePath()}}),t.restore()}contains(t,e){let n=super.contains(t,e);if(n)return n;const r=this.anchors||[];for(const i of r){const r=i.bounds;if(!r)continue;const{left:s,top:o,width:a,height:c}=r;if(n=t<Math.max(s+a,s)&&t>Math.min(s+a,s)&&e<Math.max(o+c,o)&&e>Math.min(o+c,o),n)return n}return!1}findInOutLines(t){return function(t,e){const n=t.state.refid;return t.root.findAll(t=>!(!t.isLine()||(t.from?.component!==n||e&&t.from.anchor!==e)&&(t.to?.component!==n||e&&t.to.anchor!==e)))}(this,t)}findOutletLines(t){return cd(this,t)}findOutletEnds(t){return function(t,e){return cd(t,e).map(t=>t.toEnd?.component).filter(Boolean)}(this,t)}findInletLines(t){return ld(this,t)}findInletEnds(t){return function(t,e){return ld(t,e).map(t=>t.fromEnd?.component).filter(Boolean)}(this,t)}}}ad.Popup=hc,Fa.register("model-layer",ad);const dd={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"round",name:"round",property:{min:0}}],help:"scene/component/rect"},ud={ondragmove:function(t,e,n){const{left:r,width:i,height:s}=n.model;let o=(n.fromParent(t.x,t.y).x-r)/(i/2)*100;o=Na(o,i,s),n.set({round:o})}};class pd extends(hd(Ha(Ba))){is3dish(){return!0}get controls(){let{left:t,top:e,width:n,round:r,height:i}=this.state;return r=null==r?0:Na(r,n,i),[{x:t+n/2*(r/100),y:e,handler:ud}]}get nature(){return dd}}Fa.register("rect",pd);const fd=[1,2,10,20,50,50,50,50,50,50];class gd extends(Ha(Ba)){render(t){const{lineWidth:e=1,fillStyle:n="lightgray",font:r="15px Arial",left:i,top:s,origin:o,width:a,height:c,side:l="bottom",strokeStyle:h="#000000",scale:d=1}=this.state;t.translate(i,s),t.beginPath();const u=Math.round(e/2);t.rect(-u,-u,a+2*u,c+2*u),t.clip(),t.beginPath(),t.rect(0,0,a,c),n&&(t.fillStyle=n,t.fill()),t.lineWidth=e,t.strokeStyle=h,t.stroke(),t.beginPath(),t.font=r;const p="bottom"!==l,f=p?0:c;let g=4*c/5,m=2*c/3,y=1*c/2,b=3*c/5;p&&(g=c-g,m=c-m,y=c-y,b=c-1.5*c/5);const v=d*this.app.PPM/this.root.unitScale;let _=Math.ceil(o/v);const x=this.app.PPM/v,w=x<=1.1?1:fd[Math.round(x)]||100;1!=w&&(_+=(w-_%w)%w);let M=Math.ceil(_*v);const S=o+a;for(t.fillStyle=h;M<S;){if(_%10==0){t.moveTo(M-o,y),t.lineTo(M-o,f);const e=(_/10).toString(),n=t.measureText(e);t.fillText(e,M-o-n.width-6,b)}else _%5==0?(t.moveTo(M-o,m),t.lineTo(M-o,f)):(t.moveTo(M-o,g),t.lineTo(M-o,f));_+=w,M=Math.ceil(_*v)}}}Fa.register("ruler",gd);const md=20,yd=20,bd=90*Math.PI/180,vd="9px Verdana",_d=20,xd="#f4f4f4",wd="#999";function Md(t,e,n){return{left:-t.x,top:-t.y,width:md,height:_d}}function Sd(t,e,n,r){return{left:md-t.x,top:0-t.y,origin:20-t.x,width:e-md,height:_d}}function Ad(t,e,n,r){const i={x:0-t.x+10,y:-t.y+yd+(n-yd)/2},s=Fa.transcoordRR(0-t.x,-t.y+yd,i,bd);return{left:s.x-(n-yd),top:s.y,origin:20-t.y,width:n-yd,height:_d}}function Ed(t){const e=t.get("translate");return{left:-e.x,top:-e.y,width:t.canvas.width/_i,height:t.canvas.height/_i}}Fa.register("guide-layer",class extends gc{constructor(t,e){super(t,e),this.appScale={x:1,y:1},"disabled"!==t.ruler&&(this.hruler=new gd({left:md,top:0,origin:20,margin:0,height:_d,unit:"m",rotation:0,font:vd,fillStyle:xd,strokeStyle:wd,capturable:!1}),this.vruler=new gd({left:0,top:0,origin:20,margin:0,height:_d,unit:"m",rotation:bd,font:vd,side:"top",fillStyle:xd,strokeStyle:wd,capturable:!1}),this.origin_rect=new pd({left:-20,top:-20,width:20,height:20,fillStyle:xd,strokeStyle:wd,lineWidth:1}),this.addComponent(this.hruler),this.addComponent(this.vruler),this.addComponent(this.origin_rect)),this.invalidate()}get capturable(){return!1}async ready(){if(await super.ready(),!this.hruler)return void(this.screen_coord=Ed(this));const t=this.rootModel,e=Object.assign({},t.get("translate"));e.x<md&&(e.x+=md),e.y<yd&&(e.y+=yd);const n=t.get("scale")||{x:1,y:1};this.appScale=n,this.hruler.set("scale",n.x),this.vruler.set("scale",n.y),t.set("translate",e),this.set("translate",e),this.screen_coord=Ed(this);const{width:r,height:i}=this.screen_coord;this.hruler.set(Sd(e,r)),this.vruler.set(Ad(e,0,i)),this.origin_rect.set(Md(e))}resize(){super.resize(),this.screen_coord=Ed(this);const{width:t,height:e}=this.screen_coord;this.hruler&&(this.hruler.set(Sd(this.model.translate,t)),this.vruler.set(Ad(this.model.translate,0,e)),this.origin_rect.set(Md(this.model.translate)))}render(t){if(this.rootModel?.is3dMode)return;if(!this.guide)return;t.save();const{x:e,y:n}=this.guide,{top:r,left:i,width:s,height:o}=this.screen_coord;t.beginPath(),t.moveTo(e,r),t.lineTo(e,r+o),t.moveTo(i,n),t.lineTo(i+s,n),t.lineWidth=1,t.strokeStyle="tomato",t.setLineDash([2,3]),t.font="10px tahoma",t.fillStyle="#333";const a=this.toGlobal(e,n,this.rootModel);t.textBaseline=a.y>200?"bottom":"top",t.textAlign=a.x>200?"right":"left";const c=a.y>200?-5:5,l=a.x>200?-5:5,h=Math.round(e/this.appScale.x),d=Math.round(n/this.appScale.y);t.fillText(` ${h}, ${d} `,e+l,n+c),t.stroke(),t.restore()}get guide(){return this._guide}set guide(t){this._guide=t,this.invalidate()}contains(t,e){return!0}get eventMap(){return{"(root)":{"(descendant)":{mousemove:this.onmousemove_child,mouseout:this.onmouseout_child,dragmove:this.onmousemove_child},"model-layer":{change:this.onchange_root_model}},"(self)":{"(descendant)":{mousedown:this.onmousedown_origin}}}}onmousedown_origin(t,e){this.rootModel.set("translate",{x:20,y:20})}onchange_root_model(t,e,n){if(t.scale&&(this.appScale=t.scale,this.hruler&&(this.hruler.set("scale",t.scale.x),this.vruler.set("scale",t.scale.y))),t.translate&&this.set({translate:{x:t.translate.x,y:t.translate.y}}),t.scale||t.translate){if(this.screen_coord=Ed(this),this.hruler){const{translate:t}=this.model,{width:e,height:n}=this.screen_coord;this.hruler.set(Sd(t,e)),this.vruler.set(Ad(t,0,n)),this.origin_rect.set(Md(t))}this._guide=null}this.invalidate()}onmouseout_child(t){this._guide=null,this.invalidate()}onmousemove_child(t,e){t.target&&"CANVAS"!==t.target.tagName?this.guide=null:this.guide=this.toLocal(t.offsetX,t.offsetY)}});Fa.register("shift-layer",class extends gc{async ready(){await super.ready();const t=this.rootModel.get("translate");this.set("translate",t)}render(t){}get pointerEvents(){return"none"}contains(t,e){return!(2!=this.app.mode)}get eventMap(){return{"(root)":{"(self)":{keydown:this.onkeydown,keyup:this.onkeyup}}}}onkeydown(t){"Space"===t.code&&void 0===this.before_mode&&(this.before_mode=this.app.mode,this.app.mode=2)}onkeyup(t){"Space"===t.code&&(void 0!==this.before_mode&&(this.app.mode=this.before_mode),delete this.before_mode)}ondragstart(t){this.last_position=this.toLocal(t.offsetX,t.offsetY)}ondragmove(t){const{x:e,y:n}=this.toLocal(t.offsetX,t.offsetY);this.rootModel.move({x:e-this.last_position.x,y:n-this.last_position.y},!1),this.last_position=this.toLocal(t.offsetX,t.offsetY)}});function kd(t,e,n,r){const i=t.selected;let s=r?i.slice(0):[];e.isContainer()||(e=e.parent);const o=e.layout.capturables(e),a=!!e.layout.joinType;if(r&&n.selected.forEach(t=>{s.splice(s.indexOf(t),1)}),n.selected=[],o.forEach(t=>{t.capturable&&function(t,e,n){const{sx:r,sy:i,ex:s,ey:o}=e;let a,c,l,h;if(r>s?(a=s,c=r):(a=r,c=s),i>o?(l=o,h=i):(l=i,h=o),n){const e=t.bounds,n=t.transcoordS2TR(e.left,e.top),r=t.transcoordS2TR(e.left+e.width,e.top+e.height),i=n.x,s=r.x,o=n.y,d=r.y,u=Math.min(a,i,c,s),p=Math.max(a,i,c,s),f=Math.min(l,o,h,d),g=Math.max(l,o,h,d);return!(p-u>Math.abs(c-a)+Math.abs(s-i)||g-f>Math.abs(h-l)+Math.abs(d-o))}{const e=t.path;if(!e)return jr("컴포넌트에 get path가 잘못 구현되어있음.",t),!1;for(let n=0;n<e.length;n++){const r=t.transcoordS2TR(e[n].x,e[n].y);if(a>r.x||c<r.x||l>r.y||h<r.y)return!1}return!0}}(t,n,a)&&-1==s.indexOf(t)&&n.selected.push(t)}),s=s.concat(n.selected),i.length!==s.length)t.selected=s;else for(let e=0;e<s.length;e++)if(i[e]!=s[e]){t.selected=s;break}}function Cd(t,e,n,r,i){i||kd(t,e,n,r)}function Pd(t,e){const n=t.components||[];for(const t of n){Pd(t,e);const n=e.indexOf(t);-1!=n&&e.splice(n,1)}}Fa.register("add-layer",class extends gc{async ready(){await super.ready();const t=this.rootModel,e=t.get("translate"),n=t.get("scale");this.set("translate",e),this.set("scale",n)}get pointerEvents(){return"none"}render(t){const e=this.addbox;if(e){const{sx:n,sy:r,ex:i,ey:s}=e,o=this.get("scale")||{x:1,y:1};t.beginPath(),t.rect(n,r,i-n,s-r),t.setLineDash([2/o.x,4/o.y]),t.lineWidth=1/o.x,t.strokeStyle="black",t.stroke()}}contains(t,e){return!(3!=this.app.mode)}get eventMap(){return{"(root)":{"(self)":{addstart:this.onaddstart,addstop:this.onaddstop,keydown:this.onkeydown,dragstart:this.ondragstart,dragmove:this.ondragmove,dragend:this.ondragend,mousedown:this.onmousedown,mouseup:this.onmouseup}},"model-layer":{"(self)":{change:this.onchange_root_model}}}}onchange_root_model(t,e,n){t.translate&&this.set("translate",t.translate),t.scale&&this.set("scale",t.scale)}onaddstart(t,e){void 0===this.before_mode&&(this.before_mode=this.app.mode,this.models=t,this.app.mode=3,this.root.target_element?.focus())}onaddstop(){void 0!==this.before_mode&&(this.app.mode=this.before_mode),delete this.before_mode,delete this.addbox,this.invalidate()}onkeydown(t){3!==this.app.mode||"Esc"!=t.code&&"Escape"!=t.code||this.root.trigger("addstop")}ondragstart(t){const{x:e,y:n}=this.toLocal(t.offsetX,t.offsetY);this.addbox={sx:e,sy:n}}ondragmove(t){if(3!==this.app.mode)return;const{x:e,y:n}=this.toLocal(t.offsetX,t.offsetY);this.addbox&&(this.addbox.ex=e,this.addbox.ey=n,this.invalidate())}ondragend(t,e){if(3!==this.app.mode)return;const{sx:n,sy:r,ex:i,ey:s}=this.addbox;Jc.call(this.root,this.models,{left:Math.min(n,i),top:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}),this.root.trigger("addstop")}onmousedown(t,e){3===this.app.mode&&(this.downpoint={x:t.offsetX,y:t.offsetY})}onmouseup(t,e){if(this.downpoint.x!==t.offsetX||this.downpoint.y!==t.offsetY)return;const{x:n,y:r}=this.toLocal(t.offsetX,t.offsetY);Jc.call(this.root,this.models,{cx:n,cy:r}),this.root.trigger("addstop")}});Fa.register("selection-layer",class extends gc{async ready(){await super.ready();const t=this.rootModel,e=t.get("translate"),n=t.get("scale");this.set("translate",e),this.set("scale",n)}contains(t,e){return!1}render(t){const e=this.selbox;if(e){const{sx:n,sy:r,ex:i,ey:s}=e,o=this.get("scale")||{x:1,y:1};t.beginPath(),t.rect(n,r,i-n,s-r),t.setLineDash([2/o.x,4/o.y]),t.lineWidth=1/o.x,t.strokeStyle="black",t.stroke()}}get eventMap(){return{"(root)":{"(self)":{keydown:this.onkeydown}},"model-layer":{"(self)":{change:this.onchange_root_model},"(all)":{dragstart:this.ondragstart_selbox,dragmove:this.ondragmove_selbox,dragend:this.ondragend_selbox,mousedown:this.onmousedown_comp,mouseup:this.onmouseup_comp}}}}onkeydown(t,e){const{deliverer:n}=e,r=n.selected;if(1!==r.length)return!1;let i=r[0];const s=i.parent;if(!s||s===n)return!1;if("Tab"===t.code){const e=s.layout.capturables(s);let n=e.indexOf(i);if(-1==n){if(!s.indexOf(i))return Rr("Container not contains [",i,"] as a component"),!1;n=0}const r=e.length;t.shiftKey?n--:n++,i=e[(n+r)%r]}else{if(!s.layout.keyNavigate)return!1;i=s.layout.keyNavigate(s,i,t)||i}n.selected=[i],t.preventDefault()}onchange_root_model(t,e,n){t.translate&&this.set("translate",t.translate),t.scale&&this.set("scale",t.scale)}_pendingDecision(t){this.downpoint={x:t.offsetX,y:t.offsetY}}_selectGroupItem(t,e){const n=this.selected.indexOf(t);let r=t.parent;for(;r.parent.isGroup();)r=r.parent;let i=[],s=!1,o=!1;if(this.selected.forEach(t=>{let e=t.parent;if(t!==r){for(;e.parent&&e.parent.isGroup();)e=e.parent;e===r&&(i.push(t),s=!0)}else o=!0}),s)if(e.shiftKey){if(-1!=n)return void this._pendingDecision(e);i.push(t)}else{if(-1!=n)return void this._pendingDecision(e);i=[t]}else{if(o)return void this._pendingDecision(e);if(e.shiftKey)if(this.selected.length>0){if(-1!=this.selected.indexOf(r))return;i=[...this.selected,r]}else i=[r];else i=[r]}this.selected=i}onmousedown_comp(t,e){const{origin:n}=e;if(this.downpoint=null,t.shiftKey){if(n.stuck)return;if(n.parent.isGroup())return void this._selectGroupItem(n,t);this._pendingDecision(t)}else{if(n.parent.isGroup())return void this._selectGroupItem(n,t);if(n.stuck)this.selected.length>0&&(this.selected=[]);else{if(-1!=this.selected.indexOf(n))return;this.selected=[n],this.sameParent=!0}}}onmouseup_comp(t,e){if(!this.downpoint)return;if(this.downpoint.x!==t.offsetX||this.downpoint.y!==t.offsetY)return;const{origin:n}=e;if(t.shiftKey){let t=this.selected.indexOf(n);if(-1==t&&n.parent.isGroup()&&(t=this.selected.indexOf(n.parent)),-1!==t){const e=this.selected.slice();e.splice(t,1),this.selected=e}else{const t=this.selected.filter(t=>!t.isRootModel()&&!!t.parent),e=t.length>0&&t[0].parent;e&&e!==n.parent&&(!function(t,e){let n=t.parent;for(;n;){const t=e.indexOf(n);-1!=t&&e.splice(t,1),n=n.parent}}(n,t),Pd(n,t)),t.push(n),this.selected=t}}else if(n.parent.isGroup())return void(this.selected=[n])}ondragstart_selbox(t,e){const{origin:n}=e;if(!n.stuck)return;const{x:r,y:i}=this.toLocal(t.offsetX,t.offsetY);this.selbox={sx:r,sy:i,selected:[]}}ondragmove_selbox(t,e){const{origin:n}=e;if(!n.stuck)return;const{x:r,y:i}=this.toLocal(t.offsetX,t.offsetY);this.selbox&&(this.selbox.ex=r,this.selbox.ey=i,Cd(this,n,this.selbox,t.shiftKey,!1),this.invalidate())}ondragend_selbox(t,e){const{origin:n}=e;n.stuck&&(this.last_pos=null,this.selbox=null,Cd(this,null,null,!1,!0),this.invalidate())}});class Td{constructor(t){this.layer=t}draw(t,e,n){const{left:r,top:i,width:s,height:o}=e.bounds;0!=s&&0!=o&&(t.beginPath(),t.rect(r,i,s,o),t.clip(),t.beginPath(),t.strokeStyle="#f26522",t.lineWidth=4,t.shadowBlur=10,t.shadowColor="black",t.shadowOffsetX=0,t.shadowOffsetY=0,t.rect(r,i,s,o),t.stroke(),t.closePath())}}class Dd{constructor(t){this.layer=t}draw(t,e,n){const r=e.bounds;t.beginPath(),t.rect(r.left-4/n.x,r.top-4/n.y,r.width+8/n.x,r.height+8/n.y),t.setLineDash([3/n.x,4/n.y]),t.lineWidth=1/n.x,t.strokeStyle="black",t.stroke(),t.setLineDash([]),t.closePath()}}class Od{constructor(t){this.layer=t}reset(){this.active=null}get selected(){return this.layer.selected}contains(t,e,n,r){const i=n.controls;return!!i&&(i.every((i,s)=>(Math.abs(t-i.x)<=4/r.x&&Math.abs(e-i.y)<=4/r.y&&(this.active={component:n,index:s,handler:i.handler}),!this.active)),!!this.active)}draw(t,e,n){const r=e.controls;r&&r.forEach((e,r)=>{t.beginPath(),t.lineWidth=1/n.x,t.ellipse(e.x,e.y,4/n.x,4/n.y,0,0,2*Math.PI,!0),t.fillStyle="#ff5d72",t.fill(),t.strokeStyle="#fff",t.stroke()})}onevent(t,e){const{handler:n,component:r,index:i}=this.active;let s=r.toLocal(e.offsetX,e.offsetY);s=r.toParent(s.x,s.y),n&&"function"==typeof n[t]&&n[t](s,i,r)}onmousedown(t){this.onevent("onmousedown",t)}ondragstart(t){const e=this.active;e.changes=zc.before([e.component]),this.onevent("ondragstart",t)}ondragmove(t){this.onevent("ondragmove",t)}ondragend(t){this.onevent("ondragend",t);const{component:e,changes:n}=this.active;zc.after(n,e.app.commander),e.parent&&e.parent.calculateBounds&&e.parent.calculateBounds()}}function zd(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}const Id=15*Math.PI/180;class Ld{constructor(t){this.layer=t}reset(){this.active=null,this.created=null}get selected(){return this.layer.selected}contains(t,e,n,r){return!!n.mutable&&(n.path.every((i,s)=>(Math.abs(t-i.x)<=4/r.x&&Math.abs(e-i.y)<=4/r.y&&(this.active={component:n,index:s}),!this.active)),!!this.active)}startLinkProcess(t,e,n){try{const r=Qc(e,t.app,void 0);return t.rootModel.addComponent(r),this.layer.selected=[r],this.active={component:r,index:1},this.ondragstart(n),r}catch(t){Rr(t)}}draw(t,e,n){if(!e.mutable||e.stuck)return;const r=e.path,i=this.active;r.forEach((r,s)=>{t.beginPath(),t.ellipse(r.x,r.y,4/n.x,4/n.y,0,0,2*Math.PI,!0),t.lineWidth=1/n.x,t.strokeStyle="#656565",t.fillStyle="#fff",i&&i.component===e&&i.index===s&&(t.strokeStyle="#fa7703",i.toFill&&(t.fillStyle="#ffb80c")),t.fill(),t.stroke()})}ondblclick(t){const e=this.active.component;if(!e.pathExtendable)return;const n=e.path.slice();n.length<3||(n.splice(this.active.index,1),e.path=n)}onmousedown(t){this.active.toFill=!0}ondragstart(t){const{index:e,component:n}=this.active;this.created||(this.active.changes=zc.before([n])),0!==e&&e!==n.path.length-1||(this.layer.counterEnd=0===e?n.toEnd||{fromto:"to"}:n.fromEnd||{fromto:"from"})}ondragmove(t){const{component:e,index:n}=this.active||{},{offsetX:r,offsetY:i}=t;let s=e.toLocal(r,i);if(s=e.toParent(s.x,s.y),t.shiftKey){const t=e.path.length;let r=e.isLine()&&0==n?e.path[1]:e.path[(n-1+t)%t];r=e.toParent(r.x,r.y);let i=0;if(t>2){let s;e.isLine()?0==n?s=e.path[2]:1!=n&&(s=e.path[n-2]):s=e.path[(n-2+t)%t],s&&(s=e.toParent(s.x,s.y),i=zd(s,r))}const c=Math.round((zd(r,s)-i)/Id)*Id+i;s=function(t,e,n){return{x:Math.cos(e)*n+t.x,y:Math.sin(e)*n+t.y}}(r,c,(o=r,a=s,Math.sqrt((a.x-o.x)*(a.x-o.x)+(a.y-o.y)*(a.y-o.y))))}var o,a;if(0===n||n===e.path.length-1){const t=this.layer.anchorTarget=e.rootModel.capture(r,i,t=>!t.isConnectable());if(t){const{x:o,y:a}=t.toLocal(r,i),c=this.layer.get("scale")||{x:1,y:1},l=this.layer.counterEnd,h=(t.anchors||[]).find(n=>{const{name:r,inout:i,multiplicity:s=1/0,position:h,filter:d}=n;if(l){const{anchor:t,fromto:e}=l;if(t&&("out"===t.inout&&"out"===i||"in"===t.inout&&"in"===i))return!1;if("from"===e&&"out"===i||"to"===e&&"in"===i)return!1}else jr("should not be here.");if(Math.abs(o-h.x)>8/c.x||Math.abs(a-h.y)>8/c.y)return!1;const u=t.findInOutLines(r);return!!u.includes(e)||!(s!==1/0&&u.length>=s)&&(!l||!d||!!d.call(n,l))});h?0==n?e.from={component:t.get("refid"),anchor:h.name,position:s}:e.to={component:t.get("refid"),anchor:h.name,position:s}:0==n?e.from={position:s}:e.to={position:s}}else 0==n?e.from={position:s}:e.to={position:s}}e.mutatePath(null,function(t){const e=t[n]?.z;t[n]=s,void 0!==e&&(s.z=e)})}ondragend(t){const{component:e,index:n,changes:r}=this.active;if(0===n||n===e.path.length-1){const{offsetX:r,offsetY:i}=t,s=e.rootModel.capture(r,i,t=>t===e||t.isLine()),{x:o,y:a}=s.toLocal(r,i),c=this.layer.get("scale")||{x:1,y:1},l=(s.anchors||[]).find(t=>t&&Math.abs(o-t.position.x)<=8/c.x&&Math.abs(a-t.position.y)<=8/c.y);l&&(0==n?e.from={component:s.get("refid"),anchor:l.name}:e.to={component:s.get("refid"),anchor:l.name}),this.layer.endLinkProcess()}if(this.created){const t=new Xc({changes:[{component:this.created,to_container:this.created.parent}]});this.created.app.commander.execute(t)}else zc.after(r,e.app.commander);e.parent&&e.parent.calculateBounds&&e.parent.calculateBounds()}}function jd(t,e,n){return t.filter(t=>{const{name:r,inout:i,multiplicity:s=1/0,filter:o}=t;if(n){const{anchor:t,fromto:e}=n;if(t&&("out"===t.inout&&"out"===i||"in"===t.inout&&"in"===i))return!1;if("from"===e&&"out"===i||"to"===e&&"in"===i)return!1}else if("in"===i)return!1;return!(s!==1/0&&e.findInOutLines(r).length>=s)&&(!o||!n||!!o.call(t,n))})}class Rd{constructor(t){this.layer=t}get active(){return this._active?.component.disposed&&(this._active=null),this._active}set active(t){this._active=t}reset(){this.active=null}contains(t,e,n,r){const i=this.active?.component===n&&this.active?.anchor;this.active=null;const s=this.layer.counterEnd;return jd(n.isConnectable()&&!n.disposed&&this.getAnchorHandles(n,r)||[],n,s).every(s=>{const o=i===s.name?2:1;return s&&s.position&&Math.abs(t-s.position.x)<=4*o/r.x&&Math.abs(e-s.position.y)<=4*o/r.y&&(this.active={component:n,anchor:s.name,template:s.template}),!this.active}),!!this.active}getAnchorHandles(t,e){const{width:n,height:r}=t.bounds;return n*e.x<30||r*e.y<30?[]:t.anchors}draw(t,e,n){if(!e.get("refid")||e.isLine())return;const r=this.active,i=this.active?.component===e&&this.active?.anchor,s=this.layer.counterEnd;jd(e.isConnectable()&&!e.disposed&&this.getAnchorHandles(e,n)||[],e,s).forEach(s=>{const{name:o,position:a}=s,c=i===o?2:1;a&&(t.beginPath(),t.ellipse(a.x,a.y,4*c/n.x,4*c/n.y,0,0,2*Math.PI),t.setLineDash([0,0]),t.lineWidth=1/n.x,t.strokeStyle="#656565",t.stroke(),t.fillStyle="#fff",r&&r.component===e&&r.anchor===o&&(t.strokeStyle="#fa7703",r.focus&&(t.fillStyle="#ffb80c")),t.fill(),t.stroke())})}onmousedown(t){this.active.focus=!0}ondragstart(t){const{component:e,anchor:n,template:r}=this.active,i=this.layer.toLocal(t.offsetX,t.offsetY);this.layer.startLinkProcess(e,{type:"ortholine",lineWidth:1,strokeStyle:"black",begin:"oval",beginSize:"size9",end:"arrow",endSize:"size9",lineDash:"solid",lineCap:"butt",round:10,...r,from:{component:e.get("refid"),anchor:n,position:i},to:{position:i}},t)}ondragmove(t){}ondragend(t){}}function Fd(t,e){const{left:n,top:r,width:i,height:s}=t,o=n+i/2,a=r+s/2,c=n+i,l=r+s,h=i*e.x>50,d=s*e.y>50;return[{x:n,y:r},h?{x:o,y:r}:{x:null,y:null},{x:c,y:r},d?{x:c,y:a}:{x:null,y:null},{x:c,y:l},h?{x:o,y:l}:{x:null,y:null},{x:n,y:l},d?{x:n,y:a}:{x:null,y:null}]}class Bd{constructor(t){this.layer=t}reset(){this.active=null}get selected(){return this.layer.selected}contains(t,e,n,r){if(!n.resizable)return!1;const i=Fd(n.bounds,r);for(let s=0;s<i.length;s++){const o=i[s];if(null!=o.x&&null!=o.y&&Math.abs(t-o.x)<=4/r.x&&Math.abs(e-o.y)<=4/r.y)return this.active={component:n,index:s},!0}return!1}draw(t,e,n){if(e.isLine())return;const{left:r,top:i,width:s,height:o}=e.bounds;if(t.beginPath(),t.rect(r-4/n.x,i-4/n.y,s+8/n.x,o+8/n.y),t.setLineDash([3/n.x,4/n.y]),t.lineWidth=1/n.x,t.strokeStyle="black",t.stroke(),t.setLineDash([]),!e.resizable)return;const a=this.active;Fd(e.bounds,n).forEach((r,i)=>{null!=r.x&&null!=r.y&&(t.beginPath(),t.rect(r.x-4/n.x,r.y-4/n.y,8/n.x,8/n.y),t.setLineDash([]),t.strokeStyle="#656565",t.stroke(),t.fillStyle="#fff",a&&a.component===e&&a.index===i&&(t.strokeStyle="#fa7703",a.focus&&(t.fillStyle="#ffb80c")),t.fill(),t.stroke())})}onmousedown(t){this.active.focus=!0}ondragstart(t){const{component:e}=this.active;this.active.bounds=e.bounds,this.active.boundsList=this.layer.selected.filter(t=>t.resizable).map(t=>t.bounds)}_resizeAll(t,e){const{component:n,index:r,boundsList:i,bounds:s}=this.active,o=n.scalable?this.layer.toLocal(t.offsetX,t.offsetY):{x:t.offsetX,y:t.offsetY};n.bounds=s;const a=function(t,e,n){const{left:r,top:i,width:s,height:o}=t.bounds;let a,c;switch(e){case 0:a=r,c=i;break;case 1:a=r+s/2,c=i;break;case 2:a=r+s,c=i;break;case 3:a=r+s,c=i+o/2;break;case 4:a=r+s,c=i+o;break;case 5:a=r+s/2,c=i+o;break;case 6:a=r,c=i+o;break;case 7:a=r,c=i+o/2}const l=a,h=c,d=t.fromScene(n.x,n.y);return{dx:d.x-l,dy:d.y-h}}(n,r,o);this.layer.selected.filter(t=>t.resizable).forEach((n,s)=>{n.bounds=i[s],function(t,e,n,r,i,s){let{left:o,top:a,width:c,height:l}=t.bounds;const h={left:o,top:a,width:c,height:l};switch(e){case 0:o+=r,a+=i,c-=r,l-=i;break;case 1:a+=i,l-=i;break;case 2:a+=i,c+=r,l-=i;break;case 3:c+=r;break;case 4:c+=r,l+=i;break;case 5:l+=i;break;case 6:o+=r,c-=r,l+=i;break;case 7:o+=r,c-=r}if(t.mutateBounds(function(e){return Math.abs(c)<=.001&&(c=.001),Math.abs(l)<=.001&&(l=.001),t.adjustResize({left:o,top:a,width:c,height:l},h,n)},this),t.isContainer()&&t.layout.ABSOLUTE&&!t.isGroup()){const e=h.left-o,n=h.top-a;return void(s?t.components.forEach(t=>{t.delta("tx",0),t.delta("ty",0),t.move({x:e,y:n},!1)}):t.components.forEach(t=>{t.delta("tx",e),t.delta("ty",n)}))}const d=s&&t.parent;d&&d.isGroup()&&d.calculateBounds()}(n,r,t.shiftKey,a.dx,a.dy,e)})}ondragmove(t){this._resizeAll(t,!1)}ondragend(t){this._resizeAll(t,!0),this.active.component.app.commander.execute(null,!1)}}const Nd=2*Math.PI,Hd=Math.PI/2;function Vd(t,e){const n=t.bounds;return{x:n.left+n.width/2,y:n.top-20/e.y}}class Gd{constructor(t){this.layer=t}reset(){this.active=null}get selected(){return this.layer.selected}contains(t,e,n,r){if(!n.rotatable)return!1;const i=Vd(n,r);return Math.abs(t-i.x)<=4/r.x&&Math.abs(e-i.y)<=4/r.y&&(this.active={component:n},!0)}draw(t,e,n){if(!e.rotatable)return;t.beginPath();const r=Vd(e,n);t.lineWidth=1.5/n.x,t.moveTo(r.x,r.y+20/n.y),t.lineTo(r.x,r.y),t.strokeStyle="#656565",t.stroke(),t.beginPath(),t.ellipse(r.x,r.y,4/n.x,4/n.y,0,0,Nd,!0),t.stroke(),t.fillStyle="#fff",t.fill();const i=this.active;i&&i.component===e&&(t.strokeStyle="#fa7703",t.stroke(),i.toFill&&(t.fillStyle="#ffb80c",t.fill()))}onmousedown(t){this.active.toFill=!0}ondragstart(t){const e=this.active;e.start_rotation=e.component.get("rotation"),e.rotations=this.layer.selected.filter(t=>t.rotatable).map(t=>t.get("rotation"))}ondragmove(t){const{component:e}=this.active;let n;e.scalable?(n=e.toLocal(t.offsetX,t.offsetY),n=e.toParent(n.x,n.y)):(n={x:t.offsetX,y:t.offsetY},e.parent?.isRootModel()||(n=e.toParent(n.x,n.y)));const r=e.rotatePoint,i=e.get("rotation")||0;let s=Math.atan((r.y-n.y)/(r.x-n.x));s=r.x>=n.x?s-Hd:Hd+s;const o=s-i;this.layer.selected.filter(t=>t.rotatable).forEach((e,n)=>{const r=((e.get("rotation")||0)+o)%Nd;e.set("rotation",e.adjustRotation(r,t.shiftKey))})}ondragend(t){const{component:e}=this.active;e.app.commander.execute(null,!1)}}Fa.register("modeling-layer",class extends mc{constructor(t,e){super(t,e),this.pathHandler=new Ld(this);const n=this.pathHandler,r=new Od(this),i=new Bd(this),s=new Gd(this);this._modelers=[n,r,i,s],this._control_mode_modelers=[r,n,i,s],this.focusOutline=new Td(this),this.groupOutline=new Dd(this),this.anchorHandler=new Rd(this),this._reversed_modelers=this._modelers.slice().reverse(),this._control_mode_reverse_modelers=this._control_mode_modelers.slice().reverse(),this.hovered=null,this.hoveredDest=null}get modelers(){return this._control_mode?this._control_mode_modelers:this._modelers}get reversedModelers(){return this._control_mode?this._control_mode_reverse_modelers:this._reversed_modelers}async ready(){await super.ready();const t=this.rootModel,e=t.get("translate"),n=t.get("scale");this.set("translate",e),this.set("scale",n)}capture(t,e,n){return!!this.contains(t,e)&&this}contains(t,e){let n=this.selected.filter(t=>!!t.parent);const r=this.fromParent(t,e),i=this.get("scale")||{x:1,y:1};let s;if(this._state_dragging){if(this._counter_end){let n=i;if(this.anchorTarget.scalable?s=this.anchorTarget.fromScene(r.x,r.y):(s=this.anchorTarget.fromScene(t,e),n={x:1,y:1}),this.anchorHandler.contains(s.x,s.y,this.anchorTarget,n))return!0}return!0}this.modelers.forEach(t=>t.reset()),n=this.selected.filter(t=>!!t.parent);for(let o=0;o<n.length;o++){const a=n[o];let c=i;a.scalable?s=a.fromScene(r.x,r.y):(s=a.fromScene(t,e),c={x:1,y:1});for(let t=0;t<this.modelers.length;t++){const e=this.modelers[t];if(e.contains(s.x,s.y,a,c))return this.currentModeler=e,!0}}if(this.anchorTarget){let n=i;if(this.anchorTarget.scalable?s=this.anchorTarget.fromScene(r.x,r.y):(s=this.anchorTarget.fromScene(t,e),n={x:1,y:1}),this.anchorHandler.contains(s.x,s.y,this.anchorTarget,n))return this.currentModeler=this.anchorHandler,!0}else this.anchorHandler.reset();return this.currentModeler=null,!1}_componentDrawer(t,e,n,r){const i=[];let s=e.parent;if(e.isRootModel())return t.save(),r(t,e,n),void t.restore();for((t=this.getContext(e))==this.auxContext2D&&(n={x:1,y:1});s&&!s.isRootModel();)i.push(s),s=s.parent;t.save(),i.reverse().forEach(function(e){const n=e.rotatePoint;t.translate(n.x,n.y);const r=e.get("scale");r&&t.scale(r.x,r.y),t.rotate(e.get("rotation")),t.translate(-n.x,-n.y);const i=e.bounds;t.translate(i.left,i.top)});const o=e.rotatePoint;t.translate(o.x,o.y);const a=e.get("scale");a&&t.scale(a.x,a.y),t.rotate(e.get("rotation")),t.translate(-o.x,-o.y),r(t,e,n),t.restore()}prerender(t){const{translate:e,scale:n={x:1,y:1},rotation:r}=this.model;t.save(),t.beginPath(),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.rect(0,0,t.canvas.width,t.canvas.height),t.fillStyle="black",t.globalAlpha=.5,t.fill(),t.restore(),e&&t.translate(e.x*_i,e.y*_i),t.scale(n.x*_i,n.y*_i),r&&t.rotate(r),t.clearRect(0,0,this.rootModel.get("width"),this.rootModel.get("height"))}render(t){if(this.rootModel?.is3dMode)return;t.beginPath();const e=this.get("scale")||{x:1,y:1},n=this.selected.filter(t=>!!t.parent);if(this.anchorTarget&&this._componentDrawer(t,this.anchorTarget,e,(t,e,n)=>{this.anchorHandler.draw(t,e,n)}),this.focused&&this._componentDrawer(t,this.focused,e,(t,e,n)=>{this.focusOutline.draw(t,e,n)}),n.length>0&&n[0].parent.isGroup()){let r=n[0].parent;for(;r.parent.isGroup();)r=r.parent;this._componentDrawer(t,r,e,(t,e,n)=>{this.groupOutline.draw(t,e,n)})}n.forEach(n=>{this._componentDrawer(t,n,e,(t,e,n)=>{this.reversedModelers.forEach(r=>r.draw(t,e,n))})})}get anchorTarget(){return this.currentModeler===this.anchorHandler||this.currentModeler===this.pathHandler||this.hovered?.isLine()||(this._anchorTarget=this.hovered),this._anchorTarget}set anchorTarget(t){this._anchorTarget=t}get hovered(){return this._hovered}set hovered(t){this._hovered=t,this.invalidate()}startLinkProcess(t,e,n){this.currentModeler=this.pathHandler,this.processingLink=this.pathHandler.startLinkProcess(t,e,n),this.counterEnd=this.processingLink.fromEnd,this.processingLink.trigger("tag")}set counterEnd(t){this.currentModeler=this.pathHandler,this._counter_end=t}get counterEnd(){return this._counter_end}endLinkProcess(){this.processingLink?.trigger("tagreset"),this.processingLink=null,this._counter_end=null}get eventMap(){return{"model-layer":{"(all)":{change:this.onchange_model,wheel:this.onwheel_scale,drop:this.ondrop},"(descendant)":{mouseenter:this.onmouseenter,mouseleave:this.onmouseleave},"(self)":{dblclick:this.ondblclick_model}},"(root)":{"(self)":{selected:this.onselected,keydown:this.onkeydown,keyup:this.onkeyup}}}}onmouseenter(t,e){this.hovered=e?.origin}onmouseleave(t,e){this.hovered=null}onkeydown(t){"Alt"==t.key&&(this._control_mode=!0,this.invalidate())}onkeyup(t){"Alt"==t.key&&(this._control_mode=!1,this.invalidate())}onselected(t,e){this.invalidate()}onchange_model(t,e,n){const{origin:r,deliverer:i}=n;r===i&&(t.translate&&this.set("translate",t.translate),void 0!==t.rotation&&this.set("rotation",t.rotation),t.scale&&this.set("scale",t.scale)),this.invalidate()}ondblclick_model(t,e){const n=e.origin;n?.root.fit()}ondblclick(t){"function"==typeof this.currentModeler.ondblclick&&this.currentModeler.ondblclick(t),this.invalidate()}onmousedown(t){this.currentModeler.onmousedown(t),this.invalidate()}onmouseup(t){"function"==typeof this.currentModeler.onmouseup&&this.currentModeler.onmouseup(t),this.invalidate()}ondragstart(t){this.currentModeler.ondragstart(t),this._state_dragging=!0}ondragmove(t){this.currentModeler.ondragmove(t),this.invalidate()}ondragend(t){this._state_dragging=!1,this.currentModeler.ondragend(t),this.invalidate()}ondrop(t,e){const{origin:n}=e,r=t.dataTransfer.files;if(r.length<1)return;const i=this.rootModel.toLocal(t.offsetX,t.offsetY),s=this.rootModel;Promise.all(Array.from(r).map(t=>new Promise((e,n)=>{const r=new FileReader;r.addEventListener("loadend",t=>{e(r.result)}),["error","abort"].forEach(t=>r.addEventListener(t,t=>{n(t)})),r.readAsDataURL(t)}))).then(e=>{if(t.altKey)return zc.around(this.app.commander,()=>{n.ondropfile(r,e)}),void(this.selected=[n]);const o=[],a=e.map((t,e)=>{let n;const a=r[e].type,c=r[e].name;return a.startsWith("image/")?(n=Qc({type:a.startsWith("image/gif")?"gif-view":"image-view",top:0,left:0,width:200,height:200,src:t},s.app),o.push(new Promise((e,r)=>{const i=new Image;i.src=t,i.onload=()=>{n.set({width:i.width,height:i.height}),e()},i.onerror=t=>{r(t)}}))):a.startsWith("audio/")?n=Qc({type:"audio",top:0,left:0,width:100,height:100,src:t},s.app):a.startsWith("vnd.ms-excel/")||/\.xlsx?$/.test(c)?n=Qc({type:"excel",top:0,left:0,width:100,height:100,src:t},s.app):Fr("dropped file",r[e]),n&&(n.center=i,i.x+=50,i.y+=50),n}).filter(Boolean).map(t=>({component:t,to_container:s}));a.length>0&&Promise.all(o).then(()=>{this.app.commander.execute(new Xc({changes:a})),this.selected=a.map(t=>t.component)},t=>{jr(t)})},t=>{jr(t)})}onwheel_scale(t,e){if(0==t.deltaY&&0==t.deltaX)return;const n=e.deliverer;let r;if(t.shiftKey)r=-1!=navigator.userAgent.indexOf("Win")?t.deltaY<0?1:-1:t.deltaX<0?1:-1,t.altKey?zc.around(this.app.commander,()=>{n.selected.forEach(t=>{let e=t.get("letterSpacing")||Mi.LETTER_SPACING;e+=r,t.set("letterSpacing",e)})}):zc.around(this.app.commander,()=>{n.selected.forEach(t=>{let e=t.get("fontSize")||Mi.FONT_SIZE;e<1&&(e=1),e+=r,t.set("fontSize",e)})});else{r=t.deltaY<0?1:-1;const e=n.get("scale")||{x:1,y:1},i=n.get("translate"),s=t.offsetX,o=t.offsetY,a=n.toLocal(s,o),c=.1*r,l={x:e.x+c,y:e.y+c};if(r<0&&e.x<.2||r>0&&e.x>10)return;n.set("scale",l);const h=n.toLocal(s,o);n.set("translate",{x:i.x+(h.x-a.x)*l.x,y:i.y+(h.y-a.y)*l.y})}}});Fa.register("scroll-layer",class extends gc{get capturable(){return!0}get pointerEvents(){return"none"}render(t){const{scrolling:e}=this.state;if(t.save(),t.beginPath(),t.fillStyle="#777",this.vscroller){const{left:n,top:r,width:i,height:s}=this.vscroller;t.globalAlpha="v"==e?1:.3,t.fillRect(n,r,i,s)}if(this.hscroller){const{left:n,top:r,width:i,height:s}=this.hscroller;t.globalAlpha="h"==e?1:.3,t.fillRect(n,r,i,s)}t.stroke(),t.restore()}resize(){super.resize(),this.calcScrollerBounds()}contains(t,e){const n=this.vscroller,r=this.hscroller;return this.setState("scrolling",n&&t>=n.left&&t<=n.left+n.width&&e>=n.top&&e<=n.top+n.height?"v":r&&t>=r.left&&t<=r.left+r.width&&e>=r.top&&e<=r.top+r.height?"h":null),!!this.getState("scrolling")}get eventMap(){return{"(root)":{"model-layer":{change:this.onchangeModelLayer}}}}onchange(t){"scrolling"in t&&this.invalidate()}ondragstart(t,e){this.lastPosition={x:t.offsetX,y:t.offsetY}}ondragmove(t,e){const n=this.root,{clientWidth:r,clientHeight:i}=this.canvas,{width:s,height:o}=this.rootModel.model,{x:a,y:c}={x:t.offsetX,y:t.offsetY},{x:l,y:h}=this._scale,{scrolling:d}=this.state,u=s/r,p=o/i;d&&n.rootModel.move({x:"h"==d?(-a+this.lastPosition.x)*l*u:0,y:"v"==d?(-c+this.lastPosition.y)*h*p:0},!1),this.lastPosition={x:t.offsetX,y:t.offsetY}}ondragend(){delete this.lastPosition,this.setState({scrolling:null})}calcScrollerBounds(){if(!this.rootModel)return;const{clientWidth:t,clientHeight:e}=this.canvas,{width:n,height:r}=this.rootModel.model,{x:i=1,y:s=1}=this._scale||{},{x:o=0,y:a=0}=this._translate||{},c=n/t,l=r/e;let h={left:-o/i/c,top:e-10,width:t/i/c,height:10};this.hscroller=h.left>1||h.width+h.left<t-1?h:null,h={left:t-10,top:-a/s/l,width:10,height:e/s/l},this.vscroller=h.top>1||h.height+h.top<e-1?h:null,this.invalidate()}onchangeModelLayer(t,e,n){if(t.scale){const{x:e=1,y:n=1}=t?.scale||{};this._scale={x:e,y:n},this.calcScrollerBounds()}if(t.translate){const{x:e=0,y:n=0}=t.translate||{};this._translate={x:e,y:n},this.calcScrollerBounds()}}});const Yd="#ff3366",Ud=[3,3];function $d(){const t=arguments,e=t[t.length-1],n=this.event_pump;n.listeners.forEach(r=>{!function(t,e,n,r,i){for(const s in n){const o=n[s];if(ca(s,r.origin,0,t))for(const t in o){const n=o[t];t==r.name&&(r.listener=e,n.apply(e,i))}}}(n.deliverer,r.listener,r.cloned_handlers,e,t)})}Fa.register("snap-guide-layer",class extends gc{constructor(){super(...arguments),this._snapResult=null}get pointerEvents(){return"none"}get capturable(){return!1}contains(t,e){return!1}get snapResult(){return this._snapResult}set snapResult(t){this._snapResult=t,this.invalidate()}clear(){this._snapResult&&(this._snapResult=null,this.invalidate())}get eventMap(){return{"(root)":{"model-layer":{change:this.onchange_root_model}}}}onchange_root_model(t){(t.translate||t.scale)&&this.syncTransform()}syncTransform(){const t=this.rootModel;if(!t)return;const e=t.get("translate")||{x:0,y:0},n=t.get("scale")||{x:1,y:1};this.set({translate:e,scale:n})}async ready(){await super.ready(),this.syncTransform()}render(t){const e=this._snapResult;if(e&&0!==e.guides.length){t.save(),t.strokeStyle=Yd,t.fillStyle=Yd,t.lineWidth=1,t.setLineDash(Ud);for(let n=0,r=e.guides.length;n<r;n++){const r=e.guides[n];t.beginPath(),"x"===r.axis?(t.moveTo(r.position,r.from),t.lineTo(r.position,r.to)):(t.moveTo(r.from,r.position),t.lineTo(r.to,r.position)),t.stroke()}t.restore()}}});class Wd{constructor(t){if(void 0===t.on)throw new Error("Deliverer should be a event handlable object.");this.deliverer=t,this.listeners=[]}start(){this.deliverer.on("(all)",$d,{event_pump:this})}stop(){this.deliverer.off("(all)",$d)}on(t,e){const n=Object.assign({},e);Object.keys(n).forEach(e=>{if(0==e.indexOf("?")){const r=n[e],i=e.substr(1),s=t.get(i);delete n[e],s?n[s]=r:Rr("EventPump#on","variable #{selector} is not evaluated on listener")}}),this.listeners.push({listener:t,handlers:e,cloned_handlers:n})}off(t,e){for(let n=0;n<this.listeners.length;n++){const r=this.listeners[n];r.listener!==t||e&&r.handlers!==e||this.listeners.splice(n,1)}}clear(){this.listeners=[]}dispose(){this.stop(),this.clear()}}class Xd{constructor(t){this.eventMaps=[],this.root=t,t.eventMap&&this.add(t,t.eventMap)}set root(t){this._root=t}get root(){return this._root}stop(){this.eventMaps.forEach(t=>t.eventPump.stop())}add(t,e){if(this.root)for(const n in e){const r=e[n];if("(self)"===n&&void 0===t.on)throw new Error("(self) selector not available when deliverer is not a event handlable object.");da(n,this.root,t).forEach(n=>{const i=new Wd(n);i.on(t,r),i.start(),this.eventMaps.push({eventPump:i,listener:t,handlerMap:e,deliverer:n})})}}remove(t,e){const n=this.eventMaps.slice(0);for(let r=0;r<n.length;r++){const i=n[r];i.listener!==t||e&&i.handlerMap!==e||(this.eventMaps.splice(r,1),i.eventPump.dispose())}}clear(){this.eventMaps.slice(0).forEach(t=>t.eventPump.dispose()),this.eventMaps=[]}dispose(){this.stop(),this.clear()}}const qd=0,Kd=1,Qd=2,Zd=0,Jd=1,tu=2;let eu={},nu=0;class ru{constructor(t,e){this._type=e||t.type,this._ctrlKey=t.ctrlKey,this._altKey=t.altKey,this._shiftKey=t.shiftKey,this._metaKey=t.metaKey;const n=function(t){if(t.touches){const e=t.touches[0];if(!e)return eu;const n=e.target.getBoundingClientRect();return eu={x:t.offsetX||e.clientX-n.left,y:t.offsetY||e.clientY-n.top},eu}return{x:t.offsetX,y:t.offsetY}}(t);if(this._offsetX=n.x,this._offsetY=n.y,t.touches&&t.touches[0]?(this._clientX=t.touches[0].clientX,this._clientY=t.touches[0].clientY):(this._clientX=t.clientX,this._clientY=t.clientY),"wheel"==t.type)this.deltaX=t.deltaX,this.deltaY=t.deltaY,this.deltaZ=t.deltaZ;else if("drop"==t.type)this.dataTransfer=t.dataTransfer;else if(t.type.match(/^touch/)&&(this._scale=t.scale,this._touches=t.touches,this._changedTouches=t.changedTouches,null==this._scale)){const e=function(t){let e,n,r=0,i=0,s=0;if(1===t.touches.length)return s;Array.from(t.touches).forEach(t=>{e=null!=e?Math.min(t.screenX,e):t.screenX,r=Math.max(t.screenX,r),n=null!=n?Math.min(t.screenY,n):t.screenY,i=Math.max(t.screenY,i)});const o=r-e||0,a=i-n||0;return s=Math.sqrt(Math.pow(o,2)+Math.pow(a,2))||0,s}(t);nu>0&&(this._scale=e/nu),nu=e}}get type(){return this._type}set type(t){this._type=t}get offsetX(){return this._offsetX}get offsetY(){return this._offsetY}get altKey(){return this._altKey}get ctrlKey(){return this._ctrlKey}get shiftKey(){return this._shiftKey}get metaKey(){return this._metaKey}get clientX(){return this._clientX}get clientY(){return this._clientY}get touches(){return this._touches}get changedTouches(){return this._changedTouches}get scale(){return this._scale}stopPropagation(){this._stop_=!0,this.originalEvent?.stopPropagation()}isPropagationStopped(){return this._stop_}preventDefault(){this._prevented=!0}isDefaultPrevented(){return this._prevented}}function iu(t,e,n){if(!t||!t.app)return;if(t.app.isViewMode&&t.hidden)return;n instanceof ru&&e===n.type||(n=new ru(n,e));const r="on"+e;t[r]&&t[r](n),n.isPropagationStopped()||t.trigger(e,n)}class su{constructor(t,e){this.gestureHandlerBuilder=t=>{const e=this[`on${t}`];return t=>{const n=new ru(t),r=this.getChildScrollOffset();return n._offsetX+=this.html_element.scrollLeft+r.scrollLeft,n._offsetY+=this.html_element.scrollTop+r.scrollTop,e(n),n.isDefaultPrevented()&&t.preventDefault(),!1}},this.keyeventHandlerBuilder=t=>this[`on${t}`],this.ondragover=t=>(iu(this.findTarget(t),t.type,t),!1),this.ondrop=t=>(iu(this.findTarget(t),t.type,t),!1),this.ondblclick=t=>(iu(this.findTarget(t),t.type,t),this.last_target=null,!1),this.onkeydown=t=>(this.container.trigger(t.type,t),!1),this.onkeyup=t=>(this.container.trigger(t.type,t),!1),this.onmousemove=t=>{switch(this.status){case Kd:const e=t.offsetX-this.__dragstart_e.offsetX,n=t.offsetY-this.__dragstart_e.offsetY;if(e*e+n*n<16)break;this.status=Qd,iu(this.last_target,"dragstart",this.__dragstart_e),this.__dragmove_e=t,iu(this.last_target,"dragmove",t);break;case Qd:this.__dragmove_e=t,iu(this.last_target,"dragmove",t);break;default:{const e=this.findTarget(t);this.last_enter_target!==e&&(this.last_enter_target&&iu(this.last_enter_target,"mouseleave",t),e&&iu(e,"mouseenter",t),this.last_enter_target=e),iu(e,t.type,t),this.last_target=e}}return!1},this.onmousedown=t=>{if(this.status===Qd)iu(this.last_target,"dragend",t),this.last_target=null,this.status=qd;else{const e=this.findTarget(t);this.last_target=e,this.status=Kd,this.__dragstart_e=t,iu(e,t.type,t)}return!1},this.onmouseup=t=>{if(this.status===Qd)iu(this.last_target,"dragend",t);else{const e=this.findTarget(t);iu(e,t.type,t),this.last_target===e&&iu(e,"click",t)}return this.last_target=null,this.status=qd,!1},this.onmouseout=t=>{const e=this.findTarget(t);if(this.status===Qd)iu(this.last_target,"dragend",t);else{if(this.last_target&&this.last_target===e)return;this.last_enter_target&&(iu(this.last_enter_target,"mouseleave",t),delete this.last_enter_target)}return this.last_target=null,this.status=qd,!1},this.ontouchstart=t=>{const e=this.findTarget(t);return this.last_target=e,this.status=Jd,this.touchPoints||(this.touchPoints=[]),this.touchPoints.push(t.changedTouches[0]),this.holdTimer=setTimeout(()=>{this.status=Zd,iu(this.last_target,"hold",t),delete this.holdTimer},500),iu(e,t.type,t),!1},this.ontouchmove=t=>{if(!t.touches||!t.changedTouches)return iu(this.last_target,"dragstart",t),iu(this.last_target,"dragmove",t),!1;let e=this.findTarget(t);switch(this.status){case Jd:Array.from(t.changedTouches).forEach(t=>{const e=this.touchPoints.find(e=>e.identifier===t.identifier);if(!e)return;const n=e.clientX-t.clientX,r=e.clientY-t.clientY;return Math.sqrt(Math.pow(n,2)+Math.pow(r,2))>=16?(this.status=tu,void(this.holdTimer&&(clearTimeout(this.holdTimer),delete this.holdTimer))):void 0});break;case tu:if(this.holdTimer&&(clearTimeout(this.holdTimer),delete this.holdTimer),2===t.changedTouches.length&&null!=t.scale&&1!==t.scale&&(t.scale<.9||t.scale>1.1))return iu(this.last_target,"pinch",t),!1;iu(this.last_target,"pan",t),e=this.last_target;break;default:this.last_enter_target!==e&&(this.last_enter_target&&iu(this.last_enter_target,"mouseleave",t),e&&iu(e,"mouseenter",t),this.last_enter_target=e),this.last_target=e}return iu(e,"touchmove",t),!1},this.ontouchend=t=>{let e=this.findTarget(t);switch(this.status){case tu:e=this.last_target;break;case Jd:{const n=performance.now(),r=n-this.touchedAt;this.holdTimer&&(clearTimeout(this.holdTimer),delete this.holdTimer,iu(e,r<500?"doubletap":"tap",t),this.touchedAt=n);break}}iu(e,"touchend",t);const n=this.touchPoints.findIndex(e=>e.identifier===t.changedTouches[0].identifier);return this.touchPoints.splice(n,1),this.last_target=null,this.status=Zd,!1},this.onwheel=t=>(iu(this.findTarget(t),t.type,t),!1),this.container=t,this.html_element=e,this.status=qd,this.last_target=null,this.gesture_handlers=xi.map(t=>this.gestureHandlerBuilder(t)),this.keyevent_handlers=wi.map(t=>this.keyeventHandlerBuilder(t)),xi.forEach((t,n)=>e.addEventListener(t,this.gesture_handlers[n]),{passive:!1}),wi.forEach((t,n)=>e.addEventListener(t,this.keyevent_handlers[n])),e.ondragover=this.gestureHandlerBuilder("dragover"),e.ondrop=this.gestureHandlerBuilder("drop"),e.tabIndex=1}dispose(){this.last_enter_target&&iu(this.last_enter_target,"mouseleave",new CustomEvent("mouseleave")),xi.forEach((t,e)=>this.html_element.removeEventListener(t,this.gesture_handlers[e])),wi.forEach((t,e)=>this.html_element.removeEventListener(t,this.keyevent_handlers[e])),delete this.gesture_handlers,delete this.keyevent_handlers,delete this.last_target}getChildScrollOffset(){for(const t of this.html_element.children)if(t.scrollTop>0||t.scrollLeft>0)return{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop};return{scrollLeft:0,scrollTop:0}}findTarget(t){const e=this.container.rootModel;if(e?.is3dMode)return e;const n=this.html_element.getBoundingClientRect(),r=this.getChildScrollOffset(),i=t.clientX-n.left+this.html_element.scrollLeft+r.scrollLeft,s=t.clientY-n.top+this.html_element.scrollTop+r.scrollTop;return this.container.capture(i,s)}}function ou(t,e,n,r=0){if(e.length<2)return e;let i=2;for(;i<e.length;i++){const s=e.substring(0,i);if(!(t.measureText(s).width+(s.length-1)*r<n))break}return e.substring(0,i-1)}function au(t,e,n,r,i=0){const s=String(e).split("\n");return r?[].concat.apply([],s.map(e=>function(t,e,n,r=0){const i=e.split(" "),s=[];let o,a,c=[];for(o=0,a=1;a<=i.length;a++)if(c=i.slice(o,a),t.measureText(c.join(" ")).width+(c.join("").length-1)*r>n){if(a-o==1){const e=ou(t,c[0],n,r);s.push([e]),i.splice(o,1,e,c[0].substring(e.length))}else{for(;""==i[a-1];)a++;s.push(i.slice(o,--a))}o=a}return a-o>1&&s.push(c),0==s.length&&s.push([""]),s}(t,e,n,i))):s.map(t=>t.split(" "))}const cu={},lu={},hu=()=>{};var du={register:function(t,e,n){cu[t]=e,n&&(lu[t]=n)},unregister:function(t){delete cu[t],delete lu[t]},get:function(t){return cu[t]},getDisposer:function(t){return lu[t]||hu}};function uu(t){if(!t.hasTextProperty||t.textHidden)return;let{text:e="",bold:n=Mi.BOLD,italic:r=Mi.ITALIC,textWrap:i=Mi.TEXT_WRAP,letterSpacing:s=0,fontFamily:o=Mi.FONT_FAMILY,fontColor:a=Mi.FONT_COLOR,textAlign:c=Mi.TEXT_ALIGN,textBaseline:l=Mi.TEXT_BASELINE,fontSize:h=Mi.FONT_SIZE,lineHeight:d=1.2*h}=t.model;const{left:u,top:p,width:f,height:g}=t.textBounds;h||=Mi.FONT_SIZE,d||=1.2*h,t.textHidden=!0;const m=document.createElement("textarea"),y=new AbortController;xi.forEach(function(t){m.addEventListener(t,t=>t.stopPropagation(),{capture:!0,signal:y.signal})});const b=t.toGlobal(u,p),{rotation:v,scale:_}=function(t){let e=0,n=1,r=t;for(;r;){e+=r.get("rotation")||0;const{x:t,y:i}=r.get("scale")||{x:1,y:1};n*=Math.max(t,i)||1,r=r.parent}return{rotation:e,scale:n}}(t);m.value=e;const x={position:"absolute",width:f+"px",height:g+"px",padding:"0",fontFamily:o,fontSize:h+"px",lineHeight:d+"px",overflow:"hidden",resize:"none",outline:"none",border:"0",backgroundColor:"transparent",display:"inline-block",color:a};switch(n&&(x.fontWeight="bold"),r&&(x.fontStyle="italic"),c){case"right":case"end":x.textAlign="right";break;case"justify":x.textAlign="justify";break;case"left":case"start":x.textAlign="left";break;default:x.textAlign="center"}const w=[n,r,h+"px",o].filter(Boolean).join(" ");function M(e){const n={left:0,top:0},r=d*function(t,e,n,r,i=0){const s=t.getContext();let o;return s.save(),s.font=n,o=au(s,e,r,t.get("textWrap"),i).length,s.restore(),o}(t,e,w,f,s);switch(x.height=r+"px",l){case"top":case"hanging":break;case"bottom":case"alphabetic":n.top=g-r;break;default:n.top=g/2-r/2}if(!i){const r=function(t,e,n,r){const i=e.split("\n");let s=r;const o=t.getContext();return o.save(),o.font=n,i.forEach(t=>{const e=o.measureText(t).width;e>s&&(s=e)}),o.restore(),s}(t,e,w,f);switch(x.width=r+"px",c){case"right":case"end":n.left=f-r;break;case"left":case"start":break;default:n.left=(f-r)/2}}x.marginLeft=n.left+"px",x.marginTop=n.top+"px",x.transform=`translate(${b.x}px, ${b.y}px) scale(${_}) rotate(${v}rad)`,x.transformOrigin=`${-n.left}px ${-n.top}px`,Object.assign(m.style,x)}M(e);const S=t.root.target_element;S.appendChild(m),m.select();let A,E=!1;m.addEventListener("keydown",function(t){t.stopPropagation(),"Escape"!=t.code&&(t.shiftKey||"Enter"!=t.code&&"NumpadEnter"!=t.code)?setTimeout(()=>{M(m.value)}):(E=A.skipUpdate="Escape"==t.code,"function"==typeof document.createEvent?m.dispatchEvent(A):m.fireEvent(A.eventType,A))},{signal:y.signal}),document.createEvent?(A=document.createEvent("HTMLEvents"),A.initEvent("blur",!0,!1)):(A=document.createEventObject(),A.eventType="blur");const k=t.root.selected,C=function(n){t.root.selected=k,t.textHidden=!1,y.abort(),m.removeEventListener("blur",C,!1),m.parentElement&&m.parentElement.removeChild(m),S.focus(),n.skipUpdate||E||t.app.commander.execute(new zc({changes:[{component:t,before:{text:e},after:{text:m.value}}]}))};m.addEventListener("blur",C,!1)}du.register("text-editor",{"(root)":{"(self)":{keydown:function(t,e){const{deliverer:n}=e,r=n.selected;return!(1!==r.length||!r[0].hasTextProperty)&&(("Enter"==t.code||"NumpadEnter"==t.code)&&(uu(r[0]),t.preventDefault(),!0))}}},"model-layer":{"(descendant)":{dblclick:function(t,e){uu(e.origin)}}}});class pu{constructor(t){const e=[],n=[];for(let r=0,i=t.length;r<i;r++){const i=t[r],s=i.left,o=i.left+i.width,a=s+i.width/2,c=i.top,l=i.top+i.height,h=c+i.height/2;e.push({value:s,perpMin:c,perpMax:l},{value:a,perpMin:c,perpMax:l},{value:o,perpMin:c,perpMax:l}),n.push({value:c,perpMin:s,perpMax:o},{value:h,perpMin:s,perpMax:o},{value:l,perpMin:s,perpMax:o})}e.sort((t,e)=>t.value-e.value),n.sort((t,e)=>t.value-e.value),this.xEdges=e,this.yEdges=n}get empty(){return 0===this.xEdges.length&&0===this.yEdges.length}calculateSnap(t,e,n,r){if(0===this.xEdges.length&&0===this.yEdges.length)return{dx:e,dy:n,guides:[]};const i={left:t.left+e,top:t.top+n,width:t.width,height:t.height},s=i.left,o=s+i.width,a=s+i.width/2,c=i.top,l=c+i.height,h=c+i.height/2,d=this.findBestSnap(this.xEdges,[s,a,o],r),u=this.findBestSnap(this.yEdges,[c,h,l],r),p=d?e+d.correction:e,f=u?n+u.correction:n;if(!d&&!u)return{dx:e,dy:n,guides:[]};const g=[];if(d){const e=t.top+f,n=e+t.height;for(const t of d.matches)g.push({axis:"x",position:t.value,from:Math.min(e,t.perpMin),to:Math.max(n,t.perpMax)})}if(u){const e=t.left+p,n=e+t.width;for(const t of u.matches)g.push({axis:"y",position:t.value,from:Math.min(e,t.perpMin),to:Math.max(n,t.perpMax)})}return{dx:p,dy:f,guides:g}}findBestSnap(t,e,n){let r=n+1,i=0,s=[];for(let o=0;o<3;o++){const a=e[o],c=this.searchNearest(t,a,n);if(!c)continue;const l=Math.abs(c.correction);if(l<r)r=l,i=c.correction,s=c.matches;else if(l===r&&c.correction===i)for(const t of c.matches)s.push(t)}return r<=n?{correction:i,matches:s}:null}searchNearest(t,e,n){const r=t.length;if(0===r)return null;let i=0,s=r;for(;i<s;){const n=i+s>>1;t[n].value<e?i=n+1:s=n}let o=-1,a=n+1;if(i<r){const r=t[i].value-e;r<=n&&(o=i,a=r)}if(i>0){const n=e-t[i-1].value;n<a&&(o=i-1,a=n)}if(o<0||a>n)return null;const c=t[o].value,l=c-e,h=[t[o]];for(let e=o-1;e>=0&&t[e].value===c;e--)h.push(t[e]);for(let e=o+1;e<r&&t[e].value===c;e++)h.push(t[e]);return{correction:l,matches:h}}}function fu(t){const e=t.root;if(!e||!e.assist_layers)return null;for(const t of e.assist_layers)if("snap-guide-layer"===t.state?.type)return t;return null}const gu=Qn(function(t,e,n){if(!t.hasSameParentForAllSelected||n)return void(t.focused=null);const r=[];e[0].parent.isGroup()?t.focused=e[0].parent:(e.forEach(t=>{t.path.forEach(e=>{r.push(t.toScene(e.x,e.y))})}),t.focused=t.capturePath(r,e))},300);let mu,yu,bu;du.register("move-handler",{"model-layer":{"(descendant)":{dragstart:function(t,e){const{origin:n,deliverer:r}=e;if(n.stuck)return;let i=r.selected;const s=r.selected.filter(t=>!t.stuck);if(i.length!==s.length&&(i=r.selected=s),0==i.length)return;let o;if(i[0].scalable?(o=i[0].toLocal(t.offsetX,t.offsetY),o=i[0].toParent(o.x,o.y)):o={x:t.offsetX,y:t.offsetY},this.last_pos=o,this.direction=0,r.focused=i[0].parent,t.altKey){const t=[],e=new Map;r.selected=r.selected.filter(t=>!t.isRootModel()).map(n=>{const i=Zc(n,t=>{const n=r.root.getNewRefid();return void 0!==t&&e.set(t,n),n});return t.push({component:i,to_container:n.parent}),i}).map(t=>(t.replaceRefids(e),t)),t.forEach(({component:t,to_container:e})=>{e.addComponent(t)}),this.duplicates=r.selected.map(t=>({component:t}))}else this.changes=zc.before(i);this.snapIndex=function(t){if(0===t.length)return null;const e=t[0].parent;if(!e||!e.components)return null;const n=new Set(t),r=[];for(const t of e.components)t.isLayer?.()||t.stuck||n.has(t)||r.push(t.bounds);return 0===r.length?null:new pu(r)}(i);const a=n.rootModel?.get("scale"),c=a?(Math.abs(a.x)+Math.abs(a.y))/2:1;this.snapThreshold=5/(c||1)},dragmove:function(t,e){const{origin:n,deliverer:r}=e;if(n.stuck)return;const i=r.selected;if(0==i.length)return;let s;i[0].scalable?(s=i[0].toLocal(t.offsetX,t.offsetY),s=i[0].toParent(s.x,s.y)):s={x:t.offsetX,y:t.offsetY},t.shiftKey?2==this.direction&&(this.direction=0):this.direction=2;let o=s.x-this.last_pos.x,a=s.y-this.last_pos.y;if(0==this.direction){if(o*o+a*a<25)return;Math.abs(o)>Math.abs(a)?this.direction=3:this.direction=4}3==this.direction?a=0:4==this.direction&&(o=0);const c=this.snapIndex,l=c&&!t.metaKey&&!t.ctrlKey,h=o,d=a;if(l){const t=function(t){return 0===t.length?null:1===t.length?t[0].bounds:Ji(t.map(t=>t.bounds))}(i);if(t){const e=c.calculateSnap(t,o,a,this.snapThreshold);o=e.dx,a=e.dy;const n=fu(r);n&&(n.snapResult=e.guides.length>0?e:null)}}else{const t=fu(r);t&&(t.snapResult=null)}i.forEach(t=>{t.move({x:o,y:a},1===i.length)}),this.last_pos={x:s.x-(h-o),y:s.y-(d-a)},gu(r,i)},dragend:function(t,e){const{origin:n,deliverer:r}=e;if(n.stuck)return;const i=r.selected;if(0==i.length)return;const s=i[0].parent,o=r.focused||e.deliverer;if(this.changes&&!o.isGroup())if(r.hasSameParentForAllSelected&&o&&o!==s){const t=this.changes.map(t=>{const{component:e}=t;return{component:e,to_container:o}});r.app.commander.execute(new Xc({changes:t}))}else zc.after(this.changes,r.app.commander);else if(this.duplicates){this.duplicates=this.duplicates.map(t=>(t.to_container=o,t));const t=new Xc({changes:this.duplicates});r.app.commander.execute(t)}i.forEach(t=>{t.parent&&t.parent.calculateBounds&&t.parent.calculateBounds()}),this.last_pos=null,this.changes=null,this.duplicates=null,this.snapIndex=null,this.snapThreshold=5;const a=fu(r);a&&a.clear(),gu(r,i,!0)}}},"(root)":{"(self)":{keydown:function(t,e){const{origin:n,deliverer:r}=e,i={},s=t.shiftKey?n.rootModel.MPP:1;switch(t.which){case 37:i.x=-s,i.y=0;break;case 38:i.x=0,i.y=-s;break;case 39:i.x=s,i.y=0;break;case 40:i.x=0,i.y=s;break;default:return}const o=r.selected;zc.around(r.app.commander,function(){o.forEach(t=>{!t.stuck&&t.move(i,!1)})})}}}});const vu=Zn(()=>{const{x:t,y:e}=bu,n=yu.deref();n&&(n.rootModel.move({x:t-mu.x,y:e-mu.y},!1),mu={x:t,y:e})},60,{leading:!0,trailing:!0});du.register("shift-handler",{"model-layer":{"(all)":{dragstart:function(t,e){mu={x:t.offsetX,y:t.offsetY}},dragmove:function(t,e){yu=new WeakRef(e.deliverer),bu={x:t.offsetX,y:t.offsetY},vu()}}}}),du.register("zoom-handler",{"model-layer":{"(all)":{wheel:function(t,e){if(0==t.deltaY&&0==t.deltaX)return;const n=e.deliverer,r=t.deltaY<0?1:-1,i=n.get("scale")||{x:1,y:1},s=n.get("translate"),o=t.offsetX,a=t.offsetY,c=n.toLocal(o,a),l=.1*r,h={x:i.x+l,y:i.y+l};if(r<0&&i.x<.2||r>0&&i.x>10)return;n.set("scale",h);const d=n.toLocal(o,a);n.set("translate",{x:s.x+(d.x-c.x)*h.x,y:s.y+(d.y-c.y)*h.y})}},"(self)":{dblclick:function(t,e){const n=e.origin;n?.root.fit()}}}});let _u={},xu={};function wu(t){const e={};for(const n in t)t.hasOwnProperty(n)&&void 0!==t[n]&&(e[n]=t[n]);return e}du.register("paste-handler",{"(root)":{"(self)":{stylepastestart:function(t){const{deliverer:e}=t,n=e.app,r=e.selected;if(r&&r[0]&&r!==e.rootModel){const t=r[0],{fillStyle:e,strokeStyle:i,alpha:s,lineWidth:o,lineDash:a,lineCap:c,lineJoin:l,fontColor:h,fontSize:d,fontFamily:u,bold:p,italic:f,textAlign:g,textBaseline:m,textOverflow:y,paddingTop:b,paddingBottom:v,paddingLeft:_,paddingRight:x}=t.state;_u=Bn({fillStyle:e,strokeStyle:i,alpha:s,lineWidth:o,lineDash:a,lineCap:c,lineJoin:l,fontColor:h,fontSize:d,fontFamily:u,bold:p,italic:f,textAlign:g,textBaseline:m,textOverflow:y,paddingTop:b,paddingBottom:v,paddingLeft:_,paddingRight:x}),n.mode=4}},stylepastestop:function(t){const{deliverer:e}=t,n=e.app;_u={},4==n.mode&&(n.mode=1)},databindpastestart:function(t){const{deliverer:e}=t,n=e.app,r=e.selected;if(r&&r[0]&&r!==e.rootModel){const t=r[0],{mappings:e}=t.state;xu=Bn({mappings:e}),n.mode=5}},databindpastestop:function(t){const{deliverer:e}=t,n=e.app;xu={},5==n.mode&&(n.mode=1)},pasteapply:function(t,e){const{deliverer:n}=e,r=n.app;t&&(4==r.mode?zc.around(r.commander,()=>{t.set(wu({...t.model,..._u}))}):5==r.mode&&zc.around(r.commander,()=>{t.set(wu({...t.model,...xu}))}))},keydown:function(t,e){const{deliverer:n}=e;"Esc"!=t.code&&"Escape"!=t.code||(4==n.app.mode?n.trigger("stylepastestop"):5==n.app.mode&&n.trigger("databindpastestop"))}}},"model-layer":{"(all)":{click:function(t,e){const{deliverer:n}=e,r=n.app;if(4!=r.mode&&5!=r.mode)return;const i=e.origin;4==r.mode?i===n?n.root.trigger("stylepastestop"):i&&zc.around(r.commander,()=>{const t=wu({...i.model,..._u});i?.set(t)}):i===n?n.root.trigger("databindpastestop"):i&&zc.around(r.commander,()=>{const t=wu({...i.model,...xu});i?.set(t)})}}}});class Mu{constructor(){this.animatorMap=new Map}waypoint(t,e){this.animatorMap.has(t)&&this.off(t);let{from:n,to:r}=e;if("string"==typeof n&&(n=t.root?.findById(n)),"string"==typeof r&&(r=t.root.findById(r)),!r)return void Rr("WaypointAnimation: Source or target component not found");const i=No(t,{type:"waypoint",fromComponent:n,toComponent:r,...e,onComplete:()=>{this.off(t)}});i&&(this.animatorMap.set(t,i),i.start())}off(t){const e=this.animatorMap.get(t);e&&(e.stop(),this.animatorMap.delete(t))}reset(t){if(this.animatorMap.size>0){for(const t of this.animatorMap.values())t.stop();this.animatorMap.clear()}}dispose(){this.reset(null),this.animatorMap=null}}function Su(t){const{origin:e}=t,n=e.root,{waypointHandler:r}=n;r?.reset()}du.register("waypoint-handler",{"model-layer":{"(descendant)":{waypoint:function(t,e){const{origin:n}=e,r=n.root;let{waypointHandler:i}=r;i||(i=new Mu,r.waypointHandler=i),i.waypoint(n,t)},waypointoff:function(t){const{origin:e}=t,n=e.root,{waypointHandler:r}=n;r?r.off(e):Rr("waypoint-handler not found")},waypointreset:Su},"(self)":{waypointreset:Su}}},function(t){const{waypointHandler:e}=t;e&&(e.dispose(),delete t.waypointHandler)});const Au=[],Eu=Qn(function(){Au.forEach(t=>{t.resize()})},100);"undefined"!=typeof window&&window.addEventListener("resize",Eu);class ku extends fc{constructor(t,e){super(Object.assign({type:"root",scale:{x:1,y:1}},t||{}),e),this._hasSameParentForAllSelected=!1,this._maxRefid=e?.isViewMode?1e6:0,t=t||{},this.fitMode=t.model&&t.model.fitMode,this._app=e,this.style=t.style,this.indexMap=new Map,this.refidIndexMap=new Map,this.templateMap={},this._serviceMap=new Map,this.target_element=t.target_element,this.rebuildContentModel(this.model.model),Au.push(this)}registerService(t,e){this._serviceMap.set(t,e)}getService(t){return this._serviceMap.get(t)}unregisterService(t){this._serviceMap.delete(t)}dispose(){hc.hideAll(this),this._app&&this._app.dispose(),super.dispose(),this._disposeAllResources(),this.target_element=null,this._refresh_mapping_debouncer&&"function"==typeof this._refresh_mapping_debouncer.cancel&&this._refresh_mapping_debouncer.cancel(),delete this._refresh_mapping_debouncer;const t=Au.indexOf(this);t>=0&&Au.splice(t,1),this.refidIndexMap.clear(),this.indexMap.clear(),this._serviceMap.clear(),this._maxRefid=0}isRoot(){return!0}get app(){return this._app}get target_element(){return this._target_element}set target_element(t){this._ua_event_handler&&(this._ua_event_handler.dispose(),delete this._ua_event_handler),t&&(t.style.position="absolute",t.style.cursor="default",t.style.overflow="hidden",t.setAttribute("scene","root-container"),this._ua_event_handler=new su(this,t)),this.forEach(e=>e.target=t),this._target_element=t}get fitMode(){return this._fitMode}set fitMode(t){this._fitMode=t}get hasSameParentForAllSelected(){return this._hasSameParentForAllSelected}set hasSameParentForAllSelected(t){this._hasSameParentForAllSelected=t}get unitScale(){switch(this.model_layer&&this.model_layer.get("unit")){case"mm":case"cm":case"in":return this.app.PPM/10;default:return 1}}addTemplate(t,e){const n=this.templateMap[t];n&&jr("Template replaced (duplicated)",t,e,n),this.templateMap[t]=e,delete this.templatePrefixes}removeTemplate(t,e){const n=this.templateMap[t];n!==e?Rr("Removing template failed (different)",t,e,n):delete this.templateMap[t],delete this.templatePrefixes}findTemplateFor(t){this.templatePrefixes||(this.templatePrefixes=Object.keys(this.templateMap).sort().reverse());const e=this.templatePrefixes.find(e=>t.startsWith(e));if(e)return this.templateMap[e]}addIndex(t,e){if(!t)return;const n=t.toString().replace(/^#/,""),r=this.indexMap.get(n)||[];r.push(e),this.indexMap.set(n,r)}removeIndex(t,e){if(!t)return;const n=t.toString().replace(/^#/,""),r=this.indexMap.get(n)||[],i=r.indexOf(e);-1===i?Rr("Removing index failed (not found)",t,e):(r.splice(i,1),0===r.length?this.indexMap.delete(n):this.indexMap.set(n,r))}addRefidIndex(t,e){null==t&&(t=this.getNewRefid(),e.set("refid",t)),this._maxRefid=Math.max(t,this._maxRefid);const n=this.refidIndexMap.get(t);n&&jr("Refid Index replaced (has not to be)",t,e,n),this.refidIndexMap.set(t,e)}removeRefidIndex(t,e){if(null==t)return;const n=this.refidIndexMap.get(t);n!==e?jr("Refid Removing index failed (has not to be)",t,e,n):this.refidIndexMap.delete(t)}getNewRefid(){return this._maxRefid=(this._maxRefid||0)+1,this._maxRefid}async subscribe(t,e){this._app.isViewMode&&t&&this._app&&(e._subscription=await this._app.subscribe(t,e))}async unsubscribe(t,e){e._subscription&&(await e._subscription.unsubscribe(),delete e._subscription)}findById(t){if(!t)return null;const e=t.toString().replace(/^#/,"");return(this.indexMap.get(e)||[])[0]}findAllById(t){if(!t)return[];const e=t.toString().replace(/^#/,"");return this.indexMap.get(e)||[]}findByRefid(t){return this.refidIndexMap.get(t)}findOrCreate(t){const e=this.findAllById(t);if(!e||0===e.length){if(this.app&&!this.app.isEditMode){const e=this.findTemplateFor(t);if(e){const n=Qc(Object.assign(Bn(e.hierarchy),{id:t,templatePrefix:""}),this.app);return this.model_layer.addComponent(n),[n]}}return[]}return e}resize(){this.components.forEach(t=>{t.resize&&t.resize()}),this.invalidate()}fit(t){const{width:e,height:n,fitMode:r}=this.model_layer.model,i=this.target_element,s=this.model_layer;if(this.fitMode=t||this.fitMode||r||"ratio",e&&n&&i&&i.clientWidth&&i.clientHeight){switch(this.fitMode){case"center":!function(t,e,n){const r=t.unitScale,{width:i,height:s}=e.model;e.set("scale",{x:r,y:r}),e.set("translate",{x:Math.max((n.clientWidth-i*r)/2,0),y:Math.max((n.clientHeight-s*r)/2,0)})}(this,s,i);break;case"both":!function(t,e,n){const{width:r,height:i}=e.model,s=n.clientWidth,o=n.clientHeight;e.set("scale",{x:s/r,y:o/i}),e.set("translate",{x:0,y:0})}(0,s,i);break;case"width":!function(t,e,n){const r=n.clientWidth/e.get("width");e.set("scale",{x:r,y:r}),e.set("translate",{x:0,y:0})}(0,s,i);break;case"height":!function(t,e,n){const r=n.clientHeight/e.get("height");e.set("scale",{x:r,y:r}),e.set("translate",{x:0,y:0})}(0,s,i);break;case"ratio":!function(t,e,n){const{width:r,height:i}=e.model,s=n.clientWidth,o=n.clientHeight,a=s/r,c=o/i,l=Math.min(a,c);e.set("scale",{x:l,y:l}),e.set("translate",{x:(s-r*l)/2,y:(o-i*l)/2})}(0,s,i);break;default:!function(t,e){const n=t.unitScale;e.set("scale",{x:n,y:n}),e.set("translate",{x:0,y:0})}(this,s)}this.resize()}}_disposeAllResources(){this.selected=[],this._focused=null,this._ready=!1,this.eventEngine&&(this.assist_handlers&&this.assist_handlers.forEach(t=>{this.eventEngine.remove(t)}),this.eventEngine.dispose(),delete this.eventEngine),(this.model.handlers||[]).map(t=>{du.getDisposer(t).call(null,this)}),this.assist_layers&&this.assist_layers.forEach(t=>{t.dispose(),this.removeComponent(t)}),delete this.assist_layers,this.model_layer&&this.model_layer.dispose(),this.model_layer&&this.removeComponent(this.model_layer),delete this.model_layer,this.indexMap=new Map,this.refidIndexMap=new Map,this.templateMap={}}rebuildContentModel(t,e){let n;e?.preserveThreeD&&this.model_layer?.is3dMode&&(n=this.model_layer.detachThreeCapability()),this._disposeAllResources(),this.eventEngine=new Xd(this),(t=t||{}).type="model-layer",this.model_layer=Qc(t,this.app),this.addComponent(this.model_layer),this.model_layer.target=this.target_element,this.assist_layers=(this.model.layers||[]).map(t=>{const e=Qc(t,this.app);if(e)return this.addComponent(e),e.target=this.target_element,e;jr("Layer compile failed",t)}).filter(Boolean),this.assist_handlers=(this.model.handlers||[]).map(t=>{const e={};return this.eventEngine.add(e,du.get(t)),e}),n&&(this.model_layer?.model?.threed?this.model_layer.adoptThreeCapability(n):n.dispose()),this._ready=!0,this.traverse(t=>t.ready())}get root(){return this}get anchors(){return[]}get isReady(){return this._ready}get rootModel(){return this.model_layer}get threed(){return this.model_layer?.model?.threed||!1}set threed(t){this.model_layer&&this.model_layer.set("threed",t)}get stuck(){return!0}get data(){const t={};for(const[e,n]of this.indexMap.entries())n.length>0&&(t[e]=n[0].data);return t}set data(t){for(const e in t){const n=this.findOrCreate(e);n&&0!==n.length&&n.forEach(n=>n.data=t[e])}}get dataByRefid(){const t={};for(const[e,n]of this.refidIndexMap.entries())t[e]=n.data;return t}set dataByRefid(t){for(const e in t){const n=this.findByRefid(Number(e));n&&(n.data=t[e])}}get values(){const t={};for(const[e,n]of this.indexMap.entries())n.length>0&&(t[e]=n[0].value);return t}set values(t){for(const e in t){const n=this.findOrCreate(e);n&&0!==n.length&&n.forEach(n=>n.value=t[e])}}get valuesByRefid(){const t={};for(const[e,n]of this.refidIndexMap.entries())t[e]=n.value;return t}set valuesByRefid(t){for(const e in t){const n=this.findByRefid(Number(e));n&&(n.value=t[e])}}get selected(){return(this._selected||[]).filter(t=>t.parent)}set selected(t){const e=this._selected;if(this._selected=t,!t||t.length<=1)this.hasSameParentForAllSelected=!0;else{const e=t[0].parent;this.hasSameParentForAllSelected=!t.find(t=>t.parent!=e)}this.trigger("selected",t,e)}get focused(){return this._focused}set focused(t){this._focused!==t&&(this._focused=t,this.invalidate())}get style(){return this._style}set style(t){this._style=t,this._compiled_style=t}get hasTextProperty(){return!1}render(){this.components.forEach(t=>t.draw())}contains(t,e){return!0}capturePath(t,e){return this.model_layer.capturePath(t,e)}invalidate(){this.components.forEach(t=>t.invalidate())}_areAliasesEqual(t,e){if(!Array.isArray(t)&&!Array.isArray(e))return!0;if(!Array.isArray(t)||!Array.isArray(e))return!1;if(t.length!==e.length)return!1;const n=[...t].sort(),r=[...e].sort();return n.every((t,e)=>t===r[e])}get eventMap(){return{"(root)":{"(descendant)":{added:this.onadded,removed:this.onremoved,change:this.onchanged}}}}refreshMappings(){if(!this._refresh_mapping_debouncer){if(this.disposed)return;this._refresh_mapping_debouncer=Qn(function t(e){e.executeMappings(),e.components&&e.components.forEach(e=>t(e))},1e3)}this._refresh_mapping_debouncer(this.model_layer)}_addTraverse(t){t.components&&t.components.forEach(t=>this._addTraverse(t));const{id:e,alias:n,refid:r,tag:i,templatePrefix:s}=t.model;this.addRefidIndex(r,t),e&&this.addIndex(e,t),Array.isArray(n)&&n.forEach(e=>{e&&this.addIndex(e,t)}),i&&this.subscribe(i,t),s&&this.addTemplate(s,t);const o=sr({},t.eventMap,t.model.eventMap);this.eventEngine.add(t,o)}_removeTraverse(t){t.components&&t.components.forEach(t=>this._removeTraverse(t));const{id:e,alias:n,refid:r,tag:i,templatePrefix:s}=t.model;this.removeRefidIndex(r,t),e&&this.removeIndex(e,t),Array.isArray(n)&&n.forEach(e=>{e&&this.removeIndex(e,t)}),i&&this.unsubscribe(i,t),s&&this.removeTemplate(s,t),this.eventEngine.remove(t)}onadded(t,e){this._addTraverse(e),this.refreshMappings(),this.invalidate()}onremoved(t,e){this._removeTraverse(e),this.invalidate()}onchanged(t,e,n){e.templatePrefix&&this.removeTemplate(e.templatePrefix,n.origin),t.templatePrefix&&this.addTemplate(t.templatePrefix,n.origin),e.id&&this.removeIndex(e.id,n.origin),t.id&&this.addIndex(t.id,n.origin),Array.isArray(e.alias)&&e.alias.forEach(t=>{t&&this.removeIndex(t,n.origin)}),Array.isArray(t.alias)&&t.alias.forEach(t=>{t&&this.addIndex(t,n.origin)}),e.tag&&this.unsubscribe(e.tag,n.origin),t.tag&&this.subscribe(t.tag,n.origin),e.id==t.id&&e.class==t.class&&this._areAliasesEqual(e.alias,t.alias)||this.refreshMappings()}}Fa.memoize(ku.prototype,"unitScale",!1);let Cu=13.3;var Pu=function(t){return void 0!==t&&(Cu=t),Cu};const Tu="$base_url";const Du=Math.PI/12;class Ou{constructor(t,e){this._postprocessing=!0,this._mode=t,this.screen=Pu(),this._baseUrl="undefined"!=typeof window?window.location.origin:null,this._refProvider=e,this.isEditMode&&(this._rotateStep=Du,this._rotateStepForced=!1)}dispose(){this._dataSubscriptionProvider?.dispose?.(),delete this._dataStorage}_calcScreen(){const t={width:screen.width,height:screen.height};this._PPI=function(t,e,n,r="d"){t<=0&&(t=1),e<=0&&(e=1);const i=("d"===r?Math.sqrt(t*t+e*e):"w"===r?t:e)/n;return i>0?Math.round(i):0}(t.width,t.height,this.screen),this._PPM=this._PPI/25.4}subscribe(t,e){return this._dataSubscriptionProvider?.subscribe?.(t,e)}get refProvider(){return this._refProvider}set dataSubscriptionProvider(t){this._dataSubscriptionProvider=t}get dataSubscriptionProvider(){return this._dataSubscriptionProvider}set commander(t){this._commander=t}get commander(){return this._commander}get screen(){return this._screen}set screen(t){this._screen=t,this._calcScreen()}get DPPX(){return _i}get PPI(){return this._PPI}get PPM(){return this._PPM}get mode(){return this._mode}set mode(t){const e=this._mode;e!==t&&(this._mode=t,this.trigger("mode",t,e))}get isViewMode(){return 0===this._mode}get isEditMode(){return 1===this._mode}get baseUrl(){return this._baseUrl}set baseUrl(t){t&&this._baseUrl!==t&&(this._baseUrl=t)}url(t){try{let e;return e=t.includes(Tu)?new URL(t.replace(Tu,this.baseUrl??""),this.baseUrl??void 0):new URL(t,location.origin),e.href}catch(e){Rr(e,t)}}get rotateStep(){return this._rotateStep}set rotateStep(t){this._rotateStep=Number(t)||Du}get rotateStepForced(){return this._rotateStepForced}set rotateStepForced(t){this._rotateStepForced=!!t}get dataStorage(){return this._dataStorage}set dataStorage(t){this._dataStorage=t}get postprocessing(){return this._postprocessing}set postprocessing(t){this._postprocessing=t}}Lr(Ou.prototype,Ar.withEvent);class zu{constructor(t,e){!(t=Number(t))||t<=0?(jr("TimeCapsule maxsize should be greater than 0.",t),this.maxsize=10):this.maxsize=t,this.reset(),e&&(this.snapshot(e),this.preserve())}preserve(){this.checkPoint=this.pos}hasUnpreservedChanges(){return this.checkPoint!=this.pos}dispose(){this.reset()}snapshot(t){if(this.q.splice(this.pos+1,this.q.length-(this.pos+1),t),this.q.length>this.maxsize){const t=this.q.splice(0,this.q.length-this.maxsize);this.checkPoint=Math.max(-1,this.checkPoint-t.length)}this.pos=this.q.length-1}forward(){if(this.snapshot_taker&&this.snapshot_taker.take(),this.forwardable)return this.q[++this.pos];Rr("Not forwardable.")}backward(){if(this.snapshot_taker&&this.snapshot_taker.take(),this.backwardable)return this.q[--this.pos];Rr("Not backwardable.")}get current(){if(-1!==this.pos)return this.q[this.pos];Rr("Non state has been recorded.")}get length(){return this.q.length}get forwardable(){return this.pos<this.q.length-1}get backwardable(){return this.pos>0}get snapshot_taker(){return this._snapshot_taker}set snapshot_taker(t){this._snapshot_taker=t}reset(){this.q=[],this.pos=-1,this.checkPoint=-1}}const Iu=Qn(t=>{t.brake||t.take()},1e3,{leading:!0,trailing:!1});function Lu(t){!t.brake&&t.dirty&&Iu(t)}class ju{constructor(t,e){this._brake=!1,this.dirty=!1,this.brake=!1,this.dirty=!1,this.state_holder=t,this.timecapsule=e,this.timecapsule.snapshot_taker=this}dispose(){Iu.cancel(),this.state_holder=null,this.timecapsule=null}touch(){this.dirty=!0,Lu(this)}take(t=!1){(this.dirty||t)&&(this.timecapsule.snapshot(this.state_holder.state),this.dirty=!1)}get brake(){return this._brake}set brake(t){this._brake=!!t,Lu(this)}}function Ru(t,e){const n=e.model_layer.get("scale"),r=e.model_layer.get("translate"),i=e.model_layer.get("threed");if(t){const s=JSON.parse(t);s.scale=n,s.translate=r,s.threed=i,e.rebuildContentModel(s,{preserveThreeD:!0})}}class Fu{constructor(t){this.container=t,this.timecapsule=new zu(20);const e=this;this.snapshot_taker=new ju({get state(){const t=e.container.model_layer.hierarchy;return JSON.stringify(t)}},this.timecapsule),this.snapshot_taker.take(!0),this.timecapsule.preserve()}dispose(){this.reset(),this.timecapsule&&this.timecapsule.dispose(),this.snapshot_taker&&this.snapshot_taker.dispose(),delete this.container,delete this.timecapsule,delete this.snapshot_taker}preserve(){this.timecapsule.preserve()}hasUnpreservedChanges(){return this.timecapsule.hasUnpreservedChanges()}execute(t,e){!1!==e&&t&&t.execute(),this.snapshot_taker.touch(),this.trigger("execute",t,!0,!1)}undo(){this.timecapsule.backwardable&&(Ru(this.timecapsule.backward(),this.container),this.trigger("undo",this.undoable(),this.redoable()))}redo(){this.timecapsule.forwardable&&(Ru(this.timecapsule.forward(),this.container),this.trigger("redo",this.undoable(),this.redoable()))}undoable(){return this.timecapsule.backwardable}redoable(){return this.timecapsule.forwardable}reset(){this.timecapsule&&this.timecapsule.reset(),this.trigger("command-reset")}}Lr(Fu.prototype,Ar.withEvent);const Bu=new class{constructor(){this._scenes=[],this.onSceneChange=null}register(t){this._cleanup(),this._scenes.push(new WeakRef(t)),this.onSceneChange?.(this._scenes.length)}unregister(t){this._scenes=this._scenes.filter(e=>{const n=e.deref();return n&&n!==t}),this.onSceneChange?.(this._scenes.length)}getScenes(){return this._cleanup(),this._scenes.map((t,e)=>{const n=t.deref();if(!n)return null;const r=n.root,i=r?.model||{};return{index:e,model:{width:i.width||0,height:i.height||0,type:i.type||"unknown"}}}).filter(Boolean)}getComponentTree(t=0){const e=this._getScene(t);if(!e)return[];const n=e.rootContainer;if(!n)return[];const r=n.model_layer;return r?this._childrenOf(r):[]}getChildTree(t,e=0){const n=this._getScene(e);if(!n)return[];const r=n.rootContainer;if(!r)return[];let i;return i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t),i?this._childrenOf(i):[]}getComponentInfo(t,e=0){const n=this._getScene(e);if(!n)return null;const r=n.rootContainer;if(!r)return null;let i;if(i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t),!i)return null;const s=this._safeBounds(i),o={model:this._safeClone(i.model),state:this._safeClone(i.state),nature:i.nature||{},data:this._safeValue(i.data),value:this._safeValue(i.value),bounds:s,type:i.model?.type||"unknown",isContainer:!!i.isContainer?.(),hidden:!!i.model?.hidden};return"model-layer"===i.model?.type&&(o.is3dMode=!!i.model?.threed),o}selectComponent(t,e=0){const n=this._getScene(e);if(!n)return!1;const r=n.rootContainer;if(!r)return!1;if(!t||"root"===t||"__root__"===t)return r.selected=[],!0;const i=this._findComponent(r,t);return!!i&&(r.selected=[i],!0)}setComponentProperty(t,e,n,r=0){const i=this._getScene(r);if(!i)return!1;const s=i.rootContainer;if(!s)return!1;let o;if(o="root"===t||"__root__"===t?s.model_layer:this._findComponent(s,t),!o)return!1;try{return o.set(e,n),!0}catch{return!1}}setCameraView(t,e=0){const n=this._getScene(e);if(!n)return!1;const r=n.rootContainer;if(!r)return!1;const i=r.model_layer;if(!i||!i._threeCapability)return!1;try{return i._threeCapability.setCameraView(t),!0}catch{return!1}}getCameraState(t=0){const e=this._getScene(t);if(!e)return null;const n=e.rootContainer;if(!n)return null;const r=n.model_layer;if(!r||!r._threeCapability)return null;try{return r._threeCapability.getCameraState()}catch{return null}}toggleHidden(t,e=0){const n=this._getScene(e);if(!n)return!1;const r=n.rootContainer;if(!r)return!1;const i=this._findComponent(r,t);if(!i)return!1;try{return i.set("hidden",!i.model?.hidden),!i.model?.hidden}catch{return!1}}evaluateData(t,e=0){const n=this._getScene(e);if(!n)return;const r=n.rootContainer;if(!r)return;const i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t);return i?this._safeValue(i.data):void 0}evaluateValue(t,e=0){const n=this._getScene(e);if(!n)return;const r=n.rootContainer;if(!r)return;const i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t);return i?this._safeValue(i.value):void 0}searchComponents(t,e=0){const n=this._getScene(e);if(!n)return[];const r=n.rootContainer;if(!r)return[];const i=r.model_layer;if(!i)return[];const s=[],o=t.toLowerCase();return this._traverseComponent(i,t=>{const e=t.state||t.model||{};[e.type||"",e.name||"",e.id||"",e.tag||"",e.class||"",String(e.refid||"")].join(" ").toLowerCase().includes(o)&&s.push(this._toTreeNode(t))}),s}getComponentPath(t,e=0){const n=this._getScene(e);if(!n)return[];const r=n.rootContainer;if(!r)return[];const i=r.model_layer;if(!i)return[];const s=[];return this._findPath(i,t,s)?s:[]}getThreedInfo(t,e=0){const n=this._getScene(e);if(!n)return null;const r=n.rootContainer;if(!r)return null;let i;if(i="root"===t||"__root__"===t?r.model_layer:this._findComponent(r,t),!i)return null;const s=i.model||{},o=s.type||"unknown",a=s.material3d,c={is3dish:"function"==typeof i.is3dish&&i.is3dish(),type:o};if(a&&(c.material3d=this._safeClone(a)),c.resolved=dh(a),"gltf-object"===o)try{c.nodeNames=i.nodeNames??[],c.animationNames=i.animationNames??[],c.autoPlay=!1!==i.autoPlay,c.nodes=this._safeClone(i.nodes),c.animations=this._safeClone(i.animations),c.fillStyleTargets=i.fillStyleTargets}catch{}return a?.spriteMode&&(c.spriteMode=a.spriteMode),a?.renderMode&&(c.renderMode=a.renderMode),c}_getScene(t){this._cleanup();const e=this._scenes[t];return e?.deref()??null}_cleanup(){this._scenes=this._scenes.filter(t=>void 0!==t.deref())}_findComponent(t,e){const n=Number(e);if(!isNaN(n)){const e=t.findByRefid(n);if(e)return e}const r=t.findById(e);return r||null}_childrenOf(t){const e=t.components;return e?e.map(t=>this._toTreeNode(t)):[]}_toTreeNode(t){const e=t.components,n=!!e&&e.length>0,r=t.state||t.model||{};return{id:String(r.refid??r.id??""),type:r.type||"unknown",model_id:r.id,hasChildren:n,childCount:n?e.length:0,refid:r.refid,tag:r.tag,name:r.name,hidden:!!r.hidden,clazz:r.class}}_componentId(t){const e=t.state||t.model||{};return String(e.refid??e.id??"")}_findPath(t,e,n){const r=this._componentId(t);if(r===e)return!0;const i=t.components;if(!i)return!1;for(const s of i)if(this._findPath(s,e,n))return n.unshift("model-layer"===t.model?.type?"__root__":r),!0;return!1}_traverseComponent(t,e){e(t);const n=t.components;if(n)for(const t of n)this._traverseComponent(t,e)}_safeBounds(t){try{const e=t.bounds;return e?{left:e.left??0,top:e.top??0,width:e.width??0,height:e.height??0}:null}catch{return null}}_safeClone(t){if(!t||"object"!=typeof t)return t??{};try{return JSON.parse(JSON.stringify(t))}catch{const e={};for(const n of Object.keys(t))try{const r=t[n];if("function"==typeof r)continue;e[n]="object"==typeof r?String(r):r}catch{e[n]="[error]"}return e}}_safeValue(t){if(null==t)return t;try{return JSON.parse(JSON.stringify(t))}catch{return String(t)}}},Nu="KHR_materials_pbrSpecularGlossiness";class Hu{constructor(t){this.name=Nu,this.parser=t}extendMaterialParams(t,e){const r=this.parser.json.materials?.[t],i=r?.extensions?.[Nu];if(!i)return Promise.resolve();const s=[];if(Array.isArray(i.diffuseFactor)){const[t,r,s,o]=i.diffuseFactor;e.color||(e.color=new n.Color),e.color.setRGB(t,r,s,n.LinearSRGBColorSpace),e.opacity=o}null!=i.diffuseTexture&&s.push(this.parser.assignTexture(e,"map",i.diffuseTexture,n.SRGBColorSpace));const o=i.glossinessFactor??1;e.roughness=1-o;const a=i.specularFactor??[1,1,1],c=Math.max(a[0],a[1],a[2]);return e.metalness=c>.5?c:0,Promise.all(s)}}const Vu={once:_.LoopOnce,repeat:_.LoopRepeat,pingpong:_.LoopPingPong};class Gu extends xh{constructor(){super(...arguments),this.objectSize=new _.Vector3,this._nodeIndex=new Map,this._originals=new Map,this._animationActions=new Map,this._fillStyleOriginals=new Map,this._clonedMaterials=new WeakSet,this._loadGen=0}static getSharedLoader(t){if(!Gu._sharedLoader){const t=new f.GLTFLoader;!function(t){t.register(t=>new Hu(t))}(t);const e=new g.DRACOLoader;e.setDecoderPath("/node_modules/three/examples/jsm/libs/draco/"),t.setDRACOLoader(e);const n=new m.KTX2Loader;n.setTranscoderPath("/node_modules/three/examples/jsm/libs/basis/"),t.setKTX2Loader(n),t.setMeshoptDecoder(y.MeshoptDecoder),t.setCrossOrigin("anonymous"),Gu._sharedLoader=t}return t&&Gu._sharedLoader.ktx2Loader?.detectSupport(t),Gu._sharedLoader}static loadGLTF(t,e){let n=Gu._gltfCache.get(t);if(!n){const r=Gu.getSharedLoader(e);n=new Promise((e,n)=>{r.load(t,e,void 0,n)}).catch(e=>{throw Gu._gltfCache.delete(t),e}),Gu._gltfCache.set(t,n)}return n}_ensureOwnMaterial(t){let e=t.material;return this._clonedMaterials.has(e)||(e=e.clone(),t.material=e,this._clonedMaterials.add(e)),e}build(){super.build();const{src:t}=this.component.state;if(!t)return void this.clear();const e=++this._loadGen,n=this.component.app.url(t);Gu.loadGLTF(n,this.threeContainer?.renderer3d).then(t=>{e===this._loadGen&&this.gltfLoaded(t)},t=>{e===this._loadGen&&(jr("GLTFLoader.load",t),this.clear(),this._showErrorPlaceholder(),this.component.setState({loadError:String(t)}))})}gltfLoaded(t){this.component.state.loadError&&this.component.setState({loadError:void 0});const e=t.scene,n=t.animations,r=e.clone();r.userData.context=this,r.traverse(t=>{t.isMesh&&(t.castShadow=!0)});const i=(new _.Box3).setFromObject(r),s=i.getCenter(r.position),o=i.getSize(new _.Vector3);s.multiplyScalar(-1);const a=this.component.state.src;if(a){const t=Gu._topViewCache.get(a);t?this.component._topViewSnapshot=t:this._renderTopViewSnapshot(a,r)}this.clear(),this.object3d.userData.context=this,this.objectSize=o,this.pivot=new _.Object3D,this.object3d.add(this.pivot),this.pivot.add(r),this._buildNodeIndex(r),this.updateDimension(),n&&n.length&&this._setupAnimations(n);const c=this.component.state.nodes;c&&this._applyNodeStates(c),this.updateFillStyle()}_renderTopViewSnapshot(t,e){const n=Gu.renderTopView(e);Gu._topViewCache.set(t,n),this.component._topViewSnapshot=n,this.component.invalidate()}static renderTopView(t){const e=256,n=new _.Scene,r=t.parent;n.add(t);const i=new _.AmbientLight(16777215,.8);n.add(i);const s=new _.DirectionalLight(16777215,1);s.position.set(0,10,0),n.add(s);const o=(new _.Box3).setFromObject(t),a=o.getSize(new _.Vector3),c=o.getCenter(new _.Vector3),l=(a.x||1)/2*1.02,h=(a.z||1)/2*1.02,d=new _.OrthographicCamera(-l,l,h,-h,.01,10*a.y+1);d.position.set(c.x,o.max.y+a.y,c.z),d.lookAt(c.x,c.y,c.z);const u=l/h,p=u>=1?e:Math.round(e*u),f=u>=1?Math.round(e/u):e;let g;try{g=new _.WebGLRenderer({antialias:!0,alpha:!0});const t=g.getContext();t&&!t.isContextLost()||(g.dispose(),g=void 0)}catch{g=void 0}if(!g){r?r.add(t):n.remove(t);const e=document.createElement("canvas");return e.width=p,e.height=f,e}g.setClearColor(0,0),g.setSize(p,f),g.render(n,d),r?r.add(t):n.remove(t);const m=document.createElement("canvas");m.width=p,m.height=f;const y=m.getContext("2d");return y&&y.drawImage(g.domElement,0,0),g.dispose(),m}static getTopViewCache(t){return Gu._topViewCache.get(t)}static setTopViewCache(t,e){Gu._topViewCache.set(t,e)}static flushCache(){Gu._gltfCache.clear(),Gu._topViewCache.clear()}_buildNodeIndex(t){this._nodeIndex.clear(),this._originals.clear(),t.traverse(t=>{if(!t.name)return;this._nodeIndex.set(t.name,t);const e={visible:t.visible,scale:t.scale.clone()};if(t.isMesh){const n=t.material;n&&(e.color=n.color.clone(),e.opacity=n.opacity,e.transparent=n.transparent,e.emissive=n.emissive.clone(),e.emissiveIntensity=n.emissiveIntensity)}this._originals.set(t.name,e)})}getNode(t){return this._nodeIndex.get(t)}get nodeNames(){return Array.from(this._nodeIndex.keys())}_applyNodeStates(t){for(const[e,n]of Object.entries(t)){const t=this._nodeIndex.get(e);if(t&&(void 0!==n.visible&&(t.visible=n.visible),void 0!==n.scale&&t.scale.setScalar(n.scale),t.isMesh)){const e=t;if(!(void 0!==n.color||void 0!==n.opacity||void 0!==n.emissive||void 0!==n.emissiveIntensity))continue;const r=this._ensureOwnMaterial(e);void 0!==n.color&&r.color.set(n.color),void 0!==n.opacity&&(r.opacity=n.opacity,r.transparent=n.opacity<1),void 0!==n.emissive&&r.emissive.set(n.emissive),void 0!==n.emissiveIntensity&&(r.emissiveIntensity=n.emissiveIntensity)}}}_resetNode(t){const e=this._nodeIndex.get(t),n=this._originals.get(t);if(e&&n&&(e.visible=n.visible,e.scale.copy(n.scale),e.isMesh)){const t=e.material;t&&n.color&&(t.color.copy(n.color),t.opacity=n.opacity,t.transparent=n.transparent,t.emissive.copy(n.emissive),t.emissiveIntensity=n.emissiveIntensity)}}_resetAllNodes(){for(const t of this._originals.keys())this._resetNode(t)}_setupAnimations(t){const e=this.threeContainer.mixer;this._animationActions.clear();for(const n of t){const t=e.clipAction(n);this._animationActions.set(n.name,t)}!1!==this.component.state.autoPlay&&this._animationActions.forEach(t=>t.play());const n=this.component.state.animations;n&&this._applyAnimationStates(n)}_applyAnimationStates(t){for(const[e,n]of Object.entries(t)){const t=this._animationActions.get(e);t&&(void 0!==n.loop&&(t.loop=Vu[n.loop]??_.LoopRepeat,"once"===n.loop&&(t.clampWhenFinished=!0)),void 0!==n.speed&&(t.timeScale=n.speed),void 0!==n.weight&&(t.weight=n.weight),void 0!==n.play&&(n.play?t.play():t.stop()))}}get animationNames(){return Array.from(this._animationActions.keys())}_showErrorPlaceholder(){const t=new _.BoxGeometry(1,1,1),e=new _.MeshStandardMaterial({color:13369344,wireframe:!0}),n=new _.Mesh(t,e);n.name="__error_placeholder__",this.object3d.add(n)}updateFillStyle(){const t=this.component.state.fillStyleTargets;if(!t||0===t.length)return;const{fillStyle:e}=this.component.state;if(!e)return;const n=xh.buildFillStyleTexture(this.component);for(const r of t){const t=this._nodeIndex.get(r);if(!t||!t.isMesh)continue;const i=this._ensureOwnMaterial(t);i&&(this._fillStyleOriginals.has(r)||this._fillStyleOriginals.set(r,{color:i.color.clone(),map:i.map,opacity:i.opacity,transparent:i.transparent}),n?(i.map&&i.map!==this._fillStyleOriginals.get(r)?.map&&i.map.dispose(),n.needsUpdate=!0,i.map=n):"string"==typeof e&&("transparent"!==e?i.color.set(e):(i.opacity=0,i.transparent=!0)))}}_restoreFillStyleTargets(t){for(const e of t){const t=this._fillStyleOriginals.get(e);if(!t)continue;const n=this._nodeIndex.get(e);if(!n||!n.isMesh)continue;const r=n.material;r&&(r.map&&r.map!==t.map&&r.map.dispose(),r.color.copy(t.color),r.map=t.map,r.opacity=t.opacity,r.transparent=t.transparent,this._fillStyleOriginals.delete(e))}}clear(){return this._animationActions.forEach(t=>t.stop()),this._animationActions.clear(),this._nodeIndex.clear(),this._originals.clear(),this._fillStyleOriginals.clear(),this.pivot&&yh(this.pivot),this.pivot=void 0,this.objectSize=void 0,super.clear()}updateDimension(){const{width:t=1,height:e=1,depth:n=1}=this.component.state,{x:r=1,y:i=1,z:s=1}=this.objectSize||{};this.pivot&&this.pivot.scale.set(t/r,n/i,e/s),this.component.invalidate()}updateSource(){this.build()}onchange(t,e){if(super.onchange(t,e),"src"in t&&this.updateSource(),"nodes"in t){this._resetAllNodes();const e=t.nodes;e&&Object.keys(e).length>0&&this._applyNodeStates(e)}if("animations"in t){const e=t.animations;e&&this._applyAnimationStates(e)}if("fillStyleTargets"in t){const t=e.fillStyleTargets??[];t.length>0&&this._restoreFillStyleTargets(t),this.updateFillStyle()}"autoPlay"in t&&(!1!==t.autoPlay?this._animationActions.forEach(t=>t.play()):this._animationActions.forEach(t=>t.stop()))}}Gu._topViewCache=new Map,Gu._gltfCache=new Map,Gu._sharedLoader=null;const Yu=["id","name","tag","type","class","text","data","property"];class Uu{constructor(){this._results=[],this._currentIndex=-1,this._lastQuery=""}get results(){return this._results}get currentIndex(){return this._currentIndex}get currentResult(){return this._results[this._currentIndex]}get resultCount(){return this._results.length}search(t,e,n){if(this._lastQuery=e,this._results=[],this._currentIndex=-1,!e||!t)return this._results;const r=n?.fields||Yu,i=n?.caseSensitive??!1,s=n?.includeHidden??!1,o=n?.maxResults??1/0,a=i?e:e.toLowerCase(),c=new Set;return this._traverse(t,t=>{if(c.has(t))return;if(this._results.length>=o)return;if(!s&&t.state.hidden)return;const e=this._matchComponent(t,a,r,i);e&&(c.add(t),this._results.push(e))}),this._results.length>0&&(this._currentIndex=0),this._results}navigateNext(){if(0!==this._results.length)return this._currentIndex=(this._currentIndex+1)%this._results.length,this._results[this._currentIndex]}navigatePrev(){if(0!==this._results.length)return this._currentIndex=(this._currentIndex-1+this._results.length)%this._results.length,this._results[this._currentIndex]}navigateTo(t){if(!(t<0||t>=this._results.length))return this._currentIndex=t,this._results[this._currentIndex]}clear(){this._results=[],this._currentIndex=-1,this._lastQuery=""}_traverse(t,e){e(t);const n=t.components;if(n)for(const t of n)this._traverse(t,e)}_matchComponent(t,e,n,r){const i=t.state,s=t=>{if(!t)return!1;return(r?t:t.toLowerCase()).includes(e)};for(const o of n)switch(o){case"id":if(s(i.id))return{component:t,matchType:"id",matchField:"id",matchValue:i.id};break;case"name":if(s(i.name))return{component:t,matchType:"name",matchField:"name",matchValue:i.name};break;case"tag":if(s(i.tag))return{component:t,matchType:"tag",matchField:"tag",matchValue:i.tag};break;case"type":if(s(i.type))return{component:t,matchType:"type",matchField:"type",matchValue:i.type};break;case"class":if(s(i.class))return{component:t,matchType:"class",matchField:"class",matchValue:i.class};break;case"text":if(s(i.text))return{component:t,matchType:"text",matchField:"text",matchValue:i.text};break;case"data":{const n=this._matchDataBinding(t,e,r);if(n)return n;break}case"property":{const n=this._matchProperties(t,e,r);if(n)return n;break}}return null}_matchDataBinding(t,e,n){const r=t._model,i=r?.mappings;if(!i||!Array.isArray(i))return null;const s=t=>{if(!t)return!1;return(n?t:t.toLowerCase()).includes(e)};for(const e of i){if(s(e.accessor))return{component:t,matchType:"data",matchField:"accessor",matchValue:e.accessor};if(s(e.target))return{component:t,matchType:"data",matchField:"target",matchValue:e.target};if(s(e.property))return{component:t,matchType:"data",matchField:"property",matchValue:e.property};if(s(e.source))return{component:t,matchType:"data",matchField:"source",matchValue:e.source}}return null}_matchProperties(t,e,n){const r=t.state,i=t=>{if(!t)return!1;return(n?t:t.toLowerCase()).includes(e)},s=["ref","src","value","action"];for(const e of s){const n=r[e];if("string"==typeof n&&i(n))return{component:t,matchType:"property",matchField:e,matchValue:n}}return null}}const $u={id:"ID",name:"Name",tag:"Tag",type:"Type",class:"Class",text:"Text",data:"Data",property:"Prop"};class Wu{constructor(){this._engine=new Uu,this._visible=!1,this._queryHistory=[],this._historyIndex=-1,this._savedInput="",this._keyboardNav=!1}get isVisible(){return this._visible}get engine(){return this._engine}setup(t){this.destroy(),this._host=t}toggle(){this._visible?this._input&&document.activeElement!==this._input?(this._input.focus(),this._input.select()):this.hide():this.show()}show(){this._host?.element&&(this._container||this._buildDOM(),this._container&&!this._container.parentElement&&this._host.element.appendChild(this._container),this._container.style.display="flex",this._visible=!0,requestAnimationFrame(()=>{this._input?.focus(),this._input?.select()}))}hide(){this._container&&(this._container.style.display="none"),this._visible=!1,this._historyIndex=-1,this._clearHighlight(),this._engine.clear(),this._updateStatus(),this._hideResultList()}destroy(){this._container?.parentElement&&this._container.parentElement.removeChild(this._container),this._container=void 0,this._input=void 0,this._statusEl=void 0,this._resultListEl=void 0,this._host=void 0,this._visible=!1,this._engine.clear()}_buildDOM(){const t=this._host,e=document.createElement("div");e.setAttribute("scene","search-overlay"),e.style.cssText=["position:absolute","top:8px","right:8px","display:flex","flex-direction:column","background:rgba(30,30,30,0.94)","border:1px solid rgba(255,255,255,0.12)","border-radius:8px","backdrop-filter:blur(12px)","pointer-events:auto","user-select:none","z-index:10000",'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',"font-size:13px","color:rgba(255,255,255,0.9)","box-shadow:0 4px 16px rgba(0,0,0,0.3)","min-width:280px","max-width:400px"].join(";");const n=document.createElement("div");n.style.cssText="display:flex;align-items:center;padding:6px 8px;gap:6px";const r=document.createElement("span");r.textContent="🔍",r.style.cssText="font-size:14px;flex-shrink:0;opacity:0.6",n.appendChild(r);const i=document.createElement("input");i.type="text",i.placeholder="Search: type, id, tag, text, data...",i.style.cssText=["flex:1","background:rgba(255,255,255,0.08)","border:1px solid rgba(255,255,255,0.15)","border-radius:4px","color:white","padding:4px 8px","font-size:13px","outline:none","min-width:0"].join(";"),i.addEventListener("focus",()=>{i.style.borderColor="rgba(74,158,255,0.6)"}),i.addEventListener("blur",()=>{i.style.borderColor="rgba(255,255,255,0.15)"}),n.appendChild(i);const s=document.createElement("span");s.style.cssText="font-size:11px;color:rgba(255,255,255,0.5);white-space:nowrap;flex-shrink:0",n.appendChild(s);const o=document.createElement("button");o.textContent="✕",o.title="Close (Esc)",o.style.cssText=this._buttonStyle(),o.addEventListener("click",()=>this.hide()),n.appendChild(o),e.appendChild(n);const a=document.createElement("div");a.style.cssText=["max-height:240px","overflow-y:auto","border-top:1px solid rgba(255,255,255,0.08)","display:none"].join(";"),e.appendChild(a),i.addEventListener("input",()=>{this._historyIndex=-1,this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>this._doSearch(i.value),150)}),i.addEventListener("keydown",e=>{if(e.stopPropagation(),"Escape"===e.key)return this.hide(),void t.element?.focus();if("ArrowDown"===e.key||"Tab"===e.key){if("Tab"===e.key&&e.shiftKey)return;return this._isHistoryMode()||!this._input?.value&&"ArrowDown"===e.key?this._navigateHistory(1):this._engine.resultCount>0&&this._focusResult(0),void e.preventDefault()}if("ArrowUp"===e.key)return this._navigateHistory(-1),void e.preventDefault();if("Enter"===e.key){const t=this._engine.currentIndex>=0?this._engine.currentIndex:0;return this._selectResult(t),void e.preventDefault()}}),this._container=e,this._input=i,this._statusEl=s,this._resultListEl=a}_buttonStyle(){return["background:none","border:none","color:rgba(255,255,255,0.6)","cursor:pointer","font-size:12px","padding:2px 4px","border-radius:3px","line-height:1"].join(";")}_doSearch(t){if(!this._host?.root)return;const e=t.trim();if(!e)return this._engine.clear(),this._clearHighlight(),this._updateStatus(),void this._hideResultList();this._engine.search(this._host.root,e),this._updateStatus(),this._renderResultList()}_addToHistory(t){const e=t.trim();if(!e)return;const n=this._queryHistory.indexOf(e);n>=0&&this._queryHistory.splice(n,1),this._queryHistory.unshift(e),this._queryHistory.length>Wu.MAX_HISTORY&&this._queryHistory.pop()}_navigateHistory(t){if(0===this._queryHistory.length)return;if(!this._input)return;-1===this._historyIndex&&-1===t&&(this._savedInput=this._input.value);const e=this._historyIndex+(-1===t?1:-1);e<-1||e>=this._queryHistory.length||(this._historyIndex=e,-1===this._historyIndex?this._input.value=this._savedInput:this._input.value=this._queryHistory[this._historyIndex],this._debounceTimer&&clearTimeout(this._debounceTimer),this._doSearch(this._input.value))}_isHistoryMode(){return this._historyIndex>=0}_focusResult(t){if(t<0||t>=this._engine.resultCount)return;if(t>=50)return;this._engine.navigateTo(t),this._keyboardNav=!0,this._updateStatus(),this._updateResultListSelection();const e=this._resultListEl?.querySelector(`[data-index="${t}"]`);e?.focus()}_selectResult(t){if(!this._host)return;if(0===this._engine.resultCount)return;if(t<0||t>=this._engine.resultCount)return;this._engine.navigateTo(t);const e=this._engine.currentResult;if(!e)return;this._addToHistory(this._input?.value||""),this._host.setSelected([e.component]),this._host.centerTo(e.component,!0);const n=this._engine.results.map(t=>t.component);this._host.highlightSearchResults?.(n),this._host.invalidate?.(),this._updateStatus(),this._updateResultListSelection()}_clearHighlight(){this._host?.highlightSearchResults?.([]),this._host?.invalidate?.()}_updateStatus(){if(!this._statusEl)return;const t=this._engine.resultCount,e=this._engine.currentIndex;0===t&&this._input?.value?.trim()?(this._statusEl.textContent="No results",this._statusEl.style.color="rgba(255,120,120,0.8)"):t>0?(this._statusEl.textContent=`${e+1}/${t}`,this._statusEl.style.color="rgba(255,255,255,0.5)"):this._statusEl.textContent=""}_renderResultList(){if(!this._resultListEl)return;const t=this._engine.results;if(this._resultListEl.innerHTML="",0===t.length)return void(this._resultListEl.style.display="none");const e=t.slice(0,50);for(let t=0;t<e.length;t++){const n=e[t],r=document.createElement("div");r.dataset.index=String(t),r.tabIndex=-1,r.style.cssText=["padding:4px 10px","cursor:pointer","display:flex","align-items:center","gap:6px","font-size:12px","border-bottom:1px solid rgba(255,255,255,0.04)","transition:background 0.1s","outline:none"].join(";"),r.addEventListener("mouseenter",()=>{this._keyboardNav=!1,r.style.background="rgba(255,255,255,0.08)"}),r.addEventListener("mouseleave",()=>{this._engine.currentIndex!==t?r.style.background="none":r.style.background="rgba(74,158,255,0.15)"}),r.addEventListener("click",()=>{this._selectResult(t)}),r.addEventListener("keydown",e=>{e.stopPropagation(),"ArrowDown"===e.key?(this._focusResult(t+1),e.preventDefault()):"ArrowUp"===e.key?(0===t?(this._input?.focus(),this._input?.select()):this._focusResult(t-1),e.preventDefault()):"Enter"===e.key?(this._selectResult(t),e.preventDefault()):"Escape"===e.key?(this.hide(),this._host?.element?.focus(),e.preventDefault()):e.shiftKey&&"Tab"===e.key?(this._input?.focus(),e.preventDefault()):1!==e.key.length||e.metaKey||e.ctrlKey||e.altKey||this._input?.focus()});const i=document.createElement("span");i.textContent=$u[n.matchType]||n.matchType,i.style.cssText=["font-size:9px","padding:1px 4px","border-radius:3px","background:rgba(74,158,255,0.2)","color:rgba(74,158,255,0.9)","flex-shrink:0","text-transform:uppercase","letter-spacing:0.5px"].join(";"),r.appendChild(i);const s=document.createElement("span");s.textContent=n.component.state.type||"?",s.style.cssText="color:rgba(255,255,255,0.7);flex-shrink:0",r.appendChild(s);const o=document.createElement("span");if(o.textContent=this._truncate(n.matchValue,30),o.style.cssText="color:rgba(255,200,100,0.8);overflow:hidden;text-overflow:ellipsis;white-space:nowrap",r.appendChild(o),"id"!==n.matchType&&n.component.state.id){const t=document.createElement("span");t.textContent=`#${n.component.state.id}`,t.style.cssText="color:rgba(255,255,255,0.3);font-size:11px;margin-left:auto;flex-shrink:0",r.appendChild(t)}this._resultListEl.appendChild(r)}if(t.length>50){const e=document.createElement("div");e.style.cssText="padding:4px 10px;font-size:11px;color:rgba(255,255,255,0.3);text-align:center",e.textContent=`... and ${t.length-50} more`,this._resultListEl.appendChild(e)}this._resultListEl.style.display="block",this._updateResultListSelection()}_updateResultListSelection(){if(!this._resultListEl)return;const t=this._engine.currentIndex;for(const e of Array.from(this._resultListEl.children)){const n=e,r=parseInt(n.dataset.index||"-1",10);n.style.background=r===t?"rgba(74,158,255,0.15)":"none"}const e=this._resultListEl.querySelector(`[data-index="${t}"]`);e?.scrollIntoView({block:"nearest"})}_hideResultList(){this._resultListEl&&(this._resultListEl.style.display="none",this._resultListEl.innerHTML="")}_truncate(t,e){return t.length>e?t.slice(0,e)+"...":t}}Wu.MAX_HISTORY=20;let Xu=0;const qu=new FinalizationRegistry(t=>{Xu--});class Ku{static get residents(){return Xu}static get residentsCount(){return Xu}constructor(t){this._searchOverlay=new Wu,this._container=t,this.app=t.app,this._commander=new Fu(this._container),this.app.commander=this._commander,Xu++,qu.register(this,Xu),Bu.register(this),this._container.target_element&&this._setupSearchOverlay()}add(t,e,n){return Jc.call(this._container,t,e,n)}duplicate(){return tl.call(this._container)}remove(){return el.call(this._container)}animate(t){return Ro.call(this,t)}fullscreen(t){return al.call(this._container,t)}get target(){return this._container.target_element}set target(t){let e;if("string"==typeof t){if(e=document.getElementById(t),!e)throw new Error(`target element '${t}' does not exist`);if(e.firstChild)throw new Error(`target element '${t}' already has children`)}else e=t;e&&e.style&&(e.style.cursor="default"),this._container.target_element=e,this._setupSearchOverlay(),this._container.invalidate()}get scale(){return this.root.get("scale")}set scale(t){this.root.set("scale",t)}get translate(){return this.root.get("translate")}set translate(t){this.root.set("translate",t)}get unit(){return this.root.get("unit")||"px"}get PPM(){return this.app.PPM}get PPI(){return this.app.PPI}get DPPX(){return this.app.DPPX}static get DPPX(){return _i}get unitScale(){return this._container.unitScale}get screen(){return this.app.screen}set screen(t){this.app.screen=t,this._container.resize()}resize(){this._container.resize()}release(){this.dispose()}dispose(){this._searchOverlay.destroy(),Bu.unregister(this),this._commander&&this._commander.dispose(),this._container&&this._container.dispose(),Gu.flushCache()}get selected(){return this._container.selected.slice()}set selected(t){this._container.selected=t}select(t,...e){return this._container.selected=this.root?.findAll(t,...e),this.selected}get commander(){return this._commander}undo(){this.commander.undo()}undoable(){return this.commander.undoable()}redo(){this.commander.redo()}redoable(){return this.commander.redoable()}preserve(){this.commander.preserve()}hasUnpreservedChanges(){return this.commander.hasUnpreservedChanges()}cut(){return hl.call(this._container)}copy(){return ll.call(this._container)}paste(t){return dl.call(this._container,t)}undoableChange(t){return Pl.call(this._container,t)}change(t,e,n){return Cl.call(this.root,t,e,n)}get model(){return this.root.hierarchy}set model(t){this._container.rebuildContentModel(t)}get rootContainer(){return this._container}get root(){return this._container?.model_layer}findAll(t,...e){return this.root.findAll(t,...e)}findFirst(t,...e){return this.root.findFirst(t,...e)}findById(t){return this._container.findById(t)}findAllById(t){return this._container.findAllById(t)}serialize(){return this.root.trim(),this.root.serialize()}align(t){return Gc.call(this._container,t)}place(t){return Rl.call(this._container,t)}distribute(t){return $c.call(this._container,t)}move(t,e,n){return qc.call(this._container,t,e,n)}zorder(t){return Kc.call(this._container,t)}symmetryX(){return El.call(this._container)}symmetryY(){return kl.call(this._container)}on(t,e,n){return il.call(this._container,t,e,n)}once(t,e,n){return sl.call(this._container,t,e,n)}off(t,e,n){return this._container&&ol.call(this._container,t,e,n)}centerTo(t,e){return this.root.centerTo(t,e)}get mode(){return this.app.mode}set mode(t){void 0!==t&&(this.app.mode=t)}toDataURL(t,e,n,r){return xl.call(this._container,t,e,n,r)}group(){return wl.call(this._container)}ungroup(){return Ml.call(this._container)}fit(t){this._container.once("redraw",()=>this._container.fit(t)),this._container.invalidate()}get fitMode(){return this._container.fitMode}get ids(){return Tl.call(this._container)}get data(){return this._container.data}set data(t){this._container.data=t}get dataByRefid(){return this._container.dataByRefid}set dataByRefid(t){this._container.dataByRefid=t}get values(){return this._container.values}set values(t){this._container.values=t}get valuesByRefid(){return this._container.valuesByRefid}set valuesByRefid(t){this._container.valuesByRefid=t}get baseUrl(){return this.app.baseUrl}set baseUrl(t){this.app.baseUrl=t}startAddMode(t){return Fl.call(this._container,t)}startStylePasteMode(){return Bl.call(this._container)}stopStylePasteMode(){return Nl.call(this._container)}startDatabindPasteMode(){return Hl.call(this._container)}stopDatabindPasteMode(){return Vl.call(this._container)}get searchOverlay(){return this._searchOverlay}_setupSearchOverlay(){const t=this;this._searchOverlay.setup({get root(){return t.root},get element(){return t.target},centerTo(e,n){t.centerTo(e,n)},setSelected(e){t.selected=e},invalidate(){t._container?.invalidate()}});const e=this._container.model_layer;e&&(e.onSearchToggle=()=>this._searchOverlay.toggle())}}const Qu=new class{async load(t){}async save(t,e){}async clear(t){}};function Zu({target:t,model:e,style:n,layers:r=[],handlers:i=[],mode:s=0,refProvider:o,dataSubscriptionProvider:a,dataStorage:c=Qu,baseUrl:l,fitMode:h,postprocessing:d=!0}){let u=null;if("string"==typeof t){if(u=document.getElementById(t),!u)throw new Error(`target element '${t}' does not exist`);if(u.firstChild)throw new Error(`target element '${t}' is not empty`)}else u=t??null;u&&u.style&&(u.style.position="absolute",u.style.cursor="default",u.style.overflow="hidden");const p=new Ou(s,o);return l&&(p.baseUrl=l),p.postprocessing=d,p.dataSubscriptionProvider=a,p.dataStorage=c,new Ku(new ku({target_element:u,model:e,style:n,layers:r,handlers:i,fitMode:h},p))}function Ju(t,e,n,r){var i,s=arguments.length,o=s<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,n,o):i(e,n))||o);return s>3&&o&&Object.defineProperty(e,n,o),o}function tp(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)}function ep(t,e,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(t,n):i?i.value=n:e.set(t,n),n}"function"==typeof SuppressedError&&SuppressedError;
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2019 Google LLC