@html-graph/html-graph 8.24.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.HtmlGraph={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=function(e){return e.Line=`line`,e.NodeCycle=`node-cycle`,e.PortCycle=`port-cycle`,e}({}),n=()=>{let e=document.createElement(`div`);return e.style.width=`100%`,e.style.height=`100%`,e.style.position=`relative`,e.style.overflow=`hidden`,e},r=()=>{let e=document.createElement(`div`);return e.style.position=`absolute`,e.style.top=`0`,e.style.left=`0`,e.style.width=`0`,e.style.height=`0`,e},i=e=>{e.style.position=`absolute`,e.style.top=`0`,e.style.left=`0`,e.style.visibility=`hidden`},a=e=>{e.style.removeProperty(`position`),e.style.removeProperty(`top`),e.style.removeProperty(`left`),e.style.removeProperty(`visibility`),e.style.removeProperty(`transform`)},o=class{graphStore;viewportStore;element;host=n();container=r();edgeIdToElementMap=new Map;attachedNodeIds=new Set;applyTransform=()=>{let e=this.viewportStore.getContentMatrix();this.container.style.transform=`matrix(${e.scale}, 0, 0, ${e.scale}, ${e.x}, ${e.y})`};constructor(e,t,n){this.graphStore=e,this.viewportStore=t,this.element=n,this.element.appendChild(this.host),this.host.appendChild(this.container),this.viewportStore.onAfterUpdated.subscribe(this.applyTransform)}attachNode(e){let t=this.graphStore.getNode(e);i(t.element),this.attachedNodeIds.add(e),this.container.appendChild(t.element),this.updateNodePosition(e),this.updateNodePriority(e),t.element.style.visibility=`visible`}detachNode(e){let t=this.graphStore.getNode(e);a(t.element),this.container.removeChild(t.element),this.attachedNodeIds.delete(e)}attachEdge(e){let t=this.graphStore.getEdge(e).payload.shape.element;this.edgeIdToElementMap.set(e,t),this.container.appendChild(t),this.renderEdge(e),this.updateEdgePriority(e)}detachEdge(e){let t=this.edgeIdToElementMap.get(e);this.container.removeChild(t),this.edgeIdToElementMap.delete(e)}clear(){this.edgeIdToElementMap.forEach((e,t)=>{this.detachEdge(t)}),this.attachedNodeIds.forEach(e=>{this.detachNode(e)})}destroy(){this.clear(),this.viewportStore.onAfterUpdated.unsubscribe(this.applyTransform),this.element.removeChild(this.host),this.host.removeChild(this.container)}updateNodePosition(e){let t=this.graphStore.getNode(e),{width:n,height:r}=t.element.getBoundingClientRect(),i=this.viewportStore.getViewportMatrix().scale,{payload:a}=t,o=a.centerFn(n,r),s=a.x-i*o.x,c=a.y-i*o.y;t.element.style.transform=`translate(${s}px, ${c}px)`}updateNodePriority(e){let t=this.graphStore.getNode(e);t.element.style.zIndex=`${t.payload.priority}`}updateEdgeShape(e){let t=this.edgeIdToElementMap.get(e);this.container.removeChild(t);let n=this.graphStore.getEdge(e).payload.shape.element;this.edgeIdToElementMap.set(e,n),this.container.appendChild(n)}renderEdge(e){let n=this.graphStore.getEdge(e),r=this.graphStore.getPort(n.from),i=this.graphStore.getPort(n.to),a=r.element.getBoundingClientRect(),o=i.element.getBoundingClientRect(),s=this.host.getBoundingClientRect(),c=this.viewportStore.getViewportMatrix().scale,l=this.createEdgeRenderPort(r,a,s,c),u=this.createEdgeRenderPort(i,o,s,c),d=t.Line;r.element===i.element?d=t.PortCycle:r.nodeId===i.nodeId&&(d=t.NodeCycle),n.payload.shape.render({from:l,to:u,category:d})}updateEdgePriority(e){let t=this.graphStore.getEdge(e);t.payload.shape.element.style.zIndex=`${t.payload.priority}`}createEdgeRenderPort(e,t,n,r){let i=this.viewportStore.createContentCoords({x:t.left-n.left,y:t.top-n.top});return{x:i.x,y:i.y,width:t.width*r,height:t.height*r,direction:e.payload.direction}}},s=class{graphStore;xFrom=1/0;yFrom=1/0;xTo=1/0;yTo=1/0;constructor(e){this.graphStore=e}setRenderingBox(e){this.xFrom=e.x,this.xTo=e.x+e.width,this.yFrom=e.y,this.yTo=e.y+e.height}hasNode(e){let{x:t,y:n}=this.graphStore.getNode(e).payload;return t>=this.xFrom&&t<=this.xTo&&n>=this.yFrom&&n<=this.yTo}hasEdge(e){let t=this.graphStore.getEdge(e),n=this.graphStore.getPort(t.from).nodeId,r=this.graphStore.getPort(t.to).nodeId,i=this.graphStore.getNode(n).payload,a=this.graphStore.getNode(r).payload,o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y);return o<=this.xTo&&s>=this.xFrom&&c<=this.yTo&&l>=this.yFrom}},c=class{htmlView;graphStore;trigger;params;attachedNodes=new Set;attachedEdges=new Set;renderingBox;updateViewport=e=>{this.renderingBox.setRenderingBox(e);let t=new Set,n=new Set,r=new Set,i=new Set;this.graphStore.getAllNodeIds().forEach(e=>{let r=this.renderingBox.hasNode(e),i=this.attachedNodes.has(e);r&&!i?t.add(e):!r&&i&&n.add(e)}),this.graphStore.getAllEdgeIds().forEach(e=>{let a=this.renderingBox.hasEdge(e),o=this.attachedEdges.has(e),s=this.graphStore.getEdge(e),c=this.graphStore.getPort(s.from).nodeId,l=this.graphStore.getPort(s.to).nodeId;a&&(this.renderingBox.hasNode(c)||(t.add(c),n.delete(c)),this.renderingBox.hasNode(l)||(t.add(l),n.delete(l))),a&&!o?r.add(e):!a&&o&&i.add(e)}),i.forEach(e=>{this.handleDetachEdge(e)}),n.forEach(e=>{this.handleDetachNode(e)}),t.forEach(e=>{this.attachedNodes.has(e)||this.handleAttachNode(e)}),r.forEach(e=>{this.handleAttachEdge(e)})};constructor(e,t,n,r){this.htmlView=e,this.graphStore=t,this.trigger=n,this.params=r,this.renderingBox=new s(this.graphStore),this.trigger.subscribe(this.updateViewport)}attachNode(e){this.renderingBox.hasNode(e)&&this.handleAttachNode(e)}detachNode(e){this.attachedNodes.has(e)&&this.handleDetachNode(e)}attachEdge(e){this.renderingBox.hasEdge(e)&&this.attachEdgeEntities(e)}detachEdge(e){this.attachedEdges.has(e)&&this.handleDetachEdge(e)}updateNodePosition(e){this.attachedNodes.has(e)?this.htmlView.updateNodePosition(e):this.renderingBox.hasNode(e)&&(this.handleAttachNode(e),this.graphStore.getNodeAdjacentEdgeIds(e).forEach(e=>{this.attachEdgeEntities(e)}))}updateNodePriority(e){this.attachedNodes.has(e)&&this.htmlView.updateNodePriority(e)}updateEdgeShape(e){this.attachedEdges.has(e)&&this.htmlView.updateEdgeShape(e)}renderEdge(e){this.attachedEdges.has(e)&&this.htmlView.renderEdge(e)}updateEdgePriority(e){this.attachedEdges.has(e)&&this.htmlView.updateEdgePriority(e)}clear(){this.htmlView.clear(),this.attachedNodes.clear(),this.attachedEdges.clear()}destroy(){this.clear(),this.htmlView.destroy(),this.trigger.unsubscribe(this.updateViewport)}attachEdgeEntities(e){let t=this.graphStore.getEdge(e),n=this.graphStore.getPort(t.from).nodeId,r=this.graphStore.getPort(t.to).nodeId;this.attachedNodes.has(n)||this.handleAttachNode(n),this.attachedNodes.has(r)||this.handleAttachNode(r),this.handleAttachEdge(e)}handleAttachNode(e){this.params.onBeforeNodeAttached(e),this.attachedNodes.add(e),this.htmlView.attachNode(e)}handleDetachNode(e){this.htmlView.detachNode(e),this.attachedNodes.delete(e),this.params.onAfterNodeDetached(e)}handleAttachEdge(e){this.attachedEdges.add(e),this.htmlView.attachEdge(e)}handleDetachEdge(e){this.htmlView.detachEdge(e),this.attachedEdges.delete(e)}},l=class{htmlView;graphStore;deferredNodes=new Set;deferredEdges=new Set;constructor(e,t){this.htmlView=e,this.graphStore=t}attachNode(e){this.isNodeValid(e)?this.htmlView.attachNode(e):this.deferredNodes.add(e)}detachNode(e){this.deferredNodes.has(e)?this.deferredNodes.delete(e):this.htmlView.detachNode(e)}attachEdge(e){this.isEdgeValid(e)?this.htmlView.attachEdge(e):this.deferredEdges.add(e)}detachEdge(e){this.deferredEdges.has(e)?this.deferredEdges.delete(e):this.htmlView.detachEdge(e)}updateNodePosition(e){this.deferredNodes.has(e)?this.tryAttachNode(e):this.htmlView.updateNodePosition(e)}updateNodePriority(e){this.deferredNodes.has(e)?this.tryAttachNode(e):this.htmlView.updateNodePriority(e)}updateEdgeShape(e){this.deferredEdges.has(e)?this.tryAttachEdge(e):this.htmlView.updateEdgeShape(e)}renderEdge(e){this.deferredEdges.has(e)?this.tryAttachEdge(e):this.htmlView.renderEdge(e)}updateEdgePriority(e){this.deferredEdges.has(e)?this.tryAttachEdge(e):this.htmlView.updateEdgePriority(e)}clear(){this.deferredNodes.clear(),this.deferredEdges.clear(),this.htmlView.clear()}destroy(){this.htmlView.destroy()}isNodeValid(e){let t=this.graphStore.getNode(e);return!(t.payload.x===null||t.payload.y===null)}tryAttachNode(e){this.isNodeValid(e)&&(this.deferredNodes.delete(e),this.htmlView.attachNode(e))}isEdgeValid(e){let t=this.graphStore.getEdge(e),n=this.graphStore.getPort(t.from),r=this.graphStore.getPort(t.to);return!(this.deferredNodes.has(n.nodeId)||this.deferredNodes.has(r.nodeId))}tryAttachEdge(e){this.isEdgeValid(e)&&(this.deferredEdges.delete(e),this.htmlView.attachEdge(e))}},u=class{callbacks=new Set;subscribe(e){this.callbacks.add(e)}unsubscribe(e){this.callbacks.delete(e)}emit(e){this.callbacks.forEach(t=>{t(e)})}},d=()=>{let e=new u;return[e,e]},f=class{graph;viewport;graphController;viewportController;beforeDestroyEmitter;destroyed=!1;onBeforeDestroy;constructor(e,t,n,r){this.graph=e,this.viewport=t,this.graphController=n,this.viewportController=r,[this.beforeDestroyEmitter,this.onBeforeDestroy]=d()}addNode(e){return this.graphController.addNode(e),this}updateNode(e,t){return this.graphController.updateNode(e,t),this}removeNode(e){return this.graphController.removeNode(e),this}markPort(e){return this.graphController.markPort(e),this}updatePort(e,t){return this.graphController.updatePort(e,t),this}unmarkPort(e){return this.graphController.unmarkPort(e),this}addEdge(e){return this.graphController.addEdge(e),this}updateEdge(e,t){return this.graphController.updateEdge(e,t),this}removeEdge(e){return this.graphController.removeEdge(e),this}clear(){return this.graphController.clear(),this}focus(e){return this.viewportController.focus(e),this}center(e,t){return this.viewportController.center(e,t),this}patchViewportMatrix(e){return this.viewportController.patchViewportMatrix(e),this}patchContentMatrix(e){return this.viewportController.patchContentMatrix(e),this}destroy(){this.destroyed||(this.destroyed=!0,this.beforeDestroyEmitter.emit(),this.graphController.destroy(),this.viewportController.destroy())}},p=class{singleToMultiMap=new Map;multiToSingleMap=new Map;addRecord(e,t){let n=this.singleToMultiMap.get(e);n===void 0?this.singleToMultiMap.set(e,new Set([t])):n.add(t),this.multiToSingleMap.set(t,e)}getMultiBySingle(e){let t=this.singleToMultiMap.get(e)??new Set;return Array.from(t.values())}removeByMulti(e){let t=this.multiToSingleMap.get(e),n=this.singleToMultiMap.get(t);n.delete(e),n.size===0&&this.singleToMultiMap.delete(t),this.multiToSingleMap.delete(e)}getByMulti(e){return this.multiToSingleMap.get(e)}removeBySingle(e){this.singleToMultiMap.get(e).forEach(e=>{this.multiToSingleMap.delete(e)}),this.singleToMultiMap.delete(e)}clear(){this.singleToMultiMap.clear(),this.multiToSingleMap.clear()}forEachSingle(e){this.singleToMultiMap.forEach((t,n)=>{e(n)})}hasSingle(e){return this.singleToMultiMap.get(e)!==void 0}hasMulti(e){return this.multiToSingleMap.get(e)!==void 0}},m=class extends Error{name=`CanvasError`},h=Object.freeze({accessNonexistingNode:e=>`Failed to access node with ID ${JSON.stringify(e)} because it does not exist`,addNodeWithExistingId:e=>`Failed to add node with ID ${JSON.stringify(e)} because a node with this ID already exists`,addNodeWithElementInUse:(e,t)=>`Failed to add node with ID ${JSON.stringify(e)} because its HTML element is already attached to node with ID ${JSON.stringify(t)}`,updateNonexistentNode:e=>`Failed to update node with ID ${JSON.stringify(e)} because it does not exist`,removeNonexistentNode:e=>`Failed to remove node with ID ${JSON.stringify(e)} because it does not exist`,accessNonexistentPort:e=>`Failed to access port with ID ${JSON.stringify(e)} because it does not exist`,addPortWithExistingId:e=>`Failed to add port with ID ${JSON.stringify(e)} because a port with this ID already exists`,addPortToNonexistentNode:(e,t)=>`Failed to add port with ID ${JSON.stringify(e)} to node with ID ${JSON.stringify(t)} because the node does not exist`,updateNonexistentPort:e=>`Failed to update port with ID ${JSON.stringify(e)} because it does not exist`,accessPortsOfNonexistentNode:e=>`Failed to access ports of node with ID ${JSON.stringify(e)} because the node does not exist`,removeNonexistentPort:e=>`Failed to remove port with ID ${JSON.stringify(e)} because it does not exist`,accessNonexistentEdge:e=>`Failed to access edge with ID ${JSON.stringify(e)} because it does not exist`,addEdgeWithExistingId:e=>`Failed to add edge with ID ${JSON.stringify(e)} because an edge with this ID already exists`,addEdgeWithElementInUse:(e,t)=>`Failed to add edge with ID ${JSON.stringify(e)} because its element is already attached to edge with ID ${JSON.stringify(t)}`,addEdgeFromNonexistentPort:(e,t)=>`Failed to add edge with ID ${JSON.stringify(e)} from port with ID ${JSON.stringify(t)} because the port does not exist`,addEdgeToNonexistentPort:(e,t)=>`Failed to add edge with ID ${JSON.stringify(e)} to port with ID ${JSON.stringify(t)} because the port does not exist`,updateNonexistentEdge:e=>`Failed to update edge with ID ${JSON.stringify(e)} because it does not exist`,updateNonexistentEdgeSource:(e,t)=>`Failed to update source of edge with ID ${JSON.stringify(e)} because source port with ID ${JSON.stringify(t)} does not exist`,updateNonexistentEdgeTarget:(e,t)=>`Failed to update target of edge with ID ${JSON.stringify(e)} because target port with ID ${JSON.stringify(t)} does not exist`,removeNonexistentEdge:e=>`Failed to remove edge with ID ${JSON.stringify(e)} because it does not exist`,accessEdgesForNonexistentPort:e=>`Failed to access edges for port with ID ${JSON.stringify(e)} because the port does not exist`}),g=class{nodes=new Map;ports=new Map;edges=new Map;nodesElementsMap=new Map;portIncomingEdges=new Map;portOutgoingEdges=new Map;portCycleEdges=new Map;elementPorts=new p;edgesElementsMap=new Map;afterNodeAddedEmitter;onAfterNodeAdded;afterNodeUpdatedEmitter;onAfterNodeUpdated;afterNodePriorityUpdatedEmitter;onAfterNodePriorityUpdated;beforeNodeRemovedEmitter;onBeforeNodeRemoved;afterPortAddedEmitter;onAfterPortAdded;afterPortUpdatedEmitter;onAfterPortUpdated;beforePortRemovedEmitter;onBeforePortRemoved;afterEdgeAddedEmitter;onAfterEdgeAdded;afterEdgeShapeUpdatedEmitter;onAfterEdgeShapeUpdated;afterEdgeUpdatedEmitter;onAfterEdgeUpdated;afterEdgePriorityUpdatedEmitter;onAfterEdgePriorityUpdated;beforeEdgeRemovedEmitter;onBeforeEdgeRemoved;beforeClearEmitter;onBeforeClear;constructor(){[this.afterNodeAddedEmitter,this.onAfterNodeAdded]=d(),[this.afterNodeUpdatedEmitter,this.onAfterNodeUpdated]=d(),[this.afterNodePriorityUpdatedEmitter,this.onAfterNodePriorityUpdated]=d(),[this.beforeNodeRemovedEmitter,this.onBeforeNodeRemoved]=d(),[this.afterPortAddedEmitter,this.onAfterPortAdded]=d(),[this.afterPortUpdatedEmitter,this.onAfterPortUpdated]=d(),[this.beforePortRemovedEmitter,this.onBeforePortRemoved]=d(),[this.afterEdgeAddedEmitter,this.onAfterEdgeAdded]=d(),[this.afterEdgeShapeUpdatedEmitter,this.onAfterEdgeShapeUpdated]=d(),[this.afterEdgeUpdatedEmitter,this.onAfterEdgeUpdated]=d(),[this.afterEdgePriorityUpdatedEmitter,this.onAfterEdgePriorityUpdated]=d(),[this.beforeEdgeRemovedEmitter,this.onBeforeEdgeRemoved]=d(),[this.beforeClearEmitter,this.onBeforeClear]=d()}hasNode(e){return this.nodes.has(e)}getNode(e){let t=this.nodes.get(e);if(t===void 0)throw new m(h.accessNonexistingNode(e));return t}addNode(e){if(this.hasNode(e.id))throw new m(h.addNodeWithExistingId(e.id));let t=this.findNodeIdByElement(e.element);if(t!==void 0)throw new m(h.addNodeWithElementInUse(e.id,t));let n=new Map,r={element:e.element,payload:{x:e.x,y:e.y,centerFn:e.centerFn,priority:e.priority},ports:n};this.nodes.set(e.id,r),this.nodesElementsMap.set(e.element,e.id),this.afterNodeAddedEmitter.emit(e.id)}getAllNodeIds(){return Array.from(this.nodes.keys())}findNodeIdByElement(e){return this.nodesElementsMap.get(e)}updateNode(e,t){if(!this.hasNode(e))throw new m(h.updateNonexistentNode(e));let{payload:n}=this.nodes.get(e);n.x=t.x??n.x,n.y=t.y??n.y,n.centerFn=t.centerFn??n.centerFn,t.priority!==void 0&&(n.priority=t.priority,this.afterNodePriorityUpdatedEmitter.emit(e)),this.afterNodeUpdatedEmitter.emit(e)}removeNode(e){if(!this.hasNode(e))throw new m(h.removeNonexistentNode(e));this.beforeNodeRemovedEmitter.emit(e);let t=this.getNode(e);this.nodesElementsMap.delete(t.element),this.nodes.delete(e)}hasPort(e){return this.ports.has(e)}getPort(e){let t=this.ports.get(e);if(t===void 0)throw new m(h.accessNonexistentPort(e));return t}addPort(e){if(this.hasPort(e.id))throw new m(h.addPortWithExistingId(e.id));if(!this.hasNode(e.nodeId))throw new m(h.addPortToNonexistentNode(e.id,e.nodeId));this.ports.set(e.id,{element:e.element,payload:{direction:e.direction},nodeId:e.nodeId}),this.elementPorts.addRecord(e.element,e.id),this.portCycleEdges.set(e.id,new Set),this.portIncomingEdges.set(e.id,new Set),this.portOutgoingEdges.set(e.id,new Set),this.getNode(e.nodeId).ports.set(e.id,e.element),this.afterPortAddedEmitter.emit(e.id)}updatePort(e,t){if(!this.hasPort(e))throw new m(h.updateNonexistentPort(e));let n=this.getPort(e).payload;n.direction=t.direction??n.direction,this.afterPortUpdatedEmitter.emit(e)}getAllPortIds(){return Array.from(this.ports.keys())}findPortIdsByElement(e){return this.elementPorts.getMultiBySingle(e)}getNodePortIds(e){let t=this.nodes.get(e);if(t===void 0)throw new m(h.accessPortsOfNonexistentNode(e));return Array.from(t.ports.keys())}removePort(e){if(!this.hasPort(e))throw new m(h.removeNonexistentPort(e));let t=this.getPort(e).nodeId;this.beforePortRemovedEmitter.emit(e),this.getNode(t).ports.delete(e),this.ports.delete(e),this.elementPorts.removeByMulti(e)}hasEdge(e){return this.edges.has(e)}getEdge(e){let t=this.edges.get(e);if(t===void 0)throw new m(h.accessNonexistentEdge(e));return t}findEdgeIdByElement(e){return this.edgesElementsMap.get(e)}addEdge(e){if(this.hasEdge(e.id))throw new m(h.addEdgeWithExistingId(e.id));if(!this.hasPort(e.from))throw new m(h.addEdgeFromNonexistentPort(e.id,e.from));if(!this.hasPort(e.to))throw new m(h.addEdgeToNonexistentPort(e.id,e.to));let t=this.findEdgeIdByElement(e.shape.element);if(t!==void 0)throw new m(h.addEdgeWithElementInUse(e.id,t));this.addEdgeInternal(e),this.afterEdgeAddedEmitter.emit(e.id)}updateEdge(e,t){if(!this.hasEdge(e))throw new m(h.updateNonexistentEdge(e));if(t.from!==void 0||t.to!==void 0){if(t.from!==void 0&&!this.hasPort(t.from))throw new m(h.updateNonexistentEdgeSource(e,t.from));if(t.to!==void 0&&!this.hasPort(t.to))throw new m(h.updateNonexistentEdgeTarget(e,t.to));let n=this.getEdge(e),r=n.payload;this.removeEdgeInternal(e),this.addEdgeInternal({id:e,from:t.from??n.from,to:t.to??n.to,shape:r.shape,priority:r.priority})}let n=this.edges.get(e);t.shape!==void 0&&(n.payload.shape=t.shape,this.afterEdgeShapeUpdatedEmitter.emit(e)),t.priority!==void 0&&(n.payload.priority=t.priority,this.afterEdgePriorityUpdatedEmitter.emit(e)),this.afterEdgeUpdatedEmitter.emit(e)}getAllEdgeIds(){return Array.from(this.edges.keys())}removeEdge(e){if(!this.hasEdge(e))throw new m(h.removeNonexistentEdge(e));this.beforeEdgeRemovedEmitter.emit(e),this.removeEdgeInternal(e)}clear(){this.beforeClearEmitter.emit(),this.portIncomingEdges.clear(),this.portOutgoingEdges.clear(),this.portCycleEdges.clear(),this.elementPorts.clear(),this.nodesElementsMap.clear(),this.edgesElementsMap.clear(),this.edges.clear(),this.ports.clear(),this.nodes.clear()}getPortIncomingEdgeIds(e){let t=this.portIncomingEdges.get(e);if(t===void 0)throw new m(h.accessEdgesForNonexistentPort(e));return Array.from(t)}getPortOutgoingEdgeIds(e){let t=this.portOutgoingEdges.get(e);if(t===void 0)throw new m(h.accessEdgesForNonexistentPort(e));return Array.from(t)}getPortCycleEdgeIds(e){let t=this.portCycleEdges.get(e);if(t===void 0)throw new m(h.accessEdgesForNonexistentPort(e));return Array.from(t)}getPortAdjacentEdgeIds(e){return[...this.getPortIncomingEdgeIds(e),...this.getPortOutgoingEdgeIds(e),...this.getPortCycleEdgeIds(e)]}getNodeIncomingEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(t=>{this.getPortIncomingEdgeIds(t).filter(t=>{let n=this.getEdge(t);return this.getPort(n.from).nodeId!==e}).forEach(e=>{n.push(e)})}),n}getNodeOutgoingEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(t=>{this.getPortOutgoingEdgeIds(t).filter(t=>{let n=this.getEdge(t);return this.getPort(n.to).nodeId!==e}).forEach(e=>{n.push(e)})}),n}getNodeCycleEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(t=>{this.getPortCycleEdgeIds(t).forEach(e=>{n.push(e)}),this.getPortIncomingEdgeIds(t).filter(t=>{let n=this.getEdge(t);return this.getPort(n.to).nodeId===e}).forEach(e=>{n.push(e)})}),n}getNodeAdjacentEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(e=>{this.getPortIncomingEdgeIds(e).forEach(e=>{n.push(e)}),this.getPortOutgoingEdgeIds(e).forEach(e=>{n.push(e)}),this.getPortCycleEdgeIds(e).forEach(e=>{n.push(e)})}),n}addEdgeInternal(e){this.edges.set(e.id,{from:e.from,to:e.to,payload:{shape:e.shape,priority:e.priority}}),this.edgesElementsMap.set(e.shape.element,e.id),e.from===e.to?this.portCycleEdges.get(e.from).add(e.id):(this.portOutgoingEdges.get(e.from).add(e.id),this.portIncomingEdges.get(e.to).add(e.id))}removeEdgeInternal(e){let{from:t,to:n,payload:r}=this.getEdge(e);this.portCycleEdges.get(t).delete(e),this.portCycleEdges.get(n).delete(e),this.portIncomingEdges.get(t).delete(e),this.portIncomingEdges.get(n).delete(e),this.portOutgoingEdges.get(t).delete(e),this.portOutgoingEdges.get(n).delete(e),this.edges.delete(e),this.edgesElementsMap.delete(r.shape.element)}},_=e=>({scale:1/e.scale,x:-e.x/e.scale,y:-e.y/e.scale}),v={scale:1,x:0,y:0},y=(e,t)=>({x:e.scale*t.x+e.x,y:e.scale*t.y+e.y}),b=class{host;viewportMatrix=v;contentMatrix=v;beforeUpdateEmitter;onBeforeUpdated;afterUpdateEmitter;onAfterUpdated;afterResizeEmitter;onAfterResize;observer=new ResizeObserver(()=>{this.afterResizeEmitter.emit()});constructor(e){this.host=e,[this.afterUpdateEmitter,this.onAfterUpdated]=d(),[this.beforeUpdateEmitter,this.onBeforeUpdated]=d(),[this.afterResizeEmitter,this.onAfterResize]=d(),this.observer.observe(this.host)}getViewportMatrix(){return this.viewportMatrix}getContentMatrix(){return this.contentMatrix}patchViewportMatrix(e){this.viewportMatrix={scale:e.scale??this.viewportMatrix.scale,x:e.x??this.viewportMatrix.x,y:e.y??this.viewportMatrix.y},this.beforeUpdateEmitter.emit(),this.contentMatrix=_(this.viewportMatrix),this.afterUpdateEmitter.emit()}patchContentMatrix(e){this.contentMatrix={scale:e.scale??this.contentMatrix.scale,x:e.x??this.contentMatrix.x,y:e.y??this.contentMatrix.y},this.beforeUpdateEmitter.emit(),this.viewportMatrix=_(this.contentMatrix),this.afterUpdateEmitter.emit()}getDimensions(){let{width:e,height:t}=this.host.getBoundingClientRect();return{width:e,height:t}}createContentCoords(e){return y(this.viewportMatrix,e)}createViewportCoords(e){return y(this.contentMatrix,e)}destroy(){this.observer.disconnect()}},x=class e{canvas;elementToNodeId=new Map;nodesResizeObserver;onAfterNodeAdded=e=>{let t=this.canvas.graph.getNode(e);this.elementToNodeId.set(t.element,e),this.nodesResizeObserver.observe(t.element)};onBeforeNodeRemoved=e=>{let t=this.canvas.graph.getNode(e);this.elementToNodeId.delete(t.element),this.nodesResizeObserver.unobserve(t.element)};reset=()=>{this.nodesResizeObserver.disconnect(),this.elementToNodeId.clear()};revert=()=>{this.reset()};constructor(e){this.canvas=e,this.nodesResizeObserver=new ResizeObserver(e=>{e.forEach(e=>{let t=e.target;this.handleNodeResize(t)})}),this.canvas.graph.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.canvas.graph.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.revert)}static configure(t){new e(t)}handleNodeResize(e){let t=this.elementToNodeId.get(e);this.canvas.updateNode(t)}},S=(e,t,n)=>{let{x:r,y:i,width:a,height:o}=e.getBoundingClientRect();return t>=r&&t<=r+a&&n>=i&&n<=i+o},ee=(e,t,n)=>t>=0&&t<=e.innerWidth&&n>=0&&n<=e.innerHeight,te=class{element;win;constructor(e,t){this.element=e,this.win=t}verify(e,t){return S(this.element,e,t)&&ee(this.win,e,t)}},C=(e,t)=>{t===null?e.style.removeProperty(`cursor`):e.style.cursor=t},w=e=>{let t=document.createElement(`div`);return{id:e.overlayNodeId,element:t,x:e.portCoords.x,y:e.portCoords.y,ports:[{id:e.overlayNodeId,element:t,direction:e.portDirection}]}},ne=(e,t)=>{let n=t;for(;n!==null;){let t=e.findPortIdsByElement(n)[0]??null;if(t!==null)return{status:`portFound`,portId:t};if(e.findNodeIdByElement(n)!==void 0)return{status:`nodeEncountered`};n=n.parentElement}return{status:`notFound`}};function*re(e,t){let n=e.elementsFromPoint(t.x,t.y);for(let e of n){if(e.shadowRoot!==null){let n=re(e.shadowRoot,t);for(let e of n)yield e}yield e}}var ie=(e,t)=>{let n=re(document,t);for(let t of n){let n=ne(e,t);if(n.status===`portFound`)return n.portId;if(n.status===`nodeEncountered`)return null}return null},T=function(e){return e.StaticNodeId=`static`,e.DraggingNodeId=`dragging`,e.EdgeId=`edge`,e}({}),ae=(e,t)=>({x:e/2,y:t/2}),E=(e,t,n)=>({x:t.x*e.x-t.y*e.y+((1-t.x)*n.x+t.y*n.y),y:t.y*e.x+t.x*e.y+((1-t.x)*n.y-t.y*n.x)}),oe=(e,t,n)=>{let r={x:e.x+e.width/2,y:e.y+e.height/2},i={x:t.x+t.width/2,y:t.y+t.height/2},a=Math.min(r.x,i.x)-n,o=Math.min(r.y,i.y)-n,s=2*n;return{x:a,y:o,width:Math.abs(i.x-r.x)+s,height:Math.abs(i.y-r.y)+s,from:{x:r.x-a,y:r.y-o},to:{x:i.x-a,y:i.y-o}}},D=.5*.5*.5,O=3*D,se=class{path;midpoint;constructor(e){let{from:t,to:n,arrowLength:r,fromDir:i,toDir:a,curvature:o,hasSourceArrow:s,hasTargetArrow:c}=e,l=E({x:t.x+r,y:t.y},i,t),u=E({x:n.x-r,y:n.y},a,n),d={x:l.x+i.x*o,y:l.y+i.y*o},f={x:u.x-a.x*o,y:u.y-a.y*o},p=D*l.x+O*d.x+O*f.x+D*u.x,m=D*l.y+O*d.y+O*f.y+D*u.y;this.midpoint={x:p,y:m};let h=`M ${l.x} ${l.y} C ${d.x} ${d.y}, ${f.x} ${f.y}, ${u.x} ${u.y}`,g=s?``:`M ${t.x} ${t.y} L ${l.x} ${l.y} `,_=c?``:` M ${u.x} ${u.y} L ${n.x} ${n.y}`;this.path=`${g}${h}${_}`}},ce=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,curvature:r,fromDir:i,toDir:a,detourDir:o,from:s,to:c,arrowLength:l,detourDistance:u}=e,d=t?E({x:s.x+l,y:s.y},i,s):s,f=n?E({x:c.x-l,y:c.y},a,c):c,p=Math.cos(o)*u,m=Math.sin(o)*u,h=E({x:s.x+l,y:s.y},i,s),g={x:h.x+p,y:h.y+m},_=E({x:c.x-l,y:c.y},a,c),v={x:_.x+p,y:_.y+m},y={x:(g.x+v.x)/2,y:(g.y+v.y)/2},b={x:h.x+r*i.x,y:h.y+r*i.y},x={x:_.x-r*a.x,y:_.y-r*a.y},S={x:h.x+p,y:h.y+m},ee={x:_.x+p,y:_.y+m};this.path=[`M ${d.x} ${d.y}`,`L ${h.x} ${h.y}`,`C ${b.x} ${b.y} ${S.x} ${S.y} ${y.x} ${y.y}`,`C ${ee.x} ${ee.y} ${x.x} ${x.y} ${_.x} ${_.y}`,`L ${f.x} ${f.y}`].join(` `),this.midpoint=y}},k=Object.freeze({edgeColor:`--edge-color`}),le=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return t.style.pointerEvents=`none`,t.style.position=`absolute`,t.style.top=`0`,t.style.left=`0`,t.style.overflow=`visible`,t.style.setProperty(k.edgeColor,e),t},ue=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`stroke`,`var(${k.edgeColor})`),t.setAttribute(`stroke-width`,`${e}`),t.setAttribute(`fill`,`none`),t},A=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return e.setAttribute(`fill`,`var(${k.edgeColor})`),e},de=(e,t)=>{e.style.transform=`translate(${t.x}px, ${t.y}px)`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`},j=(e,t)=>{let n=[];if(e.length>0&&n.push(`M ${e[0].x} ${e[0].y}`),e.length===2&&n.push(`L ${e[1].x} ${e[1].y}`),e.length>2){let r=e.length-1,i=0,a=0,o=0;e.forEach((s,c)=>{let l=0,u=0,d=0,f=c>0,p=c<r,m=f&&p;if(f&&(l=-i,u=-a,d=o),p){let t=e[c+1];i=t.x-s.x,a=t.y-s.y,o=Math.sqrt(i*i+a*a)}let h=o===0?0:Math.min((m?t:0)/o,c<r-1?.5:1),g=m?{x:s.x+i*h,y:s.y+a*h}:s,_=d===0?0:Math.min((m?t:0)/d,c>1?.5:1),v=m?{x:s.x+l*_,y:s.y+u*_}:s;c>0&&n.push(`L ${v.x} ${v.y}`),m&&n.push(`C ${s.x} ${s.y} ${s.x} ${s.y} ${g.x} ${g.y}`)})}return n.join(` `)},M=(e,t)=>{let n=e.linePoint,r=t.linePoint,i=r.x-n.x>=0,a=e.dir.x>=0;if(a===t.dir.x>=0){let o=a===i,s={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return o?{points:[e.arrowPoint,{x:s.x,y:n.y},{x:s.x,y:r.y},t.arrowPoint],midpoint:s}:{points:[e.arrowPoint,n,{x:n.x,y:s.y},{x:r.x,y:s.y},r,t.arrowPoint],midpoint:s}}let o=a===i,s=(n.y+r.y)/2;if(o){let i={x:r.x,y:n.y};return{points:[e.arrowPoint,i,r,t.arrowPoint],midpoint:{x:i.x,y:s}}}let c={x:n.x,y:r.y};return{points:[e.arrowPoint,n,c,t.arrowPoint],midpoint:{x:c.x,y:s}}},N=e=>({x:e.y,y:e.x}),fe=(e,t)=>{let n=M({arrowPoint:N(e.arrowPoint),linePoint:N(e.linePoint),dir:N(e.dir)},{arrowPoint:N(t.arrowPoint),linePoint:N(t.linePoint),dir:N(t.dir)});return{points:n.points.map(e=>N(e)),midpoint:N(n.midpoint)}},P=e=>{let t=[];for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n],a=i.x-r.x,o=i.y-r.y,s=Math.sqrt(a*a+o*o);t.push({start:r,end:i,distance:s})}let n=t.reduce((e,t)=>e+t.distance,0)/2,r=0;for(let e of t){let t=r+e.distance;if(t>=n){let t=n-r,{start:i,end:a,distance:o}=e;if(o===0)continue;let s=t/o,c=a.x-i.x,l=a.y-i.y;return{x:i.x+c*s,y:i.y+l*s}}r=t}if(r===0&&e.length>0)return e[0];throw Error(`Failed to calculate midpoint`)},pe=(e,t)=>{let n=e.linePoint,r=e.arrowPoint,i=t.linePoint,a=t.arrowPoint,o=t.dir.y>=0,s=e.dir.x>=0,c=i.y-n.y>=0,l=s===i.x-n.x>=0,u=o===c;if(l){if(u){let e={x:a.x,y:r.y};return{points:[r,e,a],midpoint:P([n,e,i])}}let e=(n.x+i.x)/2,t={x:e,y:n.y},o={x:e,y:i.y};return{points:[r,t,o,i,a],midpoint:P([n,t,o,i])}}if(u){let e=(n.y+i.y)/2,t={x:n.x,y:e},o={x:i.x,y:e};return{points:[r,n,t,o,a],midpoint:P([n,t,o,i])}}let d={x:n.x,y:i.y};return{points:[r,n,d,i,a],midpoint:P([n,d,i])}},me=(e,t)=>{let n=pe({arrowPoint:N(e.arrowPoint),linePoint:N(e.linePoint),dir:N(e.dir)},{arrowPoint:N(t.arrowPoint),linePoint:N(t.linePoint),dir:N(t.dir)});return{points:n.points.map(e=>N(e)),midpoint:N(n.midpoint)}},he=(e,t)=>{let n=Math.abs(e.dir.y)<1e-10,r=Math.abs(t.dir.y)<1e-10;return n?r?M(e,t):pe(e,t):r?me(e,t):fe(e,t)},ge=class{path;midpoint;constructor(e){let{from:t,to:n,fromDir:r,toDir:i,arrowLength:a,arrowOffset:o,roundness:s,hasSourceArrow:c,hasTargetArrow:l}=e,u=c?E({x:t.x+a,y:t.y},r,t):t,d=l?E({x:n.x-a,y:n.y},i,n):n,f=a+o,p=E({x:t.x+f,y:t.y},r,t),m=E({x:n.x-f,y:n.y},i,n),h=M({arrowPoint:u,linePoint:p,dir:r},{arrowPoint:d,linePoint:m,dir:i});this.path=j(h.points,s),this.midpoint=h.midpoint}},_e=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,from:r,to:i,arrowLength:a,fromDir:o,toDir:s,arrowOffset:c,detourDir:l,detourDistance:u,roundness:d}=e,f=t?E({x:r.x+a,y:r.y},o,r):r,p=n?E({x:i.x-a,y:i.y},s,i):i,m=a+c,h=Math.cos(l)*u,g=Math.sin(l)*u,_=E({x:r.x+m,y:r.y},o,r),v={x:_.x+h,y:_.y+g},y=E({x:i.x-m,y:i.y},s,i),b={x:y.x+h,y:y.y+g};this.midpoint={x:(v.x+b.x)/2,y:(v.y+b.y)/2},this.path=j([f,_,v,b,y,p],d)}},ve=class{path;midpoint;constructor(e){let{from:t,to:n,hasSourceArrow:r,hasTargetArrow:i,arrowLength:a,fromDir:o,toDir:s,arrowOffset:c,roundness:l}=e,u=this.createArrowPoint(r,o,t,a),d=this.createArrowPoint(i,s,n,-a),f=a+c,p=E({x:t.x+f,y:t.y},o,t),m=E({x:n.x-f,y:n.y},s,n);this.path=j([u,p,m,d],l);let h=(p.x+m.x)/2,g=(p.y+m.y)/2;this.midpoint={x:h,y:g}}createArrowPoint(e,t,n,r){return e?E({x:n.x+r,y:n.y},t,n):n}},ye=class{path;midpoint;constructor(e){let{from:t,to:n,hasSourceArrow:r,hasTargetArrow:i,arrowLength:a,arrowOffset:o,fromDir:s,toDir:c,roundness:l}=e,u=r?E({x:t.x+a,y:t.y},s,t):t,d=i?E({x:n.x-a,y:n.y},c,n):n,f=a+o,p=E({x:t.x+f,y:t.y},s,t),m=E({x:n.x-f,y:n.y},c,n),h=fe({arrowPoint:u,linePoint:p,dir:s},{arrowPoint:d,linePoint:m,dir:c});this.path=j(h.points,l),this.midpoint=h.midpoint}},be=class{path;midpoint;constructor(e){let{from:t,to:n,fromDir:r,toDir:i,arrowLength:a,arrowOffset:o,roundness:s,hasSourceArrow:c,hasTargetArrow:l}=e,u=c?E({x:t.x+a,y:t.y},r,t):t,d=l?E({x:n.x-a,y:n.y},i,n):n,f=a+o,p=E({x:t.x+f,y:t.y},r,t),m=E({x:n.x-f,y:n.y},i,n),h=he({arrowPoint:u,linePoint:p,dir:r},{arrowPoint:d,linePoint:m,dir:i});this.path=j(h.points,s),this.midpoint=h.midpoint}},F=class{path;midpoint;constructor(e){let{side:t,arrowLength:n,arrowOffset:r,dir:i,origin:a,hasArrow:o}=e,s=n+r,c=s+2*t,l=[{x:n,y:0},{x:s,y:0},{x:s,y:t},{x:c,y:t},{x:c,y:-t},{x:s,y:-t},{x:s,y:0},{x:n,y:0}].map(e=>E(e,i,{x:0,y:0})).map(e=>({x:e.x+a.x,y:e.y+a.y})),u=`M ${a.x} ${a.y} L ${l[0].x} ${l[0].y} `;this.path=`${o?``:u}${j(l,e.roundness)}`,this.midpoint={x:(l[3].x+l[4].x)/2,y:(l[3].y+l[4].y)/2}}},xe=class{path;midpoint;constructor(e){let{arrowLength:t,radius:n,smallRadius:r,dir:i,origin:a,hasArrow:o}=e,s=r+n,c=r*n/s,l=Math.sqrt(s*s-r*r),u=l*r/s,d=l+n+t,f=t+u,p=[{x:t,y:0},{x:f,y:c},{x:f,y:-c},{x:d,y:0}].map(e=>E(e,i,{x:0,y:0})).map(e=>({x:e.x+a.x,y:e.y+a.y})),m=[`M ${p[0].x} ${p[0].y}`,`A ${r} ${r} 0 0 1 ${p[1].x} ${p[1].y}`,`A ${n} ${n} 0 1 0 ${p[2].x} ${p[2].y}`,`A ${r} ${r} 0 0 1 ${p[0].x} ${p[0].y}`].join(` `),h=`M ${a.x} ${a.y} L ${p[0].x} ${p[0].y} `;this.path=`${o?``:h}${m}`,this.midpoint=p[3]}},Se=(e,t,n)=>{let r=Math.max(e.y,t.y),i=Math.min(e.y,t.y);return(n>=0?r:i)+n},Ce=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,arrowLength:r,from:i,to:a,fromDir:o,toDir:s,arrowOffset:c,roundness:l,detourDistance:u}=e,d=t?E({x:i.x+r,y:i.y},o,i):i,f=n?E({x:a.x-r,y:a.y},s,a):a,p=r+c,m=E({x:i.x+p,y:i.y},o,i),h=E({x:a.x-p,y:a.y},s,a),g=Se(m,h,u);this.midpoint={x:(m.x+h.x)/2,y:g},this.path=j([d,m,{x:m.x,y:g},{x:h.x,y:g},h,f],l)}},we=(e,t,n)=>{let r=Math.max(e.x,t.x),i=Math.min(e.x,t.x);return(n>=0?r:i)+n},Te=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,arrowLength:r,fromDir:i,toDir:a,from:o,to:s,arrowOffset:c,detourDistance:l,roundness:u}=e,d=t?E({x:o.x+r,y:o.y},i,o):o,f=n?E({x:s.x-r,y:s.y},a,s):s,p=r+c,m=E({x:o.x+p,y:o.y},i,o),h=E({x:s.x-p,y:s.y},a,s),g=we(m,h,l);this.midpoint={x:g,y:(m.y+h.y)/2},this.path=j([d,m,{x:g,y:m.y},{x:g,y:h.y},h,f],u)}},Ee=class{path;midpoint;constructor(e){let t=Math.abs(e.fromDir.y)<1e-10,n=Math.abs(e.toDir.y)<1e-10;if(t&&n){let t=new Ce(e);this.path=t.path,this.midpoint=t.midpoint;return}if(!t&&!n){let t=new Te(e);this.path=t.path,this.midpoint=t.midpoint;return}let r=new be(e);this.path=r.path,this.midpoint=r.midpoint}},I=Object.freeze({color:`#777777`,width:1,arrowLength:20,polygonArrowRadius:4,circleArrowRadius:8,wedgeArrowSmallRadius:20,wedgeArrowRadius:100,wedgeArrowAngle:Math.PI/12,arrowOffset:15,hasSourceArrow:!1,hasTargetArrow:!1,cycleRadius:30,cycleSquareSide:30,roundness:10,detourDistance:100,detourDirection:-Math.PI/2,detourDirectionVertical:0,smallCycleRadius:15,curvature:90,interactiveWidth:10,portOffset:0}),De=e=>({x:Math.cos(e),y:Math.sin(e)}),L=class{params;element;svg;group=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);line;sourceArrow=null;targetArrow=null;onAfterRender;afterRenderEmitter;arrowRenderer;constructor(e){this.params=e,[this.afterRenderEmitter,this.onAfterRender]=d(),this.arrowRenderer=this.params.arrowRenderer,this.element=le(e.color),this.svg=this.element,this.element.appendChild(this.group),this.line=ue(e.width),this.group.appendChild(this.line),e.hasSourceArrow&&(this.sourceArrow=A(),this.group.appendChild(this.sourceArrow)),e.hasTargetArrow&&(this.targetArrow=A(),this.group.appendChild(this.targetArrow))}render(e){let{x:n,y:r,width:i,height:a,from:o,to:s}=oe(e.from,e.to,this.params.padding);de(this.element,{x:n,y:r,width:i,height:a});let c=De(e.from.direction),l=De(e.to.direction),u={x:-l.x,y:-l.y},d;e.category===t.PortCycle?(d=this.params.createCyclePath,u=c):d=e.category===t.NodeCycle?this.params.createDetourPath:this.params.createLinePath;let f=d(o,s,c,l);this.line.setAttribute(`d`,f.path);let p=null;this.sourceArrow&&(p=this.arrowRenderer({direction:c,shift:o,arrowLength:this.params.arrowLength}),this.sourceArrow.setAttribute(`d`,p));let m=null;this.targetArrow&&(m=this.arrowRenderer({direction:u,shift:s,arrowLength:this.params.arrowLength}),this.targetArrow.setAttribute(`d`,m)),this.afterRenderEmitter.emit({edgePath:f,sourceArrowPath:p,targetArrowPath:m})}},Oe=e=>t=>{let n=[{x:0,y:0},{x:t.arrowLength,y:e.radius},{x:t.arrowLength,y:-e.radius}].map(e=>E(e,t.direction,{x:0,y:0})).map(e=>({x:e.x+t.shift.x,y:e.y+t.shift.y}));return`${`M ${n[0].x} ${n[0].y}`} ${`L ${n[1].x} ${n[1].y}`} ${`L ${n[2].x} ${n[2].y}`} Z`},ke=e=>t=>{let n=e.radius,r=t.arrowLength,i=(r*r+2*r*n)/(2*n),a=i+n,o=r+n-n*(r+n)/a,s=n*i/a,c=[{x:0,y:0},{x:o,y:-s},{x:o,y:s}].map(e=>E(e,t.direction,{x:0,y:0})).map(e=>({x:e.x+t.shift.x,y:e.y+t.shift.y}));return`${`M ${c[0].x} ${c[0].y}`} ${`A ${i} ${i} 0 0 0 ${c[1].x} ${c[1].y}`} ${`A ${n} ${n} 0 0 0 ${c[2].x} ${c[2].y}`} ${`A ${i} ${i} 0 0 0 ${c[0].x} ${c[0].y}`}`},Ae=e=>t=>{let n=e.smallRadius,r=e.radius,i=E({x:t.arrowLength,y:0},{x:Math.cos(e.angle),y:Math.sin(e.angle)},{x:t.arrowLength+e.smallRadius,y:0}),a=[{x:0,y:0},{x:i.x,y:-i.y},i].map(e=>E(e,t.direction,{x:0,y:0})).map(e=>({x:e.x+t.shift.x,y:e.y+t.shift.y}));return`${`M ${a[0].x} ${a[0].y}`} ${`A ${r} ${r} 0 0 1 ${a[1].x} ${a[1].y}`} ${`A ${n} ${n} 0 0 1 ${a[2].x} ${a[2].y}`} ${`A ${r} ${r} 0 0 1 ${a[0].x} ${a[0].y}`}`},R=e=>{if(typeof e==`function`)return e;switch(e.type){case`triangle`:return Oe({radius:e.radius??I.polygonArrowRadius});case`arc`:return ke({radius:e.radius??I.circleArrowRadius});default:return Ae({smallRadius:e.smallRadius??I.wedgeArrowSmallRadius,angle:e.angle??I.wedgeArrowAngle,radius:e.radius??I.wedgeArrowRadius})}},je=class{element;svg;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;curvature;portCycleRadius;portCycleSmallRadius;detourDirection;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new xe({origin:e,dir:n,radius:this.portCycleRadius,smallRadius:this.portCycleSmallRadius,arrowLength:this.arrowLength,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new ce({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,detourDir:this.detourDirection,detourDistance:this.detourDistance,curvature:this.curvature,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new se({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,curvature:this.curvature,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??I.arrowLength,this.curvature=e?.curvature??I.curvature,this.portCycleRadius=e?.cycleRadius??I.cycleRadius,this.portCycleSmallRadius=e?.smallCycleRadius??I.smallCycleRadius,this.detourDirection=e?.detourDirection??I.detourDirection,this.detourDistance=e?.detourDistance??I.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??I.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??I.hasTargetArrow,this.pathShape=new L({color:e?.color??I.color,width:e?.width??I.width,arrowRenderer:R(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.svg=this.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){this.pathShape.render(e)}},Me=e=>Math.cos(e)>0?0:Math.PI,Ne=class{element;svg;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;arrowOffset;roundness;cycleSquareSide;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new F({origin:e,dir:n,arrowLength:this.arrowLength,side:this.cycleSquareSide,arrowOffset:this.arrowOffset,roundness:this.roundness,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new Ce({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,detourDistance:this.detourDistance,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new ge({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??I.arrowLength,this.arrowOffset=e?.arrowOffset??I.arrowOffset,this.cycleSquareSide=e?.cycleSquareSide??I.cycleSquareSide;let t=e?.roundness??I.roundness;this.roundness=Math.min(t,this.arrowOffset,this.cycleSquareSide/2),this.detourDistance=e?.detourDistance??I.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??I.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??I.hasTargetArrow,this.pathShape=new L({color:e?.color??I.color,width:e?.width??I.width,arrowRenderer:R(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.svg=this.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){let{from:t,to:n,category:r}=e;this.pathShape.render({category:r,from:{...t,direction:Me(t.direction)},to:{...n,direction:Me(n.direction)}})}},Pe=class{element;svg;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;arrowOffset;roundness;cycleSquareSide;detourDirection;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new F({origin:e,dir:n,arrowLength:this.arrowLength,side:this.cycleSquareSide,arrowOffset:this.arrowOffset,roundness:this.roundness,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new _e({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,detourDir:this.detourDirection,detourDistance:this.detourDistance,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new ve({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??I.arrowLength,this.arrowOffset=e?.arrowOffset??I.arrowOffset,this.cycleSquareSide=e?.cycleSquareSide??I.cycleSquareSide;let t=e?.roundness??I.roundness;this.roundness=Math.min(t,this.arrowOffset,this.cycleSquareSide/2),this.detourDirection=e?.detourDirection??I.detourDirection,this.detourDistance=e?.detourDistance??I.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??I.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??I.hasTargetArrow,this.pathShape=new L({color:e?.color??I.color,width:e?.width??I.width,arrowRenderer:R(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.svg=this.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){this.pathShape.render(e)}},Fe=Math.PI/2,Ie=e=>Math.sin(e)>0?Fe:-Fe,Le=class{element;svg;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;arrowOffset;roundness;cycleSquareSide;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new F({origin:e,dir:n,arrowLength:this.arrowLength,side:this.cycleSquareSide,arrowOffset:this.arrowOffset,roundness:this.roundness,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new Te({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,detourDistance:this.detourDistance,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new ye({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??I.arrowLength,this.arrowOffset=e?.arrowOffset??I.arrowOffset,this.cycleSquareSide=e?.cycleSquareSide??I.cycleSquareSide;let t=e?.roundness??I.roundness;this.roundness=Math.min(t,this.arrowOffset,this.cycleSquareSide/2),this.detourDistance=e?.detourDistance??I.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??I.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??I.hasTargetArrow,this.pathShape=new L({color:e?.color??I.color,width:e?.width??I.width,arrowRenderer:R(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.svg=this.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){let{from:t,to:n,category:r}=e;this.pathShape.render({category:r,from:{...t,direction:Ie(t.direction)},to:{...n,direction:Ie(n.direction)}})}},Re=e=>{let t=e+Math.PI/4,n=Math.cos(t),r=Math.sin(t);return n>0?r>0?0:-Math.PI/2:r>0?Math.PI/2:Math.PI},ze=class{element;svg;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;arrowOffset;roundness;cycleSquareSide;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new F({origin:e,dir:n,arrowLength:this.arrowLength,side:this.cycleSquareSide,arrowOffset:this.arrowOffset,roundness:this.roundness,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new Ee({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,detourDistance:this.detourDistance,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new be({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??I.arrowLength,this.arrowOffset=e?.arrowOffset??I.arrowOffset,this.cycleSquareSide=e?.cycleSquareSide??I.cycleSquareSide;let t=e?.roundness??I.roundness;this.roundness=Math.min(t,this.arrowOffset,this.cycleSquareSide/2),this.detourDistance=e?.detourDistance??I.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??I.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??I.hasTargetArrow,this.pathShape=new L({color:e?.color??I.color,width:e?.width??I.width,arrowRenderer:R(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.svg=this.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){let{from:t,to:n,category:r}=e;this.pathShape.render({category:r,from:{...t,direction:Re(t.direction)},to:{...n,direction:Re(n.direction)}})}},Be=e=>{let{direction:t,radius:n}=e,{x:r,y:i}=t,{horizontal:a,vertical:o}=n,s=i/r,c=Math.abs(o/s),l=Math.abs(a*s),u=Math.min(a,c),d=Math.min(o,l);return Math.sqrt(u*u+d*d)},Ve=e=>typeof e==`number`?()=>e:e===`box`?Be:e,He=I.portOffset,z=class{element;svg;group=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);line;sourceArrow=null;targetArrow=null;color;width;arrowLength;sourceOffsetFn;targetOffsetFn;onAfterRender;afterRenderEmitter;arrowRenderer;constructor(e){[this.afterRenderEmitter,this.onAfterRender]=d(),this.color=e?.color??I.color,this.width=e?.width??I.width,this.arrowLength=e?.arrowLength??I.arrowLength,this.arrowRenderer=R(e?.arrowRenderer??{}),this.sourceOffsetFn=Ve(e?.sourceOffset??He),this.targetOffsetFn=Ve(e?.targetOffset??He),this.element=le(this.color),this.svg=this.element,this.element.appendChild(this.group),this.line=ue(this.width),this.group.appendChild(this.line),e?.hasSourceArrow&&(this.sourceArrow=A(),this.group.appendChild(this.sourceArrow)),e?.hasTargetArrow&&(this.targetArrow=A(),this.group.appendChild(this.targetArrow))}render(e){let{x:t,y:n,width:r,height:i,from:a,to:o}=oe(e.from,e.to,50);de(this.element,{x:t,y:n,width:r,height:i});let s=o.x-a.x,c=o.y-a.y,l=Math.sqrt(s*s+c*c);if(l===0){this.renderEmpty(a);return}let u={x:s/l,y:c/l},d=this.sourceOffsetFn({direction:{x:u.x,y:u.y},radius:{horizontal:e.from.width/2,vertical:e.from.height/2}}),f=this.targetOffsetFn({direction:{x:-u.x,y:-u.y},radius:{horizontal:e.to.width/2,vertical:e.to.height/2}}),p={x:a.x+d*u.x,y:a.y+d*u.y},m={x:o.x-f*u.x,y:o.y-f*u.y},h=this.sourceArrow===null?0:this.arrowLength,g={x:p.x+h*u.x,y:p.y+h*u.y},_=this.targetArrow===null?0:this.arrowLength,v={x:m.x-_*u.x,y:m.y-_*u.y},y={x:(p.x+m.x)/2,y:(p.y+m.y)/2},b=`M ${g.x} ${g.y} L ${v.x} ${v.y}`;this.line.setAttribute(`d`,b);let x=null,S=null;if(this.sourceArrow){let e={x:u.x*d+a.x,y:u.y*d+a.y};x=this.arrowRenderer({direction:u,shift:e,arrowLength:this.arrowLength}),this.sourceArrow.setAttribute(`d`,x)}if(this.targetArrow){let e={x:u.x*f,y:u.y*f};S=this.arrowRenderer({direction:{x:-u.x,y:-u.y},shift:{x:o.x-e.x,y:o.y-e.y},arrowLength:this.arrowLength}),this.targetArrow.setAttribute(`d`,S)}this.afterRenderEmitter.emit({edgePath:{path:b,midpoint:y},sourceArrowPath:x,targetArrowPath:S})}renderEmpty(e){let t=null,n=null;this.line.setAttribute(`d`,``),this.sourceArrow!==null&&(t=``,this.sourceArrow.setAttribute(`d`,t)),this.targetArrow!==null&&(n=``,this.targetArrow.setAttribute(`d`,n)),this.afterRenderEmitter.emit({edgePath:{path:``,midpoint:e},sourceArrowPath:t,targetArrowPath:n})}},Ue=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);return e.style.pointerEvents=`auto`,e.style.cursor=`pointer`,e},We=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`stroke`,`transparent`),t.setAttribute(`stroke-width`,`${e}`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke-linecap`,`round`),t},Ge=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`stroke-width`,`${e}`),t.setAttribute(`fill`,`transparent`),t.setAttribute(`stroke`,`transparent`),t},Ke=class extends Error{constructor(e){super(e),this.name=`InteractiveEdgeError`}},qe=class e{baseEdge;element;svg;group;line;sourceArrow;targetArrow;handle=Ue();onAfterRender;interactiveLine;interactiveSourceArrow=null;interactiveTargetArrow=null;constructor(t,n){if(this.baseEdge=t,t instanceof e)throw new Ke(`interactive edge can be configured only once`);this.element=this.baseEdge.element,this.svg=this.element,this.group=this.baseEdge.group,this.line=this.baseEdge.line,this.sourceArrow=this.baseEdge.sourceArrow,this.targetArrow=this.baseEdge.targetArrow,this.onAfterRender=this.baseEdge.onAfterRender;let r=n?.distance??I.interactiveWidth;this.interactiveLine=We(r),this.handle.appendChild(this.interactiveLine),this.sourceArrow&&(this.interactiveSourceArrow=Ge(r),this.handle.appendChild(this.interactiveSourceArrow)),this.targetArrow&&(this.interactiveTargetArrow=Ge(r),this.handle.appendChild(this.interactiveTargetArrow)),this.group.appendChild(this.handle),this.baseEdge.onAfterRender.subscribe(e=>{this.interactiveLine.setAttribute(`d`,e.edgePath.path),this.interactiveSourceArrow&&this.interactiveSourceArrow.setAttribute(`d`,e.sourceArrowPath),this.interactiveTargetArrow&&this.interactiveTargetArrow.setAttribute(`d`,e.targetArrowPath)})}render(e){this.baseEdge.render(e)}},Je=class{baseShape;midpointElement;group;line;sourceArrow;targetArrow;onAfterRender;element;svg;constructor(e,t){this.baseShape=e,this.midpointElement=t,this.element=this.baseShape.element,this.svg=this.element,this.group=this.baseShape.group,this.line=this.baseShape.line,this.sourceArrow=this.baseShape.sourceArrow,this.targetArrow=this.baseShape.targetArrow,this.onAfterRender=this.baseShape.onAfterRender,this.element.append(this.midpointElement),this.baseShape.onAfterRender.subscribe(e=>{let t=e.edgePath.midpoint,n=`translate(${t.x}px, ${t.y}px)`;this.midpointElement.style.setProperty(`transform`,n)})}render(e){this.baseShape.render(e)}},Ye=class{graphStore;onAfterNodeAdded;onAfterNodeUpdated;onAfterNodePriorityUpdated;onBeforeNodeRemoved;onAfterPortMarked;onAfterPortUpdated;onBeforePortUnmarked;onAfterEdgeAdded;onAfterEdgeShapeUpdated;onAfterEdgeUpdated;onAfterEdgePriorityUpdated;onBeforeEdgeRemoved;onBeforeClear;constructor(e){this.graphStore=e,this.onAfterNodeAdded=this.graphStore.onAfterNodeAdded,this.onAfterNodeUpdated=this.graphStore.onAfterNodeUpdated,this.onAfterNodePriorityUpdated=this.graphStore.onAfterNodePriorityUpdated,this.onBeforeNodeRemoved=this.graphStore.onBeforeNodeRemoved,this.onAfterPortMarked=this.graphStore.onAfterPortAdded,this.onAfterPortUpdated=this.graphStore.onAfterPortUpdated,this.onBeforePortUnmarked=this.graphStore.onBeforePortRemoved,this.onAfterEdgeAdded=this.graphStore.onAfterEdgeAdded,this.onAfterEdgeShapeUpdated=this.graphStore.onAfterEdgeShapeUpdated,this.onAfterEdgeUpdated=this.graphStore.onAfterEdgeUpdated,this.onAfterEdgePriorityUpdated=this.graphStore.onAfterEdgePriorityUpdated,this.onBeforeEdgeRemoved=this.graphStore.onBeforeEdgeRemoved,this.onBeforeClear=this.graphStore.onBeforeClear}hasNode(e){return this.graphStore.hasNode(e)}getNode(e){let t=this.graphStore.getNode(e),{payload:n}=t;return{element:t.element,x:n.x,y:n.y,centerFn:n.centerFn,priority:n.priority}}findNodeIdByElement(e){return this.graphStore.findNodeIdByElement(e)}getAllNodeIds(){return this.graphStore.getAllNodeIds()}hasPort(e){return this.graphStore.hasPort(e)}getPort(e){let t=this.graphStore.getPort(e);return{element:t.element,direction:t.payload.direction,nodeId:t.nodeId}}getAllPortIds(){return this.graphStore.getAllPortIds()}getNodePortIds(e){return this.graphStore.getNodePortIds(e)}findPortIdsByElement(e){return this.graphStore.findPortIdsByElement(e)}getAllEdgeIds(){return this.graphStore.getAllEdgeIds()}hasEdge(e){return this.graphStore.hasEdge(e)}getEdge(e){let t=this.graphStore.getEdge(e),{payload:n}=t;return{from:t.from,to:t.to,priority:n.priority,shape:n.shape}}findEdgeIdByElement(e){return this.graphStore.findEdgeIdByElement(e)}getPortIncomingEdgeIds(e){return this.graphStore.getPortIncomingEdgeIds(e)}getPortOutgoingEdgeIds(e){return this.graphStore.getPortOutgoingEdgeIds(e)}getPortCycleEdgeIds(e){return this.graphStore.getPortCycleEdgeIds(e)}getPortAdjacentEdgeIds(e){return this.graphStore.getPortAdjacentEdgeIds(e)}getNodeIncomingEdgeIds(e){return this.graphStore.getNodeIncomingEdgeIds(e)}getNodeOutgoingEdgeIds(e){return this.graphStore.getNodeOutgoingEdgeIds(e)}getNodeCycleEdgeIds(e){return this.graphStore.getNodeCycleEdgeIds(e)}getNodeAdjacentEdgeIds(e){return this.graphStore.getNodeAdjacentEdgeIds(e)}},B=class{checkExists;counter=0;constructor(e){this.checkExists=e}create(e){if(e!==void 0)return e;for(;this.checkExists(this.counter);)this.counter++;return this.counter}reset(){this.counter=0}},Xe=class{graphStore;htmlView;params;nodeIdGenerator=new B(e=>this.graphStore.hasNode(e));portIdGenerator=new B(e=>this.graphStore.hasPort(e));edgeIdGenerator=new B(e=>this.graphStore.hasEdge(e));onAfterNodeAdded=e=>{this.htmlView.attachNode(e)};onAfterNodeUpdated=e=>{this.htmlView.updateNodePosition(e),this.graphStore.getNodeAdjacentEdgeIds(e).forEach(e=>{this.htmlView.renderEdge(e)})};onAfterNodePriorityUpdated=e=>{this.htmlView.updateNodePriority(e)};onBeforeNodeRemoved=e=>{this.graphStore.getNodePortIds(e).forEach(e=>{this.unmarkPort(e)}),this.htmlView.detachNode(e)};onAfterPortUpdated=e=>{this.graphStore.getPortAdjacentEdgeIds(e).forEach(e=>{this.htmlView.renderEdge(e)})};onBeforePortUnmarked=e=>{this.graphStore.getPortAdjacentEdgeIds(e).forEach(e=>{this.removeEdge(e)})};onAfterEdgeAdded=e=>{this.htmlView.attachEdge(e)};onAfterEdgeShapeUpdated=e=>{this.htmlView.updateEdgeShape(e)};onAfterEdgeUpdated=e=>{this.htmlView.renderEdge(e)};onAfterEdgePriorityUpdated=e=>{this.htmlView.updateEdgePriority(e)};onBeforeEdgeRemoved=e=>{this.htmlView.detachEdge(e)};onBeforeClear=()=>{this.nodeIdGenerator.reset(),this.portIdGenerator.reset(),this.edgeIdGenerator.reset(),this.htmlView.clear()};constructor(e,t,n){this.graphStore=e,this.htmlView=t,this.params=n,this.graphStore.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.graphStore.onAfterNodeUpdated.subscribe(this.onAfterNodeUpdated),this.graphStore.onAfterNodePriorityUpdated.subscribe(this.onAfterNodePriorityUpdated),this.graphStore.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.graphStore.onAfterPortUpdated.subscribe(this.onAfterPortUpdated),this.graphStore.onBeforePortRemoved.subscribe(this.onBeforePortUnmarked),this.graphStore.onAfterEdgeAdded.subscribe(this.onAfterEdgeAdded),this.graphStore.onAfterEdgeShapeUpdated.subscribe(this.onAfterEdgeShapeUpdated),this.graphStore.onAfterEdgeUpdated.subscribe(this.onAfterEdgeUpdated),this.graphStore.onAfterEdgePriorityUpdated.subscribe(this.onAfterEdgePriorityUpdated),this.graphStore.onBeforeEdgeRemoved.subscribe(this.onBeforeEdgeRemoved),this.graphStore.onBeforeClear.subscribe(this.onBeforeClear)}addNode(e){let t=this.nodeIdGenerator.create(e.id);if(this.graphStore.addNode({id:t,element:e.element,x:e.x??null,y:e.y??null,centerFn:e.centerFn??this.params.nodes.centerFn,priority:e.priority??this.params.nodes.priorityFn()}),e.ports!==void 0)for(let n of e.ports)this.markPort({id:n.id,element:n.element,nodeId:t,direction:n.direction})}updateNode(e,t){this.graphStore.updateNode(e,t??{})}removeNode(e){this.graphStore.removeNode(e)}markPort(e){let t=this.portIdGenerator.create(e.id);this.graphStore.addPort({id:t,element:e.element,nodeId:e.nodeId,direction:e.direction??this.params.ports.direction})}updatePort(e,t){this.graphStore.updatePort(e,t??{})}unmarkPort(e){this.graphStore.removePort(e)}addEdge(e){let t=this.edgeIdGenerator.create(e.id);this.graphStore.addEdge({id:t,from:e.from,to:e.to,shape:e.shape??this.params.edges.shapeFactory(t),priority:e.priority??this.params.edges.priorityFn()})}updateEdge(e,t){this.graphStore.updateEdge(e,t??{})}removeEdge(e){this.graphStore.removeEdge(e)}clear(){this.graphStore.clear()}destroy(){this.graphStore.onAfterNodeAdded.unsubscribe(this.onAfterNodeAdded),this.graphStore.onAfterNodeUpdated.unsubscribe(this.onAfterNodeUpdated),this.graphStore.onAfterNodePriorityUpdated.unsubscribe(this.onAfterNodePriorityUpdated),this.graphStore.onBeforeNodeRemoved.unsubscribe(this.onBeforeNodeRemoved),this.graphStore.onAfterPortUpdated.unsubscribe(this.onAfterPortUpdated),this.graphStore.onBeforePortRemoved.unsubscribe(this.onBeforePortUnmarked),this.graphStore.onAfterEdgeAdded.unsubscribe(this.onAfterEdgeAdded),this.graphStore.onAfterEdgeShapeUpdated.unsubscribe(this.onAfterEdgeShapeUpdated),this.graphStore.onAfterEdgeUpdated.unsubscribe(this.onAfterEdgeUpdated),this.graphStore.onAfterEdgePriorityUpdated.unsubscribe(this.onAfterEdgePriorityUpdated),this.graphStore.onBeforeEdgeRemoved.unsubscribe(this.onBeforeEdgeRemoved),this.graphStore.onBeforeClear.unsubscribe(this.onBeforeClear),this.htmlView.destroy()}},Ze=e=>{setTimeout(()=>{e()})},Qe=e=>{queueMicrotask(()=>{e()})},V=e=>{e()},$e=class{viewportStore;onBeforeUpdated;onAfterUpdated;onAfterResize;constructor(e){this.viewportStore=e,this.onBeforeUpdated=this.viewportStore.onBeforeUpdated,this.onAfterUpdated=this.viewportStore.onAfterUpdated,this.onAfterResize=this.viewportStore.onAfterResize}getViewportMatrix(){return{...this.viewportStore.getViewportMatrix()}}getContentMatrix(){return{...this.viewportStore.getContentMatrix()}}getDimensions(){return this.viewportStore.getDimensions()}createContentCoords(e){return this.viewportStore.createContentCoords(e)}createViewportCoords(e){return this.viewportStore.createViewportCoords(e)}},et=(e,t)=>Symbol.iterator in e?{minContentScale:t.focus.minContentScale,nodes:e,contentPadding:t.focus.contentPadding,animationDuration:t.focus.animationDuration}:{minContentScale:e.minContentScale??t.focus.minContentScale,nodes:e.nodes??[],contentPadding:e.contentPadding??e.contentOffset??t.focus.contentPadding,animationDuration:e.animationDuration??t.focus.animationDuration},tt=(e,t,n)=>({scale:e.scale,x:e.x+e.scale*t,y:e.y+e.scale*n}),nt=(e,t,n,r)=>({scale:e.scale*t,x:e.scale*(1-t)*n+e.x,y:e.scale*(1-t)*r+e.y}),rt=class{graphStore;viewportStore;params;win;constructor(e,t,n,r){this.graphStore=e,this.viewportStore=t,this.params=n,this.win=r}patchViewportMatrix(e){this.viewportStore.patchViewportMatrix(e)}patchContentMatrix(e){this.viewportStore.patchContentMatrix(e)}center(e,t){let{width:n,height:r}=this.viewportStore.getDimensions(),i={x:n/2,y:r/2},a=this.viewportStore.getViewportMatrix(),o=this.viewportStore.createViewportCoords(e),s=tt(a,o.x-i.x,o.y-i.y),c=t?.contentScale;if(c!==void 0){let e=1/c;s=nt(s,e/a.scale,i.x,i.y)}let l=t?.animationDuration??0;l>0?this.animateNavigation(a,s,l):this.viewportStore.patchViewportMatrix(s)}focus(e){let t=et(e??{},this.params);this.params.focus.schedule(()=>{this.navigate(t)})}destroy(){this.viewportStore.destroy()}navigate(e){let t=1/0,n=-1/0,r=1/0,i=-1/0,a=0,o=new Set;for(let t of e.nodes)o.add(t);if(this.graphStore.getAllNodeIds().forEach(e=>{let{payload:s}=this.graphStore.getNode(e);s.x!==null&&s.y!==null&&(o.size===0||o.has(e))&&(t=Math.min(s.x,t),n=Math.max(s.x,n),r=Math.min(s.y,r),i=Math.max(s.y,i),a++)}),a>0){t-=e.contentPadding,r-=e.contentPadding,n+=e.contentPadding,i+=e.contentPadding;let a={x:(t+n)/2,y:(r+i)/2},{scale:o}=this.viewportStore.getContentMatrix(),s=(i-r)*o,c=(n-t)*o,{width:l,height:u}=this.viewportStore.getDimensions(),d=Math.max(c/l,s/u),f=d>1?o/d:o,p=Math.max(f,e.minContentScale);this.center(a,{contentScale:p,animationDuration:e.animationDuration})}}animateNavigation(e,t,n){let r,i={scale:t.scale-e.scale,x:t.x-e.x,y:t.y-e.y},a=t=>{r===void 0&&(r=t);let o=Math.min((t-r)/n,1);this.viewportStore.patchViewportMatrix({scale:e.scale+o*i.scale,x:e.x+o*i.x,y:e.y+o*i.y}),o<1&&this.win.requestAnimationFrame(a)};this.win.requestAnimationFrame(a)}},it=(e,t,n)=>{let r=new g;return new f(new Ye(r),new $e(t),new Xe(r,new o(r,t,e),{nodes:{centerFn:ae,priorityFn:()=>0},edges:{shapeFactory:()=>new z,priorityFn:()=>0},ports:{direction:0}}),new rt(r,t,{focus:{contentPadding:0,minContentScale:0,schedule:V,animationDuration:0}},n))},H=Symbol(),at=class e{canvas;window;pointInsideVerifier;eventTagger;params;onAfterPortMarked=e=>{let t=this.canvas.graph.getPort(e);this.canvas.graph.findPortIdsByElement(t.element).length===1&&this.hookPortEvents(t.element)};onBeforePortUnmarked=e=>{let t=this.canvas.graph.getPort(e);this.canvas.graph.findPortIdsByElement(t.element).length===1&&this.unhookPortEvents(t.element)};onPortMouseDown=e=>{let t=e;if(!this.params.mouseDownEventVerifier(t))return;let n=e.currentTarget,r=this.canvas.graph.findPortIdsByElement(n)[0];this.params.onPointerDownVerifier(r,{x:t.clientX,y:t.clientY})&&(this.eventTagger.tag(e,H),this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0}))};onWindowMouseMove=e=>{if(!this.pointInsideVerifier.verify(e.clientX,e.clientY)){this.removeWindowMouseListeners(),this.params.onPointerOutside();return}this.params.onPointerMove({x:e.clientX,y:e.clientY})};onWindowMouseUp=e=>{this.params.mouseUpEventVerifier(e)&&(this.removeWindowMouseListeners(),this.params.onPointerUp({x:e.clientX,y:e.clientY}))};onPortTouchStart=e=>{let t=e;if(t.touches.length!==1)return;let n=t.touches[0],r=e.currentTarget,i=this.canvas.graph.findPortIdsByElement(r)[0];this.params.onPointerDownVerifier(i,{x:n.clientX,y:n.clientY})&&(this.eventTagger.tag(e,H),this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchFinish,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchFinish,{passive:!0}))};onWindowTouchMove=e=>{let t=e.touches[0];if(!this.pointInsideVerifier.verify(t.clientX,t.clientY)){this.removeWindowTouchListeners(),this.params.onPointerOutside();return}this.params.onPointerMove({x:t.clientX,y:t.clientY})};onWindowTouchFinish=e=>{this.removeWindowTouchListeners();let t=e.changedTouches[0];this.params.onPointerUp({x:t.clientX,y:t.clientY})};reset=()=>{this.canvas.graph.getAllPortIds().forEach(e=>{let t=this.canvas.graph.getPort(e);this.unhookPortEvents(t.element)})};revert=()=>{this.removeWindowMouseListeners(),this.removeWindowTouchListeners(),this.reset()};constructor(e,t,n,r,i){this.canvas=e,this.window=t,this.pointInsideVerifier=n,this.eventTagger=r,this.params=i,this.canvas.graph.onAfterPortMarked.subscribe(this.onAfterPortMarked),this.canvas.graph.onBeforePortUnmarked.subscribe(this.onBeforePortUnmarked),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.revert)}static configure(t,n,r,i,a){new e(t,n,r,i,a)}hookPortEvents(e){e.addEventListener(`mousedown`,this.onPortMouseDown,{passive:!0}),e.addEventListener(`touchstart`,this.onPortTouchStart,{passive:!0})}unhookPortEvents(e){e.removeEventListener(`mousedown`,this.onPortMouseDown),e.removeEventListener(`touchstart`,this.onPortTouchStart)}removeWindowMouseListeners(){this.window.removeEventListener(`mousemove`,this.onWindowMouseMove),this.window.removeEventListener(`mouseup`,this.onWindowMouseUp)}removeWindowTouchListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchFinish),this.window.removeEventListener(`touchcancel`,this.onWindowTouchFinish)}},U=Symbol(),ot=class{has(e,t){let n=e[U];return n!==void 0&&n.has(t)}tag(e,t){let n=e,r=n[U];r===void 0?n[U]=new Set([t]):r.add(t)}},W=Symbol(),G=class{window;pointInsideVerifier;onSelected;mouseDownEventVerifier;mouseUpEventVerifier;movementThreshold;selectionCandidate=null;previousMouse=null;previousTouch=null;movedDistance=0;onElementMouseDown=e=>{let t=e;this.mouseDownEventVerifier(t)&&(this.selectionCandidate=t.currentTarget,this.previousMouse={x:t.clientX,y:t.clientY},this.movedDistance=0,this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0}))};onElementTouchStart=e=>{let t=e,n=t.touches;n.length===1&&(this.selectionCandidate=t.currentTarget,this.previousTouch=n[0],this.movedDistance=0,this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchEnd,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchCancel,{passive:!0}))};onWindowMouseMove=e=>{let t=e;if(!this.pointInsideVerifier.verify(t.clientX,t.clientY)){this.removeWindowMouseListeners();return}let n=this.previousMouse,r=t.clientX-n.x,i=t.clientY-n.y;this.previousMouse={x:t.clientX,y:t.clientY},this.processMoveThresholdVerification(r,i,()=>{this.removeWindowMouseListeners()})};onWindowMouseUp=e=>{let t=e;this.mouseUpEventVerifier(t)&&(this.removeWindowMouseListeners(),this.onSelected(this.selectionCandidate,e))};onWindowTouchMove=e=>{let t=e.touches;if(t.length!==1){this.removeWindowTouchListeners();return}let n=t[0];if(!this.pointInsideVerifier.verify(n.clientX,n.clientY)){this.removeWindowTouchListeners();return}let r=this.previousTouch,i=n.clientX-r.clientX,a=n.clientY-r.clientY;this.previousTouch=n,this.processMoveThresholdVerification(i,a,()=>{this.removeWindowTouchListeners()})};onWindowTouchEnd=e=>{this.removeWindowTouchListeners(),this.onSelected(this.selectionCandidate,e)};onWindowTouchCancel=()=>{this.removeWindowTouchListeners()};constructor(e,t,n){this.window=e,this.pointInsideVerifier=t,this.mouseDownEventVerifier=n.mouseDownEventVerifier,this.mouseUpEventVerifier=n.mouseUpEventVerifier,this.onSelected=n.onSelected,this.movementThreshold=n.movementThreshold}enable(e){e.addEventListener(`mousedown`,this.onElementMouseDown),e.addEventListener(`touchstart`,this.onElementTouchStart)}disable(e){e.removeEventListener(`mousedown`,this.onElementMouseDown),e.removeEventListener(`touchstart`,this.onElementTouchStart),e===this.selectionCandidate&&(this.removeWindowMouseListeners(),this.removeWindowTouchListeners())}removeWindowMouseListeners(){this.window.removeEventListener(`mousemove`,this.onWindowMouseMove),this.window.removeEventListener(`mouseup`,this.onWindowMouseUp)}removeWindowTouchListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchEnd),this.window.removeEventListener(`touchcancel`,this.onWindowTouchCancel)}processMoveThresholdVerification(e,t,n){let r=Math.sqrt(e*e+t*t);this.movedDistance+=r,this.movedDistance>this.movementThreshold&&n()}},K=(e,t)=>({from:e.isDirect?e.staticPortId:t,to:e.isDirect?t:e.staticPortId}),st=class{graph;connectionAllowedVerifier;constructor(e,t){this.graph=e,this.connectionAllowedVerifier=t}resolve(e){let t,n=1/0,{cursor:r}=e;return this.graph.getAllPortIds().forEach(i=>{let{element:a,direction:o,nodeId:s}=this.graph.getPort(i),{x:c,y:l}=this.graph.getNode(s);if(c===null||l===null)return;let u=K(e,i);if(!this.connectionAllowedVerifier(u))return;let{top:d,left:f,width:p,height:m}=a.getBoundingClientRect(),h={x:f+p/2,y:d+m/2},g=r.x-h.x,_=r.y-h.y,v=Math.sqrt(g*g+_*_);v<n&&(n=v,t=o)}),t}},ct=class{direction;constructor(e){this.direction=e}resolve(){return this.direction}},lt=class e{canvas;element;window;pointInsideVerifier;eventTagger;params;grabbedNodeState=null;maxNodePriority=0;graph;onAfterNodeAdded=e=>{this.updateMaxNodePriority(e);let{element:t}=this.graph.getNode(e);t.addEventListener(`mousedown`,this.onMouseDown,{passive:!0}),t.addEventListener(`touchstart`,this.onTouchStart,{passive:!0})};onAfterNodeUpdated=e=>{this.updateMaxNodePriority(e)};onBeforeNodeRemoved=e=>{let{element:t}=this.graph.getNode(e);t.removeEventListener(`mousedown`,this.onMouseDown),t.removeEventListener(`touchstart`,this.onTouchStart)};onMouseDown=e=>{if(this.eventTagger.has(e,H))return;let t=e;if(!this.params.mouseDownEventVerifier(t))return;let n=e.currentTarget,r=this.graph.findNodeIdByElement(n),i=this.graph.getNode(r);if(!this.params.nodeDragVerifier(r))return;this.eventTagger.tag(e,H),this.params.onNodeDragStarted(r);let a=this.calculateContentPoint({x:t.clientX,y:t.clientY});this.grabbedNodeState={nodeId:r,dx:a.x-i.x,dy:a.y-i.y},C(this.element,this.params.dragCursor),this.moveNodeOnTop(r),this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0})};onTouchStart=e=>{if(this.eventTagger.has(e,H))return;let t=e;if(t.touches.length!==1)return;let n=t.touches[0],r=e.currentTarget,i=this.canvas.graph.findNodeIdByElement(r),a=this.graph.getNode(i);if(!this.params.nodeDragVerifier({nodeId:i,element:a.element,x:a.x,y:a.y}))return;this.eventTagger.tag(e,H);let o=this.calculateContentPoint({x:n.clientX,y:n.clientY});this.grabbedNodeState={nodeId:i,dx:o.x-a.x,dy:o.y-a.y},this.moveNodeOnTop(i),this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchFinish,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchFinish,{passive:!0})};onWindowMouseMove=e=>{if(!this.pointInsideVerifier.verify(e.clientX,e.clientY)){this.stopMouseDrag();return}this.moveNode(this.grabbedNodeState,{x:e.clientX,y:e.clientY})};onWindowMouseUp=e=>{this.params.mouseUpEventVerifier(e)&&this.stopMouseDrag()};onWindowTouchMove=e=>{if(e.touches.length!==1)return;let t=e.touches[0];if(!this.pointInsideVerifier.verify(t.clientX,t.clientY)){this.stopTouchDrag();return}this.moveNode(this.grabbedNodeState,{x:t.clientX,y:t.clientY})};onWindowTouchFinish=()=>{this.stopTouchDrag()};reset=()=>{this.canvas.graph.getAllNodeIds().forEach(e=>{let{element:t}=this.canvas.graph.getNode(e);t.removeEventListener(`mousedown`,this.onMouseDown),t.removeEventListener(`touchstart`,this.onTouchStart)}),this.maxNodePriority=0};revert=()=>{this.reset(),this.removeMouseDragListeners(),this.removeTouchDragListeners()};constructor(e,t,n,r,i,a){this.canvas=e,this.element=t,this.window=n,this.pointInsideVerifier=r,this.eventTagger=i,this.params=a,this.graph=e.graph,this.graph.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.graph.onAfterNodeUpdated.subscribe(this.onAfterNodeUpdated),this.graph.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.revert)}static configure(t,n,r,i,a,o){new e(t,n,r,i,a,o)}moveNode(e,t){if(!this.graph.hasNode(e.nodeId))return;let n=this.calculateContentPoint(t),r={x:n.x-e.dx,y:n.y-e.dy},i=this.adjustNodeCoords(r);this.canvas.updateNode(e.nodeId,{x:i.x,y:i.y}),this.params.onNodeDrag(e.nodeId)}moveNodeOnTop(e){if(this.params.moveOnTop){if(this.maxNodePriority++,this.params.moveEdgesOnTop){let t=this.maxNodePriority;this.maxNodePriority++,this.graph.getNodeAdjacentEdgeIds(e).forEach(e=>{this.canvas.updateEdge(e,{priority:t})})}this.canvas.updateNode(e,{priority:this.maxNodePriority})}}stopMouseDrag(){this.finishDrag(),C(this.element,null),this.removeMouseDragListeners()}removeMouseDragListeners(){this.window.removeEventListener(`mouseup`,this.onWindowMouseUp),this.window.removeEventListener(`mousemove`,this.onWindowMouseMove)}stopTouchDrag(){this.finishDrag(),this.removeTouchDragListeners()}removeTouchDragListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchFinish),this.window.removeEventListener(`touchcancel`,this.onWindowTouchFinish)}updateMaxNodePriority(e){let t=this.graph.getNode(e).priority;this.maxNodePriority=Math.max(this.maxNodePriority,t)}calculateContentPoint(e){let t=this.element.getBoundingClientRect();return this.canvas.viewport.createContentCoords({x:e.x-t.x,y:e.y-t.y})}adjustNodeCoords(e){let t=this.params.gridSize;if(t!==null){let n=t/2;return{x:Math.floor((e.x+n)/t)*t,y:Math.floor((e.y+n)/t)*t}}return e}finishDrag(){let e=this.grabbedNodeState.nodeId;this.graph.hasNode(e)&&this.params.onNodeDragFinished(e),this.grabbedNodeState=null}},q=e=>{let t=[],n=e.touches.length;for(let r=0;r<n;r++)t.push([e.touches[r].clientX,e.touches[r].clientY]);let r=t.reduce((e,t)=>[e[0]+t[0],e[1]+t[1]],[0,0]),i=[r[0]/n,r[1]/n],a=t.map(e=>[e[0]-i[0],e[1]-i[1]]).reduce((e,t)=>e+Math.sqrt(t[0]*t[0]+t[1]*t[1]),0);return{x:i[0],y:i[1],scale:a/n,touchesCnt:n,touches:t}},ut=class e{canvas;element;window;pointInsideVerifier;eventTagger;params;viewport;prevTouches=null;wheelFinishTimer=null;transformInProgress=!1;revert=()=>{this.removeMouseDragListeners(),this.removeTouchDragListeners()};onMouseDown=e=>{this.eventTagger.has(e,H)||this.params.mouseDownEventVerifier(e)&&(C(this.element,this.params.shiftCursor),this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0}),this.startRegisteredTransform())};onWindowMouseMove=e=>{let t=this.pointInsideVerifier.verify(e.clientX,e.clientY);if(this.element===null||!t){this.stopMouseDrag();return}let n=-e.movementX,r=-e.movementY;this.moveViewport(n,r)};onWindowMouseUp=e=>{this.params.mouseUpEventVerifier(e)&&this.stopMouseDrag()};onWheelScroll=e=>{if(!this.params.mouseWheelEventVerifier(e))return;let{left:t,top:n}=this.element.getBoundingClientRect(),r=e.clientX-t,i=e.clientY-n,a=1/(e.deltaY<0?this.params.wheelSensitivity:1/this.params.wheelSensitivity);this.wheelFinishTimer===null&&this.params.onTransformStarted(),this.scaleViewport(a,r,i),this.wheelFinishTimer!==null&&clearTimeout(this.wheelFinishTimer),this.wheelFinishTimer=setTimeout(()=>{this.transformInProgress||this.params.onTransformFinished(),this.wheelFinishTimer=null},this.params.scaleWheelFinishTimeout)};onTouchStart=e=>{if(!this.eventTagger.has(e,H)){if(this.prevTouches!==null){this.prevTouches=q(e);return}this.prevTouches=q(e),this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchFinish,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchFinish,{passive:!0}),this.startRegisteredTransform()}};onWindowTouchMove=e=>{let t=q(e);if(!t.touches.every(e=>this.pointInsideVerifier.verify(e[0],e[1]))){this.stopTouchDrag();return}if(t.touchesCnt===1||t.touchesCnt===2){let{x:e,y:n}=this.prevTouches,r=t.x-e,i=t.y-n;this.moveViewport(-r,-i)}if(t.touchesCnt===2){let{left:e,top:n}=this.element.getBoundingClientRect(),r=this.prevTouches.x-e,i=this.prevTouches.y-n,a=1/(t.scale/this.prevTouches.scale);this.scaleViewport(a,r,i)}this.prevTouches=t};onWindowTouchFinish=e=>{e.touches.length>0?this.prevTouches=q(e):this.stopTouchDrag()};preventWheelScaleListener=e=>{e.preventDefault()};constructor(e,t,n,r,i,a){this.canvas=e,this.element=t,this.window=n,this.pointInsideVerifier=r,this.eventTagger=i,this.params=a,this.element.addEventListener(`wheel`,this.preventWheelScaleListener,{passive:!1}),this.viewport=e.viewport,this.handleResize(),this.viewport.onAfterResize.subscribe(()=>{this.handleResize()}),this.element.addEventListener(`mousedown`,this.onMouseDown,{passive:!0}),this.element.addEventListener(`wheel`,this.onWheelScroll,{passive:!0}),this.element.addEventListener(`touchstart`,this.onTouchStart,{passive:!0}),e.onBeforeDestroy.subscribe(this.revert)}static configure(t,n,r,i,a,o){new e(t,n,r,i,a,o)}moveViewport(e,t){let n=this.viewport.getViewportMatrix(),r=tt(n,e,t),{width:i,height:a}=this.viewport.getDimensions(),o=this.params.transformPreprocessor({prevTransform:n,nextTransform:r,canvasWidth:i,canvasHeight:a});this.performTransform(o)}scaleViewport(e,t,n){let r=this.canvas.viewport.getViewportMatrix(),i=nt(r,e,t,n),{width:a,height:o}=this.viewport.getDimensions(),s=this.params.transformPreprocessor({prevTransform:r,nextTransform:i,canvasWidth:a,canvasHeight:o});this.performTransform(s)}stopMouseDrag(){C(this.element,null),this.removeMouseDragListeners(),this.finishRegisteredTransform()}removeMouseDragListeners(){this.window.removeEventListener(`mousemove`,this.onWindowMouseMove),this.window.removeEventListener(`mouseup`,this.onWindowMouseUp)}stopTouchDrag(){this.prevTouches=null,this.removeTouchDragListeners(),this.finishRegisteredTransform()}removeTouchDragListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchFinish),this.window.removeEventListener(`touchcancel`,this.onWindowTouchFinish)}performTransform(e){this.params.onBeforeTransformChange(),this.canvas.patchViewportMatrix(e),this.params.onTransformChange()}startRegisteredTransform(){this.transformInProgress=!0,this.params.onTransformStarted()}finishRegisteredTransform(){this.transformInProgress=!1,this.params.onTransformFinished()}handleResize(){let e=this.viewport.getViewportMatrix(),{width:t,height:n}=this.viewport.getDimensions(),r=this.params.transformPreprocessor({prevTransform:e,nextTransform:e,canvasWidth:t,canvasHeight:n});this.params.onResizeTransformStarted(),this.canvas.patchViewportMatrix(r),this.params.onResizeTransformFinished()}},dt=class e{canvas;element;window;trigger;pointInsideVerifier;params;nodeHorizontal;nodeVertical;viewport;currentScale;loadedArea={xFrom:1/0,xTo:1/0,yFrom:1/0,yTo:1/0};updateLoadedArea=e=>{this.loadedArea={xFrom:e.x,xTo:e.x+e.width,yFrom:e.y,yTo:e.y+e.height}};onAfterViewportUpdated=()=>{this.userTransformInProgress||this.loadAreaAroundViewport()};userTransformInProgress=!1;constructor(e,t,n,r,i,a,o,s){this.canvas=e,this.element=t,this.window=n,this.trigger=i,this.pointInsideVerifier=a,this.params=s,this.nodeHorizontal=this.params.nodeVerticalRadius,this.nodeVertical=this.params.nodeHorizontalRadius,this.viewport=e.viewport,this.currentScale=this.viewport.getViewportMatrix().scale,this.scheduleLoadAreaAroundViewport(),this.viewport.onAfterResize.subscribe(()=>{this.scheduleLoadAreaAroundViewport()});let c={...r,onResizeTransformStarted:()=>{this.userTransformInProgress=!0,r.onResizeTransformStarted()},onResizeTransformFinished:()=>{this.userTransformInProgress=!1,r.onResizeTransformFinished()},onBeforeTransformChange:()=>{this.userTransformInProgress=!0,r.onBeforeTransformChange()},onTransformChange:()=>{this.userTransformInProgress=!1;let e=this.currentScale;this.currentScale=this.viewport.getViewportMatrix().scale,e!==this.currentScale&&this.scheduleEnsureViewportAreaLoaded(),r.onTransformChange()},onTransformFinished:()=>{this.scheduleLoadAreaAroundViewport(),r.onTransformFinished()}};ut.configure(e,this.element,this.window,this.pointInsideVerifier,o,c),this.trigger.subscribe(this.updateLoadedArea),this.canvas.viewport.onAfterUpdated.subscribe(this.onAfterViewportUpdated)}static configure(t,n,r,i,a,o,s,c){new e(t,n,r,i,a,o,s,c)}scheduleLoadAreaAroundViewport(){setTimeout(()=>{this.loadAreaAroundViewport()})}scheduleEnsureViewportAreaLoaded(){setTimeout(()=>{let{width:e,height:t}=this.viewport.getDimensions(),{scale:n,x:r,y:i}=this.viewport.getViewportMatrix(),a=e*n,o=t*n,s=r-this.nodeHorizontal,c=i-this.nodeVertical,l=r+a+this.nodeHorizontal,u=i+o+this.nodeVertical;this.loadedArea.xFrom<s&&this.loadedArea.xTo>l&&this.loadedArea.yFrom<c&&this.loadedArea.yTo>u||this.loadAreaAroundViewport()})}loadAreaAroundViewport(){let{width:e,height:t}=this.viewport.getDimensions(),{scale:n,x:r,y:i}=this.viewport.getViewportMatrix(),a=e*n,o=t*n,s=r-a-this.nodeHorizontal,c=i-o-this.nodeVertical,l=3*a+2*this.nodeHorizontal,u=3*o+2*this.nodeVertical;this.trigger.emit({x:s,y:c,width:l,height:u})}},ft=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return e.style.position=`absolute`,e.style.inset=`0`,e},pt=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);return e.setAttribute(`fill`,`url(#pattern)`),e},mt=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);return e.setAttribute(`id`,`pattern`),e},ht=class e{canvas;backgroundHost;svg=ft();patternRenderingRectangle=pt();pattern=mt();patternContent;tileWidth;tileHeight;halfTileWidth;halfTileHeight;maxViewportScale;visible=!1;onAfterTransformUpdated=()=>{let e=this.canvas.viewport.getContentMatrix(),t=e.x-this.halfTileWidth*e.scale,n=e.y-this.halfTileHeight*e.scale,r=`matrix(${e.scale}, 0, 0, ${e.scale}, ${t}, ${n})`;this.pattern.setAttribute(`patternTransform`,r),this.updateVisibility()};constructor(e,t,n){this.canvas=e,this.backgroundHost=n,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.halfTileWidth=this.tileWidth/2,this.halfTileHeight=this.tileHeight/2,this.patternContent=t.renderer,this.maxViewportScale=t.maxViewportScale;let r=`translate(${this.halfTileWidth}, ${this.halfTileHeight})`;this.patternContent.setAttribute(`transform`,r),this.pattern.appendChild(this.patternContent);let i=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`);i.appendChild(this.pattern),this.svg.appendChild(i),this.svg.appendChild(this.patternRenderingRectangle),this.updateDimensions(),this.canvas.viewport.onAfterResize.subscribe(()=>{this.updateDimensions()}),this.canvas.viewport.onAfterUpdated.subscribe(this.onAfterTransformUpdated),this.onAfterTransformUpdated()}static configure(t,n,r){new e(t,n,r)}updateVisibility(){let{scale:e}=this.canvas.viewport.getViewportMatrix(),t=e>this.maxViewportScale;t&&this.visible?(this.visible=!1,this.backgroundHost.removeChild(this.svg)):!t&&!this.visible&&(this.visible=!0,this.backgroundHost.appendChild(this.svg))}updateDimensions(){let{width:e,height:t}=this.canvas.viewport.getDimensions();if(this.svg.setAttribute(`width`,`${e}`),this.svg.setAttribute(`height`,`${t}`),this.patternRenderingRectangle.setAttribute(`width`,`${e}`),this.patternRenderingRectangle.setAttribute(`height`,`${t}`),e>0&&t>0){let n=this.tileWidth/e,r=this.tileHeight/t;this.pattern.setAttribute(`width`,`${n}`),this.pattern.setAttribute(`height`,`${r}`)}}},gt=class e{canvas;overlayLayer;viewportStore;window;pointInsideVerifier;eventTagger;params;overlayCanvas;edgeInProgress=null;onEdgeCreated=e=>{this.params.onAfterEdgeCreated(e)};constructor(e,t,n,r,i,a,o){this.canvas=e,this.overlayLayer=t,this.viewportStore=n,this.window=r,this.pointInsideVerifier=i,this.eventTagger=a,this.params=o,this.overlayCanvas=it(this.overlayLayer,this.viewportStore,this.window);let s={mouseDownEventVerifier:this.params.mouseDownEventVerifier,mouseUpEventVerifier:this.params.mouseUpEventVerifier,onPointerDownVerifier:(e,t)=>{let n=this.params.connectionTypeResolver(e);return n===null?!1:(this.grabPort(e,t,n),!0)},onPointerMove:e=>{this.moveDraggingPort(e)},onPointerUp:e=>{this.tryCreateConnection(e),this.resetDragState()},onPointerOutside:()=>{let e=this.edgeInProgress;this.resetDragState(),this.params.onEdgeCreationInterrupted(e)}};at.configure(this.canvas,this.window,this.pointInsideVerifier,this.eventTagger,s)}static configure(t,n,r,i,a,o,s){new e(t,n,r,i,a,o,s)}grabPort(e,t,n){let r=this.canvas.graph.getPort(e),i=r.element.getBoundingClientRect(),a=i.x+i.width/2,o=i.y+i.height/2,s=this.overlayLayer.getBoundingClientRect(),c=this.canvas.viewport.createContentCoords({x:a-s.x,y:o-s.y}),l=this.canvas.viewport.createContentCoords({x:t.x-s.x,y:t.y-s.y}),u={overlayNodeId:T.StaticNodeId,portCoords:c,portDirection:r.direction},d=n===`direct`;this.edgeInProgress={staticPortId:e,isDirect:d};let f=this.params.draggingPortDirectionResolver.resolve({cursor:t,...this.edgeInProgress}),p={overlayNodeId:T.DraggingNodeId,portCoords:l,portDirection:f??r.direction},[m,h]=d?[u,p]:[p,u];this.overlayCanvas.addNode(w(m)),this.overlayCanvas.addNode(w(h)),this.overlayCanvas.addEdge({from:m.overlayNodeId,to:h.overlayNodeId,shape:this.params.edgeShapeFactory(T.EdgeId)})}resetDragState(){this.edgeInProgress=null,this.overlayCanvas.clear()}tryCreateConnection(e){let t=ie(this.canvas.graph,e);if(t===null){this.params.onEdgeCreationInterrupted(this.edgeInProgress);return}let n=K(this.edgeInProgress,t),r=this.params.connectionAllowedVerifier(n),i=this.params.connectionPreprocessor({from:n.from,to:n.to});r&&i!==null?(this.canvas.graph.onAfterEdgeAdded.subscribe(this.onEdgeCreated),this.canvas.addEdge(i),this.canvas.graph.onAfterEdgeAdded.unsubscribe(this.onEdgeCreated)):this.params.onEdgeCreationPrevented(n)}moveDraggingPort(e){let t=this.overlayLayer.getBoundingClientRect(),n=this.canvas.viewport.createContentCoords({x:e.x-t.x,y:e.y-t.y}),r=this.params.draggingPortDirectionResolver.resolve({cursor:e,...this.edgeInProgress});this.overlayCanvas.updateNode(T.DraggingNodeId,{x:n.x,y:n.y}).updatePort(T.DraggingNodeId,{direction:r})}},_t=class e{canvas;overlayLayer;viewportStore;window;pointInsideVerifier;eventTagger;params;overlayCanvas;edgeInProgress=null;draggingEdgePayload=null;onEdgeReattached=e=>{this.params.onAfterEdgeReattached(e)};constructor(e,t,n,r,i,a,o){this.canvas=e,this.overlayLayer=t,this.viewportStore=n,this.window=r,this.pointInsideVerifier=i,this.eventTagger=a,this.params=o,this.overlayCanvas=it(this.overlayLayer,this.viewportStore,this.window);let s={mouseDownEventVerifier:this.params.mouseDownEventVerifier,mouseUpEventVerifier:this.params.mouseUpEventVerifier,onPointerDownVerifier:(e,t)=>this.tryStartEdgeDragging(e,t),onPointerMove:e=>{this.moveDraggingPort(e)},onPointerUp:e=>{this.tryCreateConnection(e),this.resetDragState()},onPointerOutside:()=>{let e=this.draggingEdgePayload;this.resetDragState(),this.params.onEdgeReattachInterrupted({id:e.id,from:e.from,to:e.to,shape:e.shape,priority:e.priority})}};at.configure(this.canvas,this.window,this.pointInsideVerifier,this.eventTagger,s)}static configure(t,n,r,i,a,o,s){new e(t,n,r,i,a,o,s)}tryStartEdgeDragging(e,t){let n=this.params.draggingEdgeResolver(e);if(n===null)return!1;let r=this.canvas.graph.getEdge(n),i=e===r.from,a=e===r.to,o=i?r.to:r.from;this.edgeInProgress={staticPortId:o,isDirect:a};let s=this.canvas.graph.getPort(e),c=this.canvas.graph.getPort(o),l=c.element.getBoundingClientRect(),u={x:l.x+l.width/2,y:l.y+l.height/2},d=this.overlayLayer.getBoundingClientRect(),f=this.canvas.viewport.createContentCoords({x:u.x-d.x,y:u.y-d.y}),p=this.canvas.viewport.createContentCoords({x:t.x-d.x,y:t.y-d.y});this.draggingEdgePayload={id:n,from:r.from,to:r.to,shape:r.shape,priority:r.priority},this.canvas.removeEdge(n);let m={overlayNodeId:T.StaticNodeId,portCoords:f,portDirection:c.direction},h=this.params.draggingPortDirectionResolver.resolve({cursor:t,...this.edgeInProgress}),g={overlayNodeId:T.DraggingNodeId,portCoords:p,portDirection:h??s.direction},[_,v]=a?[m,g]:[g,m];this.overlayCanvas.addNode(w(_)),this.overlayCanvas.addNode(w(v));let y=this.params.draggingEdgeShapeFactory===null?r.shape:this.params.draggingEdgeShapeFactory(T.EdgeId);return this.overlayCanvas.addEdge({id:T.EdgeId,from:_.overlayNodeId,to:v.overlayNodeId,shape:y}),!0}resetDragState(){this.draggingEdgePayload=null,this.edgeInProgress=null,this.overlayCanvas.clear()}moveDraggingPort(e){let t=this.overlayLayer.getBoundingClientRect(),n={x:e.x-t.x,y:e.y-t.y},r=this.canvas.viewport.createContentCoords(n),i=this.params.draggingPortDirectionResolver.resolve({cursor:e,...this.edgeInProgress});this.overlayCanvas.updateNode(T.DraggingNodeId,{x:r.x,y:r.y}).updatePort(T.DraggingNodeId,{direction:i})}tryCreateConnection(e){let t=ie(this.canvas.graph,e);if(this.overlayCanvas.removeEdge(T.EdgeId),t===null){let e=this.draggingEdgePayload;this.params.onEdgeReattachInterrupted({id:e.id,from:e.from,to:e.to,shape:e.shape,priority:e.priority});return}let{from:n,to:r}=K(this.edgeInProgress,t),i=this.draggingEdgePayload,a={id:i.id,from:n,to:r,shape:i.shape,priority:i.priority},o=this.params.connectionAllowedVerifier({from:n,to:r}),s=this.params.connectionPreprocessor(a);if(o&&s!==null)this.canvas.graph.onAfterEdgeAdded.subscribe(this.onEdgeReattached),this.canvas.addEdge(s),this.canvas.graph.onAfterEdgeAdded.unsubscribe(this.onEdgeReattached);else{let e=this.draggingEdgePayload;this.params.onEdgeReattachPrevented({id:e.id,from:e.from,to:e.to,shape:e.shape,priority:e.priority})}}},vt=class e{applier;trigger;constructor(e,t){this.applier=e,this.trigger=t,this.trigger.subscribe(()=>{this.applier.apply()})}static configure(t,n){new e(t,n)}},yt=class e{graph;applier;defererFn;applyScheduled=!1;apply=()=>{this.applyScheduled=!1,this.applier.apply()};constructor(e,t,n){this.graph=e,this.applier=t,this.defererFn=n,this.graph.onAfterNodeAdded.subscribe(()=>{this.scheduleApply()}),this.graph.onBeforeNodeRemoved.subscribe(()=>{this.scheduleApply()}),this.graph.onAfterEdgeAdded.subscribe(()=>{this.scheduleApply()}),this.graph.onBeforeEdgeRemoved.subscribe(()=>{this.scheduleApply()})}static configure(t,n,r){new e(t,n,r)}scheduleApply(){this.applyScheduled||(this.applyScheduled=!0,this.defererFn(this.apply))}},bt=class{canvas;layoutAlgorithm;params;constructor(e,t,n){this.canvas=e,this.layoutAlgorithm=t,this.params=n}apply(){let e=this.layoutAlgorithm.calculateCoordinates({graph:this.canvas.graph,viewport:this.canvas.viewport});this.params.onBeforeApplied(),e.forEach((e,t)=>{this.params.staticNodeResolver(t)||this.canvas.updateNode(t,e)}),this.params.onAfterApplied()}},xt=class{static configure(e,t){let n=t.applyOn,r=new bt(e,t.algorithm,{staticNodeResolver:t.staticNodeResolver,onBeforeApplied:t.onBeforeApplied,onAfterApplied:t.onAfterApplied});switch(n.type){case`trigger`:vt.configure(r,n.trigger);break;case`topologyChangeSchedule`:yt.configure(e.graph,r,n.schedule);break}}},St=class{win;callback;previousTimeStamp=void 0;step=e=>{if(this.previousTimeStamp===void 0)this.previousTimeStamp=e;else{let t=(e-this.previousTimeStamp)/1e3;this.previousTimeStamp=e,this.callback(t)}this.win.requestAnimationFrame(this.step)};constructor(e,t){this.win=e,this.callback=t,this.win.requestAnimationFrame(this.step)}},Ct=class{canvas;layoutAlgorithm;params;constructor(e,t,n){this.canvas=e,this.layoutAlgorithm=t,this.params=n}apply(e){let t=this.layoutAlgorithm.calculateNextCoordinates({graph:this.canvas.graph,viewport:this.canvas.viewport,dt:e});this.params.onBeforeApplied(),t.forEach((e,t)=>{this.params.staticNodeResolver(t)||this.canvas.updateNode(t,e)}),this.params.onAfterApplied()}},wt=class e{win;applier;step=e=>{this.applier.apply(e)};constructor(e,t,n){this.win=n,this.applier=new Ct(e,t.algorithm,{staticNodeResolver:t.staticNodeResolver,onBeforeApplied:t.onBeforeApplied,onAfterApplied:t.onAfterApplied}),new St(this.win,this.step)}static configure(t,n,r){new e(t,n,r)}},Tt=class e{canvas;window;pointInsideVerifier;eventTagger;configurator;onNodeSelected;eventHandledTag=W;onAfterNodeAdded=e=>{let{element:t}=this.canvas.graph.getNode(e);this.configurator.enable(t)};onBeforeNodeRemoved=e=>{let{element:t}=this.canvas.graph.getNode(e);this.configurator.disable(t)};reset=()=>{this.canvas.graph.getAllNodeIds().forEach(e=>{let{element:t}=this.canvas.graph.getNode(e);this.configurator.disable(t)})};constructor(e,t,n,r,i){this.canvas=e,this.window=t,this.pointInsideVerifier=n,this.eventTagger=r,this.onNodeSelected=i.onNodeSelected,this.configurator=new G(this.window,this.pointInsideVerifier,{onSelected:(e,t)=>{let n=this.canvas.graph.findNodeIdByElement(e);this.eventTagger.tag(t,this.eventHandledTag),this.onNodeSelected(n)},movementThreshold:i.movementThreshold,mouseDownEventVerifier:i.mouseDownEventVerifier,mouseUpEventVerifier:i.mouseUpEventVerifier}),this.canvas.graph.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.canvas.graph.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.reset)}static configure(t,n,r,i,a){new e(t,n,r,i,a)}},Et=class e{canvas;window;pointInsideVerifier;eventTagger;configurator;eventHandledTag=W;onEdgeSelected;onAfterEdgeAdded=e=>{let{shape:t}=this.canvas.graph.getEdge(e);this.configurator.enable(t.element)};onBeforeEdgeRemoved=e=>{let{shape:t}=this.canvas.graph.getEdge(e);this.configurator.disable(t.element)};reset=()=>{this.canvas.graph.getAllEdgeIds().forEach(e=>{let{shape:t}=this.canvas.graph.getEdge(e);this.configurator.disable(t.element)})};constructor(e,t,n,r,i){this.canvas=e,this.window=t,this.pointInsideVerifier=n,this.eventTagger=r,this.onEdgeSelected=i.onEdgeSelected,this.configurator=new G(this.window,this.pointInsideVerifier,{onSelected:(e,t)=>{let n=this.canvas.graph.findEdgeIdByElement(e);this.eventTagger.tag(t,this.eventHandledTag),this.onEdgeSelected(n)},movementThreshold:i.movementThreshold,mouseDownEventVerifier:i.mouseDownEventVerifier,mouseUpEventVerifier:i.mouseUpEventVerifier}),this.canvas.graph.onAfterEdgeAdded.subscribe(this.onAfterEdgeAdded),this.canvas.graph.onBeforeEdgeRemoved.subscribe(this.onBeforeEdgeRemoved),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.reset)}static configure(t,n,r,i,a){new e(t,n,r,i,a)}},Dt=class e{canvas;element;window;pointInsideVerifier;eventTagger;configurator;onCanvasSelected;eventHandledTag=W;constructor(e,t,n,r,i,a){this.canvas=e,this.element=t,this.window=n,this.pointInsideVerifier=r,this.eventTagger=i,this.onCanvasSelected=a.onCanvasSelected,this.configurator=new G(this.window,this.pointInsideVerifier,{onSelected:(e,t)=>{this.eventTagger.has(t,this.eventHandledTag)||this.onCanvasSelected()},movementThreshold:a.movementThreshold,mouseDownEventVerifier:a.mouseDownEventVerifier,mouseUpEventVerifier:a.mouseUpEventVerifier}),this.configurator.enable(this.element),this.canvas.onBeforeDestroy.subscribe(()=>{this.configurator.disable(this.element)})}static configure(t,n,r,i,a,o){new e(t,n,r,i,a,o)}},Ot=()=>{let e=document.createElement(`div`);return e.style.width=`100%`,e.style.height=`100%`,e.style.position=`relative`,e},kt=()=>{let e=document.createElement(`div`);return e.style.position=`absolute`,e.style.inset=`0`,e},At=()=>{let e=kt();return e.style.pointerEvents=`none`,e},jt=class{element;background=kt();main=kt();overlayConnectablePorts=At();overlayDraggableEdges=At();host=Ot();constructor(e){this.element=e,this.element.appendChild(this.host),this.host.appendChild(this.background),this.host.appendChild(this.main),this.host.appendChild(this.overlayConnectablePorts),this.host.appendChild(this.overlayDraggableEdges)}destroy(){this.host.removeChild(this.background),this.host.removeChild(this.main),this.host.removeChild(this.overlayConnectablePorts),this.host.removeChild(this.overlayDraggableEdges),this.element.removeChild(this.host)}},J=Object.freeze({seed:`HTMLGraph is awesome`,maxTimeDeltaSec:.01,nodeCharge:1e5,nodeMass:1,edgeEquilibriumLength:300,edgeStiffness:1e3,dtSec:.01,maxIterations:1e3,convergenceVelocity:10,maxForce:1e7,nodeForceCoefficient:1,barnesHutAreaRadiusThreshold:.01,barnesHutTheta:1}),Y=Object.freeze({mouseDownEventVerifier:e=>e.button===0,mouseUpEventVerifier:e=>e.button===0,movementThreshold:10}),X=()=>{},Mt=(e,t,n)=>e===`closest-connectable-port`||e===`nearest-connectable-port`?new st(t,n):new ct(e),Nt=e=>{if(typeof e==`function`)return e;switch(e.type){case`straight`:return()=>new Pe({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowOffset:e.arrowOffset,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleSquareSide:e.cycleSquareSide,roundness:e.roundness,detourDistance:e.detourDistance,detourDirection:e.detourDirection});case`horizontal`:return()=>new Ne({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowOffset:e.arrowOffset,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleSquareSide:e.cycleSquareSide,roundness:e.roundness,detourDistance:e.detourDistance});case`vertical`:return()=>new Le({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowOffset:e.arrowOffset,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleSquareSide:e.cycleSquareSide,roundness:e.roundness,detourDistance:e.detourDistance});case`orthogonal`:return()=>new ze({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowOffset:e.arrowOffset,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleSquareSide:e.cycleSquareSide,roundness:e.roundness,detourDistance:e.detourDistance});case`direct`:return()=>new z({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,sourceOffset:e.sourceOffset,targetOffset:e.targetOffset});default:return()=>new je({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleRadius:e.cycleRadius,smallCycleRadius:e.smallCycleRadius,curvature:e.curvature,detourDistance:e.detourDistance,detourDirection:e.detourDirection})}},Pt=e=>{let t=e.nodeDragVerifier??(()=>!0),n=e.moveOnTop!==!1,r=e.moveEdgesOnTop!==!1&&n,i=e.mouse?.dragCursor,a=i===void 0?`grab`:i,o=e.mouse?.mouseDownEventVerifier,s=o===void 0?e=>e.button===0:o,c=e.mouse?.mouseUpEventVerifier,l=c===void 0?e=>e.button===0:c;return{moveOnTop:n,moveEdgesOnTop:r,dragCursor:a,gridSize:e.gridSize??null,mouseDownEventVerifier:s,mouseUpEventVerifier:l,onNodeDragStarted:e.events?.onNodeDragStarted??X,onNodeDrag:e.events?.onNodeDrag??X,nodeDragVerifier:t,onNodeDragFinished:e.events?.onNodeDragFinished??X}},Ft=e=>{let t=e.minX===null?-1/0:e.minX,n=e.maxX===null?1/0:e.maxX,r=e.minY===null?-1/0:e.minY,i=e.maxY===null?1/0:e.maxY;return e=>{let a=e.nextTransform.x,o=e.nextTransform.y;a<t&&a<e.prevTransform.x&&(a=Math.min(e.prevTransform.x,t));let s=n-e.canvasWidth*e.prevTransform.scale;a>s&&a>e.prevTransform.x&&(a=Math.max(e.prevTransform.x,s)),o<r&&o<e.prevTransform.y&&(o=Math.min(e.prevTransform.y,r));let c=i-e.canvasHeight*e.prevTransform.scale;return o>c&&o>e.prevTransform.y&&(o=Math.max(e.prevTransform.y,c)),{scale:e.nextTransform.scale,x:a,y:o}}},It=e=>{let t=e.maxContentScale,n=e.minContentScale,r=t===null?0:1/t,i=n===null?1/0:1/n;return e=>{let t=e.prevTransform,n=e.nextTransform,a=n.scale,o=n.x,s=n.y;if(n.scale>i&&n.scale>t.scale){a=Math.max(t.scale,i);let e=(a-t.scale)/(n.scale-t.scale);o=t.x+(n.x-t.x)*e,s=t.y+(n.y-t.y)*e}if(n.scale<r&&n.scale<t.scale){a=Math.min(t.scale,r);let e=(a-t.scale)/(n.scale-t.scale);o=t.x+(n.x-t.x)*e,s=t.y+(n.y-t.y)*e}return{scale:a,x:o,y:s}}},Lt=e=>t=>e.reduce((e,n)=>n({prevTransform:t.prevTransform,nextTransform:e,canvasWidth:t.canvasWidth,canvasHeight:t.canvasHeight}),t.nextTransform),Rt=e=>{if(typeof e==`function`)return e;switch(e.type){case`scale-limit`:return It({minContentScale:e.minContentScale??0,maxContentScale:e.maxContentScale??1/0});case`shift-limit`:return Ft({minX:e.minX??-1/0,maxX:e.maxX??1/0,minY:e.minY??-1/0,maxY:e.maxY??1/0})}},zt=e=>{let t=e?.scale?.mouseWheelSensitivity,n=t===void 0?1.2:t,r=e?.transformPreprocessor,i;i=r===void 0?e=>e.nextTransform:Array.isArray(r)?Lt(r.map(e=>Rt(e))):Rt(r);let a=e?.shift?.cursor===void 0?`grab`:e.shift.cursor,o=e?.shift?.mouseDownEventVerifier,s=o===void 0?e=>e.button===0:o,c=e?.shift?.mouseUpEventVerifier,l=c===void 0?e=>e.button===0:c,u=e?.scale?.mouseWheelEventVerifier,d=u===void 0?()=>!0:u;return{wheelSensitivity:n,onTransformStarted:e?.events?.onTransformStarted??X,onTransformFinished:e?.events?.onTransformFinished??X,onBeforeTransformChange:e?.events?.onBeforeTransformChange??X,onTransformChange:e?.events?.onTransformChange??X,transformPreprocessor:i,shiftCursor:a,mouseDownEventVerifier:s,mouseUpEventVerifier:l,mouseWheelEventVerifier:d,scaleWheelFinishTimeout:e?.scale?.wheelFinishTimeout??500,onResizeTransformStarted:e?.events?.onResizeTransformStarted??X,onResizeTransformFinished:e?.events?.onResizeTransformFinished??X}},Bt=(e,t)=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);return n.setAttribute(`cx`,`0`),n.setAttribute(`cy`,`0`),n.setAttribute(`r`,`${e}`),n.setAttribute(`fill`,`${t}`),n},Vt=e=>e instanceof SVGElement?e:Bt(e?.radius??1.5,e?.color??`#d8d8d8`),Ht=e=>{let t=e.tileDimensions;return{tileWidth:t?.width??25,tileHeight:t?.height??25,renderer:Vt(e.renderer??{}),maxViewportScale:e.maxViewportScale??10}},Z=Object.freeze({connectionTypeResolver:()=>`direct`,connectionPreprocessor:e=>e,connectionAllowedVerifier:()=>!0,mouseEventVerifier:e=>e.button===0}),Ut=(e,t,n)=>{let r=e.connectionAllowedVerifier??Z.connectionAllowedVerifier;return{connectionTypeResolver:e.connectionTypeResolver??Z.connectionTypeResolver,connectionAllowedVerifier:r,draggingPortDirectionResolver:Mt(e.dragPortDirection,n,r),edgeShapeFactory:e.edgeShape===void 0?t:Nt(e.edgeShape),connectionPreprocessor:e.connectionPreprocessor??Z.connectionPreprocessor,mouseDownEventVerifier:e.mouseDownEventVerifier??Z.mouseEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??Z.mouseEventVerifier,onAfterEdgeCreated:e.events?.onAfterEdgeCreated??X,onEdgeCreationInterrupted:e.events?.onEdgeCreationInterrupted??X,onEdgeCreationPrevented:e.events?.onEdgeCreationPrevented??X}},Q=Object.freeze({connectionAllowedVerifier:()=>!0,connectionPreprocessor:e=>e,mouseDownEventVerifier:e=>e.button===0&&e.ctrlKey,mouseUpEventVerifier:e=>e.button===0}),Wt=(e,t)=>{let n=e=>{let n=t.getPortAdjacentEdgeIds(e);return n.length>0?n[n.length-1]:null},r=e.connectionAllowedVerifier??Q.connectionAllowedVerifier;return{connectionPreprocessor:e.connectionPreprocessor??Q.connectionPreprocessor,connectionAllowedVerifier:r,mouseDownEventVerifier:e.mouseDownEventVerifier??Q.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??Q.mouseUpEventVerifier,draggingEdgeResolver:e.draggingEdgeResolver??n,draggingEdgeShapeFactory:e.draggingEdgeShape===void 0?null:Nt(e.draggingEdgeShape),onAfterEdgeReattached:e.events?.onAfterEdgeReattached??X,onEdgeReattachInterrupted:e.events?.onEdgeReattachInterrupted??X,onEdgeReattachPrevented:e.events?.onEdgeReattachPrevented??X,draggingPortDirectionResolver:Mt(e.dragPortDirection,t,r)}},Gt=e=>({nodeVerticalRadius:e.nodeContainingRadius.vertical,nodeHorizontalRadius:e.nodeContainingRadius.horizontal}),Kt=e=>({onAfterNodeDetached:e?.events?.onAfterNodeDetached??X,onBeforeNodeAttached:e?.events?.onBeforeNodeAttached??X}),qt=class extends Error{name=`CanvasBuilderError`},Jt=class{graph;currentCoords;dt;nodeMass;edgeEquilibriumLength;edgeStiffness;nodeForcesApplicationStrategy;distanceVectorGenerator;constructor(e,t,n){this.graph=e,this.currentCoords=t,this.dt=n.dtSec,this.nodeMass=n.nodeMass,this.edgeEquilibriumLength=n.edgeEquilibriumLength,this.edgeStiffness=n.edgeStiffness,this.distanceVectorGenerator=n.distanceVectorGenerator,this.nodeForcesApplicationStrategy=n.nodeForcesApplicationStrategy}apply(){let e=0,t=new Map;return this.graph.getAllNodeIds().forEach(e=>{t.set(e,{x:0,y:0})}),this.nodeForcesApplicationStrategy.apply(this.currentCoords,t),this.applyEdgeForces(t),this.currentCoords.forEach((n,r)=>{let i=t.get(r),a={x:i.x/this.nodeMass*this.dt,y:i.y/this.nodeMass*this.dt};e=Math.max(e,Math.sqrt(a.x*a.x+a.y*a.y));let o=a.x*this.dt,s=a.y*this.dt;n.x+=o,n.y+=s}),e}applyEdgeForces(e){this.graph.getAllEdgeIds().forEach(t=>{let n=this.graph.getEdge(t),r=this.graph.getPort(n.from),i=this.graph.getPort(n.to),a=this.currentCoords.get(r.nodeId),o=this.currentCoords.get(i.nodeId),s=this.distanceVectorGenerator.create(a,o),c=(s.d-this.edgeEquilibriumLength)*this.edgeStiffness,l=s.ex*c,u=s.ey*c,d=e.get(r.nodeId),f=e.get(i.nodeId);d.x+=l,d.y+=u,f.x-=l,f.y-=u})}},Yt=class{rand;PI2=2*Math.PI;constructor(e){this.rand=e}create(e,t){let n=t.x-e.x,r=t.y-e.y,i=n*n+r*r;if(i===0){let e=this.PI2*this.rand();return{ex:Math.cos(e),ey:Math.sin(e),d:0}}let a=Math.sqrt(i);return{ex:n/a,ey:r/a,d:a}}},Xt=e=>{if(e.distance===0)return e.maxForce;let t=e.coefficient*(e.sourceCharge*e.targetCharge/(e.distance*e.distance));return Math.min(t,e.maxForce)},Zt=class{nodeCharge;distanceVectorGenerator;maxForce;constructor(e){this.nodeCharge=e.nodeCharge,this.distanceVectorGenerator=e.distanceVectorGenerator,this.maxForce=e.maxForce}apply(e,t){let n=Array.from(t.keys()),r=n.length;for(let i=0;i<r;i++){let a=n[i];for(let o=i+1;o<r;o++){let r=n[o],i=e.get(a),s=e.get(r),c=this.distanceVectorGenerator.create(i,s),l=Xt({coefficient:1,sourceCharge:this.nodeCharge,targetCharge:this.nodeCharge,distance:c.d,maxForce:this.maxForce}),u=l*c.ex,d=l*c.ey,f=t.get(a),p=t.get(r);f.x-=u,f.y-=d,p.x+=u,p.y+=d}}}},Qt=e=>{if(e.size===0)return{centerX:0,centerY:0,radius:0};let t=1/0,n=-1/0,r=1/0,i=-1/0;e.forEach(e=>{t=Math.min(t,e.x),n=Math.max(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.y)});let a=n-t,o=i-r,s=Math.max(a,o);return{centerX:(t+n)/2,centerY:(r+i)/2,radius:s/2}},$t=class{root;leaves=new Map;coords;areaRadiusThreshold;nodeMass;nodeCharge;sortedParentNodes=[];constructor(e){this.coords=e.coords,this.areaRadiusThreshold=e.areaRadiusThreshold,this.nodeMass=e.nodeMass,this.nodeCharge=e.nodeCharge,this.root={nodeIds:new Set(e.coords.keys()),box:e.box,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},parent:null,lb:null,lt:null,rb:null,rt:null};let t=[this.root];for(;t.length>0;){let e=[];for(;t.length>0;){let n=t.pop();this.processNode(n).forEach(t=>{e.push(t)})}t=e}this.sortedParentNodes.reverse().forEach(e=>{let t=0,n=0,r=0,i=0;e.lb!==null&&(r+=e.lb.totalMass,i+=e.lb.totalCharge,t+=e.lb.chargeCenter.x*e.lb.totalCharge,n+=e.lb.chargeCenter.y*e.lb.totalCharge),e.lt!==null&&(r+=e.lt.totalMass,i+=e.lt.totalCharge,t+=e.lt.chargeCenter.x*e.lt.totalCharge,n+=e.lt.chargeCenter.y*e.lt.totalCharge),e.rb!==null&&(r+=e.rb.totalMass,i+=e.rb.totalCharge,t+=e.rb.chargeCenter.x*e.rb.totalCharge,n+=e.rb.chargeCenter.y*e.rb.totalCharge),e.rt!==null&&(r+=e.rt.totalMass,i+=e.rt.totalCharge,t+=e.rt.chargeCenter.x*e.rt.totalCharge,n+=e.rt.chargeCenter.y*e.rt.totalCharge),e.totalMass=r,e.totalCharge=i,e.chargeCenter.x=t/i,e.chargeCenter.y=n/i})}getRoot(){return this.root}getLeaf(e){return this.leaves.get(e)}processNode(e){if(e.nodeIds.size<2)return this.setLeaf(e),[];let{centerX:t,centerY:n,radius:r}=e.box;if(r<this.areaRadiusThreshold)return this.setLeaf(e),[];this.sortedParentNodes.push(e);let i=new Set,a=new Set,o=new Set,s=new Set,c=r/2;e.nodeIds.forEach(r=>{let{x:c,y:l}=this.coords.get(r);c<t?l<n?s.add(r):o.add(r):l<n?a.add(r):i.add(r),e.nodeIds.delete(r)});let l={parent:e,lb:null,lt:null,rb:null,rt:null},u=[];if(i.size>0){let r={nodeIds:i,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t+c,centerY:n+c,radius:c},...l};e.rt=r,u.push(r)}if(a.size>0){let r={nodeIds:a,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t+c,centerY:n-c,radius:c},...l};e.rb=r,u.push(r)}if(o.size>0){let r={nodeIds:o,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t-c,centerY:n+c,radius:c},...l};e.lt=r,u.push(r)}if(s.size>0){let r={nodeIds:s,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t-c,centerY:n-c,radius:c},...l};e.lb=r,u.push(r)}return u}setLeaf(e){e.totalMass=this.nodeMass*e.nodeIds.size,e.totalCharge=this.nodeCharge*e.nodeIds.size,e.chargeCenter=this.calculateLeafChargeCenter(e.nodeIds),e.nodeIds.forEach(t=>{this.leaves.set(t,e)})}calculateLeafChargeCenter(e){if(e.size===0)return{x:0,y:0};let t=0,n=0;return e.forEach(e=>{let r=this.coords.get(e);t+=r.x,n+=r.y}),{x:t/e.size,y:n/e.size}}},en=class{areaRadiusThreshold;nodeMass;nodeCharge;theta;distanceVectorGenerator;nodeForceCoefficient;maxForce;constructor(e){this.areaRadiusThreshold=e.areaRadiusThreshold,this.nodeMass=e.nodeMass,this.nodeCharge=e.nodeCharge,this.theta=e.theta,this.distanceVectorGenerator=e.distanceVectorGenerator,this.nodeForceCoefficient=e.nodeForceCoefficient,this.maxForce=e.maxForce}apply(e,t){let n=new $t({box:Qt(e),coords:e,areaRadiusThreshold:this.areaRadiusThreshold,nodeMass:this.nodeMass,nodeCharge:this.nodeCharge});e.forEach((r,i)=>{let a=this.calculateForceForNode(n.getLeaf(i),i,e),o=t.get(i);this.applyForce(o,a)})}calculateForceForNode(e,t,n){let r=n.get(t),i={x:0,y:0};e.nodeIds.forEach(e=>{if(e!==t){let t=n.get(e),a=this.calculateNodeRepulsiveForce({sourceCharge:this.nodeCharge,targetCharge:this.nodeCharge,sourceCoords:t,targetCoords:r});this.applyForce(i,a)}});let a=e;for(;a!==null;){let e=a.parent;if(e!==null){let t=this.distanceVectorGenerator.create(e.chargeCenter,r);e.box.radius*2<t.d*this.theta?(this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.lb,current:a}),this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.rb,current:a}),this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.rt,current:a}),this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.lt,current:a})):(this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.lb,current:a,nodesCoords:n}),this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.rb,current:a,nodesCoords:n}),this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.rt,current:a,nodesCoords:n}),this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.lt,current:a,nodesCoords:n}))}a=a.parent}return i}calculateExactForce(e,t,n){let r={x:0,y:0},i=[e];for(;i.length>0;){let e=i.pop();e.nodeIds.forEach(e=>{let i=n.get(e),a=this.calculateNodeRepulsiveForce({sourceCharge:this.nodeCharge,targetCharge:this.nodeCharge,sourceCoords:i,targetCoords:t});this.applyForce(r,a)}),e.lb!==null&&i.push(e.lb),e.rb!==null&&i.push(e.rb),e.lt!==null&&i.push(e.lt),e.rt!==null&&i.push(e.rt)}return r}calculateApproximateForce(e,t){return this.calculateNodeRepulsiveForce({sourceCharge:this.nodeCharge,targetCharge:e.totalCharge,sourceCoords:e.chargeCenter,targetCoords:t})}calculateNodeRepulsiveForce(e){let t=this.distanceVectorGenerator.create(e.sourceCoords,e.targetCoords),n=Xt({coefficient:this.nodeForceCoefficient,sourceCharge:e.sourceCharge,targetCharge:e.targetCharge,distance:t.d,maxForce:this.maxForce});return{x:n*t.ex,y:n*t.ey}}applyForce(e,t){e.x+=t.x,e.y+=t.y}tryApplyFarForce(e){if(e.target!==null&&e.target!==e.current){let t=this.calculateApproximateForce(e.target,e.targetCoords);this.applyForce(e.totalForce,t)}}tryApplyNearForce(e){if(e.target!==null&&e.target!==e.current){let t=this.calculateExactForce(e.target,e.targetCoords,e.nodesCoords);this.applyForce(e.totalForce,t)}}},tn=e=>e.theta===0?new Zt({nodeCharge:e.nodeCharge,nodeForceCoefficient:e.nodeForceCoefficient,distanceVectorGenerator:e.distanceVectorGenerator,maxForce:e.maxForce}):new en({nodeCharge:e.nodeCharge,nodeForceCoefficient:e.nodeForceCoefficient,distanceVectorGenerator:e.distanceVectorGenerator,maxForce:e.maxForce,theta:e.theta,nodeMass:e.nodeMass,areaRadiusThreshold:e.areaRadiusThreshold}),nn=class{rand;sparsity;constructor(e){this.rand=e.rand,this.sparsity=e.sparsity}calculateCoordinates(e){let{graph:t,viewport:n}=e,r=new Map,i=t.getAllNodeIds().filter(e=>{let n=t.getNode(e);return n.x===null||n.y===null}),a=Math.sqrt(i.length)*this.sparsity,{width:o,height:s}=n.getDimensions(),c={x:o/2,y:s/2},l=n.createContentCoords(c),u=a/2,d={x:l.x-u,y:l.y-u};return t.getAllNodeIds().forEach(e=>{let n=t.getNode(e);r.set(e,{x:n.x??d.x+a*this.rand(),y:n.y??d.y+a*this.rand()})}),r}},rn=class{distanceVectorGenerator;nodeForcesApplicationStrategy;fillerLayoutAlgorithm;maxIterations;dtSec;nodeMass;edgeEquilibriumLength;edgeStiffness;convergenceVelocity;constructor(e){this.maxIterations=e.maxIterations,this.dtSec=e.dtSec,this.nodeMass=e.nodeMass,this.edgeEquilibriumLength=e.edgeEquilibriumLength,this.edgeStiffness=e.edgeStiffness,this.convergenceVelocity=e.convergenceVelocity,this.distanceVectorGenerator=new Yt(e.rand),this.nodeForcesApplicationStrategy=tn({distanceVectorGenerator:this.distanceVectorGenerator,nodeCharge:e.nodeCharge,maxForce:e.maxForce,nodeForceCoefficient:e.nodeForceCoefficient,theta:e.barnesHutTheta,areaRadiusThreshold:e.barnesHutAreaRadiusThreshold,nodeMass:e.nodeMass}),this.fillerLayoutAlgorithm=new nn({rand:e.rand,sparsity:e.edgeEquilibriumLength})}calculateCoordinates(e){let{graph:t,viewport:n}=e,r=this.fillerLayoutAlgorithm.calculateCoordinates({graph:t,viewport:n});for(let e=0;e<this.maxIterations&&!(new Jt(t,r,{distanceVectorGenerator:this.distanceVectorGenerator,nodeForcesApplicationStrategy:this.nodeForcesApplicationStrategy,dtSec:this.dtSec,nodeMass:this.nodeMass,edgeEquilibriumLength:this.edgeEquilibriumLength,edgeStiffness:this.edgeStiffness}).apply()<this.convergenceVelocity);e++);return r}},an=class{graph;nextLayerNodesResolver;forest=new Set;remainingNodeIds;constructor(e,t){for(this.graph=e,this.nextLayerNodesResolver=t,this.remainingNodeIds=new Set(this.graph.getAllNodeIds());this.remainingNodeIds.size>0;){let[e]=this.remainingNodeIds;this.traverse(e)}}generate(){return this.forest}traverse(e){let t={nodeId:e,children:new Set},n=[];this.forest.add({root:t,sequence:n});let r=[t];for(this.remainingNodeIds.delete(t.nodeId);r.length>0;){let e=[];r.forEach(t=>{n.push(t);let r=this.nextLayerNodesResolver({graph:this.graph,currentNodeId:t.nodeId});for(let n of r){if(!this.remainingNodeIds.has(n))continue;this.remainingNodeIds.delete(n);let r={nodeId:n,children:new Set};t.children.add(r),e.push(r)}}),r=e}}},on=class{params;constructor(e){this.params=e}generate(e){let t=0,n=[],r=e.length-1,i=[];e.forEach((a,o)=>{if(t+=this.params.spaceAroundRadius,a.forEach((e,n)=>{i[n]===void 0?i[n]={start:t+e.start,end:t+e.end}:i[n].end=t+e.end}),n.push(t),o!==r){let n=e[o+1],r=i.map(e=>({start:e.start-t,end:e.end-t}));t+=this.calculateMaxDiff(r,n)}t+=this.params.spaceAroundRadius});let a=t/2;return{childOffsets:n.map(e=>e-a),subtreeSpans:i.map(e=>({start:e.start-a,end:e.end-a}))}}calculateMaxDiff(e,t){let n=0,r=Math.min(e.length,t.length);for(let i=0;i<r;i++){let r=e[i].end-t[i].start;n=Math.max(n,r)}return n-2*this.params.spaceAroundRadius}},sn=class{tree;offsets=new Map;treeSpans=new Map;constructor(e,t){this.tree=e;let n=t.spaceAroundRadius,r=new on({spaceAroundRadius:n});[...this.tree.sequence].reverse().forEach(e=>{let t=Array.from(e.children).map(e=>this.treeSpans.get(e.nodeId)),i=r.generate(t),a=0;e.children.forEach(e=>{this.offsets.set(e.nodeId,i.childOffsets[a]),a++}),this.treeSpans.set(e.nodeId,[{start:-n,end:n},...i.subtreeSpans]),e.children.forEach(e=>{this.treeSpans.delete(e.nodeId)})}),this.offsets.set(this.tree.root.nodeId,0)}generate(){return this.offsets}},cn=class{params;constructor(e){this.params=e}calculateCoordinates(e){let t=new Map,n=new an(e.graph,this.params.nextLayerNodesResolver).generate(),r=0;return n.forEach(e=>{t.set(e.root.nodeId,{x:r,y:0});let n=new sn(e,{spaceAroundRadius:this.params.layerSpace/2}).generate(),i=[e.root];for(;i.length>0;){let e=[];r+=this.params.layerWidth,i.forEach(i=>{i.children.forEach(a=>{let o=t.get(i.nodeId).y;t.set(a.nodeId,{y:o+n.get(a.nodeId),x:r}),e.push(a)})}),i=e}}),t.forEach((e,n)=>{t.set(n,this.params.transform(e))}),t}},ln=e=>{let{graph:t,currentNodeId:n}=e,r=t.getNodeOutgoingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.to).nodeId}),i=t.getNodeIncomingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.from).nodeId});return new Set([...r,...i])},un=e=>{let{graph:t,currentNodeId:n}=e,r=t.getNodeOutgoingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.to).nodeId});return new Set(r)},dn=e=>{let{graph:t,currentNodeId:n}=e,r=t.getNodeIncomingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.from).nodeId});return new Set(r)},fn=class{distanceVectorGenerator;nodeForcesApplicationStrategy;convergenceVelocity;maxTimeDeltaSec;nodeMass;edgeEquilibriumLength;edgeStiffness;fillerLayoutAlgorithm;constructor(e){this.convergenceVelocity=e.convergenceVelocity,this.maxTimeDeltaSec=e.maxTimeDeltaSec,this.nodeMass=e.nodeMass,this.edgeEquilibriumLength=e.edgeEquilibriumLength,this.edgeStiffness=e.edgeStiffness,this.distanceVectorGenerator=new Yt(e.rand),this.nodeForcesApplicationStrategy=tn({distanceVectorGenerator:this.distanceVectorGenerator,nodeCharge:e.nodeCharge,maxForce:e.maxForce,nodeForceCoefficient:e.nodeForceCoefficient,theta:e.barnesHutTheta,areaRadiusThreshold:e.barnesHutAreaRadiusThreshold,nodeMass:e.nodeMass}),this.fillerLayoutAlgorithm=new nn({rand:e.rand,sparsity:e.edgeEquilibriumLength})}calculateNextCoordinates(e){let{graph:t,viewport:n,dt:r}=e,i=this.fillerLayoutAlgorithm.calculateCoordinates({graph:t,viewport:n});return new Jt(t,i,{distanceVectorGenerator:this.distanceVectorGenerator,nodeForcesApplicationStrategy:this.nodeForcesApplicationStrategy,dtSec:Math.min(r,this.maxTimeDeltaSec),nodeMass:this.nodeMass,edgeEquilibriumLength:this.edgeEquilibriumLength,edgeStiffness:this.edgeStiffness}).apply()<this.convergenceVelocity&&!t.getAllNodeIds().some(e=>{let n=t.getNode(e);return n.x===null||n.y===null})?new Map:i}},pn=e=>{let t=1779033703,n=3144134277,r=1013904242,i=2773480762;for(let a=0,o;a<e.length;a++)o=e.charCodeAt(a),t=n^Math.imul(t^o,597399067),n=r^Math.imul(n^o,2869860233),r=i^Math.imul(r^o,951274213),i=t^Math.imul(i^o,2716044179);return t=Math.imul(r^t>>>18,597399067),n=Math.imul(i^n>>>22,2869860233),r=Math.imul(t^r>>>17,951274213),i=Math.imul(n^i>>>19,2716044179),t^=n^r^i,n^=t,r^=t,i^=t,[t>>>0,n>>>0,r>>>0,i>>>0]},mn=(e,t,n,r)=>function(){e|=0,t|=0,n|=0,r|=0;let i=(e+t|0)+r|0;return r=r+1|0,e=t^t>>>9,t=n+(n<<3)|0,n=n<<21|n>>>11,n=n+i|0,(i>>>0)/4294967296},hn=e=>{switch(e?.type){case`custom`:return e.instance;default:{let t=pn(e?.seed??J.seed);return new fn({rand:mn(t[0],t[1],t[2],t[3]),maxTimeDeltaSec:e?.maxTimeDeltaSec??J.maxTimeDeltaSec,nodeCharge:e?.nodeCharge??J.nodeCharge,nodeMass:e?.nodeMass??J.nodeMass,edgeEquilibriumLength:e?.edgeEquilibriumLength??J.edgeEquilibriumLength,edgeStiffness:e?.edgeStiffness??J.edgeStiffness,convergenceVelocity:e?.convergenceVelocity??J.convergenceVelocity,maxForce:e?.maxForce??J.maxForce,nodeForceCoefficient:e?.nodeForceCoefficient??J.nodeForceCoefficient,barnesHutTheta:e?.barnesHut?.theta??J.barnesHutTheta,barnesHutAreaRadiusThreshold:e?.barnesHut?.areaRadiusThreshold??J.barnesHutAreaRadiusThreshold})}}},gn={staticNodeResolver:()=>!1},_n=e=>({algorithm:hn(e?.algorithm??{}),staticNodeResolver:e?.staticNodeResolver??gn.staticNodeResolver,onBeforeApplied:e?.events?.onBeforeApplied??X,onAfterApplied:e?.events?.onAfterApplied??X}),vn=e=>e instanceof u?{type:`trigger`,trigger:e}:e===`topologyChangeMicrotask`?{type:`topologyChangeSchedule`,schedule:Qe}:e?.type===`topologyChangeMacrotask`?{type:`topologyChangeSchedule`,schedule:Ze}:{type:`topologyChangeSchedule`,schedule:Qe},yn=Object.freeze({staticNodeResolver:()=>!1,hierarchicalLayout:{layerWidth:300,layerSpace:300}}),$=(e,t)=>({a:e.a*t.a+e.b*t.d,b:e.a*t.b+e.b*t.e,c:e.a*t.c+e.b*t.f+e.c,d:e.d*t.a+e.e*t.d,e:e.d*t.b+e.e*t.e,f:e.d*t.c+e.e*t.f+e.f}),bn=e=>{let{a:t,b:n,c:r,d:i,e:a,f:o}=e,s=t*a-n*i;return{a:a/s,b:-n/s,c:(n*o-r*a)/s,d:-i/s,e:t/s,f:(r*i-t*o)/s}},xn=class{resolve(e){if(`shift`in e)return this.createShiftBaseMatrix(e.shift);if(`scale`in e){let t=e.origin??{x:0,y:0};return this.createScaleRelativeMatrix(e.scale,t)}if(`rotate`in e){let t=e.origin??{x:0,y:0};return this.createRotateRelativeMatrix(e.rotate,t)}if(`mirror`in e){let t=e.origin??{x:0,y:0};return this.createMirrorRelativeMatrix(e.mirror,t)}return{a:e.a??1,b:e.b??0,c:e.c??0,d:e.d??0,e:e.e??1,f:e.f??0}}createScaleRelativeMatrix(e,t){let n=this.createScaleBaseMatrix(e),r=this.createShiftBaseMatrix(t);return this.createRelativeTransform(n,r)}createRotateRelativeMatrix(e,t){let n=this.createRotateBaseMatrix(e),r=this.createShiftBaseMatrix(t);return this.createRelativeTransform(n,r)}createMirrorRelativeMatrix(e,t){let n=this.createMirrorYBaseMatrix(),r=$(this.createShiftBaseMatrix(t),this.createRotateBaseMatrix(e));return this.createRelativeTransform(n,r)}createRelativeTransform(e,t){return $($(t,e),bn(t))}createShiftBaseMatrix(e){return{a:1,b:0,c:e.x,d:0,e:1,f:e.y}}createScaleBaseMatrix(e){return{a:e,b:0,c:0,d:0,e,f:0}}createRotateBaseMatrix(e){let t=Math.sin(e),n=Math.cos(e);return{a:n,b:-t,c:0,d:t,e:n,f:0}}createMirrorYBaseMatrix(){return{a:1,b:0,c:0,d:0,e:-1,f:0}}},Sn=e=>{if(e===void 0)return e=>e;if(typeof e==`function`)return e;let t=Array.isArray(e)?e:[e],n={a:1,b:0,c:0,d:0,e:1,f:0},r=new xn;return t.forEach(e=>{let t=r.resolve(e);n=$(n,t)}),e=>{let{x:t,y:r}=e;return{x:n.a*t+n.b*r+n.c,y:n.d*t+n.e*r+n.f}}},Cn=e=>{if(typeof e==`function`)return e;switch(e){case`outgoing`:return un;case`incoming`:return dn;default:return ln}},wn=e=>{switch(e?.type){case`custom`:return e.instance;case`hierarchical`:return new cn({layerWidth:e.layerWidth??yn.hierarchicalLayout.layerWidth,layerSpace:e.layerSpace??yn.hierarchicalLayout.layerSpace,transform:Sn(e.transform),nextLayerNodesResolver:Cn(e.nextLayerNodesResolver)});default:{let t=pn(e?.seed??J.seed),n=mn(t[0],t[1],t[2],t[3]);return new rn({dtSec:e?.dtSec??J.dtSec,maxIterations:e?.maxIterations??J.maxIterations,rand:n,nodeCharge:e?.nodeCharge??J.nodeCharge,nodeMass:e?.nodeMass??J.nodeMass,edgeEquilibriumLength:e?.edgeEquilibriumLength??J.edgeEquilibriumLength,edgeStiffness:e?.edgeStiffness??J.edgeStiffness,convergenceVelocity:e?.convergenceVelocity??J.convergenceVelocity,maxForce:e?.maxForce??J.maxForce,nodeForceCoefficient:e?.nodeForceCoefficient??J.nodeForceCoefficient,barnesHutTheta:e?.barnesHut?.theta??J.barnesHutTheta,barnesHutAreaRadiusThreshold:e?.barnesHut?.areaRadiusThreshold??J.barnesHutAreaRadiusThreshold})}}},Tn=e=>({algorithm:wn(e.algorithm),applyOn:vn(e.applyOn),staticNodeResolver:e.staticNodeResolver??yn.staticNodeResolver,onBeforeApplied:e.events?.onBeforeApplied??X,onAfterApplied:e.events?.onAfterApplied??X}),En=(e,t)=>({...e,onNodeDragStarted:n=>{t.add(n),e.onNodeDragStarted(n)},onNodeDragFinished:n=>{t.delete(n),e.onNodeDragFinished(n)}}),Dn=(e,t)=>{e.graph.onBeforeNodeRemoved.subscribe(e=>{t.delete(e)}),e.graph.onBeforeClear.subscribe(()=>{t.clear()}),e.onBeforeDestroy.subscribe(()=>{t.clear()})},On=(e,t)=>({...e,staticNodeResolver:n=>e.staticNodeResolver(n)||t.has(n)}),kn=e=>()=>e,An=kn(0),jn=()=>{let e=0;return()=>e++},Mn=(e,t)=>{let n=An,r=An,i=jn();return e===`incremental`&&(n=i),t===`incremental`&&(r=i),typeof e==`number`&&(n=kn(e)),typeof t==`number`&&(r=kn(t)),typeof e==`function`&&(n=e),typeof t==`function`&&(r=t),{nodesPriorityFn:n,edgesPriorityFn:r}},Nn=e=>{let t=Mn(e.nodes?.priority,e.edges?.priority);return{nodes:{centerFn:e.nodes?.centerFn??ae,priorityFn:t.nodesPriorityFn},ports:{direction:e.ports?.direction??0},edges:{shapeFactory:Nt(e.edges?.shape??{}),priorityFn:t.edgesPriorityFn}}},Pn=e=>e.applyOn.type===`topologyChangeSchedule`?e.applyOn.schedule:V,Fn=e=>{let{canvasDefaults:t}=e,n=e.hasLayout?Pn(e.layoutParams):V;return{focus:{contentPadding:t.focus?.contentPadding??t.focus?.contentOffset??100,minContentScale:t.focus?.minContentScale??0,schedule:n,animationDuration:t.focus?.animationDuration??0}}},In=e=>({onNodeSelected:e.onNodeSelected,mouseDownEventVerifier:e.mouseDownEventVerifier??Y.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??Y.mouseUpEventVerifier,movementThreshold:e.movementThreshold??Y.movementThreshold}),Ln=e=>({onCanvasSelected:e.onCanvasSelected,mouseDownEventVerifier:e.mouseDownEventVerifier??Y.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??Y.mouseUpEventVerifier,movementThreshold:e.movementThreshold??Y.movementThreshold}),Rn=e=>({onEdgeSelected:e.onEdgeSelected,mouseDownEventVerifier:e.mouseDownEventVerifier??Y.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??Y.mouseUpEventVerifier,movementThreshold:e.movementThreshold??Y.movementThreshold}),zn=class{element;used=!1;canvasDefaults={};dragConfig={};transformConfig={};backgroundConfig={};connectablePortsConfig={};draggableEdgesConfig={};virtualScrollConfig=void 0;layoutConfig={};animatedLayoutConfig={};userSelectableNodesConfig=void 0;userSelectableEdgesConfig=void 0;userSelectableCanvasConfig=void 0;hasDraggableNodes=!1;hasTransformableViewport=!1;hasNodeResizeReactiveEdges=!1;hasBackground=!1;hasUserConnectablePorts=!1;hasUserDraggableEdges=!1;hasAnimatedLayout=!1;hasLayout=!1;boxRenderingTrigger=new u;window=window;animationStaticNodes=new Set;pointInsideVerifier;eventTagger=new ot;constructor(e){this.element=e,this.pointInsideVerifier=new te(e,this.window)}setDefaults(e){return this.canvasDefaults=e,this}enableUserDraggableNodes(e){return this.hasDraggableNodes=!0,this.dragConfig=e??{},this}enableUserTransformableViewport(e){return this.hasTransformableViewport=!0,this.transformConfig=e??{},this}enableNodeResizeReactiveEdges(){return this.hasNodeResizeReactiveEdges=!0,this}enableVirtualScroll(e){return this.virtualScrollConfig=e,this}enableBackground(e){return this.hasBackground=!0,this.backgroundConfig=e??{},this}enableUserConnectablePorts(e){return this.hasUserConnectablePorts=!0,this.connectablePortsConfig=e??{},this}enableUserDraggableEdges(e){return this.hasUserDraggableEdges=!0,this.draggableEdgesConfig=e??{},this}enableLayout(e){return this.layoutConfig=e??{},this.hasLayout=!0,this.hasAnimatedLayout=!1,this}enableAnimatedLayout(e){return this.animatedLayoutConfig=e??{},this.hasAnimatedLayout=!0,this.hasLayout=!1,this}enableUserSelectableNodes(e){return this.userSelectableNodesConfig=e,this}enableUserSelectableEdges(e){return this.userSelectableEdgesConfig=e,this}enableUserSelectableCanvas(e){return this.userSelectableCanvasConfig=e,this}build(){if(this.used)throw new qt(`Failed to build Canvas because CanvasBuilder is a single-use object`);this.used=!0;let e=new b(this.element),t=new g,n=new jt(this.element),r=this.createHtmlView(n.main,t,e),i=Nn(this.canvasDefaults),a=new Xe(t,r,i),o=Tn(this.layoutConfig),s=new rt(t,e,Fn({canvasDefaults:this.canvasDefaults,hasLayout:this.hasLayout,layoutParams:o}),this.window),c=new $e(e),l=new f(new Ye(t),c,a,s);if(this.hasBackground&&ht.configure(l,Ht(this.backgroundConfig),n.background),this.hasNodeResizeReactiveEdges&&x.configure(l),this.userSelectableEdgesConfig!==void 0){let e=Rn(this.userSelectableEdgesConfig);Et.configure(l,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.userSelectableNodesConfig!==void 0){let e=In(this.userSelectableNodesConfig);Tt.configure(l,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.userSelectableCanvasConfig!==void 0){let e=Ln(this.userSelectableCanvasConfig);Dt.configure(l,n.main,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.hasDraggableNodes){let e=Pt(this.dragConfig);this.hasAnimatedLayout&&(e=En(e,this.animationStaticNodes)),lt.configure(l,n.main,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.hasUserConnectablePorts){let t=Ut(this.connectablePortsConfig,i.edges.shapeFactory,l.graph);gt.configure(l,n.overlayConnectablePorts,e,this.window,this.pointInsideVerifier,this.eventTagger,t)}if(this.hasUserDraggableEdges){let t=Wt(this.draggableEdgesConfig,l.graph);_t.configure(l,n.overlayDraggableEdges,e,this.window,this.pointInsideVerifier,this.eventTagger,t)}if(this.virtualScrollConfig===void 0?this.hasTransformableViewport&&ut.configure(l,n.main,this.window,this.pointInsideVerifier,this.eventTagger,zt(this.transformConfig)):dt.configure(l,n.main,this.window,zt(this.transformConfig),this.boxRenderingTrigger,this.pointInsideVerifier,this.eventTagger,Gt(this.virtualScrollConfig)),this.hasLayout&&xt.configure(l,o),this.hasAnimatedLayout){let e=_n(this.animatedLayoutConfig);this.hasDraggableNodes&&(Dn(l,this.animationStaticNodes),e=On(e,this.animationStaticNodes)),wt.configure(l,e,this.window)}return l.onBeforeDestroy.subscribe(()=>{n.destroy()}),l}createHtmlView(e,t,n){let r=new o(t,n,e);return this.virtualScrollConfig!==void 0&&(r=new c(r,t,this.boxRenderingTrigger,Kt(this.virtualScrollConfig))),r=new l(r,t),r}};e.BezierEdgeShape=je,e.CanvasBuilder=zn,e.CanvasBuilderError=qt,e.CanvasError=m,e.ConnectionCategory=t,e.DirectEdgeShape=z,e.EventSubject=u,e.HorizontalEdgeShape=Ne,e.InteractiveEdgeError=Ke,e.InteractiveEdgeShape=qe,e.MidpointEdgeShape=Je,e.OrthogonalEdgeShape=ze,e.StraightEdgeShape=Pe,e.VerticalEdgeShape=Le,e.boxPortOffsetFn=Be});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.HtmlGraph={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=function(e){return e.Line=`line`,e.NodeCycle=`node-cycle`,e.PortCycle=`port-cycle`,e}({}),n=()=>{let e=document.createElement(`div`);return e.style.width=`100%`,e.style.height=`100%`,e.style.position=`relative`,e.style.overflow=`hidden`,e},r=()=>{let e=document.createElement(`div`);return e.style.position=`absolute`,e.style.top=`0`,e.style.left=`0`,e.style.width=`0`,e.style.height=`0`,e},i=e=>{e.style.position=`absolute`,e.style.top=`0`,e.style.left=`0`,e.style.visibility=`hidden`},a=e=>{e.style.removeProperty(`position`),e.style.removeProperty(`top`),e.style.removeProperty(`left`),e.style.removeProperty(`visibility`),e.style.removeProperty(`transform`)},o=class{graphStore;viewportStore;element;host=n();container=r();edgeIdToElementMap=new Map;attachedNodeIds=new Set;applyTransform=()=>{let e=this.viewportStore.getContentMatrix();this.container.style.transform=`matrix(${e.scale}, 0, 0, ${e.scale}, ${e.x}, ${e.y})`};constructor(e,t,n){this.graphStore=e,this.viewportStore=t,this.element=n,this.element.appendChild(this.host),this.host.appendChild(this.container),this.viewportStore.onAfterUpdated.subscribe(this.applyTransform)}attachNode(e){let t=this.graphStore.getNode(e);i(t.element),this.attachedNodeIds.add(e),this.container.appendChild(t.element),this.updateNodePosition(e),this.updateNodePriority(e),t.element.style.visibility=`visible`}detachNode(e){let t=this.graphStore.getNode(e);a(t.element),this.container.removeChild(t.element),this.attachedNodeIds.delete(e)}attachEdge(e){let t=this.graphStore.getEdge(e).payload.shape.element;this.edgeIdToElementMap.set(e,t),this.container.appendChild(t),this.renderEdge(e),this.updateEdgePriority(e)}detachEdge(e){let t=this.edgeIdToElementMap.get(e);this.container.removeChild(t),this.edgeIdToElementMap.delete(e)}clear(){this.edgeIdToElementMap.forEach((e,t)=>{this.detachEdge(t)}),this.attachedNodeIds.forEach(e=>{this.detachNode(e)})}destroy(){this.clear(),this.viewportStore.onAfterUpdated.unsubscribe(this.applyTransform),this.element.removeChild(this.host),this.host.removeChild(this.container)}updateNodePosition(e){let t=this.graphStore.getNode(e),{width:n,height:r}=t.element.getBoundingClientRect(),i=this.viewportStore.getViewportMatrix().scale,{payload:a}=t,o=a.centerFn(n,r),s=a.x-i*o.x,c=a.y-i*o.y;t.element.style.transform=`translate(${s}px, ${c}px)`}updateNodePriority(e){let t=this.graphStore.getNode(e);t.element.style.zIndex=`${t.payload.priority}`}updateEdgeShape(e){let t=this.edgeIdToElementMap.get(e);this.container.removeChild(t);let{element:n}=this.graphStore.getEdge(e).payload.shape;this.edgeIdToElementMap.set(e,n),this.container.appendChild(n)}renderEdge(e){let n=this.graphStore.getEdge(e),r=this.graphStore.getPort(n.from),i=this.graphStore.getPort(n.to),a=r.element.getBoundingClientRect(),o=i.element.getBoundingClientRect(),s=this.host.getBoundingClientRect(),c=this.viewportStore.getViewportMatrix().scale,l=this.createEdgeRenderPort(r,a,s,c),u=this.createEdgeRenderPort(i,o,s,c),d=t.Line;r.element===i.element?d=t.PortCycle:r.nodeId===i.nodeId&&(d=t.NodeCycle),n.payload.shape.render({from:l,to:u,category:d})}updateEdgePriority(e){let t=this.graphStore.getEdge(e);t.payload.shape.element.style.zIndex=`${t.payload.priority}`}createEdgeRenderPort(e,t,n,r){let i=this.viewportStore.createContentCoords({x:t.left-n.left,y:t.top-n.top});return{x:i.x,y:i.y,width:t.width*r,height:t.height*r,direction:e.payload.direction}}},s=class{graphStore;xFrom=1/0;yFrom=1/0;xTo=1/0;yTo=1/0;constructor(e){this.graphStore=e}setRenderingBox(e){this.xFrom=e.x,this.xTo=e.x+e.width,this.yFrom=e.y,this.yTo=e.y+e.height}hasNode(e){let{x:t,y:n}=this.graphStore.getNode(e).payload;return t>=this.xFrom&&t<=this.xTo&&n>=this.yFrom&&n<=this.yTo}hasEdge(e){let t=this.graphStore.getEdge(e),n=this.graphStore.getPort(t.from).nodeId,r=this.graphStore.getPort(t.to).nodeId,i=this.graphStore.getNode(n).payload,a=this.graphStore.getNode(r).payload,o=Math.min(i.x,a.x),s=Math.max(i.x,a.x),c=Math.min(i.y,a.y),l=Math.max(i.y,a.y);return o<=this.xTo&&s>=this.xFrom&&c<=this.yTo&&l>=this.yFrom}},c=class{htmlView;graphStore;trigger;params;attachedNodes=new Set;attachedEdges=new Set;renderingBox;updateViewport=e=>{this.renderingBox.setRenderingBox(e);let t=new Set,n=new Set,r=new Set,i=new Set;this.graphStore.getAllNodeIds().forEach(e=>{let r=this.renderingBox.hasNode(e),i=this.attachedNodes.has(e);r&&!i?t.add(e):!r&&i&&n.add(e)}),this.graphStore.getAllEdgeIds().forEach(e=>{let a=this.renderingBox.hasEdge(e),o=this.attachedEdges.has(e),s=this.graphStore.getEdge(e),c=this.graphStore.getPort(s.from).nodeId,l=this.graphStore.getPort(s.to).nodeId;a&&(this.renderingBox.hasNode(c)||(t.add(c),n.delete(c)),this.renderingBox.hasNode(l)||(t.add(l),n.delete(l))),a&&!o?r.add(e):!a&&o&&i.add(e)}),i.forEach(e=>{this.handleDetachEdge(e)}),n.forEach(e=>{this.handleDetachNode(e)}),t.forEach(e=>{this.attachedNodes.has(e)||this.handleAttachNode(e)}),r.forEach(e=>{this.handleAttachEdge(e)})};constructor(e,t,n,r){this.htmlView=e,this.graphStore=t,this.trigger=n,this.params=r,this.renderingBox=new s(this.graphStore),this.trigger.subscribe(this.updateViewport)}attachNode(e){this.renderingBox.hasNode(e)&&this.handleAttachNode(e)}detachNode(e){this.attachedNodes.has(e)&&this.handleDetachNode(e)}attachEdge(e){this.renderingBox.hasEdge(e)&&this.attachEdgeEntities(e)}detachEdge(e){this.attachedEdges.has(e)&&this.handleDetachEdge(e)}updateNodePosition(e){this.attachedNodes.has(e)?this.htmlView.updateNodePosition(e):this.renderingBox.hasNode(e)&&(this.handleAttachNode(e),this.graphStore.getNodeAdjacentEdgeIds(e).forEach(e=>{this.attachEdgeEntities(e)}))}updateNodePriority(e){this.attachedNodes.has(e)&&this.htmlView.updateNodePriority(e)}updateEdgeShape(e){this.attachedEdges.has(e)&&this.htmlView.updateEdgeShape(e)}renderEdge(e){this.attachedEdges.has(e)&&this.htmlView.renderEdge(e)}updateEdgePriority(e){this.attachedEdges.has(e)&&this.htmlView.updateEdgePriority(e)}clear(){this.htmlView.clear(),this.attachedNodes.clear(),this.attachedEdges.clear()}destroy(){this.clear(),this.htmlView.destroy(),this.trigger.unsubscribe(this.updateViewport)}attachEdgeEntities(e){let t=this.graphStore.getEdge(e),n=this.graphStore.getPort(t.from).nodeId,r=this.graphStore.getPort(t.to).nodeId;this.attachedNodes.has(n)||this.handleAttachNode(n),this.attachedNodes.has(r)||this.handleAttachNode(r),this.handleAttachEdge(e)}handleAttachNode(e){this.params.onBeforeNodeAttached(e),this.attachedNodes.add(e),this.htmlView.attachNode(e)}handleDetachNode(e){this.htmlView.detachNode(e),this.attachedNodes.delete(e),this.params.onAfterNodeDetached(e)}handleAttachEdge(e){this.attachedEdges.add(e),this.htmlView.attachEdge(e)}handleDetachEdge(e){this.htmlView.detachEdge(e),this.attachedEdges.delete(e)}},l=class{htmlView;graphStore;deferredNodes=new Set;deferredEdges=new Set;constructor(e,t){this.htmlView=e,this.graphStore=t}attachNode(e){this.isNodeValid(e)?this.htmlView.attachNode(e):this.deferredNodes.add(e)}detachNode(e){this.deferredNodes.has(e)?this.deferredNodes.delete(e):this.htmlView.detachNode(e)}attachEdge(e){this.isEdgeValid(e)?this.htmlView.attachEdge(e):this.deferredEdges.add(e)}detachEdge(e){this.deferredEdges.has(e)?this.deferredEdges.delete(e):this.htmlView.detachEdge(e)}updateNodePosition(e){this.deferredNodes.has(e)?this.tryAttachNode(e):this.htmlView.updateNodePosition(e)}updateNodePriority(e){this.deferredNodes.has(e)?this.tryAttachNode(e):this.htmlView.updateNodePriority(e)}updateEdgeShape(e){this.deferredEdges.has(e)?this.tryAttachEdge(e):this.htmlView.updateEdgeShape(e)}renderEdge(e){this.deferredEdges.has(e)?this.tryAttachEdge(e):this.htmlView.renderEdge(e)}updateEdgePriority(e){this.deferredEdges.has(e)?this.tryAttachEdge(e):this.htmlView.updateEdgePriority(e)}clear(){this.deferredNodes.clear(),this.deferredEdges.clear(),this.htmlView.clear()}destroy(){this.htmlView.destroy()}isNodeValid(e){let t=this.graphStore.getNode(e);return!(t.payload.x===null||t.payload.y===null)}tryAttachNode(e){this.isNodeValid(e)&&(this.deferredNodes.delete(e),this.htmlView.attachNode(e))}isEdgeValid(e){let t=this.graphStore.getEdge(e),n=this.graphStore.getPort(t.from),r=this.graphStore.getPort(t.to);return!(this.deferredNodes.has(n.nodeId)||this.deferredNodes.has(r.nodeId))}tryAttachEdge(e){this.isEdgeValid(e)&&(this.deferredEdges.delete(e),this.htmlView.attachEdge(e))}},u=class{callbacks=new Set;subscribe(e){this.callbacks.add(e)}unsubscribe(e){this.callbacks.delete(e)}emit(e){this.callbacks.forEach(t=>{t(e)})}},d=()=>{let e=new u;return[e,e]},f=class{graph;viewport;graphController;viewportController;beforeDestroyEmitter;destroyed=!1;onBeforeDestroy;constructor(e,t,n,r){this.graph=e,this.viewport=t,this.graphController=n,this.viewportController=r,[this.beforeDestroyEmitter,this.onBeforeDestroy]=d()}addNode(e){return this.graphController.addNode(e),this}updateNode(e,t){return this.graphController.updateNode(e,t),this}removeNode(e){return this.graphController.removeNode(e),this}markPort(e){return this.graphController.markPort(e),this}updatePort(e,t){return this.graphController.updatePort(e,t),this}unmarkPort(e){return this.graphController.unmarkPort(e),this}addEdge(e){return this.graphController.addEdge(e),this}updateEdge(e,t){return this.graphController.updateEdge(e,t),this}removeEdge(e){return this.graphController.removeEdge(e),this}clear(){return this.graphController.clear(),this}focus(e){return this.viewportController.focus(e),this}center(e,t){return this.viewportController.center(e,t),this}patchViewportMatrix(e){return this.viewportController.patchViewportMatrix(e),this}patchContentMatrix(e){return this.viewportController.patchContentMatrix(e),this}destroy(){this.destroyed||(this.destroyed=!0,this.beforeDestroyEmitter.emit(),this.graphController.destroy(),this.viewportController.destroy())}},p=class{singleToMultiMap=new Map;multiToSingleMap=new Map;addRecord(e,t){let n=this.singleToMultiMap.get(e);n===void 0?this.singleToMultiMap.set(e,new Set([t])):n.add(t),this.multiToSingleMap.set(t,e)}getMultiBySingle(e){let t=this.singleToMultiMap.get(e)??new Set;return Array.from(t.values())}removeByMulti(e){let t=this.multiToSingleMap.get(e),n=this.singleToMultiMap.get(t);n.delete(e),n.size===0&&this.singleToMultiMap.delete(t),this.multiToSingleMap.delete(e)}getByMulti(e){return this.multiToSingleMap.get(e)}removeBySingle(e){this.singleToMultiMap.get(e).forEach(e=>{this.multiToSingleMap.delete(e)}),this.singleToMultiMap.delete(e)}clear(){this.singleToMultiMap.clear(),this.multiToSingleMap.clear()}forEachSingle(e){this.singleToMultiMap.forEach((t,n)=>{e(n)})}hasSingle(e){return this.singleToMultiMap.get(e)!==void 0}hasMulti(e){return this.multiToSingleMap.get(e)!==void 0}},m=class extends Error{name=`CanvasError`},h=Object.freeze({accessNonexistingNode:e=>`Failed to access node with ID ${JSON.stringify(e)} because it does not exist`,addNodeWithExistingId:e=>`Failed to add node with ID ${JSON.stringify(e)} because a node with this ID already exists`,addNodeWithElementInUse:(e,t)=>`Failed to add node with ID ${JSON.stringify(e)} because its HTML element is already attached to node with ID ${JSON.stringify(t)}`,updateNonexistentNode:e=>`Failed to update node with ID ${JSON.stringify(e)} because it does not exist`,removeNonexistentNode:e=>`Failed to remove node with ID ${JSON.stringify(e)} because it does not exist`,accessNonexistentPort:e=>`Failed to access port with ID ${JSON.stringify(e)} because it does not exist`,addPortWithExistingId:e=>`Failed to add port with ID ${JSON.stringify(e)} because a port with this ID already exists`,addPortToNonexistentNode:(e,t)=>`Failed to add port with ID ${JSON.stringify(e)} to node with ID ${JSON.stringify(t)} because the node does not exist`,updateNonexistentPort:e=>`Failed to update port with ID ${JSON.stringify(e)} because it does not exist`,accessPortsOfNonexistentNode:e=>`Failed to access ports of node with ID ${JSON.stringify(e)} because the node does not exist`,removeNonexistentPort:e=>`Failed to remove port with ID ${JSON.stringify(e)} because it does not exist`,accessNonexistentEdge:e=>`Failed to access edge with ID ${JSON.stringify(e)} because it does not exist`,addEdgeWithExistingId:e=>`Failed to add edge with ID ${JSON.stringify(e)} because an edge with this ID already exists`,addEdgeWithElementInUse:(e,t)=>`Failed to add edge with ID ${JSON.stringify(e)} because its element is already attached to edge with ID ${JSON.stringify(t)}`,addEdgeFromNonexistentPort:(e,t)=>`Failed to add edge with ID ${JSON.stringify(e)} from port with ID ${JSON.stringify(t)} because the port does not exist`,addEdgeToNonexistentPort:(e,t)=>`Failed to add edge with ID ${JSON.stringify(e)} to port with ID ${JSON.stringify(t)} because the port does not exist`,updateNonexistentEdge:e=>`Failed to update edge with ID ${JSON.stringify(e)} because it does not exist`,updateNonexistentEdgeSource:(e,t)=>`Failed to update source of edge with ID ${JSON.stringify(e)} because source port with ID ${JSON.stringify(t)} does not exist`,updateNonexistentEdgeTarget:(e,t)=>`Failed to update target of edge with ID ${JSON.stringify(e)} because target port with ID ${JSON.stringify(t)} does not exist`,removeNonexistentEdge:e=>`Failed to remove edge with ID ${JSON.stringify(e)} because it does not exist`,accessEdgesForNonexistentPort:e=>`Failed to access edges for port with ID ${JSON.stringify(e)} because the port does not exist`}),g=class{nodes=new Map;ports=new Map;edges=new Map;nodesElementsMap=new Map;portIncomingEdges=new Map;portOutgoingEdges=new Map;portCycleEdges=new Map;elementPorts=new p;edgesElementsMap=new Map;afterNodeAddedEmitter;onAfterNodeAdded;afterNodeUpdatedEmitter;onAfterNodeUpdated;afterNodePriorityUpdatedEmitter;onAfterNodePriorityUpdated;beforeNodeRemovedEmitter;onBeforeNodeRemoved;afterPortAddedEmitter;onAfterPortAdded;afterPortUpdatedEmitter;onAfterPortUpdated;beforePortRemovedEmitter;onBeforePortRemoved;afterEdgeAddedEmitter;onAfterEdgeAdded;afterEdgeShapeUpdatedEmitter;onAfterEdgeShapeUpdated;afterEdgeUpdatedEmitter;onAfterEdgeUpdated;afterEdgePriorityUpdatedEmitter;onAfterEdgePriorityUpdated;beforeEdgeRemovedEmitter;onBeforeEdgeRemoved;beforeClearEmitter;onBeforeClear;constructor(){[this.afterNodeAddedEmitter,this.onAfterNodeAdded]=d(),[this.afterNodeUpdatedEmitter,this.onAfterNodeUpdated]=d(),[this.afterNodePriorityUpdatedEmitter,this.onAfterNodePriorityUpdated]=d(),[this.beforeNodeRemovedEmitter,this.onBeforeNodeRemoved]=d(),[this.afterPortAddedEmitter,this.onAfterPortAdded]=d(),[this.afterPortUpdatedEmitter,this.onAfterPortUpdated]=d(),[this.beforePortRemovedEmitter,this.onBeforePortRemoved]=d(),[this.afterEdgeAddedEmitter,this.onAfterEdgeAdded]=d(),[this.afterEdgeShapeUpdatedEmitter,this.onAfterEdgeShapeUpdated]=d(),[this.afterEdgeUpdatedEmitter,this.onAfterEdgeUpdated]=d(),[this.afterEdgePriorityUpdatedEmitter,this.onAfterEdgePriorityUpdated]=d(),[this.beforeEdgeRemovedEmitter,this.onBeforeEdgeRemoved]=d(),[this.beforeClearEmitter,this.onBeforeClear]=d()}hasNode(e){return this.nodes.has(e)}getNode(e){let t=this.nodes.get(e);if(t===void 0)throw new m(h.accessNonexistingNode(e));return t}addNode(e){if(this.hasNode(e.id))throw new m(h.addNodeWithExistingId(e.id));let t=this.findNodeIdByElement(e.element);if(t!==void 0)throw new m(h.addNodeWithElementInUse(e.id,t));let n=new Map,r={element:e.element,payload:{x:e.x,y:e.y,centerFn:e.centerFn,priority:e.priority},ports:n};this.nodes.set(e.id,r),this.nodesElementsMap.set(e.element,e.id),this.afterNodeAddedEmitter.emit(e.id)}getAllNodeIds(){return Array.from(this.nodes.keys())}findNodeIdByElement(e){return this.nodesElementsMap.get(e)}updateNode(e,t){if(!this.hasNode(e))throw new m(h.updateNonexistentNode(e));let{payload:n}=this.nodes.get(e);n.x=t.x??n.x,n.y=t.y??n.y,n.centerFn=t.centerFn??n.centerFn,t.priority!==void 0&&(n.priority=t.priority,this.afterNodePriorityUpdatedEmitter.emit(e)),this.afterNodeUpdatedEmitter.emit(e)}removeNode(e){if(!this.hasNode(e))throw new m(h.removeNonexistentNode(e));this.beforeNodeRemovedEmitter.emit(e);let t=this.getNode(e);this.nodesElementsMap.delete(t.element),this.nodes.delete(e)}hasPort(e){return this.ports.has(e)}getPort(e){let t=this.ports.get(e);if(t===void 0)throw new m(h.accessNonexistentPort(e));return t}addPort(e){if(this.hasPort(e.id))throw new m(h.addPortWithExistingId(e.id));if(!this.hasNode(e.nodeId))throw new m(h.addPortToNonexistentNode(e.id,e.nodeId));this.ports.set(e.id,{element:e.element,payload:{direction:e.direction},nodeId:e.nodeId}),this.elementPorts.addRecord(e.element,e.id),this.portCycleEdges.set(e.id,new Set),this.portIncomingEdges.set(e.id,new Set),this.portOutgoingEdges.set(e.id,new Set),this.getNode(e.nodeId).ports.set(e.id,e.element),this.afterPortAddedEmitter.emit(e.id)}updatePort(e,t){if(!this.hasPort(e))throw new m(h.updateNonexistentPort(e));let n=this.getPort(e).payload;n.direction=t.direction??n.direction,this.afterPortUpdatedEmitter.emit(e)}getAllPortIds(){return Array.from(this.ports.keys())}findPortIdsByElement(e){return this.elementPorts.getMultiBySingle(e)}getNodePortIds(e){let t=this.nodes.get(e);if(t===void 0)throw new m(h.accessPortsOfNonexistentNode(e));return Array.from(t.ports.keys())}removePort(e){if(!this.hasPort(e))throw new m(h.removeNonexistentPort(e));let t=this.getPort(e).nodeId;this.beforePortRemovedEmitter.emit(e),this.getNode(t).ports.delete(e),this.ports.delete(e),this.elementPorts.removeByMulti(e)}hasEdge(e){return this.edges.has(e)}getEdge(e){let t=this.edges.get(e);if(t===void 0)throw new m(h.accessNonexistentEdge(e));return t}findEdgeIdByElement(e){return this.edgesElementsMap.get(e)}addEdge(e){if(this.hasEdge(e.id))throw new m(h.addEdgeWithExistingId(e.id));if(!this.hasPort(e.from))throw new m(h.addEdgeFromNonexistentPort(e.id,e.from));if(!this.hasPort(e.to))throw new m(h.addEdgeToNonexistentPort(e.id,e.to));let t=this.findEdgeIdByElement(e.shape.element);if(t!==void 0)throw new m(h.addEdgeWithElementInUse(e.id,t));this.addEdgeInternal(e),this.afterEdgeAddedEmitter.emit(e.id)}updateEdge(e,t){if(!this.hasEdge(e))throw new m(h.updateNonexistentEdge(e));if(t.from!==void 0||t.to!==void 0){if(t.from!==void 0&&!this.hasPort(t.from))throw new m(h.updateNonexistentEdgeSource(e,t.from));if(t.to!==void 0&&!this.hasPort(t.to))throw new m(h.updateNonexistentEdgeTarget(e,t.to));let n=this.getEdge(e),r=n.payload;this.removeEdgeInternal(e),this.addEdgeInternal({id:e,from:t.from??n.from,to:t.to??n.to,shape:r.shape,priority:r.priority})}let n=this.edges.get(e);t.shape!==void 0&&(n.payload.shape=t.shape,this.afterEdgeShapeUpdatedEmitter.emit(e)),t.priority!==void 0&&(n.payload.priority=t.priority,this.afterEdgePriorityUpdatedEmitter.emit(e)),this.afterEdgeUpdatedEmitter.emit(e)}getAllEdgeIds(){return Array.from(this.edges.keys())}removeEdge(e){if(!this.hasEdge(e))throw new m(h.removeNonexistentEdge(e));this.beforeEdgeRemovedEmitter.emit(e),this.removeEdgeInternal(e)}clear(){this.beforeClearEmitter.emit(),this.portIncomingEdges.clear(),this.portOutgoingEdges.clear(),this.portCycleEdges.clear(),this.elementPorts.clear(),this.nodesElementsMap.clear(),this.edgesElementsMap.clear(),this.edges.clear(),this.ports.clear(),this.nodes.clear()}getPortIncomingEdgeIds(e){let t=this.portIncomingEdges.get(e);if(t===void 0)throw new m(h.accessEdgesForNonexistentPort(e));return Array.from(t)}getPortOutgoingEdgeIds(e){let t=this.portOutgoingEdges.get(e);if(t===void 0)throw new m(h.accessEdgesForNonexistentPort(e));return Array.from(t)}getPortCycleEdgeIds(e){let t=this.portCycleEdges.get(e);if(t===void 0)throw new m(h.accessEdgesForNonexistentPort(e));return Array.from(t)}getPortAdjacentEdgeIds(e){return[...this.getPortIncomingEdgeIds(e),...this.getPortOutgoingEdgeIds(e),...this.getPortCycleEdgeIds(e)]}getNodeIncomingEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(t=>{this.getPortIncomingEdgeIds(t).filter(t=>{let n=this.getEdge(t);return this.getPort(n.from).nodeId!==e}).forEach(e=>{n.push(e)})}),n}getNodeOutgoingEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(t=>{this.getPortOutgoingEdgeIds(t).filter(t=>{let n=this.getEdge(t);return this.getPort(n.to).nodeId!==e}).forEach(e=>{n.push(e)})}),n}getNodeCycleEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(t=>{this.getPortCycleEdgeIds(t).forEach(e=>{n.push(e)}),this.getPortIncomingEdgeIds(t).filter(t=>{let n=this.getEdge(t);return this.getPort(n.to).nodeId===e}).forEach(e=>{n.push(e)})}),n}getNodeAdjacentEdgeIds(e){let t=Array.from(this.getNode(e).ports.keys()),n=[];return t.forEach(e=>{this.getPortIncomingEdgeIds(e).forEach(e=>{n.push(e)}),this.getPortOutgoingEdgeIds(e).forEach(e=>{n.push(e)}),this.getPortCycleEdgeIds(e).forEach(e=>{n.push(e)})}),n}addEdgeInternal(e){this.edges.set(e.id,{from:e.from,to:e.to,payload:{shape:e.shape,priority:e.priority}}),this.edgesElementsMap.set(e.shape.element,e.id),e.from===e.to?this.portCycleEdges.get(e.from).add(e.id):(this.portOutgoingEdges.get(e.from).add(e.id),this.portIncomingEdges.get(e.to).add(e.id))}removeEdgeInternal(e){let{from:t,to:n,payload:r}=this.getEdge(e);this.portCycleEdges.get(t).delete(e),this.portCycleEdges.get(n).delete(e),this.portIncomingEdges.get(t).delete(e),this.portIncomingEdges.get(n).delete(e),this.portOutgoingEdges.get(t).delete(e),this.portOutgoingEdges.get(n).delete(e),this.edges.delete(e),this.edgesElementsMap.delete(r.shape.element)}},_=e=>({scale:1/e.scale,x:-e.x/e.scale,y:-e.y/e.scale}),v={scale:1,x:0,y:0},y=(e,t)=>({x:e.scale*t.x+e.x,y:e.scale*t.y+e.y}),b=class{host;viewportMatrix=v;contentMatrix=v;beforeUpdateEmitter;onBeforeUpdated;afterUpdateEmitter;onAfterUpdated;afterResizeEmitter;onAfterResize;observer=new ResizeObserver(()=>{this.afterResizeEmitter.emit()});constructor(e){this.host=e,[this.afterUpdateEmitter,this.onAfterUpdated]=d(),[this.beforeUpdateEmitter,this.onBeforeUpdated]=d(),[this.afterResizeEmitter,this.onAfterResize]=d(),this.observer.observe(this.host)}getViewportMatrix(){return this.viewportMatrix}getContentMatrix(){return this.contentMatrix}patchViewportMatrix(e){this.viewportMatrix={scale:e.scale??this.viewportMatrix.scale,x:e.x??this.viewportMatrix.x,y:e.y??this.viewportMatrix.y},this.beforeUpdateEmitter.emit(),this.contentMatrix=_(this.viewportMatrix),this.afterUpdateEmitter.emit()}patchContentMatrix(e){this.contentMatrix={scale:e.scale??this.contentMatrix.scale,x:e.x??this.contentMatrix.x,y:e.y??this.contentMatrix.y},this.beforeUpdateEmitter.emit(),this.viewportMatrix=_(this.contentMatrix),this.afterUpdateEmitter.emit()}getDimensions(){let{width:e,height:t}=this.host.getBoundingClientRect();return{width:e,height:t}}createContentCoords(e){return y(this.viewportMatrix,e)}createViewportCoords(e){return y(this.contentMatrix,e)}destroy(){this.observer.disconnect()}},x=class e{canvas;elementToNodeId=new Map;nodesResizeObserver;onAfterNodeAdded=e=>{let t=this.canvas.graph.getNode(e);this.elementToNodeId.set(t.element,e),this.nodesResizeObserver.observe(t.element)};onBeforeNodeRemoved=e=>{let t=this.canvas.graph.getNode(e);this.elementToNodeId.delete(t.element),this.nodesResizeObserver.unobserve(t.element)};reset=()=>{this.nodesResizeObserver.disconnect(),this.elementToNodeId.clear()};revert=()=>{this.reset()};constructor(e){this.canvas=e,this.nodesResizeObserver=new ResizeObserver(e=>{e.forEach(e=>{let t=e.target;this.handleNodeResize(t)})}),this.canvas.graph.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.canvas.graph.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.revert)}static configure(t){new e(t)}handleNodeResize(e){let t=this.elementToNodeId.get(e);this.canvas.updateNode(t)}},S=(e,t,n)=>{let{x:r,y:i,width:a,height:o}=e.getBoundingClientRect();return t>=r&&t<=r+a&&n>=i&&n<=i+o},ee=(e,t,n)=>t>=0&&t<=e.innerWidth&&n>=0&&n<=e.innerHeight,te=class{element;win;constructor(e,t){this.element=e,this.win=t}verify(e,t){return S(this.element,e,t)&&ee(this.win,e,t)}},C=(e,t)=>{t===null?e.style.removeProperty(`cursor`):e.style.cursor=t},w=e=>{let t=document.createElement(`div`);return{id:e.overlayNodeId,element:t,x:e.portCoords.x,y:e.portCoords.y,ports:[{id:e.overlayNodeId,element:t,direction:e.portDirection}]}},ne=(e,t,n)=>{let r=t;for(;r!==null;){let t=n(e.findPortIdsByElement(r));if(t!==null)return{status:`portFound`,portId:t};if(e.findNodeIdByElement(r)!==void 0)return{status:`nodeEncountered`};r=r.parentElement}return{status:`notFound`}};function*re(e,t){let n=e.elementsFromPoint(t.x,t.y);for(let e of n){if(e.shadowRoot!==null){let n=re(e.shadowRoot,t);for(let e of n)yield e}yield e}}var ie=(e,t,n)=>{let r=re(document,t);for(let t of r){let r=ne(e,t,n);if(r.status===`portFound`)return r.portId;if(r.status===`nodeEncountered`)return null}return null},T=function(e){return e.StaticNodeId=`static`,e.DraggingNodeId=`dragging`,e.EdgeId=`edge`,e}({}),ae=(e,t)=>({x:e/2,y:t/2}),E=(e,t,n)=>({x:t.x*e.x-t.y*e.y+((1-t.x)*n.x+t.y*n.y),y:t.y*e.x+t.x*e.y+((1-t.x)*n.y-t.y*n.x)}),oe=(e,t,n)=>{let r={x:e.x+e.width/2,y:e.y+e.height/2},i={x:t.x+t.width/2,y:t.y+t.height/2},a=Math.min(r.x,i.x)-n,o=Math.min(r.y,i.y)-n,s=2*n;return{x:a,y:o,width:Math.abs(i.x-r.x)+s,height:Math.abs(i.y-r.y)+s,from:{x:r.x-a,y:r.y-o},to:{x:i.x-a,y:i.y-o}}},D=.5*.5*.5,O=3*D,se=class{path;midpoint;constructor(e){let{from:t,to:n,arrowLength:r,fromDir:i,toDir:a,curvature:o,hasSourceArrow:s,hasTargetArrow:c}=e,l=E({x:t.x+r,y:t.y},i,t),u=E({x:n.x-r,y:n.y},a,n),d={x:l.x+i.x*o,y:l.y+i.y*o},f={x:u.x-a.x*o,y:u.y-a.y*o},p=D*l.x+O*d.x+O*f.x+D*u.x,m=D*l.y+O*d.y+O*f.y+D*u.y;this.midpoint={x:p,y:m};let h=`M ${l.x} ${l.y} C ${d.x} ${d.y}, ${f.x} ${f.y}, ${u.x} ${u.y}`,g=s?``:`M ${t.x} ${t.y} L ${l.x} ${l.y} `,_=c?``:` M ${u.x} ${u.y} L ${n.x} ${n.y}`;this.path=`${g}${h}${_}`}},ce=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,curvature:r,fromDir:i,toDir:a,detourDir:o,from:s,to:c,arrowLength:l,detourDistance:u}=e,d=t?E({x:s.x+l,y:s.y},i,s):s,f=n?E({x:c.x-l,y:c.y},a,c):c,p=Math.cos(o)*u,m=Math.sin(o)*u,h=E({x:s.x+l,y:s.y},i,s),g={x:h.x+p,y:h.y+m},_=E({x:c.x-l,y:c.y},a,c),v={x:_.x+p,y:_.y+m},y={x:(g.x+v.x)/2,y:(g.y+v.y)/2},b={x:h.x+r*i.x,y:h.y+r*i.y},x={x:_.x-r*a.x,y:_.y-r*a.y},S={x:h.x+p,y:h.y+m},ee={x:_.x+p,y:_.y+m};this.path=[`M ${d.x} ${d.y}`,`L ${h.x} ${h.y}`,`C ${b.x} ${b.y} ${S.x} ${S.y} ${y.x} ${y.y}`,`C ${ee.x} ${ee.y} ${x.x} ${x.y} ${_.x} ${_.y}`,`L ${f.x} ${f.y}`].join(` `),this.midpoint=y}},k=Object.freeze({edgeColor:`--edge-color`}),le=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return t.style.pointerEvents=`none`,t.style.position=`absolute`,t.style.top=`0`,t.style.left=`0`,t.style.overflow=`visible`,t.style.setProperty(k.edgeColor,e),t},ue=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`stroke`,`var(${k.edgeColor})`),t.setAttribute(`stroke-width`,`${e}`),t.setAttribute(`fill`,`none`),t},A=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return e.setAttribute(`fill`,`var(${k.edgeColor})`),e},de=(e,t)=>{e.style.transform=`translate(${t.x}px, ${t.y}px)`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`},j=(e,t)=>{let n=[];if(e.length>0&&n.push(`M ${e[0].x} ${e[0].y}`),e.length===2&&n.push(`L ${e[1].x} ${e[1].y}`),e.length>2){let r=e.length-1,i=0,a=0,o=0;e.forEach((s,c)=>{let l=0,u=0,d=0,f=c>0,p=c<r,m=f&&p;if(f&&(l=-i,u=-a,d=o),p){let t=e[c+1];i=t.x-s.x,a=t.y-s.y,o=Math.sqrt(i*i+a*a)}let h=o===0?0:Math.min((m?t:0)/o,c<r-1?.5:1),g=m?{x:s.x+i*h,y:s.y+a*h}:s,_=d===0?0:Math.min((m?t:0)/d,c>1?.5:1),v=m?{x:s.x+l*_,y:s.y+u*_}:s;c>0&&n.push(`L ${v.x} ${v.y}`),m&&n.push(`C ${s.x} ${s.y} ${s.x} ${s.y} ${g.x} ${g.y}`)})}return n.join(` `)},fe=(e,t)=>{let n=e.linePoint,r=t.linePoint,i=r.x-n.x>=0,a=e.dir.x>=0;if(a===t.dir.x>=0){let o=a===i,s={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return o?{points:[e.arrowPoint,{x:s.x,y:n.y},{x:s.x,y:r.y},t.arrowPoint],midpoint:s}:{points:[e.arrowPoint,n,{x:n.x,y:s.y},{x:r.x,y:s.y},r,t.arrowPoint],midpoint:s}}let o=a===i,s=(n.y+r.y)/2;if(o){let i={x:r.x,y:n.y};return{points:[e.arrowPoint,i,r,t.arrowPoint],midpoint:{x:i.x,y:s}}}let c={x:n.x,y:r.y};return{points:[e.arrowPoint,n,c,t.arrowPoint],midpoint:{x:c.x,y:s}}},M=e=>({x:e.y,y:e.x}),pe=(e,t)=>{let n=fe({arrowPoint:M(e.arrowPoint),linePoint:M(e.linePoint),dir:M(e.dir)},{arrowPoint:M(t.arrowPoint),linePoint:M(t.linePoint),dir:M(t.dir)});return{points:n.points.map(e=>M(e)),midpoint:M(n.midpoint)}},N=e=>{let t=[];for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n],a=i.x-r.x,o=i.y-r.y,s=Math.sqrt(a*a+o*o);t.push({start:r,end:i,distance:s})}let n=t.reduce((e,t)=>e+t.distance,0)/2,r=0;for(let e of t){let t=r+e.distance;if(t>=n){let t=n-r,{start:i,end:a,distance:o}=e;if(o===0)continue;let s=t/o,c=a.x-i.x,l=a.y-i.y;return{x:i.x+c*s,y:i.y+l*s}}r=t}if(r===0&&e.length>0)return e[0];throw Error(`Failed to calculate midpoint`)},me=(e,t)=>{let n=e.linePoint,r=e.arrowPoint,i=t.linePoint,a=t.arrowPoint,o=t.dir.y>=0,s=e.dir.x>=0,c=i.y-n.y>=0,l=s===i.x-n.x>=0,u=o===c;if(l){if(u){let e={x:a.x,y:r.y};return{points:[r,e,a],midpoint:N([n,e,i])}}let e=(n.x+i.x)/2,t={x:e,y:n.y},o={x:e,y:i.y};return{points:[r,t,o,i,a],midpoint:N([n,t,o,i])}}if(u){let e=(n.y+i.y)/2,t={x:n.x,y:e},o={x:i.x,y:e};return{points:[r,n,t,o,a],midpoint:N([n,t,o,i])}}let d={x:n.x,y:i.y};return{points:[r,n,d,i,a],midpoint:N([n,d,i])}},he=(e,t)=>{let n=me({arrowPoint:M(e.arrowPoint),linePoint:M(e.linePoint),dir:M(e.dir)},{arrowPoint:M(t.arrowPoint),linePoint:M(t.linePoint),dir:M(t.dir)});return{points:n.points.map(e=>M(e)),midpoint:M(n.midpoint)}},ge=(e,t)=>{let n=Math.abs(e.dir.y)<1e-10,r=Math.abs(t.dir.y)<1e-10;return n?r?fe(e,t):me(e,t):r?he(e,t):pe(e,t)},_e=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,from:r,to:i,arrowLength:a,fromDir:o,toDir:s,arrowOffset:c,detourDir:l,detourDistance:u,roundness:d}=e,f=t?E({x:r.x+a,y:r.y},o,r):r,p=n?E({x:i.x-a,y:i.y},s,i):i,m=a+c,h=Math.cos(l)*u,g=Math.sin(l)*u,_=E({x:r.x+m,y:r.y},o,r),v={x:_.x+h,y:_.y+g},y=E({x:i.x-m,y:i.y},s,i),b={x:y.x+h,y:y.y+g};this.midpoint={x:(v.x+b.x)/2,y:(v.y+b.y)/2},this.path=j([f,_,v,b,y,p],d)}},ve=class{path;midpoint;constructor(e){let{from:t,to:n,hasSourceArrow:r,hasTargetArrow:i,arrowLength:a,fromDir:o,toDir:s,arrowOffset:c,roundness:l}=e,u=this.createArrowPoint(r,o,t,a),d=this.createArrowPoint(i,s,n,-a),f=a+c,p=E({x:t.x+f,y:t.y},o,t),m=E({x:n.x-f,y:n.y},s,n);this.path=j([u,p,m,d],l);let h=(p.x+m.x)/2,g=(p.y+m.y)/2;this.midpoint={x:h,y:g}}createArrowPoint(e,t,n,r){return e?E({x:n.x+r,y:n.y},t,n):n}},ye=class{path;midpoint;constructor(e){let{from:t,to:n,fromDir:r,toDir:i,arrowLength:a,arrowOffset:o,roundness:s,hasSourceArrow:c,hasTargetArrow:l}=e,u=c?E({x:t.x+a,y:t.y},r,t):t,d=l?E({x:n.x-a,y:n.y},i,n):n,f=a+o,p=E({x:t.x+f,y:t.y},r,t),m=E({x:n.x-f,y:n.y},i,n),h=ge({arrowPoint:u,linePoint:p,dir:r},{arrowPoint:d,linePoint:m,dir:i});this.path=j(h.points,s),this.midpoint=h.midpoint}},be=class{path;midpoint;constructor(e){let{side:t,arrowLength:n,arrowOffset:r,dir:i,origin:a,hasArrow:o}=e,s=n+r,c=s+2*t,l=[{x:n,y:0},{x:s,y:0},{x:s,y:t},{x:c,y:t},{x:c,y:-t},{x:s,y:-t},{x:s,y:0},{x:n,y:0}].map(e=>E(e,i,{x:0,y:0})).map(e=>({x:e.x+a.x,y:e.y+a.y})),u=`M ${a.x} ${a.y} L ${l[0].x} ${l[0].y} `;this.path=`${o?``:u}${j(l,e.roundness)}`,this.midpoint={x:(l[3].x+l[4].x)/2,y:(l[3].y+l[4].y)/2}}},xe=class{path;midpoint;constructor(e){let{arrowLength:t,radius:n,smallRadius:r,dir:i,origin:a,hasArrow:o}=e,s=r+n,c=r*n/s,l=Math.sqrt(s*s-r*r),u=l*r/s,d=l+n+t,f=t+u,p=[{x:t,y:0},{x:f,y:c},{x:f,y:-c},{x:d,y:0}].map(e=>E(e,i,{x:0,y:0})).map(e=>({x:e.x+a.x,y:e.y+a.y})),m=[`M ${p[0].x} ${p[0].y}`,`A ${r} ${r} 0 0 1 ${p[1].x} ${p[1].y}`,`A ${n} ${n} 0 1 0 ${p[2].x} ${p[2].y}`,`A ${r} ${r} 0 0 1 ${p[0].x} ${p[0].y}`].join(` `),h=`M ${a.x} ${a.y} L ${p[0].x} ${p[0].y} `;this.path=`${o?``:h}${m}`,this.midpoint=p[3]}},Se=(e,t,n)=>{let r=Math.max(e.y,t.y),i=Math.min(e.y,t.y);return(n>=0?r:i)+n},Ce=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,arrowLength:r,from:i,to:a,fromDir:o,toDir:s,arrowOffset:c,roundness:l,detourDistance:u}=e,d=t?E({x:i.x+r,y:i.y},o,i):i,f=n?E({x:a.x-r,y:a.y},s,a):a,p=r+c,m=E({x:i.x+p,y:i.y},o,i),h=E({x:a.x-p,y:a.y},s,a),g=Se(m,h,u);this.midpoint={x:(m.x+h.x)/2,y:g},this.path=j([d,m,{x:m.x,y:g},{x:h.x,y:g},h,f],l)}},we=(e,t,n)=>{let r=Math.max(e.x,t.x),i=Math.min(e.x,t.x);return(n>=0?r:i)+n},Te=class{path;midpoint;constructor(e){let{hasSourceArrow:t,hasTargetArrow:n,arrowLength:r,fromDir:i,toDir:a,from:o,to:s,arrowOffset:c,detourDistance:l,roundness:u}=e,d=t?E({x:o.x+r,y:o.y},i,o):o,f=n?E({x:s.x-r,y:s.y},a,s):s,p=r+c,m=E({x:o.x+p,y:o.y},i,o),h=E({x:s.x-p,y:s.y},a,s),g=we(m,h,l);this.midpoint={x:g,y:(m.y+h.y)/2},this.path=j([d,m,{x:g,y:m.y},{x:g,y:h.y},h,f],u)}},Ee=class{path;midpoint;constructor(e){let t=Math.abs(e.fromDir.y)<1e-10,n=Math.abs(e.toDir.y)<1e-10;if(t&&n){let t=new Ce(e);this.path=t.path,this.midpoint=t.midpoint;return}if(!t&&!n){let t=new Te(e);this.path=t.path,this.midpoint=t.midpoint;return}let r=new ye(e);this.path=r.path,this.midpoint=r.midpoint}},P=Object.freeze({color:`#777777`,width:1,arrowLength:20,polygonArrowRadius:4,circleArrowRadius:8,wedgeArrowSmallRadius:20,wedgeArrowRadius:100,wedgeArrowAngle:Math.PI/12,arrowOffset:15,hasSourceArrow:!1,hasTargetArrow:!1,cycleRadius:30,cycleSquareSide:30,roundness:10,detourDistance:100,detourDirection:-Math.PI/2,detourDirectionVertical:0,smallCycleRadius:15,curvature:90,interactiveWidth:10,portOffset:0}),De=e=>({x:Math.cos(e),y:Math.sin(e)}),F=class{params;element;group=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);line;sourceArrow=null;targetArrow=null;onAfterRender;afterRenderEmitter;arrowRenderer;constructor(e){this.params=e,[this.afterRenderEmitter,this.onAfterRender]=d(),this.arrowRenderer=this.params.arrowRenderer,this.element=le(e.color),this.element.appendChild(this.group),this.line=ue(e.width),this.group.appendChild(this.line),e.hasSourceArrow&&(this.sourceArrow=A(),this.group.appendChild(this.sourceArrow)),e.hasTargetArrow&&(this.targetArrow=A(),this.group.appendChild(this.targetArrow))}render(e){let{x:n,y:r,width:i,height:a,from:o,to:s}=oe(e.from,e.to,this.params.padding);de(this.element,{x:n,y:r,width:i,height:a});let c=De(e.from.direction),l=De(e.to.direction),u={x:-l.x,y:-l.y},d;e.category===t.PortCycle?(d=this.params.createCyclePath,u=c):d=e.category===t.NodeCycle?this.params.createDetourPath:this.params.createLinePath;let f=d(o,s,c,l);this.line.setAttribute(`d`,f.path);let p=null;this.sourceArrow&&(p=this.arrowRenderer({direction:c,shift:o,arrowLength:this.params.arrowLength}),this.sourceArrow.setAttribute(`d`,p));let m=null;this.targetArrow&&(m=this.arrowRenderer({direction:u,shift:s,arrowLength:this.params.arrowLength}),this.targetArrow.setAttribute(`d`,m)),this.afterRenderEmitter.emit({edgePath:f,sourceArrowPath:p,targetArrowPath:m})}},Oe=e=>t=>{let n=[{x:0,y:0},{x:t.arrowLength,y:e.radius},{x:t.arrowLength,y:-e.radius}].map(e=>E(e,t.direction,{x:0,y:0})).map(e=>({x:e.x+t.shift.x,y:e.y+t.shift.y}));return`${`M ${n[0].x} ${n[0].y}`} ${`L ${n[1].x} ${n[1].y}`} ${`L ${n[2].x} ${n[2].y}`} Z`},ke=e=>t=>{let n=e.radius,r=t.arrowLength,i=(r*r+2*r*n)/(2*n),a=i+n,o=r+n-n*(r+n)/a,s=n*i/a,c=[{x:0,y:0},{x:o,y:-s},{x:o,y:s}].map(e=>E(e,t.direction,{x:0,y:0})).map(e=>({x:e.x+t.shift.x,y:e.y+t.shift.y}));return`${`M ${c[0].x} ${c[0].y}`} ${`A ${i} ${i} 0 0 0 ${c[1].x} ${c[1].y}`} ${`A ${n} ${n} 0 0 0 ${c[2].x} ${c[2].y}`} ${`A ${i} ${i} 0 0 0 ${c[0].x} ${c[0].y}`}`},Ae=e=>t=>{let n=e.smallRadius,r=e.radius,i=E({x:t.arrowLength,y:0},{x:Math.cos(e.angle),y:Math.sin(e.angle)},{x:t.arrowLength+e.smallRadius,y:0}),a=[{x:0,y:0},{x:i.x,y:-i.y},i].map(e=>E(e,t.direction,{x:0,y:0})).map(e=>({x:e.x+t.shift.x,y:e.y+t.shift.y}));return`${`M ${a[0].x} ${a[0].y}`} ${`A ${r} ${r} 0 0 1 ${a[1].x} ${a[1].y}`} ${`A ${n} ${n} 0 0 1 ${a[2].x} ${a[2].y}`} ${`A ${r} ${r} 0 0 1 ${a[0].x} ${a[0].y}`}`},I=e=>{if(typeof e==`function`)return e;switch(e.type){case`triangle`:return Oe({radius:e.radius??P.polygonArrowRadius});case`arc`:return ke({radius:e.radius??P.circleArrowRadius});default:return Ae({smallRadius:e.smallRadius??P.wedgeArrowSmallRadius,angle:e.angle??P.wedgeArrowAngle,radius:e.radius??P.wedgeArrowRadius})}},je=class{element;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;curvature;portCycleRadius;portCycleSmallRadius;detourDirection;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new xe({origin:e,dir:n,radius:this.portCycleRadius,smallRadius:this.portCycleSmallRadius,arrowLength:this.arrowLength,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new ce({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,detourDir:this.detourDirection,detourDistance:this.detourDistance,curvature:this.curvature,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new se({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,curvature:this.curvature,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??P.arrowLength,this.curvature=e?.curvature??P.curvature,this.portCycleRadius=e?.cycleRadius??P.cycleRadius,this.portCycleSmallRadius=e?.smallCycleRadius??P.smallCycleRadius,this.detourDirection=e?.detourDirection??P.detourDirection,this.detourDistance=e?.detourDistance??P.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??P.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??P.hasTargetArrow,this.pathShape=new F({color:e?.color??P.color,width:e?.width??P.width,arrowRenderer:I(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){this.pathShape.render(e)}},Me=class{element;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;arrowOffset;roundness;cycleSquareSide;detourDirection;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new be({origin:e,dir:n,arrowLength:this.arrowLength,side:this.cycleSquareSide,arrowOffset:this.arrowOffset,roundness:this.roundness,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new _e({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,detourDir:this.detourDirection,detourDistance:this.detourDistance,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new ve({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??P.arrowLength,this.arrowOffset=e?.arrowOffset??P.arrowOffset,this.cycleSquareSide=e?.cycleSquareSide??P.cycleSquareSide;let t=e?.roundness??P.roundness;this.roundness=Math.min(t,this.arrowOffset,this.cycleSquareSide/2),this.detourDirection=e?.detourDirection??P.detourDirection,this.detourDistance=e?.detourDistance??P.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??P.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??P.hasTargetArrow,this.pathShape=new F({color:e?.color??P.color,width:e?.width??P.width,arrowRenderer:I(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){this.pathShape.render(e)}},Ne=e=>{let t=e+Math.PI/4,n=Math.cos(t),r=Math.sin(t);return n>0?r>0?0:-Math.PI/2:r>0?Math.PI/2:Math.PI},Pe=class{element;group;line;sourceArrow;targetArrow;onAfterRender;arrowLength;arrowOffset;roundness;cycleSquareSide;detourDistance;hasSourceArrow;hasTargetArrow;pathShape;createCyclePath=(e,t,n)=>new be({origin:e,dir:n,arrowLength:this.arrowLength,side:this.cycleSquareSide,arrowOffset:this.arrowOffset,roundness:this.roundness,hasArrow:this.hasSourceArrow||this.hasTargetArrow});createDetourPath=(e,t,n,r)=>new Ee({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,detourDistance:this.detourDistance,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});createLinePath=(e,t,n,r)=>new ye({from:e,to:t,fromDir:n,toDir:r,arrowLength:this.arrowLength,arrowOffset:this.arrowOffset,roundness:this.roundness,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow});constructor(e){this.arrowLength=e?.arrowLength??P.arrowLength,this.arrowOffset=e?.arrowOffset??P.arrowOffset,this.cycleSquareSide=e?.cycleSquareSide??P.cycleSquareSide;let t=e?.roundness??P.roundness;this.roundness=Math.min(t,this.arrowOffset,this.cycleSquareSide/2),this.detourDistance=e?.detourDistance??P.detourDistance,this.hasSourceArrow=e?.hasSourceArrow??P.hasSourceArrow,this.hasTargetArrow=e?.hasTargetArrow??P.hasTargetArrow,this.pathShape=new F({color:e?.color??P.color,width:e?.width??P.width,arrowRenderer:I(e?.arrowRenderer??{}),arrowLength:this.arrowLength,hasSourceArrow:this.hasSourceArrow,hasTargetArrow:this.hasTargetArrow,createCyclePath:this.createCyclePath,createDetourPath:this.createDetourPath,createLinePath:this.createLinePath,padding:50}),this.element=this.pathShape.element,this.group=this.pathShape.group,this.line=this.pathShape.line,this.sourceArrow=this.pathShape.sourceArrow,this.targetArrow=this.pathShape.targetArrow,this.onAfterRender=this.pathShape.onAfterRender}render(e){let{from:t,to:n,category:r}=e;this.pathShape.render({category:r,from:{...t,direction:Ne(t.direction)},to:{...n,direction:Ne(n.direction)}})}},Fe=e=>{let{direction:t,radius:n}=e,{x:r,y:i}=t,{horizontal:a,vertical:o}=n,s=i/r,c=Math.abs(o/s),l=Math.abs(a*s),u=Math.min(a,c),d=Math.min(o,l);return Math.sqrt(u*u+d*d)},Ie=e=>typeof e==`number`?()=>e:e===`box`?Fe:e,Le=P.portOffset,L=class{element;group=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);line;sourceArrow=null;targetArrow=null;color;width;arrowLength;sourceOffsetFn;targetOffsetFn;onAfterRender;afterRenderEmitter;arrowRenderer;constructor(e){[this.afterRenderEmitter,this.onAfterRender]=d(),this.color=e?.color??P.color,this.width=e?.width??P.width,this.arrowLength=e?.arrowLength??P.arrowLength,this.arrowRenderer=I(e?.arrowRenderer??{}),this.sourceOffsetFn=Ie(e?.sourceOffset??Le),this.targetOffsetFn=Ie(e?.targetOffset??Le),this.element=le(this.color),this.element.appendChild(this.group),this.line=ue(this.width),this.group.appendChild(this.line),e?.hasSourceArrow&&(this.sourceArrow=A(),this.group.appendChild(this.sourceArrow)),e?.hasTargetArrow&&(this.targetArrow=A(),this.group.appendChild(this.targetArrow))}render(e){let{x:t,y:n,width:r,height:i,from:a,to:o}=oe(e.from,e.to,50);de(this.element,{x:t,y:n,width:r,height:i});let s=o.x-a.x,c=o.y-a.y,l=Math.sqrt(s*s+c*c);if(l===0){this.renderEmpty(a);return}let u={x:s/l,y:c/l},d=this.sourceOffsetFn({direction:{x:u.x,y:u.y},radius:{horizontal:e.from.width/2,vertical:e.from.height/2}}),f=this.targetOffsetFn({direction:{x:-u.x,y:-u.y},radius:{horizontal:e.to.width/2,vertical:e.to.height/2}}),p={x:a.x+d*u.x,y:a.y+d*u.y},m={x:o.x-f*u.x,y:o.y-f*u.y},h=this.sourceArrow===null?0:this.arrowLength,g={x:p.x+h*u.x,y:p.y+h*u.y},_=this.targetArrow===null?0:this.arrowLength,v={x:m.x-_*u.x,y:m.y-_*u.y},y={x:(p.x+m.x)/2,y:(p.y+m.y)/2},b=`M ${g.x} ${g.y} L ${v.x} ${v.y}`;this.line.setAttribute(`d`,b);let x=null,S=null;if(this.sourceArrow){let e={x:u.x*d+a.x,y:u.y*d+a.y};x=this.arrowRenderer({direction:u,shift:e,arrowLength:this.arrowLength}),this.sourceArrow.setAttribute(`d`,x)}if(this.targetArrow){let e={x:u.x*f,y:u.y*f};S=this.arrowRenderer({direction:{x:-u.x,y:-u.y},shift:{x:o.x-e.x,y:o.y-e.y},arrowLength:this.arrowLength}),this.targetArrow.setAttribute(`d`,S)}this.afterRenderEmitter.emit({edgePath:{path:b,midpoint:y},sourceArrowPath:x,targetArrowPath:S})}renderEmpty(e){let t=null,n=null;this.line.setAttribute(`d`,``),this.sourceArrow!==null&&(t=``,this.sourceArrow.setAttribute(`d`,t)),this.targetArrow!==null&&(n=``,this.targetArrow.setAttribute(`d`,n)),this.afterRenderEmitter.emit({edgePath:{path:``,midpoint:e},sourceArrowPath:t,targetArrowPath:n})}},Re=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);return e.style.pointerEvents=`auto`,e.style.cursor=`pointer`,e},ze=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`stroke`,`transparent`),t.setAttribute(`stroke-width`,`${e}`),t.setAttribute(`fill`,`none`),t.setAttribute(`stroke-linecap`,`round`),t},Be=e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return t.setAttribute(`stroke-linejoin`,`round`),t.setAttribute(`stroke-width`,`${e}`),t.setAttribute(`fill`,`transparent`),t.setAttribute(`stroke`,`transparent`),t},Ve=class extends Error{constructor(e){super(e),this.name=`InteractiveEdgeError`}},He=class e{baseEdge;element;group;line;sourceArrow;targetArrow;handle=Re();onAfterRender;interactiveLine;interactiveSourceArrow=null;interactiveTargetArrow=null;constructor(t,n){if(this.baseEdge=t,t instanceof e)throw new Ve(`interactive edge can be configured only once`);this.element=this.baseEdge.element,this.group=this.baseEdge.group,this.line=this.baseEdge.line,this.sourceArrow=this.baseEdge.sourceArrow,this.targetArrow=this.baseEdge.targetArrow,this.onAfterRender=this.baseEdge.onAfterRender;let r=n?.distance??P.interactiveWidth;this.interactiveLine=ze(r),this.handle.appendChild(this.interactiveLine),this.sourceArrow&&(this.interactiveSourceArrow=Be(r),this.handle.appendChild(this.interactiveSourceArrow)),this.targetArrow&&(this.interactiveTargetArrow=Be(r),this.handle.appendChild(this.interactiveTargetArrow)),this.group.appendChild(this.handle),this.baseEdge.onAfterRender.subscribe(e=>{this.interactiveLine.setAttribute(`d`,e.edgePath.path),this.interactiveSourceArrow&&this.interactiveSourceArrow.setAttribute(`d`,e.sourceArrowPath),this.interactiveTargetArrow&&this.interactiveTargetArrow.setAttribute(`d`,e.targetArrowPath)})}render(e){this.baseEdge.render(e)}},Ue=class{baseShape;midpointElement;group;line;sourceArrow;targetArrow;onAfterRender;element;constructor(e,t){this.baseShape=e,this.midpointElement=t,this.element=this.baseShape.element,this.group=this.baseShape.group,this.line=this.baseShape.line,this.sourceArrow=this.baseShape.sourceArrow,this.targetArrow=this.baseShape.targetArrow,this.onAfterRender=this.baseShape.onAfterRender,this.element.append(this.midpointElement),this.baseShape.onAfterRender.subscribe(e=>{let t=e.edgePath.midpoint,n=`translate(${t.x}px, ${t.y}px)`;this.midpointElement.style.setProperty(`transform`,n)})}render(e){this.baseShape.render(e)}},We=class{graphStore;onAfterNodeAdded;onAfterNodeUpdated;onAfterNodePriorityUpdated;onBeforeNodeRemoved;onAfterPortMarked;onAfterPortUpdated;onBeforePortUnmarked;onAfterEdgeAdded;onAfterEdgeShapeUpdated;onAfterEdgeUpdated;onAfterEdgePriorityUpdated;onBeforeEdgeRemoved;onBeforeClear;constructor(e){this.graphStore=e,this.onAfterNodeAdded=this.graphStore.onAfterNodeAdded,this.onAfterNodeUpdated=this.graphStore.onAfterNodeUpdated,this.onAfterNodePriorityUpdated=this.graphStore.onAfterNodePriorityUpdated,this.onBeforeNodeRemoved=this.graphStore.onBeforeNodeRemoved,this.onAfterPortMarked=this.graphStore.onAfterPortAdded,this.onAfterPortUpdated=this.graphStore.onAfterPortUpdated,this.onBeforePortUnmarked=this.graphStore.onBeforePortRemoved,this.onAfterEdgeAdded=this.graphStore.onAfterEdgeAdded,this.onAfterEdgeShapeUpdated=this.graphStore.onAfterEdgeShapeUpdated,this.onAfterEdgeUpdated=this.graphStore.onAfterEdgeUpdated,this.onAfterEdgePriorityUpdated=this.graphStore.onAfterEdgePriorityUpdated,this.onBeforeEdgeRemoved=this.graphStore.onBeforeEdgeRemoved,this.onBeforeClear=this.graphStore.onBeforeClear}hasNode(e){return this.graphStore.hasNode(e)}getNode(e){let t=this.graphStore.getNode(e),{payload:n}=t;return{element:t.element,x:n.x,y:n.y,centerFn:n.centerFn,priority:n.priority}}findNodeIdByElement(e){return this.graphStore.findNodeIdByElement(e)}getAllNodeIds(){return this.graphStore.getAllNodeIds()}hasPort(e){return this.graphStore.hasPort(e)}getPort(e){let t=this.graphStore.getPort(e);return{element:t.element,direction:t.payload.direction,nodeId:t.nodeId}}getAllPortIds(){return this.graphStore.getAllPortIds()}getNodePortIds(e){return this.graphStore.getNodePortIds(e)}findPortIdsByElement(e){return this.graphStore.findPortIdsByElement(e)}getAllEdgeIds(){return this.graphStore.getAllEdgeIds()}hasEdge(e){return this.graphStore.hasEdge(e)}getEdge(e){let t=this.graphStore.getEdge(e),{payload:n}=t;return{from:t.from,to:t.to,priority:n.priority,shape:n.shape}}findEdgeIdByElement(e){return this.graphStore.findEdgeIdByElement(e)}getPortIncomingEdgeIds(e){return this.graphStore.getPortIncomingEdgeIds(e)}getPortOutgoingEdgeIds(e){return this.graphStore.getPortOutgoingEdgeIds(e)}getPortCycleEdgeIds(e){return this.graphStore.getPortCycleEdgeIds(e)}getPortAdjacentEdgeIds(e){return this.graphStore.getPortAdjacentEdgeIds(e)}getNodeIncomingEdgeIds(e){return this.graphStore.getNodeIncomingEdgeIds(e)}getNodeOutgoingEdgeIds(e){return this.graphStore.getNodeOutgoingEdgeIds(e)}getNodeCycleEdgeIds(e){return this.graphStore.getNodeCycleEdgeIds(e)}getNodeAdjacentEdgeIds(e){return this.graphStore.getNodeAdjacentEdgeIds(e)}},R=class{checkExists;counter=0;constructor(e){this.checkExists=e}create(e){if(e!==void 0)return e;for(;this.checkExists(this.counter);)this.counter++;return this.counter}reset(){this.counter=0}},Ge=class{graphStore;htmlView;params;nodeIdGenerator=new R(e=>this.graphStore.hasNode(e));portIdGenerator=new R(e=>this.graphStore.hasPort(e));edgeIdGenerator=new R(e=>this.graphStore.hasEdge(e));onAfterNodeAdded=e=>{this.htmlView.attachNode(e)};onAfterNodeUpdated=e=>{this.htmlView.updateNodePosition(e),this.graphStore.getNodeAdjacentEdgeIds(e).forEach(e=>{this.htmlView.renderEdge(e)})};onAfterNodePriorityUpdated=e=>{this.htmlView.updateNodePriority(e)};onBeforeNodeRemoved=e=>{this.graphStore.getNodePortIds(e).forEach(e=>{this.unmarkPort(e)}),this.htmlView.detachNode(e)};onAfterPortUpdated=e=>{this.graphStore.getPortAdjacentEdgeIds(e).forEach(e=>{this.htmlView.renderEdge(e)})};onBeforePortUnmarked=e=>{this.graphStore.getPortAdjacentEdgeIds(e).forEach(e=>{this.removeEdge(e)})};onAfterEdgeAdded=e=>{this.htmlView.attachEdge(e)};onAfterEdgeShapeUpdated=e=>{this.htmlView.updateEdgeShape(e)};onAfterEdgeUpdated=e=>{this.htmlView.renderEdge(e)};onAfterEdgePriorityUpdated=e=>{this.htmlView.updateEdgePriority(e)};onBeforeEdgeRemoved=e=>{this.htmlView.detachEdge(e)};onBeforeClear=()=>{this.nodeIdGenerator.reset(),this.portIdGenerator.reset(),this.edgeIdGenerator.reset(),this.htmlView.clear()};constructor(e,t,n){this.graphStore=e,this.htmlView=t,this.params=n,this.graphStore.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.graphStore.onAfterNodeUpdated.subscribe(this.onAfterNodeUpdated),this.graphStore.onAfterNodePriorityUpdated.subscribe(this.onAfterNodePriorityUpdated),this.graphStore.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.graphStore.onAfterPortUpdated.subscribe(this.onAfterPortUpdated),this.graphStore.onBeforePortRemoved.subscribe(this.onBeforePortUnmarked),this.graphStore.onAfterEdgeAdded.subscribe(this.onAfterEdgeAdded),this.graphStore.onAfterEdgeShapeUpdated.subscribe(this.onAfterEdgeShapeUpdated),this.graphStore.onAfterEdgeUpdated.subscribe(this.onAfterEdgeUpdated),this.graphStore.onAfterEdgePriorityUpdated.subscribe(this.onAfterEdgePriorityUpdated),this.graphStore.onBeforeEdgeRemoved.subscribe(this.onBeforeEdgeRemoved),this.graphStore.onBeforeClear.subscribe(this.onBeforeClear)}addNode(e){let t=this.nodeIdGenerator.create(e.id);if(this.graphStore.addNode({id:t,element:e.element,x:e.x??null,y:e.y??null,centerFn:e.centerFn??this.params.nodes.centerFn,priority:e.priority??this.params.nodes.priorityFn()}),e.ports!==void 0)for(let n of e.ports)this.markPort({id:n.id,element:n.element,nodeId:t,direction:n.direction})}updateNode(e,t){this.graphStore.updateNode(e,t??{})}removeNode(e){this.graphStore.removeNode(e)}markPort(e){let t=this.portIdGenerator.create(e.id);this.graphStore.addPort({id:t,element:e.element,nodeId:e.nodeId,direction:e.direction??this.params.ports.direction})}updatePort(e,t){this.graphStore.updatePort(e,t??{})}unmarkPort(e){this.graphStore.removePort(e)}addEdge(e){let t=this.edgeIdGenerator.create(e.id);this.graphStore.addEdge({id:t,from:e.from,to:e.to,shape:e.shape??this.params.edges.shapeFactory(t),priority:e.priority??this.params.edges.priorityFn()})}updateEdge(e,t){this.graphStore.updateEdge(e,t??{})}removeEdge(e){this.graphStore.removeEdge(e)}clear(){this.graphStore.clear()}destroy(){this.graphStore.onAfterNodeAdded.unsubscribe(this.onAfterNodeAdded),this.graphStore.onAfterNodeUpdated.unsubscribe(this.onAfterNodeUpdated),this.graphStore.onAfterNodePriorityUpdated.unsubscribe(this.onAfterNodePriorityUpdated),this.graphStore.onBeforeNodeRemoved.unsubscribe(this.onBeforeNodeRemoved),this.graphStore.onAfterPortUpdated.unsubscribe(this.onAfterPortUpdated),this.graphStore.onBeforePortRemoved.unsubscribe(this.onBeforePortUnmarked),this.graphStore.onAfterEdgeAdded.unsubscribe(this.onAfterEdgeAdded),this.graphStore.onAfterEdgeShapeUpdated.unsubscribe(this.onAfterEdgeShapeUpdated),this.graphStore.onAfterEdgeUpdated.unsubscribe(this.onAfterEdgeUpdated),this.graphStore.onAfterEdgePriorityUpdated.unsubscribe(this.onAfterEdgePriorityUpdated),this.graphStore.onBeforeEdgeRemoved.unsubscribe(this.onBeforeEdgeRemoved),this.graphStore.onBeforeClear.unsubscribe(this.onBeforeClear),this.htmlView.destroy()}},Ke=e=>{queueMicrotask(()=>{e()})},z=e=>{e()},qe=class{viewportStore;onBeforeUpdated;onAfterUpdated;onAfterResize;constructor(e){this.viewportStore=e,this.onBeforeUpdated=this.viewportStore.onBeforeUpdated,this.onAfterUpdated=this.viewportStore.onAfterUpdated,this.onAfterResize=this.viewportStore.onAfterResize}getViewportMatrix(){return{...this.viewportStore.getViewportMatrix()}}getContentMatrix(){return{...this.viewportStore.getContentMatrix()}}getDimensions(){return this.viewportStore.getDimensions()}createContentCoords(e){return this.viewportStore.createContentCoords(e)}createViewportCoords(e){return this.viewportStore.createViewportCoords(e)}},Je=(e,t)=>Symbol.iterator in e?{minContentScale:t.focus.minContentScale,nodes:e,contentPadding:t.focus.contentPadding,animationDuration:t.focus.animationDuration}:{minContentScale:e.minContentScale??t.focus.minContentScale,nodes:e.nodes??[],contentPadding:e.contentPadding??t.focus.contentPadding,animationDuration:e.animationDuration??t.focus.animationDuration},Ye=(e,t,n)=>({scale:e.scale,x:e.x+e.scale*t,y:e.y+e.scale*n}),Xe=(e,t,n,r)=>({scale:e.scale*t,x:e.scale*(1-t)*n+e.x,y:e.scale*(1-t)*r+e.y}),Ze=class{graphStore;viewportStore;params;win;constructor(e,t,n,r){this.graphStore=e,this.viewportStore=t,this.params=n,this.win=r}patchViewportMatrix(e){this.viewportStore.patchViewportMatrix(e)}patchContentMatrix(e){this.viewportStore.patchContentMatrix(e)}center(e,t){let{width:n,height:r}=this.viewportStore.getDimensions(),i={x:n/2,y:r/2},a=this.viewportStore.getViewportMatrix(),o=this.viewportStore.createViewportCoords(e),s=Ye(a,o.x-i.x,o.y-i.y),c=t?.contentScale;if(c!==void 0){let e=1/c;s=Xe(s,e/a.scale,i.x,i.y)}let l=t?.animationDuration??0;l>0?this.animateNavigation(a,s,l):this.viewportStore.patchViewportMatrix(s)}focus(e){let t=Je(e??{},this.params);this.params.focus.schedule(()=>{this.navigate(t)})}destroy(){this.viewportStore.destroy()}navigate(e){let t=1/0,n=-1/0,r=1/0,i=-1/0,a=0,o=new Set;for(let t of e.nodes)o.add(t);if(this.graphStore.getAllNodeIds().forEach(e=>{let{payload:s}=this.graphStore.getNode(e);s.x!==null&&s.y!==null&&(o.size===0||o.has(e))&&(t=Math.min(s.x,t),n=Math.max(s.x,n),r=Math.min(s.y,r),i=Math.max(s.y,i),a++)}),a>0){t-=e.contentPadding,r-=e.contentPadding,n+=e.contentPadding,i+=e.contentPadding;let a={x:(t+n)/2,y:(r+i)/2},{scale:o}=this.viewportStore.getContentMatrix(),s=(i-r)*o,c=(n-t)*o,{width:l,height:u}=this.viewportStore.getDimensions(),d=Math.max(c/l,s/u),f=d>1?o/d:o,p=Math.max(f,e.minContentScale);this.center(a,{contentScale:p,animationDuration:e.animationDuration})}}animateNavigation(e,t,n){let r,i={scale:t.scale-e.scale,x:t.x-e.x,y:t.y-e.y},a=t=>{r===void 0&&(r=t);let o=Math.min((t-r)/n,1);this.viewportStore.patchViewportMatrix({scale:e.scale+o*i.scale,x:e.x+o*i.x,y:e.y+o*i.y}),o<1&&this.win.requestAnimationFrame(a)};this.win.requestAnimationFrame(a)}},Qe=(e,t,n)=>{let r=new g;return new f(new We(r),new qe(t),new Ge(r,new o(r,t,e),{nodes:{centerFn:ae,priorityFn:()=>0},edges:{shapeFactory:()=>new L,priorityFn:()=>0},ports:{direction:0}}),new Ze(r,t,{focus:{contentPadding:0,minContentScale:0,schedule:z,animationDuration:0}},n))},B=Symbol(),$e=class e{canvas;window;pointInsideVerifier;eventTagger;params;onAfterPortMarked=e=>{let t=this.canvas.graph.getPort(e);this.canvas.graph.findPortIdsByElement(t.element).length===1&&this.hookPortEvents(t.element)};onBeforePortUnmarked=e=>{let t=this.canvas.graph.getPort(e);this.canvas.graph.findPortIdsByElement(t.element).length===1&&this.unhookPortEvents(t.element)};onPortMouseDown=e=>{let t=e;if(!this.params.mouseDownEventVerifier(t))return;let n=e.currentTarget,r=this.canvas.graph.findPortIdsByElement(n),i=this.params.grabbedPortIdResolver(r);i!==null&&this.params.onPointerDownVerifier(i,{x:t.clientX,y:t.clientY})&&(this.eventTagger.tag(e,B),this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0}))};onWindowMouseMove=e=>{if(!this.pointInsideVerifier.verify(e.clientX,e.clientY)){this.removeWindowMouseListeners(),this.params.onPointerOutside();return}this.params.onPointerMove({x:e.clientX,y:e.clientY})};onWindowMouseUp=e=>{this.params.mouseUpEventVerifier(e)&&(this.removeWindowMouseListeners(),this.params.onPointerUp({x:e.clientX,y:e.clientY}))};onPortTouchStart=e=>{let t=e;if(t.touches.length!==1)return;let n=t.touches[0],r=e.currentTarget,i=this.canvas.graph.findPortIdsByElement(r)[0];this.params.onPointerDownVerifier(i,{x:n.clientX,y:n.clientY})&&(this.eventTagger.tag(e,B),this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchFinish,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchFinish,{passive:!0}))};onWindowTouchMove=e=>{let t=e.touches[0];if(!this.pointInsideVerifier.verify(t.clientX,t.clientY)){this.removeWindowTouchListeners(),this.params.onPointerOutside();return}this.params.onPointerMove({x:t.clientX,y:t.clientY})};onWindowTouchFinish=e=>{this.removeWindowTouchListeners();let t=e.changedTouches[0];this.params.onPointerUp({x:t.clientX,y:t.clientY})};reset=()=>{this.canvas.graph.getAllPortIds().forEach(e=>{let t=this.canvas.graph.getPort(e);this.unhookPortEvents(t.element)})};revert=()=>{this.removeWindowMouseListeners(),this.removeWindowTouchListeners(),this.reset()};constructor(e,t,n,r,i){this.canvas=e,this.window=t,this.pointInsideVerifier=n,this.eventTagger=r,this.params=i,this.canvas.graph.onAfterPortMarked.subscribe(this.onAfterPortMarked),this.canvas.graph.onBeforePortUnmarked.subscribe(this.onBeforePortUnmarked),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.revert)}static configure(t,n,r,i,a){new e(t,n,r,i,a)}hookPortEvents(e){e.addEventListener(`mousedown`,this.onPortMouseDown,{passive:!0}),e.addEventListener(`touchstart`,this.onPortTouchStart,{passive:!0})}unhookPortEvents(e){e.removeEventListener(`mousedown`,this.onPortMouseDown),e.removeEventListener(`touchstart`,this.onPortTouchStart)}removeWindowMouseListeners(){this.window.removeEventListener(`mousemove`,this.onWindowMouseMove),this.window.removeEventListener(`mouseup`,this.onWindowMouseUp)}removeWindowTouchListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchFinish),this.window.removeEventListener(`touchcancel`,this.onWindowTouchFinish)}},V=Symbol(),et=class{has(e,t){let n=e[V];return n!==void 0&&n.has(t)}tag(e,t){let n=e,r=n[V];r===void 0?n[V]=new Set([t]):r.add(t)}},H=Symbol(),U=class{window;pointInsideVerifier;onSelected;mouseDownEventVerifier;mouseUpEventVerifier;movementThreshold;selectionCandidate=null;previousMouse=null;previousTouch=null;movedDistance=0;onElementMouseDown=e=>{let t=e;this.mouseDownEventVerifier(t)&&(this.selectionCandidate=t.currentTarget,this.previousMouse={x:t.clientX,y:t.clientY},this.movedDistance=0,this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0}))};onElementTouchStart=e=>{let t=e,n=t.touches;n.length===1&&(this.selectionCandidate=t.currentTarget,this.previousTouch=n[0],this.movedDistance=0,this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchEnd,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchCancel,{passive:!0}))};onWindowMouseMove=e=>{let t=e;if(!this.pointInsideVerifier.verify(t.clientX,t.clientY)){this.removeWindowMouseListeners();return}let n=this.previousMouse,r=t.clientX-n.x,i=t.clientY-n.y;this.previousMouse={x:t.clientX,y:t.clientY},this.processMoveThresholdVerification(r,i,()=>{this.removeWindowMouseListeners()})};onWindowMouseUp=e=>{let t=e;this.mouseUpEventVerifier(t)&&(this.removeWindowMouseListeners(),this.onSelected(this.selectionCandidate,e))};onWindowTouchMove=e=>{let t=e.touches;if(t.length!==1){this.removeWindowTouchListeners();return}let n=t[0];if(!this.pointInsideVerifier.verify(n.clientX,n.clientY)){this.removeWindowTouchListeners();return}let r=this.previousTouch,i=n.clientX-r.clientX,a=n.clientY-r.clientY;this.previousTouch=n,this.processMoveThresholdVerification(i,a,()=>{this.removeWindowTouchListeners()})};onWindowTouchEnd=e=>{this.removeWindowTouchListeners(),this.onSelected(this.selectionCandidate,e)};onWindowTouchCancel=()=>{this.removeWindowTouchListeners()};constructor(e,t,n){this.window=e,this.pointInsideVerifier=t,this.mouseDownEventVerifier=n.mouseDownEventVerifier,this.mouseUpEventVerifier=n.mouseUpEventVerifier,this.onSelected=n.onSelected,this.movementThreshold=n.movementThreshold}enable(e){e.addEventListener(`mousedown`,this.onElementMouseDown),e.addEventListener(`touchstart`,this.onElementTouchStart)}disable(e){e.removeEventListener(`mousedown`,this.onElementMouseDown),e.removeEventListener(`touchstart`,this.onElementTouchStart),e===this.selectionCandidate&&(this.removeWindowMouseListeners(),this.removeWindowTouchListeners())}removeWindowMouseListeners(){this.window.removeEventListener(`mousemove`,this.onWindowMouseMove),this.window.removeEventListener(`mouseup`,this.onWindowMouseUp)}removeWindowTouchListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchEnd),this.window.removeEventListener(`touchcancel`,this.onWindowTouchCancel)}processMoveThresholdVerification(e,t,n){let r=Math.sqrt(e*e+t*t);this.movedDistance+=r,this.movedDistance>this.movementThreshold&&n()}},W=(e,t)=>({from:e.isDirect?e.staticPortId:t,to:e.isDirect?t:e.staticPortId}),tt=class{graph;connectionAllowedVerifier;constructor(e,t){this.graph=e,this.connectionAllowedVerifier=t}resolve(e){let t,n=1/0,{cursor:r}=e;return this.graph.getAllPortIds().forEach(i=>{let{element:a,direction:o,nodeId:s}=this.graph.getPort(i),{x:c,y:l}=this.graph.getNode(s);if(c===null||l===null)return;let u=W(e,i);if(!this.connectionAllowedVerifier(u))return;let{top:d,left:f,width:p,height:m}=a.getBoundingClientRect(),h={x:f+p/2,y:d+m/2},g=r.x-h.x,_=r.y-h.y,v=Math.sqrt(g*g+_*_);v<n&&(n=v,t=o)}),t}},nt=class{direction;constructor(e){this.direction=e}resolve(){return this.direction}},G=e=>e.length>0?e[0]:null,rt=class e{canvas;element;window;pointInsideVerifier;eventTagger;params;grabbedNodeState=null;maxNodePriority=0;graph;onAfterNodeAdded=e=>{this.updateMaxNodePriority(e);let{element:t}=this.graph.getNode(e);t.addEventListener(`mousedown`,this.onMouseDown,{passive:!0}),t.addEventListener(`touchstart`,this.onTouchStart,{passive:!0})};onAfterNodeUpdated=e=>{this.updateMaxNodePriority(e)};onBeforeNodeRemoved=e=>{let{element:t}=this.graph.getNode(e);t.removeEventListener(`mousedown`,this.onMouseDown),t.removeEventListener(`touchstart`,this.onTouchStart)};onMouseDown=e=>{if(this.eventTagger.has(e,B))return;let t=e;if(!this.params.mouseDownEventVerifier(t))return;let n=e.currentTarget,r=this.graph.findNodeIdByElement(n),i=this.graph.getNode(r);if(!this.params.nodeDragVerifier(r))return;this.eventTagger.tag(e,B),this.params.onNodeDragStarted(r);let a=this.calculateContentPoint({x:t.clientX,y:t.clientY});this.grabbedNodeState={nodeId:r,dx:a.x-i.x,dy:a.y-i.y},C(this.element,this.params.dragCursor),this.moveNodeOnTop(r),this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0})};onTouchStart=e=>{if(this.eventTagger.has(e,B))return;let t=e;if(t.touches.length!==1)return;let n=t.touches[0],r=e.currentTarget,i=this.canvas.graph.findNodeIdByElement(r),a=this.graph.getNode(i);if(!this.params.nodeDragVerifier(i))return;this.eventTagger.tag(e,B);let o=this.calculateContentPoint({x:n.clientX,y:n.clientY});this.grabbedNodeState={nodeId:i,dx:o.x-a.x,dy:o.y-a.y},this.moveNodeOnTop(i),this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchFinish,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchFinish,{passive:!0})};onWindowMouseMove=e=>{if(!this.pointInsideVerifier.verify(e.clientX,e.clientY)){this.stopMouseDrag();return}this.moveNode(this.grabbedNodeState,{x:e.clientX,y:e.clientY})};onWindowMouseUp=e=>{this.params.mouseUpEventVerifier(e)&&this.stopMouseDrag()};onWindowTouchMove=e=>{if(e.touches.length!==1)return;let t=e.touches[0];if(!this.pointInsideVerifier.verify(t.clientX,t.clientY)){this.stopTouchDrag();return}this.moveNode(this.grabbedNodeState,{x:t.clientX,y:t.clientY})};onWindowTouchFinish=()=>{this.stopTouchDrag()};reset=()=>{this.canvas.graph.getAllNodeIds().forEach(e=>{let{element:t}=this.canvas.graph.getNode(e);t.removeEventListener(`mousedown`,this.onMouseDown),t.removeEventListener(`touchstart`,this.onTouchStart)}),this.maxNodePriority=0};revert=()=>{this.reset(),this.removeMouseDragListeners(),this.removeTouchDragListeners()};constructor(e,t,n,r,i,a){this.canvas=e,this.element=t,this.window=n,this.pointInsideVerifier=r,this.eventTagger=i,this.params=a,this.graph=e.graph,this.graph.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.graph.onAfterNodeUpdated.subscribe(this.onAfterNodeUpdated),this.graph.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.revert)}static configure(t,n,r,i,a,o){new e(t,n,r,i,a,o)}moveNode(e,t){if(!this.graph.hasNode(e.nodeId))return;let n=this.calculateContentPoint(t),r={x:n.x-e.dx,y:n.y-e.dy},i=this.adjustNodeCoords(r);this.canvas.updateNode(e.nodeId,{x:i.x,y:i.y}),this.params.onNodeDrag(e.nodeId)}moveNodeOnTop(e){if(this.params.moveOnTop){if(this.maxNodePriority++,this.params.moveEdgesOnTop){let t=this.maxNodePriority;this.maxNodePriority++,this.graph.getNodeAdjacentEdgeIds(e).forEach(e=>{this.canvas.updateEdge(e,{priority:t})})}this.canvas.updateNode(e,{priority:this.maxNodePriority})}}stopMouseDrag(){this.finishDrag(),C(this.element,null),this.removeMouseDragListeners()}removeMouseDragListeners(){this.window.removeEventListener(`mouseup`,this.onWindowMouseUp),this.window.removeEventListener(`mousemove`,this.onWindowMouseMove)}stopTouchDrag(){this.finishDrag(),this.removeTouchDragListeners()}removeTouchDragListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchFinish),this.window.removeEventListener(`touchcancel`,this.onWindowTouchFinish)}updateMaxNodePriority(e){let t=this.graph.getNode(e).priority;this.maxNodePriority=Math.max(this.maxNodePriority,t)}calculateContentPoint(e){let t=this.element.getBoundingClientRect();return this.canvas.viewport.createContentCoords({x:e.x-t.x,y:e.y-t.y})}adjustNodeCoords(e){let t=this.params.gridSize;if(t!==null){let n=t/2;return{x:Math.floor((e.x+n)/t)*t,y:Math.floor((e.y+n)/t)*t}}return e}finishDrag(){let e=this.grabbedNodeState.nodeId;this.graph.hasNode(e)&&this.params.onNodeDragFinished(e),this.grabbedNodeState=null}},K=e=>{let t=[],n=e.touches.length;for(let r=0;r<n;r++)t.push([e.touches[r].clientX,e.touches[r].clientY]);let r=t.reduce((e,t)=>[e[0]+t[0],e[1]+t[1]],[0,0]),i=[r[0]/n,r[1]/n],a=t.map(e=>[e[0]-i[0],e[1]-i[1]]).reduce((e,t)=>e+Math.sqrt(t[0]*t[0]+t[1]*t[1]),0);return{x:i[0],y:i[1],scale:a/n,touchesCnt:n,touches:t}},it=class e{canvas;element;window;pointInsideVerifier;eventTagger;params;viewport;prevTouches=null;wheelFinishTimer=null;transformInProgress=!1;revert=()=>{this.removeMouseDragListeners(),this.removeTouchDragListeners()};onMouseDown=e=>{this.eventTagger.has(e,B)||this.params.mouseDownEventVerifier(e)&&(C(this.element,this.params.shiftCursor),this.window.addEventListener(`mousemove`,this.onWindowMouseMove,{passive:!0}),this.window.addEventListener(`mouseup`,this.onWindowMouseUp,{passive:!0}),this.startRegisteredTransform())};onWindowMouseMove=e=>{let t=this.pointInsideVerifier.verify(e.clientX,e.clientY);if(this.element===null||!t){this.stopMouseDrag();return}let n=-e.movementX,r=-e.movementY;this.moveViewport(n,r)};onWindowMouseUp=e=>{this.params.mouseUpEventVerifier(e)&&this.stopMouseDrag()};onWheelScroll=e=>{if(!this.params.mouseWheelEventVerifier(e))return;let{left:t,top:n}=this.element.getBoundingClientRect(),r=e.clientX-t,i=e.clientY-n,a=1/(e.deltaY<0?this.params.wheelSensitivity:1/this.params.wheelSensitivity);this.wheelFinishTimer===null&&this.params.onTransformStarted(),this.scaleViewport(a,r,i),this.wheelFinishTimer!==null&&clearTimeout(this.wheelFinishTimer),this.wheelFinishTimer=setTimeout(()=>{this.transformInProgress||this.params.onTransformFinished(),this.wheelFinishTimer=null},this.params.scaleWheelFinishTimeout)};onTouchStart=e=>{if(!this.eventTagger.has(e,B)){if(this.prevTouches!==null){this.prevTouches=K(e);return}this.prevTouches=K(e),this.window.addEventListener(`touchmove`,this.onWindowTouchMove,{passive:!0}),this.window.addEventListener(`touchend`,this.onWindowTouchFinish,{passive:!0}),this.window.addEventListener(`touchcancel`,this.onWindowTouchFinish,{passive:!0}),this.startRegisteredTransform()}};onWindowTouchMove=e=>{let t=K(e);if(!t.touches.every(e=>this.pointInsideVerifier.verify(e[0],e[1]))){this.stopTouchDrag();return}if(t.touchesCnt===1||t.touchesCnt===2){let{x:e,y:n}=this.prevTouches,r=t.x-e,i=t.y-n;this.moveViewport(-r,-i)}if(t.touchesCnt===2){let{left:e,top:n}=this.element.getBoundingClientRect(),r=this.prevTouches.x-e,i=this.prevTouches.y-n,a=1/(t.scale/this.prevTouches.scale);this.scaleViewport(a,r,i)}this.prevTouches=t};onWindowTouchFinish=e=>{e.touches.length>0?this.prevTouches=K(e):this.stopTouchDrag()};preventWheelScaleListener=e=>{e.preventDefault()};constructor(e,t,n,r,i,a){this.canvas=e,this.element=t,this.window=n,this.pointInsideVerifier=r,this.eventTagger=i,this.params=a,this.element.addEventListener(`wheel`,this.preventWheelScaleListener,{passive:!1}),this.viewport=e.viewport,this.handleResize(),this.viewport.onAfterResize.subscribe(()=>{this.handleResize()}),this.element.addEventListener(`mousedown`,this.onMouseDown,{passive:!0}),this.element.addEventListener(`wheel`,this.onWheelScroll,{passive:!0}),this.element.addEventListener(`touchstart`,this.onTouchStart,{passive:!0}),e.onBeforeDestroy.subscribe(this.revert)}static configure(t,n,r,i,a,o){new e(t,n,r,i,a,o)}moveViewport(e,t){let n=this.viewport.getViewportMatrix(),r=Ye(n,e,t),{width:i,height:a}=this.viewport.getDimensions(),o=this.params.transformPreprocessor({prevTransform:n,nextTransform:r,viewport:{width:i,height:a}});this.performTransform(o)}scaleViewport(e,t,n){let r=this.canvas.viewport.getViewportMatrix(),i=Xe(r,e,t,n),{width:a,height:o}=this.viewport.getDimensions(),s=this.params.transformPreprocessor({prevTransform:r,nextTransform:i,viewport:{width:a,height:o}});this.performTransform(s)}stopMouseDrag(){C(this.element,null),this.removeMouseDragListeners(),this.finishRegisteredTransform()}removeMouseDragListeners(){this.window.removeEventListener(`mousemove`,this.onWindowMouseMove),this.window.removeEventListener(`mouseup`,this.onWindowMouseUp)}stopTouchDrag(){this.prevTouches=null,this.removeTouchDragListeners(),this.finishRegisteredTransform()}removeTouchDragListeners(){this.window.removeEventListener(`touchmove`,this.onWindowTouchMove),this.window.removeEventListener(`touchend`,this.onWindowTouchFinish),this.window.removeEventListener(`touchcancel`,this.onWindowTouchFinish)}performTransform(e){this.params.onBeforeTransformChange(),this.canvas.patchViewportMatrix(e),this.params.onTransformChange()}startRegisteredTransform(){this.transformInProgress=!0,this.params.onTransformStarted()}finishRegisteredTransform(){this.transformInProgress=!1,this.params.onTransformFinished()}handleResize(){let e=this.viewport.getViewportMatrix(),{width:t,height:n}=this.viewport.getDimensions(),r=this.params.transformPreprocessor({prevTransform:e,nextTransform:e,viewport:{width:t,height:n}});this.params.onResizeTransformStarted(),this.canvas.patchViewportMatrix(r),this.params.onResizeTransformFinished()}},at=class e{canvas;element;window;trigger;pointInsideVerifier;params;nodeHorizontal;nodeVertical;viewport;currentScale;loadedArea={xFrom:1/0,xTo:1/0,yFrom:1/0,yTo:1/0};updateLoadedArea=e=>{this.loadedArea={xFrom:e.x,xTo:e.x+e.width,yFrom:e.y,yTo:e.y+e.height}};onAfterViewportUpdated=()=>{this.userTransformInProgress||this.loadAreaAroundViewport()};userTransformInProgress=!1;constructor(e,t,n,r,i,a,o,s){this.canvas=e,this.element=t,this.window=n,this.trigger=i,this.pointInsideVerifier=a,this.params=s,this.nodeHorizontal=this.params.nodeVerticalRadius,this.nodeVertical=this.params.nodeHorizontalRadius,this.viewport=e.viewport,this.currentScale=this.viewport.getViewportMatrix().scale,this.scheduleLoadAreaAroundViewport(),this.viewport.onAfterResize.subscribe(()=>{this.scheduleLoadAreaAroundViewport()});let c={...r,onResizeTransformStarted:()=>{this.userTransformInProgress=!0,r.onResizeTransformStarted()},onResizeTransformFinished:()=>{this.userTransformInProgress=!1,r.onResizeTransformFinished()},onBeforeTransformChange:()=>{this.userTransformInProgress=!0,r.onBeforeTransformChange()},onTransformChange:()=>{this.userTransformInProgress=!1;let e=this.currentScale;this.currentScale=this.viewport.getViewportMatrix().scale,e!==this.currentScale&&this.scheduleEnsureViewportAreaLoaded(),r.onTransformChange()},onTransformFinished:()=>{this.scheduleLoadAreaAroundViewport(),r.onTransformFinished()}};it.configure(e,this.element,this.window,this.pointInsideVerifier,o,c),this.trigger.subscribe(this.updateLoadedArea),this.canvas.viewport.onAfterUpdated.subscribe(this.onAfterViewportUpdated)}static configure(t,n,r,i,a,o,s,c){new e(t,n,r,i,a,o,s,c)}scheduleLoadAreaAroundViewport(){setTimeout(()=>{this.loadAreaAroundViewport()})}scheduleEnsureViewportAreaLoaded(){setTimeout(()=>{let{width:e,height:t}=this.viewport.getDimensions(),{scale:n,x:r,y:i}=this.viewport.getViewportMatrix(),a=e*n,o=t*n,s=r-this.nodeHorizontal,c=i-this.nodeVertical,l=r+a+this.nodeHorizontal,u=i+o+this.nodeVertical;this.loadedArea.xFrom<s&&this.loadedArea.xTo>l&&this.loadedArea.yFrom<c&&this.loadedArea.yTo>u||this.loadAreaAroundViewport()})}loadAreaAroundViewport(){let{width:e,height:t}=this.viewport.getDimensions(),{scale:n,x:r,y:i}=this.viewport.getViewportMatrix(),a=e*n,o=t*n,s=r-a-this.nodeHorizontal,c=i-o-this.nodeVertical,l=3*a+2*this.nodeHorizontal,u=3*o+2*this.nodeVertical;this.trigger.emit({x:s,y:c,width:l,height:u})}},ot=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return e.style.position=`absolute`,e.style.inset=`0`,e},st=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);return e.setAttribute(`fill`,`url(#pattern)`),e},ct=()=>{let e=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);return e.setAttribute(`id`,`pattern`),e},lt=class e{canvas;backgroundHost;svg=ot();patternRenderingRectangle=st();pattern=ct();patternContent;tileWidth;tileHeight;halfTileWidth;halfTileHeight;maxViewportScale;visible=!1;onAfterTransformUpdated=()=>{let e=this.canvas.viewport.getContentMatrix(),t=e.x-this.halfTileWidth*e.scale,n=e.y-this.halfTileHeight*e.scale,r=`matrix(${e.scale}, 0, 0, ${e.scale}, ${t}, ${n})`;this.pattern.setAttribute(`patternTransform`,r),this.updateVisibility()};constructor(e,t,n){this.canvas=e,this.backgroundHost=n,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.halfTileWidth=this.tileWidth/2,this.halfTileHeight=this.tileHeight/2,this.patternContent=t.renderer,this.maxViewportScale=t.maxViewportScale;let r=`translate(${this.halfTileWidth}, ${this.halfTileHeight})`;this.patternContent.setAttribute(`transform`,r),this.pattern.appendChild(this.patternContent);let i=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`);i.appendChild(this.pattern),this.svg.appendChild(i),this.svg.appendChild(this.patternRenderingRectangle),this.updateDimensions(),this.canvas.viewport.onAfterResize.subscribe(()=>{this.updateDimensions()}),this.canvas.viewport.onAfterUpdated.subscribe(this.onAfterTransformUpdated),this.onAfterTransformUpdated()}static configure(t,n,r){new e(t,n,r)}updateVisibility(){let{scale:e}=this.canvas.viewport.getViewportMatrix(),t=e>this.maxViewportScale;t&&this.visible?(this.visible=!1,this.backgroundHost.removeChild(this.svg)):!t&&!this.visible&&(this.visible=!0,this.backgroundHost.appendChild(this.svg))}updateDimensions(){let{width:e,height:t}=this.canvas.viewport.getDimensions();if(this.svg.setAttribute(`width`,`${e}`),this.svg.setAttribute(`height`,`${t}`),this.patternRenderingRectangle.setAttribute(`width`,`${e}`),this.patternRenderingRectangle.setAttribute(`height`,`${t}`),e>0&&t>0){let n=this.tileWidth/e,r=this.tileHeight/t;this.pattern.setAttribute(`width`,`${n}`),this.pattern.setAttribute(`height`,`${r}`)}}},ut=class e{canvas;overlayLayer;viewportStore;window;pointInsideVerifier;eventTagger;params;overlayCanvas;edgeInProgress=null;onEdgeCreated=e=>{this.params.onAfterEdgeCreated(e)};constructor(e,t,n,r,i,a,o){this.canvas=e,this.overlayLayer=t,this.viewportStore=n,this.window=r,this.pointInsideVerifier=i,this.eventTagger=a,this.params=o,this.overlayCanvas=Qe(this.overlayLayer,this.viewportStore,this.window);let s={mouseDownEventVerifier:this.params.mouseDownEventVerifier,mouseUpEventVerifier:this.params.mouseUpEventVerifier,onPointerDownVerifier:(e,t)=>{let n=this.params.connectionTypeResolver(e);return n===null?!1:(this.grabPort(e,t,n),!0)},onPointerMove:e=>{this.moveDraggingPort(e)},onPointerUp:e=>{this.tryCreateConnection(e),this.resetDragState()},onPointerOutside:()=>{let e=this.edgeInProgress;this.resetDragState(),this.params.onEdgeCreationInterrupted(e)},grabbedPortIdResolver:this.params.grabbedPortIdResolver};$e.configure(this.canvas,this.window,this.pointInsideVerifier,this.eventTagger,s)}static configure(t,n,r,i,a,o,s){new e(t,n,r,i,a,o,s)}grabPort(e,t,n){let r=this.canvas.graph.getPort(e),i=r.element.getBoundingClientRect(),a=i.x+i.width/2,o=i.y+i.height/2,s=this.overlayLayer.getBoundingClientRect(),c=this.canvas.viewport.createContentCoords({x:a-s.x,y:o-s.y}),l=this.canvas.viewport.createContentCoords({x:t.x-s.x,y:t.y-s.y}),u={overlayNodeId:T.StaticNodeId,portCoords:c,portDirection:r.direction},d=n===`direct`;this.edgeInProgress={staticPortId:e,isDirect:d};let f=this.params.draggingPortDirectionResolver.resolve({cursor:t,...this.edgeInProgress}),p={overlayNodeId:T.DraggingNodeId,portCoords:l,portDirection:f??r.direction},[m,h]=d?[u,p]:[p,u];this.overlayCanvas.addNode(w(m)),this.overlayCanvas.addNode(w(h)),this.overlayCanvas.addEdge({from:m.overlayNodeId,to:h.overlayNodeId,shape:this.params.edgeShapeFactory(T.EdgeId)})}resetDragState(){this.edgeInProgress=null,this.overlayCanvas.clear()}tryCreateConnection(e){let t=ie(this.canvas.graph,e,this.params.releasedPortIdResolver);if(t===null){this.params.onEdgeCreationInterrupted(this.edgeInProgress);return}let n=W(this.edgeInProgress,t),r=this.params.connectionAllowedVerifier(n),i=this.params.connectionPreprocessor({from:n.from,to:n.to});r&&i!==null?(this.canvas.graph.onAfterEdgeAdded.subscribe(this.onEdgeCreated),this.canvas.addEdge(i),this.canvas.graph.onAfterEdgeAdded.unsubscribe(this.onEdgeCreated)):this.params.onEdgeCreationPrevented(n)}moveDraggingPort(e){let t=this.overlayLayer.getBoundingClientRect(),n=this.canvas.viewport.createContentCoords({x:e.x-t.x,y:e.y-t.y}),r=this.params.draggingPortDirectionResolver.resolve({cursor:e,...this.edgeInProgress});this.overlayCanvas.updateNode(T.DraggingNodeId,{x:n.x,y:n.y}).updatePort(T.DraggingNodeId,{direction:r})}},dt=class e{canvas;overlayLayer;viewportStore;window;pointInsideVerifier;eventTagger;params;overlayCanvas;edgeInProgress=null;draggingEdgePayload=null;onEdgeReattached=e=>{this.params.onAfterEdgeReattached(e)};constructor(e,t,n,r,i,a,o){this.canvas=e,this.overlayLayer=t,this.viewportStore=n,this.window=r,this.pointInsideVerifier=i,this.eventTagger=a,this.params=o,this.overlayCanvas=Qe(this.overlayLayer,this.viewportStore,this.window);let s={mouseDownEventVerifier:this.params.mouseDownEventVerifier,mouseUpEventVerifier:this.params.mouseUpEventVerifier,onPointerDownVerifier:(e,t)=>this.tryStartEdgeDragging(e,t),onPointerMove:e=>{this.moveDraggingPort(e)},onPointerUp:e=>{this.tryCreateConnection(e),this.resetDragState()},onPointerOutside:()=>{let e=this.draggingEdgePayload;this.resetDragState(),this.params.onEdgeReattachInterrupted({id:e.id,from:e.from,to:e.to,shape:e.shape,priority:e.priority})},grabbedPortIdResolver:this.params.grabbedPortIdResolver};$e.configure(this.canvas,this.window,this.pointInsideVerifier,this.eventTagger,s)}static configure(t,n,r,i,a,o,s){new e(t,n,r,i,a,o,s)}tryStartEdgeDragging(e,t){let n=this.params.draggingEdgeResolver(e);if(n===null)return!1;let r=this.canvas.graph.getEdge(n),i=e===r.from,a=e===r.to,o=i?r.to:r.from;this.edgeInProgress={staticPortId:o,isDirect:a};let s=this.canvas.graph.getPort(e),c=this.canvas.graph.getPort(o),l=c.element.getBoundingClientRect(),u={x:l.x+l.width/2,y:l.y+l.height/2},d=this.overlayLayer.getBoundingClientRect(),f=this.canvas.viewport.createContentCoords({x:u.x-d.x,y:u.y-d.y}),p=this.canvas.viewport.createContentCoords({x:t.x-d.x,y:t.y-d.y});this.draggingEdgePayload={id:n,from:r.from,to:r.to,shape:r.shape,priority:r.priority},this.canvas.removeEdge(n);let m={overlayNodeId:T.StaticNodeId,portCoords:f,portDirection:c.direction},h=this.params.draggingPortDirectionResolver.resolve({cursor:t,...this.edgeInProgress}),g={overlayNodeId:T.DraggingNodeId,portCoords:p,portDirection:h??s.direction},[_,v]=a?[m,g]:[g,m];this.overlayCanvas.addNode(w(_)),this.overlayCanvas.addNode(w(v));let y=this.params.draggingEdgeShapeFactory===null?r.shape:this.params.draggingEdgeShapeFactory(T.EdgeId);return this.overlayCanvas.addEdge({id:T.EdgeId,from:_.overlayNodeId,to:v.overlayNodeId,shape:y}),!0}resetDragState(){this.draggingEdgePayload=null,this.edgeInProgress=null,this.overlayCanvas.clear()}moveDraggingPort(e){let t=this.overlayLayer.getBoundingClientRect(),n={x:e.x-t.x,y:e.y-t.y},r=this.canvas.viewport.createContentCoords(n),i=this.params.draggingPortDirectionResolver.resolve({cursor:e,...this.edgeInProgress});this.overlayCanvas.updateNode(T.DraggingNodeId,{x:r.x,y:r.y}).updatePort(T.DraggingNodeId,{direction:i})}tryCreateConnection(e){let t=ie(this.canvas.graph,e,this.params.releasedPortIdResolver);if(this.overlayCanvas.removeEdge(T.EdgeId),t===null){let e=this.draggingEdgePayload;this.params.onEdgeReattachInterrupted({id:e.id,from:e.from,to:e.to,shape:e.shape,priority:e.priority});return}let{from:n,to:r}=W(this.edgeInProgress,t),i=this.draggingEdgePayload,a={id:i.id,from:n,to:r,shape:i.shape,priority:i.priority},o=this.params.connectionAllowedVerifier({from:n,to:r}),s=this.params.connectionPreprocessor(a);if(o&&s!==null)this.canvas.graph.onAfterEdgeAdded.subscribe(this.onEdgeReattached),this.canvas.addEdge(s),this.canvas.graph.onAfterEdgeAdded.unsubscribe(this.onEdgeReattached);else{let e=this.draggingEdgePayload;this.params.onEdgeReattachPrevented({id:e.id,from:e.from,to:e.to,shape:e.shape,priority:e.priority})}}},ft=class e{applier;trigger;constructor(e,t){this.applier=e,this.trigger=t,this.trigger.subscribe(()=>{this.applier.apply()})}static configure(t,n){new e(t,n)}},pt=class e{graph;applier;defererFn;applyScheduled=!1;apply=()=>{this.applyScheduled=!1,this.applier.apply()};constructor(e,t,n){this.graph=e,this.applier=t,this.defererFn=n,this.graph.onAfterNodeAdded.subscribe(()=>{this.scheduleApply()}),this.graph.onBeforeNodeRemoved.subscribe(()=>{this.scheduleApply()}),this.graph.onAfterEdgeAdded.subscribe(()=>{this.scheduleApply()}),this.graph.onBeforeEdgeRemoved.subscribe(()=>{this.scheduleApply()})}static configure(t,n,r){new e(t,n,r)}scheduleApply(){this.applyScheduled||(this.applyScheduled=!0,this.defererFn(this.apply))}},mt=class{canvas;layoutAlgorithm;params;constructor(e,t,n){this.canvas=e,this.layoutAlgorithm=t,this.params=n}apply(){let e=this.layoutAlgorithm.calculateCoordinates({graph:this.canvas.graph,viewport:this.canvas.viewport});this.params.onBeforeApplied(),e.forEach((e,t)=>{this.params.staticNodeResolver(t)||this.canvas.updateNode(t,e)}),this.params.onAfterApplied()}},ht=class{static configure(e,t){let n=t.applyOn,r=new mt(e,t.algorithm,{staticNodeResolver:t.staticNodeResolver,onBeforeApplied:t.onBeforeApplied,onAfterApplied:t.onAfterApplied});switch(n.type){case`trigger`:ft.configure(r,n.trigger);break;case`topologyChangeSchedule`:pt.configure(e.graph,r,n.schedule);break}}},gt=class{win;callback;previousTimeStamp=void 0;step=e=>{if(this.previousTimeStamp===void 0)this.previousTimeStamp=e;else{let t=(e-this.previousTimeStamp)/1e3;this.previousTimeStamp=e,this.callback(t)}this.win.requestAnimationFrame(this.step)};constructor(e,t){this.win=e,this.callback=t,this.win.requestAnimationFrame(this.step)}},_t=class{canvas;layoutAlgorithm;params;constructor(e,t,n){this.canvas=e,this.layoutAlgorithm=t,this.params=n}apply(e){let t=this.layoutAlgorithm.calculateNextCoordinates({graph:this.canvas.graph,viewport:this.canvas.viewport,dt:e});this.params.onBeforeApplied(),t.forEach((e,t)=>{this.params.staticNodeResolver(t)||this.canvas.updateNode(t,e)}),this.params.onAfterApplied()}},vt=class e{applier;step=e=>{this.applier.apply(e)};constructor(e,t,n){this.applier=new _t(e,t.algorithm,{staticNodeResolver:t.staticNodeResolver,onBeforeApplied:t.onBeforeApplied,onAfterApplied:t.onAfterApplied}),new gt(n,this.step)}static configure(t,n,r){new e(t,n,r)}},yt=class e{canvas;window;pointInsideVerifier;eventTagger;configurator;onNodeSelected;eventHandledTag=H;onAfterNodeAdded=e=>{let{element:t}=this.canvas.graph.getNode(e);this.configurator.enable(t)};onBeforeNodeRemoved=e=>{let{element:t}=this.canvas.graph.getNode(e);this.configurator.disable(t)};reset=()=>{this.canvas.graph.getAllNodeIds().forEach(e=>{let{element:t}=this.canvas.graph.getNode(e);this.configurator.disable(t)})};constructor(e,t,n,r,i){this.canvas=e,this.window=t,this.pointInsideVerifier=n,this.eventTagger=r,this.onNodeSelected=i.onNodeSelected,this.configurator=new U(this.window,this.pointInsideVerifier,{onSelected:(e,t)=>{let n=this.canvas.graph.findNodeIdByElement(e);this.eventTagger.tag(t,this.eventHandledTag),this.onNodeSelected(n)},movementThreshold:i.movementThreshold,mouseDownEventVerifier:i.mouseDownEventVerifier,mouseUpEventVerifier:i.mouseUpEventVerifier}),this.canvas.graph.onAfterNodeAdded.subscribe(this.onAfterNodeAdded),this.canvas.graph.onBeforeNodeRemoved.subscribe(this.onBeforeNodeRemoved),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.reset)}static configure(t,n,r,i,a){new e(t,n,r,i,a)}},bt=class e{canvas;window;pointInsideVerifier;eventTagger;configurator;eventHandledTag=H;onEdgeSelected;onAfterEdgeAdded=e=>{let{shape:t}=this.canvas.graph.getEdge(e);this.configurator.enable(t.element)};onBeforeEdgeRemoved=e=>{let{shape:t}=this.canvas.graph.getEdge(e);this.configurator.disable(t.element)};reset=()=>{this.canvas.graph.getAllEdgeIds().forEach(e=>{let{shape:t}=this.canvas.graph.getEdge(e);this.configurator.disable(t.element)})};constructor(e,t,n,r,i){this.canvas=e,this.window=t,this.pointInsideVerifier=n,this.eventTagger=r,this.onEdgeSelected=i.onEdgeSelected,this.configurator=new U(this.window,this.pointInsideVerifier,{onSelected:(e,t)=>{let n=this.canvas.graph.findEdgeIdByElement(e);this.eventTagger.tag(t,this.eventHandledTag),this.onEdgeSelected(n)},movementThreshold:i.movementThreshold,mouseDownEventVerifier:i.mouseDownEventVerifier,mouseUpEventVerifier:i.mouseUpEventVerifier}),this.canvas.graph.onAfterEdgeAdded.subscribe(this.onAfterEdgeAdded),this.canvas.graph.onBeforeEdgeRemoved.subscribe(this.onBeforeEdgeRemoved),this.canvas.graph.onBeforeClear.subscribe(this.reset),this.canvas.onBeforeDestroy.subscribe(this.reset)}static configure(t,n,r,i,a){new e(t,n,r,i,a)}},xt=class e{canvas;element;window;pointInsideVerifier;eventTagger;configurator;onCanvasSelected;eventHandledTag=H;constructor(e,t,n,r,i,a){this.canvas=e,this.element=t,this.window=n,this.pointInsideVerifier=r,this.eventTagger=i,this.onCanvasSelected=a.onCanvasSelected,this.configurator=new U(this.window,this.pointInsideVerifier,{onSelected:(e,t)=>{this.eventTagger.has(t,this.eventHandledTag)||this.onCanvasSelected()},movementThreshold:a.movementThreshold,mouseDownEventVerifier:a.mouseDownEventVerifier,mouseUpEventVerifier:a.mouseUpEventVerifier}),this.configurator.enable(this.element),this.canvas.onBeforeDestroy.subscribe(()=>{this.configurator.disable(this.element)})}static configure(t,n,r,i,a,o){new e(t,n,r,i,a,o)}},St=()=>{let e=document.createElement(`div`);return e.style.width=`100%`,e.style.height=`100%`,e.style.position=`relative`,e},Ct=()=>{let e=document.createElement(`div`);return e.style.position=`absolute`,e.style.inset=`0`,e},wt=()=>{let e=Ct();return e.style.pointerEvents=`none`,e},Tt=class{element;background=Ct();main=Ct();overlayConnectablePorts=wt();overlayDraggableEdges=wt();host=St();constructor(e){this.element=e,this.element.appendChild(this.host),this.host.appendChild(this.background),this.host.appendChild(this.main),this.host.appendChild(this.overlayConnectablePorts),this.host.appendChild(this.overlayDraggableEdges)}destroy(){this.host.removeChild(this.background),this.host.removeChild(this.main),this.host.removeChild(this.overlayConnectablePorts),this.host.removeChild(this.overlayDraggableEdges),this.element.removeChild(this.host)}},q=Object.freeze({seed:`HTMLGraph is awesome`,maxTimeDeltaSec:.01,nodeCharge:1e5,nodeMass:1,edgeEquilibriumLength:300,edgeStiffness:1e3,dtSec:.01,maxIterations:1e3,convergenceVelocity:10,maxForce:1e7,nodeForceCoefficient:1,barnesHutAreaRadiusThreshold:.01,barnesHutTheta:1}),J=Object.freeze({mouseDownEventVerifier:e=>e.button===0,mouseUpEventVerifier:e=>e.button===0,movementThreshold:10}),Y=()=>{},Et=(e,t,n)=>e===`nearest-connectable-port`?new tt(t,n):typeof e==`number`?new nt(e):new nt(void 0),Dt=e=>{if(typeof e==`function`)return e;switch(e.type){case`straight`:return()=>new Me({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowOffset:e.arrowOffset,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleSquareSide:e.cycleSquareSide,roundness:e.roundness,detourDistance:e.detourDistance,detourDirection:e.detourDirection});case`orthogonal`:return()=>new Pe({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowOffset:e.arrowOffset,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleSquareSide:e.cycleSquareSide,roundness:e.roundness,detourDistance:e.detourDistance});case`direct`:return()=>new L({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,sourceOffset:e.sourceOffset,targetOffset:e.targetOffset});default:return()=>new je({color:e.color,width:e.width,arrowLength:e.arrowLength,arrowRenderer:e.arrowRenderer,hasSourceArrow:e.hasSourceArrow,hasTargetArrow:e.hasTargetArrow,cycleRadius:e.cycleRadius,smallCycleRadius:e.smallCycleRadius,curvature:e.curvature,detourDistance:e.detourDistance,detourDirection:e.detourDirection})}},Ot=e=>{let t=e.nodeDragVerifier??(()=>!0),n=e.moveOnTop!==!1,r=e.moveEdgesOnTop!==!1&&n,i=e.mouse?.dragCursor,a=i===void 0?`grab`:i,o=e.mouse?.mouseDownEventVerifier,s=o===void 0?e=>e.button===0:o,c=e.mouse?.mouseUpEventVerifier,l=c===void 0?e=>e.button===0:c;return{moveOnTop:n,moveEdgesOnTop:r,dragCursor:a,gridSize:e.gridSize??null,mouseDownEventVerifier:s,mouseUpEventVerifier:l,onNodeDragStarted:e.events?.onNodeDragStarted??Y,onNodeDrag:e.events?.onNodeDrag??Y,nodeDragVerifier:t,onNodeDragFinished:e.events?.onNodeDragFinished??Y}},kt=e=>{let t=e.minX===null?-1/0:e.minX,n=e.maxX===null?1/0:e.maxX,r=e.minY===null?-1/0:e.minY,i=e.maxY===null?1/0:e.maxY;return e=>{let a=e.nextTransform.x,o=e.nextTransform.y;a<t&&a<e.prevTransform.x&&(a=Math.min(e.prevTransform.x,t));let s=n-e.viewport.width*e.prevTransform.scale;a>s&&a>e.prevTransform.x&&(a=Math.max(e.prevTransform.x,s)),o<r&&o<e.prevTransform.y&&(o=Math.min(e.prevTransform.y,r));let c=i-e.viewport.height*e.prevTransform.scale;return o>c&&o>e.prevTransform.y&&(o=Math.max(e.prevTransform.y,c)),{scale:e.nextTransform.scale,x:a,y:o}}},At=e=>{let t=e.maxContentScale,n=e.minContentScale,r=t===null?0:1/t,i=n===null?1/0:1/n;return e=>{let t=e.prevTransform,n=e.nextTransform,a=n.scale,o=n.x,s=n.y;if(n.scale>i&&n.scale>t.scale){a=Math.max(t.scale,i);let e=(a-t.scale)/(n.scale-t.scale);o=t.x+(n.x-t.x)*e,s=t.y+(n.y-t.y)*e}if(n.scale<r&&n.scale<t.scale){a=Math.min(t.scale,r);let e=(a-t.scale)/(n.scale-t.scale);o=t.x+(n.x-t.x)*e,s=t.y+(n.y-t.y)*e}return{scale:a,x:o,y:s}}},jt=e=>t=>e.reduce((e,n)=>n({prevTransform:t.prevTransform,nextTransform:e,viewport:t.viewport}),t.nextTransform),Mt=e=>{if(typeof e==`function`)return e;switch(e.type){case`scale-limit`:return At({minContentScale:e.minContentScale??0,maxContentScale:e.maxContentScale??1/0});case`shift-limit`:return kt({minX:e.minX??-1/0,maxX:e.maxX??1/0,minY:e.minY??-1/0,maxY:e.maxY??1/0})}},Nt=e=>{let t=e?.scale?.mouseWheelSensitivity,n=t===void 0?1.2:t,r=e?.transformPreprocessor,i;i=r===void 0?e=>e.nextTransform:Array.isArray(r)?jt(r.map(e=>Mt(e))):Mt(r);let a=e?.pan?.cursor===void 0?`grab`:e.pan.cursor,o=e?.pan?.mouseDownEventVerifier,s=o===void 0?e=>e.button===0:o,c=e?.pan?.mouseUpEventVerifier,l=c===void 0?e=>e.button===0:c,u=e?.scale?.mouseWheelEventVerifier,d=u===void 0?()=>!0:u;return{wheelSensitivity:n,onTransformStarted:e?.events?.onTransformStarted??Y,onTransformFinished:e?.events?.onTransformFinished??Y,onBeforeTransformChange:e?.events?.onBeforeTransformChange??Y,onTransformChange:e?.events?.onTransformChange??Y,transformPreprocessor:i,shiftCursor:a,mouseDownEventVerifier:s,mouseUpEventVerifier:l,mouseWheelEventVerifier:d,scaleWheelFinishTimeout:e?.scale?.wheelFinishTimeout??500,onResizeTransformStarted:e?.events?.onResizeTransformStarted??Y,onResizeTransformFinished:e?.events?.onResizeTransformFinished??Y}},Pt=(e,t)=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,`circle`);return n.setAttribute(`cx`,`0`),n.setAttribute(`cy`,`0`),n.setAttribute(`r`,`${e}`),n.setAttribute(`fill`,`${t}`),n},Ft=e=>e instanceof SVGElement?e:Pt(e?.radius??1.5,e?.color??`#d8d8d8`),It=e=>{let t=e.tileDimensions;return{tileWidth:t?.width??25,tileHeight:t?.height??25,renderer:Ft(e.renderer??{}),maxViewportScale:e.maxViewportScale??10}},X=Object.freeze({connectionTypeResolver:()=>`direct`,connectionPreprocessor:e=>e,connectionAllowedVerifier:()=>!0,mouseEventVerifier:e=>e.button===0}),Lt=(e,t,n)=>{let r=e.connectionAllowedVerifier??X.connectionAllowedVerifier;return{connectionTypeResolver:e.connectionTypeResolver??X.connectionTypeResolver,connectionAllowedVerifier:r,draggingPortDirectionResolver:Et(e.dragPortDirection,n,r),edgeShapeFactory:e.edgeShape===void 0?t:Dt(e.edgeShape),connectionPreprocessor:e.connectionPreprocessor??X.connectionPreprocessor,mouseDownEventVerifier:e.mouseDownEventVerifier??X.mouseEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??X.mouseEventVerifier,onAfterEdgeCreated:e.events?.onAfterEdgeCreated??Y,onEdgeCreationInterrupted:e.events?.onEdgeCreationInterrupted??Y,onEdgeCreationPrevented:e.events?.onEdgeCreationPrevented??Y,grabbedPortIdResolver:e.grabbedPortIdResolver??G,releasedPortIdResolver:e.releasedPortIdResolver??G}},Z=Object.freeze({connectionAllowedVerifier:()=>!0,connectionPreprocessor:e=>e,mouseDownEventVerifier:e=>e.button===0,mouseUpEventVerifier:e=>e.button===0}),Rt=(e,t)=>{let n=e=>{let n=t.getPortAdjacentEdgeIds(e);return n.length>0?n[n.length-1]:null},r=e.connectionAllowedVerifier??Z.connectionAllowedVerifier;return{connectionPreprocessor:e.connectionPreprocessor??Z.connectionPreprocessor,connectionAllowedVerifier:r,mouseDownEventVerifier:e.mouseDownEventVerifier??Z.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??Z.mouseUpEventVerifier,draggingEdgeResolver:e.draggingEdgeResolver??n,draggingEdgeShapeFactory:e.draggingEdgeShape===void 0?null:Dt(e.draggingEdgeShape),onAfterEdgeReattached:e.events?.onAfterEdgeReattached??Y,onEdgeReattachInterrupted:e.events?.onEdgeReattachInterrupted??Y,onEdgeReattachPrevented:e.events?.onEdgeReattachPrevented??Y,draggingPortDirectionResolver:Et(e.dragPortDirection,t,r),grabbedPortIdResolver:e.grabbedPortIdResolver??G,releasedPortIdResolver:e.releasedPortIdResolver??G}},zt=e=>({nodeVerticalRadius:e.nodeContainingRadius.vertical,nodeHorizontalRadius:e.nodeContainingRadius.horizontal}),Bt=e=>({onAfterNodeDetached:e?.events?.onAfterNodeDetached??Y,onBeforeNodeAttached:e?.events?.onBeforeNodeAttached??Y}),Vt=class extends Error{name=`CanvasBuilderError`},Ht=class{graph;currentCoords;dt;nodeMass;edgeEquilibriumLength;edgeStiffness;nodeForcesApplicationStrategy;distanceVectorGenerator;constructor(e,t,n){this.graph=e,this.currentCoords=t,this.dt=n.dtSec,this.nodeMass=n.nodeMass,this.edgeEquilibriumLength=n.edgeEquilibriumLength,this.edgeStiffness=n.edgeStiffness,this.distanceVectorGenerator=n.distanceVectorGenerator,this.nodeForcesApplicationStrategy=n.nodeForcesApplicationStrategy}apply(){let e=0,t=new Map;return this.graph.getAllNodeIds().forEach(e=>{t.set(e,{x:0,y:0})}),this.nodeForcesApplicationStrategy.apply(this.currentCoords,t),this.applyEdgeForces(t),this.currentCoords.forEach((n,r)=>{let i=t.get(r),a={x:i.x/this.nodeMass*this.dt,y:i.y/this.nodeMass*this.dt};e=Math.max(e,Math.sqrt(a.x*a.x+a.y*a.y));let o=a.x*this.dt,s=a.y*this.dt;n.x+=o,n.y+=s}),e}applyEdgeForces(e){this.graph.getAllEdgeIds().forEach(t=>{let n=this.graph.getEdge(t),r=this.graph.getPort(n.from),i=this.graph.getPort(n.to),a=this.currentCoords.get(r.nodeId),o=this.currentCoords.get(i.nodeId),s=this.distanceVectorGenerator.create(a,o),c=(s.d-this.edgeEquilibriumLength)*this.edgeStiffness,l=s.ex*c,u=s.ey*c,d=e.get(r.nodeId),f=e.get(i.nodeId);d.x+=l,d.y+=u,f.x-=l,f.y-=u})}},Ut=class{rand;PI2=2*Math.PI;constructor(e){this.rand=e}create(e,t){let n=t.x-e.x,r=t.y-e.y,i=n*n+r*r;if(i===0){let e=this.PI2*this.rand();return{ex:Math.cos(e),ey:Math.sin(e),d:0}}let a=Math.sqrt(i);return{ex:n/a,ey:r/a,d:a}}},Wt=e=>{if(e.distance===0)return e.maxForce;let t=e.coefficient*(e.sourceCharge*e.targetCharge/(e.distance*e.distance));return Math.min(t,e.maxForce)},Gt=class{nodeCharge;distanceVectorGenerator;maxForce;constructor(e){this.nodeCharge=e.nodeCharge,this.distanceVectorGenerator=e.distanceVectorGenerator,this.maxForce=e.maxForce}apply(e,t){let n=Array.from(t.keys()),r=n.length;for(let i=0;i<r;i++){let a=n[i];for(let o=i+1;o<r;o++){let r=n[o],i=e.get(a),s=e.get(r),c=this.distanceVectorGenerator.create(i,s),l=Wt({coefficient:1,sourceCharge:this.nodeCharge,targetCharge:this.nodeCharge,distance:c.d,maxForce:this.maxForce}),u=l*c.ex,d=l*c.ey,f=t.get(a),p=t.get(r);f.x-=u,f.y-=d,p.x+=u,p.y+=d}}}},Kt=e=>{if(e.size===0)return{centerX:0,centerY:0,radius:0};let t=1/0,n=-1/0,r=1/0,i=-1/0;e.forEach(e=>{t=Math.min(t,e.x),n=Math.max(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.y)});let a=n-t,o=i-r,s=Math.max(a,o);return{centerX:(t+n)/2,centerY:(r+i)/2,radius:s/2}},qt=class{root;leaves=new Map;coords;areaRadiusThreshold;nodeMass;nodeCharge;sortedParentNodes=[];constructor(e){this.coords=e.coords,this.areaRadiusThreshold=e.areaRadiusThreshold,this.nodeMass=e.nodeMass,this.nodeCharge=e.nodeCharge,this.root={nodeIds:new Set(e.coords.keys()),box:e.box,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},parent:null,lb:null,lt:null,rb:null,rt:null};let t=[this.root];for(;t.length>0;){let e=[];for(;t.length>0;){let n=t.pop();this.processNode(n).forEach(t=>{e.push(t)})}t=e}this.sortedParentNodes.reverse().forEach(e=>{let t=0,n=0,r=0,i=0;e.lb!==null&&(r+=e.lb.totalMass,i+=e.lb.totalCharge,t+=e.lb.chargeCenter.x*e.lb.totalCharge,n+=e.lb.chargeCenter.y*e.lb.totalCharge),e.lt!==null&&(r+=e.lt.totalMass,i+=e.lt.totalCharge,t+=e.lt.chargeCenter.x*e.lt.totalCharge,n+=e.lt.chargeCenter.y*e.lt.totalCharge),e.rb!==null&&(r+=e.rb.totalMass,i+=e.rb.totalCharge,t+=e.rb.chargeCenter.x*e.rb.totalCharge,n+=e.rb.chargeCenter.y*e.rb.totalCharge),e.rt!==null&&(r+=e.rt.totalMass,i+=e.rt.totalCharge,t+=e.rt.chargeCenter.x*e.rt.totalCharge,n+=e.rt.chargeCenter.y*e.rt.totalCharge),e.totalMass=r,e.totalCharge=i,e.chargeCenter.x=t/i,e.chargeCenter.y=n/i})}getRoot(){return this.root}getLeaf(e){return this.leaves.get(e)}processNode(e){if(e.nodeIds.size<2)return this.setLeaf(e),[];let{centerX:t,centerY:n,radius:r}=e.box;if(r<this.areaRadiusThreshold)return this.setLeaf(e),[];this.sortedParentNodes.push(e);let i=new Set,a=new Set,o=new Set,s=new Set,c=r/2;e.nodeIds.forEach(r=>{let{x:c,y:l}=this.coords.get(r);c<t?l<n?s.add(r):o.add(r):l<n?a.add(r):i.add(r),e.nodeIds.delete(r)});let l={parent:e,lb:null,lt:null,rb:null,rt:null},u=[];if(i.size>0){let r={nodeIds:i,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t+c,centerY:n+c,radius:c},...l};e.rt=r,u.push(r)}if(a.size>0){let r={nodeIds:a,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t+c,centerY:n-c,radius:c},...l};e.rb=r,u.push(r)}if(o.size>0){let r={nodeIds:o,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t-c,centerY:n+c,radius:c},...l};e.lt=r,u.push(r)}if(s.size>0){let r={nodeIds:s,totalMass:0,totalCharge:0,chargeCenter:{x:0,y:0},box:{centerX:t-c,centerY:n-c,radius:c},...l};e.lb=r,u.push(r)}return u}setLeaf(e){e.totalMass=this.nodeMass*e.nodeIds.size,e.totalCharge=this.nodeCharge*e.nodeIds.size,e.chargeCenter=this.calculateLeafChargeCenter(e.nodeIds),e.nodeIds.forEach(t=>{this.leaves.set(t,e)})}calculateLeafChargeCenter(e){if(e.size===0)return{x:0,y:0};let t=0,n=0;return e.forEach(e=>{let r=this.coords.get(e);t+=r.x,n+=r.y}),{x:t/e.size,y:n/e.size}}},Jt=class{areaRadiusThreshold;nodeMass;nodeCharge;theta;distanceVectorGenerator;nodeForceCoefficient;maxForce;constructor(e){this.areaRadiusThreshold=e.areaRadiusThreshold,this.nodeMass=e.nodeMass,this.nodeCharge=e.nodeCharge,this.theta=e.theta,this.distanceVectorGenerator=e.distanceVectorGenerator,this.nodeForceCoefficient=e.nodeForceCoefficient,this.maxForce=e.maxForce}apply(e,t){let n=new qt({box:Kt(e),coords:e,areaRadiusThreshold:this.areaRadiusThreshold,nodeMass:this.nodeMass,nodeCharge:this.nodeCharge});e.forEach((r,i)=>{let a=this.calculateForceForNode(n.getLeaf(i),i,e),o=t.get(i);this.applyForce(o,a)})}calculateForceForNode(e,t,n){let r=n.get(t),i={x:0,y:0};e.nodeIds.forEach(e=>{if(e!==t){let t=n.get(e),a=this.calculateNodeRepulsiveForce({sourceCharge:this.nodeCharge,targetCharge:this.nodeCharge,sourceCoords:t,targetCoords:r});this.applyForce(i,a)}});let a=e;for(;a!==null;){let e=a.parent;if(e!==null){let t=this.distanceVectorGenerator.create(e.chargeCenter,r);e.box.radius*2<t.d*this.theta?(this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.lb,current:a}),this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.rb,current:a}),this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.rt,current:a}),this.tryApplyFarForce({totalForce:i,targetCoords:r,target:e.lt,current:a})):(this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.lb,current:a,nodesCoords:n}),this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.rb,current:a,nodesCoords:n}),this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.rt,current:a,nodesCoords:n}),this.tryApplyNearForce({totalForce:i,targetCoords:r,target:e.lt,current:a,nodesCoords:n}))}a=a.parent}return i}calculateExactForce(e,t,n){let r={x:0,y:0},i=[e];for(;i.length>0;){let e=i.pop();e.nodeIds.forEach(e=>{let i=n.get(e),a=this.calculateNodeRepulsiveForce({sourceCharge:this.nodeCharge,targetCharge:this.nodeCharge,sourceCoords:i,targetCoords:t});this.applyForce(r,a)}),e.lb!==null&&i.push(e.lb),e.rb!==null&&i.push(e.rb),e.lt!==null&&i.push(e.lt),e.rt!==null&&i.push(e.rt)}return r}calculateApproximateForce(e,t){return this.calculateNodeRepulsiveForce({sourceCharge:this.nodeCharge,targetCharge:e.totalCharge,sourceCoords:e.chargeCenter,targetCoords:t})}calculateNodeRepulsiveForce(e){let t=this.distanceVectorGenerator.create(e.sourceCoords,e.targetCoords),n=Wt({coefficient:this.nodeForceCoefficient,sourceCharge:e.sourceCharge,targetCharge:e.targetCharge,distance:t.d,maxForce:this.maxForce});return{x:n*t.ex,y:n*t.ey}}applyForce(e,t){e.x+=t.x,e.y+=t.y}tryApplyFarForce(e){if(e.target!==null&&e.target!==e.current){let t=this.calculateApproximateForce(e.target,e.targetCoords);this.applyForce(e.totalForce,t)}}tryApplyNearForce(e){if(e.target!==null&&e.target!==e.current){let t=this.calculateExactForce(e.target,e.targetCoords,e.nodesCoords);this.applyForce(e.totalForce,t)}}},Yt=e=>e.theta===0?new Gt({nodeCharge:e.nodeCharge,nodeForceCoefficient:e.nodeForceCoefficient,distanceVectorGenerator:e.distanceVectorGenerator,maxForce:e.maxForce}):new Jt({nodeCharge:e.nodeCharge,nodeForceCoefficient:e.nodeForceCoefficient,distanceVectorGenerator:e.distanceVectorGenerator,maxForce:e.maxForce,theta:e.theta,nodeMass:e.nodeMass,areaRadiusThreshold:e.areaRadiusThreshold}),Xt=class{rand;sparsity;constructor(e){this.rand=e.rand,this.sparsity=e.sparsity}calculateCoordinates(e){let{graph:t,viewport:n}=e,r=new Map,i=t.getAllNodeIds().filter(e=>{let n=t.getNode(e);return n.x===null||n.y===null}),a=Math.sqrt(i.length)*this.sparsity,{width:o,height:s}=n.getDimensions(),c={x:o/2,y:s/2},l=n.createContentCoords(c),u=a/2,d={x:l.x-u,y:l.y-u};return t.getAllNodeIds().forEach(e=>{let n=t.getNode(e);r.set(e,{x:n.x??d.x+a*this.rand(),y:n.y??d.y+a*this.rand()})}),r}},Zt=class{distanceVectorGenerator;nodeForcesApplicationStrategy;fillerLayoutAlgorithm;maxIterations;dtSec;nodeMass;edgeEquilibriumLength;edgeStiffness;convergenceVelocity;constructor(e){this.maxIterations=e.maxIterations,this.dtSec=e.dtSec,this.nodeMass=e.nodeMass,this.edgeEquilibriumLength=e.edgeEquilibriumLength,this.edgeStiffness=e.edgeStiffness,this.convergenceVelocity=e.stopVelocity,this.distanceVectorGenerator=new Ut(e.rand),this.nodeForcesApplicationStrategy=Yt({distanceVectorGenerator:this.distanceVectorGenerator,nodeCharge:e.nodeCharge,maxForce:e.maxForce,nodeForceCoefficient:e.nodeForceCoefficient,theta:e.barnesHutTheta,areaRadiusThreshold:e.barnesHutAreaRadiusThreshold,nodeMass:e.nodeMass}),this.fillerLayoutAlgorithm=new Xt({rand:e.rand,sparsity:e.edgeEquilibriumLength})}calculateCoordinates(e){let{graph:t,viewport:n}=e,r=this.fillerLayoutAlgorithm.calculateCoordinates({graph:t,viewport:n});for(let e=0;e<this.maxIterations&&!(new Ht(t,r,{distanceVectorGenerator:this.distanceVectorGenerator,nodeForcesApplicationStrategy:this.nodeForcesApplicationStrategy,dtSec:this.dtSec,nodeMass:this.nodeMass,edgeEquilibriumLength:this.edgeEquilibriumLength,edgeStiffness:this.edgeStiffness}).apply()<this.convergenceVelocity);e++);return r}},Qt=class{graph;nextLayerNodesResolver;forest=new Set;remainingNodeIds;constructor(e,t){for(this.graph=e,this.nextLayerNodesResolver=t,this.remainingNodeIds=new Set(this.graph.getAllNodeIds());this.remainingNodeIds.size>0;){let[e]=this.remainingNodeIds;this.traverse(e)}}generate(){return this.forest}traverse(e){let t={nodeId:e,children:new Set},n=[];this.forest.add({root:t,sequence:n});let r=[t];for(this.remainingNodeIds.delete(t.nodeId);r.length>0;){let e=[];r.forEach(t=>{n.push(t);let r=this.nextLayerNodesResolver({graph:this.graph,currentNodeId:t.nodeId});for(let n of r){if(!this.remainingNodeIds.has(n))continue;this.remainingNodeIds.delete(n);let r={nodeId:n,children:new Set};t.children.add(r),e.push(r)}}),r=e}}},$t=class{params;constructor(e){this.params=e}generate(e){let t=0,n=[],r=e.length-1,i=[];e.forEach((a,o)=>{if(t+=this.params.spaceAroundRadius,a.forEach((e,n)=>{i[n]===void 0?i[n]={start:t+e.start,end:t+e.end}:i[n].end=t+e.end}),n.push(t),o!==r){let n=e[o+1],r=i.map(e=>({start:e.start-t,end:e.end-t}));t+=this.calculateMaxDiff(r,n)}t+=this.params.spaceAroundRadius});let a=t/2;return{childOffsets:n.map(e=>e-a),subtreeSpans:i.map(e=>({start:e.start-a,end:e.end-a}))}}calculateMaxDiff(e,t){let n=0,r=Math.min(e.length,t.length);for(let i=0;i<r;i++){let r=e[i].end-t[i].start;n=Math.max(n,r)}return n-2*this.params.spaceAroundRadius}},en=class{tree;offsets=new Map;treeSpans=new Map;constructor(e,t){this.tree=e;let n=t.spaceAroundRadius,r=new $t({spaceAroundRadius:n});[...this.tree.sequence].reverse().forEach(e=>{let t=Array.from(e.children).map(e=>this.treeSpans.get(e.nodeId)),i=r.generate(t),a=0;e.children.forEach(e=>{this.offsets.set(e.nodeId,i.childOffsets[a]),a++}),this.treeSpans.set(e.nodeId,[{start:-n,end:n},...i.subtreeSpans]),e.children.forEach(e=>{this.treeSpans.delete(e.nodeId)})}),this.offsets.set(this.tree.root.nodeId,0)}generate(){return this.offsets}},tn=class{params;constructor(e){this.params=e}calculateCoordinates(e){let t=new Map,n=new Qt(e.graph,this.params.nextLayerNodesResolver).generate(),r=0;return n.forEach(e=>{t.set(e.root.nodeId,{x:r,y:0});let n=new en(e,{spaceAroundRadius:this.params.layerSpace/2}).generate(),i=[e.root];for(;i.length>0;){let e=[];r+=this.params.layerWidth,i.forEach(i=>{i.children.forEach(a=>{let o=t.get(i.nodeId).y;t.set(a.nodeId,{y:o+n.get(a.nodeId),x:r}),e.push(a)})}),i=e}}),t.forEach((e,n)=>{t.set(n,this.params.transform(e))}),t}},nn=e=>{let{graph:t,currentNodeId:n}=e,r=t.getNodeOutgoingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.to).nodeId}),i=t.getNodeIncomingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.from).nodeId});return new Set([...r,...i])},rn=e=>{let{graph:t,currentNodeId:n}=e,r=t.getNodeOutgoingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.to).nodeId});return new Set(r)},an=e=>{let{graph:t,currentNodeId:n}=e,r=t.getNodeIncomingEdgeIds(n).map(e=>{let n=t.getEdge(e);return t.getPort(n.from).nodeId});return new Set(r)},on=class{distanceVectorGenerator;nodeForcesApplicationStrategy;convergenceVelocity;maxTimeDeltaSec;nodeMass;edgeEquilibriumLength;edgeStiffness;fillerLayoutAlgorithm;constructor(e){this.convergenceVelocity=e.stopVelocity,this.maxTimeDeltaSec=e.maxTimeDeltaSec,this.nodeMass=e.nodeMass,this.edgeEquilibriumLength=e.edgeEquilibriumLength,this.edgeStiffness=e.edgeStiffness,this.distanceVectorGenerator=new Ut(e.rand),this.nodeForcesApplicationStrategy=Yt({distanceVectorGenerator:this.distanceVectorGenerator,nodeCharge:e.nodeCharge,maxForce:e.maxForce,nodeForceCoefficient:e.nodeForceCoefficient,theta:e.barnesHutTheta,areaRadiusThreshold:e.barnesHutAreaRadiusThreshold,nodeMass:e.nodeMass}),this.fillerLayoutAlgorithm=new Xt({rand:e.rand,sparsity:e.edgeEquilibriumLength})}calculateNextCoordinates(e){let{graph:t,viewport:n,dt:r}=e,i=this.fillerLayoutAlgorithm.calculateCoordinates({graph:t,viewport:n});return new Ht(t,i,{distanceVectorGenerator:this.distanceVectorGenerator,nodeForcesApplicationStrategy:this.nodeForcesApplicationStrategy,dtSec:Math.min(r,this.maxTimeDeltaSec),nodeMass:this.nodeMass,edgeEquilibriumLength:this.edgeEquilibriumLength,edgeStiffness:this.edgeStiffness}).apply()<this.convergenceVelocity&&!t.getAllNodeIds().some(e=>{let n=t.getNode(e);return n.x===null||n.y===null})?new Map:i}},sn=e=>{let t=1779033703,n=3144134277,r=1013904242,i=2773480762;for(let a=0,o;a<e.length;a++)o=e.charCodeAt(a),t=n^Math.imul(t^o,597399067),n=r^Math.imul(n^o,2869860233),r=i^Math.imul(r^o,951274213),i=t^Math.imul(i^o,2716044179);return t=Math.imul(r^t>>>18,597399067),n=Math.imul(i^n>>>22,2869860233),r=Math.imul(t^r>>>17,951274213),i=Math.imul(n^i>>>19,2716044179),t^=n^r^i,n^=t,r^=t,i^=t,[t>>>0,n>>>0,r>>>0,i>>>0]},cn=(e,t,n,r)=>function(){e|=0,t|=0,n|=0,r|=0;let i=(e+t|0)+r|0;return r=r+1|0,e=t^t>>>9,t=n+(n<<3)|0,n=n<<21|n>>>11,n=n+i|0,(i>>>0)/4294967296},ln=e=>{switch(e?.type){case`custom`:return e.instance;default:{let t=sn(e?.seed??q.seed);return new on({rand:cn(t[0],t[1],t[2],t[3]),maxTimeDeltaSec:e?.maxTimeDeltaSec??q.maxTimeDeltaSec,nodeCharge:e?.nodeCharge??q.nodeCharge,nodeMass:e?.nodeMass??q.nodeMass,edgeEquilibriumLength:e?.edgeEquilibriumLength??q.edgeEquilibriumLength,edgeStiffness:e?.edgeStiffness??q.edgeStiffness,stopVelocity:e?.stopVelocity??q.convergenceVelocity,maxForce:e?.maxForce??q.maxForce,nodeForceCoefficient:e?.nodeForceCoefficient??q.nodeForceCoefficient,barnesHutTheta:e?.barnesHut?.theta??q.barnesHutTheta,barnesHutAreaRadiusThreshold:e?.barnesHut?.areaRadiusThreshold??q.barnesHutAreaRadiusThreshold})}}},un={staticNodeResolver:()=>!1},dn=e=>({algorithm:ln(e?.algorithm??{}),staticNodeResolver:e?.staticNodeResolver??un.staticNodeResolver,onBeforeApplied:e?.events?.onBeforeApplied??Y,onAfterApplied:e?.events?.onAfterApplied??Y}),fn=e=>e instanceof u?{type:`trigger`,trigger:e}:{type:`topologyChangeSchedule`,schedule:Ke},pn=Object.freeze({staticNodeResolver:()=>!1,hierarchicalLayout:{layerWidth:300,layerSpace:300}}),Q=(e,t)=>({a:e.a*t.a+e.b*t.d,b:e.a*t.b+e.b*t.e,c:e.a*t.c+e.b*t.f+e.c,d:e.d*t.a+e.e*t.d,e:e.d*t.b+e.e*t.e,f:e.d*t.c+e.e*t.f+e.f}),mn=e=>{let{a:t,b:n,c:r,d:i,e:a,f:o}=e,s=t*a-n*i;return{a:a/s,b:-n/s,c:(n*o-r*a)/s,d:-i/s,e:t/s,f:(r*i-t*o)/s}},hn=class{resolve(e){if(`shift`in e)return this.createShiftBaseMatrix(e.shift);if(`scale`in e){let t=e.origin??{x:0,y:0};return this.createScaleRelativeMatrix(e.scale,t)}if(`rotate`in e){let t=e.origin??{x:0,y:0};return this.createRotateRelativeMatrix(e.rotate,t)}if(`mirror`in e){let t=e.origin??{x:0,y:0};return this.createMirrorRelativeMatrix(e.mirror,t)}return{a:e.a??1,b:e.b??0,c:e.c??0,d:e.d??0,e:e.e??1,f:e.f??0}}createScaleRelativeMatrix(e,t){let n=this.createScaleBaseMatrix(e),r=this.createShiftBaseMatrix(t);return this.createRelativeTransform(n,r)}createRotateRelativeMatrix(e,t){let n=this.createRotateBaseMatrix(e),r=this.createShiftBaseMatrix(t);return this.createRelativeTransform(n,r)}createMirrorRelativeMatrix(e,t){let n=this.createMirrorYBaseMatrix(),r=Q(this.createShiftBaseMatrix(t),this.createRotateBaseMatrix(e));return this.createRelativeTransform(n,r)}createRelativeTransform(e,t){return Q(Q(t,e),mn(t))}createShiftBaseMatrix(e){return{a:1,b:0,c:e.x,d:0,e:1,f:e.y}}createScaleBaseMatrix(e){return{a:e,b:0,c:0,d:0,e,f:0}}createRotateBaseMatrix(e){let t=Math.sin(e),n=Math.cos(e);return{a:n,b:-t,c:0,d:t,e:n,f:0}}createMirrorYBaseMatrix(){return{a:1,b:0,c:0,d:0,e:-1,f:0}}},gn=e=>{if(e===void 0)return e=>e;if(typeof e==`function`)return e;let t=Array.isArray(e)?e:[e],n={a:1,b:0,c:0,d:0,e:1,f:0},r=new hn;return t.forEach(e=>{let t=r.resolve(e);n=Q(n,t)}),e=>{let{x:t,y:r}=e;return{x:n.a*t+n.b*r+n.c,y:n.d*t+n.e*r+n.f}}},_n=e=>{if(typeof e==`function`)return e;switch(e){case`outgoing`:return rn;case`incoming`:return an;default:return nn}},vn=e=>{switch(e?.type){case`custom`:return e.instance;case`hierarchical`:return new tn({layerWidth:e.layerWidth??pn.hierarchicalLayout.layerWidth,layerSpace:e.layerSpace??pn.hierarchicalLayout.layerSpace,transform:gn(e.transform),nextLayerNodesResolver:_n(e.nextLayerNodesResolver)});default:{let t=sn(e?.seed??q.seed),n=cn(t[0],t[1],t[2],t[3]);return new Zt({dtSec:e?.dtSec??q.dtSec,maxIterations:e?.maxIterations??q.maxIterations,rand:n,nodeCharge:e?.nodeCharge??q.nodeCharge,nodeMass:e?.nodeMass??q.nodeMass,edgeEquilibriumLength:e?.edgeEquilibriumLength??q.edgeEquilibriumLength,edgeStiffness:e?.edgeStiffness??q.edgeStiffness,stopVelocity:e?.stopVelocity??q.convergenceVelocity,maxForce:e?.maxForce??q.maxForce,nodeForceCoefficient:e?.nodeForceCoefficient??q.nodeForceCoefficient,barnesHutTheta:e?.barnesHut?.theta??q.barnesHutTheta,barnesHutAreaRadiusThreshold:e?.barnesHut?.areaRadiusThreshold??q.barnesHutAreaRadiusThreshold})}}},yn=e=>({algorithm:vn(e.algorithm),applyOn:fn(e.applyOn),staticNodeResolver:e.staticNodeResolver??pn.staticNodeResolver,onBeforeApplied:e.events?.onBeforeApplied??Y,onAfterApplied:e.events?.onAfterApplied??Y}),bn=(e,t)=>({...e,onNodeDragStarted:n=>{t.add(n),e.onNodeDragStarted(n)},onNodeDragFinished:n=>{t.delete(n),e.onNodeDragFinished(n)}}),xn=(e,t)=>{e.graph.onBeforeNodeRemoved.subscribe(e=>{t.delete(e)}),e.graph.onBeforeClear.subscribe(()=>{t.clear()}),e.onBeforeDestroy.subscribe(()=>{t.clear()})},Sn=(e,t)=>({...e,staticNodeResolver:n=>e.staticNodeResolver(n)||t.has(n)}),$=e=>()=>e,Cn=$(0),wn=()=>{let e=0;return()=>e++},Tn=(e,t)=>{let n=Cn,r=Cn,i=wn();return e===`incremental`&&(n=i),t===`incremental`&&(r=i),typeof e==`number`&&(n=$(e)),typeof t==`number`&&(r=$(t)),typeof e==`function`&&(n=e),typeof t==`function`&&(r=t),{nodesPriorityFn:n,edgesPriorityFn:r}},En=e=>{let t=Tn(e.nodes?.priority,e.edges?.priority);return{nodes:{centerFn:e.nodes?.centerFn??ae,priorityFn:t.nodesPriorityFn},ports:{direction:e.ports?.direction??0},edges:{shapeFactory:Dt(e.edges?.shape??{}),priorityFn:t.edgesPriorityFn}}},Dn=e=>e.applyOn.type===`topologyChangeSchedule`?e.applyOn.schedule:z,On=e=>{let{canvasDefaults:t}=e,n=e.hasLayout?Dn(e.layoutParams):z;return{focus:{contentPadding:t.focus?.contentPadding??100,minContentScale:t.focus?.minContentScale??0,schedule:n,animationDuration:t.focus?.animationDuration??0}}},kn=e=>({onNodeSelected:e.onNodeSelected,mouseDownEventVerifier:e.mouseDownEventVerifier??J.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??J.mouseUpEventVerifier,movementThreshold:e.movementThreshold??J.movementThreshold}),An=e=>({onCanvasSelected:e.onCanvasSelected,mouseDownEventVerifier:e.mouseDownEventVerifier??J.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??J.mouseUpEventVerifier,movementThreshold:e.movementThreshold??J.movementThreshold}),jn=e=>({onEdgeSelected:e.onEdgeSelected,mouseDownEventVerifier:e.mouseDownEventVerifier??J.mouseDownEventVerifier,mouseUpEventVerifier:e.mouseUpEventVerifier??J.mouseUpEventVerifier,movementThreshold:e.movementThreshold??J.movementThreshold}),Mn=class{element;used=!1;canvasDefaults={};dragConfig={};transformConfig={};backgroundConfig={};connectablePortsConfig={};draggableEdgesConfig={};virtualScrollConfig=void 0;layoutConfig={};animatedLayoutConfig={};userSelectableNodesConfig=void 0;userSelectableEdgesConfig=void 0;userSelectableCanvasConfig=void 0;hasDraggableNodes=!1;hasTransformableViewport=!1;hasNodeResizeReactiveEdges=!1;hasBackground=!1;hasUserConnectablePorts=!1;hasUserDraggableEdges=!1;hasAnimatedLayout=!1;hasLayout=!1;boxRenderingTrigger=new u;window=window;animationStaticNodes=new Set;pointInsideVerifier;eventTagger=new et;constructor(e){this.element=e,this.pointInsideVerifier=new te(e,this.window)}setDefaults(e){return this.canvasDefaults=e,this}enableUserDraggableNodes(e){return this.hasDraggableNodes=!0,this.dragConfig=e??{},this}enableUserTransformableViewport(e){return this.hasTransformableViewport=!0,this.transformConfig=e??{},this}enableNodeResizeReactiveEdges(){return this.hasNodeResizeReactiveEdges=!0,this}enableVirtualScroll(e){return this.virtualScrollConfig=e,this}enableBackground(e){return this.hasBackground=!0,this.backgroundConfig=e??{},this}enableUserConnectablePorts(e){return this.hasUserConnectablePorts=!0,this.connectablePortsConfig=e??{},this}enableUserDraggableEdges(e){return this.hasUserDraggableEdges=!0,this.draggableEdgesConfig=e??{},this}enableLayout(e){return this.layoutConfig=e??{},this.hasLayout=!0,this.hasAnimatedLayout=!1,this}enableAnimatedLayout(e){return this.animatedLayoutConfig=e??{},this.hasAnimatedLayout=!0,this.hasLayout=!1,this}enableUserSelectableNodes(e){return this.userSelectableNodesConfig=e,this}enableUserSelectableEdges(e){return this.userSelectableEdgesConfig=e,this}enableUserSelectableCanvas(e){return this.userSelectableCanvasConfig=e,this}build(){if(this.used)throw new Vt(`Failed to build Canvas because CanvasBuilder is a single-use object`);this.used=!0;let e=new b(this.element),t=new g,n=new Tt(this.element),r=this.createHtmlView(n.main,t,e),i=En(this.canvasDefaults),a=new Ge(t,r,i),o=yn(this.layoutConfig),s=new Ze(t,e,On({canvasDefaults:this.canvasDefaults,hasLayout:this.hasLayout,layoutParams:o}),this.window),c=new qe(e),l=new f(new We(t),c,a,s);if(this.hasBackground&&lt.configure(l,It(this.backgroundConfig),n.background),this.hasNodeResizeReactiveEdges&&x.configure(l),this.userSelectableEdgesConfig!==void 0){let e=jn(this.userSelectableEdgesConfig);bt.configure(l,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.userSelectableNodesConfig!==void 0){let e=kn(this.userSelectableNodesConfig);yt.configure(l,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.userSelectableCanvasConfig!==void 0){let e=An(this.userSelectableCanvasConfig);xt.configure(l,n.main,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.hasDraggableNodes){let e=Ot(this.dragConfig);this.hasAnimatedLayout&&(e=bn(e,this.animationStaticNodes)),rt.configure(l,n.main,this.window,this.pointInsideVerifier,this.eventTagger,e)}if(this.hasUserConnectablePorts){let t=Lt(this.connectablePortsConfig,i.edges.shapeFactory,l.graph);ut.configure(l,n.overlayConnectablePorts,e,this.window,this.pointInsideVerifier,this.eventTagger,t)}if(this.hasUserDraggableEdges){let t=Rt(this.draggableEdgesConfig,l.graph);dt.configure(l,n.overlayDraggableEdges,e,this.window,this.pointInsideVerifier,this.eventTagger,t)}if(this.virtualScrollConfig===void 0?this.hasTransformableViewport&&it.configure(l,n.main,this.window,this.pointInsideVerifier,this.eventTagger,Nt(this.transformConfig)):at.configure(l,n.main,this.window,Nt(this.transformConfig),this.boxRenderingTrigger,this.pointInsideVerifier,this.eventTagger,zt(this.virtualScrollConfig)),this.hasLayout&&ht.configure(l,o),this.hasAnimatedLayout){let e=dn(this.animatedLayoutConfig);this.hasDraggableNodes&&(xn(l,this.animationStaticNodes),e=Sn(e,this.animationStaticNodes)),vt.configure(l,e,this.window)}return l.onBeforeDestroy.subscribe(()=>{n.destroy()}),l}createHtmlView(e,t,n){let r=new o(t,n,e);return this.virtualScrollConfig!==void 0&&(r=new c(r,t,this.boxRenderingTrigger,Bt(this.virtualScrollConfig))),r=new l(r,t),r}};e.BezierEdgeShape=je,e.CanvasBuilder=Mn,e.CanvasBuilderError=Vt,e.CanvasError=m,e.ConnectionCategory=t,e.DirectEdgeShape=L,e.EventSubject=u,e.InteractiveEdgeError=Ve,e.InteractiveEdgeShape=He,e.MidpointEdgeShape=Ue,e.OrthogonalEdgeShape=Pe,e.StraightEdgeShape=Me});