/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
(self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] = self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] || []).push([["vendors-node_modules_mermaid_dist_mindmap-definition-e19a4bed_js"],{

/***/ "../node_modules/cose-base/cose-base.js":
/*!**********************************************!*\
  !*** ../node_modules/cose-base/cose-base.js ***!
  \**********************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

eval("(function webpackUniversalModuleDefinition(root, factory) {\n\tif(true)\n\t\tmodule.exports = factory(__webpack_require__(/*! layout-base */ \"../node_modules/layout-base/layout-base.js\"));\n\telse {}\n})(this, function(__WEBPACK_EXTERNAL_MODULE_0__) {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __nested_webpack_require_643__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_643__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__nested_webpack_require_643__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__nested_webpack_require_643__.c = installedModules;\n/******/\n/******/ \t// identity function for calling harmony imports with the correct context\n/******/ \t__nested_webpack_require_643__.i = function(value) { return value; };\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__nested_webpack_require_643__.d = function(exports, name, getter) {\n/******/ \t\tif(!__nested_webpack_require_643__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__nested_webpack_require_643__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__nested_webpack_require_643__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__nested_webpack_require_643__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__nested_webpack_require_643__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __nested_webpack_require_643__(__nested_webpack_require_643__.s = 7);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_0__;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports, __nested_webpack_require_3185__) {\n\n\"use strict\";\n\n\nvar FDLayoutConstants = __nested_webpack_require_3185__(0).FDLayoutConstants;\n\nfunction CoSEConstants() {}\n\n//CoSEConstants inherits static props in FDLayoutConstants\nfor (var prop in FDLayoutConstants) {\n  CoSEConstants[prop] = FDLayoutConstants[prop];\n}\n\nCoSEConstants.DEFAULT_USE_MULTI_LEVEL_SCALING = false;\nCoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;\nCoSEConstants.DEFAULT_COMPONENT_SEPERATION = 60;\nCoSEConstants.TILE = true;\nCoSEConstants.TILING_PADDING_VERTICAL = 10;\nCoSEConstants.TILING_PADDING_HORIZONTAL = 10;\nCoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = false; // make this true when cose is used incrementally as a part of other non-incremental layout\n\nmodule.exports = CoSEConstants;\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __nested_webpack_require_4002__) {\n\n\"use strict\";\n\n\nvar FDLayoutEdge = __nested_webpack_require_4002__(0).FDLayoutEdge;\n\nfunction CoSEEdge(source, target, vEdge) {\n  FDLayoutEdge.call(this, source, target, vEdge);\n}\n\nCoSEEdge.prototype = Object.create(FDLayoutEdge.prototype);\nfor (var prop in FDLayoutEdge) {\n  CoSEEdge[prop] = FDLayoutEdge[prop];\n}\n\nmodule.exports = CoSEEdge;\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __nested_webpack_require_4409__) {\n\n\"use strict\";\n\n\nvar LGraph = __nested_webpack_require_4409__(0).LGraph;\n\nfunction CoSEGraph(parent, graphMgr, vGraph) {\n  LGraph.call(this, parent, graphMgr, vGraph);\n}\n\nCoSEGraph.prototype = Object.create(LGraph.prototype);\nfor (var prop in LGraph) {\n  CoSEGraph[prop] = LGraph[prop];\n}\n\nmodule.exports = CoSEGraph;\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __nested_webpack_require_4790__) {\n\n\"use strict\";\n\n\nvar LGraphManager = __nested_webpack_require_4790__(0).LGraphManager;\n\nfunction CoSEGraphManager(layout) {\n  LGraphManager.call(this, layout);\n}\n\nCoSEGraphManager.prototype = Object.create(LGraphManager.prototype);\nfor (var prop in LGraphManager) {\n  CoSEGraphManager[prop] = LGraphManager[prop];\n}\n\nmodule.exports = CoSEGraphManager;\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __nested_webpack_require_5205__) {\n\n\"use strict\";\n\n\nvar FDLayoutNode = __nested_webpack_require_5205__(0).FDLayoutNode;\nvar IMath = __nested_webpack_require_5205__(0).IMath;\n\nfunction CoSENode(gm, loc, size, vNode) {\n  FDLayoutNode.call(this, gm, loc, size, vNode);\n}\n\nCoSENode.prototype = Object.create(FDLayoutNode.prototype);\nfor (var prop in FDLayoutNode) {\n  CoSENode[prop] = FDLayoutNode[prop];\n}\n\nCoSENode.prototype.move = function () {\n  var layout = this.graphManager.getLayout();\n  this.displacementX = layout.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.noOfChildren;\n  this.displacementY = layout.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.noOfChildren;\n\n  if (Math.abs(this.displacementX) > layout.coolingFactor * layout.maxNodeDisplacement) {\n    this.displacementX = layout.coolingFactor * layout.maxNodeDisplacement * IMath.sign(this.displacementX);\n  }\n\n  if (Math.abs(this.displacementY) > layout.coolingFactor * layout.maxNodeDisplacement) {\n    this.displacementY = layout.coolingFactor * layout.maxNodeDisplacement * IMath.sign(this.displacementY);\n  }\n\n  // a simple node, just move it\n  if (this.child == null) {\n    this.moveBy(this.displacementX, this.displacementY);\n  }\n  // an empty compound node, again just move it\n  else if (this.child.getNodes().length == 0) {\n      this.moveBy(this.displacementX, this.displacementY);\n    }\n    // non-empty compound node, propogate movement to children as well\n    else {\n        this.propogateDisplacementToChildren(this.displacementX, this.displacementY);\n      }\n\n  layout.totalDisplacement += Math.abs(this.displacementX) + Math.abs(this.displacementY);\n\n  this.springForceX = 0;\n  this.springForceY = 0;\n  this.repulsionForceX = 0;\n  this.repulsionForceY = 0;\n  this.gravitationForceX = 0;\n  this.gravitationForceY = 0;\n  this.displacementX = 0;\n  this.displacementY = 0;\n};\n\nCoSENode.prototype.propogateDisplacementToChildren = function (dX, dY) {\n  var nodes = this.getChild().getNodes();\n  var node;\n  for (var i = 0; i < nodes.length; i++) {\n    node = nodes[i];\n    if (node.getChild() == null) {\n      node.moveBy(dX, dY);\n      node.displacementX += dX;\n      node.displacementY += dY;\n    } else {\n      node.propogateDisplacementToChildren(dX, dY);\n    }\n  }\n};\n\nCoSENode.prototype.setPred1 = function (pred1) {\n  this.pred1 = pred1;\n};\n\nCoSENode.prototype.getPred1 = function () {\n  return pred1;\n};\n\nCoSENode.prototype.getPred2 = function () {\n  return pred2;\n};\n\nCoSENode.prototype.setNext = function (next) {\n  this.next = next;\n};\n\nCoSENode.prototype.getNext = function () {\n  return next;\n};\n\nCoSENode.prototype.setProcessed = function (processed) {\n  this.processed = processed;\n};\n\nCoSENode.prototype.isProcessed = function () {\n  return processed;\n};\n\nmodule.exports = CoSENode;\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __nested_webpack_require_8085__) {\n\n\"use strict\";\n\n\nvar FDLayout = __nested_webpack_require_8085__(0).FDLayout;\nvar CoSEGraphManager = __nested_webpack_require_8085__(4);\nvar CoSEGraph = __nested_webpack_require_8085__(3);\nvar CoSENode = __nested_webpack_require_8085__(5);\nvar CoSEEdge = __nested_webpack_require_8085__(2);\nvar CoSEConstants = __nested_webpack_require_8085__(1);\nvar FDLayoutConstants = __nested_webpack_require_8085__(0).FDLayoutConstants;\nvar LayoutConstants = __nested_webpack_require_8085__(0).LayoutConstants;\nvar Point = __nested_webpack_require_8085__(0).Point;\nvar PointD = __nested_webpack_require_8085__(0).PointD;\nvar Layout = __nested_webpack_require_8085__(0).Layout;\nvar Integer = __nested_webpack_require_8085__(0).Integer;\nvar IGeometry = __nested_webpack_require_8085__(0).IGeometry;\nvar LGraph = __nested_webpack_require_8085__(0).LGraph;\nvar Transform = __nested_webpack_require_8085__(0).Transform;\n\nfunction CoSELayout() {\n  FDLayout.call(this);\n\n  this.toBeTiled = {}; // Memorize if a node is to be tiled or is tiled\n}\n\nCoSELayout.prototype = Object.create(FDLayout.prototype);\n\nfor (var prop in FDLayout) {\n  CoSELayout[prop] = FDLayout[prop];\n}\n\nCoSELayout.prototype.newGraphManager = function () {\n  var gm = new CoSEGraphManager(this);\n  this.graphManager = gm;\n  return gm;\n};\n\nCoSELayout.prototype.newGraph = function (vGraph) {\n  return new CoSEGraph(null, this.graphManager, vGraph);\n};\n\nCoSELayout.prototype.newNode = function (vNode) {\n  return new CoSENode(this.graphManager, vNode);\n};\n\nCoSELayout.prototype.newEdge = function (vEdge) {\n  return new CoSEEdge(null, null, vEdge);\n};\n\nCoSELayout.prototype.initParameters = function () {\n  FDLayout.prototype.initParameters.call(this, arguments);\n  if (!this.isSubLayout) {\n    if (CoSEConstants.DEFAULT_EDGE_LENGTH < 10) {\n      this.idealEdgeLength = 10;\n    } else {\n      this.idealEdgeLength = CoSEConstants.DEFAULT_EDGE_LENGTH;\n    }\n\n    this.useSmartIdealEdgeLengthCalculation = CoSEConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;\n    this.springConstant = FDLayoutConstants.DEFAULT_SPRING_STRENGTH;\n    this.repulsionConstant = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH;\n    this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;\n    this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;\n    this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;\n    this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;\n\n    // variables for tree reduction support\n    this.prunedNodesAll = [];\n    this.growTreeIterations = 0;\n    this.afterGrowthIterations = 0;\n    this.isTreeGrowing = false;\n    this.isGrowthFinished = false;\n\n    // variables for cooling\n    this.coolingCycle = 0;\n    this.maxCoolingCycle = this.maxIterations / FDLayoutConstants.CONVERGENCE_CHECK_PERIOD;\n    this.finalTemperature = FDLayoutConstants.CONVERGENCE_CHECK_PERIOD / this.maxIterations;\n    this.coolingAdjuster = 1;\n  }\n};\n\nCoSELayout.prototype.layout = function () {\n  var createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;\n  if (createBendsAsNeeded) {\n    this.createBendpoints();\n    this.graphManager.resetAllEdges();\n  }\n\n  this.level = 0;\n  return this.classicLayout();\n};\n\nCoSELayout.prototype.classicLayout = function () {\n  this.nodesWithGravity = this.calculateNodesToApplyGravitationTo();\n  this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity);\n  this.calcNoOfChildrenForAllNodes();\n  this.graphManager.calcLowestCommonAncestors();\n  this.graphManager.calcInclusionTreeDepths();\n  this.graphManager.getRoot().calcEstimatedSize();\n  this.calcIdealEdgeLengths();\n\n  if (!this.incremental) {\n    var forest = this.getFlatForest();\n\n    // The graph associated with this layout is flat and a forest\n    if (forest.length > 0) {\n      this.positionNodesRadially(forest);\n    }\n    // The graph associated with this layout is not flat or a forest\n    else {\n        // Reduce the trees when incremental mode is not enabled and graph is not a forest \n        this.reduceTrees();\n        // Update nodes that gravity will be applied\n        this.graphManager.resetAllNodesToApplyGravitation();\n        var allNodes = new Set(this.getAllNodes());\n        var intersection = this.nodesWithGravity.filter(function (x) {\n          return allNodes.has(x);\n        });\n        this.graphManager.setAllNodesToApplyGravitation(intersection);\n\n        this.positionNodesRandomly();\n      }\n  } else {\n    if (CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL) {\n      // Reduce the trees in incremental mode if only this constant is set to true \n      this.reduceTrees();\n      // Update nodes that gravity will be applied\n      this.graphManager.resetAllNodesToApplyGravitation();\n      var allNodes = new Set(this.getAllNodes());\n      var intersection = this.nodesWithGravity.filter(function (x) {\n        return allNodes.has(x);\n      });\n      this.graphManager.setAllNodesToApplyGravitation(intersection);\n    }\n  }\n\n  this.initSpringEmbedder();\n  this.runSpringEmbedder();\n\n  return true;\n};\n\nCoSELayout.prototype.tick = function () {\n  this.totalIterations++;\n\n  if (this.totalIterations === this.maxIterations && !this.isTreeGrowing && !this.isGrowthFinished) {\n    if (this.prunedNodesAll.length > 0) {\n      this.isTreeGrowing = true;\n    } else {\n      return true;\n    }\n  }\n\n  if (this.totalIterations % FDLayoutConstants.CONVERGENCE_CHECK_PERIOD == 0 && !this.isTreeGrowing && !this.isGrowthFinished) {\n    if (this.isConverged()) {\n      if (this.prunedNodesAll.length > 0) {\n        this.isTreeGrowing = true;\n      } else {\n        return true;\n      }\n    }\n\n    this.coolingCycle++;\n\n    if (this.layoutQuality == 0) {\n      // quality - \"draft\"\n      this.coolingAdjuster = this.coolingCycle;\n    } else if (this.layoutQuality == 1) {\n      // quality - \"default\"\n      this.coolingAdjuster = this.coolingCycle / 3;\n    }\n\n    // cooling schedule is based on http://www.btluke.com/simanf1.html -> cooling schedule 3\n    this.coolingFactor = Math.max(this.initialCoolingFactor - Math.pow(this.coolingCycle, Math.log(100 * (this.initialCoolingFactor - this.finalTemperature)) / Math.log(this.maxCoolingCycle)) / 100 * this.coolingAdjuster, this.finalTemperature);\n    this.animationPeriod = Math.ceil(this.initialAnimationPeriod * Math.sqrt(this.coolingFactor));\n  }\n  // Operations while tree is growing again \n  if (this.isTreeGrowing) {\n    if (this.growTreeIterations % 10 == 0) {\n      if (this.prunedNodesAll.length > 0) {\n        this.graphManager.updateBounds();\n        this.updateGrid();\n        this.growTree(this.prunedNodesAll);\n        // Update nodes that gravity will be applied\n        this.graphManager.resetAllNodesToApplyGravitation();\n        var allNodes = new Set(this.getAllNodes());\n        var intersection = this.nodesWithGravity.filter(function (x) {\n          return allNodes.has(x);\n        });\n        this.graphManager.setAllNodesToApplyGravitation(intersection);\n\n        this.graphManager.updateBounds();\n        this.updateGrid();\n        this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;\n      } else {\n        this.isTreeGrowing = false;\n        this.isGrowthFinished = true;\n      }\n    }\n    this.growTreeIterations++;\n  }\n  // Operations after growth is finished\n  if (this.isGrowthFinished) {\n    if (this.isConverged()) {\n      return true;\n    }\n    if (this.afterGrowthIterations % 10 == 0) {\n      this.graphManager.updateBounds();\n      this.updateGrid();\n    }\n    this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL * ((100 - this.afterGrowthIterations) / 100);\n    this.afterGrowthIterations++;\n  }\n\n  var gridUpdateAllowed = !this.isTreeGrowing && !this.isGrowthFinished;\n  var forceToNodeSurroundingUpdate = this.growTreeIterations % 10 == 1 && this.isTreeGrowing || this.afterGrowthIterations % 10 == 1 && this.isGrowthFinished;\n\n  this.totalDisplacement = 0;\n  this.graphManager.updateBounds();\n  this.calcSpringForces();\n  this.calcRepulsionForces(gridUpdateAllowed, forceToNodeSurroundingUpdate);\n  this.calcGravitationalForces();\n  this.moveNodes();\n  this.animate();\n\n  return false; // Layout is not ended yet return false\n};\n\nCoSELayout.prototype.getPositionsData = function () {\n  var allNodes = this.graphManager.getAllNodes();\n  var pData = {};\n  for (var i = 0; i < allNodes.length; i++) {\n    var rect = allNodes[i].rect;\n    var id = allNodes[i].id;\n    pData[id] = {\n      id: id,\n      x: rect.getCenterX(),\n      y: rect.getCenterY(),\n      w: rect.width,\n      h: rect.height\n    };\n  }\n\n  return pData;\n};\n\nCoSELayout.prototype.runSpringEmbedder = function () {\n  this.initialAnimationPeriod = 25;\n  this.animationPeriod = this.initialAnimationPeriod;\n  var layoutEnded = false;\n\n  // If aminate option is 'during' signal that layout is supposed to start iterating\n  if (FDLayoutConstants.ANIMATE === 'during') {\n    this.emit('layoutstarted');\n  } else {\n    // If aminate option is 'during' tick() function will be called on index.js\n    while (!layoutEnded) {\n      layoutEnded = this.tick();\n    }\n\n    this.graphManager.updateBounds();\n  }\n};\n\nCoSELayout.prototype.calculateNodesToApplyGravitationTo = function () {\n  var nodeList = [];\n  var graph;\n\n  var graphs = this.graphManager.getGraphs();\n  var size = graphs.length;\n  var i;\n  for (i = 0; i < size; i++) {\n    graph = graphs[i];\n\n    graph.updateConnected();\n\n    if (!graph.isConnected) {\n      nodeList = nodeList.concat(graph.getNodes());\n    }\n  }\n\n  return nodeList;\n};\n\nCoSELayout.prototype.createBendpoints = function () {\n  var edges = [];\n  edges = edges.concat(this.graphManager.getAllEdges());\n  var visited = new Set();\n  var i;\n  for (i = 0; i < edges.length; i++) {\n    var edge = edges[i];\n\n    if (!visited.has(edge)) {\n      var source = edge.getSource();\n      var target = edge.getTarget();\n\n      if (source == target) {\n        edge.getBendpoints().push(new PointD());\n        edge.getBendpoints().push(new PointD());\n        this.createDummyNodesForBendpoints(edge);\n        visited.add(edge);\n      } else {\n        var edgeList = [];\n\n        edgeList = edgeList.concat(source.getEdgeListToNode(target));\n        edgeList = edgeList.concat(target.getEdgeListToNode(source));\n\n        if (!visited.has(edgeList[0])) {\n          if (edgeList.length > 1) {\n            var k;\n            for (k = 0; k < edgeList.length; k++) {\n              var multiEdge = edgeList[k];\n              multiEdge.getBendpoints().push(new PointD());\n              this.createDummyNodesForBendpoints(multiEdge);\n            }\n          }\n          edgeList.forEach(function (edge) {\n            visited.add(edge);\n          });\n        }\n      }\n    }\n\n    if (visited.size == edges.length) {\n      break;\n    }\n  }\n};\n\nCoSELayout.prototype.positionNodesRadially = function (forest) {\n  // We tile the trees to a grid row by row; first tree starts at (0,0)\n  var currentStartingPoint = new Point(0, 0);\n  var numberOfColumns = Math.ceil(Math.sqrt(forest.length));\n  var height = 0;\n  var currentY = 0;\n  var currentX = 0;\n  var point = new PointD(0, 0);\n\n  for (var i = 0; i < forest.length; i++) {\n    if (i % numberOfColumns == 0) {\n      // Start of a new row, make the x coordinate 0, increment the\n      // y coordinate with the max height of the previous row\n      currentX = 0;\n      currentY = height;\n\n      if (i != 0) {\n        currentY += CoSEConstants.DEFAULT_COMPONENT_SEPERATION;\n      }\n\n      height = 0;\n    }\n\n    var tree = forest[i];\n\n    // Find the center of the tree\n    var centerNode = Layout.findCenterOfTree(tree);\n\n    // Set the staring point of the next tree\n    currentStartingPoint.x = currentX;\n    currentStartingPoint.y = currentY;\n\n    // Do a radial layout starting with the center\n    point = CoSELayout.radialLayout(tree, centerNode, currentStartingPoint);\n\n    if (point.y > height) {\n      height = Math.floor(point.y);\n    }\n\n    currentX = Math.floor(point.x + CoSEConstants.DEFAULT_COMPONENT_SEPERATION);\n  }\n\n  this.transform(new PointD(LayoutConstants.WORLD_CENTER_X - point.x / 2, LayoutConstants.WORLD_CENTER_Y - point.y / 2));\n};\n\nCoSELayout.radialLayout = function (tree, centerNode, startingPoint) {\n  var radialSep = Math.max(this.maxDiagonalInTree(tree), CoSEConstants.DEFAULT_RADIAL_SEPARATION);\n  CoSELayout.branchRadialLayout(centerNode, null, 0, 359, 0, radialSep);\n  var bounds = LGraph.calculateBounds(tree);\n\n  var transform = new Transform();\n  transform.setDeviceOrgX(bounds.getMinX());\n  transform.setDeviceOrgY(bounds.getMinY());\n  transform.setWorldOrgX(startingPoint.x);\n  transform.setWorldOrgY(startingPoint.y);\n\n  for (var i = 0; i < tree.length; i++) {\n    var node = tree[i];\n    node.transform(transform);\n  }\n\n  var bottomRight = new PointD(bounds.getMaxX(), bounds.getMaxY());\n\n  return transform.inverseTransformPoint(bottomRight);\n};\n\nCoSELayout.branchRadialLayout = function (node, parentOfNode, startAngle, endAngle, distance, radialSeparation) {\n  // First, position this node by finding its angle.\n  var halfInterval = (endAngle - startAngle + 1) / 2;\n\n  if (halfInterval < 0) {\n    halfInterval += 180;\n  }\n\n  var nodeAngle = (halfInterval + startAngle) % 360;\n  var teta = nodeAngle * IGeometry.TWO_PI / 360;\n\n  // Make polar to java cordinate conversion.\n  var cos_teta = Math.cos(teta);\n  var x_ = distance * Math.cos(teta);\n  var y_ = distance * Math.sin(teta);\n\n  node.setCenter(x_, y_);\n\n  // Traverse all neighbors of this node and recursively call this\n  // function.\n  var neighborEdges = [];\n  neighborEdges = neighborEdges.concat(node.getEdges());\n  var childCount = neighborEdges.length;\n\n  if (parentOfNode != null) {\n    childCount--;\n  }\n\n  var branchCount = 0;\n\n  var incEdgesCount = neighborEdges.length;\n  var startIndex;\n\n  var edges = node.getEdgesBetween(parentOfNode);\n\n  // If there are multiple edges, prune them until there remains only one\n  // edge.\n  while (edges.length > 1) {\n    //neighborEdges.remove(edges.remove(0));\n    var temp = edges[0];\n    edges.splice(0, 1);\n    var index = neighborEdges.indexOf(temp);\n    if (index >= 0) {\n      neighborEdges.splice(index, 1);\n    }\n    incEdgesCount--;\n    childCount--;\n  }\n\n  if (parentOfNode != null) {\n    //assert edges.length == 1;\n    startIndex = (neighborEdges.indexOf(edges[0]) + 1) % incEdgesCount;\n  } else {\n    startIndex = 0;\n  }\n\n  var stepAngle = Math.abs(endAngle - startAngle) / childCount;\n\n  for (var i = startIndex; branchCount != childCount; i = ++i % incEdgesCount) {\n    var currentNeighbor = neighborEdges[i].getOtherEnd(node);\n\n    // Don't back traverse to root node in current tree.\n    if (currentNeighbor == parentOfNode) {\n      continue;\n    }\n\n    var childStartAngle = (startAngle + branchCount * stepAngle) % 360;\n    var childEndAngle = (childStartAngle + stepAngle) % 360;\n\n    CoSELayout.branchRadialLayout(currentNeighbor, node, childStartAngle, childEndAngle, distance + radialSeparation, radialSeparation);\n\n    branchCount++;\n  }\n};\n\nCoSELayout.maxDiagonalInTree = function (tree) {\n  var maxDiagonal = Integer.MIN_VALUE;\n\n  for (var i = 0; i < tree.length; i++) {\n    var node = tree[i];\n    var diagonal = node.getDiagonal();\n\n    if (diagonal > maxDiagonal) {\n      maxDiagonal = diagonal;\n    }\n  }\n\n  return maxDiagonal;\n};\n\nCoSELayout.prototype.calcRepulsionRange = function () {\n  // formula is 2 x (level + 1) x idealEdgeLength\n  return 2 * (this.level + 1) * this.idealEdgeLength;\n};\n\n// Tiling methods\n\n// Group zero degree members whose parents are not to be tiled, create dummy parents where needed and fill memberGroups by their dummp parent id's\nCoSELayout.prototype.groupZeroDegreeMembers = function () {\n  var self = this;\n  // array of [parent_id x oneDegreeNode_id]\n  var tempMemberGroups = {}; // A temporary map of parent node and its zero degree members\n  this.memberGroups = {}; // A map of dummy parent node and its zero degree members whose parents are not to be tiled\n  this.idToDummyNode = {}; // A map of id to dummy node \n\n  var zeroDegree = []; // List of zero degree nodes whose parents are not to be tiled\n  var allNodes = this.graphManager.getAllNodes();\n\n  // Fill zero degree list\n  for (var i = 0; i < allNodes.length; i++) {\n    var node = allNodes[i];\n    var parent = node.getParent();\n    // If a node has zero degree and its parent is not to be tiled if exists add that node to zeroDegres list\n    if (this.getNodeDegreeWithChildren(node) === 0 && (parent.id == undefined || !this.getToBeTiled(parent))) {\n      zeroDegree.push(node);\n    }\n  }\n\n  // Create a map of parent node and its zero degree members\n  for (var i = 0; i < zeroDegree.length; i++) {\n    var node = zeroDegree[i]; // Zero degree node itself\n    var p_id = node.getParent().id; // Parent id\n\n    if (typeof tempMemberGroups[p_id] === \"undefined\") tempMemberGroups[p_id] = [];\n\n    tempMemberGroups[p_id] = tempMemberGroups[p_id].concat(node); // Push node to the list belongs to its parent in tempMemberGroups\n  }\n\n  // If there are at least two nodes at a level, create a dummy compound for them\n  Object.keys(tempMemberGroups).forEach(function (p_id) {\n    if (tempMemberGroups[p_id].length > 1) {\n      var dummyCompoundId = \"DummyCompound_\" + p_id; // The id of dummy compound which will be created soon\n      self.memberGroups[dummyCompoundId] = tempMemberGroups[p_id]; // Add dummy compound to memberGroups\n\n      var parent = tempMemberGroups[p_id][0].getParent(); // The parent of zero degree nodes will be the parent of new dummy compound\n\n      // Create a dummy compound with calculated id\n      var dummyCompound = new CoSENode(self.graphManager);\n      dummyCompound.id = dummyCompoundId;\n      dummyCompound.paddingLeft = parent.paddingLeft || 0;\n      dummyCompound.paddingRight = parent.paddingRight || 0;\n      dummyCompound.paddingBottom = parent.paddingBottom || 0;\n      dummyCompound.paddingTop = parent.paddingTop || 0;\n\n      self.idToDummyNode[dummyCompoundId] = dummyCompound;\n\n      var dummyParentGraph = self.getGraphManager().add(self.newGraph(), dummyCompound);\n      var parentGraph = parent.getChild();\n\n      // Add dummy compound to parent the graph\n      parentGraph.add(dummyCompound);\n\n      // For each zero degree node in this level remove it from its parent graph and add it to the graph of dummy parent\n      for (var i = 0; i < tempMemberGroups[p_id].length; i++) {\n        var node = tempMemberGroups[p_id][i];\n\n        parentGraph.remove(node);\n        dummyParentGraph.add(node);\n      }\n    }\n  });\n};\n\nCoSELayout.prototype.clearCompounds = function () {\n  var childGraphMap = {};\n  var idToNode = {};\n\n  // Get compound ordering by finding the inner one first\n  this.performDFSOnCompounds();\n\n  for (var i = 0; i < this.compoundOrder.length; i++) {\n\n    idToNode[this.compoundOrder[i].id] = this.compoundOrder[i];\n    childGraphMap[this.compoundOrder[i].id] = [].concat(this.compoundOrder[i].getChild().getNodes());\n\n    // Remove children of compounds\n    this.graphManager.remove(this.compoundOrder[i].getChild());\n    this.compoundOrder[i].child = null;\n  }\n\n  this.graphManager.resetAllNodes();\n\n  // Tile the removed children\n  this.tileCompoundMembers(childGraphMap, idToNode);\n};\n\nCoSELayout.prototype.clearZeroDegreeMembers = function () {\n  var self = this;\n  var tiledZeroDegreePack = this.tiledZeroDegreePack = [];\n\n  Object.keys(this.memberGroups).forEach(function (id) {\n    var compoundNode = self.idToDummyNode[id]; // Get the dummy compound\n\n    tiledZeroDegreePack[id] = self.tileNodes(self.memberGroups[id], compoundNode.paddingLeft + compoundNode.paddingRight);\n\n    // Set the width and height of the dummy compound as calculated\n    compoundNode.rect.width = tiledZeroDegreePack[id].width;\n    compoundNode.rect.height = tiledZeroDegreePack[id].height;\n  });\n};\n\nCoSELayout.prototype.repopulateCompounds = function () {\n  for (var i = this.compoundOrder.length - 1; i >= 0; i--) {\n    var lCompoundNode = this.compoundOrder[i];\n    var id = lCompoundNode.id;\n    var horizontalMargin = lCompoundNode.paddingLeft;\n    var verticalMargin = lCompoundNode.paddingTop;\n\n    this.adjustLocations(this.tiledMemberPack[id], lCompoundNode.rect.x, lCompoundNode.rect.y, horizontalMargin, verticalMargin);\n  }\n};\n\nCoSELayout.prototype.repopulateZeroDegreeMembers = function () {\n  var self = this;\n  var tiledPack = this.tiledZeroDegreePack;\n\n  Object.keys(tiledPack).forEach(function (id) {\n    var compoundNode = self.idToDummyNode[id]; // Get the dummy compound by its id\n    var horizontalMargin = compoundNode.paddingLeft;\n    var verticalMargin = compoundNode.paddingTop;\n\n    // Adjust the positions of nodes wrt its compound\n    self.adjustLocations(tiledPack[id], compoundNode.rect.x, compoundNode.rect.y, horizontalMargin, verticalMargin);\n  });\n};\n\nCoSELayout.prototype.getToBeTiled = function (node) {\n  var id = node.id;\n  //firstly check the previous results\n  if (this.toBeTiled[id] != null) {\n    return this.toBeTiled[id];\n  }\n\n  //only compound nodes are to be tiled\n  var childGraph = node.getChild();\n  if (childGraph == null) {\n    this.toBeTiled[id] = false;\n    return false;\n  }\n\n  var children = childGraph.getNodes(); // Get the children nodes\n\n  //a compound node is not to be tiled if all of its compound children are not to be tiled\n  for (var i = 0; i < children.length; i++) {\n    var theChild = children[i];\n\n    if (this.getNodeDegree(theChild) > 0) {\n      this.toBeTiled[id] = false;\n      return false;\n    }\n\n    //pass the children not having the compound structure\n    if (theChild.getChild() == null) {\n      this.toBeTiled[theChild.id] = false;\n      continue;\n    }\n\n    if (!this.getToBeTiled(theChild)) {\n      this.toBeTiled[id] = false;\n      return false;\n    }\n  }\n  this.toBeTiled[id] = true;\n  return true;\n};\n\n// Get degree of a node depending of its edges and independent of its children\nCoSELayout.prototype.getNodeDegree = function (node) {\n  var id = node.id;\n  var edges = node.getEdges();\n  var degree = 0;\n\n  // For the edges connected\n  for (var i = 0; i < edges.length; i++) {\n    var edge = edges[i];\n    if (edge.getSource().id !== edge.getTarget().id) {\n      degree = degree + 1;\n    }\n  }\n  return degree;\n};\n\n// Get degree of a node with its children\nCoSELayout.prototype.getNodeDegreeWithChildren = function (node) {\n  var degree = this.getNodeDegree(node);\n  if (node.getChild() == null) {\n    return degree;\n  }\n  var children = node.getChild().getNodes();\n  for (var i = 0; i < children.length; i++) {\n    var child = children[i];\n    degree += this.getNodeDegreeWithChildren(child);\n  }\n  return degree;\n};\n\nCoSELayout.prototype.performDFSOnCompounds = function () {\n  this.compoundOrder = [];\n  this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes());\n};\n\nCoSELayout.prototype.fillCompexOrderByDFS = function (children) {\n  for (var i = 0; i < children.length; i++) {\n    var child = children[i];\n    if (child.getChild() != null) {\n      this.fillCompexOrderByDFS(child.getChild().getNodes());\n    }\n    if (this.getToBeTiled(child)) {\n      this.compoundOrder.push(child);\n    }\n  }\n};\n\n/**\n* This method places each zero degree member wrt given (x,y) coordinates (top left).\n*/\nCoSELayout.prototype.adjustLocations = function (organization, x, y, compoundHorizontalMargin, compoundVerticalMargin) {\n  x += compoundHorizontalMargin;\n  y += compoundVerticalMargin;\n\n  var left = x;\n\n  for (var i = 0; i < organization.rows.length; i++) {\n    var row = organization.rows[i];\n    x = left;\n    var maxHeight = 0;\n\n    for (var j = 0; j < row.length; j++) {\n      var lnode = row[j];\n\n      lnode.rect.x = x; // + lnode.rect.width / 2;\n      lnode.rect.y = y; // + lnode.rect.height / 2;\n\n      x += lnode.rect.width + organization.horizontalPadding;\n\n      if (lnode.rect.height > maxHeight) maxHeight = lnode.rect.height;\n    }\n\n    y += maxHeight + organization.verticalPadding;\n  }\n};\n\nCoSELayout.prototype.tileCompoundMembers = function (childGraphMap, idToNode) {\n  var self = this;\n  this.tiledMemberPack = [];\n\n  Object.keys(childGraphMap).forEach(function (id) {\n    // Get the compound node\n    var compoundNode = idToNode[id];\n\n    self.tiledMemberPack[id] = self.tileNodes(childGraphMap[id], compoundNode.paddingLeft + compoundNode.paddingRight);\n\n    compoundNode.rect.width = self.tiledMemberPack[id].width;\n    compoundNode.rect.height = self.tiledMemberPack[id].height;\n  });\n};\n\nCoSELayout.prototype.tileNodes = function (nodes, minWidth) {\n  var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;\n  var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;\n  var organization = {\n    rows: [],\n    rowWidth: [],\n    rowHeight: [],\n    width: 0,\n    height: minWidth, // assume minHeight equals to minWidth\n    verticalPadding: verticalPadding,\n    horizontalPadding: horizontalPadding\n  };\n\n  // Sort the nodes in ascending order of their areas\n  nodes.sort(function (n1, n2) {\n    if (n1.rect.width * n1.rect.height > n2.rect.width * n2.rect.height) return -1;\n    if (n1.rect.width * n1.rect.height < n2.rect.width * n2.rect.height) return 1;\n    return 0;\n  });\n\n  // Create the organization -> tile members\n  for (var i = 0; i < nodes.length; i++) {\n    var lNode = nodes[i];\n\n    if (organization.rows.length == 0) {\n      this.insertNodeToRow(organization, lNode, 0, minWidth);\n    } else if (this.canAddHorizontal(organization, lNode.rect.width, lNode.rect.height)) {\n      this.insertNodeToRow(organization, lNode, this.getShortestRowIndex(organization), minWidth);\n    } else {\n      this.insertNodeToRow(organization, lNode, organization.rows.length, minWidth);\n    }\n\n    this.shiftToLastRow(organization);\n  }\n\n  return organization;\n};\n\nCoSELayout.prototype.insertNodeToRow = function (organization, node, rowIndex, minWidth) {\n  var minCompoundSize = minWidth;\n\n  // Add new row if needed\n  if (rowIndex == organization.rows.length) {\n    var secondDimension = [];\n\n    organization.rows.push(secondDimension);\n    organization.rowWidth.push(minCompoundSize);\n    organization.rowHeight.push(0);\n  }\n\n  // Update row width\n  var w = organization.rowWidth[rowIndex] + node.rect.width;\n\n  if (organization.rows[rowIndex].length > 0) {\n    w += organization.horizontalPadding;\n  }\n\n  organization.rowWidth[rowIndex] = w;\n  // Update compound width\n  if (organization.width < w) {\n    organization.width = w;\n  }\n\n  // Update height\n  var h = node.rect.height;\n  if (rowIndex > 0) h += organization.verticalPadding;\n\n  var extraHeight = 0;\n  if (h > organization.rowHeight[rowIndex]) {\n    extraHeight = organization.rowHeight[rowIndex];\n    organization.rowHeight[rowIndex] = h;\n    extraHeight = organization.rowHeight[rowIndex] - extraHeight;\n  }\n\n  organization.height += extraHeight;\n\n  // Insert node\n  organization.rows[rowIndex].push(node);\n};\n\n//Scans the rows of an organization and returns the one with the min width\nCoSELayout.prototype.getShortestRowIndex = function (organization) {\n  var r = -1;\n  var min = Number.MAX_VALUE;\n\n  for (var i = 0; i < organization.rows.length; i++) {\n    if (organization.rowWidth[i] < min) {\n      r = i;\n      min = organization.rowWidth[i];\n    }\n  }\n  return r;\n};\n\n//Scans the rows of an organization and returns the one with the max width\nCoSELayout.prototype.getLongestRowIndex = function (organization) {\n  var r = -1;\n  var max = Number.MIN_VALUE;\n\n  for (var i = 0; i < organization.rows.length; i++) {\n\n    if (organization.rowWidth[i] > max) {\n      r = i;\n      max = organization.rowWidth[i];\n    }\n  }\n\n  return r;\n};\n\n/**\n* This method checks whether adding extra width to the organization violates\n* the aspect ratio(1) or not.\n*/\nCoSELayout.prototype.canAddHorizontal = function (organization, extraWidth, extraHeight) {\n\n  var sri = this.getShortestRowIndex(organization);\n\n  if (sri < 0) {\n    return true;\n  }\n\n  var min = organization.rowWidth[sri];\n\n  if (min + organization.horizontalPadding + extraWidth <= organization.width) return true;\n\n  var hDiff = 0;\n\n  // Adding to an existing row\n  if (organization.rowHeight[sri] < extraHeight) {\n    if (sri > 0) hDiff = extraHeight + organization.verticalPadding - organization.rowHeight[sri];\n  }\n\n  var add_to_row_ratio;\n  if (organization.width - min >= extraWidth + organization.horizontalPadding) {\n    add_to_row_ratio = (organization.height + hDiff) / (min + extraWidth + organization.horizontalPadding);\n  } else {\n    add_to_row_ratio = (organization.height + hDiff) / organization.width;\n  }\n\n  // Adding a new row for this node\n  hDiff = extraHeight + organization.verticalPadding;\n  var add_new_row_ratio;\n  if (organization.width < extraWidth) {\n    add_new_row_ratio = (organization.height + hDiff) / extraWidth;\n  } else {\n    add_new_row_ratio = (organization.height + hDiff) / organization.width;\n  }\n\n  if (add_new_row_ratio < 1) add_new_row_ratio = 1 / add_new_row_ratio;\n\n  if (add_to_row_ratio < 1) add_to_row_ratio = 1 / add_to_row_ratio;\n\n  return add_to_row_ratio < add_new_row_ratio;\n};\n\n//If moving the last node from the longest row and adding it to the last\n//row makes the bounding box smaller, do it.\nCoSELayout.prototype.shiftToLastRow = function (organization) {\n  var longest = this.getLongestRowIndex(organization);\n  var last = organization.rowWidth.length - 1;\n  var row = organization.rows[longest];\n  var node = row[row.length - 1];\n\n  var diff = node.width + organization.horizontalPadding;\n\n  // Check if there is enough space on the last row\n  if (organization.width - organization.rowWidth[last] > diff && longest != last) {\n    // Remove the last element of the longest row\n    row.splice(-1, 1);\n\n    // Push it to the last row\n    organization.rows[last].push(node);\n\n    organization.rowWidth[longest] = organization.rowWidth[longest] - diff;\n    organization.rowWidth[last] = organization.rowWidth[last] + diff;\n    organization.width = organization.rowWidth[instance.getLongestRowIndex(organization)];\n\n    // Update heights of the organization\n    var maxHeight = Number.MIN_VALUE;\n    for (var i = 0; i < row.length; i++) {\n      if (row[i].height > maxHeight) maxHeight = row[i].height;\n    }\n    if (longest > 0) maxHeight += organization.verticalPadding;\n\n    var prevTotal = organization.rowHeight[longest] + organization.rowHeight[last];\n\n    organization.rowHeight[longest] = maxHeight;\n    if (organization.rowHeight[last] < node.height + organization.verticalPadding) organization.rowHeight[last] = node.height + organization.verticalPadding;\n\n    var finalTotal = organization.rowHeight[longest] + organization.rowHeight[last];\n    organization.height += finalTotal - prevTotal;\n\n    this.shiftToLastRow(organization);\n  }\n};\n\nCoSELayout.prototype.tilingPreLayout = function () {\n  if (CoSEConstants.TILE) {\n    // Find zero degree nodes and create a compound for each level\n    this.groupZeroDegreeMembers();\n    // Tile and clear children of each compound\n    this.clearCompounds();\n    // Separately tile and clear zero degree nodes for each level\n    this.clearZeroDegreeMembers();\n  }\n};\n\nCoSELayout.prototype.tilingPostLayout = function () {\n  if (CoSEConstants.TILE) {\n    this.repopulateZeroDegreeMembers();\n    this.repopulateCompounds();\n  }\n};\n\n// -----------------------------------------------------------------------------\n// Section: Tree Reduction methods\n// -----------------------------------------------------------------------------\n// Reduce trees \nCoSELayout.prototype.reduceTrees = function () {\n  var prunedNodesAll = [];\n  var containsLeaf = true;\n  var node;\n\n  while (containsLeaf) {\n    var allNodes = this.graphManager.getAllNodes();\n    var prunedNodesInStepTemp = [];\n    containsLeaf = false;\n\n    for (var i = 0; i < allNodes.length; i++) {\n      node = allNodes[i];\n      if (node.getEdges().length == 1 && !node.getEdges()[0].isInterGraph && node.getChild() == null) {\n        prunedNodesInStepTemp.push([node, node.getEdges()[0], node.getOwner()]);\n        containsLeaf = true;\n      }\n    }\n    if (containsLeaf == true) {\n      var prunedNodesInStep = [];\n      for (var j = 0; j < prunedNodesInStepTemp.length; j++) {\n        if (prunedNodesInStepTemp[j][0].getEdges().length == 1) {\n          prunedNodesInStep.push(prunedNodesInStepTemp[j]);\n          prunedNodesInStepTemp[j][0].getOwner().remove(prunedNodesInStepTemp[j][0]);\n        }\n      }\n      prunedNodesAll.push(prunedNodesInStep);\n      this.graphManager.resetAllNodes();\n      this.graphManager.resetAllEdges();\n    }\n  }\n  this.prunedNodesAll = prunedNodesAll;\n};\n\n// Grow tree one step \nCoSELayout.prototype.growTree = function (prunedNodesAll) {\n  var lengthOfPrunedNodesInStep = prunedNodesAll.length;\n  var prunedNodesInStep = prunedNodesAll[lengthOfPrunedNodesInStep - 1];\n\n  var nodeData;\n  for (var i = 0; i < prunedNodesInStep.length; i++) {\n    nodeData = prunedNodesInStep[i];\n\n    this.findPlaceforPrunedNode(nodeData);\n\n    nodeData[2].add(nodeData[0]);\n    nodeData[2].add(nodeData[1], nodeData[1].source, nodeData[1].target);\n  }\n\n  prunedNodesAll.splice(prunedNodesAll.length - 1, 1);\n  this.graphManager.resetAllNodes();\n  this.graphManager.resetAllEdges();\n};\n\n// Find an appropriate position to replace pruned node, this method can be improved\nCoSELayout.prototype.findPlaceforPrunedNode = function (nodeData) {\n\n  var gridForPrunedNode;\n  var nodeToConnect;\n  var prunedNode = nodeData[0];\n  if (prunedNode == nodeData[1].source) {\n    nodeToConnect = nodeData[1].target;\n  } else {\n    nodeToConnect = nodeData[1].source;\n  }\n  var startGridX = nodeToConnect.startX;\n  var finishGridX = nodeToConnect.finishX;\n  var startGridY = nodeToConnect.startY;\n  var finishGridY = nodeToConnect.finishY;\n\n  var upNodeCount = 0;\n  var downNodeCount = 0;\n  var rightNodeCount = 0;\n  var leftNodeCount = 0;\n  var controlRegions = [upNodeCount, rightNodeCount, downNodeCount, leftNodeCount];\n\n  if (startGridY > 0) {\n    for (var i = startGridX; i <= finishGridX; i++) {\n      controlRegions[0] += this.grid[i][startGridY - 1].length + this.grid[i][startGridY].length - 1;\n    }\n  }\n  if (finishGridX < this.grid.length - 1) {\n    for (var i = startGridY; i <= finishGridY; i++) {\n      controlRegions[1] += this.grid[finishGridX + 1][i].length + this.grid[finishGridX][i].length - 1;\n    }\n  }\n  if (finishGridY < this.grid[0].length - 1) {\n    for (var i = startGridX; i <= finishGridX; i++) {\n      controlRegions[2] += this.grid[i][finishGridY + 1].length + this.grid[i][finishGridY].length - 1;\n    }\n  }\n  if (startGridX > 0) {\n    for (var i = startGridY; i <= finishGridY; i++) {\n      controlRegions[3] += this.grid[startGridX - 1][i].length + this.grid[startGridX][i].length - 1;\n    }\n  }\n  var min = Integer.MAX_VALUE;\n  var minCount;\n  var minIndex;\n  for (var j = 0; j < controlRegions.length; j++) {\n    if (controlRegions[j] < min) {\n      min = controlRegions[j];\n      minCount = 1;\n      minIndex = j;\n    } else if (controlRegions[j] == min) {\n      minCount++;\n    }\n  }\n\n  if (minCount == 3 && min == 0) {\n    if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[2] == 0) {\n      gridForPrunedNode = 1;\n    } else if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[3] == 0) {\n      gridForPrunedNode = 0;\n    } else if (controlRegions[0] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {\n      gridForPrunedNode = 3;\n    } else if (controlRegions[1] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {\n      gridForPrunedNode = 2;\n    }\n  } else if (minCount == 2 && min == 0) {\n    var random = Math.floor(Math.random() * 2);\n    if (controlRegions[0] == 0 && controlRegions[1] == 0) {\n      ;\n      if (random == 0) {\n        gridForPrunedNode = 0;\n      } else {\n        gridForPrunedNode = 1;\n      }\n    } else if (controlRegions[0] == 0 && controlRegions[2] == 0) {\n      if (random == 0) {\n        gridForPrunedNode = 0;\n      } else {\n        gridForPrunedNode = 2;\n      }\n    } else if (controlRegions[0] == 0 && controlRegions[3] == 0) {\n      if (random == 0) {\n        gridForPrunedNode = 0;\n      } else {\n        gridForPrunedNode = 3;\n      }\n    } else if (controlRegions[1] == 0 && controlRegions[2] == 0) {\n      if (random == 0) {\n        gridForPrunedNode = 1;\n      } else {\n        gridForPrunedNode = 2;\n      }\n    } else if (controlRegions[1] == 0 && controlRegions[3] == 0) {\n      if (random == 0) {\n        gridForPrunedNode = 1;\n      } else {\n        gridForPrunedNode = 3;\n      }\n    } else {\n      if (random == 0) {\n        gridForPrunedNode = 2;\n      } else {\n        gridForPrunedNode = 3;\n      }\n    }\n  } else if (minCount == 4 && min == 0) {\n    var random = Math.floor(Math.random() * 4);\n    gridForPrunedNode = random;\n  } else {\n    gridForPrunedNode = minIndex;\n  }\n\n  if (gridForPrunedNode == 0) {\n    prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() - nodeToConnect.getHeight() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getHeight() / 2);\n  } else if (gridForPrunedNode == 1) {\n    prunedNode.setCenter(nodeToConnect.getCenterX() + nodeToConnect.getWidth() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getWidth() / 2, nodeToConnect.getCenterY());\n  } else if (gridForPrunedNode == 2) {\n    prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() + nodeToConnect.getHeight() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getHeight() / 2);\n  } else {\n    prunedNode.setCenter(nodeToConnect.getCenterX() - nodeToConnect.getWidth() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getWidth() / 2, nodeToConnect.getCenterY());\n  }\n};\n\nmodule.exports = CoSELayout;\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __nested_webpack_require_45620__) {\n\n\"use strict\";\n\n\nvar coseBase = {};\n\ncoseBase.layoutBase = __nested_webpack_require_45620__(0);\ncoseBase.CoSEConstants = __nested_webpack_require_45620__(1);\ncoseBase.CoSEEdge = __nested_webpack_require_45620__(2);\ncoseBase.CoSEGraph = __nested_webpack_require_45620__(3);\ncoseBase.CoSEGraphManager = __nested_webpack_require_45620__(4);\ncoseBase.CoSELayout = __nested_webpack_require_45620__(6);\ncoseBase.CoSENode = __nested_webpack_require_45620__(5);\n\nmodule.exports = coseBase;\n\n/***/ })\n/******/ ]);\n});\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/cose-base/cose-base.js?");

/***/ }),

/***/ "../node_modules/cytoscape-cose-bilkent/cytoscape-cose-bilkent.js":
/*!************************************************************************!*\
  !*** ../node_modules/cytoscape-cose-bilkent/cytoscape-cose-bilkent.js ***!
  \************************************************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

eval("(function webpackUniversalModuleDefinition(root, factory) {\n\tif(true)\n\t\tmodule.exports = factory(__webpack_require__(/*! cose-base */ \"../node_modules/cose-base/cose-base.js\"));\n\telse {}\n})(this, function(__WEBPACK_EXTERNAL_MODULE_0__) {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __nested_webpack_require_659__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_659__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__nested_webpack_require_659__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__nested_webpack_require_659__.c = installedModules;\n/******/\n/******/ \t// identity function for calling harmony imports with the correct context\n/******/ \t__nested_webpack_require_659__.i = function(value) { return value; };\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__nested_webpack_require_659__.d = function(exports, name, getter) {\n/******/ \t\tif(!__nested_webpack_require_659__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__nested_webpack_require_659__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__nested_webpack_require_659__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__nested_webpack_require_659__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__nested_webpack_require_659__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __nested_webpack_require_659__(__nested_webpack_require_659__.s = 1);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports) {\n\nmodule.exports = __WEBPACK_EXTERNAL_MODULE_0__;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports, __nested_webpack_require_3201__) {\n\n\"use strict\";\n\n\nvar LayoutConstants = __nested_webpack_require_3201__(0).layoutBase.LayoutConstants;\nvar FDLayoutConstants = __nested_webpack_require_3201__(0).layoutBase.FDLayoutConstants;\nvar CoSEConstants = __nested_webpack_require_3201__(0).CoSEConstants;\nvar CoSELayout = __nested_webpack_require_3201__(0).CoSELayout;\nvar CoSENode = __nested_webpack_require_3201__(0).CoSENode;\nvar PointD = __nested_webpack_require_3201__(0).layoutBase.PointD;\nvar DimensionD = __nested_webpack_require_3201__(0).layoutBase.DimensionD;\n\nvar defaults = {\n  // Called on `layoutready`\n  ready: function ready() {},\n  // Called on `layoutstop`\n  stop: function stop() {},\n  // 'draft', 'default' or 'proof\" \n  // - 'draft' fast cooling rate \n  // - 'default' moderate cooling rate \n  // - \"proof\" slow cooling rate\n  quality: 'default',\n  // include labels in node dimensions\n  nodeDimensionsIncludeLabels: false,\n  // number of ticks per frame; higher is faster but more jerky\n  refresh: 30,\n  // Whether to fit the network view after when done\n  fit: true,\n  // Padding on fit\n  padding: 10,\n  // Whether to enable incremental mode\n  randomize: true,\n  // Node repulsion (non overlapping) multiplier\n  nodeRepulsion: 4500,\n  // Ideal edge (non nested) length\n  idealEdgeLength: 50,\n  // Divisor to compute edge forces\n  edgeElasticity: 0.45,\n  // Nesting factor (multiplier) to compute ideal edge length for nested edges\n  nestingFactor: 0.1,\n  // Gravity force (constant)\n  gravity: 0.25,\n  // Maximum number of iterations to perform\n  numIter: 2500,\n  // For enabling tiling\n  tile: true,\n  // Type of layout animation. The option set is {'during', 'end', false}\n  animate: 'end',\n  // Duration for animate:end\n  animationDuration: 500,\n  // Represents the amount of the vertical space to put between the zero degree members during the tiling operation(can also be a function)\n  tilingPaddingVertical: 10,\n  // Represents the amount of the horizontal space to put between the zero degree members during the tiling operation(can also be a function)\n  tilingPaddingHorizontal: 10,\n  // Gravity range (constant) for compounds\n  gravityRangeCompound: 1.5,\n  // Gravity force (constant) for compounds\n  gravityCompound: 1.0,\n  // Gravity range (constant)\n  gravityRange: 3.8,\n  // Initial cooling factor for incremental layout\n  initialEnergyOnIncremental: 0.5\n};\n\nfunction extend(defaults, options) {\n  var obj = {};\n\n  for (var i in defaults) {\n    obj[i] = defaults[i];\n  }\n\n  for (var i in options) {\n    obj[i] = options[i];\n  }\n\n  return obj;\n};\n\nfunction _CoSELayout(_options) {\n  this.options = extend(defaults, _options);\n  getUserOptions(this.options);\n}\n\nvar getUserOptions = function getUserOptions(options) {\n  if (options.nodeRepulsion != null) CoSEConstants.DEFAULT_REPULSION_STRENGTH = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH = options.nodeRepulsion;\n  if (options.idealEdgeLength != null) CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = options.idealEdgeLength;\n  if (options.edgeElasticity != null) CoSEConstants.DEFAULT_SPRING_STRENGTH = FDLayoutConstants.DEFAULT_SPRING_STRENGTH = options.edgeElasticity;\n  if (options.nestingFactor != null) CoSEConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = options.nestingFactor;\n  if (options.gravity != null) CoSEConstants.DEFAULT_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = options.gravity;\n  if (options.numIter != null) CoSEConstants.MAX_ITERATIONS = FDLayoutConstants.MAX_ITERATIONS = options.numIter;\n  if (options.gravityRange != null) CoSEConstants.DEFAULT_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = options.gravityRange;\n  if (options.gravityCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = options.gravityCompound;\n  if (options.gravityRangeCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = options.gravityRangeCompound;\n  if (options.initialEnergyOnIncremental != null) CoSEConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = options.initialEnergyOnIncremental;\n\n  if (options.quality == 'draft') LayoutConstants.QUALITY = 0;else if (options.quality == 'proof') LayoutConstants.QUALITY = 2;else LayoutConstants.QUALITY = 1;\n\n  CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS = FDLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = options.nodeDimensionsIncludeLabels;\n  CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = !options.randomize;\n  CoSEConstants.ANIMATE = FDLayoutConstants.ANIMATE = LayoutConstants.ANIMATE = options.animate;\n  CoSEConstants.TILE = options.tile;\n  CoSEConstants.TILING_PADDING_VERTICAL = typeof options.tilingPaddingVertical === 'function' ? options.tilingPaddingVertical.call() : options.tilingPaddingVertical;\n  CoSEConstants.TILING_PADDING_HORIZONTAL = typeof options.tilingPaddingHorizontal === 'function' ? options.tilingPaddingHorizontal.call() : options.tilingPaddingHorizontal;\n};\n\n_CoSELayout.prototype.run = function () {\n  var ready;\n  var frameId;\n  var options = this.options;\n  var idToLNode = this.idToLNode = {};\n  var layout = this.layout = new CoSELayout();\n  var self = this;\n\n  self.stopped = false;\n\n  this.cy = this.options.cy;\n\n  this.cy.trigger({ type: 'layoutstart', layout: this });\n\n  var gm = layout.newGraphManager();\n  this.gm = gm;\n\n  var nodes = this.options.eles.nodes();\n  var edges = this.options.eles.edges();\n\n  this.root = gm.addRoot();\n  this.processChildrenList(this.root, this.getTopMostNodes(nodes), layout);\n\n  for (var i = 0; i < edges.length; i++) {\n    var edge = edges[i];\n    var sourceNode = this.idToLNode[edge.data(\"source\")];\n    var targetNode = this.idToLNode[edge.data(\"target\")];\n    if (sourceNode !== targetNode && sourceNode.getEdgesBetween(targetNode).length == 0) {\n      var e1 = gm.add(layout.newEdge(), sourceNode, targetNode);\n      e1.id = edge.id();\n    }\n  }\n\n  var getPositions = function getPositions(ele, i) {\n    if (typeof ele === \"number\") {\n      ele = i;\n    }\n    var theId = ele.data('id');\n    var lNode = self.idToLNode[theId];\n\n    return {\n      x: lNode.getRect().getCenterX(),\n      y: lNode.getRect().getCenterY()\n    };\n  };\n\n  /*\n   * Reposition nodes in iterations animatedly\n   */\n  var iterateAnimated = function iterateAnimated() {\n    // Thigs to perform after nodes are repositioned on screen\n    var afterReposition = function afterReposition() {\n      if (options.fit) {\n        options.cy.fit(options.eles, options.padding);\n      }\n\n      if (!ready) {\n        ready = true;\n        self.cy.one('layoutready', options.ready);\n        self.cy.trigger({ type: 'layoutready', layout: self });\n      }\n    };\n\n    var ticksPerFrame = self.options.refresh;\n    var isDone;\n\n    for (var i = 0; i < ticksPerFrame && !isDone; i++) {\n      isDone = self.stopped || self.layout.tick();\n    }\n\n    // If layout is done\n    if (isDone) {\n      // If the layout is not a sublayout and it is successful perform post layout.\n      if (layout.checkLayoutSuccess() && !layout.isSubLayout) {\n        layout.doPostLayout();\n      }\n\n      // If layout has a tilingPostLayout function property call it.\n      if (layout.tilingPostLayout) {\n        layout.tilingPostLayout();\n      }\n\n      layout.isLayoutFinished = true;\n\n      self.options.eles.nodes().positions(getPositions);\n\n      afterReposition();\n\n      // trigger layoutstop when the layout stops (e.g. finishes)\n      self.cy.one('layoutstop', self.options.stop);\n      self.cy.trigger({ type: 'layoutstop', layout: self });\n\n      if (frameId) {\n        cancelAnimationFrame(frameId);\n      }\n\n      ready = false;\n      return;\n    }\n\n    var animationData = self.layout.getPositionsData(); // Get positions of layout nodes note that all nodes may not be layout nodes because of tiling\n\n    // Position nodes, for the nodes whose id does not included in data (because they are removed from their parents and included in dummy compounds)\n    // use position of their ancestors or dummy ancestors\n    options.eles.nodes().positions(function (ele, i) {\n      if (typeof ele === \"number\") {\n        ele = i;\n      }\n      // If ele is a compound node, then its position will be defined by its children\n      if (!ele.isParent()) {\n        var theId = ele.id();\n        var pNode = animationData[theId];\n        var temp = ele;\n        // If pNode is undefined search until finding position data of its first ancestor (It may be dummy as well)\n        while (pNode == null) {\n          pNode = animationData[temp.data('parent')] || animationData['DummyCompound_' + temp.data('parent')];\n          animationData[theId] = pNode;\n          temp = temp.parent()[0];\n          if (temp == undefined) {\n            break;\n          }\n        }\n        if (pNode != null) {\n          return {\n            x: pNode.x,\n            y: pNode.y\n          };\n        } else {\n          return {\n            x: ele.position('x'),\n            y: ele.position('y')\n          };\n        }\n      }\n    });\n\n    afterReposition();\n\n    frameId = requestAnimationFrame(iterateAnimated);\n  };\n\n  /*\n  * Listen 'layoutstarted' event and start animated iteration if animate option is 'during'\n  */\n  layout.addListener('layoutstarted', function () {\n    if (self.options.animate === 'during') {\n      frameId = requestAnimationFrame(iterateAnimated);\n    }\n  });\n\n  layout.runLayout(); // Run cose layout\n\n  /*\n   * If animate option is not 'during' ('end' or false) perform these here (If it is 'during' similar things are already performed)\n   */\n  if (this.options.animate !== \"during\") {\n    self.options.eles.nodes().not(\":parent\").layoutPositions(self, self.options, getPositions); // Use layout positions to reposition the nodes it considers the options parameter\n    ready = false;\n  }\n\n  return this; // chaining\n};\n\n//Get the top most ones of a list of nodes\n_CoSELayout.prototype.getTopMostNodes = function (nodes) {\n  var nodesMap = {};\n  for (var i = 0; i < nodes.length; i++) {\n    nodesMap[nodes[i].id()] = true;\n  }\n  var roots = nodes.filter(function (ele, i) {\n    if (typeof ele === \"number\") {\n      ele = i;\n    }\n    var parent = ele.parent()[0];\n    while (parent != null) {\n      if (nodesMap[parent.id()]) {\n        return false;\n      }\n      parent = parent.parent()[0];\n    }\n    return true;\n  });\n\n  return roots;\n};\n\n_CoSELayout.prototype.processChildrenList = function (parent, children, layout) {\n  var size = children.length;\n  for (var i = 0; i < size; i++) {\n    var theChild = children[i];\n    var children_of_children = theChild.children();\n    var theNode;\n\n    var dimensions = theChild.layoutDimensions({\n      nodeDimensionsIncludeLabels: this.options.nodeDimensionsIncludeLabels\n    });\n\n    if (theChild.outerWidth() != null && theChild.outerHeight() != null) {\n      theNode = parent.add(new CoSENode(layout.graphManager, new PointD(theChild.position('x') - dimensions.w / 2, theChild.position('y') - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));\n    } else {\n      theNode = parent.add(new CoSENode(this.graphManager));\n    }\n    // Attach id to the layout node\n    theNode.id = theChild.data(\"id\");\n    // Attach the paddings of cy node to layout node\n    theNode.paddingLeft = parseInt(theChild.css('padding'));\n    theNode.paddingTop = parseInt(theChild.css('padding'));\n    theNode.paddingRight = parseInt(theChild.css('padding'));\n    theNode.paddingBottom = parseInt(theChild.css('padding'));\n\n    //Attach the label properties to compound if labels will be included in node dimensions  \n    if (this.options.nodeDimensionsIncludeLabels) {\n      if (theChild.isParent()) {\n        var labelWidth = theChild.boundingBox({ includeLabels: true, includeNodes: false }).w;\n        var labelHeight = theChild.boundingBox({ includeLabels: true, includeNodes: false }).h;\n        var labelPos = theChild.css(\"text-halign\");\n        theNode.labelWidth = labelWidth;\n        theNode.labelHeight = labelHeight;\n        theNode.labelPos = labelPos;\n      }\n    }\n\n    // Map the layout node\n    this.idToLNode[theChild.data(\"id\")] = theNode;\n\n    if (isNaN(theNode.rect.x)) {\n      theNode.rect.x = 0;\n    }\n\n    if (isNaN(theNode.rect.y)) {\n      theNode.rect.y = 0;\n    }\n\n    if (children_of_children != null && children_of_children.length > 0) {\n      var theNewGraph;\n      theNewGraph = layout.getGraphManager().add(layout.newGraph(), theNode);\n      this.processChildrenList(theNewGraph, children_of_children, layout);\n    }\n  }\n};\n\n/**\n * @brief : called on continuous layouts to stop them before they finish\n */\n_CoSELayout.prototype.stop = function () {\n  this.stopped = true;\n\n  return this; // chaining\n};\n\nvar register = function register(cytoscape) {\n  //  var Layout = getLayout( cytoscape );\n\n  cytoscape('layout', 'cose-bilkent', _CoSELayout);\n};\n\n// auto reg for globals\nif (typeof cytoscape !== 'undefined') {\n  register(cytoscape);\n}\n\nmodule.exports = register;\n\n/***/ })\n/******/ ]);\n});\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/cytoscape-cose-bilkent/cytoscape-cose-bilkent.js?");

/***/ }),

/***/ "../node_modules/cytoscape/dist/cytoscape.umd.js":
/*!*******************************************************!*\
  !*** ../node_modules/cytoscape/dist/cytoscape.umd.js ***!
  \*******************************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

eval("/**\n * Copyright (c) 2016-2023, The Cytoscape Consortium.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the “Software”), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n * of the Software, and to permit persons to whom the Software is furnished to do\n * so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n(function (global, factory) {\n   true ? module.exports = factory() :\n  0;\n})(this, (function () { 'use strict';\n\n  function _typeof(obj) {\n    \"@babel/helpers - typeof\";\n\n    return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n      return typeof obj;\n    } : function (obj) {\n      return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n    }, _typeof(obj);\n  }\n\n  function _classCallCheck(instance, Constructor) {\n    if (!(instance instanceof Constructor)) {\n      throw new TypeError(\"Cannot call a class as a function\");\n    }\n  }\n\n  function _defineProperties(target, props) {\n    for (var i = 0; i < props.length; i++) {\n      var descriptor = props[i];\n      descriptor.enumerable = descriptor.enumerable || false;\n      descriptor.configurable = true;\n      if (\"value\" in descriptor) descriptor.writable = true;\n      Object.defineProperty(target, descriptor.key, descriptor);\n    }\n  }\n\n  function _createClass(Constructor, protoProps, staticProps) {\n    if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n    if (staticProps) _defineProperties(Constructor, staticProps);\n    Object.defineProperty(Constructor, \"prototype\", {\n      writable: false\n    });\n    return Constructor;\n  }\n\n  function _defineProperty$1(obj, key, value) {\n    if (key in obj) {\n      Object.defineProperty(obj, key, {\n        value: value,\n        enumerable: true,\n        configurable: true,\n        writable: true\n      });\n    } else {\n      obj[key] = value;\n    }\n\n    return obj;\n  }\n\n  function _slicedToArray(arr, i) {\n    return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n  }\n\n  function _arrayWithHoles(arr) {\n    if (Array.isArray(arr)) return arr;\n  }\n\n  function _iterableToArrayLimit(arr, i) {\n    var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n    if (_i == null) return;\n    var _arr = [];\n    var _n = true;\n    var _d = false;\n\n    var _s, _e;\n\n    try {\n      for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n        _arr.push(_s.value);\n\n        if (i && _arr.length === i) break;\n      }\n    } catch (err) {\n      _d = true;\n      _e = err;\n    } finally {\n      try {\n        if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n      } finally {\n        if (_d) throw _e;\n      }\n    }\n\n    return _arr;\n  }\n\n  function _unsupportedIterableToArray(o, minLen) {\n    if (!o) return;\n    if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n    var n = Object.prototype.toString.call(o).slice(8, -1);\n    if (n === \"Object\" && o.constructor) n = o.constructor.name;\n    if (n === \"Map\" || n === \"Set\") return Array.from(o);\n    if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n  }\n\n  function _arrayLikeToArray(arr, len) {\n    if (len == null || len > arr.length) len = arr.length;\n\n    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n    return arr2;\n  }\n\n  function _nonIterableRest() {\n    throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n  }\n\n  var _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef\n\n  var navigator = _window ? _window.navigator : null;\n  _window ? _window.document : null;\n\n  var typeofstr = _typeof('');\n\n  var typeofobj = _typeof({});\n\n  var typeoffn = _typeof(function () {});\n\n  var typeofhtmlele = typeof HTMLElement === \"undefined\" ? \"undefined\" : _typeof(HTMLElement);\n\n  var instanceStr = function instanceStr(obj) {\n    return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;\n  };\n\n  var string = function string(obj) {\n    return obj != null && _typeof(obj) == typeofstr;\n  };\n  var fn$6 = function fn(obj) {\n    return obj != null && _typeof(obj) === typeoffn;\n  };\n  var array = function array(obj) {\n    return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);\n  };\n  var plainObject = function plainObject(obj) {\n    return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;\n  };\n  var object = function object(obj) {\n    return obj != null && _typeof(obj) === typeofobj;\n  };\n  var number$1 = function number(obj) {\n    return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);\n  };\n  var integer = function integer(obj) {\n    return number$1(obj) && Math.floor(obj) === obj;\n  };\n  var htmlElement = function htmlElement(obj) {\n    if ('undefined' === typeofhtmlele) {\n      return undefined;\n    } else {\n      return null != obj && obj instanceof HTMLElement;\n    }\n  };\n  var elementOrCollection = function elementOrCollection(obj) {\n    return element(obj) || collection(obj);\n  };\n  var element = function element(obj) {\n    return instanceStr(obj) === 'collection' && obj._private.single;\n  };\n  var collection = function collection(obj) {\n    return instanceStr(obj) === 'collection' && !obj._private.single;\n  };\n  var core = function core(obj) {\n    return instanceStr(obj) === 'core';\n  };\n  var stylesheet = function stylesheet(obj) {\n    return instanceStr(obj) === 'stylesheet';\n  };\n  var event = function event(obj) {\n    return instanceStr(obj) === 'event';\n  };\n  var emptyString = function emptyString(obj) {\n    if (obj === undefined || obj === null) {\n      // null is empty\n      return true;\n    } else if (obj === '' || obj.match(/^\\s+$/)) {\n      return true; // empty string is empty\n    }\n\n    return false; // otherwise, we don't know what we've got\n  };\n  var domElement = function domElement(obj) {\n    if (typeof HTMLElement === 'undefined') {\n      return false; // we're not in a browser so it doesn't matter\n    } else {\n      return obj instanceof HTMLElement;\n    }\n  };\n  var boundingBox = function boundingBox(obj) {\n    return plainObject(obj) && number$1(obj.x1) && number$1(obj.x2) && number$1(obj.y1) && number$1(obj.y2);\n  };\n  var promise = function promise(obj) {\n    return object(obj) && fn$6(obj.then);\n  };\n  var ms = function ms() {\n    return navigator && navigator.userAgent.match(/msie|trident|edge/i);\n  }; // probably a better way to detect this...\n\n  var memoize$1 = function memoize(fn, keyFn) {\n    if (!keyFn) {\n      keyFn = function keyFn() {\n        if (arguments.length === 1) {\n          return arguments[0];\n        } else if (arguments.length === 0) {\n          return 'undefined';\n        }\n\n        var args = [];\n\n        for (var i = 0; i < arguments.length; i++) {\n          args.push(arguments[i]);\n        }\n\n        return args.join('$');\n      };\n    }\n\n    var memoizedFn = function memoizedFn() {\n      var self = this;\n      var args = arguments;\n      var ret;\n      var k = keyFn.apply(self, args);\n      var cache = memoizedFn.cache;\n\n      if (!(ret = cache[k])) {\n        ret = cache[k] = fn.apply(self, args);\n      }\n\n      return ret;\n    };\n\n    memoizedFn.cache = {};\n    return memoizedFn;\n  };\n\n  var camel2dash = memoize$1(function (str) {\n    return str.replace(/([A-Z])/g, function (v) {\n      return '-' + v.toLowerCase();\n    });\n  });\n  var dash2camel = memoize$1(function (str) {\n    return str.replace(/(-\\w)/g, function (v) {\n      return v[1].toUpperCase();\n    });\n  });\n  var prependCamel = memoize$1(function (prefix, str) {\n    return prefix + str[0].toUpperCase() + str.substring(1);\n  }, function (prefix, str) {\n    return prefix + '$' + str;\n  });\n  var capitalize = function capitalize(str) {\n    if (emptyString(str)) {\n      return str;\n    }\n\n    return str.charAt(0).toUpperCase() + str.substring(1);\n  };\n\n  var number = '(?:[-+]?(?:(?:\\\\d+|\\\\d*\\\\.\\\\d+)(?:[Ee][+-]?\\\\d+)?))';\n  var rgba = 'rgb[a]?\\\\((' + number + '[%]?)\\\\s*,\\\\s*(' + number + '[%]?)\\\\s*,\\\\s*(' + number + '[%]?)(?:\\\\s*,\\\\s*(' + number + '))?\\\\)';\n  var rgbaNoBackRefs = 'rgb[a]?\\\\((?:' + number + '[%]?)\\\\s*,\\\\s*(?:' + number + '[%]?)\\\\s*,\\\\s*(?:' + number + '[%]?)(?:\\\\s*,\\\\s*(?:' + number + '))?\\\\)';\n  var hsla = 'hsl[a]?\\\\((' + number + ')\\\\s*,\\\\s*(' + number + '[%])\\\\s*,\\\\s*(' + number + '[%])(?:\\\\s*,\\\\s*(' + number + '))?\\\\)';\n  var hslaNoBackRefs = 'hsl[a]?\\\\((?:' + number + ')\\\\s*,\\\\s*(?:' + number + '[%])\\\\s*,\\\\s*(?:' + number + '[%])(?:\\\\s*,\\\\s*(?:' + number + '))?\\\\)';\n  var hex3 = '\\\\#[0-9a-fA-F]{3}';\n  var hex6 = '\\\\#[0-9a-fA-F]{6}';\n\n  var ascending = function ascending(a, b) {\n    if (a < b) {\n      return -1;\n    } else if (a > b) {\n      return 1;\n    } else {\n      return 0;\n    }\n  };\n  var descending = function descending(a, b) {\n    return -1 * ascending(a, b);\n  };\n\n  var extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {\n    var args = arguments;\n\n    for (var i = 1; i < args.length; i++) {\n      var obj = args[i];\n\n      if (obj == null) {\n        continue;\n      }\n\n      var keys = Object.keys(obj);\n\n      for (var j = 0; j < keys.length; j++) {\n        var k = keys[j];\n        tgt[k] = obj[k];\n      }\n    }\n\n    return tgt;\n  };\n\n  var hex2tuple = function hex2tuple(hex) {\n    if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {\n      return;\n    }\n\n    var shortHex = hex.length === 4;\n    var r, g, b;\n    var base = 16;\n\n    if (shortHex) {\n      r = parseInt(hex[1] + hex[1], base);\n      g = parseInt(hex[2] + hex[2], base);\n      b = parseInt(hex[3] + hex[3], base);\n    } else {\n      r = parseInt(hex[1] + hex[2], base);\n      g = parseInt(hex[3] + hex[4], base);\n      b = parseInt(hex[5] + hex[6], base);\n    }\n\n    return [r, g, b];\n  }; // get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)\n\n  var hsl2tuple = function hsl2tuple(hsl) {\n    var ret;\n    var h, s, l, a, r, g, b;\n\n    function hue2rgb(p, q, t) {\n      if (t < 0) t += 1;\n      if (t > 1) t -= 1;\n      if (t < 1 / 6) return p + (q - p) * 6 * t;\n      if (t < 1 / 2) return q;\n      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;\n      return p;\n    }\n\n    var m = new RegExp('^' + hsla + '$').exec(hsl);\n\n    if (m) {\n      // get hue\n      h = parseInt(m[1]);\n\n      if (h < 0) {\n        h = (360 - -1 * h % 360) % 360;\n      } else if (h > 360) {\n        h = h % 360;\n      }\n\n      h /= 360; // normalise on [0, 1]\n\n      s = parseFloat(m[2]);\n\n      if (s < 0 || s > 100) {\n        return;\n      } // saturation is [0, 100]\n\n\n      s = s / 100; // normalise on [0, 1]\n\n      l = parseFloat(m[3]);\n\n      if (l < 0 || l > 100) {\n        return;\n      } // lightness is [0, 100]\n\n\n      l = l / 100; // normalise on [0, 1]\n\n      a = m[4];\n\n      if (a !== undefined) {\n        a = parseFloat(a);\n\n        if (a < 0 || a > 1) {\n          return;\n        } // alpha is [0, 1]\n\n      } // now, convert to rgb\n      // code from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n\n\n      if (s === 0) {\n        r = g = b = Math.round(l * 255); // achromatic\n      } else {\n        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n        var p = 2 * l - q;\n        r = Math.round(255 * hue2rgb(p, q, h + 1 / 3));\n        g = Math.round(255 * hue2rgb(p, q, h));\n        b = Math.round(255 * hue2rgb(p, q, h - 1 / 3));\n      }\n\n      ret = [r, g, b, a];\n    }\n\n    return ret;\n  }; // get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)\n\n  var rgb2tuple = function rgb2tuple(rgb) {\n    var ret;\n    var m = new RegExp('^' + rgba + '$').exec(rgb);\n\n    if (m) {\n      ret = [];\n      var isPct = [];\n\n      for (var i = 1; i <= 3; i++) {\n        var channel = m[i];\n\n        if (channel[channel.length - 1] === '%') {\n          isPct[i] = true;\n        }\n\n        channel = parseFloat(channel);\n\n        if (isPct[i]) {\n          channel = channel / 100 * 255; // normalise to [0, 255]\n        }\n\n        if (channel < 0 || channel > 255) {\n          return;\n        } // invalid channel value\n\n\n        ret.push(Math.floor(channel));\n      }\n\n      var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];\n      var allArePct = isPct[1] && isPct[2] && isPct[3];\n\n      if (atLeastOneIsPct && !allArePct) {\n        return;\n      } // must all be percent values if one is\n\n\n      var alpha = m[4];\n\n      if (alpha !== undefined) {\n        alpha = parseFloat(alpha);\n\n        if (alpha < 0 || alpha > 1) {\n          return;\n        } // invalid alpha value\n\n\n        ret.push(alpha);\n      }\n    }\n\n    return ret;\n  };\n  var colorname2tuple = function colorname2tuple(color) {\n    return colors[color.toLowerCase()];\n  };\n  var color2tuple = function color2tuple(color) {\n    return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);\n  };\n  var colors = {\n    // special colour names\n    transparent: [0, 0, 0, 0],\n    // NB alpha === 0\n    // regular colours\n    aliceblue: [240, 248, 255],\n    antiquewhite: [250, 235, 215],\n    aqua: [0, 255, 255],\n    aquamarine: [127, 255, 212],\n    azure: [240, 255, 255],\n    beige: [245, 245, 220],\n    bisque: [255, 228, 196],\n    black: [0, 0, 0],\n    blanchedalmond: [255, 235, 205],\n    blue: [0, 0, 255],\n    blueviolet: [138, 43, 226],\n    brown: [165, 42, 42],\n    burlywood: [222, 184, 135],\n    cadetblue: [95, 158, 160],\n    chartreuse: [127, 255, 0],\n    chocolate: [210, 105, 30],\n    coral: [255, 127, 80],\n    cornflowerblue: [100, 149, 237],\n    cornsilk: [255, 248, 220],\n    crimson: [220, 20, 60],\n    cyan: [0, 255, 255],\n    darkblue: [0, 0, 139],\n    darkcyan: [0, 139, 139],\n    darkgoldenrod: [184, 134, 11],\n    darkgray: [169, 169, 169],\n    darkgreen: [0, 100, 0],\n    darkgrey: [169, 169, 169],\n    darkkhaki: [189, 183, 107],\n    darkmagenta: [139, 0, 139],\n    darkolivegreen: [85, 107, 47],\n    darkorange: [255, 140, 0],\n    darkorchid: [153, 50, 204],\n    darkred: [139, 0, 0],\n    darksalmon: [233, 150, 122],\n    darkseagreen: [143, 188, 143],\n    darkslateblue: [72, 61, 139],\n    darkslategray: [47, 79, 79],\n    darkslategrey: [47, 79, 79],\n    darkturquoise: [0, 206, 209],\n    darkviolet: [148, 0, 211],\n    deeppink: [255, 20, 147],\n    deepskyblue: [0, 191, 255],\n    dimgray: [105, 105, 105],\n    dimgrey: [105, 105, 105],\n    dodgerblue: [30, 144, 255],\n    firebrick: [178, 34, 34],\n    floralwhite: [255, 250, 240],\n    forestgreen: [34, 139, 34],\n    fuchsia: [255, 0, 255],\n    gainsboro: [220, 220, 220],\n    ghostwhite: [248, 248, 255],\n    gold: [255, 215, 0],\n    goldenrod: [218, 165, 32],\n    gray: [128, 128, 128],\n    grey: [128, 128, 128],\n    green: [0, 128, 0],\n    greenyellow: [173, 255, 47],\n    honeydew: [240, 255, 240],\n    hotpink: [255, 105, 180],\n    indianred: [205, 92, 92],\n    indigo: [75, 0, 130],\n    ivory: [255, 255, 240],\n    khaki: [240, 230, 140],\n    lavender: [230, 230, 250],\n    lavenderblush: [255, 240, 245],\n    lawngreen: [124, 252, 0],\n    lemonchiffon: [255, 250, 205],\n    lightblue: [173, 216, 230],\n    lightcoral: [240, 128, 128],\n    lightcyan: [224, 255, 255],\n    lightgoldenrodyellow: [250, 250, 210],\n    lightgray: [211, 211, 211],\n    lightgreen: [144, 238, 144],\n    lightgrey: [211, 211, 211],\n    lightpink: [255, 182, 193],\n    lightsalmon: [255, 160, 122],\n    lightseagreen: [32, 178, 170],\n    lightskyblue: [135, 206, 250],\n    lightslategray: [119, 136, 153],\n    lightslategrey: [119, 136, 153],\n    lightsteelblue: [176, 196, 222],\n    lightyellow: [255, 255, 224],\n    lime: [0, 255, 0],\n    limegreen: [50, 205, 50],\n    linen: [250, 240, 230],\n    magenta: [255, 0, 255],\n    maroon: [128, 0, 0],\n    mediumaquamarine: [102, 205, 170],\n    mediumblue: [0, 0, 205],\n    mediumorchid: [186, 85, 211],\n    mediumpurple: [147, 112, 219],\n    mediumseagreen: [60, 179, 113],\n    mediumslateblue: [123, 104, 238],\n    mediumspringgreen: [0, 250, 154],\n    mediumturquoise: [72, 209, 204],\n    mediumvioletred: [199, 21, 133],\n    midnightblue: [25, 25, 112],\n    mintcream: [245, 255, 250],\n    mistyrose: [255, 228, 225],\n    moccasin: [255, 228, 181],\n    navajowhite: [255, 222, 173],\n    navy: [0, 0, 128],\n    oldlace: [253, 245, 230],\n    olive: [128, 128, 0],\n    olivedrab: [107, 142, 35],\n    orange: [255, 165, 0],\n    orangered: [255, 69, 0],\n    orchid: [218, 112, 214],\n    palegoldenrod: [238, 232, 170],\n    palegreen: [152, 251, 152],\n    paleturquoise: [175, 238, 238],\n    palevioletred: [219, 112, 147],\n    papayawhip: [255, 239, 213],\n    peachpuff: [255, 218, 185],\n    peru: [205, 133, 63],\n    pink: [255, 192, 203],\n    plum: [221, 160, 221],\n    powderblue: [176, 224, 230],\n    purple: [128, 0, 128],\n    red: [255, 0, 0],\n    rosybrown: [188, 143, 143],\n    royalblue: [65, 105, 225],\n    saddlebrown: [139, 69, 19],\n    salmon: [250, 128, 114],\n    sandybrown: [244, 164, 96],\n    seagreen: [46, 139, 87],\n    seashell: [255, 245, 238],\n    sienna: [160, 82, 45],\n    silver: [192, 192, 192],\n    skyblue: [135, 206, 235],\n    slateblue: [106, 90, 205],\n    slategray: [112, 128, 144],\n    slategrey: [112, 128, 144],\n    snow: [255, 250, 250],\n    springgreen: [0, 255, 127],\n    steelblue: [70, 130, 180],\n    tan: [210, 180, 140],\n    teal: [0, 128, 128],\n    thistle: [216, 191, 216],\n    tomato: [255, 99, 71],\n    turquoise: [64, 224, 208],\n    violet: [238, 130, 238],\n    wheat: [245, 222, 179],\n    white: [255, 255, 255],\n    whitesmoke: [245, 245, 245],\n    yellow: [255, 255, 0],\n    yellowgreen: [154, 205, 50]\n  };\n\n  var setMap = function setMap(options) {\n    var obj = options.map;\n    var keys = options.keys;\n    var l = keys.length;\n\n    for (var i = 0; i < l; i++) {\n      var key = keys[i];\n\n      if (plainObject(key)) {\n        throw Error('Tried to set map with object key');\n      }\n\n      if (i < keys.length - 1) {\n        // extend the map if necessary\n        if (obj[key] == null) {\n          obj[key] = {};\n        }\n\n        obj = obj[key];\n      } else {\n        // set the value\n        obj[key] = options.value;\n      }\n    }\n  }; // gets the value in a map even if it's not built in places\n\n  var getMap = function getMap(options) {\n    var obj = options.map;\n    var keys = options.keys;\n    var l = keys.length;\n\n    for (var i = 0; i < l; i++) {\n      var key = keys[i];\n\n      if (plainObject(key)) {\n        throw Error('Tried to get map with object key');\n      }\n\n      obj = obj[key];\n\n      if (obj == null) {\n        return obj;\n      }\n    }\n\n    return obj;\n  }; // deletes the entry in the map\n\n  /**\n   * Checks if `value` is the\n   * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n   * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n   *\n   * @static\n   * @memberOf _\n   * @since 0.1.0\n   * @category Lang\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n   * @example\n   *\n   * _.isObject({});\n   * // => true\n   *\n   * _.isObject([1, 2, 3]);\n   * // => true\n   *\n   * _.isObject(_.noop);\n   * // => true\n   *\n   * _.isObject(null);\n   * // => false\n   */\n  function isObject(value) {\n    var type = typeof value;\n    return value != null && (type == 'object' || type == 'function');\n  }\n\n  var isObject_1 = isObject;\n\n  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {};\n\n  function createCommonjsModule(fn, module) {\n  \treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n  }\n\n  /** Detect free variable `global` from Node.js. */\n  var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;\n\n  var _freeGlobal = freeGlobal;\n\n  /** Detect free variable `self`. */\n  var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n  /** Used as a reference to the global object. */\n  var root = _freeGlobal || freeSelf || Function('return this')();\n\n  var _root = root;\n\n  /**\n   * Gets the timestamp of the number of milliseconds that have elapsed since\n   * the Unix epoch (1 January 1970 00:00:00 UTC).\n   *\n   * @static\n   * @memberOf _\n   * @since 2.4.0\n   * @category Date\n   * @returns {number} Returns the timestamp.\n   * @example\n   *\n   * _.defer(function(stamp) {\n   *   console.log(_.now() - stamp);\n   * }, _.now());\n   * // => Logs the number of milliseconds it took for the deferred invocation.\n   */\n  var now = function() {\n    return _root.Date.now();\n  };\n\n  var now_1 = now;\n\n  /** Used to match a single whitespace character. */\n  var reWhitespace = /\\s/;\n\n  /**\n   * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n   * character of `string`.\n   *\n   * @private\n   * @param {string} string The string to inspect.\n   * @returns {number} Returns the index of the last non-whitespace character.\n   */\n  function trimmedEndIndex(string) {\n    var index = string.length;\n\n    while (index-- && reWhitespace.test(string.charAt(index))) {}\n    return index;\n  }\n\n  var _trimmedEndIndex = trimmedEndIndex;\n\n  /** Used to match leading whitespace. */\n  var reTrimStart = /^\\s+/;\n\n  /**\n   * The base implementation of `_.trim`.\n   *\n   * @private\n   * @param {string} string The string to trim.\n   * @returns {string} Returns the trimmed string.\n   */\n  function baseTrim(string) {\n    return string\n      ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n      : string;\n  }\n\n  var _baseTrim = baseTrim;\n\n  /** Built-in value references. */\n  var Symbol$1 = _root.Symbol;\n\n  var _Symbol = Symbol$1;\n\n  /** Used for built-in method references. */\n  var objectProto$5 = Object.prototype;\n\n  /** Used to check objects for own properties. */\n  var hasOwnProperty$4 = objectProto$5.hasOwnProperty;\n\n  /**\n   * Used to resolve the\n   * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n   * of values.\n   */\n  var nativeObjectToString$1 = objectProto$5.toString;\n\n  /** Built-in value references. */\n  var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;\n\n  /**\n   * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n   *\n   * @private\n   * @param {*} value The value to query.\n   * @returns {string} Returns the raw `toStringTag`.\n   */\n  function getRawTag(value) {\n    var isOwn = hasOwnProperty$4.call(value, symToStringTag$1),\n        tag = value[symToStringTag$1];\n\n    try {\n      value[symToStringTag$1] = undefined;\n      var unmasked = true;\n    } catch (e) {}\n\n    var result = nativeObjectToString$1.call(value);\n    if (unmasked) {\n      if (isOwn) {\n        value[symToStringTag$1] = tag;\n      } else {\n        delete value[symToStringTag$1];\n      }\n    }\n    return result;\n  }\n\n  var _getRawTag = getRawTag;\n\n  /** Used for built-in method references. */\n  var objectProto$4 = Object.prototype;\n\n  /**\n   * Used to resolve the\n   * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n   * of values.\n   */\n  var nativeObjectToString = objectProto$4.toString;\n\n  /**\n   * Converts `value` to a string using `Object.prototype.toString`.\n   *\n   * @private\n   * @param {*} value The value to convert.\n   * @returns {string} Returns the converted string.\n   */\n  function objectToString(value) {\n    return nativeObjectToString.call(value);\n  }\n\n  var _objectToString = objectToString;\n\n  /** `Object#toString` result references. */\n  var nullTag = '[object Null]',\n      undefinedTag = '[object Undefined]';\n\n  /** Built-in value references. */\n  var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;\n\n  /**\n   * The base implementation of `getTag` without fallbacks for buggy environments.\n   *\n   * @private\n   * @param {*} value The value to query.\n   * @returns {string} Returns the `toStringTag`.\n   */\n  function baseGetTag(value) {\n    if (value == null) {\n      return value === undefined ? undefinedTag : nullTag;\n    }\n    return (symToStringTag && symToStringTag in Object(value))\n      ? _getRawTag(value)\n      : _objectToString(value);\n  }\n\n  var _baseGetTag = baseGetTag;\n\n  /**\n   * Checks if `value` is object-like. A value is object-like if it's not `null`\n   * and has a `typeof` result of \"object\".\n   *\n   * @static\n   * @memberOf _\n   * @since 4.0.0\n   * @category Lang\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n   * @example\n   *\n   * _.isObjectLike({});\n   * // => true\n   *\n   * _.isObjectLike([1, 2, 3]);\n   * // => true\n   *\n   * _.isObjectLike(_.noop);\n   * // => false\n   *\n   * _.isObjectLike(null);\n   * // => false\n   */\n  function isObjectLike(value) {\n    return value != null && typeof value == 'object';\n  }\n\n  var isObjectLike_1 = isObjectLike;\n\n  /** `Object#toString` result references. */\n  var symbolTag = '[object Symbol]';\n\n  /**\n   * Checks if `value` is classified as a `Symbol` primitive or object.\n   *\n   * @static\n   * @memberOf _\n   * @since 4.0.0\n   * @category Lang\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n   * @example\n   *\n   * _.isSymbol(Symbol.iterator);\n   * // => true\n   *\n   * _.isSymbol('abc');\n   * // => false\n   */\n  function isSymbol(value) {\n    return typeof value == 'symbol' ||\n      (isObjectLike_1(value) && _baseGetTag(value) == symbolTag);\n  }\n\n  var isSymbol_1 = isSymbol;\n\n  /** Used as references for various `Number` constants. */\n  var NAN = 0 / 0;\n\n  /** Used to detect bad signed hexadecimal string values. */\n  var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n  /** Used to detect binary string values. */\n  var reIsBinary = /^0b[01]+$/i;\n\n  /** Used to detect octal string values. */\n  var reIsOctal = /^0o[0-7]+$/i;\n\n  /** Built-in method references without a dependency on `root`. */\n  var freeParseInt = parseInt;\n\n  /**\n   * Converts `value` to a number.\n   *\n   * @static\n   * @memberOf _\n   * @since 4.0.0\n   * @category Lang\n   * @param {*} value The value to process.\n   * @returns {number} Returns the number.\n   * @example\n   *\n   * _.toNumber(3.2);\n   * // => 3.2\n   *\n   * _.toNumber(Number.MIN_VALUE);\n   * // => 5e-324\n   *\n   * _.toNumber(Infinity);\n   * // => Infinity\n   *\n   * _.toNumber('3.2');\n   * // => 3.2\n   */\n  function toNumber(value) {\n    if (typeof value == 'number') {\n      return value;\n    }\n    if (isSymbol_1(value)) {\n      return NAN;\n    }\n    if (isObject_1(value)) {\n      var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n      value = isObject_1(other) ? (other + '') : other;\n    }\n    if (typeof value != 'string') {\n      return value === 0 ? value : +value;\n    }\n    value = _baseTrim(value);\n    var isBinary = reIsBinary.test(value);\n    return (isBinary || reIsOctal.test(value))\n      ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n      : (reIsBadHex.test(value) ? NAN : +value);\n  }\n\n  var toNumber_1 = toNumber;\n\n  /** Error message constants. */\n  var FUNC_ERROR_TEXT$1 = 'Expected a function';\n\n  /* Built-in method references for those with the same name as other `lodash` methods. */\n  var nativeMax = Math.max,\n      nativeMin = Math.min;\n\n  /**\n   * Creates a debounced function that delays invoking `func` until after `wait`\n   * milliseconds have elapsed since the last time the debounced function was\n   * invoked. The debounced function comes with a `cancel` method to cancel\n   * delayed `func` invocations and a `flush` method to immediately invoke them.\n   * Provide `options` to indicate whether `func` should be invoked on the\n   * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n   * with the last arguments provided to the debounced function. Subsequent\n   * calls to the debounced function return the result of the last `func`\n   * invocation.\n   *\n   * **Note:** If `leading` and `trailing` options are `true`, `func` is\n   * invoked on the trailing edge of the timeout only if the debounced function\n   * is invoked more than once during the `wait` timeout.\n   *\n   * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n   * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n   *\n   * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n   * for details over the differences between `_.debounce` and `_.throttle`.\n   *\n   * @static\n   * @memberOf _\n   * @since 0.1.0\n   * @category Function\n   * @param {Function} func The function to debounce.\n   * @param {number} [wait=0] The number of milliseconds to delay.\n   * @param {Object} [options={}] The options object.\n   * @param {boolean} [options.leading=false]\n   *  Specify invoking on the leading edge of the timeout.\n   * @param {number} [options.maxWait]\n   *  The maximum time `func` is allowed to be delayed before it's invoked.\n   * @param {boolean} [options.trailing=true]\n   *  Specify invoking on the trailing edge of the timeout.\n   * @returns {Function} Returns the new debounced function.\n   * @example\n   *\n   * // Avoid costly calculations while the window size is in flux.\n   * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n   *\n   * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n   * jQuery(element).on('click', _.debounce(sendMail, 300, {\n   *   'leading': true,\n   *   'trailing': false\n   * }));\n   *\n   * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n   * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n   * var source = new EventSource('/stream');\n   * jQuery(source).on('message', debounced);\n   *\n   * // Cancel the trailing debounced invocation.\n   * jQuery(window).on('popstate', debounced.cancel);\n   */\n  function debounce(func, wait, options) {\n    var lastArgs,\n        lastThis,\n        maxWait,\n        result,\n        timerId,\n        lastCallTime,\n        lastInvokeTime = 0,\n        leading = false,\n        maxing = false,\n        trailing = true;\n\n    if (typeof func != 'function') {\n      throw new TypeError(FUNC_ERROR_TEXT$1);\n    }\n    wait = toNumber_1(wait) || 0;\n    if (isObject_1(options)) {\n      leading = !!options.leading;\n      maxing = 'maxWait' in options;\n      maxWait = maxing ? nativeMax(toNumber_1(options.maxWait) || 0, wait) : maxWait;\n      trailing = 'trailing' in options ? !!options.trailing : trailing;\n    }\n\n    function invokeFunc(time) {\n      var args = lastArgs,\n          thisArg = lastThis;\n\n      lastArgs = lastThis = undefined;\n      lastInvokeTime = time;\n      result = func.apply(thisArg, args);\n      return result;\n    }\n\n    function leadingEdge(time) {\n      // Reset any `maxWait` timer.\n      lastInvokeTime = time;\n      // Start the timer for the trailing edge.\n      timerId = setTimeout(timerExpired, wait);\n      // Invoke the leading edge.\n      return leading ? invokeFunc(time) : result;\n    }\n\n    function remainingWait(time) {\n      var timeSinceLastCall = time - lastCallTime,\n          timeSinceLastInvoke = time - lastInvokeTime,\n          timeWaiting = wait - timeSinceLastCall;\n\n      return maxing\n        ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n        : timeWaiting;\n    }\n\n    function shouldInvoke(time) {\n      var timeSinceLastCall = time - lastCallTime,\n          timeSinceLastInvoke = time - lastInvokeTime;\n\n      // Either this is the first call, activity has stopped and we're at the\n      // trailing edge, the system time has gone backwards and we're treating\n      // it as the trailing edge, or we've hit the `maxWait` limit.\n      return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n        (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n    }\n\n    function timerExpired() {\n      var time = now_1();\n      if (shouldInvoke(time)) {\n        return trailingEdge(time);\n      }\n      // Restart the timer.\n      timerId = setTimeout(timerExpired, remainingWait(time));\n    }\n\n    function trailingEdge(time) {\n      timerId = undefined;\n\n      // Only invoke if we have `lastArgs` which means `func` has been\n      // debounced at least once.\n      if (trailing && lastArgs) {\n        return invokeFunc(time);\n      }\n      lastArgs = lastThis = undefined;\n      return result;\n    }\n\n    function cancel() {\n      if (timerId !== undefined) {\n        clearTimeout(timerId);\n      }\n      lastInvokeTime = 0;\n      lastArgs = lastCallTime = lastThis = timerId = undefined;\n    }\n\n    function flush() {\n      return timerId === undefined ? result : trailingEdge(now_1());\n    }\n\n    function debounced() {\n      var time = now_1(),\n          isInvoking = shouldInvoke(time);\n\n      lastArgs = arguments;\n      lastThis = this;\n      lastCallTime = time;\n\n      if (isInvoking) {\n        if (timerId === undefined) {\n          return leadingEdge(lastCallTime);\n        }\n        if (maxing) {\n          // Handle invocations in a tight loop.\n          clearTimeout(timerId);\n          timerId = setTimeout(timerExpired, wait);\n          return invokeFunc(lastCallTime);\n        }\n      }\n      if (timerId === undefined) {\n        timerId = setTimeout(timerExpired, wait);\n      }\n      return result;\n    }\n    debounced.cancel = cancel;\n    debounced.flush = flush;\n    return debounced;\n  }\n\n  var debounce_1 = debounce;\n\n  var performance = _window ? _window.performance : null;\n  var pnow = performance && performance.now ? function () {\n    return performance.now();\n  } : function () {\n    return Date.now();\n  };\n\n  var raf = function () {\n    if (_window) {\n      if (_window.requestAnimationFrame) {\n        return function (fn) {\n          _window.requestAnimationFrame(fn);\n        };\n      } else if (_window.mozRequestAnimationFrame) {\n        return function (fn) {\n          _window.mozRequestAnimationFrame(fn);\n        };\n      } else if (_window.webkitRequestAnimationFrame) {\n        return function (fn) {\n          _window.webkitRequestAnimationFrame(fn);\n        };\n      } else if (_window.msRequestAnimationFrame) {\n        return function (fn) {\n          _window.msRequestAnimationFrame(fn);\n        };\n      }\n    }\n\n    return function (fn) {\n      if (fn) {\n        setTimeout(function () {\n          fn(pnow());\n        }, 1000 / 60);\n      }\n    };\n  }();\n\n  var requestAnimationFrame = function requestAnimationFrame(fn) {\n    return raf(fn);\n  };\n  var performanceNow = pnow;\n\n  var DEFAULT_HASH_SEED = 9261;\n  var K = 65599; // 37 also works pretty well\n\n  var DEFAULT_HASH_SEED_ALT = 5381;\n  var hashIterableInts = function hashIterableInts(iterator) {\n    var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;\n    // sdbm/string-hash\n    var hash = seed;\n    var entry;\n\n    for (;;) {\n      entry = iterator.next();\n\n      if (entry.done) {\n        break;\n      }\n\n      hash = hash * K + entry.value | 0;\n    }\n\n    return hash;\n  };\n  var hashInt = function hashInt(num) {\n    var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;\n    // sdbm/string-hash\n    return seed * K + num | 0;\n  };\n  var hashIntAlt = function hashIntAlt(num) {\n    var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED_ALT;\n    // djb2/string-hash\n    return (seed << 5) + seed + num | 0;\n  };\n  var combineHashes = function combineHashes(hash1, hash2) {\n    return hash1 * 0x200000 + hash2;\n  };\n  var combineHashesArray = function combineHashesArray(hashes) {\n    return hashes[0] * 0x200000 + hashes[1];\n  };\n  var hashArrays = function hashArrays(hashes1, hashes2) {\n    return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];\n  };\n  var hashIntsArray = function hashIntsArray(ints, seed) {\n    var entry = {\n      value: 0,\n      done: false\n    };\n    var i = 0;\n    var length = ints.length;\n    var iterator = {\n      next: function next() {\n        if (i < length) {\n          entry.value = ints[i++];\n        } else {\n          entry.done = true;\n        }\n\n        return entry;\n      }\n    };\n    return hashIterableInts(iterator, seed);\n  };\n  var hashString = function hashString(str, seed) {\n    var entry = {\n      value: 0,\n      done: false\n    };\n    var i = 0;\n    var length = str.length;\n    var iterator = {\n      next: function next() {\n        if (i < length) {\n          entry.value = str.charCodeAt(i++);\n        } else {\n          entry.done = true;\n        }\n\n        return entry;\n      }\n    };\n    return hashIterableInts(iterator, seed);\n  };\n  var hashStrings = function hashStrings() {\n    return hashStringsArray(arguments);\n  };\n  var hashStringsArray = function hashStringsArray(strs) {\n    var hash;\n\n    for (var i = 0; i < strs.length; i++) {\n      var str = strs[i];\n\n      if (i === 0) {\n        hash = hashString(str);\n      } else {\n        hash = hashString(str, hash);\n      }\n    }\n\n    return hash;\n  };\n\n  /*global console */\n  var warningsEnabled = true;\n  var warnSupported = console.warn != null; // eslint-disable-line no-console\n\n  var traceSupported = console.trace != null; // eslint-disable-line no-console\n\n  var MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;\n  var trueify = function trueify() {\n    return true;\n  };\n  var falsify = function falsify() {\n    return false;\n  };\n  var zeroify = function zeroify() {\n    return 0;\n  };\n  var noop$1 = function noop() {};\n  var error = function error(msg) {\n    throw new Error(msg);\n  };\n  var warnings = function warnings(enabled) {\n    if (enabled !== undefined) {\n      warningsEnabled = !!enabled;\n    } else {\n      return warningsEnabled;\n    }\n  };\n  var warn = function warn(msg) {\n    /* eslint-disable no-console */\n    if (!warnings()) {\n      return;\n    }\n\n    if (warnSupported) {\n      console.warn(msg);\n    } else {\n      console.log(msg);\n\n      if (traceSupported) {\n        console.trace();\n      }\n    }\n  };\n  /* eslint-enable */\n\n  var clone = function clone(obj) {\n    return extend({}, obj);\n  }; // gets a shallow copy of the argument\n\n  var copy = function copy(obj) {\n    if (obj == null) {\n      return obj;\n    }\n\n    if (array(obj)) {\n      return obj.slice();\n    } else if (plainObject(obj)) {\n      return clone(obj);\n    } else {\n      return obj;\n    }\n  };\n  var copyArray$1 = function copyArray(arr) {\n    return arr.slice();\n  };\n  var uuid = function uuid(a, b\n  /* placeholders */\n  ) {\n    for ( // loop :)\n    b = a = ''; // b - result , a - numeric letiable\n    a++ < 36; //\n    b += a * 51 & 52 // if \"a\" is not 9 or 14 or 19 or 24\n    ? //  return a random number or 4\n    (a ^ 15 // if \"a\" is not 15\n    ? // generate a random number from 0 to 15\n    8 ^ Math.random() * (a ^ 20 ? 16 : 4) // unless \"a\" is 20, in which case a random number from 8 to 11\n    : 4 //  otherwise 4\n    ).toString(16) : '-' //  in other cases (if \"a\" is 9,14,19,24) insert \"-\"\n    ) {\n    }\n\n    return b;\n  };\n  var _staticEmptyObject = {};\n  var staticEmptyObject = function staticEmptyObject() {\n    return _staticEmptyObject;\n  };\n  var defaults$g = function defaults(_defaults) {\n    var keys = Object.keys(_defaults);\n    return function (opts) {\n      var filledOpts = {};\n\n      for (var i = 0; i < keys.length; i++) {\n        var key = keys[i];\n        var optVal = opts == null ? undefined : opts[key];\n        filledOpts[key] = optVal === undefined ? _defaults[key] : optVal;\n      }\n\n      return filledOpts;\n    };\n  };\n  var removeFromArray = function removeFromArray(arr, ele, oneCopy) {\n    for (var i = arr.length - 1; i >= 0; i--) {\n      if (arr[i] === ele) {\n        arr.splice(i, 1);\n\n        if (oneCopy) {\n          break;\n        }\n      }\n    }\n  };\n  var clearArray = function clearArray(arr) {\n    arr.splice(0, arr.length);\n  };\n  var push = function push(arr, otherArr) {\n    for (var i = 0; i < otherArr.length; i++) {\n      var el = otherArr[i];\n      arr.push(el);\n    }\n  };\n  var getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {\n    if (prefix) {\n      propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth\n    }\n\n    return obj[propName];\n  };\n  var setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {\n    if (prefix) {\n      propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth\n    }\n\n    obj[propName] = value;\n  };\n\n  /* global Map */\n  var ObjectMap = /*#__PURE__*/function () {\n    function ObjectMap() {\n      _classCallCheck(this, ObjectMap);\n\n      this._obj = {};\n    }\n\n    _createClass(ObjectMap, [{\n      key: \"set\",\n      value: function set(key, val) {\n        this._obj[key] = val;\n        return this;\n      }\n    }, {\n      key: \"delete\",\n      value: function _delete(key) {\n        this._obj[key] = undefined;\n        return this;\n      }\n    }, {\n      key: \"clear\",\n      value: function clear() {\n        this._obj = {};\n      }\n    }, {\n      key: \"has\",\n      value: function has(key) {\n        return this._obj[key] !== undefined;\n      }\n    }, {\n      key: \"get\",\n      value: function get(key) {\n        return this._obj[key];\n      }\n    }]);\n\n    return ObjectMap;\n  }();\n\n  var Map$2 = typeof Map !== 'undefined' ? Map : ObjectMap;\n\n  /* global Set */\n  var undef = \"undefined\" ;\n\n  var ObjectSet = /*#__PURE__*/function () {\n    function ObjectSet(arrayOrObjectSet) {\n      _classCallCheck(this, ObjectSet);\n\n      this._obj = Object.create(null);\n      this.size = 0;\n\n      if (arrayOrObjectSet != null) {\n        var arr;\n\n        if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {\n          arr = arrayOrObjectSet.toArray();\n        } else {\n          arr = arrayOrObjectSet;\n        }\n\n        for (var i = 0; i < arr.length; i++) {\n          this.add(arr[i]);\n        }\n      }\n    }\n\n    _createClass(ObjectSet, [{\n      key: \"instanceString\",\n      value: function instanceString() {\n        return 'set';\n      }\n    }, {\n      key: \"add\",\n      value: function add(val) {\n        var o = this._obj;\n\n        if (o[val] !== 1) {\n          o[val] = 1;\n          this.size++;\n        }\n      }\n    }, {\n      key: \"delete\",\n      value: function _delete(val) {\n        var o = this._obj;\n\n        if (o[val] === 1) {\n          o[val] = 0;\n          this.size--;\n        }\n      }\n    }, {\n      key: \"clear\",\n      value: function clear() {\n        this._obj = Object.create(null);\n      }\n    }, {\n      key: \"has\",\n      value: function has(val) {\n        return this._obj[val] === 1;\n      }\n    }, {\n      key: \"toArray\",\n      value: function toArray() {\n        var _this = this;\n\n        return Object.keys(this._obj).filter(function (key) {\n          return _this.has(key);\n        });\n      }\n    }, {\n      key: \"forEach\",\n      value: function forEach(callback, thisArg) {\n        return this.toArray().forEach(callback, thisArg);\n      }\n    }]);\n\n    return ObjectSet;\n  }();\n\n  var Set$1 = (typeof Set === \"undefined\" ? \"undefined\" : _typeof(Set)) !== undef ? Set : ObjectSet;\n\n  var Element = function Element(cy, params) {\n    var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n\n    if (cy === undefined || params === undefined || !core(cy)) {\n      error('An element must have a core reference and parameters set');\n      return;\n    }\n\n    var group = params.group; // try to automatically infer the group if unspecified\n\n    if (group == null) {\n      if (params.data && params.data.source != null && params.data.target != null) {\n        group = 'edges';\n      } else {\n        group = 'nodes';\n      }\n    } // validate group\n\n\n    if (group !== 'nodes' && group !== 'edges') {\n      error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');\n      return;\n    } // make the element array-like, just like a collection\n\n\n    this.length = 1;\n    this[0] = this; // NOTE: when something is added here, add also to ele.json()\n\n    var _p = this._private = {\n      cy: cy,\n      single: true,\n      // indicates this is an element\n      data: params.data || {},\n      // data object\n      position: params.position || {\n        x: 0,\n        y: 0\n      },\n      // (x, y) position pair\n      autoWidth: undefined,\n      // width and height of nodes calculated by the renderer when set to special 'auto' value\n      autoHeight: undefined,\n      autoPadding: undefined,\n      compoundBoundsClean: false,\n      // whether the compound dimensions need to be recalculated the next time dimensions are read\n      listeners: [],\n      // array of bound listeners\n      group: group,\n      // string; 'nodes' or 'edges'\n      style: {},\n      // properties as set by the style\n      rstyle: {},\n      // properties for style sent from the renderer to the core\n      styleCxts: [],\n      // applied style contexts from the styler\n      styleKeys: {},\n      // per-group keys of style property values\n      removed: true,\n      // whether it's inside the vis; true if removed (set true here since we call restore)\n      selected: params.selected ? true : false,\n      // whether it's selected\n      selectable: params.selectable === undefined ? true : params.selectable ? true : false,\n      // whether it's selectable\n      locked: params.locked ? true : false,\n      // whether the element is locked (cannot be moved)\n      grabbed: false,\n      // whether the element is grabbed by the mouse; renderer sets this privately\n      grabbable: params.grabbable === undefined ? true : params.grabbable ? true : false,\n      // whether the element can be grabbed\n      pannable: params.pannable === undefined ? group === 'edges' ? true : false : params.pannable ? true : false,\n      // whether the element has passthrough panning enabled\n      active: false,\n      // whether the element is active from user interaction\n      classes: new Set$1(),\n      // map ( className => true )\n      animation: {\n        // object for currently-running animations\n        current: [],\n        queue: []\n      },\n      rscratch: {},\n      // object in which the renderer can store information\n      scratch: params.scratch || {},\n      // scratch objects\n      edges: [],\n      // array of connected edges\n      children: [],\n      // array of children\n      parent: params.parent && params.parent.isNode() ? params.parent : null,\n      // parent ref\n      traversalCache: {},\n      // cache of output of traversal functions\n      backgrounding: false,\n      // whether background images are loading\n      bbCache: null,\n      // cache of the current bounding box\n      bbCacheShift: {\n        x: 0,\n        y: 0\n      },\n      // shift applied to cached bb to be applied on next get\n      bodyBounds: null,\n      // bounds cache of element body, w/o overlay\n      overlayBounds: null,\n      // bounds cache of element body, including overlay\n      labelBounds: {\n        // bounds cache of labels\n        all: null,\n        source: null,\n        target: null,\n        main: null\n      },\n      arrowBounds: {\n        // bounds cache of edge arrows\n        source: null,\n        target: null,\n        'mid-source': null,\n        'mid-target': null\n      }\n    };\n\n    if (_p.position.x == null) {\n      _p.position.x = 0;\n    }\n\n    if (_p.position.y == null) {\n      _p.position.y = 0;\n    } // renderedPosition overrides if specified\n\n\n    if (params.renderedPosition) {\n      var rpos = params.renderedPosition;\n      var pan = cy.pan();\n      var zoom = cy.zoom();\n      _p.position = {\n        x: (rpos.x - pan.x) / zoom,\n        y: (rpos.y - pan.y) / zoom\n      };\n    }\n\n    var classes = [];\n\n    if (array(params.classes)) {\n      classes = params.classes;\n    } else if (string(params.classes)) {\n      classes = params.classes.split(/\\s+/);\n    }\n\n    for (var i = 0, l = classes.length; i < l; i++) {\n      var cls = classes[i];\n\n      if (!cls || cls === '') {\n        continue;\n      }\n\n      _p.classes.add(cls);\n    }\n\n    this.createEmitter();\n    var bypass = params.style || params.css;\n\n    if (bypass) {\n      warn('Setting a `style` bypass at element creation should be done only when absolutely necessary.  Try to use the stylesheet instead.');\n      this.style(bypass);\n    }\n\n    if (restore === undefined || restore) {\n      this.restore();\n    }\n  };\n\n  var defineSearch = function defineSearch(params) {\n    params = {\n      bfs: params.bfs || !params.dfs,\n      dfs: params.dfs || !params.bfs\n    }; // from pseudocode on wikipedia\n\n    return function searchFn(roots, fn, directed) {\n      var options;\n\n      if (plainObject(roots) && !elementOrCollection(roots)) {\n        options = roots;\n        roots = options.roots || options.root;\n        fn = options.visit;\n        directed = options.directed;\n      }\n\n      directed = arguments.length === 2 && !fn$6(fn) ? fn : directed;\n      fn = fn$6(fn) ? fn : function () {};\n      var cy = this._private.cy;\n      var v = roots = string(roots) ? this.filter(roots) : roots;\n      var Q = [];\n      var connectedNodes = [];\n      var connectedBy = {};\n      var id2depth = {};\n      var V = {};\n      var j = 0;\n      var found;\n\n      var _this$byGroup = this.byGroup(),\n          nodes = _this$byGroup.nodes,\n          edges = _this$byGroup.edges; // enqueue v\n\n\n      for (var i = 0; i < v.length; i++) {\n        var vi = v[i];\n        var viId = vi.id();\n\n        if (vi.isNode()) {\n          Q.unshift(vi);\n\n          if (params.bfs) {\n            V[viId] = true;\n            connectedNodes.push(vi);\n          }\n\n          id2depth[viId] = 0;\n        }\n      }\n\n      var _loop = function _loop() {\n        var v = params.bfs ? Q.shift() : Q.pop();\n        var vId = v.id();\n\n        if (params.dfs) {\n          if (V[vId]) {\n            return \"continue\";\n          }\n\n          V[vId] = true;\n          connectedNodes.push(v);\n        }\n\n        var depth = id2depth[vId];\n        var prevEdge = connectedBy[vId];\n        var src = prevEdge != null ? prevEdge.source() : null;\n        var tgt = prevEdge != null ? prevEdge.target() : null;\n        var prevNode = prevEdge == null ? undefined : v.same(src) ? tgt[0] : src[0];\n        var ret = void 0;\n        ret = fn(v, prevEdge, prevNode, j++, depth);\n\n        if (ret === true) {\n          found = v;\n          return \"break\";\n        }\n\n        if (ret === false) {\n          return \"break\";\n        }\n\n        var vwEdges = v.connectedEdges().filter(function (e) {\n          return (!directed || e.source().same(v)) && edges.has(e);\n        });\n\n        for (var _i2 = 0; _i2 < vwEdges.length; _i2++) {\n          var e = vwEdges[_i2];\n          var w = e.connectedNodes().filter(function (n) {\n            return !n.same(v) && nodes.has(n);\n          });\n          var wId = w.id();\n\n          if (w.length !== 0 && !V[wId]) {\n            w = w[0];\n            Q.push(w);\n\n            if (params.bfs) {\n              V[wId] = true;\n              connectedNodes.push(w);\n            }\n\n            connectedBy[wId] = e;\n            id2depth[wId] = id2depth[vId] + 1;\n          }\n        }\n      };\n\n      while (Q.length !== 0) {\n        var _ret = _loop();\n\n        if (_ret === \"continue\") continue;\n        if (_ret === \"break\") break;\n      }\n\n      var connectedEles = cy.collection();\n\n      for (var _i = 0; _i < connectedNodes.length; _i++) {\n        var node = connectedNodes[_i];\n        var edge = connectedBy[node.id()];\n\n        if (edge != null) {\n          connectedEles.push(edge);\n        }\n\n        connectedEles.push(node);\n      }\n\n      return {\n        path: cy.collection(connectedEles),\n        found: cy.collection(found)\n      };\n    };\n  }; // search, spanning trees, etc\n\n\n  var elesfn$v = {\n    breadthFirstSearch: defineSearch({\n      bfs: true\n    }),\n    depthFirstSearch: defineSearch({\n      dfs: true\n    })\n  }; // nice, short mathematical alias\n\n  elesfn$v.bfs = elesfn$v.breadthFirstSearch;\n  elesfn$v.dfs = elesfn$v.depthFirstSearch;\n\n  var heap$1 = createCommonjsModule(function (module, exports) {\n  // Generated by CoffeeScript 1.8.0\n  (function() {\n    var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n    floor = Math.floor, min = Math.min;\n\n\n    /*\n    Default comparison function to be used\n     */\n\n    defaultCmp = function(x, y) {\n      if (x < y) {\n        return -1;\n      }\n      if (x > y) {\n        return 1;\n      }\n      return 0;\n    };\n\n\n    /*\n    Insert item x in list a, and keep it sorted assuming a is sorted.\n    \n    If x is already in a, insert it to the right of the rightmost x.\n    \n    Optional args lo (default 0) and hi (default a.length) bound the slice\n    of a to be searched.\n     */\n\n    insort = function(a, x, lo, hi, cmp) {\n      var mid;\n      if (lo == null) {\n        lo = 0;\n      }\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      if (lo < 0) {\n        throw new Error('lo must be non-negative');\n      }\n      if (hi == null) {\n        hi = a.length;\n      }\n      while (lo < hi) {\n        mid = floor((lo + hi) / 2);\n        if (cmp(x, a[mid]) < 0) {\n          hi = mid;\n        } else {\n          lo = mid + 1;\n        }\n      }\n      return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n    };\n\n\n    /*\n    Push item onto heap, maintaining the heap invariant.\n     */\n\n    heappush = function(array, item, cmp) {\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      array.push(item);\n      return _siftdown(array, 0, array.length - 1, cmp);\n    };\n\n\n    /*\n    Pop the smallest item off the heap, maintaining the heap invariant.\n     */\n\n    heappop = function(array, cmp) {\n      var lastelt, returnitem;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      lastelt = array.pop();\n      if (array.length) {\n        returnitem = array[0];\n        array[0] = lastelt;\n        _siftup(array, 0, cmp);\n      } else {\n        returnitem = lastelt;\n      }\n      return returnitem;\n    };\n\n\n    /*\n    Pop and return the current smallest value, and add the new item.\n    \n    This is more efficient than heappop() followed by heappush(), and can be\n    more appropriate when using a fixed size heap. Note that the value\n    returned may be larger than item! That constrains reasonable use of\n    this routine unless written as part of a conditional replacement:\n        if item > array[0]\n          item = heapreplace(array, item)\n     */\n\n    heapreplace = function(array, item, cmp) {\n      var returnitem;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      returnitem = array[0];\n      array[0] = item;\n      _siftup(array, 0, cmp);\n      return returnitem;\n    };\n\n\n    /*\n    Fast version of a heappush followed by a heappop.\n     */\n\n    heappushpop = function(array, item, cmp) {\n      var _ref;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      if (array.length && cmp(array[0], item) < 0) {\n        _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n        _siftup(array, 0, cmp);\n      }\n      return item;\n    };\n\n\n    /*\n    Transform list into a heap, in-place, in O(array.length) time.\n     */\n\n    heapify = function(array, cmp) {\n      var i, _i, _len, _ref1, _results, _results1;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      _ref1 = (function() {\n        _results1 = [];\n        for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n        return _results1;\n      }).apply(this).reverse();\n      _results = [];\n      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n        i = _ref1[_i];\n        _results.push(_siftup(array, i, cmp));\n      }\n      return _results;\n    };\n\n\n    /*\n    Update the position of the given item in the heap.\n    This function should be called every time the item is being modified.\n     */\n\n    updateItem = function(array, item, cmp) {\n      var pos;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      pos = array.indexOf(item);\n      if (pos === -1) {\n        return;\n      }\n      _siftdown(array, 0, pos, cmp);\n      return _siftup(array, pos, cmp);\n    };\n\n\n    /*\n    Find the n largest elements in a dataset.\n     */\n\n    nlargest = function(array, n, cmp) {\n      var elem, result, _i, _len, _ref;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      result = array.slice(0, n);\n      if (!result.length) {\n        return result;\n      }\n      heapify(result, cmp);\n      _ref = array.slice(n);\n      for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n        elem = _ref[_i];\n        heappushpop(result, elem, cmp);\n      }\n      return result.sort(cmp).reverse();\n    };\n\n\n    /*\n    Find the n smallest elements in a dataset.\n     */\n\n    nsmallest = function(array, n, cmp) {\n      var elem, los, result, _i, _j, _len, _ref, _ref1, _results;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      if (n * 10 <= array.length) {\n        result = array.slice(0, n).sort(cmp);\n        if (!result.length) {\n          return result;\n        }\n        los = result[result.length - 1];\n        _ref = array.slice(n);\n        for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n          elem = _ref[_i];\n          if (cmp(elem, los) < 0) {\n            insort(result, elem, 0, null, cmp);\n            result.pop();\n            los = result[result.length - 1];\n          }\n        }\n        return result;\n      }\n      heapify(array, cmp);\n      _results = [];\n      for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {\n        _results.push(heappop(array, cmp));\n      }\n      return _results;\n    };\n\n    _siftdown = function(array, startpos, pos, cmp) {\n      var newitem, parent, parentpos;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      newitem = array[pos];\n      while (pos > startpos) {\n        parentpos = (pos - 1) >> 1;\n        parent = array[parentpos];\n        if (cmp(newitem, parent) < 0) {\n          array[pos] = parent;\n          pos = parentpos;\n          continue;\n        }\n        break;\n      }\n      return array[pos] = newitem;\n    };\n\n    _siftup = function(array, pos, cmp) {\n      var childpos, endpos, newitem, rightpos, startpos;\n      if (cmp == null) {\n        cmp = defaultCmp;\n      }\n      endpos = array.length;\n      startpos = pos;\n      newitem = array[pos];\n      childpos = 2 * pos + 1;\n      while (childpos < endpos) {\n        rightpos = childpos + 1;\n        if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n          childpos = rightpos;\n        }\n        array[pos] = array[childpos];\n        pos = childpos;\n        childpos = 2 * pos + 1;\n      }\n      array[pos] = newitem;\n      return _siftdown(array, startpos, pos, cmp);\n    };\n\n    Heap = (function() {\n      Heap.push = heappush;\n\n      Heap.pop = heappop;\n\n      Heap.replace = heapreplace;\n\n      Heap.pushpop = heappushpop;\n\n      Heap.heapify = heapify;\n\n      Heap.updateItem = updateItem;\n\n      Heap.nlargest = nlargest;\n\n      Heap.nsmallest = nsmallest;\n\n      function Heap(cmp) {\n        this.cmp = cmp != null ? cmp : defaultCmp;\n        this.nodes = [];\n      }\n\n      Heap.prototype.push = function(x) {\n        return heappush(this.nodes, x, this.cmp);\n      };\n\n      Heap.prototype.pop = function() {\n        return heappop(this.nodes, this.cmp);\n      };\n\n      Heap.prototype.peek = function() {\n        return this.nodes[0];\n      };\n\n      Heap.prototype.contains = function(x) {\n        return this.nodes.indexOf(x) !== -1;\n      };\n\n      Heap.prototype.replace = function(x) {\n        return heapreplace(this.nodes, x, this.cmp);\n      };\n\n      Heap.prototype.pushpop = function(x) {\n        return heappushpop(this.nodes, x, this.cmp);\n      };\n\n      Heap.prototype.heapify = function() {\n        return heapify(this.nodes, this.cmp);\n      };\n\n      Heap.prototype.updateItem = function(x) {\n        return updateItem(this.nodes, x, this.cmp);\n      };\n\n      Heap.prototype.clear = function() {\n        return this.nodes = [];\n      };\n\n      Heap.prototype.empty = function() {\n        return this.nodes.length === 0;\n      };\n\n      Heap.prototype.size = function() {\n        return this.nodes.length;\n      };\n\n      Heap.prototype.clone = function() {\n        var heap;\n        heap = new Heap();\n        heap.nodes = this.nodes.slice(0);\n        return heap;\n      };\n\n      Heap.prototype.toArray = function() {\n        return this.nodes.slice(0);\n      };\n\n      Heap.prototype.insert = Heap.prototype.push;\n\n      Heap.prototype.top = Heap.prototype.peek;\n\n      Heap.prototype.front = Heap.prototype.peek;\n\n      Heap.prototype.has = Heap.prototype.contains;\n\n      Heap.prototype.copy = Heap.prototype.clone;\n\n      return Heap;\n\n    })();\n\n    (function(root, factory) {\n      {\n        return module.exports = factory();\n      }\n    })(this, function() {\n      return Heap;\n    });\n\n  }).call(commonjsGlobal);\n  });\n\n  var heap = heap$1;\n\n  var dijkstraDefaults = defaults$g({\n    root: null,\n    weight: function weight(edge) {\n      return 1;\n    },\n    directed: false\n  });\n  var elesfn$u = {\n    dijkstra: function dijkstra(options) {\n      if (!plainObject(options)) {\n        var args = arguments;\n        options = {\n          root: args[0],\n          weight: args[1],\n          directed: args[2]\n        };\n      }\n\n      var _dijkstraDefaults = dijkstraDefaults(options),\n          root = _dijkstraDefaults.root,\n          weight = _dijkstraDefaults.weight,\n          directed = _dijkstraDefaults.directed;\n\n      var eles = this;\n      var weightFn = weight;\n      var source = string(root) ? this.filter(root)[0] : root[0];\n      var dist = {};\n      var prev = {};\n      var knownDist = {};\n\n      var _this$byGroup = this.byGroup(),\n          nodes = _this$byGroup.nodes,\n          edges = _this$byGroup.edges;\n\n      edges.unmergeBy(function (ele) {\n        return ele.isLoop();\n      });\n\n      var getDist = function getDist(node) {\n        return dist[node.id()];\n      };\n\n      var setDist = function setDist(node, d) {\n        dist[node.id()] = d;\n        Q.updateItem(node);\n      };\n\n      var Q = new heap(function (a, b) {\n        return getDist(a) - getDist(b);\n      });\n\n      for (var i = 0; i < nodes.length; i++) {\n        var node = nodes[i];\n        dist[node.id()] = node.same(source) ? 0 : Infinity;\n        Q.push(node);\n      }\n\n      var distBetween = function distBetween(u, v) {\n        var uvs = (directed ? u.edgesTo(v) : u.edgesWith(v)).intersect(edges);\n        var smallestDistance = Infinity;\n        var smallestEdge;\n\n        for (var _i = 0; _i < uvs.length; _i++) {\n          var edge = uvs[_i];\n\n          var _weight = weightFn(edge);\n\n          if (_weight < smallestDistance || !smallestEdge) {\n            smallestDistance = _weight;\n            smallestEdge = edge;\n          }\n        }\n\n        return {\n          edge: smallestEdge,\n          dist: smallestDistance\n        };\n      };\n\n      while (Q.size() > 0) {\n        var u = Q.pop();\n        var smalletsDist = getDist(u);\n        var uid = u.id();\n        knownDist[uid] = smalletsDist;\n\n        if (smalletsDist === Infinity) {\n          continue;\n        }\n\n        var neighbors = u.neighborhood().intersect(nodes);\n\n        for (var _i2 = 0; _i2 < neighbors.length; _i2++) {\n          var v = neighbors[_i2];\n          var vid = v.id();\n          var vDist = distBetween(u, v);\n          var alt = smalletsDist + vDist.dist;\n\n          if (alt < getDist(v)) {\n            setDist(v, alt);\n            prev[vid] = {\n              node: u,\n              edge: vDist.edge\n            };\n          }\n        } // for\n\n      } // while\n\n\n      return {\n        distanceTo: function distanceTo(node) {\n          var target = string(node) ? nodes.filter(node)[0] : node[0];\n          return knownDist[target.id()];\n        },\n        pathTo: function pathTo(node) {\n          var target = string(node) ? nodes.filter(node)[0] : node[0];\n          var S = [];\n          var u = target;\n          var uid = u.id();\n\n          if (target.length > 0) {\n            S.unshift(target);\n\n            while (prev[uid]) {\n              var p = prev[uid];\n              S.unshift(p.edge);\n              S.unshift(p.node);\n              u = p.node;\n              uid = u.id();\n            }\n          }\n\n          return eles.spawn(S);\n        }\n      };\n    }\n  };\n\n  var elesfn$t = {\n    // kruskal's algorithm (finds min spanning tree, assuming undirected graph)\n    // implemented from pseudocode from wikipedia\n    kruskal: function kruskal(weightFn) {\n      weightFn = weightFn || function (edge) {\n        return 1;\n      };\n\n      var _this$byGroup = this.byGroup(),\n          nodes = _this$byGroup.nodes,\n          edges = _this$byGroup.edges;\n\n      var numNodes = nodes.length;\n      var forest = new Array(numNodes);\n      var A = nodes; // assumes byGroup() creates new collections that can be safely mutated\n\n      var findSetIndex = function findSetIndex(ele) {\n        for (var i = 0; i < forest.length; i++) {\n          var eles = forest[i];\n\n          if (eles.has(ele)) {\n            return i;\n          }\n        }\n      }; // start with one forest per node\n\n\n      for (var i = 0; i < numNodes; i++) {\n        forest[i] = this.spawn(nodes[i]);\n      }\n\n      var S = edges.sort(function (a, b) {\n        return weightFn(a) - weightFn(b);\n      });\n\n      for (var _i = 0; _i < S.length; _i++) {\n        var edge = S[_i];\n        var u = edge.source()[0];\n        var v = edge.target()[0];\n        var setUIndex = findSetIndex(u);\n        var setVIndex = findSetIndex(v);\n        var setU = forest[setUIndex];\n        var setV = forest[setVIndex];\n\n        if (setUIndex !== setVIndex) {\n          A.merge(edge); // combine forests for u and v\n\n          setU.merge(setV);\n          forest.splice(setVIndex, 1);\n        }\n      }\n\n      return A;\n    }\n  };\n\n  var aStarDefaults = defaults$g({\n    root: null,\n    goal: null,\n    weight: function weight(edge) {\n      return 1;\n    },\n    heuristic: function heuristic(edge) {\n      return 0;\n    },\n    directed: false\n  });\n  var elesfn$s = {\n    // Implemented from pseudocode from wikipedia\n    aStar: function aStar(options) {\n      var cy = this.cy();\n\n      var _aStarDefaults = aStarDefaults(options),\n          root = _aStarDefaults.root,\n          goal = _aStarDefaults.goal,\n          heuristic = _aStarDefaults.heuristic,\n          directed = _aStarDefaults.directed,\n          weight = _aStarDefaults.weight;\n\n      root = cy.collection(root)[0];\n      goal = cy.collection(goal)[0];\n      var sid = root.id();\n      var tid = goal.id();\n      var gScore = {};\n      var fScore = {};\n      var closedSetIds = {};\n      var openSet = new heap(function (a, b) {\n        return fScore[a.id()] - fScore[b.id()];\n      });\n      var openSetIds = new Set$1();\n      var cameFrom = {};\n      var cameFromEdge = {};\n\n      var addToOpenSet = function addToOpenSet(ele, id) {\n        openSet.push(ele);\n        openSetIds.add(id);\n      };\n\n      var cMin, cMinId;\n\n      var popFromOpenSet = function popFromOpenSet() {\n        cMin = openSet.pop();\n        cMinId = cMin.id();\n        openSetIds[\"delete\"](cMinId);\n      };\n\n      var isInOpenSet = function isInOpenSet(id) {\n        return openSetIds.has(id);\n      };\n\n      addToOpenSet(root, sid);\n      gScore[sid] = 0;\n      fScore[sid] = heuristic(root); // Counter\n\n      var steps = 0; // Main loop\n\n      while (openSet.size() > 0) {\n        popFromOpenSet();\n        steps++; // If we've found our goal, then we are done\n\n        if (cMinId === tid) {\n          var path = [];\n          var pathNode = goal;\n          var pathNodeId = tid;\n          var pathEdge = cameFromEdge[pathNodeId];\n\n          for (;;) {\n            path.unshift(pathNode);\n\n            if (pathEdge != null) {\n              path.unshift(pathEdge);\n            }\n\n            pathNode = cameFrom[pathNodeId];\n\n            if (pathNode == null) {\n              break;\n            }\n\n            pathNodeId = pathNode.id();\n            pathEdge = cameFromEdge[pathNodeId];\n          }\n\n          return {\n            found: true,\n            distance: gScore[cMinId],\n            path: this.spawn(path),\n            steps: steps\n          };\n        } // Add cMin to processed nodes\n\n\n        closedSetIds[cMinId] = true; // Update scores for neighbors of cMin\n        // Take into account if graph is directed or not\n\n        var vwEdges = cMin._private.edges;\n\n        for (var i = 0; i < vwEdges.length; i++) {\n          var e = vwEdges[i]; // edge must be in set of calling eles\n\n          if (!this.hasElementWithId(e.id())) {\n            continue;\n          } // cMin must be the source of edge if directed\n\n\n          if (directed && e.data('source') !== cMinId) {\n            continue;\n          }\n\n          var wSrc = e.source();\n          var wTgt = e.target();\n          var w = wSrc.id() !== cMinId ? wSrc : wTgt;\n          var wid = w.id(); // node must be in set of calling eles\n\n          if (!this.hasElementWithId(wid)) {\n            continue;\n          } // if node is in closedSet, ignore it\n\n\n          if (closedSetIds[wid]) {\n            continue;\n          } // New tentative score for node w\n\n\n          var tempScore = gScore[cMinId] + weight(e); // Update gScore for node w if:\n          //   w not present in openSet\n          // OR\n          //   tentative gScore is less than previous value\n          // w not in openSet\n\n          if (!isInOpenSet(wid)) {\n            gScore[wid] = tempScore;\n            fScore[wid] = tempScore + heuristic(w);\n            addToOpenSet(w, wid);\n            cameFrom[wid] = cMin;\n            cameFromEdge[wid] = e;\n            continue;\n          } // w already in openSet, but with greater gScore\n\n\n          if (tempScore < gScore[wid]) {\n            gScore[wid] = tempScore;\n            fScore[wid] = tempScore + heuristic(w);\n            cameFrom[wid] = cMin;\n            cameFromEdge[wid] = e;\n          }\n        } // End of neighbors update\n\n      } // End of main loop\n      // If we've reached here, then we've not reached our goal\n\n\n      return {\n        found: false,\n        distance: undefined,\n        path: undefined,\n        steps: steps\n      };\n    }\n  }; // elesfn\n\n  var floydWarshallDefaults = defaults$g({\n    weight: function weight(edge) {\n      return 1;\n    },\n    directed: false\n  });\n  var elesfn$r = {\n    // Implemented from pseudocode from wikipedia\n    floydWarshall: function floydWarshall(options) {\n      var cy = this.cy();\n\n      var _floydWarshallDefault = floydWarshallDefaults(options),\n          weight = _floydWarshallDefault.weight,\n          directed = _floydWarshallDefault.directed;\n\n      var weightFn = weight;\n\n      var _this$byGroup = this.byGroup(),\n          nodes = _this$byGroup.nodes,\n          edges = _this$byGroup.edges;\n\n      var N = nodes.length;\n      var Nsq = N * N;\n\n      var indexOf = function indexOf(node) {\n        return nodes.indexOf(node);\n      };\n\n      var atIndex = function atIndex(i) {\n        return nodes[i];\n      }; // Initialize distance matrix\n\n\n      var dist = new Array(Nsq);\n\n      for (var n = 0; n < Nsq; n++) {\n        var j = n % N;\n        var i = (n - j) / N;\n\n        if (i === j) {\n          dist[n] = 0;\n        } else {\n          dist[n] = Infinity;\n        }\n      } // Initialize matrix used for path reconstruction\n      // Initialize distance matrix\n\n\n      var next = new Array(Nsq);\n      var edgeNext = new Array(Nsq); // Process edges\n\n      for (var _i = 0; _i < edges.length; _i++) {\n        var edge = edges[_i];\n        var src = edge.source()[0];\n        var tgt = edge.target()[0];\n\n        if (src === tgt) {\n          continue;\n        } // exclude loops\n\n\n        var s = indexOf(src);\n        var t = indexOf(tgt);\n        var st = s * N + t; // source to target index\n\n        var _weight = weightFn(edge); // Check if already process another edge between same 2 nodes\n\n\n        if (dist[st] > _weight) {\n          dist[st] = _weight;\n          next[st] = t;\n          edgeNext[st] = edge;\n        } // If undirected graph, process 'reversed' edge\n\n\n        if (!directed) {\n          var ts = t * N + s; // target to source index\n\n          if (!directed && dist[ts] > _weight) {\n            dist[ts] = _weight;\n            next[ts] = s;\n            edgeNext[ts] = edge;\n          }\n        }\n      } // Main loop\n\n\n      for (var k = 0; k < N; k++) {\n        for (var _i2 = 0; _i2 < N; _i2++) {\n          var ik = _i2 * N + k;\n\n          for (var _j = 0; _j < N; _j++) {\n            var ij = _i2 * N + _j;\n            var kj = k * N + _j;\n\n            if (dist[ik] + dist[kj] < dist[ij]) {\n              dist[ij] = dist[ik] + dist[kj];\n              next[ij] = next[ik];\n            }\n          }\n        }\n      }\n\n      var getArgEle = function getArgEle(ele) {\n        return (string(ele) ? cy.filter(ele) : ele)[0];\n      };\n\n      var indexOfArgEle = function indexOfArgEle(ele) {\n        return indexOf(getArgEle(ele));\n      };\n\n      var res = {\n        distance: function distance(from, to) {\n          var i = indexOfArgEle(from);\n          var j = indexOfArgEle(to);\n          return dist[i * N + j];\n        },\n        path: function path(from, to) {\n          var i = indexOfArgEle(from);\n          var j = indexOfArgEle(to);\n          var fromNode = atIndex(i);\n\n          if (i === j) {\n            return fromNode.collection();\n          }\n\n          if (next[i * N + j] == null) {\n            return cy.collection();\n          }\n\n          var path = cy.collection();\n          var prev = i;\n          var edge;\n          path.merge(fromNode);\n\n          while (i !== j) {\n            prev = i;\n            i = next[i * N + j];\n            edge = edgeNext[prev * N + i];\n            path.merge(edge);\n            path.merge(atIndex(i));\n          }\n\n          return path;\n        }\n      };\n      return res;\n    } // floydWarshall\n\n  }; // elesfn\n\n  var bellmanFordDefaults = defaults$g({\n    weight: function weight(edge) {\n      return 1;\n    },\n    directed: false,\n    root: null\n  });\n  var elesfn$q = {\n    // Implemented from pseudocode from wikipedia\n    bellmanFord: function bellmanFord(options) {\n      var _this = this;\n\n      var _bellmanFordDefaults = bellmanFordDefaults(options),\n          weight = _bellmanFordDefaults.weight,\n          directed = _bellmanFordDefaults.directed,\n          root = _bellmanFordDefaults.root;\n\n      var weightFn = weight;\n      var eles = this;\n      var cy = this.cy();\n\n      var _this$byGroup = this.byGroup(),\n          edges = _this$byGroup.edges,\n          nodes = _this$byGroup.nodes;\n\n      var numNodes = nodes.length;\n      var infoMap = new Map$2();\n      var hasNegativeWeightCycle = false;\n      var negativeWeightCycles = [];\n      root = cy.collection(root)[0]; // in case selector passed\n\n      edges.unmergeBy(function (edge) {\n        return edge.isLoop();\n      });\n      var numEdges = edges.length;\n\n      var getInfo = function getInfo(node) {\n        var obj = infoMap.get(node.id());\n\n        if (!obj) {\n          obj = {};\n          infoMap.set(node.id(), obj);\n        }\n\n        return obj;\n      };\n\n      var getNodeFromTo = function getNodeFromTo(to) {\n        return (string(to) ? cy.$(to) : to)[0];\n      };\n\n      var distanceTo = function distanceTo(to) {\n        return getInfo(getNodeFromTo(to)).dist;\n      };\n\n      var pathTo = function pathTo(to) {\n        var thisStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;\n        var end = getNodeFromTo(to);\n        var path = [];\n        var node = end;\n\n        for (;;) {\n          if (node == null) {\n            return _this.spawn();\n          }\n\n          var _getInfo = getInfo(node),\n              edge = _getInfo.edge,\n              pred = _getInfo.pred;\n\n          path.unshift(node[0]);\n\n          if (node.same(thisStart) && path.length > 0) {\n            break;\n          }\n\n          if (edge != null) {\n            path.unshift(edge);\n          }\n\n          node = pred;\n        }\n\n        return eles.spawn(path);\n      }; // Initializations { dist, pred, edge }\n\n\n      for (var i = 0; i < numNodes; i++) {\n        var node = nodes[i];\n        var info = getInfo(node);\n\n        if (node.same(root)) {\n          info.dist = 0;\n        } else {\n          info.dist = Infinity;\n        }\n\n        info.pred = null;\n        info.edge = null;\n      } // Edges relaxation\n\n\n      var replacedEdge = false;\n\n      var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {\n        var dist = info1.dist + weight;\n\n        if (dist < info2.dist && !edge.same(info1.edge)) {\n          info2.dist = dist;\n          info2.pred = node1;\n          info2.edge = edge;\n          replacedEdge = true;\n        }\n      };\n\n      for (var _i = 1; _i < numNodes; _i++) {\n        replacedEdge = false;\n\n        for (var e = 0; e < numEdges; e++) {\n          var edge = edges[e];\n          var src = edge.source();\n          var tgt = edge.target();\n\n          var _weight = weightFn(edge);\n\n          var srcInfo = getInfo(src);\n          var tgtInfo = getInfo(tgt);\n          checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight); // If undirected graph, we need to take into account the 'reverse' edge\n\n          if (!directed) {\n            checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);\n          }\n        }\n\n        if (!replacedEdge) {\n          break;\n        }\n      }\n\n      if (replacedEdge) {\n        // Check for negative weight cycles\n        var negativeWeightCycleIds = [];\n\n        for (var _e = 0; _e < numEdges; _e++) {\n          var _edge = edges[_e];\n\n          var _src = _edge.source();\n\n          var _tgt = _edge.target();\n\n          var _weight2 = weightFn(_edge);\n\n          var srcDist = getInfo(_src).dist;\n          var tgtDist = getInfo(_tgt).dist;\n\n          if (srcDist + _weight2 < tgtDist || !directed && tgtDist + _weight2 < srcDist) {\n            if (!hasNegativeWeightCycle) {\n              warn('Graph contains a negative weight cycle for Bellman-Ford');\n              hasNegativeWeightCycle = true;\n            }\n\n            if (options.findNegativeWeightCycles !== false) {\n              var negativeNodes = [];\n\n              if (srcDist + _weight2 < tgtDist) {\n                negativeNodes.push(_src);\n              }\n\n              if (!directed && tgtDist + _weight2 < srcDist) {\n                negativeNodes.push(_tgt);\n              }\n\n              var numNegativeNodes = negativeNodes.length;\n\n              for (var n = 0; n < numNegativeNodes; n++) {\n                var start = negativeNodes[n];\n                var cycle = [start];\n                cycle.push(getInfo(start).edge);\n                var _node = getInfo(start).pred;\n\n                while (cycle.indexOf(_node) === -1) {\n                  cycle.push(_node);\n                  cycle.push(getInfo(_node).edge);\n                  _node = getInfo(_node).pred;\n                }\n\n                cycle = cycle.slice(cycle.indexOf(_node));\n                var smallestId = cycle[0].id();\n                var smallestIndex = 0;\n\n                for (var c = 2; c < cycle.length; c += 2) {\n                  if (cycle[c].id() < smallestId) {\n                    smallestId = cycle[c].id();\n                    smallestIndex = c;\n                  }\n                }\n\n                cycle = cycle.slice(smallestIndex).concat(cycle.slice(0, smallestIndex));\n                cycle.push(cycle[0]);\n                var cycleId = cycle.map(function (el) {\n                  return el.id();\n                }).join(\",\");\n\n                if (negativeWeightCycleIds.indexOf(cycleId) === -1) {\n                  negativeWeightCycles.push(eles.spawn(cycle));\n                  negativeWeightCycleIds.push(cycleId);\n                }\n              }\n            } else {\n              break;\n            }\n          }\n        }\n      }\n\n      return {\n        distanceTo: distanceTo,\n        pathTo: pathTo,\n        hasNegativeWeightCycle: hasNegativeWeightCycle,\n        negativeWeightCycles: negativeWeightCycles\n      };\n    } // bellmanFord\n\n  }; // elesfn\n\n  var sqrt2 = Math.sqrt(2); // Function which colapses 2 (meta) nodes into one\n  // Updates the remaining edge lists\n  // Receives as a paramater the edge which causes the collapse\n\n  var collapse = function collapse(edgeIndex, nodeMap, remainingEdges) {\n    if (remainingEdges.length === 0) {\n      error(\"Karger-Stein must be run on a connected (sub)graph\");\n    }\n\n    var edgeInfo = remainingEdges[edgeIndex];\n    var sourceIn = edgeInfo[1];\n    var targetIn = edgeInfo[2];\n    var partition1 = nodeMap[sourceIn];\n    var partition2 = nodeMap[targetIn];\n    var newEdges = remainingEdges; // re-use array\n    // Delete all edges between partition1 and partition2\n\n    for (var i = newEdges.length - 1; i >= 0; i--) {\n      var edge = newEdges[i];\n      var src = edge[1];\n      var tgt = edge[2];\n\n      if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {\n        newEdges.splice(i, 1);\n      }\n    } // All edges pointing to partition2 should now point to partition1\n\n\n    for (var _i = 0; _i < newEdges.length; _i++) {\n      var _edge = newEdges[_i];\n\n      if (_edge[1] === partition2) {\n        // Check source\n        newEdges[_i] = _edge.slice(); // copy\n\n        newEdges[_i][1] = partition1;\n      } else if (_edge[2] === partition2) {\n        // Check target\n        newEdges[_i] = _edge.slice(); // copy\n\n        newEdges[_i][2] = partition1;\n      }\n    } // Move all nodes from partition2 to partition1\n\n\n    for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {\n      if (nodeMap[_i2] === partition2) {\n        nodeMap[_i2] = partition1;\n      }\n    }\n\n    return newEdges;\n  }; // Contracts a graph until we reach a certain number of meta nodes\n\n\n  var contractUntil = function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {\n    while (size > sizeLimit) {\n      // Choose an edge randomly\n      var edgeIndex = Math.floor(Math.random() * remainingEdges.length); // Collapse graph based on edge\n\n      remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);\n      size--;\n    }\n\n    return remainingEdges;\n  };\n\n  var elesfn$p = {\n    // Computes the minimum cut of an undirected graph\n    // Returns the correct answer with high probability\n    kargerStein: function kargerStein() {\n      var _this = this;\n\n      var _this$byGroup = this.byGroup(),\n          nodes = _this$byGroup.nodes,\n          edges = _this$byGroup.edges;\n\n      edges.unmergeBy(function (edge) {\n        return edge.isLoop();\n      });\n      var numNodes = nodes.length;\n      var numEdges = edges.length;\n      var numIter = Math.ceil(Math.pow(Math.log(numNodes) / Math.LN2, 2));\n      var stopSize = Math.floor(numNodes / sqrt2);\n\n      if (numNodes < 2) {\n        error('At least 2 nodes are required for Karger-Stein algorithm');\n        return undefined;\n      } // Now store edge destination as indexes\n      // Format for each edge (edge index, source node index, target node index)\n\n\n      var edgeIndexes = [];\n\n      for (var i = 0; i < numEdges; i++) {\n        var e = edges[i];\n        edgeIndexes.push([i, nodes.indexOf(e.source()), nodes.indexOf(e.target())]);\n      } // We will store the best cut found here\n\n\n      var minCutSize = Infinity;\n      var minCutEdgeIndexes = [];\n      var minCutNodeMap = new Array(numNodes); // Initial meta node partition\n\n      var metaNodeMap = new Array(numNodes);\n      var metaNodeMap2 = new Array(numNodes);\n\n      var copyNodesMap = function copyNodesMap(from, to) {\n        for (var _i3 = 0; _i3 < numNodes; _i3++) {\n          to[_i3] = from[_i3];\n        }\n      }; // Main loop\n\n\n      for (var iter = 0; iter <= numIter; iter++) {\n        // Reset meta node partition\n        for (var _i4 = 0; _i4 < numNodes; _i4++) {\n          metaNodeMap[_i4] = _i4;\n        } // Contract until stop point (stopSize nodes)\n\n\n        var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);\n        var edgesState2 = edgesState.slice(); // copy\n        // Create a copy of the colapsed nodes state\n\n        copyNodesMap(metaNodeMap, metaNodeMap2); // Run 2 iterations starting in the stop state\n\n        var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);\n        var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2); // Is any of the 2 results the best cut so far?\n\n        if (res1.length <= res2.length && res1.length < minCutSize) {\n          minCutSize = res1.length;\n          minCutEdgeIndexes = res1;\n          copyNodesMap(metaNodeMap, minCutNodeMap);\n        } else if (res2.length <= res1.length && res2.length < minCutSize) {\n          minCutSize = res2.length;\n          minCutEdgeIndexes = res2;\n          copyNodesMap(metaNodeMap2, minCutNodeMap);\n        }\n      } // end of main loop\n      // Construct result\n\n\n      var cut = this.spawn(minCutEdgeIndexes.map(function (e) {\n        return edges[e[0]];\n      }));\n      var partition1 = this.spawn();\n      var partition2 = this.spawn(); // traverse metaNodeMap for best cut\n\n      var witnessNodePartition = minCutNodeMap[0];\n\n      for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {\n        var partitionId = minCutNodeMap[_i5];\n        var node = nodes[_i5];\n\n        if (partitionId === witnessNodePartition) {\n          partition1.merge(node);\n        } else {\n          partition2.merge(node);\n        }\n      } // construct components corresponding to each disjoint subset of nodes\n\n\n      var constructComponent = function constructComponent(subset) {\n        var component = _this.spawn();\n\n        subset.forEach(function (node) {\n          component.merge(node);\n          node.connectedEdges().forEach(function (edge) {\n            // ensure edge is within calling collection and edge is not in cut\n            if (_this.contains(edge) && !cut.contains(edge)) {\n              component.merge(edge);\n            }\n          });\n        });\n        return component;\n      };\n\n      var components = [constructComponent(partition1), constructComponent(partition2)];\n      var ret = {\n        cut: cut,\n        components: components,\n        // n.b. partitions are included to be compatible with the old api spec\n        // (could be removed in a future major version)\n        partition1: partition1,\n        partition2: partition2\n      };\n      return ret;\n    }\n  }; // elesfn\n\n  var copyPosition = function copyPosition(p) {\n    return {\n      x: p.x,\n      y: p.y\n    };\n  };\n  var modelToRenderedPosition = function modelToRenderedPosition(p, zoom, pan) {\n    return {\n      x: p.x * zoom + pan.x,\n      y: p.y * zoom + pan.y\n    };\n  };\n  var renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {\n    return {\n      x: (p.x - pan.x) / zoom,\n      y: (p.y - pan.y) / zoom\n    };\n  };\n  var array2point = function array2point(arr) {\n    return {\n      x: arr[0],\n      y: arr[1]\n    };\n  };\n  var min = function min(arr) {\n    var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n    var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n    var min = Infinity;\n\n    for (var i = begin; i < end; i++) {\n      var val = arr[i];\n\n      if (isFinite(val)) {\n        min = Math.min(val, min);\n      }\n    }\n\n    return min;\n  };\n  var max = function max(arr) {\n    var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n    var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n    var max = -Infinity;\n\n    for (var i = begin; i < end; i++) {\n      var val = arr[i];\n\n      if (isFinite(val)) {\n        max = Math.max(val, max);\n      }\n    }\n\n    return max;\n  };\n  var mean = function mean(arr) {\n    var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n    var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n    var total = 0;\n    var n = 0;\n\n    for (var i = begin; i < end; i++) {\n      var val = arr[i];\n\n      if (isFinite(val)) {\n        total += val;\n        n++;\n      }\n    }\n\n    return total / n;\n  };\n  var median = function median(arr) {\n    var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n    var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;\n    var copy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n    var sort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    var includeHoles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n\n    if (copy) {\n      arr = arr.slice(begin, end);\n    } else {\n      if (end < arr.length) {\n        arr.splice(end, arr.length - end);\n      }\n\n      if (begin > 0) {\n        arr.splice(0, begin);\n      }\n    } // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start\n\n\n    var off = 0; // offset from non-finite values\n\n    for (var i = arr.length - 1; i >= 0; i--) {\n      var v = arr[i];\n\n      if (includeHoles) {\n        if (!isFinite(v)) {\n          arr[i] = -Infinity;\n          off++;\n        }\n      } else {\n        // just remove it if we don't want to consider holes\n        arr.splice(i, 1);\n      }\n    }\n\n    if (sort) {\n      arr.sort(function (a, b) {\n        return a - b;\n      }); // requires copy = true if you don't want to change the orig\n    }\n\n    var len = arr.length;\n    var mid = Math.floor(len / 2);\n\n    if (len % 2 !== 0) {\n      return arr[mid + 1 + off];\n    } else {\n      return (arr[mid - 1 + off] + arr[mid + off]) / 2;\n    }\n  };\n  var deg2rad = function deg2rad(deg) {\n    return Math.PI * deg / 180;\n  };\n  var getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {\n    return Math.atan2(dispY, dispX) - Math.PI / 2;\n  };\n  var log2 = Math.log2 || function (n) {\n    return Math.log(n) / Math.log(2);\n  };\n  var signum = function signum(x) {\n    if (x > 0) {\n      return 1;\n    } else if (x < 0) {\n      return -1;\n    } else {\n      return 0;\n    }\n  };\n  var dist = function dist(p1, p2) {\n    return Math.sqrt(sqdist(p1, p2));\n  };\n  var sqdist = function sqdist(p1, p2) {\n    var dx = p2.x - p1.x;\n    var dy = p2.y - p1.y;\n    return dx * dx + dy * dy;\n  };\n  var inPlaceSumNormalize = function inPlaceSumNormalize(v) {\n    var length = v.length; // First, get sum of all elements\n\n    var total = 0;\n\n    for (var i = 0; i < length; i++) {\n      total += v[i];\n    } // Now, divide each by the sum of all elements\n\n\n    for (var _i = 0; _i < length; _i++) {\n      v[_i] = v[_i] / total;\n    }\n\n    return v;\n  };\n\n  var qbezierAt = function qbezierAt(p0, p1, p2, t) {\n    return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;\n  };\n  var qbezierPtAt = function qbezierPtAt(p0, p1, p2, t) {\n    return {\n      x: qbezierAt(p0.x, p1.x, p2.x, t),\n      y: qbezierAt(p0.y, p1.y, p2.y, t)\n    };\n  };\n  var lineAt = function lineAt(p0, p1, t, d) {\n    var vec = {\n      x: p1.x - p0.x,\n      y: p1.y - p0.y\n    };\n    var vecDist = dist(p0, p1);\n    var normVec = {\n      x: vec.x / vecDist,\n      y: vec.y / vecDist\n    };\n    t = t == null ? 0 : t;\n    d = d != null ? d : t * vecDist;\n    return {\n      x: p0.x + normVec.x * d,\n      y: p0.y + normVec.y * d\n    };\n  };\n  var bound = function bound(min, val, max) {\n    return Math.max(min, Math.min(max, val));\n  }; // makes a full bb (x1, y1, x2, y2, w, h) from implicit params\n\n  var makeBoundingBox = function makeBoundingBox(bb) {\n    if (bb == null) {\n      return {\n        x1: Infinity,\n        y1: Infinity,\n        x2: -Infinity,\n        y2: -Infinity,\n        w: 0,\n        h: 0\n      };\n    } else if (bb.x1 != null && bb.y1 != null) {\n      if (bb.x2 != null && bb.y2 != null && bb.x2 >= bb.x1 && bb.y2 >= bb.y1) {\n        return {\n          x1: bb.x1,\n          y1: bb.y1,\n          x2: bb.x2,\n          y2: bb.y2,\n          w: bb.x2 - bb.x1,\n          h: bb.y2 - bb.y1\n        };\n      } else if (bb.w != null && bb.h != null && bb.w >= 0 && bb.h >= 0) {\n        return {\n          x1: bb.x1,\n          y1: bb.y1,\n          x2: bb.x1 + bb.w,\n          y2: bb.y1 + bb.h,\n          w: bb.w,\n          h: bb.h\n        };\n      }\n    }\n  };\n  var copyBoundingBox = function copyBoundingBox(bb) {\n    return {\n      x1: bb.x1,\n      x2: bb.x2,\n      w: bb.w,\n      y1: bb.y1,\n      y2: bb.y2,\n      h: bb.h\n    };\n  };\n  var clearBoundingBox = function clearBoundingBox(bb) {\n    bb.x1 = Infinity;\n    bb.y1 = Infinity;\n    bb.x2 = -Infinity;\n    bb.y2 = -Infinity;\n    bb.w = 0;\n    bb.h = 0;\n  };\n  var updateBoundingBox = function updateBoundingBox(bb1, bb2) {\n    // update bb1 with bb2 bounds\n    bb1.x1 = Math.min(bb1.x1, bb2.x1);\n    bb1.x2 = Math.max(bb1.x2, bb2.x2);\n    bb1.w = bb1.x2 - bb1.x1;\n    bb1.y1 = Math.min(bb1.y1, bb2.y1);\n    bb1.y2 = Math.max(bb1.y2, bb2.y2);\n    bb1.h = bb1.y2 - bb1.y1;\n  };\n  var expandBoundingBoxByPoint = function expandBoundingBoxByPoint(bb, x, y) {\n    bb.x1 = Math.min(bb.x1, x);\n    bb.x2 = Math.max(bb.x2, x);\n    bb.w = bb.x2 - bb.x1;\n    bb.y1 = Math.min(bb.y1, y);\n    bb.y2 = Math.max(bb.y2, y);\n    bb.h = bb.y2 - bb.y1;\n  };\n  var expandBoundingBox = function expandBoundingBox(bb) {\n    var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n    bb.x1 -= padding;\n    bb.x2 += padding;\n    bb.y1 -= padding;\n    bb.y2 += padding;\n    bb.w = bb.x2 - bb.x1;\n    bb.h = bb.y2 - bb.y1;\n    return bb;\n  };\n  var expandBoundingBoxSides = function expandBoundingBoxSides(bb) {\n    var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];\n    var top, right, bottom, left;\n\n    if (padding.length === 1) {\n      top = right = bottom = left = padding[0];\n    } else if (padding.length === 2) {\n      top = bottom = padding[0];\n      left = right = padding[1];\n    } else if (padding.length === 4) {\n      var _padding = _slicedToArray(padding, 4);\n\n      top = _padding[0];\n      right = _padding[1];\n      bottom = _padding[2];\n      left = _padding[3];\n    }\n\n    bb.x1 -= left;\n    bb.x2 += right;\n    bb.y1 -= top;\n    bb.y2 += bottom;\n    bb.w = bb.x2 - bb.x1;\n    bb.h = bb.y2 - bb.y1;\n    return bb;\n  };\n\n  var assignBoundingBox = function assignBoundingBox(bb1, bb2) {\n    bb1.x1 = bb2.x1;\n    bb1.y1 = bb2.y1;\n    bb1.x2 = bb2.x2;\n    bb1.y2 = bb2.y2;\n    bb1.w = bb1.x2 - bb1.x1;\n    bb1.h = bb1.y2 - bb1.y1;\n  };\n  var boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {\n    // case: one bb to right of other\n    if (bb1.x1 > bb2.x2) {\n      return false;\n    }\n\n    if (bb2.x1 > bb1.x2) {\n      return false;\n    } // case: one bb to left of other\n\n\n    if (bb1.x2 < bb2.x1) {\n      return false;\n    }\n\n    if (bb2.x2 < bb1.x1) {\n      return false;\n    } // case: one bb above other\n\n\n    if (bb1.y2 < bb2.y1) {\n      return false;\n    }\n\n    if (bb2.y2 < bb1.y1) {\n      return false;\n    } // case: one bb below other\n\n\n    if (bb1.y1 > bb2.y2) {\n      return false;\n    }\n\n    if (bb2.y1 > bb1.y2) {\n      return false;\n    } // otherwise, must have some overlap\n\n\n    return true;\n  };\n  var inBoundingBox = function inBoundingBox(bb, x, y) {\n    return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;\n  };\n  var pointInBoundingBox = function pointInBoundingBox(bb, pt) {\n    return inBoundingBox(bb, pt.x, pt.y);\n  };\n  var boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {\n    return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);\n  };\n  var roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {\n    var cornerRadius = getRoundRectangleRadius(width, height);\n    var halfWidth = width / 2;\n    var halfHeight = height / 2; // Check intersections with straight line segments\n\n    var straightLineIntersections; // Top segment, left to right\n\n    {\n      var topStartX = nodeX - halfWidth + cornerRadius - padding;\n      var topStartY = nodeY - halfHeight - padding;\n      var topEndX = nodeX + halfWidth - cornerRadius + padding;\n      var topEndY = topStartY;\n      straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);\n\n      if (straightLineIntersections.length > 0) {\n        return straightLineIntersections;\n      }\n    } // Right segment, top to bottom\n\n    {\n      var rightStartX = nodeX + halfWidth + padding;\n      var rightStartY = nodeY - halfHeight + cornerRadius - padding;\n      var rightEndX = rightStartX;\n      var rightEndY = nodeY + halfHeight - cornerRadius + padding;\n      straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, rightStartX, rightStartY, rightEndX, rightEndY, false);\n\n      if (straightLineIntersections.length > 0) {\n        return straightLineIntersections;\n      }\n    } // Bottom segment, left to right\n\n    {\n      var bottomStartX = nodeX - halfWidth + cornerRadius - padding;\n      var bottomStartY = nodeY + halfHeight + padding;\n      var bottomEndX = nodeX + halfWidth - cornerRadius + padding;\n      var bottomEndY = bottomStartY;\n      straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, bottomStartX, bottomStartY, bottomEndX, bottomEndY, false);\n\n      if (straightLineIntersections.length > 0) {\n        return straightLineIntersections;\n      }\n    } // Left segment, top to bottom\n\n    {\n      var leftStartX = nodeX - halfWidth - padding;\n      var leftStartY = nodeY - halfHeight + cornerRadius - padding;\n      var leftEndX = leftStartX;\n      var leftEndY = nodeY + halfHeight - cornerRadius + padding;\n      straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, leftStartX, leftStartY, leftEndX, leftEndY, false);\n\n      if (straightLineIntersections.length > 0) {\n        return straightLineIntersections;\n      }\n    } // Check intersections with arc segments\n\n    var arcIntersections; // Top Left\n\n    {\n      var topLeftCenterX = nodeX - halfWidth + cornerRadius;\n      var topLeftCenterY = nodeY - halfHeight + cornerRadius;\n      arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding); // Ensure the intersection is on the desired quarter of the circle\n\n      if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {\n        return [arcIntersections[0], arcIntersections[1]];\n      }\n    } // Top Right\n\n    {\n      var topRightCenterX = nodeX + halfWidth - cornerRadius;\n      var topRightCenterY = nodeY - halfHeight + cornerRadius;\n      arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding); // Ensure the intersection is on the desired quarter of the circle\n\n      if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {\n        return [arcIntersections[0], arcIntersections[1]];\n      }\n    } // Bottom Right\n\n    {\n      var bottomRightCenterX = nodeX + halfWidth - cornerRadius;\n      var bottomRightCenterY = nodeY + halfHeight - cornerRadius;\n      arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding); // Ensure the intersection is on the desired quarter of the circle\n\n      if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {\n        return [arcIntersections[0], arcIntersections[1]];\n      }\n    } // Bottom Left\n\n    {\n      var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;\n      var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;\n      arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding); // Ensure the intersection is on the desired quarter of the circle\n\n      if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {\n        return [arcIntersections[0], arcIntersections[1]];\n      }\n    }\n    return []; // if nothing\n  };\n  var inLineVicinity = function inLineVicinity(x, y, lx1, ly1, lx2, ly2, tolerance) {\n    var t = tolerance;\n    var x1 = Math.min(lx1, lx2);\n    var x2 = Math.max(lx1, lx2);\n    var y1 = Math.min(ly1, ly2);\n    var y2 = Math.max(ly1, ly2);\n    return x1 - t <= x && x <= x2 + t && y1 - t <= y && y <= y2 + t;\n  };\n  var inBezierVicinity = function inBezierVicinity(x, y, x1, y1, x2, y2, x3, y3, tolerance) {\n    var bb = {\n      x1: Math.min(x1, x3, x2) - tolerance,\n      x2: Math.max(x1, x3, x2) + tolerance,\n      y1: Math.min(y1, y3, y2) - tolerance,\n      y2: Math.max(y1, y3, y2) + tolerance\n    }; // if outside the rough bounding box for the bezier, then it can't be a hit\n\n    if (x < bb.x1 || x > bb.x2 || y < bb.y1 || y > bb.y2) {\n      // console.log('bezier out of rough bb')\n      return false;\n    } else {\n      // console.log('do more expensive check');\n      return true;\n    }\n  };\n  var solveQuadratic = function solveQuadratic(a, b, c, val) {\n    c -= val;\n    var r = b * b - 4 * a * c;\n\n    if (r < 0) {\n      return [];\n    }\n\n    var sqrtR = Math.sqrt(r);\n    var denom = 2 * a;\n    var root1 = (-b + sqrtR) / denom;\n    var root2 = (-b - sqrtR) / denom;\n    return [root1, root2];\n  };\n  var solveCubic = function solveCubic(a, b, c, d, result) {\n    // Solves a cubic function, returns root in form [r1, i1, r2, i2, r3, i3], where\n    // r is the real component, i is the imaginary component\n    // An implementation of the Cardano method from the year 1545\n    // http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots\n    var epsilon = 0.00001; // avoid division by zero while keeping the overall expression close in value\n\n    if (a === 0) {\n      a = epsilon;\n    }\n\n    b /= a;\n    c /= a;\n    d /= a;\n    var discriminant, q, r, dum1, s, t, term1, r13;\n    q = (3.0 * c - b * b) / 9.0;\n    r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b));\n    r /= 54.0;\n    discriminant = q * q * q + r * r;\n    result[1] = 0;\n    term1 = b / 3.0;\n\n    if (discriminant > 0) {\n      s = r + Math.sqrt(discriminant);\n      s = s < 0 ? -Math.pow(-s, 1.0 / 3.0) : Math.pow(s, 1.0 / 3.0);\n      t = r - Math.sqrt(discriminant);\n      t = t < 0 ? -Math.pow(-t, 1.0 / 3.0) : Math.pow(t, 1.0 / 3.0);\n      result[0] = -term1 + s + t;\n      term1 += (s + t) / 2.0;\n      result[4] = result[2] = -term1;\n      term1 = Math.sqrt(3.0) * (-t + s) / 2;\n      result[3] = term1;\n      result[5] = -term1;\n      return;\n    }\n\n    result[5] = result[3] = 0;\n\n    if (discriminant === 0) {\n      r13 = r < 0 ? -Math.pow(-r, 1.0 / 3.0) : Math.pow(r, 1.0 / 3.0);\n      result[0] = -term1 + 2.0 * r13;\n      result[4] = result[2] = -(r13 + term1);\n      return;\n    }\n\n    q = -q;\n    dum1 = q * q * q;\n    dum1 = Math.acos(r / Math.sqrt(dum1));\n    r13 = 2.0 * Math.sqrt(q);\n    result[0] = -term1 + r13 * Math.cos(dum1 / 3.0);\n    result[2] = -term1 + r13 * Math.cos((dum1 + 2.0 * Math.PI) / 3.0);\n    result[4] = -term1 + r13 * Math.cos((dum1 + 4.0 * Math.PI) / 3.0);\n    return;\n  };\n  var sqdistToQuadraticBezier = function sqdistToQuadraticBezier(x, y, x1, y1, x2, y2, x3, y3) {\n    // Find minimum distance by using the minimum of the distance\n    // function between the given point and the curve\n    // This gives the coefficients of the resulting cubic equation\n    // whose roots tell us where a possible minimum is\n    // (Coefficients are divided by 4)\n    var a = 1.0 * x1 * x1 - 4 * x1 * x2 + 2 * x1 * x3 + 4 * x2 * x2 - 4 * x2 * x3 + x3 * x3 + y1 * y1 - 4 * y1 * y2 + 2 * y1 * y3 + 4 * y2 * y2 - 4 * y2 * y3 + y3 * y3;\n    var b = 1.0 * 9 * x1 * x2 - 3 * x1 * x1 - 3 * x1 * x3 - 6 * x2 * x2 + 3 * x2 * x3 + 9 * y1 * y2 - 3 * y1 * y1 - 3 * y1 * y3 - 6 * y2 * y2 + 3 * y2 * y3;\n    var c = 1.0 * 3 * x1 * x1 - 6 * x1 * x2 + x1 * x3 - x1 * x + 2 * x2 * x2 + 2 * x2 * x - x3 * x + 3 * y1 * y1 - 6 * y1 * y2 + y1 * y3 - y1 * y + 2 * y2 * y2 + 2 * y2 * y - y3 * y;\n    var d = 1.0 * x1 * x2 - x1 * x1 + x1 * x - x2 * x + y1 * y2 - y1 * y1 + y1 * y - y2 * y; // debug(\"coefficients: \" + a / a + \", \" + b / a + \", \" + c / a + \", \" + d / a);\n\n    var roots = []; // Use the cubic solving algorithm\n\n    solveCubic(a, b, c, d, roots);\n    var zeroThreshold = 0.0000001;\n    var params = [];\n\n    for (var index = 0; index < 6; index += 2) {\n      if (Math.abs(roots[index + 1]) < zeroThreshold && roots[index] >= 0 && roots[index] <= 1.0) {\n        params.push(roots[index]);\n      }\n    }\n\n    params.push(1.0);\n    params.push(0.0);\n    var minDistanceSquared = -1;\n    var curX, curY, distSquared;\n\n    for (var i = 0; i < params.length; i++) {\n      curX = Math.pow(1.0 - params[i], 2.0) * x1 + 2.0 * (1 - params[i]) * params[i] * x2 + params[i] * params[i] * x3;\n      curY = Math.pow(1 - params[i], 2.0) * y1 + 2 * (1.0 - params[i]) * params[i] * y2 + params[i] * params[i] * y3;\n      distSquared = Math.pow(curX - x, 2) + Math.pow(curY - y, 2); // debug('distance for param ' + params[i] + \": \" + Math.sqrt(distSquared));\n\n      if (minDistanceSquared >= 0) {\n        if (distSquared < minDistanceSquared) {\n          minDistanceSquared = distSquared;\n        }\n      } else {\n        minDistanceSquared = distSquared;\n      }\n    }\n\n    return minDistanceSquared;\n  };\n  var sqdistToFiniteLine = function sqdistToFiniteLine(x, y, x1, y1, x2, y2) {\n    var offset = [x - x1, y - y1];\n    var line = [x2 - x1, y2 - y1];\n    var lineSq = line[0] * line[0] + line[1] * line[1];\n    var hypSq = offset[0] * offset[0] + offset[1] * offset[1];\n    var dotProduct = offset[0] * line[0] + offset[1] * line[1];\n    var adjSq = dotProduct * dotProduct / lineSq;\n\n    if (dotProduct < 0) {\n      return hypSq;\n    }\n\n    if (adjSq > lineSq) {\n      return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n    }\n\n    return hypSq - adjSq;\n  };\n  var pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {\n    var x1, y1, x2, y2;\n    var y3; // Intersect with vertical line through (x, y)\n\n    var up = 0; // let down = 0;\n\n    for (var i = 0; i < points.length / 2; i++) {\n      x1 = points[i * 2];\n      y1 = points[i * 2 + 1];\n\n      if (i + 1 < points.length / 2) {\n        x2 = points[(i + 1) * 2];\n        y2 = points[(i + 1) * 2 + 1];\n      } else {\n        x2 = points[(i + 1 - points.length / 2) * 2];\n        y2 = points[(i + 1 - points.length / 2) * 2 + 1];\n      }\n\n      if (x1 == x && x2 == x) ; else if (x1 >= x && x >= x2 || x1 <= x && x <= x2) {\n        y3 = (x - x1) / (x2 - x1) * (y2 - y1) + y1;\n\n        if (y3 > y) {\n          up++;\n        } // if( y3 < y ){\n        // down++;\n        // }\n\n      } else {\n        continue;\n      }\n    }\n\n    if (up % 2 === 0) {\n      return false;\n    } else {\n      return true;\n    }\n  };\n  var pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {\n    var transformedPoints = new Array(basePoints.length); // Gives negative angle\n\n    var angle;\n\n    if (direction[0] != null) {\n      angle = Math.atan(direction[1] / direction[0]);\n\n      if (direction[0] < 0) {\n        angle = angle + Math.PI / 2;\n      } else {\n        angle = -angle - Math.PI / 2;\n      }\n    } else {\n      angle = direction;\n    }\n\n    var cos = Math.cos(-angle);\n    var sin = Math.sin(-angle); //    console.log(\"base: \" + basePoints);\n\n    for (var i = 0; i < transformedPoints.length / 2; i++) {\n      transformedPoints[i * 2] = width / 2 * (basePoints[i * 2] * cos - basePoints[i * 2 + 1] * sin);\n      transformedPoints[i * 2 + 1] = height / 2 * (basePoints[i * 2 + 1] * cos + basePoints[i * 2] * sin);\n      transformedPoints[i * 2] += centerX;\n      transformedPoints[i * 2 + 1] += centerY;\n    }\n\n    var points;\n\n    if (padding > 0) {\n      var expandedLineSet = expandPolygon(transformedPoints, -padding);\n      points = joinLines(expandedLineSet);\n    } else {\n      points = transformedPoints;\n    }\n\n    return pointInsidePolygonPoints(x, y, points);\n  };\n  var pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height) {\n    var cutPolygonPoints = new Array(basePoints.length);\n    var halfW = width / 2;\n    var halfH = height / 2;\n    var cornerRadius = getRoundPolygonRadius(width, height);\n    var squaredCornerRadius = cornerRadius * cornerRadius;\n\n    for (var i = 0; i < basePoints.length / 4; i++) {\n      var sourceUv = void 0,\n          destUv = void 0;\n\n      if (i === 0) {\n        sourceUv = basePoints.length - 2;\n      } else {\n        sourceUv = i * 4 - 2;\n      }\n\n      destUv = i * 4 + 2;\n      var px = centerX + halfW * basePoints[i * 4];\n      var py = centerY + halfH * basePoints[i * 4 + 1];\n      var cosTheta = -basePoints[sourceUv] * basePoints[destUv] - basePoints[sourceUv + 1] * basePoints[destUv + 1];\n      var offset = cornerRadius / Math.tan(Math.acos(cosTheta) / 2);\n      var cp0x = px - offset * basePoints[sourceUv];\n      var cp0y = py - offset * basePoints[sourceUv + 1];\n      var cp1x = px + offset * basePoints[destUv];\n      var cp1y = py + offset * basePoints[destUv + 1];\n      cutPolygonPoints[i * 4] = cp0x;\n      cutPolygonPoints[i * 4 + 1] = cp0y;\n      cutPolygonPoints[i * 4 + 2] = cp1x;\n      cutPolygonPoints[i * 4 + 3] = cp1y;\n      var orthx = basePoints[sourceUv + 1];\n      var orthy = -basePoints[sourceUv];\n      var cosAlpha = orthx * basePoints[destUv] + orthy * basePoints[destUv + 1];\n\n      if (cosAlpha < 0) {\n        orthx *= -1;\n        orthy *= -1;\n      }\n\n      var cx = cp0x + orthx * cornerRadius;\n      var cy = cp0y + orthy * cornerRadius;\n      var squaredDistance = Math.pow(cx - x, 2) + Math.pow(cy - y, 2);\n\n      if (squaredDistance <= squaredCornerRadius) {\n        return true;\n      }\n    }\n\n    return pointInsidePolygonPoints(x, y, cutPolygonPoints);\n  };\n  var joinLines = function joinLines(lineSet) {\n    var vertices = new Array(lineSet.length / 2);\n    var currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY;\n    var nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY;\n\n    for (var i = 0; i < lineSet.length / 4; i++) {\n      currentLineStartX = lineSet[i * 4];\n      currentLineStartY = lineSet[i * 4 + 1];\n      currentLineEndX = lineSet[i * 4 + 2];\n      currentLineEndY = lineSet[i * 4 + 3];\n\n      if (i < lineSet.length / 4 - 1) {\n        nextLineStartX = lineSet[(i + 1) * 4];\n        nextLineStartY = lineSet[(i + 1) * 4 + 1];\n        nextLineEndX = lineSet[(i + 1) * 4 + 2];\n        nextLineEndY = lineSet[(i + 1) * 4 + 3];\n      } else {\n        nextLineStartX = lineSet[0];\n        nextLineStartY = lineSet[1];\n        nextLineEndX = lineSet[2];\n        nextLineEndY = lineSet[3];\n      }\n\n      var intersection = finiteLinesIntersect(currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY, nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY, true);\n      vertices[i * 2] = intersection[0];\n      vertices[i * 2 + 1] = intersection[1];\n    }\n\n    return vertices;\n  };\n  var expandPolygon = function expandPolygon(points, pad) {\n    var expandedLineSet = new Array(points.length * 2);\n    var currentPointX, currentPointY, nextPointX, nextPointY;\n\n    for (var i = 0; i < points.length / 2; i++) {\n      currentPointX = points[i * 2];\n      currentPointY = points[i * 2 + 1];\n\n      if (i < points.length / 2 - 1) {\n        nextPointX = points[(i + 1) * 2];\n        nextPointY = points[(i + 1) * 2 + 1];\n      } else {\n        nextPointX = points[0];\n        nextPointY = points[1];\n      } // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]\n      // Assume CCW polygon winding\n\n\n      var offsetX = nextPointY - currentPointY;\n      var offsetY = -(nextPointX - currentPointX); // Normalize\n\n      var offsetLength = Math.sqrt(offsetX * offsetX + offsetY * offsetY);\n      var normalizedOffsetX = offsetX / offsetLength;\n      var normalizedOffsetY = offsetY / offsetLength;\n      expandedLineSet[i * 4] = currentPointX + normalizedOffsetX * pad;\n      expandedLineSet[i * 4 + 1] = currentPointY + normalizedOffsetY * pad;\n      expandedLineSet[i * 4 + 2] = nextPointX + normalizedOffsetX * pad;\n      expandedLineSet[i * 4 + 3] = nextPointY + normalizedOffsetY * pad;\n    }\n\n    return expandedLineSet;\n  };\n  var intersectLineEllipse = function intersectLineEllipse(x, y, centerX, centerY, ellipseWradius, ellipseHradius) {\n    var dispX = centerX - x;\n    var dispY = centerY - y;\n    dispX /= ellipseWradius;\n    dispY /= ellipseHradius;\n    var len = Math.sqrt(dispX * dispX + dispY * dispY);\n    var newLength = len - 1;\n\n    if (newLength < 0) {\n      return [];\n    }\n\n    var lenProportion = newLength / len;\n    return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];\n  };\n  var checkInEllipse = function checkInEllipse(x, y, width, height, centerX, centerY, padding) {\n    x -= centerX;\n    y -= centerY;\n    x /= width / 2 + padding;\n    y /= height / 2 + padding;\n    return x * x + y * y <= 1;\n  }; // Returns intersections of increasing distance from line's start point\n\n  var intersectLineCircle = function intersectLineCircle(x1, y1, x2, y2, centerX, centerY, radius) {\n    // Calculate d, direction vector of line\n    var d = [x2 - x1, y2 - y1]; // Direction vector of line\n\n    var f = [x1 - centerX, y1 - centerY];\n    var a = d[0] * d[0] + d[1] * d[1];\n    var b = 2 * (f[0] * d[0] + f[1] * d[1]);\n    var c = f[0] * f[0] + f[1] * f[1] - radius * radius;\n    var discriminant = b * b - 4 * a * c;\n\n    if (discriminant < 0) {\n      return [];\n    }\n\n    var t1 = (-b + Math.sqrt(discriminant)) / (2 * a);\n    var t2 = (-b - Math.sqrt(discriminant)) / (2 * a);\n    var tMin = Math.min(t1, t2);\n    var tMax = Math.max(t1, t2);\n    var inRangeParams = [];\n\n    if (tMin >= 0 && tMin <= 1) {\n      inRangeParams.push(tMin);\n    }\n\n    if (tMax >= 0 && tMax <= 1) {\n      inRangeParams.push(tMax);\n    }\n\n    if (inRangeParams.length === 0) {\n      return [];\n    }\n\n    var nearIntersectionX = inRangeParams[0] * d[0] + x1;\n    var nearIntersectionY = inRangeParams[0] * d[1] + y1;\n\n    if (inRangeParams.length > 1) {\n      if (inRangeParams[0] == inRangeParams[1]) {\n        return [nearIntersectionX, nearIntersectionY];\n      } else {\n        var farIntersectionX = inRangeParams[1] * d[0] + x1;\n        var farIntersectionY = inRangeParams[1] * d[1] + y1;\n        return [nearIntersectionX, nearIntersectionY, farIntersectionX, farIntersectionY];\n      }\n    } else {\n      return [nearIntersectionX, nearIntersectionY];\n    }\n  };\n  var midOfThree = function midOfThree(a, b, c) {\n    if (b <= a && a <= c || c <= a && a <= b) {\n      return a;\n    } else if (a <= b && b <= c || c <= b && b <= a) {\n      return b;\n    } else {\n      return c;\n    }\n  }; // (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)\n\n  var finiteLinesIntersect = function finiteLinesIntersect(x1, y1, x2, y2, x3, y3, x4, y4, infiniteLines) {\n    var dx13 = x1 - x3;\n    var dx21 = x2 - x1;\n    var dx43 = x4 - x3;\n    var dy13 = y1 - y3;\n    var dy21 = y2 - y1;\n    var dy43 = y4 - y3;\n    var ua_t = dx43 * dy13 - dy43 * dx13;\n    var ub_t = dx21 * dy13 - dy21 * dx13;\n    var u_b = dy43 * dx21 - dx43 * dy21;\n\n    if (u_b !== 0) {\n      var ua = ua_t / u_b;\n      var ub = ub_t / u_b;\n      var flptThreshold = 0.001;\n\n      var _min = 0 - flptThreshold;\n\n      var _max = 1 + flptThreshold;\n\n      if (_min <= ua && ua <= _max && _min <= ub && ub <= _max) {\n        return [x1 + ua * dx21, y1 + ua * dy21];\n      } else {\n        if (!infiniteLines) {\n          return [];\n        } else {\n          return [x1 + ua * dx21, y1 + ua * dy21];\n        }\n      }\n    } else {\n      if (ua_t === 0 || ub_t === 0) {\n        // Parallel, coincident lines. Check if overlap\n        // Check endpoint of second line\n        if (midOfThree(x1, x2, x4) === x4) {\n          return [x4, y4];\n        } // Check start point of second line\n\n\n        if (midOfThree(x1, x2, x3) === x3) {\n          return [x3, y3];\n        } // Endpoint of first line\n\n\n        if (midOfThree(x3, x4, x2) === x2) {\n          return [x2, y2];\n        }\n\n        return [];\n      } else {\n        // Parallel, non-coincident\n        return [];\n      }\n    }\n  }; // math.polygonIntersectLine( x, y, basePoints, centerX, centerY, width, height, padding )\n  // intersect a node polygon (pts transformed)\n  //\n  // math.polygonIntersectLine( x, y, basePoints, centerX, centerY )\n  // intersect the points (no transform)\n\n  var polygonIntersectLine = function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {\n    var intersections = [];\n    var intersection;\n    var transformedPoints = new Array(basePoints.length);\n    var doTransform = true;\n\n    if (width == null) {\n      doTransform = false;\n    }\n\n    var points;\n\n    if (doTransform) {\n      for (var i = 0; i < transformedPoints.length / 2; i++) {\n        transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;\n        transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;\n      }\n\n      if (padding > 0) {\n        var expandedLineSet = expandPolygon(transformedPoints, -padding);\n        points = joinLines(expandedLineSet);\n      } else {\n        points = transformedPoints;\n      }\n    } else {\n      points = basePoints;\n    }\n\n    var currentX, currentY, nextX, nextY;\n\n    for (var _i2 = 0; _i2 < points.length / 2; _i2++) {\n      currentX = points[_i2 * 2];\n      currentY = points[_i2 * 2 + 1];\n\n      if (_i2 < points.length / 2 - 1) {\n        nextX = points[(_i2 + 1) * 2];\n        nextY = points[(_i2 + 1) * 2 + 1];\n      } else {\n        nextX = points[0];\n        nextY = points[1];\n      }\n\n      intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);\n\n      if (intersection.length !== 0) {\n        intersections.push(intersection[0], intersection[1]);\n      }\n    }\n\n    return intersections;\n  };\n  var roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {\n    var intersections = [];\n    var intersection;\n    var lines = new Array(basePoints.length);\n    var halfW = width / 2;\n    var halfH = height / 2;\n    var cornerRadius = getRoundPolygonRadius(width, height);\n\n    for (var i = 0; i < basePoints.length / 4; i++) {\n      var sourceUv = void 0,\n          destUv = void 0;\n\n      if (i === 0) {\n        sourceUv = basePoints.length - 2;\n      } else {\n        sourceUv = i * 4 - 2;\n      }\n\n      destUv = i * 4 + 2;\n      var px = centerX + halfW * basePoints[i * 4];\n      var py = centerY + halfH * basePoints[i * 4 + 1];\n      var cosTheta = -basePoints[sourceUv] * basePoints[destUv] - basePoints[sourceUv + 1] * basePoints[destUv + 1];\n      var offset = cornerRadius / Math.tan(Math.acos(cosTheta) / 2);\n      var cp0x = px - offset * basePoints[sourceUv];\n      var cp0y = py - offset * basePoints[sourceUv + 1];\n      var cp1x = px + offset * basePoints[destUv];\n      var cp1y = py + offset * basePoints[destUv + 1];\n\n      if (i === 0) {\n        lines[basePoints.length - 2] = cp0x;\n        lines[basePoints.length - 1] = cp0y;\n      } else {\n        lines[i * 4 - 2] = cp0x;\n        lines[i * 4 - 1] = cp0y;\n      }\n\n      lines[i * 4] = cp1x;\n      lines[i * 4 + 1] = cp1y;\n      var orthx = basePoints[sourceUv + 1];\n      var orthy = -basePoints[sourceUv];\n      var cosAlpha = orthx * basePoints[destUv] + orthy * basePoints[destUv + 1];\n\n      if (cosAlpha < 0) {\n        orthx *= -1;\n        orthy *= -1;\n      }\n\n      var cx = cp0x + orthx * cornerRadius;\n      var cy = cp0y + orthy * cornerRadius;\n      intersection = intersectLineCircle(x, y, centerX, centerY, cx, cy, cornerRadius);\n\n      if (intersection.length !== 0) {\n        intersections.push(intersection[0], intersection[1]);\n      }\n    }\n\n    for (var _i3 = 0; _i3 < lines.length / 4; _i3++) {\n      intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[_i3 * 4], lines[_i3 * 4 + 1], lines[_i3 * 4 + 2], lines[_i3 * 4 + 3], false);\n\n      if (intersection.length !== 0) {\n        intersections.push(intersection[0], intersection[1]);\n      }\n    }\n\n    if (intersections.length > 2) {\n      var lowestIntersection = [intersections[0], intersections[1]];\n      var lowestSquaredDistance = Math.pow(lowestIntersection[0] - x, 2) + Math.pow(lowestIntersection[1] - y, 2);\n\n      for (var _i4 = 1; _i4 < intersections.length / 2; _i4++) {\n        var squaredDistance = Math.pow(intersections[_i4 * 2] - x, 2) + Math.pow(intersections[_i4 * 2 + 1] - y, 2);\n\n        if (squaredDistance <= lowestSquaredDistance) {\n          lowestIntersection[0] = intersections[_i4 * 2];\n          lowestIntersection[1] = intersections[_i4 * 2 + 1];\n          lowestSquaredDistance = squaredDistance;\n        }\n      }\n\n      return lowestIntersection;\n    }\n\n    return intersections;\n  };\n  var shortenIntersection = function shortenIntersection(intersection, offset, amount) {\n    var disp = [intersection[0] - offset[0], intersection[1] - offset[1]];\n    var length = Math.sqrt(disp[0] * disp[0] + disp[1] * disp[1]);\n    var lenRatio = (length - amount) / length;\n\n    if (lenRatio < 0) {\n      lenRatio = 0.00001;\n    }\n\n    return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];\n  };\n  var generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {\n    var points = generateUnitNgonPoints(sides, rotationRadians);\n    points = fitPolygonToSquare(points);\n    return points;\n  };\n  var fitPolygonToSquare = function fitPolygonToSquare(points) {\n    var x, y;\n    var sides = points.length / 2;\n    var minX = Infinity,\n        minY = Infinity,\n        maxX = -Infinity,\n        maxY = -Infinity;\n\n    for (var i = 0; i < sides; i++) {\n      x = points[2 * i];\n      y = points[2 * i + 1];\n      minX = Math.min(minX, x);\n      maxX = Math.max(maxX, x);\n      minY = Math.min(minY, y);\n      maxY = Math.max(maxY, y);\n    } // stretch factors\n\n\n    var sx = 2 / (maxX - minX);\n    var sy = 2 / (maxY - minY);\n\n    for (var _i5 = 0; _i5 < sides; _i5++) {\n      x = points[2 * _i5] = points[2 * _i5] * sx;\n      y = points[2 * _i5 + 1] = points[2 * _i5 + 1] * sy;\n      minX = Math.min(minX, x);\n      maxX = Math.max(maxX, x);\n      minY = Math.min(minY, y);\n      maxY = Math.max(maxY, y);\n    }\n\n    if (minY < -1) {\n      for (var _i6 = 0; _i6 < sides; _i6++) {\n        y = points[2 * _i6 + 1] = points[2 * _i6 + 1] + (-1 - minY);\n      }\n    }\n\n    return points;\n  };\n  var generateUnitNgonPoints = function generateUnitNgonPoints(sides, rotationRadians) {\n    var increment = 1.0 / sides * 2 * Math.PI;\n    var startAngle = sides % 2 === 0 ? Math.PI / 2.0 + increment / 2.0 : Math.PI / 2.0;\n    startAngle += rotationRadians;\n    var points = new Array(sides * 2);\n    var currentAngle;\n\n    for (var i = 0; i < sides; i++) {\n      currentAngle = i * increment + startAngle;\n      points[2 * i] = Math.cos(currentAngle); // x\n\n      points[2 * i + 1] = Math.sin(-currentAngle); // y\n    }\n\n    return points;\n  }; // Set the default radius, unless half of width or height is smaller than default\n\n  var getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {\n    return Math.min(width / 4, height / 4, 8);\n  }; // Set the default radius\n\n  var getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {\n    return Math.min(width / 10, height / 10, 8);\n  };\n  var getCutRectangleCornerLength = function getCutRectangleCornerLength() {\n    return 8;\n  };\n  var bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {\n    return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];\n  }; // get curve width, height, and control point position offsets as a percentage of node height / width\n\n  var getBarrelCurveConstants = function getBarrelCurveConstants(width, height) {\n    return {\n      heightOffset: Math.min(15, 0.05 * height),\n      widthOffset: Math.min(100, 0.25 * width),\n      ctrlPtOffsetPct: 0.05\n    };\n  };\n\n  var pageRankDefaults = defaults$g({\n    dampingFactor: 0.8,\n    precision: 0.000001,\n    iterations: 200,\n    weight: function weight(edge) {\n      return 1;\n    }\n  });\n  var elesfn$o = {\n    pageRank: function pageRank(options) {\n      var _pageRankDefaults = pageRankDefaults(options),\n          dampingFactor = _pageRankDefaults.dampingFactor,\n          precision = _pageRankDefaults.precision,\n          iterations = _pageRankDefaults.iterations,\n          weight = _pageRankDefaults.weight;\n\n      var cy = this._private.cy;\n\n      var _this$byGroup = this.byGroup(),\n          nodes = _this$byGroup.nodes,\n          edges = _this$byGroup.edges;\n\n      var numNodes = nodes.length;\n      var numNodesSqd = numNodes * numNodes;\n      var numEdges = edges.length; // Construct transposed adjacency matrix\n      // First lets have a zeroed matrix of the right size\n      // We'll also keep track of the sum of each column\n\n      var matrix = new Array(numNodesSqd);\n      var columnSum = new Array(numNodes);\n      var additionalProb = (1 - dampingFactor) / numNodes; // Create null matrix\n\n      for (var i = 0; i < numNodes; i++) {\n        for (var j = 0; j < numNodes; j++) {\n          var n = i * numNodes + j;\n          matrix[n] = 0;\n        }\n\n        columnSum[i] = 0;\n      } // Now, process edges\n\n\n      for (var _i = 0; _i < numEdges; _i++) {\n        var edge = edges[_i];\n        var srcId = edge.data('source');\n        var tgtId = edge.data('target'); // Don't include loops in the matrix\n\n        if (srcId === tgtId) {\n          continue;\n        }\n\n        var s = nodes.indexOfId(srcId);\n        var t = nodes.indexOfId(tgtId);\n        var w = weight(edge);\n\n        var _n = t * numNodes + s; // Update matrix\n\n\n        matrix[_n] += w; // Update column sum\n\n        columnSum[s] += w;\n      } // Add additional probability based on damping factor\n      // Also, take into account columns that have sum = 0\n\n\n      var p = 1.0 / numNodes + additionalProb; // Shorthand\n      // Traverse matrix, column by column\n\n      for (var _j = 0; _j < numNodes; _j++) {\n        if (columnSum[_j] === 0) {\n          // No 'links' out from node jth, assume equal probability for each possible node\n          for (var _i2 = 0; _i2 < numNodes; _i2++) {\n            var _n2 = _i2 * numNodes + _j;\n\n            matrix[_n2] = p;\n          }\n        } else {\n          // Node jth has outgoing link, compute normalized probabilities\n          for (var _i3 = 0; _i3 < numNodes; _i3++) {\n            var _n3 = _i3 * numNodes + _j;\n\n            matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;\n          }\n        }\n      } // Compute dominant eigenvector using power method\n\n\n      var eigenvector = new Array(numNodes);\n      var temp = new Array(numNodes);\n      var previous; // Start with a vector of all 1's\n      // Also, initialize a null vector which will be used as shorthand\n\n      for (var _i4 = 0; _i4 < numNodes; _i4++) {\n        eigenvector[_i4] = 1;\n      }\n\n      for (var iter = 0; iter < iterations; iter++) {\n        // Temp array with all 0's\n        for (var _i5 = 0; _i5 < numNodes; _i5++) {\n          temp[_i5] = 0;\n        } // Multiply matrix with previous result\n\n\n        for (var _i6 = 0; _i6 < numNodes; _i6++) {\n          for (var _j2 = 0; _j2 < numNodes; _j2++) {\n            var _n4 = _i6 * numNodes + _j2;\n\n            temp[_i6] += matrix[_n4] * eigenvector[_j2];\n          }\n        }\n\n        inPlaceSumNormalize(temp);\n        previous = eigenvector;\n        eigenvector = temp;\n        temp = previous;\n        var diff = 0; // Compute difference (squared module) of both vectors\n\n        for (var _i7 = 0; _i7 < numNodes; _i7++) {\n          var delta = previous[_i7] - eigenvector[_i7];\n          diff += delta * delta;\n        } // If difference is less than the desired threshold, stop iterating\n\n\n        if (diff < precision) {\n          break;\n        }\n      } // Construct result\n\n\n      var res = {\n        rank: function rank(node) {\n          node = cy.collection(node)[0];\n          return eigenvector[nodes.indexOf(node)];\n        }\n      };\n      return res;\n    } // pageRank\n\n  }; // elesfn\n\n  var defaults$f = defaults$g({\n    root: null,\n    weight: function weight(edge) {\n      return 1;\n    },\n    directed: false,\n    alpha: 0\n  });\n  var elesfn$n = {\n    degreeCentralityNormalized: function degreeCentralityNormalized(options) {\n      options = defaults$f(options);\n      var cy = this.cy();\n      var nodes = this.nodes();\n      var numNodes = nodes.length;\n\n      if (!options.directed) {\n        var degrees = {};\n        var maxDegree = 0;\n\n        for (var i = 0; i < numNodes; i++) {\n          var node = nodes[i]; // add current node to the current options object and call degreeCentrality\n\n          options.root = node;\n          var currDegree = this.degreeCentrality(options);\n\n          if (maxDegree < currDegree.degree) {\n            maxDegree = currDegree.degree;\n          }\n\n          degrees[node.id()] = currDegree.degree;\n        }\n\n        return {\n          degree: function degree(node) {\n            if (maxDegree === 0) {\n              return 0;\n            }\n\n            if (string(node)) {\n              // from is a selector string\n              node = cy.filter(node);\n            }\n\n            return degrees[node.id()] / maxDegree;\n          }\n        };\n      } else {\n        var indegrees = {};\n        var outdegrees = {};\n        var maxIndegree = 0;\n        var maxOutdegree = 0;\n\n        for (var _i = 0; _i < numNodes; _i++) {\n          var _node = nodes[_i];\n\n          var id = _node.id(); // add current node to the current options object and call degreeCentrality\n\n\n          options.root = _node;\n\n          var _currDegree = this.degreeCentrality(options);\n\n          if (maxIndegree < _currDegree.indegree) maxIndegree = _currDegree.indegree;\n          if (maxOutdegree < _currDegree.outdegree) maxOutdegree = _currDegree.outdegree;\n          indegrees[id] = _currDegree.indegree;\n          outdegrees[id] = _currDegree.outdegree;\n        }\n\n        return {\n          indegree: function indegree(node) {\n            if (maxIndegree == 0) {\n              return 0;\n            }\n\n            if (string(node)) {\n              // from is a selector string\n              node = cy.filter(node);\n            }\n\n            return indegrees[node.id()] / maxIndegree;\n          },\n          outdegree: function outdegree(node) {\n            if (maxOutdegree === 0) {\n              return 0;\n            }\n\n            if (string(node)) {\n              // from is a selector string\n              node = cy.filter(node);\n            }\n\n            return outdegrees[node.id()] / maxOutdegree;\n          }\n        };\n      }\n    },\n    // degreeCentralityNormalized\n    // Implemented from the algorithm in Opsahl's paper\n    // \"Node centrality in weighted networks: Generalizing degree and shortest paths\"\n    // check the heading 2 \"Degree\"\n    degreeCentrality: function degreeCentrality(options) {\n      options = defaults$f(options);\n      var cy = this.cy();\n      var callingEles = this;\n      var _options = options,\n          root = _options.root,\n          weight = _options.weight,\n          directed = _options.directed,\n          alpha = _options.alpha;\n      root = cy.collection(root)[0];\n\n      if (!directed) {\n        var connEdges = root.connectedEdges().intersection(callingEles);\n        var k = connEdges.length;\n        var s = 0; // Now, sum edge weights\n\n        for (var i = 0; i < connEdges.length; i++) {\n          s += weight(connEdges[i]);\n        }\n\n        return {\n          degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha)\n        };\n      } else {\n        var edges = root.connectedEdges();\n        var incoming = edges.filter(function (edge) {\n          return edge.target().same(root) && callingEles.has(edge);\n        });\n        var outgoing = edges.filter(function (edge) {\n          return edge.source().same(root) && callingEles.has(edge);\n        });\n        var k_in = incoming.length;\n        var k_out = outgoing.length;\n        var s_in = 0;\n        var s_out = 0; // Now, sum incoming edge weights\n\n        for (var _i2 = 0; _i2 < incoming.length; _i2++) {\n          s_in += weight(incoming[_i2]);\n        } // Now, sum outgoing edge weights\n\n\n        for (var _i3 = 0; _i3 < outgoing.length; _i3++) {\n          s_out += weight(outgoing[_i3]);\n        }\n\n        return {\n          indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha),\n          outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha)\n        };\n      }\n    } // degreeCentrality\n\n  }; // elesfn\n  // nice, short mathematical alias\n\n  elesfn$n.dc = elesfn$n.degreeCentrality;\n  elesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;\n\n  var defaults$e = defaults$g({\n    harmonic: true,\n    weight: function weight() {\n      return 1;\n    },\n    directed: false,\n    root: null\n  });\n  var elesfn$m = {\n    closenessCentralityNormalized: function closenessCentralityNormalized(options) {\n      var _defaults = defaults$e(options),\n          harmonic = _defaults.harmonic,\n          weight = _defaults.weight,\n          directed = _defaults.directed;\n\n      var cy = this.cy();\n      var closenesses = {};\n      var maxCloseness = 0;\n      var nodes = this.nodes();\n      var fw = this.floydWarshall({\n        weight: weight,\n        directed: directed\n      }); // Compute closeness for every node and find the maximum closeness\n\n      for (var i = 0; i < nodes.length; i++) {\n        var currCloseness = 0;\n        var node_i = nodes[i];\n\n        for (var j = 0; j < nodes.length; j++) {\n          if (i !== j) {\n            var d = fw.distance(node_i, nodes[j]);\n\n            if (harmonic) {\n              currCloseness += 1 / d;\n            } else {\n              currCloseness += d;\n            }\n          }\n        }\n\n        if (!harmonic) {\n          currCloseness = 1 / currCloseness;\n        }\n\n        if (maxCloseness < currCloseness) {\n          maxCloseness = currCloseness;\n        }\n\n        closenesses[node_i.id()] = currCloseness;\n      }\n\n      return {\n        closeness: function closeness(node) {\n          if (maxCloseness == 0) {\n            return 0;\n          }\n\n          if (string(node)) {\n            // from is a selector string\n            node = cy.filter(node)[0].id();\n          } else {\n            // from is a node\n            node = node.id();\n          }\n\n          return closenesses[node] / maxCloseness;\n        }\n      };\n    },\n    // Implemented from pseudocode from wikipedia\n    closenessCentrality: function closenessCentrality(options) {\n      var _defaults2 = defaults$e(options),\n          root = _defaults2.root,\n          weight = _defaults2.weight,\n          directed = _defaults2.directed,\n          harmonic = _defaults2.harmonic;\n\n      root = this.filter(root)[0]; // we need distance from this node to every other node\n\n      var dijkstra = this.dijkstra({\n        root: root,\n        weight: weight,\n        directed: directed\n      });\n      var totalDistance = 0;\n      var nodes = this.nodes();\n\n      for (var i = 0; i < nodes.length; i++) {\n        var n = nodes[i];\n\n        if (!n.same(root)) {\n          var d = dijkstra.distanceTo(n);\n\n          if (harmonic) {\n            totalDistance += 1 / d;\n          } else {\n            totalDistance += d;\n          }\n        }\n      }\n\n      return harmonic ? totalDistance : 1 / totalDistance;\n    } // closenessCentrality\n\n  }; // elesfn\n  // nice, short mathematical alias\n\n  elesfn$m.cc = elesfn$m.closenessCentrality;\n  elesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;\n\n  var defaults$d = defaults$g({\n    weight: null,\n    directed: false\n  });\n  var elesfn$l = {\n    // Implemented from the algorithm in the paper \"On Variants of Shortest-Path Betweenness Centrality and their Generic Computation\" by Ulrik Brandes\n    betweennessCentrality: function betweennessCentrality(options) {\n      var _defaults = defaults$d(options),\n          directed = _defaults.directed,\n          weight = _defaults.weight;\n\n      var weighted = weight != null;\n      var cy = this.cy(); // starting\n\n      var V = this.nodes();\n      var A = {};\n      var _C = {};\n      var max = 0;\n      var C = {\n        set: function set(key, val) {\n          _C[key] = val;\n\n          if (val > max) {\n            max = val;\n          }\n        },\n        get: function get(key) {\n          return _C[key];\n        }\n      }; // A contains the neighborhoods of every node\n\n      for (var i = 0; i < V.length; i++) {\n        var v = V[i];\n        var vid = v.id();\n\n        if (directed) {\n          A[vid] = v.outgoers().nodes(); // get outgoers of every node\n        } else {\n          A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node\n        }\n\n        C.set(vid, 0);\n      }\n\n      var _loop = function _loop(s) {\n        var sid = V[s].id();\n        var S = []; // stack\n\n        var P = {};\n        var g = {};\n        var d = {};\n        var Q = new heap(function (a, b) {\n          return d[a] - d[b];\n        }); // queue\n        // init dictionaries\n\n        for (var _i = 0; _i < V.length; _i++) {\n          var _vid = V[_i].id();\n\n          P[_vid] = [];\n          g[_vid] = 0;\n          d[_vid] = Infinity;\n        }\n\n        g[sid] = 1; // sigma\n\n        d[sid] = 0; // distance to s\n\n        Q.push(sid);\n\n        while (!Q.empty()) {\n          var _v = Q.pop();\n\n          S.push(_v);\n\n          if (weighted) {\n            for (var j = 0; j < A[_v].length; j++) {\n              var w = A[_v][j];\n              var vEle = cy.getElementById(_v);\n              var edge = void 0;\n\n              if (vEle.edgesTo(w).length > 0) {\n                edge = vEle.edgesTo(w)[0];\n              } else {\n                edge = w.edgesTo(vEle)[0];\n              }\n\n              var edgeWeight = weight(edge);\n              w = w.id();\n\n              if (d[w] > d[_v] + edgeWeight) {\n                d[w] = d[_v] + edgeWeight;\n\n                if (Q.nodes.indexOf(w) < 0) {\n                  //if w is not in Q\n                  Q.push(w);\n                } else {\n                  // update position if w is in Q\n                  Q.updateItem(w);\n                }\n\n                g[w] = 0;\n                P[w] = [];\n              }\n\n              if (d[w] == d[_v] + edgeWeight) {\n                g[w] = g[w] + g[_v];\n                P[w].push(_v);\n              }\n            }\n          } else {\n            for (var _j = 0; _j < A[_v].length; _j++) {\n              var _w = A[_v][_j].id();\n\n              if (d[_w] == Infinity) {\n                Q.push(_w);\n                d[_w] = d[_v] + 1;\n              }\n\n              if (d[_w] == d[_v] + 1) {\n                g[_w] = g[_w] + g[_v];\n\n                P[_w].push(_v);\n              }\n            }\n          }\n        }\n\n        var e = {};\n\n        for (var _i2 = 0; _i2 < V.length; _i2++) {\n          e[V[_i2].id()] = 0;\n        }\n\n        while (S.length > 0) {\n          var _w2 = S.pop();\n\n          for (var _j2 = 0; _j2 < P[_w2].length; _j2++) {\n            var _v2 = P[_w2][_j2];\n            e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]);\n          }\n\n          if (_w2 != V[s].id()) {\n            C.set(_w2, C.get(_w2) + e[_w2]);\n          }\n        }\n      };\n\n      for (var s = 0; s < V.length; s++) {\n        _loop(s);\n      }\n\n      var ret = {\n        betweenness: function betweenness(node) {\n          var id = cy.collection(node).id();\n          return C.get(id);\n        },\n        betweennessNormalized: function betweennessNormalized(node) {\n          if (max == 0) {\n            return 0;\n          }\n\n          var id = cy.collection(node).id();\n          return C.get(id) / max;\n        }\n      }; // alias\n\n      ret.betweennessNormalised = ret.betweennessNormalized;\n      return ret;\n    } // betweennessCentrality\n\n  }; // elesfn\n  // nice, short mathematical alias\n\n  elesfn$l.bc = elesfn$l.betweennessCentrality;\n\n  // Implemented by Zoe Xi @zoexi for GSOC 2016\n  /* eslint-disable no-unused-vars */\n\n  var defaults$c = defaults$g({\n    expandFactor: 2,\n    // affects time of computation and cluster granularity to some extent: M * M\n    inflateFactor: 2,\n    // affects cluster granularity (the greater the value, the more clusters): M(i,j) / E(j)\n    multFactor: 1,\n    // optional self loops for each node. Use a neutral value to improve cluster computations.\n    maxIterations: 20,\n    // maximum number of iterations of the MCL algorithm in a single run\n    attributes: [// attributes/features used to group nodes, ie. similarity values between nodes\n    function (edge) {\n      return 1;\n    }]\n  });\n  /* eslint-enable */\n\n  var setOptions$3 = function setOptions(options) {\n    return defaults$c(options);\n  };\n  /* eslint-enable */\n\n\n  var getSimilarity$1 = function getSimilarity(edge, attributes) {\n    var total = 0;\n\n    for (var i = 0; i < attributes.length; i++) {\n      total += attributes[i](edge);\n    }\n\n    return total;\n  };\n\n  var addLoops = function addLoops(M, n, val) {\n    for (var i = 0; i < n; i++) {\n      M[i * n + i] = val;\n    }\n  };\n\n  var normalize = function normalize(M, n) {\n    var sum;\n\n    for (var col = 0; col < n; col++) {\n      sum = 0;\n\n      for (var row = 0; row < n; row++) {\n        sum += M[row * n + col];\n      }\n\n      for (var _row = 0; _row < n; _row++) {\n        M[_row * n + col] = M[_row * n + col] / sum;\n      }\n    }\n  }; // TODO: blocked matrix multiplication?\n\n\n  var mmult = function mmult(A, B, n) {\n    var C = new Array(n * n);\n\n    for (var i = 0; i < n; i++) {\n      for (var j = 0; j < n; j++) {\n        C[i * n + j] = 0;\n      }\n\n      for (var k = 0; k < n; k++) {\n        for (var _j = 0; _j < n; _j++) {\n          C[i * n + _j] += A[i * n + k] * B[k * n + _j];\n        }\n      }\n    }\n\n    return C;\n  };\n\n  var expand = function expand(M, n, expandFactor\n  /** power **/\n  ) {\n    var _M = M.slice(0);\n\n    for (var p = 1; p < expandFactor; p++) {\n      M = mmult(M, _M, n);\n    }\n\n    return M;\n  };\n\n  var inflate = function inflate(M, n, inflateFactor\n  /** r **/\n  ) {\n    var _M = new Array(n * n); // M(i,j) ^ inflatePower\n\n\n    for (var i = 0; i < n * n; i++) {\n      _M[i] = Math.pow(M[i], inflateFactor);\n    }\n\n    normalize(_M, n);\n    return _M;\n  };\n\n  var hasConverged = function hasConverged(M, _M, n2, roundFactor) {\n    // Check that both matrices have the same elements (i,j)\n    for (var i = 0; i < n2; i++) {\n      var v1 = Math.round(M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor); // truncate to 'roundFactor' decimal places\n\n      var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);\n\n      if (v1 !== v2) {\n        return false;\n      }\n    }\n\n    return true;\n  };\n\n  var assign$2 = function assign(M, n, nodes, cy) {\n    var clusters = [];\n\n    for (var i = 0; i < n; i++) {\n      var cluster = [];\n\n      for (var j = 0; j < n; j++) {\n        // Row-wise attractors and elements that they attract belong in same cluster\n        if (Math.round(M[i * n + j] * 1000) / 1000 > 0) {\n          cluster.push(nodes[j]);\n        }\n      }\n\n      if (cluster.length !== 0) {\n        clusters.push(cy.collection(cluster));\n      }\n    }\n\n    return clusters;\n  };\n\n  var isDuplicate = function isDuplicate(c1, c2) {\n    for (var i = 0; i < c1.length; i++) {\n      if (!c2[i] || c1[i].id() !== c2[i].id()) {\n        return false;\n      }\n    }\n\n    return true;\n  };\n\n  var removeDuplicates = function removeDuplicates(clusters) {\n    for (var i = 0; i < clusters.length; i++) {\n      for (var j = 0; j < clusters.length; j++) {\n        if (i != j && isDuplicate(clusters[i], clusters[j])) {\n          clusters.splice(j, 1);\n        }\n      }\n    }\n\n    return clusters;\n  };\n\n  var markovClustering = function markovClustering(options) {\n    var nodes = this.nodes();\n    var edges = this.edges();\n    var cy = this.cy(); // Set parameters of algorithm:\n\n    var opts = setOptions$3(options); // Map each node to its position in node array\n\n    var id2position = {};\n\n    for (var i = 0; i < nodes.length; i++) {\n      id2position[nodes[i].id()] = i;\n    } // Generate stochastic matrix M from input graph G (should be symmetric/undirected)\n\n\n    var n = nodes.length,\n        n2 = n * n;\n\n    var M = new Array(n2),\n        _M;\n\n    for (var _i = 0; _i < n2; _i++) {\n      M[_i] = 0;\n    }\n\n    for (var e = 0; e < edges.length; e++) {\n      var edge = edges[e];\n      var _i2 = id2position[edge.source().id()];\n      var j = id2position[edge.target().id()];\n      var sim = getSimilarity$1(edge, opts.attributes);\n      M[_i2 * n + j] += sim; // G should be symmetric and undirected\n\n      M[j * n + _i2] += sim;\n    } // Begin Markov cluster algorithm\n    // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal\n\n\n    addLoops(M, n, opts.multFactor); // Step 2: M = normalize( M );\n\n    normalize(M, n);\n    var isStillMoving = true;\n    var iterations = 0;\n\n    while (isStillMoving && iterations < opts.maxIterations) {\n      isStillMoving = false; // Step 3:\n\n      _M = expand(M, n, opts.expandFactor); // Step 4:\n\n      M = inflate(_M, n, opts.inflateFactor); // Step 5: check to see if ~steady state has been reached\n\n      if (!hasConverged(M, _M, n2, 4)) {\n        isStillMoving = true;\n      }\n\n      iterations++;\n    } // Build clusters from matrix\n\n\n    var clusters = assign$2(M, n, nodes, cy); // Remove duplicate clusters due to symmetry of graph and M matrix\n\n    clusters = removeDuplicates(clusters);\n    return clusters;\n  };\n\n  var markovClustering$1 = {\n    markovClustering: markovClustering,\n    mcl: markovClustering\n  };\n\n  // Common distance metrics for clustering algorithms\n\n  var identity = function identity(x) {\n    return x;\n  };\n\n  var absDiff = function absDiff(p, q) {\n    return Math.abs(q - p);\n  };\n\n  var addAbsDiff = function addAbsDiff(total, p, q) {\n    return total + absDiff(p, q);\n  };\n\n  var addSquaredDiff = function addSquaredDiff(total, p, q) {\n    return total + Math.pow(q - p, 2);\n  };\n\n  var sqrt = function sqrt(x) {\n    return Math.sqrt(x);\n  };\n\n  var maxAbsDiff = function maxAbsDiff(currentMax, p, q) {\n    return Math.max(currentMax, absDiff(p, q));\n  };\n\n  var getDistance = function getDistance(length, getP, getQ, init, visit) {\n    var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity;\n    var ret = init;\n    var p, q;\n\n    for (var dim = 0; dim < length; dim++) {\n      p = getP(dim);\n      q = getQ(dim);\n      ret = visit(ret, p, q);\n    }\n\n    return post(ret);\n  };\n\n  var distances = {\n    euclidean: function euclidean(length, getP, getQ) {\n      if (length >= 2) {\n        return getDistance(length, getP, getQ, 0, addSquaredDiff, sqrt);\n      } else {\n        // for single attr case, more efficient to avoid sqrt\n        return getDistance(length, getP, getQ, 0, addAbsDiff);\n      }\n    },\n    squaredEuclidean: function squaredEuclidean(length, getP, getQ) {\n      return getDistance(length, getP, getQ, 0, addSquaredDiff);\n    },\n    manhattan: function manhattan(length, getP, getQ) {\n      return getDistance(length, getP, getQ, 0, addAbsDiff);\n    },\n    max: function max(length, getP, getQ) {\n      return getDistance(length, getP, getQ, -Infinity, maxAbsDiff);\n    }\n  }; // in case the user accidentally doesn't use camel case\n\n  distances['squared-euclidean'] = distances['squaredEuclidean'];\n  distances['squaredeuclidean'] = distances['squaredEuclidean'];\n  function clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {\n    var impl;\n\n    if (fn$6(method)) {\n      impl = method;\n    } else {\n      impl = distances[method] || distances.euclidean;\n    }\n\n    if (length === 0 && fn$6(method)) {\n      return impl(nodeP, nodeQ);\n    } else {\n      return impl(length, getP, getQ, nodeP, nodeQ);\n    }\n  }\n\n  var defaults$b = defaults$g({\n    k: 2,\n    m: 2,\n    sensitivityThreshold: 0.0001,\n    distance: 'euclidean',\n    maxIterations: 10,\n    attributes: [],\n    testMode: false,\n    testCentroids: null\n  });\n\n  var setOptions$2 = function setOptions(options) {\n    return defaults$b(options);\n  };\n  /* eslint-enable */\n\n\n  var getDist = function getDist(type, node, centroid, attributes, mode) {\n    var noNodeP = mode !== 'kMedoids';\n    var getP = noNodeP ? function (i) {\n      return centroid[i];\n    } : function (i) {\n      return attributes[i](centroid);\n    };\n\n    var getQ = function getQ(i) {\n      return attributes[i](node);\n    };\n\n    var nodeP = centroid;\n    var nodeQ = node;\n    return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);\n  };\n\n  var randomCentroids = function randomCentroids(nodes, k, attributes) {\n    var ndim = attributes.length;\n    var min = new Array(ndim);\n    var max = new Array(ndim);\n    var centroids = new Array(k);\n    var centroid = null; // Find min, max values for each attribute dimension\n\n    for (var i = 0; i < ndim; i++) {\n      min[i] = nodes.min(attributes[i]).value;\n      max[i] = nodes.max(attributes[i]).value;\n    } // Build k centroids, each represented as an n-dim feature vector\n\n\n    for (var c = 0; c < k; c++) {\n      centroid = [];\n\n      for (var _i = 0; _i < ndim; _i++) {\n        centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value\n      }\n\n      centroids[c] = centroid;\n    }\n\n    return centroids;\n  };\n\n  var classify = function classify(node, centroids, distance, attributes, type) {\n    var min = Infinity;\n    var index = 0;\n\n    for (var i = 0; i < centroids.length; i++) {\n      var dist = getDist(distance, node, centroids[i], attributes, type);\n\n      if (dist < min) {\n        min = dist;\n        index = i;\n      }\n    }\n\n    return index;\n  };\n\n  var buildCluster = function buildCluster(centroid, nodes, assignment) {\n    var cluster = [];\n    var node = null;\n\n    for (var n = 0; n < nodes.length; n++) {\n      node = nodes[n];\n\n      if (assignment[node.id()] === centroid) {\n        //console.log(\"Node \" + node.id() + \" is associated with medoid #: \" + m);\n        cluster.push(node);\n      }\n    }\n\n    return cluster;\n  };\n\n  var haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {\n    return Math.abs(v2 - v1) <= sensitivityThreshold;\n  };\n\n  var haveMatricesConverged = function haveMatricesConverged(v1, v2, sensitivityThreshold) {\n    for (var i = 0; i < v1.length; i++) {\n      for (var j = 0; j < v1[i].length; j++) {\n        var diff = Math.abs(v1[i][j] - v2[i][j]);\n\n        if (diff > sensitivityThreshold) {\n          return false;\n        }\n      }\n    }\n\n    return true;\n  };\n\n  var seenBefore = function seenBefore(node, medoids, n) {\n    for (var i = 0; i < n; i++) {\n      if (node === medoids[i]) return true;\n    }\n\n    return false;\n  };\n\n  var randomMedoids = function randomMedoids(nodes, k) {\n    var medoids = new Array(k); // For small data sets, the probability of medoid conflict is greater,\n    // so we need to check to see if we've already seen or chose this node before.\n\n    if (nodes.length < 50) {\n      // Randomly select k medoids from the n nodes\n      for (var i = 0; i < k; i++) {\n        var node = nodes[Math.floor(Math.random() * nodes.length)]; // If we've already chosen this node to be a medoid, don't choose it again (for small data sets).\n        // Instead choose a different random node.\n\n        while (seenBefore(node, medoids, i)) {\n          node = nodes[Math.floor(Math.random() * nodes.length)];\n        }\n\n        medoids[i] = node;\n      }\n    } else {\n      // Relatively large data set, so pretty safe to not check and just select random nodes\n      for (var _i2 = 0; _i2 < k; _i2++) {\n        medoids[_i2] = nodes[Math.floor(Math.random() * nodes.length)];\n      }\n    }\n\n    return medoids;\n  };\n\n  var findCost = function findCost(potentialNewMedoid, cluster, attributes) {\n    var cost = 0;\n\n    for (var n = 0; n < cluster.length; n++) {\n      cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');\n    }\n\n    return cost;\n  };\n\n  var kMeans = function kMeans(options) {\n    var cy = this.cy();\n    var nodes = this.nodes();\n    var node = null; // Set parameters of algorithm: # of clusters, distance metric, etc.\n\n    var opts = setOptions$2(options); // Begin k-means algorithm\n\n    var clusters = new Array(opts.k);\n    var assignment = {};\n    var centroids; // Step 1: Initialize centroid positions\n\n    if (opts.testMode) {\n      if (typeof opts.testCentroids === 'number') {\n        // TODO: implement a seeded random number generator.\n        opts.testCentroids;\n        centroids = randomCentroids(nodes, opts.k, opts.attributes);\n      } else if (_typeof(opts.testCentroids) === 'object') {\n        centroids = opts.testCentroids;\n      } else {\n        centroids = randomCentroids(nodes, opts.k, opts.attributes);\n      }\n    } else {\n      centroids = randomCentroids(nodes, opts.k, opts.attributes);\n    }\n\n    var isStillMoving = true;\n    var iterations = 0;\n\n    while (isStillMoving && iterations < opts.maxIterations) {\n      // Step 2: Assign nodes to the nearest centroid\n      for (var n = 0; n < nodes.length; n++) {\n        node = nodes[n]; // Determine which cluster this node belongs to: node id => cluster #\n\n        assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');\n      } // Step 3: For each of the k clusters, update its centroid\n\n\n      isStillMoving = false;\n\n      for (var c = 0; c < opts.k; c++) {\n        // Get all nodes that belong to this cluster\n        var cluster = buildCluster(c, nodes, assignment);\n\n        if (cluster.length === 0) {\n          // If cluster is empty, break out early & move to next cluster\n          continue;\n        } // Update centroids by calculating avg of all nodes within the cluster.\n\n\n        var ndim = opts.attributes.length;\n        var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]\n\n        var newCentroid = new Array(ndim);\n        var sum = new Array(ndim);\n\n        for (var d = 0; d < ndim; d++) {\n          sum[d] = 0.0;\n\n          for (var i = 0; i < cluster.length; i++) {\n            node = cluster[i];\n            sum[d] += opts.attributes[d](node);\n          }\n\n          newCentroid[d] = sum[d] / cluster.length; // Check to see if algorithm has converged, i.e. when centroids no longer change\n\n          if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {\n            isStillMoving = true;\n          }\n        }\n\n        centroids[c] = newCentroid;\n        clusters[c] = cy.collection(cluster);\n      }\n\n      iterations++;\n    }\n\n    return clusters;\n  };\n\n  var kMedoids = function kMedoids(options) {\n    var cy = this.cy();\n    var nodes = this.nodes();\n    var node = null;\n    var opts = setOptions$2(options); // Begin k-medoids algorithm\n\n    var clusters = new Array(opts.k);\n    var medoids;\n    var assignment = {};\n    var curCost;\n    var minCosts = new Array(opts.k); // minimum cost configuration for each cluster\n    // Step 1: Initialize k medoids\n\n    if (opts.testMode) {\n      if (typeof opts.testCentroids === 'number') ; else if (_typeof(opts.testCentroids) === 'object') {\n        medoids = opts.testCentroids;\n      } else {\n        medoids = randomMedoids(nodes, opts.k);\n      }\n    } else {\n      medoids = randomMedoids(nodes, opts.k);\n    }\n\n    var isStillMoving = true;\n    var iterations = 0;\n\n    while (isStillMoving && iterations < opts.maxIterations) {\n      // Step 2: Assign nodes to the nearest medoid\n      for (var n = 0; n < nodes.length; n++) {\n        node = nodes[n]; // Determine which cluster this node belongs to: node id => cluster #\n\n        assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');\n      }\n\n      isStillMoving = false; // Step 3: For each medoid m, and for each node associated with mediod m,\n      // select the node with the lowest configuration cost as new medoid.\n\n      for (var m = 0; m < medoids.length; m++) {\n        // Get all nodes that belong to this medoid\n        var cluster = buildCluster(m, nodes, assignment);\n\n        if (cluster.length === 0) {\n          // If cluster is empty, break out early & move to next cluster\n          continue;\n        }\n\n        minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost\n        // Select different medoid if its configuration has the lowest cost\n\n        for (var _n = 0; _n < cluster.length; _n++) {\n          curCost = findCost(cluster[_n], cluster, opts.attributes);\n\n          if (curCost < minCosts[m]) {\n            minCosts[m] = curCost;\n            medoids[m] = cluster[_n];\n            isStillMoving = true;\n          }\n        }\n\n        clusters[m] = cy.collection(cluster);\n      }\n\n      iterations++;\n    }\n\n    return clusters;\n  };\n\n  var updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {\n    var numerator, denominator;\n\n    for (var n = 0; n < nodes.length; n++) {\n      for (var c = 0; c < centroids.length; c++) {\n        weight[n][c] = Math.pow(U[n][c], opts.m);\n      }\n    }\n\n    for (var _c = 0; _c < centroids.length; _c++) {\n      for (var dim = 0; dim < opts.attributes.length; dim++) {\n        numerator = 0;\n        denominator = 0;\n\n        for (var _n2 = 0; _n2 < nodes.length; _n2++) {\n          numerator += weight[_n2][_c] * opts.attributes[dim](nodes[_n2]);\n          denominator += weight[_n2][_c];\n        }\n\n        centroids[_c][dim] = numerator / denominator;\n      }\n    }\n  };\n\n  var updateMembership = function updateMembership(U, _U, centroids, nodes, opts) {\n    // Save previous step\n    for (var i = 0; i < U.length; i++) {\n      _U[i] = U[i].slice();\n    }\n\n    var sum, numerator, denominator;\n    var pow = 2 / (opts.m - 1);\n\n    for (var c = 0; c < centroids.length; c++) {\n      for (var n = 0; n < nodes.length; n++) {\n        sum = 0;\n\n        for (var k = 0; k < centroids.length; k++) {\n          // against all other centroids\n          numerator = getDist(opts.distance, nodes[n], centroids[c], opts.attributes, 'cmeans');\n          denominator = getDist(opts.distance, nodes[n], centroids[k], opts.attributes, 'cmeans');\n          sum += Math.pow(numerator / denominator, pow);\n        }\n\n        U[n][c] = 1 / sum;\n      }\n    }\n  };\n\n  var assign$1 = function assign(nodes, U, opts, cy) {\n    var clusters = new Array(opts.k);\n\n    for (var c = 0; c < clusters.length; c++) {\n      clusters[c] = [];\n    }\n\n    var max;\n    var index;\n\n    for (var n = 0; n < U.length; n++) {\n      // for each node (U is N x C matrix)\n      max = -Infinity;\n      index = -1; // Determine which cluster the node is most likely to belong in\n\n      for (var _c2 = 0; _c2 < U[0].length; _c2++) {\n        if (U[n][_c2] > max) {\n          max = U[n][_c2];\n          index = _c2;\n        }\n      }\n\n      clusters[index].push(nodes[n]);\n    } // Turn every array into a collection of nodes\n\n\n    for (var _c3 = 0; _c3 < clusters.length; _c3++) {\n      clusters[_c3] = cy.collection(clusters[_c3]);\n    }\n\n    return clusters;\n  };\n\n  var fuzzyCMeans = function fuzzyCMeans(options) {\n    var cy = this.cy();\n    var nodes = this.nodes();\n    var opts = setOptions$2(options); // Begin fuzzy c-means algorithm\n\n    var clusters;\n    var centroids;\n    var U;\n\n    var _U;\n\n    var weight; // Step 1: Initialize letiables.\n\n    _U = new Array(nodes.length);\n\n    for (var i = 0; i < nodes.length; i++) {\n      // N x C matrix\n      _U[i] = new Array(opts.k);\n    }\n\n    U = new Array(nodes.length);\n\n    for (var _i3 = 0; _i3 < nodes.length; _i3++) {\n      // N x C matrix\n      U[_i3] = new Array(opts.k);\n    }\n\n    for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n      var total = 0;\n\n      for (var j = 0; j < opts.k; j++) {\n        U[_i4][j] = Math.random();\n        total += U[_i4][j];\n      }\n\n      for (var _j = 0; _j < opts.k; _j++) {\n        U[_i4][_j] = U[_i4][_j] / total;\n      }\n    }\n\n    centroids = new Array(opts.k);\n\n    for (var _i5 = 0; _i5 < opts.k; _i5++) {\n      centroids[_i5] = new Array(opts.attributes.length);\n    }\n\n    weight = new Array(nodes.length);\n\n    for (var _i6 = 0; _i6 < nodes.length; _i6++) {\n      // N x C matrix\n      weight[_i6] = new Array(opts.k);\n    } // end init FCM\n\n\n    var isStillMoving = true;\n    var iterations = 0;\n\n    while (isStillMoving && iterations < opts.maxIterations) {\n      isStillMoving = false; // Step 2: Calculate the centroids for each step.\n\n      updateCentroids(centroids, nodes, U, weight, opts); // Step 3: Update the partition matrix U.\n\n      updateMembership(U, _U, centroids, nodes, opts); // Step 4: Check for convergence.\n\n      if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {\n        isStillMoving = true;\n      }\n\n      iterations++;\n    } // Assign nodes to clusters with highest probability.\n\n\n    clusters = assign$1(nodes, U, opts, cy);\n    return {\n      clusters: clusters,\n      degreeOfMembership: U\n    };\n  };\n\n  var kClustering = {\n    kMeans: kMeans,\n    kMedoids: kMedoids,\n    fuzzyCMeans: fuzzyCMeans,\n    fcm: fuzzyCMeans\n  };\n\n  // Implemented by Zoe Xi @zoexi for GSOC 2016\n  var defaults$a = defaults$g({\n    distance: 'euclidean',\n    // distance metric to compare nodes\n    linkage: 'min',\n    // linkage criterion : how to determine the distance between clusters of nodes\n    mode: 'threshold',\n    // mode:'threshold' => clusters must be threshold distance apart\n    threshold: Infinity,\n    // the distance threshold\n    // mode:'dendrogram' => the nodes are organised as leaves in a tree (siblings are close), merging makes clusters\n    addDendrogram: false,\n    // whether to add the dendrogram to the graph for viz\n    dendrogramDepth: 0,\n    // depth at which dendrogram branches are merged into the returned clusters\n    attributes: [] // array of attr functions\n\n  });\n  var linkageAliases = {\n    'single': 'min',\n    'complete': 'max'\n  };\n\n  var setOptions$1 = function setOptions(options) {\n    var opts = defaults$a(options);\n    var preferredAlias = linkageAliases[opts.linkage];\n\n    if (preferredAlias != null) {\n      opts.linkage = preferredAlias;\n    }\n\n    return opts;\n  };\n\n  var mergeClosest = function mergeClosest(clusters, index, dists, mins, opts) {\n    // Find two closest clusters from cached mins\n    var minKey = 0;\n    var min = Infinity;\n    var dist;\n    var attrs = opts.attributes;\n\n    var getDist = function getDist(n1, n2) {\n      return clusteringDistance(opts.distance, attrs.length, function (i) {\n        return attrs[i](n1);\n      }, function (i) {\n        return attrs[i](n2);\n      }, n1, n2);\n    };\n\n    for (var i = 0; i < clusters.length; i++) {\n      var key = clusters[i].key;\n      var _dist = dists[key][mins[key]];\n\n      if (_dist < min) {\n        minKey = key;\n        min = _dist;\n      }\n    }\n\n    if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {\n      return false;\n    }\n\n    var c1 = index[minKey];\n    var c2 = index[mins[minKey]];\n    var merged; // Merge two closest clusters\n\n    if (opts.mode === 'dendrogram') {\n      merged = {\n        left: c1,\n        right: c2,\n        key: c1.key\n      };\n    } else {\n      merged = {\n        value: c1.value.concat(c2.value),\n        key: c1.key\n      };\n    }\n\n    clusters[c1.index] = merged;\n    clusters.splice(c2.index, 1);\n    index[c1.key] = merged; // Update distances with new merged cluster\n\n    for (var _i = 0; _i < clusters.length; _i++) {\n      var cur = clusters[_i];\n\n      if (c1.key === cur.key) {\n        dist = Infinity;\n      } else if (opts.linkage === 'min') {\n        dist = dists[c1.key][cur.key];\n\n        if (dists[c1.key][cur.key] > dists[c2.key][cur.key]) {\n          dist = dists[c2.key][cur.key];\n        }\n      } else if (opts.linkage === 'max') {\n        dist = dists[c1.key][cur.key];\n\n        if (dists[c1.key][cur.key] < dists[c2.key][cur.key]) {\n          dist = dists[c2.key][cur.key];\n        }\n      } else if (opts.linkage === 'mean') {\n        dist = (dists[c1.key][cur.key] * c1.size + dists[c2.key][cur.key] * c2.size) / (c1.size + c2.size);\n      } else {\n        if (opts.mode === 'dendrogram') dist = getDist(cur.value, c1.value);else dist = getDist(cur.value[0], c1.value[0]);\n      }\n\n      dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric\n    } // Update cached mins\n\n\n    for (var _i2 = 0; _i2 < clusters.length; _i2++) {\n      var key1 = clusters[_i2].key;\n\n      if (mins[key1] === c1.key || mins[key1] === c2.key) {\n        var _min = key1;\n\n        for (var j = 0; j < clusters.length; j++) {\n          var key2 = clusters[j].key;\n\n          if (dists[key1][key2] < dists[key1][_min]) {\n            _min = key2;\n          }\n        }\n\n        mins[key1] = _min;\n      }\n\n      clusters[_i2].index = _i2;\n    } // Clean up meta data used for clustering\n\n\n    c1.key = c2.key = c1.index = c2.index = null;\n    return true;\n  };\n\n  var getAllChildren = function getAllChildren(root, arr, cy) {\n    if (!root) return;\n\n    if (root.value) {\n      arr.push(root.value);\n    } else {\n      if (root.left) getAllChildren(root.left, arr);\n      if (root.right) getAllChildren(root.right, arr);\n    }\n  };\n\n  var buildDendrogram = function buildDendrogram(root, cy) {\n    if (!root) return '';\n\n    if (root.left && root.right) {\n      var leftStr = buildDendrogram(root.left, cy);\n      var rightStr = buildDendrogram(root.right, cy);\n      var node = cy.add({\n        group: 'nodes',\n        data: {\n          id: leftStr + ',' + rightStr\n        }\n      });\n      cy.add({\n        group: 'edges',\n        data: {\n          source: leftStr,\n          target: node.id()\n        }\n      });\n      cy.add({\n        group: 'edges',\n        data: {\n          source: rightStr,\n          target: node.id()\n        }\n      });\n      return node.id();\n    } else if (root.value) {\n      return root.value.id();\n    }\n  };\n\n  var buildClustersFromTree = function buildClustersFromTree(root, k, cy) {\n    if (!root) return [];\n    var left = [],\n        right = [],\n        leaves = [];\n\n    if (k === 0) {\n      // don't cut tree, simply return all nodes as 1 single cluster\n      if (root.left) getAllChildren(root.left, left);\n      if (root.right) getAllChildren(root.right, right);\n      leaves = left.concat(right);\n      return [cy.collection(leaves)];\n    } else if (k === 1) {\n      // cut at root\n      if (root.value) {\n        // leaf node\n        return [cy.collection(root.value)];\n      } else {\n        if (root.left) getAllChildren(root.left, left);\n        if (root.right) getAllChildren(root.right, right);\n        return [cy.collection(left), cy.collection(right)];\n      }\n    } else {\n      if (root.value) {\n        return [cy.collection(root.value)];\n      } else {\n        if (root.left) left = buildClustersFromTree(root.left, k - 1, cy);\n        if (root.right) right = buildClustersFromTree(root.right, k - 1, cy);\n        return left.concat(right);\n      }\n    }\n  };\n  /* eslint-enable */\n\n\n  var hierarchicalClustering = function hierarchicalClustering(options) {\n    var cy = this.cy();\n    var nodes = this.nodes(); // Set parameters of algorithm: linkage type, distance metric, etc.\n\n    var opts = setOptions$1(options);\n    var attrs = opts.attributes;\n\n    var getDist = function getDist(n1, n2) {\n      return clusteringDistance(opts.distance, attrs.length, function (i) {\n        return attrs[i](n1);\n      }, function (i) {\n        return attrs[i](n2);\n      }, n1, n2);\n    }; // Begin hierarchical algorithm\n\n\n    var clusters = [];\n    var dists = []; // distances between each pair of clusters\n\n    var mins = []; // closest cluster for each cluster\n\n    var index = []; // hash of all clusters by key\n    // In agglomerative (bottom-up) clustering, each node starts as its own cluster\n\n    for (var n = 0; n < nodes.length; n++) {\n      var cluster = {\n        value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],\n        key: n,\n        index: n\n      };\n      clusters[n] = cluster;\n      index[n] = cluster;\n      dists[n] = [];\n      mins[n] = 0;\n    } // Calculate the distance between each pair of clusters\n\n\n    for (var i = 0; i < clusters.length; i++) {\n      for (var j = 0; j <= i; j++) {\n        var dist = void 0;\n\n        if (opts.mode === 'dendrogram') {\n          // modes store cluster values differently\n          dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);\n        } else {\n          dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);\n        }\n\n        dists[i][j] = dist;\n        dists[j][i] = dist;\n\n        if (dist < dists[i][mins[i]]) {\n          mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j\n        }\n      }\n    } // Find the closest pair of clusters and merge them into a single cluster.\n    // Update distances between new cluster and each of the old clusters, and loop until threshold reached.\n\n\n    var merged = mergeClosest(clusters, index, dists, mins, opts);\n\n    while (merged) {\n      merged = mergeClosest(clusters, index, dists, mins, opts);\n    }\n\n    var retClusters; // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges\n    // in addition to returning the clusters.\n\n    if (opts.mode === 'dendrogram') {\n      retClusters = buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);\n      if (opts.addDendrogram) buildDendrogram(clusters[0], cy);\n    } else {\n      // Regular mode simply returns the clusters\n      retClusters = new Array(clusters.length);\n      clusters.forEach(function (cluster, i) {\n        // Clean up meta data used for clustering\n        cluster.key = cluster.index = null;\n        retClusters[i] = cy.collection(cluster.value);\n      });\n    }\n\n    return retClusters;\n  };\n\n  var hierarchicalClustering$1 = {\n    hierarchicalClustering: hierarchicalClustering,\n    hca: hierarchicalClustering\n  };\n\n  // Implemented by Zoe Xi @zoexi for GSOC 2016\n  var defaults$9 = defaults$g({\n    distance: 'euclidean',\n    // distance metric to compare attributes between two nodes\n    preference: 'median',\n    // suitability of a data point to serve as an exemplar\n    damping: 0.8,\n    // damping factor between [0.5, 1)\n    maxIterations: 1000,\n    // max number of iterations to run\n    minIterations: 100,\n    // min number of iterations to run in order for clustering to stop\n    attributes: [// functions to quantify the similarity between any two points\n      // e.g. node => node.data('weight')\n    ]\n  });\n\n  var setOptions = function setOptions(options) {\n    var dmp = options.damping;\n    var pref = options.preference;\n\n    if (!(0.5 <= dmp && dmp < 1)) {\n      error(\"Damping must range on [0.5, 1).  Got: \".concat(dmp));\n    }\n\n    var validPrefs = ['median', 'mean', 'min', 'max'];\n\n    if (!(validPrefs.some(function (v) {\n      return v === pref;\n    }) || number$1(pref))) {\n      error(\"Preference must be one of [\".concat(validPrefs.map(function (p) {\n        return \"'\".concat(p, \"'\");\n      }).join(', '), \"] or a number.  Got: \").concat(pref));\n    }\n\n    return defaults$9(options);\n  };\n  /* eslint-enable */\n\n\n  var getSimilarity = function getSimilarity(type, n1, n2, attributes) {\n    var attr = function attr(n, i) {\n      return attributes[i](n);\n    }; // nb negative because similarity should have an inverse relationship to distance\n\n\n    return -clusteringDistance(type, attributes.length, function (i) {\n      return attr(n1, i);\n    }, function (i) {\n      return attr(n2, i);\n    }, n1, n2);\n  };\n\n  var getPreference = function getPreference(S, preference) {\n    // larger preference = greater # of clusters\n    var p = null;\n\n    if (preference === 'median') {\n      p = median(S);\n    } else if (preference === 'mean') {\n      p = mean(S);\n    } else if (preference === 'min') {\n      p = min(S);\n    } else if (preference === 'max') {\n      p = max(S);\n    } else {\n      // Custom preference number, as set by user\n      p = preference;\n    }\n\n    return p;\n  };\n\n  var findExemplars = function findExemplars(n, R, A) {\n    var indices = [];\n\n    for (var i = 0; i < n; i++) {\n      if (R[i * n + i] + A[i * n + i] > 0) {\n        indices.push(i);\n      }\n    }\n\n    return indices;\n  };\n\n  var assignClusters = function assignClusters(n, S, exemplars) {\n    var clusters = [];\n\n    for (var i = 0; i < n; i++) {\n      var index = -1;\n      var max = -Infinity;\n\n      for (var ei = 0; ei < exemplars.length; ei++) {\n        var e = exemplars[ei];\n\n        if (S[i * n + e] > max) {\n          index = e;\n          max = S[i * n + e];\n        }\n      }\n\n      if (index > 0) {\n        clusters.push(index);\n      }\n    }\n\n    for (var _ei = 0; _ei < exemplars.length; _ei++) {\n      clusters[exemplars[_ei]] = exemplars[_ei];\n    }\n\n    return clusters;\n  };\n\n  var assign = function assign(n, S, exemplars) {\n    var clusters = assignClusters(n, S, exemplars);\n\n    for (var ei = 0; ei < exemplars.length; ei++) {\n      var ii = [];\n\n      for (var c = 0; c < clusters.length; c++) {\n        if (clusters[c] === exemplars[ei]) {\n          ii.push(c);\n        }\n      }\n\n      var maxI = -1;\n      var maxSum = -Infinity;\n\n      for (var i = 0; i < ii.length; i++) {\n        var sum = 0;\n\n        for (var j = 0; j < ii.length; j++) {\n          sum += S[ii[j] * n + ii[i]];\n        }\n\n        if (sum > maxSum) {\n          maxI = i;\n          maxSum = sum;\n        }\n      }\n\n      exemplars[ei] = ii[maxI];\n    }\n\n    clusters = assignClusters(n, S, exemplars);\n    return clusters;\n  };\n\n  var affinityPropagation = function affinityPropagation(options) {\n    var cy = this.cy();\n    var nodes = this.nodes();\n    var opts = setOptions(options); // Map each node to its position in node array\n\n    var id2position = {};\n\n    for (var i = 0; i < nodes.length; i++) {\n      id2position[nodes[i].id()] = i;\n    } // Begin affinity propagation algorithm\n\n\n    var n; // number of data points\n\n    var n2; // size of matrices\n\n    var S; // similarity matrix (1D array)\n\n    var p; // preference/suitability of a data point to serve as an exemplar\n\n    var R; // responsibility matrix (1D array)\n\n    var A; // availability matrix (1D array)\n\n    n = nodes.length;\n    n2 = n * n; // Initialize and build S similarity matrix\n\n    S = new Array(n2);\n\n    for (var _i = 0; _i < n2; _i++) {\n      S[_i] = -Infinity; // for cases where two data points shouldn't be linked together\n    }\n\n    for (var _i2 = 0; _i2 < n; _i2++) {\n      for (var j = 0; j < n; j++) {\n        if (_i2 !== j) {\n          S[_i2 * n + j] = getSimilarity(opts.distance, nodes[_i2], nodes[j], opts.attributes);\n        }\n      }\n    } // Place preferences on the diagonal of S\n\n\n    p = getPreference(S, opts.preference);\n\n    for (var _i3 = 0; _i3 < n; _i3++) {\n      S[_i3 * n + _i3] = p;\n    } // Initialize R responsibility matrix\n\n\n    R = new Array(n2);\n\n    for (var _i4 = 0; _i4 < n2; _i4++) {\n      R[_i4] = 0.0;\n    } // Initialize A availability matrix\n\n\n    A = new Array(n2);\n\n    for (var _i5 = 0; _i5 < n2; _i5++) {\n      A[_i5] = 0.0;\n    }\n\n    var old = new Array(n);\n    var Rp = new Array(n);\n    var se = new Array(n);\n\n    for (var _i6 = 0; _i6 < n; _i6++) {\n      old[_i6] = 0.0;\n      Rp[_i6] = 0.0;\n      se[_i6] = 0;\n    }\n\n    var e = new Array(n * opts.minIterations);\n\n    for (var _i7 = 0; _i7 < e.length; _i7++) {\n      e[_i7] = 0;\n    }\n\n    var iter;\n\n    for (iter = 0; iter < opts.maxIterations; iter++) {\n      // main algorithmic loop\n      // Update R responsibility matrix\n      for (var _i8 = 0; _i8 < n; _i8++) {\n        var max = -Infinity,\n            max2 = -Infinity,\n            maxI = -1,\n            AS = 0.0;\n\n        for (var _j = 0; _j < n; _j++) {\n          old[_j] = R[_i8 * n + _j];\n          AS = A[_i8 * n + _j] + S[_i8 * n + _j];\n\n          if (AS >= max) {\n            max2 = max;\n            max = AS;\n            maxI = _j;\n          } else if (AS > max2) {\n            max2 = AS;\n          }\n        }\n\n        for (var _j2 = 0; _j2 < n; _j2++) {\n          R[_i8 * n + _j2] = (1 - opts.damping) * (S[_i8 * n + _j2] - max) + opts.damping * old[_j2];\n        }\n\n        R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];\n      } // Update A availability matrix\n\n\n      for (var _i9 = 0; _i9 < n; _i9++) {\n        var sum = 0;\n\n        for (var _j3 = 0; _j3 < n; _j3++) {\n          old[_j3] = A[_j3 * n + _i9];\n          Rp[_j3] = Math.max(0, R[_j3 * n + _i9]);\n          sum += Rp[_j3];\n        }\n\n        sum -= Rp[_i9];\n        Rp[_i9] = R[_i9 * n + _i9];\n        sum += Rp[_i9];\n\n        for (var _j4 = 0; _j4 < n; _j4++) {\n          A[_j4 * n + _i9] = (1 - opts.damping) * Math.min(0, sum - Rp[_j4]) + opts.damping * old[_j4];\n        }\n\n        A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];\n      } // Check for convergence\n\n\n      var K = 0;\n\n      for (var _i10 = 0; _i10 < n; _i10++) {\n        var E = A[_i10 * n + _i10] + R[_i10 * n + _i10] > 0 ? 1 : 0;\n        e[iter % opts.minIterations * n + _i10] = E;\n        K += E;\n      }\n\n      if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {\n        var _sum = 0;\n\n        for (var _i11 = 0; _i11 < n; _i11++) {\n          se[_i11] = 0;\n\n          for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {\n            se[_i11] += e[_j5 * n + _i11];\n          }\n\n          if (se[_i11] === 0 || se[_i11] === opts.minIterations) {\n            _sum++;\n          }\n        }\n\n        if (_sum === n) {\n          // then we have convergence\n          break;\n        }\n      }\n    } // Identify exemplars (cluster centers)\n\n\n    var exemplarsIndices = findExemplars(n, R, A); // Assign nodes to clusters\n\n    var clusterIndices = assign(n, S, exemplarsIndices);\n    var clusters = {};\n\n    for (var c = 0; c < exemplarsIndices.length; c++) {\n      clusters[exemplarsIndices[c]] = [];\n    }\n\n    for (var _i12 = 0; _i12 < nodes.length; _i12++) {\n      var pos = id2position[nodes[_i12].id()];\n\n      var clusterIndex = clusterIndices[pos];\n\n      if (clusterIndex != null) {\n        // the node may have not been assigned a cluster if no valid attributes were specified\n        clusters[clusterIndex].push(nodes[_i12]);\n      }\n    }\n\n    var retClusters = new Array(exemplarsIndices.length);\n\n    for (var _c = 0; _c < exemplarsIndices.length; _c++) {\n      retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);\n    }\n\n    return retClusters;\n  };\n\n  var affinityPropagation$1 = {\n    affinityPropagation: affinityPropagation,\n    ap: affinityPropagation\n  };\n\n  var hierholzerDefaults = defaults$g({\n    root: undefined,\n    directed: false\n  });\n  var elesfn$k = {\n    hierholzer: function hierholzer(options) {\n      if (!plainObject(options)) {\n        var args = arguments;\n        options = {\n          root: args[0],\n          directed: args[1]\n        };\n      }\n\n      var _hierholzerDefaults = hierholzerDefaults(options),\n          root = _hierholzerDefaults.root,\n          directed = _hierholzerDefaults.directed;\n\n      var eles = this;\n      var dflag = false;\n      var oddIn;\n      var oddOut;\n      var startVertex;\n      if (root) startVertex = string(root) ? this.filter(root)[0].id() : root[0].id();\n      var nodes = {};\n      var edges = {};\n\n      if (directed) {\n        eles.forEach(function (ele) {\n          var id = ele.id();\n\n          if (ele.isNode()) {\n            var ind = ele.indegree(true);\n            var outd = ele.outdegree(true);\n            var d1 = ind - outd;\n            var d2 = outd - ind;\n\n            if (d1 == 1) {\n              if (oddIn) dflag = true;else oddIn = id;\n            } else if (d2 == 1) {\n              if (oddOut) dflag = true;else oddOut = id;\n            } else if (d2 > 1 || d1 > 1) {\n              dflag = true;\n            }\n\n            nodes[id] = [];\n            ele.outgoers().forEach(function (e) {\n              if (e.isEdge()) nodes[id].push(e.id());\n            });\n          } else {\n            edges[id] = [undefined, ele.target().id()];\n          }\n        });\n      } else {\n        eles.forEach(function (ele) {\n          var id = ele.id();\n\n          if (ele.isNode()) {\n            var d = ele.degree(true);\n\n            if (d % 2) {\n              if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;\n            }\n\n            nodes[id] = [];\n            ele.connectedEdges().forEach(function (e) {\n              return nodes[id].push(e.id());\n            });\n          } else {\n            edges[id] = [ele.source().id(), ele.target().id()];\n          }\n        });\n      }\n\n      var result = {\n        found: false,\n        trail: undefined\n      };\n      if (dflag) return result;else if (oddOut && oddIn) {\n        if (directed) {\n          if (startVertex && oddOut != startVertex) {\n            return result;\n          }\n\n          startVertex = oddOut;\n        } else {\n          if (startVertex && oddOut != startVertex && oddIn != startVertex) {\n            return result;\n          } else if (!startVertex) {\n            startVertex = oddOut;\n          }\n        }\n      } else {\n        if (!startVertex) startVertex = eles[0].id();\n      }\n\n      var walk = function walk(v) {\n        var currentNode = v;\n        var subtour = [v];\n        var adj, adjTail, adjHead;\n\n        while (nodes[currentNode].length) {\n          adj = nodes[currentNode].shift();\n          adjTail = edges[adj][0];\n          adjHead = edges[adj][1];\n\n          if (currentNode != adjHead) {\n            nodes[adjHead] = nodes[adjHead].filter(function (e) {\n              return e != adj;\n            });\n            currentNode = adjHead;\n          } else if (!directed && currentNode != adjTail) {\n            nodes[adjTail] = nodes[adjTail].filter(function (e) {\n              return e != adj;\n            });\n            currentNode = adjTail;\n          }\n\n          subtour.unshift(adj);\n          subtour.unshift(currentNode);\n        }\n\n        return subtour;\n      };\n\n      var trail = [];\n      var subtour = [];\n      subtour = walk(startVertex);\n\n      while (subtour.length != 1) {\n        if (nodes[subtour[0]].length == 0) {\n          trail.unshift(eles.getElementById(subtour.shift()));\n          trail.unshift(eles.getElementById(subtour.shift()));\n        } else {\n          subtour = walk(subtour.shift()).concat(subtour);\n        }\n      }\n\n      trail.unshift(eles.getElementById(subtour.shift())); // final node\n\n      for (var d in nodes) {\n        if (nodes[d].length) {\n          return result;\n        }\n      }\n\n      result.found = true;\n      result.trail = this.spawn(trail, true);\n      return result;\n    }\n  };\n\n  var hopcroftTarjanBiconnected = function hopcroftTarjanBiconnected() {\n    var eles = this;\n    var nodes = {};\n    var id = 0;\n    var edgeCount = 0;\n    var components = [];\n    var stack = [];\n    var visitedEdges = {};\n\n    var buildComponent = function buildComponent(x, y) {\n      var i = stack.length - 1;\n      var cutset = [];\n      var component = eles.spawn();\n\n      while (stack[i].x != x || stack[i].y != y) {\n        cutset.push(stack.pop().edge);\n        i--;\n      }\n\n      cutset.push(stack.pop().edge);\n      cutset.forEach(function (edge) {\n        var connectedNodes = edge.connectedNodes().intersection(eles);\n        component.merge(edge);\n        connectedNodes.forEach(function (node) {\n          var nodeId = node.id();\n          var connectedEdges = node.connectedEdges().intersection(eles);\n          component.merge(node);\n\n          if (!nodes[nodeId].cutVertex) {\n            component.merge(connectedEdges);\n          } else {\n            component.merge(connectedEdges.filter(function (edge) {\n              return edge.isLoop();\n            }));\n          }\n        });\n      });\n      components.push(component);\n    };\n\n    var biconnectedSearch = function biconnectedSearch(root, currentNode, parent) {\n      if (root === parent) edgeCount += 1;\n      nodes[currentNode] = {\n        id: id,\n        low: id++,\n        cutVertex: false\n      };\n      var edges = eles.getElementById(currentNode).connectedEdges().intersection(eles);\n\n      if (edges.size() === 0) {\n        components.push(eles.spawn(eles.getElementById(currentNode)));\n      } else {\n        var sourceId, targetId, otherNodeId, edgeId;\n        edges.forEach(function (edge) {\n          sourceId = edge.source().id();\n          targetId = edge.target().id();\n          otherNodeId = sourceId === currentNode ? targetId : sourceId;\n\n          if (otherNodeId !== parent) {\n            edgeId = edge.id();\n\n            if (!visitedEdges[edgeId]) {\n              visitedEdges[edgeId] = true;\n              stack.push({\n                x: currentNode,\n                y: otherNodeId,\n                edge: edge\n              });\n            }\n\n            if (!(otherNodeId in nodes)) {\n              biconnectedSearch(root, otherNodeId, currentNode);\n              nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].low);\n\n              if (nodes[currentNode].id <= nodes[otherNodeId].low) {\n                nodes[currentNode].cutVertex = true;\n                buildComponent(currentNode, otherNodeId);\n              }\n            } else {\n              nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].id);\n            }\n          }\n        });\n      }\n    };\n\n    eles.forEach(function (ele) {\n      if (ele.isNode()) {\n        var nodeId = ele.id();\n\n        if (!(nodeId in nodes)) {\n          edgeCount = 0;\n          biconnectedSearch(nodeId, nodeId);\n          nodes[nodeId].cutVertex = edgeCount > 1;\n        }\n      }\n    });\n    var cutVertices = Object.keys(nodes).filter(function (id) {\n      return nodes[id].cutVertex;\n    }).map(function (id) {\n      return eles.getElementById(id);\n    });\n    return {\n      cut: eles.spawn(cutVertices),\n      components: components\n    };\n  };\n\n  var hopcroftTarjanBiconnected$1 = {\n    hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,\n    htbc: hopcroftTarjanBiconnected,\n    htb: hopcroftTarjanBiconnected,\n    hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected\n  };\n\n  var tarjanStronglyConnected = function tarjanStronglyConnected() {\n    var eles = this;\n    var nodes = {};\n    var index = 0;\n    var components = [];\n    var stack = [];\n    var cut = eles.spawn(eles);\n\n    var stronglyConnectedSearch = function stronglyConnectedSearch(sourceNodeId) {\n      stack.push(sourceNodeId);\n      nodes[sourceNodeId] = {\n        index: index,\n        low: index++,\n        explored: false\n      };\n      var connectedEdges = eles.getElementById(sourceNodeId).connectedEdges().intersection(eles);\n      connectedEdges.forEach(function (edge) {\n        var targetNodeId = edge.target().id();\n\n        if (targetNodeId !== sourceNodeId) {\n          if (!(targetNodeId in nodes)) {\n            stronglyConnectedSearch(targetNodeId);\n          }\n\n          if (!nodes[targetNodeId].explored) {\n            nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);\n          }\n        }\n      });\n\n      if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {\n        var componentNodes = eles.spawn();\n\n        for (;;) {\n          var nodeId = stack.pop();\n          componentNodes.merge(eles.getElementById(nodeId));\n          nodes[nodeId].low = nodes[sourceNodeId].index;\n          nodes[nodeId].explored = true;\n\n          if (nodeId === sourceNodeId) {\n            break;\n          }\n        }\n\n        var componentEdges = componentNodes.edgesWith(componentNodes);\n        var component = componentNodes.merge(componentEdges);\n        components.push(component);\n        cut = cut.difference(component);\n      }\n    };\n\n    eles.forEach(function (ele) {\n      if (ele.isNode()) {\n        var nodeId = ele.id();\n\n        if (!(nodeId in nodes)) {\n          stronglyConnectedSearch(nodeId);\n        }\n      }\n    });\n    return {\n      cut: cut,\n      components: components\n    };\n  };\n\n  var tarjanStronglyConnected$1 = {\n    tarjanStronglyConnected: tarjanStronglyConnected,\n    tsc: tarjanStronglyConnected,\n    tscc: tarjanStronglyConnected,\n    tarjanStronglyConnectedComponents: tarjanStronglyConnected\n  };\n\n  var elesfn$j = {};\n  [elesfn$v, elesfn$u, elesfn$t, elesfn$s, elesfn$r, elesfn$q, elesfn$p, elesfn$o, elesfn$n, elesfn$m, elesfn$l, markovClustering$1, kClustering, hierarchicalClustering$1, affinityPropagation$1, elesfn$k, hopcroftTarjanBiconnected$1, tarjanStronglyConnected$1].forEach(function (props) {\n    extend(elesfn$j, props);\n  });\n\n  /*!\n  Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable\n  Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)\n  Licensed under The MIT License (http://opensource.org/licenses/MIT)\n  */\n\n  /*  promise states [Promises/A+ 2.1]  */\n  var STATE_PENDING = 0;\n  /*  [Promises/A+ 2.1.1]  */\n\n  var STATE_FULFILLED = 1;\n  /*  [Promises/A+ 2.1.2]  */\n\n  var STATE_REJECTED = 2;\n  /*  [Promises/A+ 2.1.3]  */\n\n  /*  promise object constructor  */\n\n  var api = function api(executor) {\n    /*  optionally support non-constructor/plain-function call  */\n    if (!(this instanceof api)) return new api(executor);\n    /*  initialize object  */\n\n    this.id = 'Thenable/1.0.7';\n    this.state = STATE_PENDING;\n    /*  initial state  */\n\n    this.fulfillValue = undefined;\n    /*  initial value  */\n\n    /*  [Promises/A+ 1.3, 2.1.2.2]  */\n\n    this.rejectReason = undefined;\n    /*  initial reason */\n\n    /*  [Promises/A+ 1.5, 2.1.3.2]  */\n\n    this.onFulfilled = [];\n    /*  initial handlers  */\n\n    this.onRejected = [];\n    /*  initial handlers  */\n\n    /*  provide optional information-hiding proxy  */\n\n    this.proxy = {\n      then: this.then.bind(this)\n    };\n    /*  support optional executor function  */\n\n    if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));\n  };\n  /*  promise API methods  */\n\n\n  api.prototype = {\n    /*  promise resolving methods  */\n    fulfill: function fulfill(value) {\n      return deliver(this, STATE_FULFILLED, 'fulfillValue', value);\n    },\n    reject: function reject(value) {\n      return deliver(this, STATE_REJECTED, 'rejectReason', value);\n    },\n\n    /*  \"The then Method\" [Promises/A+ 1.1, 1.2, 2.2]  */\n    then: function then(onFulfilled, onRejected) {\n      var curr = this;\n      var next = new api();\n      /*  [Promises/A+ 2.2.7]  */\n\n      curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill'));\n      /*  [Promises/A+ 2.2.2/2.2.6]  */\n\n      curr.onRejected.push(resolver(onRejected, next, 'reject'));\n      /*  [Promises/A+ 2.2.3/2.2.6]  */\n\n      execute(curr);\n      return next.proxy;\n      /*  [Promises/A+ 2.2.7, 3.3]  */\n    }\n  };\n  /*  deliver an action  */\n\n  var deliver = function deliver(curr, state, name, value) {\n    if (curr.state === STATE_PENDING) {\n      curr.state = state;\n      /*  [Promises/A+ 2.1.2.1, 2.1.3.1]  */\n\n      curr[name] = value;\n      /*  [Promises/A+ 2.1.2.2, 2.1.3.2]  */\n\n      execute(curr);\n    }\n\n    return curr;\n  };\n  /*  execute all handlers  */\n\n\n  var execute = function execute(curr) {\n    if (curr.state === STATE_FULFILLED) execute_handlers(curr, 'onFulfilled', curr.fulfillValue);else if (curr.state === STATE_REJECTED) execute_handlers(curr, 'onRejected', curr.rejectReason);\n  };\n  /*  execute particular set of handlers  */\n\n\n  var execute_handlers = function execute_handlers(curr, name, value) {\n    /* global setImmediate: true */\n\n    /* global setTimeout: true */\n\n    /*  short-circuit processing  */\n    if (curr[name].length === 0) return;\n    /*  iterate over all handlers, exactly once  */\n\n    var handlers = curr[name];\n    curr[name] = [];\n    /*  [Promises/A+ 2.2.2.3, 2.2.3.3]  */\n\n    var func = function func() {\n      for (var i = 0; i < handlers.length; i++) {\n        handlers[i](value);\n      }\n      /*  [Promises/A+ 2.2.5]  */\n\n    };\n    /*  execute procedure asynchronously  */\n\n    /*  [Promises/A+ 2.2.4, 3.1]  */\n\n\n    if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);\n  };\n  /*  generate a resolver function  */\n\n\n  var resolver = function resolver(cb, next, method) {\n    return function (value) {\n      if (typeof cb !== 'function')\n        /*  [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4]  */\n        next[method].call(next, value);\n        /*  [Promises/A+ 2.2.7.3, 2.2.7.4]  */\n      else {\n        var result;\n\n        try {\n          result = cb(value);\n        }\n        /*  [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2]  */\n        catch (e) {\n          next.reject(e);\n          /*  [Promises/A+ 2.2.7.2]  */\n\n          return;\n        }\n\n        resolve(next, result);\n        /*  [Promises/A+ 2.2.7.1]  */\n      }\n    };\n  };\n  /*  \"Promise Resolution Procedure\"  */\n\n  /*  [Promises/A+ 2.3]  */\n\n\n  var resolve = function resolve(promise, x) {\n    /*  sanity check arguments  */\n\n    /*  [Promises/A+ 2.3.1]  */\n    if (promise === x || promise.proxy === x) {\n      promise.reject(new TypeError('cannot resolve promise with itself'));\n      return;\n    }\n    /*  surgically check for a \"then\" method\n      (mainly to just call the \"getter\" of \"then\" only once)  */\n\n\n    var then;\n\n    if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {\n      try {\n        then = x.then;\n      }\n      /*  [Promises/A+ 2.3.3.1, 3.5]  */\n      catch (e) {\n        promise.reject(e);\n        /*  [Promises/A+ 2.3.3.2]  */\n\n        return;\n      }\n    }\n    /*  handle own Thenables    [Promises/A+ 2.3.2]\n      and similar \"thenables\" [Promises/A+ 2.3.3]  */\n\n\n    if (typeof then === 'function') {\n      var resolved = false;\n\n      try {\n        /*  call retrieved \"then\" method */\n\n        /*  [Promises/A+ 2.3.3.3]  */\n        then.call(x,\n        /*  resolvePromise  */\n\n        /*  [Promises/A+ 2.3.3.3.1]  */\n        function (y) {\n          if (resolved) return;\n          resolved = true;\n          /*  [Promises/A+ 2.3.3.3.3]  */\n\n          if (y === x)\n            /*  [Promises/A+ 3.6]  */\n            promise.reject(new TypeError('circular thenable chain'));else resolve(promise, y);\n        },\n        /*  rejectPromise  */\n\n        /*  [Promises/A+ 2.3.3.3.2]  */\n        function (r) {\n          if (resolved) return;\n          resolved = true;\n          /*  [Promises/A+ 2.3.3.3.3]  */\n\n          promise.reject(r);\n        });\n      } catch (e) {\n        if (!resolved)\n          /*  [Promises/A+ 2.3.3.3.3]  */\n          promise.reject(e);\n        /*  [Promises/A+ 2.3.3.3.4]  */\n      }\n\n      return;\n    }\n    /*  handle other values  */\n\n\n    promise.fulfill(x);\n    /*  [Promises/A+ 2.3.4, 2.3.3.4]  */\n  }; // so we always have Promise.all()\n\n\n  api.all = function (ps) {\n    return new api(function (resolveAll, rejectAll) {\n      var vals = new Array(ps.length);\n      var doneCount = 0;\n\n      var fulfill = function fulfill(i, val) {\n        vals[i] = val;\n        doneCount++;\n\n        if (doneCount === ps.length) {\n          resolveAll(vals);\n        }\n      };\n\n      for (var i = 0; i < ps.length; i++) {\n        (function (i) {\n          var p = ps[i];\n          var isPromise = p != null && p.then != null;\n\n          if (isPromise) {\n            p.then(function (val) {\n              fulfill(i, val);\n            }, function (err) {\n              rejectAll(err);\n            });\n          } else {\n            var val = p;\n            fulfill(i, val);\n          }\n        })(i);\n      }\n    });\n  };\n\n  api.resolve = function (val) {\n    return new api(function (resolve, reject) {\n      resolve(val);\n    });\n  };\n\n  api.reject = function (val) {\n    return new api(function (resolve, reject) {\n      reject(val);\n    });\n  };\n\n  var Promise$1 = typeof Promise !== 'undefined' ? Promise : api; // eslint-disable-line no-undef\n\n  var Animation = function Animation(target, opts, opts2) {\n    var isCore = core(target);\n    var isEle = !isCore;\n\n    var _p = this._private = extend({\n      duration: 1000\n    }, opts, opts2);\n\n    _p.target = target;\n    _p.style = _p.style || _p.css;\n    _p.started = false;\n    _p.playing = false;\n    _p.hooked = false;\n    _p.applying = false;\n    _p.progress = 0;\n    _p.completes = [];\n    _p.frames = [];\n\n    if (_p.complete && fn$6(_p.complete)) {\n      _p.completes.push(_p.complete);\n    }\n\n    if (isEle) {\n      var pos = target.position();\n      _p.startPosition = _p.startPosition || {\n        x: pos.x,\n        y: pos.y\n      };\n      _p.startStyle = _p.startStyle || target.cy().style().getAnimationStartStyle(target, _p.style);\n    }\n\n    if (isCore) {\n      var pan = target.pan();\n      _p.startPan = {\n        x: pan.x,\n        y: pan.y\n      };\n      _p.startZoom = target.zoom();\n    } // for future timeline/animations impl\n\n\n    this.length = 1;\n    this[0] = this;\n  };\n\n  var anifn = Animation.prototype;\n  extend(anifn, {\n    instanceString: function instanceString() {\n      return 'animation';\n    },\n    hook: function hook() {\n      var _p = this._private;\n\n      if (!_p.hooked) {\n        // add to target's animation queue\n        var q;\n        var tAni = _p.target._private.animation;\n\n        if (_p.queue) {\n          q = tAni.queue;\n        } else {\n          q = tAni.current;\n        }\n\n        q.push(this); // add to the animation loop pool\n\n        if (elementOrCollection(_p.target)) {\n          _p.target.cy().addToAnimationPool(_p.target);\n        }\n\n        _p.hooked = true;\n      }\n\n      return this;\n    },\n    play: function play() {\n      var _p = this._private; // autorewind\n\n      if (_p.progress === 1) {\n        _p.progress = 0;\n      }\n\n      _p.playing = true;\n      _p.started = false; // needs to be started by animation loop\n\n      _p.stopped = false;\n      this.hook(); // the animation loop will start the animation...\n\n      return this;\n    },\n    playing: function playing() {\n      return this._private.playing;\n    },\n    apply: function apply() {\n      var _p = this._private;\n      _p.applying = true;\n      _p.started = false; // needs to be started by animation loop\n\n      _p.stopped = false;\n      this.hook(); // the animation loop will apply the animation at this progress\n\n      return this;\n    },\n    applying: function applying() {\n      return this._private.applying;\n    },\n    pause: function pause() {\n      var _p = this._private;\n      _p.playing = false;\n      _p.started = false;\n      return this;\n    },\n    stop: function stop() {\n      var _p = this._private;\n      _p.playing = false;\n      _p.started = false;\n      _p.stopped = true; // to be removed from animation queues\n\n      return this;\n    },\n    rewind: function rewind() {\n      return this.progress(0);\n    },\n    fastforward: function fastforward() {\n      return this.progress(1);\n    },\n    time: function time(t) {\n      var _p = this._private;\n\n      if (t === undefined) {\n        return _p.progress * _p.duration;\n      } else {\n        return this.progress(t / _p.duration);\n      }\n    },\n    progress: function progress(p) {\n      var _p = this._private;\n      var wasPlaying = _p.playing;\n\n      if (p === undefined) {\n        return _p.progress;\n      } else {\n        if (wasPlaying) {\n          this.pause();\n        }\n\n        _p.progress = p;\n        _p.started = false;\n\n        if (wasPlaying) {\n          this.play();\n        }\n      }\n\n      return this;\n    },\n    completed: function completed() {\n      return this._private.progress === 1;\n    },\n    reverse: function reverse() {\n      var _p = this._private;\n      var wasPlaying = _p.playing;\n\n      if (wasPlaying) {\n        this.pause();\n      }\n\n      _p.progress = 1 - _p.progress;\n      _p.started = false;\n\n      var swap = function swap(a, b) {\n        var _pa = _p[a];\n\n        if (_pa == null) {\n          return;\n        }\n\n        _p[a] = _p[b];\n        _p[b] = _pa;\n      };\n\n      swap('zoom', 'startZoom');\n      swap('pan', 'startPan');\n      swap('position', 'startPosition'); // swap styles\n\n      if (_p.style) {\n        for (var i = 0; i < _p.style.length; i++) {\n          var prop = _p.style[i];\n          var name = prop.name;\n          var startStyleProp = _p.startStyle[name];\n          _p.startStyle[name] = prop;\n          _p.style[i] = startStyleProp;\n        }\n      }\n\n      if (wasPlaying) {\n        this.play();\n      }\n\n      return this;\n    },\n    promise: function promise(type) {\n      var _p = this._private;\n      var arr;\n\n      switch (type) {\n        case 'frame':\n          arr = _p.frames;\n          break;\n\n        default:\n        case 'complete':\n        case 'completed':\n          arr = _p.completes;\n      }\n\n      return new Promise$1(function (resolve, reject) {\n        arr.push(function () {\n          resolve();\n        });\n      });\n    }\n  });\n  anifn.complete = anifn.completed;\n  anifn.run = anifn.play;\n  anifn.running = anifn.playing;\n\n  var define$3 = {\n    animated: function animated() {\n      return function animatedImpl() {\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n        var cy = this._private.cy || this;\n\n        if (!cy.styleEnabled()) {\n          return false;\n        }\n\n        var ele = all[0];\n\n        if (ele) {\n          return ele._private.animation.current.length > 0;\n        }\n      };\n    },\n    // animated\n    clearQueue: function clearQueue() {\n      return function clearQueueImpl() {\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n        var cy = this._private.cy || this;\n\n        if (!cy.styleEnabled()) {\n          return this;\n        }\n\n        for (var i = 0; i < all.length; i++) {\n          var ele = all[i];\n          ele._private.animation.queue = [];\n        }\n\n        return this;\n      };\n    },\n    // clearQueue\n    delay: function delay() {\n      return function delayImpl(time, complete) {\n        var cy = this._private.cy || this;\n\n        if (!cy.styleEnabled()) {\n          return this;\n        }\n\n        return this.animate({\n          delay: time,\n          duration: time,\n          complete: complete\n        });\n      };\n    },\n    // delay\n    delayAnimation: function delayAnimation() {\n      return function delayAnimationImpl(time, complete) {\n        var cy = this._private.cy || this;\n\n        if (!cy.styleEnabled()) {\n          return this;\n        }\n\n        return this.animation({\n          delay: time,\n          duration: time,\n          complete: complete\n        });\n      };\n    },\n    // delay\n    animation: function animation() {\n      return function animationImpl(properties, params) {\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n        var cy = this._private.cy || this;\n        var isCore = !selfIsArrayLike;\n        var isEles = !isCore;\n\n        if (!cy.styleEnabled()) {\n          return this;\n        }\n\n        var style = cy.style();\n        properties = extend({}, properties, params);\n        var propertiesEmpty = Object.keys(properties).length === 0;\n\n        if (propertiesEmpty) {\n          return new Animation(all[0], properties); // nothing to animate\n        }\n\n        if (properties.duration === undefined) {\n          properties.duration = 400;\n        }\n\n        switch (properties.duration) {\n          case 'slow':\n            properties.duration = 600;\n            break;\n\n          case 'fast':\n            properties.duration = 200;\n            break;\n        }\n\n        if (isEles) {\n          properties.style = style.getPropsList(properties.style || properties.css);\n          properties.css = undefined;\n        }\n\n        if (isEles && properties.renderedPosition != null) {\n          var rpos = properties.renderedPosition;\n          var pan = cy.pan();\n          var zoom = cy.zoom();\n          properties.position = renderedToModelPosition(rpos, zoom, pan);\n        } // override pan w/ panBy if set\n\n\n        if (isCore && properties.panBy != null) {\n          var panBy = properties.panBy;\n          var cyPan = cy.pan();\n          properties.pan = {\n            x: cyPan.x + panBy.x,\n            y: cyPan.y + panBy.y\n          };\n        } // override pan w/ center if set\n\n\n        var center = properties.center || properties.centre;\n\n        if (isCore && center != null) {\n          var centerPan = cy.getCenterPan(center.eles, properties.zoom);\n\n          if (centerPan != null) {\n            properties.pan = centerPan;\n          }\n        } // override pan & zoom w/ fit if set\n\n\n        if (isCore && properties.fit != null) {\n          var fit = properties.fit;\n          var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);\n\n          if (fitVp != null) {\n            properties.pan = fitVp.pan;\n            properties.zoom = fitVp.zoom;\n          }\n        } // override zoom (& potentially pan) w/ zoom obj if set\n\n\n        if (isCore && plainObject(properties.zoom)) {\n          var vp = cy.getZoomedViewport(properties.zoom);\n\n          if (vp != null) {\n            if (vp.zoomed) {\n              properties.zoom = vp.zoom;\n            }\n\n            if (vp.panned) {\n              properties.pan = vp.pan;\n            }\n          } else {\n            properties.zoom = null; // an inavalid zoom (e.g. no delta) gets automatically destroyed\n          }\n        }\n\n        return new Animation(all[0], properties);\n      };\n    },\n    // animate\n    animate: function animate() {\n      return function animateImpl(properties, params) {\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n        var cy = this._private.cy || this;\n\n        if (!cy.styleEnabled()) {\n          return this;\n        }\n\n        if (params) {\n          properties = extend({}, properties, params);\n        } // manually hook and run the animation\n\n\n        for (var i = 0; i < all.length; i++) {\n          var ele = all[i];\n          var queue = ele.animated() && (properties.queue === undefined || properties.queue);\n          var ani = ele.animation(properties, queue ? {\n            queue: true\n          } : undefined);\n          ani.play();\n        }\n\n        return this; // chaining\n      };\n    },\n    // animate\n    stop: function stop() {\n      return function stopImpl(clearQueue, jumpToEnd) {\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n        var cy = this._private.cy || this;\n\n        if (!cy.styleEnabled()) {\n          return this;\n        }\n\n        for (var i = 0; i < all.length; i++) {\n          var ele = all[i];\n          var _p = ele._private;\n          var anis = _p.animation.current;\n\n          for (var j = 0; j < anis.length; j++) {\n            var ani = anis[j];\n            var ani_p = ani._private;\n\n            if (jumpToEnd) {\n              // next iteration of the animation loop, the animation\n              // will go straight to the end and be removed\n              ani_p.duration = 0;\n            }\n          } // clear the queue of future animations\n\n\n          if (clearQueue) {\n            _p.animation.queue = [];\n          }\n\n          if (!jumpToEnd) {\n            _p.animation.current = [];\n          }\n        } // we have to notify (the animation loop doesn't do it for us on `stop`)\n\n\n        cy.notify('draw');\n        return this;\n      };\n    } // stop\n\n  }; // define\n\n  /**\n   * Checks if `value` is classified as an `Array` object.\n   *\n   * @static\n   * @memberOf _\n   * @since 0.1.0\n   * @category Lang\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n   * @example\n   *\n   * _.isArray([1, 2, 3]);\n   * // => true\n   *\n   * _.isArray(document.body.children);\n   * // => false\n   *\n   * _.isArray('abc');\n   * // => false\n   *\n   * _.isArray(_.noop);\n   * // => false\n   */\n  var isArray = Array.isArray;\n\n  var isArray_1 = isArray;\n\n  /** Used to match property names within property paths. */\n  var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n      reIsPlainProp = /^\\w*$/;\n\n  /**\n   * Checks if `value` is a property name and not a property path.\n   *\n   * @private\n   * @param {*} value The value to check.\n   * @param {Object} [object] The object to query keys on.\n   * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n   */\n  function isKey(value, object) {\n    if (isArray_1(value)) {\n      return false;\n    }\n    var type = typeof value;\n    if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n        value == null || isSymbol_1(value)) {\n      return true;\n    }\n    return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n      (object != null && value in Object(object));\n  }\n\n  var _isKey = isKey;\n\n  /** `Object#toString` result references. */\n  var asyncTag = '[object AsyncFunction]',\n      funcTag = '[object Function]',\n      genTag = '[object GeneratorFunction]',\n      proxyTag = '[object Proxy]';\n\n  /**\n   * Checks if `value` is classified as a `Function` object.\n   *\n   * @static\n   * @memberOf _\n   * @since 0.1.0\n   * @category Lang\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n   * @example\n   *\n   * _.isFunction(_);\n   * // => true\n   *\n   * _.isFunction(/abc/);\n   * // => false\n   */\n  function isFunction(value) {\n    if (!isObject_1(value)) {\n      return false;\n    }\n    // The use of `Object#toString` avoids issues with the `typeof` operator\n    // in Safari 9 which returns 'object' for typed arrays and other constructors.\n    var tag = _baseGetTag(value);\n    return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n  }\n\n  var isFunction_1 = isFunction;\n\n  /** Used to detect overreaching core-js shims. */\n  var coreJsData = _root['__core-js_shared__'];\n\n  var _coreJsData = coreJsData;\n\n  /** Used to detect methods masquerading as native. */\n  var maskSrcKey = (function() {\n    var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');\n    return uid ? ('Symbol(src)_1.' + uid) : '';\n  }());\n\n  /**\n   * Checks if `func` has its source masked.\n   *\n   * @private\n   * @param {Function} func The function to check.\n   * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n   */\n  function isMasked(func) {\n    return !!maskSrcKey && (maskSrcKey in func);\n  }\n\n  var _isMasked = isMasked;\n\n  /** Used for built-in method references. */\n  var funcProto$1 = Function.prototype;\n\n  /** Used to resolve the decompiled source of functions. */\n  var funcToString$1 = funcProto$1.toString;\n\n  /**\n   * Converts `func` to its source code.\n   *\n   * @private\n   * @param {Function} func The function to convert.\n   * @returns {string} Returns the source code.\n   */\n  function toSource(func) {\n    if (func != null) {\n      try {\n        return funcToString$1.call(func);\n      } catch (e) {}\n      try {\n        return (func + '');\n      } catch (e) {}\n    }\n    return '';\n  }\n\n  var _toSource = toSource;\n\n  /**\n   * Used to match `RegExp`\n   * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n   */\n  var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n  /** Used to detect host constructors (Safari). */\n  var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n  /** Used for built-in method references. */\n  var funcProto = Function.prototype,\n      objectProto$3 = Object.prototype;\n\n  /** Used to resolve the decompiled source of functions. */\n  var funcToString = funcProto.toString;\n\n  /** Used to check objects for own properties. */\n  var hasOwnProperty$3 = objectProto$3.hasOwnProperty;\n\n  /** Used to detect if a method is native. */\n  var reIsNative = RegExp('^' +\n    funcToString.call(hasOwnProperty$3).replace(reRegExpChar, '\\\\$&')\n    .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n  );\n\n  /**\n   * The base implementation of `_.isNative` without bad shim checks.\n   *\n   * @private\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is a native function,\n   *  else `false`.\n   */\n  function baseIsNative(value) {\n    if (!isObject_1(value) || _isMasked(value)) {\n      return false;\n    }\n    var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;\n    return pattern.test(_toSource(value));\n  }\n\n  var _baseIsNative = baseIsNative;\n\n  /**\n   * Gets the value at `key` of `object`.\n   *\n   * @private\n   * @param {Object} [object] The object to query.\n   * @param {string} key The key of the property to get.\n   * @returns {*} Returns the property value.\n   */\n  function getValue$1(object, key) {\n    return object == null ? undefined : object[key];\n  }\n\n  var _getValue = getValue$1;\n\n  /**\n   * Gets the native function at `key` of `object`.\n   *\n   * @private\n   * @param {Object} object The object to query.\n   * @param {string} key The key of the method to get.\n   * @returns {*} Returns the function if it's native, else `undefined`.\n   */\n  function getNative(object, key) {\n    var value = _getValue(object, key);\n    return _baseIsNative(value) ? value : undefined;\n  }\n\n  var _getNative = getNative;\n\n  /* Built-in method references that are verified to be native. */\n  var nativeCreate = _getNative(Object, 'create');\n\n  var _nativeCreate = nativeCreate;\n\n  /**\n   * Removes all key-value entries from the hash.\n   *\n   * @private\n   * @name clear\n   * @memberOf Hash\n   */\n  function hashClear() {\n    this.__data__ = _nativeCreate ? _nativeCreate(null) : {};\n    this.size = 0;\n  }\n\n  var _hashClear = hashClear;\n\n  /**\n   * Removes `key` and its value from the hash.\n   *\n   * @private\n   * @name delete\n   * @memberOf Hash\n   * @param {Object} hash The hash to modify.\n   * @param {string} key The key of the value to remove.\n   * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n   */\n  function hashDelete(key) {\n    var result = this.has(key) && delete this.__data__[key];\n    this.size -= result ? 1 : 0;\n    return result;\n  }\n\n  var _hashDelete = hashDelete;\n\n  /** Used to stand-in for `undefined` hash values. */\n  var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';\n\n  /** Used for built-in method references. */\n  var objectProto$2 = Object.prototype;\n\n  /** Used to check objects for own properties. */\n  var hasOwnProperty$2 = objectProto$2.hasOwnProperty;\n\n  /**\n   * Gets the hash value for `key`.\n   *\n   * @private\n   * @name get\n   * @memberOf Hash\n   * @param {string} key The key of the value to get.\n   * @returns {*} Returns the entry value.\n   */\n  function hashGet(key) {\n    var data = this.__data__;\n    if (_nativeCreate) {\n      var result = data[key];\n      return result === HASH_UNDEFINED$1 ? undefined : result;\n    }\n    return hasOwnProperty$2.call(data, key) ? data[key] : undefined;\n  }\n\n  var _hashGet = hashGet;\n\n  /** Used for built-in method references. */\n  var objectProto$1 = Object.prototype;\n\n  /** Used to check objects for own properties. */\n  var hasOwnProperty$1 = objectProto$1.hasOwnProperty;\n\n  /**\n   * Checks if a hash value for `key` exists.\n   *\n   * @private\n   * @name has\n   * @memberOf Hash\n   * @param {string} key The key of the entry to check.\n   * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n   */\n  function hashHas(key) {\n    var data = this.__data__;\n    return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$1.call(data, key);\n  }\n\n  var _hashHas = hashHas;\n\n  /** Used to stand-in for `undefined` hash values. */\n  var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n  /**\n   * Sets the hash `key` to `value`.\n   *\n   * @private\n   * @name set\n   * @memberOf Hash\n   * @param {string} key The key of the value to set.\n   * @param {*} value The value to set.\n   * @returns {Object} Returns the hash instance.\n   */\n  function hashSet(key, value) {\n    var data = this.__data__;\n    this.size += this.has(key) ? 0 : 1;\n    data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n    return this;\n  }\n\n  var _hashSet = hashSet;\n\n  /**\n   * Creates a hash object.\n   *\n   * @private\n   * @constructor\n   * @param {Array} [entries] The key-value pairs to cache.\n   */\n  function Hash(entries) {\n    var index = -1,\n        length = entries == null ? 0 : entries.length;\n\n    this.clear();\n    while (++index < length) {\n      var entry = entries[index];\n      this.set(entry[0], entry[1]);\n    }\n  }\n\n  // Add methods to `Hash`.\n  Hash.prototype.clear = _hashClear;\n  Hash.prototype['delete'] = _hashDelete;\n  Hash.prototype.get = _hashGet;\n  Hash.prototype.has = _hashHas;\n  Hash.prototype.set = _hashSet;\n\n  var _Hash = Hash;\n\n  /**\n   * Removes all key-value entries from the list cache.\n   *\n   * @private\n   * @name clear\n   * @memberOf ListCache\n   */\n  function listCacheClear() {\n    this.__data__ = [];\n    this.size = 0;\n  }\n\n  var _listCacheClear = listCacheClear;\n\n  /**\n   * Performs a\n   * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n   * comparison between two values to determine if they are equivalent.\n   *\n   * @static\n   * @memberOf _\n   * @since 4.0.0\n   * @category Lang\n   * @param {*} value The value to compare.\n   * @param {*} other The other value to compare.\n   * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n   * @example\n   *\n   * var object = { 'a': 1 };\n   * var other = { 'a': 1 };\n   *\n   * _.eq(object, object);\n   * // => true\n   *\n   * _.eq(object, other);\n   * // => false\n   *\n   * _.eq('a', 'a');\n   * // => true\n   *\n   * _.eq('a', Object('a'));\n   * // => false\n   *\n   * _.eq(NaN, NaN);\n   * // => true\n   */\n  function eq(value, other) {\n    return value === other || (value !== value && other !== other);\n  }\n\n  var eq_1 = eq;\n\n  /**\n   * Gets the index at which the `key` is found in `array` of key-value pairs.\n   *\n   * @private\n   * @param {Array} array The array to inspect.\n   * @param {*} key The key to search for.\n   * @returns {number} Returns the index of the matched value, else `-1`.\n   */\n  function assocIndexOf(array, key) {\n    var length = array.length;\n    while (length--) {\n      if (eq_1(array[length][0], key)) {\n        return length;\n      }\n    }\n    return -1;\n  }\n\n  var _assocIndexOf = assocIndexOf;\n\n  /** Used for built-in method references. */\n  var arrayProto = Array.prototype;\n\n  /** Built-in value references. */\n  var splice = arrayProto.splice;\n\n  /**\n   * Removes `key` and its value from the list cache.\n   *\n   * @private\n   * @name delete\n   * @memberOf ListCache\n   * @param {string} key The key of the value to remove.\n   * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n   */\n  function listCacheDelete(key) {\n    var data = this.__data__,\n        index = _assocIndexOf(data, key);\n\n    if (index < 0) {\n      return false;\n    }\n    var lastIndex = data.length - 1;\n    if (index == lastIndex) {\n      data.pop();\n    } else {\n      splice.call(data, index, 1);\n    }\n    --this.size;\n    return true;\n  }\n\n  var _listCacheDelete = listCacheDelete;\n\n  /**\n   * Gets the list cache value for `key`.\n   *\n   * @private\n   * @name get\n   * @memberOf ListCache\n   * @param {string} key The key of the value to get.\n   * @returns {*} Returns the entry value.\n   */\n  function listCacheGet(key) {\n    var data = this.__data__,\n        index = _assocIndexOf(data, key);\n\n    return index < 0 ? undefined : data[index][1];\n  }\n\n  var _listCacheGet = listCacheGet;\n\n  /**\n   * Checks if a list cache value for `key` exists.\n   *\n   * @private\n   * @name has\n   * @memberOf ListCache\n   * @param {string} key The key of the entry to check.\n   * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n   */\n  function listCacheHas(key) {\n    return _assocIndexOf(this.__data__, key) > -1;\n  }\n\n  var _listCacheHas = listCacheHas;\n\n  /**\n   * Sets the list cache `key` to `value`.\n   *\n   * @private\n   * @name set\n   * @memberOf ListCache\n   * @param {string} key The key of the value to set.\n   * @param {*} value The value to set.\n   * @returns {Object} Returns the list cache instance.\n   */\n  function listCacheSet(key, value) {\n    var data = this.__data__,\n        index = _assocIndexOf(data, key);\n\n    if (index < 0) {\n      ++this.size;\n      data.push([key, value]);\n    } else {\n      data[index][1] = value;\n    }\n    return this;\n  }\n\n  var _listCacheSet = listCacheSet;\n\n  /**\n   * Creates an list cache object.\n   *\n   * @private\n   * @constructor\n   * @param {Array} [entries] The key-value pairs to cache.\n   */\n  function ListCache(entries) {\n    var index = -1,\n        length = entries == null ? 0 : entries.length;\n\n    this.clear();\n    while (++index < length) {\n      var entry = entries[index];\n      this.set(entry[0], entry[1]);\n    }\n  }\n\n  // Add methods to `ListCache`.\n  ListCache.prototype.clear = _listCacheClear;\n  ListCache.prototype['delete'] = _listCacheDelete;\n  ListCache.prototype.get = _listCacheGet;\n  ListCache.prototype.has = _listCacheHas;\n  ListCache.prototype.set = _listCacheSet;\n\n  var _ListCache = ListCache;\n\n  /* Built-in method references that are verified to be native. */\n  var Map$1 = _getNative(_root, 'Map');\n\n  var _Map = Map$1;\n\n  /**\n   * Removes all key-value entries from the map.\n   *\n   * @private\n   * @name clear\n   * @memberOf MapCache\n   */\n  function mapCacheClear() {\n    this.size = 0;\n    this.__data__ = {\n      'hash': new _Hash,\n      'map': new (_Map || _ListCache),\n      'string': new _Hash\n    };\n  }\n\n  var _mapCacheClear = mapCacheClear;\n\n  /**\n   * Checks if `value` is suitable for use as unique object key.\n   *\n   * @private\n   * @param {*} value The value to check.\n   * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n   */\n  function isKeyable(value) {\n    var type = typeof value;\n    return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n      ? (value !== '__proto__')\n      : (value === null);\n  }\n\n  var _isKeyable = isKeyable;\n\n  /**\n   * Gets the data for `map`.\n   *\n   * @private\n   * @param {Object} map The map to query.\n   * @param {string} key The reference key.\n   * @returns {*} Returns the map data.\n   */\n  function getMapData(map, key) {\n    var data = map.__data__;\n    return _isKeyable(key)\n      ? data[typeof key == 'string' ? 'string' : 'hash']\n      : data.map;\n  }\n\n  var _getMapData = getMapData;\n\n  /**\n   * Removes `key` and its value from the map.\n   *\n   * @private\n   * @name delete\n   * @memberOf MapCache\n   * @param {string} key The key of the value to remove.\n   * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n   */\n  function mapCacheDelete(key) {\n    var result = _getMapData(this, key)['delete'](key);\n    this.size -= result ? 1 : 0;\n    return result;\n  }\n\n  var _mapCacheDelete = mapCacheDelete;\n\n  /**\n   * Gets the map value for `key`.\n   *\n   * @private\n   * @name get\n   * @memberOf MapCache\n   * @param {string} key The key of the value to get.\n   * @returns {*} Returns the entry value.\n   */\n  function mapCacheGet(key) {\n    return _getMapData(this, key).get(key);\n  }\n\n  var _mapCacheGet = mapCacheGet;\n\n  /**\n   * Checks if a map value for `key` exists.\n   *\n   * @private\n   * @name has\n   * @memberOf MapCache\n   * @param {string} key The key of the entry to check.\n   * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n   */\n  function mapCacheHas(key) {\n    return _getMapData(this, key).has(key);\n  }\n\n  var _mapCacheHas = mapCacheHas;\n\n  /**\n   * Sets the map `key` to `value`.\n   *\n   * @private\n   * @name set\n   * @memberOf MapCache\n   * @param {string} key The key of the value to set.\n   * @param {*} value The value to set.\n   * @returns {Object} Returns the map cache instance.\n   */\n  function mapCacheSet(key, value) {\n    var data = _getMapData(this, key),\n        size = data.size;\n\n    data.set(key, value);\n    this.size += data.size == size ? 0 : 1;\n    return this;\n  }\n\n  var _mapCacheSet = mapCacheSet;\n\n  /**\n   * Creates a map cache object to store key-value pairs.\n   *\n   * @private\n   * @constructor\n   * @param {Array} [entries] The key-value pairs to cache.\n   */\n  function MapCache(entries) {\n    var index = -1,\n        length = entries == null ? 0 : entries.length;\n\n    this.clear();\n    while (++index < length) {\n      var entry = entries[index];\n      this.set(entry[0], entry[1]);\n    }\n  }\n\n  // Add methods to `MapCache`.\n  MapCache.prototype.clear = _mapCacheClear;\n  MapCache.prototype['delete'] = _mapCacheDelete;\n  MapCache.prototype.get = _mapCacheGet;\n  MapCache.prototype.has = _mapCacheHas;\n  MapCache.prototype.set = _mapCacheSet;\n\n  var _MapCache = MapCache;\n\n  /** Error message constants. */\n  var FUNC_ERROR_TEXT = 'Expected a function';\n\n  /**\n   * Creates a function that memoizes the result of `func`. If `resolver` is\n   * provided, it determines the cache key for storing the result based on the\n   * arguments provided to the memoized function. By default, the first argument\n   * provided to the memoized function is used as the map cache key. The `func`\n   * is invoked with the `this` binding of the memoized function.\n   *\n   * **Note:** The cache is exposed as the `cache` property on the memoized\n   * function. Its creation may be customized by replacing the `_.memoize.Cache`\n   * constructor with one whose instances implement the\n   * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n   * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n   *\n   * @static\n   * @memberOf _\n   * @since 0.1.0\n   * @category Function\n   * @param {Function} func The function to have its output memoized.\n   * @param {Function} [resolver] The function to resolve the cache key.\n   * @returns {Function} Returns the new memoized function.\n   * @example\n   *\n   * var object = { 'a': 1, 'b': 2 };\n   * var other = { 'c': 3, 'd': 4 };\n   *\n   * var values = _.memoize(_.values);\n   * values(object);\n   * // => [1, 2]\n   *\n   * values(other);\n   * // => [3, 4]\n   *\n   * object.a = 2;\n   * values(object);\n   * // => [1, 2]\n   *\n   * // Modify the result cache.\n   * values.cache.set(object, ['a', 'b']);\n   * values(object);\n   * // => ['a', 'b']\n   *\n   * // Replace `_.memoize.Cache`.\n   * _.memoize.Cache = WeakMap;\n   */\n  function memoize(func, resolver) {\n    if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n      throw new TypeError(FUNC_ERROR_TEXT);\n    }\n    var memoized = function() {\n      var args = arguments,\n          key = resolver ? resolver.apply(this, args) : args[0],\n          cache = memoized.cache;\n\n      if (cache.has(key)) {\n        return cache.get(key);\n      }\n      var result = func.apply(this, args);\n      memoized.cache = cache.set(key, result) || cache;\n      return result;\n    };\n    memoized.cache = new (memoize.Cache || _MapCache);\n    return memoized;\n  }\n\n  // Expose `MapCache`.\n  memoize.Cache = _MapCache;\n\n  var memoize_1 = memoize;\n\n  /** Used as the maximum memoize cache size. */\n  var MAX_MEMOIZE_SIZE = 500;\n\n  /**\n   * A specialized version of `_.memoize` which clears the memoized function's\n   * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n   *\n   * @private\n   * @param {Function} func The function to have its output memoized.\n   * @returns {Function} Returns the new memoized function.\n   */\n  function memoizeCapped(func) {\n    var result = memoize_1(func, function(key) {\n      if (cache.size === MAX_MEMOIZE_SIZE) {\n        cache.clear();\n      }\n      return key;\n    });\n\n    var cache = result.cache;\n    return result;\n  }\n\n  var _memoizeCapped = memoizeCapped;\n\n  /** Used to match property names within property paths. */\n  var rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n  /** Used to match backslashes in property paths. */\n  var reEscapeChar = /\\\\(\\\\)?/g;\n\n  /**\n   * Converts `string` to a property path array.\n   *\n   * @private\n   * @param {string} string The string to convert.\n   * @returns {Array} Returns the property path array.\n   */\n  var stringToPath = _memoizeCapped(function(string) {\n    var result = [];\n    if (string.charCodeAt(0) === 46 /* . */) {\n      result.push('');\n    }\n    string.replace(rePropName, function(match, number, quote, subString) {\n      result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n    });\n    return result;\n  });\n\n  var _stringToPath = stringToPath;\n\n  /**\n   * A specialized version of `_.map` for arrays without support for iteratee\n   * shorthands.\n   *\n   * @private\n   * @param {Array} [array] The array to iterate over.\n   * @param {Function} iteratee The function invoked per iteration.\n   * @returns {Array} Returns the new mapped array.\n   */\n  function arrayMap(array, iteratee) {\n    var index = -1,\n        length = array == null ? 0 : array.length,\n        result = Array(length);\n\n    while (++index < length) {\n      result[index] = iteratee(array[index], index, array);\n    }\n    return result;\n  }\n\n  var _arrayMap = arrayMap;\n\n  /** Used as references for various `Number` constants. */\n  var INFINITY$1 = 1 / 0;\n\n  /** Used to convert symbols to primitives and strings. */\n  var symbolProto = _Symbol ? _Symbol.prototype : undefined,\n      symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n  /**\n   * The base implementation of `_.toString` which doesn't convert nullish\n   * values to empty strings.\n   *\n   * @private\n   * @param {*} value The value to process.\n   * @returns {string} Returns the string.\n   */\n  function baseToString(value) {\n    // Exit early for strings to avoid a performance hit in some environments.\n    if (typeof value == 'string') {\n      return value;\n    }\n    if (isArray_1(value)) {\n      // Recursively convert values (susceptible to call stack limits).\n      return _arrayMap(value, baseToString) + '';\n    }\n    if (isSymbol_1(value)) {\n      return symbolToString ? symbolToString.call(value) : '';\n    }\n    var result = (value + '');\n    return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;\n  }\n\n  var _baseToString = baseToString;\n\n  /**\n   * Converts `value` to a string. An empty string is returned for `null`\n   * and `undefined` values. The sign of `-0` is preserved.\n   *\n   * @static\n   * @memberOf _\n   * @since 4.0.0\n   * @category Lang\n   * @param {*} value The value to convert.\n   * @returns {string} Returns the converted string.\n   * @example\n   *\n   * _.toString(null);\n   * // => ''\n   *\n   * _.toString(-0);\n   * // => '-0'\n   *\n   * _.toString([1, 2, 3]);\n   * // => '1,2,3'\n   */\n  function toString$1(value) {\n    return value == null ? '' : _baseToString(value);\n  }\n\n  var toString_1 = toString$1;\n\n  /**\n   * Casts `value` to a path array if it's not one.\n   *\n   * @private\n   * @param {*} value The value to inspect.\n   * @param {Object} [object] The object to query keys on.\n   * @returns {Array} Returns the cast property path array.\n   */\n  function castPath(value, object) {\n    if (isArray_1(value)) {\n      return value;\n    }\n    return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));\n  }\n\n  var _castPath = castPath;\n\n  /** Used as references for various `Number` constants. */\n  var INFINITY = 1 / 0;\n\n  /**\n   * Converts `value` to a string key if it's not a string or symbol.\n   *\n   * @private\n   * @param {*} value The value to inspect.\n   * @returns {string|symbol} Returns the key.\n   */\n  function toKey(value) {\n    if (typeof value == 'string' || isSymbol_1(value)) {\n      return value;\n    }\n    var result = (value + '');\n    return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n  }\n\n  var _toKey = toKey;\n\n  /**\n   * The base implementation of `_.get` without support for default values.\n   *\n   * @private\n   * @param {Object} object The object to query.\n   * @param {Array|string} path The path of the property to get.\n   * @returns {*} Returns the resolved value.\n   */\n  function baseGet(object, path) {\n    path = _castPath(path, object);\n\n    var index = 0,\n        length = path.length;\n\n    while (object != null && index < length) {\n      object = object[_toKey(path[index++])];\n    }\n    return (index && index == length) ? object : undefined;\n  }\n\n  var _baseGet = baseGet;\n\n  /**\n   * Gets the value at `path` of `object`. If the resolved value is\n   * `undefined`, the `defaultValue` is returned in its place.\n   *\n   * @static\n   * @memberOf _\n   * @since 3.7.0\n   * @category Object\n   * @param {Object} object The object to query.\n   * @param {Array|string} path The path of the property to get.\n   * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n   * @returns {*} Returns the resolved value.\n   * @example\n   *\n   * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n   *\n   * _.get(object, 'a[0].b.c');\n   * // => 3\n   *\n   * _.get(object, ['a', '0', 'b', 'c']);\n   * // => 3\n   *\n   * _.get(object, 'a.b.c', 'default');\n   * // => 'default'\n   */\n  function get(object, path, defaultValue) {\n    var result = object == null ? undefined : _baseGet(object, path);\n    return result === undefined ? defaultValue : result;\n  }\n\n  var get_1 = get;\n\n  var defineProperty = (function() {\n    try {\n      var func = _getNative(Object, 'defineProperty');\n      func({}, '', {});\n      return func;\n    } catch (e) {}\n  }());\n\n  var _defineProperty = defineProperty;\n\n  /**\n   * The base implementation of `assignValue` and `assignMergeValue` without\n   * value checks.\n   *\n   * @private\n   * @param {Object} object The object to modify.\n   * @param {string} key The key of the property to assign.\n   * @param {*} value The value to assign.\n   */\n  function baseAssignValue(object, key, value) {\n    if (key == '__proto__' && _defineProperty) {\n      _defineProperty(object, key, {\n        'configurable': true,\n        'enumerable': true,\n        'value': value,\n        'writable': true\n      });\n    } else {\n      object[key] = value;\n    }\n  }\n\n  var _baseAssignValue = baseAssignValue;\n\n  /** Used for built-in method references. */\n  var objectProto = Object.prototype;\n\n  /** Used to check objects for own properties. */\n  var hasOwnProperty = objectProto.hasOwnProperty;\n\n  /**\n   * Assigns `value` to `key` of `object` if the existing value is not equivalent\n   * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n   * for equality comparisons.\n   *\n   * @private\n   * @param {Object} object The object to modify.\n   * @param {string} key The key of the property to assign.\n   * @param {*} value The value to assign.\n   */\n  function assignValue(object, key, value) {\n    var objValue = object[key];\n    if (!(hasOwnProperty.call(object, key) && eq_1(objValue, value)) ||\n        (value === undefined && !(key in object))) {\n      _baseAssignValue(object, key, value);\n    }\n  }\n\n  var _assignValue = assignValue;\n\n  /** Used as references for various `Number` constants. */\n  var MAX_SAFE_INTEGER = 9007199254740991;\n\n  /** Used to detect unsigned integer values. */\n  var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n  /**\n   * Checks if `value` is a valid array-like index.\n   *\n   * @private\n   * @param {*} value The value to check.\n   * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n   * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n   */\n  function isIndex(value, length) {\n    var type = typeof value;\n    length = length == null ? MAX_SAFE_INTEGER : length;\n\n    return !!length &&\n      (type == 'number' ||\n        (type != 'symbol' && reIsUint.test(value))) &&\n          (value > -1 && value % 1 == 0 && value < length);\n  }\n\n  var _isIndex = isIndex;\n\n  /**\n   * The base implementation of `_.set`.\n   *\n   * @private\n   * @param {Object} object The object to modify.\n   * @param {Array|string} path The path of the property to set.\n   * @param {*} value The value to set.\n   * @param {Function} [customizer] The function to customize path creation.\n   * @returns {Object} Returns `object`.\n   */\n  function baseSet(object, path, value, customizer) {\n    if (!isObject_1(object)) {\n      return object;\n    }\n    path = _castPath(path, object);\n\n    var index = -1,\n        length = path.length,\n        lastIndex = length - 1,\n        nested = object;\n\n    while (nested != null && ++index < length) {\n      var key = _toKey(path[index]),\n          newValue = value;\n\n      if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n        return object;\n      }\n\n      if (index != lastIndex) {\n        var objValue = nested[key];\n        newValue = customizer ? customizer(objValue, key, nested) : undefined;\n        if (newValue === undefined) {\n          newValue = isObject_1(objValue)\n            ? objValue\n            : (_isIndex(path[index + 1]) ? [] : {});\n        }\n      }\n      _assignValue(nested, key, newValue);\n      nested = nested[key];\n    }\n    return object;\n  }\n\n  var _baseSet = baseSet;\n\n  /**\n   * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n   * it's created. Arrays are created for missing index properties while objects\n   * are created for all other missing properties. Use `_.setWith` to customize\n   * `path` creation.\n   *\n   * **Note:** This method mutates `object`.\n   *\n   * @static\n   * @memberOf _\n   * @since 3.7.0\n   * @category Object\n   * @param {Object} object The object to modify.\n   * @param {Array|string} path The path of the property to set.\n   * @param {*} value The value to set.\n   * @returns {Object} Returns `object`.\n   * @example\n   *\n   * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n   *\n   * _.set(object, 'a[0].b.c', 4);\n   * console.log(object.a[0].b.c);\n   * // => 4\n   *\n   * _.set(object, ['x', '0', 'y', 'z'], 5);\n   * console.log(object.x[0].y.z);\n   * // => 5\n   */\n  function set(object, path, value) {\n    return object == null ? object : _baseSet(object, path, value);\n  }\n\n  var set_1 = set;\n\n  /**\n   * Copies the values of `source` to `array`.\n   *\n   * @private\n   * @param {Array} source The array to copy values from.\n   * @param {Array} [array=[]] The array to copy values to.\n   * @returns {Array} Returns `array`.\n   */\n  function copyArray(source, array) {\n    var index = -1,\n        length = source.length;\n\n    array || (array = Array(length));\n    while (++index < length) {\n      array[index] = source[index];\n    }\n    return array;\n  }\n\n  var _copyArray = copyArray;\n\n  /**\n   * Converts `value` to a property path array.\n   *\n   * @static\n   * @memberOf _\n   * @since 4.0.0\n   * @category Util\n   * @param {*} value The value to convert.\n   * @returns {Array} Returns the new property path array.\n   * @example\n   *\n   * _.toPath('a.b.c');\n   * // => ['a', 'b', 'c']\n   *\n   * _.toPath('a[0].b.c');\n   * // => ['a', '0', 'b', 'c']\n   */\n  function toPath(value) {\n    if (isArray_1(value)) {\n      return _arrayMap(value, _toKey);\n    }\n    return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));\n  }\n\n  var toPath_1 = toPath;\n\n  var define$2 = {\n    // access data field\n    data: function data(params) {\n      var defaults = {\n        field: 'data',\n        bindingEvent: 'data',\n        allowBinding: false,\n        allowSetting: false,\n        allowGetting: false,\n        settingEvent: 'data',\n        settingTriggersEvent: false,\n        triggerFnName: 'trigger',\n        immutableKeys: {},\n        // key => true if immutable\n        updateStyle: false,\n        beforeGet: function beforeGet(self) {},\n        beforeSet: function beforeSet(self, obj) {},\n        onSet: function onSet(self) {},\n        canSet: function canSet(self) {\n          return true;\n        }\n      };\n      params = extend({}, defaults, params);\n      return function dataImpl(name, value) {\n        var p = params;\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n\n        var single = selfIsArrayLike ? self[0] : self; // .data('foo', ...)\n\n        if (string(name)) {\n          // set or get property\n          var isPathLike = name.indexOf('.') !== -1; // there might be a normal field with a dot \n\n          var path = isPathLike && toPath_1(name); // .data('foo')\n\n          if (p.allowGetting && value === undefined) {\n            // get\n            var ret;\n\n            if (single) {\n              p.beforeGet(single); // check if it's path and a field with the same name doesn't exist\n\n              if (path && single._private[p.field][name] === undefined) {\n                ret = get_1(single._private[p.field], path);\n              } else {\n                ret = single._private[p.field][name];\n              }\n            }\n\n            return ret; // .data('foo', 'bar')\n          } else if (p.allowSetting && value !== undefined) {\n            // set\n            var valid = !p.immutableKeys[name];\n\n            if (valid) {\n              var change = _defineProperty$1({}, name, value);\n\n              p.beforeSet(self, change);\n\n              for (var i = 0, l = all.length; i < l; i++) {\n                var ele = all[i];\n\n                if (p.canSet(ele)) {\n                  if (path && single._private[p.field][name] === undefined) {\n                    set_1(ele._private[p.field], path, value);\n                  } else {\n                    ele._private[p.field][name] = value;\n                  }\n                }\n              } // update mappers if asked\n\n\n              if (p.updateStyle) {\n                self.updateStyle();\n              } // call onSet callback\n\n\n              p.onSet(self);\n\n              if (p.settingTriggersEvent) {\n                self[p.triggerFnName](p.settingEvent);\n              }\n            }\n          } // .data({ 'foo': 'bar' })\n\n        } else if (p.allowSetting && plainObject(name)) {\n          // extend\n          var obj = name;\n          var k, v;\n          var keys = Object.keys(obj);\n          p.beforeSet(self, obj);\n\n          for (var _i = 0; _i < keys.length; _i++) {\n            k = keys[_i];\n            v = obj[k];\n\n            var _valid = !p.immutableKeys[k];\n\n            if (_valid) {\n              for (var j = 0; j < all.length; j++) {\n                var _ele = all[j];\n\n                if (p.canSet(_ele)) {\n                  _ele._private[p.field][k] = v;\n                }\n              }\n            }\n          } // update mappers if asked\n\n\n          if (p.updateStyle) {\n            self.updateStyle();\n          } // call onSet callback\n\n\n          p.onSet(self);\n\n          if (p.settingTriggersEvent) {\n            self[p.triggerFnName](p.settingEvent);\n          } // .data(function(){ ... })\n\n        } else if (p.allowBinding && fn$6(name)) {\n          // bind to event\n          var fn = name;\n          self.on(p.bindingEvent, fn); // .data()\n        } else if (p.allowGetting && name === undefined) {\n          // get whole object\n          var _ret;\n\n          if (single) {\n            p.beforeGet(single);\n            _ret = single._private[p.field];\n          }\n\n          return _ret;\n        }\n\n        return self; // maintain chainability\n      }; // function\n    },\n    // data\n    // remove data field\n    removeData: function removeData(params) {\n      var defaults = {\n        field: 'data',\n        event: 'data',\n        triggerFnName: 'trigger',\n        triggerEvent: false,\n        immutableKeys: {} // key => true if immutable\n\n      };\n      params = extend({}, defaults, params);\n      return function removeDataImpl(names) {\n        var p = params;\n        var self = this;\n        var selfIsArrayLike = self.length !== undefined;\n        var all = selfIsArrayLike ? self : [self]; // put in array if not array-like\n        // .removeData('foo bar')\n\n        if (string(names)) {\n          // then get the list of keys, and delete them\n          var keys = names.split(/\\s+/);\n          var l = keys.length;\n\n          for (var i = 0; i < l; i++) {\n            // delete each non-empty key\n            var key = keys[i];\n\n            if (emptyString(key)) {\n              continue;\n            }\n\n            var valid = !p.immutableKeys[key]; // not valid if immutable\n\n            if (valid) {\n              for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {\n                all[i_a]._private[p.field][key] = undefined;\n              }\n            }\n          }\n\n          if (p.triggerEvent) {\n            self[p.triggerFnName](p.event);\n          } // .removeData()\n\n        } else if (names === undefined) {\n          // then delete all keys\n          for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {\n            var _privateFields = all[_i_a]._private[p.field];\n\n            var _keys = Object.keys(_privateFields);\n\n            for (var _i2 = 0; _i2 < _keys.length; _i2++) {\n              var _key = _keys[_i2];\n              var validKeyToDelete = !p.immutableKeys[_key];\n\n              if (validKeyToDelete) {\n                _privateFields[_key] = undefined;\n              }\n            }\n          }\n\n          if (p.triggerEvent) {\n            self[p.triggerFnName](p.event);\n          }\n        }\n\n        return self; // maintain chaining\n      }; // function\n    } // removeData\n\n  }; // define\n\n  var define$1 = {\n    eventAliasesOn: function eventAliasesOn(proto) {\n      var p = proto;\n      p.addListener = p.listen = p.bind = p.on;\n      p.unlisten = p.unbind = p.off = p.removeListener;\n      p.trigger = p.emit; // this is just a wrapper alias of .on()\n\n      p.pon = p.promiseOn = function (events, selector) {\n        var self = this;\n        var args = Array.prototype.slice.call(arguments, 0);\n        return new Promise$1(function (resolve, reject) {\n          var callback = function callback(e) {\n            self.off.apply(self, offArgs);\n            resolve(e);\n          };\n\n          var onArgs = args.concat([callback]);\n          var offArgs = onArgs.concat([]);\n          self.on.apply(self, onArgs);\n        });\n      };\n    }\n  }; // define\n\n  // use this module to cherry pick functions into your prototype\n  var define = {};\n  [define$3, define$2, define$1].forEach(function (m) {\n    extend(define, m);\n  });\n\n  var elesfn$i = {\n    animate: define.animate(),\n    animation: define.animation(),\n    animated: define.animated(),\n    clearQueue: define.clearQueue(),\n    delay: define.delay(),\n    delayAnimation: define.delayAnimation(),\n    stop: define.stop()\n  };\n\n  var elesfn$h = {\n    classes: function classes(_classes) {\n      var self = this;\n\n      if (_classes === undefined) {\n        var ret = [];\n\n        self[0]._private.classes.forEach(function (cls) {\n          return ret.push(cls);\n        });\n\n        return ret;\n      } else if (!array(_classes)) {\n        // extract classes from string\n        _classes = (_classes || '').match(/\\S+/g) || [];\n      }\n\n      var changed = [];\n      var classesSet = new Set$1(_classes); // check and update each ele\n\n      for (var j = 0; j < self.length; j++) {\n        var ele = self[j];\n        var _p = ele._private;\n        var eleClasses = _p.classes;\n        var changedEle = false; // check if ele has all of the passed classes\n\n        for (var i = 0; i < _classes.length; i++) {\n          var cls = _classes[i];\n          var eleHasClass = eleClasses.has(cls);\n\n          if (!eleHasClass) {\n            changedEle = true;\n            break;\n          }\n        } // check if ele has classes outside of those passed\n\n\n        if (!changedEle) {\n          changedEle = eleClasses.size !== _classes.length;\n        }\n\n        if (changedEle) {\n          _p.classes = classesSet;\n          changed.push(ele);\n        }\n      } // trigger update style on those eles that had class changes\n\n\n      if (changed.length > 0) {\n        this.spawn(changed).updateStyle().emit('class');\n      }\n\n      return self;\n    },\n    addClass: function addClass(classes) {\n      return this.toggleClass(classes, true);\n    },\n    hasClass: function hasClass(className) {\n      var ele = this[0];\n      return ele != null && ele._private.classes.has(className);\n    },\n    toggleClass: function toggleClass(classes, toggle) {\n      if (!array(classes)) {\n        // extract classes from string\n        classes = classes.match(/\\S+/g) || [];\n      }\n\n      var self = this;\n      var toggleUndefd = toggle === undefined;\n      var changed = []; // eles who had classes changed\n\n      for (var i = 0, il = self.length; i < il; i++) {\n        var ele = self[i];\n        var eleClasses = ele._private.classes;\n        var changedEle = false;\n\n        for (var j = 0; j < classes.length; j++) {\n          var cls = classes[j];\n          var hasClass = eleClasses.has(cls);\n          var changedNow = false;\n\n          if (toggle || toggleUndefd && !hasClass) {\n            eleClasses.add(cls);\n            changedNow = true;\n          } else if (!toggle || toggleUndefd && hasClass) {\n            eleClasses[\"delete\"](cls);\n            changedNow = true;\n          }\n\n          if (!changedEle && changedNow) {\n            changed.push(ele);\n            changedEle = true;\n          }\n        } // for j classes\n\n      } // for i eles\n      // trigger update style on those eles that had class changes\n\n\n      if (changed.length > 0) {\n        this.spawn(changed).updateStyle().emit('class');\n      }\n\n      return self;\n    },\n    removeClass: function removeClass(classes) {\n      return this.toggleClass(classes, false);\n    },\n    flashClass: function flashClass(classes, duration) {\n      var self = this;\n\n      if (duration == null) {\n        duration = 250;\n      } else if (duration === 0) {\n        return self; // nothing to do really\n      }\n\n      self.addClass(classes);\n      setTimeout(function () {\n        self.removeClass(classes);\n      }, duration);\n      return self;\n    }\n  };\n  elesfn$h.className = elesfn$h.classNames = elesfn$h.classes;\n\n  var tokens = {\n    metaChar: '[\\\\!\\\\\"\\\\#\\\\$\\\\%\\\\&\\\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\.\\\\/\\\\:\\\\;\\\\<\\\\=\\\\>\\\\?\\\\@\\\\[\\\\]\\\\^\\\\`\\\\{\\\\|\\\\}\\\\~]',\n    // chars we need to escape in let names, etc\n    comparatorOp: '=|\\\\!=|>|>=|<|<=|\\\\$=|\\\\^=|\\\\*=',\n    // binary comparison op (used in data selectors)\n    boolOp: '\\\\?|\\\\!|\\\\^',\n    // boolean (unary) operators (used in data selectors)\n    string: '\"(?:\\\\\\\\\"|[^\"])*\"' + '|' + \"'(?:\\\\\\\\'|[^'])*'\",\n    // string literals (used in data selectors) -- doublequotes | singlequotes\n    number: number,\n    // number literal (used in data selectors) --- e.g. 0.1234, 1234, 12e123\n    meta: 'degree|indegree|outdegree',\n    // allowed metadata fields (i.e. allowed functions to use from Collection)\n    separator: '\\\\s*,\\\\s*',\n    // queries are separated by commas, e.g. edge[foo = 'bar'], node.someClass\n    descendant: '\\\\s+',\n    child: '\\\\s+>\\\\s+',\n    subject: '\\\\$',\n    group: 'node|edge|\\\\*',\n    directedEdge: '\\\\s+->\\\\s+',\n    undirectedEdge: '\\\\s+<->\\\\s+'\n  };\n  tokens.variable = '(?:[\\\\w-.]|(?:\\\\\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods\n\n  tokens.className = '(?:[\\\\w-]|(?:\\\\\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name\n\n  tokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number\n\n  tokens.id = tokens.variable; // an element id (follows variable conventions)\n\n  (function () {\n    var ops, op, i; // add @ variants to comparatorOp\n\n    ops = tokens.comparatorOp.split('|');\n\n    for (i = 0; i < ops.length; i++) {\n      op = ops[i];\n      tokens.comparatorOp += '|@' + op;\n    } // add ! variants to comparatorOp\n\n\n    ops = tokens.comparatorOp.split('|');\n\n    for (i = 0; i < ops.length; i++) {\n      op = ops[i];\n\n      if (op.indexOf('!') >= 0) {\n        continue;\n      } // skip ops that explicitly contain !\n\n\n      if (op === '=') {\n        continue;\n      } // skip = b/c != is explicitly defined\n\n\n      tokens.comparatorOp += '|\\\\!' + op;\n    }\n  })();\n\n  /**\n   * Make a new query object\n   *\n   * @prop type {Type} The type enum (int) of the query\n   * @prop checks List of checks to make against an ele to test for a match\n   */\n  var newQuery = function newQuery() {\n    return {\n      checks: []\n    };\n  };\n\n  /**\n   * A check type enum-like object.  Uses integer values for fast match() lookup.\n   * The ordering does not matter as long as the ints are unique.\n   */\n  var Type = {\n    /** E.g. node */\n    GROUP: 0,\n\n    /** A collection of elements */\n    COLLECTION: 1,\n\n    /** A filter(ele) function */\n    FILTER: 2,\n\n    /** E.g. [foo > 1] */\n    DATA_COMPARE: 3,\n\n    /** E.g. [foo] */\n    DATA_EXIST: 4,\n\n    /** E.g. [?foo] */\n    DATA_BOOL: 5,\n\n    /** E.g. [[degree > 2]] */\n    META_COMPARE: 6,\n\n    /** E.g. :selected */\n    STATE: 7,\n\n    /** E.g. #foo */\n    ID: 8,\n\n    /** E.g. .foo */\n    CLASS: 9,\n\n    /** E.g. #foo <-> #bar */\n    UNDIRECTED_EDGE: 10,\n\n    /** E.g. #foo -> #bar */\n    DIRECTED_EDGE: 11,\n\n    /** E.g. $#foo -> #bar */\n    NODE_SOURCE: 12,\n\n    /** E.g. #foo -> $#bar */\n    NODE_TARGET: 13,\n\n    /** E.g. $#foo <-> #bar */\n    NODE_NEIGHBOR: 14,\n\n    /** E.g. #foo > #bar */\n    CHILD: 15,\n\n    /** E.g. #foo #bar */\n    DESCENDANT: 16,\n\n    /** E.g. $#foo > #bar */\n    PARENT: 17,\n\n    /** E.g. $#foo #bar */\n    ANCESTOR: 18,\n\n    /** E.g. #foo > $bar > #baz */\n    COMPOUND_SPLIT: 19,\n\n    /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */\n    TRUE: 20\n  };\n\n  var stateSelectors = [{\n    selector: ':selected',\n    matches: function matches(ele) {\n      return ele.selected();\n    }\n  }, {\n    selector: ':unselected',\n    matches: function matches(ele) {\n      return !ele.selected();\n    }\n  }, {\n    selector: ':selectable',\n    matches: function matches(ele) {\n      return ele.selectable();\n    }\n  }, {\n    selector: ':unselectable',\n    matches: function matches(ele) {\n      return !ele.selectable();\n    }\n  }, {\n    selector: ':locked',\n    matches: function matches(ele) {\n      return ele.locked();\n    }\n  }, {\n    selector: ':unlocked',\n    matches: function matches(ele) {\n      return !ele.locked();\n    }\n  }, {\n    selector: ':visible',\n    matches: function matches(ele) {\n      return ele.visible();\n    }\n  }, {\n    selector: ':hidden',\n    matches: function matches(ele) {\n      return !ele.visible();\n    }\n  }, {\n    selector: ':transparent',\n    matches: function matches(ele) {\n      return ele.transparent();\n    }\n  }, {\n    selector: ':grabbed',\n    matches: function matches(ele) {\n      return ele.grabbed();\n    }\n  }, {\n    selector: ':free',\n    matches: function matches(ele) {\n      return !ele.grabbed();\n    }\n  }, {\n    selector: ':removed',\n    matches: function matches(ele) {\n      return ele.removed();\n    }\n  }, {\n    selector: ':inside',\n    matches: function matches(ele) {\n      return !ele.removed();\n    }\n  }, {\n    selector: ':grabbable',\n    matches: function matches(ele) {\n      return ele.grabbable();\n    }\n  }, {\n    selector: ':ungrabbable',\n    matches: function matches(ele) {\n      return !ele.grabbable();\n    }\n  }, {\n    selector: ':animated',\n    matches: function matches(ele) {\n      return ele.animated();\n    }\n  }, {\n    selector: ':unanimated',\n    matches: function matches(ele) {\n      return !ele.animated();\n    }\n  }, {\n    selector: ':parent',\n    matches: function matches(ele) {\n      return ele.isParent();\n    }\n  }, {\n    selector: ':childless',\n    matches: function matches(ele) {\n      return ele.isChildless();\n    }\n  }, {\n    selector: ':child',\n    matches: function matches(ele) {\n      return ele.isChild();\n    }\n  }, {\n    selector: ':orphan',\n    matches: function matches(ele) {\n      return ele.isOrphan();\n    }\n  }, {\n    selector: ':nonorphan',\n    matches: function matches(ele) {\n      return ele.isChild();\n    }\n  }, {\n    selector: ':compound',\n    matches: function matches(ele) {\n      if (ele.isNode()) {\n        return ele.isParent();\n      } else {\n        return ele.source().isParent() || ele.target().isParent();\n      }\n    }\n  }, {\n    selector: ':loop',\n    matches: function matches(ele) {\n      return ele.isLoop();\n    }\n  }, {\n    selector: ':simple',\n    matches: function matches(ele) {\n      return ele.isSimple();\n    }\n  }, {\n    selector: ':active',\n    matches: function matches(ele) {\n      return ele.active();\n    }\n  }, {\n    selector: ':inactive',\n    matches: function matches(ele) {\n      return !ele.active();\n    }\n  }, {\n    selector: ':backgrounding',\n    matches: function matches(ele) {\n      return ele.backgrounding();\n    }\n  }, {\n    selector: ':nonbackgrounding',\n    matches: function matches(ele) {\n      return !ele.backgrounding();\n    }\n  }].sort(function (a, b) {\n    // n.b. selectors that are starting substrings of others must have the longer ones first\n    return descending(a.selector, b.selector);\n  });\n\n  var lookup = function () {\n    var selToFn = {};\n    var s;\n\n    for (var i = 0; i < stateSelectors.length; i++) {\n      s = stateSelectors[i];\n      selToFn[s.selector] = s.matches;\n    }\n\n    return selToFn;\n  }();\n\n  var stateSelectorMatches = function stateSelectorMatches(sel, ele) {\n    return lookup[sel](ele);\n  };\n  var stateSelectorRegex = '(' + stateSelectors.map(function (s) {\n    return s.selector;\n  }).join('|') + ')';\n\n  // so that values get compared properly in Selector.filter()\n\n  var cleanMetaChars = function cleanMetaChars(str) {\n    return str.replace(new RegExp('\\\\\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {\n      return $1;\n    });\n  };\n\n  var replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {\n    selector[selector.length - 1] = replacementQuery;\n  }; // NOTE: add new expression syntax here to have it recognised by the parser;\n  // - a query contains all adjacent (i.e. no separator in between) expressions;\n  // - the current query is stored in selector[i]\n  // - you need to check the query objects in match() for it actually filter properly, but that's pretty straight forward\n\n\n  var exprs = [{\n    name: 'group',\n    // just used for identifying when debugging\n    query: true,\n    regex: '(' + tokens.group + ')',\n    populate: function populate(selector, query, _ref) {\n      var _ref2 = _slicedToArray(_ref, 1),\n          group = _ref2[0];\n\n      query.checks.push({\n        type: Type.GROUP,\n        value: group === '*' ? group : group + 's'\n      });\n    }\n  }, {\n    name: 'state',\n    query: true,\n    regex: stateSelectorRegex,\n    populate: function populate(selector, query, _ref3) {\n      var _ref4 = _slicedToArray(_ref3, 1),\n          state = _ref4[0];\n\n      query.checks.push({\n        type: Type.STATE,\n        value: state\n      });\n    }\n  }, {\n    name: 'id',\n    query: true,\n    regex: '\\\\#(' + tokens.id + ')',\n    populate: function populate(selector, query, _ref5) {\n      var _ref6 = _slicedToArray(_ref5, 1),\n          id = _ref6[0];\n\n      query.checks.push({\n        type: Type.ID,\n        value: cleanMetaChars(id)\n      });\n    }\n  }, {\n    name: 'className',\n    query: true,\n    regex: '\\\\.(' + tokens.className + ')',\n    populate: function populate(selector, query, _ref7) {\n      var _ref8 = _slicedToArray(_ref7, 1),\n          className = _ref8[0];\n\n      query.checks.push({\n        type: Type.CLASS,\n        value: cleanMetaChars(className)\n      });\n    }\n  }, {\n    name: 'dataExists',\n    query: true,\n    regex: '\\\\[\\\\s*(' + tokens.variable + ')\\\\s*\\\\]',\n    populate: function populate(selector, query, _ref9) {\n      var _ref10 = _slicedToArray(_ref9, 1),\n          variable = _ref10[0];\n\n      query.checks.push({\n        type: Type.DATA_EXIST,\n        field: cleanMetaChars(variable)\n      });\n    }\n  }, {\n    name: 'dataCompare',\n    query: true,\n    regex: '\\\\[\\\\s*(' + tokens.variable + ')\\\\s*(' + tokens.comparatorOp + ')\\\\s*(' + tokens.value + ')\\\\s*\\\\]',\n    populate: function populate(selector, query, _ref11) {\n      var _ref12 = _slicedToArray(_ref11, 3),\n          variable = _ref12[0],\n          comparatorOp = _ref12[1],\n          value = _ref12[2];\n\n      var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;\n\n      if (valueIsString) {\n        value = value.substring(1, value.length - 1);\n      } else {\n        value = parseFloat(value);\n      }\n\n      query.checks.push({\n        type: Type.DATA_COMPARE,\n        field: cleanMetaChars(variable),\n        operator: comparatorOp,\n        value: value\n      });\n    }\n  }, {\n    name: 'dataBool',\n    query: true,\n    regex: '\\\\[\\\\s*(' + tokens.boolOp + ')\\\\s*(' + tokens.variable + ')\\\\s*\\\\]',\n    populate: function populate(selector, query, _ref13) {\n      var _ref14 = _slicedToArray(_ref13, 2),\n          boolOp = _ref14[0],\n          variable = _ref14[1];\n\n      query.checks.push({\n        type: Type.DATA_BOOL,\n        field: cleanMetaChars(variable),\n        operator: boolOp\n      });\n    }\n  }, {\n    name: 'metaCompare',\n    query: true,\n    regex: '\\\\[\\\\[\\\\s*(' + tokens.meta + ')\\\\s*(' + tokens.comparatorOp + ')\\\\s*(' + tokens.number + ')\\\\s*\\\\]\\\\]',\n    populate: function populate(selector, query, _ref15) {\n      var _ref16 = _slicedToArray(_ref15, 3),\n          meta = _ref16[0],\n          comparatorOp = _ref16[1],\n          number = _ref16[2];\n\n      query.checks.push({\n        type: Type.META_COMPARE,\n        field: cleanMetaChars(meta),\n        operator: comparatorOp,\n        value: parseFloat(number)\n      });\n    }\n  }, {\n    name: 'nextQuery',\n    separator: true,\n    regex: tokens.separator,\n    populate: function populate(selector, query) {\n      var currentSubject = selector.currentSubject;\n      var edgeCount = selector.edgeCount;\n      var compoundCount = selector.compoundCount;\n      var lastQ = selector[selector.length - 1];\n\n      if (currentSubject != null) {\n        lastQ.subject = currentSubject;\n        selector.currentSubject = null;\n      }\n\n      lastQ.edgeCount = edgeCount;\n      lastQ.compoundCount = compoundCount;\n      selector.edgeCount = 0;\n      selector.compoundCount = 0; // go on to next query\n\n      var nextQuery = selector[selector.length++] = newQuery();\n      return nextQuery; // this is the new query to be filled by the following exprs\n    }\n  }, {\n    name: 'directedEdge',\n    separator: true,\n    regex: tokens.directedEdge,\n    populate: function populate(selector, query) {\n      if (selector.currentSubject == null) {\n        // undirected edge\n        var edgeQuery = newQuery();\n        var source = query;\n        var target = newQuery();\n        edgeQuery.checks.push({\n          type: Type.DIRECTED_EDGE,\n          source: source,\n          target: target\n        }); // the query in the selector should be the edge rather than the source\n\n        replaceLastQuery(selector, query, edgeQuery);\n        selector.edgeCount++; // we're now populating the target query with expressions that follow\n\n        return target;\n      } else {\n        // source/target\n        var srcTgtQ = newQuery();\n        var _source = query;\n\n        var _target = newQuery();\n\n        srcTgtQ.checks.push({\n          type: Type.NODE_SOURCE,\n          source: _source,\n          target: _target\n        }); // the query in the selector should be the neighbourhood rather than the node\n\n        replaceLastQuery(selector, query, srcTgtQ);\n        selector.edgeCount++;\n        return _target; // now populating the target with the following expressions\n      }\n    }\n  }, {\n    name: 'undirectedEdge',\n    separator: true,\n    regex: tokens.undirectedEdge,\n    populate: function populate(selector, query) {\n      if (selector.currentSubject == null) {\n        // undirected edge\n        var edgeQuery = newQuery();\n        var source = query;\n        var target = newQuery();\n        edgeQuery.checks.push({\n          type: Type.UNDIRECTED_EDGE,\n          nodes: [source, target]\n        }); // the query in the selector should be the edge rather than the source\n\n        replaceLastQuery(selector, query, edgeQuery);\n        selector.edgeCount++; // we're now populating the target query with expressions that follow\n\n        return target;\n      } else {\n        // neighbourhood\n        var nhoodQ = newQuery();\n        var node = query;\n        var neighbor = newQuery();\n        nhoodQ.checks.push({\n          type: Type.NODE_NEIGHBOR,\n          node: node,\n          neighbor: neighbor\n        }); // the query in the selector should be the neighbourhood rather than the node\n\n        replaceLastQuery(selector, query, nhoodQ);\n        return neighbor; // now populating the neighbor with following expressions\n      }\n    }\n  }, {\n    name: 'child',\n    separator: true,\n    regex: tokens.child,\n    populate: function populate(selector, query) {\n      if (selector.currentSubject == null) {\n        // default: child query\n        var parentChildQuery = newQuery();\n        var child = newQuery();\n        var parent = selector[selector.length - 1];\n        parentChildQuery.checks.push({\n          type: Type.CHILD,\n          parent: parent,\n          child: child\n        }); // the query in the selector should be the '>' itself\n\n        replaceLastQuery(selector, query, parentChildQuery);\n        selector.compoundCount++; // we're now populating the child query with expressions that follow\n\n        return child;\n      } else if (selector.currentSubject === query) {\n        // compound split query\n        var compound = newQuery();\n        var left = selector[selector.length - 1];\n        var right = newQuery();\n        var subject = newQuery();\n\n        var _child = newQuery();\n\n        var _parent = newQuery(); // set up the root compound q\n\n\n        compound.checks.push({\n          type: Type.COMPOUND_SPLIT,\n          left: left,\n          right: right,\n          subject: subject\n        }); // populate the subject and replace the q at the old spot (within left) with TRUE\n\n        subject.checks = query.checks; // take the checks from the left\n\n        query.checks = [{\n          type: Type.TRUE\n        }]; // checks under left refs the subject implicitly\n        // set up the right q\n\n        _parent.checks.push({\n          type: Type.TRUE\n        }); // parent implicitly refs the subject\n\n\n        right.checks.push({\n          type: Type.PARENT,\n          // type is swapped on right side queries\n          parent: _parent,\n          child: _child // empty for now\n\n        });\n        replaceLastQuery(selector, left, compound); // update the ref since we moved things around for `query`\n\n        selector.currentSubject = subject;\n        selector.compoundCount++;\n        return _child; // now populating the right side's child\n      } else {\n        // parent query\n        // info for parent query\n        var _parent2 = newQuery();\n\n        var _child2 = newQuery();\n\n        var pcQChecks = [{\n          type: Type.PARENT,\n          parent: _parent2,\n          child: _child2\n        }]; // the parent-child query takes the place of the query previously being populated\n\n        _parent2.checks = query.checks; // the previous query contains the checks for the parent\n\n        query.checks = pcQChecks; // pc query takes over\n\n        selector.compoundCount++;\n        return _child2; // we're now populating the child\n      }\n    }\n  }, {\n    name: 'descendant',\n    separator: true,\n    regex: tokens.descendant,\n    populate: function populate(selector, query) {\n      if (selector.currentSubject == null) {\n        // default: descendant query\n        var ancChQuery = newQuery();\n        var descendant = newQuery();\n        var ancestor = selector[selector.length - 1];\n        ancChQuery.checks.push({\n          type: Type.DESCENDANT,\n          ancestor: ancestor,\n          descendant: descendant\n        }); // the query in the selector should be the '>' itself\n\n        replaceLastQuery(selector, query, ancChQuery);\n        selector.compoundCount++; // we're now populating the descendant query with expressions that follow\n\n        return descendant;\n      } else if (selector.currentSubject === query) {\n        // compound split query\n        var compound = newQuery();\n        var left = selector[selector.length - 1];\n        var right = newQuery();\n        var subject = newQuery();\n\n        var _descendant = newQuery();\n\n        var _ancestor = newQuery(); // set up the root compound q\n\n\n        compound.checks.push({\n          type: Type.COMPOUND_SPLIT,\n          left: left,\n          right: right,\n          subject: subject\n        }); // populate the subject and replace the q at the old spot (within left) with TRUE\n\n        subject.checks = query.checks; // take the checks from the left\n\n        query.checks = [{\n          type: Type.TRUE\n        }]; // checks under left refs the subject implicitly\n        // set up the right q\n\n        _ancestor.checks.push({\n          type: Type.TRUE\n        }); // ancestor implicitly refs the subject\n\n\n        right.checks.push({\n          type: Type.ANCESTOR,\n          // type is swapped on right side queries\n          ancestor: _ancestor,\n          descendant: _descendant // empty for now\n\n        });\n        replaceLastQuery(selector, left, compound); // update the ref since we moved things around for `query`\n\n        selector.currentSubject = subject;\n        selector.compoundCount++;\n        return _descendant; // now populating the right side's descendant\n      } else {\n        // ancestor query\n        // info for parent query\n        var _ancestor2 = newQuery();\n\n        var _descendant2 = newQuery();\n\n        var adQChecks = [{\n          type: Type.ANCESTOR,\n          ancestor: _ancestor2,\n          descendant: _descendant2\n        }]; // the parent-child query takes the place of the query previously being populated\n\n        _ancestor2.checks = query.checks; // the previous query contains the checks for the parent\n\n        query.checks = adQChecks; // pc query takes over\n\n        selector.compoundCount++;\n        return _descendant2; // we're now populating the child\n      }\n    }\n  }, {\n    name: 'subject',\n    modifier: true,\n    regex: tokens.subject,\n    populate: function populate(selector, query) {\n      if (selector.currentSubject != null && selector.currentSubject !== query) {\n        warn('Redefinition of subject in selector `' + selector.toString() + '`');\n        return false;\n      }\n\n      selector.currentSubject = query;\n      var topQ = selector[selector.length - 1];\n      var topChk = topQ.checks[0];\n      var topType = topChk == null ? null : topChk.type;\n\n      if (topType === Type.DIRECTED_EDGE) {\n        // directed edge with subject on the target\n        // change to target node check\n        topChk.type = Type.NODE_TARGET;\n      } else if (topType === Type.UNDIRECTED_EDGE) {\n        // undirected edge with subject on the second node\n        // change to neighbor check\n        topChk.type = Type.NODE_NEIGHBOR;\n        topChk.node = topChk.nodes[1]; // second node is subject\n\n        topChk.neighbor = topChk.nodes[0]; // clean up unused fields for new type\n\n        topChk.nodes = null;\n      }\n    }\n  }];\n  exprs.forEach(function (e) {\n    return e.regexObj = new RegExp('^' + e.regex);\n  });\n\n  /**\n   * Of all the expressions, find the first match in the remaining text.\n   * @param {string} remaining The remaining text to parse\n   * @returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`\n   */\n\n  var consumeExpr = function consumeExpr(remaining) {\n    var expr;\n    var match;\n    var name;\n\n    for (var j = 0; j < exprs.length; j++) {\n      var e = exprs[j];\n      var n = e.name;\n      var m = remaining.match(e.regexObj);\n\n      if (m != null) {\n        match = m;\n        expr = e;\n        name = n;\n        var consumed = m[0];\n        remaining = remaining.substring(consumed.length);\n        break; // we've consumed one expr, so we can return now\n      }\n    }\n\n    return {\n      expr: expr,\n      match: match,\n      name: name,\n      remaining: remaining\n    };\n  };\n  /**\n   * Consume all the leading whitespace\n   * @param {string} remaining The text to consume\n   * @returns The text with the leading whitespace removed\n   */\n\n\n  var consumeWhitespace = function consumeWhitespace(remaining) {\n    var match = remaining.match(/^\\s+/);\n\n    if (match) {\n      var consumed = match[0];\n      remaining = remaining.substring(consumed.length);\n    }\n\n    return remaining;\n  };\n  /**\n   * Parse the string and store the parsed representation in the Selector.\n   * @param {string} selector The selector string\n   * @returns `true` if the selector was successfully parsed, `false` otherwise\n   */\n\n\n  var parse = function parse(selector) {\n    var self = this;\n    var remaining = self.inputText = selector;\n    var currentQuery = self[0] = newQuery();\n    self.length = 1;\n    remaining = consumeWhitespace(remaining); // get rid of leading whitespace\n\n    for (;;) {\n      var exprInfo = consumeExpr(remaining);\n\n      if (exprInfo.expr == null) {\n        warn('The selector `' + selector + '`is invalid');\n        return false;\n      } else {\n        var args = exprInfo.match.slice(1); // let the token populate the selector object in currentQuery\n\n        var ret = exprInfo.expr.populate(self, currentQuery, args);\n\n        if (ret === false) {\n          return false; // exit if population failed\n        } else if (ret != null) {\n          currentQuery = ret; // change the current query to be filled if the expr specifies\n        }\n      }\n\n      remaining = exprInfo.remaining; // we're done when there's nothing left to parse\n\n      if (remaining.match(/^\\s*$/)) {\n        break;\n      }\n    }\n\n    var lastQ = self[self.length - 1];\n\n    if (self.currentSubject != null) {\n      lastQ.subject = self.currentSubject;\n    }\n\n    lastQ.edgeCount = self.edgeCount;\n    lastQ.compoundCount = self.compoundCount;\n\n    for (var i = 0; i < self.length; i++) {\n      var q = self[i]; // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations\n\n      if (q.compoundCount > 0 && q.edgeCount > 0) {\n        warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');\n        return false;\n      }\n\n      if (q.edgeCount > 1) {\n        warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');\n        return false;\n      } else if (q.edgeCount === 1) {\n        warn('The selector `' + selector + '` is deprecated.  Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons.  Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.');\n      }\n    }\n\n    return true; // success\n  };\n  /**\n   * Get the selector represented as a string.  This value uses default formatting,\n   * so things like spacing may differ from the input text passed to the constructor.\n   * @returns {string} The selector string\n   */\n\n\n  var toString = function toString() {\n    if (this.toStringCache != null) {\n      return this.toStringCache;\n    }\n\n    var clean = function clean(obj) {\n      if (obj == null) {\n        return '';\n      } else {\n        return obj;\n      }\n    };\n\n    var cleanVal = function cleanVal(val) {\n      if (string(val)) {\n        return '\"' + val + '\"';\n      } else {\n        return clean(val);\n      }\n    };\n\n    var space = function space(val) {\n      return ' ' + val + ' ';\n    };\n\n    var checkToString = function checkToString(check, subject) {\n      var type = check.type,\n          value = check.value;\n\n      switch (type) {\n        case Type.GROUP:\n          {\n            var group = clean(value);\n            return group.substring(0, group.length - 1);\n          }\n\n        case Type.DATA_COMPARE:\n          {\n            var field = check.field,\n                operator = check.operator;\n            return '[' + field + space(clean(operator)) + cleanVal(value) + ']';\n          }\n\n        case Type.DATA_BOOL:\n          {\n            var _operator = check.operator,\n                _field = check.field;\n            return '[' + clean(_operator) + _field + ']';\n          }\n\n        case Type.DATA_EXIST:\n          {\n            var _field2 = check.field;\n            return '[' + _field2 + ']';\n          }\n\n        case Type.META_COMPARE:\n          {\n            var _operator2 = check.operator,\n                _field3 = check.field;\n            return '[[' + _field3 + space(clean(_operator2)) + cleanVal(value) + ']]';\n          }\n\n        case Type.STATE:\n          {\n            return value;\n          }\n\n        case Type.ID:\n          {\n            return '#' + value;\n          }\n\n        case Type.CLASS:\n          {\n            return '.' + value;\n          }\n\n        case Type.PARENT:\n        case Type.CHILD:\n          {\n            return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);\n          }\n\n        case Type.ANCESTOR:\n        case Type.DESCENDANT:\n          {\n            return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);\n          }\n\n        case Type.COMPOUND_SPLIT:\n          {\n            var lhs = queryToString(check.left, subject);\n            var sub = queryToString(check.subject, subject);\n            var rhs = queryToString(check.right, subject);\n            return lhs + (lhs.length > 0 ? ' ' : '') + sub + rhs;\n          }\n\n        case Type.TRUE:\n          {\n            return '';\n          }\n      }\n    };\n\n    var queryToString = function queryToString(query, subject) {\n      return query.checks.reduce(function (str, chk, i) {\n        return str + (subject === query && i === 0 ? '$' : '') + checkToString(chk, subject);\n      }, '');\n    };\n\n    var str = '';\n\n    for (var i = 0; i < this.length; i++) {\n      var query = this[i];\n      str += queryToString(query, query.subject);\n\n      if (this.length > 1 && i < this.length - 1) {\n        str += ', ';\n      }\n    }\n\n    this.toStringCache = str;\n    return str;\n  };\n  var parse$1 = {\n    parse: parse,\n    toString: toString\n  };\n\n  var valCmp = function valCmp(fieldVal, operator, value) {\n    var matches;\n    var isFieldStr = string(fieldVal);\n    var isFieldNum = number$1(fieldVal);\n    var isValStr = string(value);\n    var fieldStr, valStr;\n    var caseInsensitive = false;\n    var notExpr = false;\n    var isIneqCmp = false;\n\n    if (operator.indexOf('!') >= 0) {\n      operator = operator.replace('!', '');\n      notExpr = true;\n    }\n\n    if (operator.indexOf('@') >= 0) {\n      operator = operator.replace('@', '');\n      caseInsensitive = true;\n    }\n\n    if (isFieldStr || isValStr || caseInsensitive) {\n      fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;\n      valStr = '' + value;\n    } // if we're doing a case insensitive comparison, then we're using a STRING comparison\n    // even if we're comparing numbers\n\n\n    if (caseInsensitive) {\n      fieldVal = fieldStr = fieldStr.toLowerCase();\n      value = valStr = valStr.toLowerCase();\n    }\n\n    switch (operator) {\n      case '*=':\n        matches = fieldStr.indexOf(valStr) >= 0;\n        break;\n\n      case '$=':\n        matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;\n        break;\n\n      case '^=':\n        matches = fieldStr.indexOf(valStr) === 0;\n        break;\n\n      case '=':\n        matches = fieldVal === value;\n        break;\n\n      case '>':\n        isIneqCmp = true;\n        matches = fieldVal > value;\n        break;\n\n      case '>=':\n        isIneqCmp = true;\n        matches = fieldVal >= value;\n        break;\n\n      case '<':\n        isIneqCmp = true;\n        matches = fieldVal < value;\n        break;\n\n      case '<=':\n        isIneqCmp = true;\n        matches = fieldVal <= value;\n        break;\n\n      default:\n        matches = false;\n        break;\n    } // apply the not op, but null vals for inequalities should always stay non-matching\n\n\n    if (notExpr && (fieldVal != null || !isIneqCmp)) {\n      matches = !matches;\n    }\n\n    return matches;\n  };\n  var boolCmp = function boolCmp(fieldVal, operator) {\n    switch (operator) {\n      case '?':\n        return fieldVal ? true : false;\n\n      case '!':\n        return fieldVal ? false : true;\n\n      case '^':\n        return fieldVal === undefined;\n    }\n  };\n  var existCmp = function existCmp(fieldVal) {\n    return fieldVal !== undefined;\n  };\n  var data$1 = function data(ele, field) {\n    return ele.data(field);\n  };\n  var meta = function meta(ele, field) {\n    return ele[field]();\n  };\n\n  /** A lookup of `match(check, ele)` functions by `Type` int */\n\n  var match = [];\n  /**\n   * Returns whether the query matches for the element\n   * @param query The `{ type, value, ... }` query object\n   * @param ele The element to compare against\n  */\n\n  var matches$1 = function matches(query, ele) {\n    return query.checks.every(function (chk) {\n      return match[chk.type](chk, ele);\n    });\n  };\n\n  match[Type.GROUP] = function (check, ele) {\n    var group = check.value;\n    return group === '*' || group === ele.group();\n  };\n\n  match[Type.STATE] = function (check, ele) {\n    var stateSelector = check.value;\n    return stateSelectorMatches(stateSelector, ele);\n  };\n\n  match[Type.ID] = function (check, ele) {\n    var id = check.value;\n    return ele.id() === id;\n  };\n\n  match[Type.CLASS] = function (check, ele) {\n    var cls = check.value;\n    return ele.hasClass(cls);\n  };\n\n  match[Type.META_COMPARE] = function (check, ele) {\n    var field = check.field,\n        operator = check.operator,\n        value = check.value;\n    return valCmp(meta(ele, field), operator, value);\n  };\n\n  match[Type.DATA_COMPARE] = function (check, ele) {\n    var field = check.field,\n        operator = check.operator,\n        value = check.value;\n    return valCmp(data$1(ele, field), operator, value);\n  };\n\n  match[Type.DATA_BOOL] = function (check, ele) {\n    var field = check.field,\n        operator = check.operator;\n    return boolCmp(data$1(ele, field), operator);\n  };\n\n  match[Type.DATA_EXIST] = function (check, ele) {\n    var field = check.field;\n        check.operator;\n    return existCmp(data$1(ele, field));\n  };\n\n  match[Type.UNDIRECTED_EDGE] = function (check, ele) {\n    var qA = check.nodes[0];\n    var qB = check.nodes[1];\n    var src = ele.source();\n    var tgt = ele.target();\n    return matches$1(qA, src) && matches$1(qB, tgt) || matches$1(qB, src) && matches$1(qA, tgt);\n  };\n\n  match[Type.NODE_NEIGHBOR] = function (check, ele) {\n    return matches$1(check.node, ele) && ele.neighborhood().some(function (n) {\n      return n.isNode() && matches$1(check.neighbor, n);\n    });\n  };\n\n  match[Type.DIRECTED_EDGE] = function (check, ele) {\n    return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());\n  };\n\n  match[Type.NODE_SOURCE] = function (check, ele) {\n    return matches$1(check.source, ele) && ele.outgoers().some(function (n) {\n      return n.isNode() && matches$1(check.target, n);\n    });\n  };\n\n  match[Type.NODE_TARGET] = function (check, ele) {\n    return matches$1(check.target, ele) && ele.incomers().some(function (n) {\n      return n.isNode() && matches$1(check.source, n);\n    });\n  };\n\n  match[Type.CHILD] = function (check, ele) {\n    return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());\n  };\n\n  match[Type.PARENT] = function (check, ele) {\n    return matches$1(check.parent, ele) && ele.children().some(function (c) {\n      return matches$1(check.child, c);\n    });\n  };\n\n  match[Type.DESCENDANT] = function (check, ele) {\n    return matches$1(check.descendant, ele) && ele.ancestors().some(function (a) {\n      return matches$1(check.ancestor, a);\n    });\n  };\n\n  match[Type.ANCESTOR] = function (check, ele) {\n    return matches$1(check.ancestor, ele) && ele.descendants().some(function (d) {\n      return matches$1(check.descendant, d);\n    });\n  };\n\n  match[Type.COMPOUND_SPLIT] = function (check, ele) {\n    return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);\n  };\n\n  match[Type.TRUE] = function () {\n    return true;\n  };\n\n  match[Type.COLLECTION] = function (check, ele) {\n    var collection = check.value;\n    return collection.has(ele);\n  };\n\n  match[Type.FILTER] = function (check, ele) {\n    var filter = check.value;\n    return filter(ele);\n  };\n\n  var filter = function filter(collection) {\n    var self = this; // for 1 id #foo queries, just get the element\n\n    if (self.length === 1 && self[0].checks.length === 1 && self[0].checks[0].type === Type.ID) {\n      return collection.getElementById(self[0].checks[0].value).collection();\n    }\n\n    var selectorFunction = function selectorFunction(element) {\n      for (var j = 0; j < self.length; j++) {\n        var query = self[j];\n\n        if (matches$1(query, element)) {\n          return true;\n        }\n      }\n\n      return false;\n    };\n\n    if (self.text() == null) {\n      selectorFunction = function selectorFunction() {\n        return true;\n      };\n    }\n\n    return collection.filter(selectorFunction);\n  }; // filter\n  // does selector match a single element?\n\n\n  var matches = function matches(ele) {\n    var self = this;\n\n    for (var j = 0; j < self.length; j++) {\n      var query = self[j];\n\n      if (matches$1(query, ele)) {\n        return true;\n      }\n    }\n\n    return false;\n  }; // matches\n\n\n  var matching = {\n    matches: matches,\n    filter: filter\n  };\n\n  var Selector = function Selector(selector) {\n    this.inputText = selector;\n    this.currentSubject = null;\n    this.compoundCount = 0;\n    this.edgeCount = 0;\n    this.length = 0;\n\n    if (selector == null || string(selector) && selector.match(/^\\s*$/)) ; else if (elementOrCollection(selector)) {\n      this.addQuery({\n        checks: [{\n          type: Type.COLLECTION,\n          value: selector.collection()\n        }]\n      });\n    } else if (fn$6(selector)) {\n      this.addQuery({\n        checks: [{\n          type: Type.FILTER,\n          value: selector\n        }]\n      });\n    } else if (string(selector)) {\n      if (!this.parse(selector)) {\n        this.invalid = true;\n      }\n    } else {\n      error('A selector must be created from a string; found ');\n    }\n  };\n\n  var selfn = Selector.prototype;\n  [parse$1, matching].forEach(function (p) {\n    return extend(selfn, p);\n  });\n\n  selfn.text = function () {\n    return this.inputText;\n  };\n\n  selfn.size = function () {\n    return this.length;\n  };\n\n  selfn.eq = function (i) {\n    return this[i];\n  };\n\n  selfn.sameText = function (otherSel) {\n    return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();\n  };\n\n  selfn.addQuery = function (q) {\n    this[this.length++] = q;\n  };\n\n  selfn.selector = selfn.toString;\n\n  var elesfn$g = {\n    allAre: function allAre(selector) {\n      var selObj = new Selector(selector);\n      return this.every(function (ele) {\n        return selObj.matches(ele);\n      });\n    },\n    is: function is(selector) {\n      var selObj = new Selector(selector);\n      return this.some(function (ele) {\n        return selObj.matches(ele);\n      });\n    },\n    some: function some(fn, thisArg) {\n      for (var i = 0; i < this.length; i++) {\n        var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);\n\n        if (ret) {\n          return true;\n        }\n      }\n\n      return false;\n    },\n    every: function every(fn, thisArg) {\n      for (var i = 0; i < this.length; i++) {\n        var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);\n\n        if (!ret) {\n          return false;\n        }\n      }\n\n      return true;\n    },\n    same: function same(collection) {\n      // cheap collection ref check\n      if (this === collection) {\n        return true;\n      }\n\n      collection = this.cy().collection(collection);\n      var thisLength = this.length;\n      var collectionLength = collection.length; // cheap length check\n\n      if (thisLength !== collectionLength) {\n        return false;\n      } // cheap element ref check\n\n\n      if (thisLength === 1) {\n        return this[0] === collection[0];\n      }\n\n      return this.every(function (ele) {\n        return collection.hasElementWithId(ele.id());\n      });\n    },\n    anySame: function anySame(collection) {\n      collection = this.cy().collection(collection);\n      return this.some(function (ele) {\n        return collection.hasElementWithId(ele.id());\n      });\n    },\n    allAreNeighbors: function allAreNeighbors(collection) {\n      collection = this.cy().collection(collection);\n      var nhood = this.neighborhood();\n      return collection.every(function (ele) {\n        return nhood.hasElementWithId(ele.id());\n      });\n    },\n    contains: function contains(collection) {\n      collection = this.cy().collection(collection);\n      var self = this;\n      return collection.every(function (ele) {\n        return self.hasElementWithId(ele.id());\n      });\n    }\n  };\n  elesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;\n  elesfn$g.has = elesfn$g.contains;\n  elesfn$g.equal = elesfn$g.equals = elesfn$g.same;\n\n  var cache = function cache(fn, name) {\n    return function traversalCache(arg1, arg2, arg3, arg4) {\n      var selectorOrEles = arg1;\n      var eles = this;\n      var key;\n\n      if (selectorOrEles == null) {\n        key = '';\n      } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {\n        key = selectorOrEles.id();\n      }\n\n      if (eles.length === 1 && key) {\n        var _p = eles[0]._private;\n        var tch = _p.traversalCache = _p.traversalCache || {};\n        var ch = tch[name] = tch[name] || [];\n        var hash = hashString(key);\n        var cacheHit = ch[hash];\n\n        if (cacheHit) {\n          return cacheHit;\n        } else {\n          return ch[hash] = fn.call(eles, arg1, arg2, arg3, arg4);\n        }\n      } else {\n        return fn.call(eles, arg1, arg2, arg3, arg4);\n      }\n    };\n  };\n\n  var elesfn$f = {\n    parent: function parent(selector) {\n      var parents = []; // optimisation for single ele call\n\n      if (this.length === 1) {\n        var parent = this[0]._private.parent;\n\n        if (parent) {\n          return parent;\n        }\n      }\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        var _parent = ele._private.parent;\n\n        if (_parent) {\n          parents.push(_parent);\n        }\n      }\n\n      return this.spawn(parents, true).filter(selector);\n    },\n    parents: function parents(selector) {\n      var parents = [];\n      var eles = this.parent();\n\n      while (eles.nonempty()) {\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          parents.push(ele);\n        }\n\n        eles = eles.parent();\n      }\n\n      return this.spawn(parents, true).filter(selector);\n    },\n    commonAncestors: function commonAncestors(selector) {\n      var ancestors;\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        var parents = ele.parents();\n        ancestors = ancestors || parents;\n        ancestors = ancestors.intersect(parents); // current list must be common with current ele parents set\n      }\n\n      return ancestors.filter(selector);\n    },\n    orphans: function orphans(selector) {\n      return this.stdFilter(function (ele) {\n        return ele.isOrphan();\n      }).filter(selector);\n    },\n    nonorphans: function nonorphans(selector) {\n      return this.stdFilter(function (ele) {\n        return ele.isChild();\n      }).filter(selector);\n    },\n    children: cache(function (selector) {\n      var children = [];\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        var eleChildren = ele._private.children;\n\n        for (var j = 0; j < eleChildren.length; j++) {\n          children.push(eleChildren[j]);\n        }\n      }\n\n      return this.spawn(children, true).filter(selector);\n    }, 'children'),\n    siblings: function siblings(selector) {\n      return this.parent().children().not(this).filter(selector);\n    },\n    isParent: function isParent() {\n      var ele = this[0];\n\n      if (ele) {\n        return ele.isNode() && ele._private.children.length !== 0;\n      }\n    },\n    isChildless: function isChildless() {\n      var ele = this[0];\n\n      if (ele) {\n        return ele.isNode() && ele._private.children.length === 0;\n      }\n    },\n    isChild: function isChild() {\n      var ele = this[0];\n\n      if (ele) {\n        return ele.isNode() && ele._private.parent != null;\n      }\n    },\n    isOrphan: function isOrphan() {\n      var ele = this[0];\n\n      if (ele) {\n        return ele.isNode() && ele._private.parent == null;\n      }\n    },\n    descendants: function descendants(selector) {\n      var elements = [];\n\n      function add(eles) {\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          elements.push(ele);\n\n          if (ele.children().nonempty()) {\n            add(ele.children());\n          }\n        }\n      }\n\n      add(this.children());\n      return this.spawn(elements, true).filter(selector);\n    }\n  };\n\n  function forEachCompound(eles, fn, includeSelf, recursiveStep) {\n    var q = [];\n    var did = new Set$1();\n    var cy = eles.cy();\n    var hasCompounds = cy.hasCompoundNodes();\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n\n      if (includeSelf) {\n        q.push(ele);\n      } else if (hasCompounds) {\n        recursiveStep(q, did, ele);\n      }\n    }\n\n    while (q.length > 0) {\n      var _ele = q.shift();\n\n      fn(_ele);\n      did.add(_ele.id());\n\n      if (hasCompounds) {\n        recursiveStep(q, did, _ele);\n      }\n    }\n\n    return eles;\n  }\n\n  function addChildren(q, did, ele) {\n    if (ele.isParent()) {\n      var children = ele._private.children;\n\n      for (var i = 0; i < children.length; i++) {\n        var child = children[i];\n\n        if (!did.has(child.id())) {\n          q.push(child);\n        }\n      }\n    }\n  } // very efficient version of eles.add( eles.descendants() ).forEach()\n  // for internal use\n\n\n  elesfn$f.forEachDown = function (fn) {\n    var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    return forEachCompound(this, fn, includeSelf, addChildren);\n  };\n\n  function addParent(q, did, ele) {\n    if (ele.isChild()) {\n      var parent = ele._private.parent;\n\n      if (!did.has(parent.id())) {\n        q.push(parent);\n      }\n    }\n  }\n\n  elesfn$f.forEachUp = function (fn) {\n    var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    return forEachCompound(this, fn, includeSelf, addParent);\n  };\n\n  function addParentAndChildren(q, did, ele) {\n    addParent(q, did, ele);\n    addChildren(q, did, ele);\n  }\n\n  elesfn$f.forEachUpAndDown = function (fn) {\n    var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    return forEachCompound(this, fn, includeSelf, addParentAndChildren);\n  }; // aliases\n\n\n  elesfn$f.ancestors = elesfn$f.parents;\n\n  var fn$5, elesfn$e;\n  fn$5 = elesfn$e = {\n    data: define.data({\n      field: 'data',\n      bindingEvent: 'data',\n      allowBinding: true,\n      allowSetting: true,\n      settingEvent: 'data',\n      settingTriggersEvent: true,\n      triggerFnName: 'trigger',\n      allowGetting: true,\n      immutableKeys: {\n        'id': true,\n        'source': true,\n        'target': true,\n        'parent': true\n      },\n      updateStyle: true\n    }),\n    removeData: define.removeData({\n      field: 'data',\n      event: 'data',\n      triggerFnName: 'trigger',\n      triggerEvent: true,\n      immutableKeys: {\n        'id': true,\n        'source': true,\n        'target': true,\n        'parent': true\n      },\n      updateStyle: true\n    }),\n    scratch: define.data({\n      field: 'scratch',\n      bindingEvent: 'scratch',\n      allowBinding: true,\n      allowSetting: true,\n      settingEvent: 'scratch',\n      settingTriggersEvent: true,\n      triggerFnName: 'trigger',\n      allowGetting: true,\n      updateStyle: true\n    }),\n    removeScratch: define.removeData({\n      field: 'scratch',\n      event: 'scratch',\n      triggerFnName: 'trigger',\n      triggerEvent: true,\n      updateStyle: true\n    }),\n    rscratch: define.data({\n      field: 'rscratch',\n      allowBinding: false,\n      allowSetting: true,\n      settingTriggersEvent: false,\n      allowGetting: true\n    }),\n    removeRscratch: define.removeData({\n      field: 'rscratch',\n      triggerEvent: false\n    }),\n    id: function id() {\n      var ele = this[0];\n\n      if (ele) {\n        return ele._private.data.id;\n      }\n    }\n  }; // aliases\n\n  fn$5.attr = fn$5.data;\n  fn$5.removeAttr = fn$5.removeData;\n  var data = elesfn$e;\n\n  var elesfn$d = {};\n\n  function defineDegreeFunction(callback) {\n    return function (includeLoops) {\n      var self = this;\n\n      if (includeLoops === undefined) {\n        includeLoops = true;\n      }\n\n      if (self.length === 0) {\n        return;\n      }\n\n      if (self.isNode() && !self.removed()) {\n        var degree = 0;\n        var node = self[0];\n        var connectedEdges = node._private.edges;\n\n        for (var i = 0; i < connectedEdges.length; i++) {\n          var edge = connectedEdges[i];\n\n          if (!includeLoops && edge.isLoop()) {\n            continue;\n          }\n\n          degree += callback(node, edge);\n        }\n\n        return degree;\n      } else {\n        return;\n      }\n    };\n  }\n\n  extend(elesfn$d, {\n    degree: defineDegreeFunction(function (node, edge) {\n      if (edge.source().same(edge.target())) {\n        return 2;\n      } else {\n        return 1;\n      }\n    }),\n    indegree: defineDegreeFunction(function (node, edge) {\n      if (edge.target().same(node)) {\n        return 1;\n      } else {\n        return 0;\n      }\n    }),\n    outdegree: defineDegreeFunction(function (node, edge) {\n      if (edge.source().same(node)) {\n        return 1;\n      } else {\n        return 0;\n      }\n    })\n  });\n\n  function defineDegreeBoundsFunction(degreeFn, callback) {\n    return function (includeLoops) {\n      var ret;\n      var nodes = this.nodes();\n\n      for (var i = 0; i < nodes.length; i++) {\n        var ele = nodes[i];\n        var degree = ele[degreeFn](includeLoops);\n\n        if (degree !== undefined && (ret === undefined || callback(degree, ret))) {\n          ret = degree;\n        }\n      }\n\n      return ret;\n    };\n  }\n\n  extend(elesfn$d, {\n    minDegree: defineDegreeBoundsFunction('degree', function (degree, min) {\n      return degree < min;\n    }),\n    maxDegree: defineDegreeBoundsFunction('degree', function (degree, max) {\n      return degree > max;\n    }),\n    minIndegree: defineDegreeBoundsFunction('indegree', function (degree, min) {\n      return degree < min;\n    }),\n    maxIndegree: defineDegreeBoundsFunction('indegree', function (degree, max) {\n      return degree > max;\n    }),\n    minOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, min) {\n      return degree < min;\n    }),\n    maxOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, max) {\n      return degree > max;\n    })\n  });\n  extend(elesfn$d, {\n    totalDegree: function totalDegree(includeLoops) {\n      var total = 0;\n      var nodes = this.nodes();\n\n      for (var i = 0; i < nodes.length; i++) {\n        total += nodes[i].degree(includeLoops);\n      }\n\n      return total;\n    }\n  });\n\n  var fn$4, elesfn$c;\n\n  var beforePositionSet = function beforePositionSet(eles, newPos, silent) {\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n\n      if (!ele.locked()) {\n        var oldPos = ele._private.position;\n        var delta = {\n          x: newPos.x != null ? newPos.x - oldPos.x : 0,\n          y: newPos.y != null ? newPos.y - oldPos.y : 0\n        };\n\n        if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {\n          ele.children().shift(delta, silent);\n        }\n\n        ele.dirtyBoundingBoxCache();\n      }\n    }\n  };\n\n  var positionDef = {\n    field: 'position',\n    bindingEvent: 'position',\n    allowBinding: true,\n    allowSetting: true,\n    settingEvent: 'position',\n    settingTriggersEvent: true,\n    triggerFnName: 'emitAndNotify',\n    allowGetting: true,\n    validKeys: ['x', 'y'],\n    beforeGet: function beforeGet(ele) {\n      ele.updateCompoundBounds();\n    },\n    beforeSet: function beforeSet(eles, newPos) {\n      beforePositionSet(eles, newPos, false);\n    },\n    onSet: function onSet(eles) {\n      eles.dirtyCompoundBoundsCache();\n    },\n    canSet: function canSet(ele) {\n      return !ele.locked();\n    }\n  };\n  fn$4 = elesfn$c = {\n    position: define.data(positionDef),\n    // position but no notification to renderer\n    silentPosition: define.data(extend({}, positionDef, {\n      allowBinding: false,\n      allowSetting: true,\n      settingTriggersEvent: false,\n      allowGetting: false,\n      beforeSet: function beforeSet(eles, newPos) {\n        beforePositionSet(eles, newPos, true);\n      },\n      onSet: function onSet(eles) {\n        eles.dirtyCompoundBoundsCache();\n      }\n    })),\n    positions: function positions(pos, silent) {\n      if (plainObject(pos)) {\n        if (silent) {\n          this.silentPosition(pos);\n        } else {\n          this.position(pos);\n        }\n      } else if (fn$6(pos)) {\n        var _fn = pos;\n        var cy = this.cy();\n        cy.startBatch();\n\n        for (var i = 0; i < this.length; i++) {\n          var ele = this[i];\n\n          var _pos = void 0;\n\n          if (_pos = _fn(ele, i)) {\n            if (silent) {\n              ele.silentPosition(_pos);\n            } else {\n              ele.position(_pos);\n            }\n          }\n        }\n\n        cy.endBatch();\n      }\n\n      return this; // chaining\n    },\n    silentPositions: function silentPositions(pos) {\n      return this.positions(pos, true);\n    },\n    shift: function shift(dim, val, silent) {\n      var delta;\n\n      if (plainObject(dim)) {\n        delta = {\n          x: number$1(dim.x) ? dim.x : 0,\n          y: number$1(dim.y) ? dim.y : 0\n        };\n        silent = val;\n      } else if (string(dim) && number$1(val)) {\n        delta = {\n          x: 0,\n          y: 0\n        };\n        delta[dim] = val;\n      }\n\n      if (delta != null) {\n        var cy = this.cy();\n        cy.startBatch();\n\n        for (var i = 0; i < this.length; i++) {\n          var ele = this[i]; // exclude any node that is a descendant of the calling collection\n\n          if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {\n            continue;\n          }\n\n          var pos = ele.position();\n          var newPos = {\n            x: pos.x + delta.x,\n            y: pos.y + delta.y\n          };\n\n          if (silent) {\n            ele.silentPosition(newPos);\n          } else {\n            ele.position(newPos);\n          }\n        }\n\n        cy.endBatch();\n      }\n\n      return this;\n    },\n    silentShift: function silentShift(dim, val) {\n      if (plainObject(dim)) {\n        this.shift(dim, true);\n      } else if (string(dim) && number$1(val)) {\n        this.shift(dim, val, true);\n      }\n\n      return this;\n    },\n    // get/set the rendered (i.e. on screen) positon of the element\n    renderedPosition: function renderedPosition(dim, val) {\n      var ele = this[0];\n      var cy = this.cy();\n      var zoom = cy.zoom();\n      var pan = cy.pan();\n      var rpos = plainObject(dim) ? dim : undefined;\n      var setting = rpos !== undefined || val !== undefined && string(dim);\n\n      if (ele && ele.isNode()) {\n        // must have an element and must be a node to return position\n        if (setting) {\n          for (var i = 0; i < this.length; i++) {\n            var _ele = this[i];\n\n            if (val !== undefined) {\n              // set one dimension\n              _ele.position(dim, (val - pan[dim]) / zoom);\n            } else if (rpos !== undefined) {\n              // set whole position\n              _ele.position(renderedToModelPosition(rpos, zoom, pan));\n            }\n          }\n        } else {\n          // getting\n          var pos = ele.position();\n          rpos = modelToRenderedPosition(pos, zoom, pan);\n\n          if (dim === undefined) {\n            // then return the whole rendered position\n            return rpos;\n          } else {\n            // then return the specified dimension\n            return rpos[dim];\n          }\n        }\n      } else if (!setting) {\n        return undefined; // for empty collection case\n      }\n\n      return this; // chaining\n    },\n    // get/set the position relative to the parent\n    relativePosition: function relativePosition(dim, val) {\n      var ele = this[0];\n      var cy = this.cy();\n      var ppos = plainObject(dim) ? dim : undefined;\n      var setting = ppos !== undefined || val !== undefined && string(dim);\n      var hasCompoundNodes = cy.hasCompoundNodes();\n\n      if (ele && ele.isNode()) {\n        // must have an element and must be a node to return position\n        if (setting) {\n          for (var i = 0; i < this.length; i++) {\n            var _ele2 = this[i];\n            var parent = hasCompoundNodes ? _ele2.parent() : null;\n            var hasParent = parent && parent.length > 0;\n            var relativeToParent = hasParent;\n\n            if (hasParent) {\n              parent = parent[0];\n            }\n\n            var origin = relativeToParent ? parent.position() : {\n              x: 0,\n              y: 0\n            };\n\n            if (val !== undefined) {\n              // set one dimension\n              _ele2.position(dim, val + origin[dim]);\n            } else if (ppos !== undefined) {\n              // set whole position\n              _ele2.position({\n                x: ppos.x + origin.x,\n                y: ppos.y + origin.y\n              });\n            }\n          }\n        } else {\n          // getting\n          var pos = ele.position();\n\n          var _parent = hasCompoundNodes ? ele.parent() : null;\n\n          var _hasParent = _parent && _parent.length > 0;\n\n          var _relativeToParent = _hasParent;\n\n          if (_hasParent) {\n            _parent = _parent[0];\n          }\n\n          var _origin = _relativeToParent ? _parent.position() : {\n            x: 0,\n            y: 0\n          };\n\n          ppos = {\n            x: pos.x - _origin.x,\n            y: pos.y - _origin.y\n          };\n\n          if (dim === undefined) {\n            // then return the whole rendered position\n            return ppos;\n          } else {\n            // then return the specified dimension\n            return ppos[dim];\n          }\n        }\n      } else if (!setting) {\n        return undefined; // for empty collection case\n      }\n\n      return this; // chaining\n    }\n  }; // aliases\n\n  fn$4.modelPosition = fn$4.point = fn$4.position;\n  fn$4.modelPositions = fn$4.points = fn$4.positions;\n  fn$4.renderedPoint = fn$4.renderedPosition;\n  fn$4.relativePoint = fn$4.relativePosition;\n  var position = elesfn$c;\n\n  var fn$3, elesfn$b;\n  fn$3 = elesfn$b = {};\n\n  elesfn$b.renderedBoundingBox = function (options) {\n    var bb = this.boundingBox(options);\n    var cy = this.cy();\n    var zoom = cy.zoom();\n    var pan = cy.pan();\n    var x1 = bb.x1 * zoom + pan.x;\n    var x2 = bb.x2 * zoom + pan.x;\n    var y1 = bb.y1 * zoom + pan.y;\n    var y2 = bb.y2 * zoom + pan.y;\n    return {\n      x1: x1,\n      x2: x2,\n      y1: y1,\n      y2: y2,\n      w: x2 - x1,\n      h: y2 - y1\n    };\n  };\n\n  elesfn$b.dirtyCompoundBoundsCache = function () {\n    var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var cy = this.cy();\n\n    if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {\n      return this;\n    }\n\n    this.forEachUp(function (ele) {\n      if (ele.isParent()) {\n        var _p = ele._private;\n        _p.compoundBoundsClean = false;\n        _p.bbCache = null;\n\n        if (!silent) {\n          ele.emitAndNotify('bounds');\n        }\n      }\n    });\n    return this;\n  };\n\n  elesfn$b.updateCompoundBounds = function () {\n    var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n    var cy = this.cy(); // not possible to do on non-compound graphs or with the style disabled\n\n    if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {\n      return this;\n    } // save cycles when batching -- but bounds will be stale (or not exist yet)\n\n\n    if (!force && cy.batching()) {\n      return this;\n    }\n\n    function update(parent) {\n      if (!parent.isParent()) {\n        return;\n      }\n\n      var _p = parent._private;\n      var children = parent.children();\n      var includeLabels = parent.pstyle('compound-sizing-wrt-labels').value === 'include';\n      var min = {\n        width: {\n          val: parent.pstyle('min-width').pfValue,\n          left: parent.pstyle('min-width-bias-left'),\n          right: parent.pstyle('min-width-bias-right')\n        },\n        height: {\n          val: parent.pstyle('min-height').pfValue,\n          top: parent.pstyle('min-height-bias-top'),\n          bottom: parent.pstyle('min-height-bias-bottom')\n        }\n      };\n      var bb = children.boundingBox({\n        includeLabels: includeLabels,\n        includeOverlays: false,\n        // updating the compound bounds happens outside of the regular\n        // cache cycle (i.e. before fired events)\n        useCache: false\n      });\n      var pos = _p.position; // if children take up zero area then keep position and fall back on stylesheet w/h\n\n      if (bb.w === 0 || bb.h === 0) {\n        bb = {\n          w: parent.pstyle('width').pfValue,\n          h: parent.pstyle('height').pfValue\n        };\n        bb.x1 = pos.x - bb.w / 2;\n        bb.x2 = pos.x + bb.w / 2;\n        bb.y1 = pos.y - bb.h / 2;\n        bb.y2 = pos.y + bb.h / 2;\n      }\n\n      function computeBiasValues(propDiff, propBias, propBiasComplement) {\n        var biasDiff = 0;\n        var biasComplementDiff = 0;\n        var biasTotal = propBias + propBiasComplement;\n\n        if (propDiff > 0 && biasTotal > 0) {\n          biasDiff = propBias / biasTotal * propDiff;\n          biasComplementDiff = propBiasComplement / biasTotal * propDiff;\n        }\n\n        return {\n          biasDiff: biasDiff,\n          biasComplementDiff: biasComplementDiff\n        };\n      }\n\n      function computePaddingValues(width, height, paddingObject, relativeTo) {\n        // Assuming percentage is number from 0 to 1\n        if (paddingObject.units === '%') {\n          switch (relativeTo) {\n            case 'width':\n              return width > 0 ? paddingObject.pfValue * width : 0;\n\n            case 'height':\n              return height > 0 ? paddingObject.pfValue * height : 0;\n\n            case 'average':\n              return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;\n\n            case 'min':\n              return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;\n\n            case 'max':\n              return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;\n\n            default:\n              return 0;\n          }\n        } else if (paddingObject.units === 'px') {\n          return paddingObject.pfValue;\n        } else {\n          return 0;\n        }\n      }\n\n      var leftVal = min.width.left.value;\n\n      if (min.width.left.units === 'px' && min.width.val > 0) {\n        leftVal = leftVal * 100 / min.width.val;\n      }\n\n      var rightVal = min.width.right.value;\n\n      if (min.width.right.units === 'px' && min.width.val > 0) {\n        rightVal = rightVal * 100 / min.width.val;\n      }\n\n      var topVal = min.height.top.value;\n\n      if (min.height.top.units === 'px' && min.height.val > 0) {\n        topVal = topVal * 100 / min.height.val;\n      }\n\n      var bottomVal = min.height.bottom.value;\n\n      if (min.height.bottom.units === 'px' && min.height.val > 0) {\n        bottomVal = bottomVal * 100 / min.height.val;\n      }\n\n      var widthBiasDiffs = computeBiasValues(min.width.val - bb.w, leftVal, rightVal);\n      var diffLeft = widthBiasDiffs.biasDiff;\n      var diffRight = widthBiasDiffs.biasComplementDiff;\n      var heightBiasDiffs = computeBiasValues(min.height.val - bb.h, topVal, bottomVal);\n      var diffTop = heightBiasDiffs.biasDiff;\n      var diffBottom = heightBiasDiffs.biasComplementDiff;\n      _p.autoPadding = computePaddingValues(bb.w, bb.h, parent.pstyle('padding'), parent.pstyle('padding-relative-to').value);\n      _p.autoWidth = Math.max(bb.w, min.width.val);\n      pos.x = (-diffLeft + bb.x1 + bb.x2 + diffRight) / 2;\n      _p.autoHeight = Math.max(bb.h, min.height.val);\n      pos.y = (-diffTop + bb.y1 + bb.y2 + diffBottom) / 2;\n    }\n\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      var _p = ele._private;\n\n      if (!_p.compoundBoundsClean || force) {\n        update(ele);\n\n        if (!cy.batching()) {\n          _p.compoundBoundsClean = true;\n        }\n      }\n    }\n\n    return this;\n  };\n\n  var noninf = function noninf(x) {\n    if (x === Infinity || x === -Infinity) {\n      return 0;\n    }\n\n    return x;\n  };\n\n  var updateBounds = function updateBounds(b, x1, y1, x2, y2) {\n    // don't update with zero area boxes\n    if (x2 - x1 === 0 || y2 - y1 === 0) {\n      return;\n    } // don't update with null dim\n\n\n    if (x1 == null || y1 == null || x2 == null || y2 == null) {\n      return;\n    }\n\n    b.x1 = x1 < b.x1 ? x1 : b.x1;\n    b.x2 = x2 > b.x2 ? x2 : b.x2;\n    b.y1 = y1 < b.y1 ? y1 : b.y1;\n    b.y2 = y2 > b.y2 ? y2 : b.y2;\n    b.w = b.x2 - b.x1;\n    b.h = b.y2 - b.y1;\n  };\n\n  var updateBoundsFromBox = function updateBoundsFromBox(b, b2) {\n    if (b2 == null) {\n      return b;\n    }\n\n    return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);\n  };\n\n  var prefixedProperty = function prefixedProperty(obj, field, prefix) {\n    return getPrefixedProperty(obj, field, prefix);\n  };\n\n  var updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {\n    if (ele.cy().headless()) {\n      return;\n    }\n\n    var _p = ele._private;\n    var rstyle = _p.rstyle;\n    var halfArW = rstyle.arrowWidth / 2;\n    var arrowType = ele.pstyle(prefix + '-arrow-shape').value;\n    var x;\n    var y;\n\n    if (arrowType !== 'none') {\n      if (prefix === 'source') {\n        x = rstyle.srcX;\n        y = rstyle.srcY;\n      } else if (prefix === 'target') {\n        x = rstyle.tgtX;\n        y = rstyle.tgtY;\n      } else {\n        x = rstyle.midX;\n        y = rstyle.midY;\n      } // always store the individual arrow bounds\n\n\n      var bbs = _p.arrowBounds = _p.arrowBounds || {};\n      var bb = bbs[prefix] = bbs[prefix] || {};\n      bb.x1 = x - halfArW;\n      bb.y1 = y - halfArW;\n      bb.x2 = x + halfArW;\n      bb.y2 = y + halfArW;\n      bb.w = bb.x2 - bb.x1;\n      bb.h = bb.y2 - bb.y1;\n      expandBoundingBox(bb, 1);\n      updateBounds(bounds, bb.x1, bb.y1, bb.x2, bb.y2);\n    }\n  };\n\n  var updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {\n    if (ele.cy().headless()) {\n      return;\n    }\n\n    var prefixDash;\n\n    if (prefix) {\n      prefixDash = prefix + '-';\n    } else {\n      prefixDash = '';\n    }\n\n    var _p = ele._private;\n    var rstyle = _p.rstyle;\n    var label = ele.pstyle(prefixDash + 'label').strValue;\n\n    if (label) {\n      var halign = ele.pstyle('text-halign');\n      var valign = ele.pstyle('text-valign');\n      var labelWidth = prefixedProperty(rstyle, 'labelWidth', prefix);\n      var labelHeight = prefixedProperty(rstyle, 'labelHeight', prefix);\n      var labelX = prefixedProperty(rstyle, 'labelX', prefix);\n      var labelY = prefixedProperty(rstyle, 'labelY', prefix);\n      var marginX = ele.pstyle(prefixDash + 'text-margin-x').pfValue;\n      var marginY = ele.pstyle(prefixDash + 'text-margin-y').pfValue;\n      var isEdge = ele.isEdge();\n      var rotation = ele.pstyle(prefixDash + 'text-rotation');\n      var outlineWidth = ele.pstyle('text-outline-width').pfValue;\n      var borderWidth = ele.pstyle('text-border-width').pfValue;\n      var halfBorderWidth = borderWidth / 2;\n      var padding = ele.pstyle('text-background-padding').pfValue;\n      var marginOfError = 2; // expand to work around browser dimension inaccuracies\n\n      var lh = labelHeight;\n      var lw = labelWidth;\n      var lw_2 = lw / 2;\n      var lh_2 = lh / 2;\n      var lx1, lx2, ly1, ly2;\n\n      if (isEdge) {\n        lx1 = labelX - lw_2;\n        lx2 = labelX + lw_2;\n        ly1 = labelY - lh_2;\n        ly2 = labelY + lh_2;\n      } else {\n        switch (halign.value) {\n          case 'left':\n            lx1 = labelX - lw;\n            lx2 = labelX;\n            break;\n\n          case 'center':\n            lx1 = labelX - lw_2;\n            lx2 = labelX + lw_2;\n            break;\n\n          case 'right':\n            lx1 = labelX;\n            lx2 = labelX + lw;\n            break;\n        }\n\n        switch (valign.value) {\n          case 'top':\n            ly1 = labelY - lh;\n            ly2 = labelY;\n            break;\n\n          case 'center':\n            ly1 = labelY - lh_2;\n            ly2 = labelY + lh_2;\n            break;\n\n          case 'bottom':\n            ly1 = labelY;\n            ly2 = labelY + lh;\n            break;\n        }\n      } // shift by margin and expand by outline and border\n\n\n      lx1 += marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;\n      lx2 += marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;\n      ly1 += marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;\n      ly2 += marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError; // always store the unrotated label bounds separately\n\n      var bbPrefix = prefix || 'main';\n      var bbs = _p.labelBounds;\n      var bb = bbs[bbPrefix] = bbs[bbPrefix] || {};\n      bb.x1 = lx1;\n      bb.y1 = ly1;\n      bb.x2 = lx2;\n      bb.y2 = ly2;\n      bb.w = lx2 - lx1;\n      bb.h = ly2 - ly1;\n      var isAutorotate = isEdge && rotation.strValue === 'autorotate';\n      var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;\n\n      if (isAutorotate || isPfValue) {\n        var theta = isAutorotate ? prefixedProperty(_p.rstyle, 'labelAngle', prefix) : rotation.pfValue;\n        var cos = Math.cos(theta);\n        var sin = Math.sin(theta); // rotation point (default value for center-center)\n\n        var xo = (lx1 + lx2) / 2;\n        var yo = (ly1 + ly2) / 2;\n\n        if (!isEdge) {\n          switch (halign.value) {\n            case 'left':\n              xo = lx2;\n              break;\n\n            case 'right':\n              xo = lx1;\n              break;\n          }\n\n          switch (valign.value) {\n            case 'top':\n              yo = ly2;\n              break;\n\n            case 'bottom':\n              yo = ly1;\n              break;\n          }\n        }\n\n        var rotate = function rotate(x, y) {\n          x = x - xo;\n          y = y - yo;\n          return {\n            x: x * cos - y * sin + xo,\n            y: x * sin + y * cos + yo\n          };\n        };\n\n        var px1y1 = rotate(lx1, ly1);\n        var px1y2 = rotate(lx1, ly2);\n        var px2y1 = rotate(lx2, ly1);\n        var px2y2 = rotate(lx2, ly2);\n        lx1 = Math.min(px1y1.x, px1y2.x, px2y1.x, px2y2.x);\n        lx2 = Math.max(px1y1.x, px1y2.x, px2y1.x, px2y2.x);\n        ly1 = Math.min(px1y1.y, px1y2.y, px2y1.y, px2y2.y);\n        ly2 = Math.max(px1y1.y, px1y2.y, px2y1.y, px2y2.y);\n      }\n\n      var bbPrefixRot = bbPrefix + 'Rot';\n      var bbRot = bbs[bbPrefixRot] = bbs[bbPrefixRot] || {};\n      bbRot.x1 = lx1;\n      bbRot.y1 = ly1;\n      bbRot.x2 = lx2;\n      bbRot.y2 = ly2;\n      bbRot.w = lx2 - lx1;\n      bbRot.h = ly2 - ly1;\n      updateBounds(bounds, lx1, ly1, lx2, ly2);\n      updateBounds(_p.labelBounds.all, lx1, ly1, lx2, ly2);\n    }\n\n    return bounds;\n  }; // get the bounding box of the elements (in raw model position)\n\n\n  var boundingBoxImpl = function boundingBoxImpl(ele, options) {\n    var cy = ele._private.cy;\n    var styleEnabled = cy.styleEnabled();\n    var headless = cy.headless();\n    var bounds = makeBoundingBox();\n    var _p = ele._private;\n    var isNode = ele.isNode();\n    var isEdge = ele.isEdge();\n    var ex1, ex2, ey1, ey2; // extrema of body / lines\n\n    var x, y; // node pos\n\n    var rstyle = _p.rstyle;\n    var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0]; // must use `display` prop only, as reading `compound.width()` causes recursion\n    // (other factors like width values will be considered later in this function anyway)\n\n    var isDisplayed = function isDisplayed(ele) {\n      return ele.pstyle('display').value !== 'none';\n    };\n\n    var displayed = !styleEnabled || isDisplayed(ele) // must take into account connected nodes b/c of implicit edge hiding on display:none node\n    && (!isEdge || isDisplayed(ele.source()) && isDisplayed(ele.target()));\n\n    if (displayed) {\n      // displayed suffices, since we will find zero area eles anyway\n      var overlayOpacity = 0;\n      var overlayPadding = 0;\n\n      if (styleEnabled && options.includeOverlays) {\n        overlayOpacity = ele.pstyle('overlay-opacity').value;\n\n        if (overlayOpacity !== 0) {\n          overlayPadding = ele.pstyle('overlay-padding').value;\n        }\n      }\n\n      var underlayOpacity = 0;\n      var underlayPadding = 0;\n\n      if (styleEnabled && options.includeUnderlays) {\n        underlayOpacity = ele.pstyle('underlay-opacity').value;\n\n        if (underlayOpacity !== 0) {\n          underlayPadding = ele.pstyle('underlay-padding').value;\n        }\n      }\n\n      var padding = Math.max(overlayPadding, underlayPadding);\n      var w = 0;\n      var wHalf = 0;\n\n      if (styleEnabled) {\n        w = ele.pstyle('width').pfValue;\n        wHalf = w / 2;\n      }\n\n      if (isNode && options.includeNodes) {\n        var pos = ele.position();\n        x = pos.x;\n        y = pos.y;\n\n        var _w = ele.outerWidth();\n\n        var halfW = _w / 2;\n        var h = ele.outerHeight();\n        var halfH = h / 2; // handle node dimensions\n        /////////////////////////\n\n        ex1 = x - halfW;\n        ex2 = x + halfW;\n        ey1 = y - halfH;\n        ey2 = y + halfH;\n        updateBounds(bounds, ex1, ey1, ex2, ey2);\n      } else if (isEdge && options.includeEdges) {\n        if (styleEnabled && !headless) {\n          var curveStyle = ele.pstyle('curve-style').strValue; // handle edge dimensions (rough box estimate)\n          //////////////////////////////////////////////\n\n          ex1 = Math.min(rstyle.srcX, rstyle.midX, rstyle.tgtX);\n          ex2 = Math.max(rstyle.srcX, rstyle.midX, rstyle.tgtX);\n          ey1 = Math.min(rstyle.srcY, rstyle.midY, rstyle.tgtY);\n          ey2 = Math.max(rstyle.srcY, rstyle.midY, rstyle.tgtY); // take into account edge width\n\n          ex1 -= wHalf;\n          ex2 += wHalf;\n          ey1 -= wHalf;\n          ey2 += wHalf;\n          updateBounds(bounds, ex1, ey1, ex2, ey2); // precise edges\n          ////////////////\n\n          if (curveStyle === 'haystack') {\n            var hpts = rstyle.haystackPts;\n\n            if (hpts && hpts.length === 2) {\n              ex1 = hpts[0].x;\n              ey1 = hpts[0].y;\n              ex2 = hpts[1].x;\n              ey2 = hpts[1].y;\n\n              if (ex1 > ex2) {\n                var temp = ex1;\n                ex1 = ex2;\n                ex2 = temp;\n              }\n\n              if (ey1 > ey2) {\n                var _temp = ey1;\n                ey1 = ey2;\n                ey2 = _temp;\n              }\n\n              updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);\n            }\n          } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || curveStyle === 'segments' || curveStyle === 'taxi') {\n            var pts;\n\n            switch (curveStyle) {\n              case 'bezier':\n              case 'unbundled-bezier':\n                pts = rstyle.bezierPts;\n                break;\n\n              case 'segments':\n              case 'taxi':\n                pts = rstyle.linePts;\n                break;\n            }\n\n            if (pts != null) {\n              for (var j = 0; j < pts.length; j++) {\n                var pt = pts[j];\n                ex1 = pt.x - wHalf;\n                ex2 = pt.x + wHalf;\n                ey1 = pt.y - wHalf;\n                ey2 = pt.y + wHalf;\n                updateBounds(bounds, ex1, ey1, ex2, ey2);\n              }\n            }\n          } // bezier-like or segment-like edge\n\n        } else {\n          // headless or style disabled\n          // fallback on source and target positions\n          //////////////////////////////////////////\n          var n1 = ele.source();\n          var n1pos = n1.position();\n          var n2 = ele.target();\n          var n2pos = n2.position();\n          ex1 = n1pos.x;\n          ex2 = n2pos.x;\n          ey1 = n1pos.y;\n          ey2 = n2pos.y;\n\n          if (ex1 > ex2) {\n            var _temp2 = ex1;\n            ex1 = ex2;\n            ex2 = _temp2;\n          }\n\n          if (ey1 > ey2) {\n            var _temp3 = ey1;\n            ey1 = ey2;\n            ey2 = _temp3;\n          } // take into account edge width\n\n\n          ex1 -= wHalf;\n          ex2 += wHalf;\n          ey1 -= wHalf;\n          ey2 += wHalf;\n          updateBounds(bounds, ex1, ey1, ex2, ey2);\n        } // headless or style disabled\n\n      } // edges\n      // handle edge arrow size\n      /////////////////////////\n\n\n      if (styleEnabled && options.includeEdges && isEdge) {\n        updateBoundsFromArrow(bounds, ele, 'mid-source');\n        updateBoundsFromArrow(bounds, ele, 'mid-target');\n        updateBoundsFromArrow(bounds, ele, 'source');\n        updateBoundsFromArrow(bounds, ele, 'target');\n      } // ghost\n      ////////\n\n\n      if (styleEnabled) {\n        var ghost = ele.pstyle('ghost').value === 'yes';\n\n        if (ghost) {\n          var gx = ele.pstyle('ghost-offset-x').pfValue;\n          var gy = ele.pstyle('ghost-offset-y').pfValue;\n          updateBounds(bounds, bounds.x1 + gx, bounds.y1 + gy, bounds.x2 + gx, bounds.y2 + gy);\n        }\n      } // always store the body bounds separately from the labels\n\n\n      var bbBody = _p.bodyBounds = _p.bodyBounds || {};\n      assignBoundingBox(bbBody, bounds);\n      expandBoundingBoxSides(bbBody, manualExpansion);\n      expandBoundingBox(bbBody, 1); // expand to work around browser dimension inaccuracies\n      // overlay\n      //////////\n\n      if (styleEnabled) {\n        ex1 = bounds.x1;\n        ex2 = bounds.x2;\n        ey1 = bounds.y1;\n        ey2 = bounds.y2;\n        updateBounds(bounds, ex1 - padding, ey1 - padding, ex2 + padding, ey2 + padding);\n      } // always store the body bounds separately from the labels\n\n\n      var bbOverlay = _p.overlayBounds = _p.overlayBounds || {};\n      assignBoundingBox(bbOverlay, bounds);\n      expandBoundingBoxSides(bbOverlay, manualExpansion);\n      expandBoundingBox(bbOverlay, 1); // expand to work around browser dimension inaccuracies\n      // handle label dimensions\n      //////////////////////////\n\n      var bbLabels = _p.labelBounds = _p.labelBounds || {};\n\n      if (bbLabels.all != null) {\n        clearBoundingBox(bbLabels.all);\n      } else {\n        bbLabels.all = makeBoundingBox();\n      }\n\n      if (styleEnabled && options.includeLabels) {\n        if (options.includeMainLabels) {\n          updateBoundsFromLabel(bounds, ele, null);\n        }\n\n        if (isEdge) {\n          if (options.includeSourceLabels) {\n            updateBoundsFromLabel(bounds, ele, 'source');\n          }\n\n          if (options.includeTargetLabels) {\n            updateBoundsFromLabel(bounds, ele, 'target');\n          }\n        }\n      } // style enabled for labels\n\n    } // if displayed\n\n\n    bounds.x1 = noninf(bounds.x1);\n    bounds.y1 = noninf(bounds.y1);\n    bounds.x2 = noninf(bounds.x2);\n    bounds.y2 = noninf(bounds.y2);\n    bounds.w = noninf(bounds.x2 - bounds.x1);\n    bounds.h = noninf(bounds.y2 - bounds.y1);\n\n    if (bounds.w > 0 && bounds.h > 0 && displayed) {\n      expandBoundingBoxSides(bounds, manualExpansion); // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides\n\n      expandBoundingBox(bounds, 1);\n    }\n\n    return bounds;\n  };\n\n  var getKey = function getKey(opts) {\n    var i = 0;\n\n    var tf = function tf(val) {\n      return (val ? 1 : 0) << i++;\n    };\n\n    var key = 0;\n    key += tf(opts.incudeNodes);\n    key += tf(opts.includeEdges);\n    key += tf(opts.includeLabels);\n    key += tf(opts.includeMainLabels);\n    key += tf(opts.includeSourceLabels);\n    key += tf(opts.includeTargetLabels);\n    key += tf(opts.includeOverlays);\n    return key;\n  };\n\n  var getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {\n    if (ele.isEdge()) {\n      var p1 = ele.source().position();\n      var p2 = ele.target().position();\n\n      var r = function r(x) {\n        return Math.round(x);\n      };\n\n      return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);\n    } else {\n      return 0;\n    }\n  };\n\n  var cachedBoundingBoxImpl = function cachedBoundingBoxImpl(ele, opts) {\n    var _p = ele._private;\n    var bb;\n    var isEdge = ele.isEdge();\n    var key = opts == null ? defBbOptsKey : getKey(opts);\n    var usingDefOpts = key === defBbOptsKey;\n    var currPosKey = getBoundingBoxPosKey(ele);\n    var isPosKeySame = _p.bbCachePosKey === currPosKey;\n    var useCache = opts.useCache && isPosKeySame;\n\n    var isDirty = function isDirty(ele) {\n      return ele._private.bbCache == null || ele._private.styleDirty;\n    };\n\n    var needRecalc = !useCache || isDirty(ele) || isEdge && isDirty(ele.source()) || isDirty(ele.target());\n\n    if (needRecalc) {\n      if (!isPosKeySame) {\n        ele.recalculateRenderedStyle(useCache);\n      }\n\n      bb = boundingBoxImpl(ele, defBbOpts);\n      _p.bbCache = bb;\n      _p.bbCachePosKey = currPosKey;\n    } else {\n      bb = _p.bbCache;\n    } // not using def opts => need to build up bb from combination of sub bbs\n\n\n    if (!usingDefOpts) {\n      var isNode = ele.isNode();\n      bb = makeBoundingBox();\n\n      if (opts.includeNodes && isNode || opts.includeEdges && !isNode) {\n        if (opts.includeOverlays) {\n          updateBoundsFromBox(bb, _p.overlayBounds);\n        } else {\n          updateBoundsFromBox(bb, _p.bodyBounds);\n        }\n      }\n\n      if (opts.includeLabels) {\n        if (opts.includeMainLabels && (!isEdge || opts.includeSourceLabels && opts.includeTargetLabels)) {\n          updateBoundsFromBox(bb, _p.labelBounds.all);\n        } else {\n          if (opts.includeMainLabels) {\n            updateBoundsFromBox(bb, _p.labelBounds.mainRot);\n          }\n\n          if (opts.includeSourceLabels) {\n            updateBoundsFromBox(bb, _p.labelBounds.sourceRot);\n          }\n\n          if (opts.includeTargetLabels) {\n            updateBoundsFromBox(bb, _p.labelBounds.targetRot);\n          }\n        }\n      }\n\n      bb.w = bb.x2 - bb.x1;\n      bb.h = bb.y2 - bb.y1;\n    }\n\n    return bb;\n  };\n\n  var defBbOpts = {\n    includeNodes: true,\n    includeEdges: true,\n    includeLabels: true,\n    includeMainLabels: true,\n    includeSourceLabels: true,\n    includeTargetLabels: true,\n    includeOverlays: true,\n    includeUnderlays: true,\n    useCache: true\n  };\n  var defBbOptsKey = getKey(defBbOpts);\n  var filledBbOpts = defaults$g(defBbOpts);\n\n  elesfn$b.boundingBox = function (options) {\n    var bounds; // the main usecase is ele.boundingBox() for a single element with no/def options\n    // specified s.t. the cache is used, so check for this case to make it faster by\n    // avoiding the overhead of the rest of the function\n\n    if (this.length === 1 && this[0]._private.bbCache != null && !this[0]._private.styleDirty && (options === undefined || options.useCache === undefined || options.useCache === true)) {\n      if (options === undefined) {\n        options = defBbOpts;\n      } else {\n        options = filledBbOpts(options);\n      }\n\n      bounds = cachedBoundingBoxImpl(this[0], options);\n    } else {\n      bounds = makeBoundingBox();\n      options = options || defBbOpts;\n      var opts = filledBbOpts(options);\n      var eles = this;\n      var cy = eles.cy();\n      var styleEnabled = cy.styleEnabled();\n\n      if (styleEnabled) {\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          var _p = ele._private;\n          var currPosKey = getBoundingBoxPosKey(ele);\n          var isPosKeySame = _p.bbCachePosKey === currPosKey;\n          var useCache = opts.useCache && isPosKeySame && !_p.styleDirty;\n          ele.recalculateRenderedStyle(useCache);\n        }\n      }\n\n      this.updateCompoundBounds(!options.useCache);\n\n      for (var _i = 0; _i < eles.length; _i++) {\n        var _ele = eles[_i];\n        updateBoundsFromBox(bounds, cachedBoundingBoxImpl(_ele, opts));\n      }\n    }\n\n    bounds.x1 = noninf(bounds.x1);\n    bounds.y1 = noninf(bounds.y1);\n    bounds.x2 = noninf(bounds.x2);\n    bounds.y2 = noninf(bounds.y2);\n    bounds.w = noninf(bounds.x2 - bounds.x1);\n    bounds.h = noninf(bounds.y2 - bounds.y1);\n    return bounds;\n  };\n\n  elesfn$b.dirtyBoundingBoxCache = function () {\n    for (var i = 0; i < this.length; i++) {\n      var _p = this[i]._private;\n      _p.bbCache = null;\n      _p.bbCachePosKey = null;\n      _p.bodyBounds = null;\n      _p.overlayBounds = null;\n      _p.labelBounds.all = null;\n      _p.labelBounds.source = null;\n      _p.labelBounds.target = null;\n      _p.labelBounds.main = null;\n      _p.labelBounds.sourceRot = null;\n      _p.labelBounds.targetRot = null;\n      _p.labelBounds.mainRot = null;\n      _p.arrowBounds.source = null;\n      _p.arrowBounds.target = null;\n      _p.arrowBounds['mid-source'] = null;\n      _p.arrowBounds['mid-target'] = null;\n    }\n\n    this.emitAndNotify('bounds');\n    return this;\n  }; // private helper to get bounding box for custom node positions\n  // - good for perf in certain cases but currently requires dirtying the rendered style\n  // - would be better to not modify the nodes but the nodes are read directly everywhere in the renderer...\n  // - try to use for only things like discrete layouts where the node position would change anyway\n\n\n  elesfn$b.boundingBoxAt = function (fn) {\n    var nodes = this.nodes();\n    var cy = this.cy();\n    var hasCompoundNodes = cy.hasCompoundNodes();\n    var parents = cy.collection();\n\n    if (hasCompoundNodes) {\n      parents = nodes.filter(function (node) {\n        return node.isParent();\n      });\n      nodes = nodes.not(parents);\n    }\n\n    if (plainObject(fn)) {\n      var obj = fn;\n\n      fn = function fn() {\n        return obj;\n      };\n    }\n\n    var storeOldPos = function storeOldPos(node, i) {\n      return node._private.bbAtOldPos = fn(node, i);\n    };\n\n    var getOldPos = function getOldPos(node) {\n      return node._private.bbAtOldPos;\n    };\n\n    cy.startBatch();\n    nodes.forEach(storeOldPos).silentPositions(fn);\n\n    if (hasCompoundNodes) {\n      parents.dirtyCompoundBoundsCache();\n      parents.dirtyBoundingBoxCache();\n      parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle\n    }\n\n    var bb = copyBoundingBox(this.boundingBox({\n      useCache: false\n    }));\n    nodes.silentPositions(getOldPos);\n\n    if (hasCompoundNodes) {\n      parents.dirtyCompoundBoundsCache();\n      parents.dirtyBoundingBoxCache();\n      parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle\n    }\n\n    cy.endBatch();\n    return bb;\n  };\n\n  fn$3.boundingbox = fn$3.bb = fn$3.boundingBox;\n  fn$3.renderedBoundingbox = fn$3.renderedBoundingBox;\n  var bounds = elesfn$b;\n\n  var fn$2, elesfn$a;\n  fn$2 = elesfn$a = {};\n\n  var defineDimFns = function defineDimFns(opts) {\n    opts.uppercaseName = capitalize(opts.name);\n    opts.autoName = 'auto' + opts.uppercaseName;\n    opts.labelName = 'label' + opts.uppercaseName;\n    opts.outerName = 'outer' + opts.uppercaseName;\n    opts.uppercaseOuterName = capitalize(opts.outerName);\n\n    fn$2[opts.name] = function dimImpl() {\n      var ele = this[0];\n      var _p = ele._private;\n      var cy = _p.cy;\n      var styleEnabled = cy._private.styleEnabled;\n\n      if (ele) {\n        if (styleEnabled) {\n          if (ele.isParent()) {\n            ele.updateCompoundBounds();\n            return _p[opts.autoName] || 0;\n          }\n\n          var d = ele.pstyle(opts.name);\n\n          switch (d.strValue) {\n            case 'label':\n              ele.recalculateRenderedStyle();\n              return _p.rstyle[opts.labelName] || 0;\n\n            default:\n              return d.pfValue;\n          }\n        } else {\n          return 1;\n        }\n      }\n    };\n\n    fn$2['outer' + opts.uppercaseName] = function outerDimImpl() {\n      var ele = this[0];\n      var _p = ele._private;\n      var cy = _p.cy;\n      var styleEnabled = cy._private.styleEnabled;\n\n      if (ele) {\n        if (styleEnabled) {\n          var dim = ele[opts.name]();\n          var border = ele.pstyle('border-width').pfValue; // n.b. 1/2 each side\n\n          var padding = 2 * ele.padding();\n          return dim + border + padding;\n        } else {\n          return 1;\n        }\n      }\n    };\n\n    fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {\n      var ele = this[0];\n\n      if (ele) {\n        var d = ele[opts.name]();\n        return d * this.cy().zoom();\n      }\n    };\n\n    fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {\n      var ele = this[0];\n\n      if (ele) {\n        var od = ele[opts.outerName]();\n        return od * this.cy().zoom();\n      }\n    };\n  };\n\n  defineDimFns({\n    name: 'width'\n  });\n  defineDimFns({\n    name: 'height'\n  });\n\n  elesfn$a.padding = function () {\n    var ele = this[0];\n    var _p = ele._private;\n\n    if (ele.isParent()) {\n      ele.updateCompoundBounds();\n\n      if (_p.autoPadding !== undefined) {\n        return _p.autoPadding;\n      } else {\n        return ele.pstyle('padding').pfValue;\n      }\n    } else {\n      return ele.pstyle('padding').pfValue;\n    }\n  };\n\n  elesfn$a.paddedHeight = function () {\n    var ele = this[0];\n    return ele.height() + 2 * ele.padding();\n  };\n\n  elesfn$a.paddedWidth = function () {\n    var ele = this[0];\n    return ele.width() + 2 * ele.padding();\n  };\n\n  var widthHeight = elesfn$a;\n\n  var ifEdge = function ifEdge(ele, getValue) {\n    if (ele.isEdge()) {\n      return getValue(ele);\n    }\n  };\n\n  var ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {\n    if (ele.isEdge()) {\n      var cy = ele.cy();\n      return modelToRenderedPosition(getPoint(ele), cy.zoom(), cy.pan());\n    }\n  };\n\n  var ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {\n    if (ele.isEdge()) {\n      var cy = ele.cy();\n      var pan = cy.pan();\n      var zoom = cy.zoom();\n      return getPoints(ele).map(function (p) {\n        return modelToRenderedPosition(p, zoom, pan);\n      });\n    }\n  };\n\n  var controlPoints = function controlPoints(ele) {\n    return ele.renderer().getControlPoints(ele);\n  };\n\n  var segmentPoints = function segmentPoints(ele) {\n    return ele.renderer().getSegmentPoints(ele);\n  };\n\n  var sourceEndpoint = function sourceEndpoint(ele) {\n    return ele.renderer().getSourceEndpoint(ele);\n  };\n\n  var targetEndpoint = function targetEndpoint(ele) {\n    return ele.renderer().getTargetEndpoint(ele);\n  };\n\n  var midpoint = function midpoint(ele) {\n    return ele.renderer().getEdgeMidpoint(ele);\n  };\n\n  var pts = {\n    controlPoints: {\n      get: controlPoints,\n      mult: true\n    },\n    segmentPoints: {\n      get: segmentPoints,\n      mult: true\n    },\n    sourceEndpoint: {\n      get: sourceEndpoint\n    },\n    targetEndpoint: {\n      get: targetEndpoint\n    },\n    midpoint: {\n      get: midpoint\n    }\n  };\n\n  var renderedName = function renderedName(name) {\n    return 'rendered' + name[0].toUpperCase() + name.substr(1);\n  };\n\n  var edgePoints = Object.keys(pts).reduce(function (obj, name) {\n    var spec = pts[name];\n    var rName = renderedName(name);\n\n    obj[name] = function () {\n      return ifEdge(this, spec.get);\n    };\n\n    if (spec.mult) {\n      obj[rName] = function () {\n        return ifEdgeRenderedPositions(this, spec.get);\n      };\n    } else {\n      obj[rName] = function () {\n        return ifEdgeRenderedPosition(this, spec.get);\n      };\n    }\n\n    return obj;\n  }, {});\n\n  var dimensions = extend({}, position, bounds, widthHeight, edgePoints);\n\n  /*!\n  Event object based on jQuery events, MIT license\n\n  https://jquery.org/license/\n  https://tldrlegal.com/license/mit-license\n  https://github.com/jquery/jquery/blob/master/src/event.js\n  */\n  var Event = function Event(src, props) {\n    this.recycle(src, props);\n  };\n\n  function returnFalse() {\n    return false;\n  }\n\n  function returnTrue() {\n    return true;\n  } // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html\n\n\n  Event.prototype = {\n    instanceString: function instanceString() {\n      return 'event';\n    },\n    recycle: function recycle(src, props) {\n      this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;\n\n      if (src != null && src.preventDefault) {\n        // Browser Event object\n        this.type = src.type; // Events bubbling up the document may have been marked as prevented\n        // by a handler lower down the tree; reflect the correct value.\n\n        this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse;\n      } else if (src != null && src.type) {\n        // Plain object containing all event details\n        props = src;\n      } else {\n        // Event string\n        this.type = src;\n      } // Put explicitly provided properties onto the event object\n\n\n      if (props != null) {\n        // more efficient to manually copy fields we use\n        this.originalEvent = props.originalEvent;\n        this.type = props.type != null ? props.type : this.type;\n        this.cy = props.cy;\n        this.target = props.target;\n        this.position = props.position;\n        this.renderedPosition = props.renderedPosition;\n        this.namespace = props.namespace;\n        this.layout = props.layout;\n      }\n\n      if (this.cy != null && this.position != null && this.renderedPosition == null) {\n        // create a rendered position based on the passed position\n        var pos = this.position;\n        var zoom = this.cy.zoom();\n        var pan = this.cy.pan();\n        this.renderedPosition = {\n          x: pos.x * zoom + pan.x,\n          y: pos.y * zoom + pan.y\n        };\n      } // Create a timestamp if incoming event doesn't have one\n\n\n      this.timeStamp = src && src.timeStamp || Date.now();\n    },\n    preventDefault: function preventDefault() {\n      this.isDefaultPrevented = returnTrue;\n      var e = this.originalEvent;\n\n      if (!e) {\n        return;\n      } // if preventDefault exists run it on the original event\n\n\n      if (e.preventDefault) {\n        e.preventDefault();\n      }\n    },\n    stopPropagation: function stopPropagation() {\n      this.isPropagationStopped = returnTrue;\n      var e = this.originalEvent;\n\n      if (!e) {\n        return;\n      } // if stopPropagation exists run it on the original event\n\n\n      if (e.stopPropagation) {\n        e.stopPropagation();\n      }\n    },\n    stopImmediatePropagation: function stopImmediatePropagation() {\n      this.isImmediatePropagationStopped = returnTrue;\n      this.stopPropagation();\n    },\n    isDefaultPrevented: returnFalse,\n    isPropagationStopped: returnFalse,\n    isImmediatePropagationStopped: returnFalse\n  };\n\n  var eventRegex = /^([^.]+)(\\.(?:[^.]+))?$/; // regex for matching event strings (e.g. \"click.namespace\")\n\n  var universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally\n\n  var defaults$8 = {\n    qualifierCompare: function qualifierCompare(q1, q2) {\n      return q1 === q2;\n    },\n    eventMatches: function\n      /*context, listener, eventObj*/\n    eventMatches() {\n      return true;\n    },\n    addEventFields: function\n      /*context, evt*/\n    addEventFields() {},\n    callbackContext: function callbackContext(context\n    /*, listener, eventObj*/\n    ) {\n      return context;\n    },\n    beforeEmit: function\n      /* context, listener, eventObj */\n    beforeEmit() {},\n    afterEmit: function\n      /* context, listener, eventObj */\n    afterEmit() {},\n    bubble: function\n      /*context*/\n    bubble() {\n      return false;\n    },\n    parent: function\n      /*context*/\n    parent() {\n      return null;\n    },\n    context: null\n  };\n  var defaultsKeys = Object.keys(defaults$8);\n  var emptyOpts = {};\n\n  function Emitter() {\n    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;\n    var context = arguments.length > 1 ? arguments[1] : undefined;\n\n    // micro-optimisation vs Object.assign() -- reduces Element instantiation time\n    for (var i = 0; i < defaultsKeys.length; i++) {\n      var key = defaultsKeys[i];\n      this[key] = opts[key] || defaults$8[key];\n    }\n\n    this.context = context || this.context;\n    this.listeners = [];\n    this.emitting = 0;\n  }\n\n  var p = Emitter.prototype;\n\n  var forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {\n    if (fn$6(qualifier)) {\n      callback = qualifier;\n      qualifier = null;\n    }\n\n    if (confOverrides) {\n      if (conf == null) {\n        conf = confOverrides;\n      } else {\n        conf = extend({}, conf, confOverrides);\n      }\n    }\n\n    var eventList = array(events) ? events : events.split(/\\s+/);\n\n    for (var i = 0; i < eventList.length; i++) {\n      var evt = eventList[i];\n\n      if (emptyString(evt)) {\n        continue;\n      }\n\n      var match = evt.match(eventRegex); // type[.namespace]\n\n      if (match) {\n        var type = match[1];\n        var namespace = match[2] ? match[2] : null;\n        var ret = handler(self, evt, type, namespace, qualifier, callback, conf);\n\n        if (ret === false) {\n          break;\n        } // allow exiting early\n\n      }\n    }\n  };\n\n  var makeEventObj = function makeEventObj(self, obj) {\n    self.addEventFields(self.context, obj);\n    return new Event(obj.type, obj);\n  };\n\n  var forEachEventObj = function forEachEventObj(self, handler, events) {\n    if (event(events)) {\n      handler(self, events);\n      return;\n    } else if (plainObject(events)) {\n      handler(self, makeEventObj(self, events));\n      return;\n    }\n\n    var eventList = array(events) ? events : events.split(/\\s+/);\n\n    for (var i = 0; i < eventList.length; i++) {\n      var evt = eventList[i];\n\n      if (emptyString(evt)) {\n        continue;\n      }\n\n      var match = evt.match(eventRegex); // type[.namespace]\n\n      if (match) {\n        var type = match[1];\n        var namespace = match[2] ? match[2] : null;\n        var eventObj = makeEventObj(self, {\n          type: type,\n          namespace: namespace,\n          target: self.context\n        });\n        handler(self, eventObj);\n      }\n    }\n  };\n\n  p.on = p.addListener = function (events, qualifier, callback, conf, confOverrides) {\n    forEachEvent(this, function (self, event, type, namespace, qualifier, callback, conf) {\n      if (fn$6(callback)) {\n        self.listeners.push({\n          event: event,\n          // full event string\n          callback: callback,\n          // callback to run\n          type: type,\n          // the event type (e.g. 'click')\n          namespace: namespace,\n          // the event namespace (e.g. \".foo\")\n          qualifier: qualifier,\n          // a restriction on whether to match this emitter\n          conf: conf // additional configuration\n\n        });\n      }\n    }, events, qualifier, callback, conf, confOverrides);\n    return this;\n  };\n\n  p.one = function (events, qualifier, callback, conf) {\n    return this.on(events, qualifier, callback, conf, {\n      one: true\n    });\n  };\n\n  p.removeListener = p.off = function (events, qualifier, callback, conf) {\n    var _this = this;\n\n    if (this.emitting !== 0) {\n      this.listeners = copyArray$1(this.listeners);\n    }\n\n    var listeners = this.listeners;\n\n    var _loop = function _loop(i) {\n      var listener = listeners[i];\n      forEachEvent(_this, function (self, event, type, namespace, qualifier, callback\n      /*, conf*/\n      ) {\n        if ((listener.type === type || events === '*') && (!namespace && listener.namespace !== '.*' || listener.namespace === namespace) && (!qualifier || self.qualifierCompare(listener.qualifier, qualifier)) && (!callback || listener.callback === callback)) {\n          listeners.splice(i, 1);\n          return false;\n        }\n      }, events, qualifier, callback, conf);\n    };\n\n    for (var i = listeners.length - 1; i >= 0; i--) {\n      _loop(i);\n    }\n\n    return this;\n  };\n\n  p.removeAllListeners = function () {\n    return this.removeListener('*');\n  };\n\n  p.emit = p.trigger = function (events, extraParams, manualCallback) {\n    var listeners = this.listeners;\n    var numListenersBeforeEmit = listeners.length;\n    this.emitting++;\n\n    if (!array(extraParams)) {\n      extraParams = [extraParams];\n    }\n\n    forEachEventObj(this, function (self, eventObj) {\n      if (manualCallback != null) {\n        listeners = [{\n          event: eventObj.event,\n          type: eventObj.type,\n          namespace: eventObj.namespace,\n          callback: manualCallback\n        }];\n        numListenersBeforeEmit = listeners.length;\n      }\n\n      var _loop2 = function _loop2(i) {\n        var listener = listeners[i];\n\n        if (listener.type === eventObj.type && (!listener.namespace || listener.namespace === eventObj.namespace || listener.namespace === universalNamespace) && self.eventMatches(self.context, listener, eventObj)) {\n          var args = [eventObj];\n\n          if (extraParams != null) {\n            push(args, extraParams);\n          }\n\n          self.beforeEmit(self.context, listener, eventObj);\n\n          if (listener.conf && listener.conf.one) {\n            self.listeners = self.listeners.filter(function (l) {\n              return l !== listener;\n            });\n          }\n\n          var context = self.callbackContext(self.context, listener, eventObj);\n          var ret = listener.callback.apply(context, args);\n          self.afterEmit(self.context, listener, eventObj);\n\n          if (ret === false) {\n            eventObj.stopPropagation();\n            eventObj.preventDefault();\n          }\n        } // if listener matches\n\n      };\n\n      for (var i = 0; i < numListenersBeforeEmit; i++) {\n        _loop2(i);\n      } // for listener\n\n\n      if (self.bubble(self.context) && !eventObj.isPropagationStopped()) {\n        self.parent(self.context).emit(eventObj, extraParams);\n      }\n    }, events);\n    this.emitting--;\n    return this;\n  };\n\n  var emitterOptions$1 = {\n    qualifierCompare: function qualifierCompare(selector1, selector2) {\n      if (selector1 == null || selector2 == null) {\n        return selector1 == null && selector2 == null;\n      } else {\n        return selector1.sameText(selector2);\n      }\n    },\n    eventMatches: function eventMatches(ele, listener, eventObj) {\n      var selector = listener.qualifier;\n\n      if (selector != null) {\n        return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);\n      }\n\n      return true;\n    },\n    addEventFields: function addEventFields(ele, evt) {\n      evt.cy = ele.cy();\n      evt.target = ele;\n    },\n    callbackContext: function callbackContext(ele, listener, eventObj) {\n      return listener.qualifier != null ? eventObj.target : ele;\n    },\n    beforeEmit: function beforeEmit(context, listener\n    /*, eventObj*/\n    ) {\n      if (listener.conf && listener.conf.once) {\n        listener.conf.onceCollection.removeListener(listener.event, listener.qualifier, listener.callback);\n      }\n    },\n    bubble: function bubble() {\n      return true;\n    },\n    parent: function parent(ele) {\n      return ele.isChild() ? ele.parent() : ele.cy();\n    }\n  };\n\n  var argSelector$1 = function argSelector(arg) {\n    if (string(arg)) {\n      return new Selector(arg);\n    } else {\n      return arg;\n    }\n  };\n\n  var elesfn$9 = {\n    createEmitter: function createEmitter() {\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        var _p = ele._private;\n\n        if (!_p.emitter) {\n          _p.emitter = new Emitter(emitterOptions$1, ele);\n        }\n      }\n\n      return this;\n    },\n    emitter: function emitter() {\n      return this._private.emitter;\n    },\n    on: function on(events, selector, callback) {\n      var argSel = argSelector$1(selector);\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        ele.emitter().on(events, argSel, callback);\n      }\n\n      return this;\n    },\n    removeListener: function removeListener(events, selector, callback) {\n      var argSel = argSelector$1(selector);\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        ele.emitter().removeListener(events, argSel, callback);\n      }\n\n      return this;\n    },\n    removeAllListeners: function removeAllListeners() {\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        ele.emitter().removeAllListeners();\n      }\n\n      return this;\n    },\n    one: function one(events, selector, callback) {\n      var argSel = argSelector$1(selector);\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        ele.emitter().one(events, argSel, callback);\n      }\n\n      return this;\n    },\n    once: function once(events, selector, callback) {\n      var argSel = argSelector$1(selector);\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        ele.emitter().on(events, argSel, callback, {\n          once: true,\n          onceCollection: this\n        });\n      }\n    },\n    emit: function emit(events, extraParams) {\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        ele.emitter().emit(events, extraParams);\n      }\n\n      return this;\n    },\n    emitAndNotify: function emitAndNotify(event, extraParams) {\n      // for internal use only\n      if (this.length === 0) {\n        return;\n      } // empty collections don't need to notify anything\n      // notify renderer\n\n\n      this.cy().notify(event, this);\n      this.emit(event, extraParams);\n      return this;\n    }\n  };\n  define.eventAliasesOn(elesfn$9);\n\n  var elesfn$8 = {\n    nodes: function nodes(selector) {\n      return this.filter(function (ele) {\n        return ele.isNode();\n      }).filter(selector);\n    },\n    edges: function edges(selector) {\n      return this.filter(function (ele) {\n        return ele.isEdge();\n      }).filter(selector);\n    },\n    // internal helper to get nodes and edges as separate collections with single iteration over elements\n    byGroup: function byGroup() {\n      var nodes = this.spawn();\n      var edges = this.spawn();\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n\n        if (ele.isNode()) {\n          nodes.push(ele);\n        } else {\n          edges.push(ele);\n        }\n      }\n\n      return {\n        nodes: nodes,\n        edges: edges\n      };\n    },\n    filter: function filter(_filter, thisArg) {\n      if (_filter === undefined) {\n        // check this first b/c it's the most common/performant case\n        return this;\n      } else if (string(_filter) || elementOrCollection(_filter)) {\n        return new Selector(_filter).filter(this);\n      } else if (fn$6(_filter)) {\n        var filterEles = this.spawn();\n        var eles = this;\n\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          var include = thisArg ? _filter.apply(thisArg, [ele, i, eles]) : _filter(ele, i, eles);\n\n          if (include) {\n            filterEles.push(ele);\n          }\n        }\n\n        return filterEles;\n      }\n\n      return this.spawn(); // if not handled by above, give 'em an empty collection\n    },\n    not: function not(toRemove) {\n      if (!toRemove) {\n        return this;\n      } else {\n        if (string(toRemove)) {\n          toRemove = this.filter(toRemove);\n        }\n\n        var elements = this.spawn();\n\n        for (var i = 0; i < this.length; i++) {\n          var element = this[i];\n          var remove = toRemove.has(element);\n\n          if (!remove) {\n            elements.push(element);\n          }\n        }\n\n        return elements;\n      }\n    },\n    absoluteComplement: function absoluteComplement() {\n      var cy = this.cy();\n      return cy.mutableElements().not(this);\n    },\n    intersect: function intersect(other) {\n      // if a selector is specified, then filter by it instead\n      if (string(other)) {\n        var selector = other;\n        return this.filter(selector);\n      }\n\n      var elements = this.spawn();\n      var col1 = this;\n      var col2 = other;\n      var col1Smaller = this.length < other.length;\n      var colS = col1Smaller ? col1 : col2;\n      var colL = col1Smaller ? col2 : col1;\n\n      for (var i = 0; i < colS.length; i++) {\n        var ele = colS[i];\n\n        if (colL.has(ele)) {\n          elements.push(ele);\n        }\n      }\n\n      return elements;\n    },\n    xor: function xor(other) {\n      var cy = this._private.cy;\n\n      if (string(other)) {\n        other = cy.$(other);\n      }\n\n      var elements = this.spawn();\n      var col1 = this;\n      var col2 = other;\n\n      var add = function add(col, other) {\n        for (var i = 0; i < col.length; i++) {\n          var ele = col[i];\n          var id = ele._private.data.id;\n          var inOther = other.hasElementWithId(id);\n\n          if (!inOther) {\n            elements.push(ele);\n          }\n        }\n      };\n\n      add(col1, col2);\n      add(col2, col1);\n      return elements;\n    },\n    diff: function diff(other) {\n      var cy = this._private.cy;\n\n      if (string(other)) {\n        other = cy.$(other);\n      }\n\n      var left = this.spawn();\n      var right = this.spawn();\n      var both = this.spawn();\n      var col1 = this;\n      var col2 = other;\n\n      var add = function add(col, other, retEles) {\n        for (var i = 0; i < col.length; i++) {\n          var ele = col[i];\n          var id = ele._private.data.id;\n          var inOther = other.hasElementWithId(id);\n\n          if (inOther) {\n            both.merge(ele);\n          } else {\n            retEles.push(ele);\n          }\n        }\n      };\n\n      add(col1, col2, left);\n      add(col2, col1, right);\n      return {\n        left: left,\n        right: right,\n        both: both\n      };\n    },\n    add: function add(toAdd) {\n      var cy = this._private.cy;\n\n      if (!toAdd) {\n        return this;\n      }\n\n      if (string(toAdd)) {\n        var selector = toAdd;\n        toAdd = cy.mutableElements().filter(selector);\n      }\n\n      var elements = this.spawnSelf();\n\n      for (var i = 0; i < toAdd.length; i++) {\n        var ele = toAdd[i];\n        var add = !this.has(ele);\n\n        if (add) {\n          elements.push(ele);\n        }\n      }\n\n      return elements;\n    },\n    // in place merge on calling collection\n    merge: function merge(toAdd) {\n      var _p = this._private;\n      var cy = _p.cy;\n\n      if (!toAdd) {\n        return this;\n      }\n\n      if (toAdd && string(toAdd)) {\n        var selector = toAdd;\n        toAdd = cy.mutableElements().filter(selector);\n      }\n\n      var map = _p.map;\n\n      for (var i = 0; i < toAdd.length; i++) {\n        var toAddEle = toAdd[i];\n        var id = toAddEle._private.data.id;\n        var add = !map.has(id);\n\n        if (add) {\n          var index = this.length++;\n          this[index] = toAddEle;\n          map.set(id, {\n            ele: toAddEle,\n            index: index\n          });\n        }\n      }\n\n      return this; // chaining\n    },\n    unmergeAt: function unmergeAt(i) {\n      var ele = this[i];\n      var id = ele.id();\n      var _p = this._private;\n      var map = _p.map; // remove ele\n\n      this[i] = undefined;\n      map[\"delete\"](id);\n      var unmergedLastEle = i === this.length - 1; // replace empty spot with last ele in collection\n\n      if (this.length > 1 && !unmergedLastEle) {\n        var lastEleI = this.length - 1;\n        var lastEle = this[lastEleI];\n        var lastEleId = lastEle._private.data.id;\n        this[lastEleI] = undefined;\n        this[i] = lastEle;\n        map.set(lastEleId, {\n          ele: lastEle,\n          index: i\n        });\n      } // the collection is now 1 ele smaller\n\n\n      this.length--;\n      return this;\n    },\n    // remove single ele in place in calling collection\n    unmergeOne: function unmergeOne(ele) {\n      ele = ele[0];\n      var _p = this._private;\n      var id = ele._private.data.id;\n      var map = _p.map;\n      var entry = map.get(id);\n\n      if (!entry) {\n        return this; // no need to remove\n      }\n\n      var i = entry.index;\n      this.unmergeAt(i);\n      return this;\n    },\n    // remove eles in place on calling collection\n    unmerge: function unmerge(toRemove) {\n      var cy = this._private.cy;\n\n      if (!toRemove) {\n        return this;\n      }\n\n      if (toRemove && string(toRemove)) {\n        var selector = toRemove;\n        toRemove = cy.mutableElements().filter(selector);\n      }\n\n      for (var i = 0; i < toRemove.length; i++) {\n        this.unmergeOne(toRemove[i]);\n      }\n\n      return this; // chaining\n    },\n    unmergeBy: function unmergeBy(toRmFn) {\n      for (var i = this.length - 1; i >= 0; i--) {\n        var ele = this[i];\n\n        if (toRmFn(ele)) {\n          this.unmergeAt(i);\n        }\n      }\n\n      return this;\n    },\n    map: function map(mapFn, thisArg) {\n      var arr = [];\n      var eles = this;\n\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n        var ret = thisArg ? mapFn.apply(thisArg, [ele, i, eles]) : mapFn(ele, i, eles);\n        arr.push(ret);\n      }\n\n      return arr;\n    },\n    reduce: function reduce(fn, initialValue) {\n      var val = initialValue;\n      var eles = this;\n\n      for (var i = 0; i < eles.length; i++) {\n        val = fn(val, eles[i], i, eles);\n      }\n\n      return val;\n    },\n    max: function max(valFn, thisArg) {\n      var max = -Infinity;\n      var maxEle;\n      var eles = this;\n\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n        var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);\n\n        if (val > max) {\n          max = val;\n          maxEle = ele;\n        }\n      }\n\n      return {\n        value: max,\n        ele: maxEle\n      };\n    },\n    min: function min(valFn, thisArg) {\n      var min = Infinity;\n      var minEle;\n      var eles = this;\n\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n        var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);\n\n        if (val < min) {\n          min = val;\n          minEle = ele;\n        }\n      }\n\n      return {\n        value: min,\n        ele: minEle\n      };\n    }\n  }; // aliases\n\n  var fn$1 = elesfn$8;\n  fn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;\n  fn$1['\\\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;\n  fn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;\n  fn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;\n  fn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;\n  fn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;\n\n  var elesfn$7 = {\n    isNode: function isNode() {\n      return this.group() === 'nodes';\n    },\n    isEdge: function isEdge() {\n      return this.group() === 'edges';\n    },\n    isLoop: function isLoop() {\n      return this.isEdge() && this.source()[0] === this.target()[0];\n    },\n    isSimple: function isSimple() {\n      return this.isEdge() && this.source()[0] !== this.target()[0];\n    },\n    group: function group() {\n      var ele = this[0];\n\n      if (ele) {\n        return ele._private.group;\n      }\n    }\n  };\n\n  /**\n   *  Elements are drawn in a specific order based on compound depth (low to high), the element type (nodes above edges),\n   *  and z-index (low to high).  These styles affect how this applies:\n   *\n   *  z-compound-depth: May be `bottom | orphan | auto | top`.  The first drawn is `bottom`, then `orphan` which is the\n   *      same depth as the root of the compound graph, followed by the default value `auto` which draws in order from\n   *      root to leaves of the compound graph.  The last drawn is `top`.\n   *  z-index-compare: May be `auto | manual`.  The default value is `auto` which always draws edges under nodes.\n   *      `manual` ignores this convention and draws based on the `z-index` value setting.\n   *  z-index: An integer value that affects the relative draw order of elements.  In general, an element with a higher\n   *      `z-index` will be drawn on top of an element with a lower `z-index`.\n   */\n\n  var zIndexSort = function zIndexSort(a, b) {\n    var cy = a.cy();\n    var hasCompoundNodes = cy.hasCompoundNodes();\n\n    function getDepth(ele) {\n      var style = ele.pstyle('z-compound-depth');\n\n      if (style.value === 'auto') {\n        return hasCompoundNodes ? ele.zDepth() : 0;\n      } else if (style.value === 'bottom') {\n        return -1;\n      } else if (style.value === 'top') {\n        return MAX_INT$1;\n      } // 'orphan'\n\n\n      return 0;\n    }\n\n    var depthDiff = getDepth(a) - getDepth(b);\n\n    if (depthDiff !== 0) {\n      return depthDiff;\n    }\n\n    function getEleDepth(ele) {\n      var style = ele.pstyle('z-index-compare');\n\n      if (style.value === 'auto') {\n        return ele.isNode() ? 1 : 0;\n      } // 'manual'\n\n\n      return 0;\n    }\n\n    var eleDiff = getEleDepth(a) - getEleDepth(b);\n\n    if (eleDiff !== 0) {\n      return eleDiff;\n    }\n\n    var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;\n\n    if (zDiff !== 0) {\n      return zDiff;\n    } // compare indices in the core (order added to graph w/ last on top)\n\n\n    return a.poolIndex() - b.poolIndex();\n  };\n\n  var elesfn$6 = {\n    forEach: function forEach(fn, thisArg) {\n      if (fn$6(fn)) {\n        var N = this.length;\n\n        for (var i = 0; i < N; i++) {\n          var ele = this[i];\n          var ret = thisArg ? fn.apply(thisArg, [ele, i, this]) : fn(ele, i, this);\n\n          if (ret === false) {\n            break;\n          } // exit each early on return false\n\n        }\n      }\n\n      return this;\n    },\n    toArray: function toArray() {\n      var array = [];\n\n      for (var i = 0; i < this.length; i++) {\n        array.push(this[i]);\n      }\n\n      return array;\n    },\n    slice: function slice(start, end) {\n      var array = [];\n      var thisSize = this.length;\n\n      if (end == null) {\n        end = thisSize;\n      }\n\n      if (start == null) {\n        start = 0;\n      }\n\n      if (start < 0) {\n        start = thisSize + start;\n      }\n\n      if (end < 0) {\n        end = thisSize + end;\n      }\n\n      for (var i = start; i >= 0 && i < end && i < thisSize; i++) {\n        array.push(this[i]);\n      }\n\n      return this.spawn(array);\n    },\n    size: function size() {\n      return this.length;\n    },\n    eq: function eq(i) {\n      return this[i] || this.spawn();\n    },\n    first: function first() {\n      return this[0] || this.spawn();\n    },\n    last: function last() {\n      return this[this.length - 1] || this.spawn();\n    },\n    empty: function empty() {\n      return this.length === 0;\n    },\n    nonempty: function nonempty() {\n      return !this.empty();\n    },\n    sort: function sort(sortFn) {\n      if (!fn$6(sortFn)) {\n        return this;\n      }\n\n      var sorted = this.toArray().sort(sortFn);\n      return this.spawn(sorted);\n    },\n    sortByZIndex: function sortByZIndex() {\n      return this.sort(zIndexSort);\n    },\n    zDepth: function zDepth() {\n      var ele = this[0];\n\n      if (!ele) {\n        return undefined;\n      } // let cy = ele.cy();\n\n\n      var _p = ele._private;\n      var group = _p.group;\n\n      if (group === 'nodes') {\n        var depth = _p.data.parent ? ele.parents().size() : 0;\n\n        if (!ele.isParent()) {\n          return MAX_INT$1 - 1; // childless nodes always on top\n        }\n\n        return depth;\n      } else {\n        var src = _p.source;\n        var tgt = _p.target;\n        var srcDepth = src.zDepth();\n        var tgtDepth = tgt.zDepth();\n        return Math.max(srcDepth, tgtDepth, 0); // depth of deepest parent\n      }\n    }\n  };\n  elesfn$6.each = elesfn$6.forEach;\n\n  var defineSymbolIterator = function defineSymbolIterator() {\n    var typeofUndef = \"undefined\" ;\n    var isIteratorSupported = (typeof Symbol === \"undefined\" ? \"undefined\" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef; // eslint-disable-line no-undef\n\n    if (isIteratorSupported) {\n      elesfn$6[Symbol.iterator] = function () {\n        var _this = this;\n\n        // eslint-disable-line no-undef\n        var entry = {\n          value: undefined,\n          done: false\n        };\n        var i = 0;\n        var length = this.length;\n        return _defineProperty$1({\n          next: function next() {\n            if (i < length) {\n              entry.value = _this[i++];\n            } else {\n              entry.value = undefined;\n              entry.done = true;\n            }\n\n            return entry;\n          }\n        }, Symbol.iterator, function () {\n          // eslint-disable-line no-undef\n          return this;\n        });\n      };\n    }\n  };\n\n  defineSymbolIterator();\n\n  var getLayoutDimensionOptions = defaults$g({\n    nodeDimensionsIncludeLabels: false\n  });\n  var elesfn$5 = {\n    // Calculates and returns node dimensions { x, y } based on options given\n    layoutDimensions: function layoutDimensions(options) {\n      options = getLayoutDimensionOptions(options);\n      var dims;\n\n      if (!this.takesUpSpace()) {\n        dims = {\n          w: 0,\n          h: 0\n        };\n      } else if (options.nodeDimensionsIncludeLabels) {\n        var bbDim = this.boundingBox();\n        dims = {\n          w: bbDim.w,\n          h: bbDim.h\n        };\n      } else {\n        dims = {\n          w: this.outerWidth(),\n          h: this.outerHeight()\n        };\n      } // sanitise the dimensions for external layouts (avoid division by zero)\n\n\n      if (dims.w === 0 || dims.h === 0) {\n        dims.w = dims.h = 1;\n      }\n\n      return dims;\n    },\n    // using standard layout options, apply position function (w/ or w/o animation)\n    layoutPositions: function layoutPositions(layout, options, fn) {\n      var nodes = this.nodes().filter(function (n) {\n        return !n.isParent();\n      });\n      var cy = this.cy();\n      var layoutEles = options.eles; // nodes & edges\n\n      var getMemoizeKey = function getMemoizeKey(node) {\n        return node.id();\n      };\n\n      var fnMem = memoize$1(fn, getMemoizeKey); // memoized version of position function\n\n      layout.emit({\n        type: 'layoutstart',\n        layout: layout\n      });\n      layout.animations = [];\n\n      var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) {\n        var center = {\n          x: nodesBb.x1 + nodesBb.w / 2,\n          y: nodesBb.y1 + nodesBb.h / 2\n        };\n        var spacingVector = {\n          // scale from center of bounding box (not necessarily 0,0)\n          x: (pos.x - center.x) * spacing,\n          y: (pos.y - center.y) * spacing\n        };\n        return {\n          x: center.x + spacingVector.x,\n          y: center.y + spacingVector.y\n        };\n      };\n\n      var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;\n\n      var spacingBb = function spacingBb() {\n        if (!useSpacingFactor) {\n          return null;\n        }\n\n        var bb = makeBoundingBox();\n\n        for (var i = 0; i < nodes.length; i++) {\n          var node = nodes[i];\n          var pos = fnMem(node, i);\n          expandBoundingBoxByPoint(bb, pos.x, pos.y);\n        }\n\n        return bb;\n      };\n\n      var bb = spacingBb();\n      var getFinalPos = memoize$1(function (node, i) {\n        var newPos = fnMem(node, i);\n\n        if (useSpacingFactor) {\n          var spacing = Math.abs(options.spacingFactor);\n          newPos = calculateSpacing(spacing, bb, newPos);\n        }\n\n        if (options.transform != null) {\n          newPos = options.transform(node, newPos);\n        }\n\n        return newPos;\n      }, getMemoizeKey);\n\n      if (options.animate) {\n        for (var i = 0; i < nodes.length; i++) {\n          var node = nodes[i];\n          var newPos = getFinalPos(node, i);\n          var animateNode = options.animateFilter == null || options.animateFilter(node, i);\n\n          if (animateNode) {\n            var ani = node.animation({\n              position: newPos,\n              duration: options.animationDuration,\n              easing: options.animationEasing\n            });\n            layout.animations.push(ani);\n          } else {\n            node.position(newPos);\n          }\n        }\n\n        if (options.fit) {\n          var fitAni = cy.animation({\n            fit: {\n              boundingBox: layoutEles.boundingBoxAt(getFinalPos),\n              padding: options.padding\n            },\n            duration: options.animationDuration,\n            easing: options.animationEasing\n          });\n          layout.animations.push(fitAni);\n        } else if (options.zoom !== undefined && options.pan !== undefined) {\n          var zoomPanAni = cy.animation({\n            zoom: options.zoom,\n            pan: options.pan,\n            duration: options.animationDuration,\n            easing: options.animationEasing\n          });\n          layout.animations.push(zoomPanAni);\n        }\n\n        layout.animations.forEach(function (ani) {\n          return ani.play();\n        });\n        layout.one('layoutready', options.ready);\n        layout.emit({\n          type: 'layoutready',\n          layout: layout\n        });\n        Promise$1.all(layout.animations.map(function (ani) {\n          return ani.promise();\n        })).then(function () {\n          layout.one('layoutstop', options.stop);\n          layout.emit({\n            type: 'layoutstop',\n            layout: layout\n          });\n        });\n      } else {\n        nodes.positions(getFinalPos);\n\n        if (options.fit) {\n          cy.fit(options.eles, options.padding);\n        }\n\n        if (options.zoom != null) {\n          cy.zoom(options.zoom);\n        }\n\n        if (options.pan) {\n          cy.pan(options.pan);\n        }\n\n        layout.one('layoutready', options.ready);\n        layout.emit({\n          type: 'layoutready',\n          layout: layout\n        });\n        layout.one('layoutstop', options.stop);\n        layout.emit({\n          type: 'layoutstop',\n          layout: layout\n        });\n      }\n\n      return this; // chaining\n    },\n    layout: function layout(options) {\n      var cy = this.cy();\n      return cy.makeLayout(extend({}, options, {\n        eles: this\n      }));\n    }\n  }; // aliases:\n\n  elesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;\n\n  function styleCache(key, fn, ele) {\n    var _p = ele._private;\n    var cache = _p.styleCache = _p.styleCache || [];\n    var val;\n\n    if ((val = cache[key]) != null) {\n      return val;\n    } else {\n      val = cache[key] = fn(ele);\n      return val;\n    }\n  }\n\n  function cacheStyleFunction(key, fn) {\n    key = hashString(key);\n    return function cachedStyleFunction(ele) {\n      return styleCache(key, fn, ele);\n    };\n  }\n\n  function cachePrototypeStyleFunction(key, fn) {\n    key = hashString(key);\n\n    var selfFn = function selfFn(ele) {\n      return fn.call(ele);\n    };\n\n    return function cachedPrototypeStyleFunction() {\n      var ele = this[0];\n\n      if (ele) {\n        return styleCache(key, selfFn, ele);\n      }\n    };\n  }\n\n  var elesfn$4 = {\n    recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {\n      var cy = this.cy();\n      var renderer = cy.renderer();\n      var styleEnabled = cy.styleEnabled();\n\n      if (renderer && styleEnabled) {\n        renderer.recalculateRenderedStyle(this, useCache);\n      }\n\n      return this;\n    },\n    dirtyStyleCache: function dirtyStyleCache() {\n      var cy = this.cy();\n\n      var dirty = function dirty(ele) {\n        return ele._private.styleCache = null;\n      };\n\n      if (cy.hasCompoundNodes()) {\n        var eles;\n        eles = this.spawnSelf().merge(this.descendants()).merge(this.parents());\n        eles.merge(eles.connectedEdges());\n        eles.forEach(dirty);\n      } else {\n        this.forEach(function (ele) {\n          dirty(ele);\n          ele.connectedEdges().forEach(dirty);\n        });\n      }\n\n      return this;\n    },\n    // fully updates (recalculates) the style for the elements\n    updateStyle: function updateStyle(notifyRenderer) {\n      var cy = this._private.cy;\n\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n\n      if (cy.batching()) {\n        var bEles = cy._private.batchStyleEles;\n        bEles.merge(this);\n        return this; // chaining and exit early when batching\n      }\n\n      var hasCompounds = cy.hasCompoundNodes();\n      var updatedEles = this;\n      notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;\n\n      if (hasCompounds) {\n        // then add everything up and down for compound selector checks\n        updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents());\n      } // let changedEles = style.apply( updatedEles );\n\n\n      var changedEles = updatedEles;\n\n      if (notifyRenderer) {\n        changedEles.emitAndNotify('style'); // let renderer know we changed style\n      } else {\n        changedEles.emit('style'); // just fire the event\n      }\n\n      updatedEles.forEach(function (ele) {\n        return ele._private.styleDirty = true;\n      });\n      return this; // chaining\n    },\n    // private: clears dirty flag and recalculates style\n    cleanStyle: function cleanStyle() {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return;\n      }\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n\n        if (ele._private.styleDirty) {\n          // n.b. this flag should be set before apply() to avoid potential infinite recursion\n          ele._private.styleDirty = false;\n          cy.style().apply(ele);\n        }\n      }\n    },\n    // get the internal parsed style object for the specified property\n    parsedStyle: function parsedStyle(property) {\n      var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n      var ele = this[0];\n      var cy = ele.cy();\n\n      if (!cy.styleEnabled()) {\n        return;\n      }\n\n      if (ele) {\n        this.cleanStyle();\n        var overriddenStyle = ele._private.style[property];\n\n        if (overriddenStyle != null) {\n          return overriddenStyle;\n        } else if (includeNonDefault) {\n          return cy.style().getDefaultProperty(property);\n        } else {\n          return null;\n        }\n      }\n    },\n    numericStyle: function numericStyle(property) {\n      var ele = this[0];\n\n      if (!ele.cy().styleEnabled()) {\n        return;\n      }\n\n      if (ele) {\n        var pstyle = ele.pstyle(property);\n        return pstyle.pfValue !== undefined ? pstyle.pfValue : pstyle.value;\n      }\n    },\n    numericStyleUnits: function numericStyleUnits(property) {\n      var ele = this[0];\n\n      if (!ele.cy().styleEnabled()) {\n        return;\n      }\n\n      if (ele) {\n        return ele.pstyle(property).units;\n      }\n    },\n    // get the specified css property as a rendered value (i.e. on-screen value)\n    // or get the whole rendered style if no property specified (NB doesn't allow setting)\n    renderedStyle: function renderedStyle(property) {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n\n      var ele = this[0];\n\n      if (ele) {\n        return cy.style().getRenderedStyle(ele, property);\n      }\n    },\n    // read the calculated css style of the element or override the style (via a bypass)\n    style: function style(name, value) {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n\n      var updateTransitions = false;\n      var style = cy.style();\n\n      if (plainObject(name)) {\n        // then extend the bypass\n        var props = name;\n        style.applyBypass(this, props, updateTransitions);\n        this.emitAndNotify('style'); // let the renderer know we've updated style\n      } else if (string(name)) {\n        if (value === undefined) {\n          // then get the property from the style\n          var ele = this[0];\n\n          if (ele) {\n            return style.getStylePropertyValue(ele, name);\n          } else {\n            // empty collection => can't get any value\n            return;\n          }\n        } else {\n          // then set the bypass with the property value\n          style.applyBypass(this, name, value, updateTransitions);\n          this.emitAndNotify('style'); // let the renderer know we've updated style\n        }\n      } else if (name === undefined) {\n        var _ele = this[0];\n\n        if (_ele) {\n          return style.getRawStyle(_ele);\n        } else {\n          // empty collection => can't get any value\n          return;\n        }\n      }\n\n      return this; // chaining\n    },\n    removeStyle: function removeStyle(names) {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n\n      var updateTransitions = false;\n      var style = cy.style();\n      var eles = this;\n\n      if (names === undefined) {\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          style.removeAllBypasses(ele, updateTransitions);\n        }\n      } else {\n        names = names.split(/\\s+/);\n\n        for (var _i = 0; _i < eles.length; _i++) {\n          var _ele2 = eles[_i];\n          style.removeBypasses(_ele2, names, updateTransitions);\n        }\n      }\n\n      this.emitAndNotify('style'); // let the renderer know we've updated style\n\n      return this; // chaining\n    },\n    show: function show() {\n      this.css('display', 'element');\n      return this; // chaining\n    },\n    hide: function hide() {\n      this.css('display', 'none');\n      return this; // chaining\n    },\n    effectiveOpacity: function effectiveOpacity() {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return 1;\n      }\n\n      var hasCompoundNodes = cy.hasCompoundNodes();\n      var ele = this[0];\n\n      if (ele) {\n        var _p = ele._private;\n        var parentOpacity = ele.pstyle('opacity').value;\n\n        if (!hasCompoundNodes) {\n          return parentOpacity;\n        }\n\n        var parents = !_p.data.parent ? null : ele.parents();\n\n        if (parents) {\n          for (var i = 0; i < parents.length; i++) {\n            var parent = parents[i];\n            var opacity = parent.pstyle('opacity').value;\n            parentOpacity = opacity * parentOpacity;\n          }\n        }\n\n        return parentOpacity;\n      }\n    },\n    transparent: function transparent() {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return false;\n      }\n\n      var ele = this[0];\n      var hasCompoundNodes = ele.cy().hasCompoundNodes();\n\n      if (ele) {\n        if (!hasCompoundNodes) {\n          return ele.pstyle('opacity').value === 0;\n        } else {\n          return ele.effectiveOpacity() === 0;\n        }\n      }\n    },\n    backgrounding: function backgrounding() {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return false;\n      }\n\n      var ele = this[0];\n      return ele._private.backgrounding ? true : false;\n    }\n  };\n\n  function checkCompound(ele, parentOk) {\n    var _p = ele._private;\n    var parents = _p.data.parent ? ele.parents() : null;\n\n    if (parents) {\n      for (var i = 0; i < parents.length; i++) {\n        var parent = parents[i];\n\n        if (!parentOk(parent)) {\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n\n  function defineDerivedStateFunction(specs) {\n    var ok = specs.ok;\n    var edgeOkViaNode = specs.edgeOkViaNode || specs.ok;\n    var parentOk = specs.parentOk || specs.ok;\n    return function () {\n      var cy = this.cy();\n\n      if (!cy.styleEnabled()) {\n        return true;\n      }\n\n      var ele = this[0];\n      var hasCompoundNodes = cy.hasCompoundNodes();\n\n      if (ele) {\n        var _p = ele._private;\n\n        if (!ok(ele)) {\n          return false;\n        }\n\n        if (ele.isNode()) {\n          return !hasCompoundNodes || checkCompound(ele, parentOk);\n        } else {\n          var src = _p.source;\n          var tgt = _p.target;\n          return edgeOkViaNode(src) && (!hasCompoundNodes || checkCompound(src, edgeOkViaNode)) && (src === tgt || edgeOkViaNode(tgt) && (!hasCompoundNodes || checkCompound(tgt, edgeOkViaNode)));\n        }\n      }\n    };\n  }\n\n  var eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {\n    return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);\n  });\n  elesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({\n    ok: eleTakesUpSpace\n  }));\n  var eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {\n    return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);\n  });\n  var parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {\n    return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);\n  });\n  elesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({\n    ok: eleInteractive,\n    parentOk: parentInteractive,\n    edgeOkViaNode: eleTakesUpSpace\n  }));\n\n  elesfn$4.noninteractive = function () {\n    var ele = this[0];\n\n    if (ele) {\n      return !ele.interactive();\n    }\n  };\n\n  var eleVisible = cacheStyleFunction('eleVisible', function (ele) {\n    return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);\n  });\n  var edgeVisibleViaNode = eleTakesUpSpace;\n  elesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({\n    ok: eleVisible,\n    edgeOkViaNode: edgeVisibleViaNode\n  }));\n\n  elesfn$4.hidden = function () {\n    var ele = this[0];\n\n    if (ele) {\n      return !ele.visible();\n    }\n  };\n\n  elesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {\n    if (!this.cy().styleEnabled()) {\n      return false;\n    }\n\n    return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();\n  });\n  elesfn$4.bypass = elesfn$4.css = elesfn$4.style;\n  elesfn$4.renderedCss = elesfn$4.renderedStyle;\n  elesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;\n  elesfn$4.pstyle = elesfn$4.parsedStyle;\n\n  var elesfn$3 = {};\n\n  function defineSwitchFunction(params) {\n    return function () {\n      var args = arguments;\n      var changedEles = []; // e.g. cy.nodes().select( data, handler )\n\n      if (args.length === 2) {\n        var data = args[0];\n        var handler = args[1];\n        this.on(params.event, data, handler);\n      } // e.g. cy.nodes().select( handler )\n      else if (args.length === 1 && fn$6(args[0])) {\n        var _handler = args[0];\n        this.on(params.event, _handler);\n      } // e.g. cy.nodes().select()\n      // e.g. (private) cy.nodes().select(['tapselect'])\n      else if (args.length === 0 || args.length === 1 && array(args[0])) {\n        var addlEvents = args.length === 1 ? args[0] : null;\n\n        for (var i = 0; i < this.length; i++) {\n          var ele = this[i];\n          var able = !params.ableField || ele._private[params.ableField];\n          var changed = ele._private[params.field] != params.value;\n\n          if (params.overrideAble) {\n            var overrideAble = params.overrideAble(ele);\n\n            if (overrideAble !== undefined) {\n              able = overrideAble;\n\n              if (!overrideAble) {\n                return this;\n              } // to save cycles assume not able for all on override\n\n            }\n          }\n\n          if (able) {\n            ele._private[params.field] = params.value;\n\n            if (changed) {\n              changedEles.push(ele);\n            }\n          }\n        }\n\n        var changedColl = this.spawn(changedEles);\n        changedColl.updateStyle(); // change of state => possible change of style\n\n        changedColl.emit(params.event);\n\n        if (addlEvents) {\n          changedColl.emit(addlEvents);\n        }\n      }\n\n      return this;\n    };\n  }\n\n  function defineSwitchSet(params) {\n    elesfn$3[params.field] = function () {\n      var ele = this[0];\n\n      if (ele) {\n        if (params.overrideField) {\n          var val = params.overrideField(ele);\n\n          if (val !== undefined) {\n            return val;\n          }\n        }\n\n        return ele._private[params.field];\n      }\n    };\n\n    elesfn$3[params.on] = defineSwitchFunction({\n      event: params.on,\n      field: params.field,\n      ableField: params.ableField,\n      overrideAble: params.overrideAble,\n      value: true\n    });\n    elesfn$3[params.off] = defineSwitchFunction({\n      event: params.off,\n      field: params.field,\n      ableField: params.ableField,\n      overrideAble: params.overrideAble,\n      value: false\n    });\n  }\n\n  defineSwitchSet({\n    field: 'locked',\n    overrideField: function overrideField(ele) {\n      return ele.cy().autolock() ? true : undefined;\n    },\n    on: 'lock',\n    off: 'unlock'\n  });\n  defineSwitchSet({\n    field: 'grabbable',\n    overrideField: function overrideField(ele) {\n      return ele.cy().autoungrabify() || ele.pannable() ? false : undefined;\n    },\n    on: 'grabify',\n    off: 'ungrabify'\n  });\n  defineSwitchSet({\n    field: 'selected',\n    ableField: 'selectable',\n    overrideAble: function overrideAble(ele) {\n      return ele.cy().autounselectify() ? false : undefined;\n    },\n    on: 'select',\n    off: 'unselect'\n  });\n  defineSwitchSet({\n    field: 'selectable',\n    overrideField: function overrideField(ele) {\n      return ele.cy().autounselectify() ? false : undefined;\n    },\n    on: 'selectify',\n    off: 'unselectify'\n  });\n  elesfn$3.deselect = elesfn$3.unselect;\n\n  elesfn$3.grabbed = function () {\n    var ele = this[0];\n\n    if (ele) {\n      return ele._private.grabbed;\n    }\n  };\n\n  defineSwitchSet({\n    field: 'active',\n    on: 'activate',\n    off: 'unactivate'\n  });\n  defineSwitchSet({\n    field: 'pannable',\n    on: 'panify',\n    off: 'unpanify'\n  });\n\n  elesfn$3.inactive = function () {\n    var ele = this[0];\n\n    if (ele) {\n      return !ele._private.active;\n    }\n  };\n\n  var elesfn$2 = {}; // DAG functions\n  ////////////////\n\n  var defineDagExtremity = function defineDagExtremity(params) {\n    return function dagExtremityImpl(selector) {\n      var eles = this;\n      var ret = [];\n\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n\n        if (!ele.isNode()) {\n          continue;\n        }\n\n        var disqualified = false;\n        var edges = ele.connectedEdges();\n\n        for (var j = 0; j < edges.length; j++) {\n          var edge = edges[j];\n          var src = edge.source();\n          var tgt = edge.target();\n\n          if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {\n            disqualified = true;\n            break;\n          }\n        }\n\n        if (!disqualified) {\n          ret.push(ele);\n        }\n      }\n\n      return this.spawn(ret, true).filter(selector);\n    };\n  };\n\n  var defineDagOneHop = function defineDagOneHop(params) {\n    return function (selector) {\n      var eles = this;\n      var oEles = [];\n\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n\n        if (!ele.isNode()) {\n          continue;\n        }\n\n        var edges = ele.connectedEdges();\n\n        for (var j = 0; j < edges.length; j++) {\n          var edge = edges[j];\n          var src = edge.source();\n          var tgt = edge.target();\n\n          if (params.outgoing && src === ele) {\n            oEles.push(edge);\n            oEles.push(tgt);\n          } else if (params.incoming && tgt === ele) {\n            oEles.push(edge);\n            oEles.push(src);\n          }\n        }\n      }\n\n      return this.spawn(oEles, true).filter(selector);\n    };\n  };\n\n  var defineDagAllHops = function defineDagAllHops(params) {\n    return function (selector) {\n      var eles = this;\n      var sEles = [];\n      var sElesIds = {};\n\n      for (;;) {\n        var next = params.outgoing ? eles.outgoers() : eles.incomers();\n\n        if (next.length === 0) {\n          break;\n        } // done if none left\n\n\n        var newNext = false;\n\n        for (var i = 0; i < next.length; i++) {\n          var n = next[i];\n          var nid = n.id();\n\n          if (!sElesIds[nid]) {\n            sElesIds[nid] = true;\n            sEles.push(n);\n            newNext = true;\n          }\n        }\n\n        if (!newNext) {\n          break;\n        } // done if touched all outgoers already\n\n\n        eles = next;\n      }\n\n      return this.spawn(sEles, true).filter(selector);\n    };\n  };\n\n  elesfn$2.clearTraversalCache = function () {\n    for (var i = 0; i < this.length; i++) {\n      this[i]._private.traversalCache = null;\n    }\n  };\n\n  extend(elesfn$2, {\n    // get the root nodes in the DAG\n    roots: defineDagExtremity({\n      noIncomingEdges: true\n    }),\n    // get the leaf nodes in the DAG\n    leaves: defineDagExtremity({\n      noOutgoingEdges: true\n    }),\n    // normally called children in graph theory\n    // these nodes =edges=> outgoing nodes\n    outgoers: cache(defineDagOneHop({\n      outgoing: true\n    }), 'outgoers'),\n    // aka DAG descendants\n    successors: defineDagAllHops({\n      outgoing: true\n    }),\n    // normally called parents in graph theory\n    // these nodes <=edges= incoming nodes\n    incomers: cache(defineDagOneHop({\n      incoming: true\n    }), 'incomers'),\n    // aka DAG ancestors\n    predecessors: defineDagAllHops({\n      incoming: true\n    })\n  }); // Neighbourhood functions\n  //////////////////////////\n\n  extend(elesfn$2, {\n    neighborhood: cache(function (selector) {\n      var elements = [];\n      var nodes = this.nodes();\n\n      for (var i = 0; i < nodes.length; i++) {\n        // for all nodes\n        var node = nodes[i];\n        var connectedEdges = node.connectedEdges(); // for each connected edge, add the edge and the other node\n\n        for (var j = 0; j < connectedEdges.length; j++) {\n          var edge = connectedEdges[j];\n          var src = edge.source();\n          var tgt = edge.target();\n          var otherNode = node === src ? tgt : src; // need check in case of loop\n\n          if (otherNode.length > 0) {\n            elements.push(otherNode[0]); // add node 1 hop away\n          } // add connected edge\n\n\n          elements.push(edge[0]);\n        }\n      }\n\n      return this.spawn(elements, true).filter(selector);\n    }, 'neighborhood'),\n    closedNeighborhood: function closedNeighborhood(selector) {\n      return this.neighborhood().add(this).filter(selector);\n    },\n    openNeighborhood: function openNeighborhood(selector) {\n      return this.neighborhood(selector);\n    }\n  }); // aliases\n\n  elesfn$2.neighbourhood = elesfn$2.neighborhood;\n  elesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;\n  elesfn$2.openNeighbourhood = elesfn$2.openNeighborhood; // Edge functions\n  /////////////////\n\n  extend(elesfn$2, {\n    source: cache(function sourceImpl(selector) {\n      var ele = this[0];\n      var src;\n\n      if (ele) {\n        src = ele._private.source || ele.cy().collection();\n      }\n\n      return src && selector ? src.filter(selector) : src;\n    }, 'source'),\n    target: cache(function targetImpl(selector) {\n      var ele = this[0];\n      var tgt;\n\n      if (ele) {\n        tgt = ele._private.target || ele.cy().collection();\n      }\n\n      return tgt && selector ? tgt.filter(selector) : tgt;\n    }, 'target'),\n    sources: defineSourceFunction({\n      attr: 'source'\n    }),\n    targets: defineSourceFunction({\n      attr: 'target'\n    })\n  });\n\n  function defineSourceFunction(params) {\n    return function sourceImpl(selector) {\n      var sources = [];\n\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        var src = ele._private[params.attr];\n\n        if (src) {\n          sources.push(src);\n        }\n      }\n\n      return this.spawn(sources, true).filter(selector);\n    };\n  }\n\n  extend(elesfn$2, {\n    edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),\n    edgesTo: cache(defineEdgesWithFunction({\n      thisIsSrc: true\n    }), 'edgesTo')\n  });\n\n  function defineEdgesWithFunction(params) {\n    return function edgesWithImpl(otherNodes) {\n      var elements = [];\n      var cy = this._private.cy;\n      var p = params || {}; // get elements if a selector is specified\n\n      if (string(otherNodes)) {\n        otherNodes = cy.$(otherNodes);\n      }\n\n      for (var h = 0; h < otherNodes.length; h++) {\n        var edges = otherNodes[h]._private.edges;\n\n        for (var i = 0; i < edges.length; i++) {\n          var edge = edges[i];\n          var edgeData = edge._private.data;\n          var thisToOther = this.hasElementWithId(edgeData.source) && otherNodes.hasElementWithId(edgeData.target);\n          var otherToThis = otherNodes.hasElementWithId(edgeData.source) && this.hasElementWithId(edgeData.target);\n          var edgeConnectsThisAndOther = thisToOther || otherToThis;\n\n          if (!edgeConnectsThisAndOther) {\n            continue;\n          }\n\n          if (p.thisIsSrc || p.thisIsTgt) {\n            if (p.thisIsSrc && !thisToOther) {\n              continue;\n            }\n\n            if (p.thisIsTgt && !otherToThis) {\n              continue;\n            }\n          }\n\n          elements.push(edge);\n        }\n      }\n\n      return this.spawn(elements, true);\n    };\n  }\n\n  extend(elesfn$2, {\n    connectedEdges: cache(function (selector) {\n      var retEles = [];\n      var eles = this;\n\n      for (var i = 0; i < eles.length; i++) {\n        var node = eles[i];\n\n        if (!node.isNode()) {\n          continue;\n        }\n\n        var edges = node._private.edges;\n\n        for (var j = 0; j < edges.length; j++) {\n          var edge = edges[j];\n          retEles.push(edge);\n        }\n      }\n\n      return this.spawn(retEles, true).filter(selector);\n    }, 'connectedEdges'),\n    connectedNodes: cache(function (selector) {\n      var retEles = [];\n      var eles = this;\n\n      for (var i = 0; i < eles.length; i++) {\n        var edge = eles[i];\n\n        if (!edge.isEdge()) {\n          continue;\n        }\n\n        retEles.push(edge.source()[0]);\n        retEles.push(edge.target()[0]);\n      }\n\n      return this.spawn(retEles, true).filter(selector);\n    }, 'connectedNodes'),\n    parallelEdges: cache(defineParallelEdgesFunction(), 'parallelEdges'),\n    codirectedEdges: cache(defineParallelEdgesFunction({\n      codirected: true\n    }), 'codirectedEdges')\n  });\n\n  function defineParallelEdgesFunction(params) {\n    var defaults = {\n      codirected: false\n    };\n    params = extend({}, defaults, params);\n    return function parallelEdgesImpl(selector) {\n      // micro-optimised for renderer\n      var elements = [];\n      var edges = this.edges();\n      var p = params; // look at all the edges in the collection\n\n      for (var i = 0; i < edges.length; i++) {\n        var edge1 = edges[i];\n        var edge1_p = edge1._private;\n        var src1 = edge1_p.source;\n        var srcid1 = src1._private.data.id;\n        var tgtid1 = edge1_p.data.target;\n        var srcEdges1 = src1._private.edges; // look at edges connected to the src node of this edge\n\n        for (var j = 0; j < srcEdges1.length; j++) {\n          var edge2 = srcEdges1[j];\n          var edge2data = edge2._private.data;\n          var tgtid2 = edge2data.target;\n          var srcid2 = edge2data.source;\n          var codirected = tgtid2 === tgtid1 && srcid2 === srcid1;\n          var oppdirected = srcid1 === tgtid2 && tgtid1 === srcid2;\n\n          if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {\n            elements.push(edge2);\n          }\n        }\n      }\n\n      return this.spawn(elements, true).filter(selector);\n    };\n  } // Misc functions\n  /////////////////\n\n\n  extend(elesfn$2, {\n    components: function components(root) {\n      var self = this;\n      var cy = self.cy();\n      var visited = cy.collection();\n      var unvisited = root == null ? self.nodes() : root.nodes();\n      var components = [];\n\n      if (root != null && unvisited.empty()) {\n        // root may contain only edges\n        unvisited = root.sources(); // doesn't matter which node to use (undirected), so just use the source sides\n      }\n\n      var visitInComponent = function visitInComponent(node, component) {\n        visited.merge(node);\n        unvisited.unmerge(node);\n        component.merge(node);\n      };\n\n      if (unvisited.empty()) {\n        return self.spawn();\n      }\n\n      var _loop = function _loop() {\n        // each iteration yields a component\n        var cmpt = cy.collection();\n        components.push(cmpt);\n        var root = unvisited[0];\n        visitInComponent(root, cmpt);\n        self.bfs({\n          directed: false,\n          roots: root,\n          visit: function visit(v) {\n            return visitInComponent(v, cmpt);\n          }\n        });\n        cmpt.forEach(function (node) {\n          node.connectedEdges().forEach(function (e) {\n            // connectedEdges() usually cached\n            if (self.has(e) && cmpt.has(e.source()) && cmpt.has(e.target())) {\n              // has() is cheap\n              cmpt.merge(e); // forEach() only considers nodes -- sets N at call time\n            }\n          });\n        });\n      };\n\n      do {\n        _loop();\n      } while (unvisited.length > 0);\n\n      return components;\n    },\n    component: function component() {\n      var ele = this[0];\n      return ele.cy().mutableElements().components(ele)[0];\n    }\n  });\n  elesfn$2.componentsOf = elesfn$2.components;\n\n  var Collection = function Collection(cy, elements) {\n    var unique = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n    var removed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n\n    if (cy === undefined) {\n      error('A collection must have a reference to the core');\n      return;\n    }\n\n    var map = new Map$2();\n    var createdElements = false;\n\n    if (!elements) {\n      elements = [];\n    } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {\n      createdElements = true; // make elements from json and restore all at once later\n\n      var eles = [];\n      var elesIds = new Set$1();\n\n      for (var i = 0, l = elements.length; i < l; i++) {\n        var json = elements[i];\n\n        if (json.data == null) {\n          json.data = {};\n        }\n\n        var _data = json.data; // make sure newly created elements have valid ids\n\n        if (_data.id == null) {\n          _data.id = uuid();\n        } else if (cy.hasElementWithId(_data.id) || elesIds.has(_data.id)) {\n          continue; // can't create element if prior id already exists\n        }\n\n        var ele = new Element(cy, json, false);\n        eles.push(ele);\n        elesIds.add(_data.id);\n      }\n\n      elements = eles;\n    }\n\n    this.length = 0;\n\n    for (var _i = 0, _l = elements.length; _i < _l; _i++) {\n      var element$1 = elements[_i][0]; // [0] in case elements is an array of collections, rather than array of elements\n\n      if (element$1 == null) {\n        continue;\n      }\n\n      var id = element$1._private.data.id;\n\n      if (!unique || !map.has(id)) {\n        if (unique) {\n          map.set(id, {\n            index: this.length,\n            ele: element$1\n          });\n        }\n\n        this[this.length] = element$1;\n        this.length++;\n      }\n    }\n\n    this._private = {\n      eles: this,\n      cy: cy,\n\n      get map() {\n        if (this.lazyMap == null) {\n          this.rebuildMap();\n        }\n\n        return this.lazyMap;\n      },\n\n      set map(m) {\n        this.lazyMap = m;\n      },\n\n      rebuildMap: function rebuildMap() {\n        var m = this.lazyMap = new Map$2();\n        var eles = this.eles;\n\n        for (var _i2 = 0; _i2 < eles.length; _i2++) {\n          var _ele = eles[_i2];\n          m.set(_ele.id(), {\n            index: _i2,\n            ele: _ele\n          });\n        }\n      }\n    };\n\n    if (unique) {\n      this._private.map = map;\n    } // restore the elements if we created them from json\n\n\n    if (createdElements && !removed) {\n      this.restore();\n    }\n  }; // Functions\n  ////////////////////////////////////////////////////////////////////////////////////////////////////\n  // keep the prototypes in sync (an element has the same functions as a collection)\n  // and use elefn and elesfn as shorthands to the prototypes\n\n\n  var elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);\n\n  elesfn$1.instanceString = function () {\n    return 'collection';\n  };\n\n  elesfn$1.spawn = function (eles, unique) {\n    return new Collection(this.cy(), eles, unique);\n  };\n\n  elesfn$1.spawnSelf = function () {\n    return this.spawn(this);\n  };\n\n  elesfn$1.cy = function () {\n    return this._private.cy;\n  };\n\n  elesfn$1.renderer = function () {\n    return this._private.cy.renderer();\n  };\n\n  elesfn$1.element = function () {\n    return this[0];\n  };\n\n  elesfn$1.collection = function () {\n    if (collection(this)) {\n      return this;\n    } else {\n      // an element\n      return new Collection(this._private.cy, [this]);\n    }\n  };\n\n  elesfn$1.unique = function () {\n    return new Collection(this._private.cy, this, true);\n  };\n\n  elesfn$1.hasElementWithId = function (id) {\n    id = '' + id; // id must be string\n\n    return this._private.map.has(id);\n  };\n\n  elesfn$1.getElementById = function (id) {\n    id = '' + id; // id must be string\n\n    var cy = this._private.cy;\n\n    var entry = this._private.map.get(id);\n\n    return entry ? entry.ele : new Collection(cy); // get ele or empty collection\n  };\n\n  elesfn$1.$id = elesfn$1.getElementById;\n\n  elesfn$1.poolIndex = function () {\n    var cy = this._private.cy;\n    var eles = cy._private.elements;\n    var id = this[0]._private.data.id;\n    return eles._private.map.get(id).index;\n  };\n\n  elesfn$1.indexOf = function (ele) {\n    var id = ele[0]._private.data.id;\n    return this._private.map.get(id).index;\n  };\n\n  elesfn$1.indexOfId = function (id) {\n    id = '' + id; // id must be string\n\n    return this._private.map.get(id).index;\n  };\n\n  elesfn$1.json = function (obj) {\n    var ele = this.element();\n    var cy = this.cy();\n\n    if (ele == null && obj) {\n      return this;\n    } // can't set to no eles\n\n\n    if (ele == null) {\n      return undefined;\n    } // can't get from no eles\n\n\n    var p = ele._private;\n\n    if (plainObject(obj)) {\n      // set\n      cy.startBatch();\n\n      if (obj.data) {\n        ele.data(obj.data);\n        var _data2 = p.data;\n\n        if (ele.isEdge()) {\n          // source and target are immutable via data()\n          var move = false;\n          var spec = {};\n          var src = obj.data.source;\n          var tgt = obj.data.target;\n\n          if (src != null && src != _data2.source) {\n            spec.source = '' + src; // id must be string\n\n            move = true;\n          }\n\n          if (tgt != null && tgt != _data2.target) {\n            spec.target = '' + tgt; // id must be string\n\n            move = true;\n          }\n\n          if (move) {\n            ele = ele.move(spec);\n          }\n        } else {\n          // parent is immutable via data()\n          var newParentValSpecd = ('parent' in obj.data);\n          var parent = obj.data.parent;\n\n          if (newParentValSpecd && (parent != null || _data2.parent != null) && parent != _data2.parent) {\n            if (parent === undefined) {\n              // can't set undefined imperatively, so use null\n              parent = null;\n            }\n\n            if (parent != null) {\n              parent = '' + parent; // id must be string\n            }\n\n            ele = ele.move({\n              parent: parent\n            });\n          }\n        }\n      }\n\n      if (obj.position) {\n        ele.position(obj.position);\n      } // ignore group -- immutable\n\n\n      var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {\n        var obj_k = obj[k];\n\n        if (obj_k != null && obj_k !== p[k]) {\n          if (obj_k) {\n            ele[trueFnName]();\n          } else {\n            ele[falseFnName]();\n          }\n        }\n      };\n\n      checkSwitch('removed', 'remove', 'restore');\n      checkSwitch('selected', 'select', 'unselect');\n      checkSwitch('selectable', 'selectify', 'unselectify');\n      checkSwitch('locked', 'lock', 'unlock');\n      checkSwitch('grabbable', 'grabify', 'ungrabify');\n      checkSwitch('pannable', 'panify', 'unpanify');\n\n      if (obj.classes != null) {\n        ele.classes(obj.classes);\n      }\n\n      cy.endBatch();\n      return this;\n    } else if (obj === undefined) {\n      // get\n      var json = {\n        data: copy(p.data),\n        position: copy(p.position),\n        group: p.group,\n        removed: p.removed,\n        selected: p.selected,\n        selectable: p.selectable,\n        locked: p.locked,\n        grabbable: p.grabbable,\n        pannable: p.pannable,\n        classes: null\n      };\n      json.classes = '';\n      var i = 0;\n      p.classes.forEach(function (cls) {\n        return json.classes += i++ === 0 ? cls : ' ' + cls;\n      });\n      return json;\n    }\n  };\n\n  elesfn$1.jsons = function () {\n    var jsons = [];\n\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      var json = ele.json();\n      jsons.push(json);\n    }\n\n    return jsons;\n  };\n\n  elesfn$1.clone = function () {\n    var cy = this.cy();\n    var elesArr = [];\n\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      var json = ele.json();\n      var clone = new Element(cy, json, false); // NB no restore\n\n      elesArr.push(clone);\n    }\n\n    return new Collection(cy, elesArr);\n  };\n\n  elesfn$1.copy = elesfn$1.clone;\n\n  elesfn$1.restore = function () {\n    var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n    var addToPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    var self = this;\n    var cy = self.cy();\n    var cy_p = cy._private; // create arrays of nodes and edges, since we need to\n    // restore the nodes first\n\n    var nodes = [];\n    var edges = [];\n    var elements;\n\n    for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {\n      var ele = self[_i3];\n\n      if (addToPool && !ele.removed()) {\n        // don't need to handle this ele\n        continue;\n      } // keep nodes first in the array and edges after\n\n\n      if (ele.isNode()) {\n        // put to front of array if node\n        nodes.push(ele);\n      } else {\n        // put to end of array if edge\n        edges.push(ele);\n      }\n    }\n\n    elements = nodes.concat(edges);\n    var i;\n\n    var removeFromElements = function removeFromElements() {\n      elements.splice(i, 1);\n      i--;\n    }; // now, restore each element\n\n\n    for (i = 0; i < elements.length; i++) {\n      var _ele2 = elements[i];\n      var _private = _ele2._private;\n      var _data3 = _private.data; // the traversal cache should start fresh when ele is added\n\n      _ele2.clearTraversalCache(); // set id and validate\n\n\n      if (!addToPool && !_private.removed) ; else if (_data3.id === undefined) {\n        _data3.id = uuid();\n      } else if (number$1(_data3.id)) {\n        _data3.id = '' + _data3.id; // now it's a string\n      } else if (emptyString(_data3.id) || !string(_data3.id)) {\n        error('Can not create element with invalid string ID `' + _data3.id + '`'); // can't create element if it has empty string as id or non-string id\n\n        removeFromElements();\n        continue;\n      } else if (cy.hasElementWithId(_data3.id)) {\n        error('Can not create second element with ID `' + _data3.id + '`'); // can't create element if one already has that id\n\n        removeFromElements();\n        continue;\n      }\n\n      var id = _data3.id; // id is finalised, now let's keep a ref\n\n      if (_ele2.isNode()) {\n        // extra checks for nodes\n        var pos = _private.position; // make sure the nodes have a defined position\n\n        if (pos.x == null) {\n          pos.x = 0;\n        }\n\n        if (pos.y == null) {\n          pos.y = 0;\n        }\n      }\n\n      if (_ele2.isEdge()) {\n        // extra checks for edges\n        var edge = _ele2;\n        var fields = ['source', 'target'];\n        var fieldsLength = fields.length;\n        var badSourceOrTarget = false;\n\n        for (var j = 0; j < fieldsLength; j++) {\n          var field = fields[j];\n          var val = _data3[field];\n\n          if (number$1(val)) {\n            val = _data3[field] = '' + _data3[field]; // now string\n          }\n\n          if (val == null || val === '') {\n            // can't create if source or target is not defined properly\n            error('Can not create edge `' + id + '` with unspecified ' + field);\n            badSourceOrTarget = true;\n          } else if (!cy.hasElementWithId(val)) {\n            // can't create edge if one of its nodes doesn't exist\n            error('Can not create edge `' + id + '` with nonexistant ' + field + ' `' + val + '`');\n            badSourceOrTarget = true;\n          }\n        }\n\n        if (badSourceOrTarget) {\n          removeFromElements();\n          continue;\n        } // can't create this\n\n\n        var src = cy.getElementById(_data3.source);\n        var tgt = cy.getElementById(_data3.target); // only one edge in node if loop\n\n        if (src.same(tgt)) {\n          src._private.edges.push(edge);\n        } else {\n          src._private.edges.push(edge);\n\n          tgt._private.edges.push(edge);\n        }\n\n        edge._private.source = src;\n        edge._private.target = tgt;\n      } // if is edge\n      // create mock ids / indexes maps for element so it can be used like collections\n\n\n      _private.map = new Map$2();\n\n      _private.map.set(id, {\n        ele: _ele2,\n        index: 0\n      });\n\n      _private.removed = false;\n\n      if (addToPool) {\n        cy.addToPool(_ele2);\n      }\n    } // for each element\n    // do compound node sanity checks\n\n\n    for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n      // each node\n      var node = nodes[_i4];\n      var _data4 = node._private.data;\n\n      if (number$1(_data4.parent)) {\n        // then automake string\n        _data4.parent = '' + _data4.parent;\n      }\n\n      var parentId = _data4.parent;\n      var specifiedParent = parentId != null;\n\n      if (specifiedParent || node._private.parent) {\n        var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);\n\n        if (parent.empty()) {\n          // non-existant parent; just remove it\n          _data4.parent = undefined;\n        } else if (parent[0].removed()) {\n          warn('Node added with missing parent, reference to parent removed');\n          _data4.parent = undefined;\n          node._private.parent = null;\n        } else {\n          var selfAsParent = false;\n          var ancestor = parent;\n\n          while (!ancestor.empty()) {\n            if (node.same(ancestor)) {\n              // mark self as parent and remove from data\n              selfAsParent = true;\n              _data4.parent = undefined; // remove parent reference\n              // exit or we loop forever\n\n              break;\n            }\n\n            ancestor = ancestor.parent();\n          }\n\n          if (!selfAsParent) {\n            // connect with children\n            parent[0]._private.children.push(node);\n\n            node._private.parent = parent[0]; // let the core know we have a compound graph\n\n            cy_p.hasCompoundNodes = true;\n          }\n        } // else\n\n      } // if specified parent\n\n    } // for each node\n\n\n    if (elements.length > 0) {\n      var restored = elements.length === self.length ? self : new Collection(cy, elements);\n\n      for (var _i5 = 0; _i5 < restored.length; _i5++) {\n        var _ele3 = restored[_i5];\n\n        if (_ele3.isNode()) {\n          continue;\n        } // adding an edge invalidates the traversal caches for the parallel edges\n\n\n        _ele3.parallelEdges().clearTraversalCache(); // adding an edge invalidates the traversal cache for the connected nodes\n\n\n        _ele3.source().clearTraversalCache();\n\n        _ele3.target().clearTraversalCache();\n      }\n\n      var toUpdateStyle;\n\n      if (cy_p.hasCompoundNodes) {\n        toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());\n      } else {\n        toUpdateStyle = restored;\n      }\n\n      toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);\n\n      if (notifyRenderer) {\n        restored.emitAndNotify('add');\n      } else if (addToPool) {\n        restored.emit('add');\n      }\n    }\n\n    return self; // chainability\n  };\n\n  elesfn$1.removed = function () {\n    var ele = this[0];\n    return ele && ele._private.removed;\n  };\n\n  elesfn$1.inside = function () {\n    var ele = this[0];\n    return ele && !ele._private.removed;\n  };\n\n  elesfn$1.remove = function () {\n    var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n    var removeFromPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    var self = this;\n    var elesToRemove = [];\n    var elesToRemoveIds = {};\n    var cy = self._private.cy; // add connected edges\n\n    function addConnectedEdges(node) {\n      var edges = node._private.edges;\n\n      for (var i = 0; i < edges.length; i++) {\n        add(edges[i]);\n      }\n    } // add descendant nodes\n\n\n    function addChildren(node) {\n      var children = node._private.children;\n\n      for (var i = 0; i < children.length; i++) {\n        add(children[i]);\n      }\n    }\n\n    function add(ele) {\n      var alreadyAdded = elesToRemoveIds[ele.id()];\n\n      if (removeFromPool && ele.removed() || alreadyAdded) {\n        return;\n      } else {\n        elesToRemoveIds[ele.id()] = true;\n      }\n\n      if (ele.isNode()) {\n        elesToRemove.push(ele); // nodes are removed last\n\n        addConnectedEdges(ele);\n        addChildren(ele);\n      } else {\n        elesToRemove.unshift(ele); // edges are removed first\n      }\n    } // make the list of elements to remove\n    // (may be removing more than specified due to connected edges etc)\n\n\n    for (var i = 0, l = self.length; i < l; i++) {\n      var ele = self[i];\n      add(ele);\n    }\n\n    function removeEdgeRef(node, edge) {\n      var connectedEdges = node._private.edges;\n      removeFromArray(connectedEdges, edge); // removing an edges invalidates the traversal cache for its nodes\n\n      node.clearTraversalCache();\n    }\n\n    function removeParallelRef(pllEdge) {\n      // removing an edge invalidates the traversal caches for the parallel edges\n      pllEdge.clearTraversalCache();\n    }\n\n    var alteredParents = [];\n    alteredParents.ids = {};\n\n    function removeChildRef(parent, ele) {\n      ele = ele[0];\n      parent = parent[0];\n      var children = parent._private.children;\n      var pid = parent.id();\n      removeFromArray(children, ele); // remove parent => child ref\n\n      ele._private.parent = null; // remove child => parent ref\n\n      if (!alteredParents.ids[pid]) {\n        alteredParents.ids[pid] = true;\n        alteredParents.push(parent);\n      }\n    }\n\n    self.dirtyCompoundBoundsCache();\n\n    if (removeFromPool) {\n      cy.removeFromPool(elesToRemove); // remove from core pool\n    }\n\n    for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {\n      var _ele4 = elesToRemove[_i6];\n\n      if (_ele4.isEdge()) {\n        // remove references to this edge in its connected nodes\n        var src = _ele4.source()[0];\n\n        var tgt = _ele4.target()[0];\n\n        removeEdgeRef(src, _ele4);\n        removeEdgeRef(tgt, _ele4);\n\n        var pllEdges = _ele4.parallelEdges();\n\n        for (var j = 0; j < pllEdges.length; j++) {\n          var pllEdge = pllEdges[j];\n          removeParallelRef(pllEdge);\n\n          if (pllEdge.isBundledBezier()) {\n            pllEdge.dirtyBoundingBoxCache();\n          }\n        }\n      } else {\n        // remove reference to parent\n        var parent = _ele4.parent();\n\n        if (parent.length !== 0) {\n          removeChildRef(parent, _ele4);\n        }\n      }\n\n      if (removeFromPool) {\n        // mark as removed\n        _ele4._private.removed = true;\n      }\n    } // check to see if we have a compound graph or not\n\n\n    var elesStillInside = cy._private.elements;\n    cy._private.hasCompoundNodes = false;\n\n    for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {\n      var _ele5 = elesStillInside[_i7];\n\n      if (_ele5.isParent()) {\n        cy._private.hasCompoundNodes = true;\n        break;\n      }\n    }\n\n    var removedElements = new Collection(this.cy(), elesToRemove);\n\n    if (removedElements.size() > 0) {\n      // must manually notify since trigger won't do this automatically once removed\n      if (notifyRenderer) {\n        removedElements.emitAndNotify('remove');\n      } else if (removeFromPool) {\n        removedElements.emit('remove');\n      }\n    } // the parents who were modified by the removal need their style updated\n\n\n    for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {\n      var _ele6 = alteredParents[_i8];\n\n      if (!removeFromPool || !_ele6.removed()) {\n        _ele6.updateStyle();\n      }\n    }\n\n    return removedElements;\n  };\n\n  elesfn$1.move = function (struct) {\n    var cy = this._private.cy;\n    var eles = this; // just clean up refs, caches, etc. in the same way as when removing and then restoring\n    // (our calls to remove/restore do not remove from the graph or make events)\n\n    var notifyRenderer = false;\n    var modifyPool = false;\n\n    var toString = function toString(id) {\n      return id == null ? id : '' + id;\n    }; // id must be string\n\n\n    if (struct.source !== undefined || struct.target !== undefined) {\n      var srcId = toString(struct.source);\n      var tgtId = toString(struct.target);\n      var srcExists = srcId != null && cy.hasElementWithId(srcId);\n      var tgtExists = tgtId != null && cy.hasElementWithId(tgtId);\n\n      if (srcExists || tgtExists) {\n        cy.batch(function () {\n          // avoid duplicate style updates\n          eles.remove(notifyRenderer, modifyPool); // clean up refs etc.\n\n          eles.emitAndNotify('moveout');\n\n          for (var i = 0; i < eles.length; i++) {\n            var ele = eles[i];\n            var _data5 = ele._private.data;\n\n            if (ele.isEdge()) {\n              if (srcExists) {\n                _data5.source = srcId;\n              }\n\n              if (tgtExists) {\n                _data5.target = tgtId;\n              }\n            }\n          }\n\n          eles.restore(notifyRenderer, modifyPool); // make new refs, style, etc.\n        });\n        eles.emitAndNotify('move');\n      }\n    } else if (struct.parent !== undefined) {\n      // move node to new parent\n      var parentId = toString(struct.parent);\n      var parentExists = parentId === null || cy.hasElementWithId(parentId);\n\n      if (parentExists) {\n        var pidToAssign = parentId === null ? undefined : parentId;\n        cy.batch(function () {\n          // avoid duplicate style updates\n          var updated = eles.remove(notifyRenderer, modifyPool); // clean up refs etc.\n\n          updated.emitAndNotify('moveout');\n\n          for (var i = 0; i < eles.length; i++) {\n            var ele = eles[i];\n            var _data6 = ele._private.data;\n\n            if (ele.isNode()) {\n              _data6.parent = pidToAssign;\n            }\n          }\n\n          updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.\n        });\n        eles.emitAndNotify('move');\n      }\n    }\n\n    return this;\n  };\n\n  [elesfn$j, elesfn$i, elesfn$h, elesfn$g, elesfn$f, data, elesfn$d, dimensions, elesfn$9, elesfn$8, elesfn$7, elesfn$6, elesfn$5, elesfn$4, elesfn$3, elesfn$2].forEach(function (props) {\n    extend(elesfn$1, props);\n  });\n\n  var corefn$9 = {\n    add: function add(opts) {\n      var elements;\n      var cy = this; // add the elements\n\n      if (elementOrCollection(opts)) {\n        var eles = opts;\n\n        if (eles._private.cy === cy) {\n          // same instance => just restore\n          elements = eles.restore();\n        } else {\n          // otherwise, copy from json\n          var jsons = [];\n\n          for (var i = 0; i < eles.length; i++) {\n            var ele = eles[i];\n            jsons.push(ele.json());\n          }\n\n          elements = new Collection(cy, jsons);\n        }\n      } // specify an array of options\n      else if (array(opts)) {\n        var _jsons = opts;\n        elements = new Collection(cy, _jsons);\n      } // specify via opts.nodes and opts.edges\n      else if (plainObject(opts) && (array(opts.nodes) || array(opts.edges))) {\n        var elesByGroup = opts;\n        var _jsons2 = [];\n        var grs = ['nodes', 'edges'];\n\n        for (var _i = 0, il = grs.length; _i < il; _i++) {\n          var group = grs[_i];\n          var elesArray = elesByGroup[group];\n\n          if (array(elesArray)) {\n            for (var j = 0, jl = elesArray.length; j < jl; j++) {\n              var json = extend({\n                group: group\n              }, elesArray[j]);\n\n              _jsons2.push(json);\n            }\n          }\n        }\n\n        elements = new Collection(cy, _jsons2);\n      } // specify options for one element\n      else {\n        var _json = opts;\n        elements = new Element(cy, _json).collection();\n      }\n\n      return elements;\n    },\n    remove: function remove(collection) {\n      if (elementOrCollection(collection)) ; else if (string(collection)) {\n        var selector = collection;\n        collection = this.$(selector);\n      }\n\n      return collection.remove();\n    }\n  };\n\n  /* global Float32Array */\n\n  /*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */\n  function generateCubicBezier(mX1, mY1, mX2, mY2) {\n    var NEWTON_ITERATIONS = 4,\n        NEWTON_MIN_SLOPE = 0.001,\n        SUBDIVISION_PRECISION = 0.0000001,\n        SUBDIVISION_MAX_ITERATIONS = 10,\n        kSplineTableSize = 11,\n        kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),\n        float32ArraySupported = typeof Float32Array !== 'undefined';\n    /* Must contain four arguments. */\n\n    if (arguments.length !== 4) {\n      return false;\n    }\n    /* Arguments must be numbers. */\n\n\n    for (var i = 0; i < 4; ++i) {\n      if (typeof arguments[i] !== \"number\" || isNaN(arguments[i]) || !isFinite(arguments[i])) {\n        return false;\n      }\n    }\n    /* X values must be in the [0, 1] range. */\n\n\n    mX1 = Math.min(mX1, 1);\n    mX2 = Math.min(mX2, 1);\n    mX1 = Math.max(mX1, 0);\n    mX2 = Math.max(mX2, 0);\n    var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);\n\n    function A(aA1, aA2) {\n      return 1.0 - 3.0 * aA2 + 3.0 * aA1;\n    }\n\n    function B(aA1, aA2) {\n      return 3.0 * aA2 - 6.0 * aA1;\n    }\n\n    function C(aA1) {\n      return 3.0 * aA1;\n    }\n\n    function calcBezier(aT, aA1, aA2) {\n      return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;\n    }\n\n    function getSlope(aT, aA1, aA2) {\n      return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);\n    }\n\n    function newtonRaphsonIterate(aX, aGuessT) {\n      for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {\n        var currentSlope = getSlope(aGuessT, mX1, mX2);\n\n        if (currentSlope === 0.0) {\n          return aGuessT;\n        }\n\n        var currentX = calcBezier(aGuessT, mX1, mX2) - aX;\n        aGuessT -= currentX / currentSlope;\n      }\n\n      return aGuessT;\n    }\n\n    function calcSampleValues() {\n      for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {\n        mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);\n      }\n    }\n\n    function binarySubdivide(aX, aA, aB) {\n      var currentX,\n          currentT,\n          i = 0;\n\n      do {\n        currentT = aA + (aB - aA) / 2.0;\n        currentX = calcBezier(currentT, mX1, mX2) - aX;\n\n        if (currentX > 0.0) {\n          aB = currentT;\n        } else {\n          aA = currentT;\n        }\n      } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);\n\n      return currentT;\n    }\n\n    function getTForX(aX) {\n      var intervalStart = 0.0,\n          currentSample = 1,\n          lastSample = kSplineTableSize - 1;\n\n      for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {\n        intervalStart += kSampleStepSize;\n      }\n\n      --currentSample;\n      var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),\n          guessForT = intervalStart + dist * kSampleStepSize,\n          initialSlope = getSlope(guessForT, mX1, mX2);\n\n      if (initialSlope >= NEWTON_MIN_SLOPE) {\n        return newtonRaphsonIterate(aX, guessForT);\n      } else if (initialSlope === 0.0) {\n        return guessForT;\n      } else {\n        return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);\n      }\n    }\n\n    var _precomputed = false;\n\n    function precompute() {\n      _precomputed = true;\n\n      if (mX1 !== mY1 || mX2 !== mY2) {\n        calcSampleValues();\n      }\n    }\n\n    var f = function f(aX) {\n      if (!_precomputed) {\n        precompute();\n      }\n\n      if (mX1 === mY1 && mX2 === mY2) {\n        return aX;\n      }\n\n      if (aX === 0) {\n        return 0;\n      }\n\n      if (aX === 1) {\n        return 1;\n      }\n\n      return calcBezier(getTForX(aX), mY1, mY2);\n    };\n\n    f.getControlPoints = function () {\n      return [{\n        x: mX1,\n        y: mY1\n      }, {\n        x: mX2,\n        y: mY2\n      }];\n    };\n\n    var str = \"generateBezier(\" + [mX1, mY1, mX2, mY2] + \")\";\n\n    f.toString = function () {\n      return str;\n    };\n\n    return f;\n  }\n\n  /*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */\n\n  /* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass\n     then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */\n  var generateSpringRK4 = function () {\n    function springAccelerationForState(state) {\n      return -state.tension * state.x - state.friction * state.v;\n    }\n\n    function springEvaluateStateWithDerivative(initialState, dt, derivative) {\n      var state = {\n        x: initialState.x + derivative.dx * dt,\n        v: initialState.v + derivative.dv * dt,\n        tension: initialState.tension,\n        friction: initialState.friction\n      };\n      return {\n        dx: state.v,\n        dv: springAccelerationForState(state)\n      };\n    }\n\n    function springIntegrateState(state, dt) {\n      var a = {\n        dx: state.v,\n        dv: springAccelerationForState(state)\n      },\n          b = springEvaluateStateWithDerivative(state, dt * 0.5, a),\n          c = springEvaluateStateWithDerivative(state, dt * 0.5, b),\n          d = springEvaluateStateWithDerivative(state, dt, c),\n          dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),\n          dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);\n      state.x = state.x + dxdt * dt;\n      state.v = state.v + dvdt * dt;\n      return state;\n    }\n\n    return function springRK4Factory(tension, friction, duration) {\n      var initState = {\n        x: -1,\n        v: 0,\n        tension: null,\n        friction: null\n      },\n          path = [0],\n          time_lapsed = 0,\n          tolerance = 1 / 10000,\n          DT = 16 / 1000,\n          have_duration,\n          dt,\n          last_state;\n      tension = parseFloat(tension) || 500;\n      friction = parseFloat(friction) || 20;\n      duration = duration || null;\n      initState.tension = tension;\n      initState.friction = friction;\n      have_duration = duration !== null;\n      /* Calculate the actual time it takes for this animation to complete with the provided conditions. */\n\n      if (have_duration) {\n        /* Run the simulation without a duration. */\n        time_lapsed = springRK4Factory(tension, friction);\n        /* Compute the adjusted time delta. */\n\n        dt = time_lapsed / duration * DT;\n      } else {\n        dt = DT;\n      }\n\n      for (;;) {\n        /* Next/step function .*/\n        last_state = springIntegrateState(last_state || initState, dt);\n        /* Store the position. */\n\n        path.push(1 + last_state.x);\n        time_lapsed += 16;\n        /* If the change threshold is reached, break. */\n\n        if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {\n          break;\n        }\n      }\n      /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the\n         computed path and returns a snapshot of the position according to a given percentComplete. */\n\n\n      return !have_duration ? time_lapsed : function (percentComplete) {\n        return path[percentComplete * (path.length - 1) | 0];\n      };\n    };\n  }();\n\n  var cubicBezier = function cubicBezier(t1, p1, t2, p2) {\n    var bezier = generateCubicBezier(t1, p1, t2, p2);\n    return function (start, end, percent) {\n      return start + (end - start) * bezier(percent);\n    };\n  };\n\n  var easings = {\n    'linear': function linear(start, end, percent) {\n      return start + (end - start) * percent;\n    },\n    // default easings\n    'ease': cubicBezier(0.25, 0.1, 0.25, 1),\n    'ease-in': cubicBezier(0.42, 0, 1, 1),\n    'ease-out': cubicBezier(0, 0, 0.58, 1),\n    'ease-in-out': cubicBezier(0.42, 0, 0.58, 1),\n    // sine\n    'ease-in-sine': cubicBezier(0.47, 0, 0.745, 0.715),\n    'ease-out-sine': cubicBezier(0.39, 0.575, 0.565, 1),\n    'ease-in-out-sine': cubicBezier(0.445, 0.05, 0.55, 0.95),\n    // quad\n    'ease-in-quad': cubicBezier(0.55, 0.085, 0.68, 0.53),\n    'ease-out-quad': cubicBezier(0.25, 0.46, 0.45, 0.94),\n    'ease-in-out-quad': cubicBezier(0.455, 0.03, 0.515, 0.955),\n    // cubic\n    'ease-in-cubic': cubicBezier(0.55, 0.055, 0.675, 0.19),\n    'ease-out-cubic': cubicBezier(0.215, 0.61, 0.355, 1),\n    'ease-in-out-cubic': cubicBezier(0.645, 0.045, 0.355, 1),\n    // quart\n    'ease-in-quart': cubicBezier(0.895, 0.03, 0.685, 0.22),\n    'ease-out-quart': cubicBezier(0.165, 0.84, 0.44, 1),\n    'ease-in-out-quart': cubicBezier(0.77, 0, 0.175, 1),\n    // quint\n    'ease-in-quint': cubicBezier(0.755, 0.05, 0.855, 0.06),\n    'ease-out-quint': cubicBezier(0.23, 1, 0.32, 1),\n    'ease-in-out-quint': cubicBezier(0.86, 0, 0.07, 1),\n    // expo\n    'ease-in-expo': cubicBezier(0.95, 0.05, 0.795, 0.035),\n    'ease-out-expo': cubicBezier(0.19, 1, 0.22, 1),\n    'ease-in-out-expo': cubicBezier(1, 0, 0, 1),\n    // circ\n    'ease-in-circ': cubicBezier(0.6, 0.04, 0.98, 0.335),\n    'ease-out-circ': cubicBezier(0.075, 0.82, 0.165, 1),\n    'ease-in-out-circ': cubicBezier(0.785, 0.135, 0.15, 0.86),\n    // user param easings...\n    'spring': function spring(tension, friction, duration) {\n      if (duration === 0) {\n        // can't get a spring w/ duration 0\n        return easings.linear; // duration 0 => jump to end so impl doesn't matter\n      }\n\n      var spring = generateSpringRK4(tension, friction, duration);\n      return function (start, end, percent) {\n        return start + (end - start) * spring(percent);\n      };\n    },\n    'cubic-bezier': cubicBezier\n  };\n\n  function getEasedValue(type, start, end, percent, easingFn) {\n    if (percent === 1) {\n      return end;\n    }\n\n    if (start === end) {\n      return end;\n    }\n\n    var val = easingFn(start, end, percent);\n\n    if (type == null) {\n      return val;\n    }\n\n    if (type.roundValue || type.color) {\n      val = Math.round(val);\n    }\n\n    if (type.min !== undefined) {\n      val = Math.max(val, type.min);\n    }\n\n    if (type.max !== undefined) {\n      val = Math.min(val, type.max);\n    }\n\n    return val;\n  }\n\n  function getValue(prop, spec) {\n    if (prop.pfValue != null || prop.value != null) {\n      if (prop.pfValue != null && (spec == null || spec.type.units !== '%')) {\n        return prop.pfValue;\n      } else {\n        return prop.value;\n      }\n    } else {\n      return prop;\n    }\n  }\n\n  function ease(startProp, endProp, percent, easingFn, propSpec) {\n    var type = propSpec != null ? propSpec.type : null;\n\n    if (percent < 0) {\n      percent = 0;\n    } else if (percent > 1) {\n      percent = 1;\n    }\n\n    var start = getValue(startProp, propSpec);\n    var end = getValue(endProp, propSpec);\n\n    if (number$1(start) && number$1(end)) {\n      return getEasedValue(type, start, end, percent, easingFn);\n    } else if (array(start) && array(end)) {\n      var easedArr = [];\n\n      for (var i = 0; i < end.length; i++) {\n        var si = start[i];\n        var ei = end[i];\n\n        if (si != null && ei != null) {\n          var val = getEasedValue(type, si, ei, percent, easingFn);\n          easedArr.push(val);\n        } else {\n          easedArr.push(ei);\n        }\n      }\n\n      return easedArr;\n    }\n\n    return undefined;\n  }\n\n  function step$1(self, ani, now, isCore) {\n    var isEles = !isCore;\n    var _p = self._private;\n    var ani_p = ani._private;\n    var pEasing = ani_p.easing;\n    var startTime = ani_p.startTime;\n    var cy = isCore ? self : self.cy();\n    var style = cy.style();\n\n    if (!ani_p.easingImpl) {\n      if (pEasing == null) {\n        // use default\n        ani_p.easingImpl = easings['linear'];\n      } else {\n        // then define w/ name\n        var easingVals;\n\n        if (string(pEasing)) {\n          var easingProp = style.parse('transition-timing-function', pEasing);\n          easingVals = easingProp.value;\n        } else {\n          // then assume preparsed array\n          easingVals = pEasing;\n        }\n\n        var name, args;\n\n        if (string(easingVals)) {\n          name = easingVals;\n          args = [];\n        } else {\n          name = easingVals[1];\n          args = easingVals.slice(2).map(function (n) {\n            return +n;\n          });\n        }\n\n        if (args.length > 0) {\n          // create with args\n          if (name === 'spring') {\n            args.push(ani_p.duration); // need duration to generate spring\n          }\n\n          ani_p.easingImpl = easings[name].apply(null, args);\n        } else {\n          // static impl by name\n          ani_p.easingImpl = easings[name];\n        }\n      }\n    }\n\n    var easing = ani_p.easingImpl;\n    var percent;\n\n    if (ani_p.duration === 0) {\n      percent = 1;\n    } else {\n      percent = (now - startTime) / ani_p.duration;\n    }\n\n    if (ani_p.applying) {\n      percent = ani_p.progress;\n    }\n\n    if (percent < 0) {\n      percent = 0;\n    } else if (percent > 1) {\n      percent = 1;\n    }\n\n    if (ani_p.delay == null) {\n      // then update\n      var startPos = ani_p.startPosition;\n      var endPos = ani_p.position;\n\n      if (endPos && isEles && !self.locked()) {\n        var newPos = {};\n\n        if (valid(startPos.x, endPos.x)) {\n          newPos.x = ease(startPos.x, endPos.x, percent, easing);\n        }\n\n        if (valid(startPos.y, endPos.y)) {\n          newPos.y = ease(startPos.y, endPos.y, percent, easing);\n        }\n\n        self.position(newPos);\n      }\n\n      var startPan = ani_p.startPan;\n      var endPan = ani_p.pan;\n      var pan = _p.pan;\n      var animatingPan = endPan != null && isCore;\n\n      if (animatingPan) {\n        if (valid(startPan.x, endPan.x)) {\n          pan.x = ease(startPan.x, endPan.x, percent, easing);\n        }\n\n        if (valid(startPan.y, endPan.y)) {\n          pan.y = ease(startPan.y, endPan.y, percent, easing);\n        }\n\n        self.emit('pan');\n      }\n\n      var startZoom = ani_p.startZoom;\n      var endZoom = ani_p.zoom;\n      var animatingZoom = endZoom != null && isCore;\n\n      if (animatingZoom) {\n        if (valid(startZoom, endZoom)) {\n          _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);\n        }\n\n        self.emit('zoom');\n      }\n\n      if (animatingPan || animatingZoom) {\n        self.emit('viewport');\n      }\n\n      var props = ani_p.style;\n\n      if (props && props.length > 0 && isEles) {\n        for (var i = 0; i < props.length; i++) {\n          var prop = props[i];\n          var _name = prop.name;\n          var end = prop;\n          var start = ani_p.startStyle[_name];\n          var propSpec = style.properties[start.name];\n          var easedVal = ease(start, end, percent, easing, propSpec);\n          style.overrideBypass(self, _name, easedVal);\n        } // for props\n\n\n        self.emit('style');\n      } // if\n\n    }\n\n    ani_p.progress = percent;\n    return percent;\n  }\n\n  function valid(start, end) {\n    if (start == null || end == null) {\n      return false;\n    }\n\n    if (number$1(start) && number$1(end)) {\n      return true;\n    } else if (start && end) {\n      return true;\n    }\n\n    return false;\n  }\n\n  function startAnimation(self, ani, now, isCore) {\n    var ani_p = ani._private;\n    ani_p.started = true;\n    ani_p.startTime = now - ani_p.progress * ani_p.duration;\n  }\n\n  function stepAll(now, cy) {\n    var eles = cy._private.aniEles;\n    var doneEles = [];\n\n    function stepOne(ele, isCore) {\n      var _p = ele._private;\n      var current = _p.animation.current;\n      var queue = _p.animation.queue;\n      var ranAnis = false; // if nothing currently animating, get something from the queue\n\n      if (current.length === 0) {\n        var next = queue.shift();\n\n        if (next) {\n          current.push(next);\n        }\n      }\n\n      var callbacks = function callbacks(_callbacks) {\n        for (var j = _callbacks.length - 1; j >= 0; j--) {\n          var cb = _callbacks[j];\n          cb();\n        }\n\n        _callbacks.splice(0, _callbacks.length);\n      }; // step and remove if done\n\n\n      for (var i = current.length - 1; i >= 0; i--) {\n        var ani = current[i];\n        var ani_p = ani._private;\n\n        if (ani_p.stopped) {\n          current.splice(i, 1);\n          ani_p.hooked = false;\n          ani_p.playing = false;\n          ani_p.started = false;\n          callbacks(ani_p.frames);\n          continue;\n        }\n\n        if (!ani_p.playing && !ani_p.applying) {\n          continue;\n        } // an apply() while playing shouldn't do anything\n\n\n        if (ani_p.playing && ani_p.applying) {\n          ani_p.applying = false;\n        }\n\n        if (!ani_p.started) {\n          startAnimation(ele, ani, now);\n        }\n\n        step$1(ele, ani, now, isCore);\n\n        if (ani_p.applying) {\n          ani_p.applying = false;\n        }\n\n        callbacks(ani_p.frames);\n\n        if (ani_p.step != null) {\n          ani_p.step(now);\n        }\n\n        if (ani.completed()) {\n          current.splice(i, 1);\n          ani_p.hooked = false;\n          ani_p.playing = false;\n          ani_p.started = false;\n          callbacks(ani_p.completes);\n        }\n\n        ranAnis = true;\n      }\n\n      if (!isCore && current.length === 0 && queue.length === 0) {\n        doneEles.push(ele);\n      }\n\n      return ranAnis;\n    } // stepElement\n    // handle all eles\n\n\n    var ranEleAni = false;\n\n    for (var e = 0; e < eles.length; e++) {\n      var ele = eles[e];\n      var handledThisEle = stepOne(ele);\n      ranEleAni = ranEleAni || handledThisEle;\n    } // each element\n\n\n    var ranCoreAni = stepOne(cy, true); // notify renderer\n\n    if (ranEleAni || ranCoreAni) {\n      if (eles.length > 0) {\n        cy.notify('draw', eles);\n      } else {\n        cy.notify('draw');\n      }\n    } // remove elements from list of currently animating if its queues are empty\n\n\n    eles.unmerge(doneEles);\n    cy.emit('step');\n  } // stepAll\n\n  var corefn$8 = {\n    // pull in animation functions\n    animate: define.animate(),\n    animation: define.animation(),\n    animated: define.animated(),\n    clearQueue: define.clearQueue(),\n    delay: define.delay(),\n    delayAnimation: define.delayAnimation(),\n    stop: define.stop(),\n    addToAnimationPool: function addToAnimationPool(eles) {\n      var cy = this;\n\n      if (!cy.styleEnabled()) {\n        return;\n      } // save cycles when no style used\n\n\n      cy._private.aniEles.merge(eles);\n    },\n    stopAnimationLoop: function stopAnimationLoop() {\n      this._private.animationsRunning = false;\n    },\n    startAnimationLoop: function startAnimationLoop() {\n      var cy = this;\n      cy._private.animationsRunning = true;\n\n      if (!cy.styleEnabled()) {\n        return;\n      } // save cycles when no style used\n      // NB the animation loop will exec in headless environments if style enabled\n      // and explicit cy.destroy() is necessary to stop the loop\n\n\n      function headlessStep() {\n        if (!cy._private.animationsRunning) {\n          return;\n        }\n\n        requestAnimationFrame(function animationStep(now) {\n          stepAll(now, cy);\n          headlessStep();\n        });\n      }\n\n      var renderer = cy.renderer();\n\n      if (renderer && renderer.beforeRender) {\n        // let the renderer schedule animations\n        renderer.beforeRender(function rendererAnimationStep(willDraw, now) {\n          stepAll(now, cy);\n        }, renderer.beforeRenderPriorities.animations);\n      } else {\n        // manage the animation loop ourselves\n        headlessStep(); // first call\n      }\n    }\n  };\n\n  var emitterOptions = {\n    qualifierCompare: function qualifierCompare(selector1, selector2) {\n      if (selector1 == null || selector2 == null) {\n        return selector1 == null && selector2 == null;\n      } else {\n        return selector1.sameText(selector2);\n      }\n    },\n    eventMatches: function eventMatches(cy, listener, eventObj) {\n      var selector = listener.qualifier;\n\n      if (selector != null) {\n        return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);\n      }\n\n      return true;\n    },\n    addEventFields: function addEventFields(cy, evt) {\n      evt.cy = cy;\n      evt.target = cy;\n    },\n    callbackContext: function callbackContext(cy, listener, eventObj) {\n      return listener.qualifier != null ? eventObj.target : cy;\n    }\n  };\n\n  var argSelector = function argSelector(arg) {\n    if (string(arg)) {\n      return new Selector(arg);\n    } else {\n      return arg;\n    }\n  };\n\n  var elesfn = {\n    createEmitter: function createEmitter() {\n      var _p = this._private;\n\n      if (!_p.emitter) {\n        _p.emitter = new Emitter(emitterOptions, this);\n      }\n\n      return this;\n    },\n    emitter: function emitter() {\n      return this._private.emitter;\n    },\n    on: function on(events, selector, callback) {\n      this.emitter().on(events, argSelector(selector), callback);\n      return this;\n    },\n    removeListener: function removeListener(events, selector, callback) {\n      this.emitter().removeListener(events, argSelector(selector), callback);\n      return this;\n    },\n    removeAllListeners: function removeAllListeners() {\n      this.emitter().removeAllListeners();\n      return this;\n    },\n    one: function one(events, selector, callback) {\n      this.emitter().one(events, argSelector(selector), callback);\n      return this;\n    },\n    once: function once(events, selector, callback) {\n      this.emitter().one(events, argSelector(selector), callback);\n      return this;\n    },\n    emit: function emit(events, extraParams) {\n      this.emitter().emit(events, extraParams);\n      return this;\n    },\n    emitAndNotify: function emitAndNotify(event, eles) {\n      this.emit(event);\n      this.notify(event, eles);\n      return this;\n    }\n  };\n  define.eventAliasesOn(elesfn);\n\n  var corefn$7 = {\n    png: function png(options) {\n      var renderer = this._private.renderer;\n      options = options || {};\n      return renderer.png(options);\n    },\n    jpg: function jpg(options) {\n      var renderer = this._private.renderer;\n      options = options || {};\n      options.bg = options.bg || '#fff';\n      return renderer.jpg(options);\n    }\n  };\n  corefn$7.jpeg = corefn$7.jpg;\n\n  var corefn$6 = {\n    layout: function layout(options) {\n      var cy = this;\n\n      if (options == null) {\n        error('Layout options must be specified to make a layout');\n        return;\n      }\n\n      if (options.name == null) {\n        error('A `name` must be specified to make a layout');\n        return;\n      }\n\n      var name = options.name;\n      var Layout = cy.extension('layout', name);\n\n      if (Layout == null) {\n        error('No such layout `' + name + '` found.  Did you forget to import it and `cytoscape.use()` it?');\n        return;\n      }\n\n      var eles;\n\n      if (string(options.eles)) {\n        eles = cy.$(options.eles);\n      } else {\n        eles = options.eles != null ? options.eles : cy.$();\n      }\n\n      var layout = new Layout(extend({}, options, {\n        cy: cy,\n        eles: eles\n      }));\n      return layout;\n    }\n  };\n  corefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;\n\n  var corefn$5 = {\n    notify: function notify(eventName, eventEles) {\n      var _p = this._private;\n\n      if (this.batching()) {\n        _p.batchNotifications = _p.batchNotifications || {};\n        var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();\n\n        if (eventEles != null) {\n          eles.merge(eventEles);\n        }\n\n        return; // notifications are disabled during batching\n      }\n\n      if (!_p.notificationsEnabled) {\n        return;\n      } // exit on disabled\n\n\n      var renderer = this.renderer(); // exit if destroy() called on core or renderer in between frames #1499 #1528\n\n      if (this.destroyed() || !renderer) {\n        return;\n      }\n\n      renderer.notify(eventName, eventEles);\n    },\n    notifications: function notifications(bool) {\n      var p = this._private;\n\n      if (bool === undefined) {\n        return p.notificationsEnabled;\n      } else {\n        p.notificationsEnabled = bool ? true : false;\n      }\n\n      return this;\n    },\n    noNotifications: function noNotifications(callback) {\n      this.notifications(false);\n      callback();\n      this.notifications(true);\n    },\n    batching: function batching() {\n      return this._private.batchCount > 0;\n    },\n    startBatch: function startBatch() {\n      var _p = this._private;\n\n      if (_p.batchCount == null) {\n        _p.batchCount = 0;\n      }\n\n      if (_p.batchCount === 0) {\n        _p.batchStyleEles = this.collection();\n        _p.batchNotifications = {};\n      }\n\n      _p.batchCount++;\n      return this;\n    },\n    endBatch: function endBatch() {\n      var _p = this._private;\n\n      if (_p.batchCount === 0) {\n        return this;\n      }\n\n      _p.batchCount--;\n\n      if (_p.batchCount === 0) {\n        // update style for dirty eles\n        _p.batchStyleEles.updateStyle();\n\n        var renderer = this.renderer(); // notify the renderer of queued eles and event types\n\n        Object.keys(_p.batchNotifications).forEach(function (eventName) {\n          var eles = _p.batchNotifications[eventName];\n\n          if (eles.empty()) {\n            renderer.notify(eventName);\n          } else {\n            renderer.notify(eventName, eles);\n          }\n        });\n      }\n\n      return this;\n    },\n    batch: function batch(callback) {\n      this.startBatch();\n      callback();\n      this.endBatch();\n      return this;\n    },\n    // for backwards compatibility\n    batchData: function batchData(map) {\n      var cy = this;\n      return this.batch(function () {\n        var ids = Object.keys(map);\n\n        for (var i = 0; i < ids.length; i++) {\n          var id = ids[i];\n          var data = map[id];\n          var ele = cy.getElementById(id);\n          ele.data(data);\n        }\n      });\n    }\n  };\n\n  var rendererDefaults = defaults$g({\n    hideEdgesOnViewport: false,\n    textureOnViewport: false,\n    motionBlur: false,\n    motionBlurOpacity: 0.05,\n    pixelRatio: undefined,\n    desktopTapThreshold: 4,\n    touchTapThreshold: 8,\n    wheelSensitivity: 1,\n    debug: false,\n    showFps: false\n  });\n  var corefn$4 = {\n    renderTo: function renderTo(context, zoom, pan, pxRatio) {\n      var r = this._private.renderer;\n      r.renderTo(context, zoom, pan, pxRatio);\n      return this;\n    },\n    renderer: function renderer() {\n      return this._private.renderer;\n    },\n    forceRender: function forceRender() {\n      this.notify('draw');\n      return this;\n    },\n    resize: function resize() {\n      this.invalidateSize();\n      this.emitAndNotify('resize');\n      return this;\n    },\n    initRenderer: function initRenderer(options) {\n      var cy = this;\n      var RendererProto = cy.extension('renderer', options.name);\n\n      if (RendererProto == null) {\n        error(\"Can not initialise: No such renderer `\".concat(options.name, \"` found. Did you forget to import it and `cytoscape.use()` it?\"));\n        return;\n      }\n\n      if (options.wheelSensitivity !== undefined) {\n        warn(\"You have set a custom wheel sensitivity.  This will make your app zoom unnaturally when using mainstream mice.  You should change this value from the default only if you can guarantee that all your users will use the same hardware and OS configuration as your current machine.\");\n      }\n\n      var rOpts = rendererDefaults(options);\n      rOpts.cy = cy;\n      cy._private.renderer = new RendererProto(rOpts);\n      this.notify('init');\n    },\n    destroyRenderer: function destroyRenderer() {\n      var cy = this;\n      cy.notify('destroy'); // destroy the renderer\n\n      var domEle = cy.container();\n\n      if (domEle) {\n        domEle._cyreg = null;\n\n        while (domEle.childNodes.length > 0) {\n          domEle.removeChild(domEle.childNodes[0]);\n        }\n      }\n\n      cy._private.renderer = null; // to be extra safe, remove the ref\n\n      cy.mutableElements().forEach(function (ele) {\n        var _p = ele._private;\n        _p.rscratch = {};\n        _p.rstyle = {};\n        _p.animation.current = [];\n        _p.animation.queue = [];\n      });\n    },\n    onRender: function onRender(fn) {\n      return this.on('render', fn);\n    },\n    offRender: function offRender(fn) {\n      return this.off('render', fn);\n    }\n  };\n  corefn$4.invalidateDimensions = corefn$4.resize;\n\n  var corefn$3 = {\n    // get a collection\n    // - empty collection on no args\n    // - collection of elements in the graph on selector arg\n    // - guarantee a returned collection when elements or collection specified\n    collection: function collection(eles, opts) {\n      if (string(eles)) {\n        return this.$(eles);\n      } else if (elementOrCollection(eles)) {\n        return eles.collection();\n      } else if (array(eles)) {\n        if (!opts) {\n          opts = {};\n        }\n\n        return new Collection(this, eles, opts.unique, opts.removed);\n      }\n\n      return new Collection(this);\n    },\n    nodes: function nodes(selector) {\n      var nodes = this.$(function (ele) {\n        return ele.isNode();\n      });\n\n      if (selector) {\n        return nodes.filter(selector);\n      }\n\n      return nodes;\n    },\n    edges: function edges(selector) {\n      var edges = this.$(function (ele) {\n        return ele.isEdge();\n      });\n\n      if (selector) {\n        return edges.filter(selector);\n      }\n\n      return edges;\n    },\n    // search the graph like jQuery\n    $: function $(selector) {\n      var eles = this._private.elements;\n\n      if (selector) {\n        return eles.filter(selector);\n      } else {\n        return eles.spawnSelf();\n      }\n    },\n    mutableElements: function mutableElements() {\n      return this._private.elements;\n    }\n  }; // aliases\n\n  corefn$3.elements = corefn$3.filter = corefn$3.$;\n\n  var styfn$8 = {}; // keys for style blocks, e.g. ttfftt\n\n  var TRUE = 't';\n  var FALSE = 'f'; // (potentially expensive calculation)\n  // apply the style to the element based on\n  // - its bypass\n  // - what selectors match it\n\n  styfn$8.apply = function (eles) {\n    var self = this;\n    var _p = self._private;\n    var cy = _p.cy;\n    var updatedEles = cy.collection();\n\n    for (var ie = 0; ie < eles.length; ie++) {\n      var ele = eles[ie];\n      var cxtMeta = self.getContextMeta(ele);\n\n      if (cxtMeta.empty) {\n        continue;\n      }\n\n      var cxtStyle = self.getContextStyle(cxtMeta);\n      var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);\n\n      if (ele._private.appliedInitStyle) {\n        self.updateTransitions(ele, app.diffProps);\n      } else {\n        ele._private.appliedInitStyle = true;\n      }\n\n      var hintsDiff = self.updateStyleHints(ele);\n\n      if (hintsDiff) {\n        updatedEles.push(ele);\n      }\n    } // for elements\n\n\n    return updatedEles;\n  };\n\n  styfn$8.getPropertiesDiff = function (oldCxtKey, newCxtKey) {\n    var self = this;\n    var cache = self._private.propDiffs = self._private.propDiffs || {};\n    var dualCxtKey = oldCxtKey + '-' + newCxtKey;\n    var cachedVal = cache[dualCxtKey];\n\n    if (cachedVal) {\n      return cachedVal;\n    }\n\n    var diffProps = [];\n    var addedProp = {};\n\n    for (var i = 0; i < self.length; i++) {\n      var cxt = self[i];\n      var oldHasCxt = oldCxtKey[i] === TRUE;\n      var newHasCxt = newCxtKey[i] === TRUE;\n      var cxtHasDiffed = oldHasCxt !== newHasCxt;\n      var cxtHasMappedProps = cxt.mappedProperties.length > 0;\n\n      if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {\n        var props = void 0;\n\n        if (cxtHasDiffed && cxtHasMappedProps) {\n          props = cxt.properties; // suffices b/c mappedProperties is a subset of properties\n        } else if (cxtHasDiffed) {\n          props = cxt.properties; // need to check them all\n        } else if (cxtHasMappedProps) {\n          props = cxt.mappedProperties; // only need to check mapped\n        }\n\n        for (var j = 0; j < props.length; j++) {\n          var prop = props[j];\n          var name = prop.name; // if a later context overrides this property, then the fact that this context has switched/diffed doesn't matter\n          // (semi expensive check since it makes this function O(n^2) on context length, but worth it since overall result\n          // is cached)\n\n          var laterCxtOverrides = false;\n\n          for (var k = i + 1; k < self.length; k++) {\n            var laterCxt = self[k];\n            var hasLaterCxt = newCxtKey[k] === TRUE;\n\n            if (!hasLaterCxt) {\n              continue;\n            } // can't override unless the context is active\n\n\n            laterCxtOverrides = laterCxt.properties[prop.name] != null;\n\n            if (laterCxtOverrides) {\n              break;\n            } // exit early as long as one later context overrides\n\n          }\n\n          if (!addedProp[name] && !laterCxtOverrides) {\n            addedProp[name] = true;\n            diffProps.push(name);\n          }\n        } // for props\n\n      } // if\n\n    } // for contexts\n\n\n    cache[dualCxtKey] = diffProps;\n    return diffProps;\n  };\n\n  styfn$8.getContextMeta = function (ele) {\n    var self = this;\n    var cxtKey = '';\n    var diffProps;\n    var prevKey = ele._private.styleCxtKey || ''; // get the cxt key\n\n    for (var i = 0; i < self.length; i++) {\n      var context = self[i];\n      var contextSelectorMatches = context.selector && context.selector.matches(ele); // NB: context.selector may be null for 'core'\n\n      if (contextSelectorMatches) {\n        cxtKey += TRUE;\n      } else {\n        cxtKey += FALSE;\n      }\n    } // for context\n\n\n    diffProps = self.getPropertiesDiff(prevKey, cxtKey);\n    ele._private.styleCxtKey = cxtKey;\n    return {\n      key: cxtKey,\n      diffPropNames: diffProps,\n      empty: diffProps.length === 0\n    };\n  }; // gets a computed ele style object based on matched contexts\n\n\n  styfn$8.getContextStyle = function (cxtMeta) {\n    var cxtKey = cxtMeta.key;\n    var self = this;\n    var cxtStyles = this._private.contextStyles = this._private.contextStyles || {}; // if already computed style, returned cached copy\n\n    if (cxtStyles[cxtKey]) {\n      return cxtStyles[cxtKey];\n    }\n\n    var style = {\n      _private: {\n        key: cxtKey\n      }\n    };\n\n    for (var i = 0; i < self.length; i++) {\n      var cxt = self[i];\n      var hasCxt = cxtKey[i] === TRUE;\n\n      if (!hasCxt) {\n        continue;\n      }\n\n      for (var j = 0; j < cxt.properties.length; j++) {\n        var prop = cxt.properties[j];\n        style[prop.name] = prop;\n      }\n    }\n\n    cxtStyles[cxtKey] = style;\n    return style;\n  };\n\n  styfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {\n    var self = this;\n    var diffProps = cxtMeta.diffPropNames;\n    var retDiffProps = {};\n    var types = self.types;\n\n    for (var i = 0; i < diffProps.length; i++) {\n      var diffPropName = diffProps[i];\n      var cxtProp = cxtStyle[diffPropName];\n      var eleProp = ele.pstyle(diffPropName);\n\n      if (!cxtProp) {\n        // no context prop means delete\n        if (!eleProp) {\n          continue; // no existing prop means nothing needs to be removed\n          // nb affects initial application on mapped values like control-point-distances\n        } else if (eleProp.bypass) {\n          cxtProp = {\n            name: diffPropName,\n            deleteBypassed: true\n          };\n        } else {\n          cxtProp = {\n            name: diffPropName,\n            \"delete\": true\n          };\n        }\n      } // save cycles when the context prop doesn't need to be applied\n\n\n      if (eleProp === cxtProp) {\n        continue;\n      } // save cycles when a mapped context prop doesn't need to be applied\n\n\n      if (cxtProp.mapped === types.fn // context prop is function mapper\n      && eleProp != null // some props can be null even by default (e.g. a prop that overrides another one)\n      && eleProp.mapping != null // ele prop is a concrete value from from a mapper\n      && eleProp.mapping.value === cxtProp.value // the current prop on the ele is a flat prop value for the function mapper\n      ) {\n        // NB don't write to cxtProp, as it's shared among eles (stored in stylesheet)\n        var mapping = eleProp.mapping; // can write to mapping, as it's a per-ele copy\n\n        var fnValue = mapping.fnValue = cxtProp.value(ele); // temporarily cache the value in case of a miss\n\n        if (fnValue === mapping.prevFnValue) {\n          continue;\n        }\n      }\n\n      var retDiffProp = retDiffProps[diffPropName] = {\n        prev: eleProp\n      };\n      self.applyParsedProperty(ele, cxtProp);\n      retDiffProp.next = ele.pstyle(diffPropName);\n\n      if (retDiffProp.next && retDiffProp.next.bypass) {\n        retDiffProp.next = retDiffProp.next.bypassed;\n      }\n    }\n\n    return {\n      diffProps: retDiffProps\n    };\n  };\n\n  styfn$8.updateStyleHints = function (ele) {\n    var _p = ele._private;\n    var self = this;\n    var propNames = self.propertyGroupNames;\n    var propGrKeys = self.propertyGroupKeys;\n\n    var propHash = function propHash(ele, propNames, seedKey) {\n      return self.getPropertiesHash(ele, propNames, seedKey);\n    };\n\n    var oldStyleKey = _p.styleKey;\n\n    if (ele.removed()) {\n      return false;\n    }\n\n    var isNode = _p.group === 'nodes'; // get the style key hashes per prop group\n    // but lazily -- only use non-default prop values to reduce the number of hashes\n    //\n\n    var overriddenStyles = ele._private.style;\n    propNames = Object.keys(overriddenStyles);\n\n    for (var i = 0; i < propGrKeys.length; i++) {\n      var grKey = propGrKeys[i];\n      _p.styleKeys[grKey] = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];\n    }\n\n    var updateGrKey1 = function updateGrKey1(val, grKey) {\n      return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);\n    };\n\n    var updateGrKey2 = function updateGrKey2(val, grKey) {\n      return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);\n    };\n\n    var updateGrKey = function updateGrKey(val, grKey) {\n      updateGrKey1(val, grKey);\n      updateGrKey2(val, grKey);\n    };\n\n    var updateGrKeyWStr = function updateGrKeyWStr(strVal, grKey) {\n      for (var j = 0; j < strVal.length; j++) {\n        var ch = strVal.charCodeAt(j);\n        updateGrKey1(ch, grKey);\n        updateGrKey2(ch, grKey);\n      }\n    }; // - hashing works on 32 bit ints b/c we use bitwise ops\n    // - small numbers get cut off (e.g. 0.123 is seen as 0 by the hashing function)\n    // - raise up small numbers so more significant digits are seen by hashing\n    // - make small numbers larger than a normal value to avoid collisions\n    // - works in practice and it's relatively cheap\n\n\n    var N = 2000000000;\n\n    var cleanNum = function cleanNum(val) {\n      return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;\n    };\n\n    for (var _i = 0; _i < propNames.length; _i++) {\n      var name = propNames[_i];\n      var parsedProp = overriddenStyles[name];\n\n      if (parsedProp == null) {\n        continue;\n      }\n\n      var propInfo = this.properties[name];\n      var type = propInfo.type;\n      var _grKey = propInfo.groupKey;\n      var normalizedNumberVal = void 0;\n\n      if (propInfo.hashOverride != null) {\n        normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);\n      } else if (parsedProp.pfValue != null) {\n        normalizedNumberVal = parsedProp.pfValue;\n      } // might not be a number if it allows enums\n\n\n      var numberVal = propInfo.enums == null ? parsedProp.value : null;\n      var haveNormNum = normalizedNumberVal != null;\n      var haveUnitedNum = numberVal != null;\n      var haveNum = haveNormNum || haveUnitedNum;\n      var units = parsedProp.units; // numbers are cheaper to hash than strings\n      // 1 hash op vs n hash ops (for length n string)\n\n      if (type.number && haveNum && !type.multiple) {\n        var v = haveNormNum ? normalizedNumberVal : numberVal;\n        updateGrKey(cleanNum(v), _grKey);\n\n        if (!haveNormNum && units != null) {\n          updateGrKeyWStr(units, _grKey);\n        }\n      } else {\n        updateGrKeyWStr(parsedProp.strValue, _grKey);\n      }\n    } // overall style key\n    //\n\n\n    var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];\n\n    for (var _i2 = 0; _i2 < propGrKeys.length; _i2++) {\n      var _grKey2 = propGrKeys[_i2];\n      var grHash = _p.styleKeys[_grKey2];\n      hash[0] = hashInt(grHash[0], hash[0]);\n      hash[1] = hashIntAlt(grHash[1], hash[1]);\n    }\n\n    _p.styleKey = combineHashes(hash[0], hash[1]); // label dims\n    //\n\n    var sk = _p.styleKeys;\n    _p.labelDimsKey = combineHashesArray(sk.labelDimensions);\n    var labelKeys = propHash(ele, ['label'], sk.labelDimensions);\n    _p.labelKey = combineHashesArray(labelKeys);\n    _p.labelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, labelKeys));\n\n    if (!isNode) {\n      var sourceLabelKeys = propHash(ele, ['source-label'], sk.labelDimensions);\n      _p.sourceLabelKey = combineHashesArray(sourceLabelKeys);\n      _p.sourceLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, sourceLabelKeys));\n      var targetLabelKeys = propHash(ele, ['target-label'], sk.labelDimensions);\n      _p.targetLabelKey = combineHashesArray(targetLabelKeys);\n      _p.targetLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, targetLabelKeys));\n    } // node\n    //\n\n\n    if (isNode) {\n      var _p$styleKeys = _p.styleKeys,\n          nodeBody = _p$styleKeys.nodeBody,\n          nodeBorder = _p$styleKeys.nodeBorder,\n          backgroundImage = _p$styleKeys.backgroundImage,\n          compound = _p$styleKeys.compound,\n          pie = _p$styleKeys.pie;\n      var nodeKeys = [nodeBody, nodeBorder, backgroundImage, compound, pie].filter(function (k) {\n        return k != null;\n      }).reduce(hashArrays, [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT]);\n      _p.nodeKey = combineHashesArray(nodeKeys);\n      _p.hasPie = pie != null && pie[0] !== DEFAULT_HASH_SEED && pie[1] !== DEFAULT_HASH_SEED_ALT;\n    }\n\n    return oldStyleKey !== _p.styleKey;\n  };\n\n  styfn$8.clearStyleHints = function (ele) {\n    var _p = ele._private;\n    _p.styleCxtKey = '';\n    _p.styleKeys = {};\n    _p.styleKey = null;\n    _p.labelKey = null;\n    _p.labelStyleKey = null;\n    _p.sourceLabelKey = null;\n    _p.sourceLabelStyleKey = null;\n    _p.targetLabelKey = null;\n    _p.targetLabelStyleKey = null;\n    _p.nodeKey = null;\n    _p.hasPie = null;\n  }; // apply a property to the style (for internal use)\n  // returns whether application was successful\n  //\n  // now, this function flattens the property, and here's how:\n  //\n  // for parsedProp:{ bypass: true, deleteBypass: true }\n  // no property is generated, instead the bypass property in the\n  // element's style is replaced by what's pointed to by the `bypassed`\n  // field in the bypass property (i.e. restoring the property the\n  // bypass was overriding)\n  //\n  // for parsedProp:{ mapped: truthy }\n  // the generated flattenedProp:{ mapping: prop }\n  //\n  // for parsedProp:{ bypass: true }\n  // the generated flattenedProp:{ bypassed: parsedProp }\n\n\n  styfn$8.applyParsedProperty = function (ele, parsedProp) {\n    var self = this;\n    var prop = parsedProp;\n    var style = ele._private.style;\n    var flatProp;\n    var types = self.types;\n    var type = self.properties[prop.name].type;\n    var propIsBypass = prop.bypass;\n    var origProp = style[prop.name];\n    var origPropIsBypass = origProp && origProp.bypass;\n    var _p = ele._private;\n    var flatPropMapping = 'mapping';\n\n    var getVal = function getVal(p) {\n      if (p == null) {\n        return null;\n      } else if (p.pfValue != null) {\n        return p.pfValue;\n      } else {\n        return p.value;\n      }\n    };\n\n    var checkTriggers = function checkTriggers() {\n      var fromVal = getVal(origProp);\n      var toVal = getVal(prop);\n      self.checkTriggers(ele, prop.name, fromVal, toVal);\n    };\n\n    if (prop && prop.name.substr(0, 3) === 'pie') {\n      warn('The pie style properties are deprecated.  Create charts using background images instead.');\n    } // edge sanity checks to prevent the client from making serious mistakes\n\n\n    if (parsedProp.name === 'curve-style' && ele.isEdge() && ( // loops must be bundled beziers\n    parsedProp.value !== 'bezier' && ele.isLoop() || // edges connected to compound nodes can not be haystacks\n    parsedProp.value === 'haystack' && (ele.source().isParent() || ele.target().isParent()))) {\n      prop = parsedProp = this.parse(parsedProp.name, 'bezier', propIsBypass);\n    }\n\n    if (prop[\"delete\"]) {\n      // delete the property and use the default value on falsey value\n      style[prop.name] = undefined;\n      checkTriggers();\n      return true;\n    }\n\n    if (prop.deleteBypassed) {\n      // delete the property that the\n      if (!origProp) {\n        checkTriggers();\n        return true; // can't delete if no prop\n      } else if (origProp.bypass) {\n        // delete bypassed\n        origProp.bypassed = undefined;\n        checkTriggers();\n        return true;\n      } else {\n        return false; // we're unsuccessful deleting the bypassed\n      }\n    } // check if we need to delete the current bypass\n\n\n    if (prop.deleteBypass) {\n      // then this property is just here to indicate we need to delete\n      if (!origProp) {\n        checkTriggers();\n        return true; // property is already not defined\n      } else if (origProp.bypass) {\n        // then replace the bypass property with the original\n        // because the bypassed property was already applied (and therefore parsed), we can just replace it (no reapplying necessary)\n        style[prop.name] = origProp.bypassed;\n        checkTriggers();\n        return true;\n      } else {\n        return false; // we're unsuccessful deleting the bypass\n      }\n    }\n\n    var printMappingErr = function printMappingErr() {\n      warn('Do not assign mappings to elements without corresponding data (i.e. ele `' + ele.id() + '` has no mapping for property `' + prop.name + '` with data field `' + prop.field + '`); try a `[' + prop.field + ']` selector to limit scope to elements with `' + prop.field + '` defined');\n    }; // put the property in the style objects\n\n\n    switch (prop.mapped) {\n      // flatten the property if mapped\n      case types.mapData:\n        {\n          // flatten the field (e.g. data.foo.bar)\n          var fields = prop.field.split('.');\n          var fieldVal = _p.data;\n\n          for (var i = 0; i < fields.length && fieldVal; i++) {\n            var field = fields[i];\n            fieldVal = fieldVal[field];\n          }\n\n          if (fieldVal == null) {\n            printMappingErr();\n            return false;\n          }\n\n          var percent;\n\n          if (!number$1(fieldVal)) {\n            // then don't apply and fall back on the existing style\n            warn('Do not use continuous mappers without specifying numeric data (i.e. `' + prop.field + ': ' + fieldVal + '` for `' + ele.id() + '` is non-numeric)');\n            return false;\n          } else {\n            var fieldWidth = prop.fieldMax - prop.fieldMin;\n\n            if (fieldWidth === 0) {\n              // safety check -- not strictly necessary as no props of zero range should be passed here\n              percent = 0;\n            } else {\n              percent = (fieldVal - prop.fieldMin) / fieldWidth;\n            }\n          } // make sure to bound percent value\n\n\n          if (percent < 0) {\n            percent = 0;\n          } else if (percent > 1) {\n            percent = 1;\n          }\n\n          if (type.color) {\n            var r1 = prop.valueMin[0];\n            var r2 = prop.valueMax[0];\n            var g1 = prop.valueMin[1];\n            var g2 = prop.valueMax[1];\n            var b1 = prop.valueMin[2];\n            var b2 = prop.valueMax[2];\n            var a1 = prop.valueMin[3] == null ? 1 : prop.valueMin[3];\n            var a2 = prop.valueMax[3] == null ? 1 : prop.valueMax[3];\n            var clr = [Math.round(r1 + (r2 - r1) * percent), Math.round(g1 + (g2 - g1) * percent), Math.round(b1 + (b2 - b1) * percent), Math.round(a1 + (a2 - a1) * percent)];\n            flatProp = {\n              // colours are simple, so just create the flat property instead of expensive string parsing\n              bypass: prop.bypass,\n              // we're a bypass if the mapping property is a bypass\n              name: prop.name,\n              value: clr,\n              strValue: 'rgb(' + clr[0] + ', ' + clr[1] + ', ' + clr[2] + ')'\n            };\n          } else if (type.number) {\n            var calcValue = prop.valueMin + (prop.valueMax - prop.valueMin) * percent;\n            flatProp = this.parse(prop.name, calcValue, prop.bypass, flatPropMapping);\n          } else {\n            return false; // can only map to colours and numbers\n          }\n\n          if (!flatProp) {\n            // if we can't flatten the property, then don't apply the property and fall back on the existing style\n            printMappingErr();\n            return false;\n          }\n\n          flatProp.mapping = prop; // keep a reference to the mapping\n\n          prop = flatProp; // the flattened (mapped) property is the one we want\n\n          break;\n        }\n      // direct mapping\n\n      case types.data:\n        {\n          // flatten the field (e.g. data.foo.bar)\n          var _fields = prop.field.split('.');\n\n          var _fieldVal = _p.data;\n\n          for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {\n            var _field = _fields[_i3];\n            _fieldVal = _fieldVal[_field];\n          }\n\n          if (_fieldVal != null) {\n            flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);\n          }\n\n          if (!flatProp) {\n            // if we can't flatten the property, then don't apply and fall back on the existing style\n            printMappingErr();\n            return false;\n          }\n\n          flatProp.mapping = prop; // keep a reference to the mapping\n\n          prop = flatProp; // the flattened (mapped) property is the one we want\n\n          break;\n        }\n\n      case types.fn:\n        {\n          var fn = prop.value;\n          var fnRetVal = prop.fnValue != null ? prop.fnValue : fn(ele); // check for cached value before calling function\n\n          prop.prevFnValue = fnRetVal;\n\n          if (fnRetVal == null) {\n            warn('Custom function mappers may not return null (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is null)');\n            return false;\n          }\n\n          flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);\n\n          if (!flatProp) {\n            warn('Custom function mappers may not return invalid values for the property type (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is invalid)');\n            return false;\n          }\n\n          flatProp.mapping = copy(prop); // keep a reference to the mapping\n\n          prop = flatProp; // the flattened (mapped) property is the one we want\n\n          break;\n        }\n\n      case undefined:\n        break;\n      // just set the property\n\n      default:\n        return false;\n      // not a valid mapping\n    } // if the property is a bypass property, then link the resultant property to the original one\n\n\n    if (propIsBypass) {\n      if (origPropIsBypass) {\n        // then this bypass overrides the existing one\n        prop.bypassed = origProp.bypassed; // steal bypassed prop from old bypass\n      } else {\n        // then link the orig prop to the new bypass\n        prop.bypassed = origProp;\n      }\n\n      style[prop.name] = prop; // and set\n    } else {\n      // prop is not bypass\n      if (origPropIsBypass) {\n        // then keep the orig prop (since it's a bypass) and link to the new prop\n        origProp.bypassed = prop;\n      } else {\n        // then just replace the old prop with the new one\n        style[prop.name] = prop;\n      }\n    }\n\n    checkTriggers();\n    return true;\n  };\n\n  styfn$8.cleanElements = function (eles, keepBypasses) {\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      this.clearStyleHints(ele);\n      ele.dirtyCompoundBoundsCache();\n      ele.dirtyBoundingBoxCache();\n\n      if (!keepBypasses) {\n        ele._private.style = {};\n      } else {\n        var style = ele._private.style;\n        var propNames = Object.keys(style);\n\n        for (var j = 0; j < propNames.length; j++) {\n          var propName = propNames[j];\n          var eleProp = style[propName];\n\n          if (eleProp != null) {\n            if (eleProp.bypass) {\n              eleProp.bypassed = null;\n            } else {\n              style[propName] = null;\n            }\n          }\n        }\n      }\n    }\n  }; // updates the visual style for all elements (useful for manual style modification after init)\n\n\n  styfn$8.update = function () {\n    var cy = this._private.cy;\n    var eles = cy.mutableElements();\n    eles.updateStyle();\n  }; // diffProps : { name => { prev, next } }\n\n\n  styfn$8.updateTransitions = function (ele, diffProps) {\n    var self = this;\n    var _p = ele._private;\n    var props = ele.pstyle('transition-property').value;\n    var duration = ele.pstyle('transition-duration').pfValue;\n    var delay = ele.pstyle('transition-delay').pfValue;\n\n    if (props.length > 0 && duration > 0) {\n      var style = {}; // build up the style to animate towards\n\n      var anyPrev = false;\n\n      for (var i = 0; i < props.length; i++) {\n        var prop = props[i];\n        var styProp = ele.pstyle(prop);\n        var diffProp = diffProps[prop];\n\n        if (!diffProp) {\n          continue;\n        }\n\n        var prevProp = diffProp.prev;\n        var fromProp = prevProp;\n        var toProp = diffProp.next != null ? diffProp.next : styProp;\n        var diff = false;\n        var initVal = void 0;\n        var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)\n\n        if (!fromProp) {\n          continue;\n        } // consider px values\n\n\n        if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {\n          diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy\n\n          initVal = fromProp.pfValue + initDt * diff; // consider numerical values\n        } else if (number$1(fromProp.value) && number$1(toProp.value)) {\n          diff = toProp.value - fromProp.value; // nonzero is truthy\n\n          initVal = fromProp.value + initDt * diff; // consider colour values\n        } else if (array(fromProp.value) && array(toProp.value)) {\n          diff = fromProp.value[0] !== toProp.value[0] || fromProp.value[1] !== toProp.value[1] || fromProp.value[2] !== toProp.value[2];\n          initVal = fromProp.strValue;\n        } // the previous value is good for an animation only if it's different\n\n\n        if (diff) {\n          style[prop] = toProp.strValue; // to val\n\n          this.applyBypass(ele, prop, initVal); // from val\n\n          anyPrev = true;\n        }\n      } // end if props allow ani\n      // can't transition if there's nothing previous to transition from\n\n\n      if (!anyPrev) {\n        return;\n      }\n\n      _p.transitioning = true;\n      new Promise$1(function (resolve) {\n        if (delay > 0) {\n          ele.delayAnimation(delay).play().promise().then(resolve);\n        } else {\n          resolve();\n        }\n      }).then(function () {\n        return ele.animation({\n          style: style,\n          duration: duration,\n          easing: ele.pstyle('transition-timing-function').value,\n          queue: false\n        }).play().promise();\n      }).then(function () {\n        // if( !isBypass ){\n        self.removeBypasses(ele, props);\n        ele.emitAndNotify('style'); // }\n\n        _p.transitioning = false;\n      });\n    } else if (_p.transitioning) {\n      this.removeBypasses(ele, props);\n      ele.emitAndNotify('style');\n      _p.transitioning = false;\n    }\n  };\n\n  styfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {\n    var prop = this.properties[name];\n    var triggerCheck = getTrigger(prop);\n\n    if (triggerCheck != null && triggerCheck(fromValue, toValue)) {\n      onTrigger(prop);\n    }\n  };\n\n  styfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {\n    var _this = this;\n\n    this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n      return prop.triggersZOrder;\n    }, function () {\n      _this._private.cy.notify('zorder', ele);\n    });\n  };\n\n  styfn$8.checkBoundsTrigger = function (ele, name, fromValue, toValue) {\n    this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n      return prop.triggersBounds;\n    }, function (prop) {\n      ele.dirtyCompoundBoundsCache();\n      ele.dirtyBoundingBoxCache(); // if the prop change makes the bb of pll bezier edges invalid,\n      // then dirty the pll edge bb cache as well\n\n      if ( // only for beziers -- so performance of other edges isn't affected\n      prop.triggersBoundsOfParallelBeziers && (name === 'curve-style' && (fromValue === 'bezier' || toValue === 'bezier') || name === 'display' && (fromValue === 'none' || toValue === 'none'))) {\n        ele.parallelEdges().forEach(function (pllEdge) {\n          if (pllEdge.isBundledBezier()) {\n            pllEdge.dirtyBoundingBoxCache();\n          }\n        });\n      }\n    });\n  };\n\n  styfn$8.checkTriggers = function (ele, name, fromValue, toValue) {\n    ele.dirtyStyleCache();\n    this.checkZOrderTrigger(ele, name, fromValue, toValue);\n    this.checkBoundsTrigger(ele, name, fromValue, toValue);\n  };\n\n  var styfn$7 = {}; // bypasses are applied to an existing style on an element, and just tacked on temporarily\n  // returns true iff application was successful for at least 1 specified property\n\n  styfn$7.applyBypass = function (eles, name, value, updateTransitions) {\n    var self = this;\n    var props = [];\n    var isBypass = true; // put all the properties (can specify one or many) in an array after parsing them\n\n    if (name === '*' || name === '**') {\n      // apply to all property names\n      if (value !== undefined) {\n        for (var i = 0; i < self.properties.length; i++) {\n          var prop = self.properties[i];\n          var _name = prop.name;\n          var parsedProp = this.parse(_name, value, true);\n\n          if (parsedProp) {\n            props.push(parsedProp);\n          }\n        }\n      }\n    } else if (string(name)) {\n      // then parse the single property\n      var _parsedProp = this.parse(name, value, true);\n\n      if (_parsedProp) {\n        props.push(_parsedProp);\n      }\n    } else if (plainObject(name)) {\n      // then parse each property\n      var specifiedProps = name;\n      updateTransitions = value;\n      var names = Object.keys(specifiedProps);\n\n      for (var _i = 0; _i < names.length; _i++) {\n        var _name2 = names[_i];\n        var _value = specifiedProps[_name2];\n\n        if (_value === undefined) {\n          // try camel case name too\n          _value = specifiedProps[dash2camel(_name2)];\n        }\n\n        if (_value !== undefined) {\n          var _parsedProp2 = this.parse(_name2, _value, true);\n\n          if (_parsedProp2) {\n            props.push(_parsedProp2);\n          }\n        }\n      }\n    } else {\n      // can't do anything without well defined properties\n      return false;\n    } // we've failed if there are no valid properties\n\n\n    if (props.length === 0) {\n      return false;\n    } // now, apply the bypass properties on the elements\n\n\n    var ret = false; // return true if at least one succesful bypass applied\n\n    for (var _i2 = 0; _i2 < eles.length; _i2++) {\n      // for each ele\n      var ele = eles[_i2];\n      var diffProps = {};\n      var diffProp = void 0;\n\n      for (var j = 0; j < props.length; j++) {\n        // for each prop\n        var _prop = props[j];\n\n        if (updateTransitions) {\n          var prevProp = ele.pstyle(_prop.name);\n          diffProp = diffProps[_prop.name] = {\n            prev: prevProp\n          };\n        }\n\n        ret = this.applyParsedProperty(ele, copy(_prop)) || ret;\n\n        if (updateTransitions) {\n          diffProp.next = ele.pstyle(_prop.name);\n        }\n      } // for props\n\n\n      if (ret) {\n        this.updateStyleHints(ele);\n      }\n\n      if (updateTransitions) {\n        this.updateTransitions(ele, diffProps, isBypass);\n      }\n    } // for eles\n\n\n    return ret;\n  }; // only useful in specific cases like animation\n\n\n  styfn$7.overrideBypass = function (eles, name, value) {\n    name = camel2dash(name);\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      var prop = ele._private.style[name];\n      var type = this.properties[name].type;\n      var isColor = type.color;\n      var isMulti = type.mutiple;\n      var oldValue = !prop ? null : prop.pfValue != null ? prop.pfValue : prop.value;\n\n      if (!prop || !prop.bypass) {\n        // need a bypass if one doesn't exist\n        this.applyBypass(ele, name, value);\n      } else {\n        prop.value = value;\n\n        if (prop.pfValue != null) {\n          prop.pfValue = value;\n        }\n\n        if (isColor) {\n          prop.strValue = 'rgb(' + value.join(',') + ')';\n        } else if (isMulti) {\n          prop.strValue = value.join(' ');\n        } else {\n          prop.strValue = '' + value;\n        }\n\n        this.updateStyleHints(ele);\n      }\n\n      this.checkTriggers(ele, name, oldValue, value);\n    }\n  };\n\n  styfn$7.removeAllBypasses = function (eles, updateTransitions) {\n    return this.removeBypasses(eles, this.propertyNames, updateTransitions);\n  };\n\n  styfn$7.removeBypasses = function (eles, props, updateTransitions) {\n    var isBypass = true;\n\n    for (var j = 0; j < eles.length; j++) {\n      var ele = eles[j];\n      var diffProps = {};\n\n      for (var i = 0; i < props.length; i++) {\n        var name = props[i];\n        var prop = this.properties[name];\n        var prevProp = ele.pstyle(prop.name);\n\n        if (!prevProp || !prevProp.bypass) {\n          // if a bypass doesn't exist for the prop, nothing needs to be removed\n          continue;\n        }\n\n        var value = ''; // empty => remove bypass\n\n        var parsedProp = this.parse(name, value, true);\n        var diffProp = diffProps[prop.name] = {\n          prev: prevProp\n        };\n        this.applyParsedProperty(ele, parsedProp);\n        diffProp.next = ele.pstyle(prop.name);\n      } // for props\n\n\n      this.updateStyleHints(ele);\n\n      if (updateTransitions) {\n        this.updateTransitions(ele, diffProps, isBypass);\n      }\n    } // for eles\n\n  };\n\n  var styfn$6 = {}; // gets what an em size corresponds to in pixels relative to a dom element\n\n  styfn$6.getEmSizeInPixels = function () {\n    var px = this.containerCss('font-size');\n\n    if (px != null) {\n      return parseFloat(px);\n    } else {\n      return 1; // for headless\n    }\n  }; // gets css property from the core container\n\n\n  styfn$6.containerCss = function (propName) {\n    var cy = this._private.cy;\n    var domElement = cy.container();\n    var containerWindow = cy.window();\n\n    if (containerWindow && domElement && containerWindow.getComputedStyle) {\n      return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);\n    }\n  };\n\n  var styfn$5 = {}; // gets the rendered style for an element\n\n  styfn$5.getRenderedStyle = function (ele, prop) {\n    if (prop) {\n      return this.getStylePropertyValue(ele, prop, true);\n    } else {\n      return this.getRawStyle(ele, true);\n    }\n  }; // gets the raw style for an element\n\n\n  styfn$5.getRawStyle = function (ele, isRenderedVal) {\n    var self = this;\n    ele = ele[0]; // insure it's an element\n\n    if (ele) {\n      var rstyle = {};\n\n      for (var i = 0; i < self.properties.length; i++) {\n        var prop = self.properties[i];\n        var val = self.getStylePropertyValue(ele, prop.name, isRenderedVal);\n\n        if (val != null) {\n          rstyle[prop.name] = val;\n          rstyle[dash2camel(prop.name)] = val;\n        }\n      }\n\n      return rstyle;\n    }\n  };\n\n  styfn$5.getIndexedStyle = function (ele, property, subproperty, index) {\n    var pstyle = ele.pstyle(property)[subproperty][index];\n    return pstyle != null ? pstyle : ele.cy().style().getDefaultProperty(property)[subproperty][0];\n  };\n\n  styfn$5.getStylePropertyValue = function (ele, propName, isRenderedVal) {\n    var self = this;\n    ele = ele[0]; // insure it's an element\n\n    if (ele) {\n      var prop = self.properties[propName];\n\n      if (prop.alias) {\n        prop = prop.pointsTo;\n      }\n\n      var type = prop.type;\n      var styleProp = ele.pstyle(prop.name);\n\n      if (styleProp) {\n        var value = styleProp.value,\n            units = styleProp.units,\n            strValue = styleProp.strValue;\n\n        if (isRenderedVal && type.number && value != null && number$1(value)) {\n          var zoom = ele.cy().zoom();\n\n          var getRenderedValue = function getRenderedValue(val) {\n            return val * zoom;\n          };\n\n          var getValueStringWithUnits = function getValueStringWithUnits(val, units) {\n            return getRenderedValue(val) + units;\n          };\n\n          var isArrayValue = array(value);\n          var haveUnits = isArrayValue ? units.every(function (u) {\n            return u != null;\n          }) : units != null;\n\n          if (haveUnits) {\n            if (isArrayValue) {\n              return value.map(function (v, i) {\n                return getValueStringWithUnits(v, units[i]);\n              }).join(' ');\n            } else {\n              return getValueStringWithUnits(value, units);\n            }\n          } else {\n            if (isArrayValue) {\n              return value.map(function (v) {\n                return string(v) ? v : '' + getRenderedValue(v);\n              }).join(' ');\n            } else {\n              return '' + getRenderedValue(value);\n            }\n          }\n        } else if (strValue != null) {\n          return strValue;\n        }\n      }\n\n      return null;\n    }\n  };\n\n  styfn$5.getAnimationStartStyle = function (ele, aniProps) {\n    var rstyle = {};\n\n    for (var i = 0; i < aniProps.length; i++) {\n      var aniProp = aniProps[i];\n      var name = aniProp.name;\n      var styleProp = ele.pstyle(name);\n\n      if (styleProp !== undefined) {\n        // then make a prop of it\n        if (plainObject(styleProp)) {\n          styleProp = this.parse(name, styleProp.strValue);\n        } else {\n          styleProp = this.parse(name, styleProp);\n        }\n      }\n\n      if (styleProp) {\n        rstyle[name] = styleProp;\n      }\n    }\n\n    return rstyle;\n  };\n\n  styfn$5.getPropsList = function (propsObj) {\n    var self = this;\n    var rstyle = [];\n    var style = propsObj;\n    var props = self.properties;\n\n    if (style) {\n      var names = Object.keys(style);\n\n      for (var i = 0; i < names.length; i++) {\n        var name = names[i];\n        var val = style[name];\n        var prop = props[name] || props[camel2dash(name)];\n        var styleProp = this.parse(prop.name, val);\n\n        if (styleProp) {\n          rstyle.push(styleProp);\n        }\n      }\n    }\n\n    return rstyle;\n  };\n\n  styfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {\n    var hash = seed.slice();\n    var name, val, strVal, chVal;\n    var i, j;\n\n    for (i = 0; i < propNames.length; i++) {\n      name = propNames[i];\n      val = ele.pstyle(name, false);\n\n      if (val == null) {\n        continue;\n      } else if (val.pfValue != null) {\n        hash[0] = hashInt(chVal, hash[0]);\n        hash[1] = hashIntAlt(chVal, hash[1]);\n      } else {\n        strVal = val.strValue;\n\n        for (j = 0; j < strVal.length; j++) {\n          chVal = strVal.charCodeAt(j);\n          hash[0] = hashInt(chVal, hash[0]);\n          hash[1] = hashIntAlt(chVal, hash[1]);\n        }\n      }\n    }\n\n    return hash;\n  };\n\n  styfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;\n\n  var styfn$4 = {};\n\n  styfn$4.appendFromJson = function (json) {\n    var style = this;\n\n    for (var i = 0; i < json.length; i++) {\n      var context = json[i];\n      var selector = context.selector;\n      var props = context.style || context.css;\n      var names = Object.keys(props);\n      style.selector(selector); // apply selector\n\n      for (var j = 0; j < names.length; j++) {\n        var name = names[j];\n        var value = props[name];\n        style.css(name, value); // apply property\n      }\n    }\n\n    return style;\n  }; // accessible cy.style() function\n\n\n  styfn$4.fromJson = function (json) {\n    var style = this;\n    style.resetToDefault();\n    style.appendFromJson(json);\n    return style;\n  }; // get json from cy.style() api\n\n\n  styfn$4.json = function () {\n    var json = [];\n\n    for (var i = this.defaultLength; i < this.length; i++) {\n      var cxt = this[i];\n      var selector = cxt.selector;\n      var props = cxt.properties;\n      var css = {};\n\n      for (var j = 0; j < props.length; j++) {\n        var prop = props[j];\n        css[prop.name] = prop.strValue;\n      }\n\n      json.push({\n        selector: !selector ? 'core' : selector.toString(),\n        style: css\n      });\n    }\n\n    return json;\n  };\n\n  var styfn$3 = {};\n\n  styfn$3.appendFromString = function (string) {\n    var self = this;\n    var style = this;\n    var remaining = '' + string;\n    var selAndBlockStr;\n    var blockRem;\n    var propAndValStr; // remove comments from the style string\n\n    remaining = remaining.replace(/[/][*](\\s|.)+?[*][/]/g, '');\n\n    function removeSelAndBlockFromRemaining() {\n      // remove the parsed selector and block from the remaining text to parse\n      if (remaining.length > selAndBlockStr.length) {\n        remaining = remaining.substr(selAndBlockStr.length);\n      } else {\n        remaining = '';\n      }\n    }\n\n    function removePropAndValFromRem() {\n      // remove the parsed property and value from the remaining block text to parse\n      if (blockRem.length > propAndValStr.length) {\n        blockRem = blockRem.substr(propAndValStr.length);\n      } else {\n        blockRem = '';\n      }\n    }\n\n    for (;;) {\n      var nothingLeftToParse = remaining.match(/^\\s*$/);\n\n      if (nothingLeftToParse) {\n        break;\n      }\n\n      var selAndBlock = remaining.match(/^\\s*((?:.|\\s)+?)\\s*\\{((?:.|\\s)+?)\\}/);\n\n      if (!selAndBlock) {\n        warn('Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: ' + remaining);\n        break;\n      }\n\n      selAndBlockStr = selAndBlock[0]; // parse the selector\n\n      var selectorStr = selAndBlock[1];\n\n      if (selectorStr !== 'core') {\n        var selector = new Selector(selectorStr);\n\n        if (selector.invalid) {\n          warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr); // skip this selector and block\n\n          removeSelAndBlockFromRemaining();\n          continue;\n        }\n      } // parse the block of properties and values\n\n\n      var blockStr = selAndBlock[2];\n      var invalidBlock = false;\n      blockRem = blockStr;\n      var props = [];\n\n      for (;;) {\n        var _nothingLeftToParse = blockRem.match(/^\\s*$/);\n\n        if (_nothingLeftToParse) {\n          break;\n        }\n\n        var propAndVal = blockRem.match(/^\\s*(.+?)\\s*:\\s*(.+?)(?:\\s*;|\\s*$)/);\n\n        if (!propAndVal) {\n          warn('Skipping parsing of block: Invalid formatting of style property and value definitions found in:' + blockStr);\n          invalidBlock = true;\n          break;\n        }\n\n        propAndValStr = propAndVal[0];\n        var propStr = propAndVal[1];\n        var valStr = propAndVal[2];\n        var prop = self.properties[propStr];\n\n        if (!prop) {\n          warn('Skipping property: Invalid property name in: ' + propAndValStr); // skip this property in the block\n\n          removePropAndValFromRem();\n          continue;\n        }\n\n        var parsedProp = style.parse(propStr, valStr);\n\n        if (!parsedProp) {\n          warn('Skipping property: Invalid property definition in: ' + propAndValStr); // skip this property in the block\n\n          removePropAndValFromRem();\n          continue;\n        }\n\n        props.push({\n          name: propStr,\n          val: valStr\n        });\n        removePropAndValFromRem();\n      }\n\n      if (invalidBlock) {\n        removeSelAndBlockFromRemaining();\n        break;\n      } // put the parsed block in the style\n\n\n      style.selector(selectorStr);\n\n      for (var i = 0; i < props.length; i++) {\n        var _prop = props[i];\n        style.css(_prop.name, _prop.val);\n      }\n\n      removeSelAndBlockFromRemaining();\n    }\n\n    return style;\n  };\n\n  styfn$3.fromString = function (string) {\n    var style = this;\n    style.resetToDefault();\n    style.appendFromString(string);\n    return style;\n  };\n\n  var styfn$2 = {};\n\n  (function () {\n    var number$1 = number;\n    var rgba = rgbaNoBackRefs;\n    var hsla = hslaNoBackRefs;\n    var hex3$1 = hex3;\n    var hex6$1 = hex6;\n\n    var data = function data(prefix) {\n      return '^' + prefix + '\\\\s*\\\\(\\\\s*([\\\\w\\\\.]+)\\\\s*\\\\)$';\n    };\n\n    var mapData = function mapData(prefix) {\n      var mapArg = number$1 + '|\\\\w+|' + rgba + '|' + hsla + '|' + hex3$1 + '|' + hex6$1;\n      return '^' + prefix + '\\\\s*\\\\(([\\\\w\\\\.]+)\\\\s*\\\\,\\\\s*(' + number$1 + ')\\\\s*\\\\,\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + mapArg + ')\\\\s*\\\\,\\\\s*(' + mapArg + ')\\\\)$';\n    };\n\n    var urlRegexes = ['^url\\\\s*\\\\(\\\\s*[\\'\"]?(.+?)[\\'\"]?\\\\s*\\\\)$', '^(none)$', '^(.+)$']; // each visual style property has a type and needs to be validated according to it\n\n    styfn$2.types = {\n      time: {\n        number: true,\n        min: 0,\n        units: 's|ms',\n        implicitUnits: 'ms'\n      },\n      percent: {\n        number: true,\n        min: 0,\n        max: 100,\n        units: '%',\n        implicitUnits: '%'\n      },\n      percentages: {\n        number: true,\n        min: 0,\n        max: 100,\n        units: '%',\n        implicitUnits: '%',\n        multiple: true\n      },\n      zeroOneNumber: {\n        number: true,\n        min: 0,\n        max: 1,\n        unitless: true\n      },\n      zeroOneNumbers: {\n        number: true,\n        min: 0,\n        max: 1,\n        unitless: true,\n        multiple: true\n      },\n      nOneOneNumber: {\n        number: true,\n        min: -1,\n        max: 1,\n        unitless: true\n      },\n      nonNegativeInt: {\n        number: true,\n        min: 0,\n        integer: true,\n        unitless: true\n      },\n      position: {\n        enums: ['parent', 'origin']\n      },\n      nodeSize: {\n        number: true,\n        min: 0,\n        enums: ['label']\n      },\n      number: {\n        number: true,\n        unitless: true\n      },\n      numbers: {\n        number: true,\n        unitless: true,\n        multiple: true\n      },\n      positiveNumber: {\n        number: true,\n        unitless: true,\n        min: 0,\n        strictMin: true\n      },\n      size: {\n        number: true,\n        min: 0\n      },\n      bidirectionalSize: {\n        number: true\n      },\n      // allows negative\n      bidirectionalSizeMaybePercent: {\n        number: true,\n        allowPercent: true\n      },\n      // allows negative\n      bidirectionalSizes: {\n        number: true,\n        multiple: true\n      },\n      // allows negative\n      sizeMaybePercent: {\n        number: true,\n        min: 0,\n        allowPercent: true\n      },\n      axisDirection: {\n        enums: ['horizontal', 'leftward', 'rightward', 'vertical', 'upward', 'downward', 'auto']\n      },\n      paddingRelativeTo: {\n        enums: ['width', 'height', 'average', 'min', 'max']\n      },\n      bgWH: {\n        number: true,\n        min: 0,\n        allowPercent: true,\n        enums: ['auto'],\n        multiple: true\n      },\n      bgPos: {\n        number: true,\n        allowPercent: true,\n        multiple: true\n      },\n      bgRelativeTo: {\n        enums: ['inner', 'include-padding'],\n        multiple: true\n      },\n      bgRepeat: {\n        enums: ['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],\n        multiple: true\n      },\n      bgFit: {\n        enums: ['none', 'contain', 'cover'],\n        multiple: true\n      },\n      bgCrossOrigin: {\n        enums: ['anonymous', 'use-credentials', 'null'],\n        multiple: true\n      },\n      bgClip: {\n        enums: ['none', 'node'],\n        multiple: true\n      },\n      bgContainment: {\n        enums: ['inside', 'over'],\n        multiple: true\n      },\n      color: {\n        color: true\n      },\n      colors: {\n        color: true,\n        multiple: true\n      },\n      fill: {\n        enums: ['solid', 'linear-gradient', 'radial-gradient']\n      },\n      bool: {\n        enums: ['yes', 'no']\n      },\n      bools: {\n        enums: ['yes', 'no'],\n        multiple: true\n      },\n      lineStyle: {\n        enums: ['solid', 'dotted', 'dashed']\n      },\n      lineCap: {\n        enums: ['butt', 'round', 'square']\n      },\n      borderStyle: {\n        enums: ['solid', 'dotted', 'dashed', 'double']\n      },\n      curveStyle: {\n        enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi']\n      },\n      fontFamily: {\n        regex: '^([\\\\w- \\\\\"]+(?:\\\\s*,\\\\s*[\\\\w- \\\\\"]+)*)$'\n      },\n      fontStyle: {\n        enums: ['italic', 'normal', 'oblique']\n      },\n      fontWeight: {\n        enums: ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '800', '900', 100, 200, 300, 400, 500, 600, 700, 800, 900]\n      },\n      textDecoration: {\n        enums: ['none', 'underline', 'overline', 'line-through']\n      },\n      textTransform: {\n        enums: ['none', 'uppercase', 'lowercase']\n      },\n      textWrap: {\n        enums: ['none', 'wrap', 'ellipsis']\n      },\n      textOverflowWrap: {\n        enums: ['whitespace', 'anywhere']\n      },\n      textBackgroundShape: {\n        enums: ['rectangle', 'roundrectangle', 'round-rectangle']\n      },\n      nodeShape: {\n        enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'cutrectangle', 'cut-rectangle', 'bottomroundrectangle', 'bottom-round-rectangle', 'barrel', 'ellipse', 'triangle', 'round-triangle', 'square', 'pentagon', 'round-pentagon', 'hexagon', 'round-hexagon', 'concavehexagon', 'concave-hexagon', 'heptagon', 'round-heptagon', 'octagon', 'round-octagon', 'tag', 'round-tag', 'star', 'diamond', 'round-diamond', 'vee', 'rhomboid', 'right-rhomboid', 'polygon']\n      },\n      overlayShape: {\n        enums: ['roundrectangle', 'round-rectangle', 'ellipse']\n      },\n      compoundIncludeLabels: {\n        enums: ['include', 'exclude']\n      },\n      arrowShape: {\n        enums: ['tee', 'triangle', 'triangle-tee', 'circle-triangle', 'triangle-cross', 'triangle-backcurve', 'vee', 'square', 'circle', 'diamond', 'chevron', 'none']\n      },\n      arrowFill: {\n        enums: ['filled', 'hollow']\n      },\n      display: {\n        enums: ['element', 'none']\n      },\n      visibility: {\n        enums: ['hidden', 'visible']\n      },\n      zCompoundDepth: {\n        enums: ['bottom', 'orphan', 'auto', 'top']\n      },\n      zIndexCompare: {\n        enums: ['auto', 'manual']\n      },\n      valign: {\n        enums: ['top', 'center', 'bottom']\n      },\n      halign: {\n        enums: ['left', 'center', 'right']\n      },\n      justification: {\n        enums: ['left', 'center', 'right', 'auto']\n      },\n      text: {\n        string: true\n      },\n      data: {\n        mapping: true,\n        regex: data('data')\n      },\n      layoutData: {\n        mapping: true,\n        regex: data('layoutData')\n      },\n      scratch: {\n        mapping: true,\n        regex: data('scratch')\n      },\n      mapData: {\n        mapping: true,\n        regex: mapData('mapData')\n      },\n      mapLayoutData: {\n        mapping: true,\n        regex: mapData('mapLayoutData')\n      },\n      mapScratch: {\n        mapping: true,\n        regex: mapData('mapScratch')\n      },\n      fn: {\n        mapping: true,\n        fn: true\n      },\n      url: {\n        regexes: urlRegexes,\n        singleRegexMatchValue: true\n      },\n      urls: {\n        regexes: urlRegexes,\n        singleRegexMatchValue: true,\n        multiple: true\n      },\n      propList: {\n        propList: true\n      },\n      angle: {\n        number: true,\n        units: 'deg|rad',\n        implicitUnits: 'rad'\n      },\n      textRotation: {\n        number: true,\n        units: 'deg|rad',\n        implicitUnits: 'rad',\n        enums: ['none', 'autorotate']\n      },\n      polygonPointList: {\n        number: true,\n        multiple: true,\n        evenMultiple: true,\n        min: -1,\n        max: 1,\n        unitless: true\n      },\n      edgeDistances: {\n        enums: ['intersection', 'node-position']\n      },\n      edgeEndpoint: {\n        number: true,\n        multiple: true,\n        units: '%|px|em|deg|rad',\n        implicitUnits: 'px',\n        enums: ['inside-to-node', 'outside-to-node', 'outside-to-node-or-label', 'outside-to-line', 'outside-to-line-or-label'],\n        singleEnum: true,\n        validate: function validate(valArr, unitsArr) {\n          switch (valArr.length) {\n            case 2:\n              // can be % or px only\n              return unitsArr[0] !== 'deg' && unitsArr[0] !== 'rad' && unitsArr[1] !== 'deg' && unitsArr[1] !== 'rad';\n\n            case 1:\n              // can be enum, deg, or rad only\n              return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';\n\n            default:\n              return false;\n          }\n        }\n      },\n      easing: {\n        regexes: ['^(spring)\\\\s*\\\\(\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*\\\\)$', '^(cubic-bezier)\\\\s*\\\\(\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*,\\\\s*(' + number$1 + ')\\\\s*\\\\)$'],\n        enums: ['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'ease-in-sine', 'ease-out-sine', 'ease-in-out-sine', 'ease-in-quad', 'ease-out-quad', 'ease-in-out-quad', 'ease-in-cubic', 'ease-out-cubic', 'ease-in-out-cubic', 'ease-in-quart', 'ease-out-quart', 'ease-in-out-quart', 'ease-in-quint', 'ease-out-quint', 'ease-in-out-quint', 'ease-in-expo', 'ease-out-expo', 'ease-in-out-expo', 'ease-in-circ', 'ease-out-circ', 'ease-in-out-circ']\n      },\n      gradientDirection: {\n        enums: ['to-bottom', 'to-top', 'to-left', 'to-right', 'to-bottom-right', 'to-bottom-left', 'to-top-right', 'to-top-left', 'to-right-bottom', 'to-left-bottom', 'to-right-top', 'to-left-top' // different order\n        ]\n      },\n      boundsExpansion: {\n        number: true,\n        multiple: true,\n        min: 0,\n        validate: function validate(valArr) {\n          var length = valArr.length;\n          return length === 1 || length === 2 || length === 4;\n        }\n      }\n    };\n    var diff = {\n      zeroNonZero: function zeroNonZero(val1, val2) {\n        if ((val1 == null || val2 == null) && val1 !== val2) {\n          return true; // null cases could represent any value\n        }\n\n        if (val1 == 0 && val2 != 0) {\n          return true;\n        } else if (val1 != 0 && val2 == 0) {\n          return true;\n        } else {\n          return false;\n        }\n      },\n      any: function any(val1, val2) {\n        return val1 != val2;\n      },\n      emptyNonEmpty: function emptyNonEmpty(str1, str2) {\n        var empty1 = emptyString(str1);\n        var empty2 = emptyString(str2);\n        return empty1 && !empty2 || !empty1 && empty2;\n      }\n    }; // define visual style properties\n    //\n    // - n.b. adding a new group of props may require updates to updateStyleHints()\n    // - adding new props to an existing group gets handled automatically\n\n    var t = styfn$2.types;\n    var mainLabel = [{\n      name: 'label',\n      type: t.text,\n      triggersBounds: diff.any,\n      triggersZOrder: diff.emptyNonEmpty\n    }, {\n      name: 'text-rotation',\n      type: t.textRotation,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-margin-x',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-margin-y',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }];\n    var sourceLabel = [{\n      name: 'source-label',\n      type: t.text,\n      triggersBounds: diff.any\n    }, {\n      name: 'source-text-rotation',\n      type: t.textRotation,\n      triggersBounds: diff.any\n    }, {\n      name: 'source-text-margin-x',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'source-text-margin-y',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'source-text-offset',\n      type: t.size,\n      triggersBounds: diff.any\n    }];\n    var targetLabel = [{\n      name: 'target-label',\n      type: t.text,\n      triggersBounds: diff.any\n    }, {\n      name: 'target-text-rotation',\n      type: t.textRotation,\n      triggersBounds: diff.any\n    }, {\n      name: 'target-text-margin-x',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'target-text-margin-y',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'target-text-offset',\n      type: t.size,\n      triggersBounds: diff.any\n    }];\n    var labelDimensions = [{\n      name: 'font-family',\n      type: t.fontFamily,\n      triggersBounds: diff.any\n    }, {\n      name: 'font-style',\n      type: t.fontStyle,\n      triggersBounds: diff.any\n    }, {\n      name: 'font-weight',\n      type: t.fontWeight,\n      triggersBounds: diff.any\n    }, {\n      name: 'font-size',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-transform',\n      type: t.textTransform,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-wrap',\n      type: t.textWrap,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-overflow-wrap',\n      type: t.textOverflowWrap,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-max-width',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-outline-width',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'line-height',\n      type: t.positiveNumber,\n      triggersBounds: diff.any\n    }];\n    var commonLabel = [{\n      name: 'text-valign',\n      type: t.valign,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-halign',\n      type: t.halign,\n      triggersBounds: diff.any\n    }, {\n      name: 'color',\n      type: t.color\n    }, {\n      name: 'text-outline-color',\n      type: t.color\n    }, {\n      name: 'text-outline-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'text-background-color',\n      type: t.color\n    }, {\n      name: 'text-background-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'text-background-padding',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-border-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'text-border-color',\n      type: t.color\n    }, {\n      name: 'text-border-width',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-border-style',\n      type: t.borderStyle,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-background-shape',\n      type: t.textBackgroundShape,\n      triggersBounds: diff.any\n    }, {\n      name: 'text-justification',\n      type: t.justification\n    }];\n    var behavior = [{\n      name: 'events',\n      type: t.bool\n    }, {\n      name: 'text-events',\n      type: t.bool\n    }];\n    var visibility = [{\n      name: 'display',\n      type: t.display,\n      triggersZOrder: diff.any,\n      triggersBounds: diff.any,\n      triggersBoundsOfParallelBeziers: true\n    }, {\n      name: 'visibility',\n      type: t.visibility,\n      triggersZOrder: diff.any\n    }, {\n      name: 'opacity',\n      type: t.zeroOneNumber,\n      triggersZOrder: diff.zeroNonZero\n    }, {\n      name: 'text-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'min-zoomed-font-size',\n      type: t.size\n    }, {\n      name: 'z-compound-depth',\n      type: t.zCompoundDepth,\n      triggersZOrder: diff.any\n    }, {\n      name: 'z-index-compare',\n      type: t.zIndexCompare,\n      triggersZOrder: diff.any\n    }, {\n      name: 'z-index',\n      type: t.nonNegativeInt,\n      triggersZOrder: diff.any\n    }];\n    var overlay = [{\n      name: 'overlay-padding',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'overlay-color',\n      type: t.color\n    }, {\n      name: 'overlay-opacity',\n      type: t.zeroOneNumber,\n      triggersBounds: diff.zeroNonZero\n    }, {\n      name: 'overlay-shape',\n      type: t.overlayShape,\n      triggersBounds: diff.any\n    }];\n    var underlay = [{\n      name: 'underlay-padding',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'underlay-color',\n      type: t.color\n    }, {\n      name: 'underlay-opacity',\n      type: t.zeroOneNumber,\n      triggersBounds: diff.zeroNonZero\n    }, {\n      name: 'underlay-shape',\n      type: t.overlayShape,\n      triggersBounds: diff.any\n    }];\n    var transition = [{\n      name: 'transition-property',\n      type: t.propList\n    }, {\n      name: 'transition-duration',\n      type: t.time\n    }, {\n      name: 'transition-delay',\n      type: t.time\n    }, {\n      name: 'transition-timing-function',\n      type: t.easing\n    }];\n\n    var nodeSizeHashOverride = function nodeSizeHashOverride(ele, parsedProp) {\n      if (parsedProp.value === 'label') {\n        return -ele.poolIndex(); // no hash key hits is using label size (hitrate for perf probably low anyway)\n      } else {\n        return parsedProp.pfValue;\n      }\n    };\n\n    var nodeBody = [{\n      name: 'height',\n      type: t.nodeSize,\n      triggersBounds: diff.any,\n      hashOverride: nodeSizeHashOverride\n    }, {\n      name: 'width',\n      type: t.nodeSize,\n      triggersBounds: diff.any,\n      hashOverride: nodeSizeHashOverride\n    }, {\n      name: 'shape',\n      type: t.nodeShape,\n      triggersBounds: diff.any\n    }, {\n      name: 'shape-polygon-points',\n      type: t.polygonPointList,\n      triggersBounds: diff.any\n    }, {\n      name: 'background-color',\n      type: t.color\n    }, {\n      name: 'background-fill',\n      type: t.fill\n    }, {\n      name: 'background-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'background-blacken',\n      type: t.nOneOneNumber\n    }, {\n      name: 'background-gradient-stop-colors',\n      type: t.colors\n    }, {\n      name: 'background-gradient-stop-positions',\n      type: t.percentages\n    }, {\n      name: 'background-gradient-direction',\n      type: t.gradientDirection\n    }, {\n      name: 'padding',\n      type: t.sizeMaybePercent,\n      triggersBounds: diff.any\n    }, {\n      name: 'padding-relative-to',\n      type: t.paddingRelativeTo,\n      triggersBounds: diff.any\n    }, {\n      name: 'bounds-expansion',\n      type: t.boundsExpansion,\n      triggersBounds: diff.any\n    }];\n    var nodeBorder = [{\n      name: 'border-color',\n      type: t.color\n    }, {\n      name: 'border-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'border-width',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'border-style',\n      type: t.borderStyle\n    }];\n    var backgroundImage = [{\n      name: 'background-image',\n      type: t.urls\n    }, {\n      name: 'background-image-crossorigin',\n      type: t.bgCrossOrigin\n    }, {\n      name: 'background-image-opacity',\n      type: t.zeroOneNumbers\n    }, {\n      name: 'background-image-containment',\n      type: t.bgContainment\n    }, {\n      name: 'background-image-smoothing',\n      type: t.bools\n    }, {\n      name: 'background-position-x',\n      type: t.bgPos\n    }, {\n      name: 'background-position-y',\n      type: t.bgPos\n    }, {\n      name: 'background-width-relative-to',\n      type: t.bgRelativeTo\n    }, {\n      name: 'background-height-relative-to',\n      type: t.bgRelativeTo\n    }, {\n      name: 'background-repeat',\n      type: t.bgRepeat\n    }, {\n      name: 'background-fit',\n      type: t.bgFit\n    }, {\n      name: 'background-clip',\n      type: t.bgClip\n    }, {\n      name: 'background-width',\n      type: t.bgWH\n    }, {\n      name: 'background-height',\n      type: t.bgWH\n    }, {\n      name: 'background-offset-x',\n      type: t.bgPos\n    }, {\n      name: 'background-offset-y',\n      type: t.bgPos\n    }];\n    var compound = [{\n      name: 'position',\n      type: t.position,\n      triggersBounds: diff.any\n    }, {\n      name: 'compound-sizing-wrt-labels',\n      type: t.compoundIncludeLabels,\n      triggersBounds: diff.any\n    }, {\n      name: 'min-width',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'min-width-bias-left',\n      type: t.sizeMaybePercent,\n      triggersBounds: diff.any\n    }, {\n      name: 'min-width-bias-right',\n      type: t.sizeMaybePercent,\n      triggersBounds: diff.any\n    }, {\n      name: 'min-height',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'min-height-bias-top',\n      type: t.sizeMaybePercent,\n      triggersBounds: diff.any\n    }, {\n      name: 'min-height-bias-bottom',\n      type: t.sizeMaybePercent,\n      triggersBounds: diff.any\n    }];\n    var edgeLine = [{\n      name: 'line-style',\n      type: t.lineStyle\n    }, {\n      name: 'line-color',\n      type: t.color\n    }, {\n      name: 'line-fill',\n      type: t.fill\n    }, {\n      name: 'line-cap',\n      type: t.lineCap\n    }, {\n      name: 'line-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'line-dash-pattern',\n      type: t.numbers\n    }, {\n      name: 'line-dash-offset',\n      type: t.number\n    }, {\n      name: 'line-gradient-stop-colors',\n      type: t.colors\n    }, {\n      name: 'line-gradient-stop-positions',\n      type: t.percentages\n    }, {\n      name: 'curve-style',\n      type: t.curveStyle,\n      triggersBounds: diff.any,\n      triggersBoundsOfParallelBeziers: true\n    }, {\n      name: 'haystack-radius',\n      type: t.zeroOneNumber,\n      triggersBounds: diff.any\n    }, {\n      name: 'source-endpoint',\n      type: t.edgeEndpoint,\n      triggersBounds: diff.any\n    }, {\n      name: 'target-endpoint',\n      type: t.edgeEndpoint,\n      triggersBounds: diff.any\n    }, {\n      name: 'control-point-step-size',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'control-point-distances',\n      type: t.bidirectionalSizes,\n      triggersBounds: diff.any\n    }, {\n      name: 'control-point-weights',\n      type: t.numbers,\n      triggersBounds: diff.any\n    }, {\n      name: 'segment-distances',\n      type: t.bidirectionalSizes,\n      triggersBounds: diff.any\n    }, {\n      name: 'segment-weights',\n      type: t.numbers,\n      triggersBounds: diff.any\n    }, {\n      name: 'taxi-turn',\n      type: t.bidirectionalSizeMaybePercent,\n      triggersBounds: diff.any\n    }, {\n      name: 'taxi-turn-min-distance',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'taxi-direction',\n      type: t.axisDirection,\n      triggersBounds: diff.any\n    }, {\n      name: 'edge-distances',\n      type: t.edgeDistances,\n      triggersBounds: diff.any\n    }, {\n      name: 'arrow-scale',\n      type: t.positiveNumber,\n      triggersBounds: diff.any\n    }, {\n      name: 'loop-direction',\n      type: t.angle,\n      triggersBounds: diff.any\n    }, {\n      name: 'loop-sweep',\n      type: t.angle,\n      triggersBounds: diff.any\n    }, {\n      name: 'source-distance-from-node',\n      type: t.size,\n      triggersBounds: diff.any\n    }, {\n      name: 'target-distance-from-node',\n      type: t.size,\n      triggersBounds: diff.any\n    }];\n    var ghost = [{\n      name: 'ghost',\n      type: t.bool,\n      triggersBounds: diff.any\n    }, {\n      name: 'ghost-offset-x',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'ghost-offset-y',\n      type: t.bidirectionalSize,\n      triggersBounds: diff.any\n    }, {\n      name: 'ghost-opacity',\n      type: t.zeroOneNumber\n    }];\n    var core = [{\n      name: 'selection-box-color',\n      type: t.color\n    }, {\n      name: 'selection-box-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'selection-box-border-color',\n      type: t.color\n    }, {\n      name: 'selection-box-border-width',\n      type: t.size\n    }, {\n      name: 'active-bg-color',\n      type: t.color\n    }, {\n      name: 'active-bg-opacity',\n      type: t.zeroOneNumber\n    }, {\n      name: 'active-bg-size',\n      type: t.size\n    }, {\n      name: 'outside-texture-bg-color',\n      type: t.color\n    }, {\n      name: 'outside-texture-bg-opacity',\n      type: t.zeroOneNumber\n    }]; // pie backgrounds for nodes\n\n    var pie = [];\n    styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)\n\n    pie.push({\n      name: 'pie-size',\n      type: t.sizeMaybePercent\n    });\n\n    for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {\n      pie.push({\n        name: 'pie-' + i + '-background-color',\n        type: t.color\n      });\n      pie.push({\n        name: 'pie-' + i + '-background-size',\n        type: t.percent\n      });\n      pie.push({\n        name: 'pie-' + i + '-background-opacity',\n        type: t.zeroOneNumber\n      });\n    } // edge arrows\n\n\n    var edgeArrow = [];\n    var arrowPrefixes = styfn$2.arrowPrefixes = ['source', 'mid-source', 'target', 'mid-target'];\n    [{\n      name: 'arrow-shape',\n      type: t.arrowShape,\n      triggersBounds: diff.any\n    }, {\n      name: 'arrow-color',\n      type: t.color\n    }, {\n      name: 'arrow-fill',\n      type: t.arrowFill\n    }].forEach(function (prop) {\n      arrowPrefixes.forEach(function (prefix) {\n        var name = prefix + '-' + prop.name;\n        var type = prop.type,\n            triggersBounds = prop.triggersBounds;\n        edgeArrow.push({\n          name: name,\n          type: type,\n          triggersBounds: triggersBounds\n        });\n      });\n    }, {});\n    var props = styfn$2.properties = [].concat(behavior, transition, visibility, overlay, underlay, ghost, commonLabel, labelDimensions, mainLabel, sourceLabel, targetLabel, nodeBody, nodeBorder, backgroundImage, pie, compound, edgeLine, edgeArrow, core);\n    var propGroups = styfn$2.propertyGroups = {\n      // common to all eles\n      behavior: behavior,\n      transition: transition,\n      visibility: visibility,\n      overlay: overlay,\n      underlay: underlay,\n      ghost: ghost,\n      // labels\n      commonLabel: commonLabel,\n      labelDimensions: labelDimensions,\n      mainLabel: mainLabel,\n      sourceLabel: sourceLabel,\n      targetLabel: targetLabel,\n      // node props\n      nodeBody: nodeBody,\n      nodeBorder: nodeBorder,\n      backgroundImage: backgroundImage,\n      pie: pie,\n      compound: compound,\n      // edge props\n      edgeLine: edgeLine,\n      edgeArrow: edgeArrow,\n      core: core\n    };\n    var propGroupNames = styfn$2.propertyGroupNames = {};\n    var propGroupKeys = styfn$2.propertyGroupKeys = Object.keys(propGroups);\n    propGroupKeys.forEach(function (key) {\n      propGroupNames[key] = propGroups[key].map(function (prop) {\n        return prop.name;\n      });\n      propGroups[key].forEach(function (prop) {\n        return prop.groupKey = key;\n      });\n    }); // define aliases\n\n    var aliases = styfn$2.aliases = [{\n      name: 'content',\n      pointsTo: 'label'\n    }, {\n      name: 'control-point-distance',\n      pointsTo: 'control-point-distances'\n    }, {\n      name: 'control-point-weight',\n      pointsTo: 'control-point-weights'\n    }, {\n      name: 'edge-text-rotation',\n      pointsTo: 'text-rotation'\n    }, {\n      name: 'padding-left',\n      pointsTo: 'padding'\n    }, {\n      name: 'padding-right',\n      pointsTo: 'padding'\n    }, {\n      name: 'padding-top',\n      pointsTo: 'padding'\n    }, {\n      name: 'padding-bottom',\n      pointsTo: 'padding'\n    }]; // list of property names\n\n    styfn$2.propertyNames = props.map(function (p) {\n      return p.name;\n    }); // allow access of properties by name ( e.g. style.properties.height )\n\n    for (var _i = 0; _i < props.length; _i++) {\n      var prop = props[_i];\n      props[prop.name] = prop; // allow lookup by name\n    } // map aliases\n\n\n    for (var _i2 = 0; _i2 < aliases.length; _i2++) {\n      var alias = aliases[_i2];\n      var pointsToProp = props[alias.pointsTo];\n      var aliasProp = {\n        name: alias.name,\n        alias: true,\n        pointsTo: pointsToProp\n      }; // add alias prop for parsing\n\n      props.push(aliasProp);\n      props[alias.name] = aliasProp; // allow lookup by name\n    }\n  })();\n\n  styfn$2.getDefaultProperty = function (name) {\n    return this.getDefaultProperties()[name];\n  };\n\n  styfn$2.getDefaultProperties = function () {\n    var _p = this._private;\n\n    if (_p.defaultProperties != null) {\n      return _p.defaultProperties;\n    }\n\n    var rawProps = extend({\n      // core props\n      'selection-box-color': '#ddd',\n      'selection-box-opacity': 0.65,\n      'selection-box-border-color': '#aaa',\n      'selection-box-border-width': 1,\n      'active-bg-color': 'black',\n      'active-bg-opacity': 0.15,\n      'active-bg-size': 30,\n      'outside-texture-bg-color': '#000',\n      'outside-texture-bg-opacity': 0.125,\n      // common node/edge props\n      'events': 'yes',\n      'text-events': 'no',\n      'text-valign': 'top',\n      'text-halign': 'center',\n      'text-justification': 'auto',\n      'line-height': 1,\n      'color': '#000',\n      'text-outline-color': '#000',\n      'text-outline-width': 0,\n      'text-outline-opacity': 1,\n      'text-opacity': 1,\n      'text-decoration': 'none',\n      'text-transform': 'none',\n      'text-wrap': 'none',\n      'text-overflow-wrap': 'whitespace',\n      'text-max-width': 9999,\n      'text-background-color': '#000',\n      'text-background-opacity': 0,\n      'text-background-shape': 'rectangle',\n      'text-background-padding': 0,\n      'text-border-opacity': 0,\n      'text-border-width': 0,\n      'text-border-style': 'solid',\n      'text-border-color': '#000',\n      'font-family': 'Helvetica Neue, Helvetica, sans-serif',\n      'font-style': 'normal',\n      'font-weight': 'normal',\n      'font-size': 16,\n      'min-zoomed-font-size': 0,\n      'text-rotation': 'none',\n      'source-text-rotation': 'none',\n      'target-text-rotation': 'none',\n      'visibility': 'visible',\n      'display': 'element',\n      'opacity': 1,\n      'z-compound-depth': 'auto',\n      'z-index-compare': 'auto',\n      'z-index': 0,\n      'label': '',\n      'text-margin-x': 0,\n      'text-margin-y': 0,\n      'source-label': '',\n      'source-text-offset': 0,\n      'source-text-margin-x': 0,\n      'source-text-margin-y': 0,\n      'target-label': '',\n      'target-text-offset': 0,\n      'target-text-margin-x': 0,\n      'target-text-margin-y': 0,\n      'overlay-opacity': 0,\n      'overlay-color': '#000',\n      'overlay-padding': 10,\n      'overlay-shape': 'round-rectangle',\n      'underlay-opacity': 0,\n      'underlay-color': '#000',\n      'underlay-padding': 10,\n      'underlay-shape': 'round-rectangle',\n      'transition-property': 'none',\n      'transition-duration': 0,\n      'transition-delay': 0,\n      'transition-timing-function': 'linear',\n      // node props\n      'background-blacken': 0,\n      'background-color': '#999',\n      'background-fill': 'solid',\n      'background-opacity': 1,\n      'background-image': 'none',\n      'background-image-crossorigin': 'anonymous',\n      'background-image-opacity': 1,\n      'background-image-containment': 'inside',\n      'background-image-smoothing': 'yes',\n      'background-position-x': '50%',\n      'background-position-y': '50%',\n      'background-offset-x': 0,\n      'background-offset-y': 0,\n      'background-width-relative-to': 'include-padding',\n      'background-height-relative-to': 'include-padding',\n      'background-repeat': 'no-repeat',\n      'background-fit': 'none',\n      'background-clip': 'node',\n      'background-width': 'auto',\n      'background-height': 'auto',\n      'border-color': '#000',\n      'border-opacity': 1,\n      'border-width': 0,\n      'border-style': 'solid',\n      'height': 30,\n      'width': 30,\n      'shape': 'ellipse',\n      'shape-polygon-points': '-1, -1,   1, -1,   1, 1,   -1, 1',\n      'bounds-expansion': 0,\n      // node gradient\n      'background-gradient-direction': 'to-bottom',\n      'background-gradient-stop-colors': '#999',\n      'background-gradient-stop-positions': '0%',\n      // ghost props\n      'ghost': 'no',\n      'ghost-offset-y': 0,\n      'ghost-offset-x': 0,\n      'ghost-opacity': 0,\n      // compound props\n      'padding': 0,\n      'padding-relative-to': 'width',\n      'position': 'origin',\n      'compound-sizing-wrt-labels': 'include',\n      'min-width': 0,\n      'min-width-bias-left': 0,\n      'min-width-bias-right': 0,\n      'min-height': 0,\n      'min-height-bias-top': 0,\n      'min-height-bias-bottom': 0\n    }, {\n      // node pie bg\n      'pie-size': '100%'\n    }, [{\n      name: 'pie-{{i}}-background-color',\n      value: 'black'\n    }, {\n      name: 'pie-{{i}}-background-size',\n      value: '0%'\n    }, {\n      name: 'pie-{{i}}-background-opacity',\n      value: 1\n    }].reduce(function (css, prop) {\n      for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {\n        var name = prop.name.replace('{{i}}', i);\n        var val = prop.value;\n        css[name] = val;\n      }\n\n      return css;\n    }, {}), {\n      // edge props\n      'line-style': 'solid',\n      'line-color': '#999',\n      'line-fill': 'solid',\n      'line-cap': 'butt',\n      'line-opacity': 1,\n      'line-gradient-stop-colors': '#999',\n      'line-gradient-stop-positions': '0%',\n      'control-point-step-size': 40,\n      'control-point-weights': 0.5,\n      'segment-weights': 0.5,\n      'segment-distances': 20,\n      'taxi-turn': '50%',\n      'taxi-turn-min-distance': 10,\n      'taxi-direction': 'auto',\n      'edge-distances': 'intersection',\n      'curve-style': 'haystack',\n      'haystack-radius': 0,\n      'arrow-scale': 1,\n      'loop-direction': '-45deg',\n      'loop-sweep': '-90deg',\n      'source-distance-from-node': 0,\n      'target-distance-from-node': 0,\n      'source-endpoint': 'outside-to-node',\n      'target-endpoint': 'outside-to-node',\n      'line-dash-pattern': [6, 3],\n      'line-dash-offset': 0\n    }, [{\n      name: 'arrow-shape',\n      value: 'none'\n    }, {\n      name: 'arrow-color',\n      value: '#999'\n    }, {\n      name: 'arrow-fill',\n      value: 'filled'\n    }].reduce(function (css, prop) {\n      styfn$2.arrowPrefixes.forEach(function (prefix) {\n        var name = prefix + '-' + prop.name;\n        var val = prop.value;\n        css[name] = val;\n      });\n      return css;\n    }, {}));\n    var parsedProps = {};\n\n    for (var i = 0; i < this.properties.length; i++) {\n      var prop = this.properties[i];\n\n      if (prop.pointsTo) {\n        continue;\n      }\n\n      var name = prop.name;\n      var val = rawProps[name];\n      var parsedProp = this.parse(name, val);\n      parsedProps[name] = parsedProp;\n    }\n\n    _p.defaultProperties = parsedProps;\n    return _p.defaultProperties;\n  };\n\n  styfn$2.addDefaultStylesheet = function () {\n    this.selector(':parent').css({\n      'shape': 'rectangle',\n      'padding': 10,\n      'background-color': '#eee',\n      'border-color': '#ccc',\n      'border-width': 1\n    }).selector('edge').css({\n      'width': 3\n    }).selector(':loop').css({\n      'curve-style': 'bezier'\n    }).selector('edge:compound').css({\n      'curve-style': 'bezier',\n      'source-endpoint': 'outside-to-line',\n      'target-endpoint': 'outside-to-line'\n    }).selector(':selected').css({\n      'background-color': '#0169D9',\n      'line-color': '#0169D9',\n      'source-arrow-color': '#0169D9',\n      'target-arrow-color': '#0169D9',\n      'mid-source-arrow-color': '#0169D9',\n      'mid-target-arrow-color': '#0169D9'\n    }).selector(':parent:selected').css({\n      'background-color': '#CCE1F9',\n      'border-color': '#aec8e5'\n    }).selector(':active').css({\n      'overlay-color': 'black',\n      'overlay-padding': 10,\n      'overlay-opacity': 0.25\n    });\n    this.defaultLength = this.length;\n  };\n\n  var styfn$1 = {}; // a caching layer for property parsing\n\n  styfn$1.parse = function (name, value, propIsBypass, propIsFlat) {\n    var self = this; // function values can't be cached in all cases, and there isn't much benefit of caching them anyway\n\n    if (fn$6(value)) {\n      return self.parseImplWarn(name, value, propIsBypass, propIsFlat);\n    }\n\n    var flatKey = propIsFlat === 'mapping' || propIsFlat === true || propIsFlat === false || propIsFlat == null ? 'dontcare' : propIsFlat;\n    var bypassKey = propIsBypass ? 't' : 'f';\n    var valueKey = '' + value;\n    var argHash = hashStrings(name, valueKey, bypassKey, flatKey);\n    var propCache = self.propCache = self.propCache || [];\n    var ret;\n\n    if (!(ret = propCache[argHash])) {\n      ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);\n    } // - bypasses can't be shared b/c the value can be changed by animations or otherwise overridden\n    // - mappings can't be shared b/c mappings are per-element\n\n\n    if (propIsBypass || propIsFlat === 'mapping') {\n      // need a copy since props are mutated later in their lifecycles\n      ret = copy(ret);\n\n      if (ret) {\n        ret.value = copy(ret.value); // because it could be an array, e.g. colour\n      }\n    }\n\n    return ret;\n  };\n\n  styfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {\n    var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);\n\n    if (!prop && value != null) {\n      warn(\"The style property `\".concat(name, \": \").concat(value, \"` is invalid\"));\n    }\n\n    if (prop && (prop.name === 'width' || prop.name === 'height') && value === 'label') {\n      warn('The style value of `label` is deprecated for `' + prop.name + '`');\n    }\n\n    return prop;\n  }; // parse a property; return null on invalid; return parsed property otherwise\n  // fields :\n  // - name : the name of the property\n  // - value : the parsed, native-typed value of the property\n  // - strValue : a string value that represents the property value in valid css\n  // - bypass : true iff the property is a bypass property\n\n\n  styfn$1.parseImpl = function (name, value, propIsBypass, propIsFlat) {\n    var self = this;\n    name = camel2dash(name); // make sure the property name is in dash form (e.g. 'property-name' not 'propertyName')\n\n    var property = self.properties[name];\n    var passedValue = value;\n    var types = self.types;\n\n    if (!property) {\n      return null;\n    } // return null on property of unknown name\n\n\n    if (value === undefined) {\n      return null;\n    } // can't assign undefined\n    // the property may be an alias\n\n\n    if (property.alias) {\n      property = property.pointsTo;\n      name = property.name;\n    }\n\n    var valueIsString = string(value);\n\n    if (valueIsString) {\n      // trim the value to make parsing easier\n      value = value.trim();\n    }\n\n    var type = property.type;\n\n    if (!type) {\n      return null;\n    } // no type, no luck\n    // check if bypass is null or empty string (i.e. indication to delete bypass property)\n\n\n    if (propIsBypass && (value === '' || value === null)) {\n      return {\n        name: name,\n        value: value,\n        bypass: true,\n        deleteBypass: true\n      };\n    } // check if value is a function used as a mapper\n\n\n    if (fn$6(value)) {\n      return {\n        name: name,\n        value: value,\n        strValue: 'fn',\n        mapped: types.fn,\n        bypass: propIsBypass\n      };\n    } // check if value is mapped\n\n\n    var data, mapData;\n\n    if (!valueIsString || propIsFlat || value.length < 7 || value[1] !== 'a') ; else if (value.length >= 7 && value[0] === 'd' && (data = new RegExp(types.data.regex).exec(value))) {\n      if (propIsBypass) {\n        return false;\n      } // mappers not allowed in bypass\n\n\n      var mapped = types.data;\n      return {\n        name: name,\n        value: data,\n        strValue: '' + value,\n        mapped: mapped,\n        field: data[1],\n        bypass: propIsBypass\n      };\n    } else if (value.length >= 10 && value[0] === 'm' && (mapData = new RegExp(types.mapData.regex).exec(value))) {\n      if (propIsBypass) {\n        return false;\n      } // mappers not allowed in bypass\n\n\n      if (type.multiple) {\n        return false;\n      } // impossible to map to num\n\n\n      var _mapped = types.mapData; // we can map only if the type is a colour or a number\n\n      if (!(type.color || type.number)) {\n        return false;\n      }\n\n      var valueMin = this.parse(name, mapData[4]); // parse to validate\n\n      if (!valueMin || valueMin.mapped) {\n        return false;\n      } // can't be invalid or mapped\n\n\n      var valueMax = this.parse(name, mapData[5]); // parse to validate\n\n      if (!valueMax || valueMax.mapped) {\n        return false;\n      } // can't be invalid or mapped\n      // check if valueMin and valueMax are the same\n\n\n      if (valueMin.pfValue === valueMax.pfValue || valueMin.strValue === valueMax.strValue) {\n        warn('`' + name + ': ' + value + '` is not a valid mapper because the output range is zero; converting to `' + name + ': ' + valueMin.strValue + '`');\n        return this.parse(name, valueMin.strValue); // can't make much of a mapper without a range\n      } else if (type.color) {\n        var c1 = valueMin.value;\n        var c2 = valueMax.value;\n        var same = c1[0] === c2[0] // red\n        && c1[1] === c2[1] // green\n        && c1[2] === c2[2] // blue\n        && ( // optional alpha\n        c1[3] === c2[3] // same alpha outright\n        || (c1[3] == null || c1[3] === 1 // full opacity for colour 1?\n        ) && (c2[3] == null || c2[3] === 1) // full opacity for colour 2?\n        );\n\n        if (same) {\n          return false;\n        } // can't make a mapper without a range\n\n      }\n\n      return {\n        name: name,\n        value: mapData,\n        strValue: '' + value,\n        mapped: _mapped,\n        field: mapData[1],\n        fieldMin: parseFloat(mapData[2]),\n        // min & max are numeric\n        fieldMax: parseFloat(mapData[3]),\n        valueMin: valueMin.value,\n        valueMax: valueMax.value,\n        bypass: propIsBypass\n      };\n    }\n\n    if (type.multiple && propIsFlat !== 'multiple') {\n      var vals;\n\n      if (valueIsString) {\n        vals = value.split(/\\s+/);\n      } else if (array(value)) {\n        vals = value;\n      } else {\n        vals = [value];\n      }\n\n      if (type.evenMultiple && vals.length % 2 !== 0) {\n        return null;\n      }\n\n      var valArr = [];\n      var unitsArr = [];\n      var pfValArr = [];\n      var strVal = '';\n      var hasEnum = false;\n\n      for (var i = 0; i < vals.length; i++) {\n        var p = self.parse(name, vals[i], propIsBypass, 'multiple');\n        hasEnum = hasEnum || string(p.value);\n        valArr.push(p.value);\n        pfValArr.push(p.pfValue != null ? p.pfValue : p.value);\n        unitsArr.push(p.units);\n        strVal += (i > 0 ? ' ' : '') + p.strValue;\n      }\n\n      if (type.validate && !type.validate(valArr, unitsArr)) {\n        return null;\n      }\n\n      if (type.singleEnum && hasEnum) {\n        if (valArr.length === 1 && string(valArr[0])) {\n          return {\n            name: name,\n            value: valArr[0],\n            strValue: valArr[0],\n            bypass: propIsBypass\n          };\n        } else {\n          return null;\n        }\n      }\n\n      return {\n        name: name,\n        value: valArr,\n        pfValue: pfValArr,\n        strValue: strVal,\n        bypass: propIsBypass,\n        units: unitsArr\n      };\n    } // several types also allow enums\n\n\n    var checkEnums = function checkEnums() {\n      for (var _i = 0; _i < type.enums.length; _i++) {\n        var en = type.enums[_i];\n\n        if (en === value) {\n          return {\n            name: name,\n            value: value,\n            strValue: '' + value,\n            bypass: propIsBypass\n          };\n        }\n      }\n\n      return null;\n    }; // check the type and return the appropriate object\n\n\n    if (type.number) {\n      var units;\n      var implicitUnits = 'px'; // not set => px\n\n      if (type.units) {\n        // use specified units if set\n        units = type.units;\n      }\n\n      if (type.implicitUnits) {\n        implicitUnits = type.implicitUnits;\n      }\n\n      if (!type.unitless) {\n        if (valueIsString) {\n          var unitsRegex = 'px|em' + (type.allowPercent ? '|\\\\%' : '');\n\n          if (units) {\n            unitsRegex = units;\n          } // only allow explicit units if so set\n\n\n          var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');\n\n          if (match) {\n            value = match[1];\n            units = match[2] || implicitUnits;\n          }\n        } else if (!units || type.implicitUnits) {\n          units = implicitUnits; // implicitly px if unspecified\n        }\n      }\n\n      value = parseFloat(value); // if not a number and enums not allowed, then the value is invalid\n\n      if (isNaN(value) && type.enums === undefined) {\n        return null;\n      } // check if this number type also accepts special keywords in place of numbers\n      // (i.e. `left`, `auto`, etc)\n\n\n      if (isNaN(value) && type.enums !== undefined) {\n        value = passedValue;\n        return checkEnums();\n      } // check if value must be an integer\n\n\n      if (type.integer && !integer(value)) {\n        return null;\n      } // check value is within range\n\n\n      if (type.min !== undefined && (value < type.min || type.strictMin && value === type.min) || type.max !== undefined && (value > type.max || type.strictMax && value === type.max)) {\n        return null;\n      }\n\n      var ret = {\n        name: name,\n        value: value,\n        strValue: '' + value + (units ? units : ''),\n        units: units,\n        bypass: propIsBypass\n      }; // normalise value in pixels\n\n      if (type.unitless || units !== 'px' && units !== 'em') {\n        ret.pfValue = value;\n      } else {\n        ret.pfValue = units === 'px' || !units ? value : this.getEmSizeInPixels() * value;\n      } // normalise value in ms\n\n\n      if (units === 'ms' || units === 's') {\n        ret.pfValue = units === 'ms' ? value : 1000 * value;\n      } // normalise value in rad\n\n\n      if (units === 'deg' || units === 'rad') {\n        ret.pfValue = units === 'rad' ? value : deg2rad(value);\n      } // normalize value in %\n\n\n      if (units === '%') {\n        ret.pfValue = value / 100;\n      }\n\n      return ret;\n    } else if (type.propList) {\n      var props = [];\n      var propsStr = '' + value;\n\n      if (propsStr === 'none') ; else {\n        // go over each prop\n        var propsSplit = propsStr.split(/\\s*,\\s*|\\s+/);\n\n        for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {\n          var propName = propsSplit[_i2].trim();\n\n          if (self.properties[propName]) {\n            props.push(propName);\n          } else {\n            warn('`' + propName + '` is not a valid property name');\n          }\n        }\n\n        if (props.length === 0) {\n          return null;\n        }\n      }\n\n      return {\n        name: name,\n        value: props,\n        strValue: props.length === 0 ? 'none' : props.join(' '),\n        bypass: propIsBypass\n      };\n    } else if (type.color) {\n      var tuple = color2tuple(value);\n\n      if (!tuple) {\n        return null;\n      }\n\n      return {\n        name: name,\n        value: tuple,\n        pfValue: tuple,\n        strValue: 'rgb(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')',\n        // n.b. no spaces b/c of multiple support\n        bypass: propIsBypass\n      };\n    } else if (type.regex || type.regexes) {\n      // first check enums\n      if (type.enums) {\n        var enumProp = checkEnums();\n\n        if (enumProp) {\n          return enumProp;\n        }\n      }\n\n      var regexes = type.regexes ? type.regexes : [type.regex];\n\n      for (var _i3 = 0; _i3 < regexes.length; _i3++) {\n        var regex = new RegExp(regexes[_i3]); // make a regex from the type string\n\n        var m = regex.exec(value);\n\n        if (m) {\n          // regex matches\n          return {\n            name: name,\n            value: type.singleRegexMatchValue ? m[1] : m,\n            strValue: '' + value,\n            bypass: propIsBypass\n          };\n        }\n      }\n\n      return null; // didn't match any\n    } else if (type.string) {\n      // just return\n      return {\n        name: name,\n        value: '' + value,\n        strValue: '' + value,\n        bypass: propIsBypass\n      };\n    } else if (type.enums) {\n      // check enums last because it's a combo type in others\n      return checkEnums();\n    } else {\n      return null; // not a type we can handle\n    }\n  };\n\n  var Style = function Style(cy) {\n    if (!(this instanceof Style)) {\n      return new Style(cy);\n    }\n\n    if (!core(cy)) {\n      error('A style must have a core reference');\n      return;\n    }\n\n    this._private = {\n      cy: cy,\n      coreStyle: {}\n    };\n    this.length = 0;\n    this.resetToDefault();\n  };\n\n  var styfn = Style.prototype;\n\n  styfn.instanceString = function () {\n    return 'style';\n  }; // remove all contexts\n\n\n  styfn.clear = function () {\n    var _p = this._private;\n    var cy = _p.cy;\n    var eles = cy.elements();\n\n    for (var i = 0; i < this.length; i++) {\n      this[i] = undefined;\n    }\n\n    this.length = 0;\n    _p.contextStyles = {};\n    _p.propDiffs = {};\n    this.cleanElements(eles, true);\n    eles.forEach(function (ele) {\n      var ele_p = ele[0]._private;\n      ele_p.styleDirty = true;\n      ele_p.appliedInitStyle = false;\n    });\n    return this; // chaining\n  };\n\n  styfn.resetToDefault = function () {\n    this.clear();\n    this.addDefaultStylesheet();\n    return this;\n  }; // builds a style object for the 'core' selector\n\n\n  styfn.core = function (propName) {\n    return this._private.coreStyle[propName] || this.getDefaultProperty(propName);\n  }; // create a new context from the specified selector string and switch to that context\n\n\n  styfn.selector = function (selectorStr) {\n    // 'core' is a special case and does not need a selector\n    var selector = selectorStr === 'core' ? null : new Selector(selectorStr);\n    var i = this.length++; // new context means new index\n\n    this[i] = {\n      selector: selector,\n      properties: [],\n      mappedProperties: [],\n      index: i\n    };\n    return this; // chaining\n  }; // add one or many css rules to the current context\n\n\n  styfn.css = function () {\n    var self = this;\n    var args = arguments;\n\n    if (args.length === 1) {\n      var map = args[0];\n\n      for (var i = 0; i < self.properties.length; i++) {\n        var prop = self.properties[i];\n        var mapVal = map[prop.name];\n\n        if (mapVal === undefined) {\n          mapVal = map[dash2camel(prop.name)];\n        }\n\n        if (mapVal !== undefined) {\n          this.cssRule(prop.name, mapVal);\n        }\n      }\n    } else if (args.length === 2) {\n      this.cssRule(args[0], args[1]);\n    } // do nothing if args are invalid\n\n\n    return this; // chaining\n  };\n\n  styfn.style = styfn.css; // add a single css rule to the current context\n\n  styfn.cssRule = function (name, value) {\n    // name-value pair\n    var property = this.parse(name, value); // add property to current context if valid\n\n    if (property) {\n      var i = this.length - 1;\n      this[i].properties.push(property);\n      this[i].properties[property.name] = property; // allow access by name as well\n\n      if (property.name.match(/pie-(\\d+)-background-size/) && property.value) {\n        this._private.hasPie = true;\n      }\n\n      if (property.mapped) {\n        this[i].mappedProperties.push(property);\n      } // add to core style if necessary\n\n\n      var currentSelectorIsCore = !this[i].selector;\n\n      if (currentSelectorIsCore) {\n        this._private.coreStyle[property.name] = property;\n      }\n    }\n\n    return this; // chaining\n  };\n\n  styfn.append = function (style) {\n    if (stylesheet(style)) {\n      style.appendToStyle(this);\n    } else if (array(style)) {\n      this.appendFromJson(style);\n    } else if (string(style)) {\n      this.appendFromString(style);\n    } // you probably wouldn't want to append a Style, since you'd duplicate the default parts\n\n\n    return this;\n  }; // static function\n\n\n  Style.fromJson = function (cy, json) {\n    var style = new Style(cy);\n    style.fromJson(json);\n    return style;\n  };\n\n  Style.fromString = function (cy, string) {\n    return new Style(cy).fromString(string);\n  };\n\n  [styfn$8, styfn$7, styfn$6, styfn$5, styfn$4, styfn$3, styfn$2, styfn$1].forEach(function (props) {\n    extend(styfn, props);\n  });\n  Style.types = styfn.types;\n  Style.properties = styfn.properties;\n  Style.propertyGroups = styfn.propertyGroups;\n  Style.propertyGroupNames = styfn.propertyGroupNames;\n  Style.propertyGroupKeys = styfn.propertyGroupKeys;\n\n  var corefn$2 = {\n    style: function style(newStyle) {\n      if (newStyle) {\n        var s = this.setStyle(newStyle);\n        s.update();\n      }\n\n      return this._private.style;\n    },\n    setStyle: function setStyle(style) {\n      var _p = this._private;\n\n      if (stylesheet(style)) {\n        _p.style = style.generateStyle(this);\n      } else if (array(style)) {\n        _p.style = Style.fromJson(this, style);\n      } else if (string(style)) {\n        _p.style = Style.fromString(this, style);\n      } else {\n        _p.style = Style(this);\n      }\n\n      return _p.style;\n    },\n    // e.g. cy.data() changed => recalc ele mappers\n    updateStyle: function updateStyle() {\n      this.mutableElements().updateStyle(); // just send to all eles\n    }\n  };\n\n  var defaultSelectionType = 'single';\n  var corefn$1 = {\n    autolock: function autolock(bool) {\n      if (bool !== undefined) {\n        this._private.autolock = bool ? true : false;\n      } else {\n        return this._private.autolock;\n      }\n\n      return this; // chaining\n    },\n    autoungrabify: function autoungrabify(bool) {\n      if (bool !== undefined) {\n        this._private.autoungrabify = bool ? true : false;\n      } else {\n        return this._private.autoungrabify;\n      }\n\n      return this; // chaining\n    },\n    autounselectify: function autounselectify(bool) {\n      if (bool !== undefined) {\n        this._private.autounselectify = bool ? true : false;\n      } else {\n        return this._private.autounselectify;\n      }\n\n      return this; // chaining\n    },\n    selectionType: function selectionType(selType) {\n      var _p = this._private;\n\n      if (_p.selectionType == null) {\n        _p.selectionType = defaultSelectionType;\n      }\n\n      if (selType !== undefined) {\n        if (selType === 'additive' || selType === 'single') {\n          _p.selectionType = selType;\n        }\n      } else {\n        return _p.selectionType;\n      }\n\n      return this;\n    },\n    panningEnabled: function panningEnabled(bool) {\n      if (bool !== undefined) {\n        this._private.panningEnabled = bool ? true : false;\n      } else {\n        return this._private.panningEnabled;\n      }\n\n      return this; // chaining\n    },\n    userPanningEnabled: function userPanningEnabled(bool) {\n      if (bool !== undefined) {\n        this._private.userPanningEnabled = bool ? true : false;\n      } else {\n        return this._private.userPanningEnabled;\n      }\n\n      return this; // chaining\n    },\n    zoomingEnabled: function zoomingEnabled(bool) {\n      if (bool !== undefined) {\n        this._private.zoomingEnabled = bool ? true : false;\n      } else {\n        return this._private.zoomingEnabled;\n      }\n\n      return this; // chaining\n    },\n    userZoomingEnabled: function userZoomingEnabled(bool) {\n      if (bool !== undefined) {\n        this._private.userZoomingEnabled = bool ? true : false;\n      } else {\n        return this._private.userZoomingEnabled;\n      }\n\n      return this; // chaining\n    },\n    boxSelectionEnabled: function boxSelectionEnabled(bool) {\n      if (bool !== undefined) {\n        this._private.boxSelectionEnabled = bool ? true : false;\n      } else {\n        return this._private.boxSelectionEnabled;\n      }\n\n      return this; // chaining\n    },\n    pan: function pan() {\n      var args = arguments;\n      var pan = this._private.pan;\n      var dim, val, dims, x, y;\n\n      switch (args.length) {\n        case 0:\n          // .pan()\n          return pan;\n\n        case 1:\n          if (string(args[0])) {\n            // .pan('x')\n            dim = args[0];\n            return pan[dim];\n          } else if (plainObject(args[0])) {\n            // .pan({ x: 0, y: 100 })\n            if (!this._private.panningEnabled) {\n              return this;\n            }\n\n            dims = args[0];\n            x = dims.x;\n            y = dims.y;\n\n            if (number$1(x)) {\n              pan.x = x;\n            }\n\n            if (number$1(y)) {\n              pan.y = y;\n            }\n\n            this.emit('pan viewport');\n          }\n\n          break;\n\n        case 2:\n          // .pan('x', 100)\n          if (!this._private.panningEnabled) {\n            return this;\n          }\n\n          dim = args[0];\n          val = args[1];\n\n          if ((dim === 'x' || dim === 'y') && number$1(val)) {\n            pan[dim] = val;\n          }\n\n          this.emit('pan viewport');\n          break;\n        // invalid\n      }\n\n      this.notify('viewport');\n      return this; // chaining\n    },\n    panBy: function panBy(arg0, arg1) {\n      var args = arguments;\n      var pan = this._private.pan;\n      var dim, val, dims, x, y;\n\n      if (!this._private.panningEnabled) {\n        return this;\n      }\n\n      switch (args.length) {\n        case 1:\n          if (plainObject(arg0)) {\n            // .panBy({ x: 0, y: 100 })\n            dims = args[0];\n            x = dims.x;\n            y = dims.y;\n\n            if (number$1(x)) {\n              pan.x += x;\n            }\n\n            if (number$1(y)) {\n              pan.y += y;\n            }\n\n            this.emit('pan viewport');\n          }\n\n          break;\n\n        case 2:\n          // .panBy('x', 100)\n          dim = arg0;\n          val = arg1;\n\n          if ((dim === 'x' || dim === 'y') && number$1(val)) {\n            pan[dim] += val;\n          }\n\n          this.emit('pan viewport');\n          break;\n        // invalid\n      }\n\n      this.notify('viewport');\n      return this; // chaining\n    },\n    fit: function fit(elements, padding) {\n      var viewportState = this.getFitViewport(elements, padding);\n\n      if (viewportState) {\n        var _p = this._private;\n        _p.zoom = viewportState.zoom;\n        _p.pan = viewportState.pan;\n        this.emit('pan zoom viewport');\n        this.notify('viewport');\n      }\n\n      return this; // chaining\n    },\n    getFitViewport: function getFitViewport(elements, padding) {\n      if (number$1(elements) && padding === undefined) {\n        // elements is optional\n        padding = elements;\n        elements = undefined;\n      }\n\n      if (!this._private.panningEnabled || !this._private.zoomingEnabled) {\n        return;\n      }\n\n      var bb;\n\n      if (string(elements)) {\n        var sel = elements;\n        elements = this.$(sel);\n      } else if (boundingBox(elements)) {\n        // assume bb\n        var bbe = elements;\n        bb = {\n          x1: bbe.x1,\n          y1: bbe.y1,\n          x2: bbe.x2,\n          y2: bbe.y2\n        };\n        bb.w = bb.x2 - bb.x1;\n        bb.h = bb.y2 - bb.y1;\n      } else if (!elementOrCollection(elements)) {\n        elements = this.mutableElements();\n      }\n\n      if (elementOrCollection(elements) && elements.empty()) {\n        return;\n      } // can't fit to nothing\n\n\n      bb = bb || elements.boundingBox();\n      var w = this.width();\n      var h = this.height();\n      var zoom;\n      padding = number$1(padding) ? padding : 0;\n\n      if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0 && !isNaN(bb.w) && !isNaN(bb.h) && bb.w > 0 && bb.h > 0) {\n        zoom = Math.min((w - 2 * padding) / bb.w, (h - 2 * padding) / bb.h); // crop zoom\n\n        zoom = zoom > this._private.maxZoom ? this._private.maxZoom : zoom;\n        zoom = zoom < this._private.minZoom ? this._private.minZoom : zoom;\n        var pan = {\n          // now pan to middle\n          x: (w - zoom * (bb.x1 + bb.x2)) / 2,\n          y: (h - zoom * (bb.y1 + bb.y2)) / 2\n        };\n        return {\n          zoom: zoom,\n          pan: pan\n        };\n      }\n\n      return;\n    },\n    zoomRange: function zoomRange(min, max) {\n      var _p = this._private;\n\n      if (max == null) {\n        var opts = min;\n        min = opts.min;\n        max = opts.max;\n      }\n\n      if (number$1(min) && number$1(max) && min <= max) {\n        _p.minZoom = min;\n        _p.maxZoom = max;\n      } else if (number$1(min) && max === undefined && min <= _p.maxZoom) {\n        _p.minZoom = min;\n      } else if (number$1(max) && min === undefined && max >= _p.minZoom) {\n        _p.maxZoom = max;\n      }\n\n      return this;\n    },\n    minZoom: function minZoom(zoom) {\n      if (zoom === undefined) {\n        return this._private.minZoom;\n      } else {\n        return this.zoomRange({\n          min: zoom\n        });\n      }\n    },\n    maxZoom: function maxZoom(zoom) {\n      if (zoom === undefined) {\n        return this._private.maxZoom;\n      } else {\n        return this.zoomRange({\n          max: zoom\n        });\n      }\n    },\n    getZoomedViewport: function getZoomedViewport(params) {\n      var _p = this._private;\n      var currentPan = _p.pan;\n      var currentZoom = _p.zoom;\n      var pos; // in rendered px\n\n      var zoom;\n      var bail = false;\n\n      if (!_p.zoomingEnabled) {\n        // zooming disabled\n        bail = true;\n      }\n\n      if (number$1(params)) {\n        // then set the zoom\n        zoom = params;\n      } else if (plainObject(params)) {\n        // then zoom about a point\n        zoom = params.level;\n\n        if (params.position != null) {\n          pos = modelToRenderedPosition(params.position, currentZoom, currentPan);\n        } else if (params.renderedPosition != null) {\n          pos = params.renderedPosition;\n        }\n\n        if (pos != null && !_p.panningEnabled) {\n          // panning disabled\n          bail = true;\n        }\n      } // crop zoom\n\n\n      zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;\n      zoom = zoom < _p.minZoom ? _p.minZoom : zoom; // can't zoom with invalid params\n\n      if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {\n        return null;\n      }\n\n      if (pos != null) {\n        // set zoom about position\n        var pan1 = currentPan;\n        var zoom1 = currentZoom;\n        var zoom2 = zoom;\n        var pan2 = {\n          x: -zoom2 / zoom1 * (pos.x - pan1.x) + pos.x,\n          y: -zoom2 / zoom1 * (pos.y - pan1.y) + pos.y\n        };\n        return {\n          zoomed: true,\n          panned: true,\n          zoom: zoom2,\n          pan: pan2\n        };\n      } else {\n        // just set the zoom\n        return {\n          zoomed: true,\n          panned: false,\n          zoom: zoom,\n          pan: currentPan\n        };\n      }\n    },\n    zoom: function zoom(params) {\n      if (params === undefined) {\n        // get\n        return this._private.zoom;\n      } else {\n        // set\n        var vp = this.getZoomedViewport(params);\n        var _p = this._private;\n\n        if (vp == null || !vp.zoomed) {\n          return this;\n        }\n\n        _p.zoom = vp.zoom;\n\n        if (vp.panned) {\n          _p.pan.x = vp.pan.x;\n          _p.pan.y = vp.pan.y;\n        }\n\n        this.emit('zoom' + (vp.panned ? ' pan' : '') + ' viewport');\n        this.notify('viewport');\n        return this; // chaining\n      }\n    },\n    viewport: function viewport(opts) {\n      var _p = this._private;\n      var zoomDefd = true;\n      var panDefd = true;\n      var events = []; // to trigger\n\n      var zoomFailed = false;\n      var panFailed = false;\n\n      if (!opts) {\n        return this;\n      }\n\n      if (!number$1(opts.zoom)) {\n        zoomDefd = false;\n      }\n\n      if (!plainObject(opts.pan)) {\n        panDefd = false;\n      }\n\n      if (!zoomDefd && !panDefd) {\n        return this;\n      }\n\n      if (zoomDefd) {\n        var z = opts.zoom;\n\n        if (z < _p.minZoom || z > _p.maxZoom || !_p.zoomingEnabled) {\n          zoomFailed = true;\n        } else {\n          _p.zoom = z;\n          events.push('zoom');\n        }\n      }\n\n      if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {\n        var p = opts.pan;\n\n        if (number$1(p.x)) {\n          _p.pan.x = p.x;\n          panFailed = false;\n        }\n\n        if (number$1(p.y)) {\n          _p.pan.y = p.y;\n          panFailed = false;\n        }\n\n        if (!panFailed) {\n          events.push('pan');\n        }\n      }\n\n      if (events.length > 0) {\n        events.push('viewport');\n        this.emit(events.join(' '));\n        this.notify('viewport');\n      }\n\n      return this; // chaining\n    },\n    center: function center(elements) {\n      var pan = this.getCenterPan(elements);\n\n      if (pan) {\n        this._private.pan = pan;\n        this.emit('pan viewport');\n        this.notify('viewport');\n      }\n\n      return this; // chaining\n    },\n    getCenterPan: function getCenterPan(elements, zoom) {\n      if (!this._private.panningEnabled) {\n        return;\n      }\n\n      if (string(elements)) {\n        var selector = elements;\n        elements = this.mutableElements().filter(selector);\n      } else if (!elementOrCollection(elements)) {\n        elements = this.mutableElements();\n      }\n\n      if (elements.length === 0) {\n        return;\n      } // can't centre pan to nothing\n\n\n      var bb = elements.boundingBox();\n      var w = this.width();\n      var h = this.height();\n      zoom = zoom === undefined ? this._private.zoom : zoom;\n      var pan = {\n        // middle\n        x: (w - zoom * (bb.x1 + bb.x2)) / 2,\n        y: (h - zoom * (bb.y1 + bb.y2)) / 2\n      };\n      return pan;\n    },\n    reset: function reset() {\n      if (!this._private.panningEnabled || !this._private.zoomingEnabled) {\n        return this;\n      }\n\n      this.viewport({\n        pan: {\n          x: 0,\n          y: 0\n        },\n        zoom: 1\n      });\n      return this; // chaining\n    },\n    invalidateSize: function invalidateSize() {\n      this._private.sizeCache = null;\n    },\n    size: function size() {\n      var _p = this._private;\n      var container = _p.container;\n      var cy = this;\n      return _p.sizeCache = _p.sizeCache || (container ? function () {\n        var style = cy.window().getComputedStyle(container);\n\n        var val = function val(name) {\n          return parseFloat(style.getPropertyValue(name));\n        };\n\n        return {\n          width: container.clientWidth - val('padding-left') - val('padding-right'),\n          height: container.clientHeight - val('padding-top') - val('padding-bottom')\n        };\n      }() : {\n        // fallback if no container (not 0 b/c can be used for dividing etc)\n        width: 1,\n        height: 1\n      });\n    },\n    width: function width() {\n      return this.size().width;\n    },\n    height: function height() {\n      return this.size().height;\n    },\n    extent: function extent() {\n      var pan = this._private.pan;\n      var zoom = this._private.zoom;\n      var rb = this.renderedExtent();\n      var b = {\n        x1: (rb.x1 - pan.x) / zoom,\n        x2: (rb.x2 - pan.x) / zoom,\n        y1: (rb.y1 - pan.y) / zoom,\n        y2: (rb.y2 - pan.y) / zoom\n      };\n      b.w = b.x2 - b.x1;\n      b.h = b.y2 - b.y1;\n      return b;\n    },\n    renderedExtent: function renderedExtent() {\n      var width = this.width();\n      var height = this.height();\n      return {\n        x1: 0,\n        y1: 0,\n        x2: width,\n        y2: height,\n        w: width,\n        h: height\n      };\n    },\n    multiClickDebounceTime: function multiClickDebounceTime(_int) {\n      if (_int) this._private.multiClickDebounceTime = _int;else return this._private.multiClickDebounceTime;\n      return this; // chaining\n    }\n  }; // aliases\n\n  corefn$1.centre = corefn$1.center; // backwards compatibility\n\n  corefn$1.autolockNodes = corefn$1.autolock;\n  corefn$1.autoungrabifyNodes = corefn$1.autoungrabify;\n\n  var fn = {\n    data: define.data({\n      field: 'data',\n      bindingEvent: 'data',\n      allowBinding: true,\n      allowSetting: true,\n      settingEvent: 'data',\n      settingTriggersEvent: true,\n      triggerFnName: 'trigger',\n      allowGetting: true,\n      updateStyle: true\n    }),\n    removeData: define.removeData({\n      field: 'data',\n      event: 'data',\n      triggerFnName: 'trigger',\n      triggerEvent: true,\n      updateStyle: true\n    }),\n    scratch: define.data({\n      field: 'scratch',\n      bindingEvent: 'scratch',\n      allowBinding: true,\n      allowSetting: true,\n      settingEvent: 'scratch',\n      settingTriggersEvent: true,\n      triggerFnName: 'trigger',\n      allowGetting: true,\n      updateStyle: true\n    }),\n    removeScratch: define.removeData({\n      field: 'scratch',\n      event: 'scratch',\n      triggerFnName: 'trigger',\n      triggerEvent: true,\n      updateStyle: true\n    })\n  }; // aliases\n\n  fn.attr = fn.data;\n  fn.removeAttr = fn.removeData;\n\n  var Core = function Core(opts) {\n    var cy = this;\n    opts = extend({}, opts);\n    var container = opts.container; // allow for passing a wrapped jquery object\n    // e.g. cytoscape({ container: $('#cy') })\n\n    if (container && !htmlElement(container) && htmlElement(container[0])) {\n      container = container[0];\n    }\n\n    var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery\n\n    reg = reg || {};\n\n    if (reg && reg.cy) {\n      reg.cy.destroy();\n      reg = {}; // old instance => replace reg completely\n    }\n\n    var readies = reg.readies = reg.readies || [];\n\n    if (container) {\n      container._cyreg = reg;\n    } // make sure container assoc'd reg points to this cy\n\n\n    reg.cy = cy;\n    var head = _window !== undefined && container !== undefined && !opts.headless;\n    var options = opts;\n    options.layout = extend({\n      name: head ? 'grid' : 'null'\n    }, options.layout);\n    options.renderer = extend({\n      name: head ? 'canvas' : 'null'\n    }, options.renderer);\n\n    var defVal = function defVal(def, val, altVal) {\n      if (val !== undefined) {\n        return val;\n      } else if (altVal !== undefined) {\n        return altVal;\n      } else {\n        return def;\n      }\n    };\n\n    var _p = this._private = {\n      container: container,\n      // html dom ele container\n      ready: false,\n      // whether ready has been triggered\n      options: options,\n      // cached options\n      elements: new Collection(this),\n      // elements in the graph\n      listeners: [],\n      // list of listeners\n      aniEles: new Collection(this),\n      // elements being animated\n      data: options.data || {},\n      // data for the core\n      scratch: {},\n      // scratch object for core\n      layout: null,\n      renderer: null,\n      destroyed: false,\n      // whether destroy was called\n      notificationsEnabled: true,\n      // whether notifications are sent to the renderer\n      minZoom: 1e-50,\n      maxZoom: 1e50,\n      zoomingEnabled: defVal(true, options.zoomingEnabled),\n      userZoomingEnabled: defVal(true, options.userZoomingEnabled),\n      panningEnabled: defVal(true, options.panningEnabled),\n      userPanningEnabled: defVal(true, options.userPanningEnabled),\n      boxSelectionEnabled: defVal(true, options.boxSelectionEnabled),\n      autolock: defVal(false, options.autolock, options.autolockNodes),\n      autoungrabify: defVal(false, options.autoungrabify, options.autoungrabifyNodes),\n      autounselectify: defVal(false, options.autounselectify),\n      styleEnabled: options.styleEnabled === undefined ? head : options.styleEnabled,\n      zoom: number$1(options.zoom) ? options.zoom : 1,\n      pan: {\n        x: plainObject(options.pan) && number$1(options.pan.x) ? options.pan.x : 0,\n        y: plainObject(options.pan) && number$1(options.pan.y) ? options.pan.y : 0\n      },\n      animation: {\n        // object for currently-running animations\n        current: [],\n        queue: []\n      },\n      hasCompoundNodes: false,\n      multiClickDebounceTime: defVal(250, options.multiClickDebounceTime)\n    };\n\n    this.createEmitter(); // set selection type\n\n    this.selectionType(options.selectionType); // init zoom bounds\n\n    this.zoomRange({\n      min: options.minZoom,\n      max: options.maxZoom\n    });\n\n    var loadExtData = function loadExtData(extData, next) {\n      var anyIsPromise = extData.some(promise);\n\n      if (anyIsPromise) {\n        return Promise$1.all(extData).then(next); // load all data asynchronously, then exec rest of init\n      } else {\n        next(extData); // exec synchronously for convenience\n      }\n    }; // start with the default stylesheet so we have something before loading an external stylesheet\n\n\n    if (_p.styleEnabled) {\n      cy.setStyle([]);\n    } // create the renderer\n\n\n    var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options\n\n    cy.initRenderer(rendererOptions);\n\n    var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {\n      cy.notifications(false); // remove old elements\n\n      var oldEles = cy.mutableElements();\n\n      if (oldEles.length > 0) {\n        oldEles.remove();\n      }\n\n      if (elements != null) {\n        if (plainObject(elements) || array(elements)) {\n          cy.add(elements);\n        }\n      }\n\n      cy.one('layoutready', function (e) {\n        cy.notifications(true);\n        cy.emit(e); // we missed this event by turning notifications off, so pass it on\n\n        cy.one('load', onload);\n        cy.emitAndNotify('load');\n      }).one('layoutstop', function () {\n        cy.one('done', ondone);\n        cy.emit('done');\n      });\n      var layoutOpts = extend({}, cy._private.options.layout);\n      layoutOpts.eles = cy.elements();\n      cy.layout(layoutOpts).run();\n    };\n\n    loadExtData([options.style, options.elements], function (thens) {\n      var initStyle = thens[0];\n      var initEles = thens[1]; // init style\n\n      if (_p.styleEnabled) {\n        cy.style().append(initStyle);\n      } // initial load\n\n\n      setElesAndLayout(initEles, function () {\n        // onready\n        cy.startAnimationLoop();\n        _p.ready = true; // if a ready callback is specified as an option, the bind it\n\n        if (fn$6(options.ready)) {\n          cy.on('ready', options.ready);\n        } // bind all the ready handlers registered before creating this instance\n\n\n        for (var i = 0; i < readies.length; i++) {\n          var fn = readies[i];\n          cy.on('ready', fn);\n        }\n\n        if (reg) {\n          reg.readies = [];\n        } // clear b/c we've bound them all and don't want to keep it around in case a new core uses the same div etc\n\n\n        cy.emit('ready');\n      }, options.done);\n    });\n  };\n\n  var corefn = Core.prototype; // short alias\n\n  extend(corefn, {\n    instanceString: function instanceString() {\n      return 'core';\n    },\n    isReady: function isReady() {\n      return this._private.ready;\n    },\n    destroyed: function destroyed() {\n      return this._private.destroyed;\n    },\n    ready: function ready(fn) {\n      if (this.isReady()) {\n        this.emitter().emit('ready', [], fn); // just calls fn as though triggered via ready event\n      } else {\n        this.on('ready', fn);\n      }\n\n      return this;\n    },\n    destroy: function destroy() {\n      var cy = this;\n      if (cy.destroyed()) return;\n      cy.stopAnimationLoop();\n      cy.destroyRenderer();\n      this.emit('destroy');\n      cy._private.destroyed = true;\n      return cy;\n    },\n    hasElementWithId: function hasElementWithId(id) {\n      return this._private.elements.hasElementWithId(id);\n    },\n    getElementById: function getElementById(id) {\n      return this._private.elements.getElementById(id);\n    },\n    hasCompoundNodes: function hasCompoundNodes() {\n      return this._private.hasCompoundNodes;\n    },\n    headless: function headless() {\n      return this._private.renderer.isHeadless();\n    },\n    styleEnabled: function styleEnabled() {\n      return this._private.styleEnabled;\n    },\n    addToPool: function addToPool(eles) {\n      this._private.elements.merge(eles);\n\n      return this; // chaining\n    },\n    removeFromPool: function removeFromPool(eles) {\n      this._private.elements.unmerge(eles);\n\n      return this;\n    },\n    container: function container() {\n      return this._private.container || null;\n    },\n    window: function window() {\n      var container = this._private.container;\n      if (container == null) return _window;\n      var ownerDocument = this._private.container.ownerDocument;\n\n      if (ownerDocument === undefined || ownerDocument == null) {\n        return _window;\n      }\n\n      return ownerDocument.defaultView || _window;\n    },\n    mount: function mount(container) {\n      if (container == null) {\n        return;\n      }\n\n      var cy = this;\n      var _p = cy._private;\n      var options = _p.options;\n\n      if (!htmlElement(container) && htmlElement(container[0])) {\n        container = container[0];\n      }\n\n      cy.stopAnimationLoop();\n      cy.destroyRenderer();\n      _p.container = container;\n      _p.styleEnabled = true;\n      cy.invalidateSize();\n      cy.initRenderer(extend({}, options, options.renderer, {\n        // allow custom renderer name to be re-used, otherwise use canvas\n        name: options.renderer.name === 'null' ? 'canvas' : options.renderer.name\n      }));\n      cy.startAnimationLoop();\n      cy.style(options.style);\n      cy.emit('mount');\n      return cy;\n    },\n    unmount: function unmount() {\n      var cy = this;\n      cy.stopAnimationLoop();\n      cy.destroyRenderer();\n      cy.initRenderer({\n        name: 'null'\n      });\n      cy.emit('unmount');\n      return cy;\n    },\n    options: function options() {\n      return copy(this._private.options);\n    },\n    json: function json(obj) {\n      var cy = this;\n      var _p = cy._private;\n      var eles = cy.mutableElements();\n\n      var getFreshRef = function getFreshRef(ele) {\n        return cy.getElementById(ele.id());\n      };\n\n      if (plainObject(obj)) {\n        // set\n        cy.startBatch();\n\n        if (obj.elements) {\n          var idInJson = {};\n\n          var updateEles = function updateEles(jsons, gr) {\n            var toAdd = [];\n            var toMod = [];\n\n            for (var i = 0; i < jsons.length; i++) {\n              var json = jsons[i];\n\n              if (!json.data.id) {\n                warn('cy.json() cannot handle elements without an ID attribute');\n                continue;\n              }\n\n              var id = '' + json.data.id; // id must be string\n\n              var ele = cy.getElementById(id);\n              idInJson[id] = true;\n\n              if (ele.length !== 0) {\n                // existing element should be updated\n                toMod.push({\n                  ele: ele,\n                  json: json\n                });\n              } else {\n                // otherwise should be added\n                if (gr) {\n                  json.group = gr;\n                  toAdd.push(json);\n                } else {\n                  toAdd.push(json);\n                }\n              }\n            }\n\n            cy.add(toAdd);\n\n            for (var _i = 0; _i < toMod.length; _i++) {\n              var _toMod$_i = toMod[_i],\n                  _ele = _toMod$_i.ele,\n                  _json = _toMod$_i.json;\n\n              _ele.json(_json);\n            }\n          };\n\n          if (array(obj.elements)) {\n            // elements: []\n            updateEles(obj.elements);\n          } else {\n            // elements: { nodes: [], edges: [] }\n            var grs = ['nodes', 'edges'];\n\n            for (var i = 0; i < grs.length; i++) {\n              var gr = grs[i];\n              var elements = obj.elements[gr];\n\n              if (array(elements)) {\n                updateEles(elements, gr);\n              }\n            }\n          }\n\n          var parentsToRemove = cy.collection();\n          eles.filter(function (ele) {\n            return !idInJson[ele.id()];\n          }).forEach(function (ele) {\n            if (ele.isParent()) {\n              parentsToRemove.merge(ele);\n            } else {\n              ele.remove();\n            }\n          }); // so that children are not removed w/parent\n\n          parentsToRemove.forEach(function (ele) {\n            return ele.children().move({\n              parent: null\n            });\n          }); // intermediate parents may be moved by prior line, so make sure we remove by fresh refs\n\n          parentsToRemove.forEach(function (ele) {\n            return getFreshRef(ele).remove();\n          });\n        }\n\n        if (obj.style) {\n          cy.style(obj.style);\n        }\n\n        if (obj.zoom != null && obj.zoom !== _p.zoom) {\n          cy.zoom(obj.zoom);\n        }\n\n        if (obj.pan) {\n          if (obj.pan.x !== _p.pan.x || obj.pan.y !== _p.pan.y) {\n            cy.pan(obj.pan);\n          }\n        }\n\n        if (obj.data) {\n          cy.data(obj.data);\n        }\n\n        var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];\n\n        for (var _i2 = 0; _i2 < fields.length; _i2++) {\n          var f = fields[_i2];\n\n          if (obj[f] != null) {\n            cy[f](obj[f]);\n          }\n        }\n\n        cy.endBatch();\n        return this; // chaining\n      } else {\n        // get\n        var flat = !!obj;\n        var json = {};\n\n        if (flat) {\n          json.elements = this.elements().map(function (ele) {\n            return ele.json();\n          });\n        } else {\n          json.elements = {};\n          eles.forEach(function (ele) {\n            var group = ele.group();\n\n            if (!json.elements[group]) {\n              json.elements[group] = [];\n            }\n\n            json.elements[group].push(ele.json());\n          });\n        }\n\n        if (this._private.styleEnabled) {\n          json.style = cy.style().json();\n        }\n\n        json.data = copy(cy.data());\n        var options = _p.options;\n        json.zoomingEnabled = _p.zoomingEnabled;\n        json.userZoomingEnabled = _p.userZoomingEnabled;\n        json.zoom = _p.zoom;\n        json.minZoom = _p.minZoom;\n        json.maxZoom = _p.maxZoom;\n        json.panningEnabled = _p.panningEnabled;\n        json.userPanningEnabled = _p.userPanningEnabled;\n        json.pan = copy(_p.pan);\n        json.boxSelectionEnabled = _p.boxSelectionEnabled;\n        json.renderer = copy(options.renderer);\n        json.hideEdgesOnViewport = options.hideEdgesOnViewport;\n        json.textureOnViewport = options.textureOnViewport;\n        json.wheelSensitivity = options.wheelSensitivity;\n        json.motionBlur = options.motionBlur;\n        json.multiClickDebounceTime = options.multiClickDebounceTime;\n        return json;\n      }\n    }\n  });\n  corefn.$id = corefn.getElementById;\n  [corefn$9, corefn$8, elesfn, corefn$7, corefn$6, corefn$5, corefn$4, corefn$3, corefn$2, corefn$1, fn].forEach(function (props) {\n    extend(corefn, props);\n  });\n\n  /* eslint-disable no-unused-vars */\n\n  var defaults$7 = {\n    fit: true,\n    // whether to fit the viewport to the graph\n    directed: false,\n    // whether the tree is directed downwards (or edges can point in any direction if false)\n    padding: 30,\n    // padding on fit\n    circle: false,\n    // put depths in concentric circles if true, put depths top down if false\n    grid: false,\n    // whether to create an even grid into which the DAG is placed (circle:false only)\n    spacingFactor: 1.75,\n    // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)\n    boundingBox: undefined,\n    // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n    avoidOverlap: true,\n    // prevents node overlap, may overflow boundingBox if not enough space\n    nodeDimensionsIncludeLabels: false,\n    // Excludes the label when calculating node bounding boxes for the layout algorithm\n    roots: undefined,\n    // the roots of the trees\n    depthSort: undefined,\n    // a sorting function to order nodes at equal depth. e.g. function(a, b){ return a.data('weight') - b.data('weight') }\n    animate: false,\n    // whether to transition the node positions\n    animationDuration: 500,\n    // duration of animation in ms if enabled\n    animationEasing: undefined,\n    // easing of animation if enabled,\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts\n    ready: undefined,\n    // callback on layoutready\n    stop: undefined,\n    // callback on layoutstop\n    transform: function transform(node, position) {\n      return position;\n    } // transform a given node position. Useful for changing flow direction in discrete layouts\n\n  };\n  var deprecatedOptionDefaults = {\n    maximal: false,\n    // whether to shift nodes down their natural BFS depths in order to avoid upwards edges (DAGS only); setting acyclic to true sets maximal to true also\n    acyclic: false // whether the tree is acyclic and thus a node could be shifted (due to the maximal option) multiple times without causing an infinite loop; setting to true sets maximal to true also; if you are uncertain whether a tree is acyclic, set to false to avoid potential infinite loops\n\n  };\n  /* eslint-enable */\n\n  var getInfo = function getInfo(ele) {\n    return ele.scratch('breadthfirst');\n  };\n\n  var setInfo = function setInfo(ele, obj) {\n    return ele.scratch('breadthfirst', obj);\n  };\n\n  function BreadthFirstLayout(options) {\n    this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);\n  }\n\n  BreadthFirstLayout.prototype.run = function () {\n    var params = this.options;\n    var options = params;\n    var cy = params.cy;\n    var eles = options.eles;\n    var nodes = eles.nodes().filter(function (n) {\n      return !n.isParent();\n    });\n    var graph = eles;\n    var directed = options.directed;\n    var maximal = options.acyclic || options.maximal || options.maximalAdjustments > 0; // maximalAdjustments for compat. w/ old code; also, setting acyclic to true sets maximal to true\n\n    var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n      x1: 0,\n      y1: 0,\n      w: cy.width(),\n      h: cy.height()\n    });\n    var roots;\n\n    if (elementOrCollection(options.roots)) {\n      roots = options.roots;\n    } else if (array(options.roots)) {\n      var rootsArray = [];\n\n      for (var i = 0; i < options.roots.length; i++) {\n        var id = options.roots[i];\n        var ele = cy.getElementById(id);\n        rootsArray.push(ele);\n      }\n\n      roots = cy.collection(rootsArray);\n    } else if (string(options.roots)) {\n      roots = cy.$(options.roots);\n    } else {\n      if (directed) {\n        roots = nodes.roots();\n      } else {\n        var components = eles.components();\n        roots = cy.collection();\n\n        var _loop = function _loop(_i) {\n          var comp = components[_i];\n          var maxDegree = comp.maxDegree(false);\n          var compRoots = comp.filter(function (ele) {\n            return ele.degree(false) === maxDegree;\n          });\n          roots = roots.add(compRoots);\n        };\n\n        for (var _i = 0; _i < components.length; _i++) {\n          _loop(_i);\n        }\n      }\n    }\n\n    var depths = [];\n    var foundByBfs = {};\n\n    var addToDepth = function addToDepth(ele, d) {\n      if (depths[d] == null) {\n        depths[d] = [];\n      }\n\n      var i = depths[d].length;\n      depths[d].push(ele);\n      setInfo(ele, {\n        index: i,\n        depth: d\n      });\n    };\n\n    var changeDepth = function changeDepth(ele, newDepth) {\n      var _getInfo = getInfo(ele),\n          depth = _getInfo.depth,\n          index = _getInfo.index;\n\n      depths[depth][index] = null;\n      addToDepth(ele, newDepth);\n    }; // find the depths of the nodes\n\n\n    graph.bfs({\n      roots: roots,\n      directed: options.directed,\n      visit: function visit(node, edge, pNode, i, depth) {\n        var ele = node[0];\n        var id = ele.id();\n        addToDepth(ele, depth);\n        foundByBfs[id] = true;\n      }\n    }); // check for nodes not found by bfs\n\n    var orphanNodes = [];\n\n    for (var _i2 = 0; _i2 < nodes.length; _i2++) {\n      var _ele = nodes[_i2];\n\n      if (foundByBfs[_ele.id()]) {\n        continue;\n      } else {\n        orphanNodes.push(_ele);\n      }\n    } // assign the nodes a depth and index\n\n\n    var assignDepthsAt = function assignDepthsAt(i) {\n      var eles = depths[i];\n\n      for (var j = 0; j < eles.length; j++) {\n        var _ele2 = eles[j];\n\n        if (_ele2 == null) {\n          eles.splice(j, 1);\n          j--;\n          continue;\n        }\n\n        setInfo(_ele2, {\n          depth: i,\n          index: j\n        });\n      }\n    };\n\n    var assignDepths = function assignDepths() {\n      for (var _i3 = 0; _i3 < depths.length; _i3++) {\n        assignDepthsAt(_i3);\n      }\n    };\n\n    var adjustMaximally = function adjustMaximally(ele, shifted) {\n      var eInfo = getInfo(ele);\n      var incomers = ele.incomers().filter(function (el) {\n        return el.isNode() && eles.has(el);\n      });\n      var maxDepth = -1;\n      var id = ele.id();\n\n      for (var k = 0; k < incomers.length; k++) {\n        var incmr = incomers[k];\n        var iInfo = getInfo(incmr);\n        maxDepth = Math.max(maxDepth, iInfo.depth);\n      }\n\n      if (eInfo.depth <= maxDepth) {\n        if (!options.acyclic && shifted[id]) {\n          return null;\n        }\n\n        var newDepth = maxDepth + 1;\n        changeDepth(ele, newDepth);\n        shifted[id] = newDepth;\n        return true;\n      }\n\n      return false;\n    }; // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)\n\n\n    if (directed && maximal) {\n      var Q = [];\n      var shifted = {};\n\n      var enqueue = function enqueue(n) {\n        return Q.push(n);\n      };\n\n      var dequeue = function dequeue() {\n        return Q.shift();\n      };\n\n      nodes.forEach(function (n) {\n        return Q.push(n);\n      });\n\n      while (Q.length > 0) {\n        var _ele3 = dequeue();\n\n        var didShift = adjustMaximally(_ele3, shifted);\n\n        if (didShift) {\n          _ele3.outgoers().filter(function (el) {\n            return el.isNode() && eles.has(el);\n          }).forEach(enqueue);\n        } else if (didShift === null) {\n          warn('Detected double maximal shift for node `' + _ele3.id() + '`.  Bailing maximal adjustment due to cycle.  Use `options.maximal: true` only on DAGs.');\n          break; // exit on failure\n        }\n      }\n    }\n\n    assignDepths(); // clear holes\n    // find min distance we need to leave between nodes\n\n    var minDistance = 0;\n\n    if (options.avoidOverlap) {\n      for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n        var n = nodes[_i4];\n        var nbb = n.layoutDimensions(options);\n        var w = nbb.w;\n        var h = nbb.h;\n        minDistance = Math.max(minDistance, w, h);\n      }\n    } // get the weighted percent for an element based on its connectivity to other levels\n\n\n    var cachedWeightedPercent = {};\n\n    var getWeightedPercent = function getWeightedPercent(ele) {\n      if (cachedWeightedPercent[ele.id()]) {\n        return cachedWeightedPercent[ele.id()];\n      }\n\n      var eleDepth = getInfo(ele).depth;\n      var neighbors = ele.neighborhood();\n      var percent = 0;\n      var samples = 0;\n\n      for (var _i5 = 0; _i5 < neighbors.length; _i5++) {\n        var neighbor = neighbors[_i5];\n\n        if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {\n          continue;\n        }\n\n        var bf = getInfo(neighbor);\n\n        if (bf == null) {\n          continue;\n        }\n\n        var index = bf.index;\n        var depth = bf.depth; // unassigned neighbours shouldn't affect the ordering\n\n        if (index == null || depth == null) {\n          continue;\n        }\n\n        var nDepth = depths[depth].length;\n\n        if (depth < eleDepth) {\n          // only get influenced by elements above\n          percent += index / nDepth;\n          samples++;\n        }\n      }\n\n      samples = Math.max(1, samples);\n      percent = percent / samples;\n\n      if (samples === 0) {\n        // put lone nodes at the start\n        percent = 0;\n      }\n\n      cachedWeightedPercent[ele.id()] = percent;\n      return percent;\n    }; // rearrange the indices in each depth level based on connectivity\n\n\n    var sortFn = function sortFn(a, b) {\n      var apct = getWeightedPercent(a);\n      var bpct = getWeightedPercent(b);\n      var diff = apct - bpct;\n\n      if (diff === 0) {\n        return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons\n      } else {\n        return diff;\n      }\n    };\n\n    if (options.depthSort !== undefined) {\n      sortFn = options.depthSort;\n    } // sort each level to make connected nodes closer\n\n\n    for (var _i6 = 0; _i6 < depths.length; _i6++) {\n      depths[_i6].sort(sortFn);\n\n      assignDepthsAt(_i6);\n    } // assign orphan nodes to a new top-level depth\n\n\n    var orphanDepth = [];\n\n    for (var _i7 = 0; _i7 < orphanNodes.length; _i7++) {\n      orphanDepth.push(orphanNodes[_i7]);\n    }\n\n    depths.unshift(orphanDepth);\n    assignDepths();\n    var biggestDepthSize = 0;\n\n    for (var _i8 = 0; _i8 < depths.length; _i8++) {\n      biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);\n    }\n\n    var center = {\n      x: bb.x1 + bb.w / 2,\n      y: bb.x1 + bb.h / 2\n    };\n    var maxDepthSize = depths.reduce(function (max, eles) {\n      return Math.max(max, eles.length);\n    }, 0);\n\n    var getPosition = function getPosition(ele) {\n      var _getInfo2 = getInfo(ele),\n          depth = _getInfo2.depth,\n          index = _getInfo2.index;\n\n      var depthSize = depths[depth].length;\n      var distanceX = Math.max(bb.w / ((options.grid ? maxDepthSize : depthSize) + 1), minDistance);\n      var distanceY = Math.max(bb.h / (depths.length + 1), minDistance);\n      var radiusStepSize = Math.min(bb.w / 2 / depths.length, bb.h / 2 / depths.length);\n      radiusStepSize = Math.max(radiusStepSize, minDistance);\n\n      if (!options.circle) {\n        var epos = {\n          x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,\n          y: (depth + 1) * distanceY\n        };\n        return epos;\n      } else {\n        var radius = radiusStepSize * depth + radiusStepSize - (depths.length > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);\n        var theta = 2 * Math.PI / depths[depth].length * index;\n\n        if (depth === 0 && depths[0].length === 1) {\n          radius = 1;\n        }\n\n        return {\n          x: center.x + radius * Math.cos(theta),\n          y: center.y + radius * Math.sin(theta)\n        };\n      }\n    };\n\n    eles.nodes().layoutPositions(this, options, getPosition);\n    return this; // chaining\n  };\n\n  var defaults$6 = {\n    fit: true,\n    // whether to fit the viewport to the graph\n    padding: 30,\n    // the padding on fit\n    boundingBox: undefined,\n    // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n    avoidOverlap: true,\n    // prevents node overlap, may overflow boundingBox and radius if not enough space\n    nodeDimensionsIncludeLabels: false,\n    // Excludes the label when calculating node bounding boxes for the layout algorithm\n    spacingFactor: undefined,\n    // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n    radius: undefined,\n    // the radius of the circle\n    startAngle: 3 / 2 * Math.PI,\n    // where nodes start in radians\n    sweep: undefined,\n    // how many radians should be between the first and last node (defaults to full circle)\n    clockwise: true,\n    // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)\n    sort: undefined,\n    // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }\n    animate: false,\n    // whether to transition the node positions\n    animationDuration: 500,\n    // duration of animation in ms if enabled\n    animationEasing: undefined,\n    // easing of animation if enabled\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts\n    ready: undefined,\n    // callback on layoutready\n    stop: undefined,\n    // callback on layoutstop\n    transform: function transform(node, position) {\n      return position;\n    } // transform a given node position. Useful for changing flow direction in discrete layouts \n\n  };\n\n  function CircleLayout(options) {\n    this.options = extend({}, defaults$6, options);\n  }\n\n  CircleLayout.prototype.run = function () {\n    var params = this.options;\n    var options = params;\n    var cy = params.cy;\n    var eles = options.eles;\n    var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;\n    var nodes = eles.nodes().not(':parent');\n\n    if (options.sort) {\n      nodes = nodes.sort(options.sort);\n    }\n\n    var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n      x1: 0,\n      y1: 0,\n      w: cy.width(),\n      h: cy.height()\n    });\n    var center = {\n      x: bb.x1 + bb.w / 2,\n      y: bb.y1 + bb.h / 2\n    };\n    var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / nodes.length : options.sweep;\n    var dTheta = sweep / Math.max(1, nodes.length - 1);\n    var r;\n    var minDistance = 0;\n\n    for (var i = 0; i < nodes.length; i++) {\n      var n = nodes[i];\n      var nbb = n.layoutDimensions(options);\n      var w = nbb.w;\n      var h = nbb.h;\n      minDistance = Math.max(minDistance, w, h);\n    }\n\n    if (number$1(options.radius)) {\n      r = options.radius;\n    } else if (nodes.length <= 1) {\n      r = 0;\n    } else {\n      r = Math.min(bb.h, bb.w) / 2 - minDistance;\n    } // calculate the radius\n\n\n    if (nodes.length > 1 && options.avoidOverlap) {\n      // but only if more than one node (can't overlap)\n      minDistance *= 1.75; // just to have some nice spacing\n\n      var dcos = Math.cos(dTheta) - Math.cos(0);\n      var dsin = Math.sin(dTheta) - Math.sin(0);\n      var rMin = Math.sqrt(minDistance * minDistance / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping\n\n      r = Math.max(rMin, r);\n    }\n\n    var getPos = function getPos(ele, i) {\n      var theta = options.startAngle + i * dTheta * (clockwise ? 1 : -1);\n      var rx = r * Math.cos(theta);\n      var ry = r * Math.sin(theta);\n      var pos = {\n        x: center.x + rx,\n        y: center.y + ry\n      };\n      return pos;\n    };\n\n    eles.nodes().layoutPositions(this, options, getPos);\n    return this; // chaining\n  };\n\n  var defaults$5 = {\n    fit: true,\n    // whether to fit the viewport to the graph\n    padding: 30,\n    // the padding on fit\n    startAngle: 3 / 2 * Math.PI,\n    // where nodes start in radians\n    sweep: undefined,\n    // how many radians should be between the first and last node (defaults to full circle)\n    clockwise: true,\n    // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)\n    equidistant: false,\n    // whether levels have an equal radial distance betwen them, may cause bounding box overflow\n    minNodeSpacing: 10,\n    // min spacing between outside of nodes (used for radius adjustment)\n    boundingBox: undefined,\n    // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n    avoidOverlap: true,\n    // prevents node overlap, may overflow boundingBox if not enough space\n    nodeDimensionsIncludeLabels: false,\n    // Excludes the label when calculating node bounding boxes for the layout algorithm\n    height: undefined,\n    // height of layout area (overrides container height)\n    width: undefined,\n    // width of layout area (overrides container width)\n    spacingFactor: undefined,\n    // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n    concentric: function concentric(node) {\n      // returns numeric value for each node, placing higher nodes in levels towards the centre\n      return node.degree();\n    },\n    levelWidth: function levelWidth(nodes) {\n      // the variation of concentric values in each level\n      return nodes.maxDegree() / 4;\n    },\n    animate: false,\n    // whether to transition the node positions\n    animationDuration: 500,\n    // duration of animation in ms if enabled\n    animationEasing: undefined,\n    // easing of animation if enabled\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts\n    ready: undefined,\n    // callback on layoutready\n    stop: undefined,\n    // callback on layoutstop\n    transform: function transform(node, position) {\n      return position;\n    } // transform a given node position. Useful for changing flow direction in discrete layouts\n\n  };\n\n  function ConcentricLayout(options) {\n    this.options = extend({}, defaults$5, options);\n  }\n\n  ConcentricLayout.prototype.run = function () {\n    var params = this.options;\n    var options = params;\n    var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;\n    var cy = params.cy;\n    var eles = options.eles;\n    var nodes = eles.nodes().not(':parent');\n    var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n      x1: 0,\n      y1: 0,\n      w: cy.width(),\n      h: cy.height()\n    });\n    var center = {\n      x: bb.x1 + bb.w / 2,\n      y: bb.y1 + bb.h / 2\n    };\n    var nodeValues = []; // { node, value }\n\n    var maxNodeSize = 0;\n\n    for (var i = 0; i < nodes.length; i++) {\n      var node = nodes[i];\n      var value = void 0; // calculate the node value\n\n      value = options.concentric(node);\n      nodeValues.push({\n        value: value,\n        node: node\n      }); // for style mapping\n\n      node._private.scratch.concentric = value;\n    } // in case we used the `concentric` in style\n\n\n    nodes.updateStyle(); // calculate max size now based on potentially updated mappers\n\n    for (var _i = 0; _i < nodes.length; _i++) {\n      var _node = nodes[_i];\n\n      var nbb = _node.layoutDimensions(options);\n\n      maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);\n    } // sort node values in descreasing order\n\n\n    nodeValues.sort(function (a, b) {\n      return b.value - a.value;\n    });\n    var levelWidth = options.levelWidth(nodes); // put the values into levels\n\n    var levels = [[]];\n    var currentLevel = levels[0];\n\n    for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {\n      var val = nodeValues[_i2];\n\n      if (currentLevel.length > 0) {\n        var diff = Math.abs(currentLevel[0].value - val.value);\n\n        if (diff >= levelWidth) {\n          currentLevel = [];\n          levels.push(currentLevel);\n        }\n      }\n\n      currentLevel.push(val);\n    } // create positions from levels\n\n\n    var minDist = maxNodeSize + options.minNodeSpacing; // min dist between nodes\n\n    if (!options.avoidOverlap) {\n      // then strictly constrain to bb\n      var firstLvlHasMulti = levels.length > 0 && levels[0].length > 1;\n      var maxR = Math.min(bb.w, bb.h) / 2 - minDist;\n      var rStep = maxR / (levels.length + firstLvlHasMulti ? 1 : 0);\n      minDist = Math.min(minDist, rStep);\n    } // find the metrics for each level\n\n\n    var r = 0;\n\n    for (var _i3 = 0; _i3 < levels.length; _i3++) {\n      var level = levels[_i3];\n      var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / level.length : options.sweep;\n      var dTheta = level.dTheta = sweep / Math.max(1, level.length - 1); // calculate the radius\n\n      if (level.length > 1 && options.avoidOverlap) {\n        // but only if more than one node (can't overlap)\n        var dcos = Math.cos(dTheta) - Math.cos(0);\n        var dsin = Math.sin(dTheta) - Math.sin(0);\n        var rMin = Math.sqrt(minDist * minDist / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping\n\n        r = Math.max(rMin, r);\n      }\n\n      level.r = r;\n      r += minDist;\n    }\n\n    if (options.equidistant) {\n      var rDeltaMax = 0;\n      var _r = 0;\n\n      for (var _i4 = 0; _i4 < levels.length; _i4++) {\n        var _level = levels[_i4];\n        var rDelta = _level.r - _r;\n        rDeltaMax = Math.max(rDeltaMax, rDelta);\n      }\n\n      _r = 0;\n\n      for (var _i5 = 0; _i5 < levels.length; _i5++) {\n        var _level2 = levels[_i5];\n\n        if (_i5 === 0) {\n          _r = _level2.r;\n        }\n\n        _level2.r = _r;\n        _r += rDeltaMax;\n      }\n    } // calculate the node positions\n\n\n    var pos = {}; // id => position\n\n    for (var _i6 = 0; _i6 < levels.length; _i6++) {\n      var _level3 = levels[_i6];\n      var _dTheta = _level3.dTheta;\n      var _r2 = _level3.r;\n\n      for (var j = 0; j < _level3.length; j++) {\n        var _val = _level3[j];\n        var theta = options.startAngle + (clockwise ? 1 : -1) * _dTheta * j;\n        var p = {\n          x: center.x + _r2 * Math.cos(theta),\n          y: center.y + _r2 * Math.sin(theta)\n        };\n        pos[_val.node.id()] = p;\n      }\n    } // position the nodes\n\n\n    eles.nodes().layoutPositions(this, options, function (ele) {\n      var id = ele.id();\n      return pos[id];\n    });\n    return this; // chaining\n  };\n\n  /*\n  The CoSE layout was written by Gerardo Huck.\n  https://www.linkedin.com/in/gerardohuck/\n\n  Based on the following article:\n  http://dl.acm.org/citation.cfm?id=1498047\n\n  Modifications tracked on Github.\n  */\n  var DEBUG;\n  /**\n   * @brief :  default layout options\n   */\n\n  var defaults$4 = {\n    // Called on `layoutready`\n    ready: function ready() {},\n    // Called on `layoutstop`\n    stop: function stop() {},\n    // Whether to animate while running the layout\n    // true : Animate continuously as the layout is running\n    // false : Just show the end result\n    // 'end' : Animate with the end result, from the initial positions to the end positions\n    animate: true,\n    // Easing of the animation for animate:'end'\n    animationEasing: undefined,\n    // The duration of the animation for animate:'end'\n    animationDuration: undefined,\n    // A function that determines whether the node should be animated\n    // All nodes animated by default on animate enabled\n    // Non-animated nodes are positioned immediately when the layout starts\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // The layout animates only after this many milliseconds for animate:true\n    // (prevents flashing on fast runs)\n    animationThreshold: 250,\n    // Number of iterations between consecutive screen positions update\n    refresh: 20,\n    // Whether to fit the network view after when done\n    fit: true,\n    // Padding on fit\n    padding: 30,\n    // Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n    boundingBox: undefined,\n    // Excludes the label when calculating node bounding boxes for the layout algorithm\n    nodeDimensionsIncludeLabels: false,\n    // Randomize the initial positions of the nodes (true) or use existing positions (false)\n    randomize: false,\n    // Extra spacing between components in non-compound graphs\n    componentSpacing: 40,\n    // Node repulsion (non overlapping) multiplier\n    nodeRepulsion: function nodeRepulsion(node) {\n      return 2048;\n    },\n    // Node repulsion (overlapping) multiplier\n    nodeOverlap: 4,\n    // Ideal edge (non nested) length\n    idealEdgeLength: function idealEdgeLength(edge) {\n      return 32;\n    },\n    // Divisor to compute edge forces\n    edgeElasticity: function edgeElasticity(edge) {\n      return 32;\n    },\n    // Nesting factor (multiplier) to compute ideal edge length for nested edges\n    nestingFactor: 1.2,\n    // Gravity force (constant)\n    gravity: 1,\n    // Maximum number of iterations to perform\n    numIter: 1000,\n    // Initial temperature (maximum node displacement)\n    initialTemp: 1000,\n    // Cooling factor (how the temperature is reduced between consecutive iterations\n    coolingFactor: 0.99,\n    // Lower temperature threshold (below this point the layout will end)\n    minTemp: 1.0\n  };\n  /**\n   * @brief       : constructor\n   * @arg options : object containing layout options\n   */\n\n  function CoseLayout(options) {\n    this.options = extend({}, defaults$4, options);\n    this.options.layout = this;\n  }\n  /**\n   * @brief : runs the layout\n   */\n\n\n  CoseLayout.prototype.run = function () {\n    var options = this.options;\n    var cy = options.cy;\n    var layout = this;\n    layout.stopped = false;\n\n    if (options.animate === true || options.animate === false) {\n      layout.emit({\n        type: 'layoutstart',\n        layout: layout\n      });\n    } // Set DEBUG - Global variable\n\n\n    if (true === options.debug) {\n      DEBUG = true;\n    } else {\n      DEBUG = false;\n    } // Initialize layout info\n\n\n    var layoutInfo = createLayoutInfo(cy, layout, options); // Show LayoutInfo contents if debugging\n\n    if (DEBUG) {\n      printLayoutInfo(layoutInfo);\n    } // If required, randomize node positions\n\n\n    if (options.randomize) {\n      randomizePositions(layoutInfo);\n    }\n\n    var startTime = performanceNow();\n\n    var refresh = function refresh() {\n      refreshPositions(layoutInfo, cy, options); // Fit the graph if necessary\n\n      if (true === options.fit) {\n        cy.fit(options.padding);\n      }\n    };\n\n    var mainLoop = function mainLoop(i) {\n      if (layout.stopped || i >= options.numIter) {\n        // logDebug(\"Layout manually stopped. Stopping computation in step \" + i);\n        return false;\n      } // Do one step in the phisical simulation\n\n\n      step(layoutInfo, options); // Update temperature\n\n      layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor; // logDebug(\"New temperature: \" + layoutInfo.temperature);\n\n      if (layoutInfo.temperature < options.minTemp) {\n        // logDebug(\"Temperature drop below minimum threshold. Stopping computation in step \" + i);\n        return false;\n      }\n\n      return true;\n    };\n\n    var done = function done() {\n      if (options.animate === true || options.animate === false) {\n        refresh(); // Layout has finished\n\n        layout.one('layoutstop', options.stop);\n        layout.emit({\n          type: 'layoutstop',\n          layout: layout\n        });\n      } else {\n        var nodes = options.eles.nodes();\n        var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);\n        nodes.layoutPositions(layout, options, getScaledPos);\n      }\n    };\n\n    var i = 0;\n    var loopRet = true;\n\n    if (options.animate === true) {\n      var frame = function frame() {\n        var f = 0;\n\n        while (loopRet && f < options.refresh) {\n          loopRet = mainLoop(i);\n          i++;\n          f++;\n        }\n\n        if (!loopRet) {\n          // it's done\n          separateComponents(layoutInfo, options);\n          done();\n        } else {\n          var now = performanceNow();\n\n          if (now - startTime >= options.animationThreshold) {\n            refresh();\n          }\n\n          requestAnimationFrame(frame);\n        }\n      };\n\n      frame();\n    } else {\n      while (loopRet) {\n        loopRet = mainLoop(i);\n        i++;\n      }\n\n      separateComponents(layoutInfo, options);\n      done();\n    }\n\n    return this; // chaining\n  };\n  /**\n   * @brief : called on continuous layouts to stop them before they finish\n   */\n\n\n  CoseLayout.prototype.stop = function () {\n    this.stopped = true;\n\n    if (this.thread) {\n      this.thread.stop();\n    }\n\n    this.emit('layoutstop');\n    return this; // chaining\n  };\n\n  CoseLayout.prototype.destroy = function () {\n    if (this.thread) {\n      this.thread.stop();\n    }\n\n    return this; // chaining\n  };\n  /**\n   * @brief     : Creates an object which is contains all the data\n   *              used in the layout process\n   * @arg cy    : cytoscape.js object\n   * @return    : layoutInfo object initialized\n   */\n\n\n  var createLayoutInfo = function createLayoutInfo(cy, layout, options) {\n    // Shortcut\n    var edges = options.eles.edges();\n    var nodes = options.eles.nodes();\n    var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n      x1: 0,\n      y1: 0,\n      w: cy.width(),\n      h: cy.height()\n    });\n    var layoutInfo = {\n      isCompound: cy.hasCompoundNodes(),\n      layoutNodes: [],\n      idToIndex: {},\n      nodeSize: nodes.size(),\n      graphSet: [],\n      indexToGraph: [],\n      layoutEdges: [],\n      edgeSize: edges.size(),\n      temperature: options.initialTemp,\n      clientWidth: bb.w,\n      clientHeight: bb.h,\n      boundingBox: bb\n    };\n    var components = options.eles.components();\n    var id2cmptId = {};\n\n    for (var i = 0; i < components.length; i++) {\n      var component = components[i];\n\n      for (var j = 0; j < component.length; j++) {\n        var node = component[j];\n        id2cmptId[node.id()] = i;\n      }\n    } // Iterate over all nodes, creating layout nodes\n\n\n    for (var i = 0; i < layoutInfo.nodeSize; i++) {\n      var n = nodes[i];\n      var nbb = n.layoutDimensions(options);\n      var tempNode = {};\n      tempNode.isLocked = n.locked();\n      tempNode.id = n.data('id');\n      tempNode.parentId = n.data('parent');\n      tempNode.cmptId = id2cmptId[n.id()];\n      tempNode.children = [];\n      tempNode.positionX = n.position('x');\n      tempNode.positionY = n.position('y');\n      tempNode.offsetX = 0;\n      tempNode.offsetY = 0;\n      tempNode.height = nbb.w;\n      tempNode.width = nbb.h;\n      tempNode.maxX = tempNode.positionX + tempNode.width / 2;\n      tempNode.minX = tempNode.positionX - tempNode.width / 2;\n      tempNode.maxY = tempNode.positionY + tempNode.height / 2;\n      tempNode.minY = tempNode.positionY - tempNode.height / 2;\n      tempNode.padLeft = parseFloat(n.style('padding'));\n      tempNode.padRight = parseFloat(n.style('padding'));\n      tempNode.padTop = parseFloat(n.style('padding'));\n      tempNode.padBottom = parseFloat(n.style('padding')); // forces\n\n      tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion; // Add new node\n\n      layoutInfo.layoutNodes.push(tempNode); // Add entry to id-index map\n\n      layoutInfo.idToIndex[tempNode.id] = i;\n    } // Inline implementation of a queue, used for traversing the graph in BFS order\n\n\n    var queue = [];\n    var start = 0; // Points to the start the queue\n\n    var end = -1; // Points to the end of the queue\n\n    var tempGraph = []; // Second pass to add child information and\n    // initialize queue for hierarchical traversal\n\n    for (var i = 0; i < layoutInfo.nodeSize; i++) {\n      var n = layoutInfo.layoutNodes[i];\n      var p_id = n.parentId; // Check if node n has a parent node\n\n      if (null != p_id) {\n        // Add node Id to parent's list of children\n        layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);\n      } else {\n        // If a node doesn't have a parent, then it's in the root graph\n        queue[++end] = n.id;\n        tempGraph.push(n.id);\n      }\n    } // Add root graph to graphSet\n\n\n    layoutInfo.graphSet.push(tempGraph); // Traverse the graph, level by level,\n\n    while (start <= end) {\n      // Get the node to visit and remove it from queue\n      var node_id = queue[start++];\n      var node_ix = layoutInfo.idToIndex[node_id];\n      var node = layoutInfo.layoutNodes[node_ix];\n      var children = node.children;\n\n      if (children.length > 0) {\n        // Add children nodes as a new graph to graph set\n        layoutInfo.graphSet.push(children); // Add children to que queue to be visited\n\n        for (var i = 0; i < children.length; i++) {\n          queue[++end] = children[i];\n        }\n      }\n    } // Create indexToGraph map\n\n\n    for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n      var graph = layoutInfo.graphSet[i];\n\n      for (var j = 0; j < graph.length; j++) {\n        var index = layoutInfo.idToIndex[graph[j]];\n        layoutInfo.indexToGraph[index] = i;\n      }\n    } // Iterate over all edges, creating Layout Edges\n\n\n    for (var i = 0; i < layoutInfo.edgeSize; i++) {\n      var e = edges[i];\n      var tempEdge = {};\n      tempEdge.id = e.data('id');\n      tempEdge.sourceId = e.data('source');\n      tempEdge.targetId = e.data('target'); // Compute ideal length\n\n      var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;\n      var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity; // Check if it's an inter graph edge\n\n      var sourceIx = layoutInfo.idToIndex[tempEdge.sourceId];\n      var targetIx = layoutInfo.idToIndex[tempEdge.targetId];\n      var sourceGraph = layoutInfo.indexToGraph[sourceIx];\n      var targetGraph = layoutInfo.indexToGraph[targetIx];\n\n      if (sourceGraph != targetGraph) {\n        // Find lowest common graph ancestor\n        var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo); // Compute sum of node depths, relative to lca graph\n\n        var lcaGraph = layoutInfo.graphSet[lca];\n        var depth = 0; // Source depth\n\n        var tempNode = layoutInfo.layoutNodes[sourceIx];\n\n        while (-1 === lcaGraph.indexOf(tempNode.id)) {\n          tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];\n          depth++;\n        } // Target depth\n\n\n        tempNode = layoutInfo.layoutNodes[targetIx];\n\n        while (-1 === lcaGraph.indexOf(tempNode.id)) {\n          tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];\n          depth++;\n        } // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +\n        //  \". Index: \" + lca + \" Contents: \" + lcaGraph.toString() +\n        //  \". Depth: \" + depth);\n        // Update idealLength\n\n\n        idealLength *= depth * options.nestingFactor;\n      }\n\n      tempEdge.idealLength = idealLength;\n      tempEdge.elasticity = elasticity;\n      layoutInfo.layoutEdges.push(tempEdge);\n    } // Finally, return layoutInfo object\n\n\n    return layoutInfo;\n  };\n  /**\n   * @brief : This function finds the index of the lowest common\n   *          graph ancestor between 2 nodes in the subtree\n   *          (from the graph hierarchy induced tree) whose\n   *          root is graphIx\n   *\n   * @arg node1: node1's ID\n   * @arg node2: node2's ID\n   * @arg layoutInfo: layoutInfo object\n   *\n   */\n\n\n  var findLCA = function findLCA(node1, node2, layoutInfo) {\n    // Find their common ancester, starting from the root graph\n    var res = findLCA_aux(node1, node2, 0, layoutInfo);\n\n    if (2 > res.count) {\n      // If aux function couldn't find the common ancester,\n      // then it is the root graph\n      return 0;\n    } else {\n      return res.graph;\n    }\n  };\n  /**\n   * @brief          : Auxiliary function used for LCA computation\n   *\n   * @arg node1      : node1's ID\n   * @arg node2      : node2's ID\n   * @arg graphIx    : subgraph index\n   * @arg layoutInfo : layoutInfo object\n   *\n   * @return         : object of the form {count: X, graph: Y}, where:\n   *                   X is the number of ancestors (max: 2) found in\n   *                   graphIx (and it's subgraphs),\n   *                   Y is the graph index of the lowest graph containing\n   *                   all X nodes\n   */\n\n\n  var findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {\n    var graph = layoutInfo.graphSet[graphIx]; // If both nodes belongs to graphIx\n\n    if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {\n      return {\n        count: 2,\n        graph: graphIx\n      };\n    } // Make recursive calls for all subgraphs\n\n\n    var c = 0;\n\n    for (var i = 0; i < graph.length; i++) {\n      var nodeId = graph[i];\n      var nodeIx = layoutInfo.idToIndex[nodeId];\n      var children = layoutInfo.layoutNodes[nodeIx].children; // If the node has no child, skip it\n\n      if (0 === children.length) {\n        continue;\n      }\n\n      var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];\n      var result = findLCA_aux(node1, node2, childGraphIx, layoutInfo);\n\n      if (0 === result.count) {\n        // Neither node1 nor node2 are present in this subgraph\n        continue;\n      } else if (1 === result.count) {\n        // One of (node1, node2) is present in this subgraph\n        c++;\n\n        if (2 === c) {\n          // We've already found both nodes, no need to keep searching\n          break;\n        }\n      } else {\n        // Both nodes are present in this subgraph\n        return result;\n      }\n    }\n\n    return {\n      count: c,\n      graph: graphIx\n    };\n  };\n  /**\n   * @brief: printsLayoutInfo into js console\n   *         Only used for debbuging\n   */\n\n\nvar printLayoutInfo; \n  /**\n   * @brief : Randomizes the position of all nodes\n   */\n\n\n  var randomizePositions = function randomizePositions(layoutInfo, cy) {\n    var width = layoutInfo.clientWidth;\n    var height = layoutInfo.clientHeight;\n\n    for (var i = 0; i < layoutInfo.nodeSize; i++) {\n      var n = layoutInfo.layoutNodes[i]; // No need to randomize compound nodes or locked nodes\n\n      if (0 === n.children.length && !n.isLocked) {\n        n.positionX = Math.random() * width;\n        n.positionY = Math.random() * height;\n      }\n    }\n  };\n\n  var getScaleInBoundsFn = function getScaleInBoundsFn(layoutInfo, options, nodes) {\n    var bb = layoutInfo.boundingBox;\n    var coseBB = {\n      x1: Infinity,\n      x2: -Infinity,\n      y1: Infinity,\n      y2: -Infinity\n    };\n\n    if (options.boundingBox) {\n      nodes.forEach(function (node) {\n        var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[node.data('id')]];\n        coseBB.x1 = Math.min(coseBB.x1, lnode.positionX);\n        coseBB.x2 = Math.max(coseBB.x2, lnode.positionX);\n        coseBB.y1 = Math.min(coseBB.y1, lnode.positionY);\n        coseBB.y2 = Math.max(coseBB.y2, lnode.positionY);\n      });\n      coseBB.w = coseBB.x2 - coseBB.x1;\n      coseBB.h = coseBB.y2 - coseBB.y1;\n    }\n\n    return function (ele, i) {\n      var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];\n\n      if (options.boundingBox) {\n        // then add extra bounding box constraint\n        var pctX = (lnode.positionX - coseBB.x1) / coseBB.w;\n        var pctY = (lnode.positionY - coseBB.y1) / coseBB.h;\n        return {\n          x: bb.x1 + pctX * bb.w,\n          y: bb.y1 + pctY * bb.h\n        };\n      } else {\n        return {\n          x: lnode.positionX,\n          y: lnode.positionY\n        };\n      }\n    };\n  };\n  /**\n   * @brief          : Updates the positions of nodes in the network\n   * @arg layoutInfo : LayoutInfo object\n   * @arg cy         : Cytoscape object\n   * @arg options    : Layout options\n   */\n\n\n  var refreshPositions = function refreshPositions(layoutInfo, cy, options) {\n    // var s = 'Refreshing positions';\n    // logDebug(s);\n    var layout = options.layout;\n    var nodes = options.eles.nodes();\n    var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);\n    nodes.positions(getScaledPos); // Trigger layoutReady only on first call\n\n    if (true !== layoutInfo.ready) {\n      // s = 'Triggering layoutready';\n      // logDebug(s);\n      layoutInfo.ready = true;\n      layout.one('layoutready', options.ready);\n      layout.emit({\n        type: 'layoutready',\n        layout: this\n      });\n    }\n  };\n  /**\n   * @brief : Logs a debug message in JS console, if DEBUG is ON\n   */\n  // var logDebug = function(text) {\n  //   if (DEBUG) {\n  //     console.debug(text);\n  //   }\n  // };\n\n  /**\n   * @brief          : Performs one iteration of the physical simulation\n   * @arg layoutInfo : LayoutInfo object already initialized\n   * @arg cy         : Cytoscape object\n   * @arg options    : Layout options\n   */\n\n\n  var step = function step(layoutInfo, options, _step) {\n    // var s = \"\\n\\n###############################\";\n    // s += \"\\nSTEP: \" + step;\n    // s += \"\\n###############################\\n\";\n    // logDebug(s);\n    // Calculate node repulsions\n    calculateNodeForces(layoutInfo, options); // Calculate edge forces\n\n    calculateEdgeForces(layoutInfo); // Calculate gravity forces\n\n    calculateGravityForces(layoutInfo, options); // Propagate forces from parent to child\n\n    propagateForces(layoutInfo); // Update positions based on calculated forces\n\n    updatePositions(layoutInfo);\n  };\n  /**\n   * @brief : Computes the node repulsion forces\n   */\n\n\n  var calculateNodeForces = function calculateNodeForces(layoutInfo, options) {\n    // Go through each of the graphs in graphSet\n    // Nodes only repel each other if they belong to the same graph\n    // var s = 'calculateNodeForces';\n    // logDebug(s);\n    for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n      var graph = layoutInfo.graphSet[i];\n      var numNodes = graph.length; // s = \"Set: \" + graph.toString();\n      // logDebug(s);\n      // Now get all the pairs of nodes\n      // Only get each pair once, (A, B) = (B, A)\n\n      for (var j = 0; j < numNodes; j++) {\n        var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];\n\n        for (var k = j + 1; k < numNodes; k++) {\n          var node2 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[k]]];\n          nodeRepulsion(node1, node2, layoutInfo, options);\n        }\n      }\n    }\n  };\n\n  var randomDistance = function randomDistance(max) {\n    return -max + 2 * max * Math.random();\n  };\n  /**\n   * @brief : Compute the node repulsion forces between a pair of nodes\n   */\n\n\n  var nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {\n    // var s = \"Node repulsion. Node1: \" + node1.id + \" Node2: \" + node2.id;\n    var cmptId1 = node1.cmptId;\n    var cmptId2 = node2.cmptId;\n\n    if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {\n      return;\n    } // Get direction of line connecting both node centers\n\n\n    var directionX = node2.positionX - node1.positionX;\n    var directionY = node2.positionY - node1.positionY;\n    var maxRandDist = 1; // s += \"\\ndirectionX: \" + directionX + \", directionY: \" + directionY;\n    // If both centers are the same, apply a random force\n\n    if (0 === directionX && 0 === directionY) {\n      directionX = randomDistance(maxRandDist);\n      directionY = randomDistance(maxRandDist);\n    }\n\n    var overlap = nodesOverlap(node1, node2, directionX, directionY);\n\n    if (overlap > 0) {\n      // s += \"\\nNodes DO overlap.\";\n      // s += \"\\nOverlap: \" + overlap;\n      // If nodes overlap, repulsion force is proportional\n      // to the overlap\n      var force = options.nodeOverlap * overlap; // Compute the module and components of the force vector\n\n      var distance = Math.sqrt(directionX * directionX + directionY * directionY); // s += \"\\nDistance: \" + distance;\n\n      var forceX = force * directionX / distance;\n      var forceY = force * directionY / distance;\n    } else {\n      // s += \"\\nNodes do NOT overlap.\";\n      // If there's no overlap, force is inversely proportional\n      // to squared distance\n      // Get clipping points for both nodes\n      var point1 = findClippingPoint(node1, directionX, directionY);\n      var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY); // Use clipping points to compute distance\n\n      var distanceX = point2.x - point1.x;\n      var distanceY = point2.y - point1.y;\n      var distanceSqr = distanceX * distanceX + distanceY * distanceY;\n      var distance = Math.sqrt(distanceSqr); // s += \"\\nDistance: \" + distance;\n      // Compute the module and components of the force vector\n\n      var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;\n      var forceX = force * distanceX / distance;\n      var forceY = force * distanceY / distance;\n    } // Apply force\n\n\n    if (!node1.isLocked) {\n      node1.offsetX -= forceX;\n      node1.offsetY -= forceY;\n    }\n\n    if (!node2.isLocked) {\n      node2.offsetX += forceX;\n      node2.offsetY += forceY;\n    } // s += \"\\nForceX: \" + forceX + \" ForceY: \" + forceY;\n    // logDebug(s);\n\n\n    return;\n  };\n  /**\n   * @brief  : Determines whether two nodes overlap or not\n   * @return : Amount of overlapping (0 => no overlap)\n   */\n\n\n  var nodesOverlap = function nodesOverlap(node1, node2, dX, dY) {\n    if (dX > 0) {\n      var overlapX = node1.maxX - node2.minX;\n    } else {\n      var overlapX = node2.maxX - node1.minX;\n    }\n\n    if (dY > 0) {\n      var overlapY = node1.maxY - node2.minY;\n    } else {\n      var overlapY = node2.maxY - node1.minY;\n    }\n\n    if (overlapX >= 0 && overlapY >= 0) {\n      return Math.sqrt(overlapX * overlapX + overlapY * overlapY);\n    } else {\n      return 0;\n    }\n  };\n  /**\n   * @brief : Finds the point in which an edge (direction dX, dY) intersects\n   *          the rectangular bounding box of it's source/target node\n   */\n\n\n  var findClippingPoint = function findClippingPoint(node, dX, dY) {\n    // Shorcuts\n    var X = node.positionX;\n    var Y = node.positionY;\n    var H = node.height || 1;\n    var W = node.width || 1;\n    var dirSlope = dY / dX;\n    var nodeSlope = H / W; // var s = 'Computing clipping point of node ' + node.id +\n    //   \" . Height:  \" + H + \", Width: \" + W +\n    //   \"\\nDirection \" + dX + \", \" + dY;\n    //\n    // Compute intersection\n\n    var res = {}; // Case: Vertical direction (up)\n\n    if (0 === dX && 0 < dY) {\n      res.x = X; // s += \"\\nUp direction\";\n\n      res.y = Y + H / 2;\n      return res;\n    } // Case: Vertical direction (down)\n\n\n    if (0 === dX && 0 > dY) {\n      res.x = X;\n      res.y = Y + H / 2; // s += \"\\nDown direction\";\n\n      return res;\n    } // Case: Intersects the right border\n\n\n    if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {\n      res.x = X + W / 2;\n      res.y = Y + W * dY / 2 / dX; // s += \"\\nRightborder\";\n\n      return res;\n    } // Case: Intersects the left border\n\n\n    if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {\n      res.x = X - W / 2;\n      res.y = Y - W * dY / 2 / dX; // s += \"\\nLeftborder\";\n\n      return res;\n    } // Case: Intersects the top border\n\n\n    if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {\n      res.x = X + H * dX / 2 / dY;\n      res.y = Y + H / 2; // s += \"\\nTop border\";\n\n      return res;\n    } // Case: Intersects the bottom border\n\n\n    if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {\n      res.x = X - H * dX / 2 / dY;\n      res.y = Y - H / 2; // s += \"\\nBottom border\";\n\n      return res;\n    } // s += \"\\nClipping point found at \" + res.x + \", \" + res.y;\n    // logDebug(s);\n\n\n    return res;\n  };\n  /**\n   * @brief : Calculates all edge forces\n   */\n\n\n  var calculateEdgeForces = function calculateEdgeForces(layoutInfo, options) {\n    // Iterate over all edges\n    for (var i = 0; i < layoutInfo.edgeSize; i++) {\n      // Get edge, source & target nodes\n      var edge = layoutInfo.layoutEdges[i];\n      var sourceIx = layoutInfo.idToIndex[edge.sourceId];\n      var source = layoutInfo.layoutNodes[sourceIx];\n      var targetIx = layoutInfo.idToIndex[edge.targetId];\n      var target = layoutInfo.layoutNodes[targetIx]; // Get direction of line connecting both node centers\n\n      var directionX = target.positionX - source.positionX;\n      var directionY = target.positionY - source.positionY; // If both centers are the same, do nothing.\n      // A random force has already been applied as node repulsion\n\n      if (0 === directionX && 0 === directionY) {\n        continue;\n      } // Get clipping points for both nodes\n\n\n      var point1 = findClippingPoint(source, directionX, directionY);\n      var point2 = findClippingPoint(target, -1 * directionX, -1 * directionY);\n      var lx = point2.x - point1.x;\n      var ly = point2.y - point1.y;\n      var l = Math.sqrt(lx * lx + ly * ly);\n      var force = Math.pow(edge.idealLength - l, 2) / edge.elasticity;\n\n      if (0 !== l) {\n        var forceX = force * lx / l;\n        var forceY = force * ly / l;\n      } else {\n        var forceX = 0;\n        var forceY = 0;\n      } // Add this force to target and source nodes\n\n\n      if (!source.isLocked) {\n        source.offsetX += forceX;\n        source.offsetY += forceY;\n      }\n\n      if (!target.isLocked) {\n        target.offsetX -= forceX;\n        target.offsetY -= forceY;\n      } // var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;\n      // s += \"\\nDistance: \" + l + \" Force: (\" + forceX + \", \" + forceY + \")\";\n      // logDebug(s);\n\n    }\n  };\n  /**\n   * @brief : Computes gravity forces for all nodes\n   */\n\n\n  var calculateGravityForces = function calculateGravityForces(layoutInfo, options) {\n    if (options.gravity === 0) {\n      return;\n    }\n\n    var distThreshold = 1; // var s = 'calculateGravityForces';\n    // logDebug(s);\n\n    for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n      var graph = layoutInfo.graphSet[i];\n      var numNodes = graph.length; // s = \"Set: \" + graph.toString();\n      // logDebug(s);\n      // Compute graph center\n\n      if (0 === i) {\n        var centerX = layoutInfo.clientHeight / 2;\n        var centerY = layoutInfo.clientWidth / 2;\n      } else {\n        // Get Parent node for this graph, and use its position as center\n        var temp = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[0]]];\n        var parent = layoutInfo.layoutNodes[layoutInfo.idToIndex[temp.parentId]];\n        var centerX = parent.positionX;\n        var centerY = parent.positionY;\n      } // s = \"Center found at: \" + centerX + \", \" + centerY;\n      // logDebug(s);\n      // Apply force to all nodes in graph\n\n\n      for (var j = 0; j < numNodes; j++) {\n        var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]]; // s = \"Node: \" + node.id;\n\n        if (node.isLocked) {\n          continue;\n        }\n\n        var dx = centerX - node.positionX;\n        var dy = centerY - node.positionY;\n        var d = Math.sqrt(dx * dx + dy * dy);\n\n        if (d > distThreshold) {\n          var fx = options.gravity * dx / d;\n          var fy = options.gravity * dy / d;\n          node.offsetX += fx;\n          node.offsetY += fy; // s += \": Applied force: \" + fx + \", \" + fy;\n        } // logDebug(s);\n\n      }\n    }\n  };\n  /**\n   * @brief          : This function propagates the existing offsets from\n   *                   parent nodes to its descendents.\n   * @arg layoutInfo : layoutInfo Object\n   * @arg cy         : cytoscape Object\n   * @arg options    : Layout options\n   */\n\n\n  var propagateForces = function propagateForces(layoutInfo, options) {\n    // Inline implementation of a queue, used for traversing the graph in BFS order\n    var queue = [];\n    var start = 0; // Points to the start the queue\n\n    var end = -1; // Points to the end of the queue\n    // logDebug('propagateForces');\n    // Start by visiting the nodes in the root graph\n\n    queue.push.apply(queue, layoutInfo.graphSet[0]);\n    end += layoutInfo.graphSet[0].length; // Traverse the graph, level by level,\n\n    while (start <= end) {\n      // Get the node to visit and remove it from queue\n      var nodeId = queue[start++];\n      var nodeIndex = layoutInfo.idToIndex[nodeId];\n      var node = layoutInfo.layoutNodes[nodeIndex];\n      var children = node.children; // We only need to process the node if it's compound\n\n      if (0 < children.length && !node.isLocked) {\n        var offX = node.offsetX;\n        var offY = node.offsetY; // var s = \"Propagating offset from parent node : \" + node.id +\n        //   \". OffsetX: \" + offX + \". OffsetY: \" + offY;\n        // s += \"\\n Children: \" + children.toString();\n        // logDebug(s);\n\n        for (var i = 0; i < children.length; i++) {\n          var childNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[children[i]]]; // Propagate offset\n\n          childNode.offsetX += offX;\n          childNode.offsetY += offY; // Add children to queue to be visited\n\n          queue[++end] = children[i];\n        } // Reset parent offsets\n\n\n        node.offsetX = 0;\n        node.offsetY = 0;\n      }\n    }\n  };\n  /**\n   * @brief : Updates the layout model positions, based on\n   *          the accumulated forces\n   */\n\n\n  var updatePositions = function updatePositions(layoutInfo, options) {\n    // var s = 'Updating positions';\n    // logDebug(s);\n    // Reset boundaries for compound nodes\n    for (var i = 0; i < layoutInfo.nodeSize; i++) {\n      var n = layoutInfo.layoutNodes[i];\n\n      if (0 < n.children.length) {\n        // logDebug(\"Resetting boundaries of compound node: \" + n.id);\n        n.maxX = undefined;\n        n.minX = undefined;\n        n.maxY = undefined;\n        n.minY = undefined;\n      }\n    }\n\n    for (var i = 0; i < layoutInfo.nodeSize; i++) {\n      var n = layoutInfo.layoutNodes[i];\n\n      if (0 < n.children.length || n.isLocked) {\n        // No need to set compound or locked node position\n        // logDebug(\"Skipping position update of node: \" + n.id);\n        continue;\n      } // s = \"Node: \" + n.id + \" Previous position: (\" +\n      // n.positionX + \", \" + n.positionY + \").\";\n      // Limit displacement in order to improve stability\n\n\n      var tempForce = limitForce(n.offsetX, n.offsetY, layoutInfo.temperature);\n      n.positionX += tempForce.x;\n      n.positionY += tempForce.y;\n      n.offsetX = 0;\n      n.offsetY = 0;\n      n.minX = n.positionX - n.width;\n      n.maxX = n.positionX + n.width;\n      n.minY = n.positionY - n.height;\n      n.maxY = n.positionY + n.height; // s += \" New Position: (\" + n.positionX + \", \" + n.positionY + \").\";\n      // logDebug(s);\n      // Update ancestry boudaries\n\n      updateAncestryBoundaries(n, layoutInfo);\n    } // Update size, position of compund nodes\n\n\n    for (var i = 0; i < layoutInfo.nodeSize; i++) {\n      var n = layoutInfo.layoutNodes[i];\n\n      if (0 < n.children.length && !n.isLocked) {\n        n.positionX = (n.maxX + n.minX) / 2;\n        n.positionY = (n.maxY + n.minY) / 2;\n        n.width = n.maxX - n.minX;\n        n.height = n.maxY - n.minY; // s = \"Updating position, size of compound node \" + n.id;\n        // s += \"\\nPositionX: \" + n.positionX + \", PositionY: \" + n.positionY;\n        // s += \"\\nWidth: \" + n.width + \", Height: \" + n.height;\n        // logDebug(s);\n      }\n    }\n  };\n  /**\n   * @brief : Limits a force (forceX, forceY) to be not\n   *          greater (in modulo) than max.\n   8          Preserves force direction.\n    */\n\n\n  var limitForce = function limitForce(forceX, forceY, max) {\n    // var s = \"Limiting force: (\" + forceX + \", \" + forceY + \"). Max: \" + max;\n    var force = Math.sqrt(forceX * forceX + forceY * forceY);\n\n    if (force > max) {\n      var res = {\n        x: max * forceX / force,\n        y: max * forceY / force\n      };\n    } else {\n      var res = {\n        x: forceX,\n        y: forceY\n      };\n    } // s += \".\\nResult: (\" + res.x + \", \" + res.y + \")\";\n    // logDebug(s);\n\n\n    return res;\n  };\n  /**\n   * @brief : Function used for keeping track of compound node\n   *          sizes, since they should bound all their subnodes.\n   */\n\n\n  var updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {\n    // var s = \"Propagating new position/size of node \" + node.id;\n    var parentId = node.parentId;\n\n    if (null == parentId) {\n      // If there's no parent, we are done\n      // s += \". No parent node.\";\n      // logDebug(s);\n      return;\n    } // Get Parent Node\n\n\n    var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];\n    var flag = false; // MaxX\n\n    if (null == p.maxX || node.maxX + p.padRight > p.maxX) {\n      p.maxX = node.maxX + p.padRight;\n      flag = true; // s += \"\\nNew maxX for parent node \" + p.id + \": \" + p.maxX;\n    } // MinX\n\n\n    if (null == p.minX || node.minX - p.padLeft < p.minX) {\n      p.minX = node.minX - p.padLeft;\n      flag = true; // s += \"\\nNew minX for parent node \" + p.id + \": \" + p.minX;\n    } // MaxY\n\n\n    if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {\n      p.maxY = node.maxY + p.padBottom;\n      flag = true; // s += \"\\nNew maxY for parent node \" + p.id + \": \" + p.maxY;\n    } // MinY\n\n\n    if (null == p.minY || node.minY - p.padTop < p.minY) {\n      p.minY = node.minY - p.padTop;\n      flag = true; // s += \"\\nNew minY for parent node \" + p.id + \": \" + p.minY;\n    } // If updated boundaries, propagate changes upward\n\n\n    if (flag) {\n      // logDebug(s);\n      return updateAncestryBoundaries(p, layoutInfo);\n    } // s += \". No changes in boundaries/position of parent node \" + p.id;\n    // logDebug(s);\n\n\n    return;\n  };\n\n  var separateComponents = function separateComponents(layoutInfo, options) {\n    var nodes = layoutInfo.layoutNodes;\n    var components = [];\n\n    for (var i = 0; i < nodes.length; i++) {\n      var node = nodes[i];\n      var cid = node.cmptId;\n      var component = components[cid] = components[cid] || [];\n      component.push(node);\n    }\n\n    var totalA = 0;\n\n    for (var i = 0; i < components.length; i++) {\n      var c = components[i];\n\n      if (!c) {\n        continue;\n      }\n\n      c.x1 = Infinity;\n      c.x2 = -Infinity;\n      c.y1 = Infinity;\n      c.y2 = -Infinity;\n\n      for (var j = 0; j < c.length; j++) {\n        var n = c[j];\n        c.x1 = Math.min(c.x1, n.positionX - n.width / 2);\n        c.x2 = Math.max(c.x2, n.positionX + n.width / 2);\n        c.y1 = Math.min(c.y1, n.positionY - n.height / 2);\n        c.y2 = Math.max(c.y2, n.positionY + n.height / 2);\n      }\n\n      c.w = c.x2 - c.x1;\n      c.h = c.y2 - c.y1;\n      totalA += c.w * c.h;\n    }\n\n    components.sort(function (c1, c2) {\n      return c2.w * c2.h - c1.w * c1.h;\n    });\n    var x = 0;\n    var y = 0;\n    var usedW = 0;\n    var rowH = 0;\n    var maxRowW = Math.sqrt(totalA) * layoutInfo.clientWidth / layoutInfo.clientHeight;\n\n    for (var i = 0; i < components.length; i++) {\n      var c = components[i];\n\n      if (!c) {\n        continue;\n      }\n\n      for (var j = 0; j < c.length; j++) {\n        var n = c[j];\n\n        if (!n.isLocked) {\n          n.positionX += x - c.x1;\n          n.positionY += y - c.y1;\n        }\n      }\n\n      x += c.w + options.componentSpacing;\n      usedW += c.w + options.componentSpacing;\n      rowH = Math.max(rowH, c.h);\n\n      if (usedW > maxRowW) {\n        y += rowH + options.componentSpacing;\n        x = 0;\n        usedW = 0;\n        rowH = 0;\n      }\n    }\n  };\n\n  var defaults$3 = {\n    fit: true,\n    // whether to fit the viewport to the graph\n    padding: 30,\n    // padding used on fit\n    boundingBox: undefined,\n    // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n    avoidOverlap: true,\n    // prevents node overlap, may overflow boundingBox if not enough space\n    avoidOverlapPadding: 10,\n    // extra spacing around nodes when avoidOverlap: true\n    nodeDimensionsIncludeLabels: false,\n    // Excludes the label when calculating node bounding boxes for the layout algorithm\n    spacingFactor: undefined,\n    // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\n    condense: false,\n    // uses all available space on false, uses minimal space on true\n    rows: undefined,\n    // force num of rows in the grid\n    cols: undefined,\n    // force num of columns in the grid\n    position: function position(node) {},\n    // returns { row, col } for element\n    sort: undefined,\n    // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }\n    animate: false,\n    // whether to transition the node positions\n    animationDuration: 500,\n    // duration of animation in ms if enabled\n    animationEasing: undefined,\n    // easing of animation if enabled\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts\n    ready: undefined,\n    // callback on layoutready\n    stop: undefined,\n    // callback on layoutstop\n    transform: function transform(node, position) {\n      return position;\n    } // transform a given node position. Useful for changing flow direction in discrete layouts \n\n  };\n\n  function GridLayout(options) {\n    this.options = extend({}, defaults$3, options);\n  }\n\n  GridLayout.prototype.run = function () {\n    var params = this.options;\n    var options = params;\n    var cy = params.cy;\n    var eles = options.eles;\n    var nodes = eles.nodes().not(':parent');\n\n    if (options.sort) {\n      nodes = nodes.sort(options.sort);\n    }\n\n    var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n      x1: 0,\n      y1: 0,\n      w: cy.width(),\n      h: cy.height()\n    });\n\n    if (bb.h === 0 || bb.w === 0) {\n      eles.nodes().layoutPositions(this, options, function (ele) {\n        return {\n          x: bb.x1,\n          y: bb.y1\n        };\n      });\n    } else {\n      // width/height * splits^2 = cells where splits is number of times to split width\n      var cells = nodes.size();\n      var splits = Math.sqrt(cells * bb.h / bb.w);\n      var rows = Math.round(splits);\n      var cols = Math.round(bb.w / bb.h * splits);\n\n      var small = function small(val) {\n        if (val == null) {\n          return Math.min(rows, cols);\n        } else {\n          var min = Math.min(rows, cols);\n\n          if (min == rows) {\n            rows = val;\n          } else {\n            cols = val;\n          }\n        }\n      };\n\n      var large = function large(val) {\n        if (val == null) {\n          return Math.max(rows, cols);\n        } else {\n          var max = Math.max(rows, cols);\n\n          if (max == rows) {\n            rows = val;\n          } else {\n            cols = val;\n          }\n        }\n      };\n\n      var oRows = options.rows;\n      var oCols = options.cols != null ? options.cols : options.columns; // if rows or columns were set in options, use those values\n\n      if (oRows != null && oCols != null) {\n        rows = oRows;\n        cols = oCols;\n      } else if (oRows != null && oCols == null) {\n        rows = oRows;\n        cols = Math.ceil(cells / rows);\n      } else if (oRows == null && oCols != null) {\n        cols = oCols;\n        rows = Math.ceil(cells / cols);\n      } // otherwise use the automatic values and adjust accordingly\n      // if rounding was up, see if we can reduce rows or columns\n      else if (cols * rows > cells) {\n        var sm = small();\n        var lg = large(); // reducing the small side takes away the most cells, so try it first\n\n        if ((sm - 1) * lg >= cells) {\n          small(sm - 1);\n        } else if ((lg - 1) * sm >= cells) {\n          large(lg - 1);\n        }\n      } else {\n        // if rounding was too low, add rows or columns\n        while (cols * rows < cells) {\n          var _sm = small();\n\n          var _lg = large(); // try to add to larger side first (adds less in multiplication)\n\n\n          if ((_lg + 1) * _sm >= cells) {\n            large(_lg + 1);\n          } else {\n            small(_sm + 1);\n          }\n        }\n      }\n\n      var cellWidth = bb.w / cols;\n      var cellHeight = bb.h / rows;\n\n      if (options.condense) {\n        cellWidth = 0;\n        cellHeight = 0;\n      }\n\n      if (options.avoidOverlap) {\n        for (var i = 0; i < nodes.length; i++) {\n          var node = nodes[i];\n          var pos = node._private.position;\n\n          if (pos.x == null || pos.y == null) {\n            // for bb\n            pos.x = 0;\n            pos.y = 0;\n          }\n\n          var nbb = node.layoutDimensions(options);\n          var p = options.avoidOverlapPadding;\n          var w = nbb.w + p;\n          var h = nbb.h + p;\n          cellWidth = Math.max(cellWidth, w);\n          cellHeight = Math.max(cellHeight, h);\n        }\n      }\n\n      var cellUsed = {}; // e.g. 'c-0-2' => true\n\n      var used = function used(row, col) {\n        return cellUsed['c-' + row + '-' + col] ? true : false;\n      };\n\n      var use = function use(row, col) {\n        cellUsed['c-' + row + '-' + col] = true;\n      }; // to keep track of current cell position\n\n\n      var row = 0;\n      var col = 0;\n\n      var moveToNextCell = function moveToNextCell() {\n        col++;\n\n        if (col >= cols) {\n          col = 0;\n          row++;\n        }\n      }; // get a cache of all the manual positions\n\n\n      var id2manPos = {};\n\n      for (var _i = 0; _i < nodes.length; _i++) {\n        var _node = nodes[_i];\n        var rcPos = options.position(_node);\n\n        if (rcPos && (rcPos.row !== undefined || rcPos.col !== undefined)) {\n          // must have at least row or col def'd\n          var _pos = {\n            row: rcPos.row,\n            col: rcPos.col\n          };\n\n          if (_pos.col === undefined) {\n            // find unused col\n            _pos.col = 0;\n\n            while (used(_pos.row, _pos.col)) {\n              _pos.col++;\n            }\n          } else if (_pos.row === undefined) {\n            // find unused row\n            _pos.row = 0;\n\n            while (used(_pos.row, _pos.col)) {\n              _pos.row++;\n            }\n          }\n\n          id2manPos[_node.id()] = _pos;\n          use(_pos.row, _pos.col);\n        }\n      }\n\n      var getPos = function getPos(element, i) {\n        var x, y;\n\n        if (element.locked() || element.isParent()) {\n          return false;\n        } // see if we have a manual position set\n\n\n        var rcPos = id2manPos[element.id()];\n\n        if (rcPos) {\n          x = rcPos.col * cellWidth + cellWidth / 2 + bb.x1;\n          y = rcPos.row * cellHeight + cellHeight / 2 + bb.y1;\n        } else {\n          // otherwise set automatically\n          while (used(row, col)) {\n            moveToNextCell();\n          }\n\n          x = col * cellWidth + cellWidth / 2 + bb.x1;\n          y = row * cellHeight + cellHeight / 2 + bb.y1;\n          use(row, col);\n          moveToNextCell();\n        }\n\n        return {\n          x: x,\n          y: y\n        };\n      };\n\n      nodes.layoutPositions(this, options, getPos);\n    }\n\n    return this; // chaining\n  };\n\n  var defaults$2 = {\n    ready: function ready() {},\n    // on layoutready\n    stop: function stop() {} // on layoutstop\n\n  }; // constructor\n  // options : object containing layout options\n\n  function NullLayout(options) {\n    this.options = extend({}, defaults$2, options);\n  } // runs the layout\n\n\n  NullLayout.prototype.run = function () {\n    var options = this.options;\n    var eles = options.eles; // elements to consider in the layout\n\n    var layout = this; // cy is automatically populated for us in the constructor\n    // (disable eslint for next line as this serves as example layout code to external developers)\n    // eslint-disable-next-line no-unused-vars\n\n    options.cy;\n    layout.emit('layoutstart'); // puts all nodes at (0, 0)\n    // n.b. most layouts would use layoutPositions(), instead of positions() and manual events\n\n    eles.nodes().positions(function () {\n      return {\n        x: 0,\n        y: 0\n      };\n    }); // trigger layoutready when each node has had its position set at least once\n\n    layout.one('layoutready', options.ready);\n    layout.emit('layoutready'); // trigger layoutstop when the layout stops (e.g. finishes)\n\n    layout.one('layoutstop', options.stop);\n    layout.emit('layoutstop');\n    return this; // chaining\n  }; // called on continuous layouts to stop them before they finish\n\n\n  NullLayout.prototype.stop = function () {\n    return this; // chaining\n  };\n\n  var defaults$1 = {\n    positions: undefined,\n    // map of (node id) => (position obj); or function(node){ return somPos; }\n    zoom: undefined,\n    // the zoom level to set (prob want fit = false if set)\n    pan: undefined,\n    // the pan level to set (prob want fit = false if set)\n    fit: true,\n    // whether to fit to viewport\n    padding: 30,\n    // padding on fit\n    animate: false,\n    // whether to transition the node positions\n    animationDuration: 500,\n    // duration of animation in ms if enabled\n    animationEasing: undefined,\n    // easing of animation if enabled\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts\n    ready: undefined,\n    // callback on layoutready\n    stop: undefined,\n    // callback on layoutstop\n    transform: function transform(node, position) {\n      return position;\n    } // transform a given node position. Useful for changing flow direction in discrete layouts\n\n  };\n\n  function PresetLayout(options) {\n    this.options = extend({}, defaults$1, options);\n  }\n\n  PresetLayout.prototype.run = function () {\n    var options = this.options;\n    var eles = options.eles;\n    var nodes = eles.nodes();\n    var posIsFn = fn$6(options.positions);\n\n    function getPosition(node) {\n      if (options.positions == null) {\n        return copyPosition(node.position());\n      }\n\n      if (posIsFn) {\n        return options.positions(node);\n      }\n\n      var pos = options.positions[node._private.data.id];\n\n      if (pos == null) {\n        return null;\n      }\n\n      return pos;\n    }\n\n    nodes.layoutPositions(this, options, function (node, i) {\n      var position = getPosition(node);\n\n      if (node.locked() || position == null) {\n        return false;\n      }\n\n      return position;\n    });\n    return this; // chaining\n  };\n\n  var defaults = {\n    fit: true,\n    // whether to fit to viewport\n    padding: 30,\n    // fit padding\n    boundingBox: undefined,\n    // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }\n    animate: false,\n    // whether to transition the node positions\n    animationDuration: 500,\n    // duration of animation in ms if enabled\n    animationEasing: undefined,\n    // easing of animation if enabled\n    animateFilter: function animateFilter(node, i) {\n      return true;\n    },\n    // a function that determines whether the node should be animated.  All nodes animated by default on animate enabled.  Non-animated nodes are positioned immediately when the layout starts\n    ready: undefined,\n    // callback on layoutready\n    stop: undefined,\n    // callback on layoutstop\n    transform: function transform(node, position) {\n      return position;\n    } // transform a given node position. Useful for changing flow direction in discrete layouts \n\n  };\n\n  function RandomLayout(options) {\n    this.options = extend({}, defaults, options);\n  }\n\n  RandomLayout.prototype.run = function () {\n    var options = this.options;\n    var cy = options.cy;\n    var eles = options.eles;\n    var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {\n      x1: 0,\n      y1: 0,\n      w: cy.width(),\n      h: cy.height()\n    });\n\n    var getPos = function getPos(node, i) {\n      return {\n        x: bb.x1 + Math.round(Math.random() * bb.w),\n        y: bb.y1 + Math.round(Math.random() * bb.h)\n      };\n    };\n\n    eles.nodes().layoutPositions(this, options, getPos);\n    return this; // chaining\n  };\n\n  var layout = [{\n    name: 'breadthfirst',\n    impl: BreadthFirstLayout\n  }, {\n    name: 'circle',\n    impl: CircleLayout\n  }, {\n    name: 'concentric',\n    impl: ConcentricLayout\n  }, {\n    name: 'cose',\n    impl: CoseLayout\n  }, {\n    name: 'grid',\n    impl: GridLayout\n  }, {\n    name: 'null',\n    impl: NullLayout\n  }, {\n    name: 'preset',\n    impl: PresetLayout\n  }, {\n    name: 'random',\n    impl: RandomLayout\n  }];\n\n  function NullRenderer(options) {\n    this.options = options;\n    this.notifications = 0; // for testing\n  }\n\n  var noop = function noop() {};\n\n  var throwImgErr = function throwImgErr() {\n    throw new Error('A headless instance can not render images');\n  };\n\n  NullRenderer.prototype = {\n    recalculateRenderedStyle: noop,\n    notify: function notify() {\n      this.notifications++;\n    },\n    init: noop,\n    isHeadless: function isHeadless() {\n      return true;\n    },\n    png: throwImgErr,\n    jpg: throwImgErr\n  };\n\n  var BRp$f = {};\n  BRp$f.arrowShapeWidth = 0.3;\n\n  BRp$f.registerArrowShapes = function () {\n    var arrowShapes = this.arrowShapes = {};\n    var renderer = this; // Contract for arrow shapes:\n    // 0, 0 is arrow tip\n    // (0, 1) is direction towards node\n    // (1, 0) is right\n    //\n    // functional api:\n    // collide: check x, y in shape\n    // roughCollide: called before collide, no false negatives\n    // draw: draw\n    // spacing: dist(arrowTip, nodeBoundary)\n    // gap: dist(edgeTip, nodeBoundary), edgeTip may != arrowTip\n\n    var bbCollide = function bbCollide(x, y, size, angle, translation, edgeWidth, padding) {\n      var x1 = translation.x - size / 2 - padding;\n      var x2 = translation.x + size / 2 + padding;\n      var y1 = translation.y - size / 2 - padding;\n      var y2 = translation.y + size / 2 + padding;\n      var inside = x1 <= x && x <= x2 && y1 <= y && y <= y2;\n      return inside;\n    };\n\n    var transform = function transform(x, y, size, angle, translation) {\n      var xRotated = x * Math.cos(angle) - y * Math.sin(angle);\n      var yRotated = x * Math.sin(angle) + y * Math.cos(angle);\n      var xScaled = xRotated * size;\n      var yScaled = yRotated * size;\n      var xTranslated = xScaled + translation.x;\n      var yTranslated = yScaled + translation.y;\n      return {\n        x: xTranslated,\n        y: yTranslated\n      };\n    };\n\n    var transformPoints = function transformPoints(pts, size, angle, translation) {\n      var retPts = [];\n\n      for (var i = 0; i < pts.length; i += 2) {\n        var x = pts[i];\n        var y = pts[i + 1];\n        retPts.push(transform(x, y, size, angle, translation));\n      }\n\n      return retPts;\n    };\n\n    var pointsToArr = function pointsToArr(pts) {\n      var ret = [];\n\n      for (var i = 0; i < pts.length; i++) {\n        var p = pts[i];\n        ret.push(p.x, p.y);\n      }\n\n      return ret;\n    };\n\n    var standardGap = function standardGap(edge) {\n      return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;\n    };\n\n    var defineArrowShape = function defineArrowShape(name, defn) {\n      if (string(defn)) {\n        defn = arrowShapes[defn];\n      }\n\n      arrowShapes[name] = extend({\n        name: name,\n        points: [-0.15, -0.3, 0.15, -0.3, 0.15, 0.3, -0.15, 0.3],\n        collide: function collide(x, y, size, angle, translation, padding) {\n          var points = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n          var inside = pointInsidePolygonPoints(x, y, points);\n          return inside;\n        },\n        roughCollide: bbCollide,\n        draw: function draw(context, size, angle, translation) {\n          var points = transformPoints(this.points, size, angle, translation);\n          renderer.arrowShapeImpl('polygon')(context, points);\n        },\n        spacing: function spacing(edge) {\n          return 0;\n        },\n        gap: standardGap\n      }, defn);\n    };\n\n    defineArrowShape('none', {\n      collide: falsify,\n      roughCollide: falsify,\n      draw: noop$1,\n      spacing: zeroify,\n      gap: zeroify\n    });\n    defineArrowShape('triangle', {\n      points: [-0.15, -0.3, 0, 0, 0.15, -0.3]\n    });\n    defineArrowShape('arrow', 'triangle');\n    defineArrowShape('triangle-backcurve', {\n      points: arrowShapes['triangle'].points,\n      controlPoint: [0, -0.15],\n      roughCollide: bbCollide,\n      draw: function draw(context, size, angle, translation, edgeWidth) {\n        var ptsTrans = transformPoints(this.points, size, angle, translation);\n        var ctrlPt = this.controlPoint;\n        var ctrlPtTrans = transform(ctrlPt[0], ctrlPt[1], size, angle, translation);\n        renderer.arrowShapeImpl(this.name)(context, ptsTrans, ctrlPtTrans);\n      },\n      gap: function gap(edge) {\n        return standardGap(edge) * 0.8;\n      }\n    });\n    defineArrowShape('triangle-tee', {\n      points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],\n      pointsTee: [-0.15, -0.4, -0.15, -0.5, 0.15, -0.5, 0.15, -0.4],\n      collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n        var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n        var teePts = pointsToArr(transformPoints(this.pointsTee, size + 2 * padding, angle, translation));\n        var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);\n        return inside;\n      },\n      draw: function draw(context, size, angle, translation, edgeWidth) {\n        var triPts = transformPoints(this.points, size, angle, translation);\n        var teePts = transformPoints(this.pointsTee, size, angle, translation);\n        renderer.arrowShapeImpl(this.name)(context, triPts, teePts);\n      }\n    });\n    defineArrowShape('circle-triangle', {\n      radius: 0.15,\n      pointsTr: [0, -0.15, 0.15, -0.45, -0.15, -0.45, 0, -0.15],\n      collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n        var t = translation;\n        var circleInside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);\n        var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n        return pointInsidePolygonPoints(x, y, triPts) || circleInside;\n      },\n      draw: function draw(context, size, angle, translation, edgeWidth) {\n        var triPts = transformPoints(this.pointsTr, size, angle, translation);\n        renderer.arrowShapeImpl(this.name)(context, triPts, translation.x, translation.y, this.radius * size);\n      },\n      spacing: function spacing(edge) {\n        return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;\n      }\n    });\n    defineArrowShape('triangle-cross', {\n      points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],\n      baseCrossLinePts: [-0.15, -0.4, // first half of the rectangle\n      -0.15, -0.4, 0.15, -0.4, // second half of the rectangle\n      0.15, -0.4],\n      crossLinePts: function crossLinePts(size, edgeWidth) {\n        // shift points so that the distance between the cross points matches edge width\n        var p = this.baseCrossLinePts.slice();\n        var shiftFactor = edgeWidth / size;\n        var y0 = 3;\n        var y1 = 5;\n        p[y0] = p[y0] - shiftFactor;\n        p[y1] = p[y1] - shiftFactor;\n        return p;\n      },\n      collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n        var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));\n        var teePts = pointsToArr(transformPoints(this.crossLinePts(size, edgeWidth), size + 2 * padding, angle, translation));\n        var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);\n        return inside;\n      },\n      draw: function draw(context, size, angle, translation, edgeWidth) {\n        var triPts = transformPoints(this.points, size, angle, translation);\n        var crossLinePts = transformPoints(this.crossLinePts(size, edgeWidth), size, angle, translation);\n        renderer.arrowShapeImpl(this.name)(context, triPts, crossLinePts);\n      }\n    });\n    defineArrowShape('vee', {\n      points: [-0.15, -0.3, 0, 0, 0.15, -0.3, 0, -0.15],\n      gap: function gap(edge) {\n        return standardGap(edge) * 0.525;\n      }\n    });\n    defineArrowShape('circle', {\n      radius: 0.15,\n      collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {\n        var t = translation;\n        var inside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);\n        return inside;\n      },\n      draw: function draw(context, size, angle, translation, edgeWidth) {\n        renderer.arrowShapeImpl(this.name)(context, translation.x, translation.y, this.radius * size);\n      },\n      spacing: function spacing(edge) {\n        return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;\n      }\n    });\n    defineArrowShape('tee', {\n      points: [-0.15, 0, -0.15, -0.1, 0.15, -0.1, 0.15, 0],\n      spacing: function spacing(edge) {\n        return 1;\n      },\n      gap: function gap(edge) {\n        return 1;\n      }\n    });\n    defineArrowShape('square', {\n      points: [-0.15, 0.00, 0.15, 0.00, 0.15, -0.3, -0.15, -0.3]\n    });\n    defineArrowShape('diamond', {\n      points: [-0.15, -0.15, 0, -0.3, 0.15, -0.15, 0, 0],\n      gap: function gap(edge) {\n        return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;\n      }\n    });\n    defineArrowShape('chevron', {\n      points: [0, 0, -0.15, -0.15, -0.1, -0.2, 0, -0.1, 0.1, -0.2, 0.15, -0.15],\n      gap: function gap(edge) {\n        return 0.95 * edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;\n      }\n    });\n  };\n\n  var BRp$e = {}; // Project mouse\n\n  BRp$e.projectIntoViewport = function (clientX, clientY) {\n    var cy = this.cy;\n    var offsets = this.findContainerClientCoords();\n    var offsetLeft = offsets[0];\n    var offsetTop = offsets[1];\n    var scale = offsets[4];\n    var pan = cy.pan();\n    var zoom = cy.zoom();\n    var x = ((clientX - offsetLeft) / scale - pan.x) / zoom;\n    var y = ((clientY - offsetTop) / scale - pan.y) / zoom;\n    return [x, y];\n  };\n\n  BRp$e.findContainerClientCoords = function () {\n    if (this.containerBB) {\n      return this.containerBB;\n    }\n\n    var container = this.container;\n    var rect = container.getBoundingClientRect();\n    var style = this.cy.window().getComputedStyle(container);\n\n    var styleValue = function styleValue(name) {\n      return parseFloat(style.getPropertyValue(name));\n    };\n\n    var padding = {\n      left: styleValue('padding-left'),\n      right: styleValue('padding-right'),\n      top: styleValue('padding-top'),\n      bottom: styleValue('padding-bottom')\n    };\n    var border = {\n      left: styleValue('border-left-width'),\n      right: styleValue('border-right-width'),\n      top: styleValue('border-top-width'),\n      bottom: styleValue('border-bottom-width')\n    };\n    var clientWidth = container.clientWidth;\n    var clientHeight = container.clientHeight;\n    var paddingHor = padding.left + padding.right;\n    var paddingVer = padding.top + padding.bottom;\n    var borderHor = border.left + border.right;\n    var scale = rect.width / (clientWidth + borderHor);\n    var unscaledW = clientWidth - paddingHor;\n    var unscaledH = clientHeight - paddingVer;\n    var left = rect.left + padding.left + border.left;\n    var top = rect.top + padding.top + border.top;\n    return this.containerBB = [left, top, unscaledW, unscaledH, scale];\n  };\n\n  BRp$e.invalidateContainerClientCoordsCache = function () {\n    this.containerBB = null;\n  };\n\n  BRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {\n    return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];\n  };\n\n  BRp$e.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {\n    var self = this;\n    var r = this;\n    var eles = r.getCachedZSortedEles();\n    var near = []; // 1 node max, 1 edge max\n\n    var zoom = r.cy.zoom();\n    var hasCompounds = r.cy.hasCompoundNodes();\n    var edgeThreshold = (isTouch ? 24 : 8) / zoom;\n    var nodeThreshold = (isTouch ? 8 : 2) / zoom;\n    var labelThreshold = (isTouch ? 8 : 2) / zoom;\n    var minSqDist = Infinity;\n    var nearEdge;\n    var nearNode;\n\n    if (interactiveElementsOnly) {\n      eles = eles.interactive;\n    }\n\n    function addEle(ele, sqDist) {\n      if (ele.isNode()) {\n        if (nearNode) {\n          return; // can't replace node\n        } else {\n          nearNode = ele;\n          near.push(ele);\n        }\n      }\n\n      if (ele.isEdge() && (sqDist == null || sqDist < minSqDist)) {\n        if (nearEdge) {\n          // then replace existing edge\n          // can replace only if same z-index\n          if (nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value && nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value) {\n            for (var i = 0; i < near.length; i++) {\n              if (near[i].isEdge()) {\n                near[i] = ele;\n                nearEdge = ele;\n                minSqDist = sqDist != null ? sqDist : minSqDist;\n                break;\n              }\n            }\n          }\n        } else {\n          near.push(ele);\n          nearEdge = ele;\n          minSqDist = sqDist != null ? sqDist : minSqDist;\n        }\n      }\n    }\n\n    function checkNode(node) {\n      var width = node.outerWidth() + 2 * nodeThreshold;\n      var height = node.outerHeight() + 2 * nodeThreshold;\n      var hw = width / 2;\n      var hh = height / 2;\n      var pos = node.position();\n\n      if (pos.x - hw <= x && x <= pos.x + hw // bb check x\n      && pos.y - hh <= y && y <= pos.y + hh // bb check y\n      ) {\n        var shape = r.nodeShapes[self.getNodeShape(node)];\n\n        if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y)) {\n          addEle(node, 0);\n          return true;\n        }\n      }\n    }\n\n    function checkEdge(edge) {\n      var _p = edge._private;\n      var rs = _p.rscratch;\n      var styleWidth = edge.pstyle('width').pfValue;\n      var scale = edge.pstyle('arrow-scale').value;\n      var width = styleWidth / 2 + edgeThreshold; // more like a distance radius from centre\n\n      var widthSq = width * width;\n      var width2 = width * 2;\n      var src = _p.source;\n      var tgt = _p.target;\n      var sqDist;\n\n      if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {\n        var pts = rs.allpts;\n\n        for (var i = 0; i + 3 < pts.length; i += 2) {\n          if (inLineVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], width2) && widthSq > (sqDist = sqdistToFiniteLine(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3]))) {\n            addEle(edge, sqDist);\n            return true;\n          }\n        }\n      } else if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {\n        var pts = rs.allpts;\n\n        for (var i = 0; i + 5 < rs.allpts.length; i += 4) {\n          if (inBezierVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5], width2) && widthSq > (sqDist = sqdistToQuadraticBezier(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5]))) {\n            addEle(edge, sqDist);\n            return true;\n          }\n        }\n      } // if we're close to the edge but didn't hit it, maybe we hit its arrows\n\n\n      var src = src || _p.source;\n      var tgt = tgt || _p.target;\n      var arSize = self.getArrowWidth(styleWidth, scale);\n      var arrows = [{\n        name: 'source',\n        x: rs.arrowStartX,\n        y: rs.arrowStartY,\n        angle: rs.srcArrowAngle\n      }, {\n        name: 'target',\n        x: rs.arrowEndX,\n        y: rs.arrowEndY,\n        angle: rs.tgtArrowAngle\n      }, {\n        name: 'mid-source',\n        x: rs.midX,\n        y: rs.midY,\n        angle: rs.midsrcArrowAngle\n      }, {\n        name: 'mid-target',\n        x: rs.midX,\n        y: rs.midY,\n        angle: rs.midtgtArrowAngle\n      }];\n\n      for (var i = 0; i < arrows.length; i++) {\n        var ar = arrows[i];\n        var shape = r.arrowShapes[edge.pstyle(ar.name + '-arrow-shape').value];\n        var edgeWidth = edge.pstyle('width').pfValue;\n\n        if (shape.roughCollide(x, y, arSize, ar.angle, {\n          x: ar.x,\n          y: ar.y\n        }, edgeWidth, edgeThreshold) && shape.collide(x, y, arSize, ar.angle, {\n          x: ar.x,\n          y: ar.y\n        }, edgeWidth, edgeThreshold)) {\n          addEle(edge);\n          return true;\n        }\n      } // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)\n\n\n      if (hasCompounds && near.length > 0) {\n        checkNode(src);\n        checkNode(tgt);\n      }\n    }\n\n    function preprop(obj, name, pre) {\n      return getPrefixedProperty(obj, name, pre);\n    }\n\n    function checkLabel(ele, prefix) {\n      var _p = ele._private;\n      var th = labelThreshold;\n      var prefixDash;\n\n      if (prefix) {\n        prefixDash = prefix + '-';\n      } else {\n        prefixDash = '';\n      }\n\n      ele.boundingBox();\n      var bb = _p.labelBounds[prefix || 'main'];\n      var text = ele.pstyle(prefixDash + 'label').value;\n      var eventsEnabled = ele.pstyle('text-events').strValue === 'yes';\n\n      if (!eventsEnabled || !text) {\n        return;\n      }\n\n      var lx = preprop(_p.rscratch, 'labelX', prefix);\n      var ly = preprop(_p.rscratch, 'labelY', prefix);\n      var theta = preprop(_p.rscratch, 'labelAngle', prefix);\n      var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;\n      var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;\n      var lx1 = bb.x1 - th - ox; // (-ox, -oy) as bb already includes margin\n\n      var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)\n\n      var ly1 = bb.y1 - th - oy;\n      var ly2 = bb.y2 + th - oy;\n\n      if (theta) {\n        var cos = Math.cos(theta);\n        var sin = Math.sin(theta);\n\n        var rotate = function rotate(x, y) {\n          x = x - lx;\n          y = y - ly;\n          return {\n            x: x * cos - y * sin + lx,\n            y: x * sin + y * cos + ly\n          };\n        };\n\n        var px1y1 = rotate(lx1, ly1);\n        var px1y2 = rotate(lx1, ly2);\n        var px2y1 = rotate(lx2, ly1);\n        var px2y2 = rotate(lx2, ly2);\n        var points = [// with the margin added after the rotation is applied\n        px1y1.x + ox, px1y1.y + oy, px2y1.x + ox, px2y1.y + oy, px2y2.x + ox, px2y2.y + oy, px1y2.x + ox, px1y2.y + oy];\n\n        if (pointInsidePolygonPoints(x, y, points)) {\n          addEle(ele);\n          return true;\n        }\n      } else {\n        // do a cheaper bb check\n        if (inBoundingBox(bb, x, y)) {\n          addEle(ele);\n          return true;\n        }\n      }\n    }\n\n    for (var i = eles.length - 1; i >= 0; i--) {\n      // reverse order for precedence\n      var ele = eles[i];\n\n      if (ele.isNode()) {\n        checkNode(ele) || checkLabel(ele);\n      } else {\n        // then edge\n        checkEdge(ele) || checkLabel(ele) || checkLabel(ele, 'source') || checkLabel(ele, 'target');\n      }\n    }\n\n    return near;\n  }; // 'Give me everything from this box'\n\n\n  BRp$e.getAllInBox = function (x1, y1, x2, y2) {\n    var eles = this.getCachedZSortedEles().interactive;\n    var box = [];\n    var x1c = Math.min(x1, x2);\n    var x2c = Math.max(x1, x2);\n    var y1c = Math.min(y1, y2);\n    var y2c = Math.max(y1, y2);\n    x1 = x1c;\n    x2 = x2c;\n    y1 = y1c;\n    y2 = y2c;\n    var boxBb = makeBoundingBox({\n      x1: x1,\n      y1: y1,\n      x2: x2,\n      y2: y2\n    });\n\n    for (var e = 0; e < eles.length; e++) {\n      var ele = eles[e];\n\n      if (ele.isNode()) {\n        var node = ele;\n        var nodeBb = node.boundingBox({\n          includeNodes: true,\n          includeEdges: false,\n          includeLabels: false\n        });\n\n        if (boundingBoxesIntersect(boxBb, nodeBb) && !boundingBoxInBoundingBox(nodeBb, boxBb)) {\n          box.push(node);\n        }\n      } else {\n        var edge = ele;\n        var _p = edge._private;\n        var rs = _p.rscratch;\n\n        if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {\n          continue;\n        }\n\n        if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {\n          continue;\n        }\n\n        if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound' || rs.edgeType === 'segments' || rs.edgeType === 'haystack') {\n          var pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;\n          var allInside = true;\n\n          for (var i = 0; i < pts.length; i++) {\n            if (!pointInBoundingBox(boxBb, pts[i])) {\n              allInside = false;\n              break;\n            }\n          }\n\n          if (allInside) {\n            box.push(edge);\n          }\n        } else if (rs.edgeType === 'haystack' || rs.edgeType === 'straight') {\n          box.push(edge);\n        }\n      }\n    }\n\n    return box;\n  };\n\n  var BRp$d = {};\n\n  BRp$d.calculateArrowAngles = function (edge) {\n    var rs = edge._private.rscratch;\n    var isHaystack = rs.edgeType === 'haystack';\n    var isBezier = rs.edgeType === 'bezier';\n    var isMultibezier = rs.edgeType === 'multibezier';\n    var isSegments = rs.edgeType === 'segments';\n    var isCompound = rs.edgeType === 'compound';\n    var isSelf = rs.edgeType === 'self'; // Displacement gives direction for arrowhead orientation\n\n    var dispX, dispY;\n    var startX, startY, endX, endY, midX, midY;\n\n    if (isHaystack) {\n      startX = rs.haystackPts[0];\n      startY = rs.haystackPts[1];\n      endX = rs.haystackPts[2];\n      endY = rs.haystackPts[3];\n    } else {\n      startX = rs.arrowStartX;\n      startY = rs.arrowStartY;\n      endX = rs.arrowEndX;\n      endY = rs.arrowEndY;\n    }\n\n    midX = rs.midX;\n    midY = rs.midY; // source\n    //\n\n    if (isSegments) {\n      dispX = startX - rs.segpts[0];\n      dispY = startY - rs.segpts[1];\n    } else if (isMultibezier || isCompound || isSelf || isBezier) {\n      var pts = rs.allpts;\n      var bX = qbezierAt(pts[0], pts[2], pts[4], 0.1);\n      var bY = qbezierAt(pts[1], pts[3], pts[5], 0.1);\n      dispX = startX - bX;\n      dispY = startY - bY;\n    } else {\n      dispX = startX - midX;\n      dispY = startY - midY;\n    }\n\n    rs.srcArrowAngle = getAngleFromDisp(dispX, dispY); // mid target\n    //\n\n    var midX = rs.midX;\n    var midY = rs.midY;\n\n    if (isHaystack) {\n      midX = (startX + endX) / 2;\n      midY = (startY + endY) / 2;\n    }\n\n    dispX = endX - startX;\n    dispY = endY - startY;\n\n    if (isSegments) {\n      var pts = rs.allpts;\n\n      if (pts.length / 2 % 2 === 0) {\n        var i2 = pts.length / 2;\n        var i1 = i2 - 2;\n        dispX = pts[i2] - pts[i1];\n        dispY = pts[i2 + 1] - pts[i1 + 1];\n      } else {\n        var i2 = pts.length / 2 - 1;\n        var i1 = i2 - 2;\n        var i3 = i2 + 2;\n        dispX = pts[i2] - pts[i1];\n        dispY = pts[i2 + 1] - pts[i1 + 1];\n      }\n    } else if (isMultibezier || isCompound || isSelf) {\n      var pts = rs.allpts;\n      var cpts = rs.ctrlpts;\n      var bp0x, bp0y;\n      var bp1x, bp1y;\n\n      if (cpts.length / 2 % 2 === 0) {\n        var p0 = pts.length / 2 - 1; // startpt\n\n        var ic = p0 + 2;\n        var p1 = ic + 2;\n        bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0);\n        bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0);\n        bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0001);\n        bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0001);\n      } else {\n        var ic = pts.length / 2 - 1; // ctrpt\n\n        var p0 = ic - 2; // startpt\n\n        var p1 = ic + 2; // endpt\n\n        bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.4999);\n        bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.4999);\n        bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.5);\n        bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.5);\n      }\n\n      dispX = bp1x - bp0x;\n      dispY = bp1y - bp0y;\n    }\n\n    rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);\n    rs.midDispX = dispX;\n    rs.midDispY = dispY; // mid source\n    //\n\n    dispX *= -1;\n    dispY *= -1;\n\n    if (isSegments) {\n      var pts = rs.allpts;\n\n      if (pts.length / 2 % 2 === 0) ; else {\n        var i2 = pts.length / 2 - 1;\n        var i3 = i2 + 2;\n        dispX = -(pts[i3] - pts[i2]);\n        dispY = -(pts[i3 + 1] - pts[i2 + 1]);\n      }\n    }\n\n    rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY); // target\n    //\n\n    if (isSegments) {\n      dispX = endX - rs.segpts[rs.segpts.length - 2];\n      dispY = endY - rs.segpts[rs.segpts.length - 1];\n    } else if (isMultibezier || isCompound || isSelf || isBezier) {\n      var pts = rs.allpts;\n      var l = pts.length;\n      var bX = qbezierAt(pts[l - 6], pts[l - 4], pts[l - 2], 0.9);\n      var bY = qbezierAt(pts[l - 5], pts[l - 3], pts[l - 1], 0.9);\n      dispX = endX - bX;\n      dispY = endY - bY;\n    } else {\n      dispX = endX - midX;\n      dispY = endY - midY;\n    }\n\n    rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);\n  };\n\n  BRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {\n    var cache = this.arrowWidthCache = this.arrowWidthCache || {};\n    var cachedVal = cache[edgeWidth + ', ' + scale];\n\n    if (cachedVal) {\n      return cachedVal;\n    }\n\n    cachedVal = Math.max(Math.pow(edgeWidth * 13.37, 0.9), 29) * scale;\n    cache[edgeWidth + ', ' + scale] = cachedVal;\n    return cachedVal;\n  };\n\n  var BRp$c = {};\n\n  BRp$c.findHaystackPoints = function (edges) {\n    for (var i = 0; i < edges.length; i++) {\n      var edge = edges[i];\n      var _p = edge._private;\n      var rs = _p.rscratch;\n\n      if (!rs.haystack) {\n        var angle = Math.random() * 2 * Math.PI;\n        rs.source = {\n          x: Math.cos(angle),\n          y: Math.sin(angle)\n        };\n        angle = Math.random() * 2 * Math.PI;\n        rs.target = {\n          x: Math.cos(angle),\n          y: Math.sin(angle)\n        };\n      }\n\n      var src = _p.source;\n      var tgt = _p.target;\n      var srcPos = src.position();\n      var tgtPos = tgt.position();\n      var srcW = src.width();\n      var tgtW = tgt.width();\n      var srcH = src.height();\n      var tgtH = tgt.height();\n      var radius = edge.pstyle('haystack-radius').value;\n      var halfRadius = radius / 2; // b/c have to half width/height\n\n      rs.haystackPts = rs.allpts = [rs.source.x * srcW * halfRadius + srcPos.x, rs.source.y * srcH * halfRadius + srcPos.y, rs.target.x * tgtW * halfRadius + tgtPos.x, rs.target.y * tgtH * halfRadius + tgtPos.y];\n      rs.midX = (rs.allpts[0] + rs.allpts[2]) / 2;\n      rs.midY = (rs.allpts[1] + rs.allpts[3]) / 2; // always override as haystack in case set to different type previously\n\n      rs.edgeType = 'haystack';\n      rs.haystack = true;\n      this.storeEdgeProjections(edge);\n      this.calculateArrowAngles(edge);\n      this.recalculateEdgeLabelProjections(edge);\n      this.calculateLabelAngles(edge);\n    }\n  };\n\n  BRp$c.findSegmentsPoints = function (edge, pairInfo) {\n    // Segments (multiple straight lines)\n    var rs = edge._private.rscratch;\n    var posPts = pairInfo.posPts,\n        intersectionPts = pairInfo.intersectionPts,\n        vectorNormInverse = pairInfo.vectorNormInverse;\n    var edgeDistances = edge.pstyle('edge-distances').value;\n    var segmentWs = edge.pstyle('segment-weights');\n    var segmentDs = edge.pstyle('segment-distances');\n    var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);\n    rs.edgeType = 'segments';\n    rs.segpts = [];\n\n    for (var s = 0; s < segmentsN; s++) {\n      var w = segmentWs.pfValue[s];\n      var d = segmentDs.pfValue[s];\n      var w1 = 1 - w;\n      var w2 = w;\n      var midptPts = edgeDistances === 'node-position' ? posPts : intersectionPts;\n      var adjustedMidpt = {\n        x: midptPts.x1 * w1 + midptPts.x2 * w2,\n        y: midptPts.y1 * w1 + midptPts.y2 * w2\n      };\n      rs.segpts.push(adjustedMidpt.x + vectorNormInverse.x * d, adjustedMidpt.y + vectorNormInverse.y * d);\n    }\n  };\n\n  BRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {\n    // Self-edge\n    var rs = edge._private.rscratch;\n    var dirCounts = pairInfo.dirCounts,\n        srcPos = pairInfo.srcPos;\n    var ctrlptDists = edge.pstyle('control-point-distances');\n    var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;\n    var loopDir = edge.pstyle('loop-direction').pfValue;\n    var loopSwp = edge.pstyle('loop-sweep').pfValue;\n    var stepSize = edge.pstyle('control-point-step-size').pfValue;\n    rs.edgeType = 'self';\n    var j = i;\n    var loopDist = stepSize;\n\n    if (edgeIsUnbundled) {\n      j = 0;\n      loopDist = ctrlptDist;\n    }\n\n    var loopAngle = loopDir - Math.PI / 2;\n    var outAngle = loopAngle - loopSwp / 2;\n    var inAngle = loopAngle + loopSwp / 2; // increase by step size for overlapping loops, keyed on direction and sweep values\n\n    var dc = String(loopDir + '_' + loopSwp);\n    j = dirCounts[dc] === undefined ? dirCounts[dc] = 0 : ++dirCounts[dc];\n    rs.ctrlpts = [srcPos.x + Math.cos(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.x + Math.cos(inAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(inAngle) * 1.4 * loopDist * (j / 3 + 1)];\n  };\n\n  BRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {\n    // Compound edge\n    var rs = edge._private.rscratch;\n    rs.edgeType = 'compound';\n    var srcPos = pairInfo.srcPos,\n        tgtPos = pairInfo.tgtPos,\n        srcW = pairInfo.srcW,\n        srcH = pairInfo.srcH,\n        tgtW = pairInfo.tgtW,\n        tgtH = pairInfo.tgtH;\n    var stepSize = edge.pstyle('control-point-step-size').pfValue;\n    var ctrlptDists = edge.pstyle('control-point-distances');\n    var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;\n    var j = i;\n    var loopDist = stepSize;\n\n    if (edgeIsUnbundled) {\n      j = 0;\n      loopDist = ctrlptDist;\n    }\n\n    var loopW = 50;\n    var loopaPos = {\n      x: srcPos.x - srcW / 2,\n      y: srcPos.y - srcH / 2\n    };\n    var loopbPos = {\n      x: tgtPos.x - tgtW / 2,\n      y: tgtPos.y - tgtH / 2\n    };\n    var loopPos = {\n      x: Math.min(loopaPos.x, loopbPos.x),\n      y: Math.min(loopaPos.y, loopbPos.y)\n    }; // avoids cases with impossible beziers\n\n    var minCompoundStretch = 0.5;\n    var compoundStretchA = Math.max(minCompoundStretch, Math.log(srcW * 0.01));\n    var compoundStretchB = Math.max(minCompoundStretch, Math.log(tgtW * 0.01));\n    rs.ctrlpts = [loopPos.x, loopPos.y - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchA, loopPos.x - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchB, loopPos.y];\n  };\n\n  BRp$c.findStraightEdgePoints = function (edge) {\n    // Straight edge within bundle\n    edge._private.rscratch.edgeType = 'straight';\n  };\n\n  BRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {\n    var rs = edge._private.rscratch;\n    var vectorNormInverse = pairInfo.vectorNormInverse,\n        posPts = pairInfo.posPts,\n        intersectionPts = pairInfo.intersectionPts;\n    var edgeDistances = edge.pstyle('edge-distances').value;\n    var stepSize = edge.pstyle('control-point-step-size').pfValue;\n    var ctrlptDists = edge.pstyle('control-point-distances');\n    var ctrlptWs = edge.pstyle('control-point-weights');\n    var bezierN = ctrlptDists && ctrlptWs ? Math.min(ctrlptDists.value.length, ctrlptWs.value.length) : 1;\n    var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;\n    var ctrlptWeight = ctrlptWs.value[0]; // (Multi)bezier\n\n    var multi = edgeIsUnbundled;\n    rs.edgeType = multi ? 'multibezier' : 'bezier';\n    rs.ctrlpts = [];\n\n    for (var b = 0; b < bezierN; b++) {\n      var normctrlptDist = (0.5 - pairInfo.eles.length / 2 + i) * stepSize * (edgeIsSwapped ? -1 : 1);\n      var manctrlptDist = void 0;\n      var sign = signum(normctrlptDist);\n\n      if (multi) {\n        ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size\n\n        ctrlptWeight = ctrlptWs.value[b];\n      }\n\n      if (edgeIsUnbundled) {\n        // multi or single unbundled\n        manctrlptDist = ctrlptDist;\n      } else {\n        manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;\n      }\n\n      var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;\n      var w1 = 1 - ctrlptWeight;\n      var w2 = ctrlptWeight;\n      var midptPts = edgeDistances === 'node-position' ? posPts : intersectionPts;\n      var adjustedMidpt = {\n        x: midptPts.x1 * w1 + midptPts.x2 * w2,\n        y: midptPts.y1 * w1 + midptPts.y2 * w2\n      };\n      rs.ctrlpts.push(adjustedMidpt.x + vectorNormInverse.x * distanceFromMidpoint, adjustedMidpt.y + vectorNormInverse.y * distanceFromMidpoint);\n    }\n  };\n\n  BRp$c.findTaxiPoints = function (edge, pairInfo) {\n    // Taxicab geometry with two turns maximum\n    var rs = edge._private.rscratch;\n    rs.edgeType = 'segments';\n    var VERTICAL = 'vertical';\n    var HORIZONTAL = 'horizontal';\n    var LEFTWARD = 'leftward';\n    var RIGHTWARD = 'rightward';\n    var DOWNWARD = 'downward';\n    var UPWARD = 'upward';\n    var AUTO = 'auto';\n    var posPts = pairInfo.posPts,\n        srcW = pairInfo.srcW,\n        srcH = pairInfo.srcH,\n        tgtW = pairInfo.tgtW,\n        tgtH = pairInfo.tgtH;\n    var edgeDistances = edge.pstyle('edge-distances').value;\n    var dIncludesNodeBody = edgeDistances !== 'node-position';\n    var taxiDir = edge.pstyle('taxi-direction').value;\n    var rawTaxiDir = taxiDir; // unprocessed value\n\n    var taxiTurn = edge.pstyle('taxi-turn');\n    var turnIsPercent = taxiTurn.units === '%';\n    var taxiTurnPfVal = taxiTurn.pfValue;\n    var turnIsNegative = taxiTurnPfVal < 0; // i.e. from target side\n\n    var minD = edge.pstyle('taxi-turn-min-distance').pfValue;\n    var dw = dIncludesNodeBody ? (srcW + tgtW) / 2 : 0;\n    var dh = dIncludesNodeBody ? (srcH + tgtH) / 2 : 0;\n    var pdx = posPts.x2 - posPts.x1;\n    var pdy = posPts.y2 - posPts.y1; // take away the effective w/h from the magnitude of the delta value\n\n    var subDWH = function subDWH(dxy, dwh) {\n      if (dxy > 0) {\n        return Math.max(dxy - dwh, 0);\n      } else {\n        return Math.min(dxy + dwh, 0);\n      }\n    };\n\n    var dx = subDWH(pdx, dw);\n    var dy = subDWH(pdy, dh);\n    var isExplicitDir = false;\n\n    if (rawTaxiDir === AUTO) {\n      taxiDir = Math.abs(dx) > Math.abs(dy) ? HORIZONTAL : VERTICAL;\n    } else if (rawTaxiDir === UPWARD || rawTaxiDir === DOWNWARD) {\n      taxiDir = VERTICAL;\n      isExplicitDir = true;\n    } else if (rawTaxiDir === LEFTWARD || rawTaxiDir === RIGHTWARD) {\n      taxiDir = HORIZONTAL;\n      isExplicitDir = true;\n    }\n\n    var isVert = taxiDir === VERTICAL;\n    var l = isVert ? dy : dx;\n    var pl = isVert ? pdy : pdx;\n    var sgnL = signum(pl);\n    var forcedDir = false;\n\n    if (!(isExplicitDir && (turnIsPercent || turnIsNegative)) // forcing in this case would cause weird growing in the opposite direction\n    && (rawTaxiDir === DOWNWARD && pl < 0 || rawTaxiDir === UPWARD && pl > 0 || rawTaxiDir === LEFTWARD && pl > 0 || rawTaxiDir === RIGHTWARD && pl < 0)) {\n      sgnL *= -1;\n      l = sgnL * Math.abs(l);\n      forcedDir = true;\n    }\n\n    var d;\n\n    if (turnIsPercent) {\n      var p = taxiTurnPfVal < 0 ? 1 + taxiTurnPfVal : taxiTurnPfVal;\n      d = p * l;\n    } else {\n      var k = taxiTurnPfVal < 0 ? l : 0;\n      d = k + taxiTurnPfVal * sgnL;\n    }\n\n    var getIsTooClose = function getIsTooClose(d) {\n      return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);\n    };\n\n    var isTooCloseSrc = getIsTooClose(d);\n    var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));\n    var isTooClose = isTooCloseSrc || isTooCloseTgt;\n\n    if (isTooClose && !forcedDir) {\n      // non-ideal routing\n      if (isVert) {\n        // vertical fallbacks\n        var lShapeInsideSrc = Math.abs(pl) <= srcH / 2;\n        var lShapeInsideTgt = Math.abs(pdx) <= tgtW / 2;\n\n        if (lShapeInsideSrc) {\n          // horizontal Z-shape (direction not respected)\n          var x = (posPts.x1 + posPts.x2) / 2;\n          var y1 = posPts.y1,\n              y2 = posPts.y2;\n          rs.segpts = [x, y1, x, y2];\n        } else if (lShapeInsideTgt) {\n          // vertical Z-shape (distance not respected)\n          var y = (posPts.y1 + posPts.y2) / 2;\n          var x1 = posPts.x1,\n              x2 = posPts.x2;\n          rs.segpts = [x1, y, x2, y];\n        } else {\n          // L-shape fallback (turn distance not respected, but works well with tree siblings)\n          rs.segpts = [posPts.x1, posPts.y2];\n        }\n      } else {\n        // horizontal fallbacks\n        var _lShapeInsideSrc = Math.abs(pl) <= srcW / 2;\n\n        var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;\n\n        if (_lShapeInsideSrc) {\n          // vertical Z-shape (direction not respected)\n          var _y = (posPts.y1 + posPts.y2) / 2;\n\n          var _x = posPts.x1,\n              _x2 = posPts.x2;\n          rs.segpts = [_x, _y, _x2, _y];\n        } else if (_lShapeInsideTgt) {\n          // horizontal Z-shape (turn distance not respected)\n          var _x3 = (posPts.x1 + posPts.x2) / 2;\n\n          var _y2 = posPts.y1,\n              _y3 = posPts.y2;\n          rs.segpts = [_x3, _y2, _x3, _y3];\n        } else {\n          // L-shape (turn distance not respected, but works well for tree siblings)\n          rs.segpts = [posPts.x2, posPts.y1];\n        }\n      }\n    } else {\n      // ideal routing\n      if (isVert) {\n        var _y4 = posPts.y1 + d + (dIncludesNodeBody ? srcH / 2 * sgnL : 0);\n\n        var _x4 = posPts.x1,\n            _x5 = posPts.x2;\n        rs.segpts = [_x4, _y4, _x5, _y4];\n      } else {\n        // horizontal\n        var _x6 = posPts.x1 + d + (dIncludesNodeBody ? srcW / 2 * sgnL : 0);\n\n        var _y5 = posPts.y1,\n            _y6 = posPts.y2;\n        rs.segpts = [_x6, _y5, _x6, _y6];\n      }\n    }\n  };\n\n  BRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {\n    var rs = edge._private.rscratch; // can only correct beziers for now...\n\n    if (rs.edgeType === 'bezier') {\n      var srcPos = pairInfo.srcPos,\n          tgtPos = pairInfo.tgtPos,\n          srcW = pairInfo.srcW,\n          srcH = pairInfo.srcH,\n          tgtW = pairInfo.tgtW,\n          tgtH = pairInfo.tgtH,\n          srcShape = pairInfo.srcShape,\n          tgtShape = pairInfo.tgtShape;\n      var badStart = !number$1(rs.startX) || !number$1(rs.startY);\n      var badAStart = !number$1(rs.arrowStartX) || !number$1(rs.arrowStartY);\n      var badEnd = !number$1(rs.endX) || !number$1(rs.endY);\n      var badAEnd = !number$1(rs.arrowEndX) || !number$1(rs.arrowEndY);\n      var minCpADistFactor = 3;\n      var arrowW = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;\n      var minCpADist = minCpADistFactor * arrowW;\n      var startACpDist = dist({\n        x: rs.ctrlpts[0],\n        y: rs.ctrlpts[1]\n      }, {\n        x: rs.startX,\n        y: rs.startY\n      });\n      var closeStartACp = startACpDist < minCpADist;\n      var endACpDist = dist({\n        x: rs.ctrlpts[0],\n        y: rs.ctrlpts[1]\n      }, {\n        x: rs.endX,\n        y: rs.endY\n      });\n      var closeEndACp = endACpDist < minCpADist;\n      var overlapping = false;\n\n      if (badStart || badAStart || closeStartACp) {\n        overlapping = true; // project control point along line from src centre to outside the src shape\n        // (otherwise intersection will yield nothing)\n\n        var cpD = {\n          // delta\n          x: rs.ctrlpts[0] - srcPos.x,\n          y: rs.ctrlpts[1] - srcPos.y\n        };\n        var cpL = Math.sqrt(cpD.x * cpD.x + cpD.y * cpD.y); // length of line\n\n        var cpM = {\n          // normalised delta\n          x: cpD.x / cpL,\n          y: cpD.y / cpL\n        };\n        var radius = Math.max(srcW, srcH);\n        var cpProj = {\n          // *2 radius guarantees outside shape\n          x: rs.ctrlpts[0] + cpM.x * 2 * radius,\n          y: rs.ctrlpts[1] + cpM.y * 2 * radius\n        };\n        var srcCtrlPtIntn = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, cpProj.x, cpProj.y, 0);\n\n        if (closeStartACp) {\n          rs.ctrlpts[0] = rs.ctrlpts[0] + cpM.x * (minCpADist - startACpDist);\n          rs.ctrlpts[1] = rs.ctrlpts[1] + cpM.y * (minCpADist - startACpDist);\n        } else {\n          rs.ctrlpts[0] = srcCtrlPtIntn[0] + cpM.x * minCpADist;\n          rs.ctrlpts[1] = srcCtrlPtIntn[1] + cpM.y * minCpADist;\n        }\n      }\n\n      if (badEnd || badAEnd || closeEndACp) {\n        overlapping = true; // project control point along line from tgt centre to outside the tgt shape\n        // (otherwise intersection will yield nothing)\n\n        var _cpD = {\n          // delta\n          x: rs.ctrlpts[0] - tgtPos.x,\n          y: rs.ctrlpts[1] - tgtPos.y\n        };\n\n        var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line\n\n\n        var _cpM = {\n          // normalised delta\n          x: _cpD.x / _cpL,\n          y: _cpD.y / _cpL\n        };\n\n        var _radius = Math.max(srcW, srcH);\n\n        var _cpProj = {\n          // *2 radius guarantees outside shape\n          x: rs.ctrlpts[0] + _cpM.x * 2 * _radius,\n          y: rs.ctrlpts[1] + _cpM.y * 2 * _radius\n        };\n        var tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0);\n\n        if (closeEndACp) {\n          rs.ctrlpts[0] = rs.ctrlpts[0] + _cpM.x * (minCpADist - endACpDist);\n          rs.ctrlpts[1] = rs.ctrlpts[1] + _cpM.y * (minCpADist - endACpDist);\n        } else {\n          rs.ctrlpts[0] = tgtCtrlPtIntn[0] + _cpM.x * minCpADist;\n          rs.ctrlpts[1] = tgtCtrlPtIntn[1] + _cpM.y * minCpADist;\n        }\n      }\n\n      if (overlapping) {\n        // recalc endpts\n        this.findEndpoints(edge);\n      }\n    }\n  };\n\n  BRp$c.storeAllpts = function (edge) {\n    var rs = edge._private.rscratch;\n\n    if (rs.edgeType === 'multibezier' || rs.edgeType === 'bezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {\n      rs.allpts = [];\n      rs.allpts.push(rs.startX, rs.startY);\n\n      for (var b = 0; b + 1 < rs.ctrlpts.length; b += 2) {\n        // ctrl pt itself\n        rs.allpts.push(rs.ctrlpts[b], rs.ctrlpts[b + 1]); // the midpt between ctrlpts as intermediate destination pts\n\n        if (b + 3 < rs.ctrlpts.length) {\n          rs.allpts.push((rs.ctrlpts[b] + rs.ctrlpts[b + 2]) / 2, (rs.ctrlpts[b + 1] + rs.ctrlpts[b + 3]) / 2);\n        }\n      }\n\n      rs.allpts.push(rs.endX, rs.endY);\n      var m, mt;\n\n      if (rs.ctrlpts.length / 2 % 2 === 0) {\n        m = rs.allpts.length / 2 - 1;\n        rs.midX = rs.allpts[m];\n        rs.midY = rs.allpts[m + 1];\n      } else {\n        m = rs.allpts.length / 2 - 3;\n        mt = 0.5;\n        rs.midX = qbezierAt(rs.allpts[m], rs.allpts[m + 2], rs.allpts[m + 4], mt);\n        rs.midY = qbezierAt(rs.allpts[m + 1], rs.allpts[m + 3], rs.allpts[m + 5], mt);\n      }\n    } else if (rs.edgeType === 'straight') {\n      // need to calc these after endpts\n      rs.allpts = [rs.startX, rs.startY, rs.endX, rs.endY]; // default midpt for labels etc\n\n      rs.midX = (rs.startX + rs.endX + rs.arrowStartX + rs.arrowEndX) / 4;\n      rs.midY = (rs.startY + rs.endY + rs.arrowStartY + rs.arrowEndY) / 4;\n    } else if (rs.edgeType === 'segments') {\n      rs.allpts = [];\n      rs.allpts.push(rs.startX, rs.startY);\n      rs.allpts.push.apply(rs.allpts, rs.segpts);\n      rs.allpts.push(rs.endX, rs.endY);\n\n      if (rs.segpts.length % 4 === 0) {\n        var i2 = rs.segpts.length / 2;\n        var i1 = i2 - 2;\n        rs.midX = (rs.segpts[i1] + rs.segpts[i2]) / 2;\n        rs.midY = (rs.segpts[i1 + 1] + rs.segpts[i2 + 1]) / 2;\n      } else {\n        var _i = rs.segpts.length / 2 - 1;\n\n        rs.midX = rs.segpts[_i];\n        rs.midY = rs.segpts[_i + 1];\n      }\n    }\n  };\n\n  BRp$c.checkForInvalidEdgeWarning = function (edge) {\n    var rs = edge[0]._private.rscratch;\n\n    if (rs.nodesOverlap || number$1(rs.startX) && number$1(rs.startY) && number$1(rs.endX) && number$1(rs.endY)) {\n      rs.loggedErr = false;\n    } else {\n      if (!rs.loggedErr) {\n        rs.loggedErr = true;\n        warn('Edge `' + edge.id() + '` has invalid endpoints and so it is impossible to draw.  Adjust your edge style (e.g. control points) accordingly or use an alternative edge type.  This is expected behaviour when the source node and the target node overlap.');\n      }\n    }\n  };\n\n  BRp$c.findEdgeControlPoints = function (edges) {\n    var _this = this;\n\n    if (!edges || edges.length === 0) {\n      return;\n    }\n\n    var r = this;\n    var cy = r.cy;\n    var hasCompounds = cy.hasCompoundNodes();\n    var hashTable = {\n      map: new Map$2(),\n      get: function get(pairId) {\n        var map2 = this.map.get(pairId[0]);\n\n        if (map2 != null) {\n          return map2.get(pairId[1]);\n        } else {\n          return null;\n        }\n      },\n      set: function set(pairId, val) {\n        var map2 = this.map.get(pairId[0]);\n\n        if (map2 == null) {\n          map2 = new Map$2();\n          this.map.set(pairId[0], map2);\n        }\n\n        map2.set(pairId[1], val);\n      }\n    };\n    var pairIds = [];\n    var haystackEdges = []; // create a table of edge (src, tgt) => list of edges between them\n\n    for (var i = 0; i < edges.length; i++) {\n      var edge = edges[i];\n      var _p = edge._private;\n      var curveStyle = edge.pstyle('curve-style').value; // ignore edges who are not to be displayed\n      // they shouldn't take up space\n\n      if (edge.removed() || !edge.takesUpSpace()) {\n        continue;\n      }\n\n      if (curveStyle === 'haystack') {\n        haystackEdges.push(edge);\n        continue;\n      }\n\n      var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || curveStyle === 'segments' || curveStyle === 'straight' || curveStyle === 'straight-triangle' || curveStyle === 'taxi';\n      var edgeIsBezier = curveStyle === 'unbundled-bezier' || curveStyle === 'bezier';\n      var src = _p.source;\n      var tgt = _p.target;\n      var srcIndex = src.poolIndex();\n      var tgtIndex = tgt.poolIndex();\n      var pairId = [srcIndex, tgtIndex].sort();\n      var tableEntry = hashTable.get(pairId);\n\n      if (tableEntry == null) {\n        tableEntry = {\n          eles: []\n        };\n        hashTable.set(pairId, tableEntry);\n        pairIds.push(pairId);\n      }\n\n      tableEntry.eles.push(edge);\n\n      if (edgeIsUnbundled) {\n        tableEntry.hasUnbundled = true;\n      }\n\n      if (edgeIsBezier) {\n        tableEntry.hasBezier = true;\n      }\n    } // for each pair (src, tgt), create the ctrl pts\n    // Nested for loop is OK; total number of iterations for both loops = edgeCount\n\n\n    var _loop = function _loop(p) {\n      var pairId = pairIds[p];\n      var pairInfo = hashTable.get(pairId);\n      var swappedpairInfo = void 0;\n\n      if (!pairInfo.hasUnbundled) {\n        var pllEdges = pairInfo.eles[0].parallelEdges().filter(function (e) {\n          return e.isBundledBezier();\n        });\n        clearArray(pairInfo.eles);\n        pllEdges.forEach(function (edge) {\n          return pairInfo.eles.push(edge);\n        }); // for each pair id, the edges should be sorted by index\n\n        pairInfo.eles.sort(function (edge1, edge2) {\n          return edge1.poolIndex() - edge2.poolIndex();\n        });\n      }\n\n      var firstEdge = pairInfo.eles[0];\n      var src = firstEdge.source();\n      var tgt = firstEdge.target(); // make sure src/tgt distinction is consistent w.r.t. pairId\n\n      if (src.poolIndex() > tgt.poolIndex()) {\n        var temp = src;\n        src = tgt;\n        tgt = temp;\n      }\n\n      var srcPos = pairInfo.srcPos = src.position();\n      var tgtPos = pairInfo.tgtPos = tgt.position();\n      var srcW = pairInfo.srcW = src.outerWidth();\n      var srcH = pairInfo.srcH = src.outerHeight();\n      var tgtW = pairInfo.tgtW = tgt.outerWidth();\n      var tgtH = pairInfo.tgtH = tgt.outerHeight();\n\n      var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];\n\n      var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];\n\n      pairInfo.dirCounts = {\n        'north': 0,\n        'west': 0,\n        'south': 0,\n        'east': 0,\n        'northwest': 0,\n        'southwest': 0,\n        'northeast': 0,\n        'southeast': 0\n      };\n\n      for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {\n        var _edge = pairInfo.eles[_i2];\n        var rs = _edge[0]._private.rscratch;\n\n        var _curveStyle = _edge.pstyle('curve-style').value;\n\n        var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || _curveStyle === 'segments' || _curveStyle === 'taxi'; // whether the normalised pair order is the reverse of the edge's src-tgt order\n\n\n        var edgeIsSwapped = !src.same(_edge.source());\n\n        if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {\n          pairInfo.calculatedIntersection = true; // pt outside src shape to calc distance/displacement from src to tgt\n\n          var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0);\n          var srcIntn = pairInfo.srcIntn = srcOutside; // pt outside tgt shape to calc distance/displacement from src to tgt\n\n          var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0);\n          var tgtIntn = pairInfo.tgtIntn = tgtOutside;\n          var intersectionPts = pairInfo.intersectionPts = {\n            x1: srcOutside[0],\n            x2: tgtOutside[0],\n            y1: srcOutside[1],\n            y2: tgtOutside[1]\n          };\n          var posPts = pairInfo.posPts = {\n            x1: srcPos.x,\n            x2: tgtPos.x,\n            y1: srcPos.y,\n            y2: tgtPos.y\n          };\n          var dy = tgtOutside[1] - srcOutside[1];\n          var dx = tgtOutside[0] - srcOutside[0];\n          var l = Math.sqrt(dx * dx + dy * dy);\n          var vector = pairInfo.vector = {\n            x: dx,\n            y: dy\n          };\n          var vectorNorm = pairInfo.vectorNorm = {\n            x: vector.x / l,\n            y: vector.y / l\n          };\n          var vectorNormInverse = {\n            x: -vectorNorm.y,\n            y: vectorNorm.x\n          }; // if node shapes overlap, then no ctrl pts to draw\n\n          pairInfo.nodesOverlap = !number$1(l) || tgtShape.checkPoint(srcOutside[0], srcOutside[1], 0, tgtW, tgtH, tgtPos.x, tgtPos.y) || srcShape.checkPoint(tgtOutside[0], tgtOutside[1], 0, srcW, srcH, srcPos.x, srcPos.y);\n          pairInfo.vectorNormInverse = vectorNormInverse;\n          swappedpairInfo = {\n            nodesOverlap: pairInfo.nodesOverlap,\n            dirCounts: pairInfo.dirCounts,\n            calculatedIntersection: true,\n            hasBezier: pairInfo.hasBezier,\n            hasUnbundled: pairInfo.hasUnbundled,\n            eles: pairInfo.eles,\n            srcPos: tgtPos,\n            tgtPos: srcPos,\n            srcW: tgtW,\n            srcH: tgtH,\n            tgtW: srcW,\n            tgtH: srcH,\n            srcIntn: tgtIntn,\n            tgtIntn: srcIntn,\n            srcShape: tgtShape,\n            tgtShape: srcShape,\n            posPts: {\n              x1: posPts.x2,\n              y1: posPts.y2,\n              x2: posPts.x1,\n              y2: posPts.y1\n            },\n            intersectionPts: {\n              x1: intersectionPts.x2,\n              y1: intersectionPts.y2,\n              x2: intersectionPts.x1,\n              y2: intersectionPts.y1\n            },\n            vector: {\n              x: -vector.x,\n              y: -vector.y\n            },\n            vectorNorm: {\n              x: -vectorNorm.x,\n              y: -vectorNorm.y\n            },\n            vectorNormInverse: {\n              x: -vectorNormInverse.x,\n              y: -vectorNormInverse.y\n            }\n          };\n        }\n\n        var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;\n        rs.nodesOverlap = passedPairInfo.nodesOverlap;\n        rs.srcIntn = passedPairInfo.srcIntn;\n        rs.tgtIntn = passedPairInfo.tgtIntn;\n\n        if (hasCompounds && (src.isParent() || src.isChild() || tgt.isParent() || tgt.isChild()) && (src.parents().anySame(tgt) || tgt.parents().anySame(src) || src.same(tgt) && src.isParent())) {\n          _this.findCompoundLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);\n        } else if (src === tgt) {\n          _this.findLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);\n        } else if (_curveStyle === 'segments') {\n          _this.findSegmentsPoints(_edge, passedPairInfo);\n        } else if (_curveStyle === 'taxi') {\n          _this.findTaxiPoints(_edge, passedPairInfo);\n        } else if (_curveStyle === 'straight' || !_edgeIsUnbundled && pairInfo.eles.length % 2 === 1 && _i2 === Math.floor(pairInfo.eles.length / 2)) {\n          _this.findStraightEdgePoints(_edge);\n        } else {\n          _this.findBezierPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled, edgeIsSwapped);\n        }\n\n        _this.findEndpoints(_edge);\n\n        _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);\n\n        _this.checkForInvalidEdgeWarning(_edge);\n\n        _this.storeAllpts(_edge);\n\n        _this.storeEdgeProjections(_edge);\n\n        _this.calculateArrowAngles(_edge);\n\n        _this.recalculateEdgeLabelProjections(_edge);\n\n        _this.calculateLabelAngles(_edge);\n      } // for pair edges\n\n    };\n\n    for (var p = 0; p < pairIds.length; p++) {\n      _loop(p);\n    } // for pair ids\n    // haystacks avoid the expense of pairInfo stuff (intersections etc.)\n\n\n    this.findHaystackPoints(haystackEdges);\n  };\n\n  function getPts(pts) {\n    var retPts = [];\n\n    if (pts == null) {\n      return;\n    }\n\n    for (var i = 0; i < pts.length; i += 2) {\n      var x = pts[i];\n      var y = pts[i + 1];\n      retPts.push({\n        x: x,\n        y: y\n      });\n    }\n\n    return retPts;\n  }\n\n  BRp$c.getSegmentPoints = function (edge) {\n    var rs = edge[0]._private.rscratch;\n    var type = rs.edgeType;\n\n    if (type === 'segments') {\n      this.recalculateRenderedStyle(edge);\n      return getPts(rs.segpts);\n    }\n  };\n\n  BRp$c.getControlPoints = function (edge) {\n    var rs = edge[0]._private.rscratch;\n    var type = rs.edgeType;\n\n    if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {\n      this.recalculateRenderedStyle(edge);\n      return getPts(rs.ctrlpts);\n    }\n  };\n\n  BRp$c.getEdgeMidpoint = function (edge) {\n    var rs = edge[0]._private.rscratch;\n    this.recalculateRenderedStyle(edge);\n    return {\n      x: rs.midX,\n      y: rs.midY\n    };\n  };\n\n  var BRp$b = {};\n\n  BRp$b.manualEndptToPx = function (node, prop) {\n    var r = this;\n    var npos = node.position();\n    var w = node.outerWidth();\n    var h = node.outerHeight();\n\n    if (prop.value.length === 2) {\n      var p = [prop.pfValue[0], prop.pfValue[1]];\n\n      if (prop.units[0] === '%') {\n        p[0] = p[0] * w;\n      }\n\n      if (prop.units[1] === '%') {\n        p[1] = p[1] * h;\n      }\n\n      p[0] += npos.x;\n      p[1] += npos.y;\n      return p;\n    } else {\n      var angle = prop.pfValue[0];\n      angle = -Math.PI / 2 + angle; // start at 12 o'clock\n\n      var l = 2 * Math.max(w, h);\n      var _p = [npos.x + Math.cos(angle) * l, npos.y + Math.sin(angle) * l];\n      return r.nodeShapes[this.getNodeShape(node)].intersectLine(npos.x, npos.y, w, h, _p[0], _p[1], 0);\n    }\n  };\n\n  BRp$b.findEndpoints = function (edge) {\n    var r = this;\n    var intersect;\n    var source = edge.source()[0];\n    var target = edge.target()[0];\n    var srcPos = source.position();\n    var tgtPos = target.position();\n    var tgtArShape = edge.pstyle('target-arrow-shape').value;\n    var srcArShape = edge.pstyle('source-arrow-shape').value;\n    var tgtDist = edge.pstyle('target-distance-from-node').pfValue;\n    var srcDist = edge.pstyle('source-distance-from-node').pfValue;\n    var curveStyle = edge.pstyle('curve-style').value;\n    var rs = edge._private.rscratch;\n    var et = rs.edgeType;\n    var taxi = curveStyle === 'taxi';\n    var self = et === 'self' || et === 'compound';\n    var bezier = et === 'bezier' || et === 'multibezier' || self;\n    var multi = et !== 'bezier';\n    var lines = et === 'straight' || et === 'segments';\n    var segments = et === 'segments';\n    var hasEndpts = bezier || multi || lines;\n    var overrideEndpts = self || taxi;\n    var srcManEndpt = edge.pstyle('source-endpoint');\n    var srcManEndptVal = overrideEndpts ? 'outside-to-node' : srcManEndpt.value;\n    var tgtManEndpt = edge.pstyle('target-endpoint');\n    var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;\n    rs.srcManEndpt = srcManEndpt;\n    rs.tgtManEndpt = tgtManEndpt;\n    var p1; // last known point of edge on target side\n\n    var p2; // last known point of edge on source side\n\n    var p1_i; // point to intersect with target shape\n\n    var p2_i; // point to intersect with source shape\n\n    if (bezier) {\n      var cpStart = [rs.ctrlpts[0], rs.ctrlpts[1]];\n      var cpEnd = multi ? [rs.ctrlpts[rs.ctrlpts.length - 2], rs.ctrlpts[rs.ctrlpts.length - 1]] : cpStart;\n      p1 = cpEnd;\n      p2 = cpStart;\n    } else if (lines) {\n      var srcArrowFromPt = !segments ? [tgtPos.x, tgtPos.y] : rs.segpts.slice(0, 2);\n      var tgtArrowFromPt = !segments ? [srcPos.x, srcPos.y] : rs.segpts.slice(rs.segpts.length - 2);\n      p1 = tgtArrowFromPt;\n      p2 = srcArrowFromPt;\n    }\n\n    if (tgtManEndptVal === 'inside-to-node') {\n      intersect = [tgtPos.x, tgtPos.y];\n    } else if (tgtManEndpt.units) {\n      intersect = this.manualEndptToPx(target, tgtManEndpt);\n    } else if (tgtManEndptVal === 'outside-to-line') {\n      intersect = rs.tgtIntn; // use cached value from ctrlpt calc\n    } else {\n      if (tgtManEndptVal === 'outside-to-node' || tgtManEndptVal === 'outside-to-node-or-label') {\n        p1_i = p1;\n      } else if (tgtManEndptVal === 'outside-to-line' || tgtManEndptVal === 'outside-to-line-or-label') {\n        p1_i = [srcPos.x, srcPos.y];\n      }\n\n      intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0);\n\n      if (tgtManEndptVal === 'outside-to-node-or-label' || tgtManEndptVal === 'outside-to-line-or-label') {\n        var trs = target._private.rscratch;\n        var lw = trs.labelWidth;\n        var lh = trs.labelHeight;\n        var lx = trs.labelX;\n        var ly = trs.labelY;\n        var lw2 = lw / 2;\n        var lh2 = lh / 2;\n        var va = target.pstyle('text-valign').value;\n\n        if (va === 'top') {\n          ly -= lh2;\n        } else if (va === 'bottom') {\n          ly += lh2;\n        }\n\n        var ha = target.pstyle('text-halign').value;\n\n        if (ha === 'left') {\n          lx -= lw2;\n        } else if (ha === 'right') {\n          lx += lw2;\n        }\n\n        var labelIntersect = polygonIntersectLine(p1_i[0], p1_i[1], [lx - lw2, ly - lh2, lx + lw2, ly - lh2, lx + lw2, ly + lh2, lx - lw2, ly + lh2], tgtPos.x, tgtPos.y);\n\n        if (labelIntersect.length > 0) {\n          var refPt = srcPos;\n          var intSqdist = sqdist(refPt, array2point(intersect));\n          var labIntSqdist = sqdist(refPt, array2point(labelIntersect));\n          var minSqDist = intSqdist;\n\n          if (labIntSqdist < intSqdist) {\n            intersect = labelIntersect;\n            minSqDist = labIntSqdist;\n          }\n\n          if (labelIntersect.length > 2) {\n            var labInt2SqDist = sqdist(refPt, {\n              x: labelIntersect[2],\n              y: labelIntersect[3]\n            });\n\n            if (labInt2SqDist < minSqDist) {\n              intersect = [labelIntersect[2], labelIntersect[3]];\n            }\n          }\n        }\n      }\n    }\n\n    var arrowEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].spacing(edge) + tgtDist);\n    var edgeEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].gap(edge) + tgtDist);\n    rs.endX = edgeEnd[0];\n    rs.endY = edgeEnd[1];\n    rs.arrowEndX = arrowEnd[0];\n    rs.arrowEndY = arrowEnd[1];\n\n    if (srcManEndptVal === 'inside-to-node') {\n      intersect = [srcPos.x, srcPos.y];\n    } else if (srcManEndpt.units) {\n      intersect = this.manualEndptToPx(source, srcManEndpt);\n    } else if (srcManEndptVal === 'outside-to-line') {\n      intersect = rs.srcIntn; // use cached value from ctrlpt calc\n    } else {\n      if (srcManEndptVal === 'outside-to-node' || srcManEndptVal === 'outside-to-node-or-label') {\n        p2_i = p2;\n      } else if (srcManEndptVal === 'outside-to-line' || srcManEndptVal === 'outside-to-line-or-label') {\n        p2_i = [tgtPos.x, tgtPos.y];\n      }\n\n      intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0);\n\n      if (srcManEndptVal === 'outside-to-node-or-label' || srcManEndptVal === 'outside-to-line-or-label') {\n        var srs = source._private.rscratch;\n        var _lw = srs.labelWidth;\n        var _lh = srs.labelHeight;\n        var _lx = srs.labelX;\n        var _ly = srs.labelY;\n\n        var _lw2 = _lw / 2;\n\n        var _lh2 = _lh / 2;\n\n        var _va = source.pstyle('text-valign').value;\n\n        if (_va === 'top') {\n          _ly -= _lh2;\n        } else if (_va === 'bottom') {\n          _ly += _lh2;\n        }\n\n        var _ha = source.pstyle('text-halign').value;\n\n        if (_ha === 'left') {\n          _lx -= _lw2;\n        } else if (_ha === 'right') {\n          _lx += _lw2;\n        }\n\n        var _labelIntersect = polygonIntersectLine(p2_i[0], p2_i[1], [_lx - _lw2, _ly - _lh2, _lx + _lw2, _ly - _lh2, _lx + _lw2, _ly + _lh2, _lx - _lw2, _ly + _lh2], srcPos.x, srcPos.y);\n\n        if (_labelIntersect.length > 0) {\n          var _refPt = tgtPos;\n\n          var _intSqdist = sqdist(_refPt, array2point(intersect));\n\n          var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));\n\n          var _minSqDist = _intSqdist;\n\n          if (_labIntSqdist < _intSqdist) {\n            intersect = [_labelIntersect[0], _labelIntersect[1]];\n            _minSqDist = _labIntSqdist;\n          }\n\n          if (_labelIntersect.length > 2) {\n            var _labInt2SqDist = sqdist(_refPt, {\n              x: _labelIntersect[2],\n              y: _labelIntersect[3]\n            });\n\n            if (_labInt2SqDist < _minSqDist) {\n              intersect = [_labelIntersect[2], _labelIntersect[3]];\n            }\n          }\n        }\n      }\n    }\n\n    var arrowStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].spacing(edge) + srcDist);\n    var edgeStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].gap(edge) + srcDist);\n    rs.startX = edgeStart[0];\n    rs.startY = edgeStart[1];\n    rs.arrowStartX = arrowStart[0];\n    rs.arrowStartY = arrowStart[1];\n\n    if (hasEndpts) {\n      if (!number$1(rs.startX) || !number$1(rs.startY) || !number$1(rs.endX) || !number$1(rs.endY)) {\n        rs.badLine = true;\n      } else {\n        rs.badLine = false;\n      }\n    }\n  };\n\n  BRp$b.getSourceEndpoint = function (edge) {\n    var rs = edge[0]._private.rscratch;\n    this.recalculateRenderedStyle(edge);\n\n    switch (rs.edgeType) {\n      case 'haystack':\n        return {\n          x: rs.haystackPts[0],\n          y: rs.haystackPts[1]\n        };\n\n      default:\n        return {\n          x: rs.arrowStartX,\n          y: rs.arrowStartY\n        };\n    }\n  };\n\n  BRp$b.getTargetEndpoint = function (edge) {\n    var rs = edge[0]._private.rscratch;\n    this.recalculateRenderedStyle(edge);\n\n    switch (rs.edgeType) {\n      case 'haystack':\n        return {\n          x: rs.haystackPts[2],\n          y: rs.haystackPts[3]\n        };\n\n      default:\n        return {\n          x: rs.arrowEndX,\n          y: rs.arrowEndY\n        };\n    }\n  };\n\n  var BRp$a = {};\n\n  function pushBezierPts(r, edge, pts) {\n    var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {\n      return qbezierAt(p1, p2, p3, t);\n    };\n\n    var _p = edge._private;\n    var bpts = _p.rstyle.bezierPts;\n\n    for (var i = 0; i < r.bezierProjPcts.length; i++) {\n      var p = r.bezierProjPcts[i];\n      bpts.push({\n        x: qbezierAt$1(pts[0], pts[2], pts[4], p),\n        y: qbezierAt$1(pts[1], pts[3], pts[5], p)\n      });\n    }\n  }\n\n  BRp$a.storeEdgeProjections = function (edge) {\n    var _p = edge._private;\n    var rs = _p.rscratch;\n    var et = rs.edgeType; // clear the cached points state\n\n    _p.rstyle.bezierPts = null;\n    _p.rstyle.linePts = null;\n    _p.rstyle.haystackPts = null;\n\n    if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {\n      _p.rstyle.bezierPts = [];\n\n      for (var i = 0; i + 5 < rs.allpts.length; i += 4) {\n        pushBezierPts(this, edge, rs.allpts.slice(i, i + 6));\n      }\n    } else if (et === 'segments') {\n      var lpts = _p.rstyle.linePts = [];\n\n      for (var i = 0; i + 1 < rs.allpts.length; i += 2) {\n        lpts.push({\n          x: rs.allpts[i],\n          y: rs.allpts[i + 1]\n        });\n      }\n    } else if (et === 'haystack') {\n      var hpts = rs.haystackPts;\n      _p.rstyle.haystackPts = [{\n        x: hpts[0],\n        y: hpts[1]\n      }, {\n        x: hpts[2],\n        y: hpts[3]\n      }];\n    }\n\n    _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;\n  };\n\n  BRp$a.recalculateEdgeProjections = function (edges) {\n    this.findEdgeControlPoints(edges);\n  };\n\n  /* global document */\n\n  var BRp$9 = {};\n\n  BRp$9.recalculateNodeLabelProjection = function (node) {\n    var content = node.pstyle('label').strValue;\n\n    if (emptyString(content)) {\n      return;\n    }\n\n    var textX, textY;\n    var _p = node._private;\n    var nodeWidth = node.width();\n    var nodeHeight = node.height();\n    var padding = node.padding();\n    var nodePos = node.position();\n    var textHalign = node.pstyle('text-halign').strValue;\n    var textValign = node.pstyle('text-valign').strValue;\n    var rs = _p.rscratch;\n    var rstyle = _p.rstyle;\n\n    switch (textHalign) {\n      case 'left':\n        textX = nodePos.x - nodeWidth / 2 - padding;\n        break;\n\n      case 'right':\n        textX = nodePos.x + nodeWidth / 2 + padding;\n        break;\n\n      default:\n        // e.g. center\n        textX = nodePos.x;\n    }\n\n    switch (textValign) {\n      case 'top':\n        textY = nodePos.y - nodeHeight / 2 - padding;\n        break;\n\n      case 'bottom':\n        textY = nodePos.y + nodeHeight / 2 + padding;\n        break;\n\n      default:\n        // e.g. middle\n        textY = nodePos.y;\n    }\n\n    rs.labelX = textX;\n    rs.labelY = textY;\n    rstyle.labelX = textX;\n    rstyle.labelY = textY;\n    this.calculateLabelAngles(node);\n    this.applyLabelDimensions(node);\n  };\n\n  var lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {\n    var angle = Math.atan(dy / dx);\n\n    if (dx === 0 && angle < 0) {\n      angle = angle * -1;\n    }\n\n    return angle;\n  };\n\n  var lineAngle = function lineAngle(p0, p1) {\n    var dx = p1.x - p0.x;\n    var dy = p1.y - p0.y;\n    return lineAngleFromDelta(dx, dy);\n  };\n\n  var bezierAngle = function bezierAngle(p0, p1, p2, t) {\n    var t0 = bound(0, t - 0.001, 1);\n    var t1 = bound(0, t + 0.001, 1);\n    var lp0 = qbezierPtAt(p0, p1, p2, t0);\n    var lp1 = qbezierPtAt(p0, p1, p2, t1);\n    return lineAngle(lp0, lp1);\n  };\n\n  BRp$9.recalculateEdgeLabelProjections = function (edge) {\n    var p;\n    var _p = edge._private;\n    var rs = _p.rscratch;\n    var r = this;\n    var content = {\n      mid: edge.pstyle('label').strValue,\n      source: edge.pstyle('source-label').strValue,\n      target: edge.pstyle('target-label').strValue\n    };\n\n    if (content.mid || content.source || content.target) ; else {\n      return; // no labels => no calcs\n    } // add center point to style so bounding box calculations can use it\n    //\n\n\n    p = {\n      x: rs.midX,\n      y: rs.midY\n    };\n\n    var setRs = function setRs(propName, prefix, value) {\n      setPrefixedProperty(_p.rscratch, propName, prefix, value);\n      setPrefixedProperty(_p.rstyle, propName, prefix, value);\n    };\n\n    setRs('labelX', null, p.x);\n    setRs('labelY', null, p.y);\n    var midAngle = lineAngleFromDelta(rs.midDispX, rs.midDispY);\n    setRs('labelAutoAngle', null, midAngle);\n\n    var createControlPointInfo = function createControlPointInfo() {\n      if (createControlPointInfo.cache) {\n        return createControlPointInfo.cache;\n      } // use cache so only 1x per edge\n\n\n      var ctrlpts = []; // store each ctrlpt info init\n\n      for (var i = 0; i + 5 < rs.allpts.length; i += 4) {\n        var p0 = {\n          x: rs.allpts[i],\n          y: rs.allpts[i + 1]\n        };\n        var p1 = {\n          x: rs.allpts[i + 2],\n          y: rs.allpts[i + 3]\n        }; // ctrlpt\n\n        var p2 = {\n          x: rs.allpts[i + 4],\n          y: rs.allpts[i + 5]\n        };\n        ctrlpts.push({\n          p0: p0,\n          p1: p1,\n          p2: p2,\n          startDist: 0,\n          length: 0,\n          segments: []\n        });\n      }\n\n      var bpts = _p.rstyle.bezierPts;\n      var nProjs = r.bezierProjPcts.length;\n\n      function addSegment(cp, p0, p1, t0, t1) {\n        var length = dist(p0, p1);\n        var prevSegment = cp.segments[cp.segments.length - 1];\n        var segment = {\n          p0: p0,\n          p1: p1,\n          t0: t0,\n          t1: t1,\n          startDist: prevSegment ? prevSegment.startDist + prevSegment.length : 0,\n          length: length\n        };\n        cp.segments.push(segment);\n        cp.length += length;\n      } // update each ctrlpt with segment info\n\n\n      for (var _i = 0; _i < ctrlpts.length; _i++) {\n        var cp = ctrlpts[_i];\n        var prevCp = ctrlpts[_i - 1];\n\n        if (prevCp) {\n          cp.startDist = prevCp.startDist + prevCp.length;\n        }\n\n        addSegment(cp, cp.p0, bpts[_i * nProjs], 0, r.bezierProjPcts[0]); // first\n\n        for (var j = 0; j < nProjs - 1; j++) {\n          addSegment(cp, bpts[_i * nProjs + j], bpts[_i * nProjs + j + 1], r.bezierProjPcts[j], r.bezierProjPcts[j + 1]);\n        }\n\n        addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last\n      }\n\n      return createControlPointInfo.cache = ctrlpts;\n    };\n\n    var calculateEndProjection = function calculateEndProjection(prefix) {\n      var angle;\n      var isSrc = prefix === 'source';\n\n      if (!content[prefix]) {\n        return;\n      }\n\n      var offset = edge.pstyle(prefix + '-text-offset').pfValue;\n\n      switch (rs.edgeType) {\n        case 'self':\n        case 'compound':\n        case 'bezier':\n        case 'multibezier':\n          {\n            var cps = createControlPointInfo();\n            var selected;\n            var startDist = 0;\n            var totalDist = 0; // find the segment we're on\n\n            for (var i = 0; i < cps.length; i++) {\n              var _cp = cps[isSrc ? i : cps.length - 1 - i];\n\n              for (var j = 0; j < _cp.segments.length; j++) {\n                var _seg = _cp.segments[isSrc ? j : _cp.segments.length - 1 - j];\n                var lastSeg = i === cps.length - 1 && j === _cp.segments.length - 1;\n                startDist = totalDist;\n                totalDist += _seg.length;\n\n                if (totalDist >= offset || lastSeg) {\n                  selected = {\n                    cp: _cp,\n                    segment: _seg\n                  };\n                  break;\n                }\n              }\n\n              if (selected) {\n                break;\n              }\n            }\n\n            var cp = selected.cp;\n            var seg = selected.segment;\n            var tSegment = (offset - startDist) / seg.length;\n            var segDt = seg.t1 - seg.t0;\n            var t = isSrc ? seg.t0 + segDt * tSegment : seg.t1 - segDt * tSegment;\n            t = bound(0, t, 1);\n            p = qbezierPtAt(cp.p0, cp.p1, cp.p2, t);\n            angle = bezierAngle(cp.p0, cp.p1, cp.p2, t);\n            break;\n          }\n\n        case 'straight':\n        case 'segments':\n        case 'haystack':\n          {\n            var d = 0,\n                di,\n                d0;\n            var p0, p1;\n            var l = rs.allpts.length;\n\n            for (var _i2 = 0; _i2 + 3 < l; _i2 += 2) {\n              if (isSrc) {\n                p0 = {\n                  x: rs.allpts[_i2],\n                  y: rs.allpts[_i2 + 1]\n                };\n                p1 = {\n                  x: rs.allpts[_i2 + 2],\n                  y: rs.allpts[_i2 + 3]\n                };\n              } else {\n                p0 = {\n                  x: rs.allpts[l - 2 - _i2],\n                  y: rs.allpts[l - 1 - _i2]\n                };\n                p1 = {\n                  x: rs.allpts[l - 4 - _i2],\n                  y: rs.allpts[l - 3 - _i2]\n                };\n              }\n\n              di = dist(p0, p1);\n              d0 = d;\n              d += di;\n\n              if (d >= offset) {\n                break;\n              }\n            }\n\n            var pD = offset - d0;\n\n            var _t = pD / di;\n\n            _t = bound(0, _t, 1);\n            p = lineAt(p0, p1, _t);\n            angle = lineAngle(p0, p1);\n            break;\n          }\n      }\n\n      setRs('labelX', prefix, p.x);\n      setRs('labelY', prefix, p.y);\n      setRs('labelAutoAngle', prefix, angle);\n    };\n\n    calculateEndProjection('source');\n    calculateEndProjection('target');\n    this.applyLabelDimensions(edge);\n  };\n\n  BRp$9.applyLabelDimensions = function (ele) {\n    this.applyPrefixedLabelDimensions(ele);\n\n    if (ele.isEdge()) {\n      this.applyPrefixedLabelDimensions(ele, 'source');\n      this.applyPrefixedLabelDimensions(ele, 'target');\n    }\n  };\n\n  BRp$9.applyPrefixedLabelDimensions = function (ele, prefix) {\n    var _p = ele._private;\n    var text = this.getLabelText(ele, prefix);\n    var labelDims = this.calculateLabelDimensions(ele, text);\n    var lineHeight = ele.pstyle('line-height').pfValue;\n    var textWrap = ele.pstyle('text-wrap').strValue;\n    var lines = getPrefixedProperty(_p.rscratch, 'labelWrapCachedLines', prefix) || [];\n    var numLines = textWrap !== 'wrap' ? 1 : Math.max(lines.length, 1);\n    var normPerLineHeight = labelDims.height / numLines;\n    var labelLineHeight = normPerLineHeight * lineHeight;\n    var width = labelDims.width;\n    var height = labelDims.height + (numLines - 1) * (lineHeight - 1) * normPerLineHeight;\n    setPrefixedProperty(_p.rstyle, 'labelWidth', prefix, width);\n    setPrefixedProperty(_p.rscratch, 'labelWidth', prefix, width);\n    setPrefixedProperty(_p.rstyle, 'labelHeight', prefix, height);\n    setPrefixedProperty(_p.rscratch, 'labelHeight', prefix, height);\n    setPrefixedProperty(_p.rscratch, 'labelLineHeight', prefix, labelLineHeight);\n  };\n\n  BRp$9.getLabelText = function (ele, prefix) {\n    var _p = ele._private;\n    var pfd = prefix ? prefix + '-' : '';\n    var text = ele.pstyle(pfd + 'label').strValue;\n    var textTransform = ele.pstyle('text-transform').value;\n\n    var rscratch = function rscratch(propName, value) {\n      if (value) {\n        setPrefixedProperty(_p.rscratch, propName, prefix, value);\n        return value;\n      } else {\n        return getPrefixedProperty(_p.rscratch, propName, prefix);\n      }\n    }; // for empty text, skip all processing\n\n\n    if (!text) {\n      return '';\n    }\n\n    if (textTransform == 'none') ; else if (textTransform == 'uppercase') {\n      text = text.toUpperCase();\n    } else if (textTransform == 'lowercase') {\n      text = text.toLowerCase();\n    }\n\n    var wrapStyle = ele.pstyle('text-wrap').value;\n\n    if (wrapStyle === 'wrap') {\n      var labelKey = rscratch('labelKey'); // save recalc if the label is the same as before\n\n      if (labelKey != null && rscratch('labelWrapKey') === labelKey) {\n        return rscratch('labelWrapCachedText');\n      }\n\n      var zwsp = \"\\u200B\";\n      var lines = text.split('\\n');\n      var maxW = ele.pstyle('text-max-width').pfValue;\n      var overflow = ele.pstyle('text-overflow-wrap').value;\n      var overflowAny = overflow === 'anywhere';\n      var wrappedLines = [];\n      var wordsRegex = /[\\s\\u200b]+/;\n      var wordSeparator = overflowAny ? '' : ' ';\n\n      for (var l = 0; l < lines.length; l++) {\n        var line = lines[l];\n        var lineDims = this.calculateLabelDimensions(ele, line);\n        var lineW = lineDims.width;\n\n        if (overflowAny) {\n          var processedLine = line.split('').join(zwsp);\n          line = processedLine;\n        }\n\n        if (lineW > maxW) {\n          // line is too long\n          var words = line.split(wordsRegex);\n          var subline = '';\n\n          for (var w = 0; w < words.length; w++) {\n            var word = words[w];\n            var testLine = subline.length === 0 ? word : subline + wordSeparator + word;\n            var testDims = this.calculateLabelDimensions(ele, testLine);\n            var testW = testDims.width;\n\n            if (testW <= maxW) {\n              // word fits on current line\n              subline += word + wordSeparator;\n            } else {\n              // word starts new line\n              if (subline) {\n                wrappedLines.push(subline);\n              }\n\n              subline = word + wordSeparator;\n            }\n          } // if there's remaining text, put it in a wrapped line\n\n\n          if (!subline.match(/^[\\s\\u200b]+$/)) {\n            wrappedLines.push(subline);\n          }\n        } else {\n          // line is already short enough\n          wrappedLines.push(line);\n        }\n      } // for\n\n\n      rscratch('labelWrapCachedLines', wrappedLines);\n      text = rscratch('labelWrapCachedText', wrappedLines.join('\\n'));\n      rscratch('labelWrapKey', labelKey);\n    } else if (wrapStyle === 'ellipsis') {\n      var _maxW = ele.pstyle('text-max-width').pfValue;\n      var ellipsized = '';\n      var ellipsis = \"\\u2026\";\n      var incLastCh = false;\n\n      if (this.calculateLabelDimensions(ele, text).width < _maxW) {\n        // the label already fits\n        return text;\n      }\n\n      for (var i = 0; i < text.length; i++) {\n        var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;\n\n        if (widthWithNextCh > _maxW) {\n          break;\n        }\n\n        ellipsized += text[i];\n\n        if (i === text.length - 1) {\n          incLastCh = true;\n        }\n      }\n\n      if (!incLastCh) {\n        ellipsized += ellipsis;\n      }\n\n      return ellipsized;\n    } // if ellipsize\n\n\n    return text;\n  };\n\n  BRp$9.getLabelJustification = function (ele) {\n    var justification = ele.pstyle('text-justification').strValue;\n    var textHalign = ele.pstyle('text-halign').strValue;\n\n    if (justification === 'auto') {\n      if (ele.isNode()) {\n        switch (textHalign) {\n          case 'left':\n            return 'right';\n\n          case 'right':\n            return 'left';\n\n          default:\n            return 'center';\n        }\n      } else {\n        return 'center';\n      }\n    } else {\n      return justification;\n    }\n  };\n\n  BRp$9.calculateLabelDimensions = function (ele, text) {\n    var r = this;\n    var cacheKey = hashString(text, ele._private.labelDimsKey);\n    var cache = r.labelDimCache || (r.labelDimCache = []);\n    var existingVal = cache[cacheKey];\n\n    if (existingVal != null) {\n      return existingVal;\n    }\n\n    var padding = 0; // add padding around text dims, as the measurement isn't that accurate\n\n    var fStyle = ele.pstyle('font-style').strValue;\n    var size = ele.pstyle('font-size').pfValue;\n    var family = ele.pstyle('font-family').strValue;\n    var weight = ele.pstyle('font-weight').strValue;\n    var canvas = this.labelCalcCanvas;\n    var c2d = this.labelCalcCanvasContext;\n\n    if (!canvas) {\n      canvas = this.labelCalcCanvas = document.createElement('canvas');\n      c2d = this.labelCalcCanvasContext = canvas.getContext('2d');\n      var ds = canvas.style;\n      ds.position = 'absolute';\n      ds.left = '-9999px';\n      ds.top = '-9999px';\n      ds.zIndex = '-1';\n      ds.visibility = 'hidden';\n      ds.pointerEvents = 'none';\n    }\n\n    c2d.font = \"\".concat(fStyle, \" \").concat(weight, \" \").concat(size, \"px \").concat(family);\n    var width = 0;\n    var height = 0;\n    var lines = text.split('\\n');\n\n    for (var i = 0; i < lines.length; i++) {\n      var line = lines[i];\n      var metrics = c2d.measureText(line);\n      var w = Math.ceil(metrics.width);\n      var h = size;\n      width = Math.max(w, width);\n      height += h;\n    }\n\n    width += padding;\n    height += padding;\n    return cache[cacheKey] = {\n      width: width,\n      height: height\n    };\n  };\n\n  BRp$9.calculateLabelAngle = function (ele, prefix) {\n    var _p = ele._private;\n    var rs = _p.rscratch;\n    var isEdge = ele.isEdge();\n    var prefixDash = prefix ? prefix + '-' : '';\n    var rot = ele.pstyle(prefixDash + 'text-rotation');\n    var rotStr = rot.strValue;\n\n    if (rotStr === 'none') {\n      return 0;\n    } else if (isEdge && rotStr === 'autorotate') {\n      return rs.labelAutoAngle;\n    } else if (rotStr === 'autorotate') {\n      return 0;\n    } else {\n      return rot.pfValue;\n    }\n  };\n\n  BRp$9.calculateLabelAngles = function (ele) {\n    var r = this;\n    var isEdge = ele.isEdge();\n    var _p = ele._private;\n    var rs = _p.rscratch;\n    rs.labelAngle = r.calculateLabelAngle(ele);\n\n    if (isEdge) {\n      rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');\n      rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');\n    }\n  };\n\n  var BRp$8 = {};\n  var TOO_SMALL_CUT_RECT = 28;\n  var warnedCutRect = false;\n\n  BRp$8.getNodeShape = function (node) {\n    var r = this;\n    var shape = node.pstyle('shape').value;\n\n    if (shape === 'cutrectangle' && (node.width() < TOO_SMALL_CUT_RECT || node.height() < TOO_SMALL_CUT_RECT)) {\n      if (!warnedCutRect) {\n        warn('The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead');\n        warnedCutRect = true;\n      }\n\n      return 'rectangle';\n    }\n\n    if (node.isParent()) {\n      if (shape === 'rectangle' || shape === 'roundrectangle' || shape === 'round-rectangle' || shape === 'cutrectangle' || shape === 'cut-rectangle' || shape === 'barrel') {\n        return shape;\n      } else {\n        return 'rectangle';\n      }\n    }\n\n    if (shape === 'polygon') {\n      var points = node.pstyle('shape-polygon-points').value;\n      return r.nodeShapes.makePolygon(points).name;\n    }\n\n    return shape;\n  };\n\n  var BRp$7 = {};\n\n  BRp$7.registerCalculationListeners = function () {\n    var cy = this.cy;\n    var elesToUpdate = cy.collection();\n    var r = this;\n\n    var enqueue = function enqueue(eles) {\n      var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n      elesToUpdate.merge(eles);\n\n      if (dirtyStyleCaches) {\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          var _p = ele._private;\n          var rstyle = _p.rstyle;\n          rstyle.clean = false;\n          rstyle.cleanConnected = false;\n        }\n      }\n    };\n\n    r.binder(cy).on('bounds.* dirty.*', function onDirtyBounds(e) {\n      var ele = e.target;\n      enqueue(ele);\n    }).on('style.* background.*', function onDirtyStyle(e) {\n      var ele = e.target;\n      enqueue(ele, false);\n    });\n\n    var updateEleCalcs = function updateEleCalcs(willDraw) {\n      if (willDraw) {\n        var fns = r.onUpdateEleCalcsFns; // because we need to have up-to-date style (e.g. stylesheet mappers)\n        // before calculating rendered style (and pstyle might not be called yet)\n\n        elesToUpdate.cleanStyle();\n\n        for (var i = 0; i < elesToUpdate.length; i++) {\n          var ele = elesToUpdate[i];\n          var rstyle = ele._private.rstyle;\n\n          if (ele.isNode() && !rstyle.cleanConnected) {\n            enqueue(ele.connectedEdges());\n            rstyle.cleanConnected = true;\n          }\n        }\n\n        if (fns) {\n          for (var _i = 0; _i < fns.length; _i++) {\n            var fn = fns[_i];\n            fn(willDraw, elesToUpdate);\n          }\n        }\n\n        r.recalculateRenderedStyle(elesToUpdate);\n        elesToUpdate = cy.collection();\n      }\n    };\n\n    r.flushRenderedStyleQueue = function () {\n      updateEleCalcs(true);\n    };\n\n    r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);\n  };\n\n  BRp$7.onUpdateEleCalcs = function (fn) {\n    var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];\n    fns.push(fn);\n  };\n\n  BRp$7.recalculateRenderedStyle = function (eles, useCache) {\n    var isCleanConnected = function isCleanConnected(ele) {\n      return ele._private.rstyle.cleanConnected;\n    };\n\n    var edges = [];\n    var nodes = []; // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()\n\n    if (this.destroyed) {\n      return;\n    } // use cache by default for perf\n\n\n    if (useCache === undefined) {\n      useCache = true;\n    }\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      var _p = ele._private;\n      var rstyle = _p.rstyle; // an edge may be implicitly dirty b/c of one of its connected nodes\n      // (and a request for recalc may come in between frames)\n\n      if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {\n        rstyle.clean = false;\n      } // only update if dirty and in graph\n\n\n      if (useCache && rstyle.clean || ele.removed()) {\n        continue;\n      } // only update if not display: none\n\n\n      if (ele.pstyle('display').value === 'none') {\n        continue;\n      }\n\n      if (_p.group === 'nodes') {\n        nodes.push(ele);\n      } else {\n        // edges\n        edges.push(ele);\n      }\n\n      rstyle.clean = true;\n    } // update node data from projections\n\n\n    for (var _i2 = 0; _i2 < nodes.length; _i2++) {\n      var _ele = nodes[_i2];\n      var _p2 = _ele._private;\n      var _rstyle = _p2.rstyle;\n\n      var pos = _ele.position();\n\n      this.recalculateNodeLabelProjection(_ele);\n      _rstyle.nodeX = pos.x;\n      _rstyle.nodeY = pos.y;\n      _rstyle.nodeW = _ele.pstyle('width').pfValue;\n      _rstyle.nodeH = _ele.pstyle('height').pfValue;\n    }\n\n    this.recalculateEdgeProjections(edges); // update edge data from projections\n\n    for (var _i3 = 0; _i3 < edges.length; _i3++) {\n      var _ele2 = edges[_i3];\n      var _p3 = _ele2._private;\n      var _rstyle2 = _p3.rstyle;\n      var rs = _p3.rscratch; // update rstyle positions\n\n      _rstyle2.srcX = rs.arrowStartX;\n      _rstyle2.srcY = rs.arrowStartY;\n      _rstyle2.tgtX = rs.arrowEndX;\n      _rstyle2.tgtY = rs.arrowEndY;\n      _rstyle2.midX = rs.midX;\n      _rstyle2.midY = rs.midY;\n      _rstyle2.labelAngle = rs.labelAngle;\n      _rstyle2.sourceLabelAngle = rs.sourceLabelAngle;\n      _rstyle2.targetLabelAngle = rs.targetLabelAngle;\n    }\n  };\n\n  var BRp$6 = {};\n\n  BRp$6.updateCachedGrabbedEles = function () {\n    var eles = this.cachedZSortedEles;\n\n    if (!eles) {\n      // just let this be recalculated on the next z sort tick\n      return;\n    }\n\n    eles.drag = [];\n    eles.nondrag = [];\n    var grabTargets = [];\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      var rs = ele._private.rscratch;\n\n      if (ele.grabbed() && !ele.isParent()) {\n        grabTargets.push(ele);\n      } else if (rs.inDragLayer) {\n        eles.drag.push(ele);\n      } else {\n        eles.nondrag.push(ele);\n      }\n    } // put the grab target nodes last so it's on top of its neighbourhood\n\n\n    for (var i = 0; i < grabTargets.length; i++) {\n      var ele = grabTargets[i];\n      eles.drag.push(ele);\n    }\n  };\n\n  BRp$6.invalidateCachedZSortedEles = function () {\n    this.cachedZSortedEles = null;\n  };\n\n  BRp$6.getCachedZSortedEles = function (forceRecalc) {\n    if (forceRecalc || !this.cachedZSortedEles) {\n      var eles = this.cy.mutableElements().toArray();\n      eles.sort(zIndexSort);\n      eles.interactive = eles.filter(function (ele) {\n        return ele.interactive();\n      });\n      this.cachedZSortedEles = eles;\n      this.updateCachedGrabbedEles();\n    } else {\n      eles = this.cachedZSortedEles;\n    }\n\n    return eles;\n  };\n\n  var BRp$5 = {};\n  [BRp$e, BRp$d, BRp$c, BRp$b, BRp$a, BRp$9, BRp$8, BRp$7, BRp$6].forEach(function (props) {\n    extend(BRp$5, props);\n  });\n\n  var BRp$4 = {};\n\n  BRp$4.getCachedImage = function (url, crossOrigin, onLoad) {\n    var r = this;\n    var imageCache = r.imageCache = r.imageCache || {};\n    var cache = imageCache[url];\n\n    if (cache) {\n      if (!cache.image.complete) {\n        cache.image.addEventListener('load', onLoad);\n      }\n\n      return cache.image;\n    } else {\n      cache = imageCache[url] = imageCache[url] || {};\n      var image = cache.image = new Image(); // eslint-disable-line no-undef\n\n      image.addEventListener('load', onLoad);\n      image.addEventListener('error', function () {\n        image.error = true;\n      }); // #1582 safari doesn't load data uris with crossOrigin properly\n      // https://bugs.webkit.org/show_bug.cgi?id=123978\n\n      var dataUriPrefix = 'data:';\n      var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;\n\n      if (!isDataUri) {\n        // if crossorigin is 'null'(stringified), then manually set it to null \n        crossOrigin = crossOrigin === 'null' ? null : crossOrigin;\n        image.crossOrigin = crossOrigin; // prevent tainted canvas\n      }\n\n      image.src = url;\n      return image;\n    }\n  };\n\n  var BRp$3 = {};\n  /* global document, window, ResizeObserver, MutationObserver */\n\n  BRp$3.registerBinding = function (target, event, handler, useCapture) {\n    // eslint-disable-line no-unused-vars\n    var args = Array.prototype.slice.apply(arguments, [1]); // copy\n\n    var b = this.binder(target);\n    return b.on.apply(b, args);\n  };\n\n  BRp$3.binder = function (tgt) {\n    var r = this;\n    var containerWindow = r.cy.window();\n    var tgtIsDom = tgt === containerWindow || tgt === containerWindow.document || tgt === containerWindow.document.body || domElement(tgt);\n\n    if (r.supportsPassiveEvents == null) {\n      // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection\n      var supportsPassive = false;\n\n      try {\n        var opts = Object.defineProperty({}, 'passive', {\n          get: function get() {\n            supportsPassive = true;\n            return true;\n          }\n        });\n        containerWindow.addEventListener('test', null, opts);\n      } catch (err) {// not supported\n      }\n\n      r.supportsPassiveEvents = supportsPassive;\n    }\n\n    var on = function on(event, handler, useCapture) {\n      var args = Array.prototype.slice.call(arguments);\n\n      if (tgtIsDom && r.supportsPassiveEvents) {\n        // replace useCapture w/ opts obj\n        args[2] = {\n          capture: useCapture != null ? useCapture : false,\n          passive: false,\n          once: false\n        };\n      }\n\n      r.bindings.push({\n        target: tgt,\n        args: args\n      });\n      (tgt.addEventListener || tgt.on).apply(tgt, args);\n      return this;\n    };\n\n    return {\n      on: on,\n      addEventListener: on,\n      addListener: on,\n      bind: on\n    };\n  };\n\n  BRp$3.nodeIsDraggable = function (node) {\n    return node && node.isNode() && !node.locked() && node.grabbable();\n  };\n\n  BRp$3.nodeIsGrabbable = function (node) {\n    return this.nodeIsDraggable(node) && node.interactive();\n  };\n\n  BRp$3.load = function () {\n    var r = this;\n    var containerWindow = r.cy.window();\n\n    var isSelected = function isSelected(ele) {\n      return ele.selected();\n    };\n\n    var triggerEvents = function triggerEvents(target, names, e, position) {\n      if (target == null) {\n        target = r.cy;\n      }\n\n      for (var i = 0; i < names.length; i++) {\n        var name = names[i];\n        target.emit({\n          originalEvent: e,\n          type: name,\n          position: position\n        });\n      }\n    };\n\n    var isMultSelKeyDown = function isMultSelKeyDown(e) {\n      return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey\n    };\n\n    var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {\n      var allowPassthrough = true;\n\n      if (r.cy.hasCompoundNodes() && down && down.pannable()) {\n        // a grabbable compound node below the ele => no passthrough panning\n        for (var i = 0; downs && i < downs.length; i++) {\n          var down = downs[i]; //if any parent node in event hierarchy isn't pannable, reject passthrough\n\n          if (down.isNode() && down.isParent() && !down.pannable()) {\n            allowPassthrough = false;\n            break;\n          }\n        }\n      } else {\n        allowPassthrough = true;\n      }\n\n      return allowPassthrough;\n    };\n\n    var setGrabbed = function setGrabbed(ele) {\n      ele[0]._private.grabbed = true;\n    };\n\n    var setFreed = function setFreed(ele) {\n      ele[0]._private.grabbed = false;\n    };\n\n    var setInDragLayer = function setInDragLayer(ele) {\n      ele[0]._private.rscratch.inDragLayer = true;\n    };\n\n    var setOutDragLayer = function setOutDragLayer(ele) {\n      ele[0]._private.rscratch.inDragLayer = false;\n    };\n\n    var setGrabTarget = function setGrabTarget(ele) {\n      ele[0]._private.rscratch.isGrabTarget = true;\n    };\n\n    var removeGrabTarget = function removeGrabTarget(ele) {\n      ele[0]._private.rscratch.isGrabTarget = false;\n    };\n\n    var addToDragList = function addToDragList(ele, opts) {\n      var list = opts.addToList;\n      var listHasEle = list.has(ele);\n\n      if (!listHasEle && ele.grabbable() && !ele.locked()) {\n        list.merge(ele);\n        setGrabbed(ele);\n      }\n    }; // helper function to determine which child nodes and inner edges\n    // of a compound node to be dragged as well as the grabbed and selected nodes\n\n\n    var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {\n      if (!node.cy().hasCompoundNodes()) {\n        return;\n      }\n\n      if (opts.inDragLayer == null && opts.addToList == null) {\n        return;\n      } // nothing to do\n\n\n      var innerNodes = node.descendants();\n\n      if (opts.inDragLayer) {\n        innerNodes.forEach(setInDragLayer);\n        innerNodes.connectedEdges().forEach(setInDragLayer);\n      }\n\n      if (opts.addToList) {\n        addToDragList(innerNodes, opts);\n      }\n    }; // adds the given nodes and its neighbourhood to the drag layer\n\n\n    var addNodesToDrag = function addNodesToDrag(nodes, opts) {\n      opts = opts || {};\n      var hasCompoundNodes = nodes.cy().hasCompoundNodes();\n\n      if (opts.inDragLayer) {\n        nodes.forEach(setInDragLayer);\n        nodes.neighborhood().stdFilter(function (ele) {\n          return !hasCompoundNodes || ele.isEdge();\n        }).forEach(setInDragLayer);\n      }\n\n      if (opts.addToList) {\n        nodes.forEach(function (ele) {\n          addToDragList(ele, opts);\n        });\n      }\n\n      addDescendantsToDrag(nodes, opts); // always add to drag\n      // also add nodes and edges related to the topmost ancestor\n\n      updateAncestorsInDragLayer(nodes, {\n        inDragLayer: opts.inDragLayer\n      });\n      r.updateCachedGrabbedEles();\n    };\n\n    var addNodeToDrag = addNodesToDrag;\n\n    var freeDraggedElements = function freeDraggedElements(grabbedEles) {\n      if (!grabbedEles) {\n        return;\n      } // just go over all elements rather than doing a bunch of (possibly expensive) traversals\n\n\n      r.getCachedZSortedEles().forEach(function (ele) {\n        setFreed(ele);\n        setOutDragLayer(ele);\n        removeGrabTarget(ele);\n      });\n      r.updateCachedGrabbedEles();\n    }; // helper function to determine which ancestor nodes and edges should go\n    // to the drag layer (or should be removed from drag layer).\n\n\n    var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {\n      if (opts.inDragLayer == null && opts.addToList == null) {\n        return;\n      } // nothing to do\n\n\n      if (!node.cy().hasCompoundNodes()) {\n        return;\n      } // find top-level parent\n\n\n      var parent = node.ancestors().orphans(); // no parent node: no nodes to add to the drag layer\n\n      if (parent.same(node)) {\n        return;\n      }\n\n      var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());\n      var edges = nodes.connectedEdges();\n\n      if (opts.inDragLayer) {\n        edges.forEach(setInDragLayer);\n        nodes.forEach(setInDragLayer);\n      }\n\n      if (opts.addToList) {\n        nodes.forEach(function (ele) {\n          addToDragList(ele, opts);\n        });\n      }\n    };\n\n    var blurActiveDomElement = function blurActiveDomElement() {\n      if (document.activeElement != null && document.activeElement.blur != null) {\n        document.activeElement.blur();\n      }\n    };\n\n    var haveMutationsApi = typeof MutationObserver !== 'undefined';\n    var haveResizeObserverApi = typeof ResizeObserver !== 'undefined'; // watch for when the cy container is removed from the dom\n\n    if (haveMutationsApi) {\n      r.removeObserver = new MutationObserver(function (mutns) {\n        // eslint-disable-line no-undef\n        for (var i = 0; i < mutns.length; i++) {\n          var mutn = mutns[i];\n          var rNodes = mutn.removedNodes;\n\n          if (rNodes) {\n            for (var j = 0; j < rNodes.length; j++) {\n              var rNode = rNodes[j];\n\n              if (rNode === r.container) {\n                r.destroy();\n                break;\n              }\n            }\n          }\n        }\n      });\n\n      if (r.container.parentNode) {\n        r.removeObserver.observe(r.container.parentNode, {\n          childList: true\n        });\n      }\n    } else {\n      r.registerBinding(r.container, 'DOMNodeRemoved', function (e) {\n        // eslint-disable-line no-unused-vars\n        r.destroy();\n      });\n    }\n\n    var onResize = debounce_1(function () {\n      r.cy.resize();\n    }, 100);\n\n    if (haveMutationsApi) {\n      r.styleObserver = new MutationObserver(onResize); // eslint-disable-line no-undef\n\n      r.styleObserver.observe(r.container, {\n        attributes: true\n      });\n    } // auto resize\n\n\n    r.registerBinding(containerWindow, 'resize', onResize); // eslint-disable-line no-undef\n\n    if (haveResizeObserverApi) {\n      r.resizeObserver = new ResizeObserver(onResize); // eslint-disable-line no-undef\n\n      r.resizeObserver.observe(r.container);\n    }\n\n    var forEachUp = function forEachUp(domEle, fn) {\n      while (domEle != null) {\n        fn(domEle);\n        domEle = domEle.parentNode;\n      }\n    };\n\n    var invalidateCoords = function invalidateCoords() {\n      r.invalidateContainerClientCoordsCache();\n    };\n\n    forEachUp(r.container, function (domEle) {\n      r.registerBinding(domEle, 'transitionend', invalidateCoords);\n      r.registerBinding(domEle, 'animationend', invalidateCoords);\n      r.registerBinding(domEle, 'scroll', invalidateCoords);\n    }); // stop right click menu from appearing on cy\n\n    r.registerBinding(r.container, 'contextmenu', function (e) {\n      e.preventDefault();\n    });\n\n    var inBoxSelection = function inBoxSelection() {\n      return r.selection[4] !== 0;\n    };\n\n    var eventInContainer = function eventInContainer(e) {\n      // save cycles if mouse events aren't to be captured\n      var containerPageCoords = r.findContainerClientCoords();\n      var x = containerPageCoords[0];\n      var y = containerPageCoords[1];\n      var width = containerPageCoords[2];\n      var height = containerPageCoords[3];\n      var positions = e.touches ? e.touches : [e];\n      var atLeastOnePosInside = false;\n\n      for (var i = 0; i < positions.length; i++) {\n        var p = positions[i];\n\n        if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {\n          atLeastOnePosInside = true;\n          break;\n        }\n      }\n\n      if (!atLeastOnePosInside) {\n        return false;\n      }\n\n      var container = r.container;\n      var target = e.target;\n      var tParent = target.parentNode;\n      var containerIsTarget = false;\n\n      while (tParent) {\n        if (tParent === container) {\n          containerIsTarget = true;\n          break;\n        }\n\n        tParent = tParent.parentNode;\n      }\n\n      if (!containerIsTarget) {\n        return false;\n      } // if target is outisde cy container, then this event is not for us\n\n\n      return true;\n    }; // Primary key\n\n\n    r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {\n      if (!eventInContainer(e)) {\n        return;\n      }\n\n      e.preventDefault();\n      blurActiveDomElement();\n      r.hoverData.capture = true;\n      r.hoverData.which = e.which;\n      var cy = r.cy;\n      var gpos = [e.clientX, e.clientY];\n      var pos = r.projectIntoViewport(gpos[0], gpos[1]);\n      var select = r.selection;\n      var nears = r.findNearestElements(pos[0], pos[1], true, false);\n      var near = nears[0];\n      var draggedElements = r.dragData.possibleDragElements;\n      r.hoverData.mdownPos = pos;\n      r.hoverData.mdownGPos = gpos;\n\n      var checkForTaphold = function checkForTaphold() {\n        r.hoverData.tapholdCancelled = false;\n        clearTimeout(r.hoverData.tapholdTimeout);\n        r.hoverData.tapholdTimeout = setTimeout(function () {\n          if (r.hoverData.tapholdCancelled) {\n            return;\n          } else {\n            var ele = r.hoverData.down;\n\n            if (ele) {\n              ele.emit({\n                originalEvent: e,\n                type: 'taphold',\n                position: {\n                  x: pos[0],\n                  y: pos[1]\n                }\n              });\n            } else {\n              cy.emit({\n                originalEvent: e,\n                type: 'taphold',\n                position: {\n                  x: pos[0],\n                  y: pos[1]\n                }\n              });\n            }\n          }\n        }, r.tapholdDuration);\n      }; // Right click button\n\n\n      if (e.which == 3) {\n        r.hoverData.cxtStarted = true;\n        var cxtEvt = {\n          originalEvent: e,\n          type: 'cxttapstart',\n          position: {\n            x: pos[0],\n            y: pos[1]\n          }\n        };\n\n        if (near) {\n          near.activate();\n          near.emit(cxtEvt);\n          r.hoverData.down = near;\n        } else {\n          cy.emit(cxtEvt);\n        }\n\n        r.hoverData.downTime = new Date().getTime();\n        r.hoverData.cxtDragged = false; // Primary button\n      } else if (e.which == 1) {\n        if (near) {\n          near.activate();\n        } // Element dragging\n\n\n        {\n          // If something is under the cursor and it is draggable, prepare to grab it\n          if (near != null) {\n            if (r.nodeIsGrabbable(near)) {\n              var makeEvent = function makeEvent(type) {\n                return {\n                  originalEvent: e,\n                  type: type,\n                  position: {\n                    x: pos[0],\n                    y: pos[1]\n                  }\n                };\n              };\n\n              var triggerGrab = function triggerGrab(ele) {\n                ele.emit(makeEvent('grab'));\n              };\n\n              setGrabTarget(near);\n\n              if (!near.selected()) {\n                draggedElements = r.dragData.possibleDragElements = cy.collection();\n                addNodeToDrag(near, {\n                  addToList: draggedElements\n                });\n                near.emit(makeEvent('grabon')).emit(makeEvent('grab'));\n              } else {\n                draggedElements = r.dragData.possibleDragElements = cy.collection();\n                var selectedNodes = cy.$(function (ele) {\n                  return ele.isNode() && ele.selected() && r.nodeIsGrabbable(ele);\n                });\n                addNodesToDrag(selectedNodes, {\n                  addToList: draggedElements\n                });\n                near.emit(makeEvent('grabon'));\n                selectedNodes.forEach(triggerGrab);\n              }\n\n              r.redrawHint('eles', true);\n              r.redrawHint('drag', true);\n            }\n          }\n\n          r.hoverData.down = near;\n          r.hoverData.downs = nears;\n          r.hoverData.downTime = new Date().getTime();\n        }\n        triggerEvents(near, ['mousedown', 'tapstart', 'vmousedown'], e, {\n          x: pos[0],\n          y: pos[1]\n        });\n\n        if (near == null) {\n          select[4] = 1;\n          r.data.bgActivePosistion = {\n            x: pos[0],\n            y: pos[1]\n          };\n          r.redrawHint('select', true);\n          r.redraw();\n        } else if (near.pannable()) {\n          select[4] = 1; // for future pan\n        }\n\n        checkForTaphold();\n      } // Initialize selection box coordinates\n\n\n      select[0] = select[2] = pos[0];\n      select[1] = select[3] = pos[1];\n    }, false);\n    r.registerBinding(containerWindow, 'mousemove', function mousemoveHandler(e) {\n      // eslint-disable-line no-undef\n      var capture = r.hoverData.capture;\n\n      if (!capture && !eventInContainer(e)) {\n        return;\n      }\n\n      var preventDefault = false;\n      var cy = r.cy;\n      var zoom = cy.zoom();\n      var gpos = [e.clientX, e.clientY];\n      var pos = r.projectIntoViewport(gpos[0], gpos[1]);\n      var mdownPos = r.hoverData.mdownPos;\n      var mdownGPos = r.hoverData.mdownGPos;\n      var select = r.selection;\n      var near = null;\n\n      if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {\n        near = r.findNearestElement(pos[0], pos[1], true, false);\n      }\n\n      var last = r.hoverData.last;\n      var down = r.hoverData.down;\n      var disp = [pos[0] - select[2], pos[1] - select[3]];\n      var draggedElements = r.dragData.possibleDragElements;\n      var isOverThresholdDrag;\n\n      if (mdownGPos) {\n        var dx = gpos[0] - mdownGPos[0];\n        var dx2 = dx * dx;\n        var dy = gpos[1] - mdownGPos[1];\n        var dy2 = dy * dy;\n        var dist2 = dx2 + dy2;\n        r.hoverData.isOverThresholdDrag = isOverThresholdDrag = dist2 >= r.desktopTapThreshold2;\n      }\n\n      var multSelKeyDown = isMultSelKeyDown(e);\n\n      if (isOverThresholdDrag) {\n        r.hoverData.tapholdCancelled = true;\n      }\n\n      var updateDragDelta = function updateDragDelta() {\n        var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];\n\n        if (dragDelta.length === 0) {\n          dragDelta.push(disp[0]);\n          dragDelta.push(disp[1]);\n        } else {\n          dragDelta[0] += disp[0];\n          dragDelta[1] += disp[1];\n        }\n      };\n\n      preventDefault = true;\n      triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {\n        x: pos[0],\n        y: pos[1]\n      });\n\n      var goIntoBoxMode = function goIntoBoxMode() {\n        r.data.bgActivePosistion = undefined;\n\n        if (!r.hoverData.selecting) {\n          cy.emit({\n            originalEvent: e,\n            type: 'boxstart',\n            position: {\n              x: pos[0],\n              y: pos[1]\n            }\n          });\n        }\n\n        select[4] = 1;\n        r.hoverData.selecting = true;\n        r.redrawHint('select', true);\n        r.redraw();\n      }; // trigger context drag if rmouse down\n\n\n      if (r.hoverData.which === 3) {\n        // but only if over threshold\n        if (isOverThresholdDrag) {\n          var cxtEvt = {\n            originalEvent: e,\n            type: 'cxtdrag',\n            position: {\n              x: pos[0],\n              y: pos[1]\n            }\n          };\n\n          if (down) {\n            down.emit(cxtEvt);\n          } else {\n            cy.emit(cxtEvt);\n          }\n\n          r.hoverData.cxtDragged = true;\n\n          if (!r.hoverData.cxtOver || near !== r.hoverData.cxtOver) {\n            if (r.hoverData.cxtOver) {\n              r.hoverData.cxtOver.emit({\n                originalEvent: e,\n                type: 'cxtdragout',\n                position: {\n                  x: pos[0],\n                  y: pos[1]\n                }\n              });\n            }\n\n            r.hoverData.cxtOver = near;\n\n            if (near) {\n              near.emit({\n                originalEvent: e,\n                type: 'cxtdragover',\n                position: {\n                  x: pos[0],\n                  y: pos[1]\n                }\n              });\n            }\n          }\n        } // Check if we are drag panning the entire graph\n\n      } else if (r.hoverData.dragging) {\n        preventDefault = true;\n\n        if (cy.panningEnabled() && cy.userPanningEnabled()) {\n          var deltaP;\n\n          if (r.hoverData.justStartedPan) {\n            var mdPos = r.hoverData.mdownPos;\n            deltaP = {\n              x: (pos[0] - mdPos[0]) * zoom,\n              y: (pos[1] - mdPos[1]) * zoom\n            };\n            r.hoverData.justStartedPan = false;\n          } else {\n            deltaP = {\n              x: disp[0] * zoom,\n              y: disp[1] * zoom\n            };\n          }\n\n          cy.panBy(deltaP);\n          cy.emit('dragpan');\n          r.hoverData.dragged = true;\n        } // Needs reproject due to pan changing viewport\n\n\n        pos = r.projectIntoViewport(e.clientX, e.clientY); // Checks primary button down & out of time & mouse not moved much\n      } else if (select[4] == 1 && (down == null || down.pannable())) {\n        if (isOverThresholdDrag) {\n          if (!r.hoverData.dragging && cy.boxSelectionEnabled() && (multSelKeyDown || !cy.panningEnabled() || !cy.userPanningEnabled())) {\n            goIntoBoxMode();\n          } else if (!r.hoverData.selecting && cy.panningEnabled() && cy.userPanningEnabled()) {\n            var allowPassthrough = allowPanningPassthrough(down, r.hoverData.downs);\n\n            if (allowPassthrough) {\n              r.hoverData.dragging = true;\n              r.hoverData.justStartedPan = true;\n              select[4] = 0;\n              r.data.bgActivePosistion = array2point(mdownPos);\n              r.redrawHint('select', true);\n              r.redraw();\n            }\n          }\n\n          if (down && down.pannable() && down.active()) {\n            down.unactivate();\n          }\n        }\n      } else {\n        if (down && down.pannable() && down.active()) {\n          down.unactivate();\n        }\n\n        if ((!down || !down.grabbed()) && near != last) {\n          if (last) {\n            triggerEvents(last, ['mouseout', 'tapdragout'], e, {\n              x: pos[0],\n              y: pos[1]\n            });\n          }\n\n          if (near) {\n            triggerEvents(near, ['mouseover', 'tapdragover'], e, {\n              x: pos[0],\n              y: pos[1]\n            });\n          }\n\n          r.hoverData.last = near;\n        }\n\n        if (down) {\n          if (isOverThresholdDrag) {\n            // then we can take action\n            if (cy.boxSelectionEnabled() && multSelKeyDown) {\n              // then selection overrides\n              if (down && down.grabbed()) {\n                freeDraggedElements(draggedElements);\n                down.emit('freeon');\n                draggedElements.emit('free');\n\n                if (r.dragData.didDrag) {\n                  down.emit('dragfreeon');\n                  draggedElements.emit('dragfree');\n                }\n              }\n\n              goIntoBoxMode();\n            } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {\n              // drag node\n              var justStartedDrag = !r.dragData.didDrag;\n\n              if (justStartedDrag) {\n                r.redrawHint('eles', true);\n              }\n\n              r.dragData.didDrag = true; // indicate that we actually did drag the node\n              // now, add the elements to the drag layer if not done already\n\n              if (!r.hoverData.draggingEles) {\n                addNodesToDrag(draggedElements, {\n                  inDragLayer: true\n                });\n              }\n\n              var totalShift = {\n                x: 0,\n                y: 0\n              };\n\n              if (number$1(disp[0]) && number$1(disp[1])) {\n                totalShift.x += disp[0];\n                totalShift.y += disp[1];\n\n                if (justStartedDrag) {\n                  var dragDelta = r.hoverData.dragDelta;\n\n                  if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {\n                    totalShift.x += dragDelta[0];\n                    totalShift.y += dragDelta[1];\n                  }\n                }\n              }\n\n              r.hoverData.draggingEles = true;\n              draggedElements.silentShift(totalShift).emit('position drag');\n              r.redrawHint('drag', true);\n              r.redraw();\n            }\n          } else {\n            // otherwise save drag delta for when we actually start dragging so the relative grab pos is constant\n            updateDragDelta();\n          }\n        } // prevent the dragging from triggering text selection on the page\n\n\n        preventDefault = true;\n      }\n\n      select[2] = pos[0];\n      select[3] = pos[1];\n\n      if (preventDefault) {\n        if (e.stopPropagation) e.stopPropagation();\n        if (e.preventDefault) e.preventDefault();\n        return false;\n      }\n    }, false);\n    var clickTimeout, didDoubleClick, prevClickTimeStamp;\n    r.registerBinding(containerWindow, 'mouseup', function mouseupHandler(e) {\n      // eslint-disable-line no-undef\n      var capture = r.hoverData.capture;\n\n      if (!capture) {\n        return;\n      }\n\n      r.hoverData.capture = false;\n      var cy = r.cy;\n      var pos = r.projectIntoViewport(e.clientX, e.clientY);\n      var select = r.selection;\n      var near = r.findNearestElement(pos[0], pos[1], true, false);\n      var draggedElements = r.dragData.possibleDragElements;\n      var down = r.hoverData.down;\n      var multSelKeyDown = isMultSelKeyDown(e);\n\n      if (r.data.bgActivePosistion) {\n        r.redrawHint('select', true);\n        r.redraw();\n      }\n\n      r.hoverData.tapholdCancelled = true;\n      r.data.bgActivePosistion = undefined; // not active bg now\n\n      if (down) {\n        down.unactivate();\n      }\n\n      if (r.hoverData.which === 3) {\n        var cxtEvt = {\n          originalEvent: e,\n          type: 'cxttapend',\n          position: {\n            x: pos[0],\n            y: pos[1]\n          }\n        };\n\n        if (down) {\n          down.emit(cxtEvt);\n        } else {\n          cy.emit(cxtEvt);\n        }\n\n        if (!r.hoverData.cxtDragged) {\n          var cxtTap = {\n            originalEvent: e,\n            type: 'cxttap',\n            position: {\n              x: pos[0],\n              y: pos[1]\n            }\n          };\n\n          if (down) {\n            down.emit(cxtTap);\n          } else {\n            cy.emit(cxtTap);\n          }\n        }\n\n        r.hoverData.cxtDragged = false;\n        r.hoverData.which = null;\n      } else if (r.hoverData.which === 1) {\n        triggerEvents(near, ['mouseup', 'tapend', 'vmouseup'], e, {\n          x: pos[0],\n          y: pos[1]\n        });\n\n        if (!r.dragData.didDrag && // didn't move a node around\n        !r.hoverData.dragged && // didn't pan\n        !r.hoverData.selecting && // not box selection\n        !r.hoverData.isOverThresholdDrag // didn't move too much\n        ) {\n          triggerEvents(down, [\"click\", \"tap\", \"vclick\"], e, {\n            x: pos[0],\n            y: pos[1]\n          });\n          didDoubleClick = false;\n\n          if (e.timeStamp - prevClickTimeStamp <= cy.multiClickDebounceTime()) {\n            clickTimeout && clearTimeout(clickTimeout);\n            didDoubleClick = true;\n            prevClickTimeStamp = null;\n            triggerEvents(down, [\"dblclick\", \"dbltap\", \"vdblclick\"], e, {\n              x: pos[0],\n              y: pos[1]\n            });\n          } else {\n            clickTimeout = setTimeout(function () {\n              if (didDoubleClick) return;\n              triggerEvents(down, [\"oneclick\", \"onetap\", \"voneclick\"], e, {\n                x: pos[0],\n                y: pos[1]\n              });\n            }, cy.multiClickDebounceTime());\n            prevClickTimeStamp = e.timeStamp;\n          }\n        } // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something\n\n\n        if (down == null // not mousedown on node\n        && !r.dragData.didDrag // didn't move the node around\n        && !r.hoverData.selecting // not box selection\n        && !r.hoverData.dragged // didn't pan\n        && !isMultSelKeyDown(e)) {\n          cy.$(isSelected).unselect(['tapunselect']);\n\n          if (draggedElements.length > 0) {\n            r.redrawHint('eles', true);\n          }\n\n          r.dragData.possibleDragElements = draggedElements = cy.collection();\n        } // Single selection\n\n\n        if (near == down && !r.dragData.didDrag && !r.hoverData.selecting) {\n          if (near != null && near._private.selectable) {\n            if (r.hoverData.dragging) ; else if (cy.selectionType() === 'additive' || multSelKeyDown) {\n              if (near.selected()) {\n                near.unselect(['tapunselect']);\n              } else {\n                near.select(['tapselect']);\n              }\n            } else {\n              if (!multSelKeyDown) {\n                cy.$(isSelected).unmerge(near).unselect(['tapunselect']);\n                near.select(['tapselect']);\n              }\n            }\n\n            r.redrawHint('eles', true);\n          }\n        }\n\n        if (r.hoverData.selecting) {\n          var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));\n          r.redrawHint('select', true);\n\n          if (box.length > 0) {\n            r.redrawHint('eles', true);\n          }\n\n          cy.emit({\n            type: 'boxend',\n            originalEvent: e,\n            position: {\n              x: pos[0],\n              y: pos[1]\n            }\n          });\n\n          var eleWouldBeSelected = function eleWouldBeSelected(ele) {\n            return ele.selectable() && !ele.selected();\n          };\n\n          if (cy.selectionType() === 'additive') {\n            box.emit('box').stdFilter(eleWouldBeSelected).select().emit('boxselect');\n          } else {\n            if (!multSelKeyDown) {\n              cy.$(isSelected).unmerge(box).unselect();\n            }\n\n            box.emit('box').stdFilter(eleWouldBeSelected).select().emit('boxselect');\n          } // always need redraw in case eles unselectable\n\n\n          r.redraw();\n        } // Cancel drag pan\n\n\n        if (r.hoverData.dragging) {\n          r.hoverData.dragging = false;\n          r.redrawHint('select', true);\n          r.redrawHint('eles', true);\n          r.redraw();\n        }\n\n        if (!select[4]) {\n          r.redrawHint('drag', true);\n          r.redrawHint('eles', true);\n          var downWasGrabbed = down && down.grabbed();\n          freeDraggedElements(draggedElements);\n\n          if (downWasGrabbed) {\n            down.emit('freeon');\n            draggedElements.emit('free');\n\n            if (r.dragData.didDrag) {\n              down.emit('dragfreeon');\n              draggedElements.emit('dragfree');\n            }\n          }\n        }\n      } // else not right mouse\n\n\n      select[4] = 0;\n      r.hoverData.down = null;\n      r.hoverData.cxtStarted = false;\n      r.hoverData.draggingEles = false;\n      r.hoverData.selecting = false;\n      r.hoverData.isOverThresholdDrag = false;\n      r.dragData.didDrag = false;\n      r.hoverData.dragged = false;\n      r.hoverData.dragDelta = [];\n      r.hoverData.mdownPos = null;\n      r.hoverData.mdownGPos = null;\n    }, false);\n\n    var wheelHandler = function wheelHandler(e) {\n      if (r.scrollingPage) {\n        return;\n      } // while scrolling, ignore wheel-to-zoom\n\n\n      var cy = r.cy;\n      var zoom = cy.zoom();\n      var pan = cy.pan();\n      var pos = r.projectIntoViewport(e.clientX, e.clientY);\n      var rpos = [pos[0] * zoom + pan.x, pos[1] * zoom + pan.y];\n\n      if (r.hoverData.draggingEles || r.hoverData.dragging || r.hoverData.cxtStarted || inBoxSelection()) {\n        // if pan dragging or cxt dragging, wheel movements make no zoom\n        e.preventDefault();\n        return;\n      }\n\n      if (cy.panningEnabled() && cy.userPanningEnabled() && cy.zoomingEnabled() && cy.userZoomingEnabled()) {\n        e.preventDefault();\n        r.data.wheelZooming = true;\n        clearTimeout(r.data.wheelTimeout);\n        r.data.wheelTimeout = setTimeout(function () {\n          r.data.wheelZooming = false;\n          r.redrawHint('eles', true);\n          r.redraw();\n        }, 150);\n        var diff;\n\n        if (e.deltaY != null) {\n          diff = e.deltaY / -250;\n        } else if (e.wheelDeltaY != null) {\n          diff = e.wheelDeltaY / 1000;\n        } else {\n          diff = e.wheelDelta / 1000;\n        }\n\n        diff = diff * r.wheelSensitivity;\n        var needsWheelFix = e.deltaMode === 1;\n\n        if (needsWheelFix) {\n          // fixes slow wheel events on ff/linux and ff/windows\n          diff *= 33;\n        }\n\n        var newZoom = cy.zoom() * Math.pow(10, diff);\n\n        if (e.type === 'gesturechange') {\n          newZoom = r.gestureStartZoom * e.scale;\n        }\n\n        cy.zoom({\n          level: newZoom,\n          renderedPosition: {\n            x: rpos[0],\n            y: rpos[1]\n          }\n        });\n        cy.emit(e.type === 'gesturechange' ? 'pinchzoom' : 'scrollzoom');\n      }\n    }; // Functions to help with whether mouse wheel should trigger zooming\n    // --\n\n\n    r.registerBinding(r.container, 'wheel', wheelHandler, true); // disable nonstandard wheel events\n    // r.registerBinding(r.container, 'mousewheel', wheelHandler, true);\n    // r.registerBinding(r.container, 'DOMMouseScroll', wheelHandler, true);\n    // r.registerBinding(r.container, 'MozMousePixelScroll', wheelHandler, true); // older firefox\n\n    r.registerBinding(containerWindow, 'scroll', function scrollHandler(e) {\n      // eslint-disable-line no-unused-vars\n      r.scrollingPage = true;\n      clearTimeout(r.scrollingPageTimeout);\n      r.scrollingPageTimeout = setTimeout(function () {\n        r.scrollingPage = false;\n      }, 250);\n    }, true); // desktop safari pinch to zoom start\n\n    r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {\n      r.gestureStartZoom = r.cy.zoom();\n\n      if (!r.hasTouchStarted) {\n        // don't affect touch devices like iphone\n        e.preventDefault();\n      }\n    }, true);\n    r.registerBinding(r.container, 'gesturechange', function (e) {\n      if (!r.hasTouchStarted) {\n        // don't affect touch devices like iphone\n        wheelHandler(e);\n      }\n    }, true); // Functions to help with handling mouseout/mouseover on the Cytoscape container\n    // Handle mouseout on Cytoscape container\n\n    r.registerBinding(r.container, 'mouseout', function mouseOutHandler(e) {\n      var pos = r.projectIntoViewport(e.clientX, e.clientY);\n      r.cy.emit({\n        originalEvent: e,\n        type: 'mouseout',\n        position: {\n          x: pos[0],\n          y: pos[1]\n        }\n      });\n    }, false);\n    r.registerBinding(r.container, 'mouseover', function mouseOverHandler(e) {\n      var pos = r.projectIntoViewport(e.clientX, e.clientY);\n      r.cy.emit({\n        originalEvent: e,\n        type: 'mouseover',\n        position: {\n          x: pos[0],\n          y: pos[1]\n        }\n      });\n    }, false);\n    var f1x1, f1y1, f2x1, f2y1; // starting points for pinch-to-zoom\n\n    var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom\n\n    var center1, modelCenter1; // center point on start pinch to zoom\n\n    var offsetLeft, offsetTop;\n    var containerWidth, containerHeight;\n    var twoFingersStartInside;\n\n    var distance = function distance(x1, y1, x2, y2) {\n      return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n    };\n\n    var distanceSq = function distanceSq(x1, y1, x2, y2) {\n      return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n    };\n\n    var touchstartHandler;\n    r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {\n      r.hasTouchStarted = true;\n\n      if (!eventInContainer(e)) {\n        return;\n      }\n\n      blurActiveDomElement();\n      r.touchData.capture = true;\n      r.data.bgActivePosistion = undefined;\n      var cy = r.cy;\n      var now = r.touchData.now;\n      var earlier = r.touchData.earlier;\n\n      if (e.touches[0]) {\n        var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n        now[0] = pos[0];\n        now[1] = pos[1];\n      }\n\n      if (e.touches[1]) {\n        var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n        now[2] = pos[0];\n        now[3] = pos[1];\n      }\n\n      if (e.touches[2]) {\n        var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n        now[4] = pos[0];\n        now[5] = pos[1];\n      } // record starting points for pinch-to-zoom\n\n\n      if (e.touches[1]) {\n        r.touchData.singleTouchMoved = true;\n        freeDraggedElements(r.dragData.touchDragEles);\n        var offsets = r.findContainerClientCoords();\n        offsetLeft = offsets[0];\n        offsetTop = offsets[1];\n        containerWidth = offsets[2];\n        containerHeight = offsets[3];\n        f1x1 = e.touches[0].clientX - offsetLeft;\n        f1y1 = e.touches[0].clientY - offsetTop;\n        f2x1 = e.touches[1].clientX - offsetLeft;\n        f2y1 = e.touches[1].clientY - offsetTop;\n        twoFingersStartInside = 0 <= f1x1 && f1x1 <= containerWidth && 0 <= f2x1 && f2x1 <= containerWidth && 0 <= f1y1 && f1y1 <= containerHeight && 0 <= f2y1 && f2y1 <= containerHeight;\n        var pan = cy.pan();\n        var zoom = cy.zoom();\n        distance1 = distance(f1x1, f1y1, f2x1, f2y1);\n        distance1Sq = distanceSq(f1x1, f1y1, f2x1, f2y1);\n        center1 = [(f1x1 + f2x1) / 2, (f1y1 + f2y1) / 2];\n        modelCenter1 = [(center1[0] - pan.x) / zoom, (center1[1] - pan.y) / zoom]; // consider context tap\n\n        var cxtDistThreshold = 200;\n        var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;\n\n        if (distance1Sq < cxtDistThresholdSq && !e.touches[2]) {\n          var near1 = r.findNearestElement(now[0], now[1], true, true);\n          var near2 = r.findNearestElement(now[2], now[3], true, true);\n\n          if (near1 && near1.isNode()) {\n            near1.activate().emit({\n              originalEvent: e,\n              type: 'cxttapstart',\n              position: {\n                x: now[0],\n                y: now[1]\n              }\n            });\n            r.touchData.start = near1;\n          } else if (near2 && near2.isNode()) {\n            near2.activate().emit({\n              originalEvent: e,\n              type: 'cxttapstart',\n              position: {\n                x: now[0],\n                y: now[1]\n              }\n            });\n            r.touchData.start = near2;\n          } else {\n            cy.emit({\n              originalEvent: e,\n              type: 'cxttapstart',\n              position: {\n                x: now[0],\n                y: now[1]\n              }\n            });\n          }\n\n          if (r.touchData.start) {\n            r.touchData.start._private.grabbed = false;\n          }\n\n          r.touchData.cxt = true;\n          r.touchData.cxtDragged = false;\n          r.data.bgActivePosistion = undefined;\n          r.redraw();\n          return;\n        }\n      }\n\n      if (e.touches[2]) {\n        // ignore\n        // safari on ios pans the page otherwise (normally you should be able to preventdefault on touchmove...)\n        if (cy.boxSelectionEnabled()) {\n          e.preventDefault();\n        }\n      } else if (e.touches[1]) ; else if (e.touches[0]) {\n        var nears = r.findNearestElements(now[0], now[1], true, true);\n        var near = nears[0];\n\n        if (near != null) {\n          near.activate();\n          r.touchData.start = near;\n          r.touchData.starts = nears;\n\n          if (r.nodeIsGrabbable(near)) {\n            var draggedEles = r.dragData.touchDragEles = cy.collection();\n            var selectedNodes = null;\n            r.redrawHint('eles', true);\n            r.redrawHint('drag', true);\n\n            if (near.selected()) {\n              // reset drag elements, since near will be added again\n              selectedNodes = cy.$(function (ele) {\n                return ele.selected() && r.nodeIsGrabbable(ele);\n              });\n              addNodesToDrag(selectedNodes, {\n                addToList: draggedEles\n              });\n            } else {\n              addNodeToDrag(near, {\n                addToList: draggedEles\n              });\n            }\n\n            setGrabTarget(near);\n\n            var makeEvent = function makeEvent(type) {\n              return {\n                originalEvent: e,\n                type: type,\n                position: {\n                  x: now[0],\n                  y: now[1]\n                }\n              };\n            };\n\n            near.emit(makeEvent('grabon'));\n\n            if (selectedNodes) {\n              selectedNodes.forEach(function (n) {\n                n.emit(makeEvent('grab'));\n              });\n            } else {\n              near.emit(makeEvent('grab'));\n            }\n          }\n        }\n\n        triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {\n          x: now[0],\n          y: now[1]\n        });\n\n        if (near == null) {\n          r.data.bgActivePosistion = {\n            x: pos[0],\n            y: pos[1]\n          };\n          r.redrawHint('select', true);\n          r.redraw();\n        } // Tap, taphold\n        // -----\n\n\n        r.touchData.singleTouchMoved = false;\n        r.touchData.singleTouchStartTime = +new Date();\n        clearTimeout(r.touchData.tapholdTimeout);\n        r.touchData.tapholdTimeout = setTimeout(function () {\n          if (r.touchData.singleTouchMoved === false && !r.pinching // if pinching, then taphold unselect shouldn't take effect\n          && !r.touchData.selecting // box selection shouldn't allow taphold through\n          ) {\n            triggerEvents(r.touchData.start, ['taphold'], e, {\n              x: now[0],\n              y: now[1]\n            });\n          }\n        }, r.tapholdDuration);\n      }\n\n      if (e.touches.length >= 1) {\n        var sPos = r.touchData.startPosition = [null, null, null, null, null, null];\n\n        for (var i = 0; i < now.length; i++) {\n          sPos[i] = earlier[i] = now[i];\n        }\n\n        var touch0 = e.touches[0];\n        r.touchData.startGPosition = [touch0.clientX, touch0.clientY];\n      }\n    }, false);\n    var touchmoveHandler;\n    r.registerBinding(window, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {\n      // eslint-disable-line no-undef\n      var capture = r.touchData.capture;\n\n      if (!capture && !eventInContainer(e)) {\n        return;\n      }\n\n      var select = r.selection;\n      var cy = r.cy;\n      var now = r.touchData.now;\n      var earlier = r.touchData.earlier;\n      var zoom = cy.zoom();\n\n      if (e.touches[0]) {\n        var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n        now[0] = pos[0];\n        now[1] = pos[1];\n      }\n\n      if (e.touches[1]) {\n        var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n        now[2] = pos[0];\n        now[3] = pos[1];\n      }\n\n      if (e.touches[2]) {\n        var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n        now[4] = pos[0];\n        now[5] = pos[1];\n      }\n\n      var startGPos = r.touchData.startGPosition;\n      var isOverThresholdDrag;\n\n      if (capture && e.touches[0] && startGPos) {\n        var disp = [];\n\n        for (var j = 0; j < now.length; j++) {\n          disp[j] = now[j] - earlier[j];\n        }\n\n        var dx = e.touches[0].clientX - startGPos[0];\n        var dx2 = dx * dx;\n        var dy = e.touches[0].clientY - startGPos[1];\n        var dy2 = dy * dy;\n        var dist2 = dx2 + dy2;\n        isOverThresholdDrag = dist2 >= r.touchTapThreshold2;\n      } // context swipe cancelling\n\n\n      if (capture && r.touchData.cxt) {\n        e.preventDefault();\n        var f1x2 = e.touches[0].clientX - offsetLeft,\n            f1y2 = e.touches[0].clientY - offsetTop;\n        var f2x2 = e.touches[1].clientX - offsetLeft,\n            f2y2 = e.touches[1].clientY - offsetTop; // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );\n\n        var distance2Sq = distanceSq(f1x2, f1y2, f2x2, f2y2);\n        var factorSq = distance2Sq / distance1Sq;\n        var distThreshold = 150;\n        var distThresholdSq = distThreshold * distThreshold;\n        var factorThreshold = 1.5;\n        var factorThresholdSq = factorThreshold * factorThreshold; // cancel ctx gestures if the distance b/t the fingers increases\n\n        if (factorSq >= factorThresholdSq || distance2Sq >= distThresholdSq) {\n          r.touchData.cxt = false;\n          r.data.bgActivePosistion = undefined;\n          r.redrawHint('select', true);\n          var cxtEvt = {\n            originalEvent: e,\n            type: 'cxttapend',\n            position: {\n              x: now[0],\n              y: now[1]\n            }\n          };\n\n          if (r.touchData.start) {\n            r.touchData.start.unactivate().emit(cxtEvt);\n            r.touchData.start = null;\n          } else {\n            cy.emit(cxtEvt);\n          }\n        }\n      } // context swipe\n\n\n      if (capture && r.touchData.cxt) {\n        var cxtEvt = {\n          originalEvent: e,\n          type: 'cxtdrag',\n          position: {\n            x: now[0],\n            y: now[1]\n          }\n        };\n        r.data.bgActivePosistion = undefined;\n        r.redrawHint('select', true);\n\n        if (r.touchData.start) {\n          r.touchData.start.emit(cxtEvt);\n        } else {\n          cy.emit(cxtEvt);\n        }\n\n        if (r.touchData.start) {\n          r.touchData.start._private.grabbed = false;\n        }\n\n        r.touchData.cxtDragged = true;\n        var near = r.findNearestElement(now[0], now[1], true, true);\n\n        if (!r.touchData.cxtOver || near !== r.touchData.cxtOver) {\n          if (r.touchData.cxtOver) {\n            r.touchData.cxtOver.emit({\n              originalEvent: e,\n              type: 'cxtdragout',\n              position: {\n                x: now[0],\n                y: now[1]\n              }\n            });\n          }\n\n          r.touchData.cxtOver = near;\n\n          if (near) {\n            near.emit({\n              originalEvent: e,\n              type: 'cxtdragover',\n              position: {\n                x: now[0],\n                y: now[1]\n              }\n            });\n          }\n        } // box selection\n\n      } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {\n        e.preventDefault();\n        r.data.bgActivePosistion = undefined;\n        this.lastThreeTouch = +new Date();\n\n        if (!r.touchData.selecting) {\n          cy.emit({\n            originalEvent: e,\n            type: 'boxstart',\n            position: {\n              x: now[0],\n              y: now[1]\n            }\n          });\n        }\n\n        r.touchData.selecting = true;\n        r.touchData.didSelect = true;\n        select[4] = 1;\n\n        if (!select || select.length === 0 || select[0] === undefined) {\n          select[0] = (now[0] + now[2] + now[4]) / 3;\n          select[1] = (now[1] + now[3] + now[5]) / 3;\n          select[2] = (now[0] + now[2] + now[4]) / 3 + 1;\n          select[3] = (now[1] + now[3] + now[5]) / 3 + 1;\n        } else {\n          select[2] = (now[0] + now[2] + now[4]) / 3;\n          select[3] = (now[1] + now[3] + now[5]) / 3;\n        }\n\n        r.redrawHint('select', true);\n        r.redraw(); // pinch to zoom\n      } else if (capture && e.touches[1] && !r.touchData.didSelect // don't allow box selection to degrade to pinch-to-zoom\n      && cy.zoomingEnabled() && cy.panningEnabled() && cy.userZoomingEnabled() && cy.userPanningEnabled()) {\n        // two fingers => pinch to zoom\n        e.preventDefault();\n        r.data.bgActivePosistion = undefined;\n        r.redrawHint('select', true);\n        var draggedEles = r.dragData.touchDragEles;\n\n        if (draggedEles) {\n          r.redrawHint('drag', true);\n\n          for (var i = 0; i < draggedEles.length; i++) {\n            var de_p = draggedEles[i]._private;\n            de_p.grabbed = false;\n            de_p.rscratch.inDragLayer = false;\n          }\n        }\n\n        var _start = r.touchData.start; // (x2, y2) for fingers 1 and 2\n\n        var f1x2 = e.touches[0].clientX - offsetLeft,\n            f1y2 = e.touches[0].clientY - offsetTop;\n        var f2x2 = e.touches[1].clientX - offsetLeft,\n            f2y2 = e.touches[1].clientY - offsetTop;\n        var distance2 = distance(f1x2, f1y2, f2x2, f2y2); // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );\n        // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );\n\n        var factor = distance2 / distance1;\n\n        if (twoFingersStartInside) {\n          // delta finger1\n          var df1x = f1x2 - f1x1;\n          var df1y = f1y2 - f1y1; // delta finger 2\n\n          var df2x = f2x2 - f2x1;\n          var df2y = f2y2 - f2y1; // translation is the normalised vector of the two fingers movement\n          // i.e. so pinching cancels out and moving together pans\n\n          var tx = (df1x + df2x) / 2;\n          var ty = (df1y + df2y) / 2; // now calculate the zoom\n\n          var zoom1 = cy.zoom();\n          var zoom2 = zoom1 * factor;\n          var pan1 = cy.pan(); // the model center point converted to the current rendered pos\n\n          var ctrx = modelCenter1[0] * zoom1 + pan1.x;\n          var ctry = modelCenter1[1] * zoom1 + pan1.y;\n          var pan2 = {\n            x: -zoom2 / zoom1 * (ctrx - pan1.x - tx) + ctrx,\n            y: -zoom2 / zoom1 * (ctry - pan1.y - ty) + ctry\n          }; // remove dragged eles\n\n          if (_start && _start.active()) {\n            var draggedEles = r.dragData.touchDragEles;\n            freeDraggedElements(draggedEles);\n            r.redrawHint('drag', true);\n            r.redrawHint('eles', true);\n\n            _start.unactivate().emit('freeon');\n\n            draggedEles.emit('free');\n\n            if (r.dragData.didDrag) {\n              _start.emit('dragfreeon');\n\n              draggedEles.emit('dragfree');\n            }\n          }\n\n          cy.viewport({\n            zoom: zoom2,\n            pan: pan2,\n            cancelOnFailedZoom: true\n          });\n          cy.emit('pinchzoom');\n          distance1 = distance2;\n          f1x1 = f1x2;\n          f1y1 = f1y2;\n          f2x1 = f2x2;\n          f2y1 = f2y2;\n          r.pinching = true;\n        } // Re-project\n\n\n        if (e.touches[0]) {\n          var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n          now[0] = pos[0];\n          now[1] = pos[1];\n        }\n\n        if (e.touches[1]) {\n          var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n          now[2] = pos[0];\n          now[3] = pos[1];\n        }\n\n        if (e.touches[2]) {\n          var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n          now[4] = pos[0];\n          now[5] = pos[1];\n        }\n      } else if (e.touches[0] && !r.touchData.didSelect // don't allow box selection to degrade to single finger events like panning\n      ) {\n        var start = r.touchData.start;\n        var last = r.touchData.last;\n        var near;\n\n        if (!r.hoverData.draggingEles && !r.swipePanning) {\n          near = r.findNearestElement(now[0], now[1], true, true);\n        }\n\n        if (capture && start != null) {\n          e.preventDefault();\n        } // dragging nodes\n\n\n        if (capture && start != null && r.nodeIsDraggable(start)) {\n          if (isOverThresholdDrag) {\n            // then dragging can happen\n            var draggedEles = r.dragData.touchDragEles;\n            var justStartedDrag = !r.dragData.didDrag;\n\n            if (justStartedDrag) {\n              addNodesToDrag(draggedEles, {\n                inDragLayer: true\n              });\n            }\n\n            r.dragData.didDrag = true;\n            var totalShift = {\n              x: 0,\n              y: 0\n            };\n\n            if (number$1(disp[0]) && number$1(disp[1])) {\n              totalShift.x += disp[0];\n              totalShift.y += disp[1];\n\n              if (justStartedDrag) {\n                r.redrawHint('eles', true);\n                var dragDelta = r.touchData.dragDelta;\n\n                if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {\n                  totalShift.x += dragDelta[0];\n                  totalShift.y += dragDelta[1];\n                }\n              }\n            }\n\n            r.hoverData.draggingEles = true;\n            draggedEles.silentShift(totalShift).emit('position drag');\n            r.redrawHint('drag', true);\n\n            if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {\n              r.redrawHint('eles', true);\n            }\n\n            r.redraw();\n          } else {\n            // otherwise keep track of drag delta for later\n            var dragDelta = r.touchData.dragDelta = r.touchData.dragDelta || [];\n\n            if (dragDelta.length === 0) {\n              dragDelta.push(disp[0]);\n              dragDelta.push(disp[1]);\n            } else {\n              dragDelta[0] += disp[0];\n              dragDelta[1] += disp[1];\n            }\n          }\n        } // touchmove\n\n\n        {\n          triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {\n            x: now[0],\n            y: now[1]\n          });\n\n          if ((!start || !start.grabbed()) && near != last) {\n            if (last) {\n              last.emit({\n                originalEvent: e,\n                type: 'tapdragout',\n                position: {\n                  x: now[0],\n                  y: now[1]\n                }\n              });\n            }\n\n            if (near) {\n              near.emit({\n                originalEvent: e,\n                type: 'tapdragover',\n                position: {\n                  x: now[0],\n                  y: now[1]\n                }\n              });\n            }\n          }\n\n          r.touchData.last = near;\n        } // check to cancel taphold\n\n        if (capture) {\n          for (var i = 0; i < now.length; i++) {\n            if (now[i] && r.touchData.startPosition[i] && isOverThresholdDrag) {\n              r.touchData.singleTouchMoved = true;\n            }\n          }\n        } // panning\n\n\n        if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {\n          var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);\n\n          if (allowPassthrough) {\n            e.preventDefault();\n\n            if (!r.data.bgActivePosistion) {\n              r.data.bgActivePosistion = array2point(r.touchData.startPosition);\n            }\n\n            if (r.swipePanning) {\n              cy.panBy({\n                x: disp[0] * zoom,\n                y: disp[1] * zoom\n              });\n              cy.emit('dragpan');\n            } else if (isOverThresholdDrag) {\n              r.swipePanning = true;\n              cy.panBy({\n                x: dx * zoom,\n                y: dy * zoom\n              });\n              cy.emit('dragpan');\n\n              if (start) {\n                start.unactivate();\n                r.redrawHint('select', true);\n                r.touchData.start = null;\n              }\n            }\n          } // Re-project\n\n\n          var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n          now[0] = pos[0];\n          now[1] = pos[1];\n        }\n      }\n\n      for (var j = 0; j < now.length; j++) {\n        earlier[j] = now[j];\n      } // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning\n\n\n      if (capture && e.touches.length > 0 && !r.hoverData.draggingEles && !r.swipePanning && r.data.bgActivePosistion != null) {\n        r.data.bgActivePosistion = undefined;\n        r.redrawHint('select', true);\n        r.redraw();\n      }\n    }, false);\n    var touchcancelHandler;\n    r.registerBinding(containerWindow, 'touchcancel', touchcancelHandler = function touchcancelHandler(e) {\n      // eslint-disable-line no-unused-vars\n      var start = r.touchData.start;\n      r.touchData.capture = false;\n\n      if (start) {\n        start.unactivate();\n      }\n    });\n    var touchendHandler, didDoubleTouch, touchTimeout, prevTouchTimeStamp;\n    r.registerBinding(containerWindow, 'touchend', touchendHandler = function touchendHandler(e) {\n      // eslint-disable-line no-unused-vars\n      var start = r.touchData.start;\n      var capture = r.touchData.capture;\n\n      if (capture) {\n        if (e.touches.length === 0) {\n          r.touchData.capture = false;\n        }\n\n        e.preventDefault();\n      } else {\n        return;\n      }\n\n      var select = r.selection;\n      r.swipePanning = false;\n      r.hoverData.draggingEles = false;\n      var cy = r.cy;\n      var zoom = cy.zoom();\n      var now = r.touchData.now;\n      var earlier = r.touchData.earlier;\n\n      if (e.touches[0]) {\n        var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);\n        now[0] = pos[0];\n        now[1] = pos[1];\n      }\n\n      if (e.touches[1]) {\n        var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);\n        now[2] = pos[0];\n        now[3] = pos[1];\n      }\n\n      if (e.touches[2]) {\n        var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);\n        now[4] = pos[0];\n        now[5] = pos[1];\n      }\n\n      if (start) {\n        start.unactivate();\n      }\n\n      var ctxTapend;\n\n      if (r.touchData.cxt) {\n        ctxTapend = {\n          originalEvent: e,\n          type: 'cxttapend',\n          position: {\n            x: now[0],\n            y: now[1]\n          }\n        };\n\n        if (start) {\n          start.emit(ctxTapend);\n        } else {\n          cy.emit(ctxTapend);\n        }\n\n        if (!r.touchData.cxtDragged) {\n          var ctxTap = {\n            originalEvent: e,\n            type: 'cxttap',\n            position: {\n              x: now[0],\n              y: now[1]\n            }\n          };\n\n          if (start) {\n            start.emit(ctxTap);\n          } else {\n            cy.emit(ctxTap);\n          }\n        }\n\n        if (r.touchData.start) {\n          r.touchData.start._private.grabbed = false;\n        }\n\n        r.touchData.cxt = false;\n        r.touchData.start = null;\n        r.redraw();\n        return;\n      } // no more box selection if we don't have three fingers\n\n\n      if (!e.touches[2] && cy.boxSelectionEnabled() && r.touchData.selecting) {\n        r.touchData.selecting = false;\n        var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));\n        select[0] = undefined;\n        select[1] = undefined;\n        select[2] = undefined;\n        select[3] = undefined;\n        select[4] = 0;\n        r.redrawHint('select', true);\n        cy.emit({\n          type: 'boxend',\n          originalEvent: e,\n          position: {\n            x: now[0],\n            y: now[1]\n          }\n        });\n\n        var eleWouldBeSelected = function eleWouldBeSelected(ele) {\n          return ele.selectable() && !ele.selected();\n        };\n\n        box.emit('box').stdFilter(eleWouldBeSelected).select().emit('boxselect');\n\n        if (box.nonempty()) {\n          r.redrawHint('eles', true);\n        }\n\n        r.redraw();\n      }\n\n      if (start != null) {\n        start.unactivate();\n      }\n\n      if (e.touches[2]) {\n        r.data.bgActivePosistion = undefined;\n        r.redrawHint('select', true);\n      } else if (e.touches[1]) ; else if (e.touches[0]) ; else if (!e.touches[0]) {\n        r.data.bgActivePosistion = undefined;\n        r.redrawHint('select', true);\n        var draggedEles = r.dragData.touchDragEles;\n\n        if (start != null) {\n          var startWasGrabbed = start._private.grabbed;\n          freeDraggedElements(draggedEles);\n          r.redrawHint('drag', true);\n          r.redrawHint('eles', true);\n\n          if (startWasGrabbed) {\n            start.emit('freeon');\n            draggedEles.emit('free');\n\n            if (r.dragData.didDrag) {\n              start.emit('dragfreeon');\n              draggedEles.emit('dragfree');\n            }\n          }\n\n          triggerEvents(start, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {\n            x: now[0],\n            y: now[1]\n          });\n          start.unactivate();\n          r.touchData.start = null;\n        } else {\n          var near = r.findNearestElement(now[0], now[1], true, true);\n          triggerEvents(near, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {\n            x: now[0],\n            y: now[1]\n          });\n        }\n\n        var dx = r.touchData.startPosition[0] - now[0];\n        var dx2 = dx * dx;\n        var dy = r.touchData.startPosition[1] - now[1];\n        var dy2 = dy * dy;\n        var dist2 = dx2 + dy2;\n        var rdist2 = dist2 * zoom * zoom; // Tap event, roughly same as mouse click event for touch\n\n        if (!r.touchData.singleTouchMoved) {\n          if (!start) {\n            cy.$(':selected').unselect(['tapunselect']);\n          }\n\n          triggerEvents(start, ['tap', 'vclick'], e, {\n            x: now[0],\n            y: now[1]\n          });\n          didDoubleTouch = false;\n\n          if (e.timeStamp - prevTouchTimeStamp <= cy.multiClickDebounceTime()) {\n            touchTimeout && clearTimeout(touchTimeout);\n            didDoubleTouch = true;\n            prevTouchTimeStamp = null;\n            triggerEvents(start, ['dbltap', 'vdblclick'], e, {\n              x: now[0],\n              y: now[1]\n            });\n          } else {\n            touchTimeout = setTimeout(function () {\n              if (didDoubleTouch) return;\n              triggerEvents(start, ['onetap', 'voneclick'], e, {\n                x: now[0],\n                y: now[1]\n              });\n            }, cy.multiClickDebounceTime());\n            prevTouchTimeStamp = e.timeStamp;\n          }\n        } // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance\n\n\n        if (start != null && !r.dragData.didDrag // didn't drag nodes around\n        && start._private.selectable && rdist2 < r.touchTapThreshold2 && !r.pinching // pinch to zoom should not affect selection\n        ) {\n          if (cy.selectionType() === 'single') {\n            cy.$(isSelected).unmerge(start).unselect(['tapunselect']);\n            start.select(['tapselect']);\n          } else {\n            if (start.selected()) {\n              start.unselect(['tapunselect']);\n            } else {\n              start.select(['tapselect']);\n            }\n          }\n\n          r.redrawHint('eles', true);\n        }\n\n        r.touchData.singleTouchMoved = true;\n      }\n\n      for (var j = 0; j < now.length; j++) {\n        earlier[j] = now[j];\n      }\n\n      r.dragData.didDrag = false; // reset for next touchstart\n\n      if (e.touches.length === 0) {\n        r.touchData.dragDelta = [];\n        r.touchData.startPosition = [null, null, null, null, null, null];\n        r.touchData.startGPosition = null;\n        r.touchData.didSelect = false;\n      }\n\n      if (e.touches.length < 2) {\n        if (e.touches.length === 1) {\n          // the old start global pos'n may not be the same finger that remains\n          r.touchData.startGPosition = [e.touches[0].clientX, e.touches[0].clientY];\n        }\n\n        r.pinching = false;\n        r.redrawHint('eles', true);\n        r.redraw();\n      } //r.redraw();\n\n    }, false); // fallback compatibility layer for ms pointer events\n\n    if (typeof TouchEvent === 'undefined') {\n      var pointers = [];\n\n      var makeTouch = function makeTouch(e) {\n        return {\n          clientX: e.clientX,\n          clientY: e.clientY,\n          force: 1,\n          identifier: e.pointerId,\n          pageX: e.pageX,\n          pageY: e.pageY,\n          radiusX: e.width / 2,\n          radiusY: e.height / 2,\n          screenX: e.screenX,\n          screenY: e.screenY,\n          target: e.target\n        };\n      };\n\n      var makePointer = function makePointer(e) {\n        return {\n          event: e,\n          touch: makeTouch(e)\n        };\n      };\n\n      var addPointer = function addPointer(e) {\n        pointers.push(makePointer(e));\n      };\n\n      var removePointer = function removePointer(e) {\n        for (var i = 0; i < pointers.length; i++) {\n          var p = pointers[i];\n\n          if (p.event.pointerId === e.pointerId) {\n            pointers.splice(i, 1);\n            return;\n          }\n        }\n      };\n\n      var updatePointer = function updatePointer(e) {\n        var p = pointers.filter(function (p) {\n          return p.event.pointerId === e.pointerId;\n        })[0];\n        p.event = e;\n        p.touch = makeTouch(e);\n      };\n\n      var addTouchesToEvent = function addTouchesToEvent(e) {\n        e.touches = pointers.map(function (p) {\n          return p.touch;\n        });\n      };\n\n      var pointerIsMouse = function pointerIsMouse(e) {\n        return e.pointerType === 'mouse' || e.pointerType === 4;\n      };\n\n      r.registerBinding(r.container, 'pointerdown', function (e) {\n        if (pointerIsMouse(e)) {\n          return;\n        } // mouse already handled\n\n\n        e.preventDefault();\n        addPointer(e);\n        addTouchesToEvent(e);\n        touchstartHandler(e);\n      });\n      r.registerBinding(r.container, 'pointerup', function (e) {\n        if (pointerIsMouse(e)) {\n          return;\n        } // mouse already handled\n\n\n        removePointer(e);\n        addTouchesToEvent(e);\n        touchendHandler(e);\n      });\n      r.registerBinding(r.container, 'pointercancel', function (e) {\n        if (pointerIsMouse(e)) {\n          return;\n        } // mouse already handled\n\n\n        removePointer(e);\n        addTouchesToEvent(e);\n        touchcancelHandler(e);\n      });\n      r.registerBinding(r.container, 'pointermove', function (e) {\n        if (pointerIsMouse(e)) {\n          return;\n        } // mouse already handled\n\n\n        e.preventDefault();\n        updatePointer(e);\n        addTouchesToEvent(e);\n        touchmoveHandler(e);\n      });\n    }\n  };\n\n  var BRp$2 = {};\n\n  BRp$2.generatePolygon = function (name, points) {\n    return this.nodeShapes[name] = {\n      renderer: this,\n      name: name,\n      points: points,\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        return polygonIntersectLine(x, y, this.points, nodeX, nodeY, width / 2, height / 2, padding);\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);\n      }\n    };\n  };\n\n  BRp$2.generateEllipse = function () {\n    return this.nodeShapes['ellipse'] = {\n      renderer: this,\n      name: 'ellipse',\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        return intersectLineEllipse(x, y, nodeX, nodeY, width / 2 + padding, height / 2 + padding);\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        return checkInEllipse(x, y, width, height, centerX, centerY, padding);\n      }\n    };\n  };\n\n  BRp$2.generateRoundPolygon = function (name, points) {\n    // Pre-compute control points\n    // Since these points depend on the radius length (which in turns depend on the width/height of the node) we will only pre-compute\n    // the unit vectors.\n    // For simplicity the layout will be:\n    // [ p0, UnitVectorP0P1, p1, UniVectorP1P2, ..., pn, UnitVectorPnP0 ]\n    var allPoints = new Array(points.length * 2);\n\n    for (var i = 0; i < points.length / 2; i++) {\n      var sourceIndex = i * 2;\n      var destIndex = void 0;\n\n      if (i < points.length / 2 - 1) {\n        destIndex = (i + 1) * 2;\n      } else {\n        destIndex = 0;\n      }\n\n      allPoints[i * 4] = points[sourceIndex];\n      allPoints[i * 4 + 1] = points[sourceIndex + 1];\n      var xDest = points[destIndex] - points[sourceIndex];\n      var yDest = points[destIndex + 1] - points[sourceIndex + 1];\n      var norm = Math.sqrt(xDest * xDest + yDest * yDest);\n      allPoints[i * 4 + 2] = xDest / norm;\n      allPoints[i * 4 + 3] = yDest / norm;\n    }\n\n    return this.nodeShapes[name] = {\n      renderer: this,\n      name: name,\n      points: allPoints,\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points);\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height);\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height);\n      }\n    };\n  };\n\n  BRp$2.generateRoundRectangle = function () {\n    return this.nodeShapes['round-rectangle'] = this.nodeShapes['roundrectangle'] = {\n      renderer: this,\n      name: 'round-rectangle',\n      points: generateUnitNgonPointsFitToSquare(4, 0),\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding);\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        var cornerRadius = getRoundRectangleRadius(width, height);\n        var diam = cornerRadius * 2; // Check hBox\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {\n          return true;\n        } // Check vBox\n\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {\n          return true;\n        } // Check top left quarter circle\n\n\n        if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY - height / 2 + cornerRadius, padding)) {\n          return true;\n        } // Check top right quarter circle\n\n\n        if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY - height / 2 + cornerRadius, padding)) {\n          return true;\n        } // Check bottom right quarter circle\n\n\n        if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n          return true;\n        } // Check bottom left quarter circle\n\n\n        if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n          return true;\n        }\n\n        return false;\n      }\n    };\n  };\n\n  BRp$2.generateCutRectangle = function () {\n    return this.nodeShapes['cut-rectangle'] = this.nodeShapes['cutrectangle'] = {\n      renderer: this,\n      name: 'cut-rectangle',\n      cornerLength: getCutRectangleCornerLength(),\n      points: generateUnitNgonPointsFitToSquare(4, 0),\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n      },\n      generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY) {\n        var cl = this.cornerLength;\n        var hh = height / 2;\n        var hw = width / 2;\n        var xBegin = centerX - hw;\n        var xEnd = centerX + hw;\n        var yBegin = centerY - hh;\n        var yEnd = centerY + hh; // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]\n\n        return {\n          topLeft: [xBegin, yBegin + cl, xBegin + cl, yBegin, xBegin + cl, yBegin + cl],\n          topRight: [xEnd - cl, yBegin, xEnd, yBegin + cl, xEnd - cl, yBegin + cl],\n          bottomRight: [xEnd, yEnd - cl, xEnd - cl, yEnd, xEnd - cl, yEnd - cl],\n          bottomLeft: [xBegin + cl, yEnd, xBegin, yEnd - cl, xBegin + cl, yEnd - cl]\n        };\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);\n        var pts = [].concat.apply([], [cPts.topLeft.splice(0, 4), cPts.topRight.splice(0, 4), cPts.bottomRight.splice(0, 4), cPts.bottomLeft.splice(0, 4)]);\n        return polygonIntersectLine(x, y, pts, nodeX, nodeY);\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        // Check hBox\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * this.cornerLength, [0, -1], padding)) {\n          return true;\n        } // Check vBox\n\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * this.cornerLength, height, [0, -1], padding)) {\n          return true;\n        }\n\n        var cutTrianglePts = this.generateCutTrianglePts(width, height, centerX, centerY);\n        return pointInsidePolygonPoints(x, y, cutTrianglePts.topLeft) || pointInsidePolygonPoints(x, y, cutTrianglePts.topRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomLeft);\n      }\n    };\n  };\n\n  BRp$2.generateBarrel = function () {\n    return this.nodeShapes['barrel'] = {\n      renderer: this,\n      name: 'barrel',\n      points: generateUnitNgonPointsFitToSquare(4, 0),\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        // use two fixed t values for the bezier curve approximation\n        var t0 = 0.15;\n        var t1 = 0.5;\n        var t2 = 0.85;\n        var bPts = this.generateBarrelBezierPts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);\n\n        var approximateBarrelCurvePts = function approximateBarrelCurvePts(pts) {\n          // approximate curve pts based on the two t values\n          var m0 = qbezierPtAt({\n            x: pts[0],\n            y: pts[1]\n          }, {\n            x: pts[2],\n            y: pts[3]\n          }, {\n            x: pts[4],\n            y: pts[5]\n          }, t0);\n          var m1 = qbezierPtAt({\n            x: pts[0],\n            y: pts[1]\n          }, {\n            x: pts[2],\n            y: pts[3]\n          }, {\n            x: pts[4],\n            y: pts[5]\n          }, t1);\n          var m2 = qbezierPtAt({\n            x: pts[0],\n            y: pts[1]\n          }, {\n            x: pts[2],\n            y: pts[3]\n          }, {\n            x: pts[4],\n            y: pts[5]\n          }, t2);\n          return [pts[0], pts[1], m0.x, m0.y, m1.x, m1.y, m2.x, m2.y, pts[4], pts[5]];\n        };\n\n        var pts = [].concat(approximateBarrelCurvePts(bPts.topLeft), approximateBarrelCurvePts(bPts.topRight), approximateBarrelCurvePts(bPts.bottomRight), approximateBarrelCurvePts(bPts.bottomLeft));\n        return polygonIntersectLine(x, y, pts, nodeX, nodeY);\n      },\n      generateBarrelBezierPts: function generateBarrelBezierPts(width, height, centerX, centerY) {\n        var hh = height / 2;\n        var hw = width / 2;\n        var xBegin = centerX - hw;\n        var xEnd = centerX + hw;\n        var yBegin = centerY - hh;\n        var yEnd = centerY + hh;\n        var curveConstants = getBarrelCurveConstants(width, height);\n        var hOffset = curveConstants.heightOffset;\n        var wOffset = curveConstants.widthOffset;\n        var ctrlPtXOffset = curveConstants.ctrlPtOffsetPct * width; // points are in clockwise order, inner (imaginary) control pt on [4, 5]\n\n        var pts = {\n          topLeft: [xBegin, yBegin + hOffset, xBegin + ctrlPtXOffset, yBegin, xBegin + wOffset, yBegin],\n          topRight: [xEnd - wOffset, yBegin, xEnd - ctrlPtXOffset, yBegin, xEnd, yBegin + hOffset],\n          bottomRight: [xEnd, yEnd - hOffset, xEnd - ctrlPtXOffset, yEnd, xEnd - wOffset, yEnd],\n          bottomLeft: [xBegin + wOffset, yEnd, xBegin + ctrlPtXOffset, yEnd, xBegin, yEnd - hOffset]\n        };\n        pts.topLeft.isTop = true;\n        pts.topRight.isTop = true;\n        pts.bottomLeft.isBottom = true;\n        pts.bottomRight.isBottom = true;\n        return pts;\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        var curveConstants = getBarrelCurveConstants(width, height);\n        var hOffset = curveConstants.heightOffset;\n        var wOffset = curveConstants.widthOffset; // Check hBox\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {\n          return true;\n        } // Check vBox\n\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {\n          return true;\n        }\n\n        var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);\n\n        var getCurveT = function getCurveT(x, y, curvePts) {\n          var x0 = curvePts[4];\n          var x1 = curvePts[2];\n          var x2 = curvePts[0];\n          var y0 = curvePts[5]; // var y1 = curvePts[ 3 ];\n\n          var y2 = curvePts[1];\n          var xMin = Math.min(x0, x2);\n          var xMax = Math.max(x0, x2);\n          var yMin = Math.min(y0, y2);\n          var yMax = Math.max(y0, y2);\n\n          if (xMin <= x && x <= xMax && yMin <= y && y <= yMax) {\n            var coeff = bezierPtsToQuadCoeff(x0, x1, x2);\n            var roots = solveQuadratic(coeff[0], coeff[1], coeff[2], x);\n            var validRoots = roots.filter(function (r) {\n              return 0 <= r && r <= 1;\n            });\n\n            if (validRoots.length > 0) {\n              return validRoots[0];\n            }\n          }\n\n          return null;\n        };\n\n        var curveRegions = Object.keys(barrelCurvePts);\n\n        for (var i = 0; i < curveRegions.length; i++) {\n          var corner = curveRegions[i];\n          var cornerPts = barrelCurvePts[corner];\n          var t = getCurveT(x, y, cornerPts);\n\n          if (t == null) {\n            continue;\n          }\n\n          var y0 = cornerPts[5];\n          var y1 = cornerPts[3];\n          var y2 = cornerPts[1];\n          var bezY = qbezierAt(y0, y1, y2, t);\n\n          if (cornerPts.isTop && bezY <= y) {\n            return true;\n          }\n\n          if (cornerPts.isBottom && y <= bezY) {\n            return true;\n          }\n        }\n\n        return false;\n      }\n    };\n  };\n\n  BRp$2.generateBottomRoundrectangle = function () {\n    return this.nodeShapes['bottom-round-rectangle'] = this.nodeShapes['bottomroundrectangle'] = {\n      renderer: this,\n      name: 'bottom-round-rectangle',\n      points: generateUnitNgonPointsFitToSquare(4, 0),\n      draw: function draw(context, centerX, centerY, width, height) {\n        this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n      },\n      intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding) {\n        var topStartX = nodeX - (width / 2 + padding);\n        var topStartY = nodeY - (height / 2 + padding);\n        var topEndY = topStartY;\n        var topEndX = nodeX + (width / 2 + padding);\n        var topIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);\n\n        if (topIntersections.length > 0) {\n          return topIntersections;\n        }\n\n        return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding);\n      },\n      checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY) {\n        var cornerRadius = getRoundRectangleRadius(width, height);\n        var diam = 2 * cornerRadius; // Check hBox\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {\n          return true;\n        } // Check vBox\n\n\n        if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {\n          return true;\n        } // check non-rounded top side\n\n\n        var outerWidth = width / 2 + 2 * padding;\n        var outerHeight = height / 2 + 2 * padding;\n        var points = [centerX - outerWidth, centerY - outerHeight, centerX - outerWidth, centerY, centerX + outerWidth, centerY, centerX + outerWidth, centerY - outerHeight];\n\n        if (pointInsidePolygonPoints(x, y, points)) {\n          return true;\n        } // Check bottom right quarter circle\n\n\n        if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n          return true;\n        } // Check bottom left quarter circle\n\n\n        if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n          return true;\n        }\n\n        return false;\n      }\n    };\n  };\n\n  BRp$2.registerNodeShapes = function () {\n    var nodeShapes = this.nodeShapes = {};\n    var renderer = this;\n    this.generateEllipse();\n    this.generatePolygon('triangle', generateUnitNgonPointsFitToSquare(3, 0));\n    this.generateRoundPolygon('round-triangle', generateUnitNgonPointsFitToSquare(3, 0));\n    this.generatePolygon('rectangle', generateUnitNgonPointsFitToSquare(4, 0));\n    nodeShapes['square'] = nodeShapes['rectangle'];\n    this.generateRoundRectangle();\n    this.generateCutRectangle();\n    this.generateBarrel();\n    this.generateBottomRoundrectangle();\n    {\n      var diamondPoints = [0, 1, 1, 0, 0, -1, -1, 0];\n      this.generatePolygon('diamond', diamondPoints);\n      this.generateRoundPolygon('round-diamond', diamondPoints);\n    }\n    this.generatePolygon('pentagon', generateUnitNgonPointsFitToSquare(5, 0));\n    this.generateRoundPolygon('round-pentagon', generateUnitNgonPointsFitToSquare(5, 0));\n    this.generatePolygon('hexagon', generateUnitNgonPointsFitToSquare(6, 0));\n    this.generateRoundPolygon('round-hexagon', generateUnitNgonPointsFitToSquare(6, 0));\n    this.generatePolygon('heptagon', generateUnitNgonPointsFitToSquare(7, 0));\n    this.generateRoundPolygon('round-heptagon', generateUnitNgonPointsFitToSquare(7, 0));\n    this.generatePolygon('octagon', generateUnitNgonPointsFitToSquare(8, 0));\n    this.generateRoundPolygon('round-octagon', generateUnitNgonPointsFitToSquare(8, 0));\n    var star5Points = new Array(20);\n    {\n      var outerPoints = generateUnitNgonPoints(5, 0);\n      var innerPoints = generateUnitNgonPoints(5, Math.PI / 5); // Outer radius is 1; inner radius of star is smaller\n\n      var innerRadius = 0.5 * (3 - Math.sqrt(5));\n      innerRadius *= 1.57;\n\n      for (var i = 0; i < innerPoints.length / 2; i++) {\n        innerPoints[i * 2] *= innerRadius;\n        innerPoints[i * 2 + 1] *= innerRadius;\n      }\n\n      for (var i = 0; i < 20 / 4; i++) {\n        star5Points[i * 4] = outerPoints[i * 2];\n        star5Points[i * 4 + 1] = outerPoints[i * 2 + 1];\n        star5Points[i * 4 + 2] = innerPoints[i * 2];\n        star5Points[i * 4 + 3] = innerPoints[i * 2 + 1];\n      }\n    }\n    star5Points = fitPolygonToSquare(star5Points);\n    this.generatePolygon('star', star5Points);\n    this.generatePolygon('vee', [-1, -1, 0, -0.333, 1, -1, 0, 1]);\n    this.generatePolygon('rhomboid', [-1, -1, 0.333, -1, 1, 1, -0.333, 1]);\n    this.generatePolygon('right-rhomboid', [-0.333, -1, 1, -1, 0.333, 1, -1, 1]);\n    this.nodeShapes['concavehexagon'] = this.generatePolygon('concave-hexagon', [-1, -0.95, -0.75, 0, -1, 0.95, 1, 0.95, 0.75, 0, 1, -0.95]);\n    {\n      var tagPoints = [-1, -1, 0.25, -1, 1, 0, 0.25, 1, -1, 1];\n      this.generatePolygon('tag', tagPoints);\n      this.generateRoundPolygon('round-tag', tagPoints);\n    }\n\n    nodeShapes.makePolygon = function (points) {\n      // use caching on user-specified polygons so they are as fast as native shapes\n      var key = points.join('$');\n      var name = 'polygon-' + key;\n      var shape;\n\n      if (shape = this[name]) {\n        // got cached shape\n        return shape;\n      } // create and cache new shape\n\n\n      return renderer.generatePolygon(name, points);\n    };\n  };\n\n  var BRp$1 = {};\n\n  BRp$1.timeToRender = function () {\n    return this.redrawTotalTime / this.redrawCount;\n  };\n\n  BRp$1.redraw = function (options) {\n    options = options || staticEmptyObject();\n    var r = this;\n\n    if (r.averageRedrawTime === undefined) {\n      r.averageRedrawTime = 0;\n    }\n\n    if (r.lastRedrawTime === undefined) {\n      r.lastRedrawTime = 0;\n    }\n\n    if (r.lastDrawTime === undefined) {\n      r.lastDrawTime = 0;\n    }\n\n    r.requestedFrame = true;\n    r.renderOptions = options;\n  };\n\n  BRp$1.beforeRender = function (fn, priority) {\n    // the renderer can't add tick callbacks when destroyed\n    if (this.destroyed) {\n      return;\n    }\n\n    if (priority == null) {\n      error('Priority is not optional for beforeRender');\n    }\n\n    var cbs = this.beforeRenderCallbacks;\n    cbs.push({\n      fn: fn,\n      priority: priority\n    }); // higher priority callbacks executed first\n\n    cbs.sort(function (a, b) {\n      return b.priority - a.priority;\n    });\n  };\n\n  var beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {\n    var cbs = r.beforeRenderCallbacks;\n\n    for (var i = 0; i < cbs.length; i++) {\n      cbs[i].fn(willDraw, startTime);\n    }\n  };\n\n  BRp$1.startRenderLoop = function () {\n    var r = this;\n    var cy = r.cy;\n\n    if (r.renderLoopStarted) {\n      return;\n    } else {\n      r.renderLoopStarted = true;\n    }\n\n    var renderFn = function renderFn(requestTime) {\n      if (r.destroyed) {\n        return;\n      }\n\n      if (cy.batching()) ; else if (r.requestedFrame && !r.skipFrame) {\n        beforeRenderCallbacks(r, true, requestTime);\n        var startTime = performanceNow();\n        r.render(r.renderOptions);\n        var endTime = r.lastDrawTime = performanceNow();\n\n        if (r.averageRedrawTime === undefined) {\n          r.averageRedrawTime = endTime - startTime;\n        }\n\n        if (r.redrawCount === undefined) {\n          r.redrawCount = 0;\n        }\n\n        r.redrawCount++;\n\n        if (r.redrawTotalTime === undefined) {\n          r.redrawTotalTime = 0;\n        }\n\n        var duration = endTime - startTime;\n        r.redrawTotalTime += duration;\n        r.lastRedrawTime = duration; // use a weighted average with a bias from the previous average so we don't spike so easily\n\n        r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;\n        r.requestedFrame = false;\n      } else {\n        beforeRenderCallbacks(r, false, requestTime);\n      }\n\n      r.skipFrame = false;\n      requestAnimationFrame(renderFn);\n    };\n\n    requestAnimationFrame(renderFn);\n  };\n\n  var BaseRenderer = function BaseRenderer(options) {\n    this.init(options);\n  };\n\n  var BR = BaseRenderer;\n  var BRp = BR.prototype;\n  BRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];\n\n  BRp.init = function (options) {\n    var r = this;\n    r.options = options;\n    r.cy = options.cy;\n    var ctr = r.container = options.cy.container();\n    var containerWindow = r.cy.window(); // prepend a stylesheet in the head such that\n\n    if (containerWindow) {\n      var document = containerWindow.document;\n      var head = document.head;\n      var stylesheetId = '__________cytoscape_stylesheet';\n      var className = '__________cytoscape_container';\n      var stylesheetAlreadyExists = document.getElementById(stylesheetId) != null;\n\n      if (ctr.className.indexOf(className) < 0) {\n        ctr.className = (ctr.className || '') + ' ' + className;\n      }\n\n      if (!stylesheetAlreadyExists) {\n        var stylesheet = document.createElement('style');\n        stylesheet.id = stylesheetId;\n        stylesheet.textContent = '.' + className + ' { position: relative; }';\n        head.insertBefore(stylesheet, head.children[0]); // first so lowest priority\n      }\n\n      var computedStyle = containerWindow.getComputedStyle(ctr);\n      var position = computedStyle.getPropertyValue('position');\n\n      if (position === 'static') {\n        warn('A Cytoscape container has style position:static and so can not use UI extensions properly');\n      }\n    }\n\n    r.selection = [undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag\n\n    r.bezierProjPcts = [0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95]; //--Pointer-related data\n\n    r.hoverData = {\n      down: null,\n      last: null,\n      downTime: null,\n      triggerMode: null,\n      dragging: false,\n      initialPan: [null, null],\n      capture: false\n    };\n    r.dragData = {\n      possibleDragElements: []\n    };\n    r.touchData = {\n      start: null,\n      capture: false,\n      // These 3 fields related to tap, taphold events\n      startPosition: [null, null, null, null, null, null],\n      singleTouchStartTime: null,\n      singleTouchMoved: true,\n      now: [null, null, null, null, null, null],\n      earlier: [null, null, null, null, null, null]\n    };\n    r.redraws = 0;\n    r.showFps = options.showFps;\n    r.debug = options.debug;\n    r.hideEdgesOnViewport = options.hideEdgesOnViewport;\n    r.textureOnViewport = options.textureOnViewport;\n    r.wheelSensitivity = options.wheelSensitivity;\n    r.motionBlurEnabled = options.motionBlur; // on by default\n\n    r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;\n    r.motionBlur = options.motionBlur; // for initial kick off\n\n    r.motionBlurOpacity = options.motionBlurOpacity;\n    r.motionBlurTransparency = 1 - r.motionBlurOpacity;\n    r.motionBlurPxRatio = 1;\n    r.mbPxRBlurry = 1; //0.8;\n\n    r.minMbLowQualFrames = 4;\n    r.fullQualityMb = false;\n    r.clearedForMotionBlur = [];\n    r.desktopTapThreshold = options.desktopTapThreshold;\n    r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;\n    r.touchTapThreshold = options.touchTapThreshold;\n    r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;\n    r.tapholdDuration = 500;\n    r.bindings = [];\n    r.beforeRenderCallbacks = [];\n    r.beforeRenderPriorities = {\n      // higher priority execs before lower one\n      animations: 400,\n      eleCalcs: 300,\n      eleTxrDeq: 200,\n      lyrTxrDeq: 150,\n      lyrTxrSkip: 100\n    };\n    r.registerNodeShapes();\n    r.registerArrowShapes();\n    r.registerCalculationListeners();\n  };\n\n  BRp.notify = function (eventName, eles) {\n    var r = this;\n    var cy = r.cy; // the renderer can't be notified after it's destroyed\n\n    if (this.destroyed) {\n      return;\n    }\n\n    if (eventName === 'init') {\n      r.load();\n      return;\n    }\n\n    if (eventName === 'destroy') {\n      r.destroy();\n      return;\n    }\n\n    if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {\n      r.invalidateCachedZSortedEles();\n    }\n\n    if (eventName === 'viewport') {\n      r.redrawHint('select', true);\n    }\n\n    if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {\n      r.invalidateContainerClientCoordsCache();\n      r.matchCanvasSize(r.container);\n    }\n\n    r.redrawHint('eles', true);\n    r.redrawHint('drag', true);\n    this.startRenderLoop();\n    this.redraw();\n  };\n\n  BRp.destroy = function () {\n    var r = this;\n    r.destroyed = true;\n    r.cy.stopAnimationLoop();\n\n    for (var i = 0; i < r.bindings.length; i++) {\n      var binding = r.bindings[i];\n      var b = binding;\n      var tgt = b.target;\n      (tgt.off || tgt.removeEventListener).apply(tgt, b.args);\n    }\n\n    r.bindings = [];\n    r.beforeRenderCallbacks = [];\n    r.onUpdateEleCalcsFns = [];\n\n    if (r.removeObserver) {\n      r.removeObserver.disconnect();\n    }\n\n    if (r.styleObserver) {\n      r.styleObserver.disconnect();\n    }\n\n    if (r.resizeObserver) {\n      r.resizeObserver.disconnect();\n    }\n\n    if (r.labelCalcDiv) {\n      try {\n        document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef\n      } catch (e) {// ie10 issue #1014\n      }\n    }\n  };\n\n  BRp.isHeadless = function () {\n    return false;\n  };\n\n  [BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {\n    extend(BRp, props);\n  });\n\n  var fullFpsTime = 1000 / 60; // assume 60 frames per second\n\n  var defs = {\n    setupDequeueing: function setupDequeueing(opts) {\n      return function setupDequeueingImpl() {\n        var self = this;\n        var r = this.renderer;\n\n        if (self.dequeueingSetup) {\n          return;\n        } else {\n          self.dequeueingSetup = true;\n        }\n\n        var queueRedraw = debounce_1(function () {\n          r.redrawHint('eles', true);\n          r.redrawHint('drag', true);\n          r.redraw();\n        }, opts.deqRedrawThreshold);\n\n        var dequeue = function dequeue(willDraw, frameStartTime) {\n          var startTime = performanceNow();\n          var avgRenderTime = r.averageRedrawTime;\n          var renderTime = r.lastRedrawTime;\n          var deqd = [];\n          var extent = r.cy.extent();\n          var pixelRatio = r.getPixelRatio(); // if we aren't in a tick that causes a draw, then the rendered style\n          // queue won't automatically be flushed before dequeueing starts\n\n          if (!willDraw) {\n            r.flushRenderedStyleQueue();\n          }\n\n          while (true) {\n            // eslint-disable-line no-constant-condition\n            var now = performanceNow();\n            var duration = now - startTime;\n            var frameDuration = now - frameStartTime;\n\n            if (renderTime < fullFpsTime) {\n              // if we're rendering faster than the ideal fps, then do dequeueing\n              // during all of the remaining frame time\n              var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);\n\n              if (frameDuration >= opts.deqFastCost * timeAvailable) {\n                break;\n              }\n            } else {\n              if (willDraw) {\n                if (duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime) {\n                  break;\n                }\n              } else if (frameDuration >= opts.deqNoDrawCost * fullFpsTime) {\n                break;\n              }\n            }\n\n            var thisDeqd = opts.deq(self, pixelRatio, extent);\n\n            if (thisDeqd.length > 0) {\n              for (var i = 0; i < thisDeqd.length; i++) {\n                deqd.push(thisDeqd[i]);\n              }\n            } else {\n              break;\n            }\n          } // callbacks on dequeue\n\n\n          if (deqd.length > 0) {\n            opts.onDeqd(self, deqd);\n\n            if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {\n              queueRedraw();\n            }\n          }\n        };\n\n        var priority = opts.priority || noop$1;\n        r.beforeRender(dequeue, priority(self));\n      };\n    }\n  };\n\n  // Uses keys so elements may share the same cache.\n\n  var ElementTextureCacheLookup = /*#__PURE__*/function () {\n    function ElementTextureCacheLookup(getKey) {\n      var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;\n\n      _classCallCheck(this, ElementTextureCacheLookup);\n\n      this.idsByKey = new Map$2();\n      this.keyForId = new Map$2();\n      this.cachesByLvl = new Map$2();\n      this.lvls = [];\n      this.getKey = getKey;\n      this.doesEleInvalidateKey = doesEleInvalidateKey;\n    }\n\n    _createClass(ElementTextureCacheLookup, [{\n      key: \"getIdsFor\",\n      value: function getIdsFor(key) {\n        if (key == null) {\n          error(\"Can not get id list for null key\");\n        }\n\n        var idsByKey = this.idsByKey;\n        var ids = this.idsByKey.get(key);\n\n        if (!ids) {\n          ids = new Set$1();\n          idsByKey.set(key, ids);\n        }\n\n        return ids;\n      }\n    }, {\n      key: \"addIdForKey\",\n      value: function addIdForKey(key, id) {\n        if (key != null) {\n          this.getIdsFor(key).add(id);\n        }\n      }\n    }, {\n      key: \"deleteIdForKey\",\n      value: function deleteIdForKey(key, id) {\n        if (key != null) {\n          this.getIdsFor(key)[\"delete\"](id);\n        }\n      }\n    }, {\n      key: \"getNumberOfIdsForKey\",\n      value: function getNumberOfIdsForKey(key) {\n        if (key == null) {\n          return 0;\n        } else {\n          return this.getIdsFor(key).size;\n        }\n      }\n    }, {\n      key: \"updateKeyMappingFor\",\n      value: function updateKeyMappingFor(ele) {\n        var id = ele.id();\n        var prevKey = this.keyForId.get(id);\n        var currKey = this.getKey(ele);\n        this.deleteIdForKey(prevKey, id);\n        this.addIdForKey(currKey, id);\n        this.keyForId.set(id, currKey);\n      }\n    }, {\n      key: \"deleteKeyMappingFor\",\n      value: function deleteKeyMappingFor(ele) {\n        var id = ele.id();\n        var prevKey = this.keyForId.get(id);\n        this.deleteIdForKey(prevKey, id);\n        this.keyForId[\"delete\"](id);\n      }\n    }, {\n      key: \"keyHasChangedFor\",\n      value: function keyHasChangedFor(ele) {\n        var id = ele.id();\n        var prevKey = this.keyForId.get(id);\n        var newKey = this.getKey(ele);\n        return prevKey !== newKey;\n      }\n    }, {\n      key: \"isInvalid\",\n      value: function isInvalid(ele) {\n        return this.keyHasChangedFor(ele) || this.doesEleInvalidateKey(ele);\n      }\n    }, {\n      key: \"getCachesAt\",\n      value: function getCachesAt(lvl) {\n        var cachesByLvl = this.cachesByLvl,\n            lvls = this.lvls;\n        var caches = cachesByLvl.get(lvl);\n\n        if (!caches) {\n          caches = new Map$2();\n          cachesByLvl.set(lvl, caches);\n          lvls.push(lvl);\n        }\n\n        return caches;\n      }\n    }, {\n      key: \"getCache\",\n      value: function getCache(key, lvl) {\n        return this.getCachesAt(lvl).get(key);\n      }\n    }, {\n      key: \"get\",\n      value: function get(ele, lvl) {\n        var key = this.getKey(ele);\n        var cache = this.getCache(key, lvl); // getting for an element may need to add to the id list b/c eles can share keys\n\n        if (cache != null) {\n          this.updateKeyMappingFor(ele);\n        }\n\n        return cache;\n      }\n    }, {\n      key: \"getForCachedKey\",\n      value: function getForCachedKey(ele, lvl) {\n        var key = this.keyForId.get(ele.id()); // n.b. use cached key, not newly computed key\n\n        var cache = this.getCache(key, lvl);\n        return cache;\n      }\n    }, {\n      key: \"hasCache\",\n      value: function hasCache(key, lvl) {\n        return this.getCachesAt(lvl).has(key);\n      }\n    }, {\n      key: \"has\",\n      value: function has(ele, lvl) {\n        var key = this.getKey(ele);\n        return this.hasCache(key, lvl);\n      }\n    }, {\n      key: \"setCache\",\n      value: function setCache(key, lvl, cache) {\n        cache.key = key;\n        this.getCachesAt(lvl).set(key, cache);\n      }\n    }, {\n      key: \"set\",\n      value: function set(ele, lvl, cache) {\n        var key = this.getKey(ele);\n        this.setCache(key, lvl, cache);\n        this.updateKeyMappingFor(ele);\n      }\n    }, {\n      key: \"deleteCache\",\n      value: function deleteCache(key, lvl) {\n        this.getCachesAt(lvl)[\"delete\"](key);\n      }\n    }, {\n      key: \"delete\",\n      value: function _delete(ele, lvl) {\n        var key = this.getKey(ele);\n        this.deleteCache(key, lvl);\n      }\n    }, {\n      key: \"invalidateKey\",\n      value: function invalidateKey(key) {\n        var _this = this;\n\n        this.lvls.forEach(function (lvl) {\n          return _this.deleteCache(key, lvl);\n        });\n      } // returns true if no other eles reference the invalidated cache (n.b. other eles may need the cache with the same key)\n\n    }, {\n      key: \"invalidate\",\n      value: function invalidate(ele) {\n        var id = ele.id();\n        var key = this.keyForId.get(id); // n.b. use stored key rather than current (potential key)\n\n        this.deleteKeyMappingFor(ele);\n        var entireKeyInvalidated = this.doesEleInvalidateKey(ele);\n\n        if (entireKeyInvalidated) {\n          // clear mapping for current key\n          this.invalidateKey(key);\n        }\n\n        return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;\n      }\n    }]);\n\n    return ElementTextureCacheLookup;\n  }();\n\n  var minTxrH = 25; // the size of the texture cache for small height eles (special case)\n\n  var txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up\n\n  var minLvl$1 = -4; // when scaling smaller than that we don't need to re-render\n\n  var maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)\n\n  var maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used\n\n  var eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps\n\n  var defTxrWidth = 1024; // default/minimum texture width\n\n  var maxTxrW = 1024; // the maximum width of a texture\n\n  var maxTxrH = 1024; // the maximum height of a texture\n\n  var minUtility = 0.2; // if usage of texture is less than this, it is retired\n\n  var maxFullness = 0.8; // fullness of texture after which queue removal is checked\n\n  var maxFullnessChecks = 10; // dequeued after this many checks\n\n  var deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame\n\n  var deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time\n\n  var deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing\n\n  var deqFastCost$1 = 0.9; // % of frame time to be used when >60fps\n\n  var deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile\n\n  var maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch\n\n  var getTxrReasons = {\n    dequeue: 'dequeue',\n    downscale: 'downscale',\n    highQuality: 'highQuality'\n  };\n  var initDefaults = defaults$g({\n    getKey: null,\n    doesEleInvalidateKey: falsify,\n    drawElement: null,\n    getBoundingBox: null,\n    getRotationPoint: null,\n    getRotationOffset: null,\n    isVisible: trueify,\n    allowEdgeTxrCaching: true,\n    allowParentTxrCaching: true\n  });\n\n  var ElementTextureCache = function ElementTextureCache(renderer, initOptions) {\n    var self = this;\n    self.renderer = renderer;\n    self.onDequeues = [];\n    var opts = initDefaults(initOptions);\n    extend(self, opts);\n    self.lookup = new ElementTextureCacheLookup(opts.getKey, opts.doesEleInvalidateKey);\n    self.setupDequeueing();\n  };\n\n  var ETCp = ElementTextureCache.prototype;\n  ETCp.reasons = getTxrReasons; // the list of textures in which new subtextures for elements can be placed\n\n  ETCp.getTextureQueue = function (txrH) {\n    var self = this;\n    self.eleImgCaches = self.eleImgCaches || {};\n    return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];\n  }; // the list of usused textures which can be recycled (in use in texture queue)\n\n\n  ETCp.getRetiredTextureQueue = function (txrH) {\n    var self = this;\n    var rtxtrQs = self.eleImgCaches.retired = self.eleImgCaches.retired || {};\n    var rtxtrQ = rtxtrQs[txrH] = rtxtrQs[txrH] || [];\n    return rtxtrQ;\n  }; // queue of element draw requests at different scale levels\n\n\n  ETCp.getElementQueue = function () {\n    var self = this;\n    var q = self.eleCacheQueue = self.eleCacheQueue || new heap(function (a, b) {\n      return b.reqs - a.reqs;\n    });\n    return q;\n  }; // queue of element draw requests at different scale levels (element id lookup)\n\n\n  ETCp.getElementKeyToQueue = function () {\n    var self = this;\n    var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};\n    return k2q;\n  };\n\n  ETCp.getElement = function (ele, bb, pxRatio, lvl, reason) {\n    var self = this;\n    var r = this.renderer;\n    var zoom = r.cy.zoom();\n    var lookup = this.lookup;\n\n    if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {\n      return null;\n    }\n\n    if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {\n      return null;\n    }\n\n    if (lvl == null) {\n      lvl = Math.ceil(log2(zoom * pxRatio));\n    }\n\n    if (lvl < minLvl$1) {\n      lvl = minLvl$1;\n    } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {\n      return null;\n    }\n\n    var scale = Math.pow(2, lvl);\n    var eleScaledH = bb.h * scale;\n    var eleScaledW = bb.w * scale;\n    var scaledLabelShown = r.eleTextBiggerThanMin(ele, scale);\n\n    if (!this.isVisible(ele, scaledLabelShown)) {\n      return null;\n    }\n\n    var eleCache = lookup.get(ele, lvl); // if this get was on an unused/invalidated cache, then restore the texture usage metric\n\n    if (eleCache && eleCache.invalidated) {\n      eleCache.invalidated = false;\n      eleCache.texture.invalidatedWidth -= eleCache.width;\n    }\n\n    if (eleCache) {\n      return eleCache;\n    }\n\n    var txrH; // which texture height this ele belongs to\n\n    if (eleScaledH <= minTxrH) {\n      txrH = minTxrH;\n    } else if (eleScaledH <= txrStepH) {\n      txrH = txrStepH;\n    } else {\n      txrH = Math.ceil(eleScaledH / txrStepH) * txrStepH;\n    }\n\n    if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {\n      return null; // caching large elements is not efficient\n    }\n\n    var txrQ = self.getTextureQueue(txrH); // first try the second last one in case it has space at the end\n\n    var txr = txrQ[txrQ.length - 2];\n\n    var addNewTxr = function addNewTxr() {\n      return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);\n    }; // try the last one if there is no second last one\n\n\n    if (!txr) {\n      txr = txrQ[txrQ.length - 1];\n    } // if the last one doesn't exist, we need a first one\n\n\n    if (!txr) {\n      txr = addNewTxr();\n    } // if there's no room in the current texture, we need a new one\n\n\n    if (txr.width - txr.usedWidth < eleScaledW) {\n      txr = addNewTxr();\n    }\n\n    var scalableFrom = function scalableFrom(otherCache) {\n      return otherCache && otherCache.scaledLabelShown === scaledLabelShown;\n    };\n\n    var deqing = reason && reason === getTxrReasons.dequeue;\n    var highQualityReq = reason && reason === getTxrReasons.highQuality;\n    var downscaleReq = reason && reason === getTxrReasons.downscale;\n    var higherCache; // the nearest cache with a higher level\n\n    for (var l = lvl + 1; l <= maxLvl$1; l++) {\n      var c = lookup.get(ele, l);\n\n      if (c) {\n        higherCache = c;\n        break;\n      }\n    }\n\n    var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;\n\n    var downscale = function downscale() {\n      txr.context.drawImage(oneUpCache.texture.canvas, oneUpCache.x, 0, oneUpCache.width, oneUpCache.height, txr.usedWidth, 0, eleScaledW, eleScaledH);\n    }; // reset ele area in texture\n\n\n    txr.context.setTransform(1, 0, 0, 1, 0, 0);\n    txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);\n\n    if (scalableFrom(oneUpCache)) {\n      // then we can relatively cheaply rescale the existing image w/o rerendering\n      downscale();\n    } else if (scalableFrom(higherCache)) {\n      // then use the higher cache for now and queue the next level down\n      // to cheaply scale towards the smaller level\n      if (highQualityReq) {\n        for (var _l = higherCache.level; _l > lvl; _l--) {\n          oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);\n        }\n\n        downscale();\n      } else {\n        self.queueElement(ele, higherCache.level - 1);\n        return higherCache;\n      }\n    } else {\n      var lowerCache; // the nearest cache with a lower level\n\n      if (!deqing && !highQualityReq && !downscaleReq) {\n        for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {\n          var _c = lookup.get(ele, _l2);\n\n          if (_c) {\n            lowerCache = _c;\n            break;\n          }\n        }\n      }\n\n      if (scalableFrom(lowerCache)) {\n        // then use the lower quality cache for now and queue the better one for later\n        self.queueElement(ele, lvl);\n        return lowerCache;\n      }\n\n      txr.context.translate(txr.usedWidth, 0);\n      txr.context.scale(scale, scale);\n      this.drawElement(txr.context, ele, bb, scaledLabelShown, false);\n      txr.context.scale(1 / scale, 1 / scale);\n      txr.context.translate(-txr.usedWidth, 0);\n    }\n\n    eleCache = {\n      x: txr.usedWidth,\n      texture: txr,\n      level: lvl,\n      scale: scale,\n      width: eleScaledW,\n      height: eleScaledH,\n      scaledLabelShown: scaledLabelShown\n    };\n    txr.usedWidth += Math.ceil(eleScaledW + eleTxrSpacing);\n    txr.eleCaches.push(eleCache);\n    lookup.set(ele, lvl, eleCache);\n    self.checkTextureFullness(txr);\n    return eleCache;\n  };\n\n  ETCp.invalidateElements = function (eles) {\n    for (var i = 0; i < eles.length; i++) {\n      this.invalidateElement(eles[i]);\n    }\n  };\n\n  ETCp.invalidateElement = function (ele) {\n    var self = this;\n    var lookup = self.lookup;\n    var caches = [];\n    var invalid = lookup.isInvalid(ele);\n\n    if (!invalid) {\n      return; // override the invalidation request if the element key has not changed\n    }\n\n    for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {\n      var cache = lookup.getForCachedKey(ele, lvl);\n\n      if (cache) {\n        caches.push(cache);\n      }\n    }\n\n    var noOtherElesUseCache = lookup.invalidate(ele);\n\n    if (noOtherElesUseCache) {\n      for (var i = 0; i < caches.length; i++) {\n        var _cache = caches[i];\n        var txr = _cache.texture; // remove space from the texture it belongs to\n\n        txr.invalidatedWidth += _cache.width; // mark the cache as invalidated\n\n        _cache.invalidated = true; // retire the texture if its utility is low\n\n        self.checkTextureUtility(txr);\n      }\n    } // remove from queue since the old req was for the old state\n\n\n    self.removeFromQueue(ele);\n  };\n\n  ETCp.checkTextureUtility = function (txr) {\n    // invalidate all entries in the cache if the cache size is small\n    if (txr.invalidatedWidth >= minUtility * txr.width) {\n      this.retireTexture(txr);\n    }\n  };\n\n  ETCp.checkTextureFullness = function (txr) {\n    // if texture has been mostly filled and passed over several times, remove\n    // it from the queue so we don't need to waste time looking at it to put new things\n    var self = this;\n    var txrQ = self.getTextureQueue(txr.height);\n\n    if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {\n      removeFromArray(txrQ, txr);\n    } else {\n      txr.fullnessChecks++;\n    }\n  };\n\n  ETCp.retireTexture = function (txr) {\n    var self = this;\n    var txrH = txr.height;\n    var txrQ = self.getTextureQueue(txrH);\n    var lookup = this.lookup; // retire the texture from the active / searchable queue:\n\n    removeFromArray(txrQ, txr);\n    txr.retired = true; // remove the refs from the eles to the caches:\n\n    var eleCaches = txr.eleCaches;\n\n    for (var i = 0; i < eleCaches.length; i++) {\n      var eleCache = eleCaches[i];\n      lookup.deleteCache(eleCache.key, eleCache.level);\n    }\n\n    clearArray(eleCaches); // add the texture to a retired queue so it can be recycled in future:\n\n    var rtxtrQ = self.getRetiredTextureQueue(txrH);\n    rtxtrQ.push(txr);\n  };\n\n  ETCp.addTexture = function (txrH, minW) {\n    var self = this;\n    var txrQ = self.getTextureQueue(txrH);\n    var txr = {};\n    txrQ.push(txr);\n    txr.eleCaches = [];\n    txr.height = txrH;\n    txr.width = Math.max(defTxrWidth, minW);\n    txr.usedWidth = 0;\n    txr.invalidatedWidth = 0;\n    txr.fullnessChecks = 0;\n    txr.canvas = self.renderer.makeOffscreenCanvas(txr.width, txr.height);\n    txr.context = txr.canvas.getContext('2d');\n    return txr;\n  };\n\n  ETCp.recycleTexture = function (txrH, minW) {\n    var self = this;\n    var txrQ = self.getTextureQueue(txrH);\n    var rtxtrQ = self.getRetiredTextureQueue(txrH);\n\n    for (var i = 0; i < rtxtrQ.length; i++) {\n      var txr = rtxtrQ[i];\n\n      if (txr.width >= minW) {\n        txr.retired = false;\n        txr.usedWidth = 0;\n        txr.invalidatedWidth = 0;\n        txr.fullnessChecks = 0;\n        clearArray(txr.eleCaches);\n        txr.context.setTransform(1, 0, 0, 1, 0, 0);\n        txr.context.clearRect(0, 0, txr.width, txr.height);\n        removeFromArray(rtxtrQ, txr);\n        txrQ.push(txr);\n        return txr;\n      }\n    }\n  };\n\n  ETCp.queueElement = function (ele, lvl) {\n    var self = this;\n    var q = self.getElementQueue();\n    var k2q = self.getElementKeyToQueue();\n    var key = this.getKey(ele);\n    var existingReq = k2q[key];\n\n    if (existingReq) {\n      // use the max lvl b/c in between lvls are cheap to make\n      existingReq.level = Math.max(existingReq.level, lvl);\n      existingReq.eles.merge(ele);\n      existingReq.reqs++;\n      q.updateItem(existingReq);\n    } else {\n      var req = {\n        eles: ele.spawn().merge(ele),\n        level: lvl,\n        reqs: 1,\n        key: key\n      };\n      q.push(req);\n      k2q[key] = req;\n    }\n  };\n\n  ETCp.dequeue = function (pxRatio\n  /*, extent*/\n  ) {\n    var self = this;\n    var q = self.getElementQueue();\n    var k2q = self.getElementKeyToQueue();\n    var dequeued = [];\n    var lookup = self.lookup;\n\n    for (var i = 0; i < maxDeqSize$1; i++) {\n      if (q.size() > 0) {\n        var req = q.pop();\n        var key = req.key;\n        var ele = req.eles[0]; // all eles have the same key\n\n        var cacheExists = lookup.hasCache(ele, req.level); // clear out the key to req lookup\n\n        k2q[key] = null; // dequeueing isn't necessary with an existing cache\n\n        if (cacheExists) {\n          continue;\n        }\n\n        dequeued.push(req);\n        var bb = self.getBoundingBox(ele);\n        self.getElement(ele, bb, pxRatio, req.level, getTxrReasons.dequeue);\n      } else {\n        break;\n      }\n    }\n\n    return dequeued;\n  };\n\n  ETCp.removeFromQueue = function (ele) {\n    var self = this;\n    var q = self.getElementQueue();\n    var k2q = self.getElementKeyToQueue();\n    var key = this.getKey(ele);\n    var req = k2q[key];\n\n    if (req != null) {\n      if (req.eles.length === 1) {\n        // remove if last ele in the req\n        // bring to front of queue\n        req.reqs = MAX_INT$1;\n        q.updateItem(req);\n        q.pop(); // remove from queue\n\n        k2q[key] = null; // remove from lookup map\n      } else {\n        // otherwise just remove ele from req\n        req.eles.unmerge(ele);\n      }\n    }\n  };\n\n  ETCp.onDequeue = function (fn) {\n    this.onDequeues.push(fn);\n  };\n\n  ETCp.offDequeue = function (fn) {\n    removeFromArray(this.onDequeues, fn);\n  };\n\n  ETCp.setupDequeueing = defs.setupDequeueing({\n    deqRedrawThreshold: deqRedrawThreshold$1,\n    deqCost: deqCost$1,\n    deqAvgCost: deqAvgCost$1,\n    deqNoDrawCost: deqNoDrawCost$1,\n    deqFastCost: deqFastCost$1,\n    deq: function deq(self, pxRatio, extent) {\n      return self.dequeue(pxRatio, extent);\n    },\n    onDeqd: function onDeqd(self, deqd) {\n      for (var i = 0; i < self.onDequeues.length; i++) {\n        var fn = self.onDequeues[i];\n        fn(deqd);\n      }\n    },\n    shouldRedraw: function shouldRedraw(self, deqd, pxRatio, extent) {\n      for (var i = 0; i < deqd.length; i++) {\n        var eles = deqd[i].eles;\n\n        for (var j = 0; j < eles.length; j++) {\n          var bb = eles[j].boundingBox();\n\n          if (boundingBoxesIntersect(bb, extent)) {\n            return true;\n          }\n        }\n      }\n\n      return false;\n    },\n    priority: function priority(self) {\n      return self.renderer.beforeRenderPriorities.eleTxrDeq;\n    }\n  });\n\n  var defNumLayers = 1; // default number of layers to use\n\n  var minLvl = -4; // when scaling smaller than that we don't need to re-render\n\n  var maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)\n\n  var maxZoom = 3.99; // beyond this zoom level, layered textures are not used\n\n  var deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile\n\n  var refineEleDebounceTime = 50; // time to debounce sharper ele texture updates\n\n  var deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame\n\n  var deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time\n\n  var deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing\n\n  var deqFastCost = 0.9; // % of frame time to be used when >60fps\n\n  var maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch\n\n  var invalidThreshold = 250; // time threshold for disabling b/c of invalidations\n\n  var maxLayerArea = 4000 * 4000; // layers can't be bigger than this\n\n  var useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)\n  // var log = function(){ console.log.apply( console, arguments ); };\n\n  var LayeredTextureCache = function LayeredTextureCache(renderer) {\n    var self = this;\n    var r = self.renderer = renderer;\n    var cy = r.cy;\n    self.layersByLevel = {}; // e.g. 2 => [ layer1, layer2, ..., layerN ]\n\n    self.firstGet = true;\n    self.lastInvalidationTime = performanceNow() - 2 * invalidThreshold;\n    self.skipping = false;\n    self.eleTxrDeqs = cy.collection();\n    self.scheduleElementRefinement = debounce_1(function () {\n      self.refineElementTextures(self.eleTxrDeqs);\n      self.eleTxrDeqs.unmerge(self.eleTxrDeqs);\n    }, refineEleDebounceTime);\n    r.beforeRender(function (willDraw, now) {\n      if (now - self.lastInvalidationTime <= invalidThreshold) {\n        self.skipping = true;\n      } else {\n        self.skipping = false;\n      }\n    }, r.beforeRenderPriorities.lyrTxrSkip);\n\n    var qSort = function qSort(a, b) {\n      return b.reqs - a.reqs;\n    };\n\n    self.layersQueue = new heap(qSort);\n    self.setupDequeueing();\n  };\n\n  var LTCp = LayeredTextureCache.prototype;\n  var layerIdPool = 0;\n  var MAX_INT = Math.pow(2, 53) - 1;\n\n  LTCp.makeLayer = function (bb, lvl) {\n    var scale = Math.pow(2, lvl);\n    var w = Math.ceil(bb.w * scale);\n    var h = Math.ceil(bb.h * scale);\n    var canvas = this.renderer.makeOffscreenCanvas(w, h);\n    var layer = {\n      id: layerIdPool = ++layerIdPool % MAX_INT,\n      bb: bb,\n      level: lvl,\n      width: w,\n      height: h,\n      canvas: canvas,\n      context: canvas.getContext('2d'),\n      eles: [],\n      elesQueue: [],\n      reqs: 0\n    }; // log('make layer %s with w %s and h %s and lvl %s', layer.id, layer.width, layer.height, layer.level);\n\n    var cxt = layer.context;\n    var dx = -layer.bb.x1;\n    var dy = -layer.bb.y1; // do the transform on creation to save cycles (it's the same for all eles)\n\n    cxt.scale(scale, scale);\n    cxt.translate(dx, dy);\n    return layer;\n  };\n\n  LTCp.getLayers = function (eles, pxRatio, lvl) {\n    var self = this;\n    var r = self.renderer;\n    var cy = r.cy;\n    var zoom = cy.zoom();\n    var firstGet = self.firstGet;\n    self.firstGet = false; // log('--\\nget layers with %s eles', eles.length);\n    //log eles.map(function(ele){ return ele.id() }) );\n\n    if (lvl == null) {\n      lvl = Math.ceil(log2(zoom * pxRatio));\n\n      if (lvl < minLvl) {\n        lvl = minLvl;\n      } else if (zoom >= maxZoom || lvl > maxLvl) {\n        return null;\n      }\n    }\n\n    self.validateLayersElesOrdering(lvl, eles);\n    var layersByLvl = self.layersByLevel;\n    var scale = Math.pow(2, lvl);\n    var layers = layersByLvl[lvl] = layersByLvl[lvl] || [];\n    var bb;\n    var lvlComplete = self.levelIsComplete(lvl, eles);\n    var tmpLayers;\n\n    var checkTempLevels = function checkTempLevels() {\n      var canUseAsTmpLvl = function canUseAsTmpLvl(l) {\n        self.validateLayersElesOrdering(l, eles);\n\n        if (self.levelIsComplete(l, eles)) {\n          tmpLayers = layersByLvl[l];\n          return true;\n        }\n      };\n\n      var checkLvls = function checkLvls(dir) {\n        if (tmpLayers) {\n          return;\n        }\n\n        for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {\n          if (canUseAsTmpLvl(l)) {\n            break;\n          }\n        }\n      };\n\n      checkLvls(+1);\n      checkLvls(-1); // remove the invalid layers; they will be replaced as needed later in this function\n\n      for (var i = layers.length - 1; i >= 0; i--) {\n        var layer = layers[i];\n\n        if (layer.invalid) {\n          removeFromArray(layers, layer);\n        }\n      }\n    };\n\n    if (!lvlComplete) {\n      // if the current level is incomplete, then use the closest, best quality layerset temporarily\n      // and later queue the current layerset so we can get the proper quality level soon\n      checkTempLevels();\n    } else {\n      // log('level complete, using existing layers\\n--');\n      return layers;\n    }\n\n    var getBb = function getBb() {\n      if (!bb) {\n        bb = makeBoundingBox();\n\n        for (var i = 0; i < eles.length; i++) {\n          updateBoundingBox(bb, eles[i].boundingBox());\n        }\n      }\n\n      return bb;\n    };\n\n    var makeLayer = function makeLayer(opts) {\n      opts = opts || {};\n      var after = opts.after;\n      getBb();\n      var area = bb.w * scale * (bb.h * scale);\n\n      if (area > maxLayerArea) {\n        return null;\n      }\n\n      var layer = self.makeLayer(bb, lvl);\n\n      if (after != null) {\n        var index = layers.indexOf(after) + 1;\n        layers.splice(index, 0, layer);\n      } else if (opts.insert === undefined || opts.insert) {\n        // no after specified => first layer made so put at start\n        layers.unshift(layer);\n      } // if( tmpLayers ){\n      //self.queueLayer( layer );\n      // }\n\n\n      return layer;\n    };\n\n    if (self.skipping && !firstGet) {\n      // log('skip layers');\n      return null;\n    } // log('do layers');\n\n\n    var layer = null;\n    var maxElesPerLayer = eles.length / defNumLayers;\n    var allowLazyQueueing = !firstGet;\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      var rs = ele._private.rscratch;\n      var caches = rs.imgLayerCaches = rs.imgLayerCaches || {}; // log('look at ele', ele.id());\n\n      var existingLayer = caches[lvl];\n\n      if (existingLayer) {\n        // reuse layer for later eles\n        // log('reuse layer for', ele.id());\n        layer = existingLayer;\n        continue;\n      }\n\n      if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {\n        // log('make new layer for ele %s', ele.id());\n        layer = makeLayer({\n          insert: true,\n          after: layer\n        }); // if now layer can be built then we can't use layers at this level\n\n        if (!layer) {\n          return null;\n        } // log('new layer with id %s', layer.id);\n\n      }\n\n      if (tmpLayers || allowLazyQueueing) {\n        // log('queue ele %s in layer %s', ele.id(), layer.id);\n        self.queueLayer(layer, ele);\n      } else {\n        // log('draw ele %s in layer %s', ele.id(), layer.id);\n        self.drawEleInLayer(layer, ele, lvl, pxRatio);\n      }\n\n      layer.eles.push(ele);\n      caches[lvl] = layer;\n    } // log('--');\n\n\n    if (tmpLayers) {\n      // then we only queued the current layerset and can't draw it yet\n      return tmpLayers;\n    }\n\n    if (allowLazyQueueing) {\n      // log('lazy queue level', lvl);\n      return null;\n    }\n\n    return layers;\n  }; // a layer may want to use an ele cache of a higher level to avoid blurriness\n  // so the layer level might not equal the ele level\n\n\n  LTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {\n    return lvl;\n  };\n\n  LTCp.drawEleInLayer = function (layer, ele, lvl, pxRatio) {\n    var self = this;\n    var r = this.renderer;\n    var context = layer.context;\n    var bb = ele.boundingBox();\n\n    if (bb.w === 0 || bb.h === 0 || !ele.visible()) {\n      return;\n    }\n\n    lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);\n\n    {\n      r.setImgSmoothing(context, false);\n    }\n\n    {\n      r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);\n    }\n\n    {\n      r.setImgSmoothing(context, true);\n    }\n  };\n\n  LTCp.levelIsComplete = function (lvl, eles) {\n    var self = this;\n    var layers = self.layersByLevel[lvl];\n\n    if (!layers || layers.length === 0) {\n      return false;\n    }\n\n    var numElesInLayers = 0;\n\n    for (var i = 0; i < layers.length; i++) {\n      var layer = layers[i]; // if there are any eles needed to be drawn yet, the level is not complete\n\n      if (layer.reqs > 0) {\n        return false;\n      } // if the layer is invalid, the level is not complete\n\n\n      if (layer.invalid) {\n        return false;\n      }\n\n      numElesInLayers += layer.eles.length;\n    } // we should have exactly the number of eles passed in to be complete\n\n\n    if (numElesInLayers !== eles.length) {\n      return false;\n    }\n\n    return true;\n  };\n\n  LTCp.validateLayersElesOrdering = function (lvl, eles) {\n    var layers = this.layersByLevel[lvl];\n\n    if (!layers) {\n      return;\n    } // if in a layer the eles are not in the same order, then the layer is invalid\n    // (i.e. there is an ele in between the eles in the layer)\n\n\n    for (var i = 0; i < layers.length; i++) {\n      var layer = layers[i];\n      var offset = -1; // find the offset\n\n      for (var j = 0; j < eles.length; j++) {\n        if (layer.eles[0] === eles[j]) {\n          offset = j;\n          break;\n        }\n      }\n\n      if (offset < 0) {\n        // then the layer has nonexistent elements and is invalid\n        this.invalidateLayer(layer);\n        continue;\n      } // the eles in the layer must be in the same continuous order, else the layer is invalid\n\n\n      var o = offset;\n\n      for (var j = 0; j < layer.eles.length; j++) {\n        if (layer.eles[j] !== eles[o + j]) {\n          // log('invalidate based on ordering', layer.id);\n          this.invalidateLayer(layer);\n          break;\n        }\n      }\n    }\n  };\n\n  LTCp.updateElementsInLayers = function (eles, update) {\n    var self = this;\n    var isEles = element(eles[0]); // collect udpated elements (cascaded from the layers) and update each\n    // layer itself along the way\n\n    for (var i = 0; i < eles.length; i++) {\n      var req = isEles ? null : eles[i];\n      var ele = isEles ? eles[i] : eles[i].ele;\n      var rs = ele._private.rscratch;\n      var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};\n\n      for (var l = minLvl; l <= maxLvl; l++) {\n        var layer = caches[l];\n\n        if (!layer) {\n          continue;\n        } // if update is a request from the ele cache, then it affects only\n        // the matching level\n\n\n        if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {\n          continue;\n        }\n\n        update(layer, ele, req);\n      }\n    }\n  };\n\n  LTCp.haveLayers = function () {\n    var self = this;\n    var haveLayers = false;\n\n    for (var l = minLvl; l <= maxLvl; l++) {\n      var layers = self.layersByLevel[l];\n\n      if (layers && layers.length > 0) {\n        haveLayers = true;\n        break;\n      }\n    }\n\n    return haveLayers;\n  };\n\n  LTCp.invalidateElements = function (eles) {\n    var self = this;\n\n    if (eles.length === 0) {\n      return;\n    }\n\n    self.lastInvalidationTime = performanceNow(); // log('update invalidate layer time from eles');\n\n    if (eles.length === 0 || !self.haveLayers()) {\n      return;\n    }\n\n    self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {\n      self.invalidateLayer(layer);\n    });\n  };\n\n  LTCp.invalidateLayer = function (layer) {\n    // log('update invalidate layer time');\n    this.lastInvalidationTime = performanceNow();\n\n    if (layer.invalid) {\n      return;\n    } // save cycles\n\n\n    var lvl = layer.level;\n    var eles = layer.eles;\n    var layers = this.layersByLevel[lvl]; // log('invalidate layer', layer.id );\n\n    removeFromArray(layers, layer); // layer.eles = [];\n\n    layer.elesQueue = [];\n    layer.invalid = true;\n\n    if (layer.replacement) {\n      layer.replacement.invalid = true;\n    }\n\n    for (var i = 0; i < eles.length; i++) {\n      var caches = eles[i]._private.rscratch.imgLayerCaches;\n\n      if (caches) {\n        caches[lvl] = null;\n      }\n    }\n  };\n\n  LTCp.refineElementTextures = function (eles) {\n    var self = this; // log('refine', eles.length);\n\n    self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {\n      var rLyr = layer.replacement;\n\n      if (!rLyr) {\n        rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);\n        rLyr.replaces = layer;\n        rLyr.eles = layer.eles; // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);\n      }\n\n      if (!rLyr.reqs) {\n        for (var i = 0; i < rLyr.eles.length; i++) {\n          self.queueLayer(rLyr, rLyr.eles[i]);\n        } // log('queue replacement layer refinement', rLyr.id);\n\n      }\n    });\n  };\n\n  LTCp.enqueueElementRefinement = function (ele) {\n\n    this.eleTxrDeqs.merge(ele);\n    this.scheduleElementRefinement();\n  };\n\n  LTCp.queueLayer = function (layer, ele) {\n    var self = this;\n    var q = self.layersQueue;\n    var elesQ = layer.elesQueue;\n    var hasId = elesQ.hasId = elesQ.hasId || {}; // if a layer is going to be replaced, queuing is a waste of time\n\n    if (layer.replacement) {\n      return;\n    }\n\n    if (ele) {\n      if (hasId[ele.id()]) {\n        return;\n      }\n\n      elesQ.push(ele);\n      hasId[ele.id()] = true;\n    }\n\n    if (layer.reqs) {\n      layer.reqs++;\n      q.updateItem(layer);\n    } else {\n      layer.reqs = 1;\n      q.push(layer);\n    }\n  };\n\n  LTCp.dequeue = function (pxRatio) {\n    var self = this;\n    var q = self.layersQueue;\n    var deqd = [];\n    var eleDeqs = 0;\n\n    while (eleDeqs < maxDeqSize) {\n      if (q.size() === 0) {\n        break;\n      }\n\n      var layer = q.peek(); // if a layer has been or will be replaced, then don't waste time with it\n\n      if (layer.replacement) {\n        // log('layer %s in queue skipped b/c it already has a replacement', layer.id);\n        q.pop();\n        continue;\n      } // if this is a replacement layer that has been superceded, then forget it\n\n\n      if (layer.replaces && layer !== layer.replaces.replacement) {\n        // log('layer is no longer the most uptodate replacement; dequeued', layer.id)\n        q.pop();\n        continue;\n      }\n\n      if (layer.invalid) {\n        // log('replacement layer %s is invalid; dequeued', layer.id);\n        q.pop();\n        continue;\n      }\n\n      var ele = layer.elesQueue.shift();\n\n      if (ele) {\n        // log('dequeue layer %s', layer.id);\n        self.drawEleInLayer(layer, ele, layer.level, pxRatio);\n        eleDeqs++;\n      }\n\n      if (deqd.length === 0) {\n        // we need only one entry in deqd to queue redrawing etc\n        deqd.push(true);\n      } // if the layer has all its eles done, then remove from the queue\n\n\n      if (layer.elesQueue.length === 0) {\n        q.pop();\n        layer.reqs = 0; // log('dequeue of layer %s complete', layer.id);\n        // when a replacement layer is dequeued, it replaces the old layer in the level\n\n        if (layer.replaces) {\n          self.applyLayerReplacement(layer);\n        }\n\n        self.requestRedraw();\n      }\n    }\n\n    return deqd;\n  };\n\n  LTCp.applyLayerReplacement = function (layer) {\n    var self = this;\n    var layersInLevel = self.layersByLevel[layer.level];\n    var replaced = layer.replaces;\n    var index = layersInLevel.indexOf(replaced); // if the replaced layer is not in the active list for the level, then replacing\n    // refs would be a mistake (i.e. overwriting the true active layer)\n\n    if (index < 0 || replaced.invalid) {\n      // log('replacement layer would have no effect', layer.id);\n      return;\n    }\n\n    layersInLevel[index] = layer; // replace level ref\n    // replace refs in eles\n\n    for (var i = 0; i < layer.eles.length; i++) {\n      var _p = layer.eles[i]._private;\n      var cache = _p.imgLayerCaches = _p.imgLayerCaches || {};\n\n      if (cache) {\n        cache[layer.level] = layer;\n      }\n    } // log('apply replacement layer %s over %s', layer.id, replaced.id);\n\n\n    self.requestRedraw();\n  };\n\n  LTCp.requestRedraw = debounce_1(function () {\n    var r = this.renderer;\n    r.redrawHint('eles', true);\n    r.redrawHint('drag', true);\n    r.redraw();\n  }, 100);\n  LTCp.setupDequeueing = defs.setupDequeueing({\n    deqRedrawThreshold: deqRedrawThreshold,\n    deqCost: deqCost,\n    deqAvgCost: deqAvgCost,\n    deqNoDrawCost: deqNoDrawCost,\n    deqFastCost: deqFastCost,\n    deq: function deq(self, pxRatio) {\n      return self.dequeue(pxRatio);\n    },\n    onDeqd: noop$1,\n    shouldRedraw: trueify,\n    priority: function priority(self) {\n      return self.renderer.beforeRenderPriorities.lyrTxrDeq;\n    }\n  });\n\n  var CRp$a = {};\n  var impl;\n\n  function polygon(context, points) {\n    for (var i = 0; i < points.length; i++) {\n      var pt = points[i];\n      context.lineTo(pt.x, pt.y);\n    }\n  }\n\n  function triangleBackcurve(context, points, controlPoint) {\n    var firstPt;\n\n    for (var i = 0; i < points.length; i++) {\n      var pt = points[i];\n\n      if (i === 0) {\n        firstPt = pt;\n      }\n\n      context.lineTo(pt.x, pt.y);\n    }\n\n    context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);\n  }\n\n  function triangleTee(context, trianglePoints, teePoints) {\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    var triPts = trianglePoints;\n\n    for (var i = 0; i < triPts.length; i++) {\n      var pt = triPts[i];\n      context.lineTo(pt.x, pt.y);\n    }\n\n    var teePts = teePoints;\n    var firstTeePt = teePoints[0];\n    context.moveTo(firstTeePt.x, firstTeePt.y);\n\n    for (var i = 1; i < teePts.length; i++) {\n      var pt = teePts[i];\n      context.lineTo(pt.x, pt.y);\n    }\n\n    if (context.closePath) {\n      context.closePath();\n    }\n  }\n\n  function circleTriangle(context, trianglePoints, rx, ry, r) {\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    context.arc(rx, ry, r, 0, Math.PI * 2, false);\n    var triPts = trianglePoints;\n    var firstTrPt = triPts[0];\n    context.moveTo(firstTrPt.x, firstTrPt.y);\n\n    for (var i = 0; i < triPts.length; i++) {\n      var pt = triPts[i];\n      context.lineTo(pt.x, pt.y);\n    }\n\n    if (context.closePath) {\n      context.closePath();\n    }\n  }\n\n  function circle(context, rx, ry, r) {\n    context.arc(rx, ry, r, 0, Math.PI * 2, false);\n  }\n\n  CRp$a.arrowShapeImpl = function (name) {\n    return (impl || (impl = {\n      'polygon': polygon,\n      'triangle-backcurve': triangleBackcurve,\n      'triangle-tee': triangleTee,\n      'circle-triangle': circleTriangle,\n      'triangle-cross': triangleTee,\n      'circle': circle\n    }))[name];\n  };\n\n  var CRp$9 = {};\n\n  CRp$9.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {\n    var r = this;\n\n    if (ele.isNode()) {\n      r.drawNode(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);\n    } else {\n      r.drawEdge(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);\n    }\n  };\n\n  CRp$9.drawElementOverlay = function (context, ele) {\n    var r = this;\n\n    if (ele.isNode()) {\n      r.drawNodeOverlay(context, ele);\n    } else {\n      r.drawEdgeOverlay(context, ele);\n    }\n  };\n\n  CRp$9.drawElementUnderlay = function (context, ele) {\n    var r = this;\n\n    if (ele.isNode()) {\n      r.drawNodeUnderlay(context, ele);\n    } else {\n      r.drawEdgeUnderlay(context, ele);\n    }\n  };\n\n  CRp$9.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {\n    var r = this;\n    var bb = eleTxrCache.getBoundingBox(ele);\n\n    if (bb.w === 0 || bb.h === 0) {\n      return;\n    } // ignore zero size case\n\n\n    var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);\n\n    if (eleCache != null) {\n      var opacity = getOpacity(r, ele);\n\n      if (opacity === 0) {\n        return;\n      }\n\n      var theta = getRotation(r, ele);\n      var x1 = bb.x1,\n          y1 = bb.y1,\n          w = bb.w,\n          h = bb.h;\n      var x, y, sx, sy, smooth;\n\n      if (theta !== 0) {\n        var rotPt = eleTxrCache.getRotationPoint(ele);\n        sx = rotPt.x;\n        sy = rotPt.y;\n        context.translate(sx, sy);\n        context.rotate(theta);\n        smooth = r.getImgSmoothing(context);\n\n        if (!smooth) {\n          r.setImgSmoothing(context, true);\n        }\n\n        var off = eleTxrCache.getRotationOffset(ele);\n        x = off.x;\n        y = off.y;\n      } else {\n        x = x1;\n        y = y1;\n      }\n\n      var oldGlobalAlpha;\n\n      if (opacity !== 1) {\n        oldGlobalAlpha = context.globalAlpha;\n        context.globalAlpha = oldGlobalAlpha * opacity;\n      }\n\n      context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);\n\n      if (opacity !== 1) {\n        context.globalAlpha = oldGlobalAlpha;\n      }\n\n      if (theta !== 0) {\n        context.rotate(-theta);\n        context.translate(-sx, -sy);\n\n        if (!smooth) {\n          r.setImgSmoothing(context, false);\n        }\n      }\n    } else {\n      eleTxrCache.drawElement(context, ele); // direct draw fallback\n    }\n  };\n\n  var getZeroRotation = function getZeroRotation() {\n    return 0;\n  };\n\n  var getLabelRotation = function getLabelRotation(r, ele) {\n    return r.getTextAngle(ele, null);\n  };\n\n  var getSourceLabelRotation = function getSourceLabelRotation(r, ele) {\n    return r.getTextAngle(ele, 'source');\n  };\n\n  var getTargetLabelRotation = function getTargetLabelRotation(r, ele) {\n    return r.getTextAngle(ele, 'target');\n  };\n\n  var getOpacity = function getOpacity(r, ele) {\n    return ele.effectiveOpacity();\n  };\n\n  var getTextOpacity = function getTextOpacity(e, ele) {\n    return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();\n  };\n\n  CRp$9.drawCachedElement = function (context, ele, pxRatio, extent, lvl, requestHighQuality) {\n    var r = this;\n    var _r$data = r.data,\n        eleTxrCache = _r$data.eleTxrCache,\n        lblTxrCache = _r$data.lblTxrCache,\n        slbTxrCache = _r$data.slbTxrCache,\n        tlbTxrCache = _r$data.tlbTxrCache;\n    var bb = ele.boundingBox();\n    var reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;\n\n    if (bb.w === 0 || bb.h === 0 || !ele.visible()) {\n      return;\n    }\n\n    if (!extent || boundingBoxesIntersect(bb, extent)) {\n      var isEdge = ele.isEdge();\n\n      var badLine = ele.element()._private.rscratch.badLine;\n\n      r.drawElementUnderlay(context, ele);\n      r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);\n\n      if (!isEdge || !badLine) {\n        r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);\n      }\n\n      if (isEdge && !badLine) {\n        r.drawCachedElementPortion(context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation, getTextOpacity);\n        r.drawCachedElementPortion(context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation, getTextOpacity);\n      }\n\n      r.drawElementOverlay(context, ele);\n    }\n  };\n\n  CRp$9.drawElements = function (context, eles) {\n    var r = this;\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      r.drawElement(context, ele);\n    }\n  };\n\n  CRp$9.drawCachedElements = function (context, eles, pxRatio, extent) {\n    var r = this;\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      r.drawCachedElement(context, ele, pxRatio, extent);\n    }\n  };\n\n  CRp$9.drawCachedNodes = function (context, eles, pxRatio, extent) {\n    var r = this;\n\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n\n      if (!ele.isNode()) {\n        continue;\n      }\n\n      r.drawCachedElement(context, ele, pxRatio, extent);\n    }\n  };\n\n  CRp$9.drawLayeredElements = function (context, eles, pxRatio, extent) {\n    var r = this;\n    var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);\n\n    if (layers) {\n      for (var i = 0; i < layers.length; i++) {\n        var layer = layers[i];\n        var bb = layer.bb;\n\n        if (bb.w === 0 || bb.h === 0) {\n          continue;\n        }\n\n        context.drawImage(layer.canvas, bb.x1, bb.y1, bb.w, bb.h);\n      }\n    } else {\n      // fall back on plain caching if no layers\n      r.drawCachedElements(context, eles, pxRatio, extent);\n    }\n  };\n\n  /* global Path2D */\n  var CRp$8 = {};\n\n  CRp$8.drawEdge = function (context, edge, shiftToOriginWithBb) {\n    var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n    var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n    var r = this;\n    var rs = edge._private.rscratch;\n\n    if (shouldDrawOpacity && !edge.visible()) {\n      return;\n    } // if bezier ctrl pts can not be calculated, then die\n\n\n    if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {\n      // isNaN in case edge is impossible and browser bugs (e.g. safari)\n      return;\n    }\n\n    var bb;\n\n    if (shiftToOriginWithBb) {\n      bb = shiftToOriginWithBb;\n      context.translate(-bb.x1, -bb.y1);\n    }\n\n    var opacity = shouldDrawOpacity ? edge.pstyle('opacity').value : 1;\n    var lineOpacity = shouldDrawOpacity ? edge.pstyle('line-opacity').value : 1;\n    var curveStyle = edge.pstyle('curve-style').value;\n    var lineStyle = edge.pstyle('line-style').value;\n    var edgeWidth = edge.pstyle('width').pfValue;\n    var lineCap = edge.pstyle('line-cap').value;\n    var effectiveLineOpacity = opacity * lineOpacity; // separate arrow opacity would require arrow-opacity property\n\n    var effectiveArrowOpacity = opacity * lineOpacity;\n\n    var drawLine = function drawLine() {\n      var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;\n\n      if (curveStyle === 'straight-triangle') {\n        r.eleStrokeStyle(context, edge, strokeOpacity);\n        r.drawEdgeTrianglePath(edge, context, rs.allpts);\n      } else {\n        context.lineWidth = edgeWidth;\n        context.lineCap = lineCap;\n        r.eleStrokeStyle(context, edge, strokeOpacity);\n        r.drawEdgePath(edge, context, rs.allpts, lineStyle);\n        context.lineCap = 'butt'; // reset for other drawing functions\n      }\n    };\n\n    var drawOverlay = function drawOverlay() {\n      if (!shouldDrawOverlay) {\n        return;\n      }\n\n      r.drawEdgeOverlay(context, edge);\n    };\n\n    var drawUnderlay = function drawUnderlay() {\n      if (!shouldDrawOverlay) {\n        return;\n      }\n\n      r.drawEdgeUnderlay(context, edge);\n    };\n\n    var drawArrows = function drawArrows() {\n      var arrowOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveArrowOpacity;\n      r.drawArrowheads(context, edge, arrowOpacity);\n    };\n\n    var drawText = function drawText() {\n      r.drawElementText(context, edge, null, drawLabel);\n    };\n\n    context.lineJoin = 'round';\n    var ghost = edge.pstyle('ghost').value === 'yes';\n\n    if (ghost) {\n      var gx = edge.pstyle('ghost-offset-x').pfValue;\n      var gy = edge.pstyle('ghost-offset-y').pfValue;\n      var ghostOpacity = edge.pstyle('ghost-opacity').value;\n      var effectiveGhostOpacity = effectiveLineOpacity * ghostOpacity;\n      context.translate(gx, gy);\n      drawLine(effectiveGhostOpacity);\n      drawArrows(effectiveGhostOpacity);\n      context.translate(-gx, -gy);\n    }\n\n    drawUnderlay();\n    drawLine();\n    drawArrows();\n    drawOverlay();\n    drawText();\n\n    if (shiftToOriginWithBb) {\n      context.translate(bb.x1, bb.y1);\n    }\n  };\n\n  var drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {\n    if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {\n      throw new Error('Invalid state');\n    }\n\n    return function (context, edge) {\n      if (!edge.visible()) {\n        return;\n      }\n\n      var opacity = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-opacity\")).value;\n\n      if (opacity === 0) {\n        return;\n      }\n\n      var r = this;\n      var usePaths = r.usePaths();\n      var rs = edge._private.rscratch;\n      var padding = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-padding\")).pfValue;\n      var width = 2 * padding;\n      var color = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-color\")).value;\n      context.lineWidth = width;\n\n      if (rs.edgeType === 'self' && !usePaths) {\n        context.lineCap = 'butt';\n      } else {\n        context.lineCap = 'round';\n      }\n\n      r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);\n      r.drawEdgePath(edge, context, rs.allpts, 'solid');\n    };\n  };\n\n  CRp$8.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');\n  CRp$8.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');\n\n  CRp$8.drawEdgePath = function (edge, context, pts, type) {\n    var rs = edge._private.rscratch;\n    var canvasCxt = context;\n    var path;\n    var pathCacheHit = false;\n    var usePaths = this.usePaths();\n    var lineDashPattern = edge.pstyle('line-dash-pattern').pfValue;\n    var lineDashOffset = edge.pstyle('line-dash-offset').pfValue;\n\n    if (usePaths) {\n      var pathCacheKey = pts.join('$');\n      var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;\n\n      if (keyMatches) {\n        path = context = rs.pathCache;\n        pathCacheHit = true;\n      } else {\n        path = context = new Path2D();\n        rs.pathCacheKey = pathCacheKey;\n        rs.pathCache = path;\n      }\n    }\n\n    if (canvasCxt.setLineDash) {\n      // for very outofdate browsers\n      switch (type) {\n        case 'dotted':\n          canvasCxt.setLineDash([1, 1]);\n          break;\n\n        case 'dashed':\n          canvasCxt.setLineDash(lineDashPattern);\n          canvasCxt.lineDashOffset = lineDashOffset;\n          break;\n\n        case 'solid':\n          canvasCxt.setLineDash([]);\n          break;\n      }\n    }\n\n    if (!pathCacheHit && !rs.badLine) {\n      if (context.beginPath) {\n        context.beginPath();\n      }\n\n      context.moveTo(pts[0], pts[1]);\n\n      switch (rs.edgeType) {\n        case 'bezier':\n        case 'self':\n        case 'compound':\n        case 'multibezier':\n          for (var i = 2; i + 3 < pts.length; i += 4) {\n            context.quadraticCurveTo(pts[i], pts[i + 1], pts[i + 2], pts[i + 3]);\n          }\n\n          break;\n\n        case 'straight':\n        case 'segments':\n        case 'haystack':\n          for (var _i = 2; _i + 1 < pts.length; _i += 2) {\n            context.lineTo(pts[_i], pts[_i + 1]);\n          }\n\n          break;\n      }\n    }\n\n    context = canvasCxt;\n\n    if (usePaths) {\n      context.stroke(path);\n    } else {\n      context.stroke();\n    } // reset any line dashes\n\n\n    if (context.setLineDash) {\n      // for very outofdate browsers\n      context.setLineDash([]);\n    }\n  };\n\n  CRp$8.drawEdgeTrianglePath = function (edge, context, pts) {\n    // use line stroke style for triangle fill style\n    context.fillStyle = context.strokeStyle;\n    var edgeWidth = edge.pstyle('width').pfValue;\n\n    for (var i = 0; i + 1 < pts.length; i += 2) {\n      var vector = [pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]];\n      var length = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);\n      var normal = [vector[1] / length, -vector[0] / length];\n      var triangleHead = [normal[0] * edgeWidth / 2, normal[1] * edgeWidth / 2];\n      context.beginPath();\n      context.moveTo(pts[i] - triangleHead[0], pts[i + 1] - triangleHead[1]);\n      context.lineTo(pts[i] + triangleHead[0], pts[i + 1] + triangleHead[1]);\n      context.lineTo(pts[i + 2], pts[i + 3]);\n      context.closePath();\n      context.fill();\n    }\n  };\n\n  CRp$8.drawArrowheads = function (context, edge, opacity) {\n    var rs = edge._private.rscratch;\n    var isHaystack = rs.edgeType === 'haystack';\n\n    if (!isHaystack) {\n      this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);\n    }\n\n    this.drawArrowhead(context, edge, 'mid-target', rs.midX, rs.midY, rs.midtgtArrowAngle, opacity);\n    this.drawArrowhead(context, edge, 'mid-source', rs.midX, rs.midY, rs.midsrcArrowAngle, opacity);\n\n    if (!isHaystack) {\n      this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);\n    }\n  };\n\n  CRp$8.drawArrowhead = function (context, edge, prefix, x, y, angle, opacity) {\n    if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {\n      return;\n    }\n\n    var self = this;\n    var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;\n\n    if (arrowShape === 'none') {\n      return;\n    }\n\n    var arrowClearFill = edge.pstyle(prefix + '-arrow-fill').value === 'hollow' ? 'both' : 'filled';\n    var arrowFill = edge.pstyle(prefix + '-arrow-fill').value;\n    var edgeWidth = edge.pstyle('width').pfValue;\n    var edgeOpacity = edge.pstyle('opacity').value;\n\n    if (opacity === undefined) {\n      opacity = edgeOpacity;\n    }\n\n    var gco = context.globalCompositeOperation;\n\n    if (opacity !== 1 || arrowFill === 'hollow') {\n      // then extra clear is needed\n      context.globalCompositeOperation = 'destination-out';\n      self.colorFillStyle(context, 255, 255, 255, 1);\n      self.colorStrokeStyle(context, 255, 255, 255, 1);\n      self.drawArrowShape(edge, context, arrowClearFill, edgeWidth, arrowShape, x, y, angle);\n      context.globalCompositeOperation = gco;\n    } // otherwise, the opaque arrow clears it for free :)\n\n\n    var color = edge.pstyle(prefix + '-arrow-color').value;\n    self.colorFillStyle(context, color[0], color[1], color[2], opacity);\n    self.colorStrokeStyle(context, color[0], color[1], color[2], opacity);\n    self.drawArrowShape(edge, context, arrowFill, edgeWidth, arrowShape, x, y, angle);\n  };\n\n  CRp$8.drawArrowShape = function (edge, context, fill, edgeWidth, shape, x, y, angle) {\n    var r = this;\n    var usePaths = this.usePaths() && shape !== 'triangle-cross';\n    var pathCacheHit = false;\n    var path;\n    var canvasContext = context;\n    var translation = {\n      x: x,\n      y: y\n    };\n    var scale = edge.pstyle('arrow-scale').value;\n    var size = this.getArrowWidth(edgeWidth, scale);\n    var shapeImpl = r.arrowShapes[shape];\n\n    if (usePaths) {\n      var cache = r.arrowPathCache = r.arrowPathCache || [];\n      var key = hashString(shape);\n      var cachedPath = cache[key];\n\n      if (cachedPath != null) {\n        path = context = cachedPath;\n        pathCacheHit = true;\n      } else {\n        path = context = new Path2D();\n        cache[key] = path;\n      }\n    }\n\n    if (!pathCacheHit) {\n      if (context.beginPath) {\n        context.beginPath();\n      }\n\n      if (usePaths) {\n        // store in the path cache with values easily manipulated later\n        shapeImpl.draw(context, 1, 0, {\n          x: 0,\n          y: 0\n        }, 1);\n      } else {\n        shapeImpl.draw(context, size, angle, translation, edgeWidth);\n      }\n\n      if (context.closePath) {\n        context.closePath();\n      }\n    }\n\n    context = canvasContext;\n\n    if (usePaths) {\n      // set transform to arrow position/orientation\n      context.translate(x, y);\n      context.rotate(angle);\n      context.scale(size, size);\n    }\n\n    if (fill === 'filled' || fill === 'both') {\n      if (usePaths) {\n        context.fill(path);\n      } else {\n        context.fill();\n      }\n    }\n\n    if (fill === 'hollow' || fill === 'both') {\n      context.lineWidth = (shapeImpl.matchEdgeWidth ? edgeWidth : 1) / (usePaths ? size : 1);\n      context.lineJoin = 'miter';\n\n      if (usePaths) {\n        context.stroke(path);\n      } else {\n        context.stroke();\n      }\n    }\n\n    if (usePaths) {\n      // reset transform by applying inverse\n      context.scale(1 / size, 1 / size);\n      context.rotate(-angle);\n      context.translate(-x, -y);\n    }\n  };\n\n  var CRp$7 = {};\n\n  CRp$7.safeDrawImage = function (context, img, ix, iy, iw, ih, x, y, w, h) {\n    // detect problematic cases for old browsers with bad images (cheaper than try-catch)\n    if (iw <= 0 || ih <= 0 || w <= 0 || h <= 0) {\n      return;\n    }\n\n    try {\n      context.drawImage(img, ix, iy, iw, ih, x, y, w, h);\n    } catch (e) {\n      warn(e);\n    }\n  };\n\n  CRp$7.drawInscribedImage = function (context, img, node, index, nodeOpacity) {\n    var r = this;\n    var pos = node.position();\n    var nodeX = pos.x;\n    var nodeY = pos.y;\n    var styleObj = node.cy().style();\n    var getIndexedStyle = styleObj.getIndexedStyle.bind(styleObj);\n    var fit = getIndexedStyle(node, 'background-fit', 'value', index);\n    var repeat = getIndexedStyle(node, 'background-repeat', 'value', index);\n    var nodeW = node.width();\n    var nodeH = node.height();\n    var paddingX2 = node.padding() * 2;\n    var nodeTW = nodeW + (getIndexedStyle(node, 'background-width-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);\n    var nodeTH = nodeH + (getIndexedStyle(node, 'background-height-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);\n    var rs = node._private.rscratch;\n    var clip = getIndexedStyle(node, 'background-clip', 'value', index);\n    var shouldClip = clip === 'node';\n    var imgOpacity = getIndexedStyle(node, 'background-image-opacity', 'value', index) * nodeOpacity;\n    var smooth = getIndexedStyle(node, 'background-image-smoothing', 'value', index);\n    var imgW = img.width || img.cachedW;\n    var imgH = img.height || img.cachedH; // workaround for broken browsers like ie\n\n    if (null == imgW || null == imgH) {\n      document.body.appendChild(img); // eslint-disable-line no-undef\n\n      imgW = img.cachedW = img.width || img.offsetWidth;\n      imgH = img.cachedH = img.height || img.offsetHeight;\n      document.body.removeChild(img); // eslint-disable-line no-undef\n    }\n\n    var w = imgW;\n    var h = imgH;\n\n    if (getIndexedStyle(node, 'background-width', 'value', index) !== 'auto') {\n      if (getIndexedStyle(node, 'background-width', 'units', index) === '%') {\n        w = getIndexedStyle(node, 'background-width', 'pfValue', index) * nodeTW;\n      } else {\n        w = getIndexedStyle(node, 'background-width', 'pfValue', index);\n      }\n    }\n\n    if (getIndexedStyle(node, 'background-height', 'value', index) !== 'auto') {\n      if (getIndexedStyle(node, 'background-height', 'units', index) === '%') {\n        h = getIndexedStyle(node, 'background-height', 'pfValue', index) * nodeTH;\n      } else {\n        h = getIndexedStyle(node, 'background-height', 'pfValue', index);\n      }\n    }\n\n    if (w === 0 || h === 0) {\n      return; // no point in drawing empty image (and chrome is broken in this case)\n    }\n\n    if (fit === 'contain') {\n      var scale = Math.min(nodeTW / w, nodeTH / h);\n      w *= scale;\n      h *= scale;\n    } else if (fit === 'cover') {\n      var scale = Math.max(nodeTW / w, nodeTH / h);\n      w *= scale;\n      h *= scale;\n    }\n\n    var x = nodeX - nodeTW / 2; // left\n\n    var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);\n    var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);\n\n    if (posXUnits === '%') {\n      x += (nodeTW - w) * posXPfVal;\n    } else {\n      x += posXPfVal;\n    }\n\n    var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);\n    var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);\n\n    if (offXUnits === '%') {\n      x += (nodeTW - w) * offXPfVal;\n    } else {\n      x += offXPfVal;\n    }\n\n    var y = nodeY - nodeTH / 2; // top\n\n    var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);\n    var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);\n\n    if (posYUnits === '%') {\n      y += (nodeTH - h) * posYPfVal;\n    } else {\n      y += posYPfVal;\n    }\n\n    var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);\n    var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);\n\n    if (offYUnits === '%') {\n      y += (nodeTH - h) * offYPfVal;\n    } else {\n      y += offYPfVal;\n    }\n\n    if (rs.pathCache) {\n      x -= nodeX;\n      y -= nodeY;\n      nodeX = 0;\n      nodeY = 0;\n    }\n\n    var gAlpha = context.globalAlpha;\n    context.globalAlpha = imgOpacity;\n    var smoothingEnabled = r.getImgSmoothing(context);\n    var isSmoothingSwitched = false;\n\n    if (smooth === 'no' && smoothingEnabled) {\n      r.setImgSmoothing(context, false);\n      isSmoothingSwitched = true;\n    } else if (smooth === 'yes' && !smoothingEnabled) {\n      r.setImgSmoothing(context, true);\n      isSmoothingSwitched = true;\n    }\n\n    if (repeat === 'no-repeat') {\n      if (shouldClip) {\n        context.save();\n\n        if (rs.pathCache) {\n          context.clip(rs.pathCache);\n        } else {\n          r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH);\n          context.clip();\n        }\n      }\n\n      r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);\n\n      if (shouldClip) {\n        context.restore();\n      }\n    } else {\n      var pattern = context.createPattern(img, repeat);\n      context.fillStyle = pattern;\n      r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH);\n      context.translate(x, y);\n      context.fill();\n      context.translate(-x, -y);\n    }\n\n    context.globalAlpha = gAlpha;\n\n    if (isSmoothingSwitched) {\n      r.setImgSmoothing(context, smoothingEnabled);\n    }\n  };\n\n  var CRp$6 = {};\n\n  CRp$6.eleTextBiggerThanMin = function (ele, scale) {\n    if (!scale) {\n      var zoom = ele.cy().zoom();\n      var pxRatio = this.getPixelRatio();\n      var lvl = Math.ceil(log2(zoom * pxRatio)); // the effective texture level\n\n      scale = Math.pow(2, lvl);\n    }\n\n    var computedSize = ele.pstyle('font-size').pfValue * scale;\n    var minSize = ele.pstyle('min-zoomed-font-size').pfValue;\n\n    if (computedSize < minSize) {\n      return false;\n    }\n\n    return true;\n  };\n\n  CRp$6.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {\n    var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n    var r = this;\n\n    if (force == null) {\n      if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {\n        return;\n      }\n    } else if (force === false) {\n      return;\n    }\n\n    if (ele.isNode()) {\n      var label = ele.pstyle('label');\n\n      if (!label || !label.value) {\n        return;\n      }\n\n      var justification = r.getLabelJustification(ele);\n      context.textAlign = justification;\n      context.textBaseline = 'bottom';\n    } else {\n      var badLine = ele.element()._private.rscratch.badLine;\n\n      var _label = ele.pstyle('label');\n\n      var srcLabel = ele.pstyle('source-label');\n      var tgtLabel = ele.pstyle('target-label');\n\n      if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {\n        return;\n      }\n\n      context.textAlign = 'center';\n      context.textBaseline = 'bottom';\n    }\n\n    var applyRotation = !shiftToOriginWithBb;\n    var bb;\n\n    if (shiftToOriginWithBb) {\n      bb = shiftToOriginWithBb;\n      context.translate(-bb.x1, -bb.y1);\n    }\n\n    if (prefix == null) {\n      r.drawText(context, ele, null, applyRotation, useEleOpacity);\n\n      if (ele.isEdge()) {\n        r.drawText(context, ele, 'source', applyRotation, useEleOpacity);\n        r.drawText(context, ele, 'target', applyRotation, useEleOpacity);\n      }\n    } else {\n      r.drawText(context, ele, prefix, applyRotation, useEleOpacity);\n    }\n\n    if (shiftToOriginWithBb) {\n      context.translate(bb.x1, bb.y1);\n    }\n  };\n\n  CRp$6.getFontCache = function (context) {\n    var cache;\n    this.fontCaches = this.fontCaches || [];\n\n    for (var i = 0; i < this.fontCaches.length; i++) {\n      cache = this.fontCaches[i];\n\n      if (cache.context === context) {\n        return cache;\n      }\n    }\n\n    cache = {\n      context: context\n    };\n    this.fontCaches.push(cache);\n    return cache;\n  }; // set up canvas context with font\n  // returns transformed text string\n\n\n  CRp$6.setupTextStyle = function (context, ele) {\n    var useEleOpacity = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n    // Font style\n    var labelStyle = ele.pstyle('font-style').strValue;\n    var labelSize = ele.pstyle('font-size').pfValue + 'px';\n    var labelFamily = ele.pstyle('font-family').strValue;\n    var labelWeight = ele.pstyle('font-weight').strValue;\n    var opacity = useEleOpacity ? ele.effectiveOpacity() * ele.pstyle('text-opacity').value : 1;\n    var outlineOpacity = ele.pstyle('text-outline-opacity').value * opacity;\n    var color = ele.pstyle('color').value;\n    var outlineColor = ele.pstyle('text-outline-color').value;\n    context.font = labelStyle + ' ' + labelWeight + ' ' + labelSize + ' ' + labelFamily;\n    context.lineJoin = 'round'; // so text outlines aren't jagged\n\n    this.colorFillStyle(context, color[0], color[1], color[2], opacity);\n    this.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], outlineOpacity);\n  }; // TODO ensure re-used\n\n\n  function roundRect(ctx, x, y, width, height) {\n    var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;\n    ctx.beginPath();\n    ctx.moveTo(x + radius, y);\n    ctx.lineTo(x + width - radius, y);\n    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);\n    ctx.lineTo(x + width, y + height - radius);\n    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);\n    ctx.lineTo(x + radius, y + height);\n    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);\n    ctx.lineTo(x, y + radius);\n    ctx.quadraticCurveTo(x, y, x + radius, y);\n    ctx.closePath();\n    ctx.fill();\n  }\n\n  CRp$6.getTextAngle = function (ele, prefix) {\n    var theta;\n    var _p = ele._private;\n    var rscratch = _p.rscratch;\n    var pdash = prefix ? prefix + '-' : '';\n    var rotation = ele.pstyle(pdash + 'text-rotation');\n    var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);\n\n    if (rotation.strValue === 'autorotate') {\n      theta = ele.isEdge() ? textAngle : 0;\n    } else if (rotation.strValue === 'none') {\n      theta = 0;\n    } else {\n      theta = rotation.pfValue;\n    }\n\n    return theta;\n  };\n\n  CRp$6.drawText = function (context, ele, prefix) {\n    var applyRotation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n    var useEleOpacity = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    var _p = ele._private;\n    var rscratch = _p.rscratch;\n    var parentOpacity = useEleOpacity ? ele.effectiveOpacity() : 1;\n\n    if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {\n      return;\n    } // use 'main' as an alias for the main label (i.e. null prefix)\n\n\n    if (prefix === 'main') {\n      prefix = null;\n    }\n\n    var textX = getPrefixedProperty(rscratch, 'labelX', prefix);\n    var textY = getPrefixedProperty(rscratch, 'labelY', prefix);\n    var orgTextX, orgTextY; // used for rotation\n\n    var text = this.getLabelText(ele, prefix);\n\n    if (text != null && text !== '' && !isNaN(textX) && !isNaN(textY)) {\n      this.setupTextStyle(context, ele, useEleOpacity);\n      var pdash = prefix ? prefix + '-' : '';\n      var textW = getPrefixedProperty(rscratch, 'labelWidth', prefix);\n      var textH = getPrefixedProperty(rscratch, 'labelHeight', prefix);\n      var marginX = ele.pstyle(pdash + 'text-margin-x').pfValue;\n      var marginY = ele.pstyle(pdash + 'text-margin-y').pfValue;\n      var isEdge = ele.isEdge();\n      var halign = ele.pstyle('text-halign').value;\n      var valign = ele.pstyle('text-valign').value;\n\n      if (isEdge) {\n        halign = 'center';\n        valign = 'center';\n      }\n\n      textX += marginX;\n      textY += marginY;\n      var theta;\n\n      if (!applyRotation) {\n        theta = 0;\n      } else {\n        theta = this.getTextAngle(ele, prefix);\n      }\n\n      if (theta !== 0) {\n        orgTextX = textX;\n        orgTextY = textY;\n        context.translate(orgTextX, orgTextY);\n        context.rotate(theta);\n        textX = 0;\n        textY = 0;\n      }\n\n      switch (valign) {\n        case 'top':\n          break;\n\n        case 'center':\n          textY += textH / 2;\n          break;\n\n        case 'bottom':\n          textY += textH;\n          break;\n      }\n\n      var backgroundOpacity = ele.pstyle('text-background-opacity').value;\n      var borderOpacity = ele.pstyle('text-border-opacity').value;\n      var textBorderWidth = ele.pstyle('text-border-width').pfValue;\n      var backgroundPadding = ele.pstyle('text-background-padding').pfValue;\n\n      if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {\n        var bgX = textX - backgroundPadding;\n\n        switch (halign) {\n          case 'left':\n            bgX -= textW;\n            break;\n\n          case 'center':\n            bgX -= textW / 2;\n            break;\n        }\n\n        var bgY = textY - textH - backgroundPadding;\n        var bgW = textW + 2 * backgroundPadding;\n        var bgH = textH + 2 * backgroundPadding;\n\n        if (backgroundOpacity > 0) {\n          var textFill = context.fillStyle;\n          var textBackgroundColor = ele.pstyle('text-background-color').value;\n          context.fillStyle = 'rgba(' + textBackgroundColor[0] + ',' + textBackgroundColor[1] + ',' + textBackgroundColor[2] + ',' + backgroundOpacity * parentOpacity + ')';\n          var styleShape = ele.pstyle('text-background-shape').strValue;\n\n          if (styleShape.indexOf('round') === 0) {\n            roundRect(context, bgX, bgY, bgW, bgH, 2);\n          } else {\n            context.fillRect(bgX, bgY, bgW, bgH);\n          }\n\n          context.fillStyle = textFill;\n        }\n\n        if (textBorderWidth > 0 && borderOpacity > 0) {\n          var textStroke = context.strokeStyle;\n          var textLineWidth = context.lineWidth;\n          var textBorderColor = ele.pstyle('text-border-color').value;\n          var textBorderStyle = ele.pstyle('text-border-style').value;\n          context.strokeStyle = 'rgba(' + textBorderColor[0] + ',' + textBorderColor[1] + ',' + textBorderColor[2] + ',' + borderOpacity * parentOpacity + ')';\n          context.lineWidth = textBorderWidth;\n\n          if (context.setLineDash) {\n            // for very outofdate browsers\n            switch (textBorderStyle) {\n              case 'dotted':\n                context.setLineDash([1, 1]);\n                break;\n\n              case 'dashed':\n                context.setLineDash([4, 2]);\n                break;\n\n              case 'double':\n                context.lineWidth = textBorderWidth / 4; // 50% reserved for white between the two borders\n\n                context.setLineDash([]);\n                break;\n\n              case 'solid':\n                context.setLineDash([]);\n                break;\n            }\n          }\n\n          context.strokeRect(bgX, bgY, bgW, bgH);\n\n          if (textBorderStyle === 'double') {\n            var whiteWidth = textBorderWidth / 2;\n            context.strokeRect(bgX + whiteWidth, bgY + whiteWidth, bgW - whiteWidth * 2, bgH - whiteWidth * 2);\n          }\n\n          if (context.setLineDash) {\n            // for very outofdate browsers\n            context.setLineDash([]);\n          }\n\n          context.lineWidth = textLineWidth;\n          context.strokeStyle = textStroke;\n        }\n      }\n\n      var lineWidth = 2 * ele.pstyle('text-outline-width').pfValue; // *2 b/c the stroke is drawn centred on the middle\n\n      if (lineWidth > 0) {\n        context.lineWidth = lineWidth;\n      }\n\n      if (ele.pstyle('text-wrap').value === 'wrap') {\n        var lines = getPrefixedProperty(rscratch, 'labelWrapCachedLines', prefix);\n        var lineHeight = getPrefixedProperty(rscratch, 'labelLineHeight', prefix);\n        var halfTextW = textW / 2;\n        var justification = this.getLabelJustification(ele);\n\n        if (justification === 'auto') ; else if (halign === 'left') {\n          // auto justification : right\n          if (justification === 'left') {\n            textX += -textW;\n          } else if (justification === 'center') {\n            textX += -halfTextW;\n          } // else same as auto\n\n        } else if (halign === 'center') {\n          // auto justfication : center\n          if (justification === 'left') {\n            textX += -halfTextW;\n          } else if (justification === 'right') {\n            textX += halfTextW;\n          } // else same as auto\n\n        } else if (halign === 'right') {\n          // auto justification : left\n          if (justification === 'center') {\n            textX += halfTextW;\n          } else if (justification === 'right') {\n            textX += textW;\n          } // else same as auto\n\n        }\n\n        switch (valign) {\n          case 'top':\n            textY -= (lines.length - 1) * lineHeight;\n            break;\n\n          case 'center':\n          case 'bottom':\n            textY -= (lines.length - 1) * lineHeight;\n            break;\n        }\n\n        for (var l = 0; l < lines.length; l++) {\n          if (lineWidth > 0) {\n            context.strokeText(lines[l], textX, textY);\n          }\n\n          context.fillText(lines[l], textX, textY);\n          textY += lineHeight;\n        }\n      } else {\n        if (lineWidth > 0) {\n          context.strokeText(text, textX, textY);\n        }\n\n        context.fillText(text, textX, textY);\n      }\n\n      if (theta !== 0) {\n        context.rotate(-theta);\n        context.translate(-orgTextX, -orgTextY);\n      }\n    }\n  };\n\n  /* global Path2D */\n  var CRp$5 = {};\n\n  CRp$5.drawNode = function (context, node, shiftToOriginWithBb) {\n    var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;\n    var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n    var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n    var r = this;\n    var nodeWidth, nodeHeight;\n    var _p = node._private;\n    var rs = _p.rscratch;\n    var pos = node.position();\n\n    if (!number$1(pos.x) || !number$1(pos.y)) {\n      return; // can't draw node with undefined position\n    }\n\n    if (shouldDrawOpacity && !node.visible()) {\n      return;\n    }\n\n    var eleOpacity = shouldDrawOpacity ? node.effectiveOpacity() : 1;\n    var usePaths = r.usePaths();\n    var path;\n    var pathCacheHit = false;\n    var padding = node.padding();\n    nodeWidth = node.width() + 2 * padding;\n    nodeHeight = node.height() + 2 * padding; //\n    // setup shift\n\n    var bb;\n\n    if (shiftToOriginWithBb) {\n      bb = shiftToOriginWithBb;\n      context.translate(-bb.x1, -bb.y1);\n    } //\n    // load bg image\n\n\n    var bgImgProp = node.pstyle('background-image');\n    var urls = bgImgProp.value;\n    var urlDefined = new Array(urls.length);\n    var image = new Array(urls.length);\n    var numImages = 0;\n\n    for (var i = 0; i < urls.length; i++) {\n      var url = urls[i];\n      var defd = urlDefined[i] = url != null && url !== 'none';\n\n      if (defd) {\n        var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);\n        numImages++; // get image, and if not loaded then ask to redraw when later loaded\n\n        image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {\n          _p.backgroundTimestamp = Date.now();\n          node.emitAndNotify('background');\n        });\n      }\n    } //\n    // setup styles\n\n\n    var darkness = node.pstyle('background-blacken').value;\n    var borderWidth = node.pstyle('border-width').pfValue;\n    var bgOpacity = node.pstyle('background-opacity').value * eleOpacity;\n    var borderColor = node.pstyle('border-color').value;\n    var borderStyle = node.pstyle('border-style').value;\n    var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;\n    context.lineJoin = 'miter'; // so borders are square with the node shape\n\n    var setupShapeColor = function setupShapeColor() {\n      var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;\n      r.eleFillStyle(context, node, bgOpy);\n    };\n\n    var setupBorderColor = function setupBorderColor() {\n      var bdrOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : borderOpacity;\n      r.colorStrokeStyle(context, borderColor[0], borderColor[1], borderColor[2], bdrOpy);\n    }; //\n    // setup shape\n\n\n    var styleShape = node.pstyle('shape').strValue;\n    var shapePts = node.pstyle('shape-polygon-points').pfValue;\n\n    if (usePaths) {\n      context.translate(pos.x, pos.y);\n      var pathCache = r.nodePathCache = r.nodePathCache || [];\n      var key = hashStrings(styleShape === 'polygon' ? styleShape + ',' + shapePts.join(',') : styleShape, '' + nodeHeight, '' + nodeWidth);\n      var cachedPath = pathCache[key];\n\n      if (cachedPath != null) {\n        path = cachedPath;\n        pathCacheHit = true;\n        rs.pathCache = path;\n      } else {\n        path = new Path2D();\n        pathCache[key] = rs.pathCache = path;\n      }\n    }\n\n    var drawShape = function drawShape() {\n      if (!pathCacheHit) {\n        var npos = pos;\n\n        if (usePaths) {\n          npos = {\n            x: 0,\n            y: 0\n          };\n        }\n\n        r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight);\n      }\n\n      if (usePaths) {\n        context.fill(path);\n      } else {\n        context.fill();\n      }\n    };\n\n    var drawImages = function drawImages() {\n      var nodeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;\n      var inside = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n      var prevBging = _p.backgrounding;\n      var totalCompleted = 0;\n\n      for (var _i = 0; _i < image.length; _i++) {\n        var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);\n\n        if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {\n          totalCompleted++;\n          continue;\n        }\n\n        if (urlDefined[_i] && image[_i].complete && !image[_i].error) {\n          totalCompleted++;\n          r.drawInscribedImage(context, image[_i], node, _i, nodeOpacity);\n        }\n      }\n\n      _p.backgrounding = !(totalCompleted === numImages);\n\n      if (prevBging !== _p.backgrounding) {\n        // update style b/c :backgrounding state changed\n        node.updateStyle(false);\n      }\n    };\n\n    var drawPie = function drawPie() {\n      var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n      var pieOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;\n\n      if (r.hasPie(node)) {\n        r.drawPie(context, node, pieOpacity); // redraw/restore path if steps after pie need it\n\n        if (redrawShape) {\n          if (!usePaths) {\n            r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight);\n          }\n        }\n      }\n    };\n\n    var darken = function darken() {\n      var darkenOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;\n      var opacity = (darkness > 0 ? darkness : -darkness) * darkenOpacity;\n      var c = darkness > 0 ? 0 : 255;\n\n      if (darkness !== 0) {\n        r.colorFillStyle(context, c, c, c, opacity);\n\n        if (usePaths) {\n          context.fill(path);\n        } else {\n          context.fill();\n        }\n      }\n    };\n\n    var drawBorder = function drawBorder() {\n      if (borderWidth > 0) {\n        context.lineWidth = borderWidth;\n        context.lineCap = 'butt';\n\n        if (context.setLineDash) {\n          // for very outofdate browsers\n          switch (borderStyle) {\n            case 'dotted':\n              context.setLineDash([1, 1]);\n              break;\n\n            case 'dashed':\n              context.setLineDash([4, 2]);\n              break;\n\n            case 'solid':\n            case 'double':\n              context.setLineDash([]);\n              break;\n          }\n        }\n\n        if (usePaths) {\n          context.stroke(path);\n        } else {\n          context.stroke();\n        }\n\n        if (borderStyle === 'double') {\n          context.lineWidth = borderWidth / 3;\n          var gco = context.globalCompositeOperation;\n          context.globalCompositeOperation = 'destination-out';\n\n          if (usePaths) {\n            context.stroke(path);\n          } else {\n            context.stroke();\n          }\n\n          context.globalCompositeOperation = gco;\n        } // reset in case we changed the border style\n\n\n        if (context.setLineDash) {\n          // for very outofdate browsers\n          context.setLineDash([]);\n        }\n      }\n    };\n\n    var drawOverlay = function drawOverlay() {\n      if (shouldDrawOverlay) {\n        r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);\n      }\n    };\n\n    var drawUnderlay = function drawUnderlay() {\n      if (shouldDrawOverlay) {\n        r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);\n      }\n    };\n\n    var drawText = function drawText() {\n      r.drawElementText(context, node, null, drawLabel);\n    };\n\n    var ghost = node.pstyle('ghost').value === 'yes';\n\n    if (ghost) {\n      var gx = node.pstyle('ghost-offset-x').pfValue;\n      var gy = node.pstyle('ghost-offset-y').pfValue;\n      var ghostOpacity = node.pstyle('ghost-opacity').value;\n      var effGhostOpacity = ghostOpacity * eleOpacity;\n      context.translate(gx, gy);\n      setupShapeColor(ghostOpacity * bgOpacity);\n      drawShape();\n      drawImages(effGhostOpacity, true);\n      setupBorderColor(ghostOpacity * borderOpacity);\n      drawBorder();\n      drawPie(darkness !== 0 || borderWidth !== 0);\n      drawImages(effGhostOpacity, false);\n      darken(effGhostOpacity);\n      context.translate(-gx, -gy);\n    }\n\n    if (usePaths) {\n      context.translate(-pos.x, -pos.y);\n    }\n\n    drawUnderlay();\n\n    if (usePaths) {\n      context.translate(pos.x, pos.y);\n    }\n\n    setupShapeColor();\n    drawShape();\n    drawImages(eleOpacity, true);\n    setupBorderColor();\n    drawBorder();\n    drawPie(darkness !== 0 || borderWidth !== 0);\n    drawImages(eleOpacity, false);\n    darken();\n\n    if (usePaths) {\n      context.translate(-pos.x, -pos.y);\n    }\n\n    drawText();\n    drawOverlay(); //\n    // clean up shift\n\n    if (shiftToOriginWithBb) {\n      context.translate(bb.x1, bb.y1);\n    }\n  };\n\n  var drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {\n    if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {\n      throw new Error('Invalid state');\n    }\n\n    return function (context, node, pos, nodeWidth, nodeHeight) {\n      var r = this;\n\n      if (!node.visible()) {\n        return;\n      }\n\n      var padding = node.pstyle(\"\".concat(overlayOrUnderlay, \"-padding\")).pfValue;\n      var opacity = node.pstyle(\"\".concat(overlayOrUnderlay, \"-opacity\")).value;\n      var color = node.pstyle(\"\".concat(overlayOrUnderlay, \"-color\")).value;\n      var shape = node.pstyle(\"\".concat(overlayOrUnderlay, \"-shape\")).value;\n\n      if (opacity > 0) {\n        pos = pos || node.position();\n\n        if (nodeWidth == null || nodeHeight == null) {\n          var _padding = node.padding();\n\n          nodeWidth = node.width() + 2 * _padding;\n          nodeHeight = node.height() + 2 * _padding;\n        }\n\n        r.colorFillStyle(context, color[0], color[1], color[2], opacity);\n        r.nodeShapes[shape].draw(context, pos.x, pos.y, nodeWidth + padding * 2, nodeHeight + padding * 2);\n        context.fill();\n      }\n    };\n  };\n\n  CRp$5.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');\n  CRp$5.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay'); // does the node have at least one pie piece?\n\n  CRp$5.hasPie = function (node) {\n    node = node[0]; // ensure ele ref\n\n    return node._private.hasPie;\n  };\n\n  CRp$5.drawPie = function (context, node, nodeOpacity, pos) {\n    node = node[0]; // ensure ele ref\n\n    pos = pos || node.position();\n    var cyStyle = node.cy().style();\n    var pieSize = node.pstyle('pie-size');\n    var x = pos.x;\n    var y = pos.y;\n    var nodeW = node.width();\n    var nodeH = node.height();\n    var radius = Math.min(nodeW, nodeH) / 2; // must fit in node\n\n    var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]\n\n    var usePaths = this.usePaths();\n\n    if (usePaths) {\n      x = 0;\n      y = 0;\n    }\n\n    if (pieSize.units === '%') {\n      radius = radius * pieSize.pfValue;\n    } else if (pieSize.pfValue !== undefined) {\n      radius = pieSize.pfValue / 2;\n    }\n\n    for (var i = 1; i <= cyStyle.pieBackgroundN; i++) {\n      // 1..N\n      var size = node.pstyle('pie-' + i + '-background-size').value;\n      var color = node.pstyle('pie-' + i + '-background-color').value;\n      var opacity = node.pstyle('pie-' + i + '-background-opacity').value * nodeOpacity;\n      var percent = size / 100; // map integer range [0, 100] to [0, 1]\n      // percent can't push beyond 1\n\n      if (percent + lastPercent > 1) {\n        percent = 1 - lastPercent;\n      }\n\n      var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise\n\n      var angleDelta = 2 * Math.PI * percent;\n      var angleEnd = angleStart + angleDelta; // ignore if\n      // - zero size\n      // - we're already beyond the full circle\n      // - adding the current slice would go beyond the full circle\n\n      if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {\n        continue;\n      }\n\n      context.beginPath();\n      context.moveTo(x, y);\n      context.arc(x, y, radius, angleStart, angleEnd);\n      context.closePath();\n      this.colorFillStyle(context, color[0], color[1], color[2], opacity);\n      context.fill();\n      lastPercent += percent;\n    }\n  };\n\n  var CRp$4 = {};\n  var motionBlurDelay = 100; // var isFirefox = typeof InstallTrigger !== 'undefined';\n\n  CRp$4.getPixelRatio = function () {\n    var context = this.data.contexts[0];\n\n    if (this.forcedPixelRatio != null) {\n      return this.forcedPixelRatio;\n    }\n\n    var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;\n    return (window.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef\n  };\n\n  CRp$4.paintCache = function (context) {\n    var caches = this.paintCaches = this.paintCaches || [];\n    var needToCreateCache = true;\n    var cache;\n\n    for (var i = 0; i < caches.length; i++) {\n      cache = caches[i];\n\n      if (cache.context === context) {\n        needToCreateCache = false;\n        break;\n      }\n    }\n\n    if (needToCreateCache) {\n      cache = {\n        context: context\n      };\n      caches.push(cache);\n    }\n\n    return cache;\n  };\n\n  CRp$4.createGradientStyleFor = function (context, shapeStyleName, ele, fill, opacity) {\n    var gradientStyle;\n    var usePaths = this.usePaths();\n    var colors = ele.pstyle(shapeStyleName + '-gradient-stop-colors').value,\n        positions = ele.pstyle(shapeStyleName + '-gradient-stop-positions').pfValue;\n\n    if (fill === 'radial-gradient') {\n      if (ele.isEdge()) {\n        var start = ele.sourceEndpoint(),\n            end = ele.targetEndpoint(),\n            mid = ele.midpoint();\n        var d1 = dist(start, mid);\n        var d2 = dist(end, mid);\n        gradientStyle = context.createRadialGradient(mid.x, mid.y, 0, mid.x, mid.y, Math.max(d1, d2));\n      } else {\n        var pos = usePaths ? {\n          x: 0,\n          y: 0\n        } : ele.position(),\n            width = ele.paddedWidth(),\n            height = ele.paddedHeight();\n        gradientStyle = context.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, Math.max(width, height));\n      }\n    } else {\n      if (ele.isEdge()) {\n        var _start = ele.sourceEndpoint(),\n            _end = ele.targetEndpoint();\n\n        gradientStyle = context.createLinearGradient(_start.x, _start.y, _end.x, _end.y);\n      } else {\n        var _pos = usePaths ? {\n          x: 0,\n          y: 0\n        } : ele.position(),\n            _width = ele.paddedWidth(),\n            _height = ele.paddedHeight(),\n            halfWidth = _width / 2,\n            halfHeight = _height / 2;\n\n        var direction = ele.pstyle('background-gradient-direction').value;\n\n        switch (direction) {\n          case 'to-bottom':\n            gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);\n            break;\n\n          case 'to-top':\n            gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);\n            break;\n\n          case 'to-left':\n            gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);\n            break;\n\n          case 'to-right':\n            gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);\n            break;\n\n          case 'to-bottom-right':\n          case 'to-right-bottom':\n            gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y - halfHeight, _pos.x + halfWidth, _pos.y + halfHeight);\n            break;\n\n          case 'to-top-right':\n          case 'to-right-top':\n            gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y + halfHeight, _pos.x + halfWidth, _pos.y - halfHeight);\n            break;\n\n          case 'to-bottom-left':\n          case 'to-left-bottom':\n            gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y - halfHeight, _pos.x - halfWidth, _pos.y + halfHeight);\n            break;\n\n          case 'to-top-left':\n          case 'to-left-top':\n            gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y + halfHeight, _pos.x - halfWidth, _pos.y - halfHeight);\n            break;\n        }\n      }\n    }\n\n    if (!gradientStyle) return null; // invalid gradient style\n\n    var hasPositions = positions.length === colors.length;\n    var length = colors.length;\n\n    for (var i = 0; i < length; i++) {\n      gradientStyle.addColorStop(hasPositions ? positions[i] : i / (length - 1), 'rgba(' + colors[i][0] + ',' + colors[i][1] + ',' + colors[i][2] + ',' + opacity + ')');\n    }\n\n    return gradientStyle;\n  };\n\n  CRp$4.gradientFillStyle = function (context, ele, fill, opacity) {\n    var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);\n    if (!gradientStyle) return null; // error\n\n    context.fillStyle = gradientStyle;\n  };\n\n  CRp$4.colorFillStyle = function (context, r, g, b, a) {\n    context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; // turn off for now, seems context does its own caching\n    // var cache = this.paintCache(context);\n    // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n    // if( cache.fillStyle !== fillStyle ){\n    //   context.fillStyle = cache.fillStyle = fillStyle;\n    // }\n  };\n\n  CRp$4.eleFillStyle = function (context, ele, opacity) {\n    var backgroundFill = ele.pstyle('background-fill').value;\n\n    if (backgroundFill === 'linear-gradient' || backgroundFill === 'radial-gradient') {\n      this.gradientFillStyle(context, ele, backgroundFill, opacity);\n    } else {\n      var backgroundColor = ele.pstyle('background-color').value;\n      this.colorFillStyle(context, backgroundColor[0], backgroundColor[1], backgroundColor[2], opacity);\n    }\n  };\n\n  CRp$4.gradientStrokeStyle = function (context, ele, fill, opacity) {\n    var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);\n    if (!gradientStyle) return null; // error\n\n    context.strokeStyle = gradientStyle;\n  };\n\n  CRp$4.colorStrokeStyle = function (context, r, g, b, a) {\n    context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; // turn off for now, seems context does its own caching\n    // var cache = this.paintCache(context);\n    // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n    // if( cache.strokeStyle !== strokeStyle ){\n    //   context.strokeStyle = cache.strokeStyle = strokeStyle;\n    // }\n  };\n\n  CRp$4.eleStrokeStyle = function (context, ele, opacity) {\n    var lineFill = ele.pstyle('line-fill').value;\n\n    if (lineFill === 'linear-gradient' || lineFill === 'radial-gradient') {\n      this.gradientStrokeStyle(context, ele, lineFill, opacity);\n    } else {\n      var lineColor = ele.pstyle('line-color').value;\n      this.colorStrokeStyle(context, lineColor[0], lineColor[1], lineColor[2], opacity);\n    }\n  }; // Resize canvas\n\n\n  CRp$4.matchCanvasSize = function (container) {\n    var r = this;\n    var data = r.data;\n    var bb = r.findContainerClientCoords();\n    var width = bb[2];\n    var height = bb[3];\n    var pixelRatio = r.getPixelRatio();\n    var mbPxRatio = r.motionBlurPxRatio;\n\n    if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {\n      pixelRatio = mbPxRatio;\n    }\n\n    var canvasWidth = width * pixelRatio;\n    var canvasHeight = height * pixelRatio;\n    var canvas;\n\n    if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {\n      return; // save cycles if same\n    }\n\n    r.fontCaches = null; // resizing resets the style\n\n    var canvasContainer = data.canvasContainer;\n    canvasContainer.style.width = width + 'px';\n    canvasContainer.style.height = height + 'px';\n\n    for (var i = 0; i < r.CANVAS_LAYERS; i++) {\n      canvas = data.canvases[i];\n      canvas.width = canvasWidth;\n      canvas.height = canvasHeight;\n      canvas.style.width = width + 'px';\n      canvas.style.height = height + 'px';\n    }\n\n    for (var i = 0; i < r.BUFFER_COUNT; i++) {\n      canvas = data.bufferCanvases[i];\n      canvas.width = canvasWidth;\n      canvas.height = canvasHeight;\n      canvas.style.width = width + 'px';\n      canvas.style.height = height + 'px';\n    }\n\n    r.textureMult = 1;\n\n    if (pixelRatio <= 1) {\n      canvas = data.bufferCanvases[r.TEXTURE_BUFFER];\n      r.textureMult = 2;\n      canvas.width = canvasWidth * r.textureMult;\n      canvas.height = canvasHeight * r.textureMult;\n    }\n\n    r.canvasWidth = canvasWidth;\n    r.canvasHeight = canvasHeight;\n  };\n\n  CRp$4.renderTo = function (cxt, zoom, pan, pxRatio) {\n    this.render({\n      forcedContext: cxt,\n      forcedZoom: zoom,\n      forcedPan: pan,\n      drawAllLayers: true,\n      forcedPxRatio: pxRatio\n    });\n  };\n\n  CRp$4.render = function (options) {\n    options = options || staticEmptyObject();\n    var forcedContext = options.forcedContext;\n    var drawAllLayers = options.drawAllLayers;\n    var drawOnlyNodeLayer = options.drawOnlyNodeLayer;\n    var forcedZoom = options.forcedZoom;\n    var forcedPan = options.forcedPan;\n    var r = this;\n    var pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;\n    var cy = r.cy;\n    var data = r.data;\n    var needDraw = data.canvasNeedsRedraw;\n    var textureDraw = r.textureOnViewport && !forcedContext && (r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming);\n    var motionBlur = options.motionBlur !== undefined ? options.motionBlur : r.motionBlur;\n    var mbPxRatio = r.motionBlurPxRatio;\n    var hasCompoundNodes = cy.hasCompoundNodes();\n    var inNodeDragGesture = r.hoverData.draggingEles;\n    var inBoxSelection = r.hoverData.selecting || r.touchData.selecting ? true : false;\n    motionBlur = motionBlur && !forcedContext && r.motionBlurEnabled && !inBoxSelection;\n    var motionBlurFadeEffect = motionBlur;\n\n    if (!forcedContext) {\n      if (r.prevPxRatio !== pixelRatio) {\n        r.invalidateContainerClientCoordsCache();\n        r.matchCanvasSize(r.container);\n        r.redrawHint('eles', true);\n        r.redrawHint('drag', true);\n      }\n\n      r.prevPxRatio = pixelRatio;\n    }\n\n    if (!forcedContext && r.motionBlurTimeout) {\n      clearTimeout(r.motionBlurTimeout);\n    }\n\n    if (motionBlur) {\n      if (r.mbFrames == null) {\n        r.mbFrames = 0;\n      }\n\n      r.mbFrames++;\n\n      if (r.mbFrames < 3) {\n        // need several frames before even high quality motionblur\n        motionBlurFadeEffect = false;\n      } // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)\n\n\n      if (r.mbFrames > r.minMbLowQualFrames) {\n        //r.fullQualityMb = false;\n        r.motionBlurPxRatio = r.mbPxRBlurry;\n      }\n    }\n\n    if (r.clearingMotionBlur) {\n      r.motionBlurPxRatio = 1;\n    } // b/c drawToContext() may be async w.r.t. redraw(), keep track of last texture frame\n    // because a rogue async texture frame would clear needDraw\n\n\n    if (r.textureDrawLastFrame && !textureDraw) {\n      needDraw[r.NODE] = true;\n      needDraw[r.SELECT_BOX] = true;\n    }\n\n    var style = cy.style();\n    var zoom = cy.zoom();\n    var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;\n    var pan = cy.pan();\n    var effectivePan = {\n      x: pan.x,\n      y: pan.y\n    };\n    var vp = {\n      zoom: zoom,\n      pan: {\n        x: pan.x,\n        y: pan.y\n      }\n    };\n    var prevVp = r.prevViewport;\n    var viewportIsDiff = prevVp === undefined || vp.zoom !== prevVp.zoom || vp.pan.x !== prevVp.pan.x || vp.pan.y !== prevVp.pan.y; // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)\n\n    if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {\n      r.motionBlurPxRatio = 1;\n    }\n\n    if (forcedPan) {\n      effectivePan = forcedPan;\n    } // apply pixel ratio\n\n\n    effectiveZoom *= pixelRatio;\n    effectivePan.x *= pixelRatio;\n    effectivePan.y *= pixelRatio;\n    var eles = r.getCachedZSortedEles();\n\n    function mbclear(context, x, y, w, h) {\n      var gco = context.globalCompositeOperation;\n      context.globalCompositeOperation = 'destination-out';\n      r.colorFillStyle(context, 255, 255, 255, r.motionBlurTransparency);\n      context.fillRect(x, y, w, h);\n      context.globalCompositeOperation = gco;\n    }\n\n    function setContextTransform(context, clear) {\n      var ePan, eZoom, w, h;\n\n      if (!r.clearingMotionBlur && (context === data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] || context === data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG])) {\n        ePan = {\n          x: pan.x * mbPxRatio,\n          y: pan.y * mbPxRatio\n        };\n        eZoom = zoom * mbPxRatio;\n        w = r.canvasWidth * mbPxRatio;\n        h = r.canvasHeight * mbPxRatio;\n      } else {\n        ePan = effectivePan;\n        eZoom = effectiveZoom;\n        w = r.canvasWidth;\n        h = r.canvasHeight;\n      }\n\n      context.setTransform(1, 0, 0, 1, 0, 0);\n\n      if (clear === 'motionBlur') {\n        mbclear(context, 0, 0, w, h);\n      } else if (!forcedContext && (clear === undefined || clear)) {\n        context.clearRect(0, 0, w, h);\n      }\n\n      if (!drawAllLayers) {\n        context.translate(ePan.x, ePan.y);\n        context.scale(eZoom, eZoom);\n      }\n\n      if (forcedPan) {\n        context.translate(forcedPan.x, forcedPan.y);\n      }\n\n      if (forcedZoom) {\n        context.scale(forcedZoom, forcedZoom);\n      }\n    }\n\n    if (!textureDraw) {\n      r.textureDrawLastFrame = false;\n    }\n\n    if (textureDraw) {\n      r.textureDrawLastFrame = true;\n\n      if (!r.textureCache) {\n        r.textureCache = {};\n        r.textureCache.bb = cy.mutableElements().boundingBox();\n        r.textureCache.texture = r.data.bufferCanvases[r.TEXTURE_BUFFER];\n        var cxt = r.data.bufferContexts[r.TEXTURE_BUFFER];\n        cxt.setTransform(1, 0, 0, 1, 0, 0);\n        cxt.clearRect(0, 0, r.canvasWidth * r.textureMult, r.canvasHeight * r.textureMult);\n        r.render({\n          forcedContext: cxt,\n          drawOnlyNodeLayer: true,\n          forcedPxRatio: pixelRatio * r.textureMult\n        });\n        var vp = r.textureCache.viewport = {\n          zoom: cy.zoom(),\n          pan: cy.pan(),\n          width: r.canvasWidth,\n          height: r.canvasHeight\n        };\n        vp.mpan = {\n          x: (0 - vp.pan.x) / vp.zoom,\n          y: (0 - vp.pan.y) / vp.zoom\n        };\n      }\n\n      needDraw[r.DRAG] = false;\n      needDraw[r.NODE] = false;\n      var context = data.contexts[r.NODE];\n      var texture = r.textureCache.texture;\n      var vp = r.textureCache.viewport;\n      context.setTransform(1, 0, 0, 1, 0, 0);\n\n      if (motionBlur) {\n        mbclear(context, 0, 0, vp.width, vp.height);\n      } else {\n        context.clearRect(0, 0, vp.width, vp.height);\n      }\n\n      var outsideBgColor = style.core('outside-texture-bg-color').value;\n      var outsideBgOpacity = style.core('outside-texture-bg-opacity').value;\n      r.colorFillStyle(context, outsideBgColor[0], outsideBgColor[1], outsideBgColor[2], outsideBgOpacity);\n      context.fillRect(0, 0, vp.width, vp.height);\n      var zoom = cy.zoom();\n      setContextTransform(context, false);\n      context.clearRect(vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);\n      context.drawImage(texture, vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);\n    } else if (r.textureOnViewport && !forcedContext) {\n      // clear the cache since we don't need it\n      r.textureCache = null;\n    }\n\n    var extent = cy.extent();\n    var vpManip = r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming || r.hoverData.draggingEles || r.cy.animated();\n    var hideEdges = r.hideEdgesOnViewport && vpManip;\n    var needMbClear = [];\n    needMbClear[r.NODE] = !needDraw[r.NODE] && motionBlur && !r.clearedForMotionBlur[r.NODE] || r.clearingMotionBlur;\n\n    if (needMbClear[r.NODE]) {\n      r.clearedForMotionBlur[r.NODE] = true;\n    }\n\n    needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;\n\n    if (needMbClear[r.DRAG]) {\n      r.clearedForMotionBlur[r.DRAG] = true;\n    }\n\n    if (needDraw[r.NODE] || drawAllLayers || drawOnlyNodeLayer || needMbClear[r.NODE]) {\n      var useBuffer = motionBlur && !needMbClear[r.NODE] && mbPxRatio !== 1;\n      var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] : data.contexts[r.NODE]);\n      var clear = motionBlur && !useBuffer ? 'motionBlur' : undefined;\n      setContextTransform(context, clear);\n\n      if (hideEdges) {\n        r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);\n      } else {\n        r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);\n      }\n\n      if (r.debug) {\n        r.drawDebugPoints(context, eles.nondrag);\n      }\n\n      if (!drawAllLayers && !motionBlur) {\n        needDraw[r.NODE] = false;\n      }\n    }\n\n    if (!drawOnlyNodeLayer && (needDraw[r.DRAG] || drawAllLayers || needMbClear[r.DRAG])) {\n      var useBuffer = motionBlur && !needMbClear[r.DRAG] && mbPxRatio !== 1;\n      var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG] : data.contexts[r.DRAG]);\n      setContextTransform(context, motionBlur && !useBuffer ? 'motionBlur' : undefined);\n\n      if (hideEdges) {\n        r.drawCachedNodes(context, eles.drag, pixelRatio, extent);\n      } else {\n        r.drawCachedElements(context, eles.drag, pixelRatio, extent);\n      }\n\n      if (r.debug) {\n        r.drawDebugPoints(context, eles.drag);\n      }\n\n      if (!drawAllLayers && !motionBlur) {\n        needDraw[r.DRAG] = false;\n      }\n    }\n\n    if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {\n      var context = forcedContext || data.contexts[r.SELECT_BOX];\n      setContextTransform(context);\n\n      if (r.selection[4] == 1 && (r.hoverData.selecting || r.touchData.selecting)) {\n        var zoom = r.cy.zoom();\n        var borderWidth = style.core('selection-box-border-width').value / zoom;\n        context.lineWidth = borderWidth;\n        context.fillStyle = 'rgba(' + style.core('selection-box-color').value[0] + ',' + style.core('selection-box-color').value[1] + ',' + style.core('selection-box-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';\n        context.fillRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);\n\n        if (borderWidth > 0) {\n          context.strokeStyle = 'rgba(' + style.core('selection-box-border-color').value[0] + ',' + style.core('selection-box-border-color').value[1] + ',' + style.core('selection-box-border-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';\n          context.strokeRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);\n        }\n      }\n\n      if (data.bgActivePosistion && !r.hoverData.selecting) {\n        var zoom = r.cy.zoom();\n        var pos = data.bgActivePosistion;\n        context.fillStyle = 'rgba(' + style.core('active-bg-color').value[0] + ',' + style.core('active-bg-color').value[1] + ',' + style.core('active-bg-color').value[2] + ',' + style.core('active-bg-opacity').value + ')';\n        context.beginPath();\n        context.arc(pos.x, pos.y, style.core('active-bg-size').pfValue / zoom, 0, 2 * Math.PI);\n        context.fill();\n      }\n\n      var timeToRender = r.lastRedrawTime;\n\n      if (r.showFps && timeToRender) {\n        timeToRender = Math.round(timeToRender);\n        var fps = Math.round(1000 / timeToRender);\n        context.setTransform(1, 0, 0, 1, 0, 0);\n        context.fillStyle = 'rgba(255, 0, 0, 0.75)';\n        context.strokeStyle = 'rgba(255, 0, 0, 0.75)';\n        context.lineWidth = 1;\n        context.fillText('1 frame = ' + timeToRender + ' ms = ' + fps + ' fps', 0, 20);\n        var maxFps = 60;\n        context.strokeRect(0, 30, 250, 20);\n        context.fillRect(0, 30, 250 * Math.min(fps / maxFps, 1), 20);\n      }\n\n      if (!drawAllLayers) {\n        needDraw[r.SELECT_BOX] = false;\n      }\n    } // motionblur: blit rendered blurry frames\n\n\n    if (motionBlur && mbPxRatio !== 1) {\n      var cxtNode = data.contexts[r.NODE];\n      var txtNode = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE];\n      var cxtDrag = data.contexts[r.DRAG];\n      var txtDrag = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG];\n\n      var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {\n        cxt.setTransform(1, 0, 0, 1, 0, 0);\n\n        if (needClear || !motionBlurFadeEffect) {\n          cxt.clearRect(0, 0, r.canvasWidth, r.canvasHeight);\n        } else {\n          mbclear(cxt, 0, 0, r.canvasWidth, r.canvasHeight);\n        }\n\n        var pxr = mbPxRatio;\n        cxt.drawImage(txt, // img\n        0, 0, // sx, sy\n        r.canvasWidth * pxr, r.canvasHeight * pxr, // sw, sh\n        0, 0, // x, y\n        r.canvasWidth, r.canvasHeight // w, h\n        );\n      };\n\n      if (needDraw[r.NODE] || needMbClear[r.NODE]) {\n        drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);\n        needDraw[r.NODE] = false;\n      }\n\n      if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {\n        drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);\n        needDraw[r.DRAG] = false;\n      }\n    }\n\n    r.prevViewport = vp;\n\n    if (r.clearingMotionBlur) {\n      r.clearingMotionBlur = false;\n      r.motionBlurCleared = true;\n      r.motionBlur = true;\n    }\n\n    if (motionBlur) {\n      r.motionBlurTimeout = setTimeout(function () {\n        r.motionBlurTimeout = null;\n        r.clearedForMotionBlur[r.NODE] = false;\n        r.clearedForMotionBlur[r.DRAG] = false;\n        r.motionBlur = false;\n        r.clearingMotionBlur = !textureDraw;\n        r.mbFrames = 0;\n        needDraw[r.NODE] = true;\n        needDraw[r.DRAG] = true;\n        r.redraw();\n      }, motionBlurDelay);\n    }\n\n    if (!forcedContext) {\n      cy.emit('render');\n    }\n  };\n\n  var CRp$3 = {}; // @O Polygon drawing\n\n  CRp$3.drawPolygonPath = function (context, x, y, width, height, points) {\n    var halfW = width / 2;\n    var halfH = height / 2;\n\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    context.moveTo(x + halfW * points[0], y + halfH * points[1]);\n\n    for (var i = 1; i < points.length / 2; i++) {\n      context.lineTo(x + halfW * points[i * 2], y + halfH * points[i * 2 + 1]);\n    }\n\n    context.closePath();\n  };\n\n  CRp$3.drawRoundPolygonPath = function (context, x, y, width, height, points) {\n    var halfW = width / 2;\n    var halfH = height / 2;\n    var cornerRadius = getRoundPolygonRadius(width, height);\n\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    for (var _i = 0; _i < points.length / 4; _i++) {\n      var sourceUv = void 0,\n          destUv = void 0;\n\n      if (_i === 0) {\n        sourceUv = points.length - 2;\n      } else {\n        sourceUv = _i * 4 - 2;\n      }\n\n      destUv = _i * 4 + 2;\n      var px = x + halfW * points[_i * 4];\n      var py = y + halfH * points[_i * 4 + 1];\n      var cosTheta = -points[sourceUv] * points[destUv] - points[sourceUv + 1] * points[destUv + 1];\n      var offset = cornerRadius / Math.tan(Math.acos(cosTheta) / 2);\n      var cp0x = px - offset * points[sourceUv];\n      var cp0y = py - offset * points[sourceUv + 1];\n      var cp1x = px + offset * points[destUv];\n      var cp1y = py + offset * points[destUv + 1];\n\n      if (_i === 0) {\n        context.moveTo(cp0x, cp0y);\n      } else {\n        context.lineTo(cp0x, cp0y);\n      }\n\n      context.arcTo(px, py, cp1x, cp1y, cornerRadius);\n    }\n\n    context.closePath();\n  }; // Round rectangle drawing\n\n\n  CRp$3.drawRoundRectanglePath = function (context, x, y, width, height) {\n    var halfWidth = width / 2;\n    var halfHeight = height / 2;\n    var cornerRadius = getRoundRectangleRadius(width, height);\n\n    if (context.beginPath) {\n      context.beginPath();\n    } // Start at top middle\n\n\n    context.moveTo(x, y - halfHeight); // Arc from middle top to right side\n\n    context.arcTo(x + halfWidth, y - halfHeight, x + halfWidth, y, cornerRadius); // Arc from right side to bottom\n\n    context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius); // Arc from bottom to left side\n\n    context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius); // Arc from left side to topBorder\n\n    context.arcTo(x - halfWidth, y - halfHeight, x, y - halfHeight, cornerRadius); // Join line\n\n    context.lineTo(x, y - halfHeight);\n    context.closePath();\n  };\n\n  CRp$3.drawBottomRoundRectanglePath = function (context, x, y, width, height) {\n    var halfWidth = width / 2;\n    var halfHeight = height / 2;\n    var cornerRadius = getRoundRectangleRadius(width, height);\n\n    if (context.beginPath) {\n      context.beginPath();\n    } // Start at top middle\n\n\n    context.moveTo(x, y - halfHeight);\n    context.lineTo(x + halfWidth, y - halfHeight);\n    context.lineTo(x + halfWidth, y);\n    context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);\n    context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);\n    context.lineTo(x - halfWidth, y - halfHeight);\n    context.lineTo(x, y - halfHeight);\n    context.closePath();\n  };\n\n  CRp$3.drawCutRectanglePath = function (context, x, y, width, height) {\n    var halfWidth = width / 2;\n    var halfHeight = height / 2;\n    var cornerLength = getCutRectangleCornerLength();\n\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    context.moveTo(x - halfWidth + cornerLength, y - halfHeight);\n    context.lineTo(x + halfWidth - cornerLength, y - halfHeight);\n    context.lineTo(x + halfWidth, y - halfHeight + cornerLength);\n    context.lineTo(x + halfWidth, y + halfHeight - cornerLength);\n    context.lineTo(x + halfWidth - cornerLength, y + halfHeight);\n    context.lineTo(x - halfWidth + cornerLength, y + halfHeight);\n    context.lineTo(x - halfWidth, y + halfHeight - cornerLength);\n    context.lineTo(x - halfWidth, y - halfHeight + cornerLength);\n    context.closePath();\n  };\n\n  CRp$3.drawBarrelPath = function (context, x, y, width, height) {\n    var halfWidth = width / 2;\n    var halfHeight = height / 2;\n    var xBegin = x - halfWidth;\n    var xEnd = x + halfWidth;\n    var yBegin = y - halfHeight;\n    var yEnd = y + halfHeight;\n    var barrelCurveConstants = getBarrelCurveConstants(width, height);\n    var wOffset = barrelCurveConstants.widthOffset;\n    var hOffset = barrelCurveConstants.heightOffset;\n    var ctrlPtXOffset = barrelCurveConstants.ctrlPtOffsetPct * wOffset;\n\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    context.moveTo(xBegin, yBegin + hOffset);\n    context.lineTo(xBegin, yEnd - hOffset);\n    context.quadraticCurveTo(xBegin + ctrlPtXOffset, yEnd, xBegin + wOffset, yEnd);\n    context.lineTo(xEnd - wOffset, yEnd);\n    context.quadraticCurveTo(xEnd - ctrlPtXOffset, yEnd, xEnd, yEnd - hOffset);\n    context.lineTo(xEnd, yBegin + hOffset);\n    context.quadraticCurveTo(xEnd - ctrlPtXOffset, yBegin, xEnd - wOffset, yBegin);\n    context.lineTo(xBegin + wOffset, yBegin);\n    context.quadraticCurveTo(xBegin + ctrlPtXOffset, yBegin, xBegin, yBegin + hOffset);\n    context.closePath();\n  };\n\n  var sin0 = Math.sin(0);\n  var cos0 = Math.cos(0);\n  var sin = {};\n  var cos = {};\n  var ellipseStepSize = Math.PI / 40;\n\n  for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {\n    sin[i] = Math.sin(i);\n    cos[i] = Math.cos(i);\n  }\n\n  CRp$3.drawEllipsePath = function (context, centerX, centerY, width, height) {\n    if (context.beginPath) {\n      context.beginPath();\n    }\n\n    if (context.ellipse) {\n      context.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, 2 * Math.PI);\n    } else {\n      var xPos, yPos;\n      var rw = width / 2;\n      var rh = height / 2;\n\n      for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {\n        xPos = centerX - rw * sin[i] * sin0 + rw * cos[i] * cos0;\n        yPos = centerY + rh * cos[i] * sin0 + rh * sin[i] * cos0;\n\n        if (i === 0) {\n          context.moveTo(xPos, yPos);\n        } else {\n          context.lineTo(xPos, yPos);\n        }\n      }\n    }\n\n    context.closePath();\n  };\n\n  /* global atob, ArrayBuffer, Uint8Array, Blob */\n  var CRp$2 = {};\n\n  CRp$2.createBuffer = function (w, h) {\n    var buffer = document.createElement('canvas'); // eslint-disable-line no-undef\n\n    buffer.width = w;\n    buffer.height = h;\n    return [buffer, buffer.getContext('2d')];\n  };\n\n  CRp$2.bufferCanvasImage = function (options) {\n    var cy = this.cy;\n    var eles = cy.mutableElements();\n    var bb = eles.boundingBox();\n    var ctrRect = this.findContainerClientCoords();\n    var width = options.full ? Math.ceil(bb.w) : ctrRect[2];\n    var height = options.full ? Math.ceil(bb.h) : ctrRect[3];\n    var specdMaxDims = number$1(options.maxWidth) || number$1(options.maxHeight);\n    var pxRatio = this.getPixelRatio();\n    var scale = 1;\n\n    if (options.scale !== undefined) {\n      width *= options.scale;\n      height *= options.scale;\n      scale = options.scale;\n    } else if (specdMaxDims) {\n      var maxScaleW = Infinity;\n      var maxScaleH = Infinity;\n\n      if (number$1(options.maxWidth)) {\n        maxScaleW = scale * options.maxWidth / width;\n      }\n\n      if (number$1(options.maxHeight)) {\n        maxScaleH = scale * options.maxHeight / height;\n      }\n\n      scale = Math.min(maxScaleW, maxScaleH);\n      width *= scale;\n      height *= scale;\n    }\n\n    if (!specdMaxDims) {\n      width *= pxRatio;\n      height *= pxRatio;\n      scale *= pxRatio;\n    }\n\n    var buffCanvas = document.createElement('canvas'); // eslint-disable-line no-undef\n\n    buffCanvas.width = width;\n    buffCanvas.height = height;\n    buffCanvas.style.width = width + 'px';\n    buffCanvas.style.height = height + 'px';\n    var buffCxt = buffCanvas.getContext('2d'); // Rasterize the layers, but only if container has nonzero size\n\n    if (width > 0 && height > 0) {\n      buffCxt.clearRect(0, 0, width, height);\n      buffCxt.globalCompositeOperation = 'source-over';\n      var zsortedEles = this.getCachedZSortedEles();\n\n      if (options.full) {\n        // draw the full bounds of the graph\n        buffCxt.translate(-bb.x1 * scale, -bb.y1 * scale);\n        buffCxt.scale(scale, scale);\n        this.drawElements(buffCxt, zsortedEles);\n        buffCxt.scale(1 / scale, 1 / scale);\n        buffCxt.translate(bb.x1 * scale, bb.y1 * scale);\n      } else {\n        // draw the current view\n        var pan = cy.pan();\n        var translation = {\n          x: pan.x * scale,\n          y: pan.y * scale\n        };\n        scale *= cy.zoom();\n        buffCxt.translate(translation.x, translation.y);\n        buffCxt.scale(scale, scale);\n        this.drawElements(buffCxt, zsortedEles);\n        buffCxt.scale(1 / scale, 1 / scale);\n        buffCxt.translate(-translation.x, -translation.y);\n      } // need to fill bg at end like this in order to fill cleared transparent pixels in jpgs\n\n\n      if (options.bg) {\n        buffCxt.globalCompositeOperation = 'destination-over';\n        buffCxt.fillStyle = options.bg;\n        buffCxt.rect(0, 0, width, height);\n        buffCxt.fill();\n      }\n    }\n\n    return buffCanvas;\n  };\n\n  function b64ToBlob(b64, mimeType) {\n    var bytes = atob(b64);\n    var buff = new ArrayBuffer(bytes.length);\n    var buffUint8 = new Uint8Array(buff);\n\n    for (var i = 0; i < bytes.length; i++) {\n      buffUint8[i] = bytes.charCodeAt(i);\n    }\n\n    return new Blob([buff], {\n      type: mimeType\n    });\n  }\n\n  function b64UriToB64(b64uri) {\n    var i = b64uri.indexOf(',');\n    return b64uri.substr(i + 1);\n  }\n\n  function output(options, canvas, mimeType) {\n    var getB64Uri = function getB64Uri() {\n      return canvas.toDataURL(mimeType, options.quality);\n    };\n\n    switch (options.output) {\n      case 'blob-promise':\n        return new Promise$1(function (resolve, reject) {\n          try {\n            canvas.toBlob(function (blob) {\n              if (blob != null) {\n                resolve(blob);\n              } else {\n                reject(new Error('`canvas.toBlob()` sent a null value in its callback'));\n              }\n            }, mimeType, options.quality);\n          } catch (err) {\n            reject(err);\n          }\n        });\n\n      case 'blob':\n        return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);\n\n      case 'base64':\n        return b64UriToB64(getB64Uri());\n\n      case 'base64uri':\n      default:\n        return getB64Uri();\n    }\n  }\n\n  CRp$2.png = function (options) {\n    return output(options, this.bufferCanvasImage(options), 'image/png');\n  };\n\n  CRp$2.jpg = function (options) {\n    return output(options, this.bufferCanvasImage(options), 'image/jpeg');\n  };\n\n  var CRp$1 = {};\n\n  CRp$1.nodeShapeImpl = function (name, context, centerX, centerY, width, height, points) {\n    switch (name) {\n      case 'ellipse':\n        return this.drawEllipsePath(context, centerX, centerY, width, height);\n\n      case 'polygon':\n        return this.drawPolygonPath(context, centerX, centerY, width, height, points);\n\n      case 'round-polygon':\n        return this.drawRoundPolygonPath(context, centerX, centerY, width, height, points);\n\n      case 'roundrectangle':\n      case 'round-rectangle':\n        return this.drawRoundRectanglePath(context, centerX, centerY, width, height);\n\n      case 'cutrectangle':\n      case 'cut-rectangle':\n        return this.drawCutRectanglePath(context, centerX, centerY, width, height);\n\n      case 'bottomroundrectangle':\n      case 'bottom-round-rectangle':\n        return this.drawBottomRoundRectanglePath(context, centerX, centerY, width, height);\n\n      case 'barrel':\n        return this.drawBarrelPath(context, centerX, centerY, width, height);\n    }\n  };\n\n  var CR = CanvasRenderer;\n  var CRp = CanvasRenderer.prototype;\n  CRp.CANVAS_LAYERS = 3; //\n\n  CRp.SELECT_BOX = 0;\n  CRp.DRAG = 1;\n  CRp.NODE = 2;\n  CRp.BUFFER_COUNT = 3; //\n\n  CRp.TEXTURE_BUFFER = 0;\n  CRp.MOTIONBLUR_BUFFER_NODE = 1;\n  CRp.MOTIONBLUR_BUFFER_DRAG = 2;\n\n  function CanvasRenderer(options) {\n    var r = this;\n    r.data = {\n      canvases: new Array(CRp.CANVAS_LAYERS),\n      contexts: new Array(CRp.CANVAS_LAYERS),\n      canvasNeedsRedraw: new Array(CRp.CANVAS_LAYERS),\n      bufferCanvases: new Array(CRp.BUFFER_COUNT),\n      bufferContexts: new Array(CRp.CANVAS_LAYERS)\n    };\n    var tapHlOffAttr = '-webkit-tap-highlight-color';\n    var tapHlOffStyle = 'rgba(0,0,0,0)';\n    r.data.canvasContainer = document.createElement('div'); // eslint-disable-line no-undef\n\n    var containerStyle = r.data.canvasContainer.style;\n    r.data.canvasContainer.style[tapHlOffAttr] = tapHlOffStyle;\n    containerStyle.position = 'relative';\n    containerStyle.zIndex = '0';\n    containerStyle.overflow = 'hidden';\n    var container = options.cy.container();\n    container.appendChild(r.data.canvasContainer);\n    container.style[tapHlOffAttr] = tapHlOffStyle;\n    var styleMap = {\n      '-webkit-user-select': 'none',\n      '-moz-user-select': '-moz-none',\n      'user-select': 'none',\n      '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',\n      'outline-style': 'none'\n    };\n\n    if (ms()) {\n      styleMap['-ms-touch-action'] = 'none';\n      styleMap['touch-action'] = 'none';\n    }\n\n    for (var i = 0; i < CRp.CANVAS_LAYERS; i++) {\n      var canvas = r.data.canvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef\n\n      r.data.contexts[i] = canvas.getContext('2d');\n      Object.keys(styleMap).forEach(function (k) {\n        canvas.style[k] = styleMap[k];\n      });\n      canvas.style.position = 'absolute';\n      canvas.setAttribute('data-id', 'layer' + i);\n      canvas.style.zIndex = String(CRp.CANVAS_LAYERS - i);\n      r.data.canvasContainer.appendChild(canvas);\n      r.data.canvasNeedsRedraw[i] = false;\n    }\n\n    r.data.topCanvas = r.data.canvases[0];\n    r.data.canvases[CRp.NODE].setAttribute('data-id', 'layer' + CRp.NODE + '-node');\n    r.data.canvases[CRp.SELECT_BOX].setAttribute('data-id', 'layer' + CRp.SELECT_BOX + '-selectbox');\n    r.data.canvases[CRp.DRAG].setAttribute('data-id', 'layer' + CRp.DRAG + '-drag');\n\n    for (var i = 0; i < CRp.BUFFER_COUNT; i++) {\n      r.data.bufferCanvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef\n\n      r.data.bufferContexts[i] = r.data.bufferCanvases[i].getContext('2d');\n      r.data.bufferCanvases[i].style.position = 'absolute';\n      r.data.bufferCanvases[i].setAttribute('data-id', 'buffer' + i);\n      r.data.bufferCanvases[i].style.zIndex = String(-i - 1);\n      r.data.bufferCanvases[i].style.visibility = 'hidden'; //r.data.canvasContainer.appendChild(r.data.bufferCanvases[i]);\n    }\n\n    r.pathsEnabled = true;\n    var emptyBb = makeBoundingBox();\n\n    var getBoxCenter = function getBoxCenter(bb) {\n      return {\n        x: (bb.x1 + bb.x2) / 2,\n        y: (bb.y1 + bb.y2) / 2\n      };\n    };\n\n    var getCenterOffset = function getCenterOffset(bb) {\n      return {\n        x: -bb.w / 2,\n        y: -bb.h / 2\n      };\n    };\n\n    var backgroundTimestampHasChanged = function backgroundTimestampHasChanged(ele) {\n      var _p = ele[0]._private;\n      var same = _p.oldBackgroundTimestamp === _p.backgroundTimestamp;\n      return !same;\n    };\n\n    var getStyleKey = function getStyleKey(ele) {\n      return ele[0]._private.nodeKey;\n    };\n\n    var getLabelKey = function getLabelKey(ele) {\n      return ele[0]._private.labelStyleKey;\n    };\n\n    var getSourceLabelKey = function getSourceLabelKey(ele) {\n      return ele[0]._private.sourceLabelStyleKey;\n    };\n\n    var getTargetLabelKey = function getTargetLabelKey(ele) {\n      return ele[0]._private.targetLabelStyleKey;\n    };\n\n    var drawElement = function drawElement(context, ele, bb, scaledLabelShown, useEleOpacity) {\n      return r.drawElement(context, ele, bb, false, false, useEleOpacity);\n    };\n\n    var drawLabel = function drawLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {\n      return r.drawElementText(context, ele, bb, scaledLabelShown, 'main', useEleOpacity);\n    };\n\n    var drawSourceLabel = function drawSourceLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {\n      return r.drawElementText(context, ele, bb, scaledLabelShown, 'source', useEleOpacity);\n    };\n\n    var drawTargetLabel = function drawTargetLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {\n      return r.drawElementText(context, ele, bb, scaledLabelShown, 'target', useEleOpacity);\n    };\n\n    var getElementBox = function getElementBox(ele) {\n      ele.boundingBox();\n      return ele[0]._private.bodyBounds;\n    };\n\n    var getLabelBox = function getLabelBox(ele) {\n      ele.boundingBox();\n      return ele[0]._private.labelBounds.main || emptyBb;\n    };\n\n    var getSourceLabelBox = function getSourceLabelBox(ele) {\n      ele.boundingBox();\n      return ele[0]._private.labelBounds.source || emptyBb;\n    };\n\n    var getTargetLabelBox = function getTargetLabelBox(ele) {\n      ele.boundingBox();\n      return ele[0]._private.labelBounds.target || emptyBb;\n    };\n\n    var isLabelVisibleAtScale = function isLabelVisibleAtScale(ele, scaledLabelShown) {\n      return scaledLabelShown;\n    };\n\n    var getElementRotationPoint = function getElementRotationPoint(ele) {\n      return getBoxCenter(getElementBox(ele));\n    };\n\n    var addTextMargin = function addTextMargin(prefix, pt, ele) {\n      var pre = prefix ? prefix + '-' : '';\n      return {\n        x: pt.x + ele.pstyle(pre + 'text-margin-x').pfValue,\n        y: pt.y + ele.pstyle(pre + 'text-margin-y').pfValue\n      };\n    };\n\n    var getRsPt = function getRsPt(ele, x, y) {\n      var rs = ele[0]._private.rscratch;\n      return {\n        x: rs[x],\n        y: rs[y]\n      };\n    };\n\n    var getLabelRotationPoint = function getLabelRotationPoint(ele) {\n      return addTextMargin('', getRsPt(ele, 'labelX', 'labelY'), ele);\n    };\n\n    var getSourceLabelRotationPoint = function getSourceLabelRotationPoint(ele) {\n      return addTextMargin('source', getRsPt(ele, 'sourceLabelX', 'sourceLabelY'), ele);\n    };\n\n    var getTargetLabelRotationPoint = function getTargetLabelRotationPoint(ele) {\n      return addTextMargin('target', getRsPt(ele, 'targetLabelX', 'targetLabelY'), ele);\n    };\n\n    var getElementRotationOffset = function getElementRotationOffset(ele) {\n      return getCenterOffset(getElementBox(ele));\n    };\n\n    var getSourceLabelRotationOffset = function getSourceLabelRotationOffset(ele) {\n      return getCenterOffset(getSourceLabelBox(ele));\n    };\n\n    var getTargetLabelRotationOffset = function getTargetLabelRotationOffset(ele) {\n      return getCenterOffset(getTargetLabelBox(ele));\n    };\n\n    var getLabelRotationOffset = function getLabelRotationOffset(ele) {\n      var bb = getLabelBox(ele);\n      var p = getCenterOffset(getLabelBox(ele));\n\n      if (ele.isNode()) {\n        switch (ele.pstyle('text-halign').value) {\n          case 'left':\n            p.x = -bb.w;\n            break;\n\n          case 'right':\n            p.x = 0;\n            break;\n        }\n\n        switch (ele.pstyle('text-valign').value) {\n          case 'top':\n            p.y = -bb.h;\n            break;\n\n          case 'bottom':\n            p.y = 0;\n            break;\n        }\n      }\n\n      return p;\n    };\n\n    var eleTxrCache = r.data.eleTxrCache = new ElementTextureCache(r, {\n      getKey: getStyleKey,\n      doesEleInvalidateKey: backgroundTimestampHasChanged,\n      drawElement: drawElement,\n      getBoundingBox: getElementBox,\n      getRotationPoint: getElementRotationPoint,\n      getRotationOffset: getElementRotationOffset,\n      allowEdgeTxrCaching: false,\n      allowParentTxrCaching: false\n    });\n    var lblTxrCache = r.data.lblTxrCache = new ElementTextureCache(r, {\n      getKey: getLabelKey,\n      drawElement: drawLabel,\n      getBoundingBox: getLabelBox,\n      getRotationPoint: getLabelRotationPoint,\n      getRotationOffset: getLabelRotationOffset,\n      isVisible: isLabelVisibleAtScale\n    });\n    var slbTxrCache = r.data.slbTxrCache = new ElementTextureCache(r, {\n      getKey: getSourceLabelKey,\n      drawElement: drawSourceLabel,\n      getBoundingBox: getSourceLabelBox,\n      getRotationPoint: getSourceLabelRotationPoint,\n      getRotationOffset: getSourceLabelRotationOffset,\n      isVisible: isLabelVisibleAtScale\n    });\n    var tlbTxrCache = r.data.tlbTxrCache = new ElementTextureCache(r, {\n      getKey: getTargetLabelKey,\n      drawElement: drawTargetLabel,\n      getBoundingBox: getTargetLabelBox,\n      getRotationPoint: getTargetLabelRotationPoint,\n      getRotationOffset: getTargetLabelRotationOffset,\n      isVisible: isLabelVisibleAtScale\n    });\n    var lyrTxrCache = r.data.lyrTxrCache = new LayeredTextureCache(r);\n    r.onUpdateEleCalcs(function invalidateTextureCaches(willDraw, eles) {\n      // each cache should check for sub-key diff to see that the update affects that cache particularly\n      eleTxrCache.invalidateElements(eles);\n      lblTxrCache.invalidateElements(eles);\n      slbTxrCache.invalidateElements(eles);\n      tlbTxrCache.invalidateElements(eles); // any change invalidates the layers\n\n      lyrTxrCache.invalidateElements(eles); // update the old bg timestamp so diffs can be done in the ele txr caches\n\n      for (var _i = 0; _i < eles.length; _i++) {\n        var _p = eles[_i]._private;\n        _p.oldBackgroundTimestamp = _p.backgroundTimestamp;\n      }\n    });\n\n    var refineInLayers = function refineInLayers(reqs) {\n      for (var i = 0; i < reqs.length; i++) {\n        lyrTxrCache.enqueueElementRefinement(reqs[i].ele);\n      }\n    };\n\n    eleTxrCache.onDequeue(refineInLayers);\n    lblTxrCache.onDequeue(refineInLayers);\n    slbTxrCache.onDequeue(refineInLayers);\n    tlbTxrCache.onDequeue(refineInLayers);\n  }\n\n  CRp.redrawHint = function (group, bool) {\n    var r = this;\n\n    switch (group) {\n      case 'eles':\n        r.data.canvasNeedsRedraw[CRp.NODE] = bool;\n        break;\n\n      case 'drag':\n        r.data.canvasNeedsRedraw[CRp.DRAG] = bool;\n        break;\n\n      case 'select':\n        r.data.canvasNeedsRedraw[CRp.SELECT_BOX] = bool;\n        break;\n    }\n  }; // whether to use Path2D caching for drawing\n\n\n  var pathsImpld = typeof Path2D !== 'undefined';\n\n  CRp.path2dEnabled = function (on) {\n    if (on === undefined) {\n      return this.pathsEnabled;\n    }\n\n    this.pathsEnabled = on ? true : false;\n  };\n\n  CRp.usePaths = function () {\n    return pathsImpld && this.pathsEnabled;\n  };\n\n  CRp.setImgSmoothing = function (context, bool) {\n    if (context.imageSmoothingEnabled != null) {\n      context.imageSmoothingEnabled = bool;\n    } else {\n      context.webkitImageSmoothingEnabled = bool;\n      context.mozImageSmoothingEnabled = bool;\n      context.msImageSmoothingEnabled = bool;\n    }\n  };\n\n  CRp.getImgSmoothing = function (context) {\n    if (context.imageSmoothingEnabled != null) {\n      return context.imageSmoothingEnabled;\n    } else {\n      return context.webkitImageSmoothingEnabled || context.mozImageSmoothingEnabled || context.msImageSmoothingEnabled;\n    }\n  };\n\n  CRp.makeOffscreenCanvas = function (width, height) {\n    var canvas;\n\n    if ((typeof OffscreenCanvas === \"undefined\" ? \"undefined\" : _typeof(OffscreenCanvas)) !== (\"undefined\" )) {\n      canvas = new OffscreenCanvas(width, height);\n    } else {\n      canvas = document.createElement('canvas'); // eslint-disable-line no-undef\n\n      canvas.width = width;\n      canvas.height = height;\n    }\n\n    return canvas;\n  };\n\n  [CRp$a, CRp$9, CRp$8, CRp$7, CRp$6, CRp$5, CRp$4, CRp$3, CRp$2, CRp$1].forEach(function (props) {\n    extend(CRp, props);\n  });\n\n  var renderer = [{\n    name: 'null',\n    impl: NullRenderer\n  }, {\n    name: 'base',\n    impl: BR\n  }, {\n    name: 'canvas',\n    impl: CR\n  }];\n\n  var incExts = [{\n    type: 'layout',\n    extensions: layout\n  }, {\n    type: 'renderer',\n    extensions: renderer\n  }];\n\n  var extensions = {}; // registered modules for extensions, indexed by name\n\n  var modules = {};\n\n  function setExtension(type, name, registrant) {\n    var ext = registrant;\n\n    var overrideErr = function overrideErr(field) {\n      warn('Can not register `' + name + '` for `' + type + '` since `' + field + '` already exists in the prototype and can not be overridden');\n    };\n\n    if (type === 'core') {\n      if (Core.prototype[name]) {\n        return overrideErr(name);\n      } else {\n        Core.prototype[name] = registrant;\n      }\n    } else if (type === 'collection') {\n      if (Collection.prototype[name]) {\n        return overrideErr(name);\n      } else {\n        Collection.prototype[name] = registrant;\n      }\n    } else if (type === 'layout') {\n      // fill in missing layout functions in the prototype\n      var Layout = function Layout(options) {\n        this.options = options;\n        registrant.call(this, options); // make sure layout has _private for use w/ std apis like .on()\n\n        if (!plainObject(this._private)) {\n          this._private = {};\n        }\n\n        this._private.cy = options.cy;\n        this._private.listeners = [];\n        this.createEmitter();\n      };\n\n      var layoutProto = Layout.prototype = Object.create(registrant.prototype);\n      var optLayoutFns = [];\n\n      for (var i = 0; i < optLayoutFns.length; i++) {\n        var fnName = optLayoutFns[i];\n\n        layoutProto[fnName] = layoutProto[fnName] || function () {\n          return this;\n        };\n      } // either .start() or .run() is defined, so autogen the other\n\n\n      if (layoutProto.start && !layoutProto.run) {\n        layoutProto.run = function () {\n          this.start();\n          return this;\n        };\n      } else if (!layoutProto.start && layoutProto.run) {\n        layoutProto.start = function () {\n          this.run();\n          return this;\n        };\n      }\n\n      var regStop = registrant.prototype.stop;\n\n      layoutProto.stop = function () {\n        var opts = this.options;\n\n        if (opts && opts.animate) {\n          var anis = this.animations;\n\n          if (anis) {\n            for (var _i = 0; _i < anis.length; _i++) {\n              anis[_i].stop();\n            }\n          }\n        }\n\n        if (regStop) {\n          regStop.call(this);\n        } else {\n          this.emit('layoutstop');\n        }\n\n        return this;\n      };\n\n      if (!layoutProto.destroy) {\n        layoutProto.destroy = function () {\n          return this;\n        };\n      }\n\n      layoutProto.cy = function () {\n        return this._private.cy;\n      };\n\n      var getCy = function getCy(layout) {\n        return layout._private.cy;\n      };\n\n      var emitterOpts = {\n        addEventFields: function addEventFields(layout, evt) {\n          evt.layout = layout;\n          evt.cy = getCy(layout);\n          evt.target = layout;\n        },\n        bubble: function bubble() {\n          return true;\n        },\n        parent: function parent(layout) {\n          return getCy(layout);\n        }\n      };\n      extend(layoutProto, {\n        createEmitter: function createEmitter() {\n          this._private.emitter = new Emitter(emitterOpts, this);\n          return this;\n        },\n        emitter: function emitter() {\n          return this._private.emitter;\n        },\n        on: function on(evt, cb) {\n          this.emitter().on(evt, cb);\n          return this;\n        },\n        one: function one(evt, cb) {\n          this.emitter().one(evt, cb);\n          return this;\n        },\n        once: function once(evt, cb) {\n          this.emitter().one(evt, cb);\n          return this;\n        },\n        removeListener: function removeListener(evt, cb) {\n          this.emitter().removeListener(evt, cb);\n          return this;\n        },\n        removeAllListeners: function removeAllListeners() {\n          this.emitter().removeAllListeners();\n          return this;\n        },\n        emit: function emit(evt, params) {\n          this.emitter().emit(evt, params);\n          return this;\n        }\n      });\n      define.eventAliasesOn(layoutProto);\n      ext = Layout; // replace with our wrapped layout\n    } else if (type === 'renderer' && name !== 'null' && name !== 'base') {\n      // user registered renderers inherit from base\n      var BaseRenderer = getExtension('renderer', 'base');\n      var bProto = BaseRenderer.prototype;\n      var RegistrantRenderer = registrant;\n      var rProto = registrant.prototype;\n\n      var Renderer = function Renderer() {\n        BaseRenderer.apply(this, arguments);\n        RegistrantRenderer.apply(this, arguments);\n      };\n\n      var proto = Renderer.prototype;\n\n      for (var pName in bProto) {\n        var pVal = bProto[pName];\n        var existsInR = rProto[pName] != null;\n\n        if (existsInR) {\n          return overrideErr(pName);\n        }\n\n        proto[pName] = pVal; // take impl from base\n      }\n\n      for (var _pName in rProto) {\n        proto[_pName] = rProto[_pName]; // take impl from registrant\n      }\n\n      bProto.clientFunctions.forEach(function (name) {\n        proto[name] = proto[name] || function () {\n          error('Renderer does not implement `renderer.' + name + '()` on its prototype');\n        };\n      });\n      ext = Renderer;\n    } else if (type === '__proto__' || type === 'constructor' || type === 'prototype') {\n      // to avoid potential prototype pollution\n      return error(type + ' is an illegal type to be registered, possibly lead to prototype pollutions');\n    }\n\n    return setMap({\n      map: extensions,\n      keys: [type, name],\n      value: ext\n    });\n  }\n\n  function getExtension(type, name) {\n    return getMap({\n      map: extensions,\n      keys: [type, name]\n    });\n  }\n\n  function setModule(type, name, moduleType, moduleName, registrant) {\n    return setMap({\n      map: modules,\n      keys: [type, name, moduleType, moduleName],\n      value: registrant\n    });\n  }\n\n  function getModule(type, name, moduleType, moduleName) {\n    return getMap({\n      map: modules,\n      keys: [type, name, moduleType, moduleName]\n    });\n  }\n\n  var extension = function extension() {\n    // e.g. extension('renderer', 'svg')\n    if (arguments.length === 2) {\n      return getExtension.apply(null, arguments);\n    } // e.g. extension('renderer', 'svg', { ... })\n    else if (arguments.length === 3) {\n      return setExtension.apply(null, arguments);\n    } // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse')\n    else if (arguments.length === 4) {\n      return getModule.apply(null, arguments);\n    } // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse', { ... })\n    else if (arguments.length === 5) {\n      return setModule.apply(null, arguments);\n    } else {\n      error('Invalid extension access syntax');\n    }\n  }; // allows a core instance to access extensions internally\n\n\n  Core.prototype.extension = extension; // included extensions\n\n  incExts.forEach(function (group) {\n    group.extensions.forEach(function (ext) {\n      setExtension(group.type, ext.name, ext.impl);\n    });\n  });\n\n  // (useful for init)\n\n  var Stylesheet = function Stylesheet() {\n    if (!(this instanceof Stylesheet)) {\n      return new Stylesheet();\n    }\n\n    this.length = 0;\n  };\n\n  var sheetfn = Stylesheet.prototype;\n\n  sheetfn.instanceString = function () {\n    return 'stylesheet';\n  }; // just store the selector to be parsed later\n\n\n  sheetfn.selector = function (selector) {\n    var i = this.length++;\n    this[i] = {\n      selector: selector,\n      properties: []\n    };\n    return this; // chaining\n  }; // just store the property to be parsed later\n\n\n  sheetfn.css = function (name, value) {\n    var i = this.length - 1;\n\n    if (string(name)) {\n      this[i].properties.push({\n        name: name,\n        value: value\n      });\n    } else if (plainObject(name)) {\n      var map = name;\n      var propNames = Object.keys(map);\n\n      for (var j = 0; j < propNames.length; j++) {\n        var key = propNames[j];\n        var mapVal = map[key];\n\n        if (mapVal == null) {\n          continue;\n        }\n\n        var prop = Style.properties[key] || Style.properties[dash2camel(key)];\n\n        if (prop == null) {\n          continue;\n        }\n\n        var _name = prop.name;\n        var _value = mapVal;\n        this[i].properties.push({\n          name: _name,\n          value: _value\n        });\n      }\n    }\n\n    return this; // chaining\n  };\n\n  sheetfn.style = sheetfn.css; // generate a real style object from the dummy stylesheet\n\n  sheetfn.generateStyle = function (cy) {\n    var style = new Style(cy);\n    return this.appendToStyle(style);\n  }; // append a dummy stylesheet object on a real style object\n\n\n  sheetfn.appendToStyle = function (style) {\n    for (var i = 0; i < this.length; i++) {\n      var context = this[i];\n      var selector = context.selector;\n      var props = context.properties;\n      style.selector(selector); // apply selector\n\n      for (var j = 0; j < props.length; j++) {\n        var prop = props[j];\n        style.css(prop.name, prop.value); // apply property\n      }\n    }\n\n    return style;\n  };\n\n  var version = \"3.26.0\";\n\n  var cytoscape = function cytoscape(options) {\n    // if no options specified, use default\n    if (options === undefined) {\n      options = {};\n    } // create instance\n\n\n    if (plainObject(options)) {\n      return new Core(options);\n    } // allow for registration of extensions\n    else if (string(options)) {\n      return extension.apply(extension, arguments);\n    }\n  }; // e.g. cytoscape.use( require('cytoscape-foo'), bar )\n\n\n  cytoscape.use = function (ext) {\n    var args = Array.prototype.slice.call(arguments, 1); // args to pass to ext\n\n    args.unshift(cytoscape); // cytoscape is first arg to ext\n\n    ext.apply(null, args);\n    return this;\n  };\n\n  cytoscape.warnings = function (bool) {\n    return warnings(bool);\n  }; // replaced by build system\n\n\n  cytoscape.version = version; // expose public apis (mostly for extensions)\n\n  cytoscape.stylesheet = cytoscape.Stylesheet = Stylesheet;\n\n  return cytoscape;\n\n}));\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/cytoscape/dist/cytoscape.umd.js?");

/***/ }),

/***/ "../node_modules/layout-base/layout-base.js":
/*!**************************************************!*\
  !*** ../node_modules/layout-base/layout-base.js ***!
  \**************************************************/
/***/ (function(module) {

eval("(function webpackUniversalModuleDefinition(root, factory) {\n\tif(true)\n\t\tmodule.exports = factory();\n\telse {}\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __nested_webpack_require_543__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_543__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__nested_webpack_require_543__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__nested_webpack_require_543__.c = installedModules;\n/******/\n/******/ \t// identity function for calling harmony imports with the correct context\n/******/ \t__nested_webpack_require_543__.i = function(value) { return value; };\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__nested_webpack_require_543__.d = function(exports, name, getter) {\n/******/ \t\tif(!__nested_webpack_require_543__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__nested_webpack_require_543__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__nested_webpack_require_543__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__nested_webpack_require_543__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__nested_webpack_require_543__.p = \"\";\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __nested_webpack_require_543__(__nested_webpack_require_543__.s = 26);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction LayoutConstants() {}\n\n/**\r\n * Layout Quality: 0:draft, 1:default, 2:proof\r\n */\nLayoutConstants.QUALITY = 1;\n\n/**\r\n * Default parameters\r\n */\nLayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED = false;\nLayoutConstants.DEFAULT_INCREMENTAL = false;\nLayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT = true;\nLayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT = false;\nLayoutConstants.DEFAULT_ANIMATION_PERIOD = 50;\nLayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = false;\n\n// -----------------------------------------------------------------------------\n// Section: General other constants\n// -----------------------------------------------------------------------------\n/*\r\n * Margins of a graph to be applied on bouding rectangle of its contents. We\r\n * assume margins on all four sides to be uniform.\r\n */\nLayoutConstants.DEFAULT_GRAPH_MARGIN = 15;\n\n/*\r\n * Whether to consider labels in node dimensions or not\r\n */\nLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = false;\n\n/*\r\n * Default dimension of a non-compound node.\r\n */\nLayoutConstants.SIMPLE_NODE_SIZE = 40;\n\n/*\r\n * Default dimension of a non-compound node.\r\n */\nLayoutConstants.SIMPLE_NODE_HALF_SIZE = LayoutConstants.SIMPLE_NODE_SIZE / 2;\n\n/*\r\n * Empty compound node size. When a compound node is empty, its both\r\n * dimensions should be of this value.\r\n */\nLayoutConstants.EMPTY_COMPOUND_NODE_SIZE = 40;\n\n/*\r\n * Minimum length that an edge should take during layout\r\n */\nLayoutConstants.MIN_EDGE_LENGTH = 1;\n\n/*\r\n * World boundaries that layout operates on\r\n */\nLayoutConstants.WORLD_BOUNDARY = 1000000;\n\n/*\r\n * World boundaries that random positioning can be performed with\r\n */\nLayoutConstants.INITIAL_WORLD_BOUNDARY = LayoutConstants.WORLD_BOUNDARY / 1000;\n\n/*\r\n * Coordinates of the world center\r\n */\nLayoutConstants.WORLD_CENTER_X = 1200;\nLayoutConstants.WORLD_CENTER_Y = 900;\n\nmodule.exports = LayoutConstants;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports, __nested_webpack_require_4947__) {\n\n\"use strict\";\n\n\nvar LGraphObject = __nested_webpack_require_4947__(2);\nvar IGeometry = __nested_webpack_require_4947__(8);\nvar IMath = __nested_webpack_require_4947__(9);\n\nfunction LEdge(source, target, vEdge) {\n  LGraphObject.call(this, vEdge);\n\n  this.isOverlapingSourceAndTarget = false;\n  this.vGraphObject = vEdge;\n  this.bendpoints = [];\n  this.source = source;\n  this.target = target;\n}\n\nLEdge.prototype = Object.create(LGraphObject.prototype);\n\nfor (var prop in LGraphObject) {\n  LEdge[prop] = LGraphObject[prop];\n}\n\nLEdge.prototype.getSource = function () {\n  return this.source;\n};\n\nLEdge.prototype.getTarget = function () {\n  return this.target;\n};\n\nLEdge.prototype.isInterGraph = function () {\n  return this.isInterGraph;\n};\n\nLEdge.prototype.getLength = function () {\n  return this.length;\n};\n\nLEdge.prototype.isOverlapingSourceAndTarget = function () {\n  return this.isOverlapingSourceAndTarget;\n};\n\nLEdge.prototype.getBendpoints = function () {\n  return this.bendpoints;\n};\n\nLEdge.prototype.getLca = function () {\n  return this.lca;\n};\n\nLEdge.prototype.getSourceInLca = function () {\n  return this.sourceInLca;\n};\n\nLEdge.prototype.getTargetInLca = function () {\n  return this.targetInLca;\n};\n\nLEdge.prototype.getOtherEnd = function (node) {\n  if (this.source === node) {\n    return this.target;\n  } else if (this.target === node) {\n    return this.source;\n  } else {\n    throw \"Node is not incident with this edge\";\n  }\n};\n\nLEdge.prototype.getOtherEndInGraph = function (node, graph) {\n  var otherEnd = this.getOtherEnd(node);\n  var root = graph.getGraphManager().getRoot();\n\n  while (true) {\n    if (otherEnd.getOwner() == graph) {\n      return otherEnd;\n    }\n\n    if (otherEnd.getOwner() == root) {\n      break;\n    }\n\n    otherEnd = otherEnd.getOwner().getParent();\n  }\n\n  return null;\n};\n\nLEdge.prototype.updateLength = function () {\n  var clipPointCoordinates = new Array(4);\n\n  this.isOverlapingSourceAndTarget = IGeometry.getIntersection(this.target.getRect(), this.source.getRect(), clipPointCoordinates);\n\n  if (!this.isOverlapingSourceAndTarget) {\n    this.lengthX = clipPointCoordinates[0] - clipPointCoordinates[2];\n    this.lengthY = clipPointCoordinates[1] - clipPointCoordinates[3];\n\n    if (Math.abs(this.lengthX) < 1.0) {\n      this.lengthX = IMath.sign(this.lengthX);\n    }\n\n    if (Math.abs(this.lengthY) < 1.0) {\n      this.lengthY = IMath.sign(this.lengthY);\n    }\n\n    this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);\n  }\n};\n\nLEdge.prototype.updateLengthSimple = function () {\n  this.lengthX = this.target.getCenterX() - this.source.getCenterX();\n  this.lengthY = this.target.getCenterY() - this.source.getCenterY();\n\n  if (Math.abs(this.lengthX) < 1.0) {\n    this.lengthX = IMath.sign(this.lengthX);\n  }\n\n  if (Math.abs(this.lengthY) < 1.0) {\n    this.lengthY = IMath.sign(this.lengthY);\n  }\n\n  this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);\n};\n\nmodule.exports = LEdge;\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction LGraphObject(vGraphObject) {\n  this.vGraphObject = vGraphObject;\n}\n\nmodule.exports = LGraphObject;\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __nested_webpack_require_8167__) {\n\n\"use strict\";\n\n\nvar LGraphObject = __nested_webpack_require_8167__(2);\nvar Integer = __nested_webpack_require_8167__(10);\nvar RectangleD = __nested_webpack_require_8167__(13);\nvar LayoutConstants = __nested_webpack_require_8167__(0);\nvar RandomSeed = __nested_webpack_require_8167__(16);\nvar PointD = __nested_webpack_require_8167__(4);\n\nfunction LNode(gm, loc, size, vNode) {\n  //Alternative constructor 1 : LNode(LGraphManager gm, Point loc, Dimension size, Object vNode)\n  if (size == null && vNode == null) {\n    vNode = loc;\n  }\n\n  LGraphObject.call(this, vNode);\n\n  //Alternative constructor 2 : LNode(Layout layout, Object vNode)\n  if (gm.graphManager != null) gm = gm.graphManager;\n\n  this.estimatedSize = Integer.MIN_VALUE;\n  this.inclusionTreeDepth = Integer.MAX_VALUE;\n  this.vGraphObject = vNode;\n  this.edges = [];\n  this.graphManager = gm;\n\n  if (size != null && loc != null) this.rect = new RectangleD(loc.x, loc.y, size.width, size.height);else this.rect = new RectangleD();\n}\n\nLNode.prototype = Object.create(LGraphObject.prototype);\nfor (var prop in LGraphObject) {\n  LNode[prop] = LGraphObject[prop];\n}\n\nLNode.prototype.getEdges = function () {\n  return this.edges;\n};\n\nLNode.prototype.getChild = function () {\n  return this.child;\n};\n\nLNode.prototype.getOwner = function () {\n  //  if (this.owner != null) {\n  //    if (!(this.owner == null || this.owner.getNodes().indexOf(this) > -1)) {\n  //      throw \"assert failed\";\n  //    }\n  //  }\n\n  return this.owner;\n};\n\nLNode.prototype.getWidth = function () {\n  return this.rect.width;\n};\n\nLNode.prototype.setWidth = function (width) {\n  this.rect.width = width;\n};\n\nLNode.prototype.getHeight = function () {\n  return this.rect.height;\n};\n\nLNode.prototype.setHeight = function (height) {\n  this.rect.height = height;\n};\n\nLNode.prototype.getCenterX = function () {\n  return this.rect.x + this.rect.width / 2;\n};\n\nLNode.prototype.getCenterY = function () {\n  return this.rect.y + this.rect.height / 2;\n};\n\nLNode.prototype.getCenter = function () {\n  return new PointD(this.rect.x + this.rect.width / 2, this.rect.y + this.rect.height / 2);\n};\n\nLNode.prototype.getLocation = function () {\n  return new PointD(this.rect.x, this.rect.y);\n};\n\nLNode.prototype.getRect = function () {\n  return this.rect;\n};\n\nLNode.prototype.getDiagonal = function () {\n  return Math.sqrt(this.rect.width * this.rect.width + this.rect.height * this.rect.height);\n};\n\n/**\n * This method returns half the diagonal length of this node.\n */\nLNode.prototype.getHalfTheDiagonal = function () {\n  return Math.sqrt(this.rect.height * this.rect.height + this.rect.width * this.rect.width) / 2;\n};\n\nLNode.prototype.setRect = function (upperLeft, dimension) {\n  this.rect.x = upperLeft.x;\n  this.rect.y = upperLeft.y;\n  this.rect.width = dimension.width;\n  this.rect.height = dimension.height;\n};\n\nLNode.prototype.setCenter = function (cx, cy) {\n  this.rect.x = cx - this.rect.width / 2;\n  this.rect.y = cy - this.rect.height / 2;\n};\n\nLNode.prototype.setLocation = function (x, y) {\n  this.rect.x = x;\n  this.rect.y = y;\n};\n\nLNode.prototype.moveBy = function (dx, dy) {\n  this.rect.x += dx;\n  this.rect.y += dy;\n};\n\nLNode.prototype.getEdgeListToNode = function (to) {\n  var edgeList = [];\n  var edge;\n  var self = this;\n\n  self.edges.forEach(function (edge) {\n\n    if (edge.target == to) {\n      if (edge.source != self) throw \"Incorrect edge source!\";\n\n      edgeList.push(edge);\n    }\n  });\n\n  return edgeList;\n};\n\nLNode.prototype.getEdgesBetween = function (other) {\n  var edgeList = [];\n  var edge;\n\n  var self = this;\n  self.edges.forEach(function (edge) {\n\n    if (!(edge.source == self || edge.target == self)) throw \"Incorrect edge source and/or target\";\n\n    if (edge.target == other || edge.source == other) {\n      edgeList.push(edge);\n    }\n  });\n\n  return edgeList;\n};\n\nLNode.prototype.getNeighborsList = function () {\n  var neighbors = new Set();\n\n  var self = this;\n  self.edges.forEach(function (edge) {\n\n    if (edge.source == self) {\n      neighbors.add(edge.target);\n    } else {\n      if (edge.target != self) {\n        throw \"Incorrect incidency!\";\n      }\n\n      neighbors.add(edge.source);\n    }\n  });\n\n  return neighbors;\n};\n\nLNode.prototype.withChildren = function () {\n  var withNeighborsList = new Set();\n  var childNode;\n  var children;\n\n  withNeighborsList.add(this);\n\n  if (this.child != null) {\n    var nodes = this.child.getNodes();\n    for (var i = 0; i < nodes.length; i++) {\n      childNode = nodes[i];\n      children = childNode.withChildren();\n      children.forEach(function (node) {\n        withNeighborsList.add(node);\n      });\n    }\n  }\n\n  return withNeighborsList;\n};\n\nLNode.prototype.getNoOfChildren = function () {\n  var noOfChildren = 0;\n  var childNode;\n\n  if (this.child == null) {\n    noOfChildren = 1;\n  } else {\n    var nodes = this.child.getNodes();\n    for (var i = 0; i < nodes.length; i++) {\n      childNode = nodes[i];\n\n      noOfChildren += childNode.getNoOfChildren();\n    }\n  }\n\n  if (noOfChildren == 0) {\n    noOfChildren = 1;\n  }\n  return noOfChildren;\n};\n\nLNode.prototype.getEstimatedSize = function () {\n  if (this.estimatedSize == Integer.MIN_VALUE) {\n    throw \"assert failed\";\n  }\n  return this.estimatedSize;\n};\n\nLNode.prototype.calcEstimatedSize = function () {\n  if (this.child == null) {\n    return this.estimatedSize = (this.rect.width + this.rect.height) / 2;\n  } else {\n    this.estimatedSize = this.child.calcEstimatedSize();\n    this.rect.width = this.estimatedSize;\n    this.rect.height = this.estimatedSize;\n\n    return this.estimatedSize;\n  }\n};\n\nLNode.prototype.scatter = function () {\n  var randomCenterX;\n  var randomCenterY;\n\n  var minX = -LayoutConstants.INITIAL_WORLD_BOUNDARY;\n  var maxX = LayoutConstants.INITIAL_WORLD_BOUNDARY;\n  randomCenterX = LayoutConstants.WORLD_CENTER_X + RandomSeed.nextDouble() * (maxX - minX) + minX;\n\n  var minY = -LayoutConstants.INITIAL_WORLD_BOUNDARY;\n  var maxY = LayoutConstants.INITIAL_WORLD_BOUNDARY;\n  randomCenterY = LayoutConstants.WORLD_CENTER_Y + RandomSeed.nextDouble() * (maxY - minY) + minY;\n\n  this.rect.x = randomCenterX;\n  this.rect.y = randomCenterY;\n};\n\nLNode.prototype.updateBounds = function () {\n  if (this.getChild() == null) {\n    throw \"assert failed\";\n  }\n  if (this.getChild().getNodes().length != 0) {\n    // wrap the children nodes by re-arranging the boundaries\n    var childGraph = this.getChild();\n    childGraph.updateBounds(true);\n\n    this.rect.x = childGraph.getLeft();\n    this.rect.y = childGraph.getTop();\n\n    this.setWidth(childGraph.getRight() - childGraph.getLeft());\n    this.setHeight(childGraph.getBottom() - childGraph.getTop());\n\n    // Update compound bounds considering its label properties    \n    if (LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {\n\n      var width = childGraph.getRight() - childGraph.getLeft();\n      var height = childGraph.getBottom() - childGraph.getTop();\n\n      if (this.labelWidth > width) {\n        this.rect.x -= (this.labelWidth - width) / 2;\n        this.setWidth(this.labelWidth);\n      }\n\n      if (this.labelHeight > height) {\n        if (this.labelPos == \"center\") {\n          this.rect.y -= (this.labelHeight - height) / 2;\n        } else if (this.labelPos == \"top\") {\n          this.rect.y -= this.labelHeight - height;\n        }\n        this.setHeight(this.labelHeight);\n      }\n    }\n  }\n};\n\nLNode.prototype.getInclusionTreeDepth = function () {\n  if (this.inclusionTreeDepth == Integer.MAX_VALUE) {\n    throw \"assert failed\";\n  }\n  return this.inclusionTreeDepth;\n};\n\nLNode.prototype.transform = function (trans) {\n  var left = this.rect.x;\n\n  if (left > LayoutConstants.WORLD_BOUNDARY) {\n    left = LayoutConstants.WORLD_BOUNDARY;\n  } else if (left < -LayoutConstants.WORLD_BOUNDARY) {\n    left = -LayoutConstants.WORLD_BOUNDARY;\n  }\n\n  var top = this.rect.y;\n\n  if (top > LayoutConstants.WORLD_BOUNDARY) {\n    top = LayoutConstants.WORLD_BOUNDARY;\n  } else if (top < -LayoutConstants.WORLD_BOUNDARY) {\n    top = -LayoutConstants.WORLD_BOUNDARY;\n  }\n\n  var leftTop = new PointD(left, top);\n  var vLeftTop = trans.inverseTransformPoint(leftTop);\n\n  this.setLocation(vLeftTop.x, vLeftTop.y);\n};\n\nLNode.prototype.getLeft = function () {\n  return this.rect.x;\n};\n\nLNode.prototype.getRight = function () {\n  return this.rect.x + this.rect.width;\n};\n\nLNode.prototype.getTop = function () {\n  return this.rect.y;\n};\n\nLNode.prototype.getBottom = function () {\n  return this.rect.y + this.rect.height;\n};\n\nLNode.prototype.getParent = function () {\n  if (this.owner == null) {\n    return null;\n  }\n\n  return this.owner.getParent();\n};\n\nmodule.exports = LNode;\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction PointD(x, y) {\n  if (x == null && y == null) {\n    this.x = 0;\n    this.y = 0;\n  } else {\n    this.x = x;\n    this.y = y;\n  }\n}\n\nPointD.prototype.getX = function () {\n  return this.x;\n};\n\nPointD.prototype.getY = function () {\n  return this.y;\n};\n\nPointD.prototype.setX = function (x) {\n  this.x = x;\n};\n\nPointD.prototype.setY = function (y) {\n  this.y = y;\n};\n\nPointD.prototype.getDifference = function (pt) {\n  return new DimensionD(this.x - pt.x, this.y - pt.y);\n};\n\nPointD.prototype.getCopy = function () {\n  return new PointD(this.x, this.y);\n};\n\nPointD.prototype.translate = function (dim) {\n  this.x += dim.width;\n  this.y += dim.height;\n  return this;\n};\n\nmodule.exports = PointD;\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __nested_webpack_require_17549__) {\n\n\"use strict\";\n\n\nvar LGraphObject = __nested_webpack_require_17549__(2);\nvar Integer = __nested_webpack_require_17549__(10);\nvar LayoutConstants = __nested_webpack_require_17549__(0);\nvar LGraphManager = __nested_webpack_require_17549__(6);\nvar LNode = __nested_webpack_require_17549__(3);\nvar LEdge = __nested_webpack_require_17549__(1);\nvar RectangleD = __nested_webpack_require_17549__(13);\nvar Point = __nested_webpack_require_17549__(12);\nvar LinkedList = __nested_webpack_require_17549__(11);\n\nfunction LGraph(parent, obj2, vGraph) {\n  LGraphObject.call(this, vGraph);\n  this.estimatedSize = Integer.MIN_VALUE;\n  this.margin = LayoutConstants.DEFAULT_GRAPH_MARGIN;\n  this.edges = [];\n  this.nodes = [];\n  this.isConnected = false;\n  this.parent = parent;\n\n  if (obj2 != null && obj2 instanceof LGraphManager) {\n    this.graphManager = obj2;\n  } else if (obj2 != null && obj2 instanceof Layout) {\n    this.graphManager = obj2.graphManager;\n  }\n}\n\nLGraph.prototype = Object.create(LGraphObject.prototype);\nfor (var prop in LGraphObject) {\n  LGraph[prop] = LGraphObject[prop];\n}\n\nLGraph.prototype.getNodes = function () {\n  return this.nodes;\n};\n\nLGraph.prototype.getEdges = function () {\n  return this.edges;\n};\n\nLGraph.prototype.getGraphManager = function () {\n  return this.graphManager;\n};\n\nLGraph.prototype.getParent = function () {\n  return this.parent;\n};\n\nLGraph.prototype.getLeft = function () {\n  return this.left;\n};\n\nLGraph.prototype.getRight = function () {\n  return this.right;\n};\n\nLGraph.prototype.getTop = function () {\n  return this.top;\n};\n\nLGraph.prototype.getBottom = function () {\n  return this.bottom;\n};\n\nLGraph.prototype.isConnected = function () {\n  return this.isConnected;\n};\n\nLGraph.prototype.add = function (obj1, sourceNode, targetNode) {\n  if (sourceNode == null && targetNode == null) {\n    var newNode = obj1;\n    if (this.graphManager == null) {\n      throw \"Graph has no graph mgr!\";\n    }\n    if (this.getNodes().indexOf(newNode) > -1) {\n      throw \"Node already in graph!\";\n    }\n    newNode.owner = this;\n    this.getNodes().push(newNode);\n\n    return newNode;\n  } else {\n    var newEdge = obj1;\n    if (!(this.getNodes().indexOf(sourceNode) > -1 && this.getNodes().indexOf(targetNode) > -1)) {\n      throw \"Source or target not in graph!\";\n    }\n\n    if (!(sourceNode.owner == targetNode.owner && sourceNode.owner == this)) {\n      throw \"Both owners must be this graph!\";\n    }\n\n    if (sourceNode.owner != targetNode.owner) {\n      return null;\n    }\n\n    // set source and target\n    newEdge.source = sourceNode;\n    newEdge.target = targetNode;\n\n    // set as intra-graph edge\n    newEdge.isInterGraph = false;\n\n    // add to graph edge list\n    this.getEdges().push(newEdge);\n\n    // add to incidency lists\n    sourceNode.edges.push(newEdge);\n\n    if (targetNode != sourceNode) {\n      targetNode.edges.push(newEdge);\n    }\n\n    return newEdge;\n  }\n};\n\nLGraph.prototype.remove = function (obj) {\n  var node = obj;\n  if (obj instanceof LNode) {\n    if (node == null) {\n      throw \"Node is null!\";\n    }\n    if (!(node.owner != null && node.owner == this)) {\n      throw \"Owner graph is invalid!\";\n    }\n    if (this.graphManager == null) {\n      throw \"Owner graph manager is invalid!\";\n    }\n    // remove incident edges first (make a copy to do it safely)\n    var edgesToBeRemoved = node.edges.slice();\n    var edge;\n    var s = edgesToBeRemoved.length;\n    for (var i = 0; i < s; i++) {\n      edge = edgesToBeRemoved[i];\n\n      if (edge.isInterGraph) {\n        this.graphManager.remove(edge);\n      } else {\n        edge.source.owner.remove(edge);\n      }\n    }\n\n    // now the node itself\n    var index = this.nodes.indexOf(node);\n    if (index == -1) {\n      throw \"Node not in owner node list!\";\n    }\n\n    this.nodes.splice(index, 1);\n  } else if (obj instanceof LEdge) {\n    var edge = obj;\n    if (edge == null) {\n      throw \"Edge is null!\";\n    }\n    if (!(edge.source != null && edge.target != null)) {\n      throw \"Source and/or target is null!\";\n    }\n    if (!(edge.source.owner != null && edge.target.owner != null && edge.source.owner == this && edge.target.owner == this)) {\n      throw \"Source and/or target owner is invalid!\";\n    }\n\n    var sourceIndex = edge.source.edges.indexOf(edge);\n    var targetIndex = edge.target.edges.indexOf(edge);\n    if (!(sourceIndex > -1 && targetIndex > -1)) {\n      throw \"Source and/or target doesn't know this edge!\";\n    }\n\n    edge.source.edges.splice(sourceIndex, 1);\n\n    if (edge.target != edge.source) {\n      edge.target.edges.splice(targetIndex, 1);\n    }\n\n    var index = edge.source.owner.getEdges().indexOf(edge);\n    if (index == -1) {\n      throw \"Not in owner's edge list!\";\n    }\n\n    edge.source.owner.getEdges().splice(index, 1);\n  }\n};\n\nLGraph.prototype.updateLeftTop = function () {\n  var top = Integer.MAX_VALUE;\n  var left = Integer.MAX_VALUE;\n  var nodeTop;\n  var nodeLeft;\n  var margin;\n\n  var nodes = this.getNodes();\n  var s = nodes.length;\n\n  for (var i = 0; i < s; i++) {\n    var lNode = nodes[i];\n    nodeTop = lNode.getTop();\n    nodeLeft = lNode.getLeft();\n\n    if (top > nodeTop) {\n      top = nodeTop;\n    }\n\n    if (left > nodeLeft) {\n      left = nodeLeft;\n    }\n  }\n\n  // Do we have any nodes in this graph?\n  if (top == Integer.MAX_VALUE) {\n    return null;\n  }\n\n  if (nodes[0].getParent().paddingLeft != undefined) {\n    margin = nodes[0].getParent().paddingLeft;\n  } else {\n    margin = this.margin;\n  }\n\n  this.left = left - margin;\n  this.top = top - margin;\n\n  // Apply the margins and return the result\n  return new Point(this.left, this.top);\n};\n\nLGraph.prototype.updateBounds = function (recursive) {\n  // calculate bounds\n  var left = Integer.MAX_VALUE;\n  var right = -Integer.MAX_VALUE;\n  var top = Integer.MAX_VALUE;\n  var bottom = -Integer.MAX_VALUE;\n  var nodeLeft;\n  var nodeRight;\n  var nodeTop;\n  var nodeBottom;\n  var margin;\n\n  var nodes = this.nodes;\n  var s = nodes.length;\n  for (var i = 0; i < s; i++) {\n    var lNode = nodes[i];\n\n    if (recursive && lNode.child != null) {\n      lNode.updateBounds();\n    }\n    nodeLeft = lNode.getLeft();\n    nodeRight = lNode.getRight();\n    nodeTop = lNode.getTop();\n    nodeBottom = lNode.getBottom();\n\n    if (left > nodeLeft) {\n      left = nodeLeft;\n    }\n\n    if (right < nodeRight) {\n      right = nodeRight;\n    }\n\n    if (top > nodeTop) {\n      top = nodeTop;\n    }\n\n    if (bottom < nodeBottom) {\n      bottom = nodeBottom;\n    }\n  }\n\n  var boundingRect = new RectangleD(left, top, right - left, bottom - top);\n  if (left == Integer.MAX_VALUE) {\n    this.left = this.parent.getLeft();\n    this.right = this.parent.getRight();\n    this.top = this.parent.getTop();\n    this.bottom = this.parent.getBottom();\n  }\n\n  if (nodes[0].getParent().paddingLeft != undefined) {\n    margin = nodes[0].getParent().paddingLeft;\n  } else {\n    margin = this.margin;\n  }\n\n  this.left = boundingRect.x - margin;\n  this.right = boundingRect.x + boundingRect.width + margin;\n  this.top = boundingRect.y - margin;\n  this.bottom = boundingRect.y + boundingRect.height + margin;\n};\n\nLGraph.calculateBounds = function (nodes) {\n  var left = Integer.MAX_VALUE;\n  var right = -Integer.MAX_VALUE;\n  var top = Integer.MAX_VALUE;\n  var bottom = -Integer.MAX_VALUE;\n  var nodeLeft;\n  var nodeRight;\n  var nodeTop;\n  var nodeBottom;\n\n  var s = nodes.length;\n\n  for (var i = 0; i < s; i++) {\n    var lNode = nodes[i];\n    nodeLeft = lNode.getLeft();\n    nodeRight = lNode.getRight();\n    nodeTop = lNode.getTop();\n    nodeBottom = lNode.getBottom();\n\n    if (left > nodeLeft) {\n      left = nodeLeft;\n    }\n\n    if (right < nodeRight) {\n      right = nodeRight;\n    }\n\n    if (top > nodeTop) {\n      top = nodeTop;\n    }\n\n    if (bottom < nodeBottom) {\n      bottom = nodeBottom;\n    }\n  }\n\n  var boundingRect = new RectangleD(left, top, right - left, bottom - top);\n\n  return boundingRect;\n};\n\nLGraph.prototype.getInclusionTreeDepth = function () {\n  if (this == this.graphManager.getRoot()) {\n    return 1;\n  } else {\n    return this.parent.getInclusionTreeDepth();\n  }\n};\n\nLGraph.prototype.getEstimatedSize = function () {\n  if (this.estimatedSize == Integer.MIN_VALUE) {\n    throw \"assert failed\";\n  }\n  return this.estimatedSize;\n};\n\nLGraph.prototype.calcEstimatedSize = function () {\n  var size = 0;\n  var nodes = this.nodes;\n  var s = nodes.length;\n\n  for (var i = 0; i < s; i++) {\n    var lNode = nodes[i];\n    size += lNode.calcEstimatedSize();\n  }\n\n  if (size == 0) {\n    this.estimatedSize = LayoutConstants.EMPTY_COMPOUND_NODE_SIZE;\n  } else {\n    this.estimatedSize = size / Math.sqrt(this.nodes.length);\n  }\n\n  return this.estimatedSize;\n};\n\nLGraph.prototype.updateConnected = function () {\n  var self = this;\n  if (this.nodes.length == 0) {\n    this.isConnected = true;\n    return;\n  }\n\n  var queue = new LinkedList();\n  var visited = new Set();\n  var currentNode = this.nodes[0];\n  var neighborEdges;\n  var currentNeighbor;\n  var childrenOfNode = currentNode.withChildren();\n  childrenOfNode.forEach(function (node) {\n    queue.push(node);\n    visited.add(node);\n  });\n\n  while (queue.length !== 0) {\n    currentNode = queue.shift();\n\n    // Traverse all neighbors of this node\n    neighborEdges = currentNode.getEdges();\n    var size = neighborEdges.length;\n    for (var i = 0; i < size; i++) {\n      var neighborEdge = neighborEdges[i];\n      currentNeighbor = neighborEdge.getOtherEndInGraph(currentNode, this);\n\n      // Add unvisited neighbors to the list to visit\n      if (currentNeighbor != null && !visited.has(currentNeighbor)) {\n        var childrenOfNeighbor = currentNeighbor.withChildren();\n\n        childrenOfNeighbor.forEach(function (node) {\n          queue.push(node);\n          visited.add(node);\n        });\n      }\n    }\n  }\n\n  this.isConnected = false;\n\n  if (visited.size >= this.nodes.length) {\n    var noOfVisitedInThisGraph = 0;\n\n    visited.forEach(function (visitedNode) {\n      if (visitedNode.owner == self) {\n        noOfVisitedInThisGraph++;\n      }\n    });\n\n    if (noOfVisitedInThisGraph == this.nodes.length) {\n      this.isConnected = true;\n    }\n  }\n};\n\nmodule.exports = LGraph;\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __nested_webpack_require_27617__) {\n\n\"use strict\";\n\n\nvar LGraph;\nvar LEdge = __nested_webpack_require_27617__(1);\n\nfunction LGraphManager(layout) {\n  LGraph = __nested_webpack_require_27617__(5); // It may be better to initilize this out of this function but it gives an error (Right-hand side of 'instanceof' is not callable) now.\n  this.layout = layout;\n\n  this.graphs = [];\n  this.edges = [];\n}\n\nLGraphManager.prototype.addRoot = function () {\n  var ngraph = this.layout.newGraph();\n  var nnode = this.layout.newNode(null);\n  var root = this.add(ngraph, nnode);\n  this.setRootGraph(root);\n  return this.rootGraph;\n};\n\nLGraphManager.prototype.add = function (newGraph, parentNode, newEdge, sourceNode, targetNode) {\n  //there are just 2 parameters are passed then it adds an LGraph else it adds an LEdge\n  if (newEdge == null && sourceNode == null && targetNode == null) {\n    if (newGraph == null) {\n      throw \"Graph is null!\";\n    }\n    if (parentNode == null) {\n      throw \"Parent node is null!\";\n    }\n    if (this.graphs.indexOf(newGraph) > -1) {\n      throw \"Graph already in this graph mgr!\";\n    }\n\n    this.graphs.push(newGraph);\n\n    if (newGraph.parent != null) {\n      throw \"Already has a parent!\";\n    }\n    if (parentNode.child != null) {\n      throw \"Already has a child!\";\n    }\n\n    newGraph.parent = parentNode;\n    parentNode.child = newGraph;\n\n    return newGraph;\n  } else {\n    //change the order of the parameters\n    targetNode = newEdge;\n    sourceNode = parentNode;\n    newEdge = newGraph;\n    var sourceGraph = sourceNode.getOwner();\n    var targetGraph = targetNode.getOwner();\n\n    if (!(sourceGraph != null && sourceGraph.getGraphManager() == this)) {\n      throw \"Source not in this graph mgr!\";\n    }\n    if (!(targetGraph != null && targetGraph.getGraphManager() == this)) {\n      throw \"Target not in this graph mgr!\";\n    }\n\n    if (sourceGraph == targetGraph) {\n      newEdge.isInterGraph = false;\n      return sourceGraph.add(newEdge, sourceNode, targetNode);\n    } else {\n      newEdge.isInterGraph = true;\n\n      // set source and target\n      newEdge.source = sourceNode;\n      newEdge.target = targetNode;\n\n      // add edge to inter-graph edge list\n      if (this.edges.indexOf(newEdge) > -1) {\n        throw \"Edge already in inter-graph edge list!\";\n      }\n\n      this.edges.push(newEdge);\n\n      // add edge to source and target incidency lists\n      if (!(newEdge.source != null && newEdge.target != null)) {\n        throw \"Edge source and/or target is null!\";\n      }\n\n      if (!(newEdge.source.edges.indexOf(newEdge) == -1 && newEdge.target.edges.indexOf(newEdge) == -1)) {\n        throw \"Edge already in source and/or target incidency list!\";\n      }\n\n      newEdge.source.edges.push(newEdge);\n      newEdge.target.edges.push(newEdge);\n\n      return newEdge;\n    }\n  }\n};\n\nLGraphManager.prototype.remove = function (lObj) {\n  if (lObj instanceof LGraph) {\n    var graph = lObj;\n    if (graph.getGraphManager() != this) {\n      throw \"Graph not in this graph mgr\";\n    }\n    if (!(graph == this.rootGraph || graph.parent != null && graph.parent.graphManager == this)) {\n      throw \"Invalid parent node!\";\n    }\n\n    // first the edges (make a copy to do it safely)\n    var edgesToBeRemoved = [];\n\n    edgesToBeRemoved = edgesToBeRemoved.concat(graph.getEdges());\n\n    var edge;\n    var s = edgesToBeRemoved.length;\n    for (var i = 0; i < s; i++) {\n      edge = edgesToBeRemoved[i];\n      graph.remove(edge);\n    }\n\n    // then the nodes (make a copy to do it safely)\n    var nodesToBeRemoved = [];\n\n    nodesToBeRemoved = nodesToBeRemoved.concat(graph.getNodes());\n\n    var node;\n    s = nodesToBeRemoved.length;\n    for (var i = 0; i < s; i++) {\n      node = nodesToBeRemoved[i];\n      graph.remove(node);\n    }\n\n    // check if graph is the root\n    if (graph == this.rootGraph) {\n      this.setRootGraph(null);\n    }\n\n    // now remove the graph itself\n    var index = this.graphs.indexOf(graph);\n    this.graphs.splice(index, 1);\n\n    // also reset the parent of the graph\n    graph.parent = null;\n  } else if (lObj instanceof LEdge) {\n    edge = lObj;\n    if (edge == null) {\n      throw \"Edge is null!\";\n    }\n    if (!edge.isInterGraph) {\n      throw \"Not an inter-graph edge!\";\n    }\n    if (!(edge.source != null && edge.target != null)) {\n      throw \"Source and/or target is null!\";\n    }\n\n    // remove edge from source and target nodes' incidency lists\n\n    if (!(edge.source.edges.indexOf(edge) != -1 && edge.target.edges.indexOf(edge) != -1)) {\n      throw \"Source and/or target doesn't know this edge!\";\n    }\n\n    var index = edge.source.edges.indexOf(edge);\n    edge.source.edges.splice(index, 1);\n    index = edge.target.edges.indexOf(edge);\n    edge.target.edges.splice(index, 1);\n\n    // remove edge from owner graph manager's inter-graph edge list\n\n    if (!(edge.source.owner != null && edge.source.owner.getGraphManager() != null)) {\n      throw \"Edge owner graph or owner graph manager is null!\";\n    }\n    if (edge.source.owner.getGraphManager().edges.indexOf(edge) == -1) {\n      throw \"Not in owner graph manager's edge list!\";\n    }\n\n    var index = edge.source.owner.getGraphManager().edges.indexOf(edge);\n    edge.source.owner.getGraphManager().edges.splice(index, 1);\n  }\n};\n\nLGraphManager.prototype.updateBounds = function () {\n  this.rootGraph.updateBounds(true);\n};\n\nLGraphManager.prototype.getGraphs = function () {\n  return this.graphs;\n};\n\nLGraphManager.prototype.getAllNodes = function () {\n  if (this.allNodes == null) {\n    var nodeList = [];\n    var graphs = this.getGraphs();\n    var s = graphs.length;\n    for (var i = 0; i < s; i++) {\n      nodeList = nodeList.concat(graphs[i].getNodes());\n    }\n    this.allNodes = nodeList;\n  }\n  return this.allNodes;\n};\n\nLGraphManager.prototype.resetAllNodes = function () {\n  this.allNodes = null;\n};\n\nLGraphManager.prototype.resetAllEdges = function () {\n  this.allEdges = null;\n};\n\nLGraphManager.prototype.resetAllNodesToApplyGravitation = function () {\n  this.allNodesToApplyGravitation = null;\n};\n\nLGraphManager.prototype.getAllEdges = function () {\n  if (this.allEdges == null) {\n    var edgeList = [];\n    var graphs = this.getGraphs();\n    var s = graphs.length;\n    for (var i = 0; i < graphs.length; i++) {\n      edgeList = edgeList.concat(graphs[i].getEdges());\n    }\n\n    edgeList = edgeList.concat(this.edges);\n\n    this.allEdges = edgeList;\n  }\n  return this.allEdges;\n};\n\nLGraphManager.prototype.getAllNodesToApplyGravitation = function () {\n  return this.allNodesToApplyGravitation;\n};\n\nLGraphManager.prototype.setAllNodesToApplyGravitation = function (nodeList) {\n  if (this.allNodesToApplyGravitation != null) {\n    throw \"assert failed\";\n  }\n\n  this.allNodesToApplyGravitation = nodeList;\n};\n\nLGraphManager.prototype.getRoot = function () {\n  return this.rootGraph;\n};\n\nLGraphManager.prototype.setRootGraph = function (graph) {\n  if (graph.getGraphManager() != this) {\n    throw \"Root not in this graph mgr!\";\n  }\n\n  this.rootGraph = graph;\n  // root graph must have a root node associated with it for convenience\n  if (graph.parent == null) {\n    graph.parent = this.layout.newNode(\"Root node\");\n  }\n};\n\nLGraphManager.prototype.getLayout = function () {\n  return this.layout;\n};\n\nLGraphManager.prototype.isOneAncestorOfOther = function (firstNode, secondNode) {\n  if (!(firstNode != null && secondNode != null)) {\n    throw \"assert failed\";\n  }\n\n  if (firstNode == secondNode) {\n    return true;\n  }\n  // Is second node an ancestor of the first one?\n  var ownerGraph = firstNode.getOwner();\n  var parentNode;\n\n  do {\n    parentNode = ownerGraph.getParent();\n\n    if (parentNode == null) {\n      break;\n    }\n\n    if (parentNode == secondNode) {\n      return true;\n    }\n\n    ownerGraph = parentNode.getOwner();\n    if (ownerGraph == null) {\n      break;\n    }\n  } while (true);\n  // Is first node an ancestor of the second one?\n  ownerGraph = secondNode.getOwner();\n\n  do {\n    parentNode = ownerGraph.getParent();\n\n    if (parentNode == null) {\n      break;\n    }\n\n    if (parentNode == firstNode) {\n      return true;\n    }\n\n    ownerGraph = parentNode.getOwner();\n    if (ownerGraph == null) {\n      break;\n    }\n  } while (true);\n\n  return false;\n};\n\nLGraphManager.prototype.calcLowestCommonAncestors = function () {\n  var edge;\n  var sourceNode;\n  var targetNode;\n  var sourceAncestorGraph;\n  var targetAncestorGraph;\n\n  var edges = this.getAllEdges();\n  var s = edges.length;\n  for (var i = 0; i < s; i++) {\n    edge = edges[i];\n\n    sourceNode = edge.source;\n    targetNode = edge.target;\n    edge.lca = null;\n    edge.sourceInLca = sourceNode;\n    edge.targetInLca = targetNode;\n\n    if (sourceNode == targetNode) {\n      edge.lca = sourceNode.getOwner();\n      continue;\n    }\n\n    sourceAncestorGraph = sourceNode.getOwner();\n\n    while (edge.lca == null) {\n      edge.targetInLca = targetNode;\n      targetAncestorGraph = targetNode.getOwner();\n\n      while (edge.lca == null) {\n        if (targetAncestorGraph == sourceAncestorGraph) {\n          edge.lca = targetAncestorGraph;\n          break;\n        }\n\n        if (targetAncestorGraph == this.rootGraph) {\n          break;\n        }\n\n        if (edge.lca != null) {\n          throw \"assert failed\";\n        }\n        edge.targetInLca = targetAncestorGraph.getParent();\n        targetAncestorGraph = edge.targetInLca.getOwner();\n      }\n\n      if (sourceAncestorGraph == this.rootGraph) {\n        break;\n      }\n\n      if (edge.lca == null) {\n        edge.sourceInLca = sourceAncestorGraph.getParent();\n        sourceAncestorGraph = edge.sourceInLca.getOwner();\n      }\n    }\n\n    if (edge.lca == null) {\n      throw \"assert failed\";\n    }\n  }\n};\n\nLGraphManager.prototype.calcLowestCommonAncestor = function (firstNode, secondNode) {\n  if (firstNode == secondNode) {\n    return firstNode.getOwner();\n  }\n  var firstOwnerGraph = firstNode.getOwner();\n\n  do {\n    if (firstOwnerGraph == null) {\n      break;\n    }\n    var secondOwnerGraph = secondNode.getOwner();\n\n    do {\n      if (secondOwnerGraph == null) {\n        break;\n      }\n\n      if (secondOwnerGraph == firstOwnerGraph) {\n        return secondOwnerGraph;\n      }\n      secondOwnerGraph = secondOwnerGraph.getParent().getOwner();\n    } while (true);\n\n    firstOwnerGraph = firstOwnerGraph.getParent().getOwner();\n  } while (true);\n\n  return firstOwnerGraph;\n};\n\nLGraphManager.prototype.calcInclusionTreeDepths = function (graph, depth) {\n  if (graph == null && depth == null) {\n    graph = this.rootGraph;\n    depth = 1;\n  }\n  var node;\n\n  var nodes = graph.getNodes();\n  var s = nodes.length;\n  for (var i = 0; i < s; i++) {\n    node = nodes[i];\n    node.inclusionTreeDepth = depth;\n\n    if (node.child != null) {\n      this.calcInclusionTreeDepths(node.child, depth + 1);\n    }\n  }\n};\n\nLGraphManager.prototype.includesInvalidEdge = function () {\n  var edge;\n\n  var s = this.edges.length;\n  for (var i = 0; i < s; i++) {\n    edge = this.edges[i];\n\n    if (this.isOneAncestorOfOther(edge.source, edge.target)) {\n      return true;\n    }\n  }\n  return false;\n};\n\nmodule.exports = LGraphManager;\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __nested_webpack_require_38707__) {\n\n\"use strict\";\n\n\nvar LayoutConstants = __nested_webpack_require_38707__(0);\n\nfunction FDLayoutConstants() {}\n\n//FDLayoutConstants inherits static props in LayoutConstants\nfor (var prop in LayoutConstants) {\n  FDLayoutConstants[prop] = LayoutConstants[prop];\n}\n\nFDLayoutConstants.MAX_ITERATIONS = 2500;\n\nFDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;\nFDLayoutConstants.DEFAULT_SPRING_STRENGTH = 0.45;\nFDLayoutConstants.DEFAULT_REPULSION_STRENGTH = 4500.0;\nFDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = 0.4;\nFDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = 1.0;\nFDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = 3.8;\nFDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = 1.5;\nFDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION = true;\nFDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION = true;\nFDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = 0.3;\nFDLayoutConstants.COOLING_ADAPTATION_FACTOR = 0.33;\nFDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT = 1000;\nFDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT = 5000;\nFDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL = 100.0;\nFDLayoutConstants.MAX_NODE_DISPLACEMENT = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL * 3;\nFDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10.0;\nFDLayoutConstants.CONVERGENCE_CHECK_PERIOD = 100;\nFDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = 0.1;\nFDLayoutConstants.MIN_EDGE_LENGTH = 1;\nFDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD = 10;\n\nmodule.exports = FDLayoutConstants;\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports, __nested_webpack_require_40298__) {\n\n\"use strict\";\n\n\n/**\n * This class maintains a list of static geometry related utility methods.\n *\n *\n * Copyright: i-Vis Research Group, Bilkent University, 2007 - present\n */\n\nvar Point = __nested_webpack_require_40298__(12);\n\nfunction IGeometry() {}\n\n/**\n * This method calculates *half* the amount in x and y directions of the two\n * input rectangles needed to separate them keeping their respective\n * positioning, and returns the result in the input array. An input\n * separation buffer added to the amount in both directions. We assume that\n * the two rectangles do intersect.\n */\nIGeometry.calcSeparationAmount = function (rectA, rectB, overlapAmount, separationBuffer) {\n  if (!rectA.intersects(rectB)) {\n    throw \"assert failed\";\n  }\n\n  var directions = new Array(2);\n\n  this.decideDirectionsForOverlappingNodes(rectA, rectB, directions);\n\n  overlapAmount[0] = Math.min(rectA.getRight(), rectB.getRight()) - Math.max(rectA.x, rectB.x);\n  overlapAmount[1] = Math.min(rectA.getBottom(), rectB.getBottom()) - Math.max(rectA.y, rectB.y);\n\n  // update the overlapping amounts for the following cases:\n  if (rectA.getX() <= rectB.getX() && rectA.getRight() >= rectB.getRight()) {\n    /* Case x.1:\n    *\n    * rectA\n    * \t|                       |\n    * \t|        _________      |\n    * \t|        |       |      |\n    * \t|________|_______|______|\n    * \t\t\t |       |\n    *           |       |\n    *        rectB\n    */\n    overlapAmount[0] += Math.min(rectB.getX() - rectA.getX(), rectA.getRight() - rectB.getRight());\n  } else if (rectB.getX() <= rectA.getX() && rectB.getRight() >= rectA.getRight()) {\n    /* Case x.2:\n    *\n    * rectB\n    * \t|                       |\n    * \t|        _________      |\n    * \t|        |       |      |\n    * \t|________|_______|______|\n    * \t\t\t |       |\n    *           |       |\n    *        rectA\n    */\n    overlapAmount[0] += Math.min(rectA.getX() - rectB.getX(), rectB.getRight() - rectA.getRight());\n  }\n  if (rectA.getY() <= rectB.getY() && rectA.getBottom() >= rectB.getBottom()) {\n    /* Case y.1:\n     *          ________ rectA\n     *         |\n     *         |\n     *   ______|____  rectB\n     *         |    |\n     *         |    |\n     *   ______|____|\n     *         |\n     *         |\n     *         |________\n     *\n     */\n    overlapAmount[1] += Math.min(rectB.getY() - rectA.getY(), rectA.getBottom() - rectB.getBottom());\n  } else if (rectB.getY() <= rectA.getY() && rectB.getBottom() >= rectA.getBottom()) {\n    /* Case y.2:\n    *          ________ rectB\n    *         |\n    *         |\n    *   ______|____  rectA\n    *         |    |\n    *         |    |\n    *   ______|____|\n    *         |\n    *         |\n    *         |________\n    *\n    */\n    overlapAmount[1] += Math.min(rectA.getY() - rectB.getY(), rectB.getBottom() - rectA.getBottom());\n  }\n\n  // find slope of the line passes two centers\n  var slope = Math.abs((rectB.getCenterY() - rectA.getCenterY()) / (rectB.getCenterX() - rectA.getCenterX()));\n  // if centers are overlapped\n  if (rectB.getCenterY() === rectA.getCenterY() && rectB.getCenterX() === rectA.getCenterX()) {\n    // assume the slope is 1 (45 degree)\n    slope = 1.0;\n  }\n\n  var moveByY = slope * overlapAmount[0];\n  var moveByX = overlapAmount[1] / slope;\n  if (overlapAmount[0] < moveByX) {\n    moveByX = overlapAmount[0];\n  } else {\n    moveByY = overlapAmount[1];\n  }\n  // return half the amount so that if each rectangle is moved by these\n  // amounts in opposite directions, overlap will be resolved\n  overlapAmount[0] = -1 * directions[0] * (moveByX / 2 + separationBuffer);\n  overlapAmount[1] = -1 * directions[1] * (moveByY / 2 + separationBuffer);\n};\n\n/**\n * This method decides the separation direction of overlapping nodes\n *\n * if directions[0] = -1, then rectA goes left\n * if directions[0] = 1,  then rectA goes right\n * if directions[1] = -1, then rectA goes up\n * if directions[1] = 1,  then rectA goes down\n */\nIGeometry.decideDirectionsForOverlappingNodes = function (rectA, rectB, directions) {\n  if (rectA.getCenterX() < rectB.getCenterX()) {\n    directions[0] = -1;\n  } else {\n    directions[0] = 1;\n  }\n\n  if (rectA.getCenterY() < rectB.getCenterY()) {\n    directions[1] = -1;\n  } else {\n    directions[1] = 1;\n  }\n};\n\n/**\n * This method calculates the intersection (clipping) points of the two\n * input rectangles with line segment defined by the centers of these two\n * rectangles. The clipping points are saved in the input double array and\n * whether or not the two rectangles overlap is returned.\n */\nIGeometry.getIntersection2 = function (rectA, rectB, result) {\n  //result[0-1] will contain clipPoint of rectA, result[2-3] will contain clipPoint of rectB\n  var p1x = rectA.getCenterX();\n  var p1y = rectA.getCenterY();\n  var p2x = rectB.getCenterX();\n  var p2y = rectB.getCenterY();\n\n  //if two rectangles intersect, then clipping points are centers\n  if (rectA.intersects(rectB)) {\n    result[0] = p1x;\n    result[1] = p1y;\n    result[2] = p2x;\n    result[3] = p2y;\n    return true;\n  }\n  //variables for rectA\n  var topLeftAx = rectA.getX();\n  var topLeftAy = rectA.getY();\n  var topRightAx = rectA.getRight();\n  var bottomLeftAx = rectA.getX();\n  var bottomLeftAy = rectA.getBottom();\n  var bottomRightAx = rectA.getRight();\n  var halfWidthA = rectA.getWidthHalf();\n  var halfHeightA = rectA.getHeightHalf();\n  //variables for rectB\n  var topLeftBx = rectB.getX();\n  var topLeftBy = rectB.getY();\n  var topRightBx = rectB.getRight();\n  var bottomLeftBx = rectB.getX();\n  var bottomLeftBy = rectB.getBottom();\n  var bottomRightBx = rectB.getRight();\n  var halfWidthB = rectB.getWidthHalf();\n  var halfHeightB = rectB.getHeightHalf();\n\n  //flag whether clipping points are found\n  var clipPointAFound = false;\n  var clipPointBFound = false;\n\n  // line is vertical\n  if (p1x === p2x) {\n    if (p1y > p2y) {\n      result[0] = p1x;\n      result[1] = topLeftAy;\n      result[2] = p2x;\n      result[3] = bottomLeftBy;\n      return false;\n    } else if (p1y < p2y) {\n      result[0] = p1x;\n      result[1] = bottomLeftAy;\n      result[2] = p2x;\n      result[3] = topLeftBy;\n      return false;\n    } else {\n      //not line, return null;\n    }\n  }\n  // line is horizontal\n  else if (p1y === p2y) {\n      if (p1x > p2x) {\n        result[0] = topLeftAx;\n        result[1] = p1y;\n        result[2] = topRightBx;\n        result[3] = p2y;\n        return false;\n      } else if (p1x < p2x) {\n        result[0] = topRightAx;\n        result[1] = p1y;\n        result[2] = topLeftBx;\n        result[3] = p2y;\n        return false;\n      } else {\n        //not valid line, return null;\n      }\n    } else {\n      //slopes of rectA's and rectB's diagonals\n      var slopeA = rectA.height / rectA.width;\n      var slopeB = rectB.height / rectB.width;\n\n      //slope of line between center of rectA and center of rectB\n      var slopePrime = (p2y - p1y) / (p2x - p1x);\n      var cardinalDirectionA = void 0;\n      var cardinalDirectionB = void 0;\n      var tempPointAx = void 0;\n      var tempPointAy = void 0;\n      var tempPointBx = void 0;\n      var tempPointBy = void 0;\n\n      //determine whether clipping point is the corner of nodeA\n      if (-slopeA === slopePrime) {\n        if (p1x > p2x) {\n          result[0] = bottomLeftAx;\n          result[1] = bottomLeftAy;\n          clipPointAFound = true;\n        } else {\n          result[0] = topRightAx;\n          result[1] = topLeftAy;\n          clipPointAFound = true;\n        }\n      } else if (slopeA === slopePrime) {\n        if (p1x > p2x) {\n          result[0] = topLeftAx;\n          result[1] = topLeftAy;\n          clipPointAFound = true;\n        } else {\n          result[0] = bottomRightAx;\n          result[1] = bottomLeftAy;\n          clipPointAFound = true;\n        }\n      }\n\n      //determine whether clipping point is the corner of nodeB\n      if (-slopeB === slopePrime) {\n        if (p2x > p1x) {\n          result[2] = bottomLeftBx;\n          result[3] = bottomLeftBy;\n          clipPointBFound = true;\n        } else {\n          result[2] = topRightBx;\n          result[3] = topLeftBy;\n          clipPointBFound = true;\n        }\n      } else if (slopeB === slopePrime) {\n        if (p2x > p1x) {\n          result[2] = topLeftBx;\n          result[3] = topLeftBy;\n          clipPointBFound = true;\n        } else {\n          result[2] = bottomRightBx;\n          result[3] = bottomLeftBy;\n          clipPointBFound = true;\n        }\n      }\n\n      //if both clipping points are corners\n      if (clipPointAFound && clipPointBFound) {\n        return false;\n      }\n\n      //determine Cardinal Direction of rectangles\n      if (p1x > p2x) {\n        if (p1y > p2y) {\n          cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 4);\n          cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 2);\n        } else {\n          cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 3);\n          cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 1);\n        }\n      } else {\n        if (p1y > p2y) {\n          cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 1);\n          cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 3);\n        } else {\n          cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 2);\n          cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 4);\n        }\n      }\n      //calculate clipping Point if it is not found before\n      if (!clipPointAFound) {\n        switch (cardinalDirectionA) {\n          case 1:\n            tempPointAy = topLeftAy;\n            tempPointAx = p1x + -halfHeightA / slopePrime;\n            result[0] = tempPointAx;\n            result[1] = tempPointAy;\n            break;\n          case 2:\n            tempPointAx = bottomRightAx;\n            tempPointAy = p1y + halfWidthA * slopePrime;\n            result[0] = tempPointAx;\n            result[1] = tempPointAy;\n            break;\n          case 3:\n            tempPointAy = bottomLeftAy;\n            tempPointAx = p1x + halfHeightA / slopePrime;\n            result[0] = tempPointAx;\n            result[1] = tempPointAy;\n            break;\n          case 4:\n            tempPointAx = bottomLeftAx;\n            tempPointAy = p1y + -halfWidthA * slopePrime;\n            result[0] = tempPointAx;\n            result[1] = tempPointAy;\n            break;\n        }\n      }\n      if (!clipPointBFound) {\n        switch (cardinalDirectionB) {\n          case 1:\n            tempPointBy = topLeftBy;\n            tempPointBx = p2x + -halfHeightB / slopePrime;\n            result[2] = tempPointBx;\n            result[3] = tempPointBy;\n            break;\n          case 2:\n            tempPointBx = bottomRightBx;\n            tempPointBy = p2y + halfWidthB * slopePrime;\n            result[2] = tempPointBx;\n            result[3] = tempPointBy;\n            break;\n          case 3:\n            tempPointBy = bottomLeftBy;\n            tempPointBx = p2x + halfHeightB / slopePrime;\n            result[2] = tempPointBx;\n            result[3] = tempPointBy;\n            break;\n          case 4:\n            tempPointBx = bottomLeftBx;\n            tempPointBy = p2y + -halfWidthB * slopePrime;\n            result[2] = tempPointBx;\n            result[3] = tempPointBy;\n            break;\n        }\n      }\n    }\n  return false;\n};\n\n/**\n * This method returns in which cardinal direction does input point stays\n * 1: North\n * 2: East\n * 3: South\n * 4: West\n */\nIGeometry.getCardinalDirection = function (slope, slopePrime, line) {\n  if (slope > slopePrime) {\n    return line;\n  } else {\n    return 1 + line % 4;\n  }\n};\n\n/**\n * This method calculates the intersection of the two lines defined by\n * point pairs (s1,s2) and (f1,f2).\n */\nIGeometry.getIntersection = function (s1, s2, f1, f2) {\n  if (f2 == null) {\n    return this.getIntersection2(s1, s2, f1);\n  }\n\n  var x1 = s1.x;\n  var y1 = s1.y;\n  var x2 = s2.x;\n  var y2 = s2.y;\n  var x3 = f1.x;\n  var y3 = f1.y;\n  var x4 = f2.x;\n  var y4 = f2.y;\n  var x = void 0,\n      y = void 0; // intersection point\n  var a1 = void 0,\n      a2 = void 0,\n      b1 = void 0,\n      b2 = void 0,\n      c1 = void 0,\n      c2 = void 0; // coefficients of line eqns.\n  var denom = void 0;\n\n  a1 = y2 - y1;\n  b1 = x1 - x2;\n  c1 = x2 * y1 - x1 * y2; // { a1*x + b1*y + c1 = 0 is line 1 }\n\n  a2 = y4 - y3;\n  b2 = x3 - x4;\n  c2 = x4 * y3 - x3 * y4; // { a2*x + b2*y + c2 = 0 is line 2 }\n\n  denom = a1 * b2 - a2 * b1;\n\n  if (denom === 0) {\n    return null;\n  }\n\n  x = (b1 * c2 - b2 * c1) / denom;\n  y = (a2 * c1 - a1 * c2) / denom;\n\n  return new Point(x, y);\n};\n\n/**\n * This method finds and returns the angle of the vector from the + x-axis\n * in clockwise direction (compatible w/ Java coordinate system!).\n */\nIGeometry.angleOfVector = function (Cx, Cy, Nx, Ny) {\n  var C_angle = void 0;\n\n  if (Cx !== Nx) {\n    C_angle = Math.atan((Ny - Cy) / (Nx - Cx));\n\n    if (Nx < Cx) {\n      C_angle += Math.PI;\n    } else if (Ny < Cy) {\n      C_angle += this.TWO_PI;\n    }\n  } else if (Ny < Cy) {\n    C_angle = this.ONE_AND_HALF_PI; // 270 degrees\n  } else {\n    C_angle = this.HALF_PI; // 90 degrees\n  }\n\n  return C_angle;\n};\n\n/**\n * This method checks whether the given two line segments (one with point\n * p1 and p2, the other with point p3 and p4) intersect at a point other\n * than these points.\n */\nIGeometry.doIntersect = function (p1, p2, p3, p4) {\n  var a = p1.x;\n  var b = p1.y;\n  var c = p2.x;\n  var d = p2.y;\n  var p = p3.x;\n  var q = p3.y;\n  var r = p4.x;\n  var s = p4.y;\n  var det = (c - a) * (s - q) - (r - p) * (d - b);\n\n  if (det === 0) {\n    return false;\n  } else {\n    var lambda = ((s - q) * (r - a) + (p - r) * (s - b)) / det;\n    var gamma = ((b - d) * (r - a) + (c - a) * (s - b)) / det;\n    return 0 < lambda && lambda < 1 && 0 < gamma && gamma < 1;\n  }\n};\n\n// -----------------------------------------------------------------------------\n// Section: Class Constants\n// -----------------------------------------------------------------------------\n/**\n * Some useful pre-calculated constants\n */\nIGeometry.HALF_PI = 0.5 * Math.PI;\nIGeometry.ONE_AND_HALF_PI = 1.5 * Math.PI;\nIGeometry.TWO_PI = 2.0 * Math.PI;\nIGeometry.THREE_PI = 3.0 * Math.PI;\n\nmodule.exports = IGeometry;\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction IMath() {}\n\n/**\n * This method returns the sign of the input value.\n */\nIMath.sign = function (value) {\n  if (value > 0) {\n    return 1;\n  } else if (value < 0) {\n    return -1;\n  } else {\n    return 0;\n  }\n};\n\nIMath.floor = function (value) {\n  return value < 0 ? Math.ceil(value) : Math.floor(value);\n};\n\nIMath.ceil = function (value) {\n  return value < 0 ? Math.floor(value) : Math.ceil(value);\n};\n\nmodule.exports = IMath;\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction Integer() {}\n\nInteger.MAX_VALUE = 2147483647;\nInteger.MIN_VALUE = -2147483648;\n\nmodule.exports = Integer;\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar nodeFrom = function nodeFrom(value) {\n  return { value: value, next: null, prev: null };\n};\n\nvar add = function add(prev, node, next, list) {\n  if (prev !== null) {\n    prev.next = node;\n  } else {\n    list.head = node;\n  }\n\n  if (next !== null) {\n    next.prev = node;\n  } else {\n    list.tail = node;\n  }\n\n  node.prev = prev;\n  node.next = next;\n\n  list.length++;\n\n  return node;\n};\n\nvar _remove = function _remove(node, list) {\n  var prev = node.prev,\n      next = node.next;\n\n\n  if (prev !== null) {\n    prev.next = next;\n  } else {\n    list.head = next;\n  }\n\n  if (next !== null) {\n    next.prev = prev;\n  } else {\n    list.tail = prev;\n  }\n\n  node.prev = node.next = null;\n\n  list.length--;\n\n  return node;\n};\n\nvar LinkedList = function () {\n  function LinkedList(vals) {\n    var _this = this;\n\n    _classCallCheck(this, LinkedList);\n\n    this.length = 0;\n    this.head = null;\n    this.tail = null;\n\n    if (vals != null) {\n      vals.forEach(function (v) {\n        return _this.push(v);\n      });\n    }\n  }\n\n  _createClass(LinkedList, [{\n    key: \"size\",\n    value: function size() {\n      return this.length;\n    }\n  }, {\n    key: \"insertBefore\",\n    value: function insertBefore(val, otherNode) {\n      return add(otherNode.prev, nodeFrom(val), otherNode, this);\n    }\n  }, {\n    key: \"insertAfter\",\n    value: function insertAfter(val, otherNode) {\n      return add(otherNode, nodeFrom(val), otherNode.next, this);\n    }\n  }, {\n    key: \"insertNodeBefore\",\n    value: function insertNodeBefore(newNode, otherNode) {\n      return add(otherNode.prev, newNode, otherNode, this);\n    }\n  }, {\n    key: \"insertNodeAfter\",\n    value: function insertNodeAfter(newNode, otherNode) {\n      return add(otherNode, newNode, otherNode.next, this);\n    }\n  }, {\n    key: \"push\",\n    value: function push(val) {\n      return add(this.tail, nodeFrom(val), null, this);\n    }\n  }, {\n    key: \"unshift\",\n    value: function unshift(val) {\n      return add(null, nodeFrom(val), this.head, this);\n    }\n  }, {\n    key: \"remove\",\n    value: function remove(node) {\n      return _remove(node, this);\n    }\n  }, {\n    key: \"pop\",\n    value: function pop() {\n      return _remove(this.tail, this).value;\n    }\n  }, {\n    key: \"popNode\",\n    value: function popNode() {\n      return _remove(this.tail, this);\n    }\n  }, {\n    key: \"shift\",\n    value: function shift() {\n      return _remove(this.head, this).value;\n    }\n  }, {\n    key: \"shiftNode\",\n    value: function shiftNode() {\n      return _remove(this.head, this);\n    }\n  }, {\n    key: \"get_object_at\",\n    value: function get_object_at(index) {\n      if (index <= this.length()) {\n        var i = 1;\n        var current = this.head;\n        while (i < index) {\n          current = current.next;\n          i++;\n        }\n        return current.value;\n      }\n    }\n  }, {\n    key: \"set_object_at\",\n    value: function set_object_at(index, value) {\n      if (index <= this.length()) {\n        var i = 1;\n        var current = this.head;\n        while (i < index) {\n          current = current.next;\n          i++;\n        }\n        current.value = value;\n      }\n    }\n  }]);\n\n  return LinkedList;\n}();\n\nmodule.exports = LinkedList;\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\n/*\r\n *This class is the javascript implementation of the Point.java class in jdk\r\n */\nfunction Point(x, y, p) {\n  this.x = null;\n  this.y = null;\n  if (x == null && y == null && p == null) {\n    this.x = 0;\n    this.y = 0;\n  } else if (typeof x == 'number' && typeof y == 'number' && p == null) {\n    this.x = x;\n    this.y = y;\n  } else if (x.constructor.name == 'Point' && y == null && p == null) {\n    p = x;\n    this.x = p.x;\n    this.y = p.y;\n  }\n}\n\nPoint.prototype.getX = function () {\n  return this.x;\n};\n\nPoint.prototype.getY = function () {\n  return this.y;\n};\n\nPoint.prototype.getLocation = function () {\n  return new Point(this.x, this.y);\n};\n\nPoint.prototype.setLocation = function (x, y, p) {\n  if (x.constructor.name == 'Point' && y == null && p == null) {\n    p = x;\n    this.setLocation(p.x, p.y);\n  } else if (typeof x == 'number' && typeof y == 'number' && p == null) {\n    //if both parameters are integer just move (x,y) location\n    if (parseInt(x) == x && parseInt(y) == y) {\n      this.move(x, y);\n    } else {\n      this.x = Math.floor(x + 0.5);\n      this.y = Math.floor(y + 0.5);\n    }\n  }\n};\n\nPoint.prototype.move = function (x, y) {\n  this.x = x;\n  this.y = y;\n};\n\nPoint.prototype.translate = function (dx, dy) {\n  this.x += dx;\n  this.y += dy;\n};\n\nPoint.prototype.equals = function (obj) {\n  if (obj.constructor.name == \"Point\") {\n    var pt = obj;\n    return this.x == pt.x && this.y == pt.y;\n  }\n  return this == obj;\n};\n\nPoint.prototype.toString = function () {\n  return new Point().constructor.name + \"[x=\" + this.x + \",y=\" + this.y + \"]\";\n};\n\nmodule.exports = Point;\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction RectangleD(x, y, width, height) {\n  this.x = 0;\n  this.y = 0;\n  this.width = 0;\n  this.height = 0;\n\n  if (x != null && y != null && width != null && height != null) {\n    this.x = x;\n    this.y = y;\n    this.width = width;\n    this.height = height;\n  }\n}\n\nRectangleD.prototype.getX = function () {\n  return this.x;\n};\n\nRectangleD.prototype.setX = function (x) {\n  this.x = x;\n};\n\nRectangleD.prototype.getY = function () {\n  return this.y;\n};\n\nRectangleD.prototype.setY = function (y) {\n  this.y = y;\n};\n\nRectangleD.prototype.getWidth = function () {\n  return this.width;\n};\n\nRectangleD.prototype.setWidth = function (width) {\n  this.width = width;\n};\n\nRectangleD.prototype.getHeight = function () {\n  return this.height;\n};\n\nRectangleD.prototype.setHeight = function (height) {\n  this.height = height;\n};\n\nRectangleD.prototype.getRight = function () {\n  return this.x + this.width;\n};\n\nRectangleD.prototype.getBottom = function () {\n  return this.y + this.height;\n};\n\nRectangleD.prototype.intersects = function (a) {\n  if (this.getRight() < a.x) {\n    return false;\n  }\n\n  if (this.getBottom() < a.y) {\n    return false;\n  }\n\n  if (a.getRight() < this.x) {\n    return false;\n  }\n\n  if (a.getBottom() < this.y) {\n    return false;\n  }\n\n  return true;\n};\n\nRectangleD.prototype.getCenterX = function () {\n  return this.x + this.width / 2;\n};\n\nRectangleD.prototype.getMinX = function () {\n  return this.getX();\n};\n\nRectangleD.prototype.getMaxX = function () {\n  return this.getX() + this.width;\n};\n\nRectangleD.prototype.getCenterY = function () {\n  return this.y + this.height / 2;\n};\n\nRectangleD.prototype.getMinY = function () {\n  return this.getY();\n};\n\nRectangleD.prototype.getMaxY = function () {\n  return this.getY() + this.height;\n};\n\nRectangleD.prototype.getWidthHalf = function () {\n  return this.width / 2;\n};\n\nRectangleD.prototype.getHeightHalf = function () {\n  return this.height / 2;\n};\n\nmodule.exports = RectangleD;\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction UniqueIDGeneretor() {}\n\nUniqueIDGeneretor.lastID = 0;\n\nUniqueIDGeneretor.createID = function (obj) {\n  if (UniqueIDGeneretor.isPrimitive(obj)) {\n    return obj;\n  }\n  if (obj.uniqueID != null) {\n    return obj.uniqueID;\n  }\n  obj.uniqueID = UniqueIDGeneretor.getString();\n  UniqueIDGeneretor.lastID++;\n  return obj.uniqueID;\n};\n\nUniqueIDGeneretor.getString = function (id) {\n  if (id == null) id = UniqueIDGeneretor.lastID;\n  return \"Object#\" + id + \"\";\n};\n\nUniqueIDGeneretor.isPrimitive = function (arg) {\n  var type = typeof arg === \"undefined\" ? \"undefined\" : _typeof(arg);\n  return arg == null || type != \"object\" && type != \"function\";\n};\n\nmodule.exports = UniqueIDGeneretor;\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __nested_webpack_require_64072__) {\n\n\"use strict\";\n\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar LayoutConstants = __nested_webpack_require_64072__(0);\nvar LGraphManager = __nested_webpack_require_64072__(6);\nvar LNode = __nested_webpack_require_64072__(3);\nvar LEdge = __nested_webpack_require_64072__(1);\nvar LGraph = __nested_webpack_require_64072__(5);\nvar PointD = __nested_webpack_require_64072__(4);\nvar Transform = __nested_webpack_require_64072__(17);\nvar Emitter = __nested_webpack_require_64072__(27);\n\nfunction Layout(isRemoteUse) {\n  Emitter.call(this);\n\n  //Layout Quality: 0:draft, 1:default, 2:proof\n  this.layoutQuality = LayoutConstants.QUALITY;\n  //Whether layout should create bendpoints as needed or not\n  this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;\n  //Whether layout should be incremental or not\n  this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;\n  //Whether we animate from before to after layout node positions\n  this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;\n  //Whether we animate the layout process or not\n  this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;\n  //Number iterations that should be done between two successive animations\n  this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;\n  /**\r\n   * Whether or not leaf nodes (non-compound nodes) are of uniform sizes. When\r\n   * they are, both spring and repulsion forces between two leaf nodes can be\r\n   * calculated without the expensive clipping point calculations, resulting\r\n   * in major speed-up.\r\n   */\n  this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;\n  /**\r\n   * This is used for creation of bendpoints by using dummy nodes and edges.\r\n   * Maps an LEdge to its dummy bendpoint path.\r\n   */\n  this.edgeToDummyNodes = new Map();\n  this.graphManager = new LGraphManager(this);\n  this.isLayoutFinished = false;\n  this.isSubLayout = false;\n  this.isRemoteUse = false;\n\n  if (isRemoteUse != null) {\n    this.isRemoteUse = isRemoteUse;\n  }\n}\n\nLayout.RANDOM_SEED = 1;\n\nLayout.prototype = Object.create(Emitter.prototype);\n\nLayout.prototype.getGraphManager = function () {\n  return this.graphManager;\n};\n\nLayout.prototype.getAllNodes = function () {\n  return this.graphManager.getAllNodes();\n};\n\nLayout.prototype.getAllEdges = function () {\n  return this.graphManager.getAllEdges();\n};\n\nLayout.prototype.getAllNodesToApplyGravitation = function () {\n  return this.graphManager.getAllNodesToApplyGravitation();\n};\n\nLayout.prototype.newGraphManager = function () {\n  var gm = new LGraphManager(this);\n  this.graphManager = gm;\n  return gm;\n};\n\nLayout.prototype.newGraph = function (vGraph) {\n  return new LGraph(null, this.graphManager, vGraph);\n};\n\nLayout.prototype.newNode = function (vNode) {\n  return new LNode(this.graphManager, vNode);\n};\n\nLayout.prototype.newEdge = function (vEdge) {\n  return new LEdge(null, null, vEdge);\n};\n\nLayout.prototype.checkLayoutSuccess = function () {\n  return this.graphManager.getRoot() == null || this.graphManager.getRoot().getNodes().length == 0 || this.graphManager.includesInvalidEdge();\n};\n\nLayout.prototype.runLayout = function () {\n  this.isLayoutFinished = false;\n\n  if (this.tilingPreLayout) {\n    this.tilingPreLayout();\n  }\n\n  this.initParameters();\n  var isLayoutSuccessfull;\n\n  if (this.checkLayoutSuccess()) {\n    isLayoutSuccessfull = false;\n  } else {\n    isLayoutSuccessfull = this.layout();\n  }\n\n  if (LayoutConstants.ANIMATE === 'during') {\n    // If this is a 'during' layout animation. Layout is not finished yet. \n    // We need to perform these in index.js when layout is really finished.\n    return false;\n  }\n\n  if (isLayoutSuccessfull) {\n    if (!this.isSubLayout) {\n      this.doPostLayout();\n    }\n  }\n\n  if (this.tilingPostLayout) {\n    this.tilingPostLayout();\n  }\n\n  this.isLayoutFinished = true;\n\n  return isLayoutSuccessfull;\n};\n\n/**\r\n * This method performs the operations required after layout.\r\n */\nLayout.prototype.doPostLayout = function () {\n  //assert !isSubLayout : \"Should not be called on sub-layout!\";\n  // Propagate geometric changes to v-level objects\n  if (!this.incremental) {\n    this.transform();\n  }\n  this.update();\n};\n\n/**\r\n * This method updates the geometry of the target graph according to\r\n * calculated layout.\r\n */\nLayout.prototype.update2 = function () {\n  // update bend points\n  if (this.createBendsAsNeeded) {\n    this.createBendpointsFromDummyNodes();\n\n    // reset all edges, since the topology has changed\n    this.graphManager.resetAllEdges();\n  }\n\n  // perform edge, node and root updates if layout is not called\n  // remotely\n  if (!this.isRemoteUse) {\n    // update all edges\n    var edge;\n    var allEdges = this.graphManager.getAllEdges();\n    for (var i = 0; i < allEdges.length; i++) {\n      edge = allEdges[i];\n      //      this.update(edge);\n    }\n\n    // recursively update nodes\n    var node;\n    var nodes = this.graphManager.getRoot().getNodes();\n    for (var i = 0; i < nodes.length; i++) {\n      node = nodes[i];\n      //      this.update(node);\n    }\n\n    // update root graph\n    this.update(this.graphManager.getRoot());\n  }\n};\n\nLayout.prototype.update = function (obj) {\n  if (obj == null) {\n    this.update2();\n  } else if (obj instanceof LNode) {\n    var node = obj;\n    if (node.getChild() != null) {\n      // since node is compound, recursively update child nodes\n      var nodes = node.getChild().getNodes();\n      for (var i = 0; i < nodes.length; i++) {\n        update(nodes[i]);\n      }\n    }\n\n    // if the l-level node is associated with a v-level graph object,\n    // then it is assumed that the v-level node implements the\n    // interface Updatable.\n    if (node.vGraphObject != null) {\n      // cast to Updatable without any type check\n      var vNode = node.vGraphObject;\n\n      // call the update method of the interface\n      vNode.update(node);\n    }\n  } else if (obj instanceof LEdge) {\n    var edge = obj;\n    // if the l-level edge is associated with a v-level graph object,\n    // then it is assumed that the v-level edge implements the\n    // interface Updatable.\n\n    if (edge.vGraphObject != null) {\n      // cast to Updatable without any type check\n      var vEdge = edge.vGraphObject;\n\n      // call the update method of the interface\n      vEdge.update(edge);\n    }\n  } else if (obj instanceof LGraph) {\n    var graph = obj;\n    // if the l-level graph is associated with a v-level graph object,\n    // then it is assumed that the v-level object implements the\n    // interface Updatable.\n\n    if (graph.vGraphObject != null) {\n      // cast to Updatable without any type check\n      var vGraph = graph.vGraphObject;\n\n      // call the update method of the interface\n      vGraph.update(graph);\n    }\n  }\n};\n\n/**\r\n * This method is used to set all layout parameters to default values\r\n * determined at compile time.\r\n */\nLayout.prototype.initParameters = function () {\n  if (!this.isSubLayout) {\n    this.layoutQuality = LayoutConstants.QUALITY;\n    this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;\n    this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;\n    this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;\n    this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;\n    this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;\n    this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;\n  }\n\n  if (this.animationDuringLayout) {\n    this.animationOnLayout = false;\n  }\n};\n\nLayout.prototype.transform = function (newLeftTop) {\n  if (newLeftTop == undefined) {\n    this.transform(new PointD(0, 0));\n  } else {\n    // create a transformation object (from Eclipse to layout). When an\n    // inverse transform is applied, we get upper-left coordinate of the\n    // drawing or the root graph at given input coordinate (some margins\n    // already included in calculation of left-top).\n\n    var trans = new Transform();\n    var leftTop = this.graphManager.getRoot().updateLeftTop();\n\n    if (leftTop != null) {\n      trans.setWorldOrgX(newLeftTop.x);\n      trans.setWorldOrgY(newLeftTop.y);\n\n      trans.setDeviceOrgX(leftTop.x);\n      trans.setDeviceOrgY(leftTop.y);\n\n      var nodes = this.getAllNodes();\n      var node;\n\n      for (var i = 0; i < nodes.length; i++) {\n        node = nodes[i];\n        node.transform(trans);\n      }\n    }\n  }\n};\n\nLayout.prototype.positionNodesRandomly = function (graph) {\n\n  if (graph == undefined) {\n    //assert !this.incremental;\n    this.positionNodesRandomly(this.getGraphManager().getRoot());\n    this.getGraphManager().getRoot().updateBounds(true);\n  } else {\n    var lNode;\n    var childGraph;\n\n    var nodes = graph.getNodes();\n    for (var i = 0; i < nodes.length; i++) {\n      lNode = nodes[i];\n      childGraph = lNode.getChild();\n\n      if (childGraph == null) {\n        lNode.scatter();\n      } else if (childGraph.getNodes().length == 0) {\n        lNode.scatter();\n      } else {\n        this.positionNodesRandomly(childGraph);\n        lNode.updateBounds();\n      }\n    }\n  }\n};\n\n/**\r\n * This method returns a list of trees where each tree is represented as a\r\n * list of l-nodes. The method returns a list of size 0 when:\r\n * - The graph is not flat or\r\n * - One of the component(s) of the graph is not a tree.\r\n */\nLayout.prototype.getFlatForest = function () {\n  var flatForest = [];\n  var isForest = true;\n\n  // Quick reference for all nodes in the graph manager associated with\n  // this layout. The list should not be changed.\n  var allNodes = this.graphManager.getRoot().getNodes();\n\n  // First be sure that the graph is flat\n  var isFlat = true;\n\n  for (var i = 0; i < allNodes.length; i++) {\n    if (allNodes[i].getChild() != null) {\n      isFlat = false;\n    }\n  }\n\n  // Return empty forest if the graph is not flat.\n  if (!isFlat) {\n    return flatForest;\n  }\n\n  // Run BFS for each component of the graph.\n\n  var visited = new Set();\n  var toBeVisited = [];\n  var parents = new Map();\n  var unProcessedNodes = [];\n\n  unProcessedNodes = unProcessedNodes.concat(allNodes);\n\n  // Each iteration of this loop finds a component of the graph and\n  // decides whether it is a tree or not. If it is a tree, adds it to the\n  // forest and continued with the next component.\n\n  while (unProcessedNodes.length > 0 && isForest) {\n    toBeVisited.push(unProcessedNodes[0]);\n\n    // Start the BFS. Each iteration of this loop visits a node in a\n    // BFS manner.\n    while (toBeVisited.length > 0 && isForest) {\n      //pool operation\n      var currentNode = toBeVisited[0];\n      toBeVisited.splice(0, 1);\n      visited.add(currentNode);\n\n      // Traverse all neighbors of this node\n      var neighborEdges = currentNode.getEdges();\n\n      for (var i = 0; i < neighborEdges.length; i++) {\n        var currentNeighbor = neighborEdges[i].getOtherEnd(currentNode);\n\n        // If BFS is not growing from this neighbor.\n        if (parents.get(currentNode) != currentNeighbor) {\n          // We haven't previously visited this neighbor.\n          if (!visited.has(currentNeighbor)) {\n            toBeVisited.push(currentNeighbor);\n            parents.set(currentNeighbor, currentNode);\n          }\n          // Since we have previously visited this neighbor and\n          // this neighbor is not parent of currentNode, given\n          // graph contains a component that is not tree, hence\n          // it is not a forest.\n          else {\n              isForest = false;\n              break;\n            }\n        }\n      }\n    }\n\n    // The graph contains a component that is not a tree. Empty\n    // previously found trees. The method will end.\n    if (!isForest) {\n      flatForest = [];\n    }\n    // Save currently visited nodes as a tree in our forest. Reset\n    // visited and parents lists. Continue with the next component of\n    // the graph, if any.\n    else {\n        var temp = [].concat(_toConsumableArray(visited));\n        flatForest.push(temp);\n        //flatForest = flatForest.concat(temp);\n        //unProcessedNodes.removeAll(visited);\n        for (var i = 0; i < temp.length; i++) {\n          var value = temp[i];\n          var index = unProcessedNodes.indexOf(value);\n          if (index > -1) {\n            unProcessedNodes.splice(index, 1);\n          }\n        }\n        visited = new Set();\n        parents = new Map();\n      }\n  }\n\n  return flatForest;\n};\n\n/**\r\n * This method creates dummy nodes (an l-level node with minimal dimensions)\r\n * for the given edge (one per bendpoint). The existing l-level structure\r\n * is updated accordingly.\r\n */\nLayout.prototype.createDummyNodesForBendpoints = function (edge) {\n  var dummyNodes = [];\n  var prev = edge.source;\n\n  var graph = this.graphManager.calcLowestCommonAncestor(edge.source, edge.target);\n\n  for (var i = 0; i < edge.bendpoints.length; i++) {\n    // create new dummy node\n    var dummyNode = this.newNode(null);\n    dummyNode.setRect(new Point(0, 0), new Dimension(1, 1));\n\n    graph.add(dummyNode);\n\n    // create new dummy edge between prev and dummy node\n    var dummyEdge = this.newEdge(null);\n    this.graphManager.add(dummyEdge, prev, dummyNode);\n\n    dummyNodes.add(dummyNode);\n    prev = dummyNode;\n  }\n\n  var dummyEdge = this.newEdge(null);\n  this.graphManager.add(dummyEdge, prev, edge.target);\n\n  this.edgeToDummyNodes.set(edge, dummyNodes);\n\n  // remove real edge from graph manager if it is inter-graph\n  if (edge.isInterGraph()) {\n    this.graphManager.remove(edge);\n  }\n  // else, remove the edge from the current graph\n  else {\n      graph.remove(edge);\n    }\n\n  return dummyNodes;\n};\n\n/**\r\n * This method creates bendpoints for edges from the dummy nodes\r\n * at l-level.\r\n */\nLayout.prototype.createBendpointsFromDummyNodes = function () {\n  var edges = [];\n  edges = edges.concat(this.graphManager.getAllEdges());\n  edges = [].concat(_toConsumableArray(this.edgeToDummyNodes.keys())).concat(edges);\n\n  for (var k = 0; k < edges.length; k++) {\n    var lEdge = edges[k];\n\n    if (lEdge.bendpoints.length > 0) {\n      var path = this.edgeToDummyNodes.get(lEdge);\n\n      for (var i = 0; i < path.length; i++) {\n        var dummyNode = path[i];\n        var p = new PointD(dummyNode.getCenterX(), dummyNode.getCenterY());\n\n        // update bendpoint's location according to dummy node\n        var ebp = lEdge.bendpoints.get(i);\n        ebp.x = p.x;\n        ebp.y = p.y;\n\n        // remove the dummy node, dummy edges incident with this\n        // dummy node is also removed (within the remove method)\n        dummyNode.getOwner().remove(dummyNode);\n      }\n\n      // add the real edge to graph\n      this.graphManager.add(lEdge, lEdge.source, lEdge.target);\n    }\n  }\n};\n\nLayout.transform = function (sliderValue, defaultValue, minDiv, maxMul) {\n  if (minDiv != undefined && maxMul != undefined) {\n    var value = defaultValue;\n\n    if (sliderValue <= 50) {\n      var minValue = defaultValue / minDiv;\n      value -= (defaultValue - minValue) / 50 * (50 - sliderValue);\n    } else {\n      var maxValue = defaultValue * maxMul;\n      value += (maxValue - defaultValue) / 50 * (sliderValue - 50);\n    }\n\n    return value;\n  } else {\n    var a, b;\n\n    if (sliderValue <= 50) {\n      a = 9.0 * defaultValue / 500.0;\n      b = defaultValue / 10.0;\n    } else {\n      a = 9.0 * defaultValue / 50.0;\n      b = -8 * defaultValue;\n    }\n\n    return a * sliderValue + b;\n  }\n};\n\n/**\r\n * This method finds and returns the center of the given nodes, assuming\r\n * that the given nodes form a tree in themselves.\r\n */\nLayout.findCenterOfTree = function (nodes) {\n  var list = [];\n  list = list.concat(nodes);\n\n  var removedNodes = [];\n  var remainingDegrees = new Map();\n  var foundCenter = false;\n  var centerNode = null;\n\n  if (list.length == 1 || list.length == 2) {\n    foundCenter = true;\n    centerNode = list[0];\n  }\n\n  for (var i = 0; i < list.length; i++) {\n    var node = list[i];\n    var degree = node.getNeighborsList().size;\n    remainingDegrees.set(node, node.getNeighborsList().size);\n\n    if (degree == 1) {\n      removedNodes.push(node);\n    }\n  }\n\n  var tempList = [];\n  tempList = tempList.concat(removedNodes);\n\n  while (!foundCenter) {\n    var tempList2 = [];\n    tempList2 = tempList2.concat(tempList);\n    tempList = [];\n\n    for (var i = 0; i < list.length; i++) {\n      var node = list[i];\n\n      var index = list.indexOf(node);\n      if (index >= 0) {\n        list.splice(index, 1);\n      }\n\n      var neighbours = node.getNeighborsList();\n\n      neighbours.forEach(function (neighbour) {\n        if (removedNodes.indexOf(neighbour) < 0) {\n          var otherDegree = remainingDegrees.get(neighbour);\n          var newDegree = otherDegree - 1;\n\n          if (newDegree == 1) {\n            tempList.push(neighbour);\n          }\n\n          remainingDegrees.set(neighbour, newDegree);\n        }\n      });\n    }\n\n    removedNodes = removedNodes.concat(tempList);\n\n    if (list.length == 1 || list.length == 2) {\n      foundCenter = true;\n      centerNode = list[0];\n    }\n  }\n\n  return centerNode;\n};\n\n/**\r\n * During the coarsening process, this layout may be referenced by two graph managers\r\n * this setter function grants access to change the currently being used graph manager\r\n */\nLayout.prototype.setGraphManager = function (gm) {\n  this.graphManager = gm;\n};\n\nmodule.exports = Layout;\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction RandomSeed() {}\n// adapted from: https://stackoverflow.com/a/19303725\nRandomSeed.seed = 1;\nRandomSeed.x = 0;\n\nRandomSeed.nextDouble = function () {\n  RandomSeed.x = Math.sin(RandomSeed.seed++) * 10000;\n  return RandomSeed.x - Math.floor(RandomSeed.x);\n};\n\nmodule.exports = RandomSeed;\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __nested_webpack_require_81860__) {\n\n\"use strict\";\n\n\nvar PointD = __nested_webpack_require_81860__(4);\n\nfunction Transform(x, y) {\n  this.lworldOrgX = 0.0;\n  this.lworldOrgY = 0.0;\n  this.ldeviceOrgX = 0.0;\n  this.ldeviceOrgY = 0.0;\n  this.lworldExtX = 1.0;\n  this.lworldExtY = 1.0;\n  this.ldeviceExtX = 1.0;\n  this.ldeviceExtY = 1.0;\n}\n\nTransform.prototype.getWorldOrgX = function () {\n  return this.lworldOrgX;\n};\n\nTransform.prototype.setWorldOrgX = function (wox) {\n  this.lworldOrgX = wox;\n};\n\nTransform.prototype.getWorldOrgY = function () {\n  return this.lworldOrgY;\n};\n\nTransform.prototype.setWorldOrgY = function (woy) {\n  this.lworldOrgY = woy;\n};\n\nTransform.prototype.getWorldExtX = function () {\n  return this.lworldExtX;\n};\n\nTransform.prototype.setWorldExtX = function (wex) {\n  this.lworldExtX = wex;\n};\n\nTransform.prototype.getWorldExtY = function () {\n  return this.lworldExtY;\n};\n\nTransform.prototype.setWorldExtY = function (wey) {\n  this.lworldExtY = wey;\n};\n\n/* Device related */\n\nTransform.prototype.getDeviceOrgX = function () {\n  return this.ldeviceOrgX;\n};\n\nTransform.prototype.setDeviceOrgX = function (dox) {\n  this.ldeviceOrgX = dox;\n};\n\nTransform.prototype.getDeviceOrgY = function () {\n  return this.ldeviceOrgY;\n};\n\nTransform.prototype.setDeviceOrgY = function (doy) {\n  this.ldeviceOrgY = doy;\n};\n\nTransform.prototype.getDeviceExtX = function () {\n  return this.ldeviceExtX;\n};\n\nTransform.prototype.setDeviceExtX = function (dex) {\n  this.ldeviceExtX = dex;\n};\n\nTransform.prototype.getDeviceExtY = function () {\n  return this.ldeviceExtY;\n};\n\nTransform.prototype.setDeviceExtY = function (dey) {\n  this.ldeviceExtY = dey;\n};\n\nTransform.prototype.transformX = function (x) {\n  var xDevice = 0.0;\n  var worldExtX = this.lworldExtX;\n  if (worldExtX != 0.0) {\n    xDevice = this.ldeviceOrgX + (x - this.lworldOrgX) * this.ldeviceExtX / worldExtX;\n  }\n\n  return xDevice;\n};\n\nTransform.prototype.transformY = function (y) {\n  var yDevice = 0.0;\n  var worldExtY = this.lworldExtY;\n  if (worldExtY != 0.0) {\n    yDevice = this.ldeviceOrgY + (y - this.lworldOrgY) * this.ldeviceExtY / worldExtY;\n  }\n\n  return yDevice;\n};\n\nTransform.prototype.inverseTransformX = function (x) {\n  var xWorld = 0.0;\n  var deviceExtX = this.ldeviceExtX;\n  if (deviceExtX != 0.0) {\n    xWorld = this.lworldOrgX + (x - this.ldeviceOrgX) * this.lworldExtX / deviceExtX;\n  }\n\n  return xWorld;\n};\n\nTransform.prototype.inverseTransformY = function (y) {\n  var yWorld = 0.0;\n  var deviceExtY = this.ldeviceExtY;\n  if (deviceExtY != 0.0) {\n    yWorld = this.lworldOrgY + (y - this.ldeviceOrgY) * this.lworldExtY / deviceExtY;\n  }\n  return yWorld;\n};\n\nTransform.prototype.inverseTransformPoint = function (inPoint) {\n  var outPoint = new PointD(this.inverseTransformX(inPoint.x), this.inverseTransformY(inPoint.y));\n  return outPoint;\n};\n\nmodule.exports = Transform;\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __nested_webpack_require_84747__) {\n\n\"use strict\";\n\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar Layout = __nested_webpack_require_84747__(15);\nvar FDLayoutConstants = __nested_webpack_require_84747__(7);\nvar LayoutConstants = __nested_webpack_require_84747__(0);\nvar IGeometry = __nested_webpack_require_84747__(8);\nvar IMath = __nested_webpack_require_84747__(9);\n\nfunction FDLayout() {\n  Layout.call(this);\n\n  this.useSmartIdealEdgeLengthCalculation = FDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;\n  this.idealEdgeLength = FDLayoutConstants.DEFAULT_EDGE_LENGTH;\n  this.springConstant = FDLayoutConstants.DEFAULT_SPRING_STRENGTH;\n  this.repulsionConstant = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH;\n  this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;\n  this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;\n  this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;\n  this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;\n  this.displacementThresholdPerNode = 3.0 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;\n  this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;\n  this.initialCoolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;\n  this.totalDisplacement = 0.0;\n  this.oldTotalDisplacement = 0.0;\n  this.maxIterations = FDLayoutConstants.MAX_ITERATIONS;\n}\n\nFDLayout.prototype = Object.create(Layout.prototype);\n\nfor (var prop in Layout) {\n  FDLayout[prop] = Layout[prop];\n}\n\nFDLayout.prototype.initParameters = function () {\n  Layout.prototype.initParameters.call(this, arguments);\n\n  this.totalIterations = 0;\n  this.notAnimatedIterations = 0;\n\n  this.useFRGridVariant = FDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION;\n\n  this.grid = [];\n};\n\nFDLayout.prototype.calcIdealEdgeLengths = function () {\n  var edge;\n  var lcaDepth;\n  var source;\n  var target;\n  var sizeOfSourceInLca;\n  var sizeOfTargetInLca;\n\n  var allEdges = this.getGraphManager().getAllEdges();\n  for (var i = 0; i < allEdges.length; i++) {\n    edge = allEdges[i];\n\n    edge.idealLength = this.idealEdgeLength;\n\n    if (edge.isInterGraph) {\n      source = edge.getSource();\n      target = edge.getTarget();\n\n      sizeOfSourceInLca = edge.getSourceInLca().getEstimatedSize();\n      sizeOfTargetInLca = edge.getTargetInLca().getEstimatedSize();\n\n      if (this.useSmartIdealEdgeLengthCalculation) {\n        edge.idealLength += sizeOfSourceInLca + sizeOfTargetInLca - 2 * LayoutConstants.SIMPLE_NODE_SIZE;\n      }\n\n      lcaDepth = edge.getLca().getInclusionTreeDepth();\n\n      edge.idealLength += FDLayoutConstants.DEFAULT_EDGE_LENGTH * FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR * (source.getInclusionTreeDepth() + target.getInclusionTreeDepth() - 2 * lcaDepth);\n    }\n  }\n};\n\nFDLayout.prototype.initSpringEmbedder = function () {\n\n  var s = this.getAllNodes().length;\n  if (this.incremental) {\n    if (s > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {\n      this.coolingFactor = Math.max(this.coolingFactor * FDLayoutConstants.COOLING_ADAPTATION_FACTOR, this.coolingFactor - (s - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * this.coolingFactor * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));\n    }\n    this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL;\n  } else {\n    if (s > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {\n      this.coolingFactor = Math.max(FDLayoutConstants.COOLING_ADAPTATION_FACTOR, 1.0 - (s - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));\n    } else {\n      this.coolingFactor = 1.0;\n    }\n    this.initialCoolingFactor = this.coolingFactor;\n    this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT;\n  }\n\n  this.maxIterations = Math.max(this.getAllNodes().length * 5, this.maxIterations);\n\n  this.totalDisplacementThreshold = this.displacementThresholdPerNode * this.getAllNodes().length;\n\n  this.repulsionRange = this.calcRepulsionRange();\n};\n\nFDLayout.prototype.calcSpringForces = function () {\n  var lEdges = this.getAllEdges();\n  var edge;\n\n  for (var i = 0; i < lEdges.length; i++) {\n    edge = lEdges[i];\n\n    this.calcSpringForce(edge, edge.idealLength);\n  }\n};\n\nFDLayout.prototype.calcRepulsionForces = function () {\n  var gridUpdateAllowed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;\n  var forceToNodeSurroundingUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n  var i, j;\n  var nodeA, nodeB;\n  var lNodes = this.getAllNodes();\n  var processedNodeSet;\n\n  if (this.useFRGridVariant) {\n    if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed) {\n      this.updateGrid();\n    }\n\n    processedNodeSet = new Set();\n\n    // calculate repulsion forces between each nodes and its surrounding\n    for (i = 0; i < lNodes.length; i++) {\n      nodeA = lNodes[i];\n      this.calculateRepulsionForceOfANode(nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate);\n      processedNodeSet.add(nodeA);\n    }\n  } else {\n    for (i = 0; i < lNodes.length; i++) {\n      nodeA = lNodes[i];\n\n      for (j = i + 1; j < lNodes.length; j++) {\n        nodeB = lNodes[j];\n\n        // If both nodes are not members of the same graph, skip.\n        if (nodeA.getOwner() != nodeB.getOwner()) {\n          continue;\n        }\n\n        this.calcRepulsionForce(nodeA, nodeB);\n      }\n    }\n  }\n};\n\nFDLayout.prototype.calcGravitationalForces = function () {\n  var node;\n  var lNodes = this.getAllNodesToApplyGravitation();\n\n  for (var i = 0; i < lNodes.length; i++) {\n    node = lNodes[i];\n    this.calcGravitationalForce(node);\n  }\n};\n\nFDLayout.prototype.moveNodes = function () {\n  var lNodes = this.getAllNodes();\n  var node;\n\n  for (var i = 0; i < lNodes.length; i++) {\n    node = lNodes[i];\n    node.move();\n  }\n};\n\nFDLayout.prototype.calcSpringForce = function (edge, idealLength) {\n  var sourceNode = edge.getSource();\n  var targetNode = edge.getTarget();\n\n  var length;\n  var springForce;\n  var springForceX;\n  var springForceY;\n\n  // Update edge length\n  if (this.uniformLeafNodeSizes && sourceNode.getChild() == null && targetNode.getChild() == null) {\n    edge.updateLengthSimple();\n  } else {\n    edge.updateLength();\n\n    if (edge.isOverlapingSourceAndTarget) {\n      return;\n    }\n  }\n\n  length = edge.getLength();\n\n  if (length == 0) return;\n\n  // Calculate spring forces\n  springForce = this.springConstant * (length - idealLength);\n\n  // Project force onto x and y axes\n  springForceX = springForce * (edge.lengthX / length);\n  springForceY = springForce * (edge.lengthY / length);\n\n  // Apply forces on the end nodes\n  sourceNode.springForceX += springForceX;\n  sourceNode.springForceY += springForceY;\n  targetNode.springForceX -= springForceX;\n  targetNode.springForceY -= springForceY;\n};\n\nFDLayout.prototype.calcRepulsionForce = function (nodeA, nodeB) {\n  var rectA = nodeA.getRect();\n  var rectB = nodeB.getRect();\n  var overlapAmount = new Array(2);\n  var clipPoints = new Array(4);\n  var distanceX;\n  var distanceY;\n  var distanceSquared;\n  var distance;\n  var repulsionForce;\n  var repulsionForceX;\n  var repulsionForceY;\n\n  if (rectA.intersects(rectB)) // two nodes overlap\n    {\n      // calculate separation amount in x and y directions\n      IGeometry.calcSeparationAmount(rectA, rectB, overlapAmount, FDLayoutConstants.DEFAULT_EDGE_LENGTH / 2.0);\n\n      repulsionForceX = 2 * overlapAmount[0];\n      repulsionForceY = 2 * overlapAmount[1];\n\n      var childrenConstant = nodeA.noOfChildren * nodeB.noOfChildren / (nodeA.noOfChildren + nodeB.noOfChildren);\n\n      // Apply forces on the two nodes\n      nodeA.repulsionForceX -= childrenConstant * repulsionForceX;\n      nodeA.repulsionForceY -= childrenConstant * repulsionForceY;\n      nodeB.repulsionForceX += childrenConstant * repulsionForceX;\n      nodeB.repulsionForceY += childrenConstant * repulsionForceY;\n    } else // no overlap\n    {\n      // calculate distance\n\n      if (this.uniformLeafNodeSizes && nodeA.getChild() == null && nodeB.getChild() == null) // simply base repulsion on distance of node centers\n        {\n          distanceX = rectB.getCenterX() - rectA.getCenterX();\n          distanceY = rectB.getCenterY() - rectA.getCenterY();\n        } else // use clipping points\n        {\n          IGeometry.getIntersection(rectA, rectB, clipPoints);\n\n          distanceX = clipPoints[2] - clipPoints[0];\n          distanceY = clipPoints[3] - clipPoints[1];\n        }\n\n      // No repulsion range. FR grid variant should take care of this.\n      if (Math.abs(distanceX) < FDLayoutConstants.MIN_REPULSION_DIST) {\n        distanceX = IMath.sign(distanceX) * FDLayoutConstants.MIN_REPULSION_DIST;\n      }\n\n      if (Math.abs(distanceY) < FDLayoutConstants.MIN_REPULSION_DIST) {\n        distanceY = IMath.sign(distanceY) * FDLayoutConstants.MIN_REPULSION_DIST;\n      }\n\n      distanceSquared = distanceX * distanceX + distanceY * distanceY;\n      distance = Math.sqrt(distanceSquared);\n\n      repulsionForce = this.repulsionConstant * nodeA.noOfChildren * nodeB.noOfChildren / distanceSquared;\n\n      // Project force onto x and y axes\n      repulsionForceX = repulsionForce * distanceX / distance;\n      repulsionForceY = repulsionForce * distanceY / distance;\n\n      // Apply forces on the two nodes    \n      nodeA.repulsionForceX -= repulsionForceX;\n      nodeA.repulsionForceY -= repulsionForceY;\n      nodeB.repulsionForceX += repulsionForceX;\n      nodeB.repulsionForceY += repulsionForceY;\n    }\n};\n\nFDLayout.prototype.calcGravitationalForce = function (node) {\n  var ownerGraph;\n  var ownerCenterX;\n  var ownerCenterY;\n  var distanceX;\n  var distanceY;\n  var absDistanceX;\n  var absDistanceY;\n  var estimatedSize;\n  ownerGraph = node.getOwner();\n\n  ownerCenterX = (ownerGraph.getRight() + ownerGraph.getLeft()) / 2;\n  ownerCenterY = (ownerGraph.getTop() + ownerGraph.getBottom()) / 2;\n  distanceX = node.getCenterX() - ownerCenterX;\n  distanceY = node.getCenterY() - ownerCenterY;\n  absDistanceX = Math.abs(distanceX) + node.getWidth() / 2;\n  absDistanceY = Math.abs(distanceY) + node.getHeight() / 2;\n\n  if (node.getOwner() == this.graphManager.getRoot()) // in the root graph\n    {\n      estimatedSize = ownerGraph.getEstimatedSize() * this.gravityRangeFactor;\n\n      if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {\n        node.gravitationForceX = -this.gravityConstant * distanceX;\n        node.gravitationForceY = -this.gravityConstant * distanceY;\n      }\n    } else // inside a compound\n    {\n      estimatedSize = ownerGraph.getEstimatedSize() * this.compoundGravityRangeFactor;\n\n      if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {\n        node.gravitationForceX = -this.gravityConstant * distanceX * this.compoundGravityConstant;\n        node.gravitationForceY = -this.gravityConstant * distanceY * this.compoundGravityConstant;\n      }\n    }\n};\n\nFDLayout.prototype.isConverged = function () {\n  var converged;\n  var oscilating = false;\n\n  if (this.totalIterations > this.maxIterations / 3) {\n    oscilating = Math.abs(this.totalDisplacement - this.oldTotalDisplacement) < 2;\n  }\n\n  converged = this.totalDisplacement < this.totalDisplacementThreshold;\n\n  this.oldTotalDisplacement = this.totalDisplacement;\n\n  return converged || oscilating;\n};\n\nFDLayout.prototype.animate = function () {\n  if (this.animationDuringLayout && !this.isSubLayout) {\n    if (this.notAnimatedIterations == this.animationPeriod) {\n      this.update();\n      this.notAnimatedIterations = 0;\n    } else {\n      this.notAnimatedIterations++;\n    }\n  }\n};\n\n//This method calculates the number of children (weight) for all nodes\nFDLayout.prototype.calcNoOfChildrenForAllNodes = function () {\n  var node;\n  var allNodes = this.graphManager.getAllNodes();\n\n  for (var i = 0; i < allNodes.length; i++) {\n    node = allNodes[i];\n    node.noOfChildren = node.getNoOfChildren();\n  }\n};\n\n// -----------------------------------------------------------------------------\n// Section: FR-Grid Variant Repulsion Force Calculation\n// -----------------------------------------------------------------------------\n\nFDLayout.prototype.calcGrid = function (graph) {\n\n  var sizeX = 0;\n  var sizeY = 0;\n\n  sizeX = parseInt(Math.ceil((graph.getRight() - graph.getLeft()) / this.repulsionRange));\n  sizeY = parseInt(Math.ceil((graph.getBottom() - graph.getTop()) / this.repulsionRange));\n\n  var grid = new Array(sizeX);\n\n  for (var i = 0; i < sizeX; i++) {\n    grid[i] = new Array(sizeY);\n  }\n\n  for (var i = 0; i < sizeX; i++) {\n    for (var j = 0; j < sizeY; j++) {\n      grid[i][j] = new Array();\n    }\n  }\n\n  return grid;\n};\n\nFDLayout.prototype.addNodeToGrid = function (v, left, top) {\n\n  var startX = 0;\n  var finishX = 0;\n  var startY = 0;\n  var finishY = 0;\n\n  startX = parseInt(Math.floor((v.getRect().x - left) / this.repulsionRange));\n  finishX = parseInt(Math.floor((v.getRect().width + v.getRect().x - left) / this.repulsionRange));\n  startY = parseInt(Math.floor((v.getRect().y - top) / this.repulsionRange));\n  finishY = parseInt(Math.floor((v.getRect().height + v.getRect().y - top) / this.repulsionRange));\n\n  for (var i = startX; i <= finishX; i++) {\n    for (var j = startY; j <= finishY; j++) {\n      this.grid[i][j].push(v);\n      v.setGridCoordinates(startX, finishX, startY, finishY);\n    }\n  }\n};\n\nFDLayout.prototype.updateGrid = function () {\n  var i;\n  var nodeA;\n  var lNodes = this.getAllNodes();\n\n  this.grid = this.calcGrid(this.graphManager.getRoot());\n\n  // put all nodes to proper grid cells\n  for (i = 0; i < lNodes.length; i++) {\n    nodeA = lNodes[i];\n    this.addNodeToGrid(nodeA, this.graphManager.getRoot().getLeft(), this.graphManager.getRoot().getTop());\n  }\n};\n\nFDLayout.prototype.calculateRepulsionForceOfANode = function (nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate) {\n\n  if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed || forceToNodeSurroundingUpdate) {\n    var surrounding = new Set();\n    nodeA.surrounding = new Array();\n    var nodeB;\n    var grid = this.grid;\n\n    for (var i = nodeA.startX - 1; i < nodeA.finishX + 2; i++) {\n      for (var j = nodeA.startY - 1; j < nodeA.finishY + 2; j++) {\n        if (!(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length)) {\n          for (var k = 0; k < grid[i][j].length; k++) {\n            nodeB = grid[i][j][k];\n\n            // If both nodes are not members of the same graph, \n            // or both nodes are the same, skip.\n            if (nodeA.getOwner() != nodeB.getOwner() || nodeA == nodeB) {\n              continue;\n            }\n\n            // check if the repulsion force between\n            // nodeA and nodeB has already been calculated\n            if (!processedNodeSet.has(nodeB) && !surrounding.has(nodeB)) {\n              var distanceX = Math.abs(nodeA.getCenterX() - nodeB.getCenterX()) - (nodeA.getWidth() / 2 + nodeB.getWidth() / 2);\n              var distanceY = Math.abs(nodeA.getCenterY() - nodeB.getCenterY()) - (nodeA.getHeight() / 2 + nodeB.getHeight() / 2);\n\n              // if the distance between nodeA and nodeB \n              // is less then calculation range\n              if (distanceX <= this.repulsionRange && distanceY <= this.repulsionRange) {\n                //then add nodeB to surrounding of nodeA\n                surrounding.add(nodeB);\n              }\n            }\n          }\n        }\n      }\n    }\n\n    nodeA.surrounding = [].concat(_toConsumableArray(surrounding));\n  }\n  for (i = 0; i < nodeA.surrounding.length; i++) {\n    this.calcRepulsionForce(nodeA, nodeA.surrounding[i]);\n  }\n};\n\nFDLayout.prototype.calcRepulsionRange = function () {\n  return 0.0;\n};\n\nmodule.exports = FDLayout;\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __nested_webpack_require_100902__) {\n\n\"use strict\";\n\n\nvar LEdge = __nested_webpack_require_100902__(1);\nvar FDLayoutConstants = __nested_webpack_require_100902__(7);\n\nfunction FDLayoutEdge(source, target, vEdge) {\n  LEdge.call(this, source, target, vEdge);\n  this.idealLength = FDLayoutConstants.DEFAULT_EDGE_LENGTH;\n}\n\nFDLayoutEdge.prototype = Object.create(LEdge.prototype);\n\nfor (var prop in LEdge) {\n  FDLayoutEdge[prop] = LEdge[prop];\n}\n\nmodule.exports = FDLayoutEdge;\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __nested_webpack_require_101387__) {\n\n\"use strict\";\n\n\nvar LNode = __nested_webpack_require_101387__(3);\n\nfunction FDLayoutNode(gm, loc, size, vNode) {\n  // alternative constructor is handled inside LNode\n  LNode.call(this, gm, loc, size, vNode);\n  //Spring, repulsion and gravitational forces acting on this node\n  this.springForceX = 0;\n  this.springForceY = 0;\n  this.repulsionForceX = 0;\n  this.repulsionForceY = 0;\n  this.gravitationForceX = 0;\n  this.gravitationForceY = 0;\n  //Amount by which this node is to be moved in this iteration\n  this.displacementX = 0;\n  this.displacementY = 0;\n\n  //Start and finish grid coordinates that this node is fallen into\n  this.startX = 0;\n  this.finishX = 0;\n  this.startY = 0;\n  this.finishY = 0;\n\n  //Geometric neighbors of this node\n  this.surrounding = [];\n}\n\nFDLayoutNode.prototype = Object.create(LNode.prototype);\n\nfor (var prop in LNode) {\n  FDLayoutNode[prop] = LNode[prop];\n}\n\nFDLayoutNode.prototype.setGridCoordinates = function (_startX, _finishX, _startY, _finishY) {\n  this.startX = _startX;\n  this.finishX = _finishX;\n  this.startY = _startY;\n  this.finishY = _finishY;\n};\n\nmodule.exports = FDLayoutNode;\n\n/***/ }),\n/* 21 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction DimensionD(width, height) {\n  this.width = 0;\n  this.height = 0;\n  if (width !== null && height !== null) {\n    this.height = height;\n    this.width = width;\n  }\n}\n\nDimensionD.prototype.getWidth = function () {\n  return this.width;\n};\n\nDimensionD.prototype.setWidth = function (width) {\n  this.width = width;\n};\n\nDimensionD.prototype.getHeight = function () {\n  return this.height;\n};\n\nDimensionD.prototype.setHeight = function (height) {\n  this.height = height;\n};\n\nmodule.exports = DimensionD;\n\n/***/ }),\n/* 22 */\n/***/ (function(module, exports, __nested_webpack_require_103173__) {\n\n\"use strict\";\n\n\nvar UniqueIDGeneretor = __nested_webpack_require_103173__(14);\n\nfunction HashMap() {\n  this.map = {};\n  this.keys = [];\n}\n\nHashMap.prototype.put = function (key, value) {\n  var theId = UniqueIDGeneretor.createID(key);\n  if (!this.contains(theId)) {\n    this.map[theId] = value;\n    this.keys.push(key);\n  }\n};\n\nHashMap.prototype.contains = function (key) {\n  var theId = UniqueIDGeneretor.createID(key);\n  return this.map[key] != null;\n};\n\nHashMap.prototype.get = function (key) {\n  var theId = UniqueIDGeneretor.createID(key);\n  return this.map[theId];\n};\n\nHashMap.prototype.keySet = function () {\n  return this.keys;\n};\n\nmodule.exports = HashMap;\n\n/***/ }),\n/* 23 */\n/***/ (function(module, exports, __nested_webpack_require_103901__) {\n\n\"use strict\";\n\n\nvar UniqueIDGeneretor = __nested_webpack_require_103901__(14);\n\nfunction HashSet() {\n  this.set = {};\n}\n;\n\nHashSet.prototype.add = function (obj) {\n  var theId = UniqueIDGeneretor.createID(obj);\n  if (!this.contains(theId)) this.set[theId] = obj;\n};\n\nHashSet.prototype.remove = function (obj) {\n  delete this.set[UniqueIDGeneretor.createID(obj)];\n};\n\nHashSet.prototype.clear = function () {\n  this.set = {};\n};\n\nHashSet.prototype.contains = function (obj) {\n  return this.set[UniqueIDGeneretor.createID(obj)] == obj;\n};\n\nHashSet.prototype.isEmpty = function () {\n  return this.size() === 0;\n};\n\nHashSet.prototype.size = function () {\n  return Object.keys(this.set).length;\n};\n\n//concats this.set to the given list\nHashSet.prototype.addAllTo = function (list) {\n  var keys = Object.keys(this.set);\n  var length = keys.length;\n  for (var i = 0; i < length; i++) {\n    list.push(this.set[keys[i]]);\n  }\n};\n\nHashSet.prototype.size = function () {\n  return Object.keys(this.set).length;\n};\n\nHashSet.prototype.addAll = function (list) {\n  var s = list.length;\n  for (var i = 0; i < s; i++) {\n    var v = list[i];\n    this.add(v);\n  }\n};\n\nmodule.exports = HashSet;\n\n/***/ }),\n/* 24 */\n/***/ (function(module, exports, __nested_webpack_require_105138__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * A classic Quicksort algorithm with Hoare's partition\n * - Works also on LinkedList objects\n *\n * Copyright: i-Vis Research Group, Bilkent University, 2007 - present\n */\n\nvar LinkedList = __nested_webpack_require_105138__(11);\n\nvar Quicksort = function () {\n    function Quicksort(A, compareFunction) {\n        _classCallCheck(this, Quicksort);\n\n        if (compareFunction !== null || compareFunction !== undefined) this.compareFunction = this._defaultCompareFunction;\n\n        var length = void 0;\n        if (A instanceof LinkedList) length = A.size();else length = A.length;\n\n        this._quicksort(A, 0, length - 1);\n    }\n\n    _createClass(Quicksort, [{\n        key: '_quicksort',\n        value: function _quicksort(A, p, r) {\n            if (p < r) {\n                var q = this._partition(A, p, r);\n                this._quicksort(A, p, q);\n                this._quicksort(A, q + 1, r);\n            }\n        }\n    }, {\n        key: '_partition',\n        value: function _partition(A, p, r) {\n            var x = this._get(A, p);\n            var i = p;\n            var j = r;\n            while (true) {\n                while (this.compareFunction(x, this._get(A, j))) {\n                    j--;\n                }while (this.compareFunction(this._get(A, i), x)) {\n                    i++;\n                }if (i < j) {\n                    this._swap(A, i, j);\n                    i++;\n                    j--;\n                } else return j;\n            }\n        }\n    }, {\n        key: '_get',\n        value: function _get(object, index) {\n            if (object instanceof LinkedList) return object.get_object_at(index);else return object[index];\n        }\n    }, {\n        key: '_set',\n        value: function _set(object, index, value) {\n            if (object instanceof LinkedList) object.set_object_at(index, value);else object[index] = value;\n        }\n    }, {\n        key: '_swap',\n        value: function _swap(A, i, j) {\n            var temp = this._get(A, i);\n            this._set(A, i, this._get(A, j));\n            this._set(A, j, temp);\n        }\n    }, {\n        key: '_defaultCompareFunction',\n        value: function _defaultCompareFunction(a, b) {\n            return b > a;\n        }\n    }]);\n\n    return Quicksort;\n}();\n\nmodule.exports = Quicksort;\n\n/***/ }),\n/* 25 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n *   Needleman-Wunsch algorithm is an procedure to compute the optimal global alignment of two string\n *   sequences by S.B.Needleman and C.D.Wunsch (1970).\n *\n *   Aside from the inputs, you can assign the scores for,\n *   - Match: The two characters at the current index are same.\n *   - Mismatch: The two characters at the current index are different.\n *   - Insertion/Deletion(gaps): The best alignment involves one letter aligning to a gap in the other string.\n */\n\nvar NeedlemanWunsch = function () {\n    function NeedlemanWunsch(sequence1, sequence2) {\n        var match_score = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n        var mismatch_penalty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : -1;\n        var gap_penalty = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : -1;\n\n        _classCallCheck(this, NeedlemanWunsch);\n\n        this.sequence1 = sequence1;\n        this.sequence2 = sequence2;\n        this.match_score = match_score;\n        this.mismatch_penalty = mismatch_penalty;\n        this.gap_penalty = gap_penalty;\n\n        // Just the remove redundancy\n        this.iMax = sequence1.length + 1;\n        this.jMax = sequence2.length + 1;\n\n        // Grid matrix of scores\n        this.grid = new Array(this.iMax);\n        for (var i = 0; i < this.iMax; i++) {\n            this.grid[i] = new Array(this.jMax);\n\n            for (var j = 0; j < this.jMax; j++) {\n                this.grid[i][j] = 0;\n            }\n        }\n\n        // Traceback matrix (2D array, each cell is an array of boolean values for [`Diag`, `Up`, `Left`] positions)\n        this.tracebackGrid = new Array(this.iMax);\n        for (var _i = 0; _i < this.iMax; _i++) {\n            this.tracebackGrid[_i] = new Array(this.jMax);\n\n            for (var _j = 0; _j < this.jMax; _j++) {\n                this.tracebackGrid[_i][_j] = [null, null, null];\n            }\n        }\n\n        // The aligned sequences (return multiple possibilities)\n        this.alignments = [];\n\n        // Final alignment score\n        this.score = -1;\n\n        // Calculate scores and tracebacks\n        this.computeGrids();\n    }\n\n    _createClass(NeedlemanWunsch, [{\n        key: \"getScore\",\n        value: function getScore() {\n            return this.score;\n        }\n    }, {\n        key: \"getAlignments\",\n        value: function getAlignments() {\n            return this.alignments;\n        }\n\n        // Main dynamic programming procedure\n\n    }, {\n        key: \"computeGrids\",\n        value: function computeGrids() {\n            // Fill in the first row\n            for (var j = 1; j < this.jMax; j++) {\n                this.grid[0][j] = this.grid[0][j - 1] + this.gap_penalty;\n                this.tracebackGrid[0][j] = [false, false, true];\n            }\n\n            // Fill in the first column\n            for (var i = 1; i < this.iMax; i++) {\n                this.grid[i][0] = this.grid[i - 1][0] + this.gap_penalty;\n                this.tracebackGrid[i][0] = [false, true, false];\n            }\n\n            // Fill the rest of the grid\n            for (var _i2 = 1; _i2 < this.iMax; _i2++) {\n                for (var _j2 = 1; _j2 < this.jMax; _j2++) {\n                    // Find the max score(s) among [`Diag`, `Up`, `Left`]\n                    var diag = void 0;\n                    if (this.sequence1[_i2 - 1] === this.sequence2[_j2 - 1]) diag = this.grid[_i2 - 1][_j2 - 1] + this.match_score;else diag = this.grid[_i2 - 1][_j2 - 1] + this.mismatch_penalty;\n\n                    var up = this.grid[_i2 - 1][_j2] + this.gap_penalty;\n                    var left = this.grid[_i2][_j2 - 1] + this.gap_penalty;\n\n                    // If there exists multiple max values, capture them for multiple paths\n                    var maxOf = [diag, up, left];\n                    var indices = this.arrayAllMaxIndexes(maxOf);\n\n                    // Update Grids\n                    this.grid[_i2][_j2] = maxOf[indices[0]];\n                    this.tracebackGrid[_i2][_j2] = [indices.includes(0), indices.includes(1), indices.includes(2)];\n                }\n            }\n\n            // Update alignment score\n            this.score = this.grid[this.iMax - 1][this.jMax - 1];\n        }\n\n        // Gets all possible valid sequence combinations\n\n    }, {\n        key: \"alignmentTraceback\",\n        value: function alignmentTraceback() {\n            var inProcessAlignments = [];\n\n            inProcessAlignments.push({ pos: [this.sequence1.length, this.sequence2.length],\n                seq1: \"\",\n                seq2: \"\"\n            });\n\n            while (inProcessAlignments[0]) {\n                var current = inProcessAlignments[0];\n                var directions = this.tracebackGrid[current.pos[0]][current.pos[1]];\n\n                if (directions[0]) {\n                    inProcessAlignments.push({ pos: [current.pos[0] - 1, current.pos[1] - 1],\n                        seq1: this.sequence1[current.pos[0] - 1] + current.seq1,\n                        seq2: this.sequence2[current.pos[1] - 1] + current.seq2\n                    });\n                }\n                if (directions[1]) {\n                    inProcessAlignments.push({ pos: [current.pos[0] - 1, current.pos[1]],\n                        seq1: this.sequence1[current.pos[0] - 1] + current.seq1,\n                        seq2: '-' + current.seq2\n                    });\n                }\n                if (directions[2]) {\n                    inProcessAlignments.push({ pos: [current.pos[0], current.pos[1] - 1],\n                        seq1: '-' + current.seq1,\n                        seq2: this.sequence2[current.pos[1] - 1] + current.seq2\n                    });\n                }\n\n                if (current.pos[0] === 0 && current.pos[1] === 0) this.alignments.push({ sequence1: current.seq1,\n                    sequence2: current.seq2\n                });\n\n                inProcessAlignments.shift();\n            }\n\n            return this.alignments;\n        }\n\n        // Helper Functions\n\n    }, {\n        key: \"getAllIndexes\",\n        value: function getAllIndexes(arr, val) {\n            var indexes = [],\n                i = -1;\n            while ((i = arr.indexOf(val, i + 1)) !== -1) {\n                indexes.push(i);\n            }\n            return indexes;\n        }\n    }, {\n        key: \"arrayAllMaxIndexes\",\n        value: function arrayAllMaxIndexes(array) {\n            return this.getAllIndexes(array, Math.max.apply(null, array));\n        }\n    }]);\n\n    return NeedlemanWunsch;\n}();\n\nmodule.exports = NeedlemanWunsch;\n\n/***/ }),\n/* 26 */\n/***/ (function(module, exports, __nested_webpack_require_115611__) {\n\n\"use strict\";\n\n\nvar layoutBase = function layoutBase() {\n  return;\n};\n\nlayoutBase.FDLayout = __nested_webpack_require_115611__(18);\nlayoutBase.FDLayoutConstants = __nested_webpack_require_115611__(7);\nlayoutBase.FDLayoutEdge = __nested_webpack_require_115611__(19);\nlayoutBase.FDLayoutNode = __nested_webpack_require_115611__(20);\nlayoutBase.DimensionD = __nested_webpack_require_115611__(21);\nlayoutBase.HashMap = __nested_webpack_require_115611__(22);\nlayoutBase.HashSet = __nested_webpack_require_115611__(23);\nlayoutBase.IGeometry = __nested_webpack_require_115611__(8);\nlayoutBase.IMath = __nested_webpack_require_115611__(9);\nlayoutBase.Integer = __nested_webpack_require_115611__(10);\nlayoutBase.Point = __nested_webpack_require_115611__(12);\nlayoutBase.PointD = __nested_webpack_require_115611__(4);\nlayoutBase.RandomSeed = __nested_webpack_require_115611__(16);\nlayoutBase.RectangleD = __nested_webpack_require_115611__(13);\nlayoutBase.Transform = __nested_webpack_require_115611__(17);\nlayoutBase.UniqueIDGeneretor = __nested_webpack_require_115611__(14);\nlayoutBase.Quicksort = __nested_webpack_require_115611__(24);\nlayoutBase.LinkedList = __nested_webpack_require_115611__(11);\nlayoutBase.LGraphObject = __nested_webpack_require_115611__(2);\nlayoutBase.LGraph = __nested_webpack_require_115611__(5);\nlayoutBase.LEdge = __nested_webpack_require_115611__(1);\nlayoutBase.LGraphManager = __nested_webpack_require_115611__(6);\nlayoutBase.LNode = __nested_webpack_require_115611__(3);\nlayoutBase.Layout = __nested_webpack_require_115611__(15);\nlayoutBase.LayoutConstants = __nested_webpack_require_115611__(0);\nlayoutBase.NeedlemanWunsch = __nested_webpack_require_115611__(25);\n\nmodule.exports = layoutBase;\n\n/***/ }),\n/* 27 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n\nfunction Emitter() {\n  this.listeners = [];\n}\n\nvar p = Emitter.prototype;\n\np.addListener = function (event, callback) {\n  this.listeners.push({\n    event: event,\n    callback: callback\n  });\n};\n\np.removeListener = function (event, callback) {\n  for (var i = this.listeners.length; i >= 0; i--) {\n    var l = this.listeners[i];\n\n    if (l.event === event && l.callback === callback) {\n      this.listeners.splice(i, 1);\n    }\n  }\n};\n\np.emit = function (event, data) {\n  for (var i = 0; i < this.listeners.length; i++) {\n    var l = this.listeners[i];\n\n    if (event === l.event) {\n      l.callback(data);\n    }\n  }\n};\n\nmodule.exports = Emitter;\n\n/***/ })\n/******/ ]);\n});\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/layout-base/layout-base.js?");

/***/ }),

/***/ "../node_modules/mermaid/dist/mindmap-definition-e19a4bed.js":
/*!*******************************************************************!*\
  !*** ../node_modules/mermaid/dist/mindmap-definition-e19a4bed.js ***!
  \*******************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   diagram: () => (/* binding */ diagram)\n/* harmony export */ });\n/* harmony import */ var _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./mermaid-04fb0060.js */ \"../node_modules/mermaid/dist/mermaid-04fb0060.js\");\n/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! d3 */ \"../node_modules/d3/src/index.js\");\n/* harmony import */ var _createText_a48a4c90_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./createText-a48a4c90.js */ \"../node_modules/mermaid/dist/createText-a48a4c90.js\");\n/* harmony import */ var cytoscape_dist_cytoscape_umd_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cytoscape/dist/cytoscape.umd.js */ \"../node_modules/cytoscape/dist/cytoscape.umd.js\");\n/* harmony import */ var cytoscape_dist_cytoscape_umd_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(cytoscape_dist_cytoscape_umd_js__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var cytoscape_cose_bilkent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cytoscape-cose-bilkent */ \"../node_modules/cytoscape-cose-bilkent/cytoscape-cose-bilkent.js\");\n/* harmony import */ var cytoscape_cose_bilkent__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(cytoscape_cose_bilkent__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var khroma__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! khroma */ \"../node_modules/khroma/dist/methods/is_dark.js\");\n/* harmony import */ var khroma__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! khroma */ \"../node_modules/khroma/dist/methods/lighten.js\");\n/* harmony import */ var khroma__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! khroma */ \"../node_modules/khroma/dist/methods/darken.js\");\n/* harmony import */ var ts_dedent__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ts-dedent */ \"../node_modules/ts-dedent/esm/index.js\");\n/* harmony import */ var dayjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! dayjs */ \"../node_modules/dayjs/dayjs.min.js\");\n/* harmony import */ var dayjs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(dayjs__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _braintree_sanitize_url__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @braintree/sanitize-url */ \"../node_modules/@braintree/sanitize-url/dist/index.js\");\n/* harmony import */ var dompurify__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! dompurify */ \"../node_modules/dompurify/dist/purify.js\");\n/* harmony import */ var dompurify__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(dompurify__WEBPACK_IMPORTED_MODULE_6__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar parser = function() {\n  var o = function(k, v, o2, l) {\n    for (o2 = o2 || {}, l = k.length; l--; o2[k[l]] = v)\n      ;\n    return o2;\n  }, $V0 = [1, 4], $V1 = [1, 13], $V2 = [1, 12], $V3 = [1, 15], $V4 = [1, 16], $V5 = [1, 20], $V6 = [1, 19], $V7 = [6, 7, 8], $V8 = [1, 26], $V9 = [1, 24], $Va = [1, 25], $Vb = [6, 7, 11], $Vc = [1, 6, 13, 15, 16, 19, 22], $Vd = [1, 33], $Ve = [1, 34], $Vf = [1, 6, 7, 11, 13, 15, 16, 19, 22];\n  var parser2 = {\n    trace: function trace() {\n    },\n    yy: {},\n    symbols_: { \"error\": 2, \"start\": 3, \"mindMap\": 4, \"spaceLines\": 5, \"SPACELINE\": 6, \"NL\": 7, \"MINDMAP\": 8, \"document\": 9, \"stop\": 10, \"EOF\": 11, \"statement\": 12, \"SPACELIST\": 13, \"node\": 14, \"ICON\": 15, \"CLASS\": 16, \"nodeWithId\": 17, \"nodeWithoutId\": 18, \"NODE_DSTART\": 19, \"NODE_DESCR\": 20, \"NODE_DEND\": 21, \"NODE_ID\": 22, \"$accept\": 0, \"$end\": 1 },\n    terminals_: { 2: \"error\", 6: \"SPACELINE\", 7: \"NL\", 8: \"MINDMAP\", 11: \"EOF\", 13: \"SPACELIST\", 15: \"ICON\", 16: \"CLASS\", 19: \"NODE_DSTART\", 20: \"NODE_DESCR\", 21: \"NODE_DEND\", 22: \"NODE_ID\" },\n    productions_: [0, [3, 1], [3, 2], [5, 1], [5, 2], [5, 2], [4, 2], [4, 3], [10, 1], [10, 1], [10, 1], [10, 2], [10, 2], [9, 3], [9, 2], [12, 2], [12, 2], [12, 2], [12, 1], [12, 1], [12, 1], [12, 1], [12, 1], [14, 1], [14, 1], [18, 3], [17, 1], [17, 4]],\n    performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {\n      var $0 = $$.length - 1;\n      switch (yystate) {\n        case 6:\n        case 7:\n          return yy;\n        case 8:\n          yy.getLogger().trace(\"Stop NL \");\n          break;\n        case 9:\n          yy.getLogger().trace(\"Stop EOF \");\n          break;\n        case 11:\n          yy.getLogger().trace(\"Stop NL2 \");\n          break;\n        case 12:\n          yy.getLogger().trace(\"Stop EOF2 \");\n          break;\n        case 15:\n          yy.getLogger().info(\"Node: \", $$[$0].id);\n          yy.addNode($$[$0 - 1].length, $$[$0].id, $$[$0].descr, $$[$0].type);\n          break;\n        case 16:\n          yy.getLogger().trace(\"Icon: \", $$[$0]);\n          yy.decorateNode({ icon: $$[$0] });\n          break;\n        case 17:\n        case 21:\n          yy.decorateNode({ class: $$[$0] });\n          break;\n        case 18:\n          yy.getLogger().trace(\"SPACELIST\");\n          break;\n        case 19:\n          yy.getLogger().trace(\"Node: \", $$[$0].id);\n          yy.addNode(0, $$[$0].id, $$[$0].descr, $$[$0].type);\n          break;\n        case 20:\n          yy.decorateNode({ icon: $$[$0] });\n          break;\n        case 25:\n          yy.getLogger().trace(\"node found ..\", $$[$0 - 2]);\n          this.$ = { id: $$[$0 - 1], descr: $$[$0 - 1], type: yy.getType($$[$0 - 2], $$[$0]) };\n          break;\n        case 26:\n          this.$ = { id: $$[$0], descr: $$[$0], type: yy.nodeType.DEFAULT };\n          break;\n        case 27:\n          yy.getLogger().trace(\"node found ..\", $$[$0 - 3]);\n          this.$ = { id: $$[$0 - 3], descr: $$[$0 - 1], type: yy.getType($$[$0 - 2], $$[$0]) };\n          break;\n      }\n    },\n    table: [{ 3: 1, 4: 2, 5: 3, 6: [1, 5], 8: $V0 }, { 1: [3] }, { 1: [2, 1] }, { 4: 6, 6: [1, 7], 7: [1, 8], 8: $V0 }, { 6: $V1, 7: [1, 10], 9: 9, 12: 11, 13: $V2, 14: 14, 15: $V3, 16: $V4, 17: 17, 18: 18, 19: $V5, 22: $V6 }, o($V7, [2, 3]), { 1: [2, 2] }, o($V7, [2, 4]), o($V7, [2, 5]), { 1: [2, 6], 6: $V1, 12: 21, 13: $V2, 14: 14, 15: $V3, 16: $V4, 17: 17, 18: 18, 19: $V5, 22: $V6 }, { 6: $V1, 9: 22, 12: 11, 13: $V2, 14: 14, 15: $V3, 16: $V4, 17: 17, 18: 18, 19: $V5, 22: $V6 }, { 6: $V8, 7: $V9, 10: 23, 11: $Va }, o($Vb, [2, 22], { 17: 17, 18: 18, 14: 27, 15: [1, 28], 16: [1, 29], 19: $V5, 22: $V6 }), o($Vb, [2, 18]), o($Vb, [2, 19]), o($Vb, [2, 20]), o($Vb, [2, 21]), o($Vb, [2, 23]), o($Vb, [2, 24]), o($Vb, [2, 26], { 19: [1, 30] }), { 20: [1, 31] }, { 6: $V8, 7: $V9, 10: 32, 11: $Va }, { 1: [2, 7], 6: $V1, 12: 21, 13: $V2, 14: 14, 15: $V3, 16: $V4, 17: 17, 18: 18, 19: $V5, 22: $V6 }, o($Vc, [2, 14], { 7: $Vd, 11: $Ve }), o($Vf, [2, 8]), o($Vf, [2, 9]), o($Vf, [2, 10]), o($Vb, [2, 15]), o($Vb, [2, 16]), o($Vb, [2, 17]), { 20: [1, 35] }, { 21: [1, 36] }, o($Vc, [2, 13], { 7: $Vd, 11: $Ve }), o($Vf, [2, 11]), o($Vf, [2, 12]), { 21: [1, 37] }, o($Vb, [2, 25]), o($Vb, [2, 27])],\n    defaultActions: { 2: [2, 1], 6: [2, 2] },\n    parseError: function parseError2(str, hash) {\n      if (hash.recoverable) {\n        this.trace(str);\n      } else {\n        var error = new Error(str);\n        error.hash = hash;\n        throw error;\n      }\n    },\n    parse: function parse(input) {\n      var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = \"\", yylineno = 0, yyleng = 0, TERROR = 2, EOF = 1;\n      var args = lstack.slice.call(arguments, 1);\n      var lexer2 = Object.create(this.lexer);\n      var sharedState = { yy: {} };\n      for (var k in this.yy) {\n        if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n          sharedState.yy[k] = this.yy[k];\n        }\n      }\n      lexer2.setInput(input, sharedState.yy);\n      sharedState.yy.lexer = lexer2;\n      sharedState.yy.parser = this;\n      if (typeof lexer2.yylloc == \"undefined\") {\n        lexer2.yylloc = {};\n      }\n      var yyloc = lexer2.yylloc;\n      lstack.push(yyloc);\n      var ranges = lexer2.options && lexer2.options.ranges;\n      if (typeof sharedState.yy.parseError === \"function\") {\n        this.parseError = sharedState.yy.parseError;\n      } else {\n        this.parseError = Object.getPrototypeOf(this).parseError;\n      }\n      function lex() {\n        var token;\n        token = tstack.pop() || lexer2.lex() || EOF;\n        if (typeof token !== \"number\") {\n          if (token instanceof Array) {\n            tstack = token;\n            token = tstack.pop();\n          }\n          token = self.symbols_[token] || token;\n        }\n        return token;\n      }\n      var symbol, state, action, r, yyval = {}, p, len, newState, expected;\n      while (true) {\n        state = stack[stack.length - 1];\n        if (this.defaultActions[state]) {\n          action = this.defaultActions[state];\n        } else {\n          if (symbol === null || typeof symbol == \"undefined\") {\n            symbol = lex();\n          }\n          action = table[state] && table[state][symbol];\n        }\n        if (typeof action === \"undefined\" || !action.length || !action[0]) {\n          var errStr = \"\";\n          expected = [];\n          for (p in table[state]) {\n            if (this.terminals_[p] && p > TERROR) {\n              expected.push(\"'\" + this.terminals_[p] + \"'\");\n            }\n          }\n          if (lexer2.showPosition) {\n            errStr = \"Parse error on line \" + (yylineno + 1) + \":\\n\" + lexer2.showPosition() + \"\\nExpecting \" + expected.join(\", \") + \", got '\" + (this.terminals_[symbol] || symbol) + \"'\";\n          } else {\n            errStr = \"Parse error on line \" + (yylineno + 1) + \": Unexpected \" + (symbol == EOF ? \"end of input\" : \"'\" + (this.terminals_[symbol] || symbol) + \"'\");\n          }\n          this.parseError(errStr, {\n            text: lexer2.match,\n            token: this.terminals_[symbol] || symbol,\n            line: lexer2.yylineno,\n            loc: yyloc,\n            expected\n          });\n        }\n        if (action[0] instanceof Array && action.length > 1) {\n          throw new Error(\"Parse Error: multiple actions possible at state: \" + state + \", token: \" + symbol);\n        }\n        switch (action[0]) {\n          case 1:\n            stack.push(symbol);\n            vstack.push(lexer2.yytext);\n            lstack.push(lexer2.yylloc);\n            stack.push(action[1]);\n            symbol = null;\n            {\n              yyleng = lexer2.yyleng;\n              yytext = lexer2.yytext;\n              yylineno = lexer2.yylineno;\n              yyloc = lexer2.yylloc;\n            }\n            break;\n          case 2:\n            len = this.productions_[action[1]][1];\n            yyval.$ = vstack[vstack.length - len];\n            yyval._$ = {\n              first_line: lstack[lstack.length - (len || 1)].first_line,\n              last_line: lstack[lstack.length - 1].last_line,\n              first_column: lstack[lstack.length - (len || 1)].first_column,\n              last_column: lstack[lstack.length - 1].last_column\n            };\n            if (ranges) {\n              yyval._$.range = [\n                lstack[lstack.length - (len || 1)].range[0],\n                lstack[lstack.length - 1].range[1]\n              ];\n            }\n            r = this.performAction.apply(yyval, [\n              yytext,\n              yyleng,\n              yylineno,\n              sharedState.yy,\n              action[1],\n              vstack,\n              lstack\n            ].concat(args));\n            if (typeof r !== \"undefined\") {\n              return r;\n            }\n            if (len) {\n              stack = stack.slice(0, -1 * len * 2);\n              vstack = vstack.slice(0, -1 * len);\n              lstack = lstack.slice(0, -1 * len);\n            }\n            stack.push(this.productions_[action[1]][0]);\n            vstack.push(yyval.$);\n            lstack.push(yyval._$);\n            newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n            stack.push(newState);\n            break;\n          case 3:\n            return true;\n        }\n      }\n      return true;\n    }\n  };\n  var lexer = function() {\n    var lexer2 = {\n      EOF: 1,\n      parseError: function parseError2(str, hash) {\n        if (this.yy.parser) {\n          this.yy.parser.parseError(str, hash);\n        } else {\n          throw new Error(str);\n        }\n      },\n      // resets the lexer, sets new input\n      setInput: function(input, yy) {\n        this.yy = yy || this.yy || {};\n        this._input = input;\n        this._more = this._backtrack = this.done = false;\n        this.yylineno = this.yyleng = 0;\n        this.yytext = this.matched = this.match = \"\";\n        this.conditionStack = [\"INITIAL\"];\n        this.yylloc = {\n          first_line: 1,\n          first_column: 0,\n          last_line: 1,\n          last_column: 0\n        };\n        if (this.options.ranges) {\n          this.yylloc.range = [0, 0];\n        }\n        this.offset = 0;\n        return this;\n      },\n      // consumes and returns one char from the input\n      input: function() {\n        var ch = this._input[0];\n        this.yytext += ch;\n        this.yyleng++;\n        this.offset++;\n        this.match += ch;\n        this.matched += ch;\n        var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n        if (lines) {\n          this.yylineno++;\n          this.yylloc.last_line++;\n        } else {\n          this.yylloc.last_column++;\n        }\n        if (this.options.ranges) {\n          this.yylloc.range[1]++;\n        }\n        this._input = this._input.slice(1);\n        return ch;\n      },\n      // unshifts one char (or a string) into the input\n      unput: function(ch) {\n        var len = ch.length;\n        var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n        this._input = ch + this._input;\n        this.yytext = this.yytext.substr(0, this.yytext.length - len);\n        this.offset -= len;\n        var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n        this.match = this.match.substr(0, this.match.length - 1);\n        this.matched = this.matched.substr(0, this.matched.length - 1);\n        if (lines.length - 1) {\n          this.yylineno -= lines.length - 1;\n        }\n        var r = this.yylloc.range;\n        this.yylloc = {\n          first_line: this.yylloc.first_line,\n          last_line: this.yylineno + 1,\n          first_column: this.yylloc.first_column,\n          last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len\n        };\n        if (this.options.ranges) {\n          this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n        }\n        this.yyleng = this.yytext.length;\n        return this;\n      },\n      // When called from action, caches matched text and appends it on next action\n      more: function() {\n        this._more = true;\n        return this;\n      },\n      // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\n      reject: function() {\n        if (this.options.backtrack_lexer) {\n          this._backtrack = true;\n        } else {\n          return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n\" + this.showPosition(), {\n            text: \"\",\n            token: null,\n            line: this.yylineno\n          });\n        }\n        return this;\n      },\n      // retain first n characters of the match\n      less: function(n) {\n        this.unput(this.match.slice(n));\n      },\n      // displays already matched input, i.e. for error messages\n      pastInput: function() {\n        var past = this.matched.substr(0, this.matched.length - this.match.length);\n        return (past.length > 20 ? \"...\" : \"\") + past.substr(-20).replace(/\\n/g, \"\");\n      },\n      // displays upcoming input, i.e. for error messages\n      upcomingInput: function() {\n        var next = this.match;\n        if (next.length < 20) {\n          next += this._input.substr(0, 20 - next.length);\n        }\n        return (next.substr(0, 20) + (next.length > 20 ? \"...\" : \"\")).replace(/\\n/g, \"\");\n      },\n      // displays the character position where the lexing error occurred, i.e. for error messages\n      showPosition: function() {\n        var pre = this.pastInput();\n        var c = new Array(pre.length + 1).join(\"-\");\n        return pre + this.upcomingInput() + \"\\n\" + c + \"^\";\n      },\n      // test the lexed token: return FALSE when not a match, otherwise return token\n      test_match: function(match, indexed_rule) {\n        var token, lines, backup;\n        if (this.options.backtrack_lexer) {\n          backup = {\n            yylineno: this.yylineno,\n            yylloc: {\n              first_line: this.yylloc.first_line,\n              last_line: this.last_line,\n              first_column: this.yylloc.first_column,\n              last_column: this.yylloc.last_column\n            },\n            yytext: this.yytext,\n            match: this.match,\n            matches: this.matches,\n            matched: this.matched,\n            yyleng: this.yyleng,\n            offset: this.offset,\n            _more: this._more,\n            _input: this._input,\n            yy: this.yy,\n            conditionStack: this.conditionStack.slice(0),\n            done: this.done\n          };\n          if (this.options.ranges) {\n            backup.yylloc.range = this.yylloc.range.slice(0);\n          }\n        }\n        lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n        if (lines) {\n          this.yylineno += lines.length;\n        }\n        this.yylloc = {\n          first_line: this.yylloc.last_line,\n          last_line: this.yylineno + 1,\n          first_column: this.yylloc.last_column,\n          last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length : this.yylloc.last_column + match[0].length\n        };\n        this.yytext += match[0];\n        this.match += match[0];\n        this.matches = match;\n        this.yyleng = this.yytext.length;\n        if (this.options.ranges) {\n          this.yylloc.range = [this.offset, this.offset += this.yyleng];\n        }\n        this._more = false;\n        this._backtrack = false;\n        this._input = this._input.slice(match[0].length);\n        this.matched += match[0];\n        token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n        if (this.done && this._input) {\n          this.done = false;\n        }\n        if (token) {\n          return token;\n        } else if (this._backtrack) {\n          for (var k in backup) {\n            this[k] = backup[k];\n          }\n          return false;\n        }\n        return false;\n      },\n      // return next match in input\n      next: function() {\n        if (this.done) {\n          return this.EOF;\n        }\n        if (!this._input) {\n          this.done = true;\n        }\n        var token, match, tempMatch, index;\n        if (!this._more) {\n          this.yytext = \"\";\n          this.match = \"\";\n        }\n        var rules = this._currentRules();\n        for (var i = 0; i < rules.length; i++) {\n          tempMatch = this._input.match(this.rules[rules[i]]);\n          if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n            match = tempMatch;\n            index = i;\n            if (this.options.backtrack_lexer) {\n              token = this.test_match(tempMatch, rules[i]);\n              if (token !== false) {\n                return token;\n              } else if (this._backtrack) {\n                match = false;\n                continue;\n              } else {\n                return false;\n              }\n            } else if (!this.options.flex) {\n              break;\n            }\n          }\n        }\n        if (match) {\n          token = this.test_match(match, rules[index]);\n          if (token !== false) {\n            return token;\n          }\n          return false;\n        }\n        if (this._input === \"\") {\n          return this.EOF;\n        } else {\n          return this.parseError(\"Lexical error on line \" + (this.yylineno + 1) + \". Unrecognized text.\\n\" + this.showPosition(), {\n            text: \"\",\n            token: null,\n            line: this.yylineno\n          });\n        }\n      },\n      // return next match that has a token\n      lex: function lex() {\n        var r = this.next();\n        if (r) {\n          return r;\n        } else {\n          return this.lex();\n        }\n      },\n      // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\n      begin: function begin(condition) {\n        this.conditionStack.push(condition);\n      },\n      // pop the previously active lexer condition state off the condition stack\n      popState: function popState() {\n        var n = this.conditionStack.length - 1;\n        if (n > 0) {\n          return this.conditionStack.pop();\n        } else {\n          return this.conditionStack[0];\n        }\n      },\n      // produce the lexer rule set which is active for the currently active lexer condition state\n      _currentRules: function _currentRules() {\n        if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n          return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n        } else {\n          return this.conditions[\"INITIAL\"].rules;\n        }\n      },\n      // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\n      topState: function topState(n) {\n        n = this.conditionStack.length - 1 - Math.abs(n || 0);\n        if (n >= 0) {\n          return this.conditionStack[n];\n        } else {\n          return \"INITIAL\";\n        }\n      },\n      // alias for begin(condition)\n      pushState: function pushState(condition) {\n        this.begin(condition);\n      },\n      // return the number of states currently on the stack\n      stateStackSize: function stateStackSize() {\n        return this.conditionStack.length;\n      },\n      options: { \"case-insensitive\": true },\n      performAction: function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {\n        switch ($avoiding_name_collisions) {\n          case 0:\n            yy.getLogger().trace(\"Found comment\", yy_.yytext);\n            return 6;\n          case 1:\n            return 8;\n          case 2:\n            this.begin(\"CLASS\");\n            break;\n          case 3:\n            this.popState();\n            return 16;\n          case 4:\n            this.popState();\n            break;\n          case 5:\n            yy.getLogger().trace(\"Begin icon\");\n            this.begin(\"ICON\");\n            break;\n          case 6:\n            yy.getLogger().trace(\"SPACELINE\");\n            return 6;\n          case 7:\n            return 7;\n          case 8:\n            return 15;\n          case 9:\n            yy.getLogger().trace(\"end icon\");\n            this.popState();\n            break;\n          case 10:\n            yy.getLogger().trace(\"Exploding node\");\n            this.begin(\"NODE\");\n            return 19;\n          case 11:\n            yy.getLogger().trace(\"Cloud\");\n            this.begin(\"NODE\");\n            return 19;\n          case 12:\n            yy.getLogger().trace(\"Explosion Bang\");\n            this.begin(\"NODE\");\n            return 19;\n          case 13:\n            yy.getLogger().trace(\"Cloud Bang\");\n            this.begin(\"NODE\");\n            return 19;\n          case 14:\n            this.begin(\"NODE\");\n            return 19;\n          case 15:\n            this.begin(\"NODE\");\n            return 19;\n          case 16:\n            this.begin(\"NODE\");\n            return 19;\n          case 17:\n            this.begin(\"NODE\");\n            return 19;\n          case 18:\n            return 13;\n          case 19:\n            return 22;\n          case 20:\n            return 11;\n          case 21:\n            this.begin(\"NSTR2\");\n            break;\n          case 22:\n            return \"NODE_DESCR\";\n          case 23:\n            this.popState();\n            break;\n          case 24:\n            yy.getLogger().trace(\"Starting NSTR\");\n            this.begin(\"NSTR\");\n            break;\n          case 25:\n            yy.getLogger().trace(\"description:\", yy_.yytext);\n            return \"NODE_DESCR\";\n          case 26:\n            this.popState();\n            break;\n          case 27:\n            this.popState();\n            yy.getLogger().trace(\"node end ))\");\n            return \"NODE_DEND\";\n          case 28:\n            this.popState();\n            yy.getLogger().trace(\"node end )\");\n            return \"NODE_DEND\";\n          case 29:\n            this.popState();\n            yy.getLogger().trace(\"node end ...\", yy_.yytext);\n            return \"NODE_DEND\";\n          case 30:\n            this.popState();\n            yy.getLogger().trace(\"node end ((\");\n            return \"NODE_DEND\";\n          case 31:\n            this.popState();\n            yy.getLogger().trace(\"node end (-\");\n            return \"NODE_DEND\";\n          case 32:\n            this.popState();\n            yy.getLogger().trace(\"node end (-\");\n            return \"NODE_DEND\";\n          case 33:\n            this.popState();\n            yy.getLogger().trace(\"node end ((\");\n            return \"NODE_DEND\";\n          case 34:\n            this.popState();\n            yy.getLogger().trace(\"node end ((\");\n            return \"NODE_DEND\";\n          case 35:\n            yy.getLogger().trace(\"Long description:\", yy_.yytext);\n            return 20;\n          case 36:\n            yy.getLogger().trace(\"Long description:\", yy_.yytext);\n            return 20;\n        }\n      },\n      rules: [/^(?:\\s*%%.*)/i, /^(?:mindmap\\b)/i, /^(?::::)/i, /^(?:.+)/i, /^(?:\\n)/i, /^(?:::icon\\()/i, /^(?:[\\s]+[\\n])/i, /^(?:[\\n]+)/i, /^(?:[^\\)]+)/i, /^(?:\\))/i, /^(?:-\\))/i, /^(?:\\(-)/i, /^(?:\\)\\))/i, /^(?:\\))/i, /^(?:\\(\\()/i, /^(?:\\{\\{)/i, /^(?:\\()/i, /^(?:\\[)/i, /^(?:[\\s]+)/i, /^(?:[^\\(\\[\\n\\)\\{\\}]+)/i, /^(?:$)/i, /^(?:[\"][`])/i, /^(?:[^`\"]+)/i, /^(?:[`][\"])/i, /^(?:[\"])/i, /^(?:[^\"]+)/i, /^(?:[\"])/i, /^(?:[\\)]\\))/i, /^(?:[\\)])/i, /^(?:[\\]])/i, /^(?:\\}\\})/i, /^(?:\\(-)/i, /^(?:-\\))/i, /^(?:\\(\\()/i, /^(?:\\()/i, /^(?:[^\\)\\]\\(\\}]+)/i, /^(?:.+(?!\\(\\())/i],\n      conditions: { \"CLASS\": { \"rules\": [3, 4], \"inclusive\": false }, \"ICON\": { \"rules\": [8, 9], \"inclusive\": false }, \"NSTR2\": { \"rules\": [22, 23], \"inclusive\": false }, \"NSTR\": { \"rules\": [25, 26], \"inclusive\": false }, \"NODE\": { \"rules\": [21, 24, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36], \"inclusive\": false }, \"INITIAL\": { \"rules\": [0, 1, 2, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], \"inclusive\": true } }\n    };\n    return lexer2;\n  }();\n  parser2.lexer = lexer;\n  function Parser() {\n    this.yy = {};\n  }\n  Parser.prototype = parser2;\n  parser2.Parser = Parser;\n  return new Parser();\n}();\nparser.parser = parser;\nconst mindmapParser = parser;\nconst sanitizeText = (text) => (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.d)(text, (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.c)());\nlet nodes = [];\nlet cnt = 0;\nlet elements = {};\nconst clear = () => {\n  nodes = [];\n  cnt = 0;\n  elements = {};\n};\nconst getParent = function(level) {\n  for (let i = nodes.length - 1; i >= 0; i--) {\n    if (nodes[i].level < level) {\n      return nodes[i];\n    }\n  }\n  return null;\n};\nconst getMindmap = () => {\n  return nodes.length > 0 ? nodes[0] : null;\n};\nconst addNode = (level, id, descr, type) => {\n  _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l.info(\"addNode\", level, id, descr, type);\n  const conf = (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.c)();\n  const node = {\n    id: cnt++,\n    nodeId: sanitizeText(id),\n    level,\n    descr: sanitizeText(descr),\n    type,\n    children: [],\n    width: (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.c)().mindmap.maxNodeWidth\n  };\n  switch (node.type) {\n    case nodeType.ROUNDED_RECT:\n      node.padding = 2 * conf.mindmap.padding;\n      break;\n    case nodeType.RECT:\n      node.padding = 2 * conf.mindmap.padding;\n      break;\n    case nodeType.HEXAGON:\n      node.padding = 2 * conf.mindmap.padding;\n      break;\n    default:\n      node.padding = conf.mindmap.padding;\n  }\n  const parent = getParent(level);\n  if (parent) {\n    parent.children.push(node);\n    nodes.push(node);\n  } else {\n    if (nodes.length === 0) {\n      nodes.push(node);\n    } else {\n      let error = new Error(\n        'There can be only one root. No parent could be found for (\"' + node.descr + '\")'\n      );\n      error.hash = {\n        text: \"branch \" + name,\n        token: \"branch \" + name,\n        line: \"1\",\n        loc: { first_line: 1, last_line: 1, first_column: 1, last_column: 1 },\n        expected: ['\"checkout ' + name + '\"']\n      };\n      throw error;\n    }\n  }\n};\nconst nodeType = {\n  DEFAULT: 0,\n  NO_BORDER: 0,\n  ROUNDED_RECT: 1,\n  RECT: 2,\n  CIRCLE: 3,\n  CLOUD: 4,\n  BANG: 5,\n  HEXAGON: 6\n};\nconst getType = (startStr, endStr) => {\n  _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l.debug(\"In get type\", startStr, endStr);\n  switch (startStr) {\n    case \"[\":\n      return nodeType.RECT;\n    case \"(\":\n      return endStr === \")\" ? nodeType.ROUNDED_RECT : nodeType.CLOUD;\n    case \"((\":\n      return nodeType.CIRCLE;\n    case \")\":\n      return nodeType.CLOUD;\n    case \"))\":\n      return nodeType.BANG;\n    case \"{{\":\n      return nodeType.HEXAGON;\n    default:\n      return nodeType.DEFAULT;\n  }\n};\nconst setElementForId = (id, element) => {\n  elements[id] = element;\n};\nconst decorateNode = (decoration) => {\n  const node = nodes[nodes.length - 1];\n  if (decoration && decoration.icon) {\n    node.icon = sanitizeText(decoration.icon);\n  }\n  if (decoration && decoration.class) {\n    node.class = sanitizeText(decoration.class);\n  }\n};\nconst type2Str = (type) => {\n  switch (type) {\n    case nodeType.DEFAULT:\n      return \"no-border\";\n    case nodeType.RECT:\n      return \"rect\";\n    case nodeType.ROUNDED_RECT:\n      return \"rounded-rect\";\n    case nodeType.CIRCLE:\n      return \"circle\";\n    case nodeType.CLOUD:\n      return \"cloud\";\n    case nodeType.BANG:\n      return \"bang\";\n    case nodeType.HEXAGON:\n      return \"hexgon\";\n    default:\n      return \"no-border\";\n  }\n};\nlet parseError;\nconst setErrorHandler = (handler) => {\n  parseError = handler;\n};\nconst getLogger = () => _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l;\nconst getNodeById = (id) => nodes[id];\nconst getElementById = (id) => elements[id];\nconst mindmapDb = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({\n  __proto__: null,\n  addNode,\n  clear,\n  decorateNode,\n  getElementById,\n  getLogger,\n  getMindmap,\n  getNodeById,\n  getType,\n  nodeType,\n  get parseError() {\n    return parseError;\n  },\n  sanitizeText,\n  setElementForId,\n  setErrorHandler,\n  type2Str\n}, Symbol.toStringTag, { value: \"Module\" }));\nconst MAX_SECTIONS = 12;\nconst defaultBkg = function(elem, node, section) {\n  const rd = 5;\n  elem.append(\"path\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + type2Str(node.type)).attr(\n    \"d\",\n    `M0 ${node.height - rd} v${-node.height + 2 * rd} q0,-5 5,-5 h${node.width - 2 * rd} q5,0 5,5 v${node.height - rd} H0 Z`\n  );\n  elem.append(\"line\").attr(\"class\", \"node-line-\" + section).attr(\"x1\", 0).attr(\"y1\", node.height).attr(\"x2\", node.width).attr(\"y2\", node.height);\n};\nconst rectBkg = function(elem, node) {\n  elem.append(\"rect\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + type2Str(node.type)).attr(\"height\", node.height).attr(\"width\", node.width);\n};\nconst cloudBkg = function(elem, node) {\n  const w = node.width;\n  const h = node.height;\n  const r1 = 0.15 * w;\n  const r2 = 0.25 * w;\n  const r3 = 0.35 * w;\n  const r4 = 0.2 * w;\n  elem.append(\"path\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + type2Str(node.type)).attr(\n    \"d\",\n    `M0 0 a${r1},${r1} 0 0,1 ${w * 0.25},${-1 * w * 0.1}\n      a${r3},${r3} 1 0,1 ${w * 0.4},${-1 * w * 0.1}\n      a${r2},${r2} 1 0,1 ${w * 0.35},${1 * w * 0.2}\n\n      a${r1},${r1} 1 0,1 ${w * 0.15},${1 * h * 0.35}\n      a${r4},${r4} 1 0,1 ${-1 * w * 0.15},${1 * h * 0.65}\n\n      a${r2},${r1} 1 0,1 ${-1 * w * 0.25},${w * 0.15}\n      a${r3},${r3} 1 0,1 ${-1 * w * 0.5},${0}\n      a${r1},${r1} 1 0,1 ${-1 * w * 0.25},${-1 * w * 0.15}\n\n      a${r1},${r1} 1 0,1 ${-1 * w * 0.1},${-1 * h * 0.35}\n      a${r4},${r4} 1 0,1 ${w * 0.1},${-1 * h * 0.65}\n\n    H0 V0 Z`\n  );\n};\nconst bangBkg = function(elem, node) {\n  const w = node.width;\n  const h = node.height;\n  const r = 0.15 * w;\n  elem.append(\"path\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + type2Str(node.type)).attr(\n    \"d\",\n    `M0 0 a${r},${r} 1 0,0 ${w * 0.25},${-1 * h * 0.1}\n      a${r},${r} 1 0,0 ${w * 0.25},${0}\n      a${r},${r} 1 0,0 ${w * 0.25},${0}\n      a${r},${r} 1 0,0 ${w * 0.25},${1 * h * 0.1}\n\n      a${r},${r} 1 0,0 ${w * 0.15},${1 * h * 0.33}\n      a${r * 0.8},${r * 0.8} 1 0,0 ${0},${1 * h * 0.34}\n      a${r},${r} 1 0,0 ${-1 * w * 0.15},${1 * h * 0.33}\n\n      a${r},${r} 1 0,0 ${-1 * w * 0.25},${h * 0.15}\n      a${r},${r} 1 0,0 ${-1 * w * 0.25},${0}\n      a${r},${r} 1 0,0 ${-1 * w * 0.25},${0}\n      a${r},${r} 1 0,0 ${-1 * w * 0.25},${-1 * h * 0.15}\n\n      a${r},${r} 1 0,0 ${-1 * w * 0.1},${-1 * h * 0.33}\n      a${r * 0.8},${r * 0.8} 1 0,0 ${0},${-1 * h * 0.34}\n      a${r},${r} 1 0,0 ${w * 0.1},${-1 * h * 0.33}\n\n    H0 V0 Z`\n  );\n};\nconst circleBkg = function(elem, node) {\n  elem.append(\"circle\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + type2Str(node.type)).attr(\"r\", node.width / 2);\n};\nfunction insertPolygonShape(parent, w, h, points, node) {\n  return parent.insert(\"polygon\", \":first-child\").attr(\n    \"points\",\n    points.map(function(d) {\n      return d.x + \",\" + d.y;\n    }).join(\" \")\n  ).attr(\"transform\", \"translate(\" + (node.width - w) / 2 + \", \" + h + \")\");\n}\nconst hexagonBkg = function(elem, node) {\n  const h = node.height;\n  const f = 4;\n  const m = h / f;\n  const w = node.width - node.padding + 2 * m;\n  const points = [\n    { x: m, y: 0 },\n    { x: w - m, y: 0 },\n    { x: w, y: -h / 2 },\n    { x: w - m, y: -h },\n    { x: m, y: -h },\n    { x: 0, y: -h / 2 }\n  ];\n  insertPolygonShape(elem, w, h, points, node);\n};\nconst roundedRectBkg = function(elem, node) {\n  elem.append(\"rect\").attr(\"id\", \"node-\" + node.id).attr(\"class\", \"node-bkg node-\" + type2Str(node.type)).attr(\"height\", node.height).attr(\"rx\", node.padding).attr(\"ry\", node.padding).attr(\"width\", node.width);\n};\nconst drawNode = function(elem, node, fullSection, conf) {\n  const htmlLabels = conf.htmlLabels;\n  const section = fullSection % (MAX_SECTIONS - 1);\n  const nodeElem = elem.append(\"g\");\n  node.section = section;\n  let sectionClass = \"section-\" + section;\n  if (section < 0) {\n    sectionClass += \" section-root\";\n  }\n  nodeElem.attr(\"class\", (node.class ? node.class + \" \" : \"\") + \"mindmap-node \" + sectionClass);\n  const bkgElem = nodeElem.append(\"g\");\n  const textElem = nodeElem.append(\"g\");\n  const description = node.descr.replace(/(<br\\/*>)/g, \"\\n\");\n  (0,_createText_a48a4c90_js__WEBPACK_IMPORTED_MODULE_8__.a)(textElem, description, {\n    useHtmlLabels: htmlLabels,\n    width: node.width,\n    classes: \"mindmap-node-label\"\n  });\n  if (!htmlLabels) {\n    textElem.attr(\"dy\", \"1em\").attr(\"alignment-baseline\", \"middle\").attr(\"dominant-baseline\", \"middle\").attr(\"text-anchor\", \"middle\");\n  }\n  const bbox = textElem.node().getBBox();\n  const fontSize = conf.fontSize.replace ? conf.fontSize.replace(\"px\", \"\") : conf.fontSize;\n  node.height = bbox.height + fontSize * 1.1 * 0.5 + node.padding;\n  node.width = bbox.width + 2 * node.padding;\n  if (node.icon) {\n    if (node.type === nodeType.CIRCLE) {\n      node.height += 50;\n      node.width += 50;\n      const icon = nodeElem.append(\"foreignObject\").attr(\"height\", \"50px\").attr(\"width\", node.width).attr(\"style\", \"text-align: center;\");\n      icon.append(\"div\").attr(\"class\", \"icon-container\").append(\"i\").attr(\"class\", \"node-icon-\" + section + \" \" + node.icon);\n      textElem.attr(\n        \"transform\",\n        \"translate(\" + node.width / 2 + \", \" + (node.height / 2 - 1.5 * node.padding) + \")\"\n      );\n    } else {\n      node.width += 50;\n      const orgHeight = node.height;\n      node.height = Math.max(orgHeight, 60);\n      const heightDiff = Math.abs(node.height - orgHeight);\n      const icon = nodeElem.append(\"foreignObject\").attr(\"width\", \"60px\").attr(\"height\", node.height).attr(\"style\", \"text-align: center;margin-top:\" + heightDiff / 2 + \"px;\");\n      icon.append(\"div\").attr(\"class\", \"icon-container\").append(\"i\").attr(\"class\", \"node-icon-\" + section + \" \" + node.icon);\n      textElem.attr(\n        \"transform\",\n        \"translate(\" + (25 + node.width / 2) + \", \" + (heightDiff / 2 + node.padding / 2) + \")\"\n      );\n    }\n  } else {\n    if (!htmlLabels) {\n      const dx = node.width / 2;\n      const dy = node.padding / 2;\n      textElem.attr(\"transform\", \"translate(\" + dx + \", \" + dy + \")\");\n    } else {\n      const dx = (node.width - bbox.width) / 2;\n      const dy = (node.height - bbox.height) / 2;\n      textElem.attr(\"transform\", \"translate(\" + dx + \", \" + dy + \")\");\n    }\n  }\n  switch (node.type) {\n    case nodeType.DEFAULT:\n      defaultBkg(bkgElem, node, section);\n      break;\n    case nodeType.ROUNDED_RECT:\n      roundedRectBkg(bkgElem, node);\n      break;\n    case nodeType.RECT:\n      rectBkg(bkgElem, node);\n      break;\n    case nodeType.CIRCLE:\n      bkgElem.attr(\"transform\", \"translate(\" + node.width / 2 + \", \" + +node.height / 2 + \")\");\n      circleBkg(bkgElem, node);\n      break;\n    case nodeType.CLOUD:\n      cloudBkg(bkgElem, node);\n      break;\n    case nodeType.BANG:\n      bangBkg(bkgElem, node);\n      break;\n    case nodeType.HEXAGON:\n      hexagonBkg(bkgElem, node);\n      break;\n  }\n  setElementForId(node.id, nodeElem);\n  return node.height;\n};\nconst drawEdge = function drawEdge2(edgesElem, mindmap, parent, depth, fullSection) {\n  const section = fullSection % (MAX_SECTIONS - 1);\n  const sx = parent.x + parent.width / 2;\n  const sy = parent.y + parent.height / 2;\n  const ex = mindmap.x + mindmap.width / 2;\n  const ey = mindmap.y + mindmap.height / 2;\n  const mx = ex > sx ? sx + Math.abs(sx - ex) / 2 : sx - Math.abs(sx - ex) / 2;\n  const my = ey > sy ? sy + Math.abs(sy - ey) / 2 : sy - Math.abs(sy - ey) / 2;\n  const qx = ex > sx ? Math.abs(sx - mx) / 2 + sx : -Math.abs(sx - mx) / 2 + sx;\n  const qy = ey > sy ? Math.abs(sy - my) / 2 + sy : -Math.abs(sy - my) / 2 + sy;\n  edgesElem.append(\"path\").attr(\n    \"d\",\n    parent.direction === \"TB\" || parent.direction === \"BT\" ? `M${sx},${sy} Q${sx},${qy} ${mx},${my} T${ex},${ey}` : `M${sx},${sy} Q${qx},${sy} ${mx},${my} T${ex},${ey}`\n  ).attr(\"class\", \"edge section-edge-\" + section + \" edge-depth-\" + depth);\n};\nconst positionNode = function(node) {\n  const nodeElem = getElementById(node.id);\n  const x = node.x || 0;\n  const y = node.y || 0;\n  nodeElem.attr(\"transform\", \"translate(\" + x + \",\" + y + \")\");\n};\nconst svgDraw = { drawNode, positionNode, drawEdge };\ncytoscape_dist_cytoscape_umd_js__WEBPACK_IMPORTED_MODULE_1___default().use((cytoscape_cose_bilkent__WEBPACK_IMPORTED_MODULE_2___default()));\nfunction drawNodes(svg, mindmap, section, conf) {\n  svgDraw.drawNode(svg, mindmap, section, conf);\n  if (mindmap.children) {\n    mindmap.children.forEach((child, index) => {\n      drawNodes(svg, child, section < 0 ? index : section, conf);\n    });\n  }\n}\nfunction drawEdges(edgesEl, cy) {\n  cy.edges().map((edge, id) => {\n    const data = edge.data();\n    if (edge[0]._private.bodyBounds) {\n      const bounds = edge[0]._private.rscratch;\n      _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l.trace(\"Edge: \", id, data);\n      edgesEl.insert(\"path\").attr(\n        \"d\",\n        `M ${bounds.startX},${bounds.startY} L ${bounds.midX},${bounds.midY} L${bounds.endX},${bounds.endY} `\n      ).attr(\"class\", \"edge section-edge-\" + data.section + \" edge-depth-\" + data.depth);\n    }\n  });\n}\nfunction addNodes(mindmap, cy, conf, level) {\n  cy.add({\n    group: \"nodes\",\n    data: {\n      id: mindmap.id,\n      labelText: mindmap.descr,\n      height: mindmap.height,\n      width: mindmap.width,\n      level,\n      nodeId: mindmap.id,\n      padding: mindmap.padding,\n      type: mindmap.type\n    },\n    position: {\n      x: mindmap.x,\n      y: mindmap.y\n    }\n  });\n  if (mindmap.children) {\n    mindmap.children.forEach((child) => {\n      addNodes(child, cy, conf, level + 1);\n      cy.add({\n        group: \"edges\",\n        data: {\n          id: `${mindmap.id}_${child.id}`,\n          source: mindmap.id,\n          target: child.id,\n          depth: level,\n          section: child.section\n        }\n      });\n    });\n  }\n}\nfunction layoutMindmap(node, conf) {\n  return new Promise((resolve) => {\n    const renderEl = (0,d3__WEBPACK_IMPORTED_MODULE_0__.select)(\"body\").append(\"div\").attr(\"id\", \"cy\").attr(\"style\", \"display:none\");\n    const cy = cytoscape_dist_cytoscape_umd_js__WEBPACK_IMPORTED_MODULE_1___default()({\n      container: document.getElementById(\"cy\"),\n      // container to render in\n      style: [\n        {\n          selector: \"edge\",\n          style: {\n            \"curve-style\": \"bezier\"\n          }\n        }\n      ]\n    });\n    renderEl.remove();\n    addNodes(node, cy, conf, 0);\n    cy.nodes().forEach(function(n) {\n      n.layoutDimensions = () => {\n        const data = n.data();\n        return { w: data.width, h: data.height };\n      };\n    });\n    cy.layout({\n      name: \"cose-bilkent\",\n      quality: \"proof\",\n      // headless: true,\n      styleEnabled: false,\n      animate: false\n    }).run();\n    cy.ready((e) => {\n      _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l.info(\"Ready\", e);\n      resolve(cy);\n    });\n  });\n}\nfunction positionNodes(cy) {\n  cy.nodes().map((node, id) => {\n    const data = node.data();\n    data.x = node.position().x;\n    data.y = node.position().y;\n    svgDraw.positionNode(data);\n    const el = getElementById(data.nodeId);\n    _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l.info(\"Id:\", id, \"Position: (\", node.position().x, \", \", node.position().y, \")\", data);\n    el.attr(\n      \"transform\",\n      `translate(${node.position().x - data.width / 2}, ${node.position().y - data.height / 2})`\n    );\n    el.attr(\"attr\", `apa-${id})`);\n  });\n}\nconst draw = async (text, id, version, diagObj) => {\n  const conf = (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.c)();\n  conf.htmlLabels = false;\n  _mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.l.debug(\"Rendering mindmap diagram\\n\" + text, diagObj.parser);\n  const securityLevel = (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.c)().securityLevel;\n  let sandboxElement;\n  if (securityLevel === \"sandbox\") {\n    sandboxElement = (0,d3__WEBPACK_IMPORTED_MODULE_0__.select)(\"#i\" + id);\n  }\n  const root = securityLevel === \"sandbox\" ? (0,d3__WEBPACK_IMPORTED_MODULE_0__.select)(sandboxElement.nodes()[0].contentDocument.body) : (0,d3__WEBPACK_IMPORTED_MODULE_0__.select)(\"body\");\n  const svg = root.select(\"#\" + id);\n  svg.append(\"g\");\n  const mm = diagObj.db.getMindmap();\n  const edgesElem = svg.append(\"g\");\n  edgesElem.attr(\"class\", \"mindmap-edges\");\n  const nodesElem = svg.append(\"g\");\n  nodesElem.attr(\"class\", \"mindmap-nodes\");\n  drawNodes(nodesElem, mm, -1, conf);\n  const cy = await layoutMindmap(mm, conf);\n  drawEdges(edgesElem, cy);\n  positionNodes(cy);\n  (0,_mermaid_04fb0060_js__WEBPACK_IMPORTED_MODULE_7__.o)(void 0, svg, conf.mindmap.padding, conf.mindmap.useMaxWidth);\n};\nconst mindmapRenderer = {\n  draw\n};\nconst genSections = (options) => {\n  let sections = \"\";\n  for (let i = 0; i < options.THEME_COLOR_LIMIT; i++) {\n    options[\"lineColor\" + i] = options[\"lineColor\" + i] || options[\"cScaleInv\" + i];\n    if ((0,khroma__WEBPACK_IMPORTED_MODULE_9__[\"default\"])(options[\"lineColor\" + i])) {\n      options[\"lineColor\" + i] = (0,khroma__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(options[\"lineColor\" + i], 20);\n    } else {\n      options[\"lineColor\" + i] = (0,khroma__WEBPACK_IMPORTED_MODULE_11__[\"default\"])(options[\"lineColor\" + i], 20);\n    }\n  }\n  for (let i = 0; i < options.THEME_COLOR_LIMIT; i++) {\n    const sw = \"\" + (17 - 3 * i);\n    sections += `\n    .section-${i - 1} rect, .section-${i - 1} path, .section-${i - 1} circle, .section-${i - 1} polygon, .section-${i - 1} path  {\n      fill: ${options[\"cScale\" + i]};\n    }\n    .section-${i - 1} text {\n     fill: ${options[\"cScaleLabel\" + i]};\n    }\n    .node-icon-${i - 1} {\n      font-size: 40px;\n      color: ${options[\"cScaleLabel\" + i]};\n    }\n    .section-edge-${i - 1}{\n      stroke: ${options[\"cScale\" + i]};\n    }\n    .edge-depth-${i - 1}{\n      stroke-width: ${sw};\n    }\n    .section-${i - 1} line {\n      stroke: ${options[\"cScaleInv\" + i]} ;\n      stroke-width: 3;\n    }\n\n    .disabled, .disabled circle, .disabled text {\n      fill: lightgray;\n    }\n    .disabled text {\n      fill: #efefef;\n    }\n    `;\n  }\n  return sections;\n};\nconst getStyles = (options) => `\n  .edge {\n    stroke-width: 3;\n  }\n  ${genSections(options)}\n  .section-root rect, .section-root path, .section-root circle, .section-root polygon  {\n    fill: ${options.git0};\n  }\n  .section-root text {\n    fill: ${options.gitBranchLabel0};\n  }\n  .icon-container {\n    height:100%;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n  }\n  .edge {\n    fill: none;\n  }\n  .mindmap-node-label {\n    dy: 1em;\n    alignment-baseline: middle;\n    text-anchor: middle;\n    dominant-baseline: middle;\n    text-align: center;\n  }\n`;\nconst mindmapStyles = getStyles;\nconst diagram = {\n  db: mindmapDb,\n  renderer: mindmapRenderer,\n  parser: mindmapParser,\n  styles: mindmapStyles\n};\n\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/mermaid/dist/mindmap-definition-e19a4bed.js?");

/***/ })

}]);