!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Le5le=e():t.Le5le=e()}(self,(()=>(()=>{var t={176:(t,e,i)=>{var n=i(52);t.exports=function(t){if(!n(t))throw TypeError(String(t)+" is not an object");return t}},540:(t,e,i)=>{var n=i(905),o=i(237),r=i(357),s=function(t){return function(e,i,s){var a,l=n(e),c=o(l.length),h=r(s,c);if(t&&i!=i){for(;c>h;)if((a=l[h++])!=a)return!0}else for(;c>h;h++)if((t||h in l)&&l[h]===i)return t||h||0;return!t&&-1}};t.exports={includes:s(!0),indexOf:s(!1)}},79:t=>{var e={}.toString;t.exports=function(t){return e.call(t).slice(8,-1)}},81:(t,e,i)=>{var n=i(816),o=i(826),r=i(933),s=i(787);t.exports=function(t,e){for(var i=o(e),a=s.f,l=r.f,c=0;c{var n=i(400),o=i(787),r=i(358);t.exports=n?function(t,e,i){return o.f(t,e,r(1,i))}:function(t,e,i){return t[e]=i,t}},358:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},400:(t,e,i)=>{var n=i(229);t.exports=!n((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},635:(t,e,i)=>{var n=i(859),o=i(52),r=n.document,s=o(r)&&o(r.createElement);t.exports=function(t){return s?r.createElement(t):{}}},837:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},103:(t,e,i)=>{var n=i(859),o=i(933).f,r=i(762),s=i(487),a=i(333),l=i(81),c=i(541);t.exports=function(t,e){var i,h,d,u,f,p=t.target,v=t.global,g=t.stat;if(i=v?n:g?n[p]||a(p,{}):(n[p]||{}).prototype)for(h in e){if(u=e[h],d=t.noTargetGet?(f=o(i,h))&&f.value:i[h],!c(v?h:p+(g?".":"#")+h,t.forced)&&void 0!==d){if(typeof u==typeof d)continue;l(u,d)}(t.sham||d&&d.sham)&&r(u,"sham",!0),s(i,h,u,t)}}},229:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},379:(t,e,i)=>{var n=i(36);t.exports=n("native-function-to-string",Function.toString)},230:(t,e,i)=>{var n=i(276),o=i(859),r=function(t){return"function"==typeof t?t:void 0};t.exports=function(t,e){return arguments.length<2?r(n[t])||r(o[t]):n[t]&&n[t][e]||o[t]&&o[t][e]}},859:(t,e,i)=>{var n=function(t){return t&&t.Math==Math&&t};t.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof i.g&&i.g)||Function("return this")()},816:t=>{var e={}.hasOwnProperty;t.exports=function(t,i){return e.call(t,i)}},977:t=>{t.exports={}},394:(t,e,i)=>{var n=i(400),o=i(229),r=i(635);t.exports=!n&&!o((function(){return 7!=Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a}))},337:(t,e,i)=>{var n=i(229),o=i(79),r="".split;t.exports=n((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?r.call(t,""):Object(t)}:Object},407:(t,e,i)=>{var n,o,r,s=i(694),a=i(859),l=i(52),c=i(762),h=i(816),d=i(399),u=i(977),f=a.WeakMap;if(s){var p=new f,v=p.get,g=p.has,y=p.set;n=function(t,e){return y.call(p,t,e),e},o=function(t){return v.call(p,t)||{}},r=function(t){return g.call(p,t)}}else{var m=d("state");u[m]=!0,n=function(t,e){return c(t,m,e),e},o=function(t){return h(t,m)?t[m]:{}},r=function(t){return h(t,m)}}t.exports={set:n,get:o,has:r,enforce:function(t){return r(t)?o(t):n(t,{})},getterFor:function(t){return function(e){var i;if(!l(e)||(i=o(e)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return i}}}},541:(t,e,i)=>{var n=i(229),o=/#|\.prototype\./,r=function(t,e){var i=a[s(t)];return i==c||i!=l&&("function"==typeof e?n(e):!!e)},s=r.normalize=function(t){return String(t).replace(o,".").toLowerCase()},a=r.data={},l=r.NATIVE="N",c=r.POLYFILL="P";t.exports=r},52:t=>{t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},231:t=>{t.exports=!1},694:(t,e,i)=>{var n=i(859),o=i(379),r=n.WeakMap;t.exports="function"==typeof r&&/native code/.test(o.call(r))},787:(t,e,i)=>{var n=i(400),o=i(394),r=i(176),s=i(66),a=Object.defineProperty;e.f=n?a:function(t,e,i){if(r(t),e=s(e,!0),r(i),o)try{return a(t,e,i)}catch(t){}if("get"in i||"set"in i)throw TypeError("Accessors not supported");return"value"in i&&(t[e]=i.value),t}},933:(t,e,i)=>{var n=i(400),o=i(195),r=i(358),s=i(905),a=i(66),l=i(816),c=i(394),h=Object.getOwnPropertyDescriptor;e.f=n?h:function(t,e){if(t=s(t),e=a(e,!0),c)try{return h(t,e)}catch(t){}if(l(t,e))return r(!o.f.call(t,e),t[e])}},151:(t,e,i)=>{var n=i(140),o=i(837).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return n(t,o)}},894:(t,e)=>{e.f=Object.getOwnPropertySymbols},140:(t,e,i)=>{var n=i(816),o=i(905),r=i(540).indexOf,s=i(977);t.exports=function(t,e){var i,a=o(t),l=0,c=[];for(i in a)!n(s,i)&&n(a,i)&&c.push(i);for(;e.length>l;)n(a,i=e[l++])&&(~r(c,i)||c.push(i));return c}},195:(t,e)=>{"use strict";var i={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor,o=n&&!i.call({1:2},1);e.f=o?function(t){var e=n(this,t);return!!e&&e.enumerable}:i},826:(t,e,i)=>{var n=i(230),o=i(151),r=i(894),s=i(176);t.exports=n("Reflect","ownKeys")||function(t){var e=o.f(s(t)),i=r.f;return i?e.concat(i(t)):e}},276:(t,e,i)=>{t.exports=i(859)},487:(t,e,i)=>{var n=i(859),o=i(36),r=i(762),s=i(816),a=i(333),l=i(379),c=i(407),h=c.get,d=c.enforce,u=String(l).split("toString");o("inspectSource",(function(t){return l.call(t)})),(t.exports=function(t,e,i,o){var l=!!o&&!!o.unsafe,c=!!o&&!!o.enumerable,h=!!o&&!!o.noTargetGet;"function"==typeof i&&("string"!=typeof e||s(i,"name")||r(i,"name",e),d(i).source=u.join("string"==typeof e?e:"")),t!==n?(l?!h&&t[e]&&(c=!0):delete t[e],c?t[e]=i:r(t,e,i)):c?t[e]=i:a(e,i)})(Function.prototype,"toString",(function(){return"function"==typeof this&&h(this).source||l.call(this)}))},885:t=>{t.exports=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t}},333:(t,e,i)=>{var n=i(859),o=i(762);t.exports=function(t,e){try{o(n,t,e)}catch(i){n[t]=e}return e}},399:(t,e,i)=>{var n=i(36),o=i(441),r=n("keys");t.exports=function(t){return r[t]||(r[t]=o(t))}},353:(t,e,i)=>{var n=i(859),o=i(333),r="__core-js_shared__",s=n[r]||o(r,{});t.exports=s},36:(t,e,i)=>{var n=i(231),o=i(353);(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.3.5",mode:n?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},357:(t,e,i)=>{var n=i(51),o=Math.max,r=Math.min;t.exports=function(t,e){var i=n(t);return i<0?o(i+e,0):r(i,e)}},905:(t,e,i)=>{var n=i(337),o=i(885);t.exports=function(t){return n(o(t))}},51:t=>{var e=Math.ceil,i=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?i:e)(t)}},237:(t,e,i)=>{var n=i(51),o=Math.min;t.exports=function(t){return t>0?o(n(t),9007199254740991):0}},66:(t,e,i)=>{var n=i(52);t.exports=function(t,e){if(!n(t))return t;var i,o;if(e&&"function"==typeof(i=t.toString)&&!n(o=i.call(t)))return o;if("function"==typeof(i=t.valueOf)&&!n(o=i.call(t)))return o;if(!e&&"function"==typeof(i=t.toString)&&!n(o=i.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},441:t=>{var e=0,i=Math.random();t.exports=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++e+i).toString(36)}},173:(t,e,i)=>{i(103)({global:!0},{globalThis:i(859)})},421:(t,e,i)=>{t.exports=function t(e,i,n){function o(s,a){if(!i[s]){if(!e[s]){if(r)return r(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[s]={exports:{}};e[s][0].call(c.exports,(function(t){return o(e[s][1][t]||t)}),c,c.exports,t,e,i,n)}return i[s].exports}for(var r=void 0,s=0;s0&&(e.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new s(e.topicAliasMaximum)),this.on("connect",(function(){const t=this.queue;g("connect :: sending queued packets"),function e(){const i=t.shift();g("deliver :: entry %o",i);let o=null;if(!i)return void n._resubscribe();o=i.packet,g("deliver :: call _sendPacket for %o",o);let r=!0;o.messageId&&0!==o.messageId&&(n.messageIdProvider.register(o.messageId)||(r=!1)),r?n._sendPacket(o,(function(t){i.cb&&i.cb(t),e()})):(g("messageId: %d has already used. The message is skipped and removed.",o.messageId),e())}()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==n.pingTimer&&(n.pingTimer.clear(),n.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),o.call(this),g("MqttClient :: setting up stream"),this._setupStream()}d(R,o),R.prototype._setupStream=function(){const t=this,e=new h,i=l.parser(this.options);let n=null;const o=[];function r(){if(o.length)y(s);else{const t=n;n=null,t()}}function s(){g("work :: getting next packet in queue");const e=o.shift();if(e)g("work :: packet pulled from queue"),t._handlePacket(e,r);else{g("work :: no packets in queue");const t=n;n=null,g("work :: done flag is %s",!!t),t&&t()}}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),i.on("packet",(function(t){g("parser :: on packet push to packets array."),o.push(t)})),e._write=function(t,e,o){n=o,g("writable stream :: parsing buffer"),i.parse(t),s()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(e),this.stream.on("error",(function(e){g("streamErrorHandler :: error",e.message),x.includes(e.code)?(g("streamErrorHandler :: emitting error"),t.emit("error",e)):C(e)})),this.stream.on("close",(function(){var e;g("(%s)stream :: on close",t.options.clientId),(e=t.outgoing)&&(g("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])}))),g("stream: emit close to MqttClient"),t.emit("close")})),g("_setupStream: sending packet `connect`");const a=Object.create(this.options);if(a.cmd="connect",this.topicAliasRecv&&(a.properties||(a.properties={}),this.topicAliasRecv&&(a.properties.topicAliasMaximum=this.topicAliasRecv.max)),T(this,a),i.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return t.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&T(this,v({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),t._cleanUp(!0)}),this.options.connectTimeout)},R.prototype._handlePacket=function(t,e){const i=this.options;if(5===i.protocolVersion&&i.properties&&i.properties.maximumPacketSize&&i.properties.maximumPacketSize0||!s())&&this._storeProcessingQueue.push({invoke:s,cbStorePut:i.cbStorePut,callback:n}),this},R.prototype.subscribe=function(){const t=this,e=new Array(arguments.length);for(let t=0;t0){const n={qos:i.qos};5===a&&(n.nl=i.nl||!1,n.rap=i.rap||!1,n.rh=i.rh||0,n.properties=i.properties),t._resubscribeTopics[i.topic]=n,e.push(i.topic)}})),t.messageIdToTopic[n.messageId]=e}return t.outgoing[n.messageId]={volatile:!0,cb:function(t,e){if(!t){const t=e.granted;for(let e=0;e0||!h())&&this._storeProcessingQueue.push({invoke:h,callback:r}),this},R.prototype.unsubscribe=function(){const t=this,e=new Array(arguments.length);for(let t=0;t0||!s())&&this._storeProcessingQueue.push({invoke:s,callback:n}),this},R.prototype.end=function(t,e,i){const n=this;function o(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",n.options.clientId,t),n._cleanUp(t,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(function(){g("end :: closeStores: closing incoming and outgoing stores"),n.disconnected=!0,n.incomingStore.close((function(t){n.outgoingStore.close((function(e){if(g("end :: closeStores: emitting end"),n.emit("end"),i){const n=t||e;g("end :: closeStores: invoking callback with args"),i(n)}}))})),n._deferredReconnect&&n._deferredReconnect()}.bind(n))}),e)}return g("end :: (%s)",this.options.clientId),null!=t&&"boolean"==typeof t||(i=e||C,e=t,t=!1,"object"!=typeof e&&(i=e,e=null,"function"!=typeof i&&(i=C))),"object"!=typeof e&&(i=e,e=null),g("end :: cb? %s",!!i),i=i||C,this.disconnecting?(i(),this):(this._clearReconnect(),this.disconnecting=!0,!t&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",n.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,o,10))):(g("end :: (%s) :: immediately calling finish",n.options.clientId),o()),this)},R.prototype.removeOutgoingMessage=function(t){const e=this.outgoing[t]?this.outgoing[t].cb:null;return delete this.outgoing[t],this.outgoingStore.del({messageId:t},(function(){e(new Error("Message removed"))})),this},R.prototype.reconnect=function(t){g("client reconnect");const e=this,i=function(){t?(e.options.incomingStore=t.incomingStore,e.options.outgoingStore=t.outgoingStore):(e.options.incomingStore=null,e.options.outgoingStore=null),e.incomingStore=e.options.incomingStore||new r,e.outgoingStore=e.options.outgoingStore||new r,e.disconnecting=!1,e.disconnected=!1,e._deferredReconnect=null,e._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=i:i(),this},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const t=this;!t.disconnecting&&!t.reconnectTimer&&t.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",t.options.reconnectPeriod),t.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),t._reconnect()}),t.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(t,e){const i=arguments[2];if(e&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",e)),g("_cleanUp :: forced? %s",t),t)0===this.options.reconnectPeriod&&this.options.clean&&(n=this.outgoing)&&(g("flush: queue exists? %b",!!n),Object.keys(n).forEach((function(t){"function"==typeof n[t].cb&&(n[t].cb(new Error("Connection closed")),delete n[t])}))),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const t=v({cmd:"disconnect"},i);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(t,m.bind(null,this.stream.end.bind(this.stream)))}var n;this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),e&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",e),e())},R.prototype._sendPacket=function(t,e,i){g("_sendPacket :: (%s) :: start",this.options.clientId),i=i||C,e=e||C;const n=function(t,e){if(5===t.options.protocolVersion&&"publish"===e.cmd){let i;e.properties&&(i=e.properties.topicAlias);const n=e.topic.toString();if(t.topicAliasSend)if(i){if(0!==n.length&&(g("applyTopicAlias :: register topic: %s - alias: %d",n,i),!t.topicAliasSend.put(n,i)))return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",n,i),new Error("Sending Topic Alias out of range")}else 0!==n.length&&(t.options.autoAssignTopicAlias?(i=t.topicAliasSend.getAliasByTopic(n))?(e.topic="",e.properties={...e.properties,topicAlias:i},g("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",n,i)):(i=t.topicAliasSend.getLruAlias(),t.topicAliasSend.put(n,i),e.properties={...e.properties,topicAlias:i},g("applyTopicAlias :: auto assign topic: %s - alias: %d",n,i)):t.options.autoUseTopicAlias&&(i=t.topicAliasSend.getAliasByTopic(n))&&(e.topic="",e.properties={...e.properties,topicAlias:i},g("applyTopicAlias :: auto use topic: %s - alias: %d",n,i)));else if(i)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",n,i),new Error("Sending Topic Alias out of range")}}(this,t);if(n)e(n);else{if(!this.connected)return"auth"===t.cmd?(this._shiftPingInterval(),void T(this,t,e)):(g("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(t,e,i));switch(this._shiftPingInterval(),t.cmd){case"publish":break;case"pubrel":return void A(this,t,e,i);default:return void T(this,t,e)}switch(t.qos){case 2:case 1:A(this,t,e,i);break;default:T(this,t,e)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(t,e,i){g("_storePacket :: packet: %o",t),g("_storePacket :: cb? %s",!!e),i=i||C;let n=t;if("publish"===n.cmd){const i=k(this,n=f(t));if(i)return e&&e(i)}0===(n.qos||0)&&this.queueQoSZero||"publish"!==n.cmd?this.queue.push({packet:n,cb:e}):n.qos>0?(e=this.outgoing[n.messageId]?this.outgoing[n.messageId].cb:null,this.outgoingStore.put(n,(function(t){if(t)return e&&e(t);i()}))):e&&e(new Error("No connection to broker"))},R.prototype._setupPingTimer=function(){g("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const t=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=u((function(){t._checkPing()}),1e3*this.options.keepalive))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(t){g("_handleConnack");const e=this.options,i=5===e.protocolVersion?t.reasonCode:t.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,t.properties){if(t.properties.topicAliasMaximum){if(t.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));t.properties.topicAliasMaximum>0&&(this.topicAliasSend=new a(t.properties.topicAliasMaximum))}t.properties.serverKeepAlive&&e.keepalive&&(e.keepalive=t.properties.serverKeepAlive,this._shiftPingInterval()),t.properties.maximumPacketSize&&(e.properties||(e.properties={}),e.properties.maximumPacketSize=t.properties.maximumPacketSize)}if(0===i)this.reconnecting=!1,this._onConnect(t);else if(i>0){const t=new Error("Connection refused: "+b[i]);t.code=i,this.emit("error",t)}},R.prototype._handleAuth=function(t){const e=this.options.protocolVersion,i=5===e?t.reasonCode:t.returnCode;if(5!==e){const t=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+e);return t.code=i,void this.emit("error",t)}const n=this;this.handleAuth(t,(function(t,e){if(t)n.emit("error",t);else if(24===i)n.reconnecting=!1,n._sendPacket(e);else{const e=new Error("Connection refused: "+b[i]);t.code=i,n.emit("error",e)}}))},R.prototype.handleAuth=function(t,e){e()},R.prototype._handlePublish=function(t,e){g("_handlePublish: packet %o",t),e=void 0!==e?e:C;let i=t.topic.toString();const n=t.payload,o=t.qos,r=t.messageId,s=this,a=this.options,l=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let e;if(t.properties&&(e=t.properties.topicAlias),void 0!==e)if(0===i.length){if(!(e>0&&e<=65535))return g("_handlePublish :: topic alias out of range. alias: %d",e),void this.emit("error",new Error("Received Topic Alias is out of range"));{const t=this.topicAliasRecv.getTopicByAlias(e);if(!t)return g("_handlePublish :: unregistered topic alias. alias: %d",e),void this.emit("error",new Error("Received unregistered Topic Alias"));g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",i=t,e)}}else{if(!this.topicAliasRecv.put(i,e))return g("_handlePublish :: topic alias out of range. alias: %d",e),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",i,e)}}switch(g("_handlePublish: qos %d",o),o){case 2:a.customHandleAcks(i,n,t,(function(i,n){return i instanceof Error||(n=i,i=null),i?s.emit("error",i):-1===l.indexOf(n)?s.emit("error",new Error("Wrong reason code for pubrec")):void(n?s._sendPacket({cmd:"pubrec",messageId:r,reasonCode:n},e):s.incomingStore.put(t,(function(){s._sendPacket({cmd:"pubrec",messageId:r},e)})))}));break;case 1:a.customHandleAcks(i,n,t,(function(o,a){return o instanceof Error||(a=o,o=null),o?s.emit("error",o):-1===l.indexOf(a)?s.emit("error",new Error("Wrong reason code for puback")):(a||s.emit("message",i,n,t),void s.handleMessage(t,(function(t){if(t)return e&&e(t);s._sendPacket({cmd:"puback",messageId:r,reasonCode:a},e)})))}));break;case 0:this.emit("message",i,n,t),this.handleMessage(t,e);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(t,e){e()},R.prototype._handleAck=function(t){const e=t.messageId,i=t.cmd;let n=null;const o=this.outgoing[e]?this.outgoing[e].cb:null,r=this;let s;if(o){switch(g("_handleAck :: packet type",i),i){case"pubcomp":case"puback":{const i=t.reasonCode;i&&i>0&&16!==i&&((s=new Error("Publish error: "+b[i])).code=i,o(s,t)),delete this.outgoing[e],this.outgoingStore.del(t,o),this.messageIdProvider.deallocate(e),this._invokeStoreProcessingQueue();break}case"pubrec":{n={cmd:"pubrel",qos:2,messageId:e};const i=t.reasonCode;i&&i>0&&16!==i?((s=new Error("Publish error: "+b[i])).code=i,o(s,t)):this._sendPacket(n);break}case"suback":delete this.outgoing[e],this.messageIdProvider.deallocate(e);for(let i=0;i0)if(this.options.resubscribe)if(5===this.options.protocolVersion){g("_resubscribe: protocolVersion 5");for(let e=0;e0){const t=this._storeProcessingQueue[0];if(t&&t.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.prototype._flushStoreProcessingQueue=function(){for(const t of this._storeProcessingQueue)t.cbStorePut&&t.cbStorePut(new Error("Connection closed")),t.callback&&t.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},e.exports=R}).call(this)}).call(this,t("_process"),void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(t,e,i){"use strict";const{Buffer:n}=t("buffer"),o=t("readable-stream").Transform,r=t("duplexify");let s,a,l,c=!1;e.exports=function(t,e){if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");const i="MQIsdp"===e.protocolId&&3===e.protocolVersion?"mqttv3.1":"mqtt";!function(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}(e);const h=function(t,e){const i="alis"===t.protocol?"wss":"ws";let n=i+"://"+t.hostname+t.path;return t.port&&80!==t.port&&443!==t.port&&(n=i+"://"+t.hostname+":"+t.port+t.path),"function"==typeof t.transformWsUrl&&(n=t.transformWsUrl(n,t,e)),n}(e,t);return(s=e.my).connectSocket({url:h,protocols:i}),a=function(){const t=new o;return t._write=function(t,e,i){s.sendSocketMessage({data:t.buffer,success:function(){i()},fail:function(){i(new Error)}})},t._flush=function(t){s.closeSocket({success:function(){t()}})},t}(),l=r.obj(),c||(c=!0,s.onSocketOpen((function(){l.setReadable(a),l.setWritable(a),l.emit("connect")})),s.onSocketMessage((function(t){if("string"==typeof t.data){const e=n.from(t.data,"base64");a.push(e)}else{const e=new FileReader;e.addEventListener("load",(function(){let t=e.result;t=t instanceof ArrayBuffer?n.from(t):n.from(t,"utf8"),a.push(t)})),e.readAsArrayBuffer(t.data)}})),s.onSocketClose((function(){l.end(),l.destroy()})),s.onSocketError((function(t){l.destroy(t)}))),l}},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(t,e,i){"use strict";const n=t("net"),o=t("debug")("mqttjs:tcp");e.exports=function(t,e){e.port=e.port||1883,e.hostname=e.hostname||e.host||"localhost";const i=e.port,r=e.hostname;return o("port %d and host %s",i,r),n.createConnection(i,r)}},{debug:18,net:16}],4:[function(t,e,i){"use strict";const n=t("tls"),o=t("net"),r=t("debug")("mqttjs:tls");e.exports=function(t,e){e.port=e.port||8883,e.host=e.hostname||e.host||"localhost",0===o.isIP(e.host)&&(e.servername=e.host),e.rejectUnauthorized=!1!==e.rejectUnauthorized,delete e.path,r("port %d host %s rejectUnauthorized %b",e.port,e.host,e.rejectUnauthorized);const i=n.connect(e);function s(n){e.rejectUnauthorized&&t.emit("error",n),i.end()}return i.on("secureConnect",(function(){e.rejectUnauthorized&&!i.authorized?i.emit("error",new Error("TLS not authorized")):i.removeListener("error",s)})),i.on("error",s),i}},{debug:18,net:16,tls:16}],5:[function(t,e,n){(function(n){(function(){"use strict";const{Buffer:o}=t("buffer"),r=t("ws"),s=t("debug")("mqttjs:ws"),a=t("duplexify"),l=t("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],h=void 0!==n&&"browser"===n.title||"function"==typeof i;function d(t,e){let i=t.protocol+"://"+t.hostname+":"+t.port+t.path;return"function"==typeof t.transformWsUrl&&(i=t.transformWsUrl(i,t,e)),i}function u(t){const e=t;return t.hostname||(e.hostname="localhost"),t.port||("wss"===t.protocol?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),h||"wss"!==t.protocol||c.forEach((function(i){Object.prototype.hasOwnProperty.call(t,i)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,i)&&(e.wsOptions[i]=t[i])})),e}e.exports=h?function(t,e){let i;s("browserStreamBuilder");const n=function(t){const e=u(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const t=new URL(document.URL);e.hostname=t.hostname,e.port||(e.port=t.port)}return void 0===e.objectMode&&(e.objectMode=!(!0===e.binary||void 0===e.binary)),e}(e).browserBufferSize||524288,r=e.browserBufferTimeout||1e3,c=!e.objectMode,h=function(t,e){const i="MQIsdp"===e.protocolId&&3===e.protocolVersion?"mqttv3.1":"mqtt",n=d(e,t),o=new WebSocket(n,[i]);return o.binaryType="arraybuffer",o}(t,e),f=function(t,e,i){const n=new l({objectModeMode:t.objectMode});return n._write=e,n._flush=function(t){h.close(),t()},n}(e,(function t(e,i,s){h.bufferedAmount>n&&setTimeout(t,r,e,i,s),c&&"string"==typeof e&&(e=o.from(e,"utf8"));try{h.send(e)}catch(t){return s(t)}s()}));e.objectMode||(f._writev=w),f.on("close",(()=>{h.close()}));const p=void 0!==h.addEventListener;function v(){i.setReadable(f),i.setWritable(f),i.emit("connect")}function g(){i.end(),i.destroy()}function y(t){i.destroy(t)}function m(t){let e=t.data;e=e instanceof ArrayBuffer?o.from(e):o.from(e,"utf8"),f.push(e)}function w(t,e){const i=new Array(t.length);for(let e=0;e{a.destroy()})),a}}).call(this)}).call(this,t("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(t,e,i){"use strict";const{Buffer:n}=t("buffer"),o=t("readable-stream").Transform,r=t("duplexify");let s,a,l;e.exports=function(t,e){if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");const i="MQIsdp"===e.protocolId&&3===e.protocolVersion?"mqttv3.1":"mqtt";!function(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}(e);const c=function(t,e){const i="wxs"===t.protocol?"wss":"ws";let n=i+"://"+t.hostname+t.path;return t.port&&80!==t.port&&443!==t.port&&(n=i+"://"+t.hostname+":"+t.port+t.path),"function"==typeof t.transformWsUrl&&(n=t.transformWsUrl(n,t,e)),n}(e,t);s=wx.connectSocket({url:c,protocols:[i]}),a=function(){const t=new o;return t._write=function(t,e,i){s.send({data:t.buffer,success:function(){i()},fail:function(t){i(new Error(t))}})},t._flush=function(t){s.close({success:function(){t()}})},t}(),(l=r.obj())._destroy=function(t,e){s.close({success:function(){e&&e(t)}})};const h=l.destroy;return l.destroy=function(){l.destroy=h;const t=this;setTimeout((function(){s.close({fail:function(){t._destroy(new Error)}})}),0)}.bind(l),s.onOpen((function(){l.setReadable(a),l.setWritable(a),l.emit("connect")})),s.onMessage((function(t){let e=t.data;e=e instanceof ArrayBuffer?n.from(e):n.from(e,"utf8"),a.push(e)})),s.onClose((function(){l.end(),l.destroy()})),s.onError((function(t){l.destroy(new Error(t.errMsg))})),l}},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(t,e,i){"use strict";function n(){if(!(this instanceof n))return new n;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}n.prototype.allocate=function(){const t=this.nextId++;return 65536===this.nextId&&(this.nextId=1),t},n.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},n.prototype.register=function(t){return!0},n.prototype.deallocate=function(t){},n.prototype.clear=function(){},e.exports=n},{}],8:[function(t,e,i){"use strict";const n=t("xtend"),o=t("readable-stream").Readable,r={objectMode:!0},s={clean:!0};function a(t){if(!(this instanceof a))return new a(t);this.options=t||{},this.options=n(s,t),this._inflights=new Map}a.prototype.put=function(t,e){return this._inflights.set(t.messageId,t),e&&e(),this},a.prototype.createStream=function(){const t=new o(r),e=[];let i=!1,n=0;return this._inflights.forEach((function(t,i){e.push(t)})),t._read=function(){!i&&nthis.max||(this.aliasToTopic[e]=t,this.length=Object.keys(this.aliasToTopic).length,0))},n.prototype.getTopicByAlias=function(t){return this.aliasToTopic[t]},n.prototype.clear=function(){this.aliasToTopic={}},e.exports=n},{}],10:[function(t,e,i){"use strict";const n=t("lru-cache"),o=t("number-allocator").NumberAllocator;function r(t){if(!(this instanceof r))return new r(t);t>0&&(this.aliasToTopic=new n({max:t}),this.topicToAlias={},this.numberAllocator=new o(1,t),this.max=t,this.length=0)}r.prototype.put=function(t,e){if(0===e||e>this.max)return!1;const i=this.aliasToTopic.get(e);return i&&delete this.topicToAlias[i],this.aliasToTopic.set(e,t),this.topicToAlias[t]=e,this.numberAllocator.use(e),this.length=this.aliasToTopic.length,!0},r.prototype.getTopicByAlias=function(t){return this.aliasToTopic.get(t)},r.prototype.getAliasByTopic=function(t){const e=this.topicToAlias[t];return void 0!==e&&this.aliasToTopic.get(e),e},r.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},r.prototype.getLruAlias=function(){return this.numberAllocator.firstVacant()||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},e.exports=r},{"lru-cache":37,"number-allocator":46}],11:[function(t,e,i){"use strict";function n(t){const e=t.split("/");for(let t=0;t0?s-4:s;for(i=0;i>16&255,l[h++]=e>>8&255,l[h++]=255&e;return 2===a&&(e=o[t.charCodeAt(i)]<<2|o[t.charCodeAt(i+1)]>>4,l[h++]=255&e),1===a&&(e=o[t.charCodeAt(i)]<<10|o[t.charCodeAt(i+1)]<<4|o[t.charCodeAt(i+2)]>>2,l[h++]=e>>8&255,l[h++]=255&e),l},i.fromByteArray=function(t){for(var e,i=t.length,o=i%3,r=[],s=0,a=i-o;sa?a:s+16383));return 1===o?(e=t[i-1],r.push(n[e>>2]+n[e<<4&63]+"==")):2===o&&(e=(t[i-2]<<8)+t[i-1],r.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"=")),r.join("")};for(var n=[],o=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,l=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var i=t.indexOf("=");return-1===i&&(i=e),[i,i===e?0:4-i%4]}function h(t,e,i){for(var o,r,s=[],a=e;a>18&63]+n[r>>12&63]+n[r>>6&63]+n[63&r]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],14:[function(t,e,i){"use strict";const{Buffer:n}=t("buffer"),o=Symbol.for("BufferList");function r(t){if(!(this instanceof r))return new r(t);r._init.call(this,t)}r._init=function(t){Object.defineProperty(this,o,{value:!0}),this._bufs=[],this.length=0,t&&this.append(t)},r.prototype._new=function(t){return new r(t)},r.prototype._offset=function(t){if(0===t)return[0,0];let e=0;for(let i=0;ithis.length||t<0)return;const e=this._offset(t);return this._bufs[e[0]][e[1]]},r.prototype.slice=function(t,e){return"number"==typeof t&&t<0&&(t+=this.length),"number"==typeof e&&e<0&&(e+=this.length),this.copy(null,0,t,e)},r.prototype.copy=function(t,e,i,o){if(("number"!=typeof i||i<0)&&(i=0),("number"!=typeof o||o>this.length)&&(o=this.length),i>=this.length)return t||n.alloc(0);if(o<=0)return t||n.alloc(0);const r=!!t,s=this._offset(i),a=o-i;let l=a,c=r&&e||0,h=s[1];if(0===i&&o===this.length){if(!r)return 1===this._bufs.length?this._bufs[0]:n.concat(this._bufs,this.length);for(let e=0;ei)){this._bufs[e].copy(t,c,h,h+l),c+=i;break}this._bufs[e].copy(t,c,h),c+=i,l-=i,h&&(h=0)}return t.length>c?t.slice(0,c):t},r.prototype.shallowSlice=function(t,e){if(t=t||0,e="number"!=typeof e?this.length:e,t<0&&(t+=this.length),e<0&&(e+=this.length),t===e)return this._new();const i=this._offset(t),n=this._offset(e),o=this._bufs.slice(i[0],n[0]+1);return 0===n[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,n[1]),0!==i[1]&&(o[0]=o[0].slice(i[1])),this._new(o)},r.prototype.toString=function(t,e,i){return this.slice(e,i).toString(t)},r.prototype.consume=function(t){if(t=Math.trunc(t),Number.isNaN(t)||t<=0)return this;for(;this._bufs.length;){if(!(t>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(t),this.length-=t;break}t-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},r.prototype.duplicate=function(){const t=this._new();for(let e=0;ethis.length?this.length:e;const o=this._offset(e);let r=o[0],s=o[1];for(;r=t.length){const i=e.indexOf(t,s);if(-1!==i)return this._reverseOffset([r,i]);s=e.length-t.length+1}else{const e=this._reverseOffset([r,s]);if(this._match(e,t))return e;s++}s=0}return-1},r.prototype._match=function(t,e){if(this.length-to)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,i){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,i)}function a(t,e,i){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var i=0|u(t,e),n=r(i),o=n.write(t,e);return o!==i&&(n=n.slice(0,o)),n}(t,e);if(ArrayBuffer.isView(t))return h(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(z(t,ArrayBuffer)||t&&z(t.buffer,ArrayBuffer))return function(t,e,i){if(e<0||t.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function u(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||z(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var i=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===i)return 0;for(var o=!1;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return N(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return B(t).length;default:if(o)return n?-1:N(t).length;e=(""+e).toLowerCase(),o=!0}}function f(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function p(t,e,i,n,o){if(0===t.length)return-1;if("string"==typeof i?(n=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),H(i=+i)&&(i=o?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(o)return-1;i=t.length-1}else if(i<0){if(!o)return-1;i=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:v(t,e,i,n,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):v(t,[e],i,n,o);throw new TypeError("val must be string, number or Buffer")}function v(t,e,i,n,o){var r,s=1,a=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,l/=2,i/=2}function c(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(o){var h=-1;for(r=i;ra&&(i=a-l),r=i;r>=0;r--){for(var d=!0,u=0;uo&&(n=o):n=o;var r=e.length;n>r/2&&(n=r/2);for(var s=0;s>8,o=i%256,r.push(o),r.push(n);return r}(e,t.length-i),t,i,n)}function k(t,i,n){return 0===i&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(i,n))}function T(t,e,i){i=Math.min(t.length,i);for(var n=[],o=e;o239?4:c>223?3:c>191?2:1;if(o+d<=i)switch(d){case 1:c<128&&(h=c);break;case 2:128==(192&(r=t[o+1]))&&(l=(31&c)<<6|63&r)>127&&(h=l);break;case 3:r=t[o+1],s=t[o+2],128==(192&r)&&128==(192&s)&&(l=(15&c)<<12|(63&r)<<6|63&s)>2047&&(l<55296||l>57343)&&(h=l);break;case 4:r=t[o+1],s=t[o+2],a=t[o+3],128==(192&r)&&128==(192&s)&&128==(192&a)&&(l=(15&c)<<18|(63&r)<<12|(63&s)<<6|63&a)>65535&&l<1114112&&(h=l)}null===h?(h=65533,d=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),o+=d}return function(t){var e=t.length;if(e<=A)return String.fromCharCode.apply(String,t);for(var i="",n=0;nthis.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return S(this,e,i);case"utf8":case"utf-8":return T(this,e,i);case"ascii":return C(this,e,i);case"latin1":case"binary":return R(this,e,i);case"base64":return k(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,i);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){var t="",e=i.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},s.prototype.compare=function(t,e,i,n,o){if(z(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||i>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=i)return 0;if(n>=o)return-1;if(e>=i)return 1;if(this===t)return 0;for(var r=(o>>>=0)-(n>>>=0),a=(i>>>=0)-(e>>>=0),l=Math.min(r,a),c=this.slice(n,o),h=t.slice(e,i),d=0;d>>=0,isFinite(i)?(i>>>=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var o=this.length-e;if((void 0===i||i>o)&&(i=o),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var r=!1;;)switch(n){case"hex":return g(this,t,e,i);case"utf8":case"utf-8":return y(this,t,e,i);case"ascii":return m(this,t,e,i);case"latin1":case"binary":return w(this,t,e,i);case"base64":return x(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),r=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function C(t,e,i){var n="";i=Math.min(t.length,i);for(var o=e;on)&&(i=n);for(var o="",r=e;ri)throw new RangeError("Trying to access beyond buffer length")}function I(t,e,i,n,o,r){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function _(t,e,i,n,o,r){if(i+n>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function L(t,e,i,o,r){return e=+e,i>>>=0,r||_(t,0,i,4),n.write(t,e,i,o,23,4),i+4}function M(t,e,i,o,r){return e=+e,i>>>=0,r||_(t,0,i,8),n.write(t,e,i,o,52,8),i+8}s.prototype.slice=function(t,e){var i=this.length;(t=~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),(e=void 0===e?i:~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),e>>=0,e>>>=0,i||E(t,e,this.length);for(var n=this[t],o=1,r=0;++r>>=0,e>>>=0,i||E(t,e,this.length);for(var n=this[t+--e],o=1;e>0&&(o*=256);)n+=this[t+--e]*o;return n},s.prototype.readUInt8=function(t,e){return t>>>=0,e||E(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||E(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||E(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||E(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||E(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,i){t>>>=0,e>>>=0,i||E(t,e,this.length);for(var n=this[t],o=1,r=0;++r=(o*=128)&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,i){t>>>=0,e>>>=0,i||E(t,e,this.length);for(var n=e,o=1,r=this[t+--n];n>0&&(o*=256);)r+=this[t+--n]*o;return r>=(o*=128)&&(r-=Math.pow(2,8*e)),r},s.prototype.readInt8=function(t,e){return t>>>=0,e||E(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||E(t,2,this.length);var i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt16BE=function(t,e){t>>>=0,e||E(t,2,this.length);var i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||E(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||E(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||E(t,4,this.length),n.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||E(t,4,this.length),n.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||E(t,8,this.length),n.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||E(t,8,this.length),n.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,i,n){t=+t,e>>>=0,i>>>=0,n||I(this,t,e,i,Math.pow(2,8*i)-1,0);var o=1,r=0;for(this[e]=255&t;++r>>=0,i>>>=0,n||I(this,t,e,i,Math.pow(2,8*i)-1,0);var o=i-1,r=1;for(this[e+o]=255&t;--o>=0&&(r*=256);)this[e+o]=t/r&255;return e+i},s.prototype.writeUInt8=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,i,n){if(t=+t,e>>>=0,!n){var o=Math.pow(2,8*i-1);I(this,t,e,i,o-1,-o)}var r=0,s=1,a=0;for(this[e]=255&t;++r>0)-a&255;return e+i},s.prototype.writeIntBE=function(t,e,i,n){if(t=+t,e>>>=0,!n){var o=Math.pow(2,8*i-1);I(this,t,e,i,o-1,-o)}var r=i-1,s=1,a=0;for(this[e+r]=255&t;--r>=0&&(s*=256);)t<0&&0===a&&0!==this[e+r+1]&&(a=1),this[e+r]=(t/s>>0)-a&255;return e+i},s.prototype.writeInt8=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,i){return t=+t,e>>>=0,i||I(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,i){return L(this,t,e,!0,i)},s.prototype.writeFloatBE=function(t,e,i){return L(this,t,e,!1,i)},s.prototype.writeDoubleLE=function(t,e,i){return M(this,t,e,!0,i)},s.prototype.writeDoubleBE=function(t,e,i){return M(this,t,e,!1,i)},s.prototype.copy=function(t,e,i,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(i||(i=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--r)t[r+e]=this[r+i];else Uint8Array.prototype.set.call(t,this.subarray(i,n),e);return o},s.prototype.fill=function(t,e,i,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var o=t.charCodeAt(0);("utf8"===n&&o<128||"latin1"===n)&&(t=o)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,i=void 0===i?this.length:i>>>0,t||(t=0),"number"==typeof t)for(r=e;r55295&&i<57344){if(!o){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&r.push(239,191,189);continue}o=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),o=i;continue}i=65536+(o-55296<<10|i-56320)}else o&&(e-=3)>-1&&r.push(239,191,189);if(o=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function B(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(D,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function F(t,e,i,n){for(var o=0;o=e.length||o>=t.length);++o)e[o+i]=t[o];return o}function z(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(t,e,i){(function(n){(function(){i.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(t=>{"%%"!==t&&"%c"===t&&(o=++n)})),t.splice(o,0,i)},i.save=function(t){try{t?i.storage.setItem("debug",t):i.storage.removeItem("debug")}catch(t){}},i.load=function(){let t;try{t=i.storage.getItem("debug")}catch(t){}return!t&&void 0!==n&&"env"in n&&(t=n.env.DEBUG),t},i.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},i.storage=function(){try{return localStorage}catch(t){}}(),i.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),i.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],i.log=console.debug||console.log||(()=>{}),e.exports=t("./common")(i);const{formatters:o}=e.exports;o.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}).call(this)}).call(this,t("_process"))},{"./common":19,_process:50}],19:[function(t,e,i){e.exports=function(e){function i(t){let e,o,r,s=null;function a(...t){if(!a.enabled)return;const n=a,o=Number(new Date),r=o-(e||o);n.diff=r,n.prev=e,n.curr=o,e=o,t[0]=i.coerce(t[0]),"string"!=typeof t[0]&&t.unshift("%O");let s=0;t[0]=t[0].replace(/%([a-zA-Z%])/g,((e,o)=>{if("%%"===e)return"%";s++;const r=i.formatters[o];if("function"==typeof r){const i=t[s];e=r.call(n,i),t.splice(s,1),s--}return e})),i.formatArgs.call(n,t),(n.log||i.log).apply(n,t)}return a.namespace=t,a.useColors=i.useColors(),a.color=i.selectColor(t),a.extend=n,a.destroy=i.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(o!==i.namespaces&&(o=i.namespaces,r=i.enabled(t)),r),set:t=>{s=t}}),"function"==typeof i.init&&i.init(a),a}function n(t,e){const n=i(this.namespace+(void 0===e?":":e)+t);return n.log=this.log,n}function o(t){return t.toString().substring(2,t.toString().length-2).replace(/\.\*\?$/,"*")}return i.debug=i,i.default=i,i.coerce=function(t){return t instanceof Error?t.stack||t.message:t},i.disable=function(){const t=[...i.names.map(o),...i.skips.map(o).map((t=>"-"+t))].join(",");return i.enable(""),t},i.enable=function(t){let e;i.save(t),i.namespaces=t,i.names=[],i.skips=[];const n=("string"==typeof t?t:"").split(/[\s,]+/),o=n.length;for(e=0;e{i[t]=e[t]})),i.names=[],i.skips=[],i.formatters={},i.selectColor=function(t){let e=0;for(let i=0;i0&&a.length>r){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(e)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');l.name="MaxListenersExceededWarning",l.emitter=t,l.type=e,l.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",l.name,l.message)}}else a=s[e]=i,++t._eventsCount;return t}function u(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var t=new Array(arguments.length),e=0;e1&&(e=arguments[1]),e instanceof Error)throw e;var l=new Error('Unhandled "error" event. ('+e+")");throw l.context=e,l}if(!(i=s[t]))return!1;var c="function"==typeof i;switch(n=arguments.length){case 1:!function(t,e,i){if(e)t.call(i);else for(var n=t.length,o=g(t,n),r=0;r=0;s--)if(i[s]===e||i[s].listener===e){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(t,e){for(var i=e,n=i+1,o=t.length;n=0;r--)this.removeListener(t,e[r]);return this},s.prototype.listeners=function(t){return p(this,t,!0)},s.prototype.rawListeners=function(t){return p(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):v.call(t,e)},s.prototype.listenerCount=v,s.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(t,e,i){i.read=function(t,e,i,n,o){var r,s,a=8*o-n-1,l=(1<>1,h=-7,d=i?o-1:0,u=i?-1:1,f=t[e+d];for(d+=u,r=f&(1<<-h)-1,f>>=-h,h+=a;h>0;r=256*r+t[e+d],d+=u,h-=8);for(s=r&(1<<-h)-1,r>>=-h,h+=n;h>0;s=256*s+t[e+d],d+=u,h-=8);if(0===r)r=1-c;else{if(r===l)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),r-=c}return(f?-1:1)*s*Math.pow(2,r-n)},i.write=function(t,e,i,n,o,r){var s,a,l,c=8*r-o-1,h=(1<>1,u=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:r-1,p=n?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),(e+=s+d>=1?u/l:u*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=h?(a=0,s=h):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s+=d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;t[i+f]=255&a,f+=p,a/=256,o-=8);for(s=s<0;t[i+f]=255&s,f+=p,s/=256,c-=8);t[i+f-p]|=128*v}},{}],24:[function(t,e,i){"function"==typeof Object.create?e.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,e){if(e){t.super_=e;var i=function(){};i.prototype=e.prototype,t.prototype=new i,t.prototype.constructor=t}}},{}],25:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=function(){function t(t,e){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=t,this.value=e}return t.prototype.rotateLeft=function(){var t=this.parent,e=this.brother,i=this.leftChild,n=this.rightChild;if(!n)throw new Error("unknown error");var o=n.leftChild,r=n.rightChild;return t&&(t.leftChild===this?t.leftChild=n:t.rightChild===this&&(t.rightChild=n)),n.parent=t,n.brother=e,n.leftChild=this,n.rightChild=r,e&&(e.brother=n),this.parent=n,this.brother=r,this.leftChild=i,this.rightChild=o,r&&(r.parent=n,r.brother=this),i&&(i.parent=this,i.brother=o),o&&(o.parent=this,o.brother=i),n},t.prototype.rotateRight=function(){var t=this.parent,e=this.brother,i=this.leftChild;if(!i)throw new Error("unknown error");var n=this.rightChild,o=i.leftChild,r=i.rightChild;return t&&(t.leftChild===this?t.leftChild=i:t.rightChild===this&&(t.rightChild=i)),i.parent=t,i.brother=e,i.leftChild=o,i.rightChild=this,e&&(e.brother=i),o&&(o.parent=i,o.brother=this),this.parent=i,this.brother=o,this.leftChild=r,this.rightChild=n,r&&(r.parent=this,r.brother=n),n&&(n.parent=this,n.brother=r),i},t.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},t.TreeNodeColorType={red:!0,black:!1},t}();Object.freeze(n),i.default=n},{}],26:[function(t,e,i){"use strict";var n=this&&this.__generator||function(t,e){var i,n,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(o=2&r[0]?n.return:r[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,r[1])).done)return o;switch(n=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]n)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(i/o.bucketSize),curNodePointerIndex:i%o.bucketSize}};this.getElementByPos=function(t){var e=d(t),n=e.curNodeBucketIndex,o=e.curNodePointerIndex;return i[n][o]},this.eraseElementByPos=function(t){var e=this;if(t<0||t>h)throw new Error("pos should more than 0 and less than queue's size");if(0===t)this.popFront();else if(t===this.size())this.popBack();else{for(var i=[],n=t+1;n0?--l:r0&&--h)},this.setElementByPos=function(t,e){var n=d(t),o=n.curNodeBucketIndex,r=n.curNodePointerIndex;i[o][r]=e},this.insert=function(t,e,i){var n=this;if(void 0===i&&(i=1),0===t)for(;i--;)this.pushFront(e);else if(t===this.size())for(;i--;)this.pushBack(e);else{for(var o=[],r=t;r0?--s:r>0&&(--r,s=o.bucketSize-1)),++h,i[r][s]=t},this.popFront=function(){this.empty()||(1!==this.size()&&(s0&&--h)},this.shrinkToFit=function(){var t=this,e=[];this.forEach((function(t){e.push(t)}));var n=e.length;i=[];for(var r=Math.ceil(n/o.bucketSize),s=0;s0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(i,"__esModule",{value:!0});var r=t("../LinkList/LinkList"),s=t("../Map/Map");function a(t,e,i){var l=this;if(void 0===t&&(t=[]),void 0===e&&(e=a.initSize),i=i||function(t){var e,i,n=0,r="";if("number"==typeof t)n=((n=Math.floor(t))<<5)-n,n&=n;else{r="string"!=typeof t?JSON.stringify(t):t;try{for(var s=o(r),a=s.next();!a.done;a=s.next())n=(n<<5)-n+a.value.charCodeAt(0),n&=n}catch(t){e={error:t}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(e)throw e.error}}}return n^n>>>16},0!=(e&e-1))throw new Error("initBucketNum must be 2 to the power of n");var c=0,h=[],d=Math.max(a.initSize,Math.min(a.maxSize,e));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,d=e,h=[]},this.forEach=function(t){var e=0;h.forEach((function(i){i.forEach((function(i){t(i,e++)}))}))},this.setElement=function(t,e){var n,l;if(null==t)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=e){var u=i(t)&d-1;if(h[u]){var f=h[u].size();if(h[u]instanceof r.default){try{for(var p=o(h[u]),v=p.next();!v.done;v=p.next()){var g=v.value;if(g.key===t)return void(g.value=e)}}catch(t){n={error:t}}finally{try{v&&!v.done&&(l=p.return)&&l.call(p)}finally{if(n)throw n.error}}h[u].pushBack({key:t,value:e}),h[u].size()>=a.treeifyThreshold&&(h[u]=new s.default(h[u]))}else h[u].setElement(t,e);var y=h[u].size();c+=y-f}else++c,h[u]=new r.default([{key:t,value:e}]);c>d*a.sigma&&function(t){if(!(t>=a.maxSize)){d=2*t;var e=[];h.forEach((function(n,o){if(!n.empty()){if(n instanceof r.default&&1===n.size()){var l=n.front(),c=l.key,u=l.value;e[i(c)&d-1]=new r.default([{key:c,value:u}])}else if(n instanceof s.default){var f=new r.default,p=new r.default;n.forEach((function(e){0==(i(e.key)&t)?f.pushBack(e):p.pushBack(e)})),f.size()>a.untreeifyThreshold?e[o]=new s.default(f):f.size()&&(e[o]=f),p.size()>a.untreeifyThreshold?e[o+t]=new s.default(p):p.size()&&(e[o+t]=p)}else{var v=new r.default,g=new r.default;n.forEach((function(e){0==(i(e.key)&t)?v.pushBack(e):g.pushBack(e)})),v.size()&&(e[o]=v),g.size()&&(e[o+t]=g)}h[o].clear()}})),h=e}}.call(this,d)}else this.eraseElementByKey(t)},this.getElementByKey=function(t){var e,n,r=i(t)&d-1;if(h[r]){if(h[r]instanceof s.default)return h[r].getElementByKey(t);try{for(var a=o(h[r]),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.key===t)return c.value}}catch(t){e={error:t}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}}},this.eraseElementByKey=function(t){var e,n,l=i(t)&d-1;if(h[l]){var u=h[l].size();if(h[l]instanceof s.default)h[l].eraseElementByKey(t),h[l].size()<=a.untreeifyThreshold&&(h[l]=new r.default(h[l]));else{var f=-1;try{for(var p=o(h[l]),v=p.next();!v.done;v=p.next())if(++f,v.value.key===t){h[l].eraseElementByPos(f);break}}catch(t){e={error:t}}finally{try{v&&!v.done&&(n=p.return)&&n.call(p)}finally{if(e)throw e.error}}}var g=h[l].size();c+=g-u}},this.find=function(t){var e,n,r=i(t)&d-1;if(!h[r])return!1;if(h[r]instanceof s.default)return h[r].find(t);try{for(var a=o(h[r]),l=a.next();!l.done;l=a.next())if(l.value.key===t)return!0}catch(t){e={error:t}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}return!1},this[Symbol.iterator]=function(){return function(){var t,e,i,r,s,a;return n(this,(function(n){switch(n.label){case 0:t=0,n.label=1;case 1:if(!(t=d)return[3,10];n.label=2;case 2:n.trys.push([2,7,8,9]),s=void 0,e=o(h[t]),i=e.next(),n.label=3;case 3:return i.done?[3,6]:[4,i.value];case 4:n.sent(),n.label=5;case 5:return i=e.next(),[3,3];case 6:return[3,9];case 7:return r=n.sent(),s={error:r},[3,9];case 8:try{i&&!i.done&&(a=e.return)&&a.call(e)}finally{if(s)throw s.error}return[7];case 9:return++t,[3,1];case 10:return[2]}}))}()},t.forEach((function(t){var e=t.key,i=t.value;return l.setElement(e,i)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),i.default=a},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(t,e,i){"use strict";var n=this&&this.__generator||function(t,e){var i,n,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(o=2&r[0]?n.return:r[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,r[1])).done)return o;switch(n=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(i,"__esModule",{value:!0});var r=t("../Set/Set"),s=t("../LinkList/LinkList");function a(t,e,i){var l=this;if(void 0===t&&(t=[]),void 0===e&&(e=a.initSize),i=i||function(t){var e=0,i="";if("number"==typeof t)e=((e=Math.floor(t))<<5)-e,e&=e;else{i="string"!=typeof t?JSON.stringify(t):t;for(var n=0;n>>16},0!=(e&e-1))throw new Error("initBucketNum must be 2 to the power of n");var c=0,h=[],d=Math.max(a.initSize,Math.min(a.maxSize,e));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,d=e,h=[]},this.forEach=function(t){var e=0;h.forEach((function(i){i.forEach((function(i){t(i,e++)}))}))},this.insert=function(t){if(null==t)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var e=i(t)&d-1;if(h[e]){var n=h[e].size();if(h[e]instanceof s.default){if(h[e].find(t))return;h[e].pushBack(t),h[e].size()>=a.treeifyThreshold&&(h[e]=new r.default(h[e]))}else h[e].insert(t);var o=h[e].size();c+=o-n}else h[e]=new s.default([t]),++c;c>d*a.sigma&&function(t){if(!(t>=a.maxSize)){d=2*t;var e=[];h.forEach((function(n,o){if(!n.empty()){if(n instanceof s.default&&1===n.size()){var l=n.front();if(void 0===l)throw new Error("unknown error");e[i(l)&d-1]=new s.default([l])}else if(n instanceof r.default){var c=new s.default,u=new s.default;n.forEach((function(e){0==(i(e)&t)?c.pushBack(e):u.pushBack(e)})),c.size()>a.untreeifyThreshold?e[o]=new r.default(c):c.size()&&(e[o]=c),u.size()>a.untreeifyThreshold?e[o+t]=new r.default(u):u.size()&&(e[o+t]=u)}else{var f=new s.default,p=new s.default;n.forEach((function(e){0==(i(e)&t)?f.pushBack(e):p.pushBack(e)})),f.size()&&(e[o]=f),p.size()&&(e[o+t]=p)}h[o].clear()}})),h=e}}.call(this,d)},this.eraseElementByValue=function(t){var e=i(t)&d-1;if(h[e]){var n=h[e].size();h[e].eraseElementByValue(t),h[e]instanceof r.default&&h[e].size()<=a.untreeifyThreshold&&(h[e]=new s.default(h[e]));var o=h[e].size();c+=o-n}},this.find=function(t){var e=i(t)&d-1;return!!h[e]&&h[e].find(t)},this[Symbol.iterator]=function(){return function(){var t,e,i,r,s,a;return n(this,(function(n){switch(n.label){case 0:t=0,n.label=1;case 1:if(!(t=d)return[3,10];n.label=2;case 2:n.trys.push([2,7,8,9]),s=void 0,e=o(h[t]),i=e.next(),n.label=3;case 3:return i.done?[3,6]:[4,i.value];case 4:n.sent(),n.label=5;case 5:return i=e.next(),[3,3];case 6:return[3,9];case 7:return r=n.sent(),s={error:r},[3,9];case 8:try{i&&!i.done&&(a=e.return)&&a.call(e)}finally{if(s)throw s.error}return[7];case 9:return++t,[3,1];case 10:return[2]}}))}()},t.forEach((function(t){return l.insert(t)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),i.default=a},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(t,e,i){"use strict";var n=this&&this.__generator||function(t,e){var i,n,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(o=2&r[0]?n.return:r[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,r[1])).done)return o;switch(n=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=i)throw new Error("pos must more then 0 and less then the list length");for(var e=r;t--&&e;)e=e.next;if(!e||void 0===e.value)throw new Error("unknown error");return e.value},this.eraseElementByPos=function(t){if(t<0||t>=i)throw new Error("erase pos must more then 0 and less then the list length");if(0===t)this.popFront();else if(t===i-1)this.popBack();else{for(var e=r;t--;){if(!(null==e?void 0:e.next))throw new Error("unknown error");e=e.next}if(!e||!e.pre||!e.next)throw new Error("unknown error");var n=e.pre,o=e.next;o.pre=n,n.next=o,i>0&&--i}},this.eraseElementByValue=function(t){for(;r&&r.value===t;)this.popFront();for(;s&&s.value===t;)this.popBack();if(r)for(var e=r;e;){if(e.value===t){var n=e.pre,o=e.next;o&&(o.pre=n),n&&(n.next=o),i>0&&--i}e=e.next}},this.pushBack=function(t){if(null==t)throw new Error("you can't push null or undefined here");++i;var e=new o(t);s?(s.next=e,e.pre=s,s=e):r=s=e},this.popBack=function(){s&&(i>0&&--i,s&&(r===s?r=s=void 0:(s=s.pre)&&(s.next=void 0)))},this.setElementByPos=function(t,e){if(null==e)throw new Error("you can't set null or undefined here");if(t<0||t>=i)throw new Error("pos must more then 0 and less then the list length");for(var n=r;t--;){if(!n)throw new Error("unknown error");n=n.next}n&&(n.value=e)},this.insert=function(t,e,n){if(void 0===n&&(n=1),null==e)throw new Error("you can't insert null or undefined here");if(t<0||t>i)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(n<0)throw new Error("insert size must more than 0");if(0===t)for(;n--;)this.pushFront(e);else if(t===i)for(;n--;)this.pushBack(e);else{for(var s=r,a=1;a0&&--i;t.next=e.next,t.next&&(t.next.pre=t),t=t.next}},this.sort=function(t){var e=[];this.forEach((function(t){e.push(t)})),e.sort(t);var i=r;e.forEach((function(t){i&&(i.value=t,i=i.next)}))},this.pushFront=function(t){if(null==t)throw new Error("you can't push null or undefined here");++i;var e=new o(t);r?(e.next=r,r.pre=e,r=e):r=s=e},this.popFront=function(){r&&(i>0&&--i,r&&(r===s?r=s=void 0:(r=r.next)&&(r.pre=void 0)))},this.merge=function(t){var e=this,n=r;t.forEach((function(t){for(;n&&void 0!==n.value&&n.value<=t;)n=n.next;if(void 0===n)e.pushBack(t),n=s;else if(n===r)e.pushFront(t),n=r;else{++i;var a=n.pre;a&&(a.next=new o(t),a.next.pre=a,a.next.next=n,n&&(n.pre=a.next))}}))},this[Symbol.iterator]=function(){return function(){var t;return n(this,(function(e){switch(e.label){case 0:t=r,e.label=1;case 1:if(void 0===t)return[3,3];if(!t.value)throw new Error("unknown error");return[4,t.value];case 2:return e.sent(),t=t.next,[3,1];case 3:return[2]}}))}()},t.forEach((function(t){return e.pushBack(t)})),Object.freeze(this)}Object.freeze(r),i.default=r},{}],30:[function(t,e,i){"use strict";var n=this&&this.__generator||function(t,e){var i,n,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(o=2&r[0]?n.return:r[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,r[1])).done)return o;switch(n=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(i,"__esModule",{value:!0});var r=t("../Base/TreeNode");function s(t,e){var i=this;void 0===t&&(t=[]),e=e||function(t,e){return te?1:0};var s=0,a=new r.default;a.color=r.default.TreeNodeColorType.black,this.size=function(){return s},this.empty=function(){return 0===s},this.clear=function(){s=0,a.key=a.value=void 0,a.leftChild=a.rightChild=a.brother=void 0};var l=function(t){if(!t||void 0===t.key)throw new Error("unknown error");return t.leftChild?l(t.leftChild):t},c=function(t){if(!t||void 0===t.key)throw new Error("unknown error");return t.rightChild?c(t.rightChild):t};this.front=function(){if(!this.empty()){var t=l(a);if(void 0===t.key||void 0===t.value)throw new Error("unknown error");return{key:t.key,value:t.value}}},this.back=function(){if(!this.empty()){var t=c(a);if(void 0===t.key||void 0===t.value)throw new Error("unknown error");return{key:t.key,value:t.value}}},this.forEach=function(t){var e,i,n=0;try{for(var r=o(this),s=r.next();!s.done;s=r.next())t(s.value,n++)}catch(t){e={error:t}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(e)throw e.error}}},this.getElementByPos=function(t){var e,i;if(t<0||t>=this.size())throw new Error("pos must more than 0 and less than set's size");var n=0;try{for(var r=o(this),s=r.next();!s.done;s=r.next()){var a=s.value;if(n===t)return a;++n}}catch(t){e={error:t}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(e)throw e.error}}throw new Error("unknown Error")};var h=function(t,i){if(t&&void 0!==t.key&&void 0!==t.value){var n=e(t.key,i);return 0===n?{key:t.key,value:t.value}:n<0?h(t.rightChild,i):h(t.leftChild,i)||{key:t.key,value:t.value}}};this.lowerBound=function(t){return h(a,t)};var d=function(t,i){if(t&&void 0!==t.key&&void 0!==t.value)return e(t.key,i)<=0?d(t.rightChild,i):d(t.leftChild,i)||{key:t.key,value:t.value}};this.upperBound=function(t){return d(a,t)};var u=function(t,i){if(t&&void 0!==t.key&&void 0!==t.value){var n=e(t.key,i);return 0===n?{key:t.key,value:t.value}:n>0?u(t.leftChild,i):u(t.rightChild,i)||{key:t.key,value:t.value}}};this.reverseLowerBound=function(t){return u(a,t)};var f=function(t,i){if(t&&void 0!==t.key&&void 0!==t.value)return e(t.key,i)>=0?f(t.leftChild,i):f(t.rightChild,i)||{key:t.key,value:t.value}};this.reverseUpperBound=function(t){return f(a,t)};var p=function(t){var e=t.parent;if(!e){if(t===a)return;throw new Error("unknown error")}if(t.color!==r.default.TreeNodeColorType.red){var i=t.brother;if(!i)throw new Error("unknown error");if(t===e.leftChild)if(i.color===r.default.TreeNodeColorType.red){i.color=r.default.TreeNodeColorType.black,e.color=r.default.TreeNodeColorType.red;var n=e.rotateLeft();a===e&&(a=n),p(t)}else i.color===r.default.TreeNodeColorType.black&&(i.rightChild&&i.rightChild.color===r.default.TreeNodeColorType.red?(i.color=e.color,e.color=r.default.TreeNodeColorType.black,i.rightChild&&(i.rightChild.color=r.default.TreeNodeColorType.black),n=e.rotateLeft(),a===e&&(a=n),t.color=r.default.TreeNodeColorType.black):i.rightChild&&i.rightChild.color!==r.default.TreeNodeColorType.black||!i.leftChild||i.leftChild.color!==r.default.TreeNodeColorType.red?i.leftChild&&i.leftChild.color!==r.default.TreeNodeColorType.black||i.rightChild&&i.rightChild.color!==r.default.TreeNodeColorType.black||(i.color=r.default.TreeNodeColorType.red,p(e)):(i.color=r.default.TreeNodeColorType.red,i.leftChild&&(i.leftChild.color=r.default.TreeNodeColorType.black),n=i.rotateRight(),a===i&&(a=n),p(t)));else t===e.rightChild&&(i.color===r.default.TreeNodeColorType.red?(i.color=r.default.TreeNodeColorType.black,e.color=r.default.TreeNodeColorType.red,n=e.rotateRight(),a===e&&(a=n),p(t)):i.color===r.default.TreeNodeColorType.black&&(i.leftChild&&i.leftChild.color===r.default.TreeNodeColorType.red?(i.color=e.color,e.color=r.default.TreeNodeColorType.black,i.leftChild&&(i.leftChild.color=r.default.TreeNodeColorType.black),n=e.rotateRight(),a===e&&(a=n),t.color=r.default.TreeNodeColorType.black):i.leftChild&&i.leftChild.color!==r.default.TreeNodeColorType.black||!i.rightChild||i.rightChild.color!==r.default.TreeNodeColorType.red?i.leftChild&&i.leftChild.color!==r.default.TreeNodeColorType.black||i.rightChild&&i.rightChild.color!==r.default.TreeNodeColorType.black||(i.color=r.default.TreeNodeColorType.red,p(e)):(i.color=r.default.TreeNodeColorType.red,i.rightChild&&(i.rightChild.color=r.default.TreeNodeColorType.black),n=i.rotateLeft(),a===i&&(a=n),p(t))))}else t.color=r.default.TreeNodeColorType.black},v=function(t){for(var e=t;e.leftChild||e.rightChild;){if(e.rightChild){e=l(e.rightChild);var i=t.key;t.key=e.key,e.key=i;var n=t.value;t.value=e.value,e.value=n,t=e}e.leftChild&&(e=c(e.leftChild),i=t.key,t.key=e.key,e.key=i,n=t.value,t.value=e.value,e.value=n,t=e)}p(e),e&&e.remove(),--s,a.color=r.default.TreeNodeColorType.black},g=function(t,e){return!(!t||void 0===t.key)&&(!!g(t.leftChild,e)||!!e(t)||g(t.rightChild,e))};this.eraseElementByPos=function(t){if(t<0||t>=s)throw new Error("pos must more than 0 and less than set's size");var e=0;g(a,(function(i){return t===e?(v(i),!0):(++e,!1)}))},this.eraseElementByKey=function(t){if(!this.empty()){var i=w(a,t);void 0!==i&&void 0!==i.key&&0===e(i.key,t)&&v(i)}};var y=function(t,i){if(!t||void 0===t.key)throw new Error("unknown error");var n=e(i,t.key);return n<0?t.leftChild?y(t.leftChild,i):(t.leftChild=new r.default,t.leftChild.parent=t,t.leftChild.brother=t.rightChild,t.rightChild&&(t.rightChild.brother=t.leftChild),t.leftChild):n>0?t.rightChild?y(t.rightChild,i):(t.rightChild=new r.default,t.rightChild.parent=t,t.rightChild.brother=t.leftChild,t.leftChild&&(t.leftChild.brother=t.rightChild),t.rightChild):t},m=function(t){var e=t.parent;if(!e){if(t===a)return;throw new Error("unknown error")}if(e.color!==r.default.TreeNodeColorType.black&&e.color===r.default.TreeNodeColorType.red){var i=e.brother,n=e.parent;if(!n)throw new Error("unknown error");if(i&&i.color===r.default.TreeNodeColorType.red)i.color=e.color=r.default.TreeNodeColorType.black,n.color=r.default.TreeNodeColorType.red,m(n);else if(!i||i.color===r.default.TreeNodeColorType.black)if(e===n.leftChild)if(t===e.leftChild){e.color=r.default.TreeNodeColorType.black,n.color=r.default.TreeNodeColorType.red;var o=n.rotateRight();n===a&&(a=o)}else t===e.rightChild&&(o=e.rotateLeft(),n===a&&(a=o),m(e));else e===n.rightChild&&(t===e.leftChild?(o=e.rotateRight(),n===a&&(a=o),m(e)):t===e.rightChild&&(e.color=r.default.TreeNodeColorType.black,n.color=r.default.TreeNodeColorType.red,o=n.rotateLeft(),n===a&&(a=o)))}};this.setElement=function(t,i){if(null==t)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=i){if(this.empty())return++s,a.key=t,a.value=i,void(a.color=r.default.TreeNodeColorType.black);var n=y(a,t);void 0===n.key||0!==e(n.key,t)?(++s,n.key=t,n.value=i,m(n),a.color=r.default.TreeNodeColorType.black):n.value=i}else this.eraseElementByKey(t)};var w=function(t,i){if(t&&void 0!==t.key){var n=e(i,t.key);return n<0?w(t.leftChild,i):n>0?w(t.rightChild,i):t}};this.find=function(t){return!!w(a,t)},this.getElementByKey=function(t){var e=w(a,t);if(void 0===(null==e?void 0:e.key)||void 0===(null==e?void 0:e.value))throw new Error("unknown error");return e.value},this.union=function(t){var e=this;t.forEach((function(t){var i=t.key,n=t.value;return e.setElement(i,n)}))},this.getHeight=function(){if(this.empty())return 0;var t=function(e){return e?Math.max(t(e.leftChild),t(e.rightChild))+1:1};return t(a)};var x=function(t){return n(this,(function(e){switch(e.label){case 0:return t&&void 0!==t.key&&void 0!==t.value?[5,o(x(t.leftChild))]:[2];case 1:return e.sent(),[4,{key:t.key,value:t.value}];case 2:return e.sent(),[5,o(x(t.rightChild))];case 3:return e.sent(),[2]}}))};this[Symbol.iterator]=function(){return x(a)},t.forEach((function(t){var e=t.key,n=t.value;return i.setElement(e,n)})),Object.freeze(this)}Object.freeze(s),i.default=s},{"../Base/TreeNode":25}],31:[function(t,e,i){"use strict";function n(t,e){void 0===t&&(t=[]),e=e||function(t,e){return t>e?-1:t=n)throw new Error("unknown error");if(e<0||e>=n)throw new Error("unknown error");var o=i[t];i[t]=i[e],i[e]=o},r=function(t){if(t<0||t>=n)throw new Error("unknown error");var r=2*t+1,s=2*t+2;r0&&o(t,r),s0&&o(t,s)};!function(){for(var t=Math.floor((n-1)/2);t>=0;--t)for(var r=t,s=2*r+1;s0&&(l=a),e(i[r],i[l])<=0)break;o(r,l),s=2*(r=l)+1}}(),this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,i.length=0},this.push=function(t){if(i.push(t),1!=++n)for(var o=n-1;o>0;){var s=Math.floor((o-1)/2);if(e(i[s],t)<=0)break;r(s),o=s}},this.pop=function(){if(!this.empty())if(1!==this.size()){var t=i[n-1];--n;for(var o=0;o=this.size())break;var a=r;if(s0&&(a=s),e(i[a],t)>=0)break;i[o]=i[a],o=a}i[o]=t}else--n},this.top=function(){return i[0]},Object.freeze(this)}Object.defineProperty(i,"__esModule",{value:!0}),Object.freeze(n),i.default=n},{}],32:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=t("../LinkList/LinkList");function o(t){void 0===t&&(t=[]);var e=new n.default(t);this.size=function(){return e.size()},this.empty=function(){return e.empty()},this.clear=function(){e.clear()},this.push=function(t){e.pushBack(t)},this.pop=function(){e.popFront()},this.front=function(){return e.front()},Object.freeze(this)}Object.freeze(o),i.default=o},{"../LinkList/LinkList":29}],33:[function(t,e,i){"use strict";var n=this&&this.__generator||function(t,e){var i,n,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(o=2&r[0]?n.return:r[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,r[1])).done)return o;switch(n=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(i,"__esModule",{value:!0});var r=t("../Base/TreeNode");function s(t,e){var i=this;void 0===t&&(t=[]),e=e||function(t,e){return te?1:0};var s=0,a=new r.default;a.color=r.default.TreeNodeColorType.black,this.size=function(){return s},this.empty=function(){return 0===s},this.clear=function(){s=0,a.key=void 0,a.leftChild=a.rightChild=a.brother=a.parent=void 0,a.color=r.default.TreeNodeColorType.black};var l=function(t){if(!t||void 0===t.key)throw new Error("unknown error");return t.leftChild?l(t.leftChild):t},c=function(t){if(!t||void 0===t.key)throw new Error("unknown error");return t.rightChild?c(t.rightChild):t};this.front=function(){if(!this.empty())return l(a).key},this.back=function(){if(!this.empty())return c(a).key},this.forEach=function(t){var e,i,n=0;try{for(var r=o(this),s=r.next();!s.done;s=r.next())t(s.value,n++)}catch(t){e={error:t}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(e)throw e.error}}},this.getElementByPos=function(t){var e,i;if(t<0||t>=this.size())throw new Error("pos must more than 0 and less than set's size");var n=0;try{for(var r=o(this),s=r.next();!s.done;s=r.next()){var a=s.value;if(n===t)return a;++n}}catch(t){e={error:t}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(e)throw e.error}}throw new Error("unknown error")};var h=function(t){var e=t.parent;if(!e){if(t===a)return;throw new Error("unknown error")}if(t.color!==r.default.TreeNodeColorType.red){var i=t.brother;if(!i)throw new Error("unknown error");if(t===e.leftChild)if(i.color===r.default.TreeNodeColorType.red){i.color=r.default.TreeNodeColorType.black,e.color=r.default.TreeNodeColorType.red;var n=e.rotateLeft();a===e&&(a=n),h(t)}else i.color===r.default.TreeNodeColorType.black&&(i.rightChild&&i.rightChild.color===r.default.TreeNodeColorType.red?(i.color=e.color,e.color=r.default.TreeNodeColorType.black,i.rightChild&&(i.rightChild.color=r.default.TreeNodeColorType.black),n=e.rotateLeft(),a===e&&(a=n),t.color=r.default.TreeNodeColorType.black):i.rightChild&&i.rightChild.color!==r.default.TreeNodeColorType.black||!i.leftChild||i.leftChild.color!==r.default.TreeNodeColorType.red?i.leftChild&&i.leftChild.color!==r.default.TreeNodeColorType.black||i.rightChild&&i.rightChild.color!==r.default.TreeNodeColorType.black||(i.color=r.default.TreeNodeColorType.red,h(e)):(i.color=r.default.TreeNodeColorType.red,i.leftChild&&(i.leftChild.color=r.default.TreeNodeColorType.black),n=i.rotateRight(),a===i&&(a=n),h(t)));else t===e.rightChild&&(i.color===r.default.TreeNodeColorType.red?(i.color=r.default.TreeNodeColorType.black,e.color=r.default.TreeNodeColorType.red,n=e.rotateRight(),a===e&&(a=n),h(t)):i.color===r.default.TreeNodeColorType.black&&(i.leftChild&&i.leftChild.color===r.default.TreeNodeColorType.red?(i.color=e.color,e.color=r.default.TreeNodeColorType.black,i.leftChild&&(i.leftChild.color=r.default.TreeNodeColorType.black),n=e.rotateRight(),a===e&&(a=n),t.color=r.default.TreeNodeColorType.black):i.leftChild&&i.leftChild.color!==r.default.TreeNodeColorType.black||!i.rightChild||i.rightChild.color!==r.default.TreeNodeColorType.red?i.leftChild&&i.leftChild.color!==r.default.TreeNodeColorType.black||i.rightChild&&i.rightChild.color!==r.default.TreeNodeColorType.black||(i.color=r.default.TreeNodeColorType.red,h(e)):(i.color=r.default.TreeNodeColorType.red,i.rightChild&&(i.rightChild.color=r.default.TreeNodeColorType.black),n=i.rotateLeft(),a===i&&(a=n),h(t))))}else t.color=r.default.TreeNodeColorType.black},d=function(t){for(var e=t;e.leftChild||e.rightChild;){if(e.rightChild){e=l(e.rightChild);var i=t.key;t.key=e.key,e.key=i,t=e}e.leftChild&&(e=c(e.leftChild),i=t.key,t.key=e.key,e.key=i,t=e)}h(e),e&&e.remove(),--s,a.color=r.default.TreeNodeColorType.black},u=function(t,e){return!(!t||void 0===t.key)&&(!!u(t.leftChild,e)||!!e(t)||u(t.rightChild,e))};this.eraseElementByPos=function(t){if(t<0||t>=s)throw new Error("pos must more than 0 and less than set's size");var e=0;u(a,(function(i){return t===e?(d(i),!0):(++e,!1)}))},this.eraseElementByValue=function(t){if(!this.empty()){var i=v(a,t);void 0!==i&&void 0!==i.key&&0===e(i.key,t)&&d(i)}};var f=function(t,i){if(!t||void 0===t.key)throw new Error("unknown error");var n=e(i,t.key);return n<0?t.leftChild?f(t.leftChild,i):(t.leftChild=new r.default,t.leftChild.parent=t,t.leftChild.brother=t.rightChild,t.rightChild&&(t.rightChild.brother=t.leftChild),t.leftChild):n>0?t.rightChild?f(t.rightChild,i):(t.rightChild=new r.default,t.rightChild.parent=t,t.rightChild.brother=t.leftChild,t.leftChild&&(t.leftChild.brother=t.rightChild),t.rightChild):t},p=function(t){var e=t.parent;if(!e){if(t===a)return;throw new Error("unknown error")}if(e.color!==r.default.TreeNodeColorType.black&&e.color===r.default.TreeNodeColorType.red){var i=e.brother,n=e.parent;if(!n)throw new Error("unknown error");if(i&&i.color===r.default.TreeNodeColorType.red)i.color=e.color=r.default.TreeNodeColorType.black,n.color=r.default.TreeNodeColorType.red,p(n);else if(!i||i.color===r.default.TreeNodeColorType.black)if(e===n.leftChild)if(t===e.leftChild){e.color=r.default.TreeNodeColorType.black,n.color=r.default.TreeNodeColorType.red;var o=n.rotateRight();n===a&&(a=o)}else t===e.rightChild&&(o=e.rotateLeft(),n===a&&(a=o),p(e));else e===n.rightChild&&(t===e.leftChild?(o=e.rotateRight(),n===a&&(a=o),p(e)):t===e.rightChild&&(e.color=r.default.TreeNodeColorType.black,n.color=r.default.TreeNodeColorType.red,o=n.rotateLeft(),n===a&&(a=o)))}};this.insert=function(t){if(null==t)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++s,a.key=t,void(a.color=r.default.TreeNodeColorType.black);var i=f(a,t);void 0!==i.key&&0===e(i.key,t)||(++s,i.key=t,p(i),a.color=r.default.TreeNodeColorType.black)};var v=function(t,i){if(t&&void 0!==t.key){var n=e(i,t.key);return n<0?v(t.leftChild,i):n>0?v(t.rightChild,i):t}};this.find=function(t){var i=v(a,t);return void 0!==i&&void 0!==i.key&&0===e(i.key,t)};var g=function(t,i){if(t&&void 0!==t.key){var n=e(t.key,i);if(0===n)return t.key;if(n<0)return g(t.rightChild,i);var o=g(t.leftChild,i);return void 0!==o?o:t.key}};this.lowerBound=function(t){return g(a,t)};var y=function(t,i){if(t&&void 0!==t.key){if(e(t.key,i)<=0)return y(t.rightChild,i);var n=y(t.leftChild,i);return void 0!==n?n:t.key}};this.upperBound=function(t){return y(a,t)};var m=function(t,i){if(t&&void 0!==t.key){var n=e(t.key,i);if(0===n)return t.key;if(n>0)return m(t.leftChild,i);var o=m(t.rightChild,i);return void 0!==o?o:t.key}};this.reverseLowerBound=function(t){return m(a,t)};var w=function(t,i){if(t&&void 0!==t.key){if(e(t.key,i)>=0)return w(t.leftChild,i);var n=w(t.rightChild,i);return void 0!==n?n:t.key}};this.reverseUpperBound=function(t){return w(a,t)},this.union=function(t){var e=this;t.forEach((function(t){return e.insert(t)}))},this.getHeight=function(){if(this.empty())return 0;var t=function(e){return e?Math.max(t(e.leftChild),t(e.rightChild))+1:1};return t(a)};var x=function(t){return n(this,(function(e){switch(e.label){case 0:return t&&void 0!==t.key?[5,o(x(t.leftChild))]:[2];case 1:return e.sent(),[4,t.key];case 2:return e.sent(),[5,o(x(t.rightChild))];case 3:return e.sent(),[2]}}))};this[Symbol.iterator]=function(){return x(a)},t.forEach((function(t){return i.insert(t)})),Object.freeze(this)}Object.freeze(s),i.default=s},{"../Base/TreeNode":25}],34:[function(t,e,i){"use strict";function n(t){var e=this;void 0===t&&(t=[]);var i=0,n=[];this.size=function(){return i},this.empty=function(){return 0===i},this.clear=function(){i=0,n.length=0},this.push=function(t){n.push(t),++i},this.pop=function(){n.pop(),i>0&&--i},this.top=function(){return n[i-1]},t.forEach((function(t){return e.push(t)})),Object.freeze(this)}Object.defineProperty(i,"__esModule",{value:!0}),Object.freeze(n),i.default=n},{}],35:[function(t,e,i){"use strict";var n=this&&this.__generator||function(t,e){var i,n,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(o=2&r[0]?n.return:r[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,r[1])).done)return o;switch(n=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,n=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]0)&&!(n=r.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return s},r=this&&this.__spreadArray||function(t,e,i){if(i||2===arguments.length)for(var n,o=0,r=e.length;o=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function a(t){var e=this;void 0===t&&(t=[]);var i=0,a=[];this.size=function(){return i},this.empty=function(){return 0===i},this.clear=function(){i=0,a.length=0},this.front=function(){if(!this.empty())return a[0]},this.back=function(){if(!this.empty())return a[i-1]},this.forEach=function(t){a.forEach(t)},this.getElementByPos=function(t){if(t<0||t>=i)throw new Error("pos must more than 0 and less than vector's size");return a[t]},this.eraseElementByPos=function(t){if(t<0||t>=i)throw new Error("pos must more than 0 and less than vector's size");for(var e=t;en;)this.popBack()},this.pushBack=function(t){a.push(t),++i},this.popBack=function(){a.pop(),i>0&&--i},this.setElementByPos=function(t,e){if(t<0||t>=i)throw new Error("pos must more than 0 and less than vector's size");a[t]=e},this.insert=function(t,e,n){if(void 0===n&&(n=1),t<0||t>i)throw new Error("pos must more than 0 and less than or equal to vector's size");a.splice.apply(a,r([t,0],o(new Array(n).fill(e)),!1)),i+=n},this.find=function(t){return a.includes(t)},this.reverse=function(){a.reverse()},this.unique=function(){var t,e=[];this.forEach((function(i,n){0!==n&&i===t||(e.push(i),t=i)})),e.forEach((function(t,e){a[e]=t}));for(var n=e.length;i>n;)this.popBack()},this.sort=function(t){a.sort(t)},this[Symbol.iterator]=function(){return function(){return n(this,(function(t){switch(t.label){case 0:return[5,s(a)];case 1:return[2,t.sent()]}}))}()},t.forEach((function(t){return e.pushBack(t)})),Object.freeze(this)}Object.defineProperty(i,"__esModule",{value:!0}),Object.freeze(a),i.default=a},{}],36:[function(t,e,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.HashMap=i.HashSet=i.Map=i.Set=i.PriorityQueue=i.Deque=i.LinkList=i.Queue=i.Stack=i.Vector=void 0;var n=t("./Vector/Vector");i.Vector=n.default;var o=t("./Stack/Stack");i.Stack=o.default;var r=t("./Queue/Queue");i.Queue=r.default;var s=t("./LinkList/LinkList");i.LinkList=s.default;var a=t("./Deque/Deque");i.Deque=a.default;var l=t("./PriorityQueue/PriorityQueue");i.PriorityQueue=l.default;var c=t("./Set/Set");i.Set=c.default;var h=t("./Map/Map");i.Map=h.default;var d=t("./HashSet/HashSet");i.HashSet=d.default;var u=t("./HashMap/HashMap");i.HashMap=u.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(t,e,i){"use strict";const n=t("yallist"),o=Symbol("max"),r=Symbol("length"),s=Symbol("lengthCalculator"),a=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),h=Symbol("noDisposeOnSet"),d=Symbol("lruList"),u=Symbol("cache"),f=Symbol("updateAgeOnGet"),p=()=>1,v=(t,e,i)=>{const n=t[u].get(e);if(n){const e=n.value;if(g(t,e)){if(m(t,n),!t[a])return}else i&&(t[f]&&(n.value.now=Date.now()),t[d].unshiftNode(n));return e.value}},g=(t,e)=>{if(!e||!e.maxAge&&!t[l])return!1;const i=Date.now()-e.now;return e.maxAge?i>e.maxAge:t[l]&&i>t[l]},y=t=>{if(t[r]>t[o])for(let e=t[d].tail;t[r]>t[o]&&null!==e;){const i=e.prev;m(t,e),e=i}},m=(t,e)=>{if(e){const i=e.value;t[c]&&t[c](i.key,i.value),t[r]-=i.length,t[u].delete(i.key),t[d].removeNode(e)}};class w{constructor(t,e,i,n,o){this.key=t,this.value=e,this.length=i,this.now=n,this.maxAge=o||0}}const x=(t,e,i,n)=>{let o=i.value;g(t,o)&&(m(t,i),t[a]||(o=void 0)),o&&e.call(n,o.value,o.key,t)};e.exports=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[o]=t.max||1/0;const e=t.length||p;if(this[s]="function"!=typeof e?p:e,this[a]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[l]=t.maxAge||0,this[c]=t.dispose,this[h]=t.noDisposeOnSet||!1,this[f]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[o]=t||1/0,y(this)}get max(){return this[o]}set allowStale(t){this[a]=!!t}get allowStale(){return this[a]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[l]=t,y(this)}get maxAge(){return this[l]}set lengthCalculator(t){"function"!=typeof t&&(t=p),t!==this[s]&&(this[s]=t,this[r]=0,this[d].forEach((t=>{t.length=this[s](t.value,t.key),this[r]+=t.length}))),y(this)}get lengthCalculator(){return this[s]}get length(){return this[r]}get itemCount(){return this[d].length}rforEach(t,e){e=e||this;for(let i=this[d].tail;null!==i;){const n=i.prev;x(this,t,i,e),i=n}}forEach(t,e){e=e||this;for(let i=this[d].head;null!==i;){const n=i.next;x(this,t,i,e),i=n}}keys(){return this[d].toArray().map((t=>t.key))}values(){return this[d].toArray().map((t=>t.value))}reset(){this[c]&&this[d]&&this[d].length&&this[d].forEach((t=>this[c](t.key,t.value))),this[u]=new Map,this[d]=new n,this[r]=0}dump(){return this[d].map((t=>!g(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[d]}set(t,e,i){if((i=i||this[l])&&"number"!=typeof i)throw new TypeError("maxAge must be a number");const n=i?Date.now():0,a=this[s](e,t);if(this[u].has(t)){if(a>this[o])return m(this,this[u].get(t)),!1;const s=this[u].get(t).value;return this[c]&&(this[h]||this[c](t,s.value)),s.now=n,s.maxAge=i,s.value=e,this[r]+=a-s.length,s.length=a,this.get(t),y(this),!0}const f=new w(t,e,a,n,i);return f.length>this[o]?(this[c]&&this[c](t,e),!1):(this[r]+=f.length,this[d].unshift(f),this[u].set(t,this[d].head),y(this),!0)}has(t){if(!this[u].has(t))return!1;const e=this[u].get(t).value;return!g(this,e)}get(t){return v(this,t,!0)}peek(t){return v(this,t,!1)}pop(){const t=this[d].tail;return t?(m(this,t),t.value):null}del(t){m(this,this[u].get(t))}load(t){this.reset();const e=Date.now();for(let i=t.length-1;i>=0;i--){const n=t[i],o=n.e||0;if(0===o)this.set(n.k,n.v);else{const t=o-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[u].forEach(((t,e)=>v(this,e,!1)))}}},{yallist:83}],38:[function(t,e,i){(function(t){(function(){const i=e.exports;i.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},i.codes={};for(const t in i.types){const e=i.types[t];i.codes[e]=t}i.CMD_SHIFT=4,i.CMD_MASK=240,i.DUP_MASK=8,i.QOS_MASK=3,i.QOS_SHIFT=1,i.RETAIN_MASK=1,i.VARBYTEINT_MASK=127,i.VARBYTEINT_FIN_MASK=128,i.VARBYTEINT_MAX=268435455,i.SESSIONPRESENT_MASK=1,i.SESSIONPRESENT_HEADER=t.from([i.SESSIONPRESENT_MASK]),i.CONNACK_HEADER=t.from([i.codes.connack<[0,1].map((o=>[0,1].map((r=>{const s=t.alloc(1);return s.writeUInt8(i.codes[e]<t.from([e]))),i.EMPTY={pingreq:t.from([i.codes.pingreq<<4,0]),pingresp:t.from([i.codes.pingresp<<4,0]),disconnect:t.from([i.codes.disconnect<<4,0])}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],39:[function(t,e,i){(function(i){(function(){const n=t("./writeToStream"),o=t("events");class r extends o{constructor(){super(),this._array=new Array(20),this._i=0}write(t){return this._array[this._i++]=t,!0}concat(){let t=0;const e=new Array(this._array.length),n=this._array;let o,r=0;for(o=0;o>8,0),i.writeUInt8(255&e,1),i}e.exports={cache:i,generateCache:function(){for(let t=0;t<65536;t++)i[t]=o(t)},generateNumber:o,genBufVariableByteInt:function(e){let i=0,o=0;const r=t.allocUnsafe(4);do{i=e%128|0,(e=e/128|0)>0&&(i|=128),r.writeUInt8(i,o++)}while(e>0&&o<4);return e>0&&(o=0),n?r.subarray(0,o):r.slice(0,o)},generate4ByteBuffer:function(e){const i=t.allocUnsafe(4);return i.writeUInt32BE(e,0),i}}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],42:[function(t,e,i){e.exports=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}},{}],43:[function(t,e,i){const n=t("bl"),o=t("events"),r=t("./packet"),s=t("./constants"),a=t("debug")("mqtt-packet:parser");class l extends o{constructor(){super(),this.parser=this.constructor.parser}static parser(t){return this instanceof l?(this.settings=t||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new l).parser(t)}_resetState(){a("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new r,this.error=null,this._list=n(),this._stateCounter=0}parse(t){for(this.error&&this._resetState(),this._list.append(t),a("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,a("parse: state complete. _stateCounter is now: %d",this._stateCounter),a("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return a("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const t=this._list.readUInt8(0);return this.packet.cmd=s.types[t>>s.CMD_SHIFT],this.packet.retain=0!=(t&s.RETAIN_MASK),this.packet.qos=t>>s.QOS_SHIFT&s.QOS_MASK,this.packet.dup=0!=(t&s.DUP_MASK),a("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const t=this._parseVarByteNum(!0);return t&&(this.packet.length=t.value,this._list.consume(t.bytes)),a("_parseLength %d",t.value),!!t}_parsePayload(){a("_parsePayload: payload %O",this._list);let t=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}t=!0}return a("_parsePayload complete result: %s",t),t}_parseConnect(){let t,e,i,n;a("_parseConnect");const o={},r=this.packet,l=this._parseString();if(null===l)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==l&&"MQIsdp"!==l)return this._emitError(new Error("Invalid protocolId"));if(r.protocolId=l,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(r.protocolVersion=this._list.readUInt8(this._pos),r.protocolVersion>=128&&(r.bridgeMode=!0,r.protocolVersion=r.protocolVersion-128),3!==r.protocolVersion&&4!==r.protocolVersion&&5!==r.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.username=this._list.readUInt8(this._pos)&s.USERNAME_MASK,o.password=this._list.readUInt8(this._pos)&s.PASSWORD_MASK,o.will=this._list.readUInt8(this._pos)&s.WILL_FLAG_MASK,o.will&&(r.will={},r.will.retain=0!=(this._list.readUInt8(this._pos)&s.WILL_RETAIN_MASK),r.will.qos=(this._list.readUInt8(this._pos)&s.WILL_QOS_MASK)>>s.WILL_QOS_SHIFT),r.clean=0!=(this._list.readUInt8(this._pos)&s.CLEAN_SESSION_MASK),this._pos++,r.keepalive=this._parseNum(),-1===r.keepalive)return this._emitError(new Error("Packet too short"));if(5===r.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(r.properties=t)}const c=this._parseString();if(null===c)return this._emitError(new Error("Packet too short"));if(r.clientId=c,a("_parseConnect: packet.clientId: %s",r.clientId),o.will){if(5===r.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(r.will.properties=t)}if(null===(t=this._parseString()))return this._emitError(new Error("Cannot parse will topic"));if(r.will.topic=t,a("_parseConnect: packet.will.topic: %s",r.will.topic),null===(e=this._parseBuffer()))return this._emitError(new Error("Cannot parse will payload"));r.will.payload=e,a("_parseConnect: packet.will.paylaod: %s",r.will.payload)}if(o.username){if(null===(n=this._parseString()))return this._emitError(new Error("Cannot parse username"));r.username=n,a("_parseConnect: packet.username: %s",r.username)}if(o.password){if(null===(i=this._parseBuffer()))return this._emitError(new Error("Cannot parse password"));r.password=i}return this.settings=r,a("_parseConnect: complete"),r}_parseConnack(){a("_parseConnack");const t=this.packet;if(this._list.length<1)return null;if(t.sessionPresent=!!(this._list.readUInt8(this._pos++)&s.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?t.reasonCode=this._list.readUInt8(this._pos++):t.reasonCode=0;else{if(this._list.length<2)return null;t.returnCode=this._list.readUInt8(this._pos++)}if(-1===t.returnCode||-1===t.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(t.properties=e)}a("_parseConnack: complete")}_parsePublish(){a("_parsePublish");const t=this.packet;if(t.topic=this._parseString(),null===t.topic)return this._emitError(new Error("Cannot parse topic"));if(!(t.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(t.properties=e)}t.payload=this._list.slice(this._pos,t.length),a("_parsePublish: payload from buffer list: %o",t.payload)}}_parseSubscribe(){a("_parseSubscribe");const t=this.packet;let e,i,n,o,r,l,c;if(1!==t.qos)return this._emitError(new Error("Wrong subscribe header"));if(t.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(t.properties=e)}for(;this._pos=t.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=(i=this._parseByte())&s.SUBSCRIBE_OPTIONS_QOS_MASK,l=0!=(i>>s.SUBSCRIBE_OPTIONS_NL_SHIFT&s.SUBSCRIBE_OPTIONS_NL_MASK),r=0!=(i>>s.SUBSCRIBE_OPTIONS_RAP_SHIFT&s.SUBSCRIBE_OPTIONS_RAP_MASK),o=i>>s.SUBSCRIBE_OPTIONS_RH_SHIFT&s.SUBSCRIBE_OPTIONS_RH_MASK,c={topic:e,qos:n},5===this.settings.protocolVersion?(c.nl=l,c.rap=r,c.rh=o):this.settings.bridgeMode&&(c.rh=0,c.rap=!0,c.nl=!0),a("_parseSubscribe: push subscription `%s` to subscription",c),t.subscriptions.push(c)}}}_parseSuback(){a("_parseSuback");const t=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(t.properties=e)}for(;this._pos2?(t.reasonCode=this._parseByte(),a("_parseConfirmation: packet.reasonCode `%d`",t.reasonCode)):t.reasonCode=0,t.length>3)){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(t.properties=e)}return!0}_parseDisconnect(){const t=this.packet;if(a("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?t.reasonCode=this._parseByte():t.reasonCode=0;const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(t.properties=e)}return a("_parseDisconnect result: true"),!0}_parseAuth(){a("_parseAuth");const t=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));t.reasonCode=this._parseByte();const e=this._parseProperties();return Object.getOwnPropertyNames(e).length&&(t.properties=e),a("_parseAuth: result: true"),!0}_parseMessageId(){const t=this.packet;return t.messageId=this._parseNum(),null===t.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(a("_parseMessageId: packet.messageId %d",t.messageId),!0)}_parseString(t){const e=this._parseNum(),i=e+this._pos;if(-1===e||i>this._list.length||i>this.packet.length)return null;const n=this._list.toString("utf8",this._pos,i);return this._pos+=e,a("_parseString: result: %s",n),n}_parseStringPair(){return a("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const t=this._parseNum(),e=t+this._pos;if(-1===t||e>this._list.length||e>this.packet.length)return null;const i=this._list.slice(this._pos,e);return this._pos+=t,a("_parseBuffer: result: %o",i),i}_parseNum(){if(this._list.length-this._pos<2)return-1;const t=this._list.readUInt16BE(this._pos);return this._pos+=2,a("_parseNum: result: %s",t),t}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const t=this._list.readUInt32BE(this._pos);return this._pos+=4,a("_parse4ByteNum: result: %s",t),t}_parseVarByteNum(t){a("_parseVarByteNum");let e,i=0,n=1,o=0,r=!1;const l=this._pos?this._pos:0;for(;i<4&&l+i=i&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=i),a("_parseVarByteNum: result: %o",r=!!r&&(t?{bytes:i,value:o}:o)),r}_parseByte(){let t;return this._pos=4)&&(d||c))g+=i.byteLength(d)+2;else{if(a<4)return e.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*c==0)return e.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof h||h<0||h>65535||h%1!=0)return e.emit("error",new Error("Invalid keepalive")),!1;if(g+=2,g+=1,5===a){var y=C(e,v);if(!y)return!1;g+=y.length}if(l){if("object"!=typeof l)return e.emit("error",new Error("Invalid will")),!1;if(!l.topic||"string"!=typeof l.topic)return e.emit("error",new Error("Invalid will topic")),!1;if(g+=i.byteLength(l.topic)+2,g+=2,l.payload){if(!(l.payload.length>=0))return e.emit("error",new Error("Invalid will payload")),!1;"string"==typeof l.payload?g+=i.byteLength(l.payload):g+=l.payload.length}var m={};if(5===a){if(!(m=C(e,l.properties)))return!1;g+=m.length}}let b=!1;if(null!=u){if(!I(u))return e.emit("error",new Error("Invalid username")),!1;b=!0,g+=i.byteLength(u)+2}if(null!=f){if(!b)return e.emit("error",new Error("Username is required to use password")),!1;if(!I(f))return e.emit("error",new Error("Invalid password")),!1;g+=E(f)+2}e.write(n.CONNECT_HEADER),w(e,g),A(e,s),r.bridgeMode&&(a+=128),e.write(131===a?n.VERSION131:132===a?n.VERSION132:4===a?n.VERSION4:5===a?n.VERSION5:n.VERSION3);let k=0;return k|=null!=u?n.USERNAME_MASK:0,k|=null!=f?n.PASSWORD_MASK:0,k|=l&&l.retain?n.WILL_RETAIN_MASK:0,k|=l&&l.qos?l.qos<0&&p(e,f),null!=y&&y.write(),l("publish: payload: %o",u),e.write(u)}(t,e,s);case"puback":case"pubrec":case"pubrel":case"pubcomp":return function(t,e,o){const r=o?o.protocolVersion:4,s=t||{},a=s.cmd||"puback",l=s.messageId,c=s.dup&&"pubrel"===a?n.DUP_MASK:0;let h=0;const d=s.reasonCode,u=s.properties;let f=5===r?3:2;if("pubrel"===a&&(h=1),"number"!=typeof l)return e.emit("error",new Error("Invalid messageId")),!1;let v=null;if(5===r&&"object"==typeof u){if(!(v=R(e,u,o,f)))return!1;f+=v.length}return e.write(n.ACKS[a][h][c][0]),w(e,f),p(e,l),5===r&&e.write(i.from([d])),null!==v&&v.write(),!0}(t,e,s);case"subscribe":return function(t,e,o){l("subscribe: packet: ");const r=o?o.protocolVersion:4,s=t||{},a=s.dup?n.DUP_MASK:0,c=s.messageId,h=s.subscriptions,d=s.properties;let u=0;if("number"!=typeof c)return e.emit("error",new Error("Invalid messageId")),!1;u+=2;let f=null;if(5===r){if(!(f=C(e,d)))return!1;u+=f.length}if("object"!=typeof h||!h.length)return e.emit("error",new Error("Invalid subscriptions")),!1;for(let t=0;t2)return e.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}u+=i.byteLength(n)+2+1}l("subscribe: writing to stream: %o",n.SUBSCRIBE_HEADER),e.write(n.SUBSCRIBE_HEADER[1][a?1:0][0]),w(e,u),p(e,c),null!==f&&f.write();let v=!0;for(const t of h){const o=t.topic,s=t.qos,a=+t.nl,l=+t.rap,c=t.rh;let h;x(e,o),h=n.SUBSCRIBE_OPTIONS_QOS[s],5===r&&(h|=a?n.SUBSCRIBE_OPTIONS_NL:0,h|=l?n.SUBSCRIBE_OPTIONS_RAP:0,h|=c?n.SUBSCRIBE_OPTIONS_RH[c]:0),v=e.write(i.from([h]))}return v}(t,e,s);case"suback":return function(t,e,o){const r=o?o.protocolVersion:4,s=t||{},a=s.messageId,l=s.granted,c=s.properties;let h=0;if("number"!=typeof a)return e.emit("error",new Error("Invalid messageId")),!1;if(h+=2,"object"!=typeof l||!l.length)return e.emit("error",new Error("Invalid qos vector")),!1;for(let t=0;tp===k,set(t){t?(c&&0!==Object.keys(c).length||(v=!0),p=k):(v=!1,p=T)}});const m={};function w(t,e){if(e>n.VARBYTEINT_MAX)return t.emit("error",new Error(`Invalid variable byte integer: ${e}`)),!1;let i=m[e];return i||(i=u(e),e<16384&&(m[e]=i)),l("writeVarByteInt: writing to stream: %o",i),t.write(i)}function x(t,e){const n=i.byteLength(e);return p(t,n),l("writeString: %s",e),t.write(e,"utf8")}function b(t,e,i){x(t,e),x(t,i)}function k(t,e){return l("writeNumberCached: number: %d",e),l("writeNumberCached: %o",c[e]),t.write(c[e])}function T(t,e){const i=h(e);return l("writeNumberGenerated: %o",i),t.write(i)}function A(t,e){"string"==typeof e?x(t,e):e?(p(t,e.length),t.write(e)):p(t,0)}function C(t,e){if("object"!=typeof e||null!=e.length)return{length:1,write(){P(t,{},0)}};let o=0;function r(e,o){let r=0;switch(n.propertiesTypes[e]){case"byte":if("boolean"!=typeof o)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=2;break;case"int8":if("number"!=typeof o||o<0||o>255)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=2;break;case"binary":if(o&&null===o)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=1+i.byteLength(o)+2;break;case"int16":if("number"!=typeof o||o<0||o>65535)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=3;break;case"int32":if("number"!=typeof o||o<0||o>4294967295)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=5;break;case"var":if("number"!=typeof o||o<0||o>268435455)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=1+i.byteLength(u(o));break;case"string":if("string"!=typeof o)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=3+i.byteLength(o.toString());break;case"pair":if("object"!=typeof o)return t.emit("error",new Error(`Invalid ${e}: ${o}`)),!1;r+=Object.getOwnPropertyNames(o).reduce(((t,e)=>{const n=o[e];return Array.isArray(n)?t+=n.reduce(((t,n)=>t+(3+i.byteLength(e.toString())+2+i.byteLength(n.toString()))),0):t+=3+i.byteLength(e.toString())+2+i.byteLength(o[e].toString()),t}),0);break;default:return t.emit("error",new Error(`Invalid property ${e}: ${o}`)),!1}return r}if(e)for(const t in e){let i=0,n=0;const s=e[t];if(Array.isArray(s))for(let e=0;er;){const i=o.shift();if(!i||!e[i])return!1;delete e[i],s=C(t,e)}return s}function S(t,e,o){switch(n.propertiesTypes[e]){case"byte":t.write(i.from([n.properties[e]])),t.write(i.from([+o]));break;case"int8":t.write(i.from([n.properties[e]])),t.write(i.from([o]));break;case"binary":t.write(i.from([n.properties[e]])),A(t,o);break;case"int16":t.write(i.from([n.properties[e]])),p(t,o);break;case"int32":t.write(i.from([n.properties[e]])),function(t,e){const i=f(e);l("write4ByteNumber: %o",i),t.write(i)}(t,o);break;case"var":t.write(i.from([n.properties[e]])),w(t,o);break;case"string":t.write(i.from([n.properties[e]])),x(t,o);break;case"pair":Object.getOwnPropertyNames(o).forEach((r=>{const s=o[r];Array.isArray(s)?s.forEach((o=>{t.write(i.from([n.properties[e]])),b(t,r.toString(),o.toString())})):(t.write(i.from([n.properties[e]])),b(t,r.toString(),s.toString()))}));break;default:return t.emit("error",new Error(`Invalid property ${e} value: ${o}`)),!1}}function P(t,e,i){w(t,i);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&null!==e[i]){const n=e[i];if(Array.isArray(n))for(let e=0;e=1.5*i;return Math.round(t/i)+" "+n+(o?"s":"")}e.exports=function(t,e){e=e||{};var i=typeof t;if("string"===i&&t.length>0)return function(t){if(!((t=String(t)).length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var i=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*i;case"weeks":case"week":case"w":return 6048e5*i;case"days":case"day":case"d":return i*s;case"hours":case"hour":case"hrs":case"hr":case"h":return i*r;case"minutes":case"minute":case"mins":case"min":case"m":return i*o;case"seconds":case"second":case"secs":case"sec":case"s":return i*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}}}(t);if("number"===i&&isFinite(t))return e.long?function(t){var e=Math.abs(t);return e>=s?a(t,e,s,"day"):e>=r?a(t,e,r,"hour"):e>=o?a(t,e,o,"minute"):e>=n?a(t,e,n,"second"):t+" ms"}(t):function(t){var e=Math.abs(t);return e>=s?Math.round(t/s)+"d":e>=r?Math.round(t/r)+"h":e>=o?Math.round(t/o)+"m":e>=n?Math.round(t/n)+"s":t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},{}],46:[function(t,e,i){const n=t("./lib/number-allocator.js");e.exports.NumberAllocator=n},{"./lib/number-allocator.js":47}],47:[function(t,e,i){"use strict";const n=t("js-sdsl").Set,o=t("debug")("number-allocator:trace"),r=t("debug")("number-allocator:error");function s(t,e){this.low=t,this.high=e}function a(t,e){if(!(this instanceof a))return new a(t,e);this.min=t,this.max=e,this.ss=new n([],((t,e)=>t.compare(e))),o("Create"),this.clear()}s.prototype.equals=function(t){return this.low===t.low&&this.high===t.high},s.prototype.compare=function(t){return this.lowt)return!1;if(i.low===t)return++i.low,o("use():"+t),!0;if(i.high===t)return--i.high,o("use():"+t),!0;const n=i.low;return i.low=t+1,this.ss.insert(new s(n,t-1)),o("use():"+t),!0}return o("use():failed"),!1},a.prototype.free=function(t){if(tthis.max)return void r("free():"+t+" is out of range");const e=new s(t,t),i=this.ss.lowerBound(e);if(i){if(i.low<=t&&t<=i.high)return void r("free():"+t+" has already been vacant");if(i===this.ss.front())t+1===i.low?--i.low:this.ss.insert(e);else{const n=this.ss.reverseLowerBound(e);n.high+1===t?t+1===i.low?(this.ss.eraseElementByValue(n),i.low=n.low):n.high=t:t+1===i.low?i.low=t:this.ss.insert(e)}}else{if(i===this.ss.front())return void this.ss.insert(e);const n=this.ss.reverseLowerBound(e);n.high+1===t?n.high=t:this.ss.insert(e)}o("free():"+t)},a.prototype.clear=function(){o("clear()"),this.ss.clear(),this.ss.insert(new s(this.min,this.max))},a.prototype.intervalCount=function(){return this.ss.size()},a.prototype.dump=function(){console.log("length:"+this.ss.size());for(const t of this.ss)console.log(t)},e.exports=a},{debug:18,"js-sdsl":36}],48:[function(t,e,i){var n=t("wrappy");function o(t){var e=function(){return e.called?e.value:(e.called=!0,e.value=t.apply(this,arguments))};return e.called=!1,e}function r(t){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=t.apply(this,arguments)},i=t.name||"Function wrapped with `once`";return e.onceError=i+" shouldn't be called more than once",e.called=!1,e}e.exports=n(o),e.exports.strict=n(r),o.proto=o((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return o(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return r(this)},configurable:!0})}))},{wrappy:79}],49:[function(t,e,i){(function(t){(function(){"use strict";void 0===t||!t.version||0===t.version.indexOf("v0.")||0===t.version.indexOf("v1.")&&0!==t.version.indexOf("v1.8.")?e.exports={nextTick:function(e,i,n,o){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var r,s,a=arguments.length;switch(a){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick((function(){e.call(null,i)}));case 3:return t.nextTick((function(){e.call(null,i,n)}));case 4:return t.nextTick((function(){e.call(null,i,n,o)}));default:for(r=new Array(a-1),s=0;s1)for(var i=1;i= 0x80 (not a basic code point)","invalid-input":"Invalid input"},m=h-1,w=Math.floor,x=String.fromCharCode;function b(t){throw new RangeError(y[t])}function k(t,e){for(var i=t.length,n=[];i--;)n[i]=e(t[i]);return n}function T(t,e){var i=t.split("@"),n="";return i.length>1&&(n=i[0]+"@",t=i[1]),n+k((t=t.replace(g,".")).split("."),e).join(".")}function A(t){for(var e,i,n=[],o=0,r=t.length;o=55296&&e<=56319&&o65535&&(e+=x((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+x(t)})).join("")}function R(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function S(t,e,i){var n=0;for(t=i?w(t/f):t>>1,t+=w(t/e);t>m*d>>1;n+=h)t=w(t/m);return w(n+(m+1)*t/(t+u))}function P(t){var e,i,n,o,r,s,a,l,u,f,p,v=[],g=t.length,y=0,m=128,x=72;for((i=t.lastIndexOf("-"))<0&&(i=0),n=0;n=128&&b("not-basic"),v.push(t.charCodeAt(n));for(o=i>0?i+1:0;o=g&&b("invalid-input"),((l=(p=t.charCodeAt(o++))-48<10?p-22:p-65<26?p-65:p-97<26?p-97:h)>=h||l>w((c-y)/s))&&b("overflow"),y+=l*s,!(l<(u=a<=x?1:a>=x+d?d:a-x));a+=h)s>w(c/(f=h-u))&&b("overflow"),s*=f;x=S(y-r,e=v.length+1,0==r),w(y/e)>c-m&&b("overflow"),m+=w(y/e),y%=e,v.splice(y++,0,m)}return C(v)}function E(t){var e,i,n,o,r,s,a,l,u,f,p,v,g,y,m,k=[];for(v=(t=A(t)).length,e=128,i=0,r=72,s=0;s=e&&pw((c-i)/(g=n+1))&&b("overflow"),i+=(a-e)*g,e=a,s=0;sc&&b("overflow"),p==e){for(l=i,u=h;!(l<(f=u<=r?1:u>=r+d?d:u-r));u+=h)m=l-f,y=h-f,k.push(x(R(f+m%y,0))),l=w(m/y);k.push(x(R(l,0))),r=S(i,g,n==o),i=0,++n}++i,++e}return k.join("")}if(a={version:"1.4.1",ucs2:{decode:A,encode:C},decode:P,encode:E,toASCII:function(t){return T(t,(function(t){return v.test(t)?"xn--"+E(t):t}))},toUnicode:function(t){return T(t,(function(t){return p.test(t)?P(t.slice(4).toLowerCase()):t}))}},o&&r)if(e.exports==o)r.exports=a;else for(l in a)a.hasOwnProperty(l)&&(o[l]=a[l]);else i.punycode=a}(this)}).call(this)}).call(this,void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(t,e,i){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,i,r){e=e||"&",i=i||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var l=1e3;r&&"number"==typeof r.maxKeys&&(l=r.maxKeys);var c=t.length;l>0&&c>l&&(c=l);for(var h=0;h=0?(d=v.substr(0,g),u=v.substr(g+1)):(d=v,u=""),f=decodeURIComponent(d),p=decodeURIComponent(u),n(s,f)?o(s[f])?s[f].push(p):s[f]=[s[f],p]:s[f]=p}return s};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],53:[function(t,e,i){"use strict";var n=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};e.exports=function(t,e,i,a){return e=e||"&",i=i||"=",null===t&&(t=void 0),"object"==typeof t?r(s(t),(function(s){var a=encodeURIComponent(n(s))+i;return o(t[s])?r(t[s],(function(t){return a+encodeURIComponent(n(t))})).join(e):a+encodeURIComponent(n(t[s]))})).join(e):a?encodeURIComponent(n(a))+i+encodeURIComponent(n(t)):""};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)};function r(t,e){if(t.map)return t.map(e);for(var i=[],n=0;n2?"one of ".concat(e," ").concat(t.slice(0,i-1).join(", "),", or ")+t[i-1]:2===i?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}return"of ".concat(e," ").concat(String(t))}o("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),o("ERR_INVALID_ARG_TYPE",(function(t,e,i){var n,o,s;if("string"==typeof e&&(o="not ",e.substr(0,o.length)===o)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,i){return(void 0===i||i>t.length)&&(i=t.length),t.substring(i-e.length,i)===e}(t," argument"))s="The ".concat(t," ").concat(n," ").concat(r(e,"type"));else{var a=function(t,e,i){return"number"!=typeof i&&(i=0),!(i+".".length>t.length)&&-1!==t.indexOf(".",i)}(t)?"property":"argument";s='The "'.concat(t,'" ').concat(a," ").concat(n," ").concat(r(e,"type"))}return s+". Received type ".concat(typeof i)}),TypeError),o("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),o("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),o("ERR_STREAM_PREMATURE_CLOSE","Premature close"),o("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),o("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),o("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),o("ERR_STREAM_WRITE_AFTER_END","write after end"),o("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),o("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),o("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.codes=n},{}],56:[function(t,e,i){(function(i){(function(){"use strict";var n=Object.keys||function(t){var e=[];for(var i in t)e.push(i);return e};e.exports=c;var o=t("./_stream_readable"),r=t("./_stream_writable");t("inherits")(c,o);for(var s=n(r.prototype),a=0;a0)if("string"==typeof e||a.objectMode||Object.getPrototypeOf(e)===l.prototype||(e=function(t){return l.from(t)}(e)),n)a.endEmitted?k(t,new b):S(t,a,e,!0);else if(a.ended)k(t,new w);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!i?(e=a.decoder.write(e),a.objectMode||0!==e.length?S(t,a,e,!1):L(t,a)):S(t,a,e,!1)}else n||(a.reading=!1,L(t,a));return!a.ended&&(a.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=P?t=P:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function I(t){var e=t._readableState;r("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(r("emitReadable",e.flowing),e.emittedReadable=!0,i.nextTick(_,t))}function _(t){var e=t._readableState;r("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,B(t)}function L(t,e){e.readingMore||(e.readingMore=!0,i.nextTick(M,t,e))}function M(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function O(t){r("readable nexttick read 0"),t.read(0)}function N(t,e){r("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),B(t),e.flowing&&!e.reading&&t.read(0)}function B(t){var e=t._readableState;for(r("flow",e.flowing);e.flowing&&null!==t.read(););}function F(t,e){return 0===e.length?null:(e.objectMode?i=e.buffer.shift():!t||t>=e.length?(i=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):i=e.buffer.consume(t,e.decoder),i);var i}function z(t){var e=t._readableState;r("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,i.nextTick(H,e,t))}function H(t,e){if(r("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var i=e._writableState;(!i||i.autoDestroy&&i.finished)&&e.destroy()}}function j(t,e){for(var i=0,n=t.length;i=e.highWaterMark:e.length>0)||e.ended))return r("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?z(this):I(this),null;if(0===(t=E(t,e))&&e.ended)return 0===e.length&&z(this),null;var n,o=e.needReadable;return r("need readable",o),(0===e.length||e.length-t0?F(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),i!==t&&e.ended&&z(this)),null!==n&&this.emit("data",n),n},C.prototype._read=function(t){k(this,new x("_read()"))},C.prototype.pipe=function(t,e){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=t;break;case 1:o.pipes=[o.pipes,t];break;default:o.pipes.push(t)}o.pipesCount+=1,r("pipe count=%d opts=%j",o.pipesCount,e);var a=e&&!1===e.end||t===i.stdout||t===i.stderr?v:l;function l(){r("onend"),t.end()}o.endEmitted?i.nextTick(a):n.once("end",a),t.on("unpipe",(function e(i,s){r("onunpipe"),i===n&&s&&!1===s.hasUnpiped&&(s.hasUnpiped=!0,r("cleanup"),t.removeListener("close",f),t.removeListener("finish",p),t.removeListener("drain",c),t.removeListener("error",u),t.removeListener("unpipe",e),n.removeListener("end",l),n.removeListener("end",v),n.removeListener("data",d),h=!0,!o.awaitDrain||t._writableState&&!t._writableState.needDrain||c())}));var c=function(t){return function(){var e=t._readableState;r("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&s(t,"data")&&(e.flowing=!0,B(t))}}(n);t.on("drain",c);var h=!1;function d(e){r("ondata");var i=t.write(e);r("dest.write",i),!1===i&&((1===o.pipesCount&&o.pipes===t||o.pipesCount>1&&-1!==j(o.pipes,t))&&!h&&(r("false write response, pause",o.awaitDrain),o.awaitDrain++),n.pause())}function u(e){r("onerror",e),v(),t.removeListener("error",u),0===s(t,"error")&&k(t,e)}function f(){t.removeListener("finish",p),v()}function p(){r("onfinish"),t.removeListener("close",f),v()}function v(){r("unpipe"),n.unpipe(t)}return n.on("data",d),function(t,e,i){if("function"==typeof t.prependListener)return t.prependListener(e,i);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(i):t._events[e]=[i,t._events[e]]:t.on(e,i)}(t,"error",u),t.once("close",f),t.once("finish",p),t.emit("pipe",n),o.flowing||(r("pipe resume"),n.resume()),t},C.prototype.unpipe=function(t){var e=this._readableState,i={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,i)),this;if(!t){var n=e.pipes,o=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var r=0;r0,!1!==o.flowing&&this.resume()):"readable"===t&&(o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,r("on readable",o.length,o.reading),o.length?I(this):o.reading||i.nextTick(O,this))),n},C.prototype.addListener=C.prototype.on,C.prototype.removeListener=function(t,e){var n=a.prototype.removeListener.call(this,t,e);return"readable"===t&&i.nextTick(D,this),n},C.prototype.removeAllListeners=function(t){var e=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||i.nextTick(D,this),e},C.prototype.resume=function(){var t=this._readableState;return t.flowing||(r("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,i.nextTick(N,t,e))}(this,t)),t.paused=!1,this},C.prototype.pause=function(){return r("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(r("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},C.prototype.wrap=function(t){var e=this,i=this._readableState,n=!1;for(var o in t.on("end",(function(){if(r("wrapped end"),i.decoder&&!i.ended){var t=i.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(o){r("wrapped data"),i.decoder&&(o=i.decoder.write(o)),(!i.objectMode||null!=o)&&(i.objectMode||o&&o.length)&&(e.push(o)||(n=!0,t.pause()))})),t)void 0===this[o]&&"function"==typeof t[o]&&(this[o]=function(e){return function(){return t[e].apply(t,arguments)}}(o));for(var s=0;s-1))throw new b(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(C.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(C.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),C.prototype._write=function(t,e,i){i(new v("_write()"))},C.prototype._writev=null,C.prototype.end=function(t,e,n){var o=this._writableState;return"function"==typeof t?(n=t,t=null,e=null):"function"==typeof e&&(n=e,e=null),null!=t&&this.write(t,e),o.corked&&(o.corked=1,this.uncork()),o.ending||function(t,e,n){e.ending=!0,_(t,e),n&&(e.finished?i.nextTick(n):t.once("finish",n)),e.ended=!0,t.writable=!1}(this,o,n),this},Object.defineProperty(C.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(C.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),C.prototype.destroy=d.destroy,C.prototype._undestroy=d.undestroy,C.prototype._destroy=function(t,e){e(t)}}).call(this)}).call(this,t("_process"),void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(t,e,i){(function(i){(function(){"use strict";var n;function o(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}var r=t("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),l=Symbol("error"),c=Symbol("ended"),h=Symbol("lastPromise"),d=Symbol("handlePromise"),u=Symbol("stream");function f(t,e){return{value:t,done:e}}function p(t){var e=t[s];if(null!==e){var i=t[u].read();null!==i&&(t[h]=null,t[s]=null,t[a]=null,e(f(i,!1)))}}var v=Object.getPrototypeOf((function(){})),g=Object.setPrototypeOf((o(n={get stream(){return this[u]},next:function(){var t=this,e=this[l];if(null!==e)return Promise.reject(e);if(this[c])return Promise.resolve(f(void 0,!0));if(this[u].destroyed)return new Promise((function(e,n){i.nextTick((function(){t[l]?n(t[l]):e(f(void 0,!0))}))}));var n,o=this[h];if(o)n=new Promise(function(t,e){return function(i,n){t.then((function(){e[c]?i(f(void 0,!0)):e[d](i,n)}),n)}}(o,this));else{var r=this[u].read();if(null!==r)return Promise.resolve(f(r,!1));n=new Promise(this[d])}return this[h]=n,n}},Symbol.asyncIterator,(function(){return this})),o(n,"return",(function(){var t=this;return new Promise((function(e,i){t[u].destroy(null,(function(t){t?i(t):e(f(void 0,!0))}))}))})),n),v);e.exports=function(t){var e,n=Object.create(g,(o(e={},u,{value:t,writable:!0}),o(e,s,{value:null,writable:!0}),o(e,a,{value:null,writable:!0}),o(e,l,{value:null,writable:!0}),o(e,c,{value:t._readableState.endEmitted,writable:!0}),o(e,d,{value:function(t,e){var i=n[u].read();i?(n[h]=null,n[s]=null,n[a]=null,t(f(i,!1))):(n[s]=t,n[a]=e)},writable:!0}),e));return n[h]=null,r(t,(function(t){if(t&&"ERR_STREAM_PREMATURE_CLOSE"!==t.code){var e=n[a];return null!==e&&(n[h]=null,n[s]=null,n[a]=null,e(t)),void(n[l]=t)}var i=n[s];null!==i&&(n[h]=null,n[s]=null,n[a]=null,i(f(void 0,!0))),n[c]=!0})),t.on("readable",function(t){i.nextTick(p,t)}.bind(null,n)),n}}).call(this)}).call(this,t("_process"))},{"./end-of-stream":64,_process:50}],62:[function(t,e,i){"use strict";function n(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,n)}return i}function o(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function r(t,e){for(var i=0;i0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,i=""+e.data;e=e.next;)i+=t+e.data;return i}},{key:"concat",value:function(t){if(0===this.length)return s.alloc(0);for(var e,i,n,o=s.allocUnsafe(t>>>0),r=this.head,a=0;r;)e=r.data,i=o,n=a,s.prototype.copy.call(e,i,n),a+=r.data.length,r=r.next;return o}},{key:"consume",value:function(t,e){var i;return to.length?o.length:t;if(r===o.length?n+=o:n+=o.slice(0,t),0==(t-=r)){r===o.length?(++i,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=o.slice(r));break}++i}return this.length-=i,n}},{key:"_getBuffer",value:function(t){var e=s.allocUnsafe(t),i=this.head,n=1;for(i.data.copy(e),t-=i.data.length;i=i.next;){var o=i.data,r=t>o.length?o.length:t;if(o.copy(e,e.length-t,0,r),0==(t-=r)){r===o.length?(++n,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(r));break}++n}return this.length-=n,e}},{key:l,value:function(t,e){return a(this,function(t){for(var e=1;e0,(function(t){h||(h=t),t&&u.forEach(l),r||(u.forEach(l),d(h))}))}));return i.reduce(c)}},{"../../../errors":55,"./end-of-stream":64}],67:[function(t,e,i){"use strict";var n=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;e.exports={getHighWaterMark:function(t,e,i,o){var r=function(t,e,i){return null!=t.highWaterMark?t.highWaterMark:e?t[i]:null}(e,o,i);if(null!=r){if(!isFinite(r)||Math.floor(r)!==r||r<0)throw new n(o?i:"highWaterMark",r);return Math.floor(r)}return t.objectMode?16:16384}}},{"../../../errors":55}],68:[function(t,e,i){e.exports=t("events").EventEmitter},{events:22}],69:[function(t,e,i){(i=e.exports=t("./lib/_stream_readable.js")).Stream=i,i.Readable=i,i.Writable=t("./lib/_stream_writable.js"),i.Duplex=t("./lib/_stream_duplex.js"),i.Transform=t("./lib/_stream_transform.js"),i.PassThrough=t("./lib/_stream_passthrough.js"),i.finished=t("./lib/internal/streams/end-of-stream.js"),i.pipeline=t("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(t,e,i){"use strict";e.exports=function(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var t;if(arguments.length>0){t=new Array(arguments.length-2);for(var e=0;e>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function a(t){var e=this.lastTotal-this.lastNeed,i=function(t,e,i){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==i?i:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function l(t,e){if((t.length-e)%2==0){var i=t.toString("utf16le",e);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],i.slice(0,-1)}return i}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function c(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,i)}return e}function h(t,e){var i=(t.length-e)%3;return 0===i?t.toString("base64",e):(this.lastNeed=3-i,this.lastTotal=3,1===i?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-i))}function d(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function u(t){return t.toString(this.encoding)}function f(t){return t&&t.length?this.write(t):""}i.StringDecoder=r,r.prototype.write=function(t){if(0===t.length)return"";var e,i;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i=0?(o>0&&(t.lastNeed=o-1),o):--n=0?(o>0&&(t.lastNeed=o-2),o):--n=0?(o>0&&(2===o?o=0:t.lastNeed=o-3),o):0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=i;var n=t.length-(i-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},r.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},{"safe-buffer":73}],76:[function(t,e,i){"use strict";var n=t("punycode"),o=t("./util");function r(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}i.parse=w,i.resolve=function(t,e){return w(t,!1,!0).resolve(e)},i.resolveObject=function(t,e){return t?w(t,!1,!0).resolveObject(e):e},i.format=function(t){return o.isString(t)&&(t=w(t)),t instanceof r?t.format():r.prototype.format.call(t)},i.Url=r;var s=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),h=["'"].concat(c),d=["%","/","?",";","#"].concat(h),u=["/","?","#"],f=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},m=t("querystring");function w(t,e,i){if(t&&o.isObject(t)&&t instanceof r)return t;var n=new r;return n.parse(t,e,i),n}r.prototype.parse=function(t,e,i){if(!o.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var r=t.indexOf("?"),a=-1!==r&&r127?M+="x":M+=L[D];if(!M.match(f)){var N=I.slice(0,S),B=I.slice(S+1),F=L.match(p);F&&(N.push(F[1]),B.unshift(F[2])),B.length&&(w="/"+B.join(".")+w),this.hostname=N.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),E||(this.hostname=n.toASCII(this.hostname));var z=this.port?":"+this.port:"",H=this.hostname||"";this.host=H+z,this.href+=this.host,E&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==w[0]&&(w="/"+w))}if(!v[k])for(S=0,_=h.length;S<_;S++){var j=h[S];if(-1!==w.indexOf(j)){var W=encodeURIComponent(j);W===j&&(W=escape(j)),w=w.split(j).join(W)}}var U=w.indexOf("#");-1!==U&&(this.hash=w.substr(U),w=w.slice(0,U));var V=w.indexOf("?");if(-1!==V?(this.search=w.substr(V),this.query=w.substr(V+1),e&&(this.query=m.parse(this.query)),w=w.slice(0,V)):e&&(this.search="",this.query={}),w&&(this.pathname=w),y[k]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){z=this.pathname||"";var q=this.search||"";this.path=z+q}return this.href=this.format(),this},r.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var e=this.protocol||"",i=this.pathname||"",n=this.hash||"",r=!1,s="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&o.isObject(this.query)&&Object.keys(this.query).length&&(s=m.stringify(this.query));var a=this.search||s&&"?"+s||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||y[e])&&!1!==r?(r="//"+(r||""),i&&"/"!==i.charAt(0)&&(i="/"+i)):r||(r=""),n&&"#"!==n.charAt(0)&&(n="#"+n),a&&"?"!==a.charAt(0)&&(a="?"+a),e+r+(i=i.replace(/[?#]/g,(function(t){return encodeURIComponent(t)})))+(a=a.replace("#","%23"))+n},r.prototype.resolve=function(t){return this.resolveObject(w(t,!1,!0)).format()},r.prototype.resolveObject=function(t){if(o.isString(t)){var e=new r;e.parse(t,!1,!0),t=e}for(var i=new r,n=Object.keys(this),s=0;s0)&&i.host.split("@"))&&(i.auth=E.shift(),i.host=i.hostname=E.shift())),i.search=t.search,i.query=t.query,o.isNull(i.pathname)&&o.isNull(i.search)||(i.path=(i.pathname?i.pathname:"")+(i.search?i.search:"")),i.href=i.format(),i;if(!T.length)return i.pathname=null,i.search?i.path="/"+i.search:i.path=null,i.href=i.format(),i;for(var C=T.slice(-1)[0],R=(i.host||t.host||T.length>1)&&("."===C||".."===C)||""===C,S=0,P=T.length;P>=0;P--)"."===(C=T[P])?T.splice(P,1):".."===C?(T.splice(P,1),S++):S&&(T.splice(P,1),S--);if(!b&&!k)for(;S--;S)T.unshift("..");!b||""===T[0]||T[0]&&"/"===T[0].charAt(0)||T.unshift(""),R&&"/"!==T.join("/").substr(-1)&&T.push("");var E,I=""===T[0]||T[0]&&"/"===T[0].charAt(0);return A&&(i.hostname=i.host=I?"":T.length?T.shift():"",(E=!!(i.host&&i.host.indexOf("@")>0)&&i.host.split("@"))&&(i.auth=E.shift(),i.host=i.hostname=E.shift())),(b=b||i.host&&T.length)&&!I&&T.unshift(""),T.length?i.pathname=T.join("/"):(i.pathname=null,i.path=null),o.isNull(i.pathname)&&o.isNull(i.search)||(i.path=(i.pathname?i.pathname:"")+(i.search?i.search:"")),i.auth=t.auth||i.auth,i.slashes=i.slashes||t.slashes,i.href=i.format(),i},r.prototype.parseHost=function(){var t=this.host,e=a.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":77,punycode:51,querystring:54}],77:[function(t,e,i){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],78:[function(t,e,n){(function(t){(function(){function i(e){try{if(!t.localStorage)return!1}catch(t){return!1}var i=t.localStorage[e];return null!=i&&"true"===String(i).toLowerCase()}e.exports=function(t,e){if(i("noDeprecation"))return t;var n=!1;return function(){if(!n){if(i("throwDeprecation"))throw new Error(e);i("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}}}).call(this)}).call(this,void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(t,e,i){e.exports=function t(e,i){if(e&&i)return t(e)(i);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),i=0;i0)for(var i=0,o=arguments.length;i1)i=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,i=this.head.value}for(var o=0;null!==n;o++)i=t(i,n.value,o),n=n.next;return i},n.prototype.reduceReverse=function(t,e){var i,n=this.tail;if(arguments.length>1)i=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,i=this.tail.value}for(var o=this.length-1;null!==n;o--)i=t(i,n.value,o),n=n.prev;return i},n.prototype.toArray=function(){for(var t=new Array(this.length),e=0,i=this.head;null!==i;e++)t[e]=i.value,i=i.next;return t},n.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,i=this.tail;null!==i;e++)t[e]=i.value,i=i.prev;return t},n.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var i=new n;if(ethis.length&&(e=this.length);for(var o=0,r=this.head;null!==r&&othis.length&&(e=this.length);for(var o=this.length,r=this.tail;null!==r&&o>e;o--)r=r.prev;for(;null!==r&&o>t;o--,r=r.prev)i.push(r.value);return i},n.prototype.splice=function(t,e,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,r=this.head;null!==r&&n{for(var n in e)i.o(e,n)&&!i.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var n={};return(()=>{"use strict";function t(t,e){const i=e||new Path2D;let n=t.calculative.borderRadius||0,o=n;const{x:r,y:s,width:a,height:l,ex:c,ey:h}=t.calculative.worldRect;n<1&&(n*=a,o*=l);let d=nho,activityDiagram:()=>Ro,activityDiagramByCtx:()=>So,chartsPens:()=>Us,classPens:()=>mo,flowAnchors:()=>qo,flowPens:()=>Vo,formPens:()=>rs,ftaAnchors:()=>Ss,ftaPens:()=>Cs,ftaPensbyCtx:()=>Rs,registerEcharts:()=>yr,registerHighcharts:()=>mr,registerLightningChart:()=>wr,sequencePens:()=>bo,sequencePensbyCtx:()=>ko}),i(173);const e=t;var o,r,s,a,l;!function(t){t[t.Node=0]="Node",t[t.Line=1]="Line"}(o||(o={})),function(t){t[t.None=0]="None",t[t.DisableEdit=1]="DisableEdit",t[t.DisableMove=2]="DisableMove",t[t.DisableScale=3]="DisableScale",t[t.DisableMoveScale=4]="DisableMoveScale",t[t.Disable=10]="Disable"}(r||(r={})),function(t){t[t.Default=0]="Default",t[t.In=1]="In",t[t.Out=2]="Out"}(s||(s={})),function(t){t[t.None=0]="None",t[t.Linear=1]="Linear",t[t.Radial=2]="Radial"}(a||(a={})),function(t){t[t.CanvasTemplate=1]="CanvasTemplate",t[t.CanvasImageBottom=2]="CanvasImageBottom",t[t.CanvasMain=3]="CanvasMain",t[t.CanvasImage=4]="CanvasImage"}(l||(l={}));const c=["text","textWidth","textHeight","textLeft","textTop","fontFamily","fontSize","lineHeight","fontStyle","fontWeight","textAlign","textBaseline","whiteSpace","ellipsis","keepDecimal"],h=["x","y","width","height","flipX","flipY"],d=["paddingTop","paddingRight","paddingBottom","paddingLeft","flipX","flipY","visible","showChild"],u=["iconLeft","iconTop","iconRotate"];var f;!function(t){t[t.Normal=0]="Normal",t[t.Beads=1]="Beads",t[t.Dot=2]="Dot",t[t.Arrow=3]="Arrow",t[t.WaterDrop=4]="WaterDrop"}(f||(f={}));const p=["gif","iframe","video","echarts","highcharts","lightningCharts"],v=["radio","checkbox","button","inputDom","slider"],g=new Set(["borderRadius","paddingLeft","paddingRight","paddingTop","paddingBottom","progress","progressColor","verticalProgress","reverseProgress","flipX","flipY","input","lineDash","lineCap","lineJoin","strokeType","lineGradientFromColor","lineGradientToColor","lineGradientAngle","color","hoverColor","activeColor","lineWidth","bkType","gradientFromColor","gradientToColor","gradientAngle","gradientRadius","hoverBackground","activeBackground","globalAlpha","anchorColor","anchorRadius","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","textHasShadow","fontFamily","fontSize","textColor","hoverTextColor","activeTextColor","textBackground","fontStyle","fontWeight","textAlign","textBaseline","lineHeight","whiteSpace","textWidth","textHeight","textLeft","textTop","ellipsis","hiddenText","keepDecimal","borderWidth","borderColor","animateLineWidth","lineAnimateType","frames","animateColor","animateType","animateReverse","background","gradientColors","lineGradientColors","animateLineWidth","gradientSmooth","lineSmooth","animations"]);var y,m,w,x;!function(t){t[t.None=0]="None",t[t.LineAnchor=1]="LineAnchor",t[t.NodeAnchor=2]="NodeAnchor",t[t.Line=3]="Line",t[t.Node=4]="Node",t[t.Resize=5]="Resize",t[t.Rotate=6]="Rotate",t[t.LineAnchorPrev=7]="LineAnchorPrev",t[t.LineAnchorNext=8]="LineAnchorNext"}(y||(y={})),function(t){t[t.None=0]="None",t[t.Translate=1]="Translate",t[t.Select=2]="Select",t[t.Resize=3]="Resize",t[t.AddAnchor=4]="AddAnchor"}(m||(m={})),function(t){t[t.None=0]="None",t[t.Down=1]="Down",t[t.Translate=2]="Translate"}(w||(w={})),function(t){t[t.None=-1]="None",t[t.Up=0]="Up",t[t.Right=1]="Right",t[t.Bottom=2]="Bottom",t[t.Left=3]="Left"}(x||(x={}));const b=["nw-resize","ne-resize","se-resize","sw-resize"],k=["n-resize","e-resize","s-resize","w-resize"],T=["curve","polyline","line"],A=["dash","lineWidth","lineCap","lineJoin","strokeType","color","lineGradientFromColor","lineGradientToColor","lineGradientAngle","globalAlpha","bkType","background","gradientFromColor","gradientToColor","gradientAngle","gradientRadius","fontFamily","fontSize","textColor","hoverTextColor","activeTextColor","textBackground","fontStyle","fontWeight","textAlign","textBaseline","lineHeight","whiteSpace","textLeft","textTop","flipX","flipY","lineDash","visible","iconColor"];var C,R,S;function P(t,e,i){if(!e||e%360==0)return;const n=e*Math.PI/180,o=(t.x-i.x)*Math.cos(n)-(t.y-i.y)*Math.sin(n)+i.x,r=(t.x-i.x)*Math.sin(n)+(t.y-i.y)*Math.cos(n)+i.y;t.x=o,t.y=r,t.prev&&P(t.prev,e,i),t.next&&P(t.next,e,i)}function E(t,e,i=5,n){if(e.type===S.Line){let o=n.rotate;n.flipX&&(o*=-1),n.flipY&&(o*=-1);let r=e.rotate+o;return n.flipX&&(r*=-1),n.flipY&&(r*=-1),Be(t,{x:e.x-e.length*n.calculative.canvas.store.data.scale/2,y:e.y-i,width:e.length*n.calculative.canvas.store.data.scale,height:2*i,rotate:r})}return t.x>e.x-i&&t.xe.y-i&&t.y0&&n>0?o=180-o:i<0&&n>0?o+=180:i<0&&n<0&&(o=360-o),o}function L(t,e){const i=t.x-e.x,n=t.y-e.y;return Math.sqrt(i*i+n*n)}function M(t,e,i){t&&(t.x+=e,t.y+=i,t.next&&(t.next.x+=e,t.next.y+=i),t.prev&&(t.prev.x+=e,t.prev.y+=i))}function D(t,e){return t.anchorId===e.anchorId&&t.connectTo===e.connectTo}function O(t,e,i){let n=Math.sqrt((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y))/i.data.scale;0===e.rotate?t.x{const o=t.measureText(n).width;e.calculative.textLineWidths.push(o),i1?r:1;switch(t.whiteSpace){case"nowrap":if(!1!==t.ellipsis){const n=X(e.split(""),t);n[0]&&(i.push(n[0]),n.length>1&&G(i))}else i.push(e);break;case"pre-line":i=e.split(/[\n]/g),!1!==t.ellipsis&&i.length>s&&(i=i.slice(0,s),G(i));break;default:const n=e.split(/[\n]/g);let o=0;t:for(const e of n){let n=X("break-all"===t.whiteSpace?e.split(""):$(e),t);if(0===n.length&&(n=[""]),0!=t.ellipsis)for(const t of n){if(o++,o>s){G(i);break t}i.push(t)}else i.push(...n)}}const a=t.calculative.keepDecimal;return null!=a&&i.forEach(((t,e)=>{const n=Number(t);isNaN(n)||(i[e]=n.toFixed(a))})),t.calculative.textLines=i,i}function $(t=""){const e=[];let i="";for(let n=0;n126?(i&&(e.push(i),i=""),e.push(t[n])):i+=t[n]}return i&&e.push(i),e}function X(t,e){const i=e.calculative.canvas,n=i.offscreen.getContext("2d"),{fontStyle:o,fontWeight:r,fontSize:s,fontFamily:a,lineHeight:l}=e.calculative;n.save();const c=[];let h=t[0]||"";for(let d=1;d{i.push(Q(t,e))})),i}if("object"==typeof t){if(null===t)return null;if(t.constructor===RegExp)return t;const i={};for(const n in t)["canvas","lastFrame"].includes(n)||t[n]instanceof HTMLImageElement||t[n]instanceof HTMLMediaElement||("calculative"!==n||e)&&(i[n]="singleton"!==n?Q(t[n],e):e?{}:t[n]);return i}return t}function J(t,e,i){if(Array.isArray(t)){const n=[];return t.forEach((t=>{n.push(J(t,e,i))})),n}if("object"==typeof t){if(null===t)return null;for(const n in t)if(e.includes(n))if(Array.isArray(t[n]))t[n].forEach(((e,o)=>{Number.isNaN(Number(e))||(t[n][o]=Number(e*i))}));else{if(Number.isNaN(Number(t[n])))continue;t[n]=Number(t[n])*i}else t[n]=J(t[n],e,i);return t}return t}const Z={};function tt(t,e,i){if(!Z[e.fromArrow])return;const n=re(e),{x:o,y:r}=n,s={x:o,y:r};if(s.step=(e.fromArrowSize||10)*i.data.scale,n.next)s.rotate=_(n.next,n)+90;else{const t=e.calculative.worldAnchors[1];if(!t)return;t.prev?s.rotate=_(t.prev,n)+90:s.rotate=_(t,n)+90}t.save(),t.beginPath(),t.setLineDash([]);const a=e.fromArrowColor||e.calculative.color;a&&(t.strokeStyle=a),Z[e.fromArrow](t,e,i,s),t.restore()}function et(t,e,i){if(!Z[e.toArrow]||e.calculative.worldAnchors.length<2)return;t.save();const n=se(e),{x:o,y:r}=n,s={x:o,y:r};if(s.step=(e.toArrowSize||10)*i.data.scale,n.prev)s.rotate=_(n.prev,n)+90;else{const t=e.calculative.worldAnchors[e.calculative.worldAnchors.length-2];t.next?s.rotate=_(t.next,n)+90:s.rotate=_(t,n)+90}t.beginPath(),t.setLineDash([]);const a=e.toArrowColor||e.calculative.color;a&&(t.strokeStyle=a),Z[e.toArrow](t,e,i,s),t.restore()}function it(t){const e=parseInt,i=Math.round;let n=t.length,o={};if(n>9){const[i,r,s,a]=t=t.split(",");if(n=t.length,n<3||n>4)return null;o.r=e("a"==i[3]?i.slice(5):i.slice(4)),o.g=e(r),o.b=e(s),o.a=a?parseFloat(a):-1}else{if(8==n||6==n||n<4)return null;n<6&&(t="#"+t[1]+t[1]+t[2]+t[2]+t[3]+t[3]+(n>4?t[4]+t[4]:"")),t=e(t.slice(1),16),9==n||5==n?(o.r=t>>24&255,o.g=t>>16&255,o.b=t>>8&255,o.a=i((255&t)/.255)/1e3):(o.r=t>>16,o.g=t>>8&255,o.b=255&t,o.a=-1)}return o}function nt(t,e,i,n){let o,r,s,a,l,c,h,d=Math.round,u="string"==typeof i;return"number"!=typeof t||t<-1||t>1||"string"!=typeof e||"r"!=e[0]&&"#"!=e[0]||i&&!u?null:(h=e.length>9,h=u?i.length>9||"c"==i&&!h:h,l=it(e),a=t<0,c=i&&"c"!=i?it(i):a?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},a=1-(t=a?-1*t:t),l&&c?(n?(o=d(a*l.r+t*c.r),r=d(a*l.g+t*c.g),s=d(a*l.b+t*c.b)):(o=d((a*l.r**2+t*c.r**2)**.5),r=d((a*l.g**2+t*c.g**2)**.5),s=d((a*l.b**2+t*c.b**2)**.5)),u=l.a,c=c.a,l=u>=0||c>=0,u=l?u<0?c:c<0?u:u*a+c*t:0,h?"rgb"+(l?"a(":"(")+o+","+r+","+s+(l?","+d(1e3*u)/1e3:"")+")":"#"+(4294967296+16777216*o+65536*r+256*s+(l?d(255*u):0)).toString(16).slice(1,l?void 0:-2)):null)}function ot(t,e){const i=it(t)||{r:0,g:0,b:0};return i.a<0?`rgba(${i.r},${i.g},${i.b},${e})`:`rgba(${i.r},${i.g},${i.b},${e+i.a})`}function rt(t,e){if(isNaN(t))return void console.warn("realValue not number");if("string"!=typeof e)return void console.warn("collection must be string");const[i,n]=[e[0],e[e.length-1]];if(!["[","("].includes(i))return void console.warn('collection must start with "[" or "("');if(!["]",")"].includes(n))return void console.warn('collection must end with "]" or ")"');const o=e.substring(1,e.length-1).split(",");if(2!==o.length)return void console.warn("collection must have 2 numbers");const[r,s]=[+o[0],+o[1]];if(!(r>=s))return(t>r||"["===i&&t===r)&&(t=r)return void console.warn("startNum must less than endNum");if(t>=o&&t<=r)return!0}else if(t==e)return!0;return!1}function at(){return(4294967296*(1+Math.random())|0).toString(16).substring(1)}Z.triangleSolid=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step;t.moveTo(o,n.y-n.step/4),t.lineTo(n.x,n.y),t.lineTo(o,n.y+n.step/4),t.closePath(),t.stroke(),t.fillStyle=t.strokeStyle,t.fill(),t.restore()},Z.triangle=(t,e,i,n)=>{t.save(),t.lineWidth<2&&(t.lineWidth=2),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step;t.moveTo(o,n.y-n.step/4),t.lineTo(n.x,n.y),t.lineTo(o,n.y+n.step/4),t.closePath(),t.stroke(),t.fillStyle=i.data.background||"#ffffff",t.fill(),t.restore()},Z.circleSolid=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.step/2;t.arc(n.x-o,n.y,o,0,2*Math.PI),t.stroke(),t.fillStyle=t.strokeStyle,t.fill(),t.restore()},Z.circle=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.step/2;t.arc(n.x-o,n.y,o,0,2*Math.PI),t.stroke(),t.fillStyle=i.data.background||"#ffffff",t.fill(),t.restore()},Z.diamondSolid=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step,r=n.step/2;t.moveTo(o,n.y),t.lineTo(o+r,n.y-r/2),t.lineTo(n.x,n.y),t.lineTo(o+r,n.y+r/2),t.closePath(),t.stroke(),t.fillStyle=t.strokeStyle,t.fill(),t.restore()},Z.diamond=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step,r=n.step/2;t.moveTo(o,n.y),t.lineTo(o+r,n.y-r/2),t.lineTo(n.x,n.y),t.lineTo(o+r,n.y+r/2),t.closePath(),t.stroke(),t.fillStyle=i.data.background||"#ffffff",t.fill(),t.restore()},Z.line=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step;t.moveTo(o,n.y-n.step/3),t.lineTo(n.x,n.y),t.lineTo(o,n.y+n.step/3),t.stroke(),t.restore()},Z.lineUp=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step;t.moveTo(o,n.y-n.step/3),t.lineTo(n.x,n.y),t.stroke(),t.restore()},Z.lineDown=(t,e,i,n)=>{t.save(),t.translate(n.x,n.y),t.rotate(n.rotate*Math.PI/180),t.translate(-n.x,-n.y);const o=n.x-n.step;t.moveTo(o,n.y+n.step/3),t.lineTo(n.x,n.y),t.stroke(),t.restore()},globalThis.pSBC=nt;const lt=t=>{let e=0,i=0,n=0,o=0;return"number"==typeof t?e=i=n=o=t:"string"==typeof t?e=i=n=o=parseInt(t,10):Array.isArray(t)&&(e=t[0],n=ct(t[1])?t[0]:t[1],o=ct(t[2])?t[0]:t[2],i=ct(t[3])?n:t[3]),[e,n,o,i]};function ct(t){return null==t}function ht(t,e){if(!t||!t.parentId||!t.calculative)return;const i=t.calculative.canvas.store.pens[t.parentId];return e&&ht(i,e)||i}function dt(t,e){if(!t||!t.children)return[];const i=[];return t.children.forEach((t=>{const n=e.pens[t];n&&(i.push(n),i.push(...dt(n,e)))})),i}function ut(t,e){if(!t||!t.followers)return[];const i=[];return t.followers.forEach((t=>{const n=e.pens[t];n&&!n.parentId&&(i.push(n),i.push(...ut(n,e)))})),i}function ft(t,e,i){const n=Math.atan(i/e)/Math.PI*180;let o=(t-90)%360,r=0;return o>n&&o<180-n||o>180+n&&o<360-n||o<0?(o>270?o=360-o:o>180?o-=180:o>90&&(o=180-o),r=Math.abs(i/Math.sin(o/180*Math.PI)/2)):(o>270?o=360-o:o>180?o-=180:o>90&&(o=180-o),r=Math.abs(e/Math.cos(o/180*Math.PI)/2)),r}function pt(t){if("string"==typeof t&&t.startsWith("linear-gradient")){let e=t.slice(16,-2).split("deg,");if(e.length>1){let t=e[1].split("%,");const i=[];return t.forEach((t=>{if(/rgba?/.test(t)){let e=t.split(") ");i.push({color:vt(e[0]+")"),i:parseFloat(e[1])/100})}else{let e=t.split(" ");e.length>2?i.push({color:e[1],i:parseFloat(e[2])/100}):i.push({color:e[0],i:parseFloat(e[1])/100})}})),{angle:parseFloat(e[0]),colors:i}}return{angle:parseFloat(e[0]),colors:[]}}return{angle:0,colors:[]}}function vt(t){if(/rgba?/.test(t)){let e=t.split(",");if(e.length<3)return"";t="#";for(let i,n=0;i=e[n++];)if(n<4)i=parseInt(i.replace(/[^\d]/gi,""),10).toString(16),t+=1==i.length?"0"+i:i;else{i=i.replace(")","");let e=parseInt(255*i+"").toString(16);e=2===e.length?e:"0"+e,t+=e}t=t.toUpperCase()}return t}function gt(t,e,i,n){let o=function(t,e,i,n,o){let r=0;r=Math.PI/2-Math.atan2(n-e,i-t);const s=(t+i)/2,a=(e+n)/2;return[s+o*Math.sin(90*Math.PI/180-r),a+o*-Math.cos(90*Math.PI/180-r),s+o*Math.sin(270*Math.PI/180-r),a+o*-Math.cos(270*Math.PI/180-r)]}(e[0].x,e[0].y,e[1].x,e[1].y,n),r=t.createLinearGradient(o[0],o[1],o[2],o[3]);return i.forEach((t=>{r.addColorStop(t.i,t.color)})),r}function yt(t,e,i){let n=[];e.calculative.gradientColorStop?n=e.calculative.gradientColorStop:(n=pt(e.calculative.lineGradientColors).colors,e.calculative.gradientColorStop=n),t.strokeStyle=gt(t,i,n,e.calculative.lineWidth/2),t.beginPath(),t.moveTo(i[0].x,i[0].y),t.lineTo(i[1].x,i[1].y),t.stroke()}function mt(t,e){const i=e.calculative.worldAnchors;let n=e.calculative.lineWidth*(e.calculative.gradientSmooth||e.calculative.lineSmooth||0);for(let o=0;o0&&o0&&o0){let r=i[o-1].curvePoints;xt(t,e,n,r?r[r.length-1]:i[o-1],i[o],i[o].curvePoints[0]),yt(t,e,[wt(n,i[o],i[o].curvePoints[0]),i[o].curvePoints[1]])}else yt(t,e,[i[o],i[o].curvePoints[0]]),yt(t,e,[i[o].curvePoints[0],i[o].curvePoints[1]]);let r=i[o].curvePoints.length-1;for(let n=1;n0&&t0&&t{P(t,c,a)})),gt(t,l,h,d)}(t,e):f===a.Radial&&(g=function(t,e){const{worldRect:i,textGradientColors:n}=e.calculative;if(!n)return;const{width:o,height:r,center:s}=i,{x:a,y:l}=s;let c=o;c{d.addColorStop(t.i,t.color)})),d}(t,e)),t.fillStyle=v||g||Pt(e,p),t.font=Lt({fontStyle:i,fontWeight:n,fontFamily:r||p.options.fontFamily,fontSize:o,lineHeight:s}),!e.calculative.textDrawRect&&K(t,e);const{x:y,y:m,width:w,height:x}=e.calculative.textDrawRect;u&&(t.save(),t.fillStyle=u,t.fillRect(y,m,w,x),t.restore());const b=.55,k=e.textAlign||p.options.textAlign,T=o*s;e.calculative.textLines.forEach(((i,n)=>{const r=e.calculative.textLineWidths[n];let s=0;"center"===k?s=(w-r)/2:"right"===k&&(s=w-r),t.fillText(i,y+s,m+(n+b)*T);const{textDecorationColor:a,textDecorationDash:l,textDecoration:c}=e;c&&function(t,e,i){const{textDecorationColor:n,textDecorationDash:o,fontSize:r}=i;let{x:s,y:a,width:l}=e;switch(t.textBaseline){case"top":a+=r;break;case"middle":a+=r/2}t.save(),t.beginPath(),t.strokeStyle=n||t.fillStyle,t.lineWidth=1,t.moveTo(s,a),t.setLineDash(o||[]),t.lineTo(s+l,a),t.stroke(),t.restore()}(t,{x:y+s,y:m+(n+b)*T,width:r},{textDecorationColor:a,textDecorationDash:l,fontSize:o});const{textStrickoutColor:h,textStrickoutDash:d,textStrickout:u}=e;u&&function(t,e,i){const{textStrickoutColor:n,textStrickoutDash:o,fontSize:r}=i;let{x:s,y:a,width:l}=e;switch(t.textBaseline){case"top":a+=r/2;break;case"bottom":a-=r/2}t.save(),t.beginPath(),t.strokeStyle=n||t.fillStyle,t.lineWidth=1,t.moveTo(s,a),t.setLineDash(o||[]),t.lineTo(s+l,a),t.stroke(),t.restore()}(t,{x:y+s,y:m+(n+b)*T,width:r},{textStrickoutColor:h,textStrickoutDash:d,fontSize:o})})),t.restore()}function It(t,e,i){if(null==i)return;const{fontStyle:n,fontWeight:o,fontSize:r,fontFamily:s,lineHeight:a,canvas:l}=e.calculative,c=l.store;let h;t.save(),e.calculative.hover?h=e.hoverTextColor||e.hoverColor||c.options.hoverColor:e.calculative.active&&(h=e.activeTextColor||e.activeColor||c.options.activeColor),t.fillStyle=h||Pt(e,c),t.font=Lt({fontStyle:n,fontWeight:o,fontFamily:s||c.options.fontFamily,fontSize:r,lineHeight:a});const d=t.measureText(i).width;let u,f;for(const n of e.calculative.worldAnchors){if(!f){f=n;continue}const e=L(f,n),o=Math.floor(e/d);u="";for(let t=0;t0?e.calculative.iconSize:n.width>n.height?n.height:n.width,t.font=Lt({fontSize:a,fontWeight:s,fontFamily:l}),t.fillStyle=e.calculative.iconColor||Pt(e,i),e.calculative.iconRotate&&(t.translate(n.center.x,n.center.y),t.rotate(e.calculative.iconRotate*Math.PI/180),t.translate(-n.center.x,-n.center.y)),t.beginPath(),t.fillText(e.calculative.icon,o,r),t.restore()}function Lt({fontStyle:t="normal",textDecoration:e="normal",fontWeight:i="normal",fontSize:n=12,fontFamily:o="Arial",lineHeight:r=1}={}){return`${t} ${e} ${i} ${n}px/${r} ${o}`}function Mt(t,e){const{x:i,ex:n,y:o,ey:r}=e.calculative.worldRect||{};e.calculative.flipX&&(t.translate(i+n+.5,.5),t.scale(-1,1)),e.calculative.flipY&&(t.translate(.5,o+r+.5),t.scale(1,-1))}function Dt(t,e,i=!1){const{x:n,y:o}=e.calculative.worldRect.pivot||e.calculative.worldRect.center;t.translate(n,o);let r=e.calculative.rotate*Math.PI/180;i||(e.calculative.flipX&&(r*=-1),e.calculative.flipY&&(r*=-1)),t.rotate(r),t.translate(-n,-o)}function Ot(t,e,i){t.save(),t.translate(.5,.5),t.beginPath();const n=e.calculative.canvas.store,r=e.textFlip||n.options.textFlip,s=e.textRotate||n.options.textRotate;let l;r&&s||t.save(),Mt(t,e),e.calculative.rotate&&"line"!==e.name&&Dt(t,e),(e.calculative.lineWidth>1||i)&&(t.lineWidth=e.calculative.lineWidth),function(t,e,i){if(e.fillWorldTextRect){t.save(),t.fillStyle="#c3deb7";const{x:e,y:n,width:o,height:r}=i.calculative.worldTextRect;t.fillRect(e,n,o,r),t.restore()}}(t,n,e);let c,h=!1;e.calculative.disabled?(c=e.disabledColor||n.options.disabledColor||nt(.4,e.calculative.color||Wt(n)),l=e.disabledBackground||n.options.disabledBackground||nt(.4,e.calculative.background||n.data.penBackground)):e.mouseDownValid&&e.calculative.mouseDown?(c=e.mouseDownColor||nt(-.4,e.calculative.color||Wt(n)),l=e.mouseDownBackground||nt(-.4,e.calculative.background||n.data.penBackground)):e.calculative.hover?(c=e.hoverColor||n.options.hoverColor,l=e.hoverBackground||n.options.hoverBackground):e.calculative.active?(c=e.activeColor||n.options.activeColor,l=e.activeBackground||n.options.activeBackground):e.calculative.isDock&&(e.type===o.Line?c=n.options.dockPenColor:l=ot(n.options.dockPenColor,.2));const d=e.calculative.strokeImg;if(e.calculative.strokeImage&&d)t.strokeStyle=c||t.createPattern(d,"repeat");else{let i;e.calculative.strokeType?e.calculative.lineGradientColors?"line"===e.name?h=!0:e.calculative.lineGradient?i=e.calculative.lineGradient:(i=function(t,e){const{x:i,y:n,ex:o,width:r,height:s,center:a}=e.calculative.worldRect;let l=[{x:o,y:n+s/2},{x:i,y:n+s/2}];const{angle:c,colors:h}=pt(e.calculative.lineGradientColors);let d=ft(c,r,s);return l.forEach((t=>{P(t,c,a)})),gt(t,l,h,d)}(t,e),e.calculative.lineGradient=i):i=function(t,e){const{worldRect:i,lineGradientFromColor:n,lineGradientToColor:o,lineGradientAngle:r}=e.calculative;return Rt(t,i,n,o,r)}(t,e):i=e.calculative.color||Wt(n),t.strokeStyle=c||i}const u=e.calculative.backgroundImg;if(e.calculative.backgroundImage&&u)t.fillStyle=l||t.createPattern(u,"repeat"),l=!0;else{let i;e.calculative.bkType===a.Linear?e.calculative.gradientColors?e.calculative.gradient?i=e.calculative.gradient:(i=function(t,e){const{x:i,y:n,ex:o,width:r,height:s,center:a}=e.calculative.worldRect;let l=[{x:o,y:n+s/2},{x:i,y:n+s/2}];const{angle:c,colors:h}=pt(e.calculative.gradientColors);let d=ft(c,r,s);return l.forEach((t=>{P(t,c,a)})),gt(t,l,h,d)}(t,e),e.calculative.gradient=i):i=function(t,e){const{worldRect:i,gradientFromColor:n,gradientToColor:o,gradientAngle:r}=e.calculative;return Rt(t,i,n,o,r)}(t,e):e.calculative.bkType===a.Radial?e.calculative.gradientColors?e.calculative.radialGradient?i=e.calculative.radialGradient:(i=function(t,e){const{worldRect:i,gradientColors:n,gradientRadius:o}=e.calculative;if(!n)return;const{width:r,height:s,center:a}=i,{x:l,y:c}=a;let h=r;h{u.addColorStop(t.i,t.color)})),u}(t,e),e.calculative.radialGradient=i):i=function(t,e){const{worldRect:i,gradientFromColor:n,gradientToColor:o,gradientRadius:r}=e.calculative;if(!n||!o)return;const{width:s,height:a,center:l}=i,{x:c,y:h}=l;let d=s;dt*e.calculative.canvas.store.data.scale))),e.calculative.lineDashOffset&&(t.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(t.shadowColor=e.calculative.shadowColor,t.shadowOffsetX=e.calculative.shadowOffsetX,t.shadowOffsetY=e.calculative.shadowOffsetY,t.shadowBlur=e.calculative.shadowBlur),h?(mt(t,e),Ht(!0,t,e,n)):(zt(!0,t,e,n,l),Te(t,e)),e.image&&e.calculative.img||!e.calculative.icon||_t(t,e),r&&s||t.restore(),r&&!s&&Mt(t,e),!r&&s&&e.calculative.rotate&&"line"!==e.name&&Dt(t,e,!0),Et(t,e),e.type===o.Line&&e.fillTexts)for(const i of e.fillTexts)It(t,e,i);t.restore()}function Nt(t,e){const i=e.lineCap||(e.type?"round":"square");i?t.lineCap=i:e.type&&(t.lineCap="round")}function Bt(t,e){const i=e.lineJoin;i?t.lineJoin=i:e.type&&(t.lineJoin="round")}function Ft(t,e,i,n){t.save(),i&&t.translate(-i.x,-i.y),t.setAttrs?.(e);let r=!1;const s=e.calculative.canvas.store,a=e.textFlip||s.options.textFlip,l=e.textRotate||s.options.textRotate;let c;if(t.beginPath(),a&&l||t.save(),e.calculative.flipX&&(t.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),t.scale(-1,1)),e.calculative.flipY&&(t.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),t.scale(1,-1)),e.calculative.rotate&&"line"!==e.name&&Dt(t,e),(e.calculative.lineWidth>1||n)&&(t.lineWidth=e.calculative.lineWidth),e.calculative.hover)t.strokeStyle=e.hoverColor||s.options.hoverColor,t.fillStyle=e.hoverBackground||s.options.hoverBackground,c=e.hoverBackground||s.options.hoverBackground;else if(e.calculative.active)t.strokeStyle=e.activeColor||s.options.activeColor,t.fillStyle=e.activeBackground||s.options.activeBackground,c=e.activeBackground||s.options.activeBackground;else{if(e.strokeImage)e.calculative.strokeImg&&(t.strokeStyle=t.createPattern(e.calculative.strokeImg,"repeat"),c=!0);else{let i;e.calculative.strokeType&&e.calculative.lineGradientColors&&"line"===e.name?r=!0:i=e.calculative.color||Wt(s),t.strokeStyle=i}e.backgroundImage?e.calculative.backgroundImg&&(t.fillStyle=t.createPattern(e.calculative.backgroundImg,"repeat"),c=!0):(t.fillStyle=e.background,c=!!e.background)}if(Nt(t,e),Bt(t,e),ke(t,e),e.calculative.lineDash&&t.setLineDash(e.calculative.lineDash),e.calculative.lineDashOffset&&(t.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(t.shadowColor=e.calculative.shadowColor,t.shadowOffsetX=e.calculative.shadowOffsetX,t.shadowOffsetY=e.calculative.shadowOffsetY,t.shadowBlur=e.calculative.shadowBlur),r?(mt(t,e),Ht(!0,t,e,s)):(zt(!1,t,e,s,c),Te(t,e)),e.calculative.img?(t.save(),t.shadowColor="",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0,St(t,e),t.restore()):e.calculative.icon&&_t(t,e),a&&l||t.restore(),a&&!l&&(e.calculative.flipX&&(t.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),t.scale(-1,1)),e.calculative.flipY&&(t.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),t.scale(1,-1))),!a&&l&&e.calculative.rotate&&"line"!==e.name&&Dt(t,e,!0),Et(t,e),e.type===o.Line&&e.fillTexts)for(const i of e.fillTexts)It(t,e,i);t.restore()}function zt(t=!0,e,i,n,r){const s=t?n.path2dMap.get(i):B.path2dDraws[i.name];let a=null,l=null;if(i.type===o.Line&&(i.fromLineCap&&"butt"!==i.fromLineCap&&(e.lineCap="butt",a=new Path2D,a.moveTo(i.calculative.worldAnchors[0].x,i.calculative.worldAnchors[0].y),a.lineTo(i.calculative.worldAnchors[0].x,i.calculative.worldAnchors[0].y)),i.toLineCap&&"butt"!==i.toLineCap&&(e.lineCap="butt",l=new Path2D,l.moveTo(i.calculative.worldAnchors[i.calculative.worldAnchors.length-1].x,i.calculative.worldAnchors[i.calculative.worldAnchors.length-1].y),l.lineTo(i.calculative.worldAnchors[i.calculative.worldAnchors.length-1].x,i.calculative.worldAnchors[i.calculative.worldAnchors.length-1].y))),s){if(i.type===o.Line&&i.borderWidth){e.save(),e.beginPath();const t=i.calculative.lineWidth+i.calculative.borderWidth;e.lineWidth=t,e.strokeStyle=i.borderColor,a&&(e.save(),e.lineCap=i.fromLineCap,e.stroke(a),e.restore()),s instanceof Path2D?(r&&e.fill(s),t&&e.stroke(s)):(s(i,e),r&&e.fill(),t&&e.stroke()),l&&(e.save(),e.lineCap=i.toLineCap,e.stroke(l),e.restore()),e.restore()}s instanceof Path2D?i.type?i.close&&r&&e.fill(s):r&&e.fill(s):(e.save(),s(i,e),r&&e.fill(),e.restore());const t=i.calculative.progress;if(null!=t){e.save();const{ex:o,x:r,y:a,width:l,height:c,ey:h}=i.calculative.worldRect;let d=null;if(d=i.verticalProgress?i.reverseProgress?e.createLinearGradient(r,a,r,a+c*t):e.createLinearGradient(r,h,r,a+c*(1-t)):i.reverseProgress?e.createLinearGradient(o,a,r+l*(1-t),a):e.createLinearGradient(r,a,r+l*t,a),i.calculative.progressGradientColors){const{colors:t}=pt(i.calculative.progressGradientColors);t.forEach((t=>{d.addColorStop(t.i,t.color)}))}else{const t=i.calculative.progressColor||i.calculative.color||n.options.activeColor;d.addColorStop(0,t),d.addColorStop(1,t)}d.addColorStop(1,"transparent"),e.fillStyle=d,s instanceof Path2D?e.fill(s):(s(i,e),e.fill()),e.restore()}if(i.calculative.lineWidth&&(s instanceof Path2D?(n.options.svgPathStroke||"svgPath"!==i.name)&&(a&&(e.save(),e.lineCap=i.fromLineCap,e.stroke(a),e.restore()),e.stroke(s),l&&(e.save(),e.lineCap=i.toLineCap,e.stroke(l),e.restore())):(s(i,e),e.stroke())),i.type){if(i.calculative.animatePos){if(e.save(),jt(e,i,n),i.lineAnimateType===f.Arrow||i.lineAnimateType===f.WaterDrop){let t=Oi(i,e);t instanceof Path2D?(e.stroke(t),e.fill(t)):(e.stroke(),e.fill())}else s instanceof Path2D?(a&&!i.lineAnimateType&&(e.save(),e.lineCap=i.fromLineCap,e.stroke(a),e.restore()),e.lineCap=i.lineCap,e.stroke(s)):(s(i,e),e.stroke());e.restore()}i.fromArrow&&tt(e,i,n),i.toArrow&&et(e,i,n),!i.calculative.active||i.calculative.pencil||n.options.disableAnchor||n.data.locked||Ut(e,i)}}}function Ht(t=!0,e,i,n){const o=t?n.path2dMap.get(i):B.path2dDraws[i.name];if(o&&i.type){if(i.calculative.animatePos){if(e.save(),jt(e,i,n),e.beginPath(),o instanceof Path2D)if("polyline"===i.lineName||"line"===i.lineName)if(i.lineAnimateType===f.Arrow||i.lineAnimateType===f.WaterDrop){const t=Oi(i);e.stroke(t),e.fill(t)}else i.calculative.gradientSmooth||i.calculative.lineSmooth?(i.calculative.gradientAnimatePath||(i.calculative.gradientAnimatePath=kt(i)),i.calculative.gradientAnimatePath instanceof Path2D&&e.stroke(i.calculative.gradientAnimatePath)):e.stroke(o);else e.stroke(o);else o(i,e),e.stroke();e.restore()}i.fromArrow&&tt(e,i,n),i.toArrow&&et(e,i,n),!i.calculative.active||i.calculative.pencil||n.options.disableAnchor||n.data.locked||Ut(e,i)}}function jt(t,e,i){t.strokeStyle=e.animateColor||i.options.animateColor,e.animateShadow&&(t.shadowBlur=e.animateShadowBlur||e.animateLineWidth||6,t.shadowColor=e.animateShadowColor||e.animateColor||i.options.animateColor),e.calculative.animateLineWidth&&(t.lineWidth=e.calculative.animateLineWidth*i.data.scale);let n=0;switch(e.lineAnimateType){case f.Beads:e.animateReverse?t.lineDashOffset=e.calculative.animatePos:t.lineDashOffset=e.length-e.calculative.animatePos,n=e.calculative.lineWidth||5,n<5&&(n=5);const o=e.animateLineDash&&e.animateLineDash.map((t=>t*n/5));t.setLineDash(o||[n,2*n]);break;case f.Dot:e.animateReverse?t.lineDashOffset=e.calculative.animatePos:t.lineDashOffset=e.length-e.calculative.animatePos,n=e.calculative.animateDotSize||2*e.calculative.lineWidth||6,n<6&&(n=6),n>40&&(n=40),t.lineWidth=(e.calculative.animateLineWidth||n)*i.data.scale,t.setLineDash([.1,e.length]);break;case f.Arrow:case f.WaterDrop:t.fillStyle=e.animateColor||i.options.animateColor,t.lineWidth=1;break;default:e.animateReverse?(t.lineDashOffset=Number.EPSILON,t.setLineDash([0,e.length-e.calculative.animatePos+1,e.calculative.animatePos])):t.setLineDash([e.calculative.animatePos,e.length+.01-e.calculative.animatePos])}}function Wt(t){const{data:e,options:i}=t;return e.color||i.color}function Ut(t,e){const i=e.calculative.canvas.store;t.save(),t.lineWidth=1,t.fillStyle=e.activeColor||i.options.activeColor,e.calculative.worldAnchors.forEach((i=>{!i.hidden&&!i.isTemp&&function(t,e,i){if(!e)return;const n=i.calculative.canvas.store.activeAnchor===i.calculative.activeAnchor&&i.calculative.activeAnchor===e;let o=3;i.calculative.lineWidth>3&&(o=i.calculative.lineWidth),i.anchorRadius&&(o=i.anchorRadius),e.radius&&(o=e.radius),n?(e.prev&&(t.save(),t.strokeStyle="#4dffff",t.beginPath(),t.moveTo(e.prev.x,e.prev.y),t.lineTo(e.x,e.y),t.stroke(),t.restore(),t.save(),t.fillStyle="#ffffff",t.beginPath(),t.arc(e.prev.x,e.prev.y,o,0,2*Math.PI),t.fill(),t.stroke(),t.restore()),e.next&&(t.save(),t.strokeStyle="#4dffff",t.beginPath(),t.moveTo(e.x,e.y),t.lineTo(e.next.x,e.next.y),t.stroke(),t.restore(),t.save(),t.fillStyle="#ffffff",t.beginPath(),t.arc(e.next.x,e.next.y,o,0,2*Math.PI),t.fill(),t.stroke(),t.restore(),t.beginPath(),t.arc(e.x,e.y,o,0,2*Math.PI),t.fill(),t.stroke()),t.beginPath(),t.arc(e.x,e.y,o,0,2*Math.PI),t.fill(),t.stroke()):(t.save(),t.fillStyle="#ffffff",t.beginPath(),t.arc(e.x,e.y,o,0,2*Math.PI),t.fill(),t.stroke(),t.restore())}(t,i,e)})),t.restore()}function Vt(t){const e=t.calculative.canvas.store;let i={x:t.x,y:t.y};if(!t.parentId||t.parentId&&!e.pens[t.parentId])t.parentId=void 0,i.width=t.width,i.height=t.height,i.rotate=t.rotate,He(i),ze(i),t.pivot&&je(i,t.pivot);else{const n=e.pens[t.parentId];let o=n.calculative.worldRect;o||(o=Vt(n)),i.x=o.x+o.width*t.x,i.y=o.y+o.height*t.y,i.width=o.width*t.width,i.height=o.height*t.height,n.flipX&&(i.x=o.width-(i.x-o.x+i.width)+o.x),n.flipY&&(i.y=o.height-(i.y-o.y+i.height)+o.y),He(i),i.rotate=o.rotate+t.rotate,ze(i),t.pivot&&je(i,t.pivot)}return t.calculative.worldRect=i,qt(t,i),i}function qt(t,e){!t.paddingTop&&(t.calculative.paddingTop=0),!t.paddingBottom&&(t.calculative.paddingBottom=0),!t.paddingLeft&&(t.calculative.paddingLeft=0),!t.paddingRight&&(t.calculative.paddingRight=0),Math.abs(t.calculative.paddingTop)<1&&(t.calculative.paddingTop*=e.height),Math.abs(t.calculative.paddingBottom)<1&&(t.calculative.paddingBottom*=e.height),Math.abs(t.calculative.paddingLeft)<1&&(t.calculative.paddingLeft*=e.width),Math.abs(t.calculative.paddingRight)<1&&(t.calculative.paddingRight*=e.width)}function Kt(t){const e=Q(t.calculative.worldRect);if(delete e.pivot,!t.parentId)return void Object.assign(t,e);const i=t.calculative.canvas.store.pens[t.parentId].calculative.worldRect;Object.assign(t,Ge(e,i))}function Yt(t){const e=t.calculative.canvas.store;let i=[];if(t.anchors){let e=Q(t.anchors);t.flipX&&e.forEach((t=>{t.x=.5-(t.x-.5)})),t.flipY&&e.forEach((t=>{t.y=.5-(t.y-.5)})),e.forEach((e=>{i.push(function(t,e){const i={...e},{x:n,y:o,width:r,height:s}=t.calculative.worldRect;return i.x=n+r*e.x,i.y=o+s*e.y,e.prev&&(i.prev={penId:t.id,connectTo:e.prev.connectTo,x:n+r*e.prev.x,y:o+s*e.prev.y}),e.next&&(i.next={penId:t.id,connectTo:e.next.connectTo,x:n+r*e.next.x,y:o+s*e.next.y}),i}(t,e))}))}if(!i.length&&!t.type&&!t.calculative.canvas.parent.isCombine(t)){const{x:n,y:o,width:r,height:s}=t.calculative.worldRect;i=e.options.defaultAnchors.map(((e,i)=>({id:`${i}`,penId:t.id,x:n+r*e.x,y:o+s*e.y})))}t.calculative.rotate&&i.forEach((e=>{P(e,t.calculative.rotate,t.calculative.worldRect.pivot||t.calculative.worldRect.center)})),t.type&&!t.anchors||(t.calculative.worldAnchors=i),t.calculative.activeAnchor&&i.length&&(t.calculative.activeAnchor=i.find((e=>{e.id,t.calculative.activeAnchor.id}))),t.calculative.gradientAnimatePath=void 0}function $t(t){if(t.children?.length){let e=t.calculative.worldRect;t.children.forEach((i=>{const n=t.calculative.canvas.store.pens[i];n.calculative.initRect&&n.calculative.initRelativeRect&&(n.calculative.initRect.x=e.x+e.width*n.calculative.initRelativeRect.x,n.calculative.initRect.y=e.y+e.height*n.calculative.initRelativeRect.y,n.calculative.initRect.ex=n.calculative.initRect.x+e.width*n.calculative.initRelativeRect.width,n.calculative.initRect.ey=n.calculative.initRect.y+e.height+n.calculative.initRelativeRect.height,ze(n.calculative.initRect)),$t(n)}))}}function Xt(t,e){const{paddingTop:i,paddingBottom:n,paddingLeft:o,paddingRight:r}=e.calculative;let s=o,a=i,l=e.calculative.worldRect.width-o-r,c=e.calculative.worldRect.height-i-n,h=e.calculative.iconLeft,d=e.calculative.iconTop;h&&Math.abs(h)<1&&(h=e.calculative.worldRect.width*h),d&&Math.abs(d)<1&&(d=e.calculative.worldRect.height*d),s+=h||0,a+=d||0,l-=h||0,c-=d||0;let u=e.calculative.iconRotate||0;if(e.parentId){const i=t[e.parentId].calculative;i&&(u+=i.rotate,u%=360)}s=e.calculative.worldRect.x+s,a=e.calculative.worldRect.y+a,e.calculative.worldIconRect={x:s,y:a,width:l,height:c,rotate:u},He(e.calculative.worldIconRect),ze(e.calculative.worldIconRect)}function Gt(t,e,i){Xe(t.calculative.worldRect,e,i,t.pivot),t.calculative.initRect&&Xe(t.calculative.initRect,e,i,t.pivot),Qt(t,e,i),t.calculative.x&&I(t.calculative,e,i),t.type&&Yt(t)}function Qt(t,e,i){t.children?.length&&t.children.forEach((n=>{const o=t.calculative.canvas.store.pens[n];o&&o.calculative.initRect&&Xe(o.calculative.initRect,e,i),Qt(o,e,i)}))}function Jt(t,e){if(!e||!e.calculative||!e.calculative.worldRect.center)return x.None;if(t.anchorId){let i=e.anchors.filter((e=>e.id===t.anchorId));if(i.length&&i[0].direction>-1)return i[0].direction}return function(t,e){let i=x.None;if(!e)return i;const n=t.x-e.x,o=t.y-e.y;return i=Math.abs(n)>Math.abs(o)?n>0?x.Right:x.Left:o>0?x.Bottom:x.Up,i}(t,e.calculative.worldRect.center)}function Zt(t,e){let i,n=1/0;return t.calculative.worldAnchors.forEach((t=>{const o=L(e,t);n>o&&(n=o,i=t)})),i}function te(t,e,i){t.x+=e,t.y+=i,t.anchors&&t.anchors.forEach((t=>{M(t,e,i)})),t.calculative.worldAnchors&&t.calculative.worldAnchors.forEach((t=>{M(t,e,i)}))}function ee(t){if(t&&t.calculative&&t.calculative.worldAnchors.length){let e=se(t);if(t.anchors&&t.anchors.length)e===t.calculative.activeAnchor?t.calculative.worldAnchors=[t.calculative.worldAnchors[0]]:t.calculative.worldAnchors[0]===t.calculative.activeAnchor&&(t.calculative.worldAnchors=[t.calculative.worldAnchors[t.calculative.worldAnchors.length-1]]);else for(;t.calculative.worldAnchors.length&&e!==t.calculative.activeAnchor;)t.calculative.worldAnchors.pop(),e=se(t)}}function ie(t,e,i,n){if(!(t&&e&&i&&n&&e.twoWay!==R.DisableConnected&&e.twoWay!==R.Disable&&n.twoWay!==R.DisableConnectTo&&n.twoWay!==R.Disable))return;if(e.twoWay===R.In){if(1===i.calculative.worldAnchors.length)return;const t=se(i);if(n.id!==t.id)return}if(e.twoWay===R.Out){const t=re(i);if(n.id!==t.id)return}if(n.connectTo===t.id&&n.anchorId===e.id)return;if(n.connectTo){const e=t.calculative.canvas.store.pens[n.connectTo];ne(e,oe(e,n.anchorId),i,n)}t.connectedLines||(t.connectedLines=[]),t.connectedLines.findIndex((t=>t.lineId===i.id&&t.lineAnchor===n.id&&t.anchor===e.id))<0&&t.connectedLines.push({lineId:i.id,lineAnchor:n.id,anchor:e.id}),n.connectTo=t.id,n.anchorId=e.id,t.type&&ie(i,n,t,e),t.calculative.canvas.store.emitter.emit("connectLine",{line:i,lineAnchor:n,pen:t,anchor:e});let o=i.calculative.worldAnchors?.length>=2?i.calculative.worldAnchors?.[0].connectTo:void 0,r=i.calculative.worldAnchors?.length>=2?i.calculative.canvas.store.pens[i.calculative.worldAnchors?.[0].connectTo]?.anchors.find((t=>t.id===i.calculative.worldAnchors?.[0].anchorId)):void 0;return t.onConnectLine?.(t,{line:i,lineAnchor:n,pen:t,anchor:e,fromPen:o,fromAnchor:r}),!0}function ne(t,e,i,n){if(t&&e&&i&&n&&t.connectedLines&&t.connectedLines.length)return i.lastConnected||(i.lastConnected={}),i.lastConnected[t.id]||(i.lastConnected[t.id]=Q(t.connectedLines)),t.connectedLines.forEach(((t,o,r)=>{t.lineId!==i.id&&t.lineId!==i.id||t.lineAnchor!==n.id||t.anchor!==e.id||r.splice(o,1)})),n.connectTo=void 0,n.anchorId=void 0,t.type&&e.connectTo===i.id&&e.anchorId===n.id&&ne(i,n,t,e),t.calculative.canvas.store.emitter.emit("disconnectLine",{line:i,lineAnchor:n,pen:t,anchor:e}),!0}function oe(t,e){if(t&&e)return t.calculative.worldAnchors?.find((t=>t.id===e))}function re(t){if(t&&t.calculative.worldAnchors)return t.calculative.worldAnchors[0]}function se(t){if(t&&t.calculative.worldAnchors)return t.calculative.worldAnchors[t.calculative.worldAnchors.length-1]}function ae(t,e){if(0===t.calculative.start||!t.frames||!t.frames.length)return t.calculative.start=void 0,0;if(!t.calculative.duration){t.calculative.duration=0;for(const e of t.frames){t.calculative.duration+=e.duration;for(const i in e)"duration"===i||t[i]||"scale"===i&&(t[i]=1)}}if(t.animateCycle||(t.animateCycle=1/0),t.calculative.start){let i=0;const n=Math.ceil((e-t.calculative.start)/t.calculative.duration);if(n>t.animateCycle)return t.currentAnimation=void 0,t.calculative.start=void 0,ce(t,1),0;const o=(e-t.calculative.start)%t.calculative.duration;let r=0;for(const e of t.frames){if(r+=e.duration,!(o>r))break;++i}if(!t.frames[i])return!0;t.calculative.frameDuration=t.frames[i].duration,t.calculative.frameStart=t.calculative.start+t.calculative.duration*(n-1),t.calculative.frameEnd=t.calculative.frameStart+t.calculative.frameDuration;const s=i!==t.calculative.frameIndex,a=n>t.calculative.cycleIndex;if(s&&(t.calculative.frameIndex=i),a&&(t.calculative.cycleIndex=n),s||a)if(t.calculative.x=t.calculative.initRect.x,t.calculative.y=t.calculative.initRect.y,t.children?.length&&!t.parentId?t.calculative.canvas.rotatePen(t,(t.calculative.initRect.rotate||0)-(t.calculative.rotate||0),t.calculative.initRect):t.calculative.rotate=t.calculative.initRect.rotate||0,i>0){t.prevFrame={};const e=t.frames[i-1];for(const i in e)t.prevFrame[i]=e[i];Object.assign(t.prevFrame,{rotate:e.rotate||0,x:e.x||0,y:e.y||0,scale:e.scale||1})}else le(t)}else{if(t.calculative.start=e,t.calculative.frameIndex=0,t.calculative.frameStart=t.calculative.start,t.calculative.frameDuration=t.frames[0].duration,t.calculative.frameEnd=t.calculative.frameStart+t.calculative.frameDuration,t.calculative.cycleIndex=1,t.calculative.x=t.calculative.worldRect.x,t.calculative.y=t.calculative.worldRect.y,t.calculative.initRect=Q(t.calculative.worldRect),t.parentId&&(t.calculative.initRelativeRect={x:t.x,y:t.y,width:t.width,height:t.height}),t.children?.length){const e=t.calculative.canvas.store;t.calculative.childrenVisible={},t.children.forEach((i=>{t.calculative.childrenVisible[i]=e.pens[i].visible}))}t.calculative.initRect.rotate=t.calculative.rotate||0,le(t)}const i=(e-t.calculative.frameStart)/t.calculative.frameDuration%1;return ce(t,i),!0}function le(t){t.prevFrame={};for(const e in t)"object"==typeof t[e]&&"lineDash"!==e||(t.prevFrame[e]=t[e]);t.prevFrame.rotate=0,t.prevFrame.x=0,t.prevFrame.y=0,t.prevFrame.scale=1}function ce(t,e){if(e<0)return;e>1&&(e=1);const i=t.frames[t.calculative.frameIndex];for(const n in i)if("duration"!==n){if("scale"===n){t.calculative.worldRect=Q(t.calculative.initRect),Xe(t.calculative.worldRect,t.prevFrame.scale,t.calculative.worldRect.center);const o=t.prevFrame.scale+(i[n]-t.prevFrame.scale)*e;Xe(t.calculative.worldRect,o/t.prevFrame.scale,t.calculative.worldRect.center),t.calculative.patchFlags=!0}else if("x"===n){const o=we(t,n,t.calculative.frameIndex);t.calculative.worldRect.x=t.calculative.initRect.x+o,t.calculative.worldRect.ex=t.calculative.initRect.ex+o,Ke(t.calculative.worldRect,i[n]*e*t.calculative.canvas.store.data.scale,0),t.calculative.patchFlags=!0}else if("y"===n){const o=we(t,n,t.calculative.frameIndex);t.calculative.worldRect.y=t.calculative.initRect.y+o,t.calculative.worldRect.ey=t.calculative.initRect.ey+o,Ke(t.calculative.worldRect,0,i[n]*e*t.calculative.canvas.store.data.scale),t.calculative.patchFlags=!0}else if("rotate"===n){t.prevFrame[n]>=360&&(t.prevFrame[n]%=360);const o=we(t,n,t.calculative.frameIndex),r=(t.calculative.initRect.rotate+o+i[n]*e)%360-(t.calculative.rotate||0);t.children?.length?t.calculative.canvas.rotatePen(t,r,t.calculative.initRect):t.calculative.rotate=(t.calculative.initRect.rotate+o+i[n]*e)%360,t.calculative.patchFlags=!0}else if("image"===n)t.image=i.image,t.calculative.image=void 0,t.calculative.canvas.loadImage(t),t.canvasLayer===l.CanvasImageBottom?t.calculative.canvas.canvasImageBottom.init():t.canvasLayer===l.CanvasImage&&t.calculative.canvas.canvasImage.init();else if(he(i[n],n,t)){null==t.prevFrame[n]&&(t.prevFrame[n]="globalAlpha"===n?1:0);const o=t.prevFrame[n]+(i[n]-t.prevFrame[n])*e;t.calculative[n]=Math.round(100*o)/100}else{if("visible"===n)if(t.calculative.image)t.canvasLayer===l.CanvasImageBottom?t.calculative.canvas.canvasImageBottom.init():t.canvasLayer===l.CanvasImage&&t.calculative.canvas.canvasImage.init();else if(t.children?.length){const e=dt(t,t.calculative.canvas.store);t.calculative.canvas.initImageCanvas(e)}t.calculative[n]=i[n];const e={};e[n]=i[n],Re(t,e)}"text"===n&&Y(t)}}function he(t,e,i){return"number"==typeof t&&!1!==i.linear&&!["strokeType","bkType","showChild"].includes(e)}function de(t,e){if(0===t.calculative.start)return t.calculative.start=void 0,0;if(t.animateCycle||(t.animateCycle=1/0),t.animateSpan||(t.animateSpan=1),t.calculative.animatePos+=t.animateSpan*(t.calculative.canvas.store.data.scale||1),t.calculative.start){if(t.calculative.animatePos>t.length){if(++t.calculative.cycleIndex,t.calculative.cycleIndex>t.animateCycle)return t.currentAnimation=void 0,t.calculative.start=void 0,0;t.calculative.animatePos=t.animateSpan}}else t.calculative.start=Date.now(),t.calculative.animatePos=t.animateSpan*(t.calculative.canvas.store.data.scale||1),t.calculative.cycleIndex=1;return!0}function ue(t,e=!0){if(!t.children)return;const i=t.calculative.canvas.store;t.children.forEach((t=>{const n=i.pens[t];n&&(n.calculative.active=e,ue(n,e))}))}function fe(t,e=!0){if(!t)return;const i=t.calculative.canvas.store;t.calculative.hover=e,t.children&&t.children.forEach((t=>{null==i.pens[t]?.hoverColor&&null==i.pens[t]?.hoverBackground&&fe(i.pens[t],e)}))}function pe(t,e){if(!e)return;const i=t.calculative.canvas.store,n=t.calculative.worldRect;e.style.opacity=t.globalAlpha+"",e.style.position="absolute",e.style.outline="none",e.style.left=n.x+i.data.x+"px",e.style.top=n.y+i.data.y+"px",e.style.width=n.width+"px",e.style.height=n.height+"px",e.style.display=0!=t.calculative.inView?t.calculative.cssDisplay||"inline":"none",!t.calculative.rotate&&(t.calculative.rotate=0),e.style.transform=`rotate(${t.calculative.rotate}deg)`,t.calculative.rotate||(t.calculative.flipX&&(e.style.transform="rotateY(180deg)"),t.calculative.flipY&&(e.style.transform="rotateX(180deg)"),t.calculative.flipX&&t.calculative.flipY&&(e.style.transform="rotateZ(180deg)")),e.style.zIndex=void 0!==t.calculative.zIndex?t.calculative.zIndex+"":"5",t.calculative.zIndex>t.calculative.canvas.maxZindex&&(t.calculative.canvas.maxZindex=t.calculative.zIndex),t.locked===r.DisableEdit||t.locked===r.DisableMove||i.data.locked?(e.style.userSelect="initial",e.style.pointerEvents="initial","gif"===t.name&&(e.style.userSelect="none",e.style.pointerEvents="none")):(e.style.userSelect="none",e.style.pointerEvents="none")}function ve(t){return t.every((t=>t.locked))}function ge(t){return t.every((t=>t.disableRotate))}function ye(t,e,i){t.type?(t.calculative.worldAnchors.forEach((t=>{P(t,e,i.center)})),function(t){if(!t.calculative.worldAnchors?.length)return;if(!isFinite(t.x)||!isFinite(t.x))return;if(null==t.x||null==t.y)return;const e=mi(t);t.parentId||Object.assign(t,e);const{fontSize:i,lineHeight:n}=t.calculative.canvas.store.options;t.fontSize||(t.fontSize=i,t.calculative.fontSize=t.fontSize*t.calculative.canvas.store.data.scale),t.lineHeight||(t.lineHeight=n,t.calculative.lineHeight=t.lineHeight),ze(e),t.calculative.worldRect=e,qt(t,e),q(t),t.calculative.worldAnchors&&(t.anchors=t.calculative.worldAnchors.map((e=>Qe(e,t.calculative.worldRect))))}(t),Kt(t)):(t.calculative.rotate?t.calculative.rotate+=e:t.calculative.rotate=e,P(t.calculative.worldRect.center,e,i.center),t.parentId&&(t.calculative.worldRect.x=t.calculative.worldRect.center.x-t.calculative.worldRect.width/2,t.calculative.worldRect.y=t.calculative.worldRect.center.y-t.calculative.worldRect.height/2,t.x=(t.calculative.worldRect.x-i.x)/i.width,t.y=(t.calculative.worldRect.y-i.y)/i.height)),t.children?.forEach((n=>{ye(t.calculative.canvas.store.pens[n],e,i)}))}function me(t){return t.every((t=>t.disableSize||t.pivot))}function we(t,e,i){if(!t.frames||!e)return 0;let n=0;for(let o=0;o{const e=i.pens[t];e&&be(e,!0)})),t.calculative.inView=!0,xe(t,i)&&0!=t.visible&&0!=t.calculative.visible){const{x:e,y:o,width:r,height:s,rotate:a}=t.calculative.worldRect,l={x:e+i.data.x,y:o+i.data.y,width:r,height:s,rotate:a};He(l),qe(l,n)||(t.calculative.inView=!1)}else t.calculative.inView=!1;t.calculative.singleton?.div&&pe(t,t.calculative.singleton.div)}function ke(t,e){const i=e.calculative.globalAlpha;"number"==typeof i&&i<1&&!isNaN(i)&&(t.globalAlpha=i)}function Te(t,e){const i=function(t,e){const i=e.drawCommand;if(i&&"line"!==e.name)return(t,e)=>{i.forEach((i=>{try{i.steps.reduce(((i,n)=>{const o=function(t,e,i,n){return{visio:Ce,dxf:Ae}[e.parseType](t,e,i,n)}(n,e,i.x,i.y);try{if(o.c){let e=[];for(const t in o.v)e.push(o.v[t]);return t[o.c](...e),t.moveTo(o.startX||o.v.x,o.startY||o.v.y),{x:o.startX||o.v.x,y:o.startY||o.v.y}}return{x:i.x,y:i.y}}catch(t){}}),{})}catch(t){}})),t.stroke()}}(0,e)||B.canvasDraws[e.name];i&&(t.save(),i(t,e),t.restore())}function Ae(t,e,i,n){const{x:o,y:r,width:s,height:a}=e.calculative.worldRect;switch(t.c){case"moveTo":return{c:"moveTo",v:{x:t.v.x*e.calculative.canvas.store.data.scale,y:window.innerHeight-t.v.y*e.calculative.canvas.store.data.scale}};case"lineTo":return{c:"lineTo",v:{x:t.v.x*e.calculative.canvas.store.data.scale,y:window.innerHeight-t.v.y*e.calculative.canvas.store.data.scale}};case"arc":return{c:"arc",v:{x:t.v.x*e.calculative.canvas.store.data.scale,y:window.innerHeight-t.v.y*e.calculative.canvas.store.data.scale,r:t.v.r*e.calculative.canvas.store.data.scale,startAngle:t.v.startAngle,endAngle:t.v.endAngle}}}return t}function Ce(t,e,i,n){const{x:o,y:r,width:s,height:a}=e.calculative.worldRect,{width:l,height:c}=e.origin;switch(t.c){case"MoveTo":return{c:"moveTo",v:{x:100*+t.v.X*(s/l)+o,y:100*+t.v.Y*(a/c)+r}};case"RelMoveTo":return{c:"moveTo",v:{x:+t.v.X*l*(s/l)+o,y:+t.v.Y*c*(a/c)+r}};case"LineTo":return{c:"lineTo",v:{x:100*+t.v.X*(s/l)+o,y:100*+t.v.Y*(a/c)+r}};case"RelLineTo":return{c:"lineTo",v:{x:+t.v.X*l*(s/l)+o,y:+t.v.Y*c*(a/c)+r}};case"Ellipse":return{c:"ellipse",v:{x:100*t.v.X*(s/l)+o,y:100*t.v.Y*(a/c)+r,radiuX:100*Math.abs(t.v.A-t.v.C)*(s/l),radiuY:100*Math.abs(t.v.B-t.v.D)*(a/c),rotation:0,startAngle:0,endAngle:2*Math.PI,anticlockwise:!0}};case"EllipticalArcTo":const e=100*t.v.X*(s/l)+o,h=100*t.v.Y*(a/c)+r,d=100*t.v.A*(s/l)+o,u=100*t.v.B*(a/c)+r,f=t.v.C,p=function(t,e,i,n,o,r,s){let a=((t-i)*(t+i)*(n-r)-(i-o)*(i+o)*(e-n)+s*s*(e-n)*(n-r)*(e-r))/(2*((t-i)*(n-r)-(i-o)*(e-n))),l=((t-i)*(i-o)*(t-o)+s*s*((i-o)*(e-n)*(e+n)-(t-i)*(n-r)*(n+r)))/(2*s*s*((i-o)*(e-n)-(t-i)*(n-r))),c=Math.sqrt(Math.pow(t-a,2)+Math.pow(s*(e-l),2));return{x0:a,y0:l,a:c,b:c/s}}(i,n,e,h,d,u,t.v.D*(s/a)*(c/l));return!t.orign&&(t.orign={}),!t.orign.startA&&(t.orign.startA=Se(p.x0,p.y0,i,n)),!t.orign.endA&&(t.orign.endA=Se(p.x0,p.y0,e,h)),{c:"ellipse",v:{centerX:p.x0,centerY:p.y0,radiuX:p.a,radiuY:p.b,rotation:0,startAngle:t.orign.startA,endAngle:t.orign.endA,anticlockwise:+f<0},startX:e,startY:h};case"ArcTo":let v=100*t.v.X*s/l+o,g=100*t.v.Y*a/c+r,y=100*t.v.A*(s/a)*(c/l),m=(i+v)/2,w=(n+g)/2,x=Math.sqrt((v-i)**2+(g-n)**2),b=x**2/(8*y)+y/2,k=m+-(g-n)/x*b,T=w+(v-i)/x*b;return{c:"arc",v:{x:k,y:T,radius:b,startAngle:Math.atan2(n-T,i-k),endAngle:Math.atan2(g-T,v-k),aclockwise:!0}};default:return{}}}function Re(t,e){for(const i in e)A.includes(i)&&(t[i]=e[i],["fontSize","lineWidth"].includes(i)?(t.calculative[i]=e[i]*t.calculative.canvas.store.data.scale,q(t)):t.calculative[i]=e[i]);if(t.calculative.canvas.parent.isCombine(t)){const i=t.children;i?.forEach((i=>{let n=Q(e);t.calculative.childrenVisible&&!1===t.calculative.childrenVisible[i]&&delete n.visible;const o=t.calculative.canvas.store.pens[i];o&&Re(o,n)}))}}function Se(t,e,i,n){let o=i-t,r=n-e,s=Math.atan2(r,o);return s<0&&(s+=2*Math.PI),s}function Pe(t,e,i){let n,o,r=1/0,s=1/0;for(const a of t.data.pens)!1!==a.calculative.inView&&Ie(a).forEach((t=>{if(t===e||t===i)return;let l=(a.calculative.worldRect.center.x-e.x)*(a.calculative.worldRect.center.x-e.x)+(a.calculative.worldRect.center.y-e.y)*(a.calculative.worldRect.center.y-e.y);const c=Math.abs(t.x-e.x);c>0&&c<8&&l0&&h<8&&l{t.x+=n.x,t.y+=n.y}))):(ze(e),o=[e.center,...Ue(e)]),Le(t,o,e,!0)}function Ie(t){if(!t.type){const e=Ue(t.calculative.worldRect);return ze(t.calculative.worldRect),[...t.calculative.worldAnchors,...e,t.calculative.worldRect.center]}if(t.type===o.Line)return t.calculative.worldAnchors}function _e(t,e,i,n){return Le(t,Ue(e),e)}function Le(t,e,i,n=!1){let o,r,s=1/0,a=1/0;const l=function(t,e){const i=lt(10),n={x:t.x-i[3],y:t.y-i[0],width:t.width+i[1]+i[3],height:t.height+i[0]+i[2]};return He(n),n}(i);return t.data.pens.forEach((c=>{const{inView:h,worldRect:d,active:u}=c.calculative;if(!1===h||!n&&u||(f=l,((p=d).x>f.ex||p.exf.ey||p.eyMe(t,e,c))))return;var f,p;const v=Ie(c);if(v)for(const t of v)for(const n of e){const e=t.x-n.x,l=t.y-n.y,h=Math.abs(e),d=Math.abs(l);i.center||(i.center={x:i.x+i.width/2,y:i.y+i.height/2}),h<10&&h{if(e.has(i)&&e.get(i)?t=e.get(i):e.set(i,t=new Map),"function"!=typeof o)return()=>{console.warn("[rewritePenLifeCycle] warn: not a function ")};let s=new Set,a=new Map;t.has(n)&&t.get(n)?s=t.get(n):(a.set(n,i[n]),t.set(n,s)),r?s.delete(o):s.add(o);let l=a.get(n);i[n]=(...t)=>{l?.(...t),s.forEach((e=>{e(...t)}))}}}();function Be(t,e){if(!e)return;if(null==e.ex&&He(e),!e.rotate||e.rotate%360==0)return t.x>e.x&&t.xe.y&&t.y{P(t,e.rotate,e.pivot||e.center)})),function(t,e){if(e.length<3)return!1;let i=!1,n=e[e.length-1];for(const o of e)n.y>t.y!=o.y>t.y&&o.x+(t.y-o.y)*(n.x-o.x)/(n.y-o.y)>t.x&&(i=!i),n=o;return i}(t,i)}function Fe(t,e,i=0){const{x:n,y:o,ex:r,ey:s}=e;return t.x>=n-i&&t.x<=r+i&&t.y>=o-i&&t.y<=s+i}function ze(t){t.center||(t.center={}),t.center.x=t.x+t.width/2,t.center.y=t.y+t.height/2}function He(t){t.ex=t.x+t.width,t.ey=t.y+t.height}function je(t,e){t.pivot||(t.pivot={}),t.pivot.x=t.x+t.width*e.x,t.pivot.y=t.y+t.height*e.y}function We(t){const e=[];t.forEach((t=>{if(t.isRuleLine)return;const i=t.calculative.worldRect;if(i){const t=Ue(i);e.push(...t)}}));const i=Ve(e);return ze(i),i}function Ue(t){const e=[{x:t.x,y:t.y},{x:t.ex,y:t.y},{x:t.ex,y:t.ey},{x:t.x,y:t.ey}];return t.rotate&&(t.center||ze(t),e.forEach((e=>{P(e,t.rotate,t.pivot||t.center)}))),e}function Ve(t){let e=1/0,i=1/0,n=-1/0,o=-1/0;return t?.forEach((t=>{isFinite(t.x)&&isFinite(t.y)&&(e=Math.min(e,t.x),i=Math.min(i,t.y),n=Math.max(n,t.x),o=Math.max(o,t.y))})),{x:e,y:i,ex:n,ey:o,width:n-e,height:o-i}}function qe(t,e,i){return t.rotate&&(t=Ve(Ue(t))),i?t.x>e.x&&t.exe.y&&t.eye.ex||t.exe.ey)}function Ke(t,e,i){t.x+=e,t.y+=i,t.ex+=e,t.ey+=i,t.center&&(t.center.x+=e,t.center.y+=i),t.pivot&&(t.pivot.x+=e,t.pivot.y+=i)}function Ye(t,e){if(De(t.k,0))return{x:e.point.x,y:t.point.y};if(De(e.k,0))return{x:t.point.x,y:e.point.y};const i=t.point.y-t.k*t.point.x,n=(e.point.y-e.k*e.point.x-i)/(t.k-e.k);return{x:n,y:t.k*n+i}}function $e(t,e,i,n){let o=t.rotate?t.rotate%360:0;if(o){const r=Ue(t),s=(r[0].y-r[1].y)/(r[0].x-r[1].x),a=(r[1].y-r[2].y)/(r[1].x-r[2].x);if(n<4){if(r[n].x+=e,t.ratio)if(0===n||2===n){let i=e*Math.tan((90-(360-o)-Math.atan(t.width/t.height)/Math.PI*180)/180*Math.PI);r[n].y+=i}else{let i=e*Math.tan((90-(360-o)+Math.atan(t.width/t.height)/Math.PI*180)/180*Math.PI);r[n].y+=i}else r[n].y+=i;const l=r[(n+2)%4];r[(n+1)%4]=Ye({k:n%2?a:s,point:r[n]},{k:n%2?s:a,point:l}),r[(n+4-1)%4]=Ye({k:n%2?s:a,point:r[n]},{k:n%2?a:s,point:l})}else{const t=[4,6].includes(n)?a:s;De(t,0)?(r[n%4].x+=e,r[(n+1)%4].x+=e):(r[n%4].y+=i,r[n%4].x+=i/t,r[(n+1)%4].y+=i,r[(n+1)%4].x+=i/t)}if((r[0].x-r[1].x)**2+(r[0].y-r[1].y)**2<25||(r[1].x-r[2].x)**2+(r[1].y-r[2].y)**2<25)return;const l=function(t,e){const i=function(t,e){const i=(t.to.y-t.from.y)/(t.to.x-t.from.x),n=(e.to.y-e.from.y)/(e.to.x-e.from.x);return Ye({k:i,point:t.from},{k:n,point:e.from})}({from:t[0],to:t[2]},{from:t[1],to:t[3]});for(const n of t)P(n,-e,i);return Ve(t)}(r,t.rotate);return ze(l),void Object.assign(t,l)}switch(n){case 0:if(t.width-e<5||t.height-i<5)break;t.x+=e,t.y+=i,t.width-=e,t.height-=i;break;case 1:if(t.width+e<5||t.height-i<5)break;t.ex+=e,t.y+=i,t.width+=e,t.height-=i;break;case 2:if(t.width+e<5||t.height+i<5)break;t.ex+=e,t.ey+=i,t.width+=e,t.height+=i;break;case 3:if(t.width-e<5||t.height+i<5)break;t.x+=e,t.ey+=i,t.width-=e,t.height+=i;break;case 4:if(t.height-i<5)break;t.y+=i,t.height-=i;break;case 5:if(t.width+e<5)break;t.ex+=e,t.width+=e;break;case 6:if(t.height+i<5)break;t.ey+=i,t.height+=i;break;case 7:if(t.width-e<5)break;t.x+=e,t.width-=e}}function Xe(t,e,i,n){t&&(t.width*=e,t.height*=e,I(t,e,i),He(t),ze(t),n&&je(t,n))}function Ge(t,e){const i={x:(t.x-e.x)/e.width,y:(t.y-e.y)/e.height,width:t.width/e.width,height:t.height/e.height};return He(i),i}function Qe(t,e){const{x:i,y:n,width:o,height:r}=e,{penId:s,connectTo:a}=t,l=Object.assign({},t,{x:o?(t.x-i)/o:0,y:r?(t.y-n)/r:0});return t.prev&&(l.prev={penId:s,connectTo:a,x:o?(t.prev.x-i)/o:0,y:r?(t.prev.y-n)/r:0}),t.next&&(l.next={penId:s,connectTo:a,x:o?(t.next.x-i)/o:0,y:r?(t.next.y-n)/r:0}),l}function Je(t,e){let i=!1;for(let n=0,o=e.length-1;nt.y!=l>t.y&&t.x<(a-r)*(t.y-s)/(l-s)+r&&(i=!i)}return i}const Ze=/^[\t\n\f\r ]*([MLHVZCSQTAmlhvzcsqta])[\t\n\f\r ]*/,ti=/^[01]/,ei=/^[+-]?(([0-9]*\.[0-9]+)|([0-9]+\.)|([0-9]+))([eE][+-]?[0-9]+)?/,ii=/^(([\t\n\f\r ]+,?[\t\n\f\r ]*)|(,[\t\n\f\r ]*))/,ni={M:[ei,ei],L:[ei,ei],H:[ei],V:[ei],Z:[],C:[ei,ei,ei,ei,ei,ei],S:[ei,ei,ei,ei],Q:[ei,ei,ei,ei],T:[ei,ei],A:[ei,ei,ei,ti,ti,ei,ei]};function oi(t){let e=1/0,i=1/0,n=-1/0,o=-1/0;return function(t){let e,i=0,n=0;t.commands.forEach((t=>{switch(t.key){case"Z":case"z":t.worldPoints=[i,n];break;case"H":t.worldPoints=[t.values[0],e.worldPoints[e.worldPoints.length-1]];break;case"h":t.worldPoints=[t.values[0]+e.worldPoints[e.worldPoints.length-2],e.worldPoints[e.worldPoints.length-1]];break;case"V":t.worldPoints=[e.worldPoints[e.worldPoints.length-2],t.values[0]];break;case"v":case"A":t.worldPoints=[e.worldPoints[e.worldPoints.length-2],t.values[0]+e.worldPoints[e.worldPoints.length-1]];break;default:!function(t,e){const i=[];let n=t.relative&&e?{x:e.worldPoints[e.worldPoints.length-2],y:e.worldPoints[e.worldPoints.length-1]}:{x:0,y:0};for(let e=0;e{t.worldPoints.forEach(((t,r)=>{r%2==0?(tn&&(n=t)):(to&&(o=t))}))})),--e,--i,{x:e,y:i,ex:n,ey:o,width:n-e+1,height:o-i+1}}function ri(t,e,i){const n=ni[t.toUpperCase()],o=[];for(;i<=e.length;){const r={key:t,values:[]};for(const t of n){const n=e.slice(i).match(t);if(null===n){if(0===r.values.length)return{cursor:i,commands:o};throw new Error("malformed path (first error at "+i+")")}{r.values.push(+n[0]),i+=n[0].length;const t=e.slice(i).match(ii);null!==t&&(i+=t[0].length)}}if(r.relative=r.key.toUpperCase()!==r.key,o.push(r),0===n.length)return{cursor:i,commands:o};"m"===t&&(t="l"),"M"===t&&(t="L")}throw new Error("malformed path (first error at "+i+")")}function si(t,e){const i=t.calculative.canvas.store.data.paths[t.pathId];if(!i)return new Path2D;const n=function(t){let e=0;const i=[];for(;e{switch(t.key){case"A":case"a":const n=t.values[0],o=t.values[1],r=Math.PI*t.values[2]/180,s=Math.cos(r),a=Math.sin(r),l=o*o*i*i*s*s+n*n*i*i*a*a,c=2*e*i*s*a*(o*o-n*n),h=n*n*e*e*s*s+o*o*e*e*a*a,d=-n*n*o*o*e*e*i*i,u=c*c-4*l*h,f=Math.sqrt((l-h)*(l-h)+c*c);t.values[2]=0!==c?180*Math.atan((h-l-f)/c)/Math.PI:l=0?t.values[4]:1-t.values[4];break;case"V":case"v":t.values[0]*=i;break;default:t.values.forEach(((n,o)=>{t.values[o]=n*(o%2==0?e:i)}))}}))}(n,t.calculative.worldRect.width/t.calculative.svgRect.width,t.calculative.worldRect.height/t.calculative.svgRect.height);const o=oi(n);ze(o),function(t,e,i){null==i&&(i=e),t.commands.forEach(((t,n)=>{if(!t.relative||!n)switch(t.key){case"A":case"a":t.values[5]+=e,t.values[6]+=i;break;case"V":case"v":t.values[0]+=i;break;default:t.values.forEach(((n,o)=>{t.values[o]=n+(o%2==0?e:i)}))}}))}(n,t.calculative.worldRect.x-o.x,t.calculative.worldRect.y-o.y);const r=function(t){let e="";return t.commands.forEach((t=>{e+=t.key+" ",t.values.forEach((t=>{e+=t+" "}))})),e}(n);if(!e)return new Path2D(r);e.svgPath?.(r)}function ai(t,e){const{x:i,y:n,width:o,ex:r,ey:s}=e.calculative.worldRect;let a=.25*o;const l=e.z;l>1?a=l:l>0&&(a=o*l);const c={x:i,y:n+a},h={x:r-a,y:n+a},d={x:r-a,y:s};li(t,[c,h,d,{x:i,y:s}],e.backgroundFront||e.background,e.color),li(t,[c,{x:i+a,y:n},{x:r,y:n},h],e.backgroundUp||e.background,e.color),li(t,[h,{x:r,y:n},{x:r,y:s-a},d],e.backgroundRight||e.background,e.color)}function li(t,e,i="",n=""){t.save(),i&&(t.fillStyle=i),n&&(t.strokeStyle=n),t.beginPath();for(let i=0;in.x?x.Right:x.Left),n.next={id:at(),penId:e.id,x:n.x,y:n.y,prevNextType:2},o.prev={id:at(),penId:e.id,x:o.x,y:o.y,prevNextType:2},r){case x.Up:n.next.y-=20,o.prev.y=n.y;break;case x.Bottom:n.next.y+=20,o.prev.y=n.y;break;case x.Left:n.next.x-=20,o.prev.x=n.x;break;default:n.next.x+=20,o.prev.x=n.x}}function vi(t,e){const i=e||new Path2D;if(("line"===t.lineName||"polyline"===t.lineName)&&t.calculative.lineSmooth){let e=kt(t);if(i.addPath(e),i instanceof Path2D)return i}const n=t.calculative.worldAnchors;if(n.length>1){let e;n.forEach((t=>{e?yi(i,e,t):t.start=!0,e=t})),t.close&&yi(i,e,n[0])}if(i instanceof Path2D)return i}function gi(t,e,i){if(e.calculative.worldAnchors||(e.calculative.worldAnchors=[]),e.calculative.worldAnchors.length<2||e.anchors?.length>1)return;const n=re(e),o=se(e);n&&o&&o.id&&n!==o&&(n.next=void 0,ee(e),o.prev=void 0,e.calculative.worldAnchors.push(o))}function yi(t,e,i){i&&!i.isTemp&&(e.start&&t.moveTo(e.x,e.y),e.next?i.prev?t.bezierCurveTo(e.next.x,e.next.y,i.prev.x,i.prev.y,i.x,i.y):t.quadraticCurveTo(e.next.x,e.next.y,i.x,i.y):i.prev?t.quadraticCurveTo(i.prev.x,i.prev.y,i.x,i.y):t.lineTo(i.x,i.y))}function mi(t){return Ci(t),Ve(wi(t))}function wi(t){const e=[];let i;return t.calculative.worldAnchors.forEach((n=>{e.push(n),i&&e.push(...bi(i,n,t)),i=n})),t.close&&t.calculative.worldAnchors.length>1&&e.push(...bi(i,t.calculative.worldAnchors[0],t)),e}function xi(t){return t?.lineWidth?t.lineWidth/2+4:4}function bi(t,e,i){const n=[];if(!e)return n;let o=.02;if(t.lineLength&&(o=xi(i)/t.lineLength),t.next)if(e.prev)for(let i=o;i<1;i+=o)n.push(ui(i,t,t.next,e.prev,e));else for(let i=o;i<1;i+=o)n.push(di(i,t,t.next,e));else if(e.prev)for(let i=o;i<1;i+=o)n.push(di(i,t,e.prev,e));else n.push({x:e.x,y:e.y});return n.length>1&&(t.curvePoints=n),n}function ki(t,e){const i=xi(e);let n,o,r=0;for(const s of e.calculative.worldAnchors){if(n){if(o=Ti(t,n,s,i),o)return{i:r,point:o};++r}n=s}if(e.close&&e.calculative.worldAnchors.length>1&&(o=Ti(t,n,e.calculative.worldAnchors[0],i)))return{i:r,point:o}}function Ti(t,e,i,n=4){if(!e.next&&!i.prev){const{x:o,y:r}=e,{x:s,y:a}=i,l=Math.min(o,s),c=Math.max(o,s),h=Math.min(r,a),d=Math.max(r,a);if(!(t.x>=l-n&&t.x<=c+n&&t.y>=h-n&&t.y<=d+n))return;return function(t,e,i,n=4){if(e.x===i.x){if(Math.abs(t.x-e.x)<=n)return{x:e.x,y:t.y}}else{const o=(e.y-i.y)/(e.x-i.x),r=e.y-o*e.x;if(Math.abs((o*t.x+r-t.y)/Math.sqrt(o*o+1))<=n){const e=(t.x+o*t.y-o*r)/(o*o+1);return{x:e,y:o*e+r}}}}(t,e,i,n)}if(e.curvePoints)for(const i of e.curvePoints)if(E(t,i,n))return i}function Ai(t,e,i,n){if(!e&&!i)return Math.sqrt(Math.pow(Math.abs(t.x-n.x),2)+Math.pow(Math.abs(t.y-n.y),2))||0;const o=document.createElementNS("http://www.w3.org/2000/svg","path");return e&&i?o.setAttribute("d",`M${t.x} ${t.y} C${e.x} ${e.y} ${i.x} ${i.y} ${n.x} ${n.y}`):e?o.setAttribute("d",`M${t.x} ${t.y} Q${e.x} ${e.y} ${n.x} ${n.y}`):o.setAttribute("d",`M${t.x} ${t.y} Q${i.x} ${i.y} ${n.x} ${n.y}`),o.getTotalLength()||0}function Ci(t){if(t.calculative.worldAnchors.length<2)return 0;let e,i=0;if(t.calculative.worldAnchors.forEach((t=>{e&&(e.lineLength=Ai(e,e.next,t.prev,t),i+=e.lineLength),e=t})),t.close){const n=re(t);e.lineLength=Ai(e,e.next,n.prev,n),i+=e.lineLength}return t.calculative.animatePos&&(t.calculative.animatePos=i/t.length*t.calculative.animatePos),t.length=i,i}function Ri(t,e){const i=t.calculative.worldAnchors;for(let t=0;t=0&&d*c+u*h+f<=0||d*a+u*l+f<=0&&d*c+u*h+f>=0||d*a+u*h+f>=0&&d*c+u*l+f<=0||d*a+u*h+f<=0&&d*c+u*l+f>=0){if(a>c){const t=a;a=c,c=t}if(lc&&r>c||o>l&&s>l||of.y&&o.yf.y))){p=u;let t=Ei;o.xt.y)o=t.x+(e.x-t.x)/2,n.push({x:o,y:t.y},{x:o,y:e.y});else{const i=(t.y+e.y)/2;n.push({x:t.x,y:i},{x:e.x,y:i})}break;case x.Right:o=e.x,r=t.y,e.xt.x&&e.yt.y-Ei)o=t.x+(e.x-t.x)/2,n.push({x:o,y:t.y},{x:o,y:e.y});else{const i=(t.y+e.y+Ei)/2;n.push({x:t.x,y:i},{x:e.x,y:i})}}return n}(o,r,d));break;case x.Right:a.push(...function(t,e,i){if(t.x===e.x||t.y===e.y)return[];const n=[];let o,r;switch(i){case x.Up:o=t.x,r=e.y,e.x>t.x&&e.y>t.y&&(o=e.x,r=t.y),n.push({x:o,y:r});break;case x.Bottom:o=t.x,r=e.y,e.x>t.x&&e.yt.y&&(o=t.x,r=e.y),n.push({x:o,y:r});break;case x.Bottom:t.y>e.y?(o=e.x,r=t.y):(o=t.x,r=e.y),n.push({x:o,y:r});break;case x.Left:o=e.x,r=t.y,e.x>t.x&&e.y>t.y&&(o=t.x,r=e.y),n.push({x:o,y:r});break;default:if(o=t.x,e.yt.y&&(o=e.x,r=t.y),n.push({x:o,y:r});break;case x.Bottom:o=t.x,r=e.y,e.xt.x)o=e.x,r=t.y+(e.y-t.y)/2,n.push({x:t.x,y:r},{x:e.x,y:r});else{const i=(t.x+e.x)/2;n.push({x:i,y:t.y},{x:i,y:e.y})}break;case x.Left:e.x>t.x?n.push({x:t.x,y:e.y}):n.push({x:e.x,y:t.y});break;default:if(o=t.x,r=e.y,e.xMath.abs(i.y-e.y));let o=t.calculative.worldAnchors.findIndex((t=>t.id==e.id));if(o>1){let r=t.calculative.worldAnchors[o-1];if(r.x===e.x&&r.y!==e.y)return n.push({x:i.x,y:e.y}),n;if(r.y===e.y&&r.x!==e.x)return n.push({x:e.x,y:i.y}),n}return t.calculative.worldAnchors.length&&(i.isTemp=void 0,t.calculative.drawlineH?(n.push({x:i.x,y:e.y}),Math.abs(i.y-e.y){t.id=at(),t.penId=e.id,e.calculative.worldAnchors.push(t)})),e.calculative.worldAnchors.push(r),p&&e.calculative.worldAnchors.push(p),u&&e.calculative.worldAnchors.push(f),n&&e.calculative.worldAnchors.reverse(),s){const t=e.calculative.worldAnchors.length-2;e.calculative.worldAnchors[t].isTemp=!1,e.calculative.worldAnchors[1].isTemp=!1}}function _i(t,e,i){const n={x:t.x,y:t.y,id:at()};switch(e){case x.Up:n.y-=i;break;case x.Right:n.x+=i;break;case x.Bottom:n.y+=i;break;case x.Left:n.x-=i;break;default:return}return n}function Li(t,e,i=!0){let n=t.calculative.worldAnchors;i||(n=[],t.calculative.worldAnchors.forEach((t=>{n.unshift(t)})));for(let t=0;t{n.unshift(t)})));for(let t=0;t1?(c=v.x-p.x,h=v.y-p.y):g>0?(c=v.x-(a+d*g),h=v.y-(l+u*g)):(c=v.x-a,h=v.y-l)):(c=v.x-a,h=v.y-l),y=c*c+h*h,y>r&&(s=e,r=y);return r>e&&(s-i>1&&o.push(...Di(t,e,i,s)),o.push({id:t[s].id,penId:t[s].penId,x:t[s].x,y:t[s].y}),n-s>1&&o.push(...Di(t,e,s,n))),o}function Oi(t,e){const i=e||new Path2D,n=t.calculative.worldAnchors;let o=t.calculative.canvas.store.data.scale,r=(t.calculative.animateLineWidth||6)*o,s=(2*t.animateLineWidth||12)*o;t.lineAnimateType===f.WaterDrop&&(s=(4*t.animateLineWidth||24)*o);let a=(t.animateInterval||100)*o,l=t.calculative.lineWidth*(t.calculative.lineSmooth||0),c=(t.calculative.animateLineWidth/2||3)*o;if(t.animateReverse&&(s=-s,r=-r),n.length>1){let e,o=0;for(let h=0;hs)&&u>l+s&&p-u>l&&(t.lineAnimateType===f.Arrow?Fi(i,h,r,n,c,s):t.lineAnimateType===f.WaterDrop&&zi(i,h,t.animateReverse,n,c,s)),h.x+=a*Math.cos(n*Math.PI/180),h.y-=a*Math.sin(n*Math.PI/180),u=Math.sqrt((h.x-e.x)**2+(h.y-e.y)**2)}e=d}}if(i instanceof Path2D)return i}function Ni(t,e){let i=e.x-t.x,n=e.y-t.y,o=180*Math.atan(n/i)/Math.PI;return o=e.x>=t.x?-o:180-o,o}function Bi(t,e,i){let n=(180-i)*Math.PI/180;return{x:(t.x-e.x)*Math.cos(n)-(t.y-e.y)*Math.sin(n)+e.x,y:(t.x-e.x)*Math.sin(n)+(t.y-e.y)*Math.cos(n)+e.y}}function Fi(t,e,i,n,o,r){let s=Bi({x:e.x+i,y:e.y+.57*i},{x:e.x,y:e.y},n),a=Bi({x:e.x+i,y:e.y-.57*i},{x:e.x,y:e.y},n),l=Bi({x:e.x+i,y:e.y+o/2},{x:e.x,y:e.y},n),c=Bi({x:e.x+r,y:e.y+o/2},{x:e.x,y:e.y},n),h=Bi({x:e.x+i,y:e.y-o/2},{x:e.x,y:e.y},n),d=Bi({x:e.x+r,y:e.y-o/2},{x:e.x,y:e.y},n);t.moveTo(s.x,s.y),t.lineTo(e.x,e.y),t.lineTo(a.x,a.y),t.lineTo(h.x,h.y),t.lineTo(d.x,d.y),t.lineTo(c.x,c.y),t.lineTo(l.x,l.y),t.lineTo(s.x,s.y)}function zi(t,e,i,n,o,r){let s=o/2;i&&(s=-o/2);let a=Bi({x:e.x,y:e.y+s},{x:e.x,y:e.y},n),l=Bi({x:e.x+r,y:e.y},{x:e.x,y:e.y},n),c=Math.PI/2;i&&(c=-Math.PI/2),t.moveTo(e.x,e.y),t.arc(e.x,e.y,o/2,-c-n/180*Math.PI,c-n/180*Math.PI,!1),t.lineTo(l.x,l.y),t.lineTo(a.x,a.y)}function Hi(t){t.onDestroy||(t.onDestroy=ji,t.onMove=Wi,t.onResize=Wi,t.onRotate=Wi,t.onValue=Wi,t.onMouseMove=Vi,t.onBeforeValue=Ui,t.onRenderPenRaw=$i),t.calculative.singleton||(t.calculative.singleton={});const e=t.calculative.worldRect;if(!t.calculative.singleton.div){const i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="-9999px",i.style.top="-9999px",i.style.width=e.width+"px",i.style.height=e.height+"px",document.body.appendChild(i),t.calculative.canvas.externalElements?.parentElement.appendChild(i),pe(t,i),t.calculative.singleton.div=i;const n=document.createElement("iframe");n.style.width="100%",n.style.height="100%",n.scrolling=t.scrolling||"no",n.frameBorder="0",n.style.border="none",n.src=t.iframe,t.calculative.iframe=t.iframe,i.appendChild(n),Ki(t),n.onload=()=>{n.setAttribute("document.domain","")}}return t.calculative.patchFlags&&pe(t,t.calculative.singleton.div),t.onRenderPenRaw(t),new Path2D}function ji(t){Yi(t),t.calculative.singleton&&t.calculative.singleton.div&&(t.calculative.singleton.div.remove(),delete t.calculative.singleton.div)}function Wi(t){t.calculative.singleton.div&&pe(t,t.calculative.singleton.div)}function Ui(t,e){if(e.iframe&&t.calculative.singleton.div&&(t.calculative.singleton.div.children[0].src=e.iframe,t.calculative.iframe=e.iframe),e.operationalRect||void 0!==e["operationalRect.x"]||void 0!==e["operationalRect.y"]||void 0!==e["operationalRect.width"]||void 0!==e["operationalRect.height"]){t.operationalRect||(t.operationalRect={});let i=Q(e);i.operationalRect||(i.operationalRect={}),void 0!==i["operationalRect.x"]&&(i.operationalRect.x=i["operationalRect.x"]),void 0!==i["operationalRect.y"]&&(i.operationalRect.y=i["operationalRect.y"]),void 0!==i["operationalRect.width"]&&(i.operationalRect.width=i["operationalRect.width"]),void 0!==i["operationalRect.height"]&&(i.operationalRect.height=i["operationalRect.height"]),Object.assign(t.operationalRect,i.operationalRect),t.calculative.singleton.div&&(1===t.calculative.singleton.div.children.length?Ki(t):(t.calculative.singleton.div.children[1].style.height=100*t.operationalRect.y+"%",t.calculative.singleton.div.children[1].style.left=100*t.operationalRect.x+"%",t.calculative.singleton.div.children[1].style.width=100*t.operationalRect.width+"%",t.calculative.singleton.div.children[2].style.width=100*(1-t.operationalRect.x-t.operationalRect.width)+"%",t.calculative.singleton.div.children[3].style.height=100*(1-t.operationalRect.y-t.operationalRect.height)+"%",t.calculative.singleton.div.children[3].style.left=100*t.operationalRect.x+"%",t.calculative.singleton.div.children[3].style.width=100*t.operationalRect.width+"%",t.calculative.singleton.div.children[4].style.width=100*t.operationalRect.x+"%"))}if(void 0!==e.blur)for(let i=1;i<5;i++)t.calculative.singleton.div.children[i].style["backdrop-filter"]=`blur(${e.blur||2}px)`;if(void 0!==e.blurBackground)for(let i=1;i<5;i++)t.calculative.singleton.div.children[i].style.backgroundColor=e.blurBackground;return e}function Vi(t,e){if((t.calculative.canvas.store.data.locked||t.locked)&&qi(t.operationalRect)&&t.calculative.zIndex<5&&e.x>t.x+t.width*t.operationalRect.x&&e.xt.y+t.height*t.operationalRect.y&&e.y{Yi(t)};i.onmouseenter=s,o.onmouseenter=s,n.onmouseenter=s,r.onmouseenter=s,e.onmouseleave=s}function Yi(t){if((t.calculative.canvas.store.data.locked||t.locked)&&t.calculative.zIndex<5){let e=t.calculative.singleton.div.parentNode.children;for(let t=1;t<6;t++)e[t].style.pointerEvents="initial"}}function $i(t){if(t.thumbImg&&!t.calculative.img){const e=new Image;e.crossOrigin="undefined"===t.crossOrigin?void 0:t.crossOrigin||"anonymous",t.calculative.canvas.store.options.cdn&&!(t.thumbImg.startsWith("http")||t.thumbImg.startsWith("//")||t.thumbImg.startsWith("data:image"))?e.src=t.calculative.canvas.store.options.cdn+t.thumbImg:e.src=t.thumbImg,e.onerror=i=>{e.remove(),t.calculative.img=void 0},t.calculative.img=e}}const Xi={},Gi=['',''];function Qi(t){if(t.onDestroy||(t.onDestroy=Ji,t.onMove=Zi,t.onResize=Zi,t.onRotate=Zi,t.onClick=tn,t.onValue=on,t.onChangeId=nn),Xi[t.id])t.video&&t.calculative.media&&t.video!==t.calculative.video?(console.warn("video 更改, 此处是否执行?"),t.calculative.media.src=t.video,t.autoPlay&&(t.calculative.media.muted=!0,t.calculative.media.autoplay=!0),t.calculative.media.loop=t.playLoop,t.calculative.video=t.video):t.audio&&t.calculative.media&&t.audio!==t.calculative.audio&&(t.calculative.media.src=t.audio,t.autoPlay&&(t.calculative.media.muted=!0,t.calculative.media.autoplay=!0),t.calculative.media.loop=t.playLoop,t.calculative.audio=t.audio);else{const e=document.createElement("div"),i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="0",i.style.bottom="0",i.style.width="0",i.style.height="2px",i.style.background="#52c41a",i.style.zIndex="1",t.hideProgress&&(i.style.display="none");const n=document.createElement("div");let o;n.innerHTML=Gi[1],n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.width="20px",n.style.height="20px",n.style.fill="hsla(0, 0%, 100%, .8)",n.style.zIndex="1",n.style.display="none",e.appendChild(i),e.appendChild(n),n.onclick=e=>{e.stopPropagation(),t.calculative.media.muted?(n.innerHTML=Gi[0],t.calculative.media.muted=!1):(n.innerHTML=Gi[1],t.calculative.media.muted=!0)},t.calculative.singleton||(t.calculative.singleton={}),t.calculative.singleton.muted=n,e.onmouseenter=t=>{n.style.display="block"},e.onmouseleave=t=>{n.style.display="none"},e.onclick=e=>{e.stopPropagation(),tn(t)},t.video?(o=document.createElement("video"),o.src=t.video):t.audio&&(o=document.createElement("audio"),o.src=t.audio),o.loop=t.playLoop,o.ontimeupdate=()=>{en(i,o,t.calculative.worldRect.width)},o.onended=()=>{t.calculative.onended&&t.calculative.onended(t)},t.calculative.media=o,o.style.position="absolute",o.style.outline="none",o.style.left="0",o.style.top="0",o.style.width="100%",o.style.height="100%",e.appendChild(o),Xi[t.id]=e,t.calculative.canvas.externalElements?.parentElement.appendChild(e),pe(t,e),t.autoPlay&&(o.autoplay=!0,o.muted=!0)}return t.calculative.patchFlags&&pe(t,Xi[t.id]),new Path2D}function Ji(t){Xi[t.id].onclick=null,Xi[t.id].remove(),Xi[t.id]=void 0}function Zi(t){pe(t,Xi[t.id]),en(Xi[t.id].children[0],Xi[t.id].children[1],t.calculative.worldRect.width)}function tn(t){t.calculative.media&&(t.calculative.media.muted=!1,t.calculative.singleton.muted.innerHTML=Gi[0],t.calculative.media.paused?t.calculative.media.play():t.calculative.media.pause())}function en(t,e,i){t.style.width=e.currentTime/e.duration*i+"px"}function nn(t,e,i){Xi[e]&&(Xi[i]=Xi[e],delete Xi[e])}function on(t){const e=Xi[t.id];if(!e)return;pe(t,e);const i=t.calculative.media.getAttribute("src");t.video?i!==t.video&&(t.calculative.media.src=t.video):t.audio&&i!==t.audio&&(t.calculative.media.src=t.audio),t.autoPlay&&(t.calculative.media.muted=!0,t.calculative.media.autoplay=!0),t.calculative.media.loop=t.playLoop}function rn(){try{const t=new OffscreenCanvas(0,0),e=t.getContext("2d");return e&&e.arc?t:document.createElement("canvas")}catch(t){return document.createElement("canvas")}}class sn{constructor(t,e){let i;this.parentElement=t,this.store=e,this.box=document.createElement("div"),this.text=document.createElement("div"),this.arrowUp=document.createElement("div"),this.arrowDown=document.createElement("div"),this.box.className="meta2d-tooltip",this.text.className="text",this.arrowUp.className="arrow",this.arrowDown.className="arrow down",this.box.appendChild(this.text),this.box.appendChild(this.arrowUp),this.box.appendChild(this.arrowDown),t.appendChild(this.box),this.box.onmouseleave=()=>{this.hide(),this.store.lastHover=void 0};for(let t=0;t0?(this.arrowUp.style.borderBottomColor="transparent",this.arrowDown.style.borderTopColor="#777777"):(r+=i.height+n.height+5,this.arrowUp.style.borderBottomColor="#777777",this.arrowDown.style.borderTopColor="transparent"),this.x=o,this.y=r,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px"}hide(){this.currentPen=null,this.x=-9999,this.box.style.left="-9999px"}translate(t,e){this.x<-1e3||(this.x+=t,this.y+=e,this.box.style.left=this.x+"px",this.box.style.top=this.y+"px")}destroy(){this.box.onmouseleave=null}}class an{constructor(t){let e;this.parent=t,this.onMouseDownH=t=>{t.preventDefault(),t.stopPropagation(),this.isDownH=t.x,this.x=this.parent.store.data.x||0,this.lastScrollX=this.scrollX},this.onMouseDownV=t=>{t.preventDefault(),t.stopPropagation(),this.isDownV=t.y,this.y=this.parent.store.data.y||0,this.lastScrollY=this.scrollY},this.onMouseMove=t=>{if(this.isDownH){const e=t.x-this.isDownH;this.scrollX=this.lastScrollX+e,this.h.style.left=`${this.scrollX}px`,this.parent.store.data.x=this.x-e*this.rect.width/this.parent.parentElement.clientWidth}if(this.isDownV){const e=t.y-this.isDownV;if(this.pageMode&&this.canMouseMove(e))return;this.scrollY=this.lastScrollY+e,this.v.style.top=`${this.scrollY}px`,this.parent.store.data.y=this.y-e*this.rect.height/this.parent.parentElement.clientHeight}(this.isDownH||this.isDownV)&&(this.parent.onMovePens(),this.parent.canvasTemplate.init(),this.parent.canvasImage.init(),this.parent.canvasImageBottom.init(),this.parent.render())},this.onMouseUp=t=>{(this.isDownH||this.isDownV)&&(this.isDownH=void 0,this.isDownV=void 0,this.scrollX<20?(this.scrollX=20,this.h.style.left=`${this.scrollX}px`):this.scrollX>this.parent.parentElement.clientWidth-this.hSize-20&&(this.scrollX=this.parent.parentElement.clientWidth-this.hSize-20,this.h.style.left=`${this.scrollX}px`),this.scrollY<20?(this.scrollY=20,this.v.style.top=`${this.scrollY}px`):this.scrollY>this.parent.parentElement.clientHeight-this.vSize-20&&(this.scrollY=this.parent.parentElement.clientHeight-this.vSize-20,this.v.style.top=`${this.scrollY}px`),this.resize())},this.h=document.createElement("div"),this.v=document.createElement("div"),this.parent.externalElements.appendChild(this.h),this.parent.externalElements.appendChild(this.v),this.h.className="meta2d-scroll h",this.h.onmousedown=this.onMouseDownH,this.v.className="meta2d-scroll v",this.v.onmousedown=this.onMouseDownV,document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp);for(let t=0;t=0||t>0&&e.ey-this.parent.height+this.parent.store.data.y<=0}changeMode(){this.pageMode=!0,this.h.style.display="none",this.parent.parent.getRect().height0?this.rect.width+=this.parent.store.data.x+(this.rect.x>0?0:this.rect.x):this.rect.width-=this.parent.store.data.x+(this.rect.x>0?0:this.rect.x),this.parent.store.data.y>0?this.rect.height+=this.parent.store.data.y+(this.rect.y>0?0:this.rect.y):this.rect.height-=this.parent.store.data.y+(this.rect.y>0?0:this.rect.y),this.rect.width<1400&&(this.rect.width=1400),this.rect.height<900&&(this.rect.height=900),this.hSize=1e3*this.parent.parentElement.clientWidth/this.rect.width/3,this.vSize=1e3*this.parent.parentElement.clientHeight/this.rect.height/3,this.h.style.width=this.hSize+"px",this.v.style.height=this.vSize+"px"}show(){this.isShow=!0,this.h.style.display="block",this.v.style.display="block",document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mouseup",this.onMouseUp)}hide(){this.isShow=!1,this.h.style.display="none",this.v.style.display="none",this.destroy()}translate(t,e){t&&(this.scrollX-=t*this.parent.parentElement.clientWidth/this.rect.width,this.h.style.left=`${this.scrollX}px`),e&&(this.scrollY-=e*this.parent.parentElement.clientHeight/this.rect.height,this.v.style.top=`${this.scrollY}px`)}wheel(t){let e=10;t&&(e=-10),this.pageMode&&this.canMouseMove(e)||(this.scrollY+=e,this.v.style.top=`${this.scrollY}px`,this.parent.store.data.y-=e*this.rect.height/this.parent.parentElement.clientHeight,this.parent.onMovePens(),this.parent.canvasTemplate.init(),this.parent.canvasImage.init(),this.parent.canvasImageBottom.init(),this.parent.render())}destroy(){document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mouseup",this.onMouseUp)}}class ln{constructor(t,e,i){this.parentElement=t,this.store=e,this.isBottom=i,this.canvas=document.createElement("canvas"),this.otherOffsreen=rn(),this.offscreen=rn(),this.animateOffsScreen=rn(),this.fitOffscreen=rn(),this.fitFlag=!1,t.appendChild(this.canvas),this.canvas.style.backgroundRepeat="no-repeat",this.canvas.style.backgroundSize="100% 100%",this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0"}resize(t,e){this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",t=t*this.store.dpiRatio|0,e=e*this.store.dpiRatio|0,this.canvas.width=t,this.canvas.height=e,this.otherOffsreen.width=t,this.otherOffsreen.height=e,this.offscreen.width=t,this.offscreen.height=e,this.animateOffsScreen.width=t,this.animateOffsScreen.height=e,this.fitOffscreen.width=t,this.fitOffscreen.height=e,this.otherOffsreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.otherOffsreen.getContext("2d").textBaseline="middle",this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle",this.animateOffsScreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.animateOffsScreen.getContext("2d").textBaseline="middle",this.fitOffscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.fitOffscreen.getContext("2d").textBaseline="middle",this.init()}init(){this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.animateOffsScreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.fitOffscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height);for(const t of this.store.data.pens)this.hasImage(t)&&(t.calculative.imageDrawed=!1);this.isBottom?this.store.patchFlagsBackground=!0:this.store.patchFlagsTop=!0}clear(){this.otherOffsreen.getContext("2d").clearRect(0,0,this.otherOffsreen.width,this.otherOffsreen.height),this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.animateOffsScreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.fitOffscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}hasImage(t){return t.calculative.hasImage=t.calculative&&t.calculative.inView&&(this.isBottom&&t.canvasLayer===l.CanvasImageBottom||!this.isBottom&&t.canvasLayer===l.CanvasImage)&&t.image&&t.calculative.img&&"gif"!==t.name,t.calculative.hasImage}render(){let t=!1,e=!1;for(const i of this.store.data.pens)this.hasImage(i)&&(this.store.animates.has(i)?e=!0:i.calculative.imageDrawed||(t=!0),i.parentId&&this.store.animates.has(ht(i,!0))&&(e=!0));const i=this.store.patchFlagsBackground,n=this.store.patchFlagsTop;if(n&&!this.isBottom){const t=this.otherOffsreen.getContext("2d");t.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderRule(t)}if(this.store.patchFlagsLast&&this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),t){const t=this.offscreen.getContext("2d");t.save(),t.clearRect(0,0,this.canvas.width,this.canvas.height),t.translate(this.store.data.x,this.store.data.y);for(const e of this.store.data.pens)!e.calculative.hasImage||this.store.animates.has(e)||this.store.animates.has(ht(e,!0))||e.canvasLayer!==l.CanvasTemplate&&(e.calculative.imageDrawed=!0,t.save(),Mt(t,e),e.calculative.rotate&&Dt(t,e),ke(t,e),St(t,e),t.restore());t.restore()}if(e){const t=this.animateOffsScreen.getContext("2d");t.save(),t.clearRect(0,0,this.canvas.width,this.canvas.height),t.translate(this.store.data.x,this.store.data.y);for(const e of this.store.animates)e.calculative.hasImage&&e.canvasLayer!==l.CanvasTemplate&&(e.calculative.imageDrawed=!0,t.save(),Mt(t,e),e.calculative.rotate&&Dt(t,e),ke(t,e),St(t,e),t.restore());for(const e of this.store.data.pens)e.calculative.hasImage&&e.parentId&&e.canvasLayer!==l.CanvasTemplate&&this.store.animates.has(ht(e,!0))&&(e.calculative.imageDrawed=!0,t.save(),Mt(t,e),e.calculative.rotate&&Dt(t,e),ke(t,e),St(t,e),t.restore());t.restore()}if(!this.isBottom&&!this.store.data.locked&&this.fitFlag){const t=(this.store.data.width||this.store.options.width)*this.store.data.scale,e=(this.store.data.height||this.store.options.height)*this.store.data.scale,i=this.store.data.origin.x+this.store.data.x||this.store.options.x||0,n=this.store.data.origin.y+this.store.data.y||this.store.options.y||0,o=this.fitOffscreen.getContext("2d");o.save(),o.clearRect(0,0,this.canvas.width,this.canvas.height),o.fillStyle="#ffffff66",o.strokeStyle=this.store.options.activeColor,this.store.data.fits?.forEach(((r,s)=>{o.fillRect(i+t*r.x,n+e*r.y,t*r.width,e*r.height),r.active&&o.strokeRect(i+t*r.x,n+e*r.y,t*r.width,e*r.height)})),o.restore()}if(t||e||i&&this.isBottom||n&&!this.isBottom){const t=this.canvas.getContext("2d");t.clearRect(0,0,this.canvas.width,this.canvas.height),this.isBottom&&(this.store.patchFlagsBackground=!1),t.drawImage(this.offscreen,0,0,this.canvas.width,this.canvas.height),t.drawImage(this.animateOffsScreen,0,0,this.canvas.width,this.canvas.height),this.isBottom||(t.drawImage(this.otherOffsreen,0,0,this.canvas.width,this.canvas.height),this.store.patchFlagsTop=!1,!this.store.data.locked&&this.fitFlag&&t.drawImage(this.fitOffscreen,0,0,this.canvas.width,this.canvas.height))}}renderRule(t){const{data:e,options:i}=this.store,{rule:n,ruleColor:o,scale:r,origin:s}=e;if(!(n??i.rule))return;const a=10*r;t.save();const l=o||i.ruleColor;t.strokeStyle=ot(l,.7);const c=s.x+e.x,h=s.y+e.y,{width:d,height:u}=this.canvas;let f=i.ruleOptions?.height||20;i.ruleOptions?.background&&(t.beginPath(),t.fillStyle=i.ruleOptions?.background,t.rect(0,0,d,f),t.fill(),t.rect(0,0,f,u),t.fill()),i.ruleOptions?.underline&&(t.beginPath(),t.fillStyle=ot(l,.7),t.moveTo(0,f),t.lineTo(d,f),t.stroke(),t.moveTo(f,0),t.lineTo(f,u),t.stroke());let p=f/4;"bottom"===i.ruleOptions?.baseline&&(p=3*f/4),t.beginPath(),t.lineWidth=f/2,t.lineDashOffset=-c%a,t.setLineDash([1,a-1]),t.moveTo(0,p),t.lineTo(d,p),t.stroke(),t.beginPath(),t.lineDashOffset=-h%a,t.moveTo(p,0),t.lineTo(p,u),t.stroke(),t.strokeStyle=l,t.beginPath(),t.lineWidth=f,t.lineDashOffset=-c%(10*a),t.setLineDash([1,10*a-1]),t.moveTo(0,f/2),t.lineTo(d,f/2),t.stroke(),t.beginPath(),t.lineDashOffset=-h%(10*a),t.moveTo(f/2,0),t.lineTo(f/2,u),t.stroke(),t.beginPath(),t.fillStyle=i.ruleOptions?.textColor||t.strokeStyle;let v=0-100*Math.floor(c/a/10),g=i.ruleOptions?.textTop||16,y=i.ruleOptions?.textLeft||4;c<0&&(v-=100);for(let e=c%(10*a);e{i.drawImage(e,n-t,o-t,this.magnifierSize,this.magnifierSize,0,0,this.magnifierSize,this.magnifierSize)})),i.restore(),i.beginPath();const r=i.createRadialGradient(t,t,t-5,t,t,t);r.addColorStop(0,"rgba(0,0,0,0.2)"),r.addColorStop(.8,"rgb(200,200,200)"),r.addColorStop(.9,"rgb(200,200,200)"),r.addColorStop(1,"rgba(200,200,200,0.9)"),i.strokeStyle=r,i.arc(t,t,t,0,2*Math.PI,!1),i.stroke(),i.restore(),this.offscreen.getContext("2d").drawImage(this.magnifierScreen,0,0,this.magnifierSize+5,this.magnifierSize+5,(n-t-2.5)/this.store.dpiRatio,(o-t-2.5)/this.store.dpiRatio,(this.magnifierSize+5)/this.store.dpiRatio,(this.magnifierSize+5)/this.store.dpiRatio)}render(){this.offscreen.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.renderMagnifier();const t=this.canvas.getContext("2d");t.clearRect(0,0,this.canvas.width,this.canvas.height),t.drawImage(this.offscreen,0,0,this.canvas.width,this.canvas.height)}}function hn(t){if(t.data.locked)throw new Error("canvas is locked")}class dn{constructor(t){this.parentElement=t,this.box=document.createElement("div"),this.dialog=document.createElement("div");let e=document.createElement("div");this.title=document.createElement("div"),this.close=document.createElement("span"),this.close.innerHTML='\n \n \n ';let i,n=document.createElement("div");this.iframe=document.createElement("iframe"),this.iframe.setAttribute("frameborder","0"),this.box.className="meta2d-dialog_mask",this.dialog.className="meta2d-dialog",n.className="meta2d-dialog_body",e.className="meta2d-dialog_header",this.title.className="meta2d-dialog-content",this.close.className="meta2d-dialog-close",e.appendChild(this.title),e.appendChild(this.close),n.appendChild(this.iframe),this.dialog.appendChild(e),this.dialog.appendChild(n),this.box.appendChild(this.dialog),t.appendChild(this.box),this.dialog.onclick=t=>{t.stopPropagation()},this.box.onclick=()=>{this.hide()},this.close.onclick=()=>{this.hide()};for(let t=0;tt[n]=e.split(".").length===++o?i:t[n]||{}),t)}class pn{constructor(t){let e;this.parentElement=t,this.box=document.createElement("div"),this.box.className="meta2d-title",t.appendChild(this.box);for(let t=0;t{t.stopPropagation()},this.curve=ci,this.polyline=Ii,this.mind=pi,this.line=gi,this.onCopy=t=>{this.store.options.disableClipboard||t.target!==this.externalElements&&t.target!==document.body&&t.target.offsetParent!==this.externalElements||this.copy()},this.onCut=t=>{this.store.options.disableClipboard||t.target!==this.externalElements&&t.target!==document.body&&t.target.offsetParent!==this.externalElements||this.cut()},this.onPaste=t=>{if(this.store.data.locked||this.store.options.disableClipboard)return;if(t.target!==this.externalElements&&t.target!==document.body&&t.target.offsetParent!==this.externalElements)return;let e;if(navigator.clipboard&&t.clipboardData){const i=t.clipboardData.items;if(i)for(let t=0;t{t=e.target.result;const o=new Image;o.src=t,o.onload=()=>{const{width:e,height:s}=o,a={name:r,x:i-25,y:n-s/e*50,externElement:"gif"===r,width:100,height:s/e*100,image:t};this.addPens([a]),this.active([a]),this.copy([a])}},e.readAsDataURL(o)}}}else this.paste()},this.onwheel=t=>{if("true"===this.inputDiv.contentEditable)return;if(this.drawingLine)return;if(this.pencil)return;if(this.store.hover&&this.store.hover.onWheel)return void this.store.hover.onWheel(this.store.hover,t);if(this.store.options.disableScale)return;if(t.preventDefault(),t.stopPropagation(),this.mouseDown&&(this.hoverType===y.Node||this.hoverType===y.Line))return;if(this.store.data.locked===r.Disable)return;if(this.store.data.locked===r.DisableScale)return;if(this.store.data.locked===r.DisableMoveScale)return;if(!t.ctrlKey&&Math.abs(t.wheelDelta)<100&&-1===t.deltaY.toString().indexOf(".")){if(this.store.options.scroll&&!t.metaKey&&this.scroll)return void this.scroll.wheel(t.deltaY<0);const e=this.store.data.scale||1;return void this.translate(-t.deltaX/e,-t.deltaY/e)}if(Math.abs(t.wheelDelta)>100&&this.store.options.scroll&&this.scroll&&!this.store.options.scrollButScale)return void this.scroll.wheel(t.deltaY<0);if(this.store.options.disableTouchPadScale)return;let e=.015;if(this.store.options.scaleOff)e=this.store.options.scaleOff,t.deltaY>0&&(e=-this.store.options.scaleOff);else if(/mac os /i.test(navigator.userAgent))t.ctrlKey?t.deltaY>0&&(e*=-1):e*=t.wheelDeltaY/240;else{let i=.2;-1!==t.deltaY.toString().indexOf(".")&&(i=.01),e=t.deltaY>0?-i:i}let{offsetX:i,offsetY:n}=t;this.scale(this.store.data.scale+e,{x:i,y:n}),this.externalElements.focus()},this.onkeydown=t=>{if(this.store.data.locked>=r.DisableEdit&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&!t.target.dataset.meta2dIgnore&&this.store.active.forEach((e=>{e.onKeyDown?.(e,t.key)})),this.store.data.locked>=r.DisableEdit||"INPUT"===t.target.tagName||"TEXTAREA"===t.target.tagName||t.target.dataset.meta2dIgnore)return;if(this.store.options.unavailableKeys.includes(t.key))return;this.keyOptions||(this.keyOptions={}),this.keyOptions.altKey=t.altKey,this.keyOptions.shiftKey=t.shiftKey,this.keyOptions.ctrlKey=t.ctrlKey,this.keyOptions.metaKey=t.metaKey;let e=10,i=10,n=null;if(this.store.options.strictScope){const t=this.store.data.width||this.store.options.width,e=this.store.data.height||this.store.options.height;t&&e&&(n={x:this.store.data.origin.x,y:this.store.data.origin.y,width:t*this.store.data.scale,height:e*this.store.data.scale})}switch(t.key){case" ":this.hotkeyType=m.Translate;break;case"Control":this.drawingLine?this.drawingLine.calculative.drawlineH=!this.drawingLine.calculative.drawlineH:this.hotkeyType||(this.patchFlags=!0,this.hotkeyType=m.Select);break;case"Meta":break;case"Shift":1===this.store.active.length&&this.store.active[0].type&&this.store.activeAnchor?this.toggleAnchorHand():this.hotkeyType||(this.patchFlags=!0,this.store.options.resizeMode||(this.hotkeyType=m.Resize));break;case"Alt":if(!t.ctrlKey&&!t.shiftKey&&this.drawingLine){const t=se(this.drawingLine);t!==this.drawingLine.calculative.activeAnchor?(ee(this.drawingLine),this.drawingLine.calculative.worldAnchors.push(t)):this.drawingLine.calculative.worldAnchors.push({x:t.x,y:t.y});const e=this.drawLineFns.indexOf(this.drawingLineName);this.drawingLineName=this.drawLineFns[(e+1)%this.drawLineFns.length],this.drawingLine.lineName=this.drawingLineName,this.drawline(),this.patchFlags=!0}t.preventDefault();break;case"a":case"A":t.ctrlKey||t.metaKey?(this.active(this.store.data.pens.filter((t=>!t.parentId&&t.locked!==r.Disable))),t.preventDefault()):this.toggleAnchorMode();break;case"Delete":case"Backspace":if(this.canvasImage.fitFlag&&this.canvasImage.activeFit){this.deleteFit();break}!this.store.data.locked&&this.delete();break;case"ArrowLeft":if(this.movingAnchor){this.translateAnchor(-1,0);break}if(e=-1,t.shiftKey&&(e=-5),(t.ctrlKey||t.metaKey)&&(e=-10),e*=this.store.data.scale,this.store.activeAnchor&&this.store.active&&1===this.store.active.length&&this.store.active[0].type){this.moveLineAnchor({x:this.store.activeAnchor.x+e,y:this.store.activeAnchor.y},{});break}n&&this.activeRect.x+en.x+n.width&&(e=n.x+n.width-(this.activeRect.x+this.activeRect.width)),this.translatePens(this.store.active,e,0);break;case"ArrowDown":if(this.movingAnchor){this.translateAnchor(0,1);break}if(i=1,t.shiftKey&&(i=5),(t.ctrlKey||t.metaKey)&&(i=10),i*=this.store.data.scale,n&&this.activeRect.y+this.activeRect.height+i>n.y+n.height&&(i=n.y+n.height-(this.activeRect.y+this.activeRect.height)),this.store.activeAnchor&&this.store.active&&1===this.store.active.length&&this.store.active[0].type){this.moveLineAnchor({x:this.store.activeAnchor.x,y:this.store.activeAnchor.y+i},{});break}this.translatePens(this.store.active,0,i);break;case"d":case"D":this.store.active[0]?.locked||this.removeAnchorHand();break;case"h":case"H":this.store.active[0]?.locked||this.addAnchorHand();break;case"m":case"M":this.toggleMagnifier();break;case"g":case"G":this.hoverType===y.NodeAnchor&&(this.movingAnchor=this.store.hoverAnchor,this.externalElements.style.cursor="move");break;case"s":case"S":this.store.data.locked||this.hoverType!==y.LineAnchor||this.store.hover!==this.store.active[0]||this.splitLine(this.store.active[0],this.store.hoverAnchor),(t.ctrlKey||t.metaKey)&&this.store.emitter.emit("save",{event:t});break;case"c":case"C":(t.ctrlKey||t.metaKey)&&this.store.options.disableClipboard&&this.copy();break;case"x":case"X":(t.ctrlKey||t.metaKey)&&this.store.options.disableClipboard&&this.cut();break;case"√":case"v":case"V":t.ctrlKey||t.metaKey||(this.pencil&&this.stopPencil(),this.drawingLineName?(this.finishDrawline(),this.drawingLineName=""):this.drawingLineName=this.store.options.drawingLineName),!this.store.data.locked&&(t.ctrlKey||t.metaKey)&&(this.store.options.disableClipboard||!this.store.options.disableClipboard&&t.altKey)&&this.paste();break;case"b":case"B":this.drawingLineName&&(this.finishDrawline(),this.drawingLineName=""),this.pencil?this.stopPencil():this.drawingPencil();break;case"y":case"Y":(t.ctrlKey||t.metaKey)&&this.redo();break;case"z":case"Z":t.ctrlKey||t.metaKey?this.undo():t.shiftKey&&this.redo();break;case"Enter":this.drawingLineName&&(this.finishDrawline(!0),this.store.active[0].anchors[0].connectTo?this.drawingLineName="":this.drawingLineName=this.store.options.drawingLineName),this.store.active&&(this.store.active.forEach((t=>{t.type?(t.close=!t.close,t.close&&wi(t),this.store.path2dMap.set(t,B.path2dDraws.line(t)),Ci(t)):t.calculative.focus=!0})),this.render());break;case"Escape":this.drawingLineName&&this.finishDrawline(),this.drawingLineName=void 0,this.stopPencil(),this.store.active&&this.store.active.forEach((t=>{t.type||(t.calculative.focus=!1)})),this.movingPens&&(this.getAllByPens(this.movingPens).forEach((t=>{this.store.pens[t.id]=void 0})),this.movingPens=void 0,this.mouseDown=void 0,this.clearDock(),this.store.active?.forEach((t=>{this.updateLines(t)})),this.calcActiveRect(),this.patchFlags=!0),this.hotkeyType=m.None,this.movingAnchor=void 0,this.magnifierCanvas.magnifier&&(this.magnifierCanvas.magnifier=!1,this.patchFlags=!0);break;case"E":case"e":this.store.options.disableAnchor=!this.store.options.disableAnchor,this.store.emitter.emit("disableAnchor",this.store.options.disableAnchor);break;case"=":(t.ctrlKey||t.metaKey)&&(this.scale(this.store.data.scale+.1),t.preventDefault(),t.stopPropagation());break;case"-":(t.ctrlKey||t.metaKey)&&(this.scale(this.store.data.scale-.1),t.preventDefault(),t.stopPropagation());break;case"l":case"L":this.canMoveLine=!0;break;case"[":this.parent.down();break;case"]":this.parent.up();break;case"{":this.parent.bottom();break;case"}":this.parent.top();break;case"F":case"f":this.setFollowers()}this.render(!1)},this.onkeyup=t=>{switch(t.key){case"l":case"L":this.canMoveLine=!1}this.hotkeyType&&this.render(),this.hotkeyType{if(this.store.data.locked)return void console.warn("canvas is locked, can not drop");t.preventDefault(),t.stopPropagation();const e=t.dataTransfer.getData("Meta2d")||t.dataTransfer.getData("Text");let i=null;try{e&&(i=JSON.parse(e))}catch(t){}if(!i){const{files:e}=t.dataTransfer;if(!e.length||!e[0].type.match("image.*")||this.addCaches&&this.addCaches.length){if(!this.addCaches||!this.addCaches.length)return void this.store.emitter.emit("drop",void 0);i=this.addCaches,this.addCaches=[]}else{const t="image/gif"===e[0].type;i=await this.fileToPen(e[0],t)}}if(i=Array.isArray(i)?i:[i],i[0]&&!1!==i[0].draggable){const e={x:t.offsetX,y:t.offsetY};this.calibrateMouse(e),this.dropPens(i,e),this.addCaches=[],this.getContainerHover(e),this.mousePos.x=e.x,this.mousePos.y=e.y,this.store.emitter.emit("mouseup",{x:e.x,y:e.y,pen:this.store.hoverContainer})}this.store.emitter.emit("drop",i||e)},this.ontouchstart=t=>{this.store.data.locked!==r.Disable&&(this.touchStartTimer&&clearTimeout(this.touchStartTimer),this.touchStartTimer=setTimeout((()=>{this.touchStart=performance.now();const e=t.touches[0].pageX-this.clientRect.x,i=t.touches[0].pageY-this.clientRect.y,n={x:e,y:i};if(this.calibrateMouse(n),this.getHover(n),this.onMouseDown({x:e,y:i,clientX:t.touches[0].clientX,clientY:t.touches[0].clientY,pageX:t.touches[0].pageX,pageY:t.touches[0].pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:1}),2===t.touches.length)return this.initTouchDis=Math.hypot(t.touches[0].pageX-t.touches[1].pageX,t.touches[0].pageY-t.touches[1].pageY),this.initScale=this.store.data.scale,this.startTouches=t.touches,void(this.touchCenter={x:t.touches[0].pageX+(t.touches[1].pageX-t.touches[0].pageX)/2-this.clientRect.x,y:t.touches[0].pageY+(t.touches[1].pageY-t.touches[0].pageY)/2-this.clientRect.y});3===t.touches.length&&(this.store.emitter.emit("contextmenu",{e:{x:e,y:i,clientX:t.touches[0].clientX,clientY:t.touches[0].clientY,pageX:t.touches[0].pageX,pageY:t.touches[0].pageY},clientRect:this.clientRect}),t.preventDefault(),t.stopPropagation()),this.touchStartTimer=void 0}),50))},this.ontouchmove=t=>{if(this.store.data.locked===r.Disable)return;t.stopPropagation(),t.preventDefault();const e=performance.now();if(e-this.touchStart<50)return;this.touchStart=e;const i=t.touches,n=i.length,o=t.touches[0].pageX-this.clientRect.x,s=t.touches[0].pageY-this.clientRect.y;if(1===n)this.onMouseMove({x:o,y:s,clientX:t.changedTouches[0].clientX,clientY:t.changedTouches[0].clientY,pageX:t.changedTouches[0].pageX,pageY:t.changedTouches[0].pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:1});else if(2===n&&2===this.startTouches?.length){if(!this.touchMoving&&!this.touchScaling){const t=this.startTouches[0].pageX-i[0].pageX,e=this.startTouches[1].pageX-i[1].pageX,n=this.startTouches[0].pageY-i[0].pageY,o=this.startTouches[1].pageY-i[1].pageY;(t>=0&&e<0||t<=0&&e>0)&&(n>=0&&o<0||n<=0&&o>0)?this.touchScaling=!0:this.touchMoving=!0}if(this.touchScaling){if(this.store.options.disableScale)return;const t=Math.hypot(i[0].pageX-i[1].pageX,i[0].pageY-i[1].pageY)/this.initTouchDis;this.scale(this.initScale*t,Q(this.touchCenter))}if(this.touchMoving){if(this.store.data.locked>=r.DisableMove&&this.store.data.locked!==r.DisableScale||this.store.options.disableScale)return;if(this.lastOffsetX){const{scale:t}=this.store.data;this.translate((o-this.lastOffsetX)/t,(s-this.lastOffsetY)/t)}this.lastOffsetX=o,this.lastOffsetY=s}}},this.ontouchend=t=>{if(this.store.data.locked===r.Disable)return;this.touchCenter=void 0,this.touchScaling=void 0,this.touchMoving=void 0,this.startTouches=void 0,this.lastOffsetX=0,this.lastOffsetY=0;const e=t.changedTouches[0].pageX-this.clientRect.x,i=t.changedTouches[0].pageY-this.clientRect.y;this.onMouseUp({x:e,y:i,clientX:t.changedTouches[0].clientX,clientY:t.changedTouches[0].clientY,pageX:t.changedTouches[0].pageX,pageY:t.changedTouches[0].pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:1}),setTimeout((()=>{this.render()}),20)},this.onGesturestart=t=>{t.preventDefault()},this.onMouseDown=t=>{if(2!==t.buttons||this.drawingLine||(this.mouseRight=w.Down),this.hideInput(),this.store.data.locked===r.Disable||1!==t.buttons&&2!==t.buttons)this.hoverType=y.None;else if(!this.magnifierCanvas.magnifier)if(this.calibrateMouse(t),this.mousePos.x=t.x,this.mousePos.y=t.y,this.mouseDown=t,this.lastMouseTime=performance.now(),this.canvasImage.fitFlag)this.canvasImage.currentFit||this.calcuActiveFit();else if(this.hotkeyType!==m.AddAnchor){if(!this.store.options.autoAnchor&&!this.drawingLine&&t.shiftKey&&t.ctrlKey&&t.altKey){this.setAnchor(this.store.pointAt),this.drawingLineName=this.store.options.drawingLineName;const t=this.store.activeAnchor;if(!t)return;const e={id:at(),x:t.x,y:t.y};this.drawingLine=this.createDrawingLine(e);let i=re(this.drawingLine);return this.drawingLine.calculative.activeAnchor=i,ie(this.store.hover,t,this.drawingLine,e),void this.drawline()}if(this.hotkeyType!==m.Translate&&(this.mouseRight!==w.Down||this.store.options.mouseRightActive)){if(this.drawingLine){if(this.store.hoverAnchor){const t=se(this.drawingLine);return this.store.hoverAnchor.type===S.Line?O(t,this.store.hoverAnchor,this.store):(t.x=this.store.hoverAnchor.x,t.y=this.store.hoverAnchor.y),ie(this.store.hover,this.store.hoverAnchor,this.drawingLine,t),this.drawline(),void this.finishDrawline(!0)}if(!this.store.options.autoAnchor&&t.shiftKey&&t.altKey&&t.ctrlKey){this.setAnchor(this.store.pointAt);const t=se(this.drawingLine),e=this.store.activeAnchor;if(!e)return;return t.x=e.x,t.y=e.y,ie(this.store.hover,e,this.drawingLine,t),this.drawline(),void this.finishDrawline(!0)}if(2===t.buttons||"mind"===this.drawingLineName&&this.drawingLine?.calculative.worldAnchors.length>1||this.store.options.drawingLineLength&&this.drawingLine?.calculative.worldAnchors.length>this.store.options.drawingLineLength)return this.finishDrawline(!0),void(this.store.active[0]?.anchors[0].connectTo||0==this.store.active.length?this.drawingLineName="":this.drawingLineName=this.store.options.drawingLineName);if(this.store.options.autoAnchor&&this.hoverType===y.Node){const e=se(this.drawingLine),i=Zt(this.store.hover,t);return e.x=i.x,e.y=i.y,this.drawingLine.autoTo=!0,ie(this.store.hover,i,this.drawingLine,e),this.drawline(),void this.finishDrawline(!0)}const e=se(this.drawingLine);e.isTemp?(this.drawingLine.calculative.activeAnchor=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2],e.isTemp=void 0):(this.drawingLine.calculative.activeAnchor=e,this.drawingLine.calculative.worldAnchors.push({x:e.x,y:e.y,penId:e.penId})),this.drawingLine.calculative.drawlineH=void 0,"polyline"!==this.drawingLineName&&this.drawline()}if(this.drawingLineName){if(this.hoverType===y.Node)if(this.store.options.autoAnchor){this.inactive(!0);const e=Zt(this.store.hover,t);this.store.hoverAnchor=e;const i={id:at(),x:e.x,y:e.y};this.drawingLine=this.createDrawingLine(i),this.drawingLine.autoFrom=!0,ie(this.store.hover,e,this.drawingLine,i)}else this.inactive(),this.hoverType=y.None;else if(this.hoverType===y.NodeAnchor){this.drawingLineName=this.store.options.drawingLineName;const t={id:at(),x:this.store.hoverAnchor.x,y:this.store.hoverAnchor.y};this.drawingLine=this.createDrawingLine(t),this.drawingLine.calculative.activeAnchor=t,ie(this.store.hover,this.store.hoverAnchor,this.drawingLine,t)}else if(!this.drawingLine&&"curve"!==this.drawingLineName){this.inactive(!0);const e={id:at(),x:t.x,y:t.y};this.drawingLine=this.createDrawingLine(e),this.drawingLine.calculative.activeAnchor=e}}else if(this.pencil){this.inactive(!0);const e=at(),i={x:t.x,y:t.y,id:at(),penId:e};this.pencilLine=this.getInitPencilLine(i)}else{switch(this.hoverType){case y.None:(this.store.data.rule||this.store.options.rule)&&!this.store.options.disableRuleLine&&this.addRuleLine(t),this.store.options.resizeMode&&(this.hotkeyType=m.None),this.inactive();break;case y.Node:case y.Line:if(this.store.hover){const e=ht(this.store.hover,!0)||this.store.hover;t.ctrlKey&&!t.shiftKey?(e.calculative.active?this.willInactivePen=e:this.store.active.length>0&&(e.calculative.active=!0,ue(e),this.store.active.push(e),this.store.emitter.emit("active",this.store.active)),this.patchFlags=!0):t.ctrlKey&&t.shiftKey&&this.store.hover.parentId?this.active([this.store.hover]):this.activeRect&&Be({x:t.x,y:t.y},this.activeRect)&&1!=this.store.active.length||e.calculative.active||(this.active([e]),this.store.options.resizeMode&&(this.hotkeyType=m.Resize)),this.calcActiveRect()}break;case y.LineAnchor:this.store.activeAnchor=this.store.hoverAnchor,this.store.hover.calculative.activeAnchor=this.store.hoverAnchor,this.active([this.store.hover]);break;case y.LineAnchorPrev:case y.LineAnchorNext:this.store.activeAnchor&&(this.prevAnchor={...this.store.activeAnchor.prev},this.nextAnchor={...this.store.activeAnchor.next});break;case y.Resize:this.activeInitPos=[],this.store.active.forEach((t=>{this.activeInitPos.push({x:(t.calculative.worldRect.x-this.activeRect.x)/this.activeRect.width,y:(t.calculative.worldRect.y-this.activeRect.y)/this.activeRect.height})}))}this.store.hover&&(this.store.hover.calculative.mouseDown=!0),this.store.emitter.emit("mousedown",{x:t.x,y:t.y,pen:this.store.hover})}this.render()}}else this.setAnchor(this.store.pointAt)},this.onMouseMove=t=>{if(this.store.data.locked===r.Disable)return void(this.hoverType=y.None);if(this.mouseDown&&!this.mouseDown.restore&&1!==t.buttons&&2!==t.buttons)return void this.onMouseUp(t);if(this.lastMouseTime){if(performance.now()-this.lastMouseTime<50)return void(this.lastMouseTime=0);this.lastMouseTime=0}if(this.calibrateMouse(t),this.mousePos.x=t.x,this.mousePos.y=t.y,this.magnifierCanvas.magnifier)return void this.render();if(this.canvasImage.fitFlag&&this.canvasImage.activeFit){const e=performance.now();return void(e-this.fitTimer>100&&(this.mouseDown?this.updateFit(t):this.inFitBorder(this.mousePos),this.fitTimer=e))}if(this.mouseDown&&!this.store.options.disableTranslate){if(this.mouseRight===w.Down&&(this.mouseRight=w.Translate),this.store.data.locked===r.DisableEdit||this.store.data.locked===r.DisableScale||this.hotkeyType===m.Translate||this.mouseRight===w.Translate){const{scale:e}=this.store.data;let i=(t.x-this.mouseDown.x)/e,n=(t.y-this.mouseDown.y)/e;return t.shiftKey&&!t.ctrlKey&&(n=0),t.ctrlKey&&(i=0),void this.translate(i,n)}if(this.store.data.locked)return;if(this.drawingLine||this.pencil){if(this.pencil){const e={...t};e.id=at(),e.penId=this.pencilLine.id,this.pencilLine.calculative.worldAnchors.push(e),this.store.path2dMap.set(this.pencilLine,B.path2dDraws[this.pencilLine.name](this.pencilLine)),this.patchFlags=!0}}else{if(this.drawingLineName||this.movingAnchor){if(this.drawingLineName&&this.hoverType===y.None){const e={id:at(),x:t.x,y:t.y};return this.drawingLine=this.createDrawingLine(e),this.drawingLine.calculative.activeAnchor=e,void this.drawline()}}else if(this.hoverType===y.NodeAnchor){if(!this.store.hoverAnchor)return;this.drawingLineName=this.store.options.drawingLineName;const t={id:at(),x:this.store.hoverAnchor.x,y:this.store.hoverAnchor.y};return this.drawingLine=this.createDrawingLine(t),this.drawingLine.calculative.activeAnchor=t,ie(this.store.hover,this.store.hoverAnchor,this.drawingLine,t),void this.drawline()}if(1===t.buttons&&(t.ctrlKey||!this.hoverType&&!this.hotkeyType)&&(!t.ctrlKey||!this.store.activeAnchor&&!this.store.active?.length))return this.dragRect={x:Math.min(this.mouseDown.x,t.x),y:Math.min(this.mouseDown.y,t.y),ex:Math.max(this.mouseDown.x,t.x),ey:Math.max(this.mouseDown.y,t.y),width:Math.abs(t.x-this.mouseDown.x),height:Math.abs(t.y-this.mouseDown.y)},void this.render();if(this.movingAnchor){const e=t.x-this.movingAnchor.x,i=t.y-this.movingAnchor.y;return this.translateAnchor(e,i),void this.render()}if(!this.store.active[0]?.locked){const e={x:t.x,y:t.y};if(this.hoverType===y.LineAnchor)return!this.dockInAnchor(t)&&"line"!==this.store.active[0]?.lineName||this.store.options.disableDock||this.store.options.disableLineDock||(this.clearDock(),this.dock=Pe(this.store,e,this.store.activeAnchor),this.dock?.xDock&&(e.x+=this.dock.xDock.step),this.dock?.yDock&&(e.y+=this.dock.yDock.step)),void this.moveLineAnchor(e,t);if(this.hoverType===y.LineAnchorPrev)return void this.moveLineAnchorPrev(t);if(this.hoverType===y.LineAnchorNext)return void this.moveLineAnchorNext(t)}if(this.hoverType===y.Rotate)return void this.rotatePens({x:t.x,y:t.y});if(this.hoverType===y.Resize)return void this.resizePens(t);if(this.hoverType===y.Node||this.hoverType===y.Line){const e=t.x-this.mouseDown.x,i=t.y-this.mouseDown.y,n=20;if(t.ctrlKey&&!t.shiftKey&&(Math.abs(e)>=n||Math.abs(i)>=n)&&(this.willInactivePen=void 0),1===this.store.active.length){const t=this.store.active[0];if((void 0===t.locked||t.locked1&&(i=se(this.drawingLine)),i?(i.prev=void 0,i.next=void 0,i.id||(i.id=at()),i.x=e.x,i.y=e.y,i.connectTo=void 0):(i={...e},this.drawingLine.calculative.worldAnchors.push(i)),this.hoverType!==y.NodeAnchor&&this.hoverType!==y.LineAnchor||(this.store.hoverAnchor.type!==S.Line&&(i.x=this.store.hoverAnchor.x,i.y=this.store.hoverAnchor.y),i.connectTo=this.store.hoverAnchor.penId,"polyline"===this.drawingLineName&&(i.isTemp=!1)),"line"===this.drawingLineName)if(t.ctrlKey&&!t.shiftKey)i.x=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2].x;else if(t.shiftKey&&!t.ctrlKey)i.y=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2].y;else if(t.shiftKey&&t.ctrlKey){let t=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2];this.getSpecialAngle(i,t)}this.drawline()}}globalThis.debug&&console.time("hover");const e=performance.now();e-this.hoverTimer>50&&(this.hoverTimer=e,this.getHover(t)),globalThis.debug&&console.timeEnd("hover"),this.hotkeyType===m.AddAnchor&&(this.patchFlags=!0),this.render(!1)},this.onMouseUp=t=>{if(this.store.data.locked!==r.Disable){if(this.mouseDown){if(this.mouseRight===w.Down&&(this.store.hover&&this.store.hover.calculative.focus?this.store.hover.onContextmenu&&this.store.hover.onContextmenu(this.store.hover,t):this.store.emitter.emit("contextmenu",{e:t,clientRect:this.clientRect,pen:this.store.hover})),this.mouseRight=w.None,this.calibrateMouse(t),this.mousePos.x=t.x,this.mousePos.y=t.y,this.pencil&&this.finishPencil(),this.drawingLine){if(this.store.hoverAnchor){const t=se(this.drawingLine);return this.store.hoverAnchor.type===S.Line?O(t,this.store.hoverAnchor,this.store):(t.x=this.store.hoverAnchor.x,t.y=this.store.hoverAnchor.y),ie(this.store.hover,this.store.hoverAnchor,this.drawingLine,t),this.drawline(),void this.finishDrawline(!0)}if(this.store.options.autoAnchor&&this.hoverType===y.Node){const e=se(this.drawingLine),i=Zt(this.store.hover,t);return e.x=i.x,e.y=i.y,this.drawingLine.autoTo=!0,ie(this.store.hover,i,this.drawingLine,e),this.drawline(),void this.finishDrawline(!0)}}if(this.hoverType===y.LineAnchor&&this.store.hover&&this.store.active[0]&&"line"===this.store.active[0].name&&this.store.active[0]!==this.store.hover){const e=this.store.active[0],i=re(e),n=se(e);if(this.store.hoverAnchor){const r=this.store.hover,s=re(r)===this.store.hoverAnchor,a=se(r)===this.store.hoverAnchor,l=i===this.store.activeAnchor,c=n===this.store.activeAnchor;if((t.ctrlKey||t.altKey)&&r.type===o.Line&&(s||a)&&(l||c)){const t=r.calculative.worldAnchors.map((t=>({...t,penId:e.id})));s?t.shift():a&&t.pop(),(s&&l||a&&c)&&t.reverse(),l?(e.calculative.worldAnchors[0].connectTo=void 0,e.calculative.worldAnchors.unshift(...t)):c&&(e.calculative.worldAnchors[e.calculative.worldAnchors.length-1].connectTo=void 0,e.calculative.worldAnchors.push(...t)),this.delete([r]),this.render()}else this.store.activeAnchor&&(this.store.hoverAnchor.type===S.Line?O(this.store.activeAnchor,this.store.hoverAnchor,this.store):(this.store.activeAnchor.x=this.store.hoverAnchor.x,this.store.activeAnchor.y=this.store.hoverAnchor.y),ie(this.store.hover,this.store.hoverAnchor,e,this.store.activeAnchor));this[e.lineName]&&"polyline"!==e.lineName&&this[e.lineName](this.store,e),this.store.path2dMap.set(e,B.path2dDraws.line(e)),this.initLineRect(e)}else i===this.store.activeAnchor&&e.autoFrom?this.calcAutoAnchor(e,i,this.store.hover):n===this.store.activeAnchor&&e.autoTo&&this.calcAutoAnchor(e,n,this.store.hover)}if(this.addCaches&&this.addCaches.length){if(!this.store.data.locked){if(this.dragRect&&1===this.addCaches.length){const e=this.addCaches[0];e.width=this.dragRect.width/this.store.data.scale,e.height=this.dragRect.height/this.store.data.scale,t.x=(this.dragRect.x+this.dragRect.ex)/2,t.y=(this.dragRect.y+this.dragRect.ey)/2}this.dropPens(this.addCaches,t)}this.addCaches=void 0}if(this.hoverType===y.Rotate&&(this.getSizeCPs(),this.store.active.forEach((t=>{t.rotate=t.calculative.rotate}))),this.patchFlagsLines.forEach((t=>{t.type&&this.initLineRect(t)})),this.patchFlagsLines.clear(),this.dragRect)if(this.canvasImage.fitFlag)this.makeFit();else{const e=this.store.data.pens.filter((e=>!(!1===e.visible||e.locked>=r.DisableMove||e.parentId||e.isRuleLine)&&(qe(e.calculative.worldRect,this.dragRect,t.ctrlKey||this.store.options.dragAllIn)?!(e.type===o.Line&&!this.store.options.dragAllIn)||Ri(e,this.dragRect):void 0)));this.active(e)}if(2!==t.button&&(L(this.mouseDown,t)<2&&(this.store.hover&&this.store.hover.input&&this.showInput(this.store.hover),this.store.emitter.emit("click",{x:t.x,y:t.y,pen:this.store.hover})),this.store.hover&&(this.store.hover.calculative.mouseDown=!1),this.store.hover!=this.store.hoverContainer&&this.store.emitter.emit("mouseup",{x:t.x,y:t.y,pen:this.store.hover}),this.store.emitter.emit("mouseup",{x:t.x,y:t.y,pen:this.store.hoverContainer})),this.willInactivePen){this.willInactivePen.calculative.active=void 0,ue(this.willInactivePen,!1);const t=this.store.active.findIndex((t=>t===this.willInactivePen));t>=0&&this.store.active.splice(t,1),this.calcActiveRect(),this.willInactivePen=void 0,this.store.emitter.emit("inactive",[this.willInactivePen]),this.render()}this.movingPens&&(t.altKey&&!t.shiftKey?this.copyMovedPens():this.movedActivePens(t.ctrlKey&&t.shiftKey),this.getAllByPens(this.movingPens).forEach((t=>{this.store.pens[t.id]=void 0})),this.movingPens=void 0),this.store.active&&this.store.active[0]&&(this.store.active[0].calculative.h=void 0),this.mouseDown=void 0,this.lastOffsetX=0,this.lastOffsetY=0,this.clearDock(),this.dragRect=void 0,this.initActiveRect=void 0,this.render()}}else this.hoverType=y.None},this.clearDock=()=>{const t=this.dock?.xDock?.penId,e=this.dock?.yDock?.penId,i=this.store.pens[t];i&&(i.calculative.isDock=!1);const n=this.store.pens[e];n&&(n.calculative.isDock=!1),this.dock=void 0},this.onResize=()=>{this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>{this.resize(),this.timer=void 0}),100)},this.onScroll=()=>{this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>{this.clientRect=this.canvas.getBoundingClientRect(),this.timer=void 0}),100)},this.calibrateMouse=t=>(t.x-=this.store.data.x,t.y-=this.store.data.y,t),this.getContainerHover=t=>{if(this.dragRect)return;this.store.hoverContainer=void 0;const e=this.store.data.pens.filter((t=>t.container||this.store.options.containerShapes?.includes(t.name)));if(e.length)for(let i=e.length-1;i>=0;--i){const n=e[i];if(0!=n.visible&&0!=n.calculative.inView&&n.locked!==r.Disable)if(Be(t,n.calculative.worldRect))this.store.hoverContainer=n,n?.onMouseMove?.(n,t),this.store.lastHoverContainer!==this.store.hoverContainer&&(this.patchFlags=!0,this.store.lastHoverContainer&&(this.store.lastHoverContainer.calculative.containerHover=!1,this.store.emitter.emit("leave",this.store.lastHoverContainer)),this.store.hoverContainer&&(this.store.hoverContainer.calculative.containerHover=!0,this.store.emitter.emit("enter",this.store.hoverContainer)),this.store.lastHoverContainer=this.store.hoverContainer);else if(this.store.hoverContainer=void 0,this.store.lastHoverContainer!==this.store.hoverContainer){this.patchFlags=!0;const t=this.store.lastHoverContainer.calculative.canvas.store.pens[this.store.lastHoverContainer.id+gn];this.store.lastHoverContainer&&!t&&(this.store.lastHoverContainer.calculative.containerHover=!1,this.store.emitter.emit("leave",this.store.lastHoverContainer)),this.store.lastHoverContainer=this.store.hoverContainer}}},this.getHover=t=>{if(this.dragRect)return;if(this.canvasImage.fitFlag)return;let e=y.None;this.store.hover=void 0,this.store.hoverAnchor=void 0,this.title.hide(),this.store.pointAt=void 0,this.store.pointAtIndex=void 0;const i=1===this.store.active.length&&this.store.active[0].type;if(!this.drawingLineName&&this.hotkeyType!==m.AddAnchor&&this.activeRect&&!i&&!this.store.data.locked){const i=ve(this.store.active),n=ge(this.store.active)||this.store.options.disableRotate,o=me(this.store.active)||this.store.options.disableSize;if(!i&&!n){const i={x:this.activeRect.center.x,y:this.activeRect.y-30};this.activeRect.rotate&&P(i,this.activeRect.rotate,this.activeRect.pivot||this.activeRect.center),!this.hotkeyType&&E(t,i,this.pointSize)&&(e=y.Rotate,this.externalElements.style.cursor=`url("${this.store.options.rotateCursor}"), auto`)}if(!i&&!o)for(let i=0;i<8;i++){const n=i<4;if((this.hotkeyType===m.Resize||n&&!this.hotkeyType)&&E(t,this.sizeCPs[i],this.pointSize)){let t=n?b:k,o=0;Math.abs(this.activeRect.rotate%90-45)<25?(t=n?k:b,o=Math.round((this.activeRect.rotate-45)/90)+(n?0:1)):o=Math.round(this.activeRect.rotate/90),e=y.Resize,this.resizeIndex=i,this.externalElements.style.cursor=t[(i+o)%4];break}}}e===y.None&&(e=this.inPens(t,this.store.data.pens)),e||i||!Be(t,this.activeRect)||(e=y.Node,this.externalElements.style.cursor="move"),this.hoverType=e,e===y.None&&(this.drawingLineName||this.pencil?this.externalElements.style.cursor="crosshair":this.mouseDown||(this.externalElements.style.cursor="default"),this.store.hover=void 0),this.store.lastHover!==this.store.hover&&(this.patchFlags=!0,this.store.lastHover&&(this.store.lastHover.calculative.hover=!1,fe(ht(this.store.lastHover,!0)||this.store.lastHover,!1),this.store.emitter.emit("leave",this.store.lastHover),this.tooltip.hide()),this.store.hover&&(this.store.hover.calculative.hover=!0,fe(ht(this.store.hover,!0)||this.store.hover),this.store.emitter.emit("enter",this.store.hover),this.tooltip.show(this.store.hover,t)),this.store.lastHover=this.store.hover),this.store.hover?.onMouseMove?.(this.store.hover,this.mousePos)},this.inPens=(t,e)=>{let i=y.None;t:for(let n=e.length-1;n>=0;--n){const s=e[n];if(0==s.visible||0==s.calculative.inView||s.locked===r.Disable)continue;const a=xi(s);if(s.calculative.active||Fe(t,s.calculative.worldRect,a)||Be(t,s.calculative.worldRect)){if(!this.store.data.locked&&this.hotkeyType!==m.Resize&&s.calculative.worldAnchors)for(const e of s.calculative.worldAnchors)if(i=this.inAnchor(t,s,e),i){let i=Q(e);Object.assign(i,t),this.title.show(i,s);break t}if(s.type){if(s.isRuleLine){let e=this.store.options.ruleOptions?.height||20;if(t.x+this.store.data.x>e&&t.y+this.store.data.y>e)break}const e=ki(t,s);if(e){this.store.data.locked||s.locked?this.externalElements.style.cursor=this.store.options.hoverCursor:this.hotkeyType===m.AddAnchor?this.externalElements.style.cursor="pointer":this.externalElements.style.cursor="move",s.calculative.disabled&&(this.externalElements.style.cursor="not-allowed"),this.store.hover=s,this.store.pointAt=e.point,this.store.pointAtIndex=e.i,this.initTemplateCanvas([this.store.hover]),i=y.Line;break}}else{if(s.children){const e=[];if(s.children.forEach((t=>{this.store.pens[t]&&e.push(this.store.pens[t])})),i=this.inPens(t,e),i)break}let e=!1;if(e="line"===s.name?Fe(t,s.calculative.worldRect,s.lineWidth):Be(t,s.calculative.worldRect),e){if(s.type===o.Node&&"line"===s.name&&!Je(t,s.calculative.worldAnchors))continue;if(this.store.data.locked||s.locked?this.externalElements.style.cursor=this.store.options.hoverCursor:this.hotkeyType===m.AddAnchor?this.externalElements.style.cursor="pointer":this.externalElements.style.cursor="move",s.calculative.disabled&&(this.externalElements.style.cursor="not-allowed"),this.store.hover=s,this.initTemplateCanvas([this.store.hover]),i=y.Node,this.store.pointAt=t,!t.ctrlKey){let{x:e,y:i,ex:n,ey:o,rotate:r,center:s}=this.store.hover.calculative.worldRect;if(r){const a=[{x:e,y:i},{x:n,y:i},{x:n,y:o},{x:e,y:o}];a.forEach((t=>{P(t,r,s)}));let l=a[a.length-1];for(const e of a){if(l.y>t.y!=e.y>t.y){const i=e.x+(t.y-e.y)*(l.x-e.x)/(l.y-e.y);Math.abs(i-this.store.pointAt.x)<10&&(this.store.pointAt.x=i)}l=e}}else this.store.pointAt.x-10n&&(this.store.pointAt.x=n),this.store.pointAt.y-10o&&(this.store.pointAt.y=o)}break}}}}return i},this.dockInAnchor=t=>{this.store.hover=void 0;for(let e=this.store.data.pens.length-1;e>=0;--e){const i=this.store.data.pens[e];if(0==i.visible||i.locked===r.Disable||i===this.store.active[0])continue;let n=xi(i);if(n+=2*this.store.options.anchorRadius,Fe(t,i.calculative.worldRect,n)&&(this.store.hover=i,this.hotkeyType!==m.Resize&&i.calculative.worldAnchors))for(const e of i.calculative.worldAnchors){if(e.twoWay===R.In){const t=se(this.store.active[0]);if(this.store.activeAnchor.id!==t.id)continue}if(e.twoWay===R.Out){const t=re(this.store.active[0]);if(this.store.activeAnchor.id!==t.id)continue}if(e.twoWay!==R.DisableConnected&&e.twoWay!==R.Disable&&this.store.activeAnchor?.twoWay!==R.DisableConnectTo&&this.store.activeAnchor?.twoWay!==R.Disable&&(this.title.hide(),this.inAnchor(t,i,e))){let n=Q(e);return Object.assign(n,t),this.title.show(n,i),!0}}}},this.render=t=>{if(t&&(this.opening=!1),this.opening)return;let e;if(null==t||!0===t||t===1/0?(e=performance.now(),this.patchFlags=!0):e=t>1?t:performance.now(),!this.patchFlags)return;if(e-this.lastRender{const t=this.offscreen.getContext("2d");t.strokeStyle=Wt(this.store);for(const e of this.store.data.pens)isFinite(e.x)&&e.canvasLayer!==l.CanvasTemplate&&e.calculative.inView&&(e.canvasLayer===l.CanvasMain&&"gif"!==e.name&&e.image&&e.calculative.img&&(t.save(),Mt(t,e),e.calculative.rotate&&Dt(t,e),ke(t,e),St(t,e),t.restore()),Ot(t,e));this.drawingLine&&Ot(t,this.drawingLine),this.pencilLine&&Ot(t,this.pencilLine),this.movingPens&&this.movingPens.forEach((e=>{this.renderPenContainChild(t,e)}))},this.renderPenContainChild=(t,e)=>{e.calculative.inView&&Ot(t,e),e.children?.forEach((e=>{const i=this.store.pens[e];i&&this.renderPenContainChild(t,i)}))},this.renderBorder=()=>{if(!this.store.data.locked&&this.activeRect&&(1!==this.store.active.length||!this.store.active[0].type)&&!this.movingPens){const t=this.offscreen.getContext("2d");t.save(),t.translate(.5,.5);const e=this.activeRect.pivot||this.activeRect.center;if(this.activeRect.rotate&&(t.translate(e.x,e.y),t.rotate(this.activeRect.rotate*Math.PI/180),t.translate(-e.x,-e.y)),t.strokeStyle=this.store.options.activeColor,t.globalAlpha=void 0===this.store.options.activeGlobalAlpha?.3:this.store.options.activeGlobalAlpha,t.beginPath(),t.lineWidth=this.store.options.activeLineWidth||1,t.setLineDash(this.store.options.activeLineDash||[]),t.strokeRect(this.activeRect.x,this.activeRect.y,this.activeRect.width,this.activeRect.height),t.setLineDash([]),t.lineWidth=1,t.globalAlpha=1,ve(this.store.active)||ge(this.store.active)||this.store.options.disableRotate)return void t.restore();t.beginPath(),t.moveTo(this.activeRect.center.x,this.activeRect.y),t.lineTo(this.activeRect.center.x,this.activeRect.y-30),t.stroke(),t.beginPath(),t.strokeStyle=this.store.options.activeColor,t.fillStyle="#ffffff",t.arc(this.activeRect.center.x,this.activeRect.y-30,5,0,2*Math.PI),t.fill(),t.stroke(),t.restore()}},this.renderHoverPoint=()=>{if(this.store.data.locked)return;const t=this.offscreen.getContext("2d");if(t.save(),t.translate(.5,.5),!this.store.options.disableAnchor&&this.store.hover&&!this.store.hover.disableAnchor&&(this.hotkeyType!==m.Resize||1!==this.store.active.length||this.store.active[0]!==this.store.hover)){const e=[...this.store.hover.calculative.worldAnchors];this.store.pointAt&&this.hotkeyType===m.AddAnchor&&e.push(this.store.pointAt),e&&(t.strokeStyle=this.store.hover.anchorColor||this.store.options.anchorColor,t.fillStyle=this.store.hover.anchorBackground||this.store.options.anchorBackground,e.forEach((e=>{if(e.hidden&&e.locked>r.DisableEdit)return;if(e===this.store.hoverAnchor){t.save();const e=this.store.hover.hoverAnchorColor||this.store.options.hoverAnchorColor;t.strokeStyle=e,t.fillStyle=e}t.beginPath();let i=e.radius||this.store.hover.anchorRadius||this.store.options.anchorRadius;if(!this.store.hover.type||e.radius||this.store.hover.anchorRadius||(i=3,this.store.hover.calculative.lineWidth>3&&(i=this.store.hover.calculative.lineWidth)),e.type===S.Line){let n=this.store.pens[e.penId].rotate||0;this.store.pens[e.penId].calculative.flipX&&(n*=-1),this.store.pens[e.penId].calculative.flipY&&(n*=-1);let o=e.rotate+n;this.store.pens[e.penId].calculative.flipX&&(o*=-1),this.store.pens[e.penId].calculative.flipY&&(o*=-1),t.save(),t.translate(e.x,e.y),t.rotate(o*Math.PI/180),t.translate(-e.x,-e.y),t.rect(e.x-e.length*this.store.data.scale/2,e.y-i,e.length*this.store.data.scale,2*i),t.restore()}else t.arc(e.x,e.y,i,0,2*Math.PI);if(this.store.hover.type&&this.store.hoverAnchor===e?(t.save(),t.strokeStyle=this.store.hover.activeColor||this.store.options.activeColor,t.fillStyle=t.strokeStyle):(e.color||e.background)&&(t.save(),t.strokeStyle=e.color,t.fillStyle=e.background),t.fill(),t.stroke(),e===this.store.hoverAnchor&&t.restore(),(this.store.hover.type&&this.store.hoverAnchor===e||e.color||e.background)&&t.restore(),!this.store.hover.parentId&&this.store.hover.children&&this.store.hover.children.length>0&&e===this.store.hoverAnchor){t.save(),t.beginPath(),t.lineWidth=3;const n=this.store.hover.hoverAnchorColor||this.store.options.hoverAnchorColor;globalThis.pSBC&&(t.strokeStyle=globalThis.pSBC(.5,n)),t.arc(e.x,e.y,i+1.5,0,2*Math.PI),t.stroke(),t.restore()}})))}this.hotkeyType===m.AddAnchor||this.movingPens||!this.activeRect||1===this.store.active.length&&this.store.active[0].type||ve(this.store.active)||me(this.store.active)||this.store.options.disableSize||(t.strokeStyle=this.store.options.activeColor,t.fillStyle="#ffffff",this.sizeCPs.forEach(((e,i)=>{this.activeRect.rotate&&(t.save(),t.translate(e.x,e.y),t.rotate(this.activeRect.rotate*Math.PI/180),t.translate(-e.x,-e.y)),(i<4||this.hotkeyType===m.Resize)&&(t.beginPath(),t.fillRect(e.x-4.5,e.y-4.5,8,8),t.strokeRect(e.x-5.5,e.y-5.5,10,10)),this.activeRect.rotate&&t.restore()}))),!this.store.data.locked&&this.dragRect&&(t.save(),t.fillStyle=ot(this.store.options.dragColor,.2),t.strokeStyle=this.store.options.dragColor,t.beginPath(),t.strokeRect(this.dragRect.x,this.dragRect.y,this.dragRect.width,this.dragRect.height),t.fillRect(this.dragRect.x,this.dragRect.y,this.dragRect.width,this.dragRect.height),t.restore()),this.dock&&(t.strokeStyle=this.store.options.dockColor,this.dock.xDock&&(t.beginPath(),t.moveTo(this.dock.xDock.x,this.dock.xDock.y),t.lineTo(this.dock.xDock.x,this.dock.xDock.prev.y),t.stroke()),this.dock.yDock&&(t.beginPath(),t.moveTo(this.dock.yDock.x,this.dock.yDock.y),t.lineTo(this.dock.yDock.prev.x,this.dock.yDock.y),t.stroke())),t.restore()},this.pastePen=(t,e)=>{const i=t.id;if(Oe(t),t.parentId=e,t.type===o.Line?this.changeNodeConnectedLine(i,t,this.store.clipboard.pens):this.changeLineAnchors(i,t,this.store.clipboard.pens),!t.parentId){const e=this.getPenRect(t,this.store.clipboard.origin,this.store.clipboard.scale),i=this.getPenRect(this.store.clipboard.initRect,this.store.clipboard.origin,this.store.clipboard.scale),{origin:n,scale:o}=this.store.data;t.x=n.x+e.x*o,t.y=n.y+e.y*o,t.width=e.width*o,t.height=e.height*o,i.x=n.x+i.x*o,i.y=n.y+i.y*o,ze(i),this.store.clipboard.pos&&(t.x-=i.center.x-this.store.clipboard.pos.x,t.y-=i.center.y-this.store.clipboard.pos.y),this.keyOptions&&this.keyOptions.altKey&&(this.keyOptions.ctrlKey||this.keyOptions.metaKey)?(t.x=-this.store.data.x+this.width/2-t.width/2,t.y=-this.store.data.y+this.height/2-t.height/2):this.keyOptions&&this.keyOptions.shiftKey&&(this.keyOptions.ctrlKey||this.keyOptions.metaKey)||(t.x+=this.store.clipboard.offset*this.store.data.scale,t.y+=this.store.clipboard.offset*this.store.data.scale)}this.makePen(t);const n=[];if(Array.isArray(t.children))for(const e of t.children){const i=this.store.clipboard.pens.find((t=>t.id===e));i&&n.push(this.pastePen(i,t.id).id)}return t.children=n,be(t,!0),t},this.ondblclick=t=>{!this.store.hover||this.store.data.locked&&!this.store.hover.dbInput||this.store.options.disableInput||(this.store.hover.onShowInput?this.store.hover.onShowInput(this.store.hover,t):this.showInput(this.store.hover)),this.store.emitter.emit("dblclick",{x:t.x,y:t.y,pen:this.store.hover})},this.showInput=(t,e,i="transparent")=>{if(!window||!this.store.hover||this.store.hover.locked||this.store.hover.externElement||this.store.hover.disableInput||this.store.hover.disabled)return;if(this.inputDiv.dataset.penId===t.id){this.inputDiv.dataset.isInput="true",this.inputDiv.contentEditable="true",this.inputDiv.focus();const t=window.getSelection();return t.selectAllChildren(this.inputDiv),t.collapseToEnd(),this.inputDiv.scrollTop=this.inputDiv.scrollHeight,void(this.inputDiv.scrollLeft=this.inputDiv.scrollWidth)}e||t.dbInput?(this.inputDiv.style.width="100%",this.inputDiv.style.height="100%"):this.setInputStyle(t);const n=e||t.calculative.worldTextRect,o=`${(void 0===t.calculative.tempText?t.text+""||"":t.calculative.tempText).replace(/\x20/g," ").split(/[\s\n]/).join("
")}
`.replace("","").replace(/\\<\/div\>/g,"

");this.inputDiv.innerHTML=o,this.inputParent.style.left=n.x+this.store.data.x-(t.textLeft||0)+"px",this.inputParent.style.top=n.y+this.store.data.y-(t.textTop||0)+"px";let r=n.width+(t.textLeft||0);this.inputParent.style.width=(r<0?12:r)+"px",this.inputParent.style.height=n.height+(t.textTop||0)+"px",this.inputParent.style.zIndex="9999",this.inputParent.style.background=i,t.rotate%360?this.inputParent.style.transform=`rotate(${t.rotate}deg)`:this.inputParent.style.transform=null,this.inputParent.style.display="flex",this.inputDiv.dataset.penId=t.id,this.inputDiv.contentEditable=null==t.disableInput?"true":t.disableInput.toString(),t.dropdownList&&"block"!==this.dropdown.style.display?(this.store.data.locked||(this.inputRight.style.display="none"),this.setDropdownList()):this.inputRight.style.display="none",this.inputDiv.contentEditable="true",this.inputDiv.focus();const s=window.getSelection();s.selectAllChildren(this.inputDiv),s.collapseToEnd(),this.inputDiv.scrollTop=this.inputDiv.scrollHeight,this.inputDiv.scrollLeft=this.inputDiv.scrollWidth,t.calculative.text=void 0,this.initTemplateCanvas([t]),this.render()},this.setInputStyle=t=>{let e;t.text||(t.text="");for(let t=0;t1?t.textLeft*o:t.textLeft*o/r}px;`),t.textTop&&(i+=`margin-top:${r>1?t.textTop*o:t.textTop*o/r}px;`),t.lineHeight&&(i+=`line-height:${r>1?t.fontSize*t.lineHeight*r:t.fontSize*t.lineHeight*o}px;`),t.textHeight)i+=`height:${r>1?t.textHeight*o*r:t.textHeight*o}px;`;else{let e=t.calculative.worldRect.height/r-(t.textTop||0);e<0&&(e=0);let n=t.fontSize*r<12?e*o:e*r*o;n-1?t.textWidth*t.calculative.worldRect.width:t.textWidth,"pre-line"!==t.whiteSpace&&(s1?s*o*r:s*o}px;`);else if(void 0===t.whiteSpace||"break-all"===t.whiteSpace){let e=(t.calculative.worldTextRect.width||12)/r;e<0&&(e=0),i+=`width:${t.fontSize*r<12?e*o:e*r}px;`}t.whiteSpace&&("pre-line"===t.whiteSpace?i+="white-space:pre;":(i+=`white-space:${t.whiteSpace};`,"nowrap"===t.whiteSpace&&(n+="display:contents;"))),"nowrap"!==t.whiteSpace&&1.2*t.fontSize*t.text.length>(s||t.calculative.worldRect.width/r)*Math.floor(t.calculative.worldRect.height/r/(t.lineHeight*t.fontSize))&&(i+="justify-content: start;"),e.deleteRule(0),e.deleteRule(0),e.insertRule(`.meta2d-input\n .input-div{\n resize:none;border:none;outline:none;background:transparent;position:absolute;flex-grow:1;height:100%;width: 100%;position:absolute;left:0;top:0;display:flex;flex-direction: column;cursor: text;${i}}`),e.insertRule(`.input-div div{${n}}`)},this.hideInput=()=>{if("flex"===this.inputParent.style.display){this.inputParent.style.display="none";const t=this.store.pens[this.inputDiv.dataset.penId];if(!t)return;if(t.calculative.text=t.text,this.inputDiv.dataset.value=this.inputDiv.innerHTML.replace(/\/g,"\n").replace(/\<\/div\>/g,"").replace(/\/g,"").replace(/ /g," ").replace(/(<([^>]+)>)/gi,""),this.inputDiv.dataset.value=this.convertSpecialCharacter(this.inputDiv.dataset.value),t.onInput)t.onInput(t,this.inputDiv.dataset.value);else if(t.text!==this.inputDiv.dataset.value){const e=[Q(t,!0)];t.text=this.inputDiv.dataset.value,t.calculative.text=t.text,this.inputDiv.dataset.penId=void 0,"text"===t.name&&t.textAutoAdjust&&function(t){let e=t.text.split("\n");const i=t.calculative.canvas,n=i.offscreen.getContext("2d"),{fontStyle:o,fontWeight:r,fontSize:s,fontFamily:a,lineHeight:l}=t.calculative;let c=0,h=0;n.save();for(let t=0;tc&&(c=h)}n.restore();let d=e.length*s*l;"left"===t.textAlign||("right"===t.textAlign?t.x=t.x-(c-t.width):t.x=t.x-(c-t.width)/2),"top"===t.textBaseline||("bottom"===t.textBaseline?t.y=t.y-(d-t.height):t.y=t.y-(d-t.height)/2),t.height=d+2,t.width=c+2,t.calculative.canvas.updatePenRect(t),t.calculative.canvas.calcActiveRect()}(t),q(t),this.patchFlags=!0,this.pushHistory({type:V.Update,pens:[Q(t,!0)],initPens:e}),this.store.emitter.emit("change",t),this.store.emitter.emit("valueUpdate",t)}else t.text===this.inputDiv.dataset.value&&0==t.calculative.textLines.length&&q(t);this.initTemplateCanvas([t])}this.inputDiv.dataset.penId=void 0,this.dropdown.style.display="none",this.inputDiv.dataset.isInput="false",this.inputDiv.contentEditable="false",this.render()},this.setDropdownList=t=>{this.clearDropdownList();const e=this.store.pens[this.inputDiv.dataset.penId];if(!this.store.data.locked&&!["tablePlus"].includes(e.name))return;if(this.dropdown.style.display="block",this.inputRight.style.display="block",setTimeout((()=>{this.inputRight.style.transform="rotate(315deg)",this.inputRight.style.zoom=this.store.data.scale})),!e||!e.dropdownList)return this.dropdown.style.display="none",this.inputRight.style.display="none",void(this.inputRight.style.transform="rotate(135deg)");if(!e.dropdownList.length){const t=document.createElement("div");return t.innerText="None",t.style.padding="5px 12px",t.style.color="#ddd",void this.dropdown.appendChild(t)}const i=this.inputDiv.innerHTML.replace(/\/g,"\n").replace(/\<\/div\>/g,"").replace(/\/g,"");let n=0;for(const o of e.dropdownList){const e="string"==typeof o?o:o.text;t&&i?e.includes(i)&&this.dropdownAppendOption(e,n):this.dropdownAppendOption(e,n),++n}if(!this.dropdown.hasChildNodes()){const t=document.createElement("div");t.innerText="None",t.style.padding="5px 12px",t.style.color="#ddd",this.dropdown.appendChild(t)}},this.selectDropdown=t=>{const e=t.target,i=this.store.pens[this.inputDiv.dataset.penId];if(!e||!i||!i.dropdownList)return;const n=+e.dataset.i,o=i.dropdownList[n];if(!o)return;const r=[Q(i,!0)];"object"==typeof o?(this.updateValue(i,{...o}),i.calculative.text=void 0,this.calcActiveRect()):i.text=o+"",this.inputDiv.innerText=i.text,this.hideInput(),this.pushHistory({type:V.Update,pens:[Q(i,!0)],initPens:r}),this.render(),this.store.emitter.emit("change",i),this.store.emitter.emit("valueUpdate",i)},this.inFitBorder=t=>{let e;const i=this.store.data.width||this.store.options.width,n=this.store.data.height||this.store.options.height;let o=(t.x-this.store.data.origin.x)/this.store.data.scale,r=(t.y-this.store.data.origin.y)/this.store.data.scale;const s=this.canvasImage.activeFit;this.externalElements.style.cursor="default",r>n*s.y-10&&rn*(s.y+s.height)-10&&ri*s.x-10&&oi*(s.x+s.width)-10&&o{this.patchFlags=!0,this.store.lastHover&&(this.store.lastHover.calculative.hover=!1),fe(this.store.data.pens.find((t=>!0===t.calculative.hover)),!1)},this.dialog=new dn(e),this.title=new pn(e),this.store.options.scroll&&(this.scroll=new an(this)),this.store.dpiRatio=globalThis.devicePixelRatio||1,this.store.dpiRatio<1?this.store.dpiRatio=1:this.store.dpiRatio>1&&this.store.dpiRatio<1.5&&(this.store.dpiRatio=1.5),this.clientRect=this.externalElements.getBoundingClientRect(),this.listen(),window?.addEventListener("resize",this.onResize),window?.addEventListener("scroll",this.onScroll)}listen(){switch(this.externalElements.addEventListener("gesturestart",this.onGesturestart),this.externalElements.ondragover=t=>t.preventDefault(),this.externalElements.ondrop=this.ondrop,this.externalElements.oncontextmenu=t=>t.preventDefault(),this.store.options.interval=50,this.externalElements.ontouchstart=this.ontouchstart,this.externalElements.ontouchmove=this.ontouchmove,this.externalElements.ontouchend=this.ontouchend,this.externalElements.onmousedown=t=>{this.onMouseDown({x:t.offsetX,y:t.offsetY,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:t.buttons})},this.externalElements.onmousemove=t=>{t.target===this.externalElements&&this.onMouseMove({x:t.offsetX,y:t.offsetY,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:t.buttons})},this.externalElements.onmouseup=t=>{this.onMouseUp({x:t.offsetX,y:t.offsetY,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,ctrlKey:t.ctrlKey||t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey,buttons:t.buttons,button:t.button})},this.externalElements.onmouseleave=t=>{this.store.data.pens.forEach((t=>{t.calculative.hover&&(t.calculative.hover=!1)})),this.store.hover&&(this.store.hover.calculative.hover=!1,this.store.hover=void 0),this.render(),t.toElement!==this.tooltip.box&&t.toElement!==this.tooltip.arrowUp&&t.toElement!==this.tooltip.arrowDown&&(this.tooltip.hide(),this.store.lastHover=void 0)},this.externalElements.ondblclick=this.ondblclick,this.externalElements.tabIndex=0,this.externalElements.onblur=()=>{this.mouseDown=void 0},this.externalElements.onwheel=this.onwheel,document.addEventListener("copy",this.onCopy),document.addEventListener("cut",this.onCut),document.addEventListener("paste",this.onPaste),this.store.options.keydown){case j.Document:document.addEventListener("keydown",this.onkeydown),document.addEventListener("keyup",this.onkeyup);break;case j.Canvas:this.externalElements.addEventListener("keydown",this.onkeydown),this.externalElements.addEventListener("keyup",this.onkeyup)}}splitLine(t,e){const i=t.calculative.worldAnchors,n=i.findIndex((t=>t===e));if([-1,0,i.length-1].includes(n))return;const o=Q(t,!0),r=Q(t,!0),s=at();r.id=s,r.calculative.canvas=this,r.calculative.active=!1,r.calculative.hover=!1;const a=Q(i.slice(0,n+1)),l=Q(i.slice(n)).map((t=>(t.penId=s,t)));t.calculative.worldAnchors=a,r.calculative.worldAnchors=l,this.initLineRect(t),this.initLineRect(r),this.store.data.pens.push(r),this.store.pens[s]=r,this.pushHistory({type:V.Add,pens:[Q(r,!0)],step:2}),this.pushHistory({type:V.Update,initPens:[o],pens:[Q(t,!0)],step:2})}translateAnchor(t,e){this.movingAnchor.x+=t,this.movingAnchor.y+=e;const i=this.movingAnchor.penId;if(i){const t=this.store.pens[i],e=t.calculative.worldRect;this.movingAnchor.xe.ex&&(this.movingAnchor.x=e.ex),this.movingAnchor.ye.ey&&(this.movingAnchor.y=e.ey);const n=Qe(this.movingAnchor,e),o=t.anchors.findIndex((t=>t.id===this.movingAnchor.id));t.anchors[o]=n,this.patchFlags=!0}}async fileToPen(t,e){let i="";return i=this.store.options.uploadFn?await this.store.options.uploadFn(t):this.store.options.uploadUrl?await async function(t,e,i,n){const o=new FormData;if(o.append("file",t),i)for(const t in i)i.hasOwnProperty(t)&&o.append(t,i[t]);const r=await fetch(e,{method:"POST",headers:n,body:o});return(await r.json()).url}(t,this.store.options.uploadUrl,this.store.options.uploadParams,this.store.options.uploadHeaders):await async function(t){return new Promise(((e,i)=>{const n=new FileReader;n.onload=t=>{e(t.target.result)},n.onerror=t=>{i(t)},n.readAsDataURL(t)}))}(t),new Promise(((t,n)=>{const o=new Image;o.onload=()=>{B.htmlElements[i]=o,t({width:o.width,height:o.height,name:e?"gif":"image",image:i})},o.onerror=t=>{n(t)},o.crossOrigin="anonymous",o.src=i}))}async dropPens(t,e){this.randomIdObj={};for(const e of t)!e.parentId&&this.randomCombineId(e,t);if(0!==Object.keys(this.randomIdObj).length)for(const e of t)e.type?(e.anchors[0].connectTo=this.randomIdObj[e.anchors[0].connectTo],e.anchors[e.anchors.length-1].connectTo=this.randomIdObj[e.anchors[e.anchors.length-1].connectTo]):e.connectedLines?.forEach((t=>{t.lineAnchor=this.randomIdObj[t.lineAnchor],t.lineId=this.randomIdObj[t.lineId]}));for(const e of t)e.id||(e.id=at()),!e.calculative&&(e.calculative={canvas:this}),this.store.pens[e.id]=e;let i=0,n=0,o=0;for(const r of t)r.parentId||(r.width*=this.store.data.scale,r.height*=this.store.data.scale,r.x=e.x-r.width/2+o,r.y=e.y-r.height/2+n,r.tags&&r.tags.includes("meta3d")&&(r.x=this.store.data.origin.x,r.y=this.store.data.origin.y),r.dataset&&(o=i%2==0?r.width-40*this.store.data.scale:0,i++,i%2==0&&(n+=r.height+10*this.store.data.scale)));const r=this.store.data.width||this.store.options.width,s=this.store.data.height||this.store.options.height;if(r&&s){let e={x:this.store.data.origin.x,y:this.store.data.origin.y,width:r*this.store.data.scale,height:s*this.store.data.scale},i=!0;for(const n of t)if(!n.parentId){let t=[{x:n.x,y:n.y},{x:n.x+n.width,y:n.y},{x:n.x,y:n.y+n.height},{x:n.x+n.width,y:n.y+n.height},{x:n.x+n.width/2,y:n.y+n.height/2}];if(n.x===e.x&&n.y===e.y&&n.width===e.width&&n.height===e.height||t.some((t=>Be(t,e)))){i=!1,this.store.options.strictScope&&(n.xe.x+e.width&&(n.x=e.x+e.width-n.width),n.y+n.height>e.y+e.height&&(n.y=e.y+e.height-n.height));break}}if(i)return void console.info("画笔在大屏范围外")}await this.addPens(t,!0),this.active(t.filter((t=>!t.parentId))),this.render(),this.externalElements.focus()}randomCombineId(t,e,i){let n=null;t.type?(t.anchors[0].connectTo||t.anchors[t.anchors.length-1].connectTo)&&(n=[t.id,t.anchors[0].id,t.anchors[t.anchors.length-1].id]):t.connectedLines&&t.connectedLines.length&&(n=[t.id]),Oe(t),n&&(1===n.length?this.randomIdObj[n[0]]=t.id:(this.randomIdObj[n[0]]=t.id,this.randomIdObj[n[1]]=t.anchors[0].id,this.randomIdObj[n[2]]=t.anchors[t.anchors.length-1].id)),t.parentId=i;const o=[];if(Array.isArray(t.children))for(const i of t.children){const n=e.find((t=>t.id===i));n&&o.push(this.randomCombineId(n,e,t.id).id)}return t.children=o,t}async addPens(t,e){if(this.beforeAddPens&&1!=await this.beforeAddPens(t))return[];const i=[];for(const e of t)this.beforeAddPen&&1!=this.beforeAddPen(e)||(this.makePen(e),i.push(e));return this.render(),this.store.emitter.emit("add",i),e&&this.pushHistory({type:V.Add,pens:Q(i,!0)}),i}getInitPencilLine(t){const{data:e,options:i}=this.store,n=e.scale,r=e.lineWidth||1;return{id:t.penId,name:"line",x:t.x,y:t.y,type:o.Line,calculative:{canvas:this,pencil:!0,active:!0,worldAnchors:[t],lineWidth:r*n},fromArrow:e.fromArrow||i.fromArrow,toArrow:e.toArrow||i.toArrow,lineWidth:r}}createDrawingLine(t){this.inactive();const{data:e,options:i}=this.store,n=e.scale,r=e.lineWidth||1;return t.penId=at(),{id:t.penId,name:"line",lineName:this.drawingLineName,x:t.x,y:t.y,type:o.Line,calculative:{canvas:this,active:!0,worldAnchors:[t],lineWidth:r*n},fromArrow:e.fromArrow||i.fromArrow,toArrow:e.toArrow||i.toArrow,lineWidth:r}}addRuleLine(t){const{x:e,y:i,scale:n,origin:r}=this.store.data,s=t.x+e,a=t.y+i;let l=t.x,c=t.y,h=0,d=0,u=0,f=0;if(s<=a&&s<20)l=-e,h=this.width,u=1,t.ctrlKey||(c=Math.round((c-r.y)/(10*n))*(10*n)+r.y);else{if(!(at.isRuleLine))}alignPenToGrid(t){if(this.store.options.autoAlignGrid&&this.store.data.grid&&!t.type){const e=this.store.data.gridSize||this.store.options.gridSize,{origin:i,scale:n}=this.store.data,{x:o,y:r}=t,s={x:o,y:r},a=this.getPenRect(t),l=parseInt((a.x/e).toFixed())*e,c=parseInt((a.y/e).toFixed())*e;s.x=i.x+l*n,s.y=i.y+c*n,Object.assign(t,s),t.onMove?.(t),this.updatePenRect(t),this.calcActiveRect(),this.getSizeCPs()}}movedActivePens(t){let e=this.getAllFollowersByPens(this.store.active,!1);const i=Q(e,!0),n=this.store.data.gridSize||this.store.options.gridSize,{origin:o,scale:r}=this.store.data,s=this.store.options.autoAlignGrid&&this.store.data.grid;if(e.forEach((t=>{const e=this.movingPens.findIndex((e=>e.id===t.id+gn));if(e<0)return;const{x:i,y:a}=this.movingPens[e],l={x:i,y:a};if(s&&!this.movingPens[e].type){const t=this.getPenRect(this.movingPens[e]),i=parseInt((t.x/n).toFixed()),s=parseInt((t.y/n).toFixed()),a=i*n,c=s*n;l.x=o.x+a*r,l.y=o.y+c*r}Object.assign(t,l),t.onMove?.(t),this.updatePenRect(t),this.updateLines(t),this.store.emitter.emit("updateLines",t),this.patchFlagsLines.forEach((t=>{t.type&&this.initLineRect(t)})),this.patchFlagsLines.clear(),t.calculative.x=t.x,t.calculative.y=t.y,t.calculative.initRect&&(t.calculative.initRect.x=t.calculative.x,t.calculative.initRect.y=t.calculative.y,t.calculative.initRect.ex=t.calculative.x+t.calculative.width,t.calculative.initRect.ey=t.calculative.y+t.calculative.height),$t(t)})),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),!this.dock)return;const{xDock:a,yDock:l}=this.dock;let c;a&&(c=this.store.pens[a.penId]),!c&&l&&(c=this.store.pens[l.penId]);const h=Q(this.store.active,!0);if(t&&1===this.store.active.length&&1===c?.type&&(a?.anchorId||l?.anchorId)){const t=re(c),e=se(c);if(a?.anchorId){const n=this.store.pens[this.store.active[0].id+gn].calculative.worldAnchors.find((t=>t.id===a.anchorId));n.x===t.x&&n.y===t.y?(i.push(Q(c,!0)),ie(this.store.active[0],n,c,t),h.push(Q(c,!0))):n.x===e.x&&n.y===e.y&&(i.push(Q(c,!0)),ie(this.store.active[0],n,c,e),h.push(Q(c,!0)))}else if(l?.anchorId){const n=this.store.pens[this.store.active[0].id+gn].calculative.worldAnchors.find((t=>t.id===l.anchorId));n.x===t.x&&n.y===t.y?(i.push(Q(c,!0)),ie(this.store.active[0],n,c,t),h.push(Q(c,!0))):n.x===e.x&&n.y===e.y&&(i.push(Q(c,!0)),ie(this.store.active[0],n,c,e),h.push(Q(c,!0)))}}s&&(this.calcActiveRect(),this.getSizeCPs()),this.pushHistory({type:V.Update,pens:h,initPens:i}),this.store.emitter.emit("translatePens",h)}copyMovedPens(){this.copy(this.store.active.map(((t,e)=>{const{x:i,y:n}=this.movingPens[e];return this.updateLines(t),{...t,x:i,y:n}}))),this.pasteOffset=!1,this.paste()}initImageCanvas(t){t.some((t=>this.hasImage(t,!1)))&&this.canvasImage.init(),t.some((t=>this.hasImage(t,!0)))&&this.canvasImageBottom.init()}initTemplateCanvas(t){t.some((t=>t.canvasLayer===l.CanvasTemplate))&&this.canvasTemplate.init()}hasImage(t,e){return t.image&&"gif"!==t.name?e?t.canvasLayer===l.CanvasImageBottom:t.canvasLayer===l.CanvasImage:t.children?.some((t=>{const i=this.store.pens[t];return i&&this.hasImage(i,e)}))}inactive(t){this.store.active.length&&(this.initTemplateCanvas(this.store.active),this.store.active.forEach((t=>{t.calculative.active=void 0,t.calculative.activeAnchor=void 0,t.calculative.hover=!1,ue(t,!1)})),!t&&this.store.emitter.emit("inactive",this.store.active),this.store.active=[],this.activeRect=void 0,this.sizeCPs=void 0,this.store.activeAnchor=void 0,this.patchFlags=!0)}active(t,e=!0){if(this.store.active){e&&this.store.emitter.emit("inactive",this.store.active);for(const t of this.store.active)t.calculative.active=void 0,t.calculative.hover=!1,ue(t,!1)}this.store.active=[],t.forEach((t=>{t.calculative.active=!0,ue(t)})),this.store.active.push(...t),this.activeRect=void 0,this.calcActiveRect(),this.initTemplateCanvas(t),this.patchFlags=!0,e&&this.store.emitter.emit("active",this.store.active)}getSizeCPs(){this.sizeCPs=Ue(this.activeRect);const{x:t,y:e,width:i,height:n,rotate:o,center:r}=this.activeRect;[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}].forEach((s=>{const a={x:s.x*i+t,y:s.y*n+e};P(a,o,r),this.sizeCPs.push(a)}))}getSpecialAngle(t,e){let i=0;t.x-e.x!=0?(i=180*Math.atan((e.y-t.y)/(t.x-e.x))/Math.PI,t.x0?i-=180:i+=180)):e.y>t.y?i=90:e.yr.DisableEdit)return y.None;if((!e.type||!e.calculative.active)&&this.store.options.disableAnchor||e.disableAnchor)return y.None;if((this.mouseDown||this.drawingLine)&&"line"===e.name&&i.connectTo){const t=this.findOne(i.connectTo);if(t?.calculative&&!t?.calculative.active){e=t;const n=t.calculative.worldAnchors.find((t=>t.id===i.anchorId));n&&(i=n)}}if(i.twoWay===R.Disable&&"line"!==e.name)return y.None;if("line"===e.name&&i.connectTo){let t=this.findOne(i.connectTo)?.anchors.find((t=>t.id===i.anchorId));if(t&&t.twoWay)return y.None}if(this.drawingLine){if(i.twoWay===R.Out)return y.None}else if(this.mouseDown&&this.hoverType===y.LineAnchor);else if(i.twoWay===R.In)return y.None;if(E(t,i,this.pointSize,i.penId?this.store.pens[i.penId]:void 0))return i!==this.store.hoverAnchor&&(this.patchFlags=!0),this.store.hoverAnchor=i,this.store.hover=e,e.type?i.connectTo&&!e.calculative.active&&(this.store.hover=this.store.pens[i.connectTo],this.store.hover)?(this.store.hoverAnchor=this.store.hover.calculative.worldAnchors.find((t=>t.id===i.anchorId)),this.store.hoverAnchor?(this.externalElements.style.cursor="crosshair",y.NodeAnchor):y.None):(this.hotkeyType===m.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="pointer",y.LineAnchor):(this.hotkeyType===m.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="crosshair",y.NodeAnchor);if(!this.mouseDown&&e.type){if(e.calculative.active&&i.prev&&E(t,i.prev,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=e,this.externalElements.style.cursor="pointer",y.LineAnchorPrev;if(e.calculative.active&&i.next&&E(t,i.next,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=e,this.externalElements.style.cursor="pointer",y.LineAnchorNext}return y.None}resize(t,e){t=t||this.parentElement.clientWidth,e=e||this.parentElement.clientHeight,this.width=t,this.height=e,this.canvasRect={x:0,y:0,width:t,height:e},He(this.canvasRect),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.externalElements.style.width=t+"px",this.externalElements.style.height=e+"px",this.canvasTemplate.resize(t,e),this.canvasImage.resize(t,e),this.canvasImageBottom.resize(t,e),this.magnifierCanvas.resize(t,e),t=t*this.store.dpiRatio|0,e=e*this.store.dpiRatio|0,this.canvas.width=t,this.canvas.height=e,this.offscreen.width=t,this.offscreen.height=e,this.clientRect=this.externalElements.getBoundingClientRect(),this.canvas.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").scale(this.store.dpiRatio,this.store.dpiRatio),this.offscreen.getContext("2d").textBaseline="middle";for(const t of this.store.data.pens)t.isRuleLine&&(t.width?t.height||(t.width=this.width):t.height=this.height),be(t);this.render()}clearCanvas(){this.activeRect=void 0,this.sizeCPs=void 0,this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height),this.offscreen.getContext("2d").clearRect(0,0,this.offscreen.width,this.offscreen.height),this.store.data.template||this.canvasTemplate.clear(),this.canvasImage.clear(),this.canvasImageBottom.clear()}async addPen(t,e,i){if(!(this.beforeAddPens&&1!=await this.beforeAddPens([t])||this.beforeAddPen&&1!=this.beforeAddPen(t)))return this.makePen(t),this.active([t]),this.render(),i&&this.store.emitter.emit("add",[t]),e&&this.pushHistory({type:V.Add,pens:[t]}),t}pushHistory(t){if(this.store.data.locked)return;const{origin:e,scale:i}=this.store.data;t.origin=Q(e),t.scale=i,t.type!==V.Update&&t.pens&&t.pens.forEach((t=>{t.calculative&&(t.calculative.layer=this.store.data.pens.findIndex((e=>e.id===t.id)))})),this.store.historyIndex{let i;if(t.initPens)for(const n of t.initPens)n.id===e.id&&(i=n);if(i)for(const t in e)null==i[t]&&(i[t]=void 0)})),this.store.histories.push(t),this.store.historyIndex=this.store.histories.length-1,this.store.emitter.emit("update",{previous:t.initPens,current:t.pens})}undo(){if(this.store.data.locked||null==this.store.historyIndex||this.store.historyIndex<0)return;const t=this.store.histories[this.store.historyIndex--];this.doEditAction(t,!0);let e=t.step;for(;e>1;){const t=this.store.histories[this.store.historyIndex--];this.doEditAction(t,!0),e--}t.type!=V.Add&&t.type!=V.Delete&&t.type!=V.Update||this.activeHistory()}redo(){if(this.store.data.locked||null==this.store.historyIndex||this.store.historyIndex>this.store.histories.length-2)return;const t=this.store.histories[++this.store.historyIndex];this.doEditAction(t,!1);let e=t.step;for(;e>1;){const t=this.store.histories[++this.store.historyIndex];this.doEditAction(t,!1),e--}t.type!=V.Add&&t.type!=V.Delete&&t.type!=V.Update||this.activeHistory()}activeHistory(){let t=this.store.histories[this.store.historyIndex+1];const e=[];if(t&&t.type===V.Update)return t.pens.forEach((t=>{e.push(this.store.pens[t.id])})),void this.active(e);let i=this.store.histories[this.store.historyIndex];!i||i.type!==V.Add&&i.type!==V.Delete||(i.pens.forEach((t=>{e.push(this.store.pens[t.id])})),this.active(e))}doEditAction(t,e){switch(this.inactive(),this.store.hoverAnchor=void 0,this.store.hover=void 0,t.type){case V.Add:t.pens.forEach((t=>{const e=Q(t,!0),i=this.store.data.pens.findIndex((t=>t.id===e.id));i>-1&&(e.onDestroy?.(this.store.pens[e.id]),this.store.data.pens.splice(i,1),this.store.pens[e.id]=void 0,e.calculative||(e.calculative={}),e.calculative.canvas=this,this.store.animates.delete(e),this.store.animateMap.delete(e))})),t.type=V.Delete;break;case V.Update:const i=e?t.initPens:t.pens,n=e?t.pens:t.initPens;i.forEach((e=>{const i=Q(e,!0),o=this.store.data.pens.findIndex((t=>t.id===i.id));if(o>-1){if(i.calculative=this.store.data.pens[o].calculative,this.store.data.pens[o].type&&this.store.data.pens[o].lastConnected)for(let t in this.store.data.pens[o].lastConnected)this.store.pens[t]&&(this.store.pens[t].connectedLines=this.store.data.pens[o].lastConnected[t]);this.store.data.pens[o]=i,this.store.pens[i.id]=i;for(const t in i)"object"==typeof i[t]&&"lineDash"!==t||(i.calculative[t]=i[t]);i.calculative.image=void 0;const e=this.getPenRect(i,t.origin,t.scale);if(this.setPenRect(i,e,!1),this.updateLines(i,!0),i.calculative.canvas.parent.isCombine(i)){let t=n.find((t=>t.id===i.id));A.forEach((e=>{i[e]!==t[e]&&this.parent.setValue({id:i.id,[e]:i[e]},{render:!0,doEvent:!1})}))}}}));break;case V.Delete:t.pens.reverse().forEach((t=>{const e=Q(t,!0);if(e.calculative||(e.calculative={}),this.store.data.pens.splice(-1!==e.calculative?.layer?e.calculative?.layer:this.store.data.pens.length,0,e),this.store.pens[e.id]=e,e.type&&e.lastConnected)for(let t in e.lastConnected)this.store.pens[t]&&(this.store.pens[t].connectedLines=e.lastConnected[t]);e.calculative.canvas=this})),t.pens.reverse().forEach((e=>{const i=this.store.pens[e.id],n=this.getPenRect(i,t.origin,t.scale);this.setPenRect(i,n,!1),i.calculative.image=void 0,i.calculative.backgroundImage=void 0,i.calculative.strokeImage=void 0,this.loadImage(i)})),t.type=V.Add;break;case V.Replace:{const i=e?t.initPens:t.pens;(e?t.pens:t.initPens).forEach((t=>{const e=Q(t,!0);if(this.store.data.pens.findIndex((t=>t.id===e.id))>-1){e.onDestroy?.(this.store.data.pens.find((t=>t.id===e.id)));const t=this.store.data.pens.findIndex((t=>t.id===e.id));this.store.data.pens.splice(t,1),this.store.pens[e.id]=void 0,e.calculative||(e.calculative={}),e.calculative.canvas=this,this.store.animates.delete(e),this.store.animateMap.delete(e)}})),i.reverse().forEach((t=>{const e=Q(t,!0);if(e.calculative||(e.calculative={}),this.store.data.pens.splice(-1!==e.calculative?.layer?e.calculative?.layer:this.store.data.pens.length,0,e),this.store.pens[e.id]=e,e.type&&e.lastConnected)for(let t in e.lastConnected)this.store.pens[t]&&(this.store.pens[t].connectedLines=e.lastConnected[t]);e.calculative.canvas=this})),i.reverse().forEach((e=>{const i=this.store.data.pens.find((t=>t.id===e.id)),n=this.getPenRect(i,t.origin,t.scale);this.setPenRect(i,n,!1),i.calculative.image=void 0,i.calculative.backgroundImage=void 0,i.calculative.strokeImage=void 0,this.loadImage(i)})),t.type=V.Replace;break}}if(t.type===V.Update){let e=[...t.pens,...t.initPens];this.initImageCanvas(e),this.initTemplateCanvas(e)}else this.initImageCanvas(t.pens),this.initTemplateCanvas(t.pens);this.parent.onSizeUpdate(),this.render(),this.store.emitter.emit(e?"undo":"redo",t)}makePen(t){if(t.id||(t.id=at()),Math.abs(this.store.lastScale-this.store.data.scale)<1e-4&&this.store.sameTemplate&&this.store.templatePens[t.id]&&t.canvasLayer===l.CanvasTemplate)return t=this.store.templatePens[t.id],this.store.data.pens.push(t),void this.updatePenRect(t);if(this.store.data.pens.push(t),this.store.pens[t.id]=t,t.path){!t.pathId&&(t.pathId=at());const e=this.store.data.paths;!e[t.pathId]&&(e[t.pathId]=t.path),t.path=void 0}null==t.lineWidth&&(t.lineWidth=1);const{fontSize:e,lineHeight:i}=this.store.options;t.fontSize||(t.fontSize=e),t.lineHeight||(t.lineHeight=i),t.image&&"gif"!==t.name&&void 0===t.canvasLayer&&(t.isBottom?t.canvasLayer=l.CanvasImageBottom:t.canvasLayer=l.CanvasImage,delete t.isBottom),t.template&&(t.canvasLayer=l.CanvasTemplate),t.calculative={canvas:this,singleton:t.calculative?.singleton},(t.video||t.audio)&&(t.calculative.onended=t=>{this.nextAnimate(t)});for(const e in t)"object"==typeof t[e]&&"lineDash"!==e||(t.calculative[e]=t[e]);if(t.calculative.image=void 0,t.calculative.backgroundImage=void 0,t.calculative.strokeImage=void 0,!t.anchors&&B.anchors[t.name]&&(t.anchors||(t.anchors=[]),B.anchors[t.name](t)),!t.anchors){const e=Q(this.store.options.defaultAnchors);e.forEach(((e,i)=>{e.id=`${i}`,e.penId=t.id})),t.anchors=e}this.updatePenRect(t),!t.anchors&&t.calculative.worldAnchors&&(t.anchors=t.calculative.worldAnchors.map((e=>Qe(e,t.calculative.worldRect)))),!t.rotate&&(t.rotate=0),this.loadImage(t),this.parent.penNetwork(t)}drawline(t){this.drawingLine&&(this[this.drawingLineName]?.(this.store,this.drawingLine,t),this.store.path2dMap.set(this.drawingLine,B.path2dDraws.line(this.drawingLine)),this.patchFlags=!0)}initLineRect(t){if(!t)return;if(!t.calculative.worldAnchors?.length)return void this._del([t]);if(!isFinite(t.x)||!isFinite(t.x))return;if(null==t.x||null==t.y)return;const e=mi(t);t.parentId||Object.assign(t,e);const{fontSize:i,lineHeight:n}=this.store.options;t.fontSize||(t.fontSize=i,t.calculative.fontSize=t.fontSize*this.store.data.scale),t.lineHeight||(t.lineHeight=n,t.calculative.lineHeight=t.lineHeight),ze(e),t.calculative.worldRect=e,qt(t,e),q(t),be(t),t.calculative&&(t.calculative.gradientAnimatePath=void 0),this.store.path2dMap.set(t,B.path2dDraws[t.name](t)),t.calculative.worldAnchors&&(t.anchors=t.calculative.worldAnchors.map((e=>Qe(e,t.calculative.worldRect))))}drawingPencil(){hn(this.store),this.pencil=!0,this.externalElements.style.cursor="crosshair"}stopPencil(){this.pencil=!1,this.pencilLine=void 0,this.externalElements.style.cursor="default"}async finishDrawline(t){if(!this.drawingLine)return;const e=re(this.drawingLine);let i=se(this.drawingLine);if(i.isTemp&&(this.drawingLine.calculative.worldAnchors.pop(),i=se(this.drawingLine)),!t&&(!i.connectTo&&this.drawingLine.calculative.worldAnchors.pop(),re(this.drawingLine)===this.drawingLine.calculative.activeAnchor))return this.drawingLine=void 0,void this.render();if(e.connectTo&&i.connectTo){if(this.store.options.disableRepeatLine&&this.store.data.pens.find((t=>{if(t.type){const n=re(t),o=se(t);return D(n,e)&&D(o,i)}})))return this.drawingLine=void 0,void this.render()}else if(this.store.options.disableEmptyLine)return e.connectTo&&(this.store.pens[e.connectTo].connectedLines=this.store.pens[e.connectTo].connectedLines.filter((t=>t.lineId!==this.drawingLine.id))),this.drawingLine=void 0,void this.render();const n=mi(this.drawingLine);Object.assign(this.drawingLine,n),this.drawingLine.calculative.worldRect=n,this.drawingLine.calculative.activeAnchor=se(this.drawingLine),this.store.activeAnchor=this.drawingLine.calculative.activeAnchor,(!this.beforeAddPens||await this.beforeAddPens([this.drawingLine]))&&(!this.beforeAddPen||this.beforeAddPen(this.drawingLine))&&(this.initLineRect(this.drawingLine),this.store.data.pens.push(this.drawingLine),this.store.pens[this.drawingLine.id]=this.drawingLine,this.store.emitter.emit("add",[this.drawingLine]),this.active([this.drawingLine]),this.pushHistory({type:V.Add,pens:Q([this.drawingLine],!0)})),this.store.path2dMap.set(this.drawingLine,B.path2dDraws[this.drawingLine.name](this.drawingLine)),this.drawingLine=void 0,this.drawingLineName=void 0,this.render()}async finishPencil(){if(this.pencilLine){const t=Di(this.pencilLine.calculative.worldAnchors,10,0,this.pencilLine.calculative.worldAnchors.length-1);let e=re(this.pencilLine);t.unshift({id:e.id,penId:e.penId,x:e.x,y:e.y}),e=se(this.pencilLine),t.push({id:e.id,penId:e.penId,x:e.x,y:e.y}),this.pencilLine.calculative.worldAnchors=function(t,e=.8,i=!1){if(t.length<3)return t;let n,o,r,s,a,l,c,h,d,u,f,p,v,g,y,m;const w=(t,e,i,n)=>(s=Math.sqrt(t*t+e*e),s>0?(v=t/s,y=e/s):(v=1,y=0),a=Math.sqrt(i*i+n*n),a>0?(g=i/a,m=n/a):(g=1,m=0),Math.acos(v*g+y*m));f=[],p=t.length,n=t[0],h=t[p-1],f.push({...t[0]});for(let h=0;h1&&(this.pencilLine.calculative.pencil=!1,this.store.path2dMap.set(this.pencilLine,B.path2dDraws[this.pencilLine.name](this.pencilLine)),(!this.beforeAddPens||await this.beforeAddPens([this.pencilLine]))&&(!this.beforeAddPen||this.beforeAddPen(this.pencilLine))&&(this.initLineRect(this.pencilLine),this.store.data.pens.push(this.pencilLine),this.store.pens[this.pencilLine.id]=this.pencilLine,this.store.emitter.emit("add",[this.pencilLine]),this.active([this.pencilLine]),this.pushHistory({type:V.Add,pens:Q([this.pencilLine],!0)}))),this.pencilLine=void 0,this.render()}}firefoxLoadSvg(t){const e=new Image,i=new XMLHttpRequest;i.open("GET",t.image,!0),i.onload=()=>{const n=(new DOMParser).parseFromString(i.responseText,"text/xml").getElementsByTagName("svg")[0],{width:o,height:r}=t.calculative.worldRect;n.setAttribute("width",`${o}px`),n.setAttribute("height",`${r}px`);const s="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent((new XMLSerializer).serializeToString(n))));e.src=s,e.onload=()=>{t.calculative.img=e,t.calculative.imgNaturalWidth=e.naturalWidth||t.iconWidth,t.calculative.imgNaturalHeight=e.naturalHeight||t.iconHeight,B.htmlElements[t.image]=e,this.imageLoaded(),t.canvasLayer===l.CanvasTemplate&&this.templateImageLoaded()}},i.send()}loadImage(t){if(t.image!==t.calculative.image||!t.calculative.img){if(t.calculative.img=void 0,t.image)if(B.htmlElements[t.image]){const e=B.htmlElements[t.image];t.calculative.img=e,t.calculative.imgNaturalWidth=e.naturalWidth||t.iconWidth,t.calculative.imgNaturalHeight=e.naturalHeight||t.iconHeight,this.imageLoaded(),t.canvasLayer===l.CanvasTemplate&&this.templateImageLoaded()}else if(navigator.userAgent.includes("Firefox")&&t.image.endsWith(".svg"))this.firefoxLoadSvg(t);else{const e=new Image;e.crossOrigin="undefined"===t.crossOrigin?void 0:t.crossOrigin||"anonymous",e.src=t.image,this.store.options.cdn&&!(t.image.startsWith("http")||t.image.startsWith("//")||t.image.startsWith("data:image"))&&(e.src=this.store.options.cdn+t.image),e.onload=()=>{t.calculative.img=e,t.calculative.imgNaturalWidth=e.naturalWidth||t.iconWidth,t.calculative.imgNaturalHeight=e.naturalHeight||t.iconHeight,B.htmlElements[t.image]=e,this.imageLoaded(),t.canvasLayer===l.CanvasTemplate&&this.templateImageLoaded()}}t.calculative.image=t.image}if(t.backgroundImage!==t.calculative.backgroundImage){if(t.calculative.backgroundImg=void 0,t.backgroundImage)if(B.htmlElements[t.backgroundImage]){const e=B.htmlElements[t.backgroundImage];t.calculative.backgroundImg=e}else{const e=new Image;e.crossOrigin="anonymous",e.src=t.backgroundImage,this.store.options.cdn&&!(t.backgroundImage.startsWith("http")||t.backgroundImage.startsWith("//")||t.backgroundImage.startsWith("data:image"))&&(e.src=this.store.options.cdn+t.backgroundImage),e.onload=()=>{t.calculative.backgroundImg=e,B.htmlElements[t.backgroundImage]=e,this.imageLoaded(),t.canvasLayer===l.CanvasTemplate&&this.templateImageLoaded()}}t.calculative.backgroundImage=t.backgroundImage}if(t.strokeImage!==t.calculative.strokeImage){if(t.calculative.strokeImg=void 0,t.strokeImage)if(B.htmlElements[t.strokeImage]){const e=B.htmlElements[t.strokeImage];t.calculative.strokeImg=e}else{const e=new Image;e.crossOrigin="anonymous",e.src=t.strokeImage,this.store.options.cdn&&!(t.strokeImage.startsWith("http")||t.strokeImage.startsWith("//")||t.strokeImage.startsWith("data:image"))&&(e.src=this.store.options.cdn+t.strokeImage),e.onload=()=>{t.calculative.strokeImg=e,B.htmlElements[t.strokeImage]=e,this.imageLoaded(),t.canvasLayer===l.CanvasTemplate&&"gif"!==t.name&&this.templateImageLoaded()}}t.calculative.strokeImage=t.strokeImage}}imageLoaded(){this.imageTimer&&clearTimeout(this.imageTimer),this.imageTimer=setTimeout((()=>{this.canvasImage.init(),this.canvasImageBottom.init(),this.render()}),100)}templateImageLoaded(){this.templateImageTimer&&clearTimeout(this.templateImageTimer),this.templateImageTimer=setTimeout((()=>{this.canvasTemplate.init(),this.render()}),100)}setCalculativeByScale(t){const e=this.store.data.scale;t.calculative.lineWidth=t.lineWidth*e,t.calculative.fontSize=t.fontSize*e,t.fontSize<1&&(t.calculative.fontSize=t.fontSize*t.calculative.worldRect.height),t.calculative.iconSize=t.iconSize*e,t.calculative.iconWidth=t.iconWidth*e,t.calculative.iconHeight=t.iconHeight*e,t.calculative.iconLeft=t.iconLeft<1&&t.iconLeft>-1?t.iconLeft:t.iconLeft*e,t.calculative.iconTop=t.iconTop<1&&t.iconTop>-1?t.iconTop:t.iconTop*e,t.calculative.textWidth=t.textWidth<1&&t.textWidth>-1?t.textWidth:t.textWidth*e,t.calculative.textHeight=t.textHeight<1&&t.textHeight>-1?t.textHeight:t.textHeight*e,t.calculative.textLeft=t.textLeft<1&&t.textLeft>-1?t.textLeft*t.calculative.worldRect.width:t.textLeft*e,t.calculative.textTop=t.textTop<1&&t.textTop>-1?t.textTop*t.calculative.worldRect.height:t.textTop*e,t.type===o.Line&&t.borderWidth&&(t.calculative.borderWidth=t.borderWidth*e)}updatePenRect(t,{worldRectIsReady:e,playingAnimate:i}={}){e?Kt(t):Vt(t),i||this.setCalculativeByScale(t),Yt(t),Xt(this.store.pens,t),q(t),be(t),B.path2dDraws[t.name]&&this.store.path2dMap.set(t,B.path2dDraws[t.name](t)),t.calculative.patchFlags=!0,this.patchFlags=!0,t.children&&t.children.forEach((t=>{const e=this.store.pens[t];e&&this.updatePenRect(e,{worldRectIsReady:!1})})),t.type&&this.initLineRect(t),t.calculative.gradientTimer&&clearTimeout(t.calculative.gradientTimer),t.calculative.gradientTimer=setTimeout((()=>{t.calculative.lineGradient&&(t.calculative.lineGradient=null),t.calculative.gradient&&(t.calculative.gradient=null),t.calculative.radialGradient&&(t.calculative.radialGradient=null),this.patchFlags=!0,t.calculative.gradientTimer=void 0}),50)}translate(t=0,e=0){if(this.store.data.x+=t*this.store.data.scale,this.store.data.y+=e*this.store.data.scale,this.store.data.x=Math.round(this.store.data.x),this.store.data.y=Math.round(this.store.data.y),this.store.options.padding){let t=lt(this.store.options.padding);const e=this.store.data.width||this.store.options.width,i=this.store.data.height||this.store.options.height;this.width<(e+t[1]+t[3])*this.store.data.scale&&(this.store.data.x+this.store.data.origin.x>t[3]*this.store.data.scale&&(this.store.data.x=t[3]*this.store.data.scale-this.store.data.origin.x),this.store.data.x+this.store.data.origin.x+e*this.store.data.scalet[0]*this.store.data.scale&&(this.store.data.y=t[0]*this.store.data.scale-this.store.data.origin.y),this.store.data.y+this.store.data.origin.y+i*this.store.data.scale=i&&t<=n))return;this.calibrateMouse(e);const o=t/this.store.data.scale;this.store.data.scale=t,this.store.data.center=e,this.store.clipboard?.pos&&I(this.store.clipboard.pos,o,e),I(this.store.data.origin,o,e),this.store.data.pens.forEach((t=>{if(!t.parentId){if(Gt(t,o,e),t.onScale&&t.onScale(t),t.isRuleLine){const e=1/o,i=t.calculative.worldRect.center;t.width&&t.height||Gt(t,e,i)}this.updatePenRect(t,{worldRectIsReady:!0}),this.execPenResize(t)}})),this.onMovePens(),this.calcActiveRect(),this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init();const r=this.parent.map;r&&r.isShow&&r.setView(),this.render(),this.store.emitter.emit("scale",this.store.data.scale)}templateScale(t,e={x:0,y:0}){const{minScale:i,maxScale:n}=this.store.options;if(!(t>=i&&t<=n))return;const o=t/this.store.data.scale;this.store.data.scale=t,this.store.data.center={x:0,y:0},this.store.data.origin={x:0,y:0},this.store.data.pens.forEach((t=>{if(!t.parentId){if(Gt(t,o,e),t.onScale&&t.onScale(t),t.isRuleLine){const e=o>1?1:1/o/o,i=t.calculative.worldRect.center;t.width&&t.height||Gt(t,e,i)}this.execPenResize(t)}})),this.calcActiveRect()}rotatePens(t){this.initPens||(this.initPens=Q(this.getAllByPens(this.store.active))),this.activeRect.rotate=_(t,this.activeRect.center),this.activeRect.rotate%90<10&&(this.activeRect.rotate-=this.activeRect.rotate%90),this.activeRect.rotate%90>80&&(this.activeRect.rotate+=90-this.activeRect.rotate%90),1===this.store.active.length&&(this.lastRotate=this.store.active[0].rotate||0);const e=this.activeRect.rotate-this.lastRotate;for(const t of this.store.active){if(t.parentId)return;this.rotatePen(t,e,this.activeRect),t.onRotate&&t.onRotate(t),this.updateLines(t)}this.lastRotate=this.activeRect.rotate,this.getSizeCPs(),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),this.render(),this.store.emitter.emit("rotatePens",this.store.active),this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>{this.timer=void 0,this.pushHistory({type:V.Update,pens:Q(this.getAllByPens(this.store.active)),initPens:this.initPens}),this.initPens=void 0}),200)}resizePens(t){if(this.initPens||(this.initPens=Q(this.store.active,!0)),!this.initActiveRect)return void(this.initActiveRect=Q(this.activeRect));const e=this.mouseDown.x,i=this.mouseDown.y;let n=t.x-e,o=t.y-i;const r=Q(this.initActiveRect);if($e(r,n,o,this.resizeIndex),ze(r),!this.store.options.disableDock){this.clearDock();const t=this.customResizeDock||_e;this.dock=t(this.store,r,this.store.active,this.resizeIndex);const{xDock:e,yDock:i}=this.dock;e&&(n+=e.step,this.store.pens[e.penId].calculative.isDock=!0),i&&(o+=i.step,this.store.pens[i.penId].calculative.isDock=!0)}const s=this.activeRect.width,a=this.activeRect.height;let l=n-this.lastOffsetX,c=o-this.lastOffsetY;if(this.lastOffsetX=n,this.lastOffsetY=o,(t.ctrlKey||1===this.initPens.length&&this.initPens[0].ratio)&&(c=([1,3].includes(this.resizeIndex)?-1:1)*(l*a)/s),this.activeRect.ratio=this.initPens[0].ratio,$e(this.activeRect,l,c,this.resizeIndex),this.store.options.strictScope){const t=this.store.data.width||this.store.options.width,e=this.store.data.height||this.store.options.height;if(t&&e){let i={x:this.store.data.origin.x,y:this.store.data.origin.y,width:t*this.store.data.scale,height:e*this.store.data.scale};this.activeRect.xi.x+i.width&&(this.activeRect.width=this.activeRect.width-(this.activeRect.x+this.activeRect.width-(i.x+i.width)),this.activeRect.x=i.x+i.width-this.activeRect.width,this.activeRect.ex=this.activeRect.x+this.activeRect.width),this.activeRect.y+this.activeRect.height>i.y+i.height&&(this.activeRect.height=this.activeRect.height-(this.activeRect.y+this.activeRect.height-(i.y+i.height)),this.activeRect.y=i.y+i.height-this.activeRect.height,this.activeRect.ey=this.activeRect.y+this.activeRect.height)}}ze(this.activeRect);const h=this.activeRect.width/s,d=this.activeRect.height/a;this.store.active.forEach(((t,e)=>{t.calculative.worldRect.x=this.activeInitPos[e].x*this.activeRect.width+this.activeRect.x,t.calculative.worldRect.y=this.activeInitPos[e].y*this.activeRect.height+this.activeRect.y,t.calculative.worldRect.width*=h,t.calculative.iconWidth&&(t.calculative.iconWidth*=h),t.calculative.worldRect.height*=d,t.calculative.iconHeight&&(t.calculative.iconHeight*=d),He(t.calculative.worldRect),ze(t.calculative.worldRect),this.updatePenRect(t,{worldRectIsReady:!0}),this.execPenResize(t),this.updateLines(t)})),this.getSizeCPs(),this.initImageCanvas(this.store.active),this.initTemplateCanvas(this.store.active),this.render(),this.store.emitter.emit("resizePens",this.store.active),this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>{this.timer=void 0,this.pushHistory({type:V.Update,pens:Q(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0}),200)}movePens(t){if(!this.activeRect||this.store.data.locked)return;if(!this.initActiveRect)return void(this.initActiveRect=Q(this.activeRect));if(!this.store.options.moveConnectedLine&&!this.canMoveLine&&1===this.store.active.length&&(this.store.active[0].anchors[0]?.connectTo||this.store.active[0].anchors[this.store.active[0].anchors.length-1]?.connectTo))return;if(this.movingPens||(this.initMovingPens(),this.store.active.forEach((t=>{fe(t,!1)})),this.store.hover=void 0),!this.mouseDown)return;let e=t.x-this.mouseDown.x,i=t.y-this.mouseDown.y;t.shiftKey&&!t.ctrlKey&&(i=0),t.ctrlKey&&(e=0);const n=Q(this.initActiveRect);Ke(n,e,i);let o=!1;if(this.store.options.strictScope){const t=this.store.data.width||this.store.options.width,e=this.store.data.height||this.store.options.height;if(t&&e){let i={x:this.store.data.origin.x,y:this.store.data.origin.y,width:t*this.store.data.scale,height:e*this.store.data.scale};n.xi.x+i.width&&(n.x=i.x+i.width-n.width,o=!0),n.y+n.height>i.y+i.height&&(n.y=i.y+i.height-n.height,o=!0)}}const r={x:n.x-this.activeRect.x,y:n.y-this.activeRect.y};if(!this.store.options.disableDock&&!o){this.clearDock();const t=this.customMoveDock||Ee;this.dock=t(this.store,n,this.movingPens,r);const{xDock:e,yDock:i}=this.dock;let o;e&&(r.x+=e.step,o=this.store.pens[e.penId],o.calculative.isDock=!0),i&&(r.y+=i.step,o=this.store.pens[i.penId],o.calculative.isDock=!0)}this.translatePens(this.movingPens,r.x,r.y,!0)}changeIdsByMoving(t,e){t.id+=gn,t.parentId&&e.find((e=>e.id===t.parentId))&&(t.parentId+=gn),t.children&&(t.children=t.children.map((t=>t+gn))),t.connectedLines&&(t.connectedLines=t.connectedLines.map((t=>(e.find((e=>e.id===t.lineId))&&(t.lineId+=gn),t)))),t.type&&t.calculative.worldAnchors&&(t.calculative.worldAnchors=t.calculative.worldAnchors.map((t=>(t.connectTo&&e.find((e=>e.id===t.connectTo))&&(t.connectTo+=gn),t))))}initMovingPens(){if(!this.store.options.moveConnectedLine&&!this.canMoveLine)for(let t=0;t{this.changeIdsByMoving(t,e),this.store.pens[t.id]=t,t.calculative.canvas=this;const i={globalAlpha:.5};0===t.lineWidth&&(i.lineWidth=1),(t.name.endsWith("Dom")||p.includes(t.name)||this.store.options.domShapes.includes(t.name)||t.image)&&(i.name="rectangle",i.onDestroy=void 0),this.updateValue(t,i),t.calculative.image=void 0}))}moveLineAnchor(t,e){if(!this.activeRect||this.store.data.locked)return;if(this.initPens||(this.initPens=Q(this.store.active,!0)),this.store.activeAnchor?.connectTo){const t=this.store.pens[this.store.activeAnchor.connectTo];ne(t,oe(t,this.store.activeAnchor.anchorId),this.store.pens[this.store.activeAnchor.penId],this.store.activeAnchor)}let i=this.store.activeAnchor?.id,n=this.store.pens[this.store.activeAnchor.penId]?.connectedLines?.filter((t=>t.anchor===i));n&&n.length>0&&n.forEach((t=>{const e=this.store.pens[t.lineId];ne(this.store.pens[this.store.activeAnchor.penId],this.store.activeAnchor,e,oe(e,t.lineAnchor))}));const o=this.store.active[0],r=(re(o),se(o));if("polyline"!==o.lineName||e.shiftKey){let i=0,n=0;if("line"===o.lineName){let r=o.calculative.worldAnchors.findIndex((t=>t.id===this.store.activeAnchor.id));0===r&&(r=2);let s=o.calculative.worldAnchors[r-1];if(e.ctrlKey&&e.shiftKey){let e=Q(t);this.getSpecialAngle(e,s),i=e.x-this.store.activeAnchor.x,n=e.y-this.store.activeAnchor.y}else if(!e.ctrlKey&&e.shiftKey){let e={x:t.x,y:s.y};i=e.x-this.store.activeAnchor.x,n=e.y-this.store.activeAnchor.y}else if(e.ctrlKey&&!e.shiftKey){let e={x:s.x,y:t.y};i=e.x-this.store.activeAnchor.x,n=e.y-this.store.activeAnchor.y}else i=t.x-this.store.activeAnchor.x,n=t.y-this.store.activeAnchor.y}else!e.ctrlKey&&e.shiftKey?(i=t.x-this.store.activeAnchor.x,n=0):e.ctrlKey&&!e.shiftKey?(i=0,n=t.y-this.store.activeAnchor.y):(i=t.x-this.store.activeAnchor.x,n=t.y-this.store.activeAnchor.y);M(this.store.activeAnchor,i,n),this.store.hover&&this.store.hoverAnchor&&this.store.hoverAnchor.penId!==this.store.activeAnchor.penId&&(this.store.hoverAnchor.type===S.Line?(i=t.x-this.store.activeAnchor.x,n=t.y-this.store.activeAnchor.y,O(this.store.activeAnchor,this.store.hoverAnchor,this.store)):(i=this.store.hoverAnchor.x-this.store.activeAnchor.x,n=this.store.hoverAnchor.y-this.store.activeAnchor.y),M(this.store.activeAnchor,i,n),r.prev=void 0,"polyline"!==o.lineName&&this[o.lineName]?.(this.store,o))}else!function(t,e,i){if(!t.calculative.worldAnchors)return;const n=t.calculative.worldAnchors.findIndex((t=>t.id===e.id)),o=re(t),r=se(t);let s=t.calculative.worldAnchors[n-1],a=t.calculative.worldAnchors[n+1];if(null==t.calculative.h&&(o.connectTo&&(Li(t,e,!0)?t.calculative.h=!0:Mi(t,e,!0)&&(t.calculative.h=!1)),null==t.calculative.h&&r.connectTo&&(Li(t,e,!1)?t.calculative.h=!0:Mi(t,e,!1)&&(t.calculative.h=!1)),null==t.calculative.h&&(s?t.calculative.h=s.y===e.y:a&&(t.calculative.h=a.y===e.y))),t.calculative.h){if(e.x=i.x,o.connectTo&&Li(t,e,!0))return void(a&&a.y!==e.y&&(a.x=e.x));if(r.connectTo&&Li(t,e,!1))return void(s&&s.y!==e.y&&(s.x=e.x));const l=t.anchors[n];let c;for(let e=n-1;e>-1;e--)if(s=t.anchors[e],null==c&&(c=s.y===l.y),!0===c){if(s.y!==l.y)break;t.calculative.worldAnchors[e].y=i.y}else{if(s.x!==l.x)break;t.calculative.worldAnchors[e].x=i.x}c=void 0;for(let e=n+1;e-1;e--)if(s=t.anchors[e],null==c&&(c=s.x===l.x),!0===c){if(s.x!==l.x)break;t.calculative.worldAnchors[e].x=i.x}else{if(s.y!==l.y)break;t.calculative.worldAnchors[e].y=i.y}c=void 0;for(let e=n+1;e{this.timer=void 0,this.pushHistory({type:V.Update,pens:Q(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0}),500)}moveLineAnchorPrev(t){if(!this.activeRect||this.store.data.locked||!this.store.activeAnchor)return;if(this.initPens||(this.initPens=Q(this.store.active,!0)),this.store.activeAnchor.prev.x=t.x,this.store.activeAnchor.prev.y=t.y,this.store.activeAnchor.next)if(this.store.activeAnchor.prevNextType){if(this.store.activeAnchor.prevNextType===C.Bilateral&&this.prevAnchor){const e=_(t,this.store.activeAnchor),i=_(this.prevAnchor,this.store.activeAnchor);this.store.activeAnchor.next.x=this.nextAnchor.x,this.store.activeAnchor.next.y=this.nextAnchor.y,P(this.store.activeAnchor.next,e-i,this.store.activeAnchor)}}else this.store.activeAnchor.next.x=t.x,this.store.activeAnchor.next.y=t.y,P(this.store.activeAnchor.next,180,this.store.activeAnchor);const e=this.store.active[0];this.patchFlagsLines.add(e),this.store.path2dMap.set(e,B.path2dDraws[e.name](e)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>{this.timer=void 0,this.pushHistory({type:V.Update,pens:Q(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0}),200)}moveLineAnchorNext(t){if(!this.activeRect||this.store.data.locked||!this.store.activeAnchor)return;if(this.initPens||(this.initPens=Q(this.store.active,!0)),this.store.activeAnchor.next.x=t.x,this.store.activeAnchor.next.y=t.y,this.store.activeAnchor.prev)if(this.store.activeAnchor.prevNextType){if(this.store.activeAnchor.prevNextType===C.Bilateral&&this.nextAnchor){const e=_(t,this.store.activeAnchor),i=_(this.nextAnchor,this.store.activeAnchor);this.store.activeAnchor.prev.x=this.prevAnchor.x,this.store.activeAnchor.prev.y=this.prevAnchor.y,P(this.store.activeAnchor.prev,e-i,this.store.activeAnchor)}}else this.store.activeAnchor.prev.x=t.x,this.store.activeAnchor.prev.y=t.y,P(this.store.activeAnchor.prev,180,this.store.activeAnchor);const e=this.store.active[0];this.patchFlagsLines.add(e),this.store.path2dMap.set(e,B.path2dDraws[e.name](e)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout((()=>{this.timer=void 0,this.pushHistory({type:V.Update,pens:Q(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0}),200)}async setAnchor(t){const e=[Q(this.store.hover,!0)],i=this.store.hover;if(this.store.hoverAnchor){if(this.beforeRemoveAnchor&&!await this.beforeRemoveAnchor(i,this.store.hoverAnchor))return;i.type===o.Line&&i.calculative.worldAnchors?.length<=2?this.delete([i]):(function(t,e){if(!t||!t.calculative.worldAnchors)return;let i=t.calculative.worldAnchors.findIndex((t=>t.id===e.id));i>-1&&t.calculative.worldAnchors.splice(i,1),i=t.anchors.findIndex((t=>t.id===e.id)),i>-1&&t.anchors.splice(i,1)}(i,this.store.hoverAnchor),i.type===o.Line&&this.initLineRect(i)),this.store.hoverAnchor=void 0,this.store.activeAnchor=void 0,this.externalElements.style.cursor="default"}else if(i){if(this.beforeAddAnchor&&!await this.beforeAddAnchor(i,this.store.pointAt))return;if(i.type===o.Line){this.store.activeAnchor=function(t,e,i){t.anchors||(t.anchors=[]),t.calculative.worldAnchors||(t.calculative.worldAnchors=[]);const n=function(t,e,i){let n=t.calculative.worldAnchors[i],o=t.calculative.worldAnchors[i+1];!o&&t.close&&(o=t.calculative.worldAnchors[0]);const r=e.step;let s;if(n.next&&o.prev){const e=n,i=n.next,a=o.prev,l=o,c=fi(e,i,r),h=fi(i,a,r),d=fi(a,l,r),u=fi(c,h,r),f=fi(h,d,r);s=fi(u,f,r),u.penId=t.id,s.prev=u,f.penId=t.id,s.next=f,n.next.x=c.x,n.next.y=c.y,o.prev.x=d.x,o.prev.y=d.y}else if(n.next||o.prev){const i=n,a=n.next||o.prev,l=o,c=fi(i,a,r),h=fi(a,l,r);s=e,c.penId=t.id,h.penId=t.id,s.prev=c,s.next=h,n.next=void 0,o.prev=void 0}else s=e;return s.penId=t.id,s.id=at(),s.prevNextType=C.Bilateral,s}(t,e,i);return t.calculative.worldAnchors.splice(i+1,0,n),t.anchors.splice(i+1,0,Qe(n,t.calculative.worldRect)),t.calculative.activeAnchor=n,n}(i,this.store.pointAt,this.store.pointAtIndex),this.initLineRect(i);const e={x:t.x,y:t.y};this.getHover(e)}else{const e={id:at(),x:t.x,y:t.y};this.store.activeAnchor=function(t,e){t.anchors||(t.anchors=[]),t.calculative.worldAnchors||(t.calculative.worldAnchors=[]);const i={id:e.id,penId:t.id,x:e.x,y:e.y};if(t.calculative.worldAnchors.push(i),t.calculative.worldRect){t.rotate%360&&P(e,-t.rotate,t.calculative.worldRect.center);const i={id:e.id,penId:t.id,x:(e.x-t.calculative.worldRect.x)/t.calculative.worldRect.width,y:(e.y-t.calculative.worldRect.y)/t.calculative.worldRect.height};t.anchors.push(i)}return i}(i,e)}}this.hotkeyType=m.None,this.render(),i&&this.pushHistory({type:V.Update,pens:[Q(i,!0)],initPens:e})}checkDisconnect(t,e){if(t.id.indexOf(gn)>0){const e=t.id;t=this.store.pens[e.replace(gn,"")]}t.anchors.forEach((i=>{if(i.connectTo&&!e.find((t=>t.id===i.connectTo||t.id===i.connectTo+gn))){const e=this.store.pens[i.connectTo];if(!e||e.type)return;ne(e,oe(e,i.anchorId),t,i)}}))}translatePens(t=this.store.active,e,i,n){if(!t||!t.length)return;if(t.some((t=>{if(t.locked>=r.DisableMove)return!0})))return;const s=!n&&Q(t,!0);this.activeRect&&Ke(this.activeRect,e,i);const a=this.getAllByPens(t);t.forEach((t=>{if(!(t.locked>=r.DisableMove)){if(t.type===o.Line){if(!this.store.options.moveConnectedLine&&!this.canMoveLine)return;if(t.isRuleLine)return;te(t,e,i),this.checkDisconnect(t,a),this.store.path2dMap.set(t,B.path2dDraws[t.name](t)),n||(this.initLineRect(t),t.connectedLines?.forEach((t=>{const e=this.store.pens[t.lineId];this.initLineRect(e)})))}else Ke(t.calculative.worldRect,e,i),this.updatePenRect(t,{worldRectIsReady:!0}),t.calculative.x=t.x,t.calculative.y=t.y,t.calculative.initRect&&(t.calculative.initRect.x=t.calculative.x,t.calculative.initRect.y=t.calculative.y,t.calculative.initRect.ex=t.calculative.x+t.calculative.width,t.calculative.initRect.ey=t.calculative.y+t.calculative.height);this.updateLines(t),t.onMove?.(t)}})),this.activeRect&&this.getSizeCPs(),this.render(),this.tooltip.translate(e,i),n||(this.pushHistory({type:V.Update,pens:Q(t,!0),initPens:s}),this.initImageCanvas(t),this.initTemplateCanvas(t),this.store.emitter.emit("translatePens",t)),this.store.emitter.emit("translatingPens",t)}templateTranslatePens(t=this.store.active,e,i){if(!t||!t.length)return;const n=this.getAllByPens(t);t.forEach((t=>{if(t.type===o.Line){if(!this.store.options.moveConnectedLine&&!this.canMoveLine)return;te(t,e,i),this.checkDisconnect(t,n),this.store.path2dMap.set(t,B.path2dDraws[t.name](t))}else Ke(t.calculative.worldRect,e,i),this.updatePenRect(t,{worldRectIsReady:!0}),t.calculative.x=t.x,t.calculative.y=t.y,t.calculative.initRect&&(t.calculative.initRect.x=t.calculative.x,t.calculative.initRect.y=t.calculative.y,t.calculative.initRect.ex=t.calculative.x+t.calculative.width,t.calculative.initRect.ey=t.calculative.y+t.calculative.height);t.onMove?.(t)}))}calcAutoAnchor(t,e,i,n){const o=re(t),r=se(t),s=Zt(i,e===o?r:o);s&&(e.x=s.x,e.y=s.y,e.prev=void 0,e.next=void 0,n?n.anchor=s.id:ie(i,s,t,e),this[t.lineName]&&this[t.lineName](this.store,t),this.store.path2dMap.set(t,B.path2dDraws.line(t)),this.initLineRect(t))}restoreNodeAnimate(t){if(t.calculative.initRect){if(t.keepAnimateState)for(const e in t)void 0!==t.calculative[e]&&("x"===e||"y"===e||"width"===e||"height"===e||"initRect"===e||"object"==typeof t[e]&&"lineDash"!==e||(t[e]="fontSize"===e||"lineWidth"===e?t.calculative[e]/t.calculative.canvas.store.data.scale:t.calculative[e]));else{const e=t.calculative.initRect.rotate-t.calculative.rotate;for(const e in t)"x"===e||"y"===e||"width"===e||"height"===e||"initRect"===e||"rotate"===e||"object"==typeof t[e]&&"lineDash"!==e||(t.calculative[e]=t[e]);t.children?.length?e&&ye(t,e,t.calculative.worldRect):t.calculative.rotate=t.rotate;const i=Q(this.store.animateMap.get(t));i&&(i.id=t.id,this.parent.setValue(i,{doEvent:!1,render:!0,history:!1})),t.calculative.worldRect=t.calculative.initRect}this.updatePenRect(t,{worldRectIsReady:!0}),this.updateLines(t),t.image&&"gif"!==t.name&&(this.canvasImage.init(),this.canvasImageBottom.init()),t.calculative.text!==t.text&&(t.calculative.text=t.text,Y(t)),this.store.active?.length&&this.calcActiveRect(),t.calculative.initRect=void 0}}updateLines(t,e){t.children?.forEach((t=>{const i=this.store.pens[t];i&&this.updateLines(i,e)})),t.connectedLines&&t.connectedLines.forEach(((i,n)=>{const o=this.store.pens[i.lineId];if(!o||o.calculative.active)return;const r=oe(o,i.lineAnchor);if(!r)return;if(!r.connectTo)return void t.connectedLines.splice(n,1);if(o.autoFrom){const e=re(o);e.id===r.id&&this.calcAutoAnchor(o,e,t,i)}if(o.autoTo){const e=se(o);e.id===r.id&&this.calcAutoAnchor(o,e,t,i)}const s=oe(t,i.anchor);if(!s)return;let a=t.rotate;t.flipX&&(a*=-1),t.flipY&&(a*=-1);let l=r.distance*this.store.data.scale*Math.cos((a+s.rotate)/180*Math.PI)||0,c=r.distance*this.store.data.scale*Math.sin((a+s.rotate)/180*Math.PI)||0;if(t.flipX&&(l=-l),t.flipY&&(c=-c),M(r,s.x-r.x+l,s.y-r.y+c),this.store.options.autoPolyline&&!this.autoPolylineFlag&&!1!==o.autoPolyline&&"polyline"===o.lineName){let t=re(o),e=se(o),i=!1;t.id===r.id?(t=r,i=!0):e.id===r.id&&(e=r,i=!0),i&&(o.calculative.worldAnchors=[t,e],o.calculative.activeAnchor=t,this.polyline(this.store,o,e),this.initLineRect(o))}this.store.path2dMap.set(o,B.path2dDraws[o.name](o)),this.patchFlagsLines.add(o),o.calculative.gradientSmooth&&(o.calculative.gradientAnimatePath=kt(o)),e&&Ci(o)}))}calcActiveRect(){const t=this.store.active.filter((t=>(!t.locked||t.locked{P(t,e,i.center)})),this.initLineRect(t),Kt(t)):(t.calculative.rotate?t.calculative.rotate+=e:t.calculative.rotate=e,P(t.calculative.worldRect.center,e,i.center),t.parentId?(t.calculative.worldRect.x=t.calculative.worldRect.center.x-t.calculative.worldRect.width/2,t.calculative.worldRect.y=t.calculative.worldRect.center.y-t.calculative.worldRect.height/2,t.x=(t.calculative.worldRect.x-i.x)/i.width,t.y=(t.calculative.worldRect.y-i.y)/i.height):(t.x=t.calculative.worldRect.center.x-t.width/2,t.y=t.calculative.worldRect.center.y-t.height/2),t.rotate=t.calculative.rotate,this.updatePenRect(t),t.children&&t.children.forEach((i=>{const n=this.store.pens[i];this.rotatePen(n,e,t.calculative.worldRect)})))}nextAnimate(t){if(!t)return;let e;this.store.emitter.emit("animateEnd",t),t.nextAnimate&&(e=this.store.data.pens.filter((e=>e.id===t.nextAnimate||e.tags&&e.tags.indexOf(t.nextAnimate)>-1))),e&&(e.forEach((t=>{if(t.calculative.pause){const e=Date.now()-t.calculative.pause;t.calculative.pause=void 0,t.calculative.frameStart+=e,t.calculative.frameEnd+=e}else if("video"===t.name)t.calculative.media.currentTime=0,t.calculative.media?.play(),t.onStartVideo?.(t);else if(t.type||t.frames?.length||t.animations&&t.animations.length){if(t.type){if(t.animations?.length){const e=Q(t.animations[0]);delete e.name,e.currentAnimation=0,this.parent.setValue({id:t.id,...e},{doEvent:!1,history:!1})}}else{if(!t.frames&&t.animations&&t.animations.length){let e=t.animations?.findIndex((t=>t.autoPlay)),i=-1===e?0:e;const n=Q(t.animations[i]);delete n.name,n.currentAnimation=i,!t.type&&n.frames&&(n.showDuration=this.parent.calcAnimateDuration(n)),this.parent.setValue({id:t.id,...n},{doEvent:!1,history:!1})}this.store.animateMap.set(t,this.getFrameProps(t))}this.store.animates.add(t)}})),this.animate())}getFrameProps(t){let e={};return t.frames&&t.frames.forEach((i=>{for(let n in i)["duration","x","y","width","height","rotate"].includes(n)||e[n]||(e[n]=t[n])})),e}animate(){this.animateRendering||requestAnimationFrame((()=>{const t=Date.now();if(t-this.lastAnimateRender0&&this.animate());this.lastAnimateRender=t,this.animateRendering=!0;const e=[];let i=!1;for(const n of this.store.animates)if(!n.calculative.pause){if(!n.calculative.active||n.type||this.movingPens||(i=!0),n.type){if(!de(n)){if(n.keepAnimateState){for(const t in n)void 0!==n.calculative[t]&&"length"!==t&&("object"==typeof n[t]&&"lineDash"!==t||(n[t]="lineWidth"===t?n.calculative[t]/n.calculative.canvas.store.data.scale:n.calculative[t]));Kt(n)}else for(const t in n)"object"==typeof n[t]&&"lineDash"!==t||(n.calculative[t]="lineWidth"===t?n[t]*n.calculative.canvas.store.data.scale:n[t]);e.push(n),this.nextAnimate(n)}}else ae(n,t)?n.calculative.patchFlags&&(ze(n.calculative.worldRect),this.updatePenRect(n,{worldRectIsReady:!0,playingAnimate:!0})):(requestAnimationFrame((()=>{this.restoreNodeAnimate(n)})),e.push(n),this.nextAnimate(n)),this.updateLines(n,!0);this.patchFlags=!0}i&&this.calcActiveRect(),e.forEach((t=>{this.store.animates.delete(t)})),this.render(!1),this.animateRendering=!1,this.animate()}))}get clipboardName(){return"meta2d-clipboard"}async copy(t,e=!0){const i=at(),{origin:n,scale:o}=this.store.data;this.store.clipboard=void 0,localStorage.removeItem(this.clipboardName),sessionStorage.setItem("page",i);let r=this.getAllByPens(Q(t||this.store.active,!0));r.forEach((t=>{t.copyIndex=this.store.data.pens.findIndex((e=>e.id===t.id)),t.pathId&&(t.path=this.store.data.paths[t.pathId])})),r.sort(((t,e)=>t.copyIndex-e.copyIndex)),r.forEach((t=>{delete t.copyIndex}));const s={meta2d:!0,pens:r,origin:Q(n),scale:o,page:i,initRect:Q(this.activeRect),offset:10};if(!navigator.clipboard||this.store.options.disableClipboard||navigator.userAgent.includes("Firefox"))localStorage.setItem(this.clipboardName,JSON.stringify(s));else try{await navigator.clipboard.writeText(JSON.stringify(s))}catch{localStorage.setItem(this.clipboardName,JSON.stringify(s))}e&&this.store.emitter.emit("copy",s.pens)}cut(t){this.copy(t,!1),this.delete(t),this.store.emitter.emit("cut",t)}async paste(){let t,e,i,n;if(!navigator.clipboard||this.store.options.disableClipboard||navigator.userAgent.includes("Firefox"))t=localStorage.getItem(this.clipboardName);else try{t=await(navigator.clipboard?.readText())}catch{t=localStorage.getItem(this.clipboardName)}if(!t)return;try{e=JSON.parse(t)}catch(t){return void console.warn("剪切板数据不是json",t.message)}if(!e||!e.meta2d)return;if(this.beforeAddPens&&1!=await this.beforeAddPens(e.pens))return;this.store.clipboard&&(i=this.store.clipboard.offset+10,n=this.store.clipboard.pos),this.store.clipboard=Q(e),sessionStorage.getItem("page")!==e.page?(this.store.clipboard.pos={x:this.mousePos.x,y:this.mousePos.y},this.store.clipboard.offset=0):this.pasteOffset?(i&&(this.store.clipboard.offset=i),n&&(this.store.clipboard.pos=n)):(this.store.clipboard.offset=0,this.pasteOffset=!0);const o=this.store.clipboard.pens.filter((t=>!t.parentId));for(const t of o)this.pastePen(t,void 0);sessionStorage.setItem("page",e.page),this.active(o),this.pushHistory({type:V.Add,pens:this.store.clipboard.pens}),this.render(),this.store.emitter.emit("add",this.store.clipboard.pens),this.store.emitter.emit("paste",this.store.clipboard.pens)}getAllByPens(t){const e=[];for(const i of t)e.push(...Q(dt(i,this.store),!0));return e.concat(t)}getAllFollowersByPens(t,e=!0){const i=t;for(const n of t){let t=ut(n,this.store);e&&(t=Q(t,!0));for(const e of t)i.find((t=>t.id===e.id))||i.push(e)}return i}setFollowers(t=this.store.active){if(t)if(t.length<2)t[0].followers=[];else{let e=t.map((t=>t.id));e.pop();const i=t[t.length-1];i.followers?e.forEach((t=>{i.followers.includes(t)||i.followers.push(t)})):i.followers=e}}changeLineAnchors(t,e,i){if(Array.isArray(e.connectedLines))for(let n=0;nt.id===o));if(r){const i=r.anchors[0],n=r.anchors[r.anchors.length-1];i.connectTo===t&&(i.connectTo=e.id),n.connectTo===t&&(n.connectTo=e.id)}else e.connectedLines.splice(n,1),n--}}changeNodeConnectedLine(t,e,i){const n=[e.anchors[0],e.anchors[e.anchors.length-1]];for(const o of n){const n=o.connectTo;if(n){const r=i.find((t=>t.id===n));r?r.connectedLines?.forEach((i=>{i.lineId===t&&(i.lineId=e.id,i.lineAnchor=o.id)})):(o.connectTo=void 0,o.prev&&(o.prev.connectTo=void 0),o.next&&(o.next.connectTo=void 0))}}}async delete(t=this.store.active,e=!1,i=!0){if(!t||!t.length)return;if(this.beforeRemovePens&&1!=await this.beforeRemovePens(t))return;if(e||(t=t.filter((t=>!t.locked))),!t||!t.length)return;const n=[];if(this._del(t,n,e),this.initImageCanvas(n),this.initTemplateCanvas(n),this.inactive(),this.clearHover(),this.render(),i){if(0===n.length)return;this.pushHistory({type:V.Delete,pens:n})}this.store.emitter.emit("delete",t)}_del(t,e,i){t&&t.forEach((t=>{if(t.type&&(t.lastConnected={}),t.parentId){if(this.getLockedParent(t))return void console.warn("父节点锁定");{const i=ht(t),n=i.children.indexOf(t.id);i.children.splice(n,1),e&&this.getDelPens(t,e),this.delForce(t)}}else{if(!i&&t.locked)return;e&&this.getDelPens(t,e),this.delForce(t)}}))}getDelPens(t,e){if(t){if(this.store.data.pens.findIndex((e=>e.id===t.id))>-1){const i=this.store.pens[t.id];i.calculative.active=void 0,e.push(i)}t.children&&t.children.forEach((t=>{this.getDelPens(this.store.pens[t],e)}))}}getLockedParent(t){if(!t.parentId)return!1;const e=ht(t);if(e.locked)return e;this.getLockedParent(e)}delForce(t){if(!t)return;const e=this.store.data.pens.findIndex((e=>e.id===t.id));e>-1&&(this.delConnectedLines(this.store.data.pens[e]),this.store.data.pens.splice(e,1),this.store.pens[t.id]=void 0,delete this.store.pens[t.id]),this.store.animates.delete(t),this.store.animateMap.delete(t),t.children&&t.children.forEach((t=>{this.delForce(this.store.pens[t])})),t.onDestroy?.(t)}delConnectedLines(t){if(t.connectedLines)for(let e=0;et.id===n));e?.connectTo===t.id&&(e.connectTo=void 0,e.anchorId=void 0,e.prev&&(e.prev.connectTo=void 0),e.next&&(e.next.connectTo=void 0)),e=oe(o,n),e&&(e.connectTo=void 0,e.anchorId=void 0,e.prev&&(e.prev.connectTo=void 0),e.next&&(e.next.connectTo=void 0))}}t.type&&t.calculative.worldAnchors?.forEach(((e,i)=>{if(!e.connectTo)return;const n=this.store.pens[e.connectTo];n&&n.calculative.worldAnchors?.forEach((i=>{ne(n,i,t,e)}))}))}convertSpecialCharacter(t){var e={lt:"<",gt:">",nbsp:" ",amp:"&",quot:'"'};return t.replace(/&(lt|gt|nbsp|amp|quot);/gi,(function(t,i){return e[i]}))}createInput(){let t;this.inputParent.classList.add("meta2d-input"),this.inputRight.classList.add("right"),this.inputDiv.classList.add("input-div"),this.inputParent.appendChild(this.inputDiv),this.inputParent.appendChild(this.inputRight),this.dropdown.onmouseleave=()=>{this.store.hover=null},this.inputParent.appendChild(this.dropdown),this.externalElements.appendChild(this.inputParent),this.inputParent.onmousedown=this.stopPropagation,this.inputDiv.onmousedown=this.stopPropagation,this.inputDiv.contentEditable="false",this.inputRight.onmousedown=this.stopPropagation,this.dropdown.onmousedown=this.stopPropagation,this.inputRight.style.transform="rotate(135deg)";for(let e=0;e{if(navigator.userAgent.includes("Firefox")){if(!t.target.innerText){let t=this.inputDiv.offsetWidth/2;"center"!==window.getComputedStyle(this.inputDiv,null).textAlign&&(t=0),this.inputDiv.innerHTML=`
`}}else if(t.target.innerText)this.inputDiv.style.paddingTop="";else{let t=window.getComputedStyle(this.inputDiv,null);"center"===t.justifyContent&&(this.inputDiv.style.paddingTop=` ${this.inputDiv.offsetHeight/2-parseFloat(t.lineHeight)/2}px`)}},this.inputDiv.onblur=()=>{setTimeout((()=>{this.hideInput()}),300)},this.inputDiv.oninput=t=>{const e=this.store.pens[this.inputDiv.dataset.penId];if(e&&"number"===e.inputType){const e=t.target.innerText,i=e.replace(/[^0-9]/g,"");e!==i&&(t.preventDefault(),t.target.innerText=i)}if(navigator.userAgent.includes("Firefox")){if(!t.target.innerText.trim()){let t=this.inputDiv.offsetWidth/2;"center"!==window.getComputedStyle(this.inputDiv,null).textAlign&&(t=0),this.inputDiv.innerHTML=`
`}}else if(t.target.innerText)this.inputDiv.style.paddingTop="";else{let t=window.getComputedStyle(this.inputDiv,null);"center"===t.justifyContent&&(this.inputDiv.style.paddingTop=` ${this.inputDiv.offsetHeight/2-parseFloat(t.lineHeight)/2}px`)}this.store.emitter.emit("input",e)},this.inputDiv.onclick=t=>{t.stopPropagation();const e=this.store.pens[this.inputDiv.dataset.penId];"block"===this.dropdown.style.display?(this.dropdown.style.display="none",this.inputRight.style.transform="rotate(135deg)"):e?.dropdownList&&this.store.data.locked&&(this.dropdown.style.display="block",this.inputRight.style.transform="rotate(315deg)"),this.store.emitter.emit("clickInput",e)},this.inputDiv.onkeyup=t=>{this.setDropdownList(!0);const e=this.store.pens[this.inputDiv.dataset.penId];this.store.emitter.emit("input",{pen:e,text:t.key}),t.stopPropagation()},this.inputDiv.onkeydown=t=>{t.stopPropagation()},this.inputDiv.onmousedown=this.stopPropagation,this.inputDiv.onwheel=t=>{t.stopPropagation()},this.inputDiv.onpaste=t=>{t.preventDefault();let e="";t.clipboardData&&t.clipboardData.getData&&(e=t.clipboardData.getData("text/plain")),document.execCommand("insertHTML",!1,e)}}clearDropdownList(){if(this.dropdown.hasChildNodes())for(let t=0;te.id==t||e.tags&&e.tags.indexOf(t)>-1))}findOne(t){return this.store.data.pens.find((e=>e.id==t||e.tags&&e.tags.indexOf(t)>-1))}changePenId(t,e){if(t===e)return;const i=this.store.pens[t];if(i&&!this.store.pens[e]){if(i.id=e,this.store.pens[e]=this.store.pens[t],i.onChangeId?.(i,t,e),delete this.store.pens[t],i.parentId){const n=this.store.pens[i.parentId],o=n.children?.findIndex((e=>e===t));-1!==o&&n.children?.splice(o,1,e)}i.children?.forEach((t=>{this.store.pens[t].parentId=e})),i.type===o.Line?this.changeNodeConnectedLine(t,i,this.store.data.pens):(this.changeLineAnchors(t,i,this.store.data.pens),i.connectedLines?.forEach((({lineId:t})=>{Yt(this.store.pens[t])}))),i.anchors?.forEach((t=>t.penId=e)),i.calculative.worldAnchors?.forEach((t=>t.penId=e))}}updateValue(t,e){const i=this.getPenRect(t),n=t.name;Object.assign(t,e);const o=n!==t.name;e.newId&&this.changePenId(t.id,e.newId);let r,s=!1,a=!1,f=!1,p=!1,v=!1,g=!1,y=!1;for(const i in e)-1===i.indexOf(".")?("rotate"===i?r=t.calculative.rotate||0:"canvasLayer"===i||"isBottom"===i||"showChild"===i?g=!0:"image"===i&&(y=!0),"object"==typeof t[i]&&"lineDash"!==i||(t.calculative[i]=e[i]),c.includes(i)&&(a=!0),["name","borderRadius","lineSmooth"].includes(i)&&(s=!0),h.includes(i)&&(v=!0),d.includes(i)&&(f=!0),u.includes(i)&&(p=!0),t.image&&"gif"!==t.name&&["globalAlpha","flipY","flipX","x","y","width","height"].includes(i)&&(y=!0)):(delete t[i],fn(t,i,e[i])),"anchors"===i.split(".")[0]&&Yt(t);if(this.setCalculativeByScale(t),o&&(t.onDestroy?.(t),function(t){t.onAdd=void 0,t.onValue=void 0,t.onBeforeValue=void 0,t.onDestroy=void 0,t.onMove=void 0,t.onResize=void 0,t.onRotate=void 0,t.onClick=void 0,t.onMouseEnter=void 0,t.onMouseLeave=void 0,t.onMouseDown=void 0,t.onMouseMove=void 0,t.onMouseUp=void 0,t.onShowInput=void 0,t.onInput=void 0,t.onChangeId=void 0,t.onBinds=void 0,t.onStartVideo=void 0,t.onPauseVideo=void 0,t.onStopVideo=void 0,t.onRenderPenRaw=void 0,t.onKeyDown=void 0,t.onContextmenu=void 0,t.onScale=void 0,t.onWheel=void 0,t.onConnectLine=void 0}(t)),v){const n={x:e.x??i.x,y:e.y??i.y,width:e.width??i.width,height:e.height??i.height};this.setPenRect(t,n,!1),this.updateLines(t,!0),this.store.active&&this.store.active.length&&t.id===this.store.active[0].id&&this.calcActiveRect()}else f?this.updatePenRect(t):(a&&q(t),p&&Xt(this.store.pens,t),s&&B.path2dDraws[t.name]&&this.store.path2dMap.set(t,B.path2dDraws[t.name](t)));if(void 0!==r){const e=t.calculative.rotate;t.calculative.rotate=r,this.rotatePen(t,e-r,t.calculative.worldRect)}(e.image||e.backgroundImage||e.strokeImage)&&(t.calculative.image=void 0,t.calculative.backgroundImage=void 0,t.calculative.strokeImage=void 0,this.loadImage(t)),e.lineGradientColors&&(t.calculative.lineGradient=void 0,t.calculative.gradientColorStop=void 0),e.gradientColors&&(t.calculative.gradient=void 0,t.calculative.radialGradient=void 0),e.gradientRadius&&(t.calculative.gradient=void 0,t.calculative.radialGradient=void 0),e.animateLineWidth&&(t.calculative.gradientAnimatePath=void 0),e.gradientSmooth&&(t.calculative.gradientAnimatePath=void 0),g?(this.canvasImage.init(),this.canvasImageBottom.init()):y&&(void 0===t.canvasLayer&&(t.canvasLayer=l.CanvasImageBottom,t.calculative.canvasLayer=l.CanvasImageBottom),t.canvasLayer===l.CanvasImageBottom?this.canvasImageBottom.init():t.canvasLayer===l.CanvasImage&&this.canvasImage.init()),void 0===e.canvasLayer&&t.canvasLayer!==l.CanvasTemplate||this.initTemplateCanvas([t]),void 0!==e.zIndex&&t.calculative.singleton?.div&&pe(t,t.calculative.singleton.div)}execPenResize(t){t.onResize?.(t),t.children?.forEach((t=>{const e=this.store.pens[t];e&&this.execPenResize(e)}))}setPenRect(t,e,i=!0){if(t.parentId)Object.assign(t,e);else{const{origin:i,scale:n}=this.store.data;t.x=i.x+e.x*n,t.y=i.y+e.y*n,t.width=e.width*n,t.height=e.height*n}this.updatePenRect(t),this.execPenResize(t),i&&this.render()}getPenRect(t,e=this.store.data.origin,i=this.store.data.scale){if(t)return t.parentId?{x:t.x,y:t.y,width:t.width,height:t.height}:{x:(t.x-e.x)/i,y:(t.y-e.y)/i,width:t.width/i,height:t.height/i}}toPng(t=2,e,i=!1,n){const o=We(this.store.data.pens),r=this.store.data.scale;if(!isFinite(o.width))throw new Error("can not to png, because width is not finite");const s=Q(o),a=this.store.data,l=i&&!a.background&&this.store.bkImg;let c=!1,h=!1;if(l){if(o.x+=a.x,o.y+=a.y,He(o),qe(o,this.canvasRect,!0))Object.assign(o,this.canvasRect);else{const t=Ve([...Ue(o),...Ue(this.canvasRect)]);Object.assign(o,t)}c=0===o.x,h=0===o.y}const d=this.store.data.width||this.store.options.width,u=this.store.data.height||this.store.options.height;let f=!1;d&&u&&!this.store.data.component&&(f=!0),f&&(o.x=this.store.data.origin.x,o.y=this.store.data.origin.y,o.width=d*this.store.data.scale,o.height=u*this.store.data.scale);const p=Q(o),v=lt(t);o.x-=v[3]*r,o.y-=v[0]*r,o.width+=(v[3]+v[1])*r,o.height+=(v[0]+v[2])*r;const g=(n||1920)/o.width;o.width*=g,o.height*=g,He(o);const y=document.createElement("canvas");if(y.width=o.width,y.height=o.height,y.width>32767||y.height>32767||!navigator.userAgent.includes("Firefox")&&y.height*y.width>268435456||navigator.userAgent.includes("Firefox")&&y.height*y.width>472907776)throw new Error("can not to png, because the size exceeds the browser limit");const m=y.getContext("2d");m.textBaseline="middle",m.scale(g,g);const w=this.store.data.background||this.store.options.background;if(w&&(m.save(),m.fillStyle=w,f?m.fillRect(0,0,p.width+(v[1]+v[3])*r,p.height+(v[0]+v[2])*r):m.fillRect(0,0,s.width+(v[3]+v[1])*r,s.height+(v[0]+v[2])*r),m.restore()),l)if(f)m.drawImage(this.store.bkImg,v[3]*r||0,v[0]*r||0,p.width,p.height);else{const t=o.x<0?-o.x:0,e=o.y<0?-o.y:0;m.drawImage(this.store.bkImg,t,e,this.canvasRect.width,this.canvasRect.height)}l?f?m.translate(-s.x+v[3]*r||0,-s.y+v[0]*r||0):m.translate((c?a.x:-s.x)+v[3]*r||0,(h?a.y:-s.y)+v[0]*r||0):m.translate(-o.x,-o.y);for(const t of this.store.data.pens){if(!xe(t,this.store)||0==t.visible)continue;const{active:e}=t.calculative;t.calculative.active=!1,t.calculative.img?Ft(m,t):Ot(m,t,!0),t.calculative.active=e}if(!e)return y.toDataURL();y.toBlob(e)}activeToPng(t=2,e){return this.pensToPng(this.store.active,t,e)}pensToPng(t=this.store.active,e=2,i){if(0===t.length)return;const n=this.getAllByPens(t);let o=n.map((t=>t.id));const r=We(n);if(!isFinite(r.width))throw new Error("can not to png, because width is not finite");const s=Q(r),a=lt(e);r.x-=a[3],r.y-=a[0],r.width+=a[3]+a[1],r.height+=a[0]+a[2],He(r);const l=(i||r.width)/r.width;r.width*=l,r.height*=l;const c=document.createElement("canvas");if(c.width=r.width,c.height=r.height,c.width>32767||c.height>32767||!navigator.userAgent.includes("Firefox")&&c.height*c.width>268435456||navigator.userAgent.includes("Firefox")&&c.height*c.width>472907776)throw new Error("can not to png, because the size exceeds the browser limit");const h=c.getContext("2d");h.textBaseline="middle",h.scale(l,l);const d=this.store.data.background||this.store.options.background;d&&(h.save(),h.fillStyle=d,h.fillRect(0,0,s.width+(a[3]+a[1]),s.height+(a[0]+a[2])),h.restore()),h.translate(-s.x+a[3],-s.y+a[0]);for(const t of this.store.data.pens)if(o.includes(t.id)){if(!xe(t,this.store)||0==t.visible)continue;const{active:e}=t.calculative;t.calculative.active=!1,t.calculative.img?Ft(h,t):Ot(h,t),t.calculative.active=e}return c.toDataURL()}toggleAnchorMode(){if(this.hotkeyType)this.hotkeyType===m.AddAnchor&&(this.hotkeyType=m.None,this.store.hoverAnchor?this.externalElements.style.cursor="vertical-text":this.store.hover&&(this.externalElements.style.cursor="move"));else{if(this.store.options.disableAnchor||this.store.hover?.disableAnchor)return;this.hotkeyType=m.AddAnchor,this.store.hover&&(this.externalElements.style.cursor="pointer")}this.patchFlags=!0}addAnchorHand(){if(this.store.activeAnchor&&this.store.active&&1===this.store.active.length&&this.store.active[0].type){const t=[Q(this.store.active[0],!0)];this.store.activeAnchor.prev?this.store.activeAnchor.next||(this.store.activeAnchor.next={...this.store.activeAnchor.prev},P(this.store.activeAnchor.next,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0):(this.store.activeAnchor.next||(this.store.activeAnchor.next={penId:this.store.activeAnchor.penId,x:this.store.activeAnchor.x+50,y:this.store.activeAnchor.y}),this.store.activeAnchor.prev={...this.store.activeAnchor.next},P(this.store.activeAnchor.prev,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:V.Update,pens:[Q(this.store.active[0],!0)],initPens:t})}}removeAnchorHand(){if(this.store.activeAnchor&&this.store.active&&1===this.store.active.length&&this.store.active[0].type){const t=[Q(this.store.active[0],!0)];this.hoverType===y.LineAnchorPrev?(this.store.activeAnchor.prev=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):this.hoverType===y.LineAnchorNext?(this.store.activeAnchor.next=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):(this.store.activeAnchor.prev=void 0,this.store.activeAnchor.next=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:V.Update,pens:[Q(this.store.active[0])],initPens:t})}}toggleAnchorHand(){1===this.store.active.length&&this.store.active[0].type&&this.store.activeAnchor&&(this.store.activeAnchor.prevNextType||(this.store.activeAnchor.prevNextType=C.Mirror),this.store.activeAnchor.prevNextType=(this.store.activeAnchor.prevNextType+1)%3)}gotoView(t,e){let i=We(this.store.data.pens);if(!isFinite(i.width))throw new Error("can not move view, because width is not finite");const n=this.store.data.width||this.store.options.width,o=this.store.data.height||this.store.options.height;n&&o&&(i={x:this.store.data.origin.x,y:this.store.data.origin.y,width:n*this.store.data.scale,height:o*this.store.data.scale}),this.store.data.x=this.canvas.clientWidth/2-t*i.width-i.x,this.store.data.y=this.canvas.clientHeight/2-e*i.height-i.y,this.onMovePens(),this.canvasTemplate.init(),this.canvasImage.init(),this.canvasImageBottom.init(),this.render()}showMagnifier(){this.magnifierCanvas.magnifier=!0,this.externalElements.style.cursor="default",this.render()}hideMagnifier(){this.magnifierCanvas.magnifier=!1,this.externalElements.style.cursor="default",this.render()}showFit(){this.store.data.locked=0,this.canvasImage.fitFlag=!0,this.canvasImage.activeFit=void 0,this.canvasImage.currentFit=void 0,this.store.data.fits||(this.store.data.fits=[]),this.store.data.fits.forEach((t=>t.active=!1)),this.canvasImage.init(),this.canvasImage.render()}hideFit(){this.canvasImage.fitFlag=!1,this.canvasImage.activeFit=void 0,this.canvasImage.currentFit=void 0,this.canvasImage.init(),this.canvasImage.render()}makeFit(){if(this.dragRect.width<100&&this.dragRect.height<100)return;const t=this.store.data.pens.filter((t=>!t.parentId&&!t.isRuleLine&&(qe(t.calculative.worldRect,this.dragRect,!0)?!(t.type===o.Line&&!this.store.options.dragAllIn)||Ri(t,this.dragRect):void 0)));if(!t.length)return;const e=this.parent.getRect(t),i=this.store.data.scale,n=this.store.data.width||this.store.options.width,r=this.store.data.height||this.store.options.height;let s={x:(Math.floor(e.x)-this.store.data.origin.x)/i/n,y:(Math.floor(e.y)-this.store.data.origin.y)/i/r,width:(Math.ceil(e.width)+1)/i/n,height:(Math.ceil(e.height)+1)/i/r,children:t.map((t=>t.id)),id:at(),active:!0};s.x<-.1&&(s.x=-.1),s.y<-.1&&(s.y=-.1),s.width>.5?(s.left=!0,s.right=!0,s.leftValue=(s.x-0)*i*n,s.rightValue=(1-(s.x+s.width))*i*n):s.x<.5?(s.left=!0,s.leftValue=(s.x-0)*i*n):(s.right=!0,s.rightValue=(1-(s.x+s.width))*i*n),s.leftValue<1&&(s.leftValue=0),s.rightValue<1&&(s.rightValue=0),s.height>.5?(s.top=!0,s.bottom=!0,s.topValue=(s.y-0)*i*r,s.bottomValue=(1-(s.y+s.height))*i*r):s.y<.5?(s.top=!0,s.topValue=(s.y-0)*i*r):(s.bottom=!0,s.bottomValue=(1-(s.y+s.height))*i*r),s.topValue<1&&(s.topValue=0),s.bottomValue<1&&(s.bottomValue=0),this.store.data.fits||(this.store.data.fits=[]),this.store.data.fits.forEach((t=>{t.active=!1})),this.store.data.fits.push(s),this.canvasImage.activeFit=s,this.store.emitter.emit("fit",s),this.canvasImage.init(),this.canvasImage.render()}updateFit(t){const e=this.store.data.scale,i=this.store.data.width||this.store.options.width,n=this.store.data.height||this.store.options.height;let r=(t.x-this.store.data.origin.x)/e/i,s=(t.y-this.store.data.origin.y)/e/n;if(this.canvasImage.currentFit){const a=this.canvasImage.activeFit;if("top"===this.canvasImage.currentFit){s<-.1&&(s=-.1);let t=s-a.y;if(a.height-=t,a.height<.01)return void(a.height=.01);a.y=s}if("bottom"===this.canvasImage.currentFit&&(s>1.1&&(s=1.1),a.height=s-a.y,a.height<=.01&&(a.height=.01)),"left"===this.canvasImage.currentFit){r<-.1&&(r=-.1);let t=r-a.x;if(a.width-=t,a.width<.01)return void(a.width=.01);a.x=r}"right"===this.canvasImage.currentFit&&(r>1.1&&(r=1.1),a.width=r-a.x,a.width<=.01&&(a.width=.01));let l={x:a.x*i*e+this.store.data.origin.x,y:a.y*n*e+this.store.data.origin.y,width:a.width*i*e,height:a.height*n*e};He(l);const c=this.store.data.pens.filter((t=>!t.parentId&&!t.isRuleLine&&(qe(t.calculative.worldRect,l,!0)?!(t.type===o.Line&&!this.store.options.dragAllIn)||Ri(t,l):void 0)));a.left=void 0,a.leftValue=void 0,a.right=void 0,a.rightValue=void 0,a.top=void 0,a.topValue=void 0,a.bottom=void 0,a.bottomValue=void 0,a.width>.5?(a.left=!0,a.right=!0,a.leftValue=(a.x-0)*e*i,a.rightValue=(1-(a.x+a.width))*e*i):a.x<.5?(a.left=!0,a.leftValue=(a.x-0)*e*i):(a.right=!0,a.rightValue=(1-(a.x+a.width))*e*i),Math.abs(a.leftValue)<1&&(a.leftValue=0),Math.abs(a.rightValue)<1&&(a.rightValue=0),a.height>.5?(a.top=!0,a.bottom=!0,a.topValue=(a.y-0)*e*n,a.bottomValue=(1-(a.y+a.height))*e*n):a.y<.5?(a.top=!0,a.topValue=(a.y-0)*e*n):(a.bottom=!0,a.bottomValue=(1-(a.y+a.height))*e*n),Math.abs(a.topValue)<1&&(a.topValue=0),Math.abs(a.bottomValue)<1&&(a.bottomValue=0),a.children=c.map((t=>t.id)),this.store.emitter.emit("fit",a),this.mouseDown.x=t.x,this.mouseDown.y=t.y,this.canvasImage.init(),this.canvasImage.render()}}updateFitRect(t=this.canvasImage.activeFit){const e=this.store.data.width||this.store.options.width,i=this.store.data.height||this.store.options.height;t.left&&(t.leftValue?t.x=Math.abs(t.leftValue)<1?t.leftValue:t.leftValue/e:t.x=0),t.right&&(t.rightValue?t.width=1-(Math.abs(t.rightValue)<1?t.rightValue:t.rightValue/e)-t.x:t.width=1-t.x),t.top&&(t.topValue?t.y=Math.abs(t.topValue)<1?t.topValue:t.topValue/i:t.y=0),t.bottom&&(t.bottomValue?t.height=1-(Math.abs(t.bottomValue)<1?t.bottomValue:t.bottomValue/i)-t.y:t.height=1-t.y),this.canvasImage.init(),this.canvasImage.render()}deleteFit(t=this.canvasImage.activeFit){if(!t)return;const e=this.store.data.fits.findIndex((e=>e.id===t.id));this.store.data.fits.splice(e,1),this.canvasImage.activeFit=void 0,this.canvasImage.init(),this.canvasImage.render(),this.store.emitter.emit("fit",void 0)}calcuActiveFit(){const t=this.store.data.width||this.store.options.width,e=this.store.data.height||this.store.options.height;let i=(this.mouseDown.x-this.store.data.origin.x)/this.store.data.scale/t,n=(this.mouseDown.y-this.store.data.origin.y)/this.store.data.scale/e,o=-1,r=-1;this.store.data.fits?.forEach(((t,e)=>{t.ex=null,t.ey=null,Be({x:i,y:n},t)&&(o=e),t.active&&(r=e)})),-1!==o&&o!==r?(this.canvasImage.activeFit=this.store.data.fits[o],this.store.data.fits[o].active=!0,-1!==r&&(this.store.data.fits[r].active=!1),this.store.emitter.emit("fit",this.store.data.fits[o])):-1===o&&-1!==r&&(this.store.data.fits[r].active=!1,this.store.emitter.emit("fit",void 0),this.canvasImage.activeFit=null),this.inactive(),this.canvasImage.init(),this.canvasImage.render()}toggleMagnifier(){this.magnifierCanvas.magnifier=!this.magnifierCanvas.magnifier,this.magnifierCanvas.magnifier&&(this.externalElements.style.cursor="default"),this.render()}destroy(){switch(this.scroll&&this.scroll.destroy(),this.tooltip?.destroy(),this.dialog?.destroy(),this.title?.destroy(),this.externalElements.removeEventListener("gesturestart",this.onGesturestart),this.externalElements.ondragover=t=>t.preventDefault(),this.externalElements.ondrop=void 0,this.externalElements.ontouchstart=void 0,this.externalElements.ontouchmove=void 0,this.externalElements.ontouchend=void 0,this.externalElements.onmousedown=void 0,this.externalElements.onmousemove=void 0,this.externalElements.onmouseup=void 0,this.externalElements.onmouseleave=void 0,this.externalElements.ondblclick=void 0,this.store.options.keydown){case j.Document:document.removeEventListener("keydown",this.onkeydown),document.removeEventListener("keyup",this.onkeyup);break;case j.Canvas:this.externalElements.removeEventListener("keydown",this.onkeydown),this.externalElements.removeEventListener("keyup",this.onkeyup)}document.removeEventListener("copy",this.onCopy),document.removeEventListener("cut",this.onCut),document.removeEventListener("paste",this.onPaste),window&&window.removeEventListener("resize",this.onResize),window&&window.removeEventListener("scroll",this.onScroll)}}function mn(t,e){const i=e||new Path2D;t.onDestroy||(t.onDestroy=xn,t.onMove=bn,t.onRotate=bn,t.onMouseEnter=kn,t.onMouseLeave=Tn,t.onMouseMove=Cn,t.onMouseUp=An,t.onInput=wn);let n=t.calculative.borderRadius||0,o=n;const{x:r,y:s,width:a,height:l,ex:c,ey:h}=t.calculative.worldRect,{x:d}=t.calculative.worldTextRect;n<1&&(n*=a,o*=l);let u=n{if(t.followers){let i=t.followers.findIndex((t=>t===e.id));if(-1!==i){const n=t.calculative.canvas.store.pens[e.id+gn];n&&n.calculative&&(qe(n.calculative.worldRect,t.calculative.worldRect,!0)||t.followers.splice(i,1))}}}))}function An(t){const e=t.calculative.canvas.store.active;e&&e.length&&e.forEach((e=>{const i=t.calculative.canvas.store.pens[e.id+gn];if(i&&i.calculative){let n=Q(t.calculative.worldRect);n.x-=1,n.y-=1,n.width+=2,n.height+=2,qe(i.calculative.worldRect,n,!0)&&(t.followers||(t.followers=[]),t.followers.includes(e.id)||t.followers.push(e.id))}}))}function Cn(t,e){}function Rn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.ellipse(n+r/2,o+s/2,r/2,s/2,0,0,2*Math.PI),i instanceof Path2D)return i}function Sn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n+r/2,o),i.lineTo(n+r,o+s/2),i.lineTo(n+r/2,o+s),i.lineTo(n,o+s/2),i.lineTo(n+r/2,o),i.closePath(),i instanceof Path2D)return i}function Pn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n+r/2,o),i.lineTo(n+r,o+s),i.lineTo(n,o+s),i.lineTo(n+r/2,o),i.closePath(),i instanceof Path2D)return i}function En(t){t.anchors=[{x:.5,y:0},{x:.75,y:.5},{x:.5,y:1},{x:.25,y:.5}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function In(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n+r/2,o),i.lineTo(n+r,o+2*s/5),i.lineTo(n+4*r/5,o+s),i.lineTo(n+r/5,o+s),i.lineTo(n,o+2*s/5),i.closePath(),i instanceof Path2D)return i}function _n(t){t.anchors=[{x:.5,y:0},{x:1,y:.4},{x:.8,y:1},{x:.2,y:1},{x:0,y:.4}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function Ln(t,e){t.onResize||(t.onResize=Dn);const i=e||new Path2D,{width:n,height:o,center:r}=t.calculative.worldRect,s=n>o?o:n,a=r.x,l=r.y,c=l-s/2,h=l-s/4,d=-(h-l)*Math.sin(Math.PI/180*324)+a,u=(h-l)*Math.cos(Math.PI/180*324)+l;i.moveTo(d,u);for(let t=0;t<5;++t)i.lineTo(-(c-l)*Math.sin(Math.PI/180*72*t)+a,(c-l)*Math.cos(Math.PI/180*72*t)+l),i.lineTo((d-a)*Math.cos(Math.PI/180*72*(t+1))-(u-l)*Math.sin(Math.PI/180*72*(t+1))+a,(d-a)*Math.sin(Math.PI/180*72*(t+1))+(u-l)*Math.cos(Math.PI/180*72*(t+1))+l);if(i.closePath(),i instanceof Path2D)return i}function Mn(t){const{width:e,height:i}=t,n=e>i?i:e,o=[];for(let r=0;r<5;++r)o.push({flag:1,id:String(r),penId:t.id,x:.5+n/2*Math.sin(Math.PI/180*72*r)/e,y:-n/2*Math.cos(Math.PI/180*72*r)/i+.5});t.anchors=o}function Dn(t){const e=t.anchors.filter((t=>1!==t.flag));Mn(t),t.anchors=t.anchors.concat(...e)}function On(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n+r/4,o),i.lineTo(n+3*r/4,o),i.lineTo(n+r,o+s/2),i.lineTo(n+3*r/4,o+s),i.lineTo(n+1*r/4,o+s),i.lineTo(n,o+s/2),i.lineTo(n+r/4,o),i.closePath(),i instanceof Path2D)return i}function Nn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n,o+s/2),i.lineTo(n+s/2,o),i.lineTo(n+s/2,o+s/3),i.lineTo(n+r,o+s/3),i.lineTo(n+r,o+2*s/3),i.lineTo(n+s/2,o+2*s/3),i.lineTo(n+s/2,o+2*s/3),i.lineTo(n+s/2,o+s),i.closePath(),i instanceof Path2D)return i}function Bn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n,o+s/3),i.lineTo(n+(r-s/2),o+s/3),i.lineTo(n+(r-s/2),o),i.lineTo(n+r,o+s/2),i.lineTo(n+(r-s/2),o+s),i.lineTo(n+(r-s/2),o+2*s/3),i.lineTo(n,o+2*s/3),i.closePath(),i instanceof Path2D)return i}function Fn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n,o+s/2),i.lineTo(n+s/2,o),i.lineTo(n+s/2,o+s/3),i.lineTo(n+(r-s/2),o+s/3),i.lineTo(n+(r-s/2),o),i.lineTo(n+r,o+s/2),i.lineTo(n+(r-s/2),o+s),i.lineTo(n+(r-s/2),o+2*s/3),i.lineTo(n+s/2,o+2*s/3),i.lineTo(n+s/2,o+s),i.closePath(),i instanceof Path2D)return i}function zn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s,ey:a}=t.calculative.worldRect;if(i.moveTo(n,o),i.lineTo(n+r,o),i.lineTo(n+r,o+3*s/4),i.lineTo(n+8*r/16,o+3*s/4),i.lineTo(n+r/4,a),i.lineTo(n+5*r/16,o+3*s/4),i.lineTo(n,o+3*s/4),i.closePath(),i instanceof Path2D)return i}function Hn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n+r/5,o+13*s/16),i.bezierCurveTo(n-r/15,o+13*s/16,n-r/15,o+7*s/16,n+r/5,o+7*s/16),i.bezierCurveTo(n+r/5,o,n+4*r/5,o,n+4*r/5,o+7*s/16),i.bezierCurveTo(n+16*r/15,o+7*s/16,n+16*r/15,o+13*s/16,n+4*r/5,o+13*s/16),i.closePath(),i instanceof Path2D)return i}function jn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,ex:s,ey:a}=t.calculative.worldRect,l=r/6;if(i.moveTo(n,o),i.lineTo(s-l,o),i.lineTo(s,o+l),i.lineTo(s,a),i.lineTo(n,a),i.closePath(),i.moveTo(s-l,o),i.lineTo(s-l,o+l),i.lineTo(s,o+l),i.closePath(),i instanceof Path2D)return i}function Wn(t,e){const i=e||new Path2D,{x:n,y:o,width:r,ex:s,ey:a}=t.calculative.worldRect,l=r/4,c=n+r/2;if(i.arc(c,o+l,l,0,2*Math.PI),i.moveTo(n,o+3*l),i.lineTo(s,o+3*l),i.moveTo(c,o+2*l),i.lineTo(c,o+4*l),i.moveTo(c,o+4*l),i.lineTo(n,a),i.moveTo(c,o+4*l),i.lineTo(s,a),i.closePath(),i instanceof Path2D)return i}const Un={};function Vn(t){t.onDestroy||(t.onDestroy=qn,t.onMove=Kn,t.onResize=Yn,t.onRotate=Kn,t.onValue=$n,t.onChangeId=Xn);const e=new Path2D;if(t.image){if(!Un[t.id]){const e=new Image;e.crossOrigin="anonymous",e.src=t.image,t.calculative.canvas.parent.store.options.cdn&&!(t.image.startsWith("http")||t.image.startsWith("//")||t.image.startsWith("data:image"))&&(e.src=t.calculative.canvas.parent.store.options.cdn+t.image),Un[t.id]=e,e.onload=()=>{Un[t.id]===e&&(t.calculative.img=e,t.calculative.imgNaturalWidth=e.naturalWidth||t.iconWidth,t.calculative.imgNaturalHeight=e.naturalHeight||t.iconHeight,t.calculative.canvas.externalElements?.parentElement.appendChild(e),Gn(t,e))}}return t.calculative.patchFlags&&Un[t.id]&&Gn(t,Un[t.id]),e}}function qn(t){Un[t.id]&&(Un[t.id].remove(),Un[t.id]=void 0)}function Kn(t){Un[t.id]&&Gn(t,Un[t.id])}function Yn(t){Un[t.id]&&Gn(t,Un[t.id])}function $n(t){Un[t.id]&&(Gn(t,Un[t.id]),Un[t.id].getAttribute("src")!==t.image&&(Un[t.id].src=t.image))}function Xn(t,e,i){Un[e]&&(Un[i]=Un[e],delete Un[e])}function Gn(t,e){e.style.objectFit=t.imageRatio?"contain":"fill",pe(t,e)}function Qn(e,i){return e.onResize||(e.onResize=Jn,e.onValue=Zn),t(e,i)}function Jn(t){const e=t.anchors.filter((t=>1!==t.flag));to(t),t.anchors=t.anchors.concat(...e)}function Zn(t){Jn(t),Yt(t)}function to(t){const e=[],{x:i,y:n,width:o,height:r}=t,s=function(t){let e=t.calculative.borderRadius||0,i=t.calculative.borderRadius||0;const{width:n,height:o}=t;t.calculative.borderRadius<1&&(e=n*t.calculative.borderRadius,i=o*t.calculative.borderRadius);let r=ei+o-s&&(c=io(i+o-s,c+s,l,s,-1)),e.push({id:String(e.length),flag:1,penId:t.id,x:(l-i)/o,y:(c-n)/r})}for(let a=0;a<3;a++){let l=n+r*(a+1)/4,c=i+o;ln+r-s&&(c=eo(c-s,n+r-s,l,s)),e.push({id:String(e.length),flag:1,penId:t.id,x:(c-i)/o,y:(l-n)/r})}for(let a=0;a<5;a++){if(2===a)continue;let l=i+o*(a+1)/6,c=n+r;li+o-s&&(c=io(i+o-s,c-s,l,s)),e.push({id:String(e.length),flag:1,penId:t.id,x:(l-i)/o,y:(c-n)/r})}for(let a=0;a<3;a++){let l=n+r*(a+1)/4,c=i;ln+r-s&&(c=eo(c+s,n+r-s,l,s,-1)),e.push({id:String(e.length),flag:1,penId:t.id,x:(c-i)/o,y:(l-n)/r})}t.anchors=e}function eo(t,e,i,n,o=1){return o*Math.sqrt(n**2-(i-e)**2)+t}function io(t,e,i,n,o=1){return o*Math.sqrt(n**2-(i-t)**2)+e}function no(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.moveTo(n,o+s),i.lineTo(n+r,o+s),i.closePath(),i instanceof Path2D)return i}function oo(t){t.anchors=[{x:0,y:1},{x:1,y:1}].map((({x:e,y:i},n)=>({id:n+"",x:e,y:i,penId:t.id})))}var ro;!function(t){t[t.Link=0]="Link",t[t.SetProps=1]="SetProps",t[t.StartAnimate=2]="StartAnimate",t[t.PauseAnimate=3]="PauseAnimate",t[t.StopAnimate=4]="StopAnimate",t[t.JS=5]="JS",t[t.GlobalFn=6]="GlobalFn",t[t.Emit=7]="Emit",t[t.StartVideo=8]="StartVideo",t[t.PauseVideo=9]="PauseVideo",t[t.StopVideo=10]="StopVideo",t[t.SendPropData=11]="SendPropData",t[t.SendVarData=12]="SendVarData",t[t.Navigator=13]="Navigator",t[t.Dialog=14]="Dialog",t[t.SendData=15]="SendData",t[t.PostMessage=16]="PostMessage",t[t.PostMessageToParent=17]="PostMessageToParent"}(ro||(ro={}));class so{constructor(t){let e;this.parent=t,this.boxWidth=320,this.boxHeight=180,this.ratio=this.boxWidth/this.boxHeight,this.padding=5,this.onMouseDown=t=>{t.preventDefault(),t.stopPropagation(),this.isDown=!0},this.onMouseMove=t=>{if(t.preventDefault(),t.stopPropagation(),this.isDown)try{this.parent.gotoView(t.offsetX/this.box.clientWidth,t.offsetY/this.box.clientHeight)}catch(t){console.warn(t.message),this.isDown=!1}},this.onMouseUp=t=>{t.preventDefault(),t.stopPropagation();try{this.parent.gotoView(t.offsetX/this.box.clientWidth,t.offsetY/this.box.clientHeight)}catch(t){console.warn(t.message)}finally{this.isDown=!1}},this.onWheel=t=>{let e=.015;if(this.parent.store.options.scaleOff)e=this.parent.store.options.scaleOff,t.deltaY>0&&(e=-this.parent.store.options.scaleOff);else if(/mac os /i.test(navigator.userAgent))t.ctrlKey?t.deltaY>0&&(e*=-1):e*=t.wheelDeltaY/240;else{let i=.2;-1!==t.deltaY.toString().indexOf(".")&&(i=.01),e=t.deltaY>0?-i:i}let{offsetX:i,offsetY:n}=t;const o=this.parent.store.data.width||this.parent.store.options.width,r=this.parent.store.data.height||this.parent.store.options.height;if(o&&r)i=i/this.boxWidth*o*this.parent.store.data.scale+this.parent.store.data.origin.x+this.parent.store.data.x,n=n/this.boxHeight*r*this.parent.store.data.scale+this.parent.store.data.origin.y+this.parent.store.data.y;else{const t=this.parent.parent.getRect();i=i/this.boxWidth*t.width+t.x+this.parent.store.data.x,n=n/this.boxHeight*t.height+t.y+this.parent.store.data.y}this.parent.scale(this.parent.store.data.scale+e,{x:i,y:n})},this.box=document.createElement("div"),this.img=new Image,this.view=document.createElement("div"),this.box.appendChild(this.img),this.box.appendChild(this.view),this.parent.externalElements?.parentElement.appendChild(this.box),this.box.className="meta2d-map",this.box.onmousedown=this.onMouseDown,this.box.onmousemove=this.onMouseMove,this.box.onmouseup=this.onMouseUp,this.box.onwheel=this.onWheel;for(let t=0;tthis.ratio){const t=e.width/this.ratio;e.y-=(t-e.height)/2,e.height=t,He(e)}else{const t=e.height*this.ratio;e.x-=(t-e.width)/2,e.width=t,He(e)}const o=this.parent.canvasRect;let r=0,s=0;if(e.x<0)r=-e.x/e.width;else if(e.x+e.width>o.width){let t=0;o.width>e.width&&(t=o.width-e.width),r=(-e.x+t)/e.width}if(e.y<0)s=-e.y/e.height;else if(e.y+e.height>o.height){let t=0;o.height>e.height&&(t=o.height-e.height),s=(-e.y+t)/e.height}const a=o.width>e.width?1:o.width/e.width,l=o.height>e.height?1:o.height/e.height;this.view.style.left=this.padding+r*this.boxWidth+"px",this.view.style.width=a*this.boxWidth+"px",this.view.style.top=this.padding+s*this.boxHeight+"px",this.view.style.height=l*this.boxHeight+"px"}}}var ao,lo=i(421);function co(t){let e=t||window.location.search.split("?")[1];const i=new URLSearchParams(e);return Object.fromEntries(i.entries())}class ho{constructor(i,n={}){this.penPluginMap=new Map,this.events={},this.facePen=Jt,this.getWords=$,this.calcTextLines=Y,this.calcTextRect=q,this.calcTextDrawRect=K,this.register=F,this.registerCanvasDraw=z,this.registerAnchors=H,this.websocketTimes=0,this.mqttTimes=0,this.httpTimerList=[],this.updateTimerList=[],this.onEvent=(t,e)=>{switch(t){case"add":e.forEach((t=>{t.onAdd?.(t)})),this.onSizeUpdate();break;case"enter":e&&e.onMouseEnter&&e.onMouseEnter(e,this.canvas.mousePos),this.store.data.locked&&this.doEvent(e,t);break;case"leave":e&&e.onMouseLeave&&e.onMouseLeave(e,this.canvas.mousePos),this.store.data.locked&&this.doEvent(e,t);break;case"active":case"inactive":this.store.data.locked&&e.forEach((e=>{this.doEvent(e,t)}));break;case"click":e.pen&&e.pen.onClick&&!e.pen.disabled&&e.pen.onClick(e.pen,this.canvas.mousePos),this.store.data.locked&&e.pen&&!e.pen.disabled&&this.doEvent(e.pen,t);break;case"contextmenu":e.pen&&e.pen.onContextmenu&&!e.pen.disabled&&e.pen.onContextmenu(e.pen,this.canvas.mousePos),this.store.data.locked&&e.pen&&!e.pen.disabled&&this.doEvent(e.pen,t);break;case"mousedown":e.pen&&e.pen.onMouseDown&&!e.pen.disabled&&e.pen.onMouseDown(e.pen,this.canvas.mousePos),this.store.data.locked&&e.pen&&!e.pen.disabled&&this.doEvent(e.pen,t);break;case"mouseup":e.pen&&e.pen.onMouseUp&&!e.pen.disabled&&e.pen.onMouseUp(e.pen,this.canvas.mousePos),this.store.data.locked&&e.pen&&!e.pen.disabled&&this.doEvent(e.pen,t);break;case"dblclick":this.store.data.locked&&e.pen&&!e.pen.disabled&&this.doEvent(e.pen,t);break;case"valueUpdate":this.store.data.locked&&this.doEvent(e,t),this.canvas.tooltip.updateText(e);break;case"update":case"delete":case"translatePens":case"rotatePens":case"resizePens":this.onSizeUpdate();break;case"navigator":this.store.data.id||console.warn("请先保存当前图纸"),this.navigatorTo(e.params);break;case"input":case"change":this.store.data.locked&&e&&!e.disabled&&this.doEvent(e,t)}this.store.messageEvents[t]&&this.store.messageEvents[t].forEach((t=>{let e=!1;t.event.conditions&&t.event.conditions.length?"and"===t.event.conditionType?e=t.event.conditions.every((e=>this.judgeCondition(t.pen,e.key,e))):"or"===t.event.conditionType&&(e=t.event.conditions.some((e=>this.judgeCondition(t.pen,e.key,e)))):e=!0,e&&t.event.actions.forEach((e=>{this.events[e.action](t.pen,e)}))}))},this.doEvent=(t,e)=>{if(!t)return;let i=!1,n=[];if(t.events?.forEach(((o,r)=>{if(o.actions&&o.actions.length){if(o.name===e){let e=!1;o.conditions&&o.conditions.length?"and"===o.conditionType?e=o.conditions.every((e=>this.judgeCondition(t,e.key,e))):"or"===o.conditionType&&(e=o.conditions.some((e=>this.judgeCondition(t,e.key,e)))):e=!0,e&&n.push(r)}}else if(i=!0,this.events[o.action]&&o.name===e){let e=!o.where?.type;if(o.where){const{fn:i,fnJs:n,comparison:r,key:s,value:a}=o.where;if(i)e=i(t,{meta2d:this});else if(n){try{o.where.fn=new Function("pen","context",n)}catch(t){console.error("Error: make function:",t)}o.where.fn&&(e=o.where.fn(t,{meta2d:this}))}else{let i=t[s];switch(["x","y","width","height"].includes(s)&&(i=this.getPenRect(t)[s]),r){case">":e=i>+a;break;case">=":e=i>=+a;break;case"<":e=i<+a;break;case"<=":e=i<=+a;break;case"=":case"==":e=i==a;break;case"!=":e=i!=a;break;case"[)":e=rt(+i,a);break;case"![)":e=!rt(+i,a);break;case"[]":e=st(i,a);break;case"![]":e=!st(i,a)}}}e&&n.push(r)}})),i?t.events?.forEach(((e,i)=>{n.includes(i)&&this.events[e.action](t,e)})):t.events?.forEach(((e,i)=>{n.includes(i)&&e.actions.forEach((e=>{this.events[e.action]&&this.events[e.action](t,e)}))})),"valueUpdate"===e){t.realTimes?.forEach((e=>{let i=[];e.triggers?.forEach(((n,o)=>{let r=!1;n.conditions?.length?"and"===n.conditionType?r=n.conditions.every((i=>this.judgeCondition(t,e.key,i))):"or"===n.conditionType&&(r=n.conditions.some((i=>this.judgeCondition(t,e.key,i)))):r=!0,r&&i.push(o)})),e.triggers?.forEach(((e,n)=>{i.includes(n)&&e.actions?.forEach((e=>{this.events[e.action](t,e)}))}))}));let e=[];if(this.store.globalTriggers[t.id]?.forEach(((t,i)=>{let n=!1;t.conditions?.length?"and"===t.conditionType?n=t.conditions.every((t=>this.judgeCondition(this.store.pens[t.source],t.key,t))):"or"===t.conditionType&&(n=t.conditions.some((t=>this.judgeCondition(this.store.pens[t.source],t.key,t)))):n=!0,n&&e.push(i)})),this.store.globalTriggers[t.id]?.forEach(((i,n)=>{e.includes(n)&&i.actions?.forEach((e=>{this.events[e.action](t,e)}))})),t.triggers?.length)for(let e of t.triggers)if(e.status?.length)for(let i of e.status){let e=!1;if(i.conditions?.length?"and"===i.conditionType?e=i.conditions.every((e=>this.judgeCondition(t,e.key,e))):"or"===i.conditionType&&(e=i.conditions.some((e=>this.judgeCondition(t,e.key,e)))):e=!0,e){i.actions?.forEach((e=>{this.events[e.action](t,e)}));break}}}this.doEvent(this.store.pens[t.parentId],e)},this.doDataEvent=t=>{if(!this.store.data.dataEvents?.length)return;const e=t.reduce(((t,{dataId:e,id:i,value:n})=>(t[i||e]=n,t)),{});let i=[];this.store.data.dataEvents?.forEach(((t,n)=>{let o=!1;t.conditions&&t.conditions.length?"and"===t.conditionType?o=t.conditions.every((t=>this.dataJudegeCondition(e,t.key,t))):"or"===t.conditionType&&(o=t.conditions.some((t=>this.dataJudegeCondition(e,t.key,t)))):o=!0,o&&i.push(n)})),this.store.data.dataEvents?.forEach(((t,n)=>{i.includes(n)&&t.actions?.forEach((t=>{this.events[t.action](e,t)}))}))},this.renderPenRaw=Ft,this.setElemPosition=pe,this.setLifeCycleFunc=Ne,this.store=((t="default")=>{var e;return B[t]||(B[t]={data:{x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{},theme:"light"},histories:[],pens:{},path2dMap:new WeakMap,animateMap:new WeakMap,active:[],animates:new Set,options:{...W},theme:{...U},emitter:{all:e=e||new Map,on:function(t,i){var n=e.get(t);n&&n.push(i)||e.set(t,[i])},off:function(t,i){var n=e.get(t);n&&n.splice(n.indexOf(i)>>>0,1)},emit:function(t,i){(e.get(t)||[]).slice().map((function(t){t(i)})),(e.get("*")||[]).slice().map((function(e){e(t,i)}))}},bindDatas:{},bind:{},pensNetwork:{},cacheDatas:[],messageEvents:{},templatePens:{},globalTriggers:{}},B[t].id=t),B[t]})(at()),this.setOptions(n),this.setDatabyOptions(n),this.init(i),this.register({rectangle:t,square:e,circle:Rn,svgPath:si,diamond:Sn,triangle:Pn,pentagon:In,pentagram:Ln,hexagon:On,leftArrow:Nn,rightArrow:Bn,twowayArrow:Fn,message:zn,cloud:Hn,file:jn,people:Wn,line:vi,iframe:Hi,video:Qi,gif:Vn,mindNode:Qn,mindLine:no,mindNode2:t,panel:mn}),this.registerCanvasDraw({cube:ai}),this.registerAnchors({triangle:En,pentagon:_n,pentagram:Mn,mindNode:to,mindLine:oo}),globalThis.meta2d=this,this.initEventFns(),this.store.emitter.on("*",this.onEvent)}get beforeAddPen(){return this.canvas.beforeAddPen}set beforeAddPen(t){this.canvas.beforeAddPen=t}get beforeAddPens(){return this.canvas.beforeAddPens}set beforeAddPens(t){this.canvas.beforeAddPens=t}get beforeAddAnchor(){return this.canvas.beforeAddAnchor}set beforeAddAnchor(t){this.canvas.beforeAddAnchor=t}get beforeRemovePens(){return this.canvas.beforeRemovePens}set beforeRemovePens(t){this.canvas.beforeRemovePens=t}get beforeRemoveAnchor(){return this.canvas.beforeRemoveAnchor}set beforeRemoveAnchor(t){this.canvas.beforeRemoveAnchor=t}setOptions(t={}){void 0===t.grid&&void 0===t.gridColor&&void 0===t.gridSize||this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),void 0===t.rule&&void 0===t.ruleColor&&void 0===t.ruleOptions||(this.store.patchFlagsTop=!0,t.ruleOptions&&this.store.options?.ruleOptions&&(Object.assign(this.store.options.ruleOptions,t.ruleOptions),t.ruleOptions=this.store.options.ruleOptions)),void 0!==t.background&&this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),void 0!==t.resizeMode&&(t.resizeMode||(this.canvas.hotkeyType=m.None)),void 0===t.width&&void 0===t.height||(this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0),this.canvas&&this.canvas.canvasTemplate.canvas.style.backgroundImage&&(this.canvas.canvasTemplate.canvas.style.backgroundImage="")),this.store.options=Object.assign(this.store.options,t),this.canvas&&void 0!==t.scroll&&(t.scroll?(!this.canvas.scroll&&(this.canvas.scroll=new an(this.canvas)),this.canvas.scroll.show()):this.canvas.scroll&&this.canvas.scroll.hide())}getOptions(){return this.store.options}setTheme(t){this.store.data.theme=t,this.setBackgroundColor(this.store.theme[t].background),this.canvas.parentElement.style.background=this.store.theme[t].parentBackground,this.store.data.color=this.store.theme[t].color,this.setOptions({ruleColor:this.store.theme[t].ruleColor,ruleOptions:this.store.theme[t].ruleOptions}),this.render()}setDatabyOptions(t={}){const{color:e,activeColor:i,activeBackground:n,grid:o,gridColor:r,gridSize:s,fromArrow:a,toArrow:l,rule:c,ruleColor:h,textColor:d}=t;this.setRule({rule:c,ruleColor:h}),this.setGrid({grid:o,gridColor:r,gridSize:s}),this.store.data=Object.assign(this.store.data,{textColor:d,color:e,activeColor:i,activeBackground:n,fromArrow:a,toArrow:l})}init(t){this.canvas=new yn(this,"string"==typeof t?document.getElementById(t):t,this.store),this.resize(),this.canvas.listen()}initEventFns(){this.events[ro.Link]=(t,e)=>{window&&e.value&&"string"==typeof e.value?window.open(e.value,e.params??"_blank"):console.warn("[meta2d] Link param is not a string")},this.events[ro.SetProps]=(t,e)=>{const i=e.value;if(i&&"object"==typeof i)return(e.params?this.find(e.params):this.find(t.id)).forEach((t=>{i.hasOwnProperty("visible")&&t.visible!==i.visible&&this.setVisible(t,i.visible),this.setValue({id:t.id,...i},{render:!1,doEvent:!1})})),void this.render();console.warn("[meta2d] SetProps value is not an object")},this.events[ro.StartAnimate]=(t,e)=>{let i=t;e.value&&(i=this.findOne(e.value)),this.store.animates.has(i)&&!i.calculative.pause||(e.targetType&&e.params?this.startAnimate(e.value||[t],e.params):e.value&&"string"!=typeof e.value?console.warn("[meta2d] StartAnimate value is not a string"):this.startAnimate(e.value||[t]))},this.events[ro.PauseAnimate]=(t,e)=>{e.value&&"string"!=typeof e.value?console.warn("[meta2d] PauseAnimate value is not a string"):this.pauseAnimate(e.value||[t])},this.events[ro.StopAnimate]=(t,e)=>{if(e.value&&"string"!=typeof e.value)console.warn("[meta2d] StopAnimate event value is not a string");else{if(e.value){let t=this.findOne(e.value);if(!this.store.animates.has(t))return}else if(!this.store.animates.has(t))return;this.stopAnimate(e.value||[t])}},this.events[ro.StartVideo]=(t,e)=>{e.value&&"string"!=typeof e.value?console.warn("[meta2d] StartVideo value is not a string"):this.startVideo(e.value||[t])},this.events[ro.PauseVideo]=(t,e)=>{e.value&&"string"!=typeof e.value?console.warn("[meta2d] PauseVideo value is not a string"):this.pauseVideo(e.value||[t])},this.events[ro.StopVideo]=(t,e)=>{e.value&&"string"!=typeof e.value?console.warn("[meta2d] StopVideo event value is not a string"):this.stopVideo(e.value||[t])},this.events[ro.JS]=(t,e)=>{if(e.value&&!e.fn)try{if("string"!=typeof e.value)throw new Error("[meta2d] Function value must be string");const t=e.value;e.fn=new Function("pen","params","context",t)}catch(t){console.error("[meta2d]: Error on make a function:",t)}e.fn?.(t,e.params,{meta2d:this,eventName:e.name})},this.events[ro.GlobalFn]=(t,e)=>{"string"==typeof e.value?globalThis[e.value]&&globalThis[e.value](t,e.params):console.warn("[meta2d] GlobalFn value must be a string")},this.events[ro.Emit]=(t,e)=>{"string"==typeof e.value?this.store.emitter.emit(e.value,{pen:t,params:e.params,eventName:e.name}):console.warn("[meta2d] Emit value must be a string")},this.events[ro.SendPropData]=(t,e)=>{const i=Q(e.value);if(i&&"object"==typeof i){const n=e.params?this.findOne(e.params):t;for(let t in i)void 0!==i[t]&&""!==i[t]||(i[t]=n[t]);return i.id=n.id,void this.doSendDataEvent(i,e.extend)}console.warn("[meta2d] SendPropData value is not an object")},this.events[ro.SendVarData]=(t,e)=>{const i=Q(e.value);if(i&&"object"==typeof i){const n=e.params?this.findOne(e.params):t;let o=[];for(let t in i){let e={dataId:t,value:i[t]};if(!e.value){let t=n.form.find((t=>t.dataIds&&t.dataIds.dataId===e.dataId));t&&(e.value=n[t.key])}o.push(e)}this.doSendDataEvent(o,e.extend)}else console.warn("[meta2d] SendVarData value is not an object")},this.events[ro.Navigator]=(t,e)=>{e.value&&"string"==typeof e.value&&this.navigatorTo(e.value)},this.events[ro.Dialog]=(t,e)=>{e.params&&"string"==typeof e.params&&e.value&&"string"==typeof e.value&&this.canvas.dialog.show(e.value,e.params)},this.events[ro.SendData]=(t,e)=>{const i=Q(e.value);if(i&&"object"==typeof i&&"id"===e.targetType){const n=e.params?this.findOne(e.params):t;for(let t in i)void 0!==i[t]&&""!==i[t]||(i[t]=n[t]);return n.deviceId&&(i.deviceId=n.deviceId),void this.sendDataToNetWork(i,t,e)}},this.events[ro.PostMessage]=(t,e)=>{if("string"!=typeof e.value)return void console.warn("[meta2d] Emit value must be a string");const i=e.params?this.findOne(e.params):t;if("iframe"!==i.name||!i.iframe)return void console.warn("不是嵌入页面");let n=co(i.iframe.split("?")[1]);i.calculative.singleton.div.children[0].contentWindow.postMessage(JSON.stringify({name:e.value,id:n.id}),"*")},this.events[ro.PostMessageToParent]=(t,e)=>{"string"==typeof e.value?window.parent.postMessage(JSON.stringify(e.value),"*"):console.warn("[meta2d] Emit value must be a string")}}navigatorTo(t){if(!t)return;let e=window.location.href.split("id=");if(e.length>1){let i=e[1].indexOf("&");window.location.href=-1===i?e[0]+"id="+t:e[0]+"id="+t+e[1].slice(i)}}doSendDataEvent(t,e){let i=JSON.stringify(t);this.mqttClient&&this.mqttClient.connected&&(e?e.split(",").forEach((t=>{this.mqttClient.publish(t,i)})):this.store.data.mqttTopics&&this.store.data.mqttTopics.split(",").forEach((t=>{this.mqttClient.publish(t,i)}))),this.websocket&&1===this.websocket.readyState&&this.websocket.send(i),(this.store.data.https||this.store.data.http)&&this.sendDatabyHttp(i),this.store.emitter.emit("sendData",i)}async sendDataToNetWork(t,e,i){const n=Q(i.network);if(n.data&&(Object.assign(n,n.data),delete n.data),n.url)if("http"===n.protocol){if("object"==typeof n.headers)for(let t in n.headers)if("string"==typeof n.headers[t]){let e=n.headers[t].match(/(?<=\$\{).*?(?=\})/g);e&&(n.headers[t]=n.headers[t].replace(`\${${e[0]}}`,this.getDynamicParam(e[0])))}let o,r=n.url;if("GET"===n.method&&(o="?"+Object.keys(t).map((e=>e+"="+t[e])).join("&")),"POST"===n.method&&r.indexOf("${")>-1){let t=r.match(/(?<=\$\{).*?(?=\})/g);t&&t.forEach((t=>{r=r.replace(`\${${t}}`,un(e,t)||this.getDynamicParam(t))}))}const s=await fetch(r+(o||""),{headers:n.headers||{},method:n.method,body:"POST"===n.method?JSON.stringify(t):void 0});if(s.ok){if(i.callback){const t=await s.text();if(!i.fn)try{if("string"!=typeof i.callback)throw new Error("[meta2d] Function callback must be string");const t=i.callback;i.fn=new Function("pen","data","context",t)}catch(t){console.error("[meta2d]: Error on make a function:",t)}i.fn?.(e,t,{meta2d:this,e:i})}console.info("http消息发送成功")}}else if("mqtt"===n.protocol){const e=this.mqttClients.filter((t=>t.options.href===n.url));if(e&&e.length)e[0].connected&&n.topics.split(",").forEach((i=>{e[0].publish(i,t)}));else{let e=lo.connect(n.url,n.options);e.on("connect",(()=>{console.info("mqtt连接成功"),n.topics.split(",").forEach((i=>{e.publish(i,t),e?.end()}))}))}}else if("websocket"===n.protocol){const e=this.websockets.filter((t=>t.url===n.url));if(e&&e.length)1===e[0].readyState&&e[0].send(t);else{let e=new WebSocket(n.url,n.protocols||void 0);e.onopen=function(){console.info("websocket连接成功"),e.send(t),setTimeout((()=>{e.close()}),100)}}}}resize(t,e){this.canvas.resize(t,e),this.render(),this.store.emitter.emit("resize",{width:t,height:e}),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.init()}async addPen(t,e,i=!0){return await this.canvas.addPen(t,e,i)}async addPens(t,e){return await this.canvas.addPens(t,e)}render(t){this.canvas?.render(t)}async setBackgroundImage(t,e){let i=this;this.store.data.bkImage=t;const n=e?.width||this.store.data?.width||this.store.options?.width,o=e?.height||this.store.data?.height||this.store.options?.height;if(n&&o?(this.canvas.canvasTemplate.canvas.style.backgroundImage=null,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)):this.canvas.canvasTemplate.canvas.style.backgroundImage=t?`url('${t}')`:"",t){const e=await async function(t){return new Promise((e=>{const n=new Image;n.src=t,i.store.options.cdn&&!(t.startsWith("http")||t.startsWith("//")||t.startsWith("data:image"))&&(n.src=i.store.options.cdn+t),n.crossOrigin="anonymous",n.onload=()=>{e(n)}}))}(t);this.store.bkImg=e,n&&o&&this.canvas&&(this.canvas.canvasTemplate.init(),this.render())}else this.store.bkImg=null}setBackgroundColor(t=this.store.data.background){this.store.data.background=t,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)}setGrid({grid:t=this.store.data.grid,gridColor:e=this.store.data.gridColor,gridSize:i=this.store.data.gridSize,gridRotate:n=this.store.data.gridRotate}={}){this.store.data.grid=t,this.store.data.gridColor=e,this.store.data.gridSize=i,this.store.data.gridRotate=n,this.canvas&&(this.canvas.canvasTemplate.bgPatchFlags=!0)}setRule({rule:t=this.store.data.rule,ruleColor:e=this.store.data.ruleColor}={}){this.store.data.rule=t,this.store.data.ruleColor=e,this.store.patchFlagsTop=!0}open(t,e=!0){if(this.clear(!1,t?.template),this.canvas.autoPolylineFlag=!0,t){this.setBackgroundImage(t.bkImage,t),Object.assign(this.store.data,t),this.store.data.pens=[];for(const e of t.pens)e.id||(e.id=at()),!e.calculative&&(e.calculative={canvas:this.canvas}),this.store.pens[e.id]=e;for(const e of t.pens)this.canvas.makePen(e)}if(this.canvas.patchFlagsLines.forEach((t=>{t.type&&this.canvas.initLineRect(t)})),this.store.data.template||(this.store.data.template=at()),e||(this.canvas.opening=!0),this.initBindDatas(),this.initBinds(),this.initMessageEvents(),this.initGlobalTriggers(),this.render(),this.listenSocket(),this.connectSocket(),this.connectNetwork(),this.startDataMock(),this.startAnimate(),this.startVideo(),this.doInitJS(),this.store.data.iconUrls)for(const t of this.store.data.iconUrls)i=t,n=()=>{this.render()},void 0,o=void 0,(o=document.createElement("link")).href=i,o.rel="stylesheet",n&&(o.onload=n),document.head.appendChild(o);var i,n,o;this.canvas.autoPolylineFlag=!1,this.store.emitter.emit("opened"),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.init()}cacheData(t){if(t&&this.store.options.cacheLength){let e=this.store.cacheDatas.findIndex((e=>e.data&&e.data._id===t));if(-1===e)this.store.cacheDatas.push({data:Q(this.store.data,!0)}),this.store.cacheDatas.length>this.store.options.cacheLength&&this.store.cacheDatas.shift();else{let t=this.store.cacheDatas.splice(e,1)[0];this.store.cacheDatas.push(t)}}}loadCacheData(t){let e=this.store.cacheDatas.findIndex((e=>e.data&&e.data._id===t));-1!==e&&(this.store.data=this.store.cacheDatas[e].data,this.setBackgroundImage(this.store.data.bkImage),this.store.pens={},this.store.data.pens.forEach((t=>{t.calculative.canvas=this.canvas,this.store.pens[t.id]=t,B.path2dDraws[t.name]&&this.store.path2dMap.set(t,B.path2dDraws[t.name](t)),t.type&&this.store.path2dMap.set(t,B.path2dDraws[t.name](t)),t.image&&(t.calculative.imageDrawed=!1,this.canvas.loadImage(t))})),this.render())}initBindDatas(){this.store.bindDatas={},this.store.data.pens.forEach((t=>{t.form?.forEach((e=>{let i;e.dataIds&&(i=Array.isArray(e.dataIds)?e.dataIds:[e.dataIds]),i?.forEach((i=>{this.store.bindDatas[i.dataId]||(this.store.bindDatas[i.dataId]=[]),this.store.bindDatas[i.dataId].push({id:t.id,formItem:e})}))}))}))}initBinds(){this.store.bind={},this.store.data.pens.forEach((t=>{t.realTimes?.forEach((e=>{e.bind&&e.bind.id&&(this.store.bind[e.bind.id]||(this.store.bind[e.bind.id]=[]),this.store.bind[e.bind.id].push({id:t.id,key:e.key}))}))}))}connectSocket(){this.connectWebsocket(),this.connectMqtt(),this.connectHttp()}doInitJS(){const t=this.store.data.initJs;if(t&&t.trim())try{new Function("context",t)({meta2d:this})}catch(t){console.warn("initJs error",t)}}drawLine(t){t&&hn(this.store),this.canvas.drawingLineName=t}alignPenToGrid(t){this.canvas.alignPenToGrid(t)}drawingPencil(){this.canvas.drawingPencil()}stopPencil(){this.canvas.stopPencil()}lock(t){this.store.data.locked=t,this.finishDrawLine(!0),this.canvas.drawingLineName="",this.stopPencil(),this.store.data.pens.forEach((t=>{!0===t.externElement&&t.calculative.singleton?.div&&pe(t,t.calculative.singleton.div)})),t>0&&this.initMessageEvents()}async finishDrawLine(t){await this.canvas.finishDrawline(t)}async finishPencil(){await this.canvas.finishPencil()}updateLineType(t,e){if(!t||"line"!=t.name||!e||!this.canvas[e])return;t.lineName=e;const i=re(t),n=se(t);i.prev=void 0,i.next=void 0,n.prev=void 0,n.next=void 0,t.calculative.worldAnchors=[i,n],t.calculative.activeAnchor=i,this.canvas[e](this.store,t,n),"curve"===t.lineName&&(i.prev={penId:i.penId,x:i.x-50,y:i.y},i.next={penId:i.penId,x:i.x+50,y:i.y},n.prev={penId:n.penId,x:n.x-50,y:n.y},n.next={penId:n.penId,x:n.x+50,y:n.y}),t.calculative.activeAnchor=void 0,this.canvas.initLineRect(t),this.render()}addDrawLineFn(t,e){this.canvas[t]=e,this.canvas.drawLineFns.push(t)}removeDrawLineFn(t){const e=this.canvas.drawLineFns.indexOf(t);e>-1&&this.canvas.drawLineFns.splice(e,1)}showMagnifier(){this.canvas.showMagnifier()}hideMagnifier(){this.canvas.hideMagnifier()}toggleMagnifier(){this.canvas.toggleMagnifier()}clear(t=!0,e){for(const t of this.store.data.pens)t.onDestroy?.(t);((t,e)=>{const i=t.data.template===e;if(i)for(const e of t.data.pens)e.canvasLayer===l.CanvasTemplate&&(t.templatePens[e.id]=e);t.lastScale=t.data.scale,t.data={x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{},template:i?e:null},t.sameTemplate=i,t.pens={},t.histories=[],t.historyIndex=null,t.path2dMap=new WeakMap,t.animateMap=new WeakMap,t.bindDatas={},t.bind={},t.pensNetwork={},t.active=[],t.hover=void 0,t.lastHover=void 0,t.animates.clear()})(this.store,e),this.hideInput(),this.canvas.tooltip.hide(),this.map&&this.map.isShow&&(this.map.show(),this.map.setView()),this.canvas.clearCanvas(),sessionStorage.removeItem("page"),this.store.clipboard=void 0,this.store.sameTemplate||(this.canvas.canvasTemplate.bgPatchFlags=!0),this.store.patchFlagsBackground=!0,this.store.patchFlagsTop=!0,this.setBackgroundImage(void 0),t&&this.render()}emit(t,e){this.store.emitter.emit(t,e)}on(t,e){return this.store.emitter.on(t,e),this}off(t,e){return this.store.emitter.off(t,e),this}registerMoveDock(t){this.canvas.customMoveDock=t}registerResizeDock(t){this.canvas.customResizeDock=t}find(t){return this.canvas.find(t)}findOne(t){return this.canvas.findOne(t)}getPenRect(t){return this.canvas.getPenRect(t)}setPenRect(t,e,i=!0){this.canvas.setPenRect(t,e,i)}startAnimate(t,e){let i;this.stopAnimate(t),i=t?"string"==typeof t?this.find(t):t:this.store.data.pens.filter((t=>(t.type||t.frames)&&t.autoPlay||t.animations&&t.animations.length&&-1!==t.animations.findIndex((t=>t.autoPlay)))),i.length&&(i.forEach((t=>{if(t.calculative.pause){const e=Date.now()-t.calculative.pause;t.calculative.pause=void 0,t.calculative.frameStart+=e,t.calculative.frameEnd+=e}else{let i=-1;if(void 0!==e&&t.animations){if("string"==typeof e){if(i=t.animations.findIndex((t=>t.name===e)),-1===i)return}else if("number"==typeof e){if(!(t.animations.length>e))return;i=e}}else void 0===e&&(i=t.animations?.findIndex((t=>t.autoPlay)),-1===i&&t.animations?.length&&(i=0));if(-1!==i&&void 0!==i){const e=Q(t.animations[i]);delete e.name,e.currentAnimation=i,!t.type&&e.frames&&(e.showDuration=this.calcAnimateDuration(e)),this.setValue({id:t.id,...e},{doEvent:!1,history:!1})}this.store.animates.add(t),t.type||this.store.animateMap.set(t,t.calculative.canvas.getFrameProps(t))}})),this.initImageCanvas(i),this.canvas.animate())}pauseAnimate(t){let e=[];t?e="string"==typeof t?this.find(t):t:this.store.animates.forEach((t=>{e.push(t)})),e.forEach((t=>{t.calculative.pause||(t.calculative.pause=Date.now())}))}stopAnimate(t){let e=[];t?e="string"==typeof t?this.find(t):t:this.store.animates.forEach((t=>{e.push(t)})),e.forEach((t=>{t.currentAnimation=void 0,t.calculative.pause=void 0,t.calculative.start=void 0,t.calculative.duration=void 0,t.calculative.animatePos=0,this.store.animates.delete(t),this.canvas.restoreNodeAnimate(t),this.canvas.updateLines(t),this.store.animateMap.delete(t)})),this.initImageCanvas(e),setTimeout((()=>{this.canvas?.calcActiveRect(),this.render()}),20)}startVideo(t){let e;e=t?"string"==typeof t?this.find(t):t:this.store.data.pens.filter((t=>(t.video||t.audio)&&t.autoPlay)),e.forEach((t=>{t.calculative.media?.play(),t.onStartVideo?.(t)}))}pauseVideo(t){let e=[];e=t?"string"==typeof t?this.find(t):t:this.store.data.pens.filter((t=>(t.video||t.audio)&&t.autoPlay)),e.forEach((t=>{t.calculative.media?.pause(),t.onPauseVideo?.(t)}))}stopVideo(t){let e=[];e=t?"string"==typeof t?this.find(t):t:this.store.data.pens.filter((t=>(t.video||t.audio)&&t.autoPlay)),e.forEach((t=>{t.calculative.media&&(t.calculative.media.currentTime=0,t.calculative.media.pause()),t.onStopVideo?.(t)}))}calcAnimateDuration(t){return t.frames.reduce(((t,e)=>t+e.duration),0)}combine(t=this.store.active,e){if(!t||!t.length)return;const i=Q(t);if(1===t.length&&t[0].type)return t[0].type=o.Node,this.canvas.active(t),this.pushHistory({type:V.Update,initPens:i,pens:Q(t,!0)}),void this.render();const n=We(t);let s={id:at(),name:"combine",...n,children:[],showChild:e};this.canvas.makePen(s);const a=Q(s);let l=1/0;return t.forEach((t=>{const e=this.store.data.pens.findIndex((e=>e.id===t.id));if(e{be(t,!0)})),this.initImageCanvas([s])),this.store.emitter.emit("combine",[s]),this.render(),s}uncombine(t){if(!t&&this.store.active&&(t=this.store.active[0]),!t||!t.children)return;const e=t.children.map((t=>this.store.pens[t]));let i=Q(e);e.forEach((t=>{t.parentId=void 0,t.x=t.calculative.worldRect.x,t.y=t.calculative.worldRect.y,t.width=t.calculative.worldRect.width,t.height=t.calculative.worldRect.height,t.locked=r.None,t.calculative.active=void 0,t.calculative.hover=!1,this.setVisible(t,!0)}));const n=this.isCombine(t)?3:2;this.pushHistory({type:V.Update,initPens:i,pens:e,step:n}),i=[Q(t)],t.children=void 0,this.pushHistory({type:V.Update,initPens:i,pens:[t],step:n}),this.isCombine(t)&&(this.delete([t]),this.store.histories[this.store.histories.length-1].step=n),this.inactive()}appendChild(t=this.store.active){if(!t)return;if(t.length<2)return;const e=t.findIndex((t=>"combine"===t.name&&void 0!==t.showChild));if(-1!==e){let i=t[e];this.pushChildren(i,[...t.slice(0,e),...t.slice(e+1)]),t.forEach((t=>{be(t,!0)})),this.initImageCanvas(t),this.render()}else console.warn("Invalid operation!")}isCombine(t){return"combine"===t.name||!!(t.children&&t.children.length>0)}active(t,e=!0){this.canvas.active(t,e)}inactive(){this.canvas.inactive()}activeAll(){this.canvas.active(this.store.data.pens.filter((t=>!t.parentId&&t.locked!==r.Disable))),this.render()}delete(t,e=!1,i=!0){this.canvas.delete(t,e,i)}scale(t,e={x:0,y:0}){this.canvas.scale(t,e)}translate(t,e){this.canvas.translate(t,e)}translatePens(t,e,i){this.canvas.translatePens(t,e,i)}getParent(t,e){return ht(t,e)}getAllChildren(t){return dt(t,this.store)}getAllFollowers(t){return ut(t,this.store)}data(){const t=Q(this.store.data),{pens:e,paths:i}=this.store.data;t.version=N,t.paths={};for(const n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.find((t=>t.pathId===n))&&(t.paths[n]=i[n]);return t.dataPoints=[...Object.keys(this.store.bind),...Object.keys(this.store.bindDatas)],t}copy(t){this.canvas.copy(t)}cut(t){this.canvas.cut(t)}paste(){this.canvas.paste()}undo(){this.canvas.undo()}redo(){this.canvas.redo()}listenSocket(){try{let t;const e=this.store.data.socketCbJs;if(e&&(t=new Function("e","context",e)),!t)return this.socketFn=null,!1;this.socketFn=t}catch(t){return console.error("Create the function for socket:",t),!1}return!0}connectWebsocket(t){this.closeWebsocket(),t&&(this.store.data.websocket=t),this.store.data.websocket&&(this.websocket=new WebSocket(this.store.data.websocket,this.store.data.websocketProtocols||void 0),this.websocket.onmessage=t=>{this.socketCallback(t.data,{type:"websocket",url:this.store.data.websocket})},this.websocket.onerror=t=>{this.store.emitter.emit("error",{type:"websocket",error:t})},this.websocket.onclose=()=>{if(this.store.options.reconnetTimes&&(this.websocketTimes++,this.websocketTimes>=this.store.options.reconnetTimes))return this.websocketTimes=0,void this.closeWebsocket();console.info("Canvas websocket closed and reconneting..."),this.connectWebsocket()})}closeWebsocket(){this.websocket&&(this.websocket.onclose=void 0,this.websocket.close(),this.websocket=void 0)}connectMqtt(t){if(this.closeMqtt(),t&&(this.store.data.mqtt=t.mqtt,this.store.data.mqttTopics=t.mqttTopics,this.store.data.mqttOptions=t.mqttOptions),this.store.data.mqtt){this.store.data.mqttOptions.clientId&&!this.store.data.mqttOptions.customClientId&&(this.store.data.mqttOptions.clientId=at());const t={...this.store.data.mqttOptions};t.username||delete t.username,t.password||delete t.password;const{username:e,password:i}=t;e&&i||!e&&!i?(this.mqttClient=lo.connect(this.store.data.mqtt,t),this.mqttClient.on("message",((t,e)=>{this.socketCallback(e.toString(),{topic:t,type:"mqtt",url:this.store.data.mqtt})})),this.mqttClient.on("error",(t=>{this.store.emitter.emit("error",{type:"mqtt",error:t})})),this.mqttClient.on("close",(()=>{this.store.options.reconnetTimes&&(this.mqttTimes++,this.mqttTimes>=this.store.options.reconnetTimes&&(this.mqttTimes=0,this.closeMqtt()))})),this.store.data.mqttTopics&&this.mqttClient.subscribe(this.store.data.mqttTopics.split(","))):console.warn("缺少用户名或密码")}}closeMqtt(){this.mqttClient?.end()}connectHttp(){this.closeHttp();const{https:t}=this.store.data;if(t)this.store.data.cancelFirstConnect||t.forEach((async t=>{this.oldRequestHttp(t)})),t.forEach(((t,e)=>{t.http&&(t.times=0,this.httpTimerList[e]=setInterval((async()=>{this.oldRequestHttp(t),this.store.options.reconnetTimes&&(t.times++,t.times>=this.store.options.reconnetTimes&&(t.times=0,clearInterval(this.httpTimerList[e]),this.httpTimerList[e]=void 0))}),t.httpTimeInterval||1e3))}));else{const{http:t,httpTimeInterval:e,httpHeaders:i}=this.store.data;t&&(this.httpTimer=setInterval((async()=>{const e=await fetch(t,{headers:i});if(e.ok){const i=await e.text();this.socketCallback(i,{type:"http",url:t})}}),e||1e3))}}async oldRequestHttp(t){let e=Q(t);if(e.http){const t=await fetch(e.http,{headers:e.httpHeaders,method:e.method||"GET",body:"POST"===e.method?JSON.stringify(e.body):void 0});if(t.ok){const i=await t.text();this.socketCallback(i,{type:"http",url:e.http})}else this.store.emitter.emit("error",{type:"http",error:t})}}async sendDatabyHttp(t){const{https:e}=this.store.data;if(e)e.forEach((async e=>{e.http&&(await fetch(e.http,{method:"post",body:t,headers:e.httpHeaders})).ok&&console.info("http消息发送成功")}));else{const{http:e,httpHeaders:i}=this.store.data;e&&(await fetch(e,{method:"post",body:t,headers:i})).ok&&console.info("http消息发送成功")}}closeHttp(){clearInterval(this.httpTimer),this.httpTimer=void 0,this.httpTimerList&&this.httpTimerList.forEach((t=>{clearInterval(t),t=void 0}))}connectNetwork(){this.closeNetwork();const{networks:t}=this.store.data,e=[];if(t){let i=0;this.mqttClients=[];let n=0;this.websockets=[],t.forEach((t=>{"subscribe"===t.type&&("mqtt"===t.protocol?(t.index=i,t.options.clientId&&!t.options.customClientId&&(t.options.clientId=at()),t.times=0,this.mqttClients[i]=lo.connect(t.url,t.options),this.mqttClients[i].on("message",((e,i)=>{this.socketCallback(i.toString(),{topic:e,type:"mqtt",url:t.url})})),this.mqttClients[i].on("error",(t=>{this.store.emitter.emit("error",{type:"mqtt",error:t})})),this.mqttClients[i].on("close",(()=>{this.store.options.reconnetTimes&&(t.times++,t.times>=this.store.options.reconnetTimes&&(t.times=0,this.mqttClients&&this.mqttClients[t.index]?.end()))})),t.topics&&this.mqttClients[i].subscribe(t.topics.split(",")),i+=1):"websocket"===t.protocol?(t.index=n,this.connectNetWebSocket(t),n+=1):"http"===t.protocol&&e.push({url:t.url,interval:t.interval,headers:t.headers||void 0,method:t.method,body:t.body}))}))}this.onNetworkConnect(e)}connectNetWebSocket(t){this.websockets[t.index]&&(this.websockets[t.index].onclose=void 0,this.websockets[t.index]?.close(),this.websockets[t.index]=void 0),this.websockets[t.index]=new WebSocket(t.url,t.protocols||void 0),this.websockets[t.index].onmessage=e=>{this.socketCallback(e.data,{type:"websocket",url:t.url})},this.websockets[t.index].onerror=t=>{this.store.emitter.emit("error",{type:"websocket",error:t})},this.websockets[t.index].onclose=()=>{if(this.store.options.reconnetTimes&&(t.times++,t.times>=this.store.options.reconnetTimes))return t.times=0,this.websockets[t.index].onclose=void 0,this.websockets[t.index]?.close(),void(this.websockets[t.index]=void 0);setTimeout((()=>{console.info("Canvas websocket closed and reconneting..."),this.connectNetWebSocket(t)}),2e3)}}randomString(t){t=t||32;let e="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",i=e.length,n="";for(let o=0;o{let i=this.mockValue(e);void 0!==i&&t.push({id:e.id,value:i})})),t.length&&this.setDatas(t,{render:!0,doEvent:!0,history:!1})}startDataMock(){this.store.data.enableMock&&(this.stopDataMock(),this.initBinds(),this.updateTimer=setInterval((()=>{this.store.data.pens.forEach((t=>{this.penMock(t)})),this.dataMock(),this.render()}),this.store.data.networkInterval||1e3))}stopDataMock(){clearInterval(this.updateTimer),this.updateTimer=void 0}penMock(t){if(t.realTimes){let e={};if(t.realTimes.forEach((t=>{let i=this.mockValue(t);void 0!==i&&(e[t.key]=i)})),Object.keys(e).length){let i=t.onBeforeValue?t.onBeforeValue(t,e):e;this.canvas.updateValue(t,i),t.onValue?.(t),this.store.emitter.emit("valueUpdate",t)}}}penNetwork(t){const e={url:t.apiUrl,method:t.apiMethod,headers:t.apiHeaders,body:t.apiBody};this.requestHttp(e),t.apiEnable?(this.store.pensNetwork||(this.store.pensNetwork={}),this.store.pensNetwork[t.id]=e):delete this.store.pensNetwork[t.id]}getDynamicParam(t){return co()[t]||localStorage[t]||function(t){let e;const i=new RegExp("(^| )"+t+"=([^;]*)(;|$)");return(e=document.cookie.match(i))?decodeURIComponent(e[2]):""}(t)||""}onNetworkConnect(t){if(t&&t.length){if(this.store.pensNetwork)for(let e in this.store.pensNetwork)t.push(this.store.pensNetwork[e]);this.store.data.cancelFirstConnect||t.forEach((async t=>{this.requestHttp(t)})),t.forEach(((t,e)=>{t.times=0,this.updateTimerList[e]=setInterval((async()=>{this.requestHttp(t),this.store.options.reconnetTimes&&(t.times++,t.times>=this.store.options.reconnetTimes&&(t.times=0,clearInterval(this.updateTimerList[e]),this.updateTimerList[e]=void 0))}),t.interval||1e3)}))}}async requestHttp(t){let e=Q(t);if(e.url){if("object"==typeof e.headers)for(let t in e.headers)if("string"==typeof e.headers[t]){let i=e.headers[t].match(/(?<=\$\{).*?(?=\})/g);i&&(e.headers[t]=e.headers[t].replace(`\${${i[0]}}`,this.getDynamicParam(i[0])))}if("object"==typeof e.body)for(let t in e.body)if("string"==typeof e.body[t]){let i=e.body[t].match(/(?<=\$\{).*?(?=\})/g);i&&(e.body[t]=e.body[t].replace(`\${${i[0]}}`,this.getDynamicParam(i[0])))}const t=await fetch(e.url,{headers:e.headers,method:e.method,body:"GET"===e.method?void 0:JSON.stringify(e.body)});if(t.ok){const i=await t.text();this.socketCallback(i,{type:"http",url:e.url})}else this.store.emitter.emit("error",{type:"http",error:t})}}closeNetwork(){this.mqttClients&&this.mqttClients.forEach((t=>{t.end()})),this.websockets&&this.websockets.forEach((t=>{t&&(t.onclose=void 0,t.close(),t=void 0)})),this.mqttClients=void 0,this.websockets=void 0,this.updateTimerList&&this.updateTimerList.forEach((t=>{clearInterval(t),t=void 0}))}socketCallback(t,e){this.store.emitter.emit("socket",{message:t,context:e});let i,n=t;if(!this.socketFn||(n=this.socketFn(t,{meta2d:this,type:e.type,topic:e.topic,url:e.url}),n)){if(!0===n&&(n=t),n.constructor===Object||n.constructor===Array)i=n;else{if("string"!=typeof n)return;try{i=JSON.parse(n)}catch(t){console.warn("Invalid socket data:",i,t)}}i&&(Array.isArray(i)||(i=[i]),i.length&&(i[0].dataId?this.setDatas(i):i.forEach((t=>{this.setValue(t)}))))}}setDatas(t,{render:e=!0,doEvent:i=!0,history:n}={}){const o=new Map;let r,s;t.forEach((e=>{this.store.bindDatas[e.dataId]?.forEach((i=>{const n=this.store.pens[i.id];if(!n)return;let r=o.get(n);if(n.noOnBinds||"function"!=typeof n.onBinds)r?r[i.formItem.key]=e.value:(r={id:i.id,[i.formItem.key]:e.value},o.set(n,r));else{if(r)return;o.set(n,n.onBinds(n,t,i.formItem))}})),this.store.bind[e.id]?.forEach((t=>{const i=this.store.pens[t.id];if(!i)return;let n=o.get(i);n?n[t.key]=e.value:(n={id:t.id,[t.key]:e.value},o.set(i,n))}))})),this.store.data.locked&&this.doDataEvent(t),n&&(r=[]),o.forEach(((t,e)=>{this.setValue(t,{render:!1,doEvent:i,history:!1}),n&&(r.push(Q(e,!0)),s.push(e))})),e&&this.render(),n&&this.pushHistory({type:V.Update,initPens:r,pens:s})}setValue(t,{render:e=!0,doEvent:i=!0,history:n}={}){let o,r=[];if(t){if(t.id){if(t.id===this.store.data.id)return this.setDatabyOptions(t),t.bkImage&&this.setBackgroundImage(t.bkImage),t.background&&this.setBackgroundColor(t.background),void this.render();const o=this.store.pens[t.id];if(o)r=[o];else{let o=this.store.bind[t.id];if(o&&o.length)return r=[],void this.setDatas([t],{render:e,doEvent:i,history:n})}}else{if(t.dataId)return r=[],void this.setDatas([t],{render:e,doEvent:i,history:n});if(!t.tag){let o=[];for(let e in t)o.push({dataId:e,id:e,value:t[e]});return void(o.length&&this.setDatas(o,{render:e,doEvent:i,history:n}))}r=this.find(t.tag)}if((n=n&&!this.store.data.locked)&&(o=Q(r)),r.forEach((e=>{const i=e.onBeforeValue?e.onBeforeValue(e,t):t;t.frames&&(this.stopAnimate([e]),t.showDuration||(t.showDuration=t.frames.reduce(((t,e)=>t+e.duration),0))),Re(e,i),this.canvas.updateValue(e,i),e.onValue?.(e)})),this.store.data.locked||!this.store.active.length||this.canvas.movingPens||this.canvas.calcActiveRect(),n){let t=Q(r);this.pushHistory({type:V.Update,initPens:o,pens:t})}i&&r.forEach((t=>{this.store.emitter.emit("valueUpdate",t)})),e&&this.render()}}_setValue(t,e=!1){this.setValue(t,{history:e,render:!1,doEvent:!1})}pushHistory(t){this.canvas.pushHistory(t)}showInput(t,e){this.canvas.showInput(t,e)}hideInput(){this.canvas.hideInput()}clearDropdownList(){this.canvas.clearDropdownList()}clearRuleLines(){this.canvas.clearRuleLines()}initGlobalTriggers(){this.store.globalTriggers={},this.store.data.triggers?.forEach((t=>{t.conditions.forEach((e=>{e.source&&(this.store.globalTriggers[e.source]||(this.store.globalTriggers[e.source]=[]),this.store.globalTriggers[e.source].includes(t)||this.store.globalTriggers[e.source].push(t))}))}))}initMessageEvents(){this.store.messageEvents={},this.store.data.pens.forEach((t=>{t.events?.forEach((e=>{"message"===e.name&&e.message&&(this.store.messageEvents[e.message]||(this.store.messageEvents[e.message]=[]),this.store.messageEvents[e.message].push({pen:t,event:e}))}))}))}dataJudegeCondition(t,e,i){const{type:n,target:o,fnJs:r,fn:s,operator:a,valueType:l}=i;let c=!1;if("fn"===n){if(s)c=s(t,{meta2d:this});else if(r){try{i.fn=new Function("data","context",r)}catch(t){console.error("Error: make function:",t)}i.fn&&(c=i.fn(t,{meta2d:this}))}}else{let n=i.value;"prop"===l&&(n=t[i.value]);let o=t[e];switch(a){case">":c=o>+n;break;case">=":c=o>=+n;break;case"<":c=o<+n;break;case"<=":c=o<=+n;break;case"=":case"==":c=o==n;break;case"!=":c=o!=n;break;case"[)":c=rt(+o,n);break;case"![)":c=!rt(+o,n);break;case"[]":c=st(o,n);break;case"![]":c=!st(o,n)}}return c}judgeCondition(t,e,i){const{type:n,target:o,fnJs:r,fn:s,operator:a,valueType:l}=i;let c=!1;if("fn"===n){if(s)c=s(t,{meta2d:this});else if(r){try{i.fn=new Function("pen","context",r)}catch(t){console.error("Error: make function:",t)}i.fn&&(c=i.fn(t,{meta2d:this}))}}else{let n=i.value;"prop"===l&&(n=this.store.pens[o][i.value]);let r=un(t,e);switch(["x","y","width","height"].includes(e)&&(r=this.getPenRect(t)[e]),a){case">":c=r>+n;break;case">=":c=r>=+n;break;case"<":c=r<+n;break;case"<=":c=r<=+n;break;case"=":case"==":c=r==n;break;case"!=":c=r!=n;break;case"[)":c=rt(+r,n);break;case"![)":c=!rt(+r,n);break;case"[]":c=st(r,n);break;case"![]":c=!st(r,n)}}return c}pushChildren(t,e){const i=[Q(t,!0)],n=[];t.children||(t.children=[]);const o=[];e.forEach((e=>{let s=Q(e,!0);if(e.id&&this.store.pens[e.id]||(this.canvas.makePen(e),s=null),e.parentId){const t=this.store.pens[e.parentId],n=t.children.findIndex((t=>t===e.id));i.push(Q(t,!0)),t.children.splice(n,1),o.push(Q(t,!0))}t.children.push(e.id),e.parentId=t.id;const a=Ge(e.calculative.worldRect,t.calculative.worldRect);Object.assign(e,a),e.locked=e.lockedOnCombine??r.DisableMove,s?(i.push(s),o.push(Q(e,!0))):n.push(Q(e,!0))})),o.push(Q(t,!0));let s=1;n.length&&(s=2,this.pushHistory({type:V.Add,pens:n,step:s})),this.pushHistory({type:V.Update,initPens:i,pens:o,step:s})}toPng(t,e,i=!1,n){return this.canvas.toPng(t,e,i,n)}activeToPng(t,e){return this.canvas.activeToPng(t,e)}pensToPng(t=this.store.active,e,i){return this.canvas.pensToPng(t,e,i)}downloadPng(t,e,i){for(const t of this.store.data.pens)(t.calculative.img||["iframe"].includes(t.name))&&t.onRenderPenRaw?.(t);setTimeout((()=>{const n=document.createElement("a");n.setAttribute("download",(t||this.store.data.name||"le5le.meta2d")+".png"),n.setAttribute("href",this.toPng(e,void 0,!0,i));const o=document.createEvent("MouseEvents");o.initEvent("click",!0,!0),n.dispatchEvent(o)}),1e3)}downloadSvg(){if(!window.C2S)throw console.error("请先加载乐吾乐官网下的canvas2svg.js","https://assets.le5lecdn.com/2d/canvas2svg.js"),new Error("请先加载乐吾乐官网下的canvas2svg.js");const t=this.getRect();t.x-=10,t.y-=10;const e=new window.C2S(t.width+20,t.height+20);e.textBaseline="middle";for(const i of this.store.data.pens)0!=i.visible&&xe(i,this.store)&&Ft(e,i,t,!0);let i=e.getSerializedSvg();this.store.data.background?(i=i.replace("{{bk}}",""),i=i.replace("{{bkRect}}",``)):(i=i.replace("{{bk}}",""),i=i.replace("{{bkRect}}","")),i=i.replace(/--le5le--/g,"&#x");const n=window.URL,o=new Blob([i]),r=n.createObjectURL(o),s=document.createElement("a");s.setAttribute("download",`${this.store.data.name||"le5le.meta2d"}.svg`),s.setAttribute("href",r);const a=document.createEvent("MouseEvents");a.initEvent("click",!0,!0),s.dispatchEvent(a)}getRect(t=this.store.data.pens){return We(t)}hiddenTemplate(){this.canvas.canvasTemplate.hidden()}showTemplate(){this.canvas.canvasTemplate.show()}lockTemplate(t){this.store.data.pens.forEach((e=>{e.canvasLayer===l.CanvasTemplate&&(e.locked=t)}))}fitView(t=!0,e=10){if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:n,offsetHeight:o}=i;this.resize(n,o);const r=lt(e),s=this.getRect(),a=(n-r[1]-r[3])/s.width,l=(o-r[0]-r[2])/s.height;let c=a;c=t?a>l?l:a:a>l?a:l,this.store.data.fits?.length&&(this.canvas.opening=!0),this.scale(c*this.store.data.scale),this.centerView(),this.store.data.fits?.length&&this.fillView()}fillView(){const t=this.getRect(),e=this.canvas.width-t.width,i=this.canvas.height-t.height;if(Math.abs(e)>10){this.store.data.fits?.forEach((i=>{let n=[];i.children.forEach((t=>{this.store.pens[t].locked=r.None,n.push(this.store.pens[t])}));let o=e/2;if(i.left&&i.right){let o=i.leftValue,r=i.rightValue;o=o?Math.abs(o)<1?o*this.canvas.width:o:0,r=r?Math.abs(r)<1?r*this.canvas.width:r:0;let s=(this.canvas.width-o-r)/(t.width-o-r);n.forEach((i=>{i.image&&i.imageRatio&&i.calculative.worldRect.width/this.canvas.width>.1&&(i.imageRatio=!1),i.calculative.worldRect.x=t.x-e/2+o+(i.calculative.worldRect.x-t.x)*s,i.calculative.worldRect.width*=s,i.calculative.worldRect.ex=i.calculative.worldRect.x+i.calculative.worldRect.width,i.calculative.width=i.calculative.worldRect.width,i.calculative.x=i.calculative.worldRect.x,i.width=i.calculative.worldRect.width,i.x=i.calculative.worldRect.x,this.canvas.updatePenRect(i,{worldRectIsReady:!1}),i.externElement&&i.onResize?.(i)}))}else i.left?(o=-o,i.leftValue&&(o+=Math.abs(i.leftValue)<1?i.leftValue*this.canvas.width:i.leftValue),this.translatePens(n,o,0)):i.right&&(i.rightValue&&(o-=Math.abs(i.rightValue)<1?i.rightValue*this.canvas.width:i.rightValue),this.translatePens(n,o,0))}));const i=this.store.data.pens.filter((t=>"iframe"===t.name));i?.forEach((i=>{const n=i.calculative.worldRect;if(n.width/this.store.data.scale>.8*t.width){let t=n.width;i.calculative.worldRect.x=n.x-e/2,i.calculative.worldRect.width=n.width+e,i.calculative.worldRect.ex=n.ex+e,i.operationalRect.x=i.operationalRect.x*t/i.calculative.worldRect.width,i.operationalRect.width=(i.calculative.worldRect.width-(1-i.operationalRect.width)*t)/i.calculative.worldRect.width,i.onBeforeValue?.(i,{operationalRect:i.operationalRect}),i.onResize?.(i)}}))}if(Math.abs(i)>10){this.store.data.fits?.forEach((e=>{let n=[];e.children.forEach((t=>{this.store.pens[t].locked=r.None,n.push(this.store.pens[t])}));let o=i/2;if(e.top&&e.bottom){let o=e.topValue,r=e.bottomValue;o=o?Math.abs(o)<1?o*this.canvas.height:o:0,r=r?Math.abs(r)<1?r*this.canvas.height:r:0;let s=(this.canvas.height-o-r)/(t.height-o-r);n.forEach((e=>{e.image&&e.imageRatio&&e.calculative.worldRect.height/this.canvas.height>.1&&(e.imageRatio=!1),e.calculative.worldRect.y=t.y-i/2+o+(e.calculative.worldRect.y-t.y)*s,e.calculative.worldRect.height*=s,e.calculative.worldRect.ey=e.calculative.worldRect.y+e.calculative.worldRect.height,e.calculative.height=e.calculative.worldRect.height,e.calculative.y=e.calculative.worldRect.y,e.height=e.calculative.worldRect.height,e.y=e.calculative.worldRect.y,this.canvas.updatePenRect(e,{worldRectIsReady:!1}),e.externElement&&e.onResize?.(e)}))}else e.top?(o=-o,e.topValue&&(o+=Math.abs(e.topValue)<1?e.topValue*this.canvas.height:e.topValue),this.translatePens(n,0,o)):e.bottom&&(e.bottomValue&&(o-=Math.abs(e.bottomValue)<1?e.bottomValue*this.canvas.height:e.bottomValue),this.translatePens(n,0,o))}));const e=this.store.data.pens.filter((t=>"iframe"===t.name));e?.forEach((e=>{const n=e.calculative.worldRect;if(n.height/this.store.data.scale>.8*t.height){let t=n.height;e.calculative.worldRect.y=n.y-i/2,e.calculative.worldRect.height=n.height+i,e.calculative.worldRect.ey=n.ey+i,e.operationalRect.y=e.operationalRect.y*t/e.calculative.worldRect.width,e.operationalRect.height=(e.calculative.worldRect.height-(1-e.operationalRect.height)*t)/e.calculative.worldRect.height,e.onBeforeValue?.(e,{operationalRect:e.operationalRect}),e.onResize?.(e)}}))}this.canvas.canvasTemplate.init(),this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.render(!0)}trimPens(){let t=this.store.data.pens.filter((t=>"line"===t.name&&t.anchors.length<2));this.delete(t)}fitTemplateView(t=!0,e=10){if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:n,offsetHeight:o}=i,r=lt(e),s=this.getRect(),a=(n-r[1]-r[3])/s.width,l=(o-r[0]-r[2])/s.height;let c=a;c=t?a>l?l:a:a>l?a:l,this.canvas.templateScale(c*this.store.data.scale);let h=this.getRect(),d=this.store.data.pens.filter((t=>!t.parentId));this.canvas.templateTranslatePens(d,-h.x,-h.y),this.store.data.pens.forEach((t=>{t.type?this.canvas.initLineRect(t):this.canvas.updateLines(t)})),this.centerView()}fitSizeView(t=!0,e=10){const{canvas:i}=this.canvas,{offsetWidth:n,offsetHeight:o}=i;this.resize(n,o);const r=lt(e),s=(this.store.data.width||this.store.options.width)*this.store.data.scale,a=(this.store.data.height||this.store.options.height)*this.store.data.scale,l=(n-r[1]-r[3])/s,c=(o-r[0]-r[2])/a;let h=l;h="width"===t?l:"height"===t?c:t?l>c?c:l:l>c?l:c,this.store.data.fits?.length&&(this.canvas.opening=!0),this.scale(h*this.store.data.scale),this.centerSizeView(),this.store.data.fits?.length&&this.fillView()}centerSizeView(){const t=this.getViewCenter(),e={x:0,y:0,width:this.store.data.width||this.store.options.width,height:this.store.data.height||this.store.options.height};ze(e);const{center:i}=e,{scale:n,origin:o,x:r,y:s}=this.store.data;this.translate((t.x-o.x)/n-i.x-r/n,(t.y-o.y)/n-i.y-s/n);const{canvas:a}=this.canvas,l=(a.scrollWidth-a.offsetWidth)/2,c=(a.scrollHeight-a.offsetHeight)/2;a.scrollTo(l,c)}scrollView(t=10,e=!1){if(!this.hasView())return;if(!this.canvas.scroll)return;const{canvas:i}=this.canvas,{offsetWidth:n,offsetHeight:o}=i;this.resize(n,o);const r=lt(t),s=this.getRect(),a=(n-r[1]-r[3])/s.width;this.scale(a*this.store.data.scale),this.topView(r[0]),e&&this.canvas.scroll.changeMode()}screenView(t=10,e=!0){if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:n,offsetHeight:o}=i;this.resize(n,o);const r=lt(t),s=this.getRect();let a=(n-r[1]-r[3])/s.width;e||(a=(o-r[0]-r[2])/s.height),this.scale(a*this.store.data.scale),this.topView(r[0])}topView(t=10){if(!this.hasView())return;const e=this.getRect(),i=this.getViewCenter(),n=this.getPenRect(e);ze(n);const{center:o}=n,{scale:r,origin:s,x:a,y:l}=this.store.data;this.translate((i.x-s.x)/r-o.x-a/r,(t-s.y)/r-n.y-l/r);const{canvas:c}=this.canvas,h=(c.scrollWidth-c.offsetWidth)/2,d=(c.scrollHeight-c.offsetHeight)/2;c.scrollTo(h,d)}centerView(){if(!this.hasView())return;const t=this.getRect(),e=this.getViewCenter(),i=this.getPenRect(t);ze(i);const{center:n}=i,{scale:o,origin:r,x:s,y:a}=this.store.data;this.translate((e.x-r.x)/o-n.x-s/o,(e.y-r.y)/o-n.y-a/o);const{canvas:l}=this.canvas,c=(l.scrollWidth-l.offsetWidth)/2,h=(l.scrollHeight-l.offsetHeight)/2;l.scrollTo(c,h)}hasView(){return!!this.store.data.pens.filter((t=>!t.isRuleLine)).length}getViewCenter(){const{width:t,height:e}=this.canvas;return{x:t/2,y:e/2}}beSameByFirst(t=this.store.data.pens,e){const i=Q(t),n=t[0],{width:o,height:r}=this.getPenRect(n);for(let i=1;i{n[t]=i[t]}));for(let e=1;e{n[t]=i[t]}));for(let e=0;e0){const i=t[0];g.forEach((t=>{e[t]=void 0!==i[t]?i[t]:this.store.options.defaultFormat[t]||this.store.options[t]}))}else{const t={};g.forEach((e=>{t[e]=this.store.options.defaultFormat[e]||this.store.options[e]||void 0}))}localStorage.setItem("meta2d-formatPainter",JSON.stringify(e))}formatPainter(){const t=this.store.active,e=Q(t),i=JSON.parse(localStorage.getItem("meta2d-formatPainter"));for(let e=0;e{for(let i=0;i!t.parentId))).length<=2)return;const n=Q(e),o=e.reduce(((e,i)=>e+this.getPenRect(i)[t]),0),r=(i-o)/(e.length-1);e=e.sort(((e,i)=>"width"===t?e.x-i.x:e.y-i.y));const s=this.getPenRect(e[0]);let a="width"===t?s.x:s.y;for(const i of e){const e=this.getPenRect(i);"width"===t?e.x=a:e.y=a,a+=e[t]+r,this.setValue({id:i.id,...e},{render:!1,doEvent:!1})}this.initImageCanvas(e),this.initTemplateCanvas(e),this.render(),this.pushHistory({type:V.Update,initPens:n,pens:e})}spaceBetween(t,e){this.spaceBetweenByDirection("width",t,e)}spaceBetweenColumn(t,e){this.spaceBetweenByDirection("height",t,e)}layout(t=this.store.data.pens,e,i=30){const n=this.getPenRect(We(t));!e&&(e=n.width);const o=Q(t=t.filter((t=>!t.type&&!t.parentId)));let r=0;t.forEach((t=>{const e=this.getPenRect(t);e.height>r&&(r=e.height)}));let s=n.x,a=n.y;t.forEach(((o,l)=>{const c=this.getPenRect(o);if(c.x=s,c.y=a+r/2-c.height/2,this.setValue({id:o.id,...c},{render:!1,doEvent:!1}),l===t.length-1)return;const h=s+c.width-n.x,d=this.getPenRect(t[l+1]);Math.round(e-h)>=Math.round(d.width+i)?s+=c.width+i:(s=n.x,a+=r+i)})),this.initImageCanvas(t),this.initTemplateCanvas(t),this.render(),this.pushHistory({type:V.Update,initPens:o,pens:t})}gotoView(t){const e=this.getViewCenter(),i=e.x-t.calculative.worldRect.x-t.calculative.worldRect.width/2,n=e.y-t.calculative.worldRect.y-t.calculative.worldRect.height/2;this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.translate(i-this.store.data.x,n-this.store.data.y),this.store.data.x=i,this.store.data.y=n;for(const t of this.store.data.pens)be(t);this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.render()}showMap(){this.map||(this.map=new so(this.canvas)),this.map.show()}hideMap(){this.map.hide()}onSizeUpdate(){this.mapTimer&&(clearTimeout(this.mapTimer),this.mapTimer=void 0),this.mapTimer=setTimeout((()=>{this.map&&this.map.isShow&&this.map.show(),this.canvas.scroll&&this.canvas.scroll.isShow&&this.canvas.scroll.resize()}),500)}toggleAnchorMode(){this.canvas.toggleAnchorMode()}addAnchorHand(){this.canvas.addAnchorHand()}removeAnchorHand(){this.canvas.removeAnchorHand()}toggleAnchorHand(){this.canvas.toggleAnchorHand()}top(t){t||(t=this.store.active),Array.isArray(t)||(t=[t]);for(const e of t){const t=this.store.data.pens,i=[...dt(e,this.store),e].map((t=>t.id));t.filter((t=>i.includes(t.id))).forEach((e=>{const i=t.findIndex((t=>t.id===e.id));i>-1&&(t.push(t[i]),t.splice(i,1),this.initTemplateCanvas([e]),this.initImageCanvas([e])),this.specificLayerMove(e,"top")}))}this.store.emitter.emit("layer",{type:"top",pens:t})}initImageCanvas(t){this.canvas.initImageCanvas(t)}initTemplateCanvas(t){this.canvas.initTemplateCanvas(t)}bottom(t){t||(t=this.store.active),Array.isArray(t)||(t=[t]);for(const e of t){const t=this.store.data.pens,i=[...dt(e,this.store),e].map((t=>t.id)),n=t.filter((t=>i.includes(t.id)));for(let e=n.length-1;e>=0;e--){const i=n[e],o=t.findIndex((t=>t.id===i.id));o>-1&&(t.unshift(t[o]),t.splice(o+1,1),this.initTemplateCanvas([i]),this.initImageCanvas([i])),this.specificLayerMove(i,"bottom")}}this.store.emitter.emit("layer",{type:"bottom",pens:t})}upByArea(t){if(-1===this.store.data.pens.findIndex((e=>e.id===t.id)))return void console.warn("upByArea: pen not in canvas");const e=[t,...dt(t,this.store)];let i=e.map((t=>this.store.data.pens.findIndex((e=>e.id===t.id))));i.includes(-1)&&(console.warn("upByArea: pen children not in canvas"),i=i.filter((t=>-1!==t)));const n=Math.min(...i),o=t.calculative.worldRect,r=this.store.data.pens.findIndex(((e,i)=>{if(i<=n)return!1;if(e.id===t.id||function(t,e){if(!t||!e)return!1;let i=ht(t);for(;i;){if(i.id===e.id)return!0;i=ht(i)}return!1}(e,t))return!1;const r=e.calculative.worldRect;return qe(o,r)}));if(-1!==r){this.store.data.pens.splice(r+1,0,...e);for(const t of e){const e=this.store.data.pens.findIndex((e=>e.id===t.id));e>-1&&this.store.data.pens.splice(e,1)}this.initImageCanvas([t])}else this.up(t)}specificLayerMove(t,e){if(t.image&&"gif"!==t.name){let i=l.CanvasImageBottom;"top"===e?i=l.CanvasImage:"up"!==e&&"down"!==e||(i=l.CanvasMain),this.setValue({id:t.id,canvasLayer:i},{render:!1,doEvent:!1,history:!1})}else if(t.externElement||"gif"===t.name){let i=0;"top"===e?(t.calculative.canvas.maxZindex+=1,i=t.calculative.canvas.maxZindex):"up"===e?i=void 0===t.calculative.zIndex?6:t.calculative.zIndex+1:"down"===e&&(i=void 0===t.calculative.zIndex?3:t.calculative.zIndex-1,i<0&&(i=0)),this.setValue({id:t.id,zIndex:i},{render:!1,doEvent:!1,history:!1}),t.calculative.singleton?.div&&pe(t,t.calculative.singleton.div)}}up(t){t||(t=this.store.active),Array.isArray(t)||(t=[t]);for(const e of t){const t=this.store.data.pens;if(e.children&&e.children.length){const i=[...dt(e,this.store),e],n=[];for(let e=0;et.id===o.id))&&(o.temIndex=e,n.push(o))}let o=-1,r=0;n.forEach((e=>{e.temIndex-=r,t.splice(e.temIndex,1),r+=1,o=e.temIndex,delete e.temIndex,this.specificLayerMove(e,"up")})),t.splice(o+1,0,...n),this.initTemplateCanvas(n),this.initImageCanvas(n)}else{const i=t.findIndex((t=>t.id===e.id));i>-1&&i!==t.length-1&&(t.splice(i+2,0,t[i]),t.splice(i,1),this.initTemplateCanvas([e]),this.initImageCanvas([e])),this.specificLayerMove(e,"up")}}this.store.emitter.emit("layer",{type:"up",pens:t})}down(t){t||(t=this.store.active),Array.isArray(t)||(t=[t]);for(const e of t){const t=this.store.data.pens;if(e.children&&e.children.length){const i=[...dt(e,this.store),e],n=[];for(let e=0;et.id===o.id))&&(o.temIndex=e,n.push(o))}let o=-1,r=0;n.forEach(((e,i)=>{e.temIndex-=r,t.splice(e.temIndex,1),r+=1,0===i&&(o=e.temIndex),delete e.temIndex,this.specificLayerMove(e,"down")})),t.splice(o-1,0,...n),this.initTemplateCanvas(n),this.initImageCanvas(n)}else{const i=t.findIndex((t=>t.id===e.id));i>-1&&0!==i&&(t.splice(i-1,0,t[i]),t.splice(i+1,1),this.initTemplateCanvas([e]),this.initImageCanvas([e])),this.specificLayerMove(e,"down")}}this.store.emitter.emit("layer",{type:"down",pens:t})}setLayer(t,e,i=this.store.data.pens){const n=i.findIndex((e=>e.id===t.id));n>-1&&(n>e?(i.splice(e,0,i[n]),i.splice(n+1,1)):n{const o=this.store.pens[n];if(o){if(!i.find((t=>t.id===o.id)))switch(e){case"all":i.push(o);break;case"in":se(o).connectTo===t.id&&i.push(o);break;case"out":re(o).connectTo===t.id&&i.push(o)}}else console.warn(t,"node contain a error connectedLine")})),i}nextNode(t){if(t.type===o.Line){const e=this.store.pens[se(t).connectTo];return e?[e]:[]}{const e=this.getLines(t,"out"),i=[];return e.forEach((t=>{const e=this.nextNode(t);for(const t of e)!i.find((e=>e.id===t.id))&&i.push(t)})),i}}previousNode(t){if(t.type===o.Line){const e=this.store.pens[re(t).connectTo];return e?[e]:[]}{const e=this.getLines(t,"in"),i=[];return e.forEach((t=>{const e=this.previousNode(t);for(const t of e)!i.find((e=>e.id===t.id))&&i.push(t)})),i}}getNext(t){if(t.type===o.Line)return void console.warn("非连线节点");const e=[];return t.connectedLines?.forEach((({lineId:i,anchor:n})=>{const o=t.anchors?.filter((t=>t.id===n))[0],r=this.findOne(i);if(r.anchors[0].connectTo==t.id){const i=r.anchors[r.anchors.length-1].connectTo;if(i){const n=this.findOne(i),s=n.connectedLines?.filter((t=>t.lineId===r.id))[0],a=n.anchors.filter((t=>t.id===s.anchor))[0];e.push({from:t,fromAnchor:o,line:r,to:n,toAnchor:a})}}})),e}addAnchor(t,e,i){if(!t)return;if(t.anchors||(t.anchors=[]),t.calculative.worldAnchors||(t.calculative.worldAnchors=[]),t.type===o.Line&&(i<0&&(i=t.anchors.length+1+i),i>t.anchors.length&&(i=t.anchors.length),i<0&&(i=0),0==i&&t.anchors[0].connectTo||i==t.anchors.length&&t.anchors[i-1].connectTo))return void console.warn("端点存在连接关系");let n=null,r=null;e.x<=1&&e.x>=0&&e.y<=1&&e.y>=0?(r={id:e.id||at(),penId:t.id,x:t.calculative.worldRect.x+t.calculative.worldRect.width*e.x,y:t.calculative.worldRect.y+t.calculative.worldRect.height*e.y},t.calculative.worldRect&&t.rotate%360&&P(r,t.rotate,t.calculative.worldRect.center),n={id:r.id,penId:t.id,x:e.x,y:e.y}):(r={id:e.id||at(),penId:t.id,x:e.x,y:e.y},t.calculative.worldRect&&(t.rotate%360&&P(e,-t.rotate,t.calculative.worldRect.center),n={id:r.id,penId:t.id,x:(e.x-t.calculative.worldRect.x)/t.calculative.worldRect.width,y:(e.y-t.calculative.worldRect.y)/t.calculative.worldRect.height})),t.type===o.Line?(t.calculative.worldAnchors.splice(i,0,r),t.anchors.splice(i,0,n),this.canvas.updateLines(t),this.canvas.initLineRect(t),this.render()):(t.calculative.worldAnchors.push(r),t.anchors.push(n))}connectLine(t,e,i,n,o=!0){if(!i){const n=e.calculative.worldRect;i=Zt(t,{x:n.x+n.width/2,y:n.y+n.height/2})}if(!n){const i=t.calculative.worldRect;n=Zt(e,{x:i.x+i.width/2,y:i.y+i.height/2})}const r=Math.abs(i.x-n.x),s={height:Math.abs(i.y-n.y),lineName:"line",lineWidth:1,name:"line",type:1,width:r,x:Math.min(i.x,n.x),y:Math.min(i.y,n.y),anchors:[{x:i.x>n.x?1:0,y:i.y>n.y?1:0,id:at()},{x:i.x>n.x?0:1,y:i.x>n.x?0:1,id:at()}]};return this.addPens([s]),ie(t,i,s,s.calculative.worldAnchors[0]),ie(e,n,s,s.calculative.worldAnchors[1]),s.calculative.active=!1,this.canvas.updateLines(s),this.canvas.updateLines(t),this.canvas.updateLines(e),this.canvas.initLineRect(s),o&&this.render(),s}toComponent(t=this.store.data.pens,e,i){if(1===t.length){const e=Q(t[0]);return e.type=o.Node,e.id=void 0,[e]}const n=Q(t,!0),s=We(n);let a={id:at(),name:"combine",...s,children:[],showChild:e};i&&(a.anchors=[{id:"0",penId:a.id,x:.5,y:0},{id:"1",penId:a.id,x:1,y:.5},{id:"2",penId:a.id,x:.5,y:1},{id:"3",penId:a.id,x:0,y:.5}]);const l=n.filter((t=>!t.parentId)),c=n.find((t=>t.width===s.width&&t.height===s.height)),h=c&&void 0===e;return 1===l.length?a=l[0]:h&&(c.children||(c.children=[]),a=c),n.forEach((t=>{if(t===a||t.parentId===a.id)return;if(t.parentId)return;a.children.push(t.id),t.parentId=a.id;const e=Ge(t.calculative.worldRect,s);Object.assign(t,e),t.locked=t.lockedOnCombine??r.DisableMove})),h||1===l.length?Q(n):Q([a,...n])}installPenPlugins(t,e){if(!t.tag&&!t.name&&!t.id)return;let i;t.id?i="id":t.tag?i="tag":t.name&&(i="name"),e.forEach((e=>{let n=e.plugin,o=e.options;if(n&&function(t){return!(!t.name&&!t.install&&(console.error("installPenPlugin Error: Validation Failed"),1))}(n)&&i)if(n.install(t,o),this.penPluginMap.has(n)){let e=this.penPluginMap.get(n).find((e=>e[i]===t[i]));e?e.option=o:this.penPluginMap.get(n).push({[i]:t[i],option:o})}else this.penPluginMap.set(n,[{[i]:t[i],option:o}])}))}uninstallPenPlugins(t,e){let i;t.id?i="id":t.tag?i="tag":t.name&&(i="name"),i&&e.forEach((e=>{let n=e.plugin;n.uninstall(t,e.options);let o=this.penPluginMap.get(n),r=o.findIndex((e=>e[i]===t[i]));-1!==r&&(o.splice(r,1),0===o.length&&this.penPluginMap.delete(n))}))}setVisible(t,e,i=!0){if(this.onSizeUpdate(),this.setValue({id:t.id,visible:e},{render:!1,doEvent:!1}),t.children)for(const i of t.children){const t=this.store.pens[i];t&&this.setVisible(t,e,!1)}let n=dt(t,this.store);n.push(t),this.initImageCanvas(n),i&&this.render()}clearHover(){this.canvas.clearHover()}closeSocket(){this.closeWebsocket(),this.closeMqtt(),this.closeHttp()}destroy(t){if(this.clear(!1),this.closeSocket(),this.closeNetwork(),this.store.emitter.all.clear(),this.canvas.destroy(),this.canvas=void 0,B[this.store.id]=void 0,!t){for(const t in B)delete B[t];B.path2dDraws={},B.canvasDraws={},B.anchors={},B.htmlElements={}}}}function uo(t,e){t.onDestroy||(t.onDestroy=po,t.onAdd=fo);const i=e||new Path2D,{x:n,y:o,width:r,height:s,ex:a}=t.calculative.worldRect;let l=t.calculative.borderRadius||0,c=l;l<1&&(l*=r,c*=s);let h=l{const i=e.data.pens.findIndex((e=>e.id===t));i>-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)})),t.children=void 0}function vo(t,e){t.onDestroy||(t.onDestroy=yo,t.onAdd=go);const i=e||new Path2D,{x:n,y:o,width:r,height:s,ex:a}=t.calculative.worldRect;let l=t.calculative.borderRadius||0,c=l;l<1&&(l*=r,c*=s);let h=l{const i=e.data.pens.findIndex((e=>e.id===t));i>-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)})),t.children=[]}function mo(){return{interfaceClass:uo,simpleClass:vo}}function wo(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;if(i.rect(n,o,r,s),i.closePath(),i instanceof Path2D)return i}function xo(t,e){const i=e.headHeight??50,{x:n,y:o,width:r,height:s,ey:a}=e.calculative.worldRect;let l=e.calculative.borderRadius||0,c=l;e.calculative.borderRadius<1&&(l*=r,c*=s);let h=l({id:n+"",x:e,y:i,penId:t.id})))}function Io(t,e){const i=e||new Path2D,{x:n,y:o,width:r,ex:s,ey:a}=t.calculative.worldRect,l=t.offsetX;let c=r/7;if(l>1?c=l:l>0&&(c=r*l),i.moveTo(n+c,o),i.lineTo(s,o),i.lineTo(n+r-c,a),i.lineTo(n,a),i.closePath(),i instanceof Path2D)return i}function _o(t){t.anchors=[{x:.5,y:0},{x:13/14,y:.5},{x:.5,y:1},{x:1/14,y:.5}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function Lo(t,e){const i=e||new Path2D,{x:n,y:o,height:r,ex:s,ey:a}=t.calculative.worldRect,l=r/7;if(i.moveTo(n,o+l),i.bezierCurveTo(n,o-l/2|0,s,o-l/2|0,s,o+l),i.lineTo(s,a-l),i.bezierCurveTo(s,a+l/2|0,n,a+l/2|0,n,a-l),i.closePath(),i.moveTo(n,a-l),i.bezierCurveTo(n,a-2*l|0,s,a-2*l|0,s,a-l),i instanceof Path2D)return i}function Mo(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s,ex:a,ey:l}=t.calculative.worldRect,c=r/8;if(i.moveTo(n+c,o),i.lineTo(a-c,o),i.bezierCurveTo(a+c/3,o,a+c/3,l,a-c,l),i.lineTo(n+c,l),i.lineTo(n,o+s/2),i.closePath(),i instanceof Path2D)return i}function Do(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s,ex:a,center:l}=t.calculative.worldRect,c=l.x,h=o+6*s/7,d=s/6;if(i.moveTo(n,o),i.lineTo(a,o),i.lineTo(a,h),i.bezierCurveTo(a-20,h-d,c+r/5,h-d,c,h),i.bezierCurveTo(c-r/5,h+d,n,h+d,n,h),i.closePath(),i instanceof Path2D)return i}function Oo(t){t.anchors=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:6/7},{x:0,y:.5}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function No(t,e){const i=e||new Path2D,{x:n,y:o,width:r,ex:s,ey:a}=t.calculative.worldRect,l=r/10;if(i.moveTo(n+2*l,o),i.bezierCurveTo(n-2*l/3,o,n-2*l/3,a,n+2*l,a),i.lineTo(s,a),i.bezierCurveTo(s-l,a,s-l,o,s,o),i.closePath(),i instanceof Path2D)return i}function Bo(t,e){const i=e||new Path2D,{x:n,y:o,width:r,ex:s,ey:a}=t.calculative.worldRect;i.moveTo(n,o),i.lineTo(s,o),i.lineTo(s,a),i.lineTo(n,a),i.closePath();const l=r/7;if(i.moveTo(n,o+l),i.lineTo(s,o+l),i.moveTo(n+l,o),i.lineTo(n+l,a),i instanceof Path2D)return i}function Fo(t,e){const i=e||new Path2D,{x:n,y:o,height:r,ex:s,ey:a}=t.calculative.worldRect,l=r/4;if(i.moveTo(n,o+l),i.lineTo(s,o),i.lineTo(s,a),i.lineTo(n,a),i.closePath(),i instanceof Path2D)return i}function zo(t){t.anchors=[{x:.5,y:.125},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function Ho(t,e){const i=e||new Path2D,{x:n,y:o,ex:r,ey:s}=t.calculative.worldRect;if(i.moveTo(n,o),i.lineTo(r,o),i.moveTo(n,s),i.lineTo(r,s),i instanceof Path2D)return i}function jo(t){t.anchors=[{x:.5,y:0},{x:.5,y:1}].map((({x:e,y:i},n)=>({id:n+"",x:e,y:i,penId:t.id})))}function Wo(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s,ex:a,ey:l}=t.calculative.worldRect;if(i.ellipse(n+r/2,o+s/2,r/2,s/2,0,0,2*Math.PI),i.moveTo(n+r/2,l),i.lineTo(a,l),i.closePath(),i instanceof Path2D)return i}function Uo(t,e){const i=e||new Path2D,{x:n,y:o,width:r,ex:s,ey:a}=t.calculative.worldRect,l=r/7;if(i.moveTo(n,o),i.lineTo(s,o),i.lineTo(s,a),i.lineTo(n,a),i.closePath(),i.moveTo(n+l,o),i.lineTo(n+l,a),i.moveTo(s-l,o),i.lineTo(s-l,a),i instanceof Path2D)return i}function Vo(){return{flowComment:Po,flowData:Io,flowDb:Lo,flowDisplay:Mo,flowDocument:Do,flowExternStorage:No,flowInternalStorage:Bo,flowManually:Fo,flowParallel:Ho,flowQueue:Wo,flowSubprocess:Uo}}function qo(){return{flowDocument:Oo,flowManually:zo,flowParallel:jo,flowComment:Eo,flowData:_o}}function Ko(t){const e=new Date,i=e.getFullYear(),n=e.getMonth()+1,o=e.getDate(),r=e.getDay(),s=e.getHours(),a=e.getMinutes(),l=e.getSeconds();return new Function("year","month","day","week","hours","minutes","seconds",t?`return ${t}`:"return `${year}:${month}:${day} ${hours}:${minutes}:${seconds} 星期${week}`")(i,n,o,["天","一","二","三","四","五","六"][r],s,a,l)}!function(t){t[t.Add=0]="Add",t[t.Replace=1]="Replace",t[t.ReplaceAll=2]="ReplaceAll"}(ao||(ao={}));let Yo=["fontSize","nameGap","margin","width","symbolSize","itemWidth","itemHeight","fontWeight","top","left","right","bottom","zoom","edgeSymbolSize","nodeWidth","nodeGap","distance","length","length2","offsetCenter","size","symbolOffset","padding","barWidth","symbolOffset","shadowOffsetY","shadowOffsetX"];function $o(t){let e=globalThis.echarts;if(!t.echarts||!e)return;if("string"==typeof t.echarts)try{t.echarts=JSON.parse(t.echarts)}catch(t){}Yo=t.calculative.canvas.store.options.diagramOptions.chart?.keyWords||Yo,t.onDestroy||(t.onDestroy=Xo,t.onMove=Go,t.onResize=Qo,t.onRotate=Go,t.onValue=Jo,t.onBeforeValue=Zo,t.onBinds=tr,t.onMouseEnter=Go,t.onRenderPenRaw=er),t.calculative.singleton||(t.calculative.singleton={});const i=new Path2D,n=t.calculative.worldRect;if(!t.calculative.singleton.div){const i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="-9999px",i.style.top="-9999px",i.style.width=n.width+"px",i.style.height=n.height+"px",document.body.appendChild(i),t.calculative.canvas.externalElements?.parentElement.appendChild(i),pe(t,i),t.calculative.singleton.div=i,t.calculative.singleton.echart=e.init(i,t.echarts.theme),t.calculative.singleton.echartsReady=!0,t.echarts.geoName&&!e.getMap(t.echarts.geoName)&&(t.echarts.geoJson?e.registerMap(t.echarts.geoName,t.echarts.geoJson):t.echarts.geoUrl&&(t.calculative.singleton.echartsReady=!1,fetch(t.echarts.geoUrl).then((i=>{i.text().then((i=>{if("string"==typeof i)try{i=JSON.parse(i)}catch{}i.constructor===Object||i.constructor===Array?(e.registerMap(t.echarts.geoName,i),t.calculative.singleton.echartsReady=!0,t.calculative.singleton.echart.setOption(ir(t.echarts.option,t.calculative.canvas.store.data.scale),!0),t.calculative.singleton.echart.resize(),setTimeout((()=>{er(t)}),300)):console.warn("Invalid data:",i)}))})))),t.calculative.singleton.echartsReady&&setTimeout((()=>{t.calculative.singleton.echart.setOption(ir(t.echarts.option,t.calculative.canvas.store.data.scale),!0),setTimeout((()=>er(t)),300)}))}return i}function Xo(t){if(t.calculative.singleton&&t.calculative.singleton.div){t.calculative.singleton.div.remove();let e=globalThis.echarts;e&&e.dispose(t.calculative.singleton.echart),delete t.calculative.singleton.div,delete t.calculative.singleton.echart}}function Go(t){t.calculative.singleton.div&&pe(t,t.calculative.singleton.div)}function Qo(t){if(!t.calculative.singleton.echart)return;let e=globalThis.echarts;pe(t,t.calculative.singleton.div),t.echarts.geoName&&!e.getMap(t.echarts.geoName)||(t.calculative.singleton.echart.setOption(ir(t.echarts.option,t.calculative.canvas.store.data.scale),!0),t.calculative.singleton.echart.resize())}function Jo(t){if(t.calculative.singleton.echart&&(pe(t,t.calculative.singleton.div),t.calculative.singleton.echartsReady))if(t.calculative.partialOption){const e=t.calculative.partialOption.echarts.option;t.calculative.singleton.echart.setOption(Q(e))}else t.calculative.singleton.echart.setOption(ir(t.echarts.option,t.calculative.canvas.store.data.scale),!0)}function Zo(t,e){if(t.calculative.partialOption=null,e.echarts){let i=globalThis.echarts;return e.echarts.geoName&&!i.getMap(e.echarts.geoName)&&(e.echarts.geoJson?i.registerMap(e.echarts.geoName,e.echarts.geoJson):e.echarts.geoUrl&&(t.calculative.singleton.echartsReady=!1,fetch(e.echarts.geoUrl).then((n=>{n.text().then((n=>{if("string"==typeof n)try{n=JSON.parse(n)}catch{}if(n.constructor===Object||n.constructor===Array)return i.registerMap(e.echarts.geoName,n),t.calculative.singleton.echartsReady=!0,t.onValue(t),!1;console.warn("Invalid data:",n)}))})))),e}if(t.realTimes&&t.realTimes.length){const{xAxis:i,yAxis:n}=t.echarts.option,{max:o,replaceMode:r,timeFormat:s}=t.echarts;let a=[];for(let n in e)if(n.includes("echarts.option")){let l=un(t,n);if(Array.isArray(l)&&r===ao.Add){l.push(e[n]),o&&l.splice(0,l.length-o),e[n]=l;let r="echarts.option.xAxis.data";Array.isArray(i)&&i.length&&(r="echarts.option.xAxis.0.data");let a=un(t,r),c=Ko(s||"`${hours}:${minutes}:${seconds}`");a.push(c),o&&a.splice(0,a.length-o),e[r]=a}if(n.includes(".data.")){let t=n.substring(0,n.indexOf(".data.")+5);a.includes(t)||a.push(t)}}const l=Q(e);return t.calculative.partialOption=function(t){const e={};return Object.keys(t).forEach((i=>{const n=i.split(".");let o=e;n.forEach(((e,r)=>{const s=!isNaN(parseInt(e));if(r===n.length-1)s?(Array.isArray(o)||(o=[]),o[parseInt(e)]=t[i]):o[e]=t[i];else if(s){const t=parseInt(e);if(Array.isArray(o)||o[n[r-1]],o[t]||(o[t]={}),Array.isArray(o))for(let t=0;t{let i=un(t,e);fn(t.calculative.partialOption,e,i)})),e}if(!e.dataX&&!e.dataY)return e;const i=t.echarts,{max:n,replaceMode:o}=i;let r=e.dataX,s=e.dataY,a=[];s&&a.push("echarts.option.series");const l=i.option.series,c=l.length,{xAxis:h,yAxis:d}=i.option;Array.isArray(h)&&h.length>1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");const u=Array.isArray(h)?h[0]:h,f=Array.isArray(d)?d[0]:d;if(o)if(o===ao.Replace)if(u||f){if(("category"===u.type||"category"===f.type)&&r&&s){const t="category"===u.type?u.data:f.data;!Array.isArray(r)&&(r=[r]),!Array.isArray(s)&&(s=[s]),"category"===u.type?a.push("echarts.option.xAxis"):a.push("echarts.option.yAxis"),1===c?s.forEach(((e,i)=>{const n=t.indexOf(r[i]);l[0].data[n]=e})):l.forEach(((e,i)=>{s[i].forEach(((i,n)=>{const o=t.indexOf(r[n]);e.data[o]=i}))}))}}else s&&(1===c?(!Array.isArray(s)&&(s=[s]),s.forEach(((t,e)=>{const i=l[0].data.find((e=>e.name===t.name));i&&(i.value=t.value)}))):l.forEach(((t,e)=>{Array.isArray(s[e])||(s[e]=[s[e]]),s[e].forEach(((e,i)=>{const n=t.data.find((t=>t.name===e.name));n&&(n.value=e.value)}))})));else o===ao.ReplaceAll&&(r&&(u.data=r,u.data.splice(0,u.data.length-n),a.push("echarts.option.xAxis")),s&&(1===c?(l[0].data=s,l[0].data.splice(0,l[0].data.length-n)):l.forEach(((t,e)=>{t.data=s[e],t.data.splice(0,t.data.length-n)}))));else{if(r){!Array.isArray(r)&&(r=[r]);const t=u.data;t.push(...r),t.splice(0,t.length-n),a.push("echarts.option.xAxis")}if(s)if(1===c){!Array.isArray(s)&&(s=[s]);const t=l[0].data;t.push(...s),t.splice(0,t.length-n)}else l.forEach(((t,e)=>{Array.isArray(s[e])||(s[e]=[s[e]]);const i=t.data;i.push(...s[e]),i.splice(0,i.length-n)}))}return t.calculative.partialOption={},a.forEach((e=>{let i=un(t,e);fn(t.calculative.partialOption,e,i)})),delete e.dataX,delete e.dataY,Object.assign(e,{echarts:i})}function tr(t,e,i){if("dataY"!==i.key)return;const n=t.echarts,{xAxis:o,yAxis:r}=n.option;Array.isArray(o)&&o.length>1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");const s=Array.isArray(o)?o[0]:o,a=Array.isArray(r)?r[0]:r,l=n.option.series;if(s||a){if("category"===s.type||"category"===a.type){const n=[],o=[],r="category"===s.type?s.data:a.data;return r?.forEach((t=>{const{dataId:r}=i.dataIds.find((e=>e.name===t));if(r){const i=e.find((t=>t.dataId===r));i&&(o.push(t),n.push(i.value))}})),{id:t.id,dataY:n,dataX:o}}if("time"===s.type){const n=[],o=+new Date;let r=!1;if(l.forEach(((t,s)=>{const a=[],{dataId:l}=i.dataIds.find((e=>e.name===t.name));if(l){const t=e.find((t=>t.dataId===l));t&&(a.push([o,t.value]),r=!0)}n[s]=a})),!r)return;return n.forEach(((t,e)=>{if(!t||0===t.length){const t=l[e].data[l[e].data.length-1];n[e]=[[o,t[1]]]}})),{id:t.id,dataY:1===n.length?n[0]:n}}}else{const n=[];if(Array.isArray(l)&&1===l.length)return l[0].data.forEach((t=>{const{dataId:o}=i.dataIds.find((e=>e.name===t.name));if(o){const i=e.find((t=>t.dataId===o));i&&n.push({name:t.name,value:i.value})}})),{id:t.id,dataY:n}}}function er(t){const e=new Image;e.src=t.calculative.singleton?.echart?.getDataURL({pixelRatio:2}),t.calculative.img=e}function ir(t,e){const i=Q(t);if(i.dataZoom){let t=["right","top","width","height","left","bottom"];for(let n=0;n{isNaN(i[t[n]])||(i[t[n]]*=e)}))}return J(i,Yo,e),i}function nr(t){const e=globalThis.Highcharts;if(!e)return;if("string"==typeof t.highcharts)try{t.highcharts=JSON.parse(t.highcharts.option)}catch(t){}if(!t.highcharts)return;t.onDestroy||(t.onDestroy=or,t.onMove=rr,t.onResize=sr,t.onRotate=rr,t.onValue=ar,t.onBeforeValue=lr,t.onRenderPenRaw=cr),t.calculative.singleton||(t.calculative.singleton={});const i=new Path2D,n=t.calculative.worldRect;if(!t.calculative.singleton.div){const i=document.createElement("div");i.style.position="absolute",i.style.outline="none",i.style.left="-9999px",i.style.top="-9999px",i.style.width=n.width+"px",i.style.height=n.height+"px",i.style.minWidth="100px",i.style.minHeight="100px",i.id=t.id,document.body.appendChild(i),t.calculative.singleton.div=i,setTimeout((()=>{t.calculative.singleton.highchart=e.chart(t.id,t.highcharts.option);const i=t.calculative.singleton.highchart.getSVG(),n=new Image;n.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(i))),t.calculative.img=n})),t.calculative.canvas.externalElements?.parentElement.appendChild(i),pe(t,i)}return t.calculative.patchFlags&&t.calculative.singleton.div&&pe(t,t.calculative.singleton.div),i}function or(t){t.calculative.singleton&&t.calculative.singleton.div&&(t.calculative.singleton.div.remove(),t.calculative.singleton.highchart.destroy(),delete t.calculative.singleton.div,delete t.calculative.singleton.highchart)}function rr(t){t.calculative.singleton.div&&pe(t,t.calculative.singleton.div)}function sr(t){t.calculative.singleton.div&&(pe(t,t.calculative.singleton.div),setTimeout((()=>{t.calculative.singleton.highchart.reflow()}),100))}function ar(t){t.calculative.singleton.div&&pe(t,t.calculative.singleton.div)}function lr(t,e){if(e.highcharts)return t.calculative.singleton.highchart.update(e.highcharts.option),e;if(!e.dataX&&!e.dataY)return e;const i=t.highcharts,n=i.max;let o=e.dataX,r=e.dataY;const s=i.option.series.length;if(e.overwrite)o&&(i.option.xAxis.categories=o,i.option.xAxis.categories.splice(0,i.option.xAxis.categories.length-n)),r&&(1===s?(i.option.series[0].data=r,i.option.series[0].data.splice(0,i.option.series[0].data.length-n)):i.option.series.forEach(((t,e)=>{t.data=r[e],t.data.splice(0,t.data.length-n)}))),t.calculative.singleton.highchart.update(i.option);else{let e=[],a=null,l=!1;if(o){Array.isArray(o)||(o=[o]);const t=i.option.xAxis,r=Array.isArray(t)?t[0].categories:t.categories;r&&(r.push(...o),r.splice(0,r.length-n),l=!0),e=[...o]}r&&(1===s?(Array.isArray(r)||(r=[r]),a=[r]):(a=[],i.option.series.forEach(((t,e)=>{Array.isArray(r[e])||(r[e]=[r[e]]),a.push(r[e])})))),a&&t.calculative.singleton.highchart.series.forEach(((t,i)=>{a[i].forEach(((i,o)=>{let r=!1;n&&t.data.length>=n&&(r=!0);const s=l||null==e[o]?i:[e[o],i];t.addPoint(s,!0,r)}))}))}return delete e.dataX,delete e.dataY,delete e.overwrite,Object.assign(e,{highcharts:i})}function cr(t){if(!t.calculative?.singleton)return;const e=t.calculative.singleton.highchart.getSVG(),i=new Image;i.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(e))),t.calculative.img=i}function hr(t){let e=globalThis.lcjs;if(!t.lightningCharts||!e)return;if("string"==typeof t.lightningCharts)try{t.lightningCharts=JSON.parse(t.lightningCharts)}catch(t){}if(!t.lightningCharts)return;t.onDestroy||(t.onDestroy=ur,t.onMove=fr,t.onResize=pr,t.onRotate=fr,t.onValue=vr,t.onRenderPenRaw=gr);const i=new Path2D,n=t.calculative.worldRect;if(t.calculative.singleton||(t.calculative.singleton={}),!t.calculative.singleton.div){const e=document.createElement("div");e.style.position="absolute",e.style.outline="none",e.style.left="-9999px",e.style.top="-9999px",e.style.width=n.width+"px",e.style.height=n.height+"px",e.id=t.id,document.body.appendChild(e),t.calculative.singleton.div=e,setTimeout((()=>{dr(t)}),100),setTimeout((()=>{t.calculative.canvas.externalElements&&t.calculative.canvas.externalElements.parentElement.appendChild(e),pe(t,e);const i=new Image;i.src=t.calculative.singleton.div.children[0].toDataURL(),t.calculative.img=i}),400)}return t.calculative.patchFlags&&t.calculative.singleton.div&&pe(t,t.calculative.singleton.div),i}function dr(t){const{lightningChart:e,PieChartTypes:i,LegendBoxBuilders:n,SliceLabelFormatters:o,Themes:r,GaugeChartTypes:s,SolidLine:a,SolidFill:l,ColorRGBA:c,UIOrigins:h,emptyLine:d,AutoCursorModes:u,AxisScrollStrategies:f,AxisTickStrategies:p,UIElementBuilders:v}=lcjs,g=t.lightningCharts.option.data,y=t.lightningCharts.option.title||"Title",m=r[t.lightningCharts.option.theme||"lightNew"];switch(t.calculative.singleton.lightningChart=e(),t.lightningCharts.option.type){case"line":const e=t.calculative.singleton.lightningChart.ChartXY({container:t.id}).setTitle(y);g.forEach((t=>{e.addLineSeries().setName(t.name).add(t.data)}));break;case"bar":const i=t.calculative.singleton.lightningChart;let r;r=e=>{const o=[],r=[],s=i.ChartXY(e).setTitle(y).setAutoCursorMode(u.onHover).setMouseInteractions(!1).setPadding({bottom:30}),a=s.getDefaultAxisX().setMouseInteractions(!1).setScrollStrategy(void 0).setTickStrategy(p.Empty);s.getDefaultAxisY().setMouseInteractions(!1).setTitle(t.lightningCharts.option.yTitle).setInterval(0,70).setScrollStrategy(f.fitting),s.setAutoCursor((t=>t.disposePointMarker().disposeTickMarkerX().disposeTickMarkerY().setGridStrokeXStyle(d).setGridStrokeYStyle(d).setResultTable((t=>{t.setOrigin(h.CenterBottom)}))));const l=s.addLegendBox(n.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.2});return{addCategory:t=>{const e=(t=>{const e=s.addRectangleSeries();return e.setCursorResultTableFormatter(((e,i,n)=>{let o={name:t.name,value:t.data[t.figures.indexOf(n)]};return e.addRow("Department:",o.name).addRow("# of employees:",String(o.value))})),e})(t).setName(t.name);t.figures=t.data.map((t=>e.add({x:0,y:0,width:0,height:0}))),l.add(e),r.push(t),(()=>{let t=0;for(let e=0;e{for(const e of t)o.push({name:e,tick:a.addCustomTick(v.AxisTick).setGridStrokeLength(0).setTextFormatter((t=>e))})}}};const s=r({theme:m,container:t.id});s.addGroups(t.lightningCharts.option.groups);const a=t.lightningCharts.option.categories;g.forEach(((t,e)=>s.addCategory({name:a[e],data:t})));break;case"pie":const w=t.calculative.singleton.lightningChart.Pie({theme:m,container:t.id}).setTitle(y).setAnimationsEnabled(!0).setMultipleSliceExplosion(!0);g.map((t=>w.addSlice(t.name,t.value))),w.setInnerRadius(t.lightningCharts.option.innerRadius||0).setLabelFormatter(o.NamePlusRelativeValue),w.addLegendBox(n.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.3}).add(w);break;case"gauge":const x=t.calculative.singleton.lightningChart.Gauge({theme:m,container:t.id}).setTitle(y).setThickness(20).setAngleInterval(t.lightningCharts.option.startAngle||225,t.lightningCharts.option.endAngle||-45);let b=function(t){let e=t.toLowerCase();if(e&&/^#([0-9|a-f]{3}|[0-9|a-f]{6})$/.test(e)){4==e.length&&(e="#"+e[1]+e[1]+e[2]+e[2]+e[3]+e[3]);for(var i=[],n=1;n<7;n+=2)i.push(parseInt("0x"+e.slice(n,n+2)));return i}return e&&/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/.test(e)?e.match(/\(([^)]*)\)/)[1].split(",").map((t=>parseInt(t))):e}(t.lightningCharts.option.background);x.getDefaultSlice().setInterval(t.lightningCharts.option.min||0,t.lightningCharts.option.max||100).setValue(g).setFillStyle(new l({color:c(b[0],b[1],b[2])}))}}function ur(t){t.calculative.singleton&&t.calculative.singleton.div&&(t.calculative.singleton.div.remove(),delete t.calculative.singleton.div,delete t.calculative.singleton.lightningChart)}function fr(t){t.calculative.singleton.div&&pe(t,t.calculative.singleton.div)}function pr(t){t.calculative.singleton.div&&pe(t,t.calculative.singleton.div)}function vr(t){t.calculative.singleton.div&&(dr(t),pe(t,t.calculative.singleton.div))}function gr(t){if(!t.calculative?.singleton)return;const e=new Image;e.src=t.calculative.singleton.div.children[0].toDataURL(),t.calculative.img=e}function yr(t){t&&(globalThis.echarts=t),F({echarts:$o})}function mr(t){t&&(globalThis.Highcharts=t),F({highcharts:nr})}function wr(t){t&&(globalThis.lcjs=t),F({lightningCharts:hr})}var xr;function br(t,e){const i=14*e.calculative.worldRect.height/16,n=(t.match(/[\u4e00-\u9fa5]/g)||"").length;return(t.length-n)*i*.6+n*i}function kr(t){if("horizontal"==t.direction){const e=[];let i=0;const n=t.height;t.checkboxHeight=n,t.options.forEach(((o,r)=>{e.push(r*(40+n)+i),i+=br(o.text,t)})),t.optionPos=e;const o=e.length*(40+n)+i;t.checkboxWidth=o,t.width=o,t.calculative.width=o,t.calculative.worldRect={x:t.x,y:t.y,height:t.height,width:t.width,center:{x:t.x+t.width/2,y:t.y+t.height/2}},He(t.calculative.worldRect)}else if("vertical"==t.direction){null==t.optionInterval&&(t.optionInterval=20),t.optionHeight||(t.optionHeight=20);const e=[];t.options.forEach(((i,n)=>{e.push(n*(t.optionInterval+t.optionHeight))})),t.optionPos=e;const i=e[e.length-1]+t.optionHeight;t.checkboxHeight=i,t.width||(t.height=i,t.calculative.height=i,t.calculative.worldRect={x:t.x,y:t.y,height:t.height,width:t.width,center:{x:t.x+t.width/2,y:t.y+t.height/2}},He(t.calculative.worldRect))}}function Tr(t,e){e.onAdd||(e.onAdd=Ar,e.rowPos&&e.colPos&&e.calculative.maxOffsetY||e.onAdd(e),e.onMouseMove=Sr,e.onMouseLeave=Pr,e.onMouseDown=Er,e.onShowInput=Cr,e.onInput=Rr,e.onValue=Nr,e.onBeforeValue=Br,e.onMouseEnter=Ur,e.onWheel=Fr,e.onDestroy=Hr),e.data.length!==e.rowPos.length&&(e.initWorldRect=null,e.calculative.isUpdateData=!0,e.onValue(e)),e.data[0].length!==e.colPos.length&&(e.initWorldRect=null,e.calculative.isUpdateData=!0,e.onValue(e));const i=e.calculative.canvas.store.data,n=e.calculative.canvas.store.options;if(e.color=e.color||i.color||n.color,e.textColor=e.textColor||e.color||i.textColor||n.textColor,e.activeColor=e.activeColor||n.activeColor,e.hoverColor=e.hoverColor||n.hoverColor,e.activeBackground=e.activeBackground||n.activeBackground,e.hoverBackground=e.hoverBackground||n.hoverBackground,!e.hasHeader){t.save(),t.beginPath();const{x:i,y:n,width:o,height:r}=e.calculative.worldRect;t.fillStyle="#fff0",t.rect(i-1,n-1,o+2,r+2),t.fill(),t.clip()}!function(t,e){if(!e.colPos)return;const{x:i,y:n,width:o,height:r,ex:s,ey:a}=e.calculative.worldRect;t.save(),t.beginPath(),t.strokeStyle=e.color;let l=e.calculative.borderRadius||0,c=l;l<1&&(l*=o,c*=r);let h=le.calculative.worldRect.height)continue}else if(o<0||o>e.calculative.worldRect.height)continue;t.beginPath(),t.moveTo(e.calculative.worldRect.x,e.calculative.worldRect.y+o),t.lineTo(e.calculative.worldRect.ex,e.calculative.worldRect.y+o),t.strokeStyle=e.borderColor||"#424B61",t.stroke()}}if(!1!==e.vLine){let i=e.colPos[e.colPos.length-1];e.colPos.forEach(((n,o)=>{if(n===i)return;const r=n*e.calculative.worldRect.width/e.tableWidth;t.beginPath(),t.moveTo(e.calculative.worldRect.x+r,e.calculative.worldRect.y),t.lineTo(e.calculative.worldRect.x+r,e.calculative.worldRect.ey),t.strokeStyle=e.borderColor||"#424B61",t.stroke()}))}t.restore()}(t,e),function(t,e){if(!e.colPos)return;e.calculative.texts||(e.calculative.texts=[]);for(let i=0;i0){let t=0;s.forEach(((e,i)=>{e.wheres&&e.wheres.every((t=>new Function("attr",`return attr ${t.comparison} ${t.value}`)(r)))&&(t=i)})),s=s[t]}else s.wheres&&Array.isArray(s.wheres)&&(a=!1,a=s.wheres.every((function(t){return new Function("attr",`return attr ${t.comparison} ${t.value}`)(r)})));let l,c=e.color,h=e.textColor||e.color,d=null,u=null,f=null,p=null;a&&(c=s.color||n.color||e.color,h=s.textColor||n.textColor||e.textColor,d=s.background||n.background,u=(s.fontSize||n.fontSize||0)*e.calculative.canvas.store.data.scale,f=s.fontWeight||n.fontWeight,p=s.fontStyle||n.fontStyle),e.stripe&&(!1!==e.hasHeader?i%2==1&&(d=d||e.stripeColor||"#407FFF1F"):i%2==0&&(d=d||e.stripeColor||"#407FFF1F")),e.calculative.active&&e.calculative.activeCell?.row===i&&e.calculative.activeCell?.col===o&&(c=e.activeColor,d=e.activeBackground,l=c,h=e.activeTextColor||e.activeColor),e.calculative.hover&&e.calculative.hoverCell?.row===i&&e.calculative.hoverCell?.col===o&&(c=e.hoverColor,d=e.hoverBackground,h=e.hoverTextColor||e.hoverColor,l=c);const v=Dr(e,i,o);if(v.y+v.heighte.calculative.worldRect.height+e.calculative.worldRect.y)continue;d&&(t.save(),t.beginPath(),t.fillStyle=d,t.fillRect(v.x,v.y,v.width+.25*e.calculative.canvas.store.data.scale,v.height),t.restore()),l&&(t.save(),t.beginPath(),t.strokeStyle=l,t.strokeRect(v.x,v.y,v.width,v.height),t.restore()),e.calculative.worldTextRect=v;let g=e.calculative.texts[i];if(e.calculative.texts[i]||(g=[],e.calculative.texts.push(g)),null==g[o]){if("object"==typeof r){const t=e.styles&&e.styles.filter((t=>t.col===o&&void 0===t.row&&t.pens));if(t.length>0){if(g[o]="",e.isFirstTime){e.maxNum&&e.hasHeader&&i>=e.maxNum&&(r.visible=!1);let n=JSON.parse(JSON.stringify(t[0].pens));n.forEach((t=>{Object.assign(t,{row:i,col:o},r),t.activeBackground=t.background,t.hoverBackground=t.background,t.activeColor=t.color,t.hoverColor=t.color,t.activeTextColor=t.textColor,t.hoverTextColor=t.textColor,t.height*=e.calculative.canvas.store.data.scale,t.width*=e.calculative.canvas.store.data.scale})),Or(e,v,n),e.calculative.canvas.parent.pushChildren(e,n)}continue}}else g[o]=void 0===r?"":r.text||r+"";if(!g[o])continue;g[o]=Y(e,g[o])}if(!g[o])continue;t.save(),t.beginPath(),t.fillStyle=h,t.textAlign="center",t.textBaseline="middle",t.font=(p||e.calculative.fontStyle||"")+" normal "+(f||e.calculative.fontWeight||"")+" "+1*(u||e.calculative.fontSize||12)+"px "+e.calculative.fontFamily;let y=e.colStyle&&e.colStyle[o]?.textAlign;if(y&&(t.textAlign=y),1===g[o].length)"left"===y?t.fillText(g[o][0],v.x,v.y+v.height/2):"right"===y?t.fillText(g[o][0],v.x+v.width,v.y+v.height/2):t.fillText(g[o][0],v.x+v.width/2,v.y+v.height/2);else{const i=.55,n=(u||e.calculative.fontSize)*e.calculative.lineHeight*1,r=g[o].length*n;let s=(v.height-r)/2;"left"===y?g[o].forEach(((e,o)=>{t.fillText(e,v.x,v.y+s+(o+i)*n)})):"right"===y?g[o].forEach(((e,o)=>{t.fillText(e,v.x+v.width,v.y+s+(o+i)*n)})):g[o].forEach(((e,o)=>{t.fillText(e,v.x+v.width/2,v.y+s+(o+i)*n)}))}t.restore()}}}(t,e),function(t,e){if(!e.calculative.hover)return;if(!e.calculative.hoverCell)return;if(e.calculative.isInput)return;if(!e.calculative.isHover)return;let i=e.calculative.worldRect,n=e.calculative.canvas.mousePos;if(!(n.x>i.x&&n.xi.y&&n.yvoid 0!==t.col&&void 0===t.row&&t.width));let s={};r&&r.forEach((t=>{s[t.col]=t.width}));for(let i=0;it.col===i&&void 0===t.row));r&&(n[i]=r[0])}let a=0;const l=t.styles&&t.styles.filter((t=>void 0===t.col&&void 0!==t.row&&t.height));let c={};l&&l.forEach((t=>{c[t.row]=t.height}));let h=a;for(let e=0;e{t.calculative.isHover=!0,t.calculative.canvas.render()}),500),t.calculative.hoverCell=Ir(t,e),t.calculative.canvas.render()}function Pr(t,e){Wr(t),t.calculative.hoverCell=void 0,t.calculative.canvas.render()}function Er(t,e){t.calculative.activeCell=Ir(t,e),t.calculative.canvas.render()}function Ir(t,e){const i=t.calculative.worldRect.width/t.tableWidth,n=t.calculative.worldRect.height/t.tableHeight,o={row:0,col:0};for(let n=0;nt.calculative.worldRect.x+t.colPos[n]*i&&(o.col=n+1);for(let i=0;it.calculative.worldRect.y+t.rowPos[i]*n-t.offsetY*t.calculative.canvas.store.data.scale&&(o.row=i+1);return o}function _r(t,e,i){if(!t.data||!Array.isArray(t.data))return;const n=t.data[e],o=t.styles&&t.styles.filter((t=>t.row===e&&t.col===i));if(Array.isArray(n))return{value:n[i],style:o?.length>0?o.length>1?o:o[0]:{}};n.data&&Array.isArray(n.data)}function Lr(t,e){if(!t.data||!Array.isArray(t.data))return;const i=t.data[e],n=t.styles&&t.styles.filter((t=>t.row===e&&!t.col));if(Array.isArray(i))return{value:i,style:n?.length>0?n[0]:{}};i.data&&Array.isArray(i.data)}function Mr(t,e,i,n){if(!t.data||!Array.isArray(t.data))return;t.isFirstTime=!1,t.calculative.texts=void 0;let o=t.data[e];o&&(o[i]instanceof Object||(o[i]=n),t.calculative.canvas.store.emitter.emit("valueUpdate",t))}function Dr(t,e,i){const n=t.calculative.worldRect.width/t.tableWidth,o=t.calculative.worldRect.height/t.tableHeight;let r=0,s=t.colPos[i]*n;i>0&&(r=t.colPos[i-1]*n);let a=0,l=t.rowPos[e]*o;e>0&&(a=t.rowPos[e-1]*o);let c=t.offsetY*t.calculative.canvas.store.data.scale;return 0===e&&t.hasHeader&&(c=0),{x:t.calculative.worldRect.x+r,y:t.calculative.worldRect.y+a-c,ex:t.calculative.worldRect.x+s,ey:t.calculative.worldRect.y+l-c,width:s-r,height:l-a}}function Or(t,e,i){if(!i||!i.length)return;const n=t.calculative.worldRect.width/t.tableWidth,o=t.calculative.worldRect.height/t.tableHeight;let r=1,s=1;t.initWorldRect&&(t.calculative.worldRect.width!==t.initWorldRect.width&&(r=t.calculative.worldRect.width/t.initWorldRect.width),t.calculative.worldRect.height!==t.initWorldRect.height&&(s=t.calculative.worldRect.height/t.initWorldRect.height));let a=0,l=0,c=0;const h=t.calculative.canvas.store.data.scale;if(i.length>1){for(const t of i)l+t.width*n+20*h*n{t.width=t.width*r,t.height=t.height*s}))}function Nr(t){if(t.calculative.isUpdateData){delete t.calculative.isUpdateData;let e=Q(t.children);t.children=[],Ar(t),e&&e.forEach((e=>{t.calculative.canvas.delForce(t.calculative.canvas.findOne(e))})),t.calculative.texts=void 0}}function Br(t,e){if(t.calculative.isUpdateData=!1,void 0!==t.swiper&&(t.swiper?Wr(t):jr(t)),e.styles&&(t.initWorldRect=void 0),e.table||null==e.col&&null==e.row){if(e.dataY){const i=t.replaceMode;let n=[];return i?i===xr.Replace?(n=t.data,e.dataX&&e.dataX.forEach(((t,i)=>{n[t]=e.dataY[i]}))):i===xr.ReplaceAll&&(e.dataX?n[0]=e.dataX:n[0]=t.data[0],n=n.concat(e.dataY)):n=t.data.concat(e.dataY),delete e.dataX,delete e.dataY,t.calculative.isUpdateData=!0,Object.assign(e,{data:n})}(e.data||e.styles||e.maxNum||e.rowHeight||e.colWidth)&&(t.calculative.isUpdateData=!0,t.initWorldRect=null);for(let i of Object.keys(e))i.includes("data.")&&(t.calculative.isUpdateData=!0);return e}let i=t.data[e.row];return i?(i[e.col]instanceof Object||(i[e.col]=e.value),Mr(t,e.row,e.col,e.value),t.calculative.canvas.render(),delete e.col,delete e.row,e):e}function Fr(t,e){if(!t.locked&&!t.calculative.canvas.store.data.locked)return;if(!t.maxNum)return;let i=0;i=e.deltaY>0?4:-4,zr(t,i)}function zr(t,e){t.offsetY||(t.offsetY=0),t.offsetY+=e,t.offsetY>t.calculative.maxOffsetY&&(t.offsetY=t.calculative.maxOffsetY),t.offsetY<0&&(t.offsetY=0),t.children?.forEach((e=>{const i=t.calculative.canvas.store.pens[e];!function(t,e){if(!e)return;e.oldY||(e.oldY=e.y);const{y:i,height:n}=e.calculative.worldRect,{y:o,height:r}=t.calculative.worldRect,s=t.calculative.canvas.store.data.scale,a=(t.calculative.worldRect.height,t.tableHeight,t.rowHeight);e.y=e.oldY-t.offsetY*s/t.calculative.worldRect.height;const l=a*(t.initScale||1)/t.tableHeight*t.maxNum;if(t.calculative.canvas.updatePenRect(e),t.hasHeader)if(e.y1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=l;let i=e.row-t.maxNum;if(!t.data[i])return;let n=Q(t.data[i][e.col]);n.background&&(n.activeBackground=n.background,n.hoverBackground=n.background),n.color&&(n.hoverColor=n.color,n.activeColor=n.color),n.textColor&&(n.activeTextColor=n.textColor,n.hoverTextColor=n.textColor),Object.assign(e,n,{row:i}),Object.assign(e.calculative,n,{row:i})}}else e.visible=!0,e.calculative.visible=!0;else if(e.y<0){if(e.calculative.visible=!1,e.visible=!1,e.y<-a/t.tableHeight/2){e.oldY+=l;let i=e.row+t.maxNum;if(!t.data[i])return;let n=Q(t.data[i][e.col]);n.background&&(n.activeBackground=n.background,n.hoverBackground=n.background),n.color&&(n.hoverColor=n.color,n.activeColor=n.color),n.textColor&&(n.activeTextColor=n.textColor,n.hoverTextColor=n.textColor),Object.assign(e,n,{row:i}),Object.assign(e.calculative,n,{row:i})}}else if(e.y+e.height>1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=l;let i=e.row-t.maxNum;if(!t.data[i])return;let n=Q(t.data[i][e.col]);n.background&&(n.activeBackground=n.background,n.hoverBackground=n.background),n.color&&(n.hoverColor=n.color,n.activeColor=n.color),n.textColor&&(n.activeTextColor=n.textColor,n.hoverTextColor=n.textColor),Object.assign(e,n,{row:i}),Object.assign(e.calculative,n,{row:i})}}else e.calculative.visible=!0,e.visible=!0}(t,i)})),t.calculative.canvas.render()}function Hr(t){jr(t)}function jr(t){t.interval&&(globalThis.clearInterval(t.interval),t.interval=null)}function Wr(t){if(t.maxNum&&t.swiper){if(t.interval)return;t.interval=globalThis.setInterval((()=>{t.offsetY>=t.calculative.maxOffsetY?(t.offsetY=0,function(t){t.children?.forEach((e=>{const i=t.rowHeight,n=t.calculative.canvas.store.pens[e];if(!n)return;const o=i*(t.initScale||1)/t.tableHeight*t.maxNum;n.oldY-=o;const r=n.row-t.maxNum;if(!t.data[r])return;let s=Q(t.data[r][n.col]);s.background&&(s.activeBackground=s.background,s.hoverBackground=s.background),s.color&&(s.hoverColor=s.color,s.activeColor=s.color),s.textColor&&(s.activeTextColor=s.textColor,s.hoverTextColor=s.textColor),n.calculative.visible=!0,n.visible=!0,Object.assign(n,s,{row:r}),Object.assign(n.calculative,s,{row:r})})),t.calculative.canvas.render()}(t)):t.offsetY%t.rowHeight?zr(t,1):(t.calculative.stap||(t.calculative.stap=0),t.calculative.stap+=1,12==t.calculative.stap&&(t.calculative.stap=0,zr(t,1)))}),50)}}function Ur(t){jr(t)}function Vr(t,e){e.onClick||(e.onClick=qr);let i=e.calculative.worldRect.x,n=e.calculative.worldRect.y,o=e.calculative.worldRect.width,r=e.calculative.worldRect.height;o<1.5*r&&(o=1.5*r),t.beginPath(),t.arc(i+r/2,n+r/2,r/2,Math.PI/2,3*Math.PI/2),t.lineTo(i+o-r/2,n),t.arc(i+o-r/2,n+r/2,r/2,-Math.PI/2,Math.PI/2),t.lineTo(i+r/2,n+r),e.checked?(t.fillStyle=e.onColor,(e.disabled||e.disable)&&(t.fillStyle=e.disableOnColor||nt(.6,e.onColor)),e.lineWidth&&(t.strokeStyle=e.onStrokeColor,t.stroke()),t.fill(),t.closePath(),t.beginPath(),t.fillStyle="#ffffff",t.moveTo(i+2*r,n+r/2),t.arc(i+o-r/2,n+r/2,r/2>2?r/2-2:1,0,2*Math.PI),t.fill()):(t.fillStyle=e.offColor,(e.disabled||e.disable)&&(t.fillStyle=e.disableOffColor||nt(.6,e.offColor)),e.lineWidth&&(t.strokeStyle=e.offStrokeColor,t.stroke()),t.fill(),t.closePath(),t.beginPath(),t.fillStyle="#ffffff",t.moveTo(i+r,n+r/2),t.arc(i+r/2,n+r/2,r/2>2?r/2-2:1,0,2*Math.PI),t.fill()),t.closePath()}function qr(t){t.disabled||t.disable||(t.checked=!t.checked,t.calculative.canvas.store.emitter.emit("valueUpdate",t),t.calculative.canvas.render())}function Kr(t,e){e.onAdd||(e.onAdd=Yr,e.onResize=Yr,e.onMove=Yr,e.onMouseMove=Gr,e.onMouseDown=Xr,e.onValue=Qr,e.onBeforeValue=Jr),e.calculative.barRect||Yr(e),e.calculative.canvas.store.data;const i=e.calculative.canvas.store.options;let n=e.background;e.disabled&&(n=e.disabledBackground||nt(.6,n)),t.fillStyle=n,t.beginPath();let o=e.calculative.worldRect.x+e.calculative.barRect.x,r=e.calculative.worldRect.y+e.calculative.barRect.y,s=e.calculative.barRect.width,a=e.calculative.barRect.height,l=a/2;t.moveTo(o+l,r),t.arcTo(o+s,r,o+s,r+a,l),t.arcTo(o+s,r+a,o,r+a,l),t.arcTo(o,r+a,e.x,e.y,l),t.arcTo(o,r,o+s,r,l),t.fill();let c=e.activeColor||i.activeColor;e.disabled&&(c=e.disabledColor||nt(.6,c)),t.fillStyle=c,t.beginPath(),s=e.calculative.ballRect.x,t.moveTo(o+l,r),t.arcTo(o+s,r,o+s,r+a,l),t.arcTo(o+s,r+a,o,r+a,l),t.arcTo(o,r+a,e.x,e.y,l),t.arcTo(o,r,o+s,r,l),t.fill(),t.fillStyle=e.btnBackground||"#fff",t.strokeStyle=c,t.lineWidth=2,t.beginPath(),o=e.calculative.worldRect.x+e.calculative.ballRect.x,r=e.calculative.worldRect.y+e.calculative.ballRect.y+e.calculative.ballRect.height/2,t.lineWidth=e.calculative.ballRect.width/10,t.arc(o,r,e.calculative.ballRect.width/2,0,2*Math.PI),t.fill(),t.stroke()}function Yr(t){if(t._textWidth||(t._textWidth=t.textWidth||50,t._fontSize=t.fontSize||12),t.textWidth=t.calculative.worldRect.width,t.calculative.textWidth=t.textWidth,t.unit||(t.unit="%"),t.sliderWidth||(t.sliderWidth=t.width),t.sliderHeight||(t.sliderHeight=t.height),!t.calculative.worldRect)return;const e=t.calculative.worldRect.width/t.sliderWidth,i=t.calculative.worldRect.height/t.sliderHeight,n=Math.min(e,i);t.fontSize=t._fontSize*n;const o=t.calculative.worldRect.width-t._textWidth*n;t.textLeft=o+10*n,t.calculative.textLeft=t.textLeft,t.calculative.barRect={x:0,y:(t.calculative.worldRect.height-t.barHeight*i)/2,width:o,height:t.barHeight*i},He(t.calculative.barRect),$r(t)}function $r(t){const e=3.5*t.calculative.barRect.height,i=t.calculative.barRect.width*t.value/100;t.calculative.ballRect={x:i,y:(t.calculative.worldRect.height-e)/2,width:e,height:e},He(t.calculative.ballRect),t.calculative.text=t.value+t.unit,q(t)}function Xr(t,e){if(t.disabled)return;const i=e.x-t.calculative.worldRect.x;if(i>t.calculative.barRect.width)return;let n=Math.round(i/t.calculative.barRect.width*100);nt.max||n<0||n>100||(t.value=n,$r(t),t.calculative.text=t.value+t.unit,q(t),t.calculative.canvas.store.emitter.emit("valueUpdate",t),t.calculative.canvas.render())}function Gr(t,e){t.calculative.canvas.mouseDown&&Xr(t,e)}function Qr(t){t.calculative.isUpdateData&&(delete t.calculative.isUpdateData,Yr(t)),$r(t)}function Jr(t,e){return t.calculative.isUpdateData=!1,(e.textWidth||e.barHeight)&&(e.textWidth&&(t._textWidth=0),t.calculative.isUpdateData=!0),e}function Zr(t,e){e.onMouseDown||(e.onMouseDown=ts),e.options||(e.options=e.data);let i=e.calculative.worldRect.x,n=e.calculative.worldRect.y,o=e.calculative.worldRect.height;e.calculative.worldRect.width;const{fontStyle:r,fontWeight:s,fontSize:a,fontFamily:l,lineHeight:c}=e.calculative;t.beginPath(),t.moveTo(i,n),t.arcTo(i+o,n,i+o,n+o,2),t.arcTo(i+o,n+o,i,n+o,2),t.arcTo(i,n+o,i,n,2),t.arcTo(i,n,i+o,n,2),t.strokeStyle="#d9d9d9",t.fillStyle="#ffffff00",e.checked&&(t.fillStyle=e.background||"#1890ff",t.strokeStyle=e.background||"#1890ff"),(e.isForbidden||e.disabled)&&(t.fillStyle=e.disabledBackground||nt(.6,e.background)||"#ebebeb",t.strokeStyle=e.disabledColor||nt(.6,e.color)||"#d9d9d9"),t.closePath(),t.fill(),t.stroke(),t.save(),e.checked&&(t.beginPath(),t.lineWidth=o/10,t.strokeStyle="#ffffff",t.moveTo(i+102/506*o,n+o/2),t.lineTo(i+220/506*o,n+346/460*o),t.lineTo(i+404/506*o,n+142/460*o),t.stroke()),t.restore(),t.save(),t.fillStyle=e.disabled||e.isForbidden?e.disabledTextColor||nt(.6,e.textColor||e.color)||"#00000040":Pt(e,e.calculative.canvas.parent.store)||"#000000d9",t.textAlign="start",t.textBaseline="middle",t.font=Lt({fontStyle:r,fontWeight:s,fontFamily:l||e.calculative.canvas.parent.store.options.fontFamily,fontSize:a,lineHeight:c}),t.fillText(e.value+"",i+o+10,n+o/2),t.restore()}function ts(t,e){t.isForbidden||(t.checked=!t.checked,t.calculative.canvas.store.emitter.emit("valueUpdate",t),t.calculative.canvas.render())}function es(t,e){e.options||(e.options=e.data),e.onAdd||(e.onAdd=is,e.optionPos||(e.onAdd(e),e.calculative.canvas.parent.active([e])),e.onMouseDown=ns,e.onValue=os);let i=e.calculative.worldRect.x,n=e.calculative.worldRect.y,o=e.calculative.worldRect.height,r=e.calculative.worldRect.width;if(!e.optionPos)return;const{fontStyle:s,fontWeight:a,fontSize:l,fontFamily:c,lineHeight:h}=e.calculative;if("horizontal"==e.direction)for(let l=0;lt.calculative.worldRect.x+t.optionPos[i]*t.calculative.worldRect.width/t.checkboxWidth&&e.xt.calculative.worldRect.y+t.optionPos[n]*i&&e.y({id:`${n}`,penId:t.id,x:e,y:i})))}function ls(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s-r,l=.5*r;if(i.moveTo(n+r/2,o),i.lineTo(n+r/2,o+a),i.moveTo(n+r,o+l+a),i.arc(n+r/2,o+l+a,l,0,2*Math.PI,!1),i.closePath(),i instanceof Path2D)return i}function cs(t){t.anchors=[{x:.5,y:0},{x:.5,y:1}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function hs(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/2,l=r/5;if(i.moveTo(n,o+a),i.lineTo(n+l,o+a),i.moveTo(n+5*l,o+a),i.ellipse(n+3*l,o+a,2*l,a,0,0,2*Math.PI),i.closePath(),i instanceof Path2D)return i}function ds(t){t.anchors=[{x:.6,y:0},{x:1,y:.5},{x:.6,y:1},{x:0,y:.5}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function us(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/4,l=.5*r;if(i.moveTo(n+l,o),i.lineTo(n+l,o+a),i.moveTo(n,o+a),i.rect(n,o+a,2*l,2*a),i.moveTo(n+l,o+3*a),i.lineTo(n+l,o+4*a),i.closePath(),i instanceof Path2D)return i}function fs(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/8,l=.25*r;if(i.moveTo(n+2*l,o),i.lineTo(n+2*l,o+2*a),i.lineTo(n+3*l,o+3*a),i.lineTo(n+3*l,o+5*a),i.lineTo(n+2*l,o+6*a),i.lineTo(n+1*l,o+5*a),i.lineTo(n+1*l,o+3*a),i.lineTo(n+2*l,o+2*a),i.moveTo(n+3*l,o+4*a),i.lineTo(n+4*l,o+4*a),i.moveTo(n+2*l,o+6*a),i.lineTo(n+2*l,o+8*a),i.closePath(),i instanceof Path2D)return i}function ps(t){t.anchors=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function vs(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=r/2,l=s/10;if(i.moveTo(n+a,o),i.lineTo(n+a,o+l),i.moveTo(n+a,o+l),i.quadraticCurveTo(n+2*a,o+l,n+2*a,o+9*l),i.moveTo(n+a,o+l),i.quadraticCurveTo(n,o+l,n,o+9*l),i.quadraticCurveTo(n+a,o+6*l,n+2*a,o+9*l),i.moveTo(n+a,o+3*s/4),i.lineTo(n+a,o+s),i.moveTo(n+2*a/5,o+201*s/250),i.lineTo(n+2*a/5,o+s),i.moveTo(n+8*a/5,o+201*s/250),i.lineTo(n+8*a/5,o+s),i.closePath(),i instanceof Path2D)return i}function gs(t){t.anchors=[{x:.5,y:0},{x:.2,y:1},{x:.5,y:1},{x:.8,y:1}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function ys(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/6,l=r/4;if(i.moveTo(n+2*l,o+0),i.lineTo(n+2*l,o+a),i.moveTo(n,o+a+2*l),i.arc(n+2*l,o+a+2*l,2*l,1*Math.PI,2*Math.PI,!1),i.lineTo(n+4*l,o+5*a),i.lineTo(n,o+5*a),i.lineTo(n,o+a+2*l),i.moveTo(n,o+5*a-a/3),i.lineTo(n+4*l,o+5*a-a/3),i.moveTo(n+l,o+5*a),i.lineTo(n+l,o+6*a),i.moveTo(n+2*l,o+5*a),i.lineTo(n+2*l,o+6*a),i.moveTo(n+3*l,o+5*a),i.lineTo(n+3*l,o+6*a),i.closePath(),i instanceof Path2D)return i}function ms(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/4,l=.5*r;if(i.moveTo(n+l,o),i.lineTo(n+l,o+a),i.lineTo(n+2*l,o+2*a),i.lineTo(n+2*l,o+4*a),i.lineTo(n,o+4*a),i.lineTo(n,o+2*a),i.lineTo(n+l,o+a),i.closePath(),i instanceof Path2D)return i}function ws(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/4,l=r/2;if(i.moveTo(n+l,o),i.lineTo(n+l,o+a),i.lineTo(n+2*l,o+4*a),i.lineTo(n,o+4*a),i.lineTo(n+l,o+a),i.closePath(),i instanceof Path2D)return i}function xs(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect,a=s/3,l=.5*r;if(i.moveTo(n+l,o),i.lineTo(n+l,o+a),i.lineTo(n+r,o+2*a),i.lineTo(n+l,o+s),i.lineTo(n,o+2*a),i.lineTo(n+l,o+a),i.closePath(),i instanceof Path2D)return i}function bs(t){t.anchors=[{x:.5,y:0},{x:1,y:2/3},{x:.5,y:1},{x:0,y:2/3}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function ks(t,e){const{x:i,y:n,width:o,height:r}=e.calculative.worldRect,s=o/2,a=r/10;t.beginPath(),t.moveTo(i+s,n),t.lineTo(i+s,n+a),t.moveTo(i+s,n+a),t.quadraticCurveTo(i+2*s,n+a,i+2*s,n+9*a),t.moveTo(i+s,n+a),t.quadraticCurveTo(i,n+a,i,n+9*a),t.quadraticCurveTo(i+s,n+6*a,i+2*s,n+9*a),t.moveTo(i+s,n+3*r/4),t.lineTo(i+s,n+9*r/10),t.moveTo(i+2*s/5,n+201*r/250),t.lineTo(i+2*s/5,n+9*r/10),t.moveTo(i+8*s/5,n+201*r/250),t.lineTo(i+8*s/5,n+9*r/10),t.stroke(),t.closePath(),t.beginPath();const l=2*s>10*a?a:s/5;t.fillStyle="#333333",t.font=l+"px Arial",t.textBaseline="bottom",t.textAlign="center",t.fillText("o",i+s,n+r),t.fillText("m",i+2*s/5,n+r),t.fillText("o",i+8*s/5,n+r),t.closePath()}function Ts(t,e){const i=e||new Path2D,{x:n,y:o,width:r,height:s}=t.calculative.worldRect;let a=r/2,l=s/10;if(i.moveTo(n+a,o),i.lineTo(n+a,o+l),i.moveTo(n+a,o+l),i.quadraticCurveTo(n+2*a,o+l,n+2*a,o+9*l),i.moveTo(n+a,o+l),i.quadraticCurveTo(n,o+l,n,o+9*l),i.quadraticCurveTo(n+a,o+6*l,n+2*a,o+9*l),i.moveTo(n,o+10*l),i.quadraticCurveTo(n+a,o+7*l,n+2*a,o+10*l),i.moveTo(n+2*a/5,o+201*s/250+l),i.lineTo(n+2*a/5,o+s),i.moveTo(n+8*a/5,o+201*s/250+l),i.lineTo(n+8*a/5,o+s),i.closePath(),i instanceof Path2D)return i}function As(t){t.anchors=[{x:.5,y:0},{x:.2,y:1},{x:.8,y:1}].map((({x:e,y:i},n)=>({id:`${n}`,penId:t.id,x:e,y:i})))}function Cs(){return{andGate:ss,basicEvent:ls,conditionalEvent:hs,event:us,forbiddenGate:fs,orGate:vs,priorityAndGate:ys,switchEvent:ms,transferSymbol:ws,unexpandedEvent:xs,xorGate:Ts}}function Rs(){return{votingGate:ks}}function Ss(){return{andGate:as,orGate:gs,priorityAndGate:as,votingGate:gs,xorGate:As,forbiddenGate:ps,basicEvent:cs,unexpandedEvent:bs,conditionalEvent:ds,transferSymbol:cs}}!function(t){t[t.Add=0]="Add",t[t.Replace=1]="Replace",t[t.ReplaceAll=2]="ReplaceAll"}(xr||(xr={}));const Ps=15;function Es(t,e=Ps){let i=""+t;return i.indexOf(".")>=0&&(i=Number.parseFloat(i).toFixed(e)),Number.parseFloat(i)}function Is(t){return"number"==typeof t&&Number.isFinite(t)}function _s(t,e){const i=e.calculative.worldRect.x,n=e.calculative.worldRect.y,o=e.calculative.worldRect.width,r=e.calculative.worldRect.height;let s=e.calculative.canvas.store.data.scale,a=[];if(e.echarts)for(let t=0;t0&&(i<0?i=0:n=0);const l=(i-n)/o;let c=Math.floor(Math.log10(l)-1);c=Math.pow(10,c);const h=l/c;let d,u=e[0]*c,f=-1;for(d=0;dh){u=e[d]*c;break}let p=i,v=n;function g(t){if(p=parseInt(""+(i/t+1))*t,v=parseInt(""+(n/t-1))*t,0===i&&(p=0),0===n&&(v=0),r&&p*v<0){const t=Math.max(Math.abs(p),Math.abs(v));p=t,v=-t}}if(g(u),s)return{max:Es(p),min:Es(v),interval:Es(u),splitNumber:Math.round((p-v)/u)};if(!r||p*v>0){let t;t:do{if(t=Math.round((p-v)/u),(d-f)*(t-o)<0)for(;t=e.length-1||d<=0||t===o)break;f=d,u=t>o?e[++d]*c:e[--d]*c,g(u)}while(t!==o)}p=Es(p),v=Es(v);const y=Es((p-v)/o);return{max:p,min:v,interval:y,splitNumber:o}}({max:Math.max.apply(null,l),min:Math.min.apply(null,l),splitNumber:5}),h=e.echarts?e.echarts.option.xAxis.data.length:e.xAxisData.length;t.beginPath(),t.strokeStyle="#BFBFBF",t.lineWidth=6*s,t.lineCap="butt";let d=(o-1*(h+1))/h;t.setLineDash([1,d]),t.moveTo(i,n+r+3*s),t.lineTo(i+o,n+r+3*s),t.stroke(),t.closePath(),t.beginPath(),t.lineWidth=1*s,t.setLineDash([]),t.moveTo(i,n+r),t.lineTo(i+o,n+r),t.stroke(),t.closePath(),t.beginPath(),t.fillStyle="#BFBFBF",t.strokeStyle="#E9E9E9",t.setLineDash([2,2]);let u={fontStyle:e.yAxis?.axisLabel?.fontStyle||e.fontStyle,textDecoration:e.yAxis?.axisLabel?.textDecoration,fontWeight:e.yAxis?.axisLabel?.fontWeight||e.fontWeight,fontFamily:e.yAxis?.axisLabel?.fontFamily||e.fontFamily,fontSize:e.yAxis?.axisLabel?.fontSize||e.fontSize,lineHeight:e.yAxis?.axisLabel?.lineHeight||e.lineHeight};t.fillStyle=e.yAxis?.axisLabel?.fontColor||e.color;for(let e=0;e{f=i+(1+l/2)+(l+1)*v,p=n+o-(u[v]-c.min)/(c.max-c.min)*o;let g=i+(1+l/2)+(l+1)*(v+1),y=n+o-(u[v+1]-c.min)/(c.max-c.min)*o,m=i+(1+l/2)+(l+1)*(v-1),w=n+o-(u[v-1]-c.min)/(c.max-c.min)*o,x=i+(1+l/2)+(l+1)*(v+2),b=n+o-(u[v+2]-c.min)/(c.max-c.min)*o;0===v?(m=i+(1+l/2)+(l+1)*v,w=n+o-(u[v]-c.min)/(c.max-c.min)*o):v===u.length-2&&(x=i+(1+l/2)+(l+1)*(v+1),b=n+o-(u[v+1]-c.min)/(c.max-c.min)*o),d.push({x:f,y:p}),e=f+(g-m)/4,r=p+(y-w)/4,s=g-(x-f)/4,a=y-(b-p)/4,t.bezierCurveTo(e,r,s,a,g,y)}))}else for(let e=1;e{t.beginPath(),t.strokeStyle="#fff",t.lineWidth=2*r,t.arc(e.x,e.y,4*r,0,2*Math.PI),t.stroke(),t.fill(),t.closePath()})),t.restore(),d=[]}}function Os(t,e){if(e.xAxisData||e.data||!e.dataX&&!e.dataY)return e;const i=t.xAxisData,n=t.data,o=t.replaceMode;let r=[],s=[];return o?o===Ms.Replace?(e.dataX.forEach(((t,o)=>{let r=i.indexOf(t);n.forEach(((t,i)=>{t[r]=e.dataY[i][o]}))})),r=i,s=n):o===Ms.ReplaceAll&&(r=e.dataX,s=e.dataY):(r=[...i,...e.dataX],n.forEach(((t,i)=>{let n=[...t,...e.dataY[i]];s.push(n)}))),delete e.dataX,delete e.dataY,Object.assign(e,{xAxisData:r,data:s})}function Ns(t,e){e.onBeforeValue||(e.onBeforeValue=Bs);let i=e.calculative.canvas.store.data.scale;const n=e.calculative.worldRect.x,o=e.calculative.worldRect.y,r=e.calculative.worldRect.width,s=e.calculative.worldRect.height,a=!!e.echarts;e.echarts?(e.echarts.option.color||(e.echarts.option.color=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]),e.chartsColor=e.echarts.option.color):e.chartsColor||(e.chartsColor=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]);const l=a?e.echarts.option.series:e.data;let c=0;for(let h=0;ht+e.value),0):d.reduce(((t,e)=>t+e.value),0);const g=u*parseFloat(a?d.radius[0]:e.chartsRadius[h][0])/100,y=u*parseFloat(a?d.radius[1]:e.chartsRadius[h][1])/100;if(g>y)return;let m=0,w=0;t.strokeStyle=a&&d.itemStyle?.borderColor||"#fff",t.lineWidth=(a&&d.itemStyle?.borderWidth||2)*i;const x=a?d.data:d;x.forEach(((n,o)=>{w+=2*Math.PI*n.value/v,t.beginPath();let r=c+o;r>=e.chartsColor.length&&(r%=e.chartsColor.length),t.fillStyle=a?e.echarts.option.color[r]:e.chartsColor[r],t.moveTo(f+g*Math.sin(w),p-g*Math.cos(w)),t.arc(f,p,g,-Math.PI/2+w,-Math.PI/2+m,!0),t.lineTo(f+y*Math.sin(m),p-y*Math.cos(m)),t.arc(f,p,y,-Math.PI/2+m,-Math.PI/2+w),t.lineTo(f+g*Math.sin(w),p-g*Math.cos(w)),t.stroke(),t.fill(),t.closePath();let s=(m+w)/2,l=f+(y+10*i)*Math.sin(s),h=p-(y+10*i)*Math.cos(s),u=t.fillStyle;d.label||(d.label={position:"outside",show:!0}),a&&["inner","inside"].includes(d.label.position)?(t.fillStyle="#ffffff",l=f+(y-g)/2*Math.sin(s),h=p-(y-g)/2*Math.cos(s)):a&&d.label.position,d.labelLine||(d.labelLine={show:!0}),(a&&!1!==d.labelLine.show||!a)&&(t.beginPath(),t.strokeStyle=a?e.echarts.option.color[c+o]:e.chartsColor[c+o],t.moveTo(f+y*Math.sin(s),p-y*Math.cos(s)),t.lineTo(l,h));let x={fontStyle:e.tickLabel?.fontStyle||e.calculative.fontStyle,fontWeight:e.tickLabel?.fontWeight||e.calculative.fontWeight,fontFamily:e.tickLabel?.fontFamily||e.calculative.fontFamily,lineHeight:e.tickLabel?.lineHeight||e.calculative.lineHeight,fontSize:(e.tickLabel?.fontSize||e.calculative.fontSize)*i};t.font=Lt(x),t.textBaseline="middle",t.textAlign="center",s>Math.PI?((a&&"outside"===d.label.position||!a)&&(t.textAlign="end"),(a&&!1!==d.labelLine.show||!a&&(e.tickLabel?.labelLine?.show??1))&&t.lineTo(l-5*i,h),(a&&!1!==d.label.show||!a&&(e.tickLabel?.show??1))&&t.fillText(n.name,l-5*i,h)):((a&&"outside"===d.label.position||!a)&&(t.textAlign="start"),(a&&!1!==d.labelLine.show||!a)&&t.lineTo(l+5*i,h),(a&&!1!==d.label.show||!a&&(e.tickLabel?.show??1))&&t.fillText(n.name,l+5*i,h)),t.stroke(),t.closePath(),t.fillStyle=u,t.strokeStyle=a&&d.itemStyle?.borderColor||"#fff",m=w})),c+=x.length}}function Bs(t,e){if(e.data||!e.dataX&&!e.dataY)return e;const i=t.data,n=t.replaceMode;let o=[];return n?n===Ms.Replace?(e.dataY.forEach(((t,e)=>{t.forEach(((t,n)=>{let o=i[e].filter((e=>e.name===t.name));o.length>0&&(o[0].value=t.value)}))})),o=i):n===Ms.ReplaceAll&&(o=e.dataY):i.forEach(((t,i)=>{let n=[...t,...e.dataY[i]];o.push(n)})),delete e.dataX,delete e.dataY,Object.assign(e,{data:o})}function Fs(t,e){e.onBeforeValue||(e.onBeforeValue=Os);let i=e.calculative.canvas.store.data.scale;const n=e.calculative.worldRect.x,o=e.calculative.worldRect.y,r=(e.calculative.worldRect.width,e.calculative.worldRect.height);let s=[];if(e.echarts&&!e.echarts.option.color&&(e.echarts.option.color=["#1890ff","#2FC25B","#FACC14","#c23531","#2f4554","#61a0a8","#d48265"]),e.echarts)for(let t=0;tr?r/2*9/10:o/2*9/10,h=i+o/2,d=n+r/2,u=(e={...a,...e}).echarts?e.echarts.option.series[0].data[0].value:e.value,f=e.startAngle-e.endAngle,p=e.background||"#E6EBF8";t.strokeStyle=p;let v=c/10;t.lineWidth=v,t.beginPath(),t.lineCap="round",t.arc(h,d,c,-e.startAngle/180*Math.PI,-e.endAngle/180*Math.PI),t.stroke(),t.closePath();let g=0;if(e.axisLine&&!e.isClock)for(let i=e.axisLine.length-1;i>=0;i--)e.axisLine[i][0]*(e.max-e.min).02?"end":o<-.02?"start":"center",t.textBaseline=r>.02?"top":r<-.02?"bottom":"middle",t.fillText(Ls(P*i+e.min,1),h+I*o,d-I*r),t.fill()}t.closePath();let _=1,L=["value"];if(e.isClock&&(_=3,L=["hourvalue","minutevalue","secondvalue"]),e.isClock)for(let i=0;i<_;i++){let n=(e.startAngle-(e[L[i]]-e.min)/(e.max-e.min)*f)/180*Math.PI;i>0&&(n=(e.startAngle-(e[L[i]]-e.min)/(5*e.max-e.min)*f)/180*Math.PI);let o=.8*c;"hourvalue"===L[i]&&(o=.6*c),"minutevalue"===L[i]&&(o=.7*c);let r=1*c/40;t.beginPath(),t.setLineDash([]),t.lineWidth=c/(i+1)/20,t.strokeStyle=e.color||"#999999",t.moveTo(h-3*r*Math.cos(n),d+3*r*Math.sin(n)),t.lineTo(h+o*Math.cos(n),d-o*Math.sin(n)),t.stroke()}else{let i=(e.startAngle-(u-e.min)/(e.max-e.min)*f)/180*Math.PI,n=.8*c,o=1*c/40;t.beginPath(),t.setLineDash([]),t.lineWidth=2,t.fillStyle=l,t.moveTo(h-3*o*Math.cos(i),d+3*o*Math.sin(i)),t.lineTo(h+o*Math.cos(i-Math.PI/2),d-o*Math.sin(i-Math.PI/2)),t.lineTo(h+n*Math.cos(i),d-n*Math.sin(i)),t.lineTo(h+o*Math.cos(i+Math.PI/2),d-o*Math.sin(i+Math.PI/2)),t.lineTo(h-3*o*Math.cos(i),d+3*o*Math.sin(i)),t.fill()}t.beginPath(),t.textAlign="center",t.textBaseline="middle";let M={fontStyle:e.titleLabel?.fontStyle||e.calculative.fontStyle,textDecoration:e.titleLabel?.textDecoration||e.textDecoration,fontWeight:e.titleLabel?.fontWeight||e.calculative.fontWeight,fontFamily:e.titleLabel?.fontFamily||e.calculative.fontFamily,fontSize:(e.titleLabel?.fontSize||e.calculative.fontSize)*s,lineHeight:e.titleLabel?.lineHeight||e.calculative.lineHeight};t.font=Lt(M),t.fillStyle=e.titleLabel?.color||l,e.isClock?t.fillText(("0"+parseInt(e.hourvalue)).slice(-2)+":"+("0"+parseInt(e.minutevalue)).slice(-2)+":"+("0"+parseInt(e.secondvalue)).slice(-2),h,d+c/2):t.fillText(u+" "+(e.unit||""),h,d+c/2),t.fill(),e.isClock&&(t.beginPath(),t.fillStyle=e.color||"#999999",t.strokeStyle="#ffffff",t.arc(h,d,c/20,0,2*Math.PI),t.stroke(),t.fill(),t.closePath())}function Hs(t){if(t.isClock)t.clockInterval=setInterval((()=>{let e=new Date,i=e.getSeconds(),n=e.getMinutes()+i/60,o=e.getHours()%12+n/60;t.calculative.canvas.parent.setValue({id:t.id,hourvalue:o,minutevalue:n,secondvalue:i},{render:!0,doEvent:!1})}),1e3);else{const e=t.value;t.value=0,t.frames=[{duration:2e3,value:e}],t.calculative.canvas.parent.startAnimate(t.id),setTimeout((()=>{t.value=e}),1e3)}}function js(t){t.clockInterval&&(clearInterval(t.clockInterval),t.clockInterval=void 0)}function Ws(t){t.isClock&&(t.onDestroy(t),t.onAdd(t))}function Us(){return{lineChart:Ds,histogram:Fs,pieChart:Ns,gauge:zs}}!function(t){t[t.Add=0]="Add",t[t.Replace=1]="Replace",t[t.ReplaceAll=2]="ReplaceAll"}(Ms||(Ms={})),globalThis.Meta2d=ho,globalThis.registerCommonDiagram=function(){var t=globalThis.meta2d;t&&(yr(),mr(),wr(),t.register(Vo()),t.registerAnchors(qo()),t.register(Ro()),t.registerCanvasDraw(So()),t.register(mo()),t.register(bo()),t.registerCanvasDraw(ko()),t.registerCanvasDraw(rs()),t.registerCanvasDraw(Us()),t.register(Cs()),t.registerCanvasDraw(Rs()),t.registerAnchors(Ss()))}})(),n})()));