"use strict";
/*
 * 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_cytoscape_dist_cytoscape_esm_mjs"],{

/***/ "../node_modules/cytoscape/dist/cytoscape.esm.mjs":
/*!********************************************************!*\
  !*** ../node_modules/cytoscape/dist/cytoscape.esm.mjs ***!
  \********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   \"default\": () => (/* binding */ cytoscape)\n/* harmony export */ });\n/**\n * Copyright (c) 2016-2025, 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\nfunction _arrayLikeToArray(r, a) {\n  (null == a || a > r.length) && (a = r.length);\n  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n  return n;\n}\nfunction _arrayWithHoles(r) {\n  if (Array.isArray(r)) return r;\n}\nfunction _arrayWithoutHoles(r) {\n  if (Array.isArray(r)) return _arrayLikeToArray(r);\n}\nfunction _classCallCheck(a, n) {\n  if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\");\n}\nfunction _defineProperties(e, r) {\n  for (var t = 0; t < r.length; t++) {\n    var o = r[t];\n    o.enumerable = o.enumerable || false, o.configurable = true, \"value\" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);\n  }\n}\nfunction _createClass(e, r, t) {\n  return r && _defineProperties(e.prototype, r), Object.defineProperty(e, \"prototype\", {\n    writable: false\n  }), e;\n}\nfunction _createForOfIteratorHelper(r, e) {\n  var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n  if (!t) {\n    if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {\n      t && (r = t);\n      var n = 0,\n        F = function () {};\n      return {\n        s: F,\n        n: function () {\n          return n >= r.length ? {\n            done: true\n          } : {\n            done: false,\n            value: r[n++]\n          };\n        },\n        e: function (r) {\n          throw r;\n        },\n        f: F\n      };\n    }\n    throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n  }\n  var o,\n    a = true,\n    u = false;\n  return {\n    s: function () {\n      t = t.call(r);\n    },\n    n: function () {\n      var r = t.next();\n      return a = r.done, r;\n    },\n    e: function (r) {\n      u = true, o = r;\n    },\n    f: function () {\n      try {\n        a || null == t.return || t.return();\n      } finally {\n        if (u) throw o;\n      }\n    }\n  };\n}\nfunction _defineProperty$1(e, r, t) {\n  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n    value: t,\n    enumerable: true,\n    configurable: true,\n    writable: true\n  }) : e[r] = t, e;\n}\nfunction _iterableToArray(r) {\n  if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nfunction _iterableToArrayLimit(r, l) {\n  var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n  if (null != t) {\n    var e,\n      n,\n      i,\n      u,\n      a = [],\n      f = true,\n      o = false;\n    try {\n      if (i = (t = t.call(r)).next, 0 === l) {\n        if (Object(t) !== t) return;\n        f = !1;\n      } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n    } catch (r) {\n      o = true, n = r;\n    } finally {\n      try {\n        if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n      } finally {\n        if (o) throw n;\n      }\n    }\n    return a;\n  }\n}\nfunction _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}\nfunction _nonIterableSpread() {\n  throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _toConsumableArray(r) {\n  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();\n}\nfunction _toPrimitive(t, r) {\n  if (\"object\" != typeof t || !t) return t;\n  var e = t[Symbol.toPrimitive];\n  if (undefined !== e) {\n    var i = e.call(t, r);\n    if (\"object\" != typeof i) return i;\n    throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n  }\n  return (String )(t);\n}\nfunction _toPropertyKey(t) {\n  var i = _toPrimitive(t, \"string\");\n  return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n  \"@babel/helpers - typeof\";\n\n  return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n    return typeof o;\n  } : function (o) {\n    return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n  }, _typeof(o);\n}\nfunction _unsupportedIterableToArray(r, a) {\n  if (r) {\n    if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n    var t = {}.toString.call(r).slice(8, -1);\n    return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : undefined;\n  }\n}\n\nvar _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef\n\nvar navigator = _window ? _window.navigator : null;\n_window ? _window.document : null;\nvar typeofstr = _typeof('');\nvar typeofobj = _typeof({});\nvar typeoffn = _typeof(function () {});\nvar typeofhtmlele = typeof HTMLElement === \"undefined\" ? \"undefined\" : _typeof(HTMLElement);\nvar instanceStr = function instanceStr(obj) {\n  return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;\n};\n\nvar string = function string(obj) {\n  return obj != null && _typeof(obj) == typeofstr;\n};\nvar fn$6 = function fn(obj) {\n  return obj != null && _typeof(obj) === typeoffn;\n};\nvar array = function array(obj) {\n  return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);\n};\nvar plainObject = function plainObject(obj) {\n  return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;\n};\nvar object = function object(obj) {\n  return obj != null && _typeof(obj) === typeofobj;\n};\nvar number$1 = function number(obj) {\n  return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);\n};\nvar integer = function integer(obj) {\n  return number$1(obj) && Math.floor(obj) === obj;\n};\nvar htmlElement = function htmlElement(obj) {\n  if ('undefined' === typeofhtmlele) {\n    return undefined;\n  } else {\n    return null != obj && obj instanceof HTMLElement;\n  }\n};\nvar elementOrCollection = function elementOrCollection(obj) {\n  return element(obj) || collection(obj);\n};\nvar element = function element(obj) {\n  return instanceStr(obj) === 'collection' && obj._private.single;\n};\nvar collection = function collection(obj) {\n  return instanceStr(obj) === 'collection' && !obj._private.single;\n};\nvar core = function core(obj) {\n  return instanceStr(obj) === 'core';\n};\nvar stylesheet = function stylesheet(obj) {\n  return instanceStr(obj) === 'stylesheet';\n};\nvar event = function event(obj) {\n  return instanceStr(obj) === 'event';\n};\nvar 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  return false; // otherwise, we don't know what we've got\n};\nvar 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};\nvar 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};\nvar promise = function promise(obj) {\n  return object(obj) && fn$6(obj.then);\n};\nvar ms = function ms() {\n  return navigator && navigator.userAgent.match(/msie|trident|edge/i);\n}; // probably a better way to detect this...\n\nvar memoize = 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      var args = [];\n      for (var i = 0; i < arguments.length; i++) {\n        args.push(arguments[i]);\n      }\n      return args.join('$');\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    if (!(ret = cache[k])) {\n      ret = cache[k] = fn.apply(self, args);\n    }\n    return ret;\n  };\n  _memoizedFn.cache = {};\n  return _memoizedFn;\n};\n\nvar camel2dash = memoize(function (str) {\n  return str.replace(/([A-Z])/g, function (v) {\n    return '-' + v.toLowerCase();\n  });\n});\nvar dash2camel = memoize(function (str) {\n  return str.replace(/(-\\w)/g, function (v) {\n    return v[1].toUpperCase();\n  });\n});\nvar prependCamel = memoize(function (prefix, str) {\n  return prefix + str[0].toUpperCase() + str.substring(1);\n}, function (prefix, str) {\n  return prefix + '$' + str;\n});\nvar capitalize = function capitalize(str) {\n  if (emptyString(str)) {\n    return str;\n  }\n  return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar number = '(?:[-+]?(?:(?:\\\\d+|\\\\d*\\\\.\\\\d+)(?:[Ee][+-]?\\\\d+)?))';\nvar rgba = 'rgb[a]?\\\\((' + number + '[%]?)\\\\s*,\\\\s*(' + number + '[%]?)\\\\s*,\\\\s*(' + number + '[%]?)(?:\\\\s*,\\\\s*(' + number + '))?\\\\)';\nvar rgbaNoBackRefs = 'rgb[a]?\\\\((?:' + number + '[%]?)\\\\s*,\\\\s*(?:' + number + '[%]?)\\\\s*,\\\\s*(?:' + number + '[%]?)(?:\\\\s*,\\\\s*(?:' + number + '))?\\\\)';\nvar hsla = 'hsl[a]?\\\\((' + number + ')\\\\s*,\\\\s*(' + number + '[%])\\\\s*,\\\\s*(' + number + '[%])(?:\\\\s*,\\\\s*(' + number + '))?\\\\)';\nvar hslaNoBackRefs = 'hsl[a]?\\\\((?:' + number + ')\\\\s*,\\\\s*(?:' + number + '[%])\\\\s*,\\\\s*(?:' + number + '[%])(?:\\\\s*,\\\\s*(?:' + number + '))?\\\\)';\nvar hex3 = '\\\\#[0-9a-fA-F]{3}';\nvar hex6 = '\\\\#[0-9a-fA-F]{6}';\n\nvar 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};\nvar descending = function descending(a, b) {\n  return -1 * ascending(a, b);\n};\n\nvar extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {\n  var args = arguments;\n  for (var i = 1; i < args.length; i++) {\n    var obj = args[i];\n    if (obj == null) {\n      continue;\n    }\n    var keys = Object.keys(obj);\n    for (var j = 0; j < keys.length; j++) {\n      var k = keys[j];\n      tgt[k] = obj[k];\n    }\n  }\n  return tgt;\n};\n\n// get [r, g, b] from #abc or #aabbcc\nvar hex2tuple = function hex2tuple(hex) {\n  if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {\n    return;\n  }\n  var shortHex = hex.length === 4;\n  var r, g, b;\n  var base = 16;\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  return [r, g, b];\n};\n\n// get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)\nvar hsl2tuple = function hsl2tuple(hsl) {\n  var ret;\n  var h, s, l, a, r, g, b;\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  var m = new RegExp('^' + hsla + '$').exec(hsl);\n  if (m) {\n    // get hue\n    h = parseInt(m[1]);\n    if (h < 0) {\n      h = (360 - -1 * h % 360) % 360;\n    } else if (h > 360) {\n      h = h % 360;\n    }\n    h /= 360; // normalise on [0, 1]\n\n    s = parseFloat(m[2]);\n    if (s < 0 || s > 100) {\n      return;\n    } // saturation is [0, 100]\n    s = s / 100; // normalise on [0, 1]\n\n    l = parseFloat(m[3]);\n    if (l < 0 || l > 100) {\n      return;\n    } // lightness is [0, 100]\n    l = l / 100; // normalise on [0, 1]\n\n    a = m[4];\n    if (a !== undefined) {\n      a = parseFloat(a);\n      if (a < 0 || a > 1) {\n        return;\n      } // alpha is [0, 1]\n    }\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    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    ret = [r, g, b, a];\n  }\n  return ret;\n};\n\n// get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)\nvar rgb2tuple = function rgb2tuple(rgb) {\n  var ret;\n  var m = new RegExp('^' + rgba + '$').exec(rgb);\n  if (m) {\n    ret = [];\n    var isPct = [];\n    for (var i = 1; i <= 3; i++) {\n      var channel = m[i];\n      if (channel[channel.length - 1] === '%') {\n        isPct[i] = true;\n      }\n      channel = parseFloat(channel);\n      if (isPct[i]) {\n        channel = channel / 100 * 255; // normalise to [0, 255]\n      }\n      if (channel < 0 || channel > 255) {\n        return;\n      } // invalid channel value\n\n      ret.push(Math.floor(channel));\n    }\n    var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];\n    var allArePct = isPct[1] && isPct[2] && isPct[3];\n    if (atLeastOneIsPct && !allArePct) {\n      return;\n    } // must all be percent values if one is\n\n    var alpha = m[4];\n    if (alpha !== undefined) {\n      alpha = parseFloat(alpha);\n      if (alpha < 0 || alpha > 1) {\n        return;\n      } // invalid alpha value\n\n      ret.push(alpha);\n    }\n  }\n  return ret;\n};\nvar colorname2tuple = function colorname2tuple(color) {\n  return colors[color.toLowerCase()];\n};\nvar color2tuple = function color2tuple(color) {\n  return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);\n};\nvar colors = {\n  // special colour names\n  transparent: [0, 0, 0, 0],\n  // NB alpha === 0\n\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// sets the value in a map (map may not be built)\nvar setMap = function setMap(options) {\n  var obj = options.map;\n  var keys = options.keys;\n  var l = keys.length;\n  for (var i = 0; i < l; i++) {\n    var key = keys[i];\n    if (plainObject(key)) {\n      throw Error('Tried to set map with object key');\n    }\n    if (i < keys.length - 1) {\n      // extend the map if necessary\n      if (obj[key] == null) {\n        obj[key] = {};\n      }\n      obj = obj[key];\n    } else {\n      // set the value\n      obj[key] = options.value;\n    }\n  }\n};\n\n// gets the value in a map even if it's not built in places\nvar getMap = function getMap(options) {\n  var obj = options.map;\n  var keys = options.keys;\n  var l = keys.length;\n  for (var i = 0; i < l; i++) {\n    var key = keys[i];\n    if (plainObject(key)) {\n      throw Error('Tried to get map with object key');\n    }\n    obj = obj[key];\n    if (obj == null) {\n      return obj;\n    }\n  }\n  return obj;\n};\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\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\nvar isObject_1;\nvar hasRequiredIsObject;\n\nfunction requireIsObject () {\n\tif (hasRequiredIsObject) return isObject_1;\n\thasRequiredIsObject = 1;\n\tfunction isObject(value) {\n\t  var type = typeof value;\n\t  return value != null && (type == 'object' || type == 'function');\n\t}\n\n\tisObject_1 = isObject;\n\treturn isObject_1;\n}\n\n/** Detect free variable `global` from Node.js. */\n\nvar _freeGlobal;\nvar hasRequired_freeGlobal;\n\nfunction require_freeGlobal () {\n\tif (hasRequired_freeGlobal) return _freeGlobal;\n\thasRequired_freeGlobal = 1;\n\tvar freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;\n\n\t_freeGlobal = freeGlobal;\n\treturn _freeGlobal;\n}\n\nvar _root;\nvar hasRequired_root;\n\nfunction require_root () {\n\tif (hasRequired_root) return _root;\n\thasRequired_root = 1;\n\tvar freeGlobal = require_freeGlobal();\n\n\t/** Detect free variable `self`. */\n\tvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n\t/** Used as a reference to the global object. */\n\tvar root = freeGlobal || freeSelf || Function('return this')();\n\n\t_root = root;\n\treturn _root;\n}\n\nvar now_1;\nvar hasRequiredNow;\n\nfunction requireNow () {\n\tif (hasRequiredNow) return now_1;\n\thasRequiredNow = 1;\n\tvar root = require_root();\n\n\t/**\n\t * Gets the timestamp of the number of milliseconds that have elapsed since\n\t * the Unix epoch (1 January 1970 00:00:00 UTC).\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 2.4.0\n\t * @category Date\n\t * @returns {number} Returns the timestamp.\n\t * @example\n\t *\n\t * _.defer(function(stamp) {\n\t *   console.log(_.now() - stamp);\n\t * }, _.now());\n\t * // => Logs the number of milliseconds it took for the deferred invocation.\n\t */\n\tvar now = function() {\n\t  return root.Date.now();\n\t};\n\n\tnow_1 = now;\n\treturn now_1;\n}\n\n/** Used to match a single whitespace character. */\n\nvar _trimmedEndIndex;\nvar hasRequired_trimmedEndIndex;\n\nfunction require_trimmedEndIndex () {\n\tif (hasRequired_trimmedEndIndex) return _trimmedEndIndex;\n\thasRequired_trimmedEndIndex = 1;\n\tvar reWhitespace = /\\s/;\n\n\t/**\n\t * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n\t * character of `string`.\n\t *\n\t * @private\n\t * @param {string} string The string to inspect.\n\t * @returns {number} Returns the index of the last non-whitespace character.\n\t */\n\tfunction trimmedEndIndex(string) {\n\t  var index = string.length;\n\n\t  while (index-- && reWhitespace.test(string.charAt(index))) {}\n\t  return index;\n\t}\n\n\t_trimmedEndIndex = trimmedEndIndex;\n\treturn _trimmedEndIndex;\n}\n\nvar _baseTrim;\nvar hasRequired_baseTrim;\n\nfunction require_baseTrim () {\n\tif (hasRequired_baseTrim) return _baseTrim;\n\thasRequired_baseTrim = 1;\n\tvar trimmedEndIndex = require_trimmedEndIndex();\n\n\t/** Used to match leading whitespace. */\n\tvar reTrimStart = /^\\s+/;\n\n\t/**\n\t * The base implementation of `_.trim`.\n\t *\n\t * @private\n\t * @param {string} string The string to trim.\n\t * @returns {string} Returns the trimmed string.\n\t */\n\tfunction baseTrim(string) {\n\t  return string\n\t    ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n\t    : string;\n\t}\n\n\t_baseTrim = baseTrim;\n\treturn _baseTrim;\n}\n\nvar _Symbol;\nvar hasRequired_Symbol;\n\nfunction require_Symbol () {\n\tif (hasRequired_Symbol) return _Symbol;\n\thasRequired_Symbol = 1;\n\tvar root = require_root();\n\n\t/** Built-in value references. */\n\tvar Symbol = root.Symbol;\n\n\t_Symbol = Symbol;\n\treturn _Symbol;\n}\n\nvar _getRawTag;\nvar hasRequired_getRawTag;\n\nfunction require_getRawTag () {\n\tif (hasRequired_getRawTag) return _getRawTag;\n\thasRequired_getRawTag = 1;\n\tvar Symbol = require_Symbol();\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Used to resolve the\n\t * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n\t * of values.\n\t */\n\tvar nativeObjectToString = objectProto.toString;\n\n\t/** Built-in value references. */\n\tvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n\t/**\n\t * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @returns {string} Returns the raw `toStringTag`.\n\t */\n\tfunction getRawTag(value) {\n\t  var isOwn = hasOwnProperty.call(value, symToStringTag),\n\t      tag = value[symToStringTag];\n\n\t  try {\n\t    value[symToStringTag] = undefined;\n\t    var unmasked = true;\n\t  } catch (e) {}\n\n\t  var result = nativeObjectToString.call(value);\n\t  if (unmasked) {\n\t    if (isOwn) {\n\t      value[symToStringTag] = tag;\n\t    } else {\n\t      delete value[symToStringTag];\n\t    }\n\t  }\n\t  return result;\n\t}\n\n\t_getRawTag = getRawTag;\n\treturn _getRawTag;\n}\n\n/** Used for built-in method references. */\n\nvar _objectToString;\nvar hasRequired_objectToString;\n\nfunction require_objectToString () {\n\tif (hasRequired_objectToString) return _objectToString;\n\thasRequired_objectToString = 1;\n\tvar objectProto = Object.prototype;\n\n\t/**\n\t * Used to resolve the\n\t * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n\t * of values.\n\t */\n\tvar nativeObjectToString = objectProto.toString;\n\n\t/**\n\t * Converts `value` to a string using `Object.prototype.toString`.\n\t *\n\t * @private\n\t * @param {*} value The value to convert.\n\t * @returns {string} Returns the converted string.\n\t */\n\tfunction objectToString(value) {\n\t  return nativeObjectToString.call(value);\n\t}\n\n\t_objectToString = objectToString;\n\treturn _objectToString;\n}\n\nvar _baseGetTag;\nvar hasRequired_baseGetTag;\n\nfunction require_baseGetTag () {\n\tif (hasRequired_baseGetTag) return _baseGetTag;\n\thasRequired_baseGetTag = 1;\n\tvar Symbol = require_Symbol(),\n\t    getRawTag = require_getRawTag(),\n\t    objectToString = require_objectToString();\n\n\t/** `Object#toString` result references. */\n\tvar nullTag = '[object Null]',\n\t    undefinedTag = '[object Undefined]';\n\n\t/** Built-in value references. */\n\tvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n\t/**\n\t * The base implementation of `getTag` without fallbacks for buggy environments.\n\t *\n\t * @private\n\t * @param {*} value The value to query.\n\t * @returns {string} Returns the `toStringTag`.\n\t */\n\tfunction baseGetTag(value) {\n\t  if (value == null) {\n\t    return value === undefined ? undefinedTag : nullTag;\n\t  }\n\t  return (symToStringTag && symToStringTag in Object(value))\n\t    ? getRawTag(value)\n\t    : objectToString(value);\n\t}\n\n\t_baseGetTag = baseGetTag;\n\treturn _baseGetTag;\n}\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\nvar isObjectLike_1;\nvar hasRequiredIsObjectLike;\n\nfunction requireIsObjectLike () {\n\tif (hasRequiredIsObjectLike) return isObjectLike_1;\n\thasRequiredIsObjectLike = 1;\n\tfunction isObjectLike(value) {\n\t  return value != null && typeof value == 'object';\n\t}\n\n\tisObjectLike_1 = isObjectLike;\n\treturn isObjectLike_1;\n}\n\nvar isSymbol_1;\nvar hasRequiredIsSymbol;\n\nfunction requireIsSymbol () {\n\tif (hasRequiredIsSymbol) return isSymbol_1;\n\thasRequiredIsSymbol = 1;\n\tvar baseGetTag = require_baseGetTag(),\n\t    isObjectLike = requireIsObjectLike();\n\n\t/** `Object#toString` result references. */\n\tvar symbolTag = '[object Symbol]';\n\n\t/**\n\t * Checks if `value` is classified as a `Symbol` primitive or object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n\t * @example\n\t *\n\t * _.isSymbol(Symbol.iterator);\n\t * // => true\n\t *\n\t * _.isSymbol('abc');\n\t * // => false\n\t */\n\tfunction isSymbol(value) {\n\t  return typeof value == 'symbol' ||\n\t    (isObjectLike(value) && baseGetTag(value) == symbolTag);\n\t}\n\n\tisSymbol_1 = isSymbol;\n\treturn isSymbol_1;\n}\n\nvar toNumber_1;\nvar hasRequiredToNumber;\n\nfunction requireToNumber () {\n\tif (hasRequiredToNumber) return toNumber_1;\n\thasRequiredToNumber = 1;\n\tvar baseTrim = require_baseTrim(),\n\t    isObject = requireIsObject(),\n\t    isSymbol = requireIsSymbol();\n\n\t/** Used as references for various `Number` constants. */\n\tvar NAN = 0 / 0;\n\n\t/** Used to detect bad signed hexadecimal string values. */\n\tvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n\t/** Used to detect binary string values. */\n\tvar reIsBinary = /^0b[01]+$/i;\n\n\t/** Used to detect octal string values. */\n\tvar reIsOctal = /^0o[0-7]+$/i;\n\n\t/** Built-in method references without a dependency on `root`. */\n\tvar freeParseInt = parseInt;\n\n\t/**\n\t * Converts `value` to a number.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to process.\n\t * @returns {number} Returns the number.\n\t * @example\n\t *\n\t * _.toNumber(3.2);\n\t * // => 3.2\n\t *\n\t * _.toNumber(Number.MIN_VALUE);\n\t * // => 5e-324\n\t *\n\t * _.toNumber(Infinity);\n\t * // => Infinity\n\t *\n\t * _.toNumber('3.2');\n\t * // => 3.2\n\t */\n\tfunction toNumber(value) {\n\t  if (typeof value == 'number') {\n\t    return value;\n\t  }\n\t  if (isSymbol(value)) {\n\t    return NAN;\n\t  }\n\t  if (isObject(value)) {\n\t    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n\t    value = isObject(other) ? (other + '') : other;\n\t  }\n\t  if (typeof value != 'string') {\n\t    return value === 0 ? value : +value;\n\t  }\n\t  value = baseTrim(value);\n\t  var isBinary = reIsBinary.test(value);\n\t  return (isBinary || reIsOctal.test(value))\n\t    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n\t    : (reIsBadHex.test(value) ? NAN : +value);\n\t}\n\n\ttoNumber_1 = toNumber;\n\treturn toNumber_1;\n}\n\nvar debounce_1;\nvar hasRequiredDebounce;\n\nfunction requireDebounce () {\n\tif (hasRequiredDebounce) return debounce_1;\n\thasRequiredDebounce = 1;\n\tvar isObject = requireIsObject(),\n\t    now = requireNow(),\n\t    toNumber = requireToNumber();\n\n\t/** Error message constants. */\n\tvar FUNC_ERROR_TEXT = 'Expected a function';\n\n\t/* Built-in method references for those with the same name as other `lodash` methods. */\n\tvar nativeMax = Math.max,\n\t    nativeMin = Math.min;\n\n\t/**\n\t * Creates a debounced function that delays invoking `func` until after `wait`\n\t * milliseconds have elapsed since the last time the debounced function was\n\t * invoked. The debounced function comes with a `cancel` method to cancel\n\t * delayed `func` invocations and a `flush` method to immediately invoke them.\n\t * Provide `options` to indicate whether `func` should be invoked on the\n\t * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n\t * with the last arguments provided to the debounced function. Subsequent\n\t * calls to the debounced function return the result of the last `func`\n\t * invocation.\n\t *\n\t * **Note:** If `leading` and `trailing` options are `true`, `func` is\n\t * invoked on the trailing edge of the timeout only if the debounced function\n\t * is invoked more than once during the `wait` timeout.\n\t *\n\t * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n\t * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n\t *\n\t * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n\t * for details over the differences between `_.debounce` and `_.throttle`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Function\n\t * @param {Function} func The function to debounce.\n\t * @param {number} [wait=0] The number of milliseconds to delay.\n\t * @param {Object} [options={}] The options object.\n\t * @param {boolean} [options.leading=false]\n\t *  Specify invoking on the leading edge of the timeout.\n\t * @param {number} [options.maxWait]\n\t *  The maximum time `func` is allowed to be delayed before it's invoked.\n\t * @param {boolean} [options.trailing=true]\n\t *  Specify invoking on the trailing edge of the timeout.\n\t * @returns {Function} Returns the new debounced function.\n\t * @example\n\t *\n\t * // Avoid costly calculations while the window size is in flux.\n\t * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n\t *\n\t * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n\t * jQuery(element).on('click', _.debounce(sendMail, 300, {\n\t *   'leading': true,\n\t *   'trailing': false\n\t * }));\n\t *\n\t * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n\t * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n\t * var source = new EventSource('/stream');\n\t * jQuery(source).on('message', debounced);\n\t *\n\t * // Cancel the trailing debounced invocation.\n\t * jQuery(window).on('popstate', debounced.cancel);\n\t */\n\tfunction debounce(func, wait, options) {\n\t  var lastArgs,\n\t      lastThis,\n\t      maxWait,\n\t      result,\n\t      timerId,\n\t      lastCallTime,\n\t      lastInvokeTime = 0,\n\t      leading = false,\n\t      maxing = false,\n\t      trailing = true;\n\n\t  if (typeof func != 'function') {\n\t    throw new TypeError(FUNC_ERROR_TEXT);\n\t  }\n\t  wait = toNumber(wait) || 0;\n\t  if (isObject(options)) {\n\t    leading = !!options.leading;\n\t    maxing = 'maxWait' in options;\n\t    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n\t    trailing = 'trailing' in options ? !!options.trailing : trailing;\n\t  }\n\n\t  function invokeFunc(time) {\n\t    var args = lastArgs,\n\t        thisArg = lastThis;\n\n\t    lastArgs = lastThis = undefined;\n\t    lastInvokeTime = time;\n\t    result = func.apply(thisArg, args);\n\t    return result;\n\t  }\n\n\t  function leadingEdge(time) {\n\t    // Reset any `maxWait` timer.\n\t    lastInvokeTime = time;\n\t    // Start the timer for the trailing edge.\n\t    timerId = setTimeout(timerExpired, wait);\n\t    // Invoke the leading edge.\n\t    return leading ? invokeFunc(time) : result;\n\t  }\n\n\t  function remainingWait(time) {\n\t    var timeSinceLastCall = time - lastCallTime,\n\t        timeSinceLastInvoke = time - lastInvokeTime,\n\t        timeWaiting = wait - timeSinceLastCall;\n\n\t    return maxing\n\t      ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n\t      : timeWaiting;\n\t  }\n\n\t  function shouldInvoke(time) {\n\t    var timeSinceLastCall = time - lastCallTime,\n\t        timeSinceLastInvoke = time - lastInvokeTime;\n\n\t    // Either this is the first call, activity has stopped and we're at the\n\t    // trailing edge, the system time has gone backwards and we're treating\n\t    // it as the trailing edge, or we've hit the `maxWait` limit.\n\t    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n\t      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n\t  }\n\n\t  function timerExpired() {\n\t    var time = now();\n\t    if (shouldInvoke(time)) {\n\t      return trailingEdge(time);\n\t    }\n\t    // Restart the timer.\n\t    timerId = setTimeout(timerExpired, remainingWait(time));\n\t  }\n\n\t  function trailingEdge(time) {\n\t    timerId = undefined;\n\n\t    // Only invoke if we have `lastArgs` which means `func` has been\n\t    // debounced at least once.\n\t    if (trailing && lastArgs) {\n\t      return invokeFunc(time);\n\t    }\n\t    lastArgs = lastThis = undefined;\n\t    return result;\n\t  }\n\n\t  function cancel() {\n\t    if (timerId !== undefined) {\n\t      clearTimeout(timerId);\n\t    }\n\t    lastInvokeTime = 0;\n\t    lastArgs = lastCallTime = lastThis = timerId = undefined;\n\t  }\n\n\t  function flush() {\n\t    return timerId === undefined ? result : trailingEdge(now());\n\t  }\n\n\t  function debounced() {\n\t    var time = now(),\n\t        isInvoking = shouldInvoke(time);\n\n\t    lastArgs = arguments;\n\t    lastThis = this;\n\t    lastCallTime = time;\n\n\t    if (isInvoking) {\n\t      if (timerId === undefined) {\n\t        return leadingEdge(lastCallTime);\n\t      }\n\t      if (maxing) {\n\t        // Handle invocations in a tight loop.\n\t        clearTimeout(timerId);\n\t        timerId = setTimeout(timerExpired, wait);\n\t        return invokeFunc(lastCallTime);\n\t      }\n\t    }\n\t    if (timerId === undefined) {\n\t      timerId = setTimeout(timerExpired, wait);\n\t    }\n\t    return result;\n\t  }\n\t  debounced.cancel = cancel;\n\t  debounced.flush = flush;\n\t  return debounced;\n\t}\n\n\tdebounce_1 = debounce;\n\treturn debounce_1;\n}\n\nvar debounceExports = requireDebounce();\nvar debounce = /*@__PURE__*/getDefaultExportFromCjs(debounceExports);\n\nvar performance$1 = _window ? _window.performance : null;\nvar pnow = performance$1 && performance$1.now ? function () {\n  return performance$1.now();\n} : function () {\n  return Date.now();\n};\nvar 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  return function (fn) {\n    if (fn) {\n      setTimeout(function () {\n        fn(pnow());\n      }, 1000 / 60);\n    }\n  };\n}();\nvar requestAnimationFrame = function requestAnimationFrame(fn) {\n  return raf(fn);\n};\nvar performanceNow = pnow;\n\nvar DEFAULT_HASH_SEED = 9261;\nvar K = 65599; // 37 also works pretty well\nvar DEFAULT_HASH_SEED_ALT = 5381;\nvar 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  for (;;) {\n    entry = iterator.next();\n    if (entry.done) {\n      break;\n    }\n    hash = hash * K + entry.value | 0;\n  }\n  return hash;\n};\nvar 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};\nvar 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};\nvar combineHashes = function combineHashes(hash1, hash2) {\n  return hash1 * 0x200000 + hash2;\n};\nvar combineHashesArray = function combineHashesArray(hashes) {\n  return hashes[0] * 0x200000 + hashes[1];\n};\nvar hashArrays = function hashArrays(hashes1, hashes2) {\n  return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];\n};\nvar 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      return entry;\n    }\n  };\n  return hashIterableInts(iterator, seed);\n};\nvar 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      return entry;\n    }\n  };\n  return hashIterableInts(iterator, seed);\n};\nvar hashStrings = function hashStrings() {\n  return hashStringsArray(arguments);\n};\nvar hashStringsArray = function hashStringsArray(strs) {\n  var hash;\n  for (var i = 0; i < strs.length; i++) {\n    var str = strs[i];\n    if (i === 0) {\n      hash = hashString(str);\n    } else {\n      hash = hashString(str, hash);\n    }\n  }\n  return hash;\n};\n\nvar warningsEnabled = true;\nvar warnSupported = console.warn != null;\nvar traceSupported = console.trace != null;\nvar MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;\nvar trueify = function trueify() {\n  return true;\n};\nvar falsify = function falsify() {\n  return false;\n};\nvar zeroify = function zeroify() {\n  return 0;\n};\nvar noop$1 = function noop() {};\nvar error = function error(msg) {\n  throw new Error(msg);\n};\nvar warnings = function warnings(enabled) {\n  if (enabled !== undefined) {\n    warningsEnabled = !!enabled;\n  } else {\n    return warningsEnabled;\n  }\n};\nvar warn = function warn(msg) {\n  if (!warnings()) {\n    return;\n  }\n  if (warnSupported) {\n    console.warn(msg);\n  } else {\n    console.log(msg);\n    if (traceSupported) {\n      console.trace();\n    }\n  }\n};\nvar clone = function clone(obj) {\n  return extend({}, obj);\n};\n\n// gets a shallow copy of the argument\nvar copy = function copy(obj) {\n  if (obj == null) {\n    return obj;\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};\nvar copyArray = function copyArray(arr) {\n  return arr.slice();\n};\nvar uuid = function uuid(a, b /* placeholders */) {\n  for (\n  // loop :)\n  b = a = '';\n  // b - result , a - numeric letiable\n  a++ < 36;\n  //\n  b += a * 51 & 52 // if \"a\" is not 9 or 14 or 19 or 24\n  ?\n  //  return a random number or 4\n  (a ^ 15 // if \"a\" is not 15\n  ?\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  return b;\n};\nvar _staticEmptyObject = {};\nvar staticEmptyObject = function staticEmptyObject() {\n  return _staticEmptyObject;\n};\nvar defaults$g = function defaults(_defaults) {\n  var keys = Object.keys(_defaults);\n  return function (opts) {\n    var filledOpts = {};\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    return filledOpts;\n  };\n};\nvar 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  }\n};\nvar clearArray = function clearArray(arr) {\n  arr.splice(0, arr.length);\n};\nvar 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};\nvar getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {\n  if (prefix) {\n    propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth\n  }\n  return obj[propName];\n};\nvar setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {\n  if (prefix) {\n    propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth\n  }\n  obj[propName] = value;\n};\n\n/* global Map */\nvar ObjectMap = /*#__PURE__*/function () {\n  function ObjectMap() {\n    _classCallCheck(this, ObjectMap);\n    this._obj = {};\n  }\n  return _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}();\nvar Map$1 = typeof Map !== 'undefined' ? Map : ObjectMap;\n\n/* global Set */\n\nvar undef = \"undefined\" ;\nvar ObjectSet = /*#__PURE__*/function () {\n  function ObjectSet(arrayOrObjectSet) {\n    _classCallCheck(this, ObjectSet);\n    this._obj = Object.create(null);\n    this.size = 0;\n    if (arrayOrObjectSet != null) {\n      var arr;\n      if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {\n        arr = arrayOrObjectSet.toArray();\n      } else {\n        arr = arrayOrObjectSet;\n      }\n      for (var i = 0; i < arr.length; i++) {\n        this.add(arr[i]);\n      }\n    }\n  }\n  return _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      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      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      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}();\nvar Set$1 = (typeof Set === \"undefined\" ? \"undefined\" : _typeof(Set)) !== undef ? Set : ObjectSet;\n\n// represents a node or an edge\nvar Element = function Element(cy, params) {\n  var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n  if (cy === undefined || params === undefined || !core(cy)) {\n    error('An element must have a core reference and parameters set');\n    return;\n  }\n  var group = params.group;\n\n  // try to automatically infer the group if unspecified\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  }\n\n  // validate group\n  if (group !== 'nodes' && group !== 'edges') {\n    error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');\n    return;\n  }\n\n  // make the element array-like, just like a collection\n  this.length = 1;\n  this[0] = this;\n\n  // NOTE: when something is added here, add also to ele.json()\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  if (_p.position.x == null) {\n    _p.position.x = 0;\n  }\n  if (_p.position.y == null) {\n    _p.position.y = 0;\n  }\n\n  // renderedPosition overrides if specified\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  var classes = [];\n  if (array(params.classes)) {\n    classes = params.classes;\n  } else if (string(params.classes)) {\n    classes = params.classes.split(/\\s+/);\n  }\n  for (var i = 0, l = classes.length; i < l; i++) {\n    var cls = classes[i];\n    if (!cls || cls === '') {\n      continue;\n    }\n    _p.classes.add(cls);\n  }\n  this.createEmitter();\n  if (restore === undefined || restore) {\n    this.restore();\n  }\n  var bypass = params.style || params.css;\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\nvar defineSearch = function defineSearch(params) {\n  params = {\n    bfs: params.bfs || !params.dfs,\n    dfs: params.dfs || !params.bfs\n  };\n\n  // from pseudocode on wikipedia\n  return function searchFn(roots, fn, directed) {\n    var options;\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    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    var _this$byGroup = this.byGroup(),\n      nodes = _this$byGroup.nodes,\n      edges = _this$byGroup.edges;\n\n    // enqueue v\n    for (var i = 0; i < v.length; i++) {\n      var vi = v[i];\n      var viId = vi.id();\n      if (vi.isNode()) {\n        Q.unshift(vi);\n        if (params.bfs) {\n          V[viId] = true;\n          connectedNodes.push(vi);\n        }\n        id2depth[viId] = 0;\n      }\n    }\n    var _loop = function _loop() {\n        var v = params.bfs ? Q.shift() : Q.pop();\n        var vId = v.id();\n        if (params.dfs) {\n          if (V[vId]) {\n            return 0; // continue\n          }\n          V[vId] = true;\n          connectedNodes.push(v);\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;\n        ret = fn(v, prevEdge, prevNode, j++, depth);\n        if (ret === true) {\n          found = v;\n          return 1; // break\n        }\n        if (ret === false) {\n          return 1; // break\n        }\n        var vwEdges = v.connectedEdges().filter(function (e) {\n          return (!directed || e.source().same(v)) && edges.has(e);\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          if (w.length !== 0 && !V[wId]) {\n            w = w[0];\n            Q.push(w);\n            if (params.bfs) {\n              V[wId] = true;\n              connectedNodes.push(w);\n            }\n            connectedBy[wId] = e;\n            id2depth[wId] = id2depth[vId] + 1;\n          }\n        }\n      },\n      _ret;\n    while (Q.length !== 0) {\n      _ret = _loop();\n      if (_ret === 0) continue;\n      if (_ret === 1) break;\n    }\n    var connectedEles = cy.collection();\n    for (var _i = 0; _i < connectedNodes.length; _i++) {\n      var node = connectedNodes[_i];\n      var edge = connectedBy[node.id()];\n      if (edge != null) {\n        connectedEles.push(edge);\n      }\n      connectedEles.push(node);\n    }\n    return {\n      path: cy.collection(connectedEles),\n      found: cy.collection(found)\n    };\n  };\n};\n\n// search, spanning trees, etc\nvar elesfn$v = {\n  breadthFirstSearch: defineSearch({\n    bfs: true\n  }),\n  depthFirstSearch: defineSearch({\n    dfs: true\n  })\n};\n\n// nice, short mathematical alias\nelesfn$v.bfs = elesfn$v.breadthFirstSearch;\nelesfn$v.dfs = elesfn$v.depthFirstSearch;\n\nvar heap$2 = {exports: {}};\n\nvar heap$1 = heap$2.exports;\n\nvar hasRequiredHeap$1;\n\nfunction requireHeap$1 () {\n\tif (hasRequiredHeap$1) return heap$2.exports;\n\thasRequiredHeap$1 = 1;\n\t(function (module, exports) {\n\t\t// Generated by CoffeeScript 1.8.0\n\t\t(function() {\n\t\t  var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n\t\t  floor = Math.floor, min = Math.min;\n\n\n\t\t  /*\n\t\t  Default comparison function to be used\n\t\t   */\n\n\t\t  defaultCmp = function(x, y) {\n\t\t    if (x < y) {\n\t\t      return -1;\n\t\t    }\n\t\t    if (x > y) {\n\t\t      return 1;\n\t\t    }\n\t\t    return 0;\n\t\t  };\n\n\n\t\t  /*\n\t\t  Insert item x in list a, and keep it sorted assuming a is sorted.\n\t\t  \n\t\t  If x is already in a, insert it to the right of the rightmost x.\n\t\t  \n\t\t  Optional args lo (default 0) and hi (default a.length) bound the slice\n\t\t  of a to be searched.\n\t\t   */\n\n\t\t  insort = function(a, x, lo, hi, cmp) {\n\t\t    var mid;\n\t\t    if (lo == null) {\n\t\t      lo = 0;\n\t\t    }\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    if (lo < 0) {\n\t\t      throw new Error('lo must be non-negative');\n\t\t    }\n\t\t    if (hi == null) {\n\t\t      hi = a.length;\n\t\t    }\n\t\t    while (lo < hi) {\n\t\t      mid = floor((lo + hi) / 2);\n\t\t      if (cmp(x, a[mid]) < 0) {\n\t\t        hi = mid;\n\t\t      } else {\n\t\t        lo = mid + 1;\n\t\t      }\n\t\t    }\n\t\t    return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n\t\t  };\n\n\n\t\t  /*\n\t\t  Push item onto heap, maintaining the heap invariant.\n\t\t   */\n\n\t\t  heappush = function(array, item, cmp) {\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    array.push(item);\n\t\t    return _siftdown(array, 0, array.length - 1, cmp);\n\t\t  };\n\n\n\t\t  /*\n\t\t  Pop the smallest item off the heap, maintaining the heap invariant.\n\t\t   */\n\n\t\t  heappop = function(array, cmp) {\n\t\t    var lastelt, returnitem;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    lastelt = array.pop();\n\t\t    if (array.length) {\n\t\t      returnitem = array[0];\n\t\t      array[0] = lastelt;\n\t\t      _siftup(array, 0, cmp);\n\t\t    } else {\n\t\t      returnitem = lastelt;\n\t\t    }\n\t\t    return returnitem;\n\t\t  };\n\n\n\t\t  /*\n\t\t  Pop and return the current smallest value, and add the new item.\n\t\t  \n\t\t  This is more efficient than heappop() followed by heappush(), and can be\n\t\t  more appropriate when using a fixed size heap. Note that the value\n\t\t  returned may be larger than item! That constrains reasonable use of\n\t\t  this routine unless written as part of a conditional replacement:\n\t\t      if item > array[0]\n\t\t        item = heapreplace(array, item)\n\t\t   */\n\n\t\t  heapreplace = function(array, item, cmp) {\n\t\t    var returnitem;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    returnitem = array[0];\n\t\t    array[0] = item;\n\t\t    _siftup(array, 0, cmp);\n\t\t    return returnitem;\n\t\t  };\n\n\n\t\t  /*\n\t\t  Fast version of a heappush followed by a heappop.\n\t\t   */\n\n\t\t  heappushpop = function(array, item, cmp) {\n\t\t    var _ref;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    if (array.length && cmp(array[0], item) < 0) {\n\t\t      _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n\t\t      _siftup(array, 0, cmp);\n\t\t    }\n\t\t    return item;\n\t\t  };\n\n\n\t\t  /*\n\t\t  Transform list into a heap, in-place, in O(array.length) time.\n\t\t   */\n\n\t\t  heapify = function(array, cmp) {\n\t\t    var i, _i, _len, _ref1, _results, _results1;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    _ref1 = (function() {\n\t\t      _results1 = [];\n\t\t      for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n\t\t      return _results1;\n\t\t    }).apply(this).reverse();\n\t\t    _results = [];\n\t\t    for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n\t\t      i = _ref1[_i];\n\t\t      _results.push(_siftup(array, i, cmp));\n\t\t    }\n\t\t    return _results;\n\t\t  };\n\n\n\t\t  /*\n\t\t  Update the position of the given item in the heap.\n\t\t  This function should be called every time the item is being modified.\n\t\t   */\n\n\t\t  updateItem = function(array, item, cmp) {\n\t\t    var pos;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    pos = array.indexOf(item);\n\t\t    if (pos === -1) {\n\t\t      return;\n\t\t    }\n\t\t    _siftdown(array, 0, pos, cmp);\n\t\t    return _siftup(array, pos, cmp);\n\t\t  };\n\n\n\t\t  /*\n\t\t  Find the n largest elements in a dataset.\n\t\t   */\n\n\t\t  nlargest = function(array, n, cmp) {\n\t\t    var elem, result, _i, _len, _ref;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    result = array.slice(0, n);\n\t\t    if (!result.length) {\n\t\t      return result;\n\t\t    }\n\t\t    heapify(result, cmp);\n\t\t    _ref = array.slice(n);\n\t\t    for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n\t\t      elem = _ref[_i];\n\t\t      heappushpop(result, elem, cmp);\n\t\t    }\n\t\t    return result.sort(cmp).reverse();\n\t\t  };\n\n\n\t\t  /*\n\t\t  Find the n smallest elements in a dataset.\n\t\t   */\n\n\t\t  nsmallest = function(array, n, cmp) {\n\t\t    var elem, los, result, _i, _j, _len, _ref, _ref1, _results;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    if (n * 10 <= array.length) {\n\t\t      result = array.slice(0, n).sort(cmp);\n\t\t      if (!result.length) {\n\t\t        return result;\n\t\t      }\n\t\t      los = result[result.length - 1];\n\t\t      _ref = array.slice(n);\n\t\t      for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n\t\t        elem = _ref[_i];\n\t\t        if (cmp(elem, los) < 0) {\n\t\t          insort(result, elem, 0, null, cmp);\n\t\t          result.pop();\n\t\t          los = result[result.length - 1];\n\t\t        }\n\t\t      }\n\t\t      return result;\n\t\t    }\n\t\t    heapify(array, cmp);\n\t\t    _results = [];\n\t\t    for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {\n\t\t      _results.push(heappop(array, cmp));\n\t\t    }\n\t\t    return _results;\n\t\t  };\n\n\t\t  _siftdown = function(array, startpos, pos, cmp) {\n\t\t    var newitem, parent, parentpos;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    newitem = array[pos];\n\t\t    while (pos > startpos) {\n\t\t      parentpos = (pos - 1) >> 1;\n\t\t      parent = array[parentpos];\n\t\t      if (cmp(newitem, parent) < 0) {\n\t\t        array[pos] = parent;\n\t\t        pos = parentpos;\n\t\t        continue;\n\t\t      }\n\t\t      break;\n\t\t    }\n\t\t    return array[pos] = newitem;\n\t\t  };\n\n\t\t  _siftup = function(array, pos, cmp) {\n\t\t    var childpos, endpos, newitem, rightpos, startpos;\n\t\t    if (cmp == null) {\n\t\t      cmp = defaultCmp;\n\t\t    }\n\t\t    endpos = array.length;\n\t\t    startpos = pos;\n\t\t    newitem = array[pos];\n\t\t    childpos = 2 * pos + 1;\n\t\t    while (childpos < endpos) {\n\t\t      rightpos = childpos + 1;\n\t\t      if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n\t\t        childpos = rightpos;\n\t\t      }\n\t\t      array[pos] = array[childpos];\n\t\t      pos = childpos;\n\t\t      childpos = 2 * pos + 1;\n\t\t    }\n\t\t    array[pos] = newitem;\n\t\t    return _siftdown(array, startpos, pos, cmp);\n\t\t  };\n\n\t\t  Heap = (function() {\n\t\t    Heap.push = heappush;\n\n\t\t    Heap.pop = heappop;\n\n\t\t    Heap.replace = heapreplace;\n\n\t\t    Heap.pushpop = heappushpop;\n\n\t\t    Heap.heapify = heapify;\n\n\t\t    Heap.updateItem = updateItem;\n\n\t\t    Heap.nlargest = nlargest;\n\n\t\t    Heap.nsmallest = nsmallest;\n\n\t\t    function Heap(cmp) {\n\t\t      this.cmp = cmp != null ? cmp : defaultCmp;\n\t\t      this.nodes = [];\n\t\t    }\n\n\t\t    Heap.prototype.push = function(x) {\n\t\t      return heappush(this.nodes, x, this.cmp);\n\t\t    };\n\n\t\t    Heap.prototype.pop = function() {\n\t\t      return heappop(this.nodes, this.cmp);\n\t\t    };\n\n\t\t    Heap.prototype.peek = function() {\n\t\t      return this.nodes[0];\n\t\t    };\n\n\t\t    Heap.prototype.contains = function(x) {\n\t\t      return this.nodes.indexOf(x) !== -1;\n\t\t    };\n\n\t\t    Heap.prototype.replace = function(x) {\n\t\t      return heapreplace(this.nodes, x, this.cmp);\n\t\t    };\n\n\t\t    Heap.prototype.pushpop = function(x) {\n\t\t      return heappushpop(this.nodes, x, this.cmp);\n\t\t    };\n\n\t\t    Heap.prototype.heapify = function() {\n\t\t      return heapify(this.nodes, this.cmp);\n\t\t    };\n\n\t\t    Heap.prototype.updateItem = function(x) {\n\t\t      return updateItem(this.nodes, x, this.cmp);\n\t\t    };\n\n\t\t    Heap.prototype.clear = function() {\n\t\t      return this.nodes = [];\n\t\t    };\n\n\t\t    Heap.prototype.empty = function() {\n\t\t      return this.nodes.length === 0;\n\t\t    };\n\n\t\t    Heap.prototype.size = function() {\n\t\t      return this.nodes.length;\n\t\t    };\n\n\t\t    Heap.prototype.clone = function() {\n\t\t      var heap;\n\t\t      heap = new Heap();\n\t\t      heap.nodes = this.nodes.slice(0);\n\t\t      return heap;\n\t\t    };\n\n\t\t    Heap.prototype.toArray = function() {\n\t\t      return this.nodes.slice(0);\n\t\t    };\n\n\t\t    Heap.prototype.insert = Heap.prototype.push;\n\n\t\t    Heap.prototype.top = Heap.prototype.peek;\n\n\t\t    Heap.prototype.front = Heap.prototype.peek;\n\n\t\t    Heap.prototype.has = Heap.prototype.contains;\n\n\t\t    Heap.prototype.copy = Heap.prototype.clone;\n\n\t\t    return Heap;\n\n\t\t  })();\n\n\t\t  (function(root, factory) {\n\t\t    {\n\t\t      return module.exports = factory();\n\t\t    }\n\t\t  })(this, function() {\n\t\t    return Heap;\n\t\t  });\n\n\t\t}).call(heap$1); \n\t} (heap$2));\n\treturn heap$2.exports;\n}\n\nvar heap;\nvar hasRequiredHeap;\n\nfunction requireHeap () {\n\tif (hasRequiredHeap) return heap;\n\thasRequiredHeap = 1;\n\theap = requireHeap$1();\n\treturn heap;\n}\n\nvar heapExports = requireHeap();\nvar Heap = /*@__PURE__*/getDefaultExportFromCjs(heapExports);\n\nvar dijkstraDefaults = defaults$g({\n  root: null,\n  weight: function weight(edge) {\n    return 1;\n  },\n  directed: false\n});\nvar 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    var _dijkstraDefaults = dijkstraDefaults(options),\n      root = _dijkstraDefaults.root,\n      weight = _dijkstraDefaults.weight,\n      directed = _dijkstraDefaults.directed;\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    var _this$byGroup = this.byGroup(),\n      nodes = _this$byGroup.nodes,\n      edges = _this$byGroup.edges;\n    edges.unmergeBy(function (ele) {\n      return ele.isLoop();\n    });\n    var getDist = function getDist(node) {\n      return dist[node.id()];\n    };\n    var setDist = function setDist(node, d) {\n      dist[node.id()] = d;\n      Q.updateItem(node);\n    };\n    var Q = new Heap(function (a, b) {\n      return getDist(a) - getDist(b);\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    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      for (var _i = 0; _i < uvs.length; _i++) {\n        var edge = uvs[_i];\n        var _weight = weightFn(edge);\n        if (_weight < smallestDistance || !smallestEdge) {\n          smallestDistance = _weight;\n          smallestEdge = edge;\n        }\n      }\n      return {\n        edge: smallestEdge,\n        dist: smallestDistance\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      if (smalletsDist === Infinity) {\n        continue;\n      }\n      var neighbors = u.neighborhood().intersect(nodes);\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        if (alt < getDist(v)) {\n          setDist(v, alt);\n          prev[vid] = {\n            node: u,\n            edge: vDist.edge\n          };\n        }\n      } // for\n    } // while\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        if (target.length > 0) {\n          S.unshift(target);\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        return eles.spawn(S);\n      }\n    };\n  }\n};\n\nvar 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    var _this$byGroup = this.byGroup(),\n      nodes = _this$byGroup.nodes,\n      edges = _this$byGroup.edges;\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        if (eles.has(ele)) {\n          return i;\n        }\n      }\n    };\n\n    // start with one forest per node\n    for (var i = 0; i < numNodes; i++) {\n      forest[i] = this.spawn(nodes[i]);\n    }\n    var S = edges.sort(function (a, b) {\n      return weightFn(a) - weightFn(b);\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      if (setUIndex !== setVIndex) {\n        A.merge(edge);\n\n        // combine forests for u and v\n        setU.merge(setV);\n        forest.splice(setVIndex, 1);\n      }\n    }\n    return A;\n  }\n};\n\nvar 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});\nvar elesfn$s = {\n  // Implemented from pseudocode from wikipedia\n  aStar: function aStar(options) {\n    var cy = this.cy();\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    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    var addToOpenSet = function addToOpenSet(ele, id) {\n      openSet.push(ele);\n      openSetIds.add(id);\n    };\n    var cMin, cMinId;\n    var popFromOpenSet = function popFromOpenSet() {\n      cMin = openSet.pop();\n      cMinId = cMin.id();\n      openSetIds[\"delete\"](cMinId);\n    };\n    var isInOpenSet = function isInOpenSet(id) {\n      return openSetIds.has(id);\n    };\n    addToOpenSet(root, sid);\n    gScore[sid] = 0;\n    fScore[sid] = heuristic(root);\n\n    // Counter\n    var steps = 0;\n\n    // Main loop\n    while (openSet.size() > 0) {\n      popFromOpenSet();\n      steps++;\n\n      // If we've found our goal, then we are done\n      if (cMinId === tid) {\n        var path = [];\n        var pathNode = goal;\n        var pathNodeId = tid;\n        var pathEdge = cameFromEdge[pathNodeId];\n        for (;;) {\n          path.unshift(pathNode);\n          if (pathEdge != null) {\n            path.unshift(pathEdge);\n          }\n          pathNode = cameFrom[pathNodeId];\n          if (pathNode == null) {\n            break;\n          }\n          pathNodeId = pathNode.id();\n          pathEdge = cameFromEdge[pathNodeId];\n        }\n        return {\n          found: true,\n          distance: gScore[cMinId],\n          path: this.spawn(path),\n          steps: steps\n        };\n      }\n\n      // Add cMin to processed nodes\n      closedSetIds[cMinId] = true;\n\n      // Update scores for neighbors of cMin\n      // Take into account if graph is directed or not\n      var vwEdges = cMin._private.edges;\n      for (var i = 0; i < vwEdges.length; i++) {\n        var e = vwEdges[i];\n\n        // edge must be in set of calling eles\n        if (!this.hasElementWithId(e.id())) {\n          continue;\n        }\n\n        // cMin must be the source of edge if directed\n        if (directed && e.data('source') !== cMinId) {\n          continue;\n        }\n        var wSrc = e.source();\n        var wTgt = e.target();\n        var w = wSrc.id() !== cMinId ? wSrc : wTgt;\n        var wid = w.id();\n\n        // node must be in set of calling eles\n        if (!this.hasElementWithId(wid)) {\n          continue;\n        }\n\n        // if node is in closedSet, ignore it\n        if (closedSetIds[wid]) {\n          continue;\n        }\n\n        // New tentative score for node w\n        var tempScore = gScore[cMinId] + weight(e);\n\n        // Update gScore for node w if:\n        //   w not present in openSet\n        // OR\n        //   tentative gScore is less than previous value\n\n        // w not in openSet\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        }\n\n        // w already in openSet, but with greater gScore\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    } // End of main loop\n\n    // If we've reached here, then we've not reached our goal\n    return {\n      found: false,\n      distance: undefined,\n      path: undefined,\n      steps: steps\n    };\n  }\n}; // elesfn\n\nvar floydWarshallDefaults = defaults$g({\n  weight: function weight(edge) {\n    return 1;\n  },\n  directed: false\n});\nvar elesfn$r = {\n  // Implemented from pseudocode from wikipedia\n  floydWarshall: function floydWarshall(options) {\n    var cy = this.cy();\n    var _floydWarshallDefault = floydWarshallDefaults(options),\n      weight = _floydWarshallDefault.weight,\n      directed = _floydWarshallDefault.directed;\n    var weightFn = weight;\n    var _this$byGroup = this.byGroup(),\n      nodes = _this$byGroup.nodes,\n      edges = _this$byGroup.edges;\n    var N = nodes.length;\n    var Nsq = N * N;\n    var indexOf = function indexOf(node) {\n      return nodes.indexOf(node);\n    };\n    var atIndex = function atIndex(i) {\n      return nodes[i];\n    };\n\n    // Initialize distance matrix\n    var dist = new Array(Nsq);\n    for (var n = 0; n < Nsq; n++) {\n      var j = n % N;\n      var i = (n - j) / N;\n      if (i === j) {\n        dist[n] = 0;\n      } else {\n        dist[n] = Infinity;\n      }\n    }\n\n    // Initialize matrix used for path reconstruction\n    // Initialize distance matrix\n    var next = new Array(Nsq);\n    var edgeNext = new Array(Nsq);\n\n    // Process edges\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      if (src === tgt) {\n        continue;\n      } // exclude loops\n\n      var s = indexOf(src);\n      var t = indexOf(tgt);\n      var st = s * N + t; // source to target index\n      var _weight = weightFn(edge);\n\n      // Check if already process another edge between same 2 nodes\n      if (dist[st] > _weight) {\n        dist[st] = _weight;\n        next[st] = t;\n        edgeNext[st] = edge;\n      }\n\n      // If undirected graph, process 'reversed' edge\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    }\n\n    // Main loop\n    for (var k = 0; k < N; k++) {\n      for (var _i2 = 0; _i2 < N; _i2++) {\n        var ik = _i2 * N + k;\n        for (var _j = 0; _j < N; _j++) {\n          var ij = _i2 * N + _j;\n          var kj = k * N + _j;\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    var getArgEle = function getArgEle(ele) {\n      return (string(ele) ? cy.filter(ele) : ele)[0];\n    };\n    var indexOfArgEle = function indexOfArgEle(ele) {\n      return indexOf(getArgEle(ele));\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        if (i === j) {\n          return fromNode.collection();\n        }\n        if (next[i * N + j] == null) {\n          return cy.collection();\n        }\n        var path = cy.collection();\n        var prev = i;\n        var edge;\n        path.merge(fromNode);\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        return path;\n      }\n    };\n    return res;\n  } // floydWarshall\n}; // elesfn\n\nvar bellmanFordDefaults = defaults$g({\n  weight: function weight(edge) {\n    return 1;\n  },\n  directed: false,\n  root: null\n});\nvar elesfn$q = {\n  // Implemented from pseudocode from wikipedia\n  bellmanFord: function bellmanFord(options) {\n    var _this = this;\n    var _bellmanFordDefaults = bellmanFordDefaults(options),\n      weight = _bellmanFordDefaults.weight,\n      directed = _bellmanFordDefaults.directed,\n      root = _bellmanFordDefaults.root;\n    var weightFn = weight;\n    var eles = this;\n    var cy = this.cy();\n    var _this$byGroup = this.byGroup(),\n      edges = _this$byGroup.edges,\n      nodes = _this$byGroup.nodes;\n    var numNodes = nodes.length;\n    var infoMap = new Map$1();\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    var getInfo = function getInfo(node) {\n      var obj = infoMap.get(node.id());\n      if (!obj) {\n        obj = {};\n        infoMap.set(node.id(), obj);\n      }\n      return obj;\n    };\n    var getNodeFromTo = function getNodeFromTo(to) {\n      return (string(to) ? cy.$(to) : to)[0];\n    };\n    var distanceTo = function distanceTo(to) {\n      return getInfo(getNodeFromTo(to)).dist;\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      for (;;) {\n        if (node == null) {\n          return _this.spawn();\n        }\n        var _getInfo = getInfo(node),\n          edge = _getInfo.edge,\n          pred = _getInfo.pred;\n        path.unshift(node[0]);\n        if (node.same(thisStart) && path.length > 0) {\n          break;\n        }\n        if (edge != null) {\n          path.unshift(edge);\n        }\n        node = pred;\n      }\n      return eles.spawn(path);\n    };\n\n    // Initializations { dist, pred, edge }\n    for (var i = 0; i < numNodes; i++) {\n      var node = nodes[i];\n      var info = getInfo(node);\n      if (node.same(root)) {\n        info.dist = 0;\n      } else {\n        info.dist = Infinity;\n      }\n      info.pred = null;\n      info.edge = null;\n    }\n\n    // Edges relaxation\n    var replacedEdge = false;\n    var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {\n      var dist = info1.dist + weight;\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    for (var _i = 1; _i < numNodes; _i++) {\n      replacedEdge = false;\n      for (var e = 0; e < numEdges; e++) {\n        var edge = edges[e];\n        var src = edge.source();\n        var tgt = edge.target();\n        var _weight = weightFn(edge);\n        var srcInfo = getInfo(src);\n        var tgtInfo = getInfo(tgt);\n        checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight);\n\n        // If undirected graph, we need to take into account the 'reverse' edge\n        if (!directed) {\n          checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);\n        }\n      }\n      if (!replacedEdge) {\n        break;\n      }\n    }\n    if (replacedEdge) {\n      // Check for negative weight cycles\n      var negativeWeightCycleIds = [];\n      for (var _e = 0; _e < numEdges; _e++) {\n        var _edge = edges[_e];\n        var _src = _edge.source();\n        var _tgt = _edge.target();\n        var _weight2 = weightFn(_edge);\n        var srcDist = getInfo(_src).dist;\n        var tgtDist = getInfo(_tgt).dist;\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          if (options.findNegativeWeightCycles !== false) {\n            var negativeNodes = [];\n            if (srcDist + _weight2 < tgtDist) {\n              negativeNodes.push(_src);\n            }\n            if (!directed && tgtDist + _weight2 < srcDist) {\n              negativeNodes.push(_tgt);\n            }\n            var numNegativeNodes = negativeNodes.length;\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              while (cycle.indexOf(_node) === -1) {\n                cycle.push(_node);\n                cycle.push(getInfo(_node).edge);\n                _node = getInfo(_node).pred;\n              }\n              cycle = cycle.slice(cycle.indexOf(_node));\n              var smallestId = cycle[0].id();\n              var smallestIndex = 0;\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              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              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    return {\n      distanceTo: distanceTo,\n      pathTo: pathTo,\n      hasNegativeWeightCycle: hasNegativeWeightCycle,\n      negativeWeightCycles: negativeWeightCycles\n    };\n  } // bellmanFord\n}; // elesfn\n\nvar sqrt2 = Math.sqrt(2);\n\n// 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\nvar 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  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\n  // Delete all edges between partition1 and partition2\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    if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {\n      newEdges.splice(i, 1);\n    }\n  }\n\n  // All edges pointing to partition2 should now point to partition1\n  for (var _i = 0; _i < newEdges.length; _i++) {\n    var _edge = newEdges[_i];\n    if (_edge[1] === partition2) {\n      // Check source\n      newEdges[_i] = _edge.slice(); // copy\n      newEdges[_i][1] = partition1;\n    } else if (_edge[2] === partition2) {\n      // Check target\n      newEdges[_i] = _edge.slice(); // copy\n      newEdges[_i][2] = partition1;\n    }\n  }\n\n  // Move all nodes from partition2 to partition1\n  for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {\n    if (nodeMap[_i2] === partition2) {\n      nodeMap[_i2] = partition1;\n    }\n  }\n  return newEdges;\n};\n\n// Contracts a graph until we reach a certain number of meta nodes\nvar 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);\n\n    // Collapse graph based on edge\n    remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);\n    size--;\n  }\n  return remainingEdges;\n};\nvar 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    var _this$byGroup = this.byGroup(),\n      nodes = _this$byGroup.nodes,\n      edges = _this$byGroup.edges;\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    if (numNodes < 2) {\n      error('At least 2 nodes are required for Karger-Stein algorithm');\n      return undefined;\n    }\n\n    // Now store edge destination as indexes\n    // Format for each edge (edge index, source node index, target node index)\n    var edgeIndexes = [];\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    }\n\n    // We will store the best cut found here\n    var minCutSize = Infinity;\n    var minCutEdgeIndexes = [];\n    var minCutNodeMap = new Array(numNodes);\n\n    // Initial meta node partition\n    var metaNodeMap = new Array(numNodes);\n    var metaNodeMap2 = new Array(numNodes);\n    var copyNodesMap = function copyNodesMap(from, to) {\n      for (var _i3 = 0; _i3 < numNodes; _i3++) {\n        to[_i3] = from[_i3];\n      }\n    };\n\n    // Main loop\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      }\n\n      // Contract until stop point (stopSize nodes)\n      var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);\n      var edgesState2 = edgesState.slice(); // copy\n\n      // Create a copy of the colapsed nodes state\n      copyNodesMap(metaNodeMap, metaNodeMap2);\n\n      // Run 2 iterations starting in the stop state\n      var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);\n      var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2);\n\n      // Is any of the 2 results the best cut so far?\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\n    // Construct result\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();\n\n    // traverse metaNodeMap for best cut\n    var witnessNodePartition = minCutNodeMap[0];\n    for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {\n      var partitionId = minCutNodeMap[_i5];\n      var node = nodes[_i5];\n      if (partitionId === witnessNodePartition) {\n        partition1.merge(node);\n      } else {\n        partition2.merge(node);\n      }\n    }\n\n    // construct components corresponding to each disjoint subset of nodes\n    var constructComponent = function constructComponent(subset) {\n      var component = _this.spawn();\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    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\nvar copyPosition = function copyPosition(p) {\n  return {\n    x: p.x,\n    y: p.y\n  };\n};\nvar modelToRenderedPosition$1 = function modelToRenderedPosition(p, zoom, pan) {\n  return {\n    x: p.x * zoom + pan.x,\n    y: p.y * zoom + pan.y\n  };\n};\nvar renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {\n  return {\n    x: (p.x - pan.x) / zoom,\n    y: (p.y - pan.y) / zoom\n  };\n};\nvar array2point = function array2point(arr) {\n  return {\n    x: arr[0],\n    y: arr[1]\n  };\n};\nvar 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  for (var i = begin; i < end; i++) {\n    var val = arr[i];\n    if (isFinite(val)) {\n      min = Math.min(val, min);\n    }\n  }\n  return min;\n};\nvar 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  for (var i = begin; i < end; i++) {\n    var val = arr[i];\n    if (isFinite(val)) {\n      max = Math.max(val, max);\n    }\n  }\n  return max;\n};\nvar 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  for (var i = begin; i < end; i++) {\n    var val = arr[i];\n    if (isFinite(val)) {\n      total += val;\n      n++;\n    }\n  }\n  return total / n;\n};\nvar 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  if (copy) {\n    arr = arr.slice(begin, end);\n  } else {\n    if (end < arr.length) {\n      arr.splice(end, arr.length - end);\n    }\n    if (begin > 0) {\n      arr.splice(0, begin);\n    }\n  }\n\n  // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start\n  var off = 0; // offset from non-finite values\n  for (var i = arr.length - 1; i >= 0; i--) {\n    var v = arr[i];\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  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  var len = arr.length;\n  var mid = Math.floor(len / 2);\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};\nvar deg2rad = function deg2rad(deg) {\n  return Math.PI * deg / 180;\n};\nvar getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {\n  return Math.atan2(dispY, dispX) - Math.PI / 2;\n};\nvar log2 = Math.log2 || function (n) {\n  return Math.log(n) / Math.log(2);\n};\nvar 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};\nvar dist = function dist(p1, p2) {\n  return Math.sqrt(sqdist(p1, p2));\n};\nvar 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};\nvar inPlaceSumNormalize = function inPlaceSumNormalize(v) {\n  var length = v.length;\n\n  // First, get sum of all elements\n  var total = 0;\n  for (var i = 0; i < length; i++) {\n    total += v[i];\n  }\n\n  // Now, divide each by the sum of all elements\n  for (var _i = 0; _i < length; _i++) {\n    v[_i] = v[_i] / total;\n  }\n  return v;\n};\n\n// from http://en.wikipedia.org/wiki/Bézier_curve#Quadratic_curves\nvar qbezierAt = function qbezierAt(p0, p1, p2, t) {\n  return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;\n};\nvar 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};\nvar 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};\nvar bound = function bound(min, val, max) {\n  return Math.max(min, Math.min(max, val));\n};\n\n// makes a full bb (x1, y1, x2, y2, w, h) from implicit params\nvar 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};\nvar 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};\nvar 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};\nvar shiftBoundingBox = function shiftBoundingBox(bb, dx, dy) {\n  return {\n    x1: bb.x1 + dx,\n    x2: bb.x2 + dx,\n    y1: bb.y1 + dy,\n    y2: bb.y2 + dy,\n    w: bb.w,\n    h: bb.h\n  };\n};\nvar updateBoundingBox = function updateBoundingBox(bb1, bb2) {\n  // update bb1 with bb2 bounds\n\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};\nvar 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};\nvar 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};\nvar expandBoundingBoxSides = function expandBoundingBoxSides(bb) {\n  var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];\n  var top, right, bottom, left;\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    top = _padding[0];\n    right = _padding[1];\n    bottom = _padding[2];\n    left = _padding[3];\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// assign the values of bb2 into bb1\nvar 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};\nvar boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {\n  // case: one bb to right of other\n  if (bb1.x1 > bb2.x2) {\n    return false;\n  }\n  if (bb2.x1 > bb1.x2) {\n    return false;\n  }\n\n  // case: one bb to left of other\n  if (bb1.x2 < bb2.x1) {\n    return false;\n  }\n  if (bb2.x2 < bb1.x1) {\n    return false;\n  }\n\n  // case: one bb above other\n  if (bb1.y2 < bb2.y1) {\n    return false;\n  }\n  if (bb2.y2 < bb1.y1) {\n    return false;\n  }\n\n  // case: one bb below other\n  if (bb1.y1 > bb2.y2) {\n    return false;\n  }\n  if (bb2.y1 > bb1.y2) {\n    return false;\n  }\n\n  // otherwise, must have some overlap\n  return true;\n};\nvar inBoundingBox = function inBoundingBox(bb, x, y) {\n  return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;\n};\nvar pointInBoundingBox = function pointInBoundingBox(bb, pt) {\n  return inBoundingBox(bb, pt.x, pt.y);\n};\nvar boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {\n  return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);\n};\nvar roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {\n  var radius = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'auto';\n  var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;\n  var halfWidth = width / 2;\n  var halfHeight = height / 2;\n  cornerRadius = Math.min(cornerRadius, halfWidth, halfHeight);\n  var doWidth = cornerRadius !== halfWidth,\n    doHeight = cornerRadius !== halfHeight;\n\n  // Check intersections with straight line segments\n  var straightLineIntersections;\n\n  // Top segment, left to right\n  if (doWidth) {\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    if (straightLineIntersections.length > 0) {\n      return straightLineIntersections;\n    }\n  }\n\n  // Right segment, top to bottom\n  if (doHeight) {\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    if (straightLineIntersections.length > 0) {\n      return straightLineIntersections;\n    }\n  }\n\n  // Bottom segment, left to right\n  if (doWidth) {\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    if (straightLineIntersections.length > 0) {\n      return straightLineIntersections;\n    }\n  }\n\n  // Left segment, top to bottom\n  if (doHeight) {\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    if (straightLineIntersections.length > 0) {\n      return straightLineIntersections;\n    }\n  }\n\n  // Check intersections with arc segments\n  var arcIntersections;\n\n  // Top Left\n  {\n    var topLeftCenterX = nodeX - halfWidth + cornerRadius;\n    var topLeftCenterY = nodeY - halfHeight + cornerRadius;\n    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding);\n\n    // Ensure the intersection is on the desired quarter of the circle\n    if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {\n      return [arcIntersections[0], arcIntersections[1]];\n    }\n  }\n\n  // Top Right\n  {\n    var topRightCenterX = nodeX + halfWidth - cornerRadius;\n    var topRightCenterY = nodeY - halfHeight + cornerRadius;\n    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding);\n\n    // Ensure the intersection is on the desired quarter of the circle\n    if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {\n      return [arcIntersections[0], arcIntersections[1]];\n    }\n  }\n\n  // Bottom Right\n  {\n    var bottomRightCenterX = nodeX + halfWidth - cornerRadius;\n    var bottomRightCenterY = nodeY + halfHeight - cornerRadius;\n    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding);\n\n    // Ensure the intersection is on the desired quarter of the circle\n    if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {\n      return [arcIntersections[0], arcIntersections[1]];\n    }\n  }\n\n  // Bottom Left\n  {\n    var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;\n    var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;\n    arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding);\n\n    // Ensure the intersection is on the desired quarter of the circle\n    if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {\n      return [arcIntersections[0], arcIntersections[1]];\n    }\n  }\n  return []; // if nothing\n};\nvar 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};\nvar 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  };\n\n  // if outside the rough bounding box for the bezier, then it can't be a hit\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};\nvar solveQuadratic = function solveQuadratic(a, b, c, val) {\n  c -= val;\n  var r = b * b - 4 * a * c;\n  if (r < 0) {\n    return [];\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};\nvar 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\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\n  var epsilon = 0.00001;\n\n  // avoid division by zero while keeping the overall expression close in value\n  if (a === 0) {\n    a = epsilon;\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  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  result[5] = result[3] = 0;\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  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};\nvar 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\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\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;\n\n  // debug(\"coefficients: \" + a / a + \", \" + b / a + \", \" + c / a + \", \" + d / a);\n\n  var roots = [];\n\n  // Use the cubic solving algorithm\n  solveCubic(a, b, c, d, roots);\n  var zeroThreshold = 0.0000001;\n  var params = [];\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  params.push(1.0);\n  params.push(0.0);\n  var minDistanceSquared = -1;\n  var curX, curY, distSquared;\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);\n    // debug('distance for param ' + params[i] + \": \" + Math.sqrt(distSquared));\n    if (minDistanceSquared >= 0) {\n      if (distSquared < minDistanceSquared) {\n        minDistanceSquared = distSquared;\n      }\n    } else {\n      minDistanceSquared = distSquared;\n    }\n  }\n  return minDistanceSquared;\n};\nvar 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  if (dotProduct < 0) {\n    return hypSq;\n  }\n  if (adjSq > lineSq) {\n    return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n  }\n  return hypSq - adjSq;\n};\nvar pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {\n  var x1, y1, x2, y2;\n  var y3;\n\n  // Intersect with vertical line through (x, y)\n  var up = 0;\n  // let down = 0;\n  for (var i = 0; i < points.length / 2; i++) {\n    x1 = points[i * 2];\n    y1 = points[i * 2 + 1];\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    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      if (y3 > y) {\n        up++;\n      }\n\n      // if( y3 < y ){\n      // down++;\n      // }\n    } else {\n      continue;\n    }\n  }\n  if (up % 2 === 0) {\n    return false;\n  } else {\n    return true;\n  }\n};\nvar pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {\n  var transformedPoints = new Array(basePoints.length);\n\n  // Gives negative angle\n  var angle;\n  if (direction[0] != null) {\n    angle = Math.atan(direction[1] / direction[0]);\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  var cos = Math.cos(-angle);\n  var sin = Math.sin(-angle);\n\n  //    console.log(\"base: \" + basePoints);\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  var points;\n  if (padding > 0) {\n    var expandedLineSet = expandPolygon(transformedPoints, -padding);\n    points = joinLines(expandedLineSet);\n  } else {\n    points = transformedPoints;\n  }\n  return pointInsidePolygonPoints(x, y, points);\n};\nvar pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height, corners) {\n  var cutPolygonPoints = new Array(basePoints.length * 2);\n  for (var i = 0; i < corners.length; i++) {\n    var corner = corners[i];\n    cutPolygonPoints[i * 4 + 0] = corner.startX;\n    cutPolygonPoints[i * 4 + 1] = corner.startY;\n    cutPolygonPoints[i * 4 + 2] = corner.stopX;\n    cutPolygonPoints[i * 4 + 3] = corner.stopY;\n    var squaredDistance = Math.pow(corner.cx - x, 2) + Math.pow(corner.cy - y, 2);\n    if (squaredDistance <= Math.pow(corner.radius, 2)) {\n      return true;\n    }\n  }\n  return pointInsidePolygonPoints(x, y, cutPolygonPoints);\n};\nvar 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  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    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    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  return vertices;\n};\nvar expandPolygon = function expandPolygon(points, pad) {\n  var expandedLineSet = new Array(points.length * 2);\n  var currentPointX, currentPointY, nextPointX, nextPointY;\n  for (var i = 0; i < points.length / 2; i++) {\n    currentPointX = points[i * 2];\n    currentPointY = points[i * 2 + 1];\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    }\n\n    // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]\n\n    // Assume CCW polygon winding\n\n    var offsetX = nextPointY - currentPointY;\n    var offsetY = -(nextPointX - currentPointX);\n\n    // Normalize\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  return expandedLineSet;\n};\nvar 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  if (newLength < 0) {\n    return [];\n  }\n  var lenProportion = newLength / len;\n  return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];\n};\nvar 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};\n\n// Returns intersections of increasing distance from line's start point\nvar 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  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  if (discriminant < 0) {\n    return [];\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  if (tMin >= 0 && tMin <= 1) {\n    inRangeParams.push(tMin);\n  }\n  if (tMax >= 0 && tMax <= 1) {\n    inRangeParams.push(tMax);\n  }\n  if (inRangeParams.length === 0) {\n    return [];\n  }\n  var nearIntersectionX = inRangeParams[0] * d[0] + x1;\n  var nearIntersectionY = inRangeParams[0] * d[1] + y1;\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};\nvar 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};\n\n// (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)\nvar 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  if (u_b !== 0) {\n    var ua = ua_t / u_b;\n    var ub = ub_t / u_b;\n    var flptThreshold = 0.001;\n    var _min = 0 - flptThreshold;\n    var _max = 1 + flptThreshold;\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\n      // Check endpoint of second line\n      if (midOfThree(x1, x2, x4) === x4) {\n        return [x4, y4];\n      }\n\n      // Check start point of second line\n      if (midOfThree(x1, x2, x3) === x3) {\n        return [x3, y3];\n      }\n\n      // Endpoint of first line\n      if (midOfThree(x3, x4, x2) === x2) {\n        return [x2, y2];\n      }\n      return [];\n    } else {\n      // Parallel, non-coincident\n      return [];\n    }\n  }\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)\nvar 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  if (width == null) {\n    doTransform = false;\n  }\n  var points;\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    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  var currentX, currentY, nextX, nextY;\n  for (var _i2 = 0; _i2 < points.length / 2; _i2++) {\n    currentX = points[_i2 * 2];\n    currentY = points[_i2 * 2 + 1];\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    intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);\n    if (intersection.length !== 0) {\n      intersections.push(intersection[0], intersection[1]);\n    }\n  }\n  return intersections;\n};\nvar roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding, corners) {\n  var intersections = [];\n  var intersection;\n  var lines = new Array(basePoints.length * 2);\n  corners.forEach(function (corner, i) {\n    if (i === 0) {\n      lines[lines.length - 2] = corner.startX;\n      lines[lines.length - 1] = corner.startY;\n    } else {\n      lines[i * 4 - 2] = corner.startX;\n      lines[i * 4 - 1] = corner.startY;\n    }\n    lines[i * 4] = corner.stopX;\n    lines[i * 4 + 1] = corner.stopY;\n    intersection = intersectLineCircle(x, y, centerX, centerY, corner.cx, corner.cy, corner.radius);\n    if (intersection.length !== 0) {\n      intersections.push(intersection[0], intersection[1]);\n    }\n  });\n  for (var i = 0; i < lines.length / 4; i++) {\n    intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[i * 4], lines[i * 4 + 1], lines[i * 4 + 2], lines[i * 4 + 3], false);\n    if (intersection.length !== 0) {\n      intersections.push(intersection[0], intersection[1]);\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    for (var _i3 = 1; _i3 < intersections.length / 2; _i3++) {\n      var squaredDistance = Math.pow(intersections[_i3 * 2] - x, 2) + Math.pow(intersections[_i3 * 2 + 1] - y, 2);\n      if (squaredDistance <= lowestSquaredDistance) {\n        lowestIntersection[0] = intersections[_i3 * 2];\n        lowestIntersection[1] = intersections[_i3 * 2 + 1];\n        lowestSquaredDistance = squaredDistance;\n      }\n    }\n    return lowestIntersection;\n  }\n  return intersections;\n};\nvar 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  if (lenRatio < 0) {\n    lenRatio = 0.00001;\n  }\n  return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];\n};\nvar generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {\n  var points = generateUnitNgonPoints(sides, rotationRadians);\n  points = fitPolygonToSquare(points);\n  return points;\n};\nvar 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  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  }\n\n  // stretch factors\n  var sx = 2 / (maxX - minX);\n  var sy = 2 / (maxY - minY);\n  for (var _i4 = 0; _i4 < sides; _i4++) {\n    x = points[2 * _i4] = points[2 * _i4] * sx;\n    y = points[2 * _i4 + 1] = points[2 * _i4 + 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  if (minY < -1) {\n    for (var _i5 = 0; _i5 < sides; _i5++) {\n      y = points[2 * _i5 + 1] = points[2 * _i5 + 1] + (-1 - minY);\n    }\n  }\n  return points;\n};\nvar 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  for (var i = 0; i < sides; i++) {\n    currentAngle = i * increment + startAngle;\n    points[2 * i] = Math.cos(currentAngle); // x\n    points[2 * i + 1] = Math.sin(-currentAngle); // y\n  }\n  return points;\n};\n\n// Set the default radius, unless half of width or height is smaller than default\nvar getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {\n  return Math.min(width / 4, height / 4, 8);\n};\n\n// Set the default radius\nvar getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {\n  return Math.min(width / 10, height / 10, 8);\n};\nvar getCutRectangleCornerLength = function getCutRectangleCornerLength() {\n  return 8;\n};\nvar bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {\n  return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];\n};\n\n// get curve width, height, and control point position offsets as a percentage of node height / width\nvar 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\nvar pageRankDefaults = defaults$g({\n  dampingFactor: 0.8,\n  precision: 0.000001,\n  iterations: 200,\n  weight: function weight(edge) {\n    return 1;\n  }\n});\nvar 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    var cy = this._private.cy;\n    var _this$byGroup = this.byGroup(),\n      nodes = _this$byGroup.nodes,\n      edges = _this$byGroup.edges;\n    var numNodes = nodes.length;\n    var numNodesSqd = numNodes * numNodes;\n    var numEdges = edges.length;\n\n    // 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    var matrix = new Array(numNodesSqd);\n    var columnSum = new Array(numNodes);\n    var additionalProb = (1 - dampingFactor) / numNodes;\n\n    // Create null matrix\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      columnSum[i] = 0;\n    }\n\n    // Now, process edges\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');\n\n      // Don't include loops in the matrix\n      if (srcId === tgtId) {\n        continue;\n      }\n      var s = nodes.indexOfId(srcId);\n      var t = nodes.indexOfId(tgtId);\n      var w = weight(edge);\n      var _n = t * numNodes + s;\n\n      // Update matrix\n      matrix[_n] += w;\n\n      // Update column sum\n      columnSum[s] += w;\n    }\n\n    // Add additional probability based on damping factor\n    // Also, take into account columns that have sum = 0\n    var p = 1.0 / numNodes + additionalProb; // Shorthand\n\n    // Traverse matrix, column by column\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          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          matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;\n        }\n      }\n    }\n\n    // Compute dominant eigenvector using power method\n    var eigenvector = new Array(numNodes);\n    var temp = new Array(numNodes);\n    var previous;\n\n    // Start with a vector of all 1's\n    // Also, initialize a null vector which will be used as shorthand\n    for (var _i4 = 0; _i4 < numNodes; _i4++) {\n      eigenvector[_i4] = 1;\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      }\n\n      // Multiply matrix with previous result\n      for (var _i6 = 0; _i6 < numNodes; _i6++) {\n        for (var _j2 = 0; _j2 < numNodes; _j2++) {\n          var _n4 = _i6 * numNodes + _j2;\n          temp[_i6] += matrix[_n4] * eigenvector[_j2];\n        }\n      }\n      inPlaceSumNormalize(temp);\n      previous = eigenvector;\n      eigenvector = temp;\n      temp = previous;\n      var diff = 0;\n      // Compute difference (squared module) of both vectors\n      for (var _i7 = 0; _i7 < numNodes; _i7++) {\n        var delta = previous[_i7] - eigenvector[_i7];\n        diff += delta * delta;\n      }\n\n      // If difference is less than the desired threshold, stop iterating\n      if (diff < precision) {\n        break;\n      }\n    }\n\n    // Construct result\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}; // elesfn\n\nvar defaults$f = defaults$g({\n  root: null,\n  weight: function weight(edge) {\n    return 1;\n  },\n  directed: false,\n  alpha: 0\n});\nvar 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    if (!options.directed) {\n      var degrees = {};\n      var maxDegree = 0;\n      for (var i = 0; i < numNodes; i++) {\n        var node = nodes[i];\n\n        // add current node to the current options object and call degreeCentrality\n        options.root = node;\n        var currDegree = this.degreeCentrality(options);\n        if (maxDegree < currDegree.degree) {\n          maxDegree = currDegree.degree;\n        }\n        degrees[node.id()] = currDegree.degree;\n      }\n      return {\n        degree: function degree(node) {\n          if (maxDegree === 0) {\n            return 0;\n          }\n          if (string(node)) {\n            // from is a selector string\n            node = cy.filter(node);\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      for (var _i = 0; _i < numNodes; _i++) {\n        var _node = nodes[_i];\n        var id = _node.id();\n\n        // add current node to the current options object and call degreeCentrality\n        options.root = _node;\n        var _currDegree = this.degreeCentrality(options);\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      return {\n        indegree: function indegree(node) {\n          if (maxIndegree == 0) {\n            return 0;\n          }\n          if (string(node)) {\n            // from is a selector string\n            node = cy.filter(node);\n          }\n          return indegrees[node.id()] / maxIndegree;\n        },\n        outdegree: function outdegree(node) {\n          if (maxOutdegree === 0) {\n            return 0;\n          }\n          if (string(node)) {\n            // from is a selector string\n            node = cy.filter(node);\n          }\n          return outdegrees[node.id()] / maxOutdegree;\n        }\n      };\n    }\n  },\n  // degreeCentralityNormalized\n\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    if (!directed) {\n      var connEdges = root.connectedEdges().intersection(callingEles);\n      var k = connEdges.length;\n      var s = 0;\n\n      // Now, sum edge weights\n      for (var i = 0; i < connEdges.length; i++) {\n        s += weight(connEdges[i]);\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;\n\n      // Now, sum incoming edge weights\n      for (var _i2 = 0; _i2 < incoming.length; _i2++) {\n        s_in += weight(incoming[_i2]);\n      }\n\n      // Now, sum outgoing edge weights\n      for (var _i3 = 0; _i3 < outgoing.length; _i3++) {\n        s_out += weight(outgoing[_i3]);\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}; // elesfn\n\n// nice, short mathematical alias\nelesfn$n.dc = elesfn$n.degreeCentrality;\nelesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;\n\nvar defaults$e = defaults$g({\n  harmonic: true,\n  weight: function weight() {\n    return 1;\n  },\n  directed: false,\n  root: null\n});\nvar 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    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    });\n\n    // Compute closeness for every node and find the maximum closeness\n    for (var i = 0; i < nodes.length; i++) {\n      var currCloseness = 0;\n      var node_i = nodes[i];\n      for (var j = 0; j < nodes.length; j++) {\n        if (i !== j) {\n          var d = fw.distance(node_i, nodes[j]);\n          if (harmonic) {\n            currCloseness += 1 / d;\n          } else {\n            currCloseness += d;\n          }\n        }\n      }\n      if (!harmonic) {\n        currCloseness = 1 / currCloseness;\n      }\n      if (maxCloseness < currCloseness) {\n        maxCloseness = currCloseness;\n      }\n      closenesses[node_i.id()] = currCloseness;\n    }\n    return {\n      closeness: function closeness(node) {\n        if (maxCloseness == 0) {\n          return 0;\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        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    root = this.filter(root)[0];\n\n    // we need distance from this node to every other node\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    for (var i = 0; i < nodes.length; i++) {\n      var n = nodes[i];\n      if (!n.same(root)) {\n        var d = dijkstra.distanceTo(n);\n        if (harmonic) {\n          totalDistance += 1 / d;\n        } else {\n          totalDistance += d;\n        }\n      }\n    }\n    return harmonic ? totalDistance : 1 / totalDistance;\n  } // closenessCentrality\n}; // elesfn\n\n// nice, short mathematical alias\nelesfn$m.cc = elesfn$m.closenessCentrality;\nelesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;\n\nvar defaults$d = defaults$g({\n  weight: null,\n  directed: false\n});\nvar 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    var weighted = weight != null;\n    var cy = this.cy();\n\n    // starting\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        if (val > max) {\n          max = val;\n        }\n      },\n      get: function get(key) {\n        return _C[key];\n      }\n    };\n\n    // A contains the neighborhoods of every node\n    for (var i = 0; i < V.length; i++) {\n      var v = V[i];\n      var vid = v.id();\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      C.set(vid, 0);\n    }\n    var _loop = function _loop() {\n      var sid = V[s].id();\n      var S = []; // stack\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\n      // init dictionaries\n      for (var _i = 0; _i < V.length; _i++) {\n        var _vid = V[_i].id();\n        P[_vid] = [];\n        g[_vid] = 0;\n        d[_vid] = Infinity;\n      }\n      g[sid] = 1; // sigma\n      d[sid] = 0; // distance to s\n\n      Q.push(sid);\n      while (!Q.empty()) {\n        var _v = Q.pop();\n        S.push(_v);\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 = undefined;\n            if (vEle.edgesTo(w).length > 0) {\n              edge = vEle.edgesTo(w)[0];\n            } else {\n              edge = w.edgesTo(vEle)[0];\n            }\n            var edgeWeight = weight(edge);\n            w = w.id();\n            if (d[w] > d[_v] + edgeWeight) {\n              d[w] = d[_v] + edgeWeight;\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              g[w] = 0;\n              P[w] = [];\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            if (d[_w] == Infinity) {\n              Q.push(_w);\n              d[_w] = d[_v] + 1;\n            }\n            if (d[_w] == d[_v] + 1) {\n              g[_w] = g[_w] + g[_v];\n              P[_w].push(_v);\n            }\n          }\n        }\n      }\n      var e = {};\n      for (var _i2 = 0; _i2 < V.length; _i2++) {\n        e[V[_i2].id()] = 0;\n      }\n      while (S.length > 0) {\n        var _w2 = S.pop();\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        if (_w2 != V[s].id()) {\n          C.set(_w2, C.get(_w2) + e[_w2]);\n        }\n      }\n    };\n    for (var s = 0; s < V.length; s++) {\n      _loop();\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        var id = cy.collection(node).id();\n        return C.get(id) / max;\n      }\n    };\n\n    // alias\n    ret.betweennessNormalised = ret.betweennessNormalized;\n    return ret;\n  } // betweennessCentrality\n}; // elesfn\n\n// nice, short mathematical alias\nelesfn$l.bc = elesfn$l.betweennessCentrality;\n\n// Implemented by Zoe Xi @zoexi for GSOC 2016\n// https://github.com/cytoscape/cytoscape.js-markov-cluster\n\n\n/* eslint-disable no-unused-vars */\nvar 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: [\n  // attributes/features used to group nodes, ie. similarity values between nodes\n  function (edge) {\n    return 1;\n  }]\n});\n/* eslint-enable */\n\nvar setOptions$3 = function setOptions(options) {\n  return defaults$c(options);\n};\n/* eslint-enable */\n\nvar getSimilarity$1 = function getSimilarity(edge, attributes) {\n  var total = 0;\n  for (var i = 0; i < attributes.length; i++) {\n    total += attributes[i](edge);\n  }\n  return total;\n};\nvar addLoops = function addLoops(M, n, val) {\n  for (var i = 0; i < n; i++) {\n    M[i * n + i] = val;\n  }\n};\nvar normalize = function normalize(M, n) {\n  var sum;\n  for (var col = 0; col < n; col++) {\n    sum = 0;\n    for (var row = 0; row < n; row++) {\n      sum += M[row * n + col];\n    }\n    for (var _row = 0; _row < n; _row++) {\n      M[_row * n + col] = M[_row * n + col] / sum;\n    }\n  }\n};\n\n// TODO: blocked matrix multiplication?\nvar mmult = function mmult(A, B, n) {\n  var C = new Array(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    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  return C;\n};\nvar expand = function expand(M, n, expandFactor /** power **/) {\n  var _M = M.slice(0);\n  for (var p = 1; p < expandFactor; p++) {\n    M = mmult(M, _M, n);\n  }\n  return M;\n};\nvar inflate = function inflate(M, n, inflateFactor /** r **/) {\n  var _M = new Array(n * n);\n\n  // M(i,j) ^ inflatePower\n  for (var i = 0; i < n * n; i++) {\n    _M[i] = Math.pow(M[i], inflateFactor);\n  }\n  normalize(_M, n);\n  return _M;\n};\nvar 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    var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);\n    if (v1 !== v2) {\n      return false;\n    }\n  }\n  return true;\n};\nvar assign$2 = function assign(M, n, nodes, cy) {\n  var clusters = [];\n  for (var i = 0; i < n; i++) {\n    var cluster = [];\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    if (cluster.length !== 0) {\n      clusters.push(cy.collection(cluster));\n    }\n  }\n  return clusters;\n};\nvar 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  return true;\n};\nvar 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  return clusters;\n};\nvar markovClustering = function markovClustering(options) {\n  var nodes = this.nodes();\n  var edges = this.edges();\n  var cy = this.cy();\n\n  // Set parameters of algorithm:\n  var opts = setOptions$3(options);\n\n  // Map each node to its position in node array\n  var id2position = {};\n  for (var i = 0; i < nodes.length; i++) {\n    id2position[nodes[i].id()] = i;\n  }\n\n  // Generate stochastic matrix M from input graph G (should be symmetric/undirected)\n  var n = nodes.length,\n    n2 = n * n;\n  var M = new Array(n2),\n    _M;\n  for (var _i = 0; _i < n2; _i++) {\n    M[_i] = 0;\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    M[j * n + _i2] += sim;\n  }\n\n  // Begin Markov cluster algorithm\n\n  // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal\n  addLoops(M, n, opts.multFactor);\n\n  // Step 2: M = normalize( M );\n  normalize(M, n);\n  var isStillMoving = true;\n  var iterations = 0;\n  while (isStillMoving && iterations < opts.maxIterations) {\n    isStillMoving = false;\n\n    // Step 3:\n    _M = expand(M, n, opts.expandFactor);\n\n    // Step 4:\n    M = inflate(_M, n, opts.inflateFactor);\n\n    // Step 5: check to see if ~steady state has been reached\n    if (!hasConverged(M, _M, n2, 4)) {\n      isStillMoving = true;\n    }\n    iterations++;\n  }\n\n  // Build clusters from matrix\n  var clusters = assign$2(M, n, nodes, cy);\n\n  // Remove duplicate clusters due to symmetry of graph and M matrix\n  clusters = removeDuplicates(clusters);\n  return clusters;\n};\nvar markovClustering$1 = {\n  markovClustering: markovClustering,\n  mcl: markovClustering\n};\n\n// Common distance metrics for clustering algorithms\n// https://en.wikipedia.org/wiki/Hierarchical_clustering#Metric\n\nvar identity$1 = function identity(x) {\n  return x;\n};\nvar absDiff = function absDiff(p, q) {\n  return Math.abs(q - p);\n};\nvar addAbsDiff = function addAbsDiff(total, p, q) {\n  return total + absDiff(p, q);\n};\nvar addSquaredDiff = function addSquaredDiff(total, p, q) {\n  return total + Math.pow(q - p, 2);\n};\nvar sqrt = function sqrt(x) {\n  return Math.sqrt(x);\n};\nvar maxAbsDiff = function maxAbsDiff(currentMax, p, q) {\n  return Math.max(currentMax, absDiff(p, q));\n};\nvar getDistance = function getDistance(length, getP, getQ, init, visit) {\n  var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity$1;\n  var ret = init;\n  var p, q;\n  for (var dim = 0; dim < length; dim++) {\n    p = getP(dim);\n    q = getQ(dim);\n    ret = visit(ret, p, q);\n  }\n  return post(ret);\n};\nvar 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};\n\n// in case the user accidentally doesn't use camel case\ndistances['squared-euclidean'] = distances['squaredEuclidean'];\ndistances['squaredeuclidean'] = distances['squaredEuclidean'];\nfunction clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {\n  var impl;\n  if (fn$6(method)) {\n    impl = method;\n  } else {\n    impl = distances[method] || distances.euclidean;\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\nvar 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});\nvar setOptions$2 = function setOptions(options) {\n  return defaults$b(options);\n};\n\nvar 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  var getQ = function getQ(i) {\n    return attributes[i](node);\n  };\n  var nodeP = centroid;\n  var nodeQ = node;\n  return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);\n};\nvar 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;\n\n  // Find min, max values for each attribute dimension\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  }\n\n  // Build k centroids, each represented as an n-dim feature vector\n  for (var c = 0; c < k; c++) {\n    centroid = [];\n    for (var _i = 0; _i < ndim; _i++) {\n      centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value\n    }\n    centroids[c] = centroid;\n  }\n  return centroids;\n};\nvar classify = function classify(node, centroids, distance, attributes, type) {\n  var min = Infinity;\n  var index = 0;\n  for (var i = 0; i < centroids.length; i++) {\n    var dist = getDist(distance, node, centroids[i], attributes, type);\n    if (dist < min) {\n      min = dist;\n      index = i;\n    }\n  }\n  return index;\n};\nvar buildCluster = function buildCluster(centroid, nodes, assignment) {\n  var cluster = [];\n  var node = null;\n  for (var n = 0; n < nodes.length; n++) {\n    node = nodes[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  return cluster;\n};\nvar haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {\n  return Math.abs(v2 - v1) <= sensitivityThreshold;\n};\nvar 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      if (diff > sensitivityThreshold) {\n        return false;\n      }\n    }\n  }\n  return true;\n};\nvar seenBefore = function seenBefore(node, medoids, n) {\n  for (var i = 0; i < n; i++) {\n    if (node === medoids[i]) return true;\n  }\n  return false;\n};\nvar randomMedoids = function randomMedoids(nodes, k) {\n  var medoids = new Array(k);\n\n  // 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  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)];\n\n      // 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      while (seenBefore(node, medoids, i)) {\n        node = nodes[Math.floor(Math.random() * nodes.length)];\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  return medoids;\n};\nvar findCost = function findCost(potentialNewMedoid, cluster, attributes) {\n  var cost = 0;\n  for (var n = 0; n < cluster.length; n++) {\n    cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');\n  }\n  return cost;\n};\nvar kMeans = function kMeans(options) {\n  var cy = this.cy();\n  var nodes = this.nodes();\n  var node = null;\n\n  // Set parameters of algorithm: # of clusters, distance metric, etc.\n  var opts = setOptions$2(options);\n\n  // Begin k-means algorithm\n  var clusters = new Array(opts.k);\n  var assignment = {};\n  var centroids;\n\n  // Step 1: Initialize centroid positions\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  var isStillMoving = true;\n  var iterations = 0;\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];\n      // Determine which cluster this node belongs to: node id => cluster #\n      assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');\n    }\n\n    // Step 3: For each of the k clusters, update its centroid\n    isStillMoving = false;\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      if (cluster.length === 0) {\n        // If cluster is empty, break out early & move to next cluster\n        continue;\n      }\n\n      // Update centroids by calculating avg of all nodes within the cluster.\n      var ndim = opts.attributes.length;\n      var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]\n      var newCentroid = new Array(ndim);\n      var sum = new Array(ndim);\n      for (var d = 0; d < ndim; d++) {\n        sum[d] = 0.0;\n        for (var i = 0; i < cluster.length; i++) {\n          node = cluster[i];\n          sum[d] += opts.attributes[d](node);\n        }\n        newCentroid[d] = sum[d] / cluster.length;\n\n        // Check to see if algorithm has converged, i.e. when centroids no longer change\n        if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {\n          isStillMoving = true;\n        }\n      }\n      centroids[c] = newCentroid;\n      clusters[c] = cy.collection(cluster);\n    }\n    iterations++;\n  }\n  return clusters;\n};\nvar kMedoids = function kMedoids(options) {\n  var cy = this.cy();\n  var nodes = this.nodes();\n  var node = null;\n  var opts = setOptions$2(options);\n\n  // Begin k-medoids algorithm\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\n  // Step 1: Initialize k medoids\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  var isStillMoving = true;\n  var iterations = 0;\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];\n      // Determine which cluster this node belongs to: node id => cluster #\n      assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');\n    }\n    isStillMoving = false;\n    // 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    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      if (cluster.length === 0) {\n        // If cluster is empty, break out early & move to next cluster\n        continue;\n      }\n      minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost\n\n      // Select different medoid if its configuration has the lowest cost\n      for (var _n = 0; _n < cluster.length; _n++) {\n        curCost = findCost(cluster[_n], cluster, opts.attributes);\n        if (curCost < minCosts[m]) {\n          minCosts[m] = curCost;\n          medoids[m] = cluster[_n];\n          isStillMoving = true;\n        }\n      }\n      clusters[m] = cy.collection(cluster);\n    }\n    iterations++;\n  }\n  return clusters;\n};\nvar updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {\n  var numerator, denominator;\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  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      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      centroids[_c][dim] = numerator / denominator;\n    }\n  }\n};\nvar 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  var sum, numerator, denominator;\n  var pow = 2 / (opts.m - 1);\n  for (var c = 0; c < centroids.length; c++) {\n    for (var n = 0; n < nodes.length; n++) {\n      sum = 0;\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      U[n][c] = 1 / sum;\n    }\n  }\n};\nvar assign$1 = function assign(nodes, U, opts, cy) {\n  var clusters = new Array(opts.k);\n  for (var c = 0; c < clusters.length; c++) {\n    clusters[c] = [];\n  }\n  var max;\n  var index;\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;\n    // Determine which cluster the node is most likely to belong in\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    clusters[index].push(nodes[n]);\n  }\n\n  // Turn every array into a collection of nodes\n  for (var _c3 = 0; _c3 < clusters.length; _c3++) {\n    clusters[_c3] = cy.collection(clusters[_c3]);\n  }\n  return clusters;\n};\nvar fuzzyCMeans = function fuzzyCMeans(options) {\n  var cy = this.cy();\n  var nodes = this.nodes();\n  var opts = setOptions$2(options);\n\n  // Begin fuzzy c-means algorithm\n  var clusters;\n  var centroids;\n  var U;\n  var _U;\n  var weight;\n\n  // Step 1: Initialize letiables.\n  _U = new Array(nodes.length);\n  for (var i = 0; i < nodes.length; i++) {\n    // N x C matrix\n    _U[i] = new Array(opts.k);\n  }\n  U = new Array(nodes.length);\n  for (var _i3 = 0; _i3 < nodes.length; _i3++) {\n    // N x C matrix\n    U[_i3] = new Array(opts.k);\n  }\n  for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n    var total = 0;\n    for (var j = 0; j < opts.k; j++) {\n      U[_i4][j] = Math.random();\n      total += U[_i4][j];\n    }\n    for (var _j = 0; _j < opts.k; _j++) {\n      U[_i4][_j] = U[_i4][_j] / total;\n    }\n  }\n  centroids = new Array(opts.k);\n  for (var _i5 = 0; _i5 < opts.k; _i5++) {\n    centroids[_i5] = new Array(opts.attributes.length);\n  }\n  weight = new Array(nodes.length);\n  for (var _i6 = 0; _i6 < nodes.length; _i6++) {\n    // N x C matrix\n    weight[_i6] = new Array(opts.k);\n  }\n  // end init FCM\n\n  var isStillMoving = true;\n  var iterations = 0;\n  while (isStillMoving && iterations < opts.maxIterations) {\n    isStillMoving = false;\n\n    // Step 2: Calculate the centroids for each step.\n    updateCentroids(centroids, nodes, U, weight, opts);\n\n    // Step 3: Update the partition matrix U.\n    updateMembership(U, _U, centroids, nodes, opts);\n\n    // Step 4: Check for convergence.\n    if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {\n      isStillMoving = true;\n    }\n    iterations++;\n  }\n\n  // Assign nodes to clusters with highest probability.\n  clusters = assign$1(nodes, U, opts, cy);\n  return {\n    clusters: clusters,\n    degreeOfMembership: U\n  };\n};\nvar 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// https://github.com/cytoscape/cytoscape.js-hierarchical\n\nvar 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});\nvar linkageAliases = {\n  'single': 'min',\n  'complete': 'max'\n};\nvar setOptions$1 = function setOptions(options) {\n  var opts = defaults$a(options);\n  var preferredAlias = linkageAliases[opts.linkage];\n  if (preferredAlias != null) {\n    opts.linkage = preferredAlias;\n  }\n  return opts;\n};\nvar 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  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  for (var i = 0; i < clusters.length; i++) {\n    var key = clusters[i].key;\n    var _dist = dists[key][mins[key]];\n    if (_dist < min) {\n      minKey = key;\n      min = _dist;\n    }\n  }\n  if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {\n    return false;\n  }\n  var c1 = index[minKey];\n  var c2 = index[mins[minKey]];\n  var merged;\n\n  // Merge two closest clusters\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  clusters[c1.index] = merged;\n  clusters.splice(c2.index, 1);\n  index[c1.key] = merged;\n\n  // Update distances with new merged cluster\n  for (var _i = 0; _i < clusters.length; _i++) {\n    var cur = clusters[_i];\n    if (c1.key === cur.key) {\n      dist = Infinity;\n    } else if (opts.linkage === 'min') {\n      dist = dists[c1.key][cur.key];\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      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    dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric\n  }\n\n  // Update cached mins\n  for (var _i2 = 0; _i2 < clusters.length; _i2++) {\n    var key1 = clusters[_i2].key;\n    if (mins[key1] === c1.key || mins[key1] === c2.key) {\n      var _min = key1;\n      for (var j = 0; j < clusters.length; j++) {\n        var key2 = clusters[j].key;\n        if (dists[key1][key2] < dists[key1][_min]) {\n          _min = key2;\n        }\n      }\n      mins[key1] = _min;\n    }\n    clusters[_i2].index = _i2;\n  }\n\n  // Clean up meta data used for clustering\n  c1.key = c2.key = c1.index = c2.index = null;\n  return true;\n};\nvar _getAllChildren = function getAllChildren(root, arr, cy) {\n  if (!root) return;\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};\nvar _buildDendrogram = function buildDendrogram(root, cy) {\n  if (!root) return '';\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};\nvar _buildClustersFromTree = function buildClustersFromTree(root, k, cy) {\n  if (!root) return [];\n  var left = [],\n    right = [],\n    leaves = [];\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\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\nvar hierarchicalClustering = function hierarchicalClustering(options) {\n  var cy = this.cy();\n  var nodes = this.nodes();\n\n  // Set parameters of algorithm: linkage type, distance metric, etc.\n  var opts = setOptions$1(options);\n  var attrs = opts.attributes;\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  // Begin hierarchical algorithm\n  var clusters = [];\n  var dists = []; // distances between each pair of clusters\n  var mins = []; // closest cluster for each cluster\n  var index = []; // hash of all clusters by key\n\n  // In agglomerative (bottom-up) clustering, each node starts as its own cluster\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  }\n\n  // Calculate the distance between each pair of clusters\n  for (var i = 0; i < clusters.length; i++) {\n    for (var j = 0; j <= i; j++) {\n      var dist = undefined;\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      dists[i][j] = dist;\n      dists[j][i] = dist;\n      if (dist < dists[i][mins[i]]) {\n        mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j\n      }\n    }\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  var merged = mergeClosest(clusters, index, dists, mins, opts);\n  while (merged) {\n    merged = mergeClosest(clusters, index, dists, mins, opts);\n  }\n  var retClusters;\n\n  // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges\n  // in addition to returning the clusters.\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\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  return retClusters;\n};\nvar hierarchicalClustering$1 = {\n  hierarchicalClustering: hierarchicalClustering,\n  hca: hierarchicalClustering\n};\n\n// Implemented by Zoe Xi @zoexi for GSOC 2016\n// https://github.com/cytoscape/cytoscape.js-affinity-propagation\n\nvar 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});\nvar setOptions = function setOptions(options) {\n  var dmp = options.damping;\n  var pref = options.preference;\n  if (!(0.5 <= dmp && dmp < 1)) {\n    error(\"Damping must range on [0.5, 1).  Got: \".concat(dmp));\n  }\n  var validPrefs = ['median', 'mean', 'min', 'max'];\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  return defaults$9(options);\n};\n\nvar getSimilarity = function getSimilarity(type, n1, n2, attributes) {\n  var attr = function attr(n, i) {\n    return attributes[i](n);\n  };\n\n  // nb negative because similarity should have an inverse relationship to distance\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};\nvar getPreference = function getPreference(S, preference) {\n  // larger preference = greater # of clusters\n  var p = null;\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  return p;\n};\nvar findExemplars = function findExemplars(n, R, A) {\n  var indices = [];\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  return indices;\n};\nvar assignClusters = function assignClusters(n, S, exemplars) {\n  var clusters = [];\n  for (var i = 0; i < n; i++) {\n    var index = -1;\n    var max = -Infinity;\n    for (var ei = 0; ei < exemplars.length; ei++) {\n      var e = exemplars[ei];\n      if (S[i * n + e] > max) {\n        index = e;\n        max = S[i * n + e];\n      }\n    }\n    if (index > 0) {\n      clusters.push(index);\n    }\n  }\n  for (var _ei = 0; _ei < exemplars.length; _ei++) {\n    clusters[exemplars[_ei]] = exemplars[_ei];\n  }\n  return clusters;\n};\nvar assign = function assign(n, S, exemplars) {\n  var clusters = assignClusters(n, S, exemplars);\n  for (var ei = 0; ei < exemplars.length; ei++) {\n    var ii = [];\n    for (var c = 0; c < clusters.length; c++) {\n      if (clusters[c] === exemplars[ei]) {\n        ii.push(c);\n      }\n    }\n    var maxI = -1;\n    var maxSum = -Infinity;\n    for (var i = 0; i < ii.length; i++) {\n      var sum = 0;\n      for (var j = 0; j < ii.length; j++) {\n        sum += S[ii[j] * n + ii[i]];\n      }\n      if (sum > maxSum) {\n        maxI = i;\n        maxSum = sum;\n      }\n    }\n    exemplars[ei] = ii[maxI];\n  }\n  clusters = assignClusters(n, S, exemplars);\n  return clusters;\n};\nvar affinityPropagation = function affinityPropagation(options) {\n  var cy = this.cy();\n  var nodes = this.nodes();\n  var opts = setOptions(options);\n\n  // Map each node to its position in node array\n  var id2position = {};\n  for (var i = 0; i < nodes.length; i++) {\n    id2position[nodes[i].id()] = i;\n  }\n\n  // Begin affinity propagation algorithm\n\n  var n; // number of data points\n  var n2; // size of matrices\n  var S; // similarity matrix (1D array)\n  var p; // preference/suitability of a data point to serve as an exemplar\n  var R; // responsibility matrix (1D array)\n  var A; // availability matrix (1D array)\n\n  n = nodes.length;\n  n2 = n * n;\n\n  // Initialize and build S similarity matrix\n  S = new Array(n2);\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  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  }\n\n  // Place preferences on the diagonal of S\n  p = getPreference(S, opts.preference);\n  for (var _i3 = 0; _i3 < n; _i3++) {\n    S[_i3 * n + _i3] = p;\n  }\n\n  // Initialize R responsibility matrix\n  R = new Array(n2);\n  for (var _i4 = 0; _i4 < n2; _i4++) {\n    R[_i4] = 0.0;\n  }\n\n  // Initialize A availability matrix\n  A = new Array(n2);\n  for (var _i5 = 0; _i5 < n2; _i5++) {\n    A[_i5] = 0.0;\n  }\n  var old = new Array(n);\n  var Rp = new Array(n);\n  var se = new Array(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  var e = new Array(n * opts.minIterations);\n  for (var _i7 = 0; _i7 < e.length; _i7++) {\n    e[_i7] = 0;\n  }\n  var iter;\n  for (iter = 0; iter < opts.maxIterations; iter++) {\n    // main algorithmic loop\n\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      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        if (AS >= max) {\n          max2 = max;\n          max = AS;\n          maxI = _j;\n        } else if (AS > max2) {\n          max2 = AS;\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      R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];\n    }\n\n    // Update A availability matrix\n    for (var _i9 = 0; _i9 < n; _i9++) {\n      var sum = 0;\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      sum -= Rp[_i9];\n      Rp[_i9] = R[_i9 * n + _i9];\n      sum += Rp[_i9];\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      A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];\n    }\n\n    // Check for convergence\n    var K = 0;\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    if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {\n      var _sum = 0;\n      for (var _i11 = 0; _i11 < n; _i11++) {\n        se[_i11] = 0;\n        for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {\n          se[_i11] += e[_j5 * n + _i11];\n        }\n        if (se[_i11] === 0 || se[_i11] === opts.minIterations) {\n          _sum++;\n        }\n      }\n      if (_sum === n) {\n        // then we have convergence\n        break;\n      }\n    }\n  }\n\n  // Identify exemplars (cluster centers)\n  var exemplarsIndices = findExemplars(n, R, A);\n\n  // Assign nodes to clusters\n  var clusterIndices = assign(n, S, exemplarsIndices);\n  var clusters = {};\n  for (var c = 0; c < exemplarsIndices.length; c++) {\n    clusters[exemplarsIndices[c]] = [];\n  }\n  for (var _i12 = 0; _i12 < nodes.length; _i12++) {\n    var pos = id2position[nodes[_i12].id()];\n    var clusterIndex = clusterIndices[pos];\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  var retClusters = new Array(exemplarsIndices.length);\n  for (var _c = 0; _c < exemplarsIndices.length; _c++) {\n    retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);\n  }\n  return retClusters;\n};\nvar affinityPropagation$1 = {\n  affinityPropagation: affinityPropagation,\n  ap: affinityPropagation\n};\n\nvar hierholzerDefaults = defaults$g({\n  root: undefined,\n  directed: false\n});\nvar 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    var _hierholzerDefaults = hierholzerDefaults(options),\n      root = _hierholzerDefaults.root,\n      directed = _hierholzerDefaults.directed;\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    if (directed) {\n      eles.forEach(function (ele) {\n        var id = ele.id();\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          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          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        if (ele.isNode()) {\n          var d = ele.degree(true);\n          if (d % 2) {\n            if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;\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    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        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    var walk = function walk(v) {\n      var currentNode = v;\n      var subtour = [v];\n      var adj, adjTail, adjHead;\n      while (nodes[currentNode].length) {\n        adj = nodes[currentNode].shift();\n        adjTail = edges[adj][0];\n        adjHead = edges[adj][1];\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        subtour.unshift(adj);\n        subtour.unshift(currentNode);\n      }\n      return subtour;\n    };\n    var trail = [];\n    var subtour = [];\n    subtour = walk(startVertex);\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    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    result.found = true;\n    result.trail = this.spawn(trail, true);\n    return result;\n  }\n};\n\nvar 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  var buildComponent = function buildComponent(x, y) {\n    var i = stack.length - 1;\n    var cutset = [];\n    var component = eles.spawn();\n    while (stack[i].x != x || stack[i].y != y) {\n      cutset.push(stack.pop().edge);\n      i--;\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        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  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    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        if (otherNodeId !== parent) {\n          edgeId = edge.id();\n          if (!visitedEdges[edgeId]) {\n            visitedEdges[edgeId] = true;\n            stack.push({\n              x: currentNode,\n              y: otherNodeId,\n              edge: edge\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            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  eles.forEach(function (ele) {\n    if (ele.isNode()) {\n      var nodeId = ele.id();\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};\nvar hopcroftTarjanBiconnected$1 = {\n  hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,\n  htbc: hopcroftTarjanBiconnected,\n  htb: hopcroftTarjanBiconnected,\n  hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected\n};\n\nvar 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  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      if (targetNodeId !== sourceNodeId) {\n        if (!(targetNodeId in nodes)) {\n          _stronglyConnectedSearch(targetNodeId);\n        }\n        if (!nodes[targetNodeId].explored) {\n          nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);\n        }\n      }\n    });\n    if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {\n      var componentNodes = eles.spawn();\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        if (nodeId === sourceNodeId) {\n          break;\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  eles.forEach(function (ele) {\n    if (ele.isNode()) {\n      var nodeId = ele.id();\n      if (!(nodeId in nodes)) {\n        _stronglyConnectedSearch(nodeId);\n      }\n    }\n  });\n  return {\n    cut: cut,\n    components: components\n  };\n};\nvar tarjanStronglyConnected$1 = {\n  tarjanStronglyConnected: tarjanStronglyConnected,\n  tsc: tarjanStronglyConnected,\n  tscc: tarjanStronglyConnected,\n  tarjanStronglyConnectedComponents: tarjanStronglyConnected\n};\n\nvar 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/*!\nEmbeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable\nCopyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)\nLicensed under The MIT License (http://opensource.org/licenses/MIT)\n*/\n\n/*  promise states [Promises/A+ 2.1]  */\nvar STATE_PENDING = 0; /*  [Promises/A+ 2.1.1]  */\nvar STATE_FULFILLED = 1; /*  [Promises/A+ 2.1.2]  */\nvar STATE_REJECTED = 2; /*  [Promises/A+ 2.1.3]  */\n\n/*  promise object constructor  */\nvar _api = function api(executor) {\n  /*  optionally support non-constructor/plain-function call  */\n  if (!(this instanceof _api)) return new _api(executor);\n\n  /*  initialize object  */\n  this.id = 'Thenable/1.0.7';\n  this.state = STATE_PENDING; /*  initial state  */\n  this.fulfillValue = undefined; /*  initial value  */ /*  [Promises/A+ 1.3, 2.1.2.2]  */\n  this.rejectReason = undefined; /*  initial reason */ /*  [Promises/A+ 1.5, 2.1.3.2]  */\n  this.onFulfilled = []; /*  initial handlers  */\n  this.onRejected = []; /*  initial handlers  */\n\n  /*  provide optional information-hiding proxy  */\n  this.proxy = {\n    then: this.then.bind(this)\n  };\n\n  /*  support optional executor function  */\n  if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));\n};\n\n/*  promise API methods  */\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  /*  \"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(); /*  [Promises/A+ 2.2.7]  */\n    curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill')); /*  [Promises/A+ 2.2.2/2.2.6]  */\n    curr.onRejected.push(resolver(onRejected, next, 'reject')); /*  [Promises/A+ 2.2.3/2.2.6]  */\n    execute(curr);\n    return next.proxy; /*  [Promises/A+ 2.2.7, 3.3]  */\n  }\n};\n\n/*  deliver an action  */\nvar deliver = function deliver(curr, state, name, value) {\n  if (curr.state === STATE_PENDING) {\n    curr.state = state; /*  [Promises/A+ 2.1.2.1, 2.1.3.1]  */\n    curr[name] = value; /*  [Promises/A+ 2.1.2.2, 2.1.3.2]  */\n    execute(curr);\n  }\n  return curr;\n};\n\n/*  execute all handlers  */\nvar 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\n/*  execute particular set of handlers  */\nvar execute_handlers = function execute_handlers(curr, name, value) {\n  /* global setImmediate: true */\n  /* global setTimeout: true */\n\n  /*  short-circuit processing  */\n  if (curr[name].length === 0) return;\n\n  /*  iterate over all handlers, exactly once  */\n  var handlers = curr[name];\n  curr[name] = []; /*  [Promises/A+ 2.2.2.3, 2.2.3.3]  */\n  var func = function func() {\n    for (var i = 0; i < handlers.length; i++) handlers[i](value); /*  [Promises/A+ 2.2.5]  */\n  };\n\n  /*  execute procedure asynchronously  */ /*  [Promises/A+ 2.2.4, 3.1]  */\n  if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);\n};\n\n/*  generate a resolver function  */\nvar resolver = function resolver(cb, next, method) {\n  return function (value) {\n    if (typeof cb !== 'function') /*  [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4]  */\n      next[method].call(next, value); /*  [Promises/A+ 2.2.7.3, 2.2.7.4]  */else {\n      var result;\n      try {\n        result = cb(value);\n      } /*  [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2]  */ catch (e) {\n        next.reject(e); /*  [Promises/A+ 2.2.7.2]  */\n        return;\n      }\n      _resolve(next, result); /*  [Promises/A+ 2.2.7.1]  */\n    }\n  };\n};\n\n/*  \"Promise Resolution Procedure\"  */ /*  [Promises/A+ 2.3]  */\nvar _resolve = function resolve(promise, x) {\n  /*  sanity check arguments  */ /*  [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\n  /*  surgically check for a \"then\" method\n    (mainly to just call the \"getter\" of \"then\" only once)  */\n  var then;\n  if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {\n    try {\n      then = x.then;\n    } /*  [Promises/A+ 2.3.3.1, 3.5]  */ catch (e) {\n      promise.reject(e); /*  [Promises/A+ 2.3.3.2]  */\n      return;\n    }\n  }\n\n  /*  handle own Thenables    [Promises/A+ 2.3.2]\n    and similar \"thenables\" [Promises/A+ 2.3.3]  */\n  if (typeof then === 'function') {\n    var resolved = false;\n    try {\n      /*  call retrieved \"then\" method */ /*  [Promises/A+ 2.3.3.3]  */\n      then.call(x, /*  resolvePromise  */ /*  [Promises/A+ 2.3.3.3.1]  */\n      function (y) {\n        if (resolved) return;\n        resolved = true; /*  [Promises/A+ 2.3.3.3.3]  */\n        if (y === x) /*  [Promises/A+ 3.6]  */\n          promise.reject(new TypeError('circular thenable chain'));else _resolve(promise, y);\n      }, /*  rejectPromise  */ /*  [Promises/A+ 2.3.3.3.2]  */\n      function (r) {\n        if (resolved) return;\n        resolved = true; /*  [Promises/A+ 2.3.3.3.3]  */\n        promise.reject(r);\n      });\n    } catch (e) {\n      if (!resolved) /*  [Promises/A+ 2.3.3.3.3]  */\n        promise.reject(e); /*  [Promises/A+ 2.3.3.3.4]  */\n    }\n    return;\n  }\n\n  /*  handle other values  */\n  promise.fulfill(x); /*  [Promises/A+ 2.3.4, 2.3.3.4]  */\n};\n\n// so we always have Promise.all()\n_api.all = function (ps) {\n  return new _api(function (resolveAll, rejectAll) {\n    var vals = new Array(ps.length);\n    var doneCount = 0;\n    var fulfill = function fulfill(i, val) {\n      vals[i] = val;\n      doneCount++;\n      if (doneCount === ps.length) {\n        resolveAll(vals);\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        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_api.resolve = function (val) {\n  return new _api(function (resolve, reject) {\n    resolve(val);\n  });\n};\n_api.reject = function (val) {\n  return new _api(function (resolve, reject) {\n    reject(val);\n  });\n};\nvar Promise$1 = typeof Promise !== 'undefined' ? Promise : _api; // eslint-disable-line no-undef\n\nvar Animation = function Animation(target, opts, opts2) {\n  var isCore = core(target);\n  var isEle = !isCore;\n  var _p = this._private = extend({\n    duration: 1000\n  }, opts, opts2);\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  if (_p.complete && fn$6(_p.complete)) {\n    _p.completes.push(_p.complete);\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  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  }\n\n  // for future timeline/animations impl\n  this.length = 1;\n  this[0] = this;\n};\nvar anifn = Animation.prototype;\nextend(anifn, {\n  instanceString: function instanceString() {\n    return 'animation';\n  },\n  hook: function hook() {\n    var _p = this._private;\n    if (!_p.hooked) {\n      // add to target's animation queue\n      var q;\n      var tAni = _p.target._private.animation;\n      if (_p.queue) {\n        q = tAni.queue;\n      } else {\n        q = tAni.current;\n      }\n      q.push(this);\n\n      // add to the animation loop pool\n      if (elementOrCollection(_p.target)) {\n        _p.target.cy().addToAnimationPool(_p.target);\n      }\n      _p.hooked = true;\n    }\n    return this;\n  },\n  play: function play() {\n    var _p = this._private;\n\n    // autorewind\n    if (_p.progress === 1) {\n      _p.progress = 0;\n    }\n    _p.playing = true;\n    _p.started = false; // needs to be started by animation loop\n    _p.stopped = false;\n    this.hook();\n\n    // 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    _p.stopped = false;\n    this.hook();\n\n    // 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    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    if (p === undefined) {\n      return _p.progress;\n    } else {\n      if (wasPlaying) {\n        this.pause();\n      }\n      _p.progress = p;\n      _p.started = false;\n      if (wasPlaying) {\n        this.play();\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    if (wasPlaying) {\n      this.pause();\n    }\n    _p.progress = 1 - _p.progress;\n    _p.started = false;\n    var swap = function swap(a, b) {\n      var _pa = _p[a];\n      if (_pa == null) {\n        return;\n      }\n      _p[a] = _p[b];\n      _p[b] = _pa;\n    };\n    swap('zoom', 'startZoom');\n    swap('pan', 'startPan');\n    swap('position', 'startPosition');\n\n    // swap styles\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    if (wasPlaying) {\n      this.play();\n    }\n    return this;\n  },\n  promise: function promise(type) {\n    var _p = this._private;\n    var arr;\n    switch (type) {\n      case 'frame':\n        arr = _p.frames;\n        break;\n      default:\n      case 'complete':\n      case 'completed':\n        arr = _p.completes;\n    }\n    return new Promise$1(function (resolve, reject) {\n      arr.push(function () {\n        resolve();\n      });\n    });\n  }\n});\nanifn.complete = anifn.completed;\nanifn.run = anifn.play;\nanifn.running = anifn.playing;\n\nvar 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      var cy = this._private.cy || this;\n      if (!cy.styleEnabled()) {\n        return false;\n      }\n      var ele = all[0];\n      if (ele) {\n        return ele._private.animation.current.length > 0;\n      }\n    };\n  },\n  // animated\n\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      var cy = this._private.cy || this;\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n      for (var i = 0; i < all.length; i++) {\n        var ele = all[i];\n        ele._private.animation.queue = [];\n      }\n      return this;\n    };\n  },\n  // clearQueue\n\n  delay: function delay() {\n    return function delayImpl(time, complete) {\n      var cy = this._private.cy || this;\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n      return this.animate({\n        delay: time,\n        duration: time,\n        complete: complete\n      });\n    };\n  },\n  // delay\n\n  delayAnimation: function delayAnimation() {\n    return function delayAnimationImpl(time, complete) {\n      var cy = this._private.cy || this;\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n      return this.animation({\n        delay: time,\n        duration: time,\n        complete: complete\n      });\n    };\n  },\n  // delay\n\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      var cy = this._private.cy || this;\n      var isCore = !selfIsArrayLike;\n      var isEles = !isCore;\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n      var style = cy.style();\n      properties = extend({}, properties, params);\n      var propertiesEmpty = Object.keys(properties).length === 0;\n      if (propertiesEmpty) {\n        return new Animation(all[0], properties); // nothing to animate\n      }\n      if (properties.duration === undefined) {\n        properties.duration = 400;\n      }\n      switch (properties.duration) {\n        case 'slow':\n          properties.duration = 600;\n          break;\n        case 'fast':\n          properties.duration = 200;\n          break;\n      }\n      if (isEles) {\n        properties.style = style.getPropsList(properties.style || properties.css);\n        properties.css = undefined;\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      }\n\n      // override pan w/ panBy if set\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      }\n\n      // override pan w/ center if set\n      var center = properties.center || properties.centre;\n      if (isCore && center != null) {\n        var centerPan = cy.getCenterPan(center.eles, properties.zoom);\n        if (centerPan != null) {\n          properties.pan = centerPan;\n        }\n      }\n\n      // override pan & zoom w/ fit if set\n      if (isCore && properties.fit != null) {\n        var fit = properties.fit;\n        var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);\n        if (fitVp != null) {\n          properties.pan = fitVp.pan;\n          properties.zoom = fitVp.zoom;\n        }\n      }\n\n      // override zoom (& potentially pan) w/ zoom obj if set\n      if (isCore && plainObject(properties.zoom)) {\n        var vp = cy.getZoomedViewport(properties.zoom);\n        if (vp != null) {\n          if (vp.zoomed) {\n            properties.zoom = vp.zoom;\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      return new Animation(all[0], properties);\n    };\n  },\n  // animate\n\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      var cy = this._private.cy || this;\n      if (!cy.styleEnabled()) {\n        return this;\n      }\n      if (params) {\n        properties = extend({}, properties, params);\n      }\n\n      // manually hook and run the animation\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      return this; // chaining\n    };\n  },\n  // animate\n\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      var cy = this._private.cy || this;\n      if (!cy.styleEnabled()) {\n        return this;\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        for (var j = 0; j < anis.length; j++) {\n          var ani = anis[j];\n          var ani_p = ani._private;\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        }\n\n        // clear the queue of future animations\n        if (clearQueue) {\n          _p.animation.queue = [];\n        }\n        if (!jumpToEnd) {\n          _p.animation.current = [];\n        }\n      }\n\n      // we have to notify (the animation loop doesn't do it for us on `stop`)\n      cy.notify('draw');\n      return this;\n    };\n  } // stop\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\nvar isArray_1;\nvar hasRequiredIsArray;\n\nfunction requireIsArray () {\n\tif (hasRequiredIsArray) return isArray_1;\n\thasRequiredIsArray = 1;\n\tvar isArray = Array.isArray;\n\n\tisArray_1 = isArray;\n\treturn isArray_1;\n}\n\nvar _isKey;\nvar hasRequired_isKey;\n\nfunction require_isKey () {\n\tif (hasRequired_isKey) return _isKey;\n\thasRequired_isKey = 1;\n\tvar isArray = requireIsArray(),\n\t    isSymbol = requireIsSymbol();\n\n\t/** Used to match property names within property paths. */\n\tvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n\t    reIsPlainProp = /^\\w*$/;\n\n\t/**\n\t * Checks if `value` is a property name and not a property path.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @param {Object} [object] The object to query keys on.\n\t * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n\t */\n\tfunction isKey(value, object) {\n\t  if (isArray(value)) {\n\t    return false;\n\t  }\n\t  var type = typeof value;\n\t  if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n\t      value == null || isSymbol(value)) {\n\t    return true;\n\t  }\n\t  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n\t    (object != null && value in Object(object));\n\t}\n\n\t_isKey = isKey;\n\treturn _isKey;\n}\n\nvar isFunction_1;\nvar hasRequiredIsFunction;\n\nfunction requireIsFunction () {\n\tif (hasRequiredIsFunction) return isFunction_1;\n\thasRequiredIsFunction = 1;\n\tvar baseGetTag = require_baseGetTag(),\n\t    isObject = requireIsObject();\n\n\t/** `Object#toString` result references. */\n\tvar asyncTag = '[object AsyncFunction]',\n\t    funcTag = '[object Function]',\n\t    genTag = '[object GeneratorFunction]',\n\t    proxyTag = '[object Proxy]';\n\n\t/**\n\t * Checks if `value` is classified as a `Function` object.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Lang\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n\t * @example\n\t *\n\t * _.isFunction(_);\n\t * // => true\n\t *\n\t * _.isFunction(/abc/);\n\t * // => false\n\t */\n\tfunction isFunction(value) {\n\t  if (!isObject(value)) {\n\t    return false;\n\t  }\n\t  // The use of `Object#toString` avoids issues with the `typeof` operator\n\t  // in Safari 9 which returns 'object' for typed arrays and other constructors.\n\t  var tag = baseGetTag(value);\n\t  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n\t}\n\n\tisFunction_1 = isFunction;\n\treturn isFunction_1;\n}\n\nvar _coreJsData;\nvar hasRequired_coreJsData;\n\nfunction require_coreJsData () {\n\tif (hasRequired_coreJsData) return _coreJsData;\n\thasRequired_coreJsData = 1;\n\tvar root = require_root();\n\n\t/** Used to detect overreaching core-js shims. */\n\tvar coreJsData = root['__core-js_shared__'];\n\n\t_coreJsData = coreJsData;\n\treturn _coreJsData;\n}\n\nvar _isMasked;\nvar hasRequired_isMasked;\n\nfunction require_isMasked () {\n\tif (hasRequired_isMasked) return _isMasked;\n\thasRequired_isMasked = 1;\n\tvar coreJsData = require_coreJsData();\n\n\t/** Used to detect methods masquerading as native. */\n\tvar maskSrcKey = (function() {\n\t  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n\t  return uid ? ('Symbol(src)_1.' + uid) : '';\n\t}());\n\n\t/**\n\t * Checks if `func` has its source masked.\n\t *\n\t * @private\n\t * @param {Function} func The function to check.\n\t * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n\t */\n\tfunction isMasked(func) {\n\t  return !!maskSrcKey && (maskSrcKey in func);\n\t}\n\n\t_isMasked = isMasked;\n\treturn _isMasked;\n}\n\n/** Used for built-in method references. */\n\nvar _toSource;\nvar hasRequired_toSource;\n\nfunction require_toSource () {\n\tif (hasRequired_toSource) return _toSource;\n\thasRequired_toSource = 1;\n\tvar funcProto = Function.prototype;\n\n\t/** Used to resolve the decompiled source of functions. */\n\tvar funcToString = funcProto.toString;\n\n\t/**\n\t * Converts `func` to its source code.\n\t *\n\t * @private\n\t * @param {Function} func The function to convert.\n\t * @returns {string} Returns the source code.\n\t */\n\tfunction toSource(func) {\n\t  if (func != null) {\n\t    try {\n\t      return funcToString.call(func);\n\t    } catch (e) {}\n\t    try {\n\t      return (func + '');\n\t    } catch (e) {}\n\t  }\n\t  return '';\n\t}\n\n\t_toSource = toSource;\n\treturn _toSource;\n}\n\nvar _baseIsNative;\nvar hasRequired_baseIsNative;\n\nfunction require_baseIsNative () {\n\tif (hasRequired_baseIsNative) return _baseIsNative;\n\thasRequired_baseIsNative = 1;\n\tvar isFunction = requireIsFunction(),\n\t    isMasked = require_isMasked(),\n\t    isObject = requireIsObject(),\n\t    toSource = require_toSource();\n\n\t/**\n\t * Used to match `RegExp`\n\t * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n\t */\n\tvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n\t/** Used to detect host constructors (Safari). */\n\tvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n\t/** Used for built-in method references. */\n\tvar funcProto = Function.prototype,\n\t    objectProto = Object.prototype;\n\n\t/** Used to resolve the decompiled source of functions. */\n\tvar funcToString = funcProto.toString;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/** Used to detect if a method is native. */\n\tvar reIsNative = RegExp('^' +\n\t  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n\t  .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n\t);\n\n\t/**\n\t * The base implementation of `_.isNative` without bad shim checks.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @returns {boolean} Returns `true` if `value` is a native function,\n\t *  else `false`.\n\t */\n\tfunction baseIsNative(value) {\n\t  if (!isObject(value) || isMasked(value)) {\n\t    return false;\n\t  }\n\t  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n\t  return pattern.test(toSource(value));\n\t}\n\n\t_baseIsNative = baseIsNative;\n\treturn _baseIsNative;\n}\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\nvar _getValue;\nvar hasRequired_getValue;\n\nfunction require_getValue () {\n\tif (hasRequired_getValue) return _getValue;\n\thasRequired_getValue = 1;\n\tfunction getValue(object, key) {\n\t  return object == null ? undefined : object[key];\n\t}\n\n\t_getValue = getValue;\n\treturn _getValue;\n}\n\nvar _getNative;\nvar hasRequired_getNative;\n\nfunction require_getNative () {\n\tif (hasRequired_getNative) return _getNative;\n\thasRequired_getNative = 1;\n\tvar baseIsNative = require_baseIsNative(),\n\t    getValue = require_getValue();\n\n\t/**\n\t * Gets the native function at `key` of `object`.\n\t *\n\t * @private\n\t * @param {Object} object The object to query.\n\t * @param {string} key The key of the method to get.\n\t * @returns {*} Returns the function if it's native, else `undefined`.\n\t */\n\tfunction getNative(object, key) {\n\t  var value = getValue(object, key);\n\t  return baseIsNative(value) ? value : undefined;\n\t}\n\n\t_getNative = getNative;\n\treturn _getNative;\n}\n\nvar _nativeCreate;\nvar hasRequired_nativeCreate;\n\nfunction require_nativeCreate () {\n\tif (hasRequired_nativeCreate) return _nativeCreate;\n\thasRequired_nativeCreate = 1;\n\tvar getNative = require_getNative();\n\n\t/* Built-in method references that are verified to be native. */\n\tvar nativeCreate = getNative(Object, 'create');\n\n\t_nativeCreate = nativeCreate;\n\treturn _nativeCreate;\n}\n\nvar _hashClear;\nvar hasRequired_hashClear;\n\nfunction require_hashClear () {\n\tif (hasRequired_hashClear) return _hashClear;\n\thasRequired_hashClear = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/**\n\t * Removes all key-value entries from the hash.\n\t *\n\t * @private\n\t * @name clear\n\t * @memberOf Hash\n\t */\n\tfunction hashClear() {\n\t  this.__data__ = nativeCreate ? nativeCreate(null) : {};\n\t  this.size = 0;\n\t}\n\n\t_hashClear = hashClear;\n\treturn _hashClear;\n}\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\nvar _hashDelete;\nvar hasRequired_hashDelete;\n\nfunction require_hashDelete () {\n\tif (hasRequired_hashDelete) return _hashDelete;\n\thasRequired_hashDelete = 1;\n\tfunction hashDelete(key) {\n\t  var result = this.has(key) && delete this.__data__[key];\n\t  this.size -= result ? 1 : 0;\n\t  return result;\n\t}\n\n\t_hashDelete = hashDelete;\n\treturn _hashDelete;\n}\n\nvar _hashGet;\nvar hasRequired_hashGet;\n\nfunction require_hashGet () {\n\tif (hasRequired_hashGet) return _hashGet;\n\thasRequired_hashGet = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/** Used to stand-in for `undefined` hash values. */\n\tvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Gets the hash value for `key`.\n\t *\n\t * @private\n\t * @name get\n\t * @memberOf Hash\n\t * @param {string} key The key of the value to get.\n\t * @returns {*} Returns the entry value.\n\t */\n\tfunction hashGet(key) {\n\t  var data = this.__data__;\n\t  if (nativeCreate) {\n\t    var result = data[key];\n\t    return result === HASH_UNDEFINED ? undefined : result;\n\t  }\n\t  return hasOwnProperty.call(data, key) ? data[key] : undefined;\n\t}\n\n\t_hashGet = hashGet;\n\treturn _hashGet;\n}\n\nvar _hashHas;\nvar hasRequired_hashHas;\n\nfunction require_hashHas () {\n\tif (hasRequired_hashHas) return _hashHas;\n\thasRequired_hashHas = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Checks if a hash value for `key` exists.\n\t *\n\t * @private\n\t * @name has\n\t * @memberOf Hash\n\t * @param {string} key The key of the entry to check.\n\t * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n\t */\n\tfunction hashHas(key) {\n\t  var data = this.__data__;\n\t  return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n\t}\n\n\t_hashHas = hashHas;\n\treturn _hashHas;\n}\n\nvar _hashSet;\nvar hasRequired_hashSet;\n\nfunction require_hashSet () {\n\tif (hasRequired_hashSet) return _hashSet;\n\thasRequired_hashSet = 1;\n\tvar nativeCreate = require_nativeCreate();\n\n\t/** Used to stand-in for `undefined` hash values. */\n\tvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n\t/**\n\t * Sets the hash `key` to `value`.\n\t *\n\t * @private\n\t * @name set\n\t * @memberOf Hash\n\t * @param {string} key The key of the value to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns the hash instance.\n\t */\n\tfunction hashSet(key, value) {\n\t  var data = this.__data__;\n\t  this.size += this.has(key) ? 0 : 1;\n\t  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n\t  return this;\n\t}\n\n\t_hashSet = hashSet;\n\treturn _hashSet;\n}\n\nvar _Hash;\nvar hasRequired_Hash;\n\nfunction require_Hash () {\n\tif (hasRequired_Hash) return _Hash;\n\thasRequired_Hash = 1;\n\tvar hashClear = require_hashClear(),\n\t    hashDelete = require_hashDelete(),\n\t    hashGet = require_hashGet(),\n\t    hashHas = require_hashHas(),\n\t    hashSet = require_hashSet();\n\n\t/**\n\t * Creates a hash object.\n\t *\n\t * @private\n\t * @constructor\n\t * @param {Array} [entries] The key-value pairs to cache.\n\t */\n\tfunction Hash(entries) {\n\t  var index = -1,\n\t      length = entries == null ? 0 : entries.length;\n\n\t  this.clear();\n\t  while (++index < length) {\n\t    var entry = entries[index];\n\t    this.set(entry[0], entry[1]);\n\t  }\n\t}\n\n\t// Add methods to `Hash`.\n\tHash.prototype.clear = hashClear;\n\tHash.prototype['delete'] = hashDelete;\n\tHash.prototype.get = hashGet;\n\tHash.prototype.has = hashHas;\n\tHash.prototype.set = hashSet;\n\n\t_Hash = Hash;\n\treturn _Hash;\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n\nvar _listCacheClear;\nvar hasRequired_listCacheClear;\n\nfunction require_listCacheClear () {\n\tif (hasRequired_listCacheClear) return _listCacheClear;\n\thasRequired_listCacheClear = 1;\n\tfunction listCacheClear() {\n\t  this.__data__ = [];\n\t  this.size = 0;\n\t}\n\n\t_listCacheClear = listCacheClear;\n\treturn _listCacheClear;\n}\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\nvar eq_1;\nvar hasRequiredEq;\n\nfunction requireEq () {\n\tif (hasRequiredEq) return eq_1;\n\thasRequiredEq = 1;\n\tfunction eq(value, other) {\n\t  return value === other || (value !== value && other !== other);\n\t}\n\n\teq_1 = eq;\n\treturn eq_1;\n}\n\nvar _assocIndexOf;\nvar hasRequired_assocIndexOf;\n\nfunction require_assocIndexOf () {\n\tif (hasRequired_assocIndexOf) return _assocIndexOf;\n\thasRequired_assocIndexOf = 1;\n\tvar eq = requireEq();\n\n\t/**\n\t * Gets the index at which the `key` is found in `array` of key-value pairs.\n\t *\n\t * @private\n\t * @param {Array} array The array to inspect.\n\t * @param {*} key The key to search for.\n\t * @returns {number} Returns the index of the matched value, else `-1`.\n\t */\n\tfunction assocIndexOf(array, key) {\n\t  var length = array.length;\n\t  while (length--) {\n\t    if (eq(array[length][0], key)) {\n\t      return length;\n\t    }\n\t  }\n\t  return -1;\n\t}\n\n\t_assocIndexOf = assocIndexOf;\n\treturn _assocIndexOf;\n}\n\nvar _listCacheDelete;\nvar hasRequired_listCacheDelete;\n\nfunction require_listCacheDelete () {\n\tif (hasRequired_listCacheDelete) return _listCacheDelete;\n\thasRequired_listCacheDelete = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/** Used for built-in method references. */\n\tvar arrayProto = Array.prototype;\n\n\t/** Built-in value references. */\n\tvar splice = arrayProto.splice;\n\n\t/**\n\t * Removes `key` and its value from the list cache.\n\t *\n\t * @private\n\t * @name delete\n\t * @memberOf ListCache\n\t * @param {string} key The key of the value to remove.\n\t * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n\t */\n\tfunction listCacheDelete(key) {\n\t  var data = this.__data__,\n\t      index = assocIndexOf(data, key);\n\n\t  if (index < 0) {\n\t    return false;\n\t  }\n\t  var lastIndex = data.length - 1;\n\t  if (index == lastIndex) {\n\t    data.pop();\n\t  } else {\n\t    splice.call(data, index, 1);\n\t  }\n\t  --this.size;\n\t  return true;\n\t}\n\n\t_listCacheDelete = listCacheDelete;\n\treturn _listCacheDelete;\n}\n\nvar _listCacheGet;\nvar hasRequired_listCacheGet;\n\nfunction require_listCacheGet () {\n\tif (hasRequired_listCacheGet) return _listCacheGet;\n\thasRequired_listCacheGet = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/**\n\t * Gets the list cache value for `key`.\n\t *\n\t * @private\n\t * @name get\n\t * @memberOf ListCache\n\t * @param {string} key The key of the value to get.\n\t * @returns {*} Returns the entry value.\n\t */\n\tfunction listCacheGet(key) {\n\t  var data = this.__data__,\n\t      index = assocIndexOf(data, key);\n\n\t  return index < 0 ? undefined : data[index][1];\n\t}\n\n\t_listCacheGet = listCacheGet;\n\treturn _listCacheGet;\n}\n\nvar _listCacheHas;\nvar hasRequired_listCacheHas;\n\nfunction require_listCacheHas () {\n\tif (hasRequired_listCacheHas) return _listCacheHas;\n\thasRequired_listCacheHas = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/**\n\t * Checks if a list cache value for `key` exists.\n\t *\n\t * @private\n\t * @name has\n\t * @memberOf ListCache\n\t * @param {string} key The key of the entry to check.\n\t * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n\t */\n\tfunction listCacheHas(key) {\n\t  return assocIndexOf(this.__data__, key) > -1;\n\t}\n\n\t_listCacheHas = listCacheHas;\n\treturn _listCacheHas;\n}\n\nvar _listCacheSet;\nvar hasRequired_listCacheSet;\n\nfunction require_listCacheSet () {\n\tif (hasRequired_listCacheSet) return _listCacheSet;\n\thasRequired_listCacheSet = 1;\n\tvar assocIndexOf = require_assocIndexOf();\n\n\t/**\n\t * Sets the list cache `key` to `value`.\n\t *\n\t * @private\n\t * @name set\n\t * @memberOf ListCache\n\t * @param {string} key The key of the value to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns the list cache instance.\n\t */\n\tfunction listCacheSet(key, value) {\n\t  var data = this.__data__,\n\t      index = assocIndexOf(data, key);\n\n\t  if (index < 0) {\n\t    ++this.size;\n\t    data.push([key, value]);\n\t  } else {\n\t    data[index][1] = value;\n\t  }\n\t  return this;\n\t}\n\n\t_listCacheSet = listCacheSet;\n\treturn _listCacheSet;\n}\n\nvar _ListCache;\nvar hasRequired_ListCache;\n\nfunction require_ListCache () {\n\tif (hasRequired_ListCache) return _ListCache;\n\thasRequired_ListCache = 1;\n\tvar listCacheClear = require_listCacheClear(),\n\t    listCacheDelete = require_listCacheDelete(),\n\t    listCacheGet = require_listCacheGet(),\n\t    listCacheHas = require_listCacheHas(),\n\t    listCacheSet = require_listCacheSet();\n\n\t/**\n\t * Creates an list cache object.\n\t *\n\t * @private\n\t * @constructor\n\t * @param {Array} [entries] The key-value pairs to cache.\n\t */\n\tfunction ListCache(entries) {\n\t  var index = -1,\n\t      length = entries == null ? 0 : entries.length;\n\n\t  this.clear();\n\t  while (++index < length) {\n\t    var entry = entries[index];\n\t    this.set(entry[0], entry[1]);\n\t  }\n\t}\n\n\t// Add methods to `ListCache`.\n\tListCache.prototype.clear = listCacheClear;\n\tListCache.prototype['delete'] = listCacheDelete;\n\tListCache.prototype.get = listCacheGet;\n\tListCache.prototype.has = listCacheHas;\n\tListCache.prototype.set = listCacheSet;\n\n\t_ListCache = ListCache;\n\treturn _ListCache;\n}\n\nvar _Map;\nvar hasRequired_Map;\n\nfunction require_Map () {\n\tif (hasRequired_Map) return _Map;\n\thasRequired_Map = 1;\n\tvar getNative = require_getNative(),\n\t    root = require_root();\n\n\t/* Built-in method references that are verified to be native. */\n\tvar Map = getNative(root, 'Map');\n\n\t_Map = Map;\n\treturn _Map;\n}\n\nvar _mapCacheClear;\nvar hasRequired_mapCacheClear;\n\nfunction require_mapCacheClear () {\n\tif (hasRequired_mapCacheClear) return _mapCacheClear;\n\thasRequired_mapCacheClear = 1;\n\tvar Hash = require_Hash(),\n\t    ListCache = require_ListCache(),\n\t    Map = require_Map();\n\n\t/**\n\t * Removes all key-value entries from the map.\n\t *\n\t * @private\n\t * @name clear\n\t * @memberOf MapCache\n\t */\n\tfunction mapCacheClear() {\n\t  this.size = 0;\n\t  this.__data__ = {\n\t    'hash': new Hash,\n\t    'map': new (Map || ListCache),\n\t    'string': new Hash\n\t  };\n\t}\n\n\t_mapCacheClear = mapCacheClear;\n\treturn _mapCacheClear;\n}\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\nvar _isKeyable;\nvar hasRequired_isKeyable;\n\nfunction require_isKeyable () {\n\tif (hasRequired_isKeyable) return _isKeyable;\n\thasRequired_isKeyable = 1;\n\tfunction isKeyable(value) {\n\t  var type = typeof value;\n\t  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n\t    ? (value !== '__proto__')\n\t    : (value === null);\n\t}\n\n\t_isKeyable = isKeyable;\n\treturn _isKeyable;\n}\n\nvar _getMapData;\nvar hasRequired_getMapData;\n\nfunction require_getMapData () {\n\tif (hasRequired_getMapData) return _getMapData;\n\thasRequired_getMapData = 1;\n\tvar isKeyable = require_isKeyable();\n\n\t/**\n\t * Gets the data for `map`.\n\t *\n\t * @private\n\t * @param {Object} map The map to query.\n\t * @param {string} key The reference key.\n\t * @returns {*} Returns the map data.\n\t */\n\tfunction getMapData(map, key) {\n\t  var data = map.__data__;\n\t  return isKeyable(key)\n\t    ? data[typeof key == 'string' ? 'string' : 'hash']\n\t    : data.map;\n\t}\n\n\t_getMapData = getMapData;\n\treturn _getMapData;\n}\n\nvar _mapCacheDelete;\nvar hasRequired_mapCacheDelete;\n\nfunction require_mapCacheDelete () {\n\tif (hasRequired_mapCacheDelete) return _mapCacheDelete;\n\thasRequired_mapCacheDelete = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Removes `key` and its value from the map.\n\t *\n\t * @private\n\t * @name delete\n\t * @memberOf MapCache\n\t * @param {string} key The key of the value to remove.\n\t * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n\t */\n\tfunction mapCacheDelete(key) {\n\t  var result = getMapData(this, key)['delete'](key);\n\t  this.size -= result ? 1 : 0;\n\t  return result;\n\t}\n\n\t_mapCacheDelete = mapCacheDelete;\n\treturn _mapCacheDelete;\n}\n\nvar _mapCacheGet;\nvar hasRequired_mapCacheGet;\n\nfunction require_mapCacheGet () {\n\tif (hasRequired_mapCacheGet) return _mapCacheGet;\n\thasRequired_mapCacheGet = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Gets the map value for `key`.\n\t *\n\t * @private\n\t * @name get\n\t * @memberOf MapCache\n\t * @param {string} key The key of the value to get.\n\t * @returns {*} Returns the entry value.\n\t */\n\tfunction mapCacheGet(key) {\n\t  return getMapData(this, key).get(key);\n\t}\n\n\t_mapCacheGet = mapCacheGet;\n\treturn _mapCacheGet;\n}\n\nvar _mapCacheHas;\nvar hasRequired_mapCacheHas;\n\nfunction require_mapCacheHas () {\n\tif (hasRequired_mapCacheHas) return _mapCacheHas;\n\thasRequired_mapCacheHas = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Checks if a map value for `key` exists.\n\t *\n\t * @private\n\t * @name has\n\t * @memberOf MapCache\n\t * @param {string} key The key of the entry to check.\n\t * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n\t */\n\tfunction mapCacheHas(key) {\n\t  return getMapData(this, key).has(key);\n\t}\n\n\t_mapCacheHas = mapCacheHas;\n\treturn _mapCacheHas;\n}\n\nvar _mapCacheSet;\nvar hasRequired_mapCacheSet;\n\nfunction require_mapCacheSet () {\n\tif (hasRequired_mapCacheSet) return _mapCacheSet;\n\thasRequired_mapCacheSet = 1;\n\tvar getMapData = require_getMapData();\n\n\t/**\n\t * Sets the map `key` to `value`.\n\t *\n\t * @private\n\t * @name set\n\t * @memberOf MapCache\n\t * @param {string} key The key of the value to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns the map cache instance.\n\t */\n\tfunction mapCacheSet(key, value) {\n\t  var data = getMapData(this, key),\n\t      size = data.size;\n\n\t  data.set(key, value);\n\t  this.size += data.size == size ? 0 : 1;\n\t  return this;\n\t}\n\n\t_mapCacheSet = mapCacheSet;\n\treturn _mapCacheSet;\n}\n\nvar _MapCache;\nvar hasRequired_MapCache;\n\nfunction require_MapCache () {\n\tif (hasRequired_MapCache) return _MapCache;\n\thasRequired_MapCache = 1;\n\tvar mapCacheClear = require_mapCacheClear(),\n\t    mapCacheDelete = require_mapCacheDelete(),\n\t    mapCacheGet = require_mapCacheGet(),\n\t    mapCacheHas = require_mapCacheHas(),\n\t    mapCacheSet = require_mapCacheSet();\n\n\t/**\n\t * Creates a map cache object to store key-value pairs.\n\t *\n\t * @private\n\t * @constructor\n\t * @param {Array} [entries] The key-value pairs to cache.\n\t */\n\tfunction MapCache(entries) {\n\t  var index = -1,\n\t      length = entries == null ? 0 : entries.length;\n\n\t  this.clear();\n\t  while (++index < length) {\n\t    var entry = entries[index];\n\t    this.set(entry[0], entry[1]);\n\t  }\n\t}\n\n\t// Add methods to `MapCache`.\n\tMapCache.prototype.clear = mapCacheClear;\n\tMapCache.prototype['delete'] = mapCacheDelete;\n\tMapCache.prototype.get = mapCacheGet;\n\tMapCache.prototype.has = mapCacheHas;\n\tMapCache.prototype.set = mapCacheSet;\n\n\t_MapCache = MapCache;\n\treturn _MapCache;\n}\n\nvar memoize_1;\nvar hasRequiredMemoize;\n\nfunction requireMemoize () {\n\tif (hasRequiredMemoize) return memoize_1;\n\thasRequiredMemoize = 1;\n\tvar MapCache = require_MapCache();\n\n\t/** Error message constants. */\n\tvar FUNC_ERROR_TEXT = 'Expected a function';\n\n\t/**\n\t * Creates a function that memoizes the result of `func`. If `resolver` is\n\t * provided, it determines the cache key for storing the result based on the\n\t * arguments provided to the memoized function. By default, the first argument\n\t * provided to the memoized function is used as the map cache key. The `func`\n\t * is invoked with the `this` binding of the memoized function.\n\t *\n\t * **Note:** The cache is exposed as the `cache` property on the memoized\n\t * function. Its creation may be customized by replacing the `_.memoize.Cache`\n\t * constructor with one whose instances implement the\n\t * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n\t * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 0.1.0\n\t * @category Function\n\t * @param {Function} func The function to have its output memoized.\n\t * @param {Function} [resolver] The function to resolve the cache key.\n\t * @returns {Function} Returns the new memoized function.\n\t * @example\n\t *\n\t * var object = { 'a': 1, 'b': 2 };\n\t * var other = { 'c': 3, 'd': 4 };\n\t *\n\t * var values = _.memoize(_.values);\n\t * values(object);\n\t * // => [1, 2]\n\t *\n\t * values(other);\n\t * // => [3, 4]\n\t *\n\t * object.a = 2;\n\t * values(object);\n\t * // => [1, 2]\n\t *\n\t * // Modify the result cache.\n\t * values.cache.set(object, ['a', 'b']);\n\t * values(object);\n\t * // => ['a', 'b']\n\t *\n\t * // Replace `_.memoize.Cache`.\n\t * _.memoize.Cache = WeakMap;\n\t */\n\tfunction memoize(func, resolver) {\n\t  if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n\t    throw new TypeError(FUNC_ERROR_TEXT);\n\t  }\n\t  var memoized = function() {\n\t    var args = arguments,\n\t        key = resolver ? resolver.apply(this, args) : args[0],\n\t        cache = memoized.cache;\n\n\t    if (cache.has(key)) {\n\t      return cache.get(key);\n\t    }\n\t    var result = func.apply(this, args);\n\t    memoized.cache = cache.set(key, result) || cache;\n\t    return result;\n\t  };\n\t  memoized.cache = new (memoize.Cache || MapCache);\n\t  return memoized;\n\t}\n\n\t// Expose `MapCache`.\n\tmemoize.Cache = MapCache;\n\n\tmemoize_1 = memoize;\n\treturn memoize_1;\n}\n\nvar _memoizeCapped;\nvar hasRequired_memoizeCapped;\n\nfunction require_memoizeCapped () {\n\tif (hasRequired_memoizeCapped) return _memoizeCapped;\n\thasRequired_memoizeCapped = 1;\n\tvar memoize = requireMemoize();\n\n\t/** Used as the maximum memoize cache size. */\n\tvar MAX_MEMOIZE_SIZE = 500;\n\n\t/**\n\t * A specialized version of `_.memoize` which clears the memoized function's\n\t * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n\t *\n\t * @private\n\t * @param {Function} func The function to have its output memoized.\n\t * @returns {Function} Returns the new memoized function.\n\t */\n\tfunction memoizeCapped(func) {\n\t  var result = memoize(func, function(key) {\n\t    if (cache.size === MAX_MEMOIZE_SIZE) {\n\t      cache.clear();\n\t    }\n\t    return key;\n\t  });\n\n\t  var cache = result.cache;\n\t  return result;\n\t}\n\n\t_memoizeCapped = memoizeCapped;\n\treturn _memoizeCapped;\n}\n\nvar _stringToPath;\nvar hasRequired_stringToPath;\n\nfunction require_stringToPath () {\n\tif (hasRequired_stringToPath) return _stringToPath;\n\thasRequired_stringToPath = 1;\n\tvar memoizeCapped = require_memoizeCapped();\n\n\t/** Used to match property names within property paths. */\n\tvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n\t/** Used to match backslashes in property paths. */\n\tvar reEscapeChar = /\\\\(\\\\)?/g;\n\n\t/**\n\t * Converts `string` to a property path array.\n\t *\n\t * @private\n\t * @param {string} string The string to convert.\n\t * @returns {Array} Returns the property path array.\n\t */\n\tvar stringToPath = memoizeCapped(function(string) {\n\t  var result = [];\n\t  if (string.charCodeAt(0) === 46 /* . */) {\n\t    result.push('');\n\t  }\n\t  string.replace(rePropName, function(match, number, quote, subString) {\n\t    result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n\t  });\n\t  return result;\n\t});\n\n\t_stringToPath = stringToPath;\n\treturn _stringToPath;\n}\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\nvar _arrayMap;\nvar hasRequired_arrayMap;\n\nfunction require_arrayMap () {\n\tif (hasRequired_arrayMap) return _arrayMap;\n\thasRequired_arrayMap = 1;\n\tfunction arrayMap(array, iteratee) {\n\t  var index = -1,\n\t      length = array == null ? 0 : array.length,\n\t      result = Array(length);\n\n\t  while (++index < length) {\n\t    result[index] = iteratee(array[index], index, array);\n\t  }\n\t  return result;\n\t}\n\n\t_arrayMap = arrayMap;\n\treturn _arrayMap;\n}\n\nvar _baseToString;\nvar hasRequired_baseToString;\n\nfunction require_baseToString () {\n\tif (hasRequired_baseToString) return _baseToString;\n\thasRequired_baseToString = 1;\n\tvar Symbol = require_Symbol(),\n\t    arrayMap = require_arrayMap(),\n\t    isArray = requireIsArray(),\n\t    isSymbol = requireIsSymbol();\n\n\t/** Used to convert symbols to primitives and strings. */\n\tvar symbolProto = Symbol ? Symbol.prototype : undefined,\n\t    symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n\t/**\n\t * The base implementation of `_.toString` which doesn't convert nullish\n\t * values to empty strings.\n\t *\n\t * @private\n\t * @param {*} value The value to process.\n\t * @returns {string} Returns the string.\n\t */\n\tfunction baseToString(value) {\n\t  // Exit early for strings to avoid a performance hit in some environments.\n\t  if (typeof value == 'string') {\n\t    return value;\n\t  }\n\t  if (isArray(value)) {\n\t    // Recursively convert values (susceptible to call stack limits).\n\t    return arrayMap(value, baseToString) + '';\n\t  }\n\t  if (isSymbol(value)) {\n\t    return symbolToString ? symbolToString.call(value) : '';\n\t  }\n\t  var result = (value + '');\n\t  return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;\n\t}\n\n\t_baseToString = baseToString;\n\treturn _baseToString;\n}\n\nvar toString_1;\nvar hasRequiredToString;\n\nfunction requireToString () {\n\tif (hasRequiredToString) return toString_1;\n\thasRequiredToString = 1;\n\tvar baseToString = require_baseToString();\n\n\t/**\n\t * Converts `value` to a string. An empty string is returned for `null`\n\t * and `undefined` values. The sign of `-0` is preserved.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Lang\n\t * @param {*} value The value to convert.\n\t * @returns {string} Returns the converted string.\n\t * @example\n\t *\n\t * _.toString(null);\n\t * // => ''\n\t *\n\t * _.toString(-0);\n\t * // => '-0'\n\t *\n\t * _.toString([1, 2, 3]);\n\t * // => '1,2,3'\n\t */\n\tfunction toString(value) {\n\t  return value == null ? '' : baseToString(value);\n\t}\n\n\ttoString_1 = toString;\n\treturn toString_1;\n}\n\nvar _castPath;\nvar hasRequired_castPath;\n\nfunction require_castPath () {\n\tif (hasRequired_castPath) return _castPath;\n\thasRequired_castPath = 1;\n\tvar isArray = requireIsArray(),\n\t    isKey = require_isKey(),\n\t    stringToPath = require_stringToPath(),\n\t    toString = requireToString();\n\n\t/**\n\t * Casts `value` to a path array if it's not one.\n\t *\n\t * @private\n\t * @param {*} value The value to inspect.\n\t * @param {Object} [object] The object to query keys on.\n\t * @returns {Array} Returns the cast property path array.\n\t */\n\tfunction castPath(value, object) {\n\t  if (isArray(value)) {\n\t    return value;\n\t  }\n\t  return isKey(value, object) ? [value] : stringToPath(toString(value));\n\t}\n\n\t_castPath = castPath;\n\treturn _castPath;\n}\n\nvar _toKey;\nvar hasRequired_toKey;\n\nfunction require_toKey () {\n\tif (hasRequired_toKey) return _toKey;\n\thasRequired_toKey = 1;\n\tvar isSymbol = requireIsSymbol();\n\n\t/**\n\t * Converts `value` to a string key if it's not a string or symbol.\n\t *\n\t * @private\n\t * @param {*} value The value to inspect.\n\t * @returns {string|symbol} Returns the key.\n\t */\n\tfunction toKey(value) {\n\t  if (typeof value == 'string' || isSymbol(value)) {\n\t    return value;\n\t  }\n\t  var result = (value + '');\n\t  return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;\n\t}\n\n\t_toKey = toKey;\n\treturn _toKey;\n}\n\nvar _baseGet;\nvar hasRequired_baseGet;\n\nfunction require_baseGet () {\n\tif (hasRequired_baseGet) return _baseGet;\n\thasRequired_baseGet = 1;\n\tvar castPath = require_castPath(),\n\t    toKey = require_toKey();\n\n\t/**\n\t * The base implementation of `_.get` without support for default values.\n\t *\n\t * @private\n\t * @param {Object} object The object to query.\n\t * @param {Array|string} path The path of the property to get.\n\t * @returns {*} Returns the resolved value.\n\t */\n\tfunction baseGet(object, path) {\n\t  path = castPath(path, object);\n\n\t  var index = 0,\n\t      length = path.length;\n\n\t  while (object != null && index < length) {\n\t    object = object[toKey(path[index++])];\n\t  }\n\t  return (index && index == length) ? object : undefined;\n\t}\n\n\t_baseGet = baseGet;\n\treturn _baseGet;\n}\n\nvar get_1;\nvar hasRequiredGet;\n\nfunction requireGet () {\n\tif (hasRequiredGet) return get_1;\n\thasRequiredGet = 1;\n\tvar baseGet = require_baseGet();\n\n\t/**\n\t * Gets the value at `path` of `object`. If the resolved value is\n\t * `undefined`, the `defaultValue` is returned in its place.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 3.7.0\n\t * @category Object\n\t * @param {Object} object The object to query.\n\t * @param {Array|string} path The path of the property to get.\n\t * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n\t * @returns {*} Returns the resolved value.\n\t * @example\n\t *\n\t * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n\t *\n\t * _.get(object, 'a[0].b.c');\n\t * // => 3\n\t *\n\t * _.get(object, ['a', '0', 'b', 'c']);\n\t * // => 3\n\t *\n\t * _.get(object, 'a.b.c', 'default');\n\t * // => 'default'\n\t */\n\tfunction get(object, path, defaultValue) {\n\t  var result = object == null ? undefined : baseGet(object, path);\n\t  return result === undefined ? defaultValue : result;\n\t}\n\n\tget_1 = get;\n\treturn get_1;\n}\n\nvar getExports = requireGet();\nvar get = /*@__PURE__*/getDefaultExportFromCjs(getExports);\n\nvar _defineProperty;\nvar hasRequired_defineProperty;\n\nfunction require_defineProperty () {\n\tif (hasRequired_defineProperty) return _defineProperty;\n\thasRequired_defineProperty = 1;\n\tvar getNative = require_getNative();\n\n\tvar defineProperty = (function() {\n\t  try {\n\t    var func = getNative(Object, 'defineProperty');\n\t    func({}, '', {});\n\t    return func;\n\t  } catch (e) {}\n\t}());\n\n\t_defineProperty = defineProperty;\n\treturn _defineProperty;\n}\n\nvar _baseAssignValue;\nvar hasRequired_baseAssignValue;\n\nfunction require_baseAssignValue () {\n\tif (hasRequired_baseAssignValue) return _baseAssignValue;\n\thasRequired_baseAssignValue = 1;\n\tvar defineProperty = require_defineProperty();\n\n\t/**\n\t * The base implementation of `assignValue` and `assignMergeValue` without\n\t * value checks.\n\t *\n\t * @private\n\t * @param {Object} object The object to modify.\n\t * @param {string} key The key of the property to assign.\n\t * @param {*} value The value to assign.\n\t */\n\tfunction baseAssignValue(object, key, value) {\n\t  if (key == '__proto__' && defineProperty) {\n\t    defineProperty(object, key, {\n\t      'configurable': true,\n\t      'enumerable': true,\n\t      'value': value,\n\t      'writable': true\n\t    });\n\t  } else {\n\t    object[key] = value;\n\t  }\n\t}\n\n\t_baseAssignValue = baseAssignValue;\n\treturn _baseAssignValue;\n}\n\nvar _assignValue;\nvar hasRequired_assignValue;\n\nfunction require_assignValue () {\n\tif (hasRequired_assignValue) return _assignValue;\n\thasRequired_assignValue = 1;\n\tvar baseAssignValue = require_baseAssignValue(),\n\t    eq = requireEq();\n\n\t/** Used for built-in method references. */\n\tvar objectProto = Object.prototype;\n\n\t/** Used to check objects for own properties. */\n\tvar hasOwnProperty = objectProto.hasOwnProperty;\n\n\t/**\n\t * Assigns `value` to `key` of `object` if the existing value is not equivalent\n\t * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n\t * for equality comparisons.\n\t *\n\t * @private\n\t * @param {Object} object The object to modify.\n\t * @param {string} key The key of the property to assign.\n\t * @param {*} value The value to assign.\n\t */\n\tfunction assignValue(object, key, value) {\n\t  var objValue = object[key];\n\t  if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n\t      (value === undefined && !(key in object))) {\n\t    baseAssignValue(object, key, value);\n\t  }\n\t}\n\n\t_assignValue = assignValue;\n\treturn _assignValue;\n}\n\n/** Used as references for various `Number` constants. */\n\nvar _isIndex;\nvar hasRequired_isIndex;\n\nfunction require_isIndex () {\n\tif (hasRequired_isIndex) return _isIndex;\n\thasRequired_isIndex = 1;\n\tvar MAX_SAFE_INTEGER = 9007199254740991;\n\n\t/** Used to detect unsigned integer values. */\n\tvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n\t/**\n\t * Checks if `value` is a valid array-like index.\n\t *\n\t * @private\n\t * @param {*} value The value to check.\n\t * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n\t * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n\t */\n\tfunction isIndex(value, length) {\n\t  var type = typeof value;\n\t  length = length == null ? MAX_SAFE_INTEGER : length;\n\n\t  return !!length &&\n\t    (type == 'number' ||\n\t      (type != 'symbol' && reIsUint.test(value))) &&\n\t        (value > -1 && value % 1 == 0 && value < length);\n\t}\n\n\t_isIndex = isIndex;\n\treturn _isIndex;\n}\n\nvar _baseSet;\nvar hasRequired_baseSet;\n\nfunction require_baseSet () {\n\tif (hasRequired_baseSet) return _baseSet;\n\thasRequired_baseSet = 1;\n\tvar assignValue = require_assignValue(),\n\t    castPath = require_castPath(),\n\t    isIndex = require_isIndex(),\n\t    isObject = requireIsObject(),\n\t    toKey = require_toKey();\n\n\t/**\n\t * The base implementation of `_.set`.\n\t *\n\t * @private\n\t * @param {Object} object The object to modify.\n\t * @param {Array|string} path The path of the property to set.\n\t * @param {*} value The value to set.\n\t * @param {Function} [customizer] The function to customize path creation.\n\t * @returns {Object} Returns `object`.\n\t */\n\tfunction baseSet(object, path, value, customizer) {\n\t  if (!isObject(object)) {\n\t    return object;\n\t  }\n\t  path = castPath(path, object);\n\n\t  var index = -1,\n\t      length = path.length,\n\t      lastIndex = length - 1,\n\t      nested = object;\n\n\t  while (nested != null && ++index < length) {\n\t    var key = toKey(path[index]),\n\t        newValue = value;\n\n\t    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n\t      return object;\n\t    }\n\n\t    if (index != lastIndex) {\n\t      var objValue = nested[key];\n\t      newValue = customizer ? customizer(objValue, key, nested) : undefined;\n\t      if (newValue === undefined) {\n\t        newValue = isObject(objValue)\n\t          ? objValue\n\t          : (isIndex(path[index + 1]) ? [] : {});\n\t      }\n\t    }\n\t    assignValue(nested, key, newValue);\n\t    nested = nested[key];\n\t  }\n\t  return object;\n\t}\n\n\t_baseSet = baseSet;\n\treturn _baseSet;\n}\n\nvar set_1;\nvar hasRequiredSet;\n\nfunction requireSet () {\n\tif (hasRequiredSet) return set_1;\n\thasRequiredSet = 1;\n\tvar baseSet = require_baseSet();\n\n\t/**\n\t * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n\t * it's created. Arrays are created for missing index properties while objects\n\t * are created for all other missing properties. Use `_.setWith` to customize\n\t * `path` creation.\n\t *\n\t * **Note:** This method mutates `object`.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 3.7.0\n\t * @category Object\n\t * @param {Object} object The object to modify.\n\t * @param {Array|string} path The path of the property to set.\n\t * @param {*} value The value to set.\n\t * @returns {Object} Returns `object`.\n\t * @example\n\t *\n\t * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n\t *\n\t * _.set(object, 'a[0].b.c', 4);\n\t * console.log(object.a[0].b.c);\n\t * // => 4\n\t *\n\t * _.set(object, ['x', '0', 'y', 'z'], 5);\n\t * console.log(object.x[0].y.z);\n\t * // => 5\n\t */\n\tfunction set(object, path, value) {\n\t  return object == null ? object : baseSet(object, path, value);\n\t}\n\n\tset_1 = set;\n\treturn set_1;\n}\n\nvar setExports = requireSet();\nvar set = /*@__PURE__*/getDefaultExportFromCjs(setExports);\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\nvar _copyArray;\nvar hasRequired_copyArray;\n\nfunction require_copyArray () {\n\tif (hasRequired_copyArray) return _copyArray;\n\thasRequired_copyArray = 1;\n\tfunction copyArray(source, array) {\n\t  var index = -1,\n\t      length = source.length;\n\n\t  array || (array = Array(length));\n\t  while (++index < length) {\n\t    array[index] = source[index];\n\t  }\n\t  return array;\n\t}\n\n\t_copyArray = copyArray;\n\treturn _copyArray;\n}\n\nvar toPath_1;\nvar hasRequiredToPath;\n\nfunction requireToPath () {\n\tif (hasRequiredToPath) return toPath_1;\n\thasRequiredToPath = 1;\n\tvar arrayMap = require_arrayMap(),\n\t    copyArray = require_copyArray(),\n\t    isArray = requireIsArray(),\n\t    isSymbol = requireIsSymbol(),\n\t    stringToPath = require_stringToPath(),\n\t    toKey = require_toKey(),\n\t    toString = requireToString();\n\n\t/**\n\t * Converts `value` to a property path array.\n\t *\n\t * @static\n\t * @memberOf _\n\t * @since 4.0.0\n\t * @category Util\n\t * @param {*} value The value to convert.\n\t * @returns {Array} Returns the new property path array.\n\t * @example\n\t *\n\t * _.toPath('a.b.c');\n\t * // => ['a', 'b', 'c']\n\t *\n\t * _.toPath('a[0].b.c');\n\t * // => ['a', '0', 'b', 'c']\n\t */\n\tfunction toPath(value) {\n\t  if (isArray(value)) {\n\t    return arrayMap(value, toKey);\n\t  }\n\t  return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));\n\t}\n\n\ttoPath_1 = toPath;\n\treturn toPath_1;\n}\n\nvar toPathExports = requireToPath();\nvar toPath = /*@__PURE__*/getDefaultExportFromCjs(toPathExports);\n\nvar 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      var single = selfIsArrayLike ? self[0] : self;\n\n      // .data('foo', ...)\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        var path = isPathLike && toPath(name);\n\n        // .data('foo')\n        if (p.allowGetting && value === undefined) {\n          // get\n\n          var ret;\n          if (single) {\n            p.beforeGet(single);\n\n            // check if it's path and a field with the same name doesn't exist\n            if (path && single._private[p.field][name] === undefined) {\n              ret = get(single._private[p.field], path);\n            } else {\n              ret = single._private[p.field][name];\n            }\n          }\n          return ret;\n\n          // .data('foo', 'bar')\n        } else if (p.allowSetting && value !== undefined) {\n          // set\n          var valid = !p.immutableKeys[name];\n          if (valid) {\n            var change = _defineProperty$1({}, name, value);\n            p.beforeSet(self, change);\n            for (var i = 0, l = all.length; i < l; i++) {\n              var ele = all[i];\n              if (p.canSet(ele)) {\n                if (path && single._private[p.field][name] === undefined) {\n                  set(ele._private[p.field], path, value);\n                } else {\n                  ele._private[p.field][name] = value;\n                }\n              }\n            }\n\n            // update mappers if asked\n            if (p.updateStyle) {\n              self.updateStyle();\n            }\n\n            // call onSet callback\n            p.onSet(self);\n            if (p.settingTriggersEvent) {\n              self[p.triggerFnName](p.settingEvent);\n            }\n          }\n        }\n\n        // .data({ 'foo': 'bar' })\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        for (var _i = 0; _i < keys.length; _i++) {\n          k = keys[_i];\n          v = obj[k];\n          var _valid = !p.immutableKeys[k];\n          if (_valid) {\n            for (var j = 0; j < all.length; j++) {\n              var _ele = all[j];\n              if (p.canSet(_ele)) {\n                _ele._private[p.field][k] = v;\n              }\n            }\n          }\n        }\n\n        // update mappers if asked\n        if (p.updateStyle) {\n          self.updateStyle();\n        }\n\n        // call onSet callback\n        p.onSet(self);\n        if (p.settingTriggersEvent) {\n          self[p.triggerFnName](p.settingEvent);\n        }\n\n        // .data(function(){ ... })\n      } else if (p.allowBinding && fn$6(name)) {\n        // bind to event\n        var fn = name;\n        self.on(p.bindingEvent, fn);\n\n        // .data()\n      } else if (p.allowGetting && name === undefined) {\n        // get whole object\n        var _ret;\n        if (single) {\n          p.beforeGet(single);\n          _ret = single._private[p.field];\n        }\n        return _ret;\n      }\n      return self; // maintain chainability\n    }; // function\n  },\n  // data\n\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    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\n      // .removeData('foo bar')\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        for (var i = 0; i < l; i++) {\n          // delete each non-empty key\n          var key = keys[i];\n          if (emptyString(key)) {\n            continue;\n          }\n          var valid = !p.immutableKeys[key]; // not valid if immutable\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        if (p.triggerEvent) {\n          self[p.triggerFnName](p.event);\n        }\n\n        // .removeData()\n      } else if (names === undefined) {\n        // then delete all keys\n\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          var _keys = Object.keys(_privateFields);\n          for (var _i2 = 0; _i2 < _keys.length; _i2++) {\n            var _key = _keys[_i2];\n            var validKeyToDelete = !p.immutableKeys[_key];\n            if (validKeyToDelete) {\n              _privateFields[_key] = undefined;\n            }\n          }\n        }\n        if (p.triggerEvent) {\n          self[p.triggerFnName](p.event);\n        }\n      }\n      return self; // maintain chaining\n    }; // function\n  } // removeData\n}; // define\n\nvar 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;\n\n    // this is just a wrapper alias of .on()\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        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// (useful for functions shared between the core and collections, for example)\n\nvar define = {};\n[define$3, define$2, define$1].forEach(function (m) {\n  extend(define, m);\n});\n\nvar 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\nvar elesfn$h = {\n  classes: function classes(_classes) {\n    var self = this;\n    if (_classes === undefined) {\n      var ret = [];\n      self[0]._private.classes.forEach(function (cls) {\n        return ret.push(cls);\n      });\n      return ret;\n    } else if (!array(_classes)) {\n      // extract classes from string\n      _classes = (_classes || '').match(/\\S+/g) || [];\n    }\n    var changed = [];\n    var classesSet = new Set$1(_classes);\n\n    // check and update each ele\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;\n\n      // check if ele has all of the passed classes\n      for (var i = 0; i < _classes.length; i++) {\n        var cls = _classes[i];\n        var eleHasClass = eleClasses.has(cls);\n        if (!eleHasClass) {\n          changedEle = true;\n          break;\n        }\n      }\n\n      // check if ele has classes outside of those passed\n      if (!changedEle) {\n        changedEle = eleClasses.size !== _classes.length;\n      }\n      if (changedEle) {\n        _p.classes = classesSet;\n        changed.push(ele);\n      }\n    }\n\n    // trigger update style on those eles that had class changes\n    if (changed.length > 0) {\n      this.spawn(changed).updateStyle().emit('class');\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    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      for (var j = 0; j < classes.length; j++) {\n        var cls = classes[j];\n        var hasClass = eleClasses.has(cls);\n        var changedNow = false;\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        if (!changedEle && changedNow) {\n          changed.push(ele);\n          changedEle = true;\n        }\n      } // for j classes\n    } // for i eles\n\n    // trigger update style on those eles that had class changes\n    if (changed.length > 0) {\n      this.spawn(changed).updateStyle().emit('class');\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    if (duration == null) {\n      duration = 250;\n    } else if (duration === 0) {\n      return self; // nothing to do really\n    }\n    self.addClass(classes);\n    setTimeout(function () {\n      self.removeClass(classes);\n    }, duration);\n    return self;\n  }\n};\nelesfn$h.className = elesfn$h.classNames = elesfn$h.classes;\n\n// tokens in the query language\nvar 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};\ntokens.variable = '(?:[\\\\w-.]|(?:\\\\\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods\ntokens.className = '(?:[\\\\w-]|(?:\\\\\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name\ntokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number\ntokens.id = tokens.variable; // an element id (follows variable conventions)\n\n(function () {\n  var ops, op, i;\n\n  // add @ variants to comparatorOp\n  ops = tokens.comparatorOp.split('|');\n  for (i = 0; i < ops.length; i++) {\n    op = ops[i];\n    tokens.comparatorOp += '|@' + op;\n  }\n\n  // add ! variants to comparatorOp\n  ops = tokens.comparatorOp.split('|');\n  for (i = 0; i < ops.length; i++) {\n    op = ops[i];\n    if (op.indexOf('!') >= 0) {\n      continue;\n    } // skip ops that explicitly contain !\n    if (op === '=') {\n      continue;\n    } // skip = b/c != is explicitly defined\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 */\nvar 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 */\nvar Type = {\n  /** E.g. node */\n  GROUP: 0,\n  /** A collection of elements */\n  COLLECTION: 1,\n  /** A filter(ele) function */\n  FILTER: 2,\n  /** E.g. [foo > 1] */\n  DATA_COMPARE: 3,\n  /** E.g. [foo] */\n  DATA_EXIST: 4,\n  /** E.g. [?foo] */\n  DATA_BOOL: 5,\n  /** E.g. [[degree > 2]] */\n  META_COMPARE: 6,\n  /** E.g. :selected */\n  STATE: 7,\n  /** E.g. #foo */\n  ID: 8,\n  /** E.g. .foo */\n  CLASS: 9,\n  /** E.g. #foo <-> #bar */\n  UNDIRECTED_EDGE: 10,\n  /** E.g. #foo -> #bar */\n  DIRECTED_EDGE: 11,\n  /** E.g. $#foo -> #bar */\n  NODE_SOURCE: 12,\n  /** E.g. #foo -> $#bar */\n  NODE_TARGET: 13,\n  /** E.g. $#foo <-> #bar */\n  NODE_NEIGHBOR: 14,\n  /** E.g. #foo > #bar */\n  CHILD: 15,\n  /** E.g. #foo #bar */\n  DESCENDANT: 16,\n  /** E.g. $#foo > #bar */\n  PARENT: 17,\n  /** E.g. $#foo #bar */\n  ANCESTOR: 18,\n  /** E.g. #foo > $bar > #baz */\n  COMPOUND_SPLIT: 19,\n  /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */\n  TRUE: 20\n};\n\nvar 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});\nvar lookup = function () {\n  var selToFn = {};\n  var s;\n  for (var i = 0; i < stateSelectors.length; i++) {\n    s = stateSelectors[i];\n    selToFn[s.selector] = s.matches;\n  }\n  return selToFn;\n}();\nvar stateSelectorMatches = function stateSelectorMatches(sel, ele) {\n  return lookup[sel](ele);\n};\nvar stateSelectorRegex = '(' + stateSelectors.map(function (s) {\n  return s.selector;\n}).join('|') + ')';\n\n// when a token like a variable has escaped meta characters, we need to clean the backslashes out\n// so that values get compared properly in Selector.filter()\nvar cleanMetaChars = function cleanMetaChars(str) {\n  return str.replace(new RegExp('\\\\\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {\n    return $1;\n  });\n};\nvar replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {\n  selector[selector.length - 1] = replacementQuery;\n};\n\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\nvar 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    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    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    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    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    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    var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;\n    if (valueIsString) {\n      value = value.substring(1, value.length - 1);\n    } else {\n      value = parseFloat(value);\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    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    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    if (currentSubject != null) {\n      lastQ.subject = currentSubject;\n      selector.currentSubject = null;\n    }\n    lastQ.edgeCount = edgeCount;\n    lastQ.compoundCount = compoundCount;\n    selector.edgeCount = 0;\n    selector.compoundCount = 0;\n\n    // go on to next query\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      });\n\n      // the query in the selector should be the edge rather than the source\n      replaceLastQuery(selector, query, edgeQuery);\n      selector.edgeCount++;\n\n      // we're now populating the target query with expressions that follow\n      return target;\n    } else {\n      // source/target\n      var srcTgtQ = newQuery();\n      var _source = query;\n      var _target = newQuery();\n      srcTgtQ.checks.push({\n        type: Type.NODE_SOURCE,\n        source: _source,\n        target: _target\n      });\n\n      // the query in the selector should be the neighbourhood rather than the node\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      });\n\n      // the query in the selector should be the edge rather than the source\n      replaceLastQuery(selector, query, edgeQuery);\n      selector.edgeCount++;\n\n      // we're now populating the target query with expressions that follow\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      });\n\n      // the query in the selector should be the neighbourhood rather than the node\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      });\n\n      // the query in the selector should be the '>' itself\n      replaceLastQuery(selector, query, parentChildQuery);\n      selector.compoundCount++;\n\n      // we're now populating the child query with expressions that follow\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      var _child = newQuery();\n      var _parent = newQuery();\n\n      // set up the root compound q\n      compound.checks.push({\n        type: Type.COMPOUND_SPLIT,\n        left: left,\n        right: right,\n        subject: subject\n      });\n\n      // populate the subject and replace the q at the old spot (within left) with TRUE\n      subject.checks = query.checks; // take the checks from the left\n      query.checks = [{\n        type: Type.TRUE\n      }]; // checks under left refs the subject implicitly\n\n      // set up the right q\n      _parent.checks.push({\n        type: Type.TRUE\n      }); // parent implicitly refs the subject\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      replaceLastQuery(selector, left, compound);\n\n      // update the ref since we moved things around for `query`\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      var _child2 = newQuery();\n      var pcQChecks = [{\n        type: Type.PARENT,\n        parent: _parent2,\n        child: _child2\n      }];\n\n      // the parent-child query takes the place of the query previously being populated\n      _parent2.checks = query.checks; // the previous query contains the checks for the parent\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      });\n\n      // the query in the selector should be the '>' itself\n      replaceLastQuery(selector, query, ancChQuery);\n      selector.compoundCount++;\n\n      // we're now populating the descendant query with expressions that follow\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      var _descendant = newQuery();\n      var _ancestor = newQuery();\n\n      // set up the root compound q\n      compound.checks.push({\n        type: Type.COMPOUND_SPLIT,\n        left: left,\n        right: right,\n        subject: subject\n      });\n\n      // populate the subject and replace the q at the old spot (within left) with TRUE\n      subject.checks = query.checks; // take the checks from the left\n      query.checks = [{\n        type: Type.TRUE\n      }]; // checks under left refs the subject implicitly\n\n      // set up the right q\n      _ancestor.checks.push({\n        type: Type.TRUE\n      }); // ancestor implicitly refs the subject\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      replaceLastQuery(selector, left, compound);\n\n      // update the ref since we moved things around for `query`\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      var _descendant2 = newQuery();\n      var adQChecks = [{\n        type: Type.ANCESTOR,\n        ancestor: _ancestor2,\n        descendant: _descendant2\n      }];\n\n      // the parent-child query takes the place of the query previously being populated\n      _ancestor2.checks = query.checks; // the previous query contains the checks for the parent\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    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    if (topType === Type.DIRECTED_EDGE) {\n      // directed edge with subject on the target\n\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\n      // change to neighbor check\n      topChk.type = Type.NODE_NEIGHBOR;\n      topChk.node = topChk.nodes[1]; // second node is subject\n      topChk.neighbor = topChk.nodes[0];\n\n      // clean up unused fields for new type\n      topChk.nodes = null;\n    }\n  }\n}];\nexprs.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 */\nvar consumeExpr = function consumeExpr(remaining) {\n  var expr;\n  var match;\n  var name;\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    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  return {\n    expr: expr,\n    match: match,\n    name: name,\n    remaining: remaining\n  };\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 */\nvar consumeWhitespace = function consumeWhitespace(remaining) {\n  var match = remaining.match(/^\\s+/);\n  if (match) {\n    var consumed = match[0];\n    remaining = remaining.substring(consumed.length);\n  }\n  return remaining;\n};\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 */\nvar 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    if (exprInfo.expr == null) {\n      warn('The selector `' + selector + '`is invalid');\n      return false;\n    } else {\n      var args = exprInfo.match.slice(1);\n\n      // let the token populate the selector object in currentQuery\n      var ret = exprInfo.expr.populate(self, currentQuery, args);\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    remaining = exprInfo.remaining;\n\n    // we're done when there's nothing left to parse\n    if (remaining.match(/^\\s*$/)) {\n      break;\n    }\n  }\n  var lastQ = self[self.length - 1];\n  if (self.currentSubject != null) {\n    lastQ.subject = self.currentSubject;\n  }\n  lastQ.edgeCount = self.edgeCount;\n  lastQ.compoundCount = self.compoundCount;\n  for (var i = 0; i < self.length; i++) {\n    var q = self[i];\n\n    // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations\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    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  return true; // success\n};\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 */\nvar toString = function toString() {\n  if (this.toStringCache != null) {\n    return this.toStringCache;\n  }\n  var clean = function clean(obj) {\n    if (obj == null) {\n      return '';\n    } else {\n      return obj;\n    }\n  };\n  var cleanVal = function cleanVal(val) {\n    if (string(val)) {\n      return '\"' + val + '\"';\n    } else {\n      return clean(val);\n    }\n  };\n  var space = function space(val) {\n    return ' ' + val + ' ';\n  };\n  var checkToString = function checkToString(check, subject) {\n    var type = check.type,\n      value = check.value;\n    switch (type) {\n      case Type.GROUP:\n        {\n          var group = clean(value);\n          return group.substring(0, group.length - 1);\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      case Type.DATA_BOOL:\n        {\n          var _operator = check.operator,\n            _field = check.field;\n          return '[' + clean(_operator) + _field + ']';\n        }\n      case Type.DATA_EXIST:\n        {\n          var _field2 = check.field;\n          return '[' + _field2 + ']';\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      case Type.STATE:\n        {\n          return value;\n        }\n      case Type.ID:\n        {\n          return '#' + value;\n        }\n      case Type.CLASS:\n        {\n          return '.' + value;\n        }\n      case Type.PARENT:\n      case Type.CHILD:\n        {\n          return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);\n        }\n      case Type.ANCESTOR:\n      case Type.DESCENDANT:\n        {\n          return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);\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      case Type.TRUE:\n        {\n          return '';\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  var str = '';\n  for (var i = 0; i < this.length; i++) {\n    var query = this[i];\n    str += queryToString(query, query.subject);\n    if (this.length > 1 && i < this.length - 1) {\n      str += ', ';\n    }\n  }\n  this.toStringCache = str;\n  return str;\n};\nvar parse$1 = {\n  parse: parse,\n  toString: toString\n};\n\nvar 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  if (operator.indexOf('!') >= 0) {\n    operator = operator.replace('!', '');\n    notExpr = true;\n  }\n  if (operator.indexOf('@') >= 0) {\n    operator = operator.replace('@', '');\n    caseInsensitive = true;\n  }\n  if (isFieldStr || isValStr || caseInsensitive) {\n    fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;\n    valStr = '' + value;\n  }\n\n  // if we're doing a case insensitive comparison, then we're using a STRING comparison\n  // even if we're comparing numbers\n  if (caseInsensitive) {\n    fieldVal = fieldStr = fieldStr.toLowerCase();\n    value = valStr = valStr.toLowerCase();\n  }\n  switch (operator) {\n    case '*=':\n      matches = fieldStr.indexOf(valStr) >= 0;\n      break;\n    case '$=':\n      matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;\n      break;\n    case '^=':\n      matches = fieldStr.indexOf(valStr) === 0;\n      break;\n    case '=':\n      matches = fieldVal === value;\n      break;\n    case '>':\n      isIneqCmp = true;\n      matches = fieldVal > value;\n      break;\n    case '>=':\n      isIneqCmp = true;\n      matches = fieldVal >= value;\n      break;\n    case '<':\n      isIneqCmp = true;\n      matches = fieldVal < value;\n      break;\n    case '<=':\n      isIneqCmp = true;\n      matches = fieldVal <= value;\n      break;\n    default:\n      matches = false;\n      break;\n  }\n\n  // apply the not op, but null vals for inequalities should always stay non-matching\n  if (notExpr && (fieldVal != null || !isIneqCmp)) {\n    matches = !matches;\n  }\n  return matches;\n};\nvar boolCmp = function boolCmp(fieldVal, operator) {\n  switch (operator) {\n    case '?':\n      return fieldVal ? true : false;\n    case '!':\n      return fieldVal ? false : true;\n    case '^':\n      return fieldVal === undefined;\n  }\n};\nvar existCmp = function existCmp(fieldVal) {\n  return fieldVal !== undefined;\n};\nvar data$1 = function data(ele, field) {\n  return ele.data(field);\n};\nvar meta = function meta(ele, field) {\n  return ele[field]();\n};\n\n/** A lookup of `match(check, ele)` functions by `Type` int */\nvar match = [];\n\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*/\nvar matches$1 = function matches(query, ele) {\n  return query.checks.every(function (chk) {\n    return match[chk.type](chk, ele);\n  });\n};\nmatch[Type.GROUP] = function (check, ele) {\n  var group = check.value;\n  return group === '*' || group === ele.group();\n};\nmatch[Type.STATE] = function (check, ele) {\n  var stateSelector = check.value;\n  return stateSelectorMatches(stateSelector, ele);\n};\nmatch[Type.ID] = function (check, ele) {\n  var id = check.value;\n  return ele.id() === id;\n};\nmatch[Type.CLASS] = function (check, ele) {\n  var cls = check.value;\n  return ele.hasClass(cls);\n};\nmatch[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};\nmatch[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};\nmatch[Type.DATA_BOOL] = function (check, ele) {\n  var field = check.field,\n    operator = check.operator;\n  return boolCmp(data$1(ele, field), operator);\n};\nmatch[Type.DATA_EXIST] = function (check, ele) {\n  var field = check.field;\n    check.operator;\n  return existCmp(data$1(ele, field));\n};\nmatch[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};\nmatch[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};\nmatch[Type.DIRECTED_EDGE] = function (check, ele) {\n  return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());\n};\nmatch[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};\nmatch[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};\nmatch[Type.CHILD] = function (check, ele) {\n  return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());\n};\nmatch[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};\nmatch[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};\nmatch[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};\nmatch[Type.COMPOUND_SPLIT] = function (check, ele) {\n  return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);\n};\nmatch[Type.TRUE] = function () {\n  return true;\n};\nmatch[Type.COLLECTION] = function (check, ele) {\n  var collection = check.value;\n  return collection.has(ele);\n};\nmatch[Type.FILTER] = function (check, ele) {\n  var filter = check.value;\n  return filter(ele);\n};\n\n// filter an existing collection\nvar filter = function filter(collection) {\n  var self = this;\n\n  // for 1 id #foo queries, just get the element\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  var selectorFunction = function selectorFunction(element) {\n    for (var j = 0; j < self.length; j++) {\n      var query = self[j];\n      if (matches$1(query, element)) {\n        return true;\n      }\n    }\n    return false;\n  };\n  if (self.text() == null) {\n    selectorFunction = function selectorFunction() {\n      return true;\n    };\n  }\n  return collection.filter(selectorFunction);\n}; // filter\n\n// does selector match a single element?\nvar matches = function matches(ele) {\n  var self = this;\n  for (var j = 0; j < self.length; j++) {\n    var query = self[j];\n    if (matches$1(query, ele)) {\n      return true;\n    }\n  }\n  return false;\n}; // matches\n\nvar matching = {\n  matches: matches,\n  filter: filter\n};\n\nvar 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  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};\nvar selfn = Selector.prototype;\n[parse$1, matching].forEach(function (p) {\n  return extend(selfn, p);\n});\nselfn.text = function () {\n  return this.inputText;\n};\nselfn.size = function () {\n  return this.length;\n};\nselfn.eq = function (i) {\n  return this[i];\n};\nselfn.sameText = function (otherSel) {\n  return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();\n};\nselfn.addQuery = function (q) {\n  this[this.length++] = q;\n};\nselfn.selector = selfn.toString;\n\nvar 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      if (ret) {\n        return true;\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      if (!ret) {\n        return false;\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    collection = this.cy().collection(collection);\n    var thisLength = this.length;\n    var collectionLength = collection.length;\n\n    // cheap length check\n    if (thisLength !== collectionLength) {\n      return false;\n    }\n\n    // cheap element ref check\n    if (thisLength === 1) {\n      return this[0] === collection[0];\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};\nelesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;\nelesfn$g.has = elesfn$g.contains;\nelesfn$g.equal = elesfn$g.equals = elesfn$g.same;\n\nvar 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    if (selectorOrEles == null) {\n      key = '';\n    } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {\n      key = selectorOrEles.id();\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      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\nvar elesfn$f = {\n  parent: function parent(selector) {\n    var parents = [];\n\n    // optimisation for single ele call\n    if (this.length === 1) {\n      var parent = this[0]._private.parent;\n      if (parent) {\n        return parent;\n      }\n    }\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      var _parent = ele._private.parent;\n      if (_parent) {\n        parents.push(_parent);\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    while (eles.nonempty()) {\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n        parents.push(ele);\n      }\n      eles = eles.parent();\n    }\n    return this.spawn(parents, true).filter(selector);\n  },\n  commonAncestors: function commonAncestors(selector) {\n    var ancestors;\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    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    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      var eleChildren = ele._private.children;\n      for (var j = 0; j < eleChildren.length; j++) {\n        children.push(eleChildren[j]);\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    if (ele) {\n      return ele.isNode() && ele._private.children.length !== 0;\n    }\n  },\n  isChildless: function isChildless() {\n    var ele = this[0];\n    if (ele) {\n      return ele.isNode() && ele._private.children.length === 0;\n    }\n  },\n  isChild: function isChild() {\n    var ele = this[0];\n    if (ele) {\n      return ele.isNode() && ele._private.parent != null;\n    }\n  },\n  isOrphan: function isOrphan() {\n    var ele = this[0];\n    if (ele) {\n      return ele.isNode() && ele._private.parent == null;\n    }\n  },\n  descendants: function descendants(selector) {\n    var elements = [];\n    function add(eles) {\n      for (var i = 0; i < eles.length; i++) {\n        var ele = eles[i];\n        elements.push(ele);\n        if (ele.children().nonempty()) {\n          add(ele.children());\n        }\n      }\n    }\n    add(this.children());\n    return this.spawn(elements, true).filter(selector);\n  }\n};\nfunction 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  for (var i = 0; i < eles.length; i++) {\n    var ele = eles[i];\n    if (includeSelf) {\n      q.push(ele);\n    } else if (hasCompounds) {\n      recursiveStep(q, did, ele);\n    }\n  }\n  while (q.length > 0) {\n    var _ele = q.shift();\n    fn(_ele);\n    did.add(_ele.id());\n    if (hasCompounds) {\n      recursiveStep(q, did, _ele);\n    }\n  }\n  return eles;\n}\nfunction addChildren(q, did, ele) {\n  if (ele.isParent()) {\n    var children = ele._private.children;\n    for (var i = 0; i < children.length; i++) {\n      var child = children[i];\n      if (!did.has(child.id())) {\n        q.push(child);\n      }\n    }\n  }\n}\n\n// very efficient version of eles.add( eles.descendants() ).forEach()\n// for internal use\nelesfn$f.forEachDown = function (fn) {\n  var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n  return forEachCompound(this, fn, includeSelf, addChildren);\n};\nfunction addParent(q, did, ele) {\n  if (ele.isChild()) {\n    var parent = ele._private.parent;\n    if (!did.has(parent.id())) {\n      q.push(parent);\n    }\n  }\n}\nelesfn$f.forEachUp = function (fn) {\n  var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n  return forEachCompound(this, fn, includeSelf, addParent);\n};\nfunction addParentAndChildren(q, did, ele) {\n  addParent(q, did, ele);\n  addChildren(q, did, ele);\n}\nelesfn$f.forEachUpAndDown = function (fn) {\n  var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n  return forEachCompound(this, fn, includeSelf, addParentAndChildren);\n};\n\n// aliases\nelesfn$f.ancestors = elesfn$f.parents;\n\nvar fn$5, elesfn$e;\nfn$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    if (ele) {\n      return ele._private.data.id;\n    }\n  }\n};\n\n// aliases\nfn$5.attr = fn$5.data;\nfn$5.removeAttr = fn$5.removeData;\nvar data = elesfn$e;\n\nvar elesfn$d = {};\nfunction defineDegreeFunction(callback) {\n  return function (includeLoops) {\n    var self = this;\n    if (includeLoops === undefined) {\n      includeLoops = true;\n    }\n    if (self.length === 0) {\n      return;\n    }\n    if (self.isNode() && !self.removed()) {\n      var degree = 0;\n      var node = self[0];\n      var connectedEdges = node._private.edges;\n      for (var i = 0; i < connectedEdges.length; i++) {\n        var edge = connectedEdges[i];\n        if (!includeLoops && edge.isLoop()) {\n          continue;\n        }\n        degree += callback(node, edge);\n      }\n      return degree;\n    } else {\n      return;\n    }\n  };\n}\nextend(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});\nfunction defineDegreeBoundsFunction(degreeFn, callback) {\n  return function (includeLoops) {\n    var ret;\n    var nodes = this.nodes();\n    for (var i = 0; i < nodes.length; i++) {\n      var ele = nodes[i];\n      var degree = ele[degreeFn](includeLoops);\n      if (degree !== undefined && (ret === undefined || callback(degree, ret))) {\n        ret = degree;\n      }\n    }\n    return ret;\n  };\n}\nextend(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});\nextend(elesfn$d, {\n  totalDegree: function totalDegree(includeLoops) {\n    var total = 0;\n    var nodes = this.nodes();\n    for (var i = 0; i < nodes.length; i++) {\n      total += nodes[i].degree(includeLoops);\n    }\n    return total;\n  }\n});\n\nvar fn$4, elesfn$c;\nvar beforePositionSet = function beforePositionSet(eles, newPos, silent) {\n  for (var i = 0; i < eles.length; i++) {\n    var ele = eles[i];\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      if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {\n        ele.children().shift(delta, silent);\n      }\n      ele.dirtyBoundingBoxCache();\n    }\n  }\n};\nvar 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};\nfn$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      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n        var _pos = undefined;\n        if (_pos = _fn(ele, i)) {\n          if (silent) {\n            ele.silentPosition(_pos);\n          } else {\n            ele.position(_pos);\n          }\n        }\n      }\n      cy.endBatch();\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    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    if (delta != null) {\n      var cy = this.cy();\n      cy.startBatch();\n      for (var i = 0; i < this.length; i++) {\n        var ele = this[i];\n\n        // exclude any node that is a descendant of the calling collection\n        if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {\n          continue;\n        }\n        var pos = ele.position();\n        var newPos = {\n          x: pos.x + delta.x,\n          y: pos.y + delta.y\n        };\n        if (silent) {\n          ele.silentPosition(newPos);\n        } else {\n          ele.position(newPos);\n        }\n      }\n      cy.endBatch();\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    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    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          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$1(pos, zoom, pan);\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    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    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          if (hasParent) {\n            parent = parent[0];\n          }\n          var origin = relativeToParent ? parent.position() : {\n            x: 0,\n            y: 0\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        var _parent = hasCompoundNodes ? ele.parent() : null;\n        var _hasParent = _parent && _parent.length > 0;\n        var _relativeToParent = _hasParent;\n        if (_hasParent) {\n          _parent = _parent[0];\n        }\n        var _origin = _relativeToParent ? _parent.position() : {\n          x: 0,\n          y: 0\n        };\n        ppos = {\n          x: pos.x - _origin.x,\n          y: pos.y - _origin.y\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    return this; // chaining\n  }\n};\n\n// aliases\nfn$4.modelPosition = fn$4.point = fn$4.position;\nfn$4.modelPositions = fn$4.points = fn$4.positions;\nfn$4.renderedPoint = fn$4.renderedPosition;\nfn$4.relativePoint = fn$4.relativePosition;\nvar position = elesfn$c;\n\nvar fn$3, elesfn$b;\nfn$3 = elesfn$b = {};\nelesfn$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};\nelesfn$b.dirtyCompoundBoundsCache = function () {\n  var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n  var cy = this.cy();\n  if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {\n    return this;\n  }\n  this.forEachUp(function (ele) {\n    if (ele.isParent()) {\n      var _p = ele._private;\n      _p.compoundBoundsClean = false;\n      _p.bbCache = null;\n      if (!silent) {\n        ele.emitAndNotify('bounds');\n      }\n    }\n  });\n  return this;\n};\nelesfn$b.updateCompoundBounds = function () {\n  var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n  var cy = this.cy();\n\n  // not possible to do on non-compound graphs or with the style disabled\n  if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {\n    return this;\n  }\n\n  // save cycles when batching -- but bounds will be stale (or not exist yet)\n  if (!force && cy.batching()) {\n    return this;\n  }\n  function update(parent) {\n    if (!parent.isParent()) {\n      return;\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;\n\n    // if children take up zero area then keep position and fall back on stylesheet w/h\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    function computeBiasValues(propDiff, propBias, propBiasComplement) {\n      var biasDiff = 0;\n      var biasComplementDiff = 0;\n      var biasTotal = propBias + propBiasComplement;\n      if (propDiff > 0 && biasTotal > 0) {\n        biasDiff = propBias / biasTotal * propDiff;\n        biasComplementDiff = propBiasComplement / biasTotal * propDiff;\n      }\n      return {\n        biasDiff: biasDiff,\n        biasComplementDiff: biasComplementDiff\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          case 'height':\n            return height > 0 ? paddingObject.pfValue * height : 0;\n          case 'average':\n            return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;\n          case 'min':\n            return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;\n          case 'max':\n            return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;\n          default:\n            return 0;\n        }\n      } else if (paddingObject.units === 'px') {\n        return paddingObject.pfValue;\n      } else {\n        return 0;\n      }\n    }\n    var leftVal = min.width.left.value;\n    if (min.width.left.units === 'px' && min.width.val > 0) {\n      leftVal = leftVal * 100 / min.width.val;\n    }\n    var rightVal = min.width.right.value;\n    if (min.width.right.units === 'px' && min.width.val > 0) {\n      rightVal = rightVal * 100 / min.width.val;\n    }\n    var topVal = min.height.top.value;\n    if (min.height.top.units === 'px' && min.height.val > 0) {\n      topVal = topVal * 100 / min.height.val;\n    }\n    var bottomVal = min.height.bottom.value;\n    if (min.height.bottom.units === 'px' && min.height.val > 0) {\n      bottomVal = bottomVal * 100 / min.height.val;\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  for (var i = 0; i < this.length; i++) {\n    var ele = this[i];\n    var _p = ele._private;\n    if (!_p.compoundBoundsClean || force) {\n      update(ele);\n      if (!cy.batching()) {\n        _p.compoundBoundsClean = true;\n      }\n    }\n  }\n  return this;\n};\nvar noninf = function noninf(x) {\n  if (x === Infinity || x === -Infinity) {\n    return 0;\n  }\n  return x;\n};\nvar 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  }\n\n  // don't update with null dim\n  if (x1 == null || y1 == null || x2 == null || y2 == null) {\n    return;\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};\nvar updateBoundsFromBox = function updateBoundsFromBox(b, b2) {\n  if (b2 == null) {\n    return b;\n  }\n  return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);\n};\nvar prefixedProperty = function prefixedProperty(obj, field, prefix) {\n  return getPrefixedProperty(obj, field, prefix);\n};\nvar updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {\n  if (ele.cy().headless()) {\n    return;\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  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    }\n\n    // always store the individual arrow bounds\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};\nvar updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {\n  if (ele.cy().headless()) {\n    return;\n  }\n  var prefixDash;\n  if (prefix) {\n    prefixDash = prefix + '-';\n  } else {\n    prefixDash = '';\n  }\n  var _p = ele._private;\n  var rstyle = _p.rstyle;\n  var label = ele.pstyle(prefixDash + 'label').strValue;\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    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        case 'center':\n          lx1 = labelX - lw_2;\n          lx2 = labelX + lw_2;\n          break;\n        case 'right':\n          lx1 = labelX;\n          lx2 = labelX + lw;\n          break;\n      }\n      switch (valign.value) {\n        case 'top':\n          ly1 = labelY - lh;\n          ly2 = labelY;\n          break;\n        case 'center':\n          ly1 = labelY - lh_2;\n          ly2 = labelY + lh_2;\n          break;\n        case 'bottom':\n          ly1 = labelY;\n          ly2 = labelY + lh;\n          break;\n      }\n    }\n\n    // shift by margin and expand by outline and border\n    var leftPad = marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;\n    var rightPad = marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;\n    var topPad = marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;\n    var botPad = marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;\n    lx1 += leftPad;\n    lx2 += rightPad;\n    ly1 += topPad;\n    ly2 += botPad;\n\n    // always store the unrotated label bounds separately\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    bb.leftPad = leftPad;\n    bb.rightPad = rightPad;\n    bb.topPad = topPad;\n    bb.botPad = botPad;\n    var isAutorotate = isEdge && rotation.strValue === 'autorotate';\n    var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;\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);\n\n      // rotation point (default value for center-center)\n      var xo = (lx1 + lx2) / 2;\n      var yo = (ly1 + ly2) / 2;\n      if (!isEdge) {\n        switch (halign.value) {\n          case 'left':\n            xo = lx2;\n            break;\n          case 'right':\n            xo = lx1;\n            break;\n        }\n        switch (valign.value) {\n          case 'top':\n            yo = ly2;\n            break;\n          case 'bottom':\n            yo = ly1;\n            break;\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      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    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  return bounds;\n};\nvar updateBoundsFromOutline = function updateBoundsFromOutline(bounds, ele) {\n  if (ele.cy().headless()) {\n    return;\n  }\n  var outlineOpacity = ele.pstyle('outline-opacity').value;\n  var outlineWidth = ele.pstyle('outline-width').value;\n  if (outlineOpacity > 0 && outlineWidth > 0) {\n    var outlineOffset = ele.pstyle('outline-offset').value;\n    var nodeShape = ele.pstyle('shape').value;\n    var outlineSize = outlineWidth + outlineOffset;\n    var scaleX = (bounds.w + outlineSize * 2) / bounds.w;\n    var scaleY = (bounds.h + outlineSize * 2) / bounds.h;\n    var xOffset = 0;\n    var yOffset = 0;\n    if ([\"diamond\", \"pentagon\", \"round-triangle\"].includes(nodeShape)) {\n      scaleX = (bounds.w + outlineSize * 2.4) / bounds.w;\n      yOffset = -outlineSize / 3.6;\n    } else if ([\"concave-hexagon\", \"rhomboid\", \"right-rhomboid\"].includes(nodeShape)) {\n      scaleX = (bounds.w + outlineSize * 2.4) / bounds.w;\n    } else if (nodeShape === \"star\") {\n      scaleX = (bounds.w + outlineSize * 2.8) / bounds.w;\n      scaleY = (bounds.h + outlineSize * 2.6) / bounds.h;\n      yOffset = -outlineSize / 3.8;\n    } else if (nodeShape === \"triangle\") {\n      scaleX = (bounds.w + outlineSize * 2.8) / bounds.w;\n      scaleY = (bounds.h + outlineSize * 2.4) / bounds.h;\n      yOffset = -outlineSize / 1.4;\n    } else if (nodeShape === \"vee\") {\n      scaleX = (bounds.w + outlineSize * 4.4) / bounds.w;\n      scaleY = (bounds.h + outlineSize * 3.8) / bounds.h;\n      yOffset = -outlineSize * .5;\n    }\n    var hDelta = bounds.h * scaleY - bounds.h;\n    var wDelta = bounds.w * scaleX - bounds.w;\n    expandBoundingBoxSides(bounds, [Math.ceil(hDelta / 2), Math.ceil(wDelta / 2)]);\n    if (xOffset != 0 || yOffset !== 0) {\n      var oBounds = shiftBoundingBox(bounds, xOffset, yOffset);\n      updateBoundingBox(bounds, oBounds);\n    }\n  }\n};\n\n// get the bounding box of the elements (in raw model position)\nvar 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  var x, y; // node pos\n  var rstyle = _p.rstyle;\n  var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0];\n\n  // 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  var isDisplayed = function isDisplayed(ele) {\n    return ele.pstyle('display').value !== 'none';\n  };\n  var displayed = !styleEnabled || isDisplayed(ele)\n\n  // 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  if (displayed) {\n    // displayed suffices, since we will find zero area eles anyway\n    var overlayOpacity = 0;\n    var overlayPadding = 0;\n    if (styleEnabled && options.includeOverlays) {\n      overlayOpacity = ele.pstyle('overlay-opacity').value;\n      if (overlayOpacity !== 0) {\n        overlayPadding = ele.pstyle('overlay-padding').value;\n      }\n    }\n    var underlayOpacity = 0;\n    var underlayPadding = 0;\n    if (styleEnabled && options.includeUnderlays) {\n      underlayOpacity = ele.pstyle('underlay-opacity').value;\n      if (underlayOpacity !== 0) {\n        underlayPadding = ele.pstyle('underlay-padding').value;\n      }\n    }\n    var padding = Math.max(overlayPadding, underlayPadding);\n    var w = 0;\n    var wHalf = 0;\n    if (styleEnabled) {\n      w = ele.pstyle('width').pfValue;\n      wHalf = w / 2;\n    }\n    if (isNode && options.includeNodes) {\n      var pos = ele.position();\n      x = pos.x;\n      y = pos.y;\n      var _w = ele.outerWidth();\n      var halfW = _w / 2;\n      var h = ele.outerHeight();\n      var halfH = h / 2;\n\n      // 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      if (styleEnabled && options.includeOutlines) {\n        updateBoundsFromOutline(bounds, ele);\n      }\n    } else if (isEdge && options.includeEdges) {\n      if (styleEnabled && !headless) {\n        var curveStyle = ele.pstyle('curve-style').strValue;\n\n        // 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);\n\n        // take into account edge width\n        ex1 -= wHalf;\n        ex2 += wHalf;\n        ey1 -= wHalf;\n        ey2 += wHalf;\n        updateBounds(bounds, ex1, ey1, ex2, ey2);\n\n        // precise edges\n        ////////////////\n\n        if (curveStyle === 'haystack') {\n          var hpts = rstyle.haystackPts;\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            if (ex1 > ex2) {\n              var temp = ex1;\n              ex1 = ex2;\n              ex2 = temp;\n            }\n            if (ey1 > ey2) {\n              var _temp = ey1;\n              ey1 = ey2;\n              ey2 = _temp;\n            }\n            updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);\n          }\n        } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || curveStyle.endsWith('segments') || curveStyle.endsWith('taxi')) {\n          var pts;\n          switch (curveStyle) {\n            case 'bezier':\n            case 'unbundled-bezier':\n              pts = rstyle.bezierPts;\n              break;\n            case 'segments':\n            case 'taxi':\n            case 'round-segments':\n            case 'round-taxi':\n              pts = rstyle.linePts;\n              break;\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      } else {\n        // headless or style disabled\n\n        // fallback on source and target positions\n        //////////////////////////////////////////\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        if (ex1 > ex2) {\n          var _temp2 = ex1;\n          ex1 = ex2;\n          ex2 = _temp2;\n        }\n        if (ey1 > ey2) {\n          var _temp3 = ey1;\n          ey1 = ey2;\n          ey2 = _temp3;\n        }\n\n        // take into account edge width\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    } // edges\n\n    // handle edge arrow size\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    }\n\n    // ghost\n    ////////\n\n    if (styleEnabled) {\n      var ghost = ele.pstyle('ghost').value === 'yes';\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    }\n\n    // always store the body bounds separately from the labels\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\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    }\n\n    // always store the body bounds separately from the labels\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\n    // handle label dimensions\n    //////////////////////////\n\n    var bbLabels = _p.labelBounds = _p.labelBounds || {};\n    if (bbLabels.all != null) {\n      clearBoundingBox(bbLabels.all);\n    } else {\n      bbLabels.all = makeBoundingBox();\n    }\n    if (styleEnabled && options.includeLabels) {\n      if (options.includeMainLabels) {\n        updateBoundsFromLabel(bounds, ele, null);\n      }\n      if (isEdge) {\n        if (options.includeSourceLabels) {\n          updateBoundsFromLabel(bounds, ele, 'source');\n        }\n        if (options.includeTargetLabels) {\n          updateBoundsFromLabel(bounds, ele, 'target');\n        }\n      }\n    } // style enabled for labels\n  } // if displayed\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  if (bounds.w > 0 && bounds.h > 0 && displayed) {\n    expandBoundingBoxSides(bounds, manualExpansion);\n\n    // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides\n    expandBoundingBox(bounds, 1);\n  }\n  return bounds;\n};\nvar getKey = function getKey(opts) {\n  var i = 0;\n  var tf = function tf(val) {\n    return (val ? 1 : 0) << i++;\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  key += tf(opts.includeOutlines);\n  return key;\n};\nvar getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {\n  if (ele.isEdge()) {\n    var p1 = ele.source().position();\n    var p2 = ele.target().position();\n    var r = function r(x) {\n      return Math.round(x);\n    };\n    return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);\n  } else {\n    return 0;\n  }\n};\nvar 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;\n  var isDirty = function isDirty(ele) {\n    return ele._private.bbCache == null || ele._private.styleDirty;\n  };\n  var needRecalc = !useCache || isDirty(ele) || isEdge && (isDirty(ele.source()) || isDirty(ele.target()));\n  if (needRecalc) {\n    if (!isPosKeySame) {\n      ele.recalculateRenderedStyle(useCache);\n    }\n    bb = boundingBoxImpl(ele, defBbOpts);\n    _p.bbCache = bb;\n    _p.bbCachePosKey = currPosKey;\n  } else {\n    bb = _p.bbCache;\n  }\n\n  // not using def opts => need to build up bb from combination of sub bbs\n  if (!usingDefOpts) {\n    var isNode = ele.isNode();\n    bb = makeBoundingBox();\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    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        if (opts.includeSourceLabels) {\n          updateBoundsFromBox(bb, _p.labelBounds.sourceRot);\n        }\n        if (opts.includeTargetLabels) {\n          updateBoundsFromBox(bb, _p.labelBounds.targetRot);\n        }\n      }\n    }\n    bb.w = bb.x2 - bb.x1;\n    bb.h = bb.y2 - bb.y1;\n  }\n  return bb;\n};\nvar 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  includeOutlines: true,\n  useCache: true\n};\nvar defBbOptsKey = getKey(defBbOpts);\nvar filledBbOpts = defaults$g(defBbOpts);\nelesfn$b.boundingBox = function (options) {\n  var bounds;\n\n  // 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  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    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    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    this.updateCompoundBounds(!options.useCache);\n    for (var _i = 0; _i < eles.length; _i++) {\n      var _ele = eles[_i];\n      updateBoundsFromBox(bounds, cachedBoundingBoxImpl(_ele, opts));\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};\nelesfn$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  this.emitAndNotify('bounds');\n  return this;\n};\n\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\nelesfn$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  if (hasCompoundNodes) {\n    parents = nodes.filter(function (node) {\n      return node.isParent();\n    });\n    nodes = nodes.not(parents);\n  }\n  if (plainObject(fn)) {\n    var obj = fn;\n    fn = function fn() {\n      return obj;\n    };\n  }\n  var storeOldPos = function storeOldPos(node, i) {\n    return node._private.bbAtOldPos = fn(node, i);\n  };\n  var getOldPos = function getOldPos(node) {\n    return node._private.bbAtOldPos;\n  };\n  cy.startBatch();\n  nodes.forEach(storeOldPos).silentPositions(fn);\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  var bb = copyBoundingBox(this.boundingBox({\n    useCache: false\n  }));\n  nodes.silentPositions(getOldPos);\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  cy.endBatch();\n  return bb;\n};\nfn$3.boundingbox = fn$3.bb = fn$3.boundingBox;\nfn$3.renderedBoundingbox = fn$3.renderedBoundingBox;\nvar bounds = elesfn$b;\n\nvar fn$2, elesfn$a;\nfn$2 = elesfn$a = {};\nvar 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  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    if (ele) {\n      if (styleEnabled) {\n        if (ele.isParent()) {\n          ele.updateCompoundBounds();\n          return _p[opts.autoName] || 0;\n        }\n        var d = ele.pstyle(opts.name);\n        switch (d.strValue) {\n          case 'label':\n            ele.recalculateRenderedStyle();\n            return _p.rstyle[opts.labelName] || 0;\n          default:\n            return d.pfValue;\n        }\n      } else {\n        return 1;\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    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        var padding = 2 * ele.padding();\n        return dim + border + padding;\n      } else {\n        return 1;\n      }\n    }\n  };\n  fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {\n    var ele = this[0];\n    if (ele) {\n      var d = ele[opts.name]();\n      return d * this.cy().zoom();\n    }\n  };\n  fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {\n    var ele = this[0];\n    if (ele) {\n      var od = ele[opts.outerName]();\n      return od * this.cy().zoom();\n    }\n  };\n};\ndefineDimFns({\n  name: 'width'\n});\ndefineDimFns({\n  name: 'height'\n});\nelesfn$a.padding = function () {\n  var ele = this[0];\n  var _p = ele._private;\n  if (ele.isParent()) {\n    ele.updateCompoundBounds();\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};\nelesfn$a.paddedHeight = function () {\n  var ele = this[0];\n  return ele.height() + 2 * ele.padding();\n};\nelesfn$a.paddedWidth = function () {\n  var ele = this[0];\n  return ele.width() + 2 * ele.padding();\n};\nvar widthHeight = elesfn$a;\n\nvar ifEdge = function ifEdge(ele, getValue) {\n  if (ele.isEdge() && ele.takesUpSpace()) {\n    return getValue(ele);\n  }\n};\nvar ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {\n  if (ele.isEdge() && ele.takesUpSpace()) {\n    var cy = ele.cy();\n    return modelToRenderedPosition$1(getPoint(ele), cy.zoom(), cy.pan());\n  }\n};\nvar ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {\n  if (ele.isEdge() && ele.takesUpSpace()) {\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$1(p, zoom, pan);\n    });\n  }\n};\nvar controlPoints = function controlPoints(ele) {\n  return ele.renderer().getControlPoints(ele);\n};\nvar segmentPoints = function segmentPoints(ele) {\n  return ele.renderer().getSegmentPoints(ele);\n};\nvar sourceEndpoint = function sourceEndpoint(ele) {\n  return ele.renderer().getSourceEndpoint(ele);\n};\nvar targetEndpoint = function targetEndpoint(ele) {\n  return ele.renderer().getTargetEndpoint(ele);\n};\nvar midpoint = function midpoint(ele) {\n  return ele.renderer().getEdgeMidpoint(ele);\n};\nvar 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};\nvar renderedName = function renderedName(name) {\n  return 'rendered' + name[0].toUpperCase() + name.substr(1);\n};\nvar edgePoints = Object.keys(pts).reduce(function (obj, name) {\n  var spec = pts[name];\n  var rName = renderedName(name);\n  obj[name] = function () {\n    return ifEdge(this, spec.get);\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  return obj;\n}, {});\n\nvar dimensions = extend({}, position, bounds, widthHeight, edgePoints);\n\n/*!\nEvent object based on jQuery events, MIT license\n\nhttps://jquery.org/license/\nhttps://tldrlegal.com/license/mit-license\nhttps://github.com/jquery/jquery/blob/master/src/event.js\n*/\n\nvar Event = function Event(src, props) {\n  this.recycle(src, props);\n};\nfunction returnFalse() {\n  return false;\n}\nfunction returnTrue() {\n  return true;\n}\n\n// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html\nEvent.prototype = {\n  instanceString: function instanceString() {\n    return 'event';\n  },\n  recycle: function recycle(src, props) {\n    this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;\n    if (src != null && src.preventDefault) {\n      // Browser Event object\n      this.type = src.type;\n\n      // Events bubbling up the document may have been marked as prevented\n      // by a handler lower down the tree; reflect the correct value.\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    }\n\n    // Put explicitly provided properties onto the event object\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    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    }\n\n    // Create a timestamp if incoming event doesn't have one\n    this.timeStamp = src && src.timeStamp || Date.now();\n  },\n  preventDefault: function preventDefault() {\n    this.isDefaultPrevented = returnTrue;\n    var e = this.originalEvent;\n    if (!e) {\n      return;\n    }\n\n    // if preventDefault exists run it on the original event\n    if (e.preventDefault) {\n      e.preventDefault();\n    }\n  },\n  stopPropagation: function stopPropagation() {\n    this.isPropagationStopped = returnTrue;\n    var e = this.originalEvent;\n    if (!e) {\n      return;\n    }\n\n    // if stopPropagation exists run it on the original event\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\nvar eventRegex = /^([^.]+)(\\.(?:[^.]+))?$/; // regex for matching event strings (e.g. \"click.namespace\")\nvar universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally\n\nvar defaults$8 = {\n  qualifierCompare: function qualifierCompare(q1, q2) {\n    return q1 === q2;\n  },\n  eventMatches: function eventMatches(/*context, listener, eventObj*/\n  ) {\n    return true;\n  },\n  addEventFields: function addEventFields(/*context, evt*/\n  ) {},\n  callbackContext: function callbackContext(context /*, listener, eventObj*/) {\n    return context;\n  },\n  beforeEmit: function beforeEmit(/* context, listener, eventObj */\n  ) {},\n  afterEmit: function afterEmit(/* context, listener, eventObj */\n  ) {},\n  bubble: function bubble(/*context*/\n  ) {\n    return false;\n  },\n  parent: function parent(/*context*/\n  ) {\n    return null;\n  },\n  context: null\n};\nvar defaultsKeys = Object.keys(defaults$8);\nvar emptyOpts = {};\nfunction Emitter() {\n  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;\n  var context = arguments.length > 1 ? arguments[1] : undefined;\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  this.context = context || this.context;\n  this.listeners = [];\n  this.emitting = 0;\n}\nvar p = Emitter.prototype;\nvar forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {\n  if (fn$6(qualifier)) {\n    callback = qualifier;\n    qualifier = null;\n  }\n  if (confOverrides) {\n    if (conf == null) {\n      conf = confOverrides;\n    } else {\n      conf = extend({}, conf, confOverrides);\n    }\n  }\n  var eventList = array(events) ? events : events.split(/\\s+/);\n  for (var i = 0; i < eventList.length; i++) {\n    var evt = eventList[i];\n    if (emptyString(evt)) {\n      continue;\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      if (ret === false) {\n        break;\n      } // allow exiting early\n    }\n  }\n};\nvar makeEventObj = function makeEventObj(self, obj) {\n  self.addEventFields(self.context, obj);\n  return new Event(obj.type, obj);\n};\nvar 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  var eventList = array(events) ? events : events.split(/\\s+/);\n  for (var i = 0; i < eventList.length; i++) {\n    var evt = eventList[i];\n    if (emptyString(evt)) {\n      continue;\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};\np.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  }, events, qualifier, callback, conf, confOverrides);\n  return this;\n};\np.one = function (events, qualifier, callback, conf) {\n  return this.on(events, qualifier, callback, conf, {\n    one: true\n  });\n};\np.removeListener = p.off = function (events, qualifier, callback, conf) {\n  var _this = this;\n  if (this.emitting !== 0) {\n    this.listeners = copyArray(this.listeners);\n  }\n  var listeners = this.listeners;\n  var _loop = function _loop(i) {\n    var listener = listeners[i];\n    forEachEvent(_this, function (self, event, type, namespace, qualifier, callback /*, conf*/) {\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  for (var i = listeners.length - 1; i >= 0; i--) {\n    _loop(i);\n  }\n  return this;\n};\np.removeAllListeners = function () {\n  return this.removeListener('*');\n};\np.emit = p.trigger = function (events, extraParams, manualCallback) {\n  var listeners = this.listeners;\n  var numListenersBeforeEmit = listeners.length;\n  this.emitting++;\n  if (!array(extraParams)) {\n    extraParams = [extraParams];\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    var _loop2 = function _loop2() {\n      var listener = listeners[i];\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        if (extraParams != null) {\n          push(args, extraParams);\n        }\n        self.beforeEmit(self.context, listener, eventObj);\n        if (listener.conf && listener.conf.one) {\n          self.listeners = self.listeners.filter(function (l) {\n            return l !== listener;\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        if (ret === false) {\n          eventObj.stopPropagation();\n          eventObj.preventDefault();\n        }\n      } // if listener matches\n    };\n    for (var i = 0; i < numListenersBeforeEmit; i++) {\n      _loop2();\n    } // for listener\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\nvar 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    if (selector != null) {\n      return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);\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 /*, eventObj*/) {\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};\nvar argSelector$1 = function argSelector(arg) {\n  if (string(arg)) {\n    return new Selector(arg);\n  } else {\n    return arg;\n  }\n};\nvar 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      if (!_p.emitter) {\n        _p.emitter = new Emitter(emitterOptions$1, ele);\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    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      ele.emitter().on(events, argSel, callback);\n    }\n    return this;\n  },\n  removeListener: function removeListener(events, selector, callback) {\n    var argSel = argSelector$1(selector);\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      ele.emitter().removeListener(events, argSel, callback);\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    return this;\n  },\n  one: function one(events, selector, callback) {\n    var argSel = argSelector$1(selector);\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      ele.emitter().one(events, argSel, callback);\n    }\n    return this;\n  },\n  once: function once(events, selector, callback) {\n    var argSel = argSelector$1(selector);\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    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\n    // notify renderer\n    this.cy().notify(event, this);\n    this.emit(event, extraParams);\n    return this;\n  }\n};\ndefine.eventAliasesOn(elesfn$9);\n\nvar 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    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      if (ele.isNode()) {\n        nodes.push(ele);\n      } else {\n        edges.push(ele);\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      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        if (include) {\n          filterEles.push(ele);\n        }\n      }\n      return filterEles;\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      var elements = this.spawn();\n      for (var i = 0; i < this.length; i++) {\n        var element = this[i];\n        var remove = toRemove.has(element);\n        if (!remove) {\n          elements.push(element);\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    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    for (var i = 0; i < colS.length; i++) {\n      var ele = colS[i];\n      if (colL.has(ele)) {\n        elements.push(ele);\n      }\n    }\n    return elements;\n  },\n  xor: function xor(other) {\n    var cy = this._private.cy;\n    if (string(other)) {\n      other = cy.$(other);\n    }\n    var elements = this.spawn();\n    var col1 = this;\n    var col2 = other;\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        if (!inOther) {\n          elements.push(ele);\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    if (string(other)) {\n      other = cy.$(other);\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    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        if (inOther) {\n          both.merge(ele);\n        } else {\n          retEles.push(ele);\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    if (!toAdd) {\n      return this;\n    }\n    if (string(toAdd)) {\n      var selector = toAdd;\n      toAdd = cy.mutableElements().filter(selector);\n    }\n    var elements = this.spawnSelf();\n    for (var i = 0; i < toAdd.length; i++) {\n      var ele = toAdd[i];\n      var add = !this.has(ele);\n      if (add) {\n        elements.push(ele);\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    if (!toAdd) {\n      return this;\n    }\n    if (toAdd && string(toAdd)) {\n      var selector = toAdd;\n      toAdd = cy.mutableElements().filter(selector);\n    }\n    var map = _p.map;\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      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    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;\n\n    // remove ele\n    this[i] = undefined;\n    map[\"delete\"](id);\n    var unmergedLastEle = i === this.length - 1;\n\n    // replace empty spot with last ele in collection\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    }\n\n    // the collection is now 1 ele smaller\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    if (!entry) {\n      return this; // no need to remove\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    if (!toRemove) {\n      return this;\n    }\n    if (toRemove && string(toRemove)) {\n      var selector = toRemove;\n      toRemove = cy.mutableElements().filter(selector);\n    }\n    for (var i = 0; i < toRemove.length; i++) {\n      this.unmergeOne(toRemove[i]);\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      if (toRmFn(ele)) {\n        this.unmergeAt(i);\n      }\n    }\n    return this;\n  },\n  map: function map(mapFn, thisArg) {\n    var arr = [];\n    var eles = this;\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    return arr;\n  },\n  reduce: function reduce(fn, initialValue) {\n    var val = initialValue;\n    var eles = this;\n    for (var i = 0; i < eles.length; i++) {\n      val = fn(val, eles[i], i, eles);\n    }\n    return val;\n  },\n  max: function max(valFn, thisArg) {\n    var max = -Infinity;\n    var maxEle;\n    var eles = this;\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      if (val > max) {\n        max = val;\n        maxEle = ele;\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    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      if (val < min) {\n        min = val;\n        minEle = ele;\n      }\n    }\n    return {\n      value: min,\n      ele: minEle\n    };\n  }\n};\n\n// aliases\nvar fn$1 = elesfn$8;\nfn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;\nfn$1['\\\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;\nfn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;\nfn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;\nfn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;\nfn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;\n\nvar 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    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 */\nvar zIndexSort = function zIndexSort(a, b) {\n  var cy = a.cy();\n  var hasCompoundNodes = cy.hasCompoundNodes();\n  function getDepth(ele) {\n    var style = ele.pstyle('z-compound-depth');\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    }\n    // 'orphan'\n    return 0;\n  }\n  var depthDiff = getDepth(a) - getDepth(b);\n  if (depthDiff !== 0) {\n    return depthDiff;\n  }\n  function getEleDepth(ele) {\n    var style = ele.pstyle('z-index-compare');\n    if (style.value === 'auto') {\n      return ele.isNode() ? 1 : 0;\n    }\n    // 'manual'\n    return 0;\n  }\n  var eleDiff = getEleDepth(a) - getEleDepth(b);\n  if (eleDiff !== 0) {\n    return eleDiff;\n  }\n  var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;\n  if (zDiff !== 0) {\n    return zDiff;\n  }\n  // compare indices in the core (order added to graph w/ last on top)\n  return a.poolIndex() - b.poolIndex();\n};\n\nvar elesfn$6 = {\n  forEach: function forEach(fn, thisArg) {\n    if (fn$6(fn)) {\n      var N = this.length;\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        if (ret === false) {\n          break;\n        } // exit each early on return false\n      }\n    }\n    return this;\n  },\n  toArray: function toArray() {\n    var array = [];\n    for (var i = 0; i < this.length; i++) {\n      array.push(this[i]);\n    }\n    return array;\n  },\n  slice: function slice(start, end) {\n    var array = [];\n    var thisSize = this.length;\n    if (end == null) {\n      end = thisSize;\n    }\n    if (start == null) {\n      start = 0;\n    }\n    if (start < 0) {\n      start = thisSize + start;\n    }\n    if (end < 0) {\n      end = thisSize + end;\n    }\n    for (var i = start; i >= 0 && i < end && i < thisSize; i++) {\n      array.push(this[i]);\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    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    if (!ele) {\n      return undefined;\n    }\n\n    // let cy = ele.cy();\n    var _p = ele._private;\n    var group = _p.group;\n    if (group === 'nodes') {\n      var depth = _p.data.parent ? ele.parents().size() : 0;\n      if (!ele.isParent()) {\n        return MAX_INT$1 - 1; // childless nodes always on top\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};\nelesfn$6.each = elesfn$6.forEach;\nvar defineSymbolIterator = function defineSymbolIterator() {\n  var typeofUndef = \"undefined\" ;\n  var isIteratorSupported = (typeof Symbol === \"undefined\" ? \"undefined\" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef;\n  if (isIteratorSupported) {\n    elesfn$6[Symbol.iterator] = function () {\n      var _this = this;\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          return entry;\n        }\n      }, Symbol.iterator, function () {\n        return this;\n      });\n    };\n  }\n};\ndefineSymbolIterator();\n\nvar getLayoutDimensionOptions = defaults$g({\n  nodeDimensionsIncludeLabels: false\n});\nvar 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    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    }\n\n    // sanitise the dimensions for external layouts (avoid division by zero)\n    if (dims.w === 0 || dims.h === 0) {\n      dims.w = dims.h = 1;\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    var getMemoizeKey = function getMemoizeKey(node) {\n      return node.id();\n    };\n    var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function\n\n    layout.emit({\n      type: 'layoutstart',\n      layout: layout\n    });\n    layout.animations = [];\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    var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;\n    var spacingBb = function spacingBb() {\n      if (!useSpacingFactor) {\n        return null;\n      }\n      var bb = makeBoundingBox();\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      return bb;\n    };\n    var bb = spacingBb();\n    var getFinalPos = memoize(function (node, i) {\n      var newPos = fnMem(node, i);\n      if (useSpacingFactor) {\n        var spacing = Math.abs(options.spacingFactor);\n        newPos = calculateSpacing(spacing, bb, newPos);\n      }\n      if (options.transform != null) {\n        newPos = options.transform(node, newPos);\n      }\n      return newPos;\n    }, getMemoizeKey);\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        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      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      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      if (options.fit) {\n        cy.fit(options.eles, options.padding);\n      }\n      if (options.zoom != null) {\n        cy.zoom(options.zoom);\n      }\n      if (options.pan) {\n        cy.pan(options.pan);\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    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};\n\n// aliases:\nelesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;\n\nfunction styleCache(key, fn, ele) {\n  var _p = ele._private;\n  var cache = _p.styleCache = _p.styleCache || [];\n  var val;\n  if ((val = cache[key]) != null) {\n    return val;\n  } else {\n    val = cache[key] = fn(ele);\n    return val;\n  }\n}\nfunction cacheStyleFunction(key, fn) {\n  key = hashString(key);\n  return function cachedStyleFunction(ele) {\n    return styleCache(key, fn, ele);\n  };\n}\nfunction cachePrototypeStyleFunction(key, fn) {\n  key = hashString(key);\n  var selfFn = function selfFn(ele) {\n    return fn.call(ele);\n  };\n  return function cachedPrototypeStyleFunction() {\n    var ele = this[0];\n    if (ele) {\n      return styleCache(key, selfFn, ele);\n    }\n  };\n}\nvar elesfn$4 = {\n  recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {\n    var cy = this.cy();\n    var renderer = cy.renderer();\n    var styleEnabled = cy.styleEnabled();\n    if (renderer && styleEnabled) {\n      renderer.recalculateRenderedStyle(this, useCache);\n    }\n    return this;\n  },\n  dirtyStyleCache: function dirtyStyleCache() {\n    var cy = this.cy();\n    var dirty = function dirty(ele) {\n      return ele._private.styleCache = null;\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    return this;\n  },\n  // fully updates (recalculates) the style for the elements\n  updateStyle: function updateStyle(notifyRenderer) {\n    var cy = this._private.cy;\n    if (!cy.styleEnabled()) {\n      return this;\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    var hasCompounds = cy.hasCompoundNodes();\n    var updatedEles = this;\n    notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;\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    }\n\n    // let changedEles = style.apply( updatedEles );\n    var changedEles = updatedEles;\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    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    if (!cy.styleEnabled()) {\n      return;\n    }\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\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    if (!cy.styleEnabled()) {\n      return;\n    }\n    if (ele) {\n      // this.cleanStyle();\n\n      // Inline the important part of cleanStyle(), for raw performance\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      var overriddenStyle = ele._private.style[property];\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    if (!ele.cy().styleEnabled()) {\n      return;\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    if (!ele.cy().styleEnabled()) {\n      return;\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    if (!cy.styleEnabled()) {\n      return this;\n    }\n    var ele = this[0];\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    if (!cy.styleEnabled()) {\n      return this;\n    }\n    var updateTransitions = false;\n    var style = cy.style();\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        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      if (_ele) {\n        return style.getRawStyle(_ele);\n      } else {\n        // empty collection => can't get any value\n        return;\n      }\n    }\n    return this; // chaining\n  },\n  removeStyle: function removeStyle(names) {\n    var cy = this.cy();\n    if (!cy.styleEnabled()) {\n      return this;\n    }\n    var updateTransitions = false;\n    var style = cy.style();\n    var eles = this;\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      for (var _i = 0; _i < eles.length; _i++) {\n        var _ele2 = eles[_i];\n        style.removeBypasses(_ele2, names, updateTransitions);\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    if (!cy.styleEnabled()) {\n      return 1;\n    }\n    var hasCompoundNodes = cy.hasCompoundNodes();\n    var ele = this[0];\n    if (ele) {\n      var _p = ele._private;\n      var parentOpacity = ele.pstyle('opacity').value;\n      if (!hasCompoundNodes) {\n        return parentOpacity;\n      }\n      var parents = !_p.data.parent ? null : ele.parents();\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      return parentOpacity;\n    }\n  },\n  transparent: function transparent() {\n    var cy = this.cy();\n    if (!cy.styleEnabled()) {\n      return false;\n    }\n    var ele = this[0];\n    var hasCompoundNodes = ele.cy().hasCompoundNodes();\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    if (!cy.styleEnabled()) {\n      return false;\n    }\n    var ele = this[0];\n    return ele._private.backgrounding ? true : false;\n  }\n};\nfunction checkCompound(ele, parentOk) {\n  var _p = ele._private;\n  var parents = _p.data.parent ? ele.parents() : null;\n  if (parents) {\n    for (var i = 0; i < parents.length; i++) {\n      var parent = parents[i];\n      if (!parentOk(parent)) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\nfunction 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    if (!cy.styleEnabled()) {\n      return true;\n    }\n    var ele = this[0];\n    var hasCompoundNodes = cy.hasCompoundNodes();\n    if (ele) {\n      var _p = ele._private;\n      if (!ok(ele)) {\n        return false;\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}\nvar eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {\n  return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);\n});\nelesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({\n  ok: eleTakesUpSpace\n}));\nvar eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {\n  return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);\n});\nvar parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {\n  return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);\n});\nelesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({\n  ok: eleInteractive,\n  parentOk: parentInteractive,\n  edgeOkViaNode: eleTakesUpSpace\n}));\nelesfn$4.noninteractive = function () {\n  var ele = this[0];\n  if (ele) {\n    return !ele.interactive();\n  }\n};\nvar eleVisible = cacheStyleFunction('eleVisible', function (ele) {\n  return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);\n});\nvar edgeVisibleViaNode = eleTakesUpSpace;\nelesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({\n  ok: eleVisible,\n  edgeOkViaNode: edgeVisibleViaNode\n}));\nelesfn$4.hidden = function () {\n  var ele = this[0];\n  if (ele) {\n    return !ele.visible();\n  }\n};\nelesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {\n  if (!this.cy().styleEnabled()) {\n    return false;\n  }\n  return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();\n});\nelesfn$4.bypass = elesfn$4.css = elesfn$4.style;\nelesfn$4.renderedCss = elesfn$4.renderedStyle;\nelesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;\nelesfn$4.pstyle = elesfn$4.parsedStyle;\n\nvar elesfn$3 = {};\nfunction defineSwitchFunction(params) {\n  return function () {\n    var args = arguments;\n    var changedEles = [];\n\n    // e.g. cy.nodes().select( data, handler )\n    if (args.length === 2) {\n      var data = args[0];\n      var handler = args[1];\n      this.on(params.event, data, handler);\n    }\n\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    }\n\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      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        if (params.overrideAble) {\n          var overrideAble = params.overrideAble(ele);\n          if (overrideAble !== undefined) {\n            able = overrideAble;\n            if (!overrideAble) {\n              return this;\n            } // to save cycles assume not able for all on override\n          }\n        }\n        if (able) {\n          ele._private[params.field] = params.value;\n          if (changed) {\n            changedEles.push(ele);\n          }\n        }\n      }\n      var changedColl = this.spawn(changedEles);\n      changedColl.updateStyle(); // change of state => possible change of style\n      changedColl.emit(params.event);\n      if (addlEvents) {\n        changedColl.emit(addlEvents);\n      }\n    }\n    return this;\n  };\n}\nfunction defineSwitchSet(params) {\n  elesfn$3[params.field] = function () {\n    var ele = this[0];\n    if (ele) {\n      if (params.overrideField) {\n        var val = params.overrideField(ele);\n        if (val !== undefined) {\n          return val;\n        }\n      }\n      return ele._private[params.field];\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}\ndefineSwitchSet({\n  field: 'locked',\n  overrideField: function overrideField(ele) {\n    return ele.cy().autolock() ? true : undefined;\n  },\n  on: 'lock',\n  off: 'unlock'\n});\ndefineSwitchSet({\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});\ndefineSwitchSet({\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});\ndefineSwitchSet({\n  field: 'selectable',\n  overrideField: function overrideField(ele) {\n    return ele.cy().autounselectify() ? false : undefined;\n  },\n  on: 'selectify',\n  off: 'unselectify'\n});\nelesfn$3.deselect = elesfn$3.unselect;\nelesfn$3.grabbed = function () {\n  var ele = this[0];\n  if (ele) {\n    return ele._private.grabbed;\n  }\n};\ndefineSwitchSet({\n  field: 'active',\n  on: 'activate',\n  off: 'unactivate'\n});\ndefineSwitchSet({\n  field: 'pannable',\n  on: 'panify',\n  off: 'unpanify'\n});\nelesfn$3.inactive = function () {\n  var ele = this[0];\n  if (ele) {\n    return !ele._private.active;\n  }\n};\n\nvar elesfn$2 = {};\n\n// DAG functions\n////////////////\n\nvar defineDagExtremity = function defineDagExtremity(params) {\n  return function dagExtremityImpl(selector) {\n    var eles = this;\n    var ret = [];\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      if (!ele.isNode()) {\n        continue;\n      }\n      var disqualified = false;\n      var edges = ele.connectedEdges();\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        if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {\n          disqualified = true;\n          break;\n        }\n      }\n      if (!disqualified) {\n        ret.push(ele);\n      }\n    }\n    return this.spawn(ret, true).filter(selector);\n  };\n};\nvar defineDagOneHop = function defineDagOneHop(params) {\n  return function (selector) {\n    var eles = this;\n    var oEles = [];\n    for (var i = 0; i < eles.length; i++) {\n      var ele = eles[i];\n      if (!ele.isNode()) {\n        continue;\n      }\n      var edges = ele.connectedEdges();\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        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    return this.spawn(oEles, true).filter(selector);\n  };\n};\nvar defineDagAllHops = function defineDagAllHops(params) {\n  return function (selector) {\n    var eles = this;\n    var sEles = [];\n    var sElesIds = {};\n    for (;;) {\n      var next = params.outgoing ? eles.outgoers() : eles.incomers();\n      if (next.length === 0) {\n        break;\n      } // done if none left\n\n      var newNext = false;\n      for (var i = 0; i < next.length; i++) {\n        var n = next[i];\n        var nid = n.id();\n        if (!sElesIds[nid]) {\n          sElesIds[nid] = true;\n          sEles.push(n);\n          newNext = true;\n        }\n      }\n      if (!newNext) {\n        break;\n      } // done if touched all outgoers already\n\n      eles = next;\n    }\n    return this.spawn(sEles, true).filter(selector);\n  };\n};\nelesfn$2.clearTraversalCache = function () {\n  for (var i = 0; i < this.length; i++) {\n    this[i]._private.traversalCache = null;\n  }\n};\nextend(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    })\n});\n\n// Neighbourhood functions\n//////////////////////////\n\nextend(elesfn$2, {\n  neighborhood: cache(function (selector) {\n    var elements = [];\n    var nodes = this.nodes();\n    for (var i = 0; i < nodes.length; i++) {\n      // for all nodes\n      var node = nodes[i];\n      var connectedEdges = node.connectedEdges();\n\n      // for each connected edge, add the edge and the other node\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;\n\n        // need check in case of loop\n        if (otherNode.length > 0) {\n          elements.push(otherNode[0]); // add node 1 hop away\n        }\n\n        // add connected edge\n        elements.push(edge[0]);\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});\n\n// aliases\nelesfn$2.neighbourhood = elesfn$2.neighborhood;\nelesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;\nelesfn$2.openNeighbourhood = elesfn$2.openNeighborhood;\n\n// Edge functions\n/////////////////\n\nextend(elesfn$2, {\n  source: cache(function sourceImpl(selector) {\n    var ele = this[0];\n    var src;\n    if (ele) {\n      src = ele._private.source || ele.cy().collection();\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    if (ele) {\n      tgt = ele._private.target || ele.cy().collection();\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});\nfunction defineSourceFunction(params) {\n  return function sourceImpl(selector) {\n    var sources = [];\n    for (var i = 0; i < this.length; i++) {\n      var ele = this[i];\n      var src = ele._private[params.attr];\n      if (src) {\n        sources.push(src);\n      }\n    }\n    return this.spawn(sources, true).filter(selector);\n  };\n}\nextend(elesfn$2, {\n  edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),\n  edgesTo: cache(defineEdgesWithFunction({\n    thisIsSrc: true\n  }), 'edgesTo')\n});\nfunction defineEdgesWithFunction(params) {\n  return function edgesWithImpl(otherNodes) {\n    var elements = [];\n    var cy = this._private.cy;\n    var p = params || {};\n\n    // get elements if a selector is specified\n    if (string(otherNodes)) {\n      otherNodes = cy.$(otherNodes);\n    }\n    for (var h = 0; h < otherNodes.length; h++) {\n      var edges = otherNodes[h]._private.edges;\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        if (!edgeConnectsThisAndOther) {\n          continue;\n        }\n        if (p.thisIsSrc || p.thisIsTgt) {\n          if (p.thisIsSrc && !thisToOther) {\n            continue;\n          }\n          if (p.thisIsTgt && !otherToThis) {\n            continue;\n          }\n        }\n        elements.push(edge);\n      }\n    }\n    return this.spawn(elements, true);\n  };\n}\nextend(elesfn$2, {\n  connectedEdges: cache(function (selector) {\n    var retEles = [];\n    var eles = this;\n    for (var i = 0; i < eles.length; i++) {\n      var node = eles[i];\n      if (!node.isNode()) {\n        continue;\n      }\n      var edges = node._private.edges;\n      for (var j = 0; j < edges.length; j++) {\n        var edge = edges[j];\n        retEles.push(edge);\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    for (var i = 0; i < eles.length; i++) {\n      var edge = eles[i];\n      if (!edge.isEdge()) {\n        continue;\n      }\n      retEles.push(edge.source()[0]);\n      retEles.push(edge.target()[0]);\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});\nfunction 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;\n\n    // look at all the edges in the collection\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;\n\n      // look at edges connected to the src node of this edge\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        if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {\n          elements.push(edge2);\n        }\n      }\n    }\n    return this.spawn(elements, true).filter(selector);\n  };\n}\n\n// Misc functions\n/////////////////\n\nextend(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    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    var visitInComponent = function visitInComponent(node, component) {\n      visited.merge(node);\n      unvisited.unmerge(node);\n      component.merge(node);\n    };\n    if (unvisited.empty()) {\n      return self.spawn();\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    do {\n      _loop();\n    } while (unvisited.length > 0);\n    return components;\n  },\n  component: function component() {\n    var ele = this[0];\n    return ele.cy().mutableElements().components(ele)[0];\n  }\n});\nelesfn$2.componentsOf = elesfn$2.components;\n\n// represents a set of nodes, edges, or both together\nvar 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  if (cy === undefined) {\n    error('A collection must have a reference to the core');\n    return;\n  }\n  var map = new Map$1();\n  var createdElements = false;\n  if (!elements) {\n    elements = [];\n  } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {\n    createdElements = true;\n\n    // make elements from json and restore all at once later\n    var eles = [];\n    var elesIds = new Set$1();\n    for (var i = 0, l = elements.length; i < l; i++) {\n      var json = elements[i];\n      if (json.data == null) {\n        json.data = {};\n      }\n      var _data = json.data;\n\n      // make sure newly created elements have valid ids\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      var ele = new Element(cy, json, false);\n      eles.push(ele);\n      elesIds.add(_data.id);\n    }\n    elements = eles;\n  }\n  this.length = 0;\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    if (element$1 == null) {\n      continue;\n    }\n    var id = element$1._private.data.id;\n    if (!unique || !map.has(id)) {\n      if (unique) {\n        map.set(id, {\n          index: this.length,\n          ele: element$1\n        });\n      }\n      this[this.length] = element$1;\n      this.length++;\n    }\n  }\n  this._private = {\n    eles: this,\n    cy: cy,\n    get map() {\n      if (this.lazyMap == null) {\n        this.rebuildMap();\n      }\n      return this.lazyMap;\n    },\n    set map(m) {\n      this.lazyMap = m;\n    },\n    rebuildMap: function rebuildMap() {\n      var m = this.lazyMap = new Map$1();\n      var eles = this.eles;\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  if (unique) {\n    this._private.map = map;\n  }\n\n  // restore the elements if we created them from json\n  if (createdElements && !removed) {\n    this.restore();\n  }\n};\n\n// Functions\n////////////////////////////////////////////////////////////////////////////////////////////////////\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\nvar elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);\nelesfn$1.instanceString = function () {\n  return 'collection';\n};\nelesfn$1.spawn = function (eles, unique) {\n  return new Collection(this.cy(), eles, unique);\n};\nelesfn$1.spawnSelf = function () {\n  return this.spawn(this);\n};\nelesfn$1.cy = function () {\n  return this._private.cy;\n};\nelesfn$1.renderer = function () {\n  return this._private.cy.renderer();\n};\nelesfn$1.element = function () {\n  return this[0];\n};\nelesfn$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};\nelesfn$1.unique = function () {\n  return new Collection(this._private.cy, this, true);\n};\nelesfn$1.hasElementWithId = function (id) {\n  id = '' + id; // id must be string\n\n  return this._private.map.has(id);\n};\nelesfn$1.getElementById = function (id) {\n  id = '' + id; // id must be string\n\n  var cy = this._private.cy;\n  var entry = this._private.map.get(id);\n  return entry ? entry.ele : new Collection(cy); // get ele or empty collection\n};\nelesfn$1.$id = elesfn$1.getElementById;\nelesfn$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};\nelesfn$1.indexOf = function (ele) {\n  var id = ele[0]._private.data.id;\n  return this._private.map.get(id).index;\n};\nelesfn$1.indexOfId = function (id) {\n  id = '' + id; // id must be string\n\n  return this._private.map.get(id).index;\n};\nelesfn$1.json = function (obj) {\n  var ele = this.element();\n  var cy = this.cy();\n  if (ele == null && obj) {\n    return this;\n  } // can't set to no eles\n\n  if (ele == null) {\n    return undefined;\n  } // can't get from no eles\n\n  var p = ele._private;\n  if (plainObject(obj)) {\n    // set\n\n    cy.startBatch();\n    if (obj.data) {\n      ele.data(obj.data);\n      var _data2 = p.data;\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        if (src != null && src != _data2.source) {\n          spec.source = '' + src; // id must be string\n          move = true;\n        }\n        if (tgt != null && tgt != _data2.target) {\n          spec.target = '' + tgt; // id must be string\n          move = true;\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        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          if (parent != null) {\n            parent = '' + parent; // id must be string\n          }\n          ele = ele.move({\n            parent: parent\n          });\n        }\n      }\n    }\n    if (obj.position) {\n      ele.position(obj.position);\n    }\n\n    // ignore group -- immutable\n\n    var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {\n      var obj_k = obj[k];\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    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    if (obj.classes != null) {\n      ele.classes(obj.classes);\n    }\n    cy.endBatch();\n    return this;\n  } else if (obj === undefined) {\n    // get\n\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};\nelesfn$1.jsons = function () {\n  var jsons = [];\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  return jsons;\n};\nelesfn$1.clone = function () {\n  var cy = this.cy();\n  var elesArr = [];\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  return new Collection(cy, elesArr);\n};\nelesfn$1.copy = elesfn$1.clone;\nelesfn$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;\n\n  // create arrays of nodes and edges, since we need to\n  // restore the nodes first\n  var nodes = [];\n  var edges = [];\n  var elements;\n  for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {\n    var ele = self[_i3];\n    if (addToPool && !ele.removed()) {\n      // don't need to handle this ele\n      continue;\n    }\n\n    // keep nodes first in the array and edges after\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  elements = nodes.concat(edges);\n  var i;\n  var removeFromElements = function removeFromElements() {\n    elements.splice(i, 1);\n    i--;\n  };\n\n  // now, restore each element\n  for (i = 0; i < elements.length; i++) {\n    var _ele2 = elements[i];\n    var _private = _ele2._private;\n    var _data3 = _private.data;\n\n    // the traversal cache should start fresh when ele is added\n    _ele2.clearTraversalCache();\n\n    // set id and validate\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 + '`');\n\n      // can't create element if it has empty string as id or non-string id\n      removeFromElements();\n      continue;\n    } else if (cy.hasElementWithId(_data3.id)) {\n      error('Can not create second element with ID `' + _data3.id + '`');\n\n      // can't create element if one already has that id\n      removeFromElements();\n      continue;\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;\n\n      // make sure the nodes have a defined position\n\n      if (pos.x == null) {\n        pos.x = 0;\n      }\n      if (pos.y == null) {\n        pos.y = 0;\n      }\n    }\n    if (_ele2.isEdge()) {\n      // extra checks for edges\n\n      var edge = _ele2;\n      var fields = ['source', 'target'];\n      var fieldsLength = fields.length;\n      var badSourceOrTarget = false;\n      for (var j = 0; j < fieldsLength; j++) {\n        var field = fields[j];\n        var val = _data3[field];\n        if (number$1(val)) {\n          val = _data3[field] = '' + _data3[field]; // now string\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      if (badSourceOrTarget) {\n        removeFromElements();\n        continue;\n      } // can't create this\n\n      var src = cy.getElementById(_data3.source);\n      var tgt = cy.getElementById(_data3.target);\n\n      // only one edge in node if loop\n      if (src.same(tgt)) {\n        src._private.edges.push(edge);\n      } else {\n        src._private.edges.push(edge);\n        tgt._private.edges.push(edge);\n      }\n      edge._private.source = src;\n      edge._private.target = tgt;\n    } // if is edge\n\n    // create mock ids / indexes maps for element so it can be used like collections\n    _private.map = new Map$1();\n    _private.map.set(id, {\n      ele: _ele2,\n      index: 0\n    });\n    _private.removed = false;\n    if (addToPool) {\n      cy.addToPool(_ele2);\n    }\n  } // for each element\n\n  // do compound node sanity checks\n  for (var _i4 = 0; _i4 < nodes.length; _i4++) {\n    // each node\n    var node = nodes[_i4];\n    var _data4 = node._private.data;\n    if (number$1(_data4.parent)) {\n      // then automake string\n      _data4.parent = '' + _data4.parent;\n    }\n    var parentId = _data4.parent;\n    var specifiedParent = parentId != null;\n    if (specifiedParent || node._private.parent) {\n      var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);\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        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\n            // exit or we loop forever\n            break;\n          }\n          ancestor = ancestor.parent();\n        }\n        if (!selfAsParent) {\n          // connect with children\n          parent[0]._private.children.push(node);\n          node._private.parent = parent[0];\n\n          // let the core know we have a compound graph\n          cy_p.hasCompoundNodes = true;\n        }\n      } // else\n    } // if specified parent\n  } // for each node\n\n  if (elements.length > 0) {\n    var restored = elements.length === self.length ? self : new Collection(cy, elements);\n    for (var _i5 = 0; _i5 < restored.length; _i5++) {\n      var _ele3 = restored[_i5];\n      if (_ele3.isNode()) {\n        continue;\n      }\n\n      // adding an edge invalidates the traversal caches for the parallel edges\n      _ele3.parallelEdges().clearTraversalCache();\n\n      // adding an edge invalidates the traversal cache for the connected nodes\n      _ele3.source().clearTraversalCache();\n      _ele3.target().clearTraversalCache();\n    }\n    var toUpdateStyle;\n    if (cy_p.hasCompoundNodes) {\n      toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());\n    } else {\n      toUpdateStyle = restored;\n    }\n    toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);\n    if (notifyRenderer) {\n      restored.emitAndNotify('add');\n    } else if (addToPool) {\n      restored.emit('add');\n    }\n  }\n  return self; // chainability\n};\nelesfn$1.removed = function () {\n  var ele = this[0];\n  return ele && ele._private.removed;\n};\nelesfn$1.inside = function () {\n  var ele = this[0];\n  return ele && !ele._private.removed;\n};\nelesfn$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;\n\n  // add connected edges\n  function addConnectedEdges(node) {\n    var edges = node._private.edges;\n    for (var i = 0; i < edges.length; i++) {\n      add(edges[i]);\n    }\n  }\n\n  // add descendant nodes\n  function addChildren(node) {\n    var children = node._private.children;\n    for (var i = 0; i < children.length; i++) {\n      add(children[i]);\n    }\n  }\n  function add(ele) {\n    var alreadyAdded = elesToRemoveIds[ele.id()];\n    if (removeFromPool && ele.removed() || alreadyAdded) {\n      return;\n    } else {\n      elesToRemoveIds[ele.id()] = true;\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  }\n\n  // make the list of elements to remove\n  // (may be removing more than specified due to connected edges etc)\n\n  for (var i = 0, l = self.length; i < l; i++) {\n    var ele = self[i];\n    add(ele);\n  }\n  function removeEdgeRef(node, edge) {\n    var connectedEdges = node._private.edges;\n    removeFromArray(connectedEdges, edge);\n\n    // removing an edges invalidates the traversal cache for its nodes\n    node.clearTraversalCache();\n  }\n  function removeParallelRef(pllEdge) {\n    // removing an edge invalidates the traversal caches for the parallel edges\n    pllEdge.clearTraversalCache();\n  }\n  var alteredParents = [];\n  alteredParents.ids = {};\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  self.dirtyCompoundBoundsCache();\n  if (removeFromPool) {\n    cy.removeFromPool(elesToRemove); // remove from core pool\n  }\n  for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {\n    var _ele4 = elesToRemove[_i6];\n    if (_ele4.isEdge()) {\n      // remove references to this edge in its connected nodes\n      var src = _ele4.source()[0];\n      var tgt = _ele4.target()[0];\n      removeEdgeRef(src, _ele4);\n      removeEdgeRef(tgt, _ele4);\n      var pllEdges = _ele4.parallelEdges();\n      for (var j = 0; j < pllEdges.length; j++) {\n        var pllEdge = pllEdges[j];\n        removeParallelRef(pllEdge);\n        if (pllEdge.isBundledBezier()) {\n          pllEdge.dirtyBoundingBoxCache();\n        }\n      }\n    } else {\n      // remove reference to parent\n      var parent = _ele4.parent();\n      if (parent.length !== 0) {\n        removeChildRef(parent, _ele4);\n      }\n    }\n    if (removeFromPool) {\n      // mark as removed\n      _ele4._private.removed = true;\n    }\n  }\n\n  // check to see if we have a compound graph or not\n  var elesStillInside = cy._private.elements;\n  cy._private.hasCompoundNodes = false;\n  for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {\n    var _ele5 = elesStillInside[_i7];\n    if (_ele5.isParent()) {\n      cy._private.hasCompoundNodes = true;\n      break;\n    }\n  }\n  var removedElements = new Collection(this.cy(), elesToRemove);\n  if (removedElements.size() > 0) {\n    // must manually notify since trigger won't do this automatically once removed\n\n    if (notifyRenderer) {\n      removedElements.emitAndNotify('remove');\n    } else if (removeFromPool) {\n      removedElements.emit('remove');\n    }\n  }\n\n  // the parents who were modified by the removal need their style updated\n  for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {\n    var _ele6 = alteredParents[_i8];\n    if (!removeFromPool || !_ele6.removed()) {\n      _ele6.updateStyle();\n    }\n  }\n  return removedElements;\n};\nelesfn$1.move = function (struct) {\n  var cy = this._private.cy;\n  var eles = this;\n\n  // 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  var notifyRenderer = false;\n  var modifyPool = false;\n  var toString = function toString(id) {\n    return id == null ? id : '' + id;\n  }; // id must be string\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    if (srcExists || tgtExists) {\n      cy.batch(function () {\n        // avoid duplicate style updates\n        eles.remove(notifyRenderer, modifyPool); // clean up refs etc.\n        eles.emitAndNotify('moveout');\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          var _data5 = ele._private.data;\n          if (ele.isEdge()) {\n            if (srcExists) {\n              _data5.source = srcId;\n            }\n            if (tgtExists) {\n              _data5.target = tgtId;\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    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        updated.emitAndNotify('moveout');\n        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          var _data6 = ele._private.data;\n          if (ele.isNode()) {\n            _data6.parent = pidToAssign;\n          }\n        }\n        updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.\n      });\n      eles.emitAndNotify('move');\n    }\n  }\n  return this;\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\nvar corefn$9 = {\n  add: function add(opts) {\n    var elements;\n    var cy = this;\n\n    // add the elements\n    if (elementOrCollection(opts)) {\n      var eles = opts;\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        for (var i = 0; i < eles.length; i++) {\n          var ele = eles[i];\n          jsons.push(ele.json());\n        }\n        elements = new Collection(cy, jsons);\n      }\n    }\n\n    // specify an array of options\n    else if (array(opts)) {\n      var _jsons = opts;\n      elements = new Collection(cy, _jsons);\n    }\n\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      for (var _i = 0, il = grs.length; _i < il; _i++) {\n        var group = grs[_i];\n        var elesArray = elesByGroup[group];\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            _jsons2.push(json);\n          }\n        }\n      }\n      elements = new Collection(cy, _jsons2);\n    }\n\n    // specify options for one element\n    else {\n      var _json = opts;\n      elements = new Element(cy, _json).collection();\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    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 */\nfunction 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\n  /* Must contain four arguments. */\n  if (arguments.length !== 4) {\n    return false;\n  }\n\n  /* Arguments must be numbers. */\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\n  /* X values must be in the [0, 1] range. */\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  function A(aA1, aA2) {\n    return 1.0 - 3.0 * aA2 + 3.0 * aA1;\n  }\n  function B(aA1, aA2) {\n    return 3.0 * aA2 - 6.0 * aA1;\n  }\n  function C(aA1) {\n    return 3.0 * aA1;\n  }\n  function calcBezier(aT, aA1, aA2) {\n    return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;\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  function newtonRaphsonIterate(aX, aGuessT) {\n    for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {\n      var currentSlope = getSlope(aGuessT, mX1, mX2);\n      if (currentSlope === 0.0) {\n        return aGuessT;\n      }\n      var currentX = calcBezier(aGuessT, mX1, mX2) - aX;\n      aGuessT -= currentX / currentSlope;\n    }\n    return aGuessT;\n  }\n  function calcSampleValues() {\n    for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {\n      mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);\n    }\n  }\n  function binarySubdivide(aX, aA, aB) {\n    var currentX,\n      currentT,\n      i = 0;\n    do {\n      currentT = aA + (aB - aA) / 2.0;\n      currentX = calcBezier(currentT, mX1, mX2) - aX;\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    return currentT;\n  }\n  function getTForX(aX) {\n    var intervalStart = 0.0,\n      currentSample = 1,\n      lastSample = kSplineTableSize - 1;\n    for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {\n      intervalStart += kSampleStepSize;\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    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  var _precomputed = false;\n  function precompute() {\n    _precomputed = true;\n    if (mX1 !== mY1 || mX2 !== mY2) {\n      calcSampleValues();\n    }\n  }\n  var f = function f(aX) {\n    if (!_precomputed) {\n      precompute();\n    }\n    if (mX1 === mY1 && mX2 === mY2) {\n      return aX;\n    }\n    if (aX === 0) {\n      return 0;\n    }\n    if (aX === 1) {\n      return 1;\n    }\n    return calcBezier(getTForX(aX), mY1, mY2);\n  };\n  f.getControlPoints = function () {\n    return [{\n      x: mX1,\n      y: mY1\n    }, {\n      x: mX2,\n      y: mY2\n    }];\n  };\n  var str = \"generateBezier(\" + [mX1, mY1, mX2, mY2] + \")\";\n  f.toString = function () {\n    return str;\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/* 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. */\nvar generateSpringRK4 = function () {\n  function springAccelerationForState(state) {\n    return -state.tension * state.x - state.friction * state.v;\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  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  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\n    /* Calculate the actual time it takes for this animation to complete with the provided conditions. */\n    if (have_duration) {\n      /* Run the simulation without a duration. */\n      time_lapsed = springRK4Factory(tension, friction);\n      /* Compute the adjusted time delta. */\n      dt = time_lapsed / duration * DT;\n    } else {\n      dt = DT;\n    }\n    for (;;) {\n      /* Next/step function .*/\n      last_state = springIntegrateState(last_state || initState, dt);\n      /* Store the position. */\n      path.push(1 + last_state.x);\n      time_lapsed += 16;\n      /* If the change threshold is reached, break. */\n      if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {\n        break;\n      }\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    return !have_duration ? time_lapsed : function (percentComplete) {\n      return path[percentComplete * (path.length - 1) | 0];\n    };\n  };\n}();\n\nvar 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};\nvar 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\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    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\nfunction getEasedValue(type, start, end, percent, easingFn) {\n  if (percent === 1) {\n    return end;\n  }\n  if (start === end) {\n    return end;\n  }\n  var val = easingFn(start, end, percent);\n  if (type == null) {\n    return val;\n  }\n  if (type.roundValue || type.color) {\n    val = Math.round(val);\n  }\n  if (type.min !== undefined) {\n    val = Math.max(val, type.min);\n  }\n  if (type.max !== undefined) {\n    val = Math.min(val, type.max);\n  }\n  return val;\n}\nfunction 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}\nfunction ease(startProp, endProp, percent, easingFn, propSpec) {\n  var type = propSpec != null ? propSpec.type : null;\n  if (percent < 0) {\n    percent = 0;\n  } else if (percent > 1) {\n    percent = 1;\n  }\n  var start = getValue(startProp, propSpec);\n  var end = getValue(endProp, propSpec);\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    for (var i = 0; i < end.length; i++) {\n      var si = start[i];\n      var ei = end[i];\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    return easedArr;\n  }\n  return undefined;\n}\n\nfunction 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  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      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      var name, args;\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      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        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  var easing = ani_p.easingImpl;\n  var percent;\n  if (ani_p.duration === 0) {\n    percent = 1;\n  } else {\n    percent = (now - startTime) / ani_p.duration;\n  }\n  if (ani_p.applying) {\n    percent = ani_p.progress;\n  }\n  if (percent < 0) {\n    percent = 0;\n  } else if (percent > 1) {\n    percent = 1;\n  }\n  if (ani_p.delay == null) {\n    // then update\n\n    var startPos = ani_p.startPosition;\n    var endPos = ani_p.position;\n    if (endPos && isEles && !self.locked()) {\n      var newPos = {};\n      if (valid(startPos.x, endPos.x)) {\n        newPos.x = ease(startPos.x, endPos.x, percent, easing);\n      }\n      if (valid(startPos.y, endPos.y)) {\n        newPos.y = ease(startPos.y, endPos.y, percent, easing);\n      }\n      self.position(newPos);\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    if (animatingPan) {\n      if (valid(startPan.x, endPan.x)) {\n        pan.x = ease(startPan.x, endPan.x, percent, easing);\n      }\n      if (valid(startPan.y, endPan.y)) {\n        pan.y = ease(startPan.y, endPan.y, percent, easing);\n      }\n      self.emit('pan');\n    }\n    var startZoom = ani_p.startZoom;\n    var endZoom = ani_p.zoom;\n    var animatingZoom = endZoom != null && isCore;\n    if (animatingZoom) {\n      if (valid(startZoom, endZoom)) {\n        _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);\n      }\n      self.emit('zoom');\n    }\n    if (animatingPan || animatingZoom) {\n      self.emit('viewport');\n    }\n    var props = ani_p.style;\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      self.emit('style');\n    } // if\n  }\n  ani_p.progress = percent;\n  return percent;\n}\nfunction valid(start, end) {\n  if (start == null || end == null) {\n    return false;\n  }\n  if (number$1(start) && number$1(end)) {\n    return true;\n  } else if (start && end) {\n    return true;\n  }\n  return false;\n}\n\nfunction 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\nfunction stepAll(now, cy) {\n  var eles = cy._private.aniEles;\n  var doneEles = [];\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;\n\n    // if nothing currently animating, get something from the queue\n    if (current.length === 0) {\n      var next = queue.shift();\n      if (next) {\n        current.push(next);\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      _callbacks.splice(0, _callbacks.length);\n    };\n\n    // step and remove if done\n    for (var i = current.length - 1; i >= 0; i--) {\n      var ani = current[i];\n      var ani_p = ani._private;\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      if (!ani_p.playing && !ani_p.applying) {\n        continue;\n      }\n\n      // an apply() while playing shouldn't do anything\n      if (ani_p.playing && ani_p.applying) {\n        ani_p.applying = false;\n      }\n      if (!ani_p.started) {\n        startAnimation(ele, ani, now);\n      }\n      step$1(ele, ani, now, isCore);\n      if (ani_p.applying) {\n        ani_p.applying = false;\n      }\n      callbacks(ani_p.frames);\n      if (ani_p.step != null) {\n        ani_p.step(now);\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      ranAnis = true;\n    }\n    if (!isCore && current.length === 0 && queue.length === 0) {\n      doneEles.push(ele);\n    }\n    return ranAnis;\n  } // stepElement\n\n  // handle all eles\n  var ranEleAni = false;\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  var ranCoreAni = stepOne(cy, true);\n\n  // notify renderer\n  if (ranEleAni || ranCoreAni) {\n    if (eles.length > 0) {\n      cy.notify('draw', eles);\n    } else {\n      cy.notify('draw');\n    }\n  }\n\n  // remove elements from list of currently animating if its queues are empty\n  eles.unmerge(doneEles);\n  cy.emit('step');\n} // stepAll\n\nvar 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    if (!cy.styleEnabled()) {\n      return;\n    } // save cycles when no style used\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    if (!cy.styleEnabled()) {\n      return;\n    } // save cycles when no style used\n\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    function headlessStep() {\n      if (!cy._private.animationsRunning) {\n        return;\n      }\n      requestAnimationFrame(function animationStep(now) {\n        stepAll(now, cy);\n        headlessStep();\n      });\n    }\n    var renderer = cy.renderer();\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\nvar 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    if (selector != null) {\n      return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);\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};\nvar argSelector = function argSelector(arg) {\n  if (string(arg)) {\n    return new Selector(arg);\n  } else {\n    return arg;\n  }\n};\nvar elesfn = {\n  createEmitter: function createEmitter() {\n    var _p = this._private;\n    if (!_p.emitter) {\n      _p.emitter = new Emitter(emitterOptions, this);\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};\ndefine.eventAliasesOn(elesfn);\n\nvar 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};\ncorefn$7.jpeg = corefn$7.jpg;\n\nvar corefn$6 = {\n  layout: function layout(options) {\n    var cy = this;\n    if (options == null) {\n      error('Layout options must be specified to make a layout');\n      return;\n    }\n    if (options.name == null) {\n      error('A `name` must be specified to make a layout');\n      return;\n    }\n    var name = options.name;\n    var Layout = cy.extension('layout', name);\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    var eles;\n    if (string(options.eles)) {\n      eles = cy.$(options.eles);\n    } else {\n      eles = options.eles != null ? options.eles : cy.$();\n    }\n    var layout = new Layout(extend({}, options, {\n      cy: cy,\n      eles: eles\n    }));\n    return layout;\n  }\n};\ncorefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;\n\nvar corefn$5 = {\n  notify: function notify(eventName, eventEles) {\n    var _p = this._private;\n    if (this.batching()) {\n      _p.batchNotifications = _p.batchNotifications || {};\n      var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();\n      if (eventEles != null) {\n        eles.merge(eventEles);\n      }\n      return; // notifications are disabled during batching\n    }\n    if (!_p.notificationsEnabled) {\n      return;\n    } // exit on disabled\n\n    var renderer = this.renderer();\n\n    // exit if destroy() called on core or renderer in between frames #1499 #1528\n    if (this.destroyed() || !renderer) {\n      return;\n    }\n    renderer.notify(eventName, eventEles);\n  },\n  notifications: function notifications(bool) {\n    var p = this._private;\n    if (bool === undefined) {\n      return p.notificationsEnabled;\n    } else {\n      p.notificationsEnabled = bool ? true : false;\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    if (_p.batchCount == null) {\n      _p.batchCount = 0;\n    }\n    if (_p.batchCount === 0) {\n      _p.batchStyleEles = this.collection();\n      _p.batchNotifications = {};\n    }\n    _p.batchCount++;\n    return this;\n  },\n  endBatch: function endBatch() {\n    var _p = this._private;\n    if (_p.batchCount === 0) {\n      return this;\n    }\n    _p.batchCount--;\n    if (_p.batchCount === 0) {\n      // update style for dirty eles\n      _p.batchStyleEles.updateStyle();\n      var renderer = this.renderer();\n\n      // notify the renderer of queued eles and event types\n      Object.keys(_p.batchNotifications).forEach(function (eventName) {\n        var eles = _p.batchNotifications[eventName];\n        if (eles.empty()) {\n          renderer.notify(eventName);\n        } else {\n          renderer.notify(eventName, eles);\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      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\nvar 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  // webgl options\n  webgl: false,\n  webglDebug: false,\n  webglDebugShowAtlases: false,\n  // defaults good for mobile\n  webglTexSize: 2048,\n  webglTexRows: 36,\n  webglTexRowsNodes: 18,\n  webglBatchSize: 2048,\n  webglTexPerBatch: 14,\n  webglBgColor: [255, 255, 255]\n});\nvar 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    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    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    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    if (domEle) {\n      domEle._cyreg = null;\n      while (domEle.childNodes.length > 0) {\n        domEle.removeChild(domEle.childNodes[0]);\n      }\n    }\n    cy._private.renderer = null; // to be extra safe, remove the ref\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};\ncorefn$4.invalidateDimensions = corefn$4.resize;\n\nvar 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      return new Collection(this, eles, opts.unique, opts.removed);\n    }\n    return new Collection(this);\n  },\n  nodes: function nodes(selector) {\n    var nodes = this.$(function (ele) {\n      return ele.isNode();\n    });\n    if (selector) {\n      return nodes.filter(selector);\n    }\n    return nodes;\n  },\n  edges: function edges(selector) {\n    var edges = this.$(function (ele) {\n      return ele.isEdge();\n    });\n    if (selector) {\n      return edges.filter(selector);\n    }\n    return edges;\n  },\n  // search the graph like jQuery\n  $: function $(selector) {\n    var eles = this._private.elements;\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};\n\n// aliases\ncorefn$3.elements = corefn$3.filter = corefn$3.$;\n\nvar styfn$8 = {};\n\n// keys for style blocks, e.g. ttfftt\nvar TRUE = 't';\nvar FALSE = 'f';\n\n// (potentially expensive calculation)\n// apply the style to the element based on\n// - its bypass\n// - what selectors match it\nstyfn$8.apply = function (eles) {\n  var self = this;\n  var _p = self._private;\n  var cy = _p.cy;\n  var updatedEles = cy.collection();\n  for (var ie = 0; ie < eles.length; ie++) {\n    var ele = eles[ie];\n    var cxtMeta = self.getContextMeta(ele);\n    if (cxtMeta.empty) {\n      continue;\n    }\n    var cxtStyle = self.getContextStyle(cxtMeta);\n    var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);\n    if (ele._private.appliedInitStyle) {\n      self.updateTransitions(ele, app.diffProps);\n    } else {\n      ele._private.appliedInitStyle = true;\n    }\n    var hintsDiff = self.updateStyleHints(ele);\n    if (hintsDiff) {\n      updatedEles.push(ele);\n    }\n  } // for elements\n\n  return updatedEles;\n};\nstyfn$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  if (cachedVal) {\n    return cachedVal;\n  }\n  var diffProps = [];\n  var addedProp = {};\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    if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {\n      var props = undefined;\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      for (var j = 0; j < props.length; j++) {\n        var prop = props[j];\n        var name = prop.name;\n\n        // 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        var laterCxtOverrides = false;\n        for (var k = i + 1; k < self.length; k++) {\n          var laterCxt = self[k];\n          var hasLaterCxt = newCxtKey[k] === TRUE;\n          if (!hasLaterCxt) {\n            continue;\n          } // can't override unless the context is active\n\n          laterCxtOverrides = laterCxt.properties[prop.name] != null;\n          if (laterCxtOverrides) {\n            break;\n          } // exit early as long as one later context overrides\n        }\n        if (!addedProp[name] && !laterCxtOverrides) {\n          addedProp[name] = true;\n          diffProps.push(name);\n        }\n      } // for props\n    } // if\n  } // for contexts\n\n  cache[dualCxtKey] = diffProps;\n  return diffProps;\n};\nstyfn$8.getContextMeta = function (ele) {\n  var self = this;\n  var cxtKey = '';\n  var diffProps;\n  var prevKey = ele._private.styleCxtKey || '';\n\n  // get the cxt key\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  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};\n\n// gets a computed ele style object based on matched contexts\nstyfn$8.getContextStyle = function (cxtMeta) {\n  var cxtKey = cxtMeta.key;\n  var self = this;\n  var cxtStyles = this._private.contextStyles = this._private.contextStyles || {};\n\n  // if already computed style, returned cached copy\n  if (cxtStyles[cxtKey]) {\n    return cxtStyles[cxtKey];\n  }\n  var style = {\n    _private: {\n      key: cxtKey\n    }\n  };\n  for (var i = 0; i < self.length; i++) {\n    var cxt = self[i];\n    var hasCxt = cxtKey[i] === TRUE;\n    if (!hasCxt) {\n      continue;\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  cxtStyles[cxtKey] = style;\n  return style;\n};\nstyfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {\n  var self = this;\n  var diffProps = cxtMeta.diffPropNames;\n  var retDiffProps = {};\n  var types = self.types;\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    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    }\n\n    // save cycles when the context prop doesn't need to be applied\n    if (eleProp === cxtProp) {\n      continue;\n    }\n\n    // save cycles when a mapped context prop doesn't need to be applied\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      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    var retDiffProp = retDiffProps[diffPropName] = {\n      prev: eleProp\n    };\n    self.applyParsedProperty(ele, cxtProp);\n    retDiffProp.next = ele.pstyle(diffPropName);\n    if (retDiffProp.next && retDiffProp.next.bypass) {\n      retDiffProp.next = retDiffProp.next.bypassed;\n    }\n  }\n  return {\n    diffProps: retDiffProps\n  };\n};\nstyfn$8.updateStyleHints = function (ele) {\n  var _p = ele._private;\n  var self = this;\n  var propNames = self.propertyGroupNames;\n  var propGrKeys = self.propertyGroupKeys;\n  var propHash = function propHash(ele, propNames, seedKey) {\n    return self.getPropertiesHash(ele, propNames, seedKey);\n  };\n  var oldStyleKey = _p.styleKey;\n  if (ele.removed()) {\n    return false;\n  }\n  var isNode = _p.group === 'nodes';\n\n  // 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  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  var updateGrKey1 = function updateGrKey1(val, grKey) {\n    return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);\n  };\n  var updateGrKey2 = function updateGrKey2(val, grKey) {\n    return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);\n  };\n  var updateGrKey = function updateGrKey(val, grKey) {\n    updateGrKey1(val, grKey);\n    updateGrKey2(val, grKey);\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  };\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  var N = 2000000000;\n  var cleanNum = function cleanNum(val) {\n    return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;\n  };\n  for (var _i = 0; _i < propNames.length; _i++) {\n    var name = propNames[_i];\n    var parsedProp = overriddenStyles[name];\n    if (parsedProp == null) {\n      continue;\n    }\n    var propInfo = this.properties[name];\n    var type = propInfo.type;\n    var _grKey = propInfo.groupKey;\n    var normalizedNumberVal = undefined;\n    if (propInfo.hashOverride != null) {\n      normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);\n    } else if (parsedProp.pfValue != null) {\n      normalizedNumberVal = parsedProp.pfValue;\n    }\n\n    // might not be a number if it allows enums\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;\n\n    // numbers are cheaper to hash than strings\n    // 1 hash op vs n hash ops (for length n string)\n    if (type.number && haveNum && !type.multiple) {\n      var v = haveNormNum ? normalizedNumberVal : numberVal;\n      updateGrKey(cleanNum(v), _grKey);\n      if (!haveNormNum && units != null) {\n        updateGrKeyWStr(units, _grKey);\n      }\n    } else {\n      updateGrKeyWStr(parsedProp.strValue, _grKey);\n    }\n  }\n\n  // overall style key\n  //\n\n  var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];\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  _p.styleKey = combineHashes(hash[0], hash[1]);\n\n  // 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  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  }\n\n  // node\n  //\n\n  if (isNode) {\n    var _p$styleKeys = _p.styleKeys,\n      nodeBody = _p$styleKeys.nodeBody,\n      nodeBorder = _p$styleKeys.nodeBorder,\n      nodeOutline = _p$styleKeys.nodeOutline,\n      backgroundImage = _p$styleKeys.backgroundImage,\n      compound = _p$styleKeys.compound,\n      pie = _p$styleKeys.pie;\n    var nodeKeys = [nodeBody, nodeBorder, nodeOutline, 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  return oldStyleKey !== _p.styleKey;\n};\nstyfn$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};\n\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 }\nstyfn$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  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  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  // edge sanity checks to prevent the client from making serious mistakes\n  if (parsedProp.name === 'curve-style' && ele.isEdge() && (\n  // loops must be bundled beziers\n  parsedProp.value !== 'bezier' && ele.isLoop() ||\n  // 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  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  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  }\n\n  // check if we need to delete the current bypass\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  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  };\n\n  // put the property in the style objects\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        for (var i = 0; i < fields.length && fieldVal; i++) {\n          var field = fields[i];\n          fieldVal = fieldVal[field];\n        }\n        if (fieldVal == null) {\n          printMappingErr();\n          return false;\n        }\n        var percent;\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          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        }\n\n        // make sure to bound percent value\n        if (percent < 0) {\n          percent = 0;\n        } else if (percent > 1) {\n          percent = 1;\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        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        flatProp.mapping = prop; // keep a reference to the mapping\n        prop = flatProp; // the flattened (mapped) property is the one we want\n\n        break;\n      }\n\n    // direct mapping\n    case types.data:\n      {\n        // flatten the field (e.g. data.foo.bar)\n        var _fields = prop.field.split('.');\n        var _fieldVal = _p.data;\n        for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {\n          var _field = _fields[_i3];\n          _fieldVal = _fieldVal[_field];\n        }\n        if (_fieldVal != null) {\n          flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);\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        flatProp.mapping = prop; // keep a reference to the mapping\n        prop = flatProp; // the flattened (mapped) property is the one we want\n\n        break;\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        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        flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);\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        flatProp.mapping = copy(prop); // keep a reference to the mapping\n        prop = flatProp; // the flattened (mapped) property is the one we want\n\n        break;\n      }\n    case undefined:\n      break;\n    // just set the property\n\n    default:\n      return false;\n    // not a valid mapping\n  }\n\n  // if the property is a bypass property, then link the resultant property to the original one\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    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  checkTriggers();\n  return true;\n};\nstyfn$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    if (!keepBypasses) {\n      ele._private.style = {};\n    } else {\n      var style = ele._private.style;\n      var propNames = Object.keys(style);\n      for (var j = 0; j < propNames.length; j++) {\n        var propName = propNames[j];\n        var eleProp = style[propName];\n        if (eleProp != null) {\n          if (eleProp.bypass) {\n            eleProp.bypassed = null;\n          } else {\n            style[propName] = null;\n          }\n        }\n      }\n    }\n  }\n};\n\n// updates the visual style for all elements (useful for manual style modification after init)\nstyfn$8.update = function () {\n  var cy = this._private.cy;\n  var eles = cy.mutableElements();\n  eles.updateStyle();\n};\n\n// diffProps : { name => { prev, next } }\nstyfn$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  if (props.length > 0 && duration > 0) {\n    var style = {};\n\n    // build up the style to animate towards\n    var anyPrev = false;\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      if (!diffProp) {\n        continue;\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 = undefined;\n      var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)\n\n      if (!fromProp) {\n        continue;\n      }\n\n      // consider px values\n      if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {\n        diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy\n        initVal = fromProp.pfValue + initDt * diff;\n\n        // consider numerical values\n      } else if (number$1(fromProp.value) && number$1(toProp.value)) {\n        diff = toProp.value - fromProp.value; // nonzero is truthy\n        initVal = fromProp.value + initDt * diff;\n\n        // 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      }\n\n      // the previous value is good for an animation only if it's different\n      if (diff) {\n        style[prop] = toProp.strValue; // to val\n        this.applyBypass(ele, prop, initVal); // from val\n        anyPrev = true;\n      }\n    } // end if props allow ani\n\n    // can't transition if there's nothing previous to transition from\n    if (!anyPrev) {\n      return;\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\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};\nstyfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {\n  var prop = this.properties[name];\n  var triggerCheck = getTrigger(prop);\n  if (ele.removed()) {\n    return;\n  }\n  if (triggerCheck != null && triggerCheck(fromValue, toValue, ele)) {\n    onTrigger(prop);\n  }\n};\nstyfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {\n  var _this = this;\n  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n    return prop.triggersZOrder;\n  }, function () {\n    _this._private.cy.notify('zorder', ele);\n  });\n};\nstyfn$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();\n  });\n};\nstyfn$8.checkConnectedEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {\n  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n    return prop.triggersBoundsOfConnectedEdges;\n  }, function (prop) {\n    ele.connectedEdges().forEach(function (edge) {\n      edge.dirtyBoundingBoxCache();\n    });\n  });\n};\nstyfn$8.checkParallelEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {\n  this.checkTrigger(ele, name, fromValue, toValue, function (prop) {\n    return prop.triggersBoundsOfParallelEdges;\n  }, function (prop) {\n    ele.parallelEdges().forEach(function (pllEdge) {\n      pllEdge.dirtyBoundingBoxCache();\n    });\n  });\n};\nstyfn$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  this.checkConnectedEdgesBoundsTrigger(ele, name, fromValue, toValue);\n  this.checkParallelEdgesBoundsTrigger(ele, name, fromValue, toValue);\n};\n\nvar styfn$7 = {};\n\n// 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\nstyfn$7.applyBypass = function (eles, name, value, updateTransitions) {\n  var self = this;\n  var props = [];\n  var isBypass = true;\n\n  // put all the properties (can specify one or many) in an array after parsing them\n  if (name === '*' || name === '**') {\n    // apply to all property names\n\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        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    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    for (var _i = 0; _i < names.length; _i++) {\n      var _name2 = names[_i];\n      var _value = specifiedProps[_name2];\n      if (_value === undefined) {\n        // try camel case name too\n        _value = specifiedProps[dash2camel(_name2)];\n      }\n      if (_value !== undefined) {\n        var _parsedProp2 = this.parse(_name2, _value, true);\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  }\n\n  // we've failed if there are no valid properties\n  if (props.length === 0) {\n    return false;\n  }\n\n  // now, apply the bypass properties on the elements\n  var ret = false; // return true if at least one succesful bypass applied\n  for (var _i2 = 0; _i2 < eles.length; _i2++) {\n    // for each ele\n    var ele = eles[_i2];\n    var diffProps = {};\n    var diffProp = undefined;\n    for (var j = 0; j < props.length; j++) {\n      // for each prop\n      var _prop = props[j];\n      if (updateTransitions) {\n        var prevProp = ele.pstyle(_prop.name);\n        diffProp = diffProps[_prop.name] = {\n          prev: prevProp\n        };\n      }\n      ret = this.applyParsedProperty(ele, copy(_prop)) || ret;\n      if (updateTransitions) {\n        diffProp.next = ele.pstyle(_prop.name);\n      }\n    } // for props\n\n    if (ret) {\n      this.updateStyleHints(ele);\n    }\n    if (updateTransitions) {\n      this.updateTransitions(ele, diffProps, isBypass);\n    }\n  } // for eles\n\n  return ret;\n};\n\n// only useful in specific cases like animation\nstyfn$7.overrideBypass = function (eles, name, value) {\n  name = camel2dash(name);\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    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      if (prop.pfValue != null) {\n        prop.pfValue = value;\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      this.updateStyleHints(ele);\n    }\n    this.checkTriggers(ele, name, oldValue, value);\n  }\n};\nstyfn$7.removeAllBypasses = function (eles, updateTransitions) {\n  return this.removeBypasses(eles, this.propertyNames, updateTransitions);\n};\nstyfn$7.removeBypasses = function (eles, props, updateTransitions) {\n  var isBypass = true;\n  for (var j = 0; j < eles.length; j++) {\n    var ele = eles[j];\n    var diffProps = {};\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      if (!prevProp || !prevProp.bypass) {\n        // if a bypass doesn't exist for the prop, nothing needs to be removed\n        continue;\n      }\n      var value = ''; // empty => remove bypass\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    this.updateStyleHints(ele);\n    if (updateTransitions) {\n      this.updateTransitions(ele, diffProps, isBypass);\n    }\n  } // for eles\n};\n\nvar styfn$6 = {};\n\n// gets what an em size corresponds to in pixels relative to a dom element\nstyfn$6.getEmSizeInPixels = function () {\n  var px = this.containerCss('font-size');\n  if (px != null) {\n    return parseFloat(px);\n  } else {\n    return 1; // for headless\n  }\n};\n\n// gets css property from the core container\nstyfn$6.containerCss = function (propName) {\n  var cy = this._private.cy;\n  var domElement = cy.container();\n  var containerWindow = cy.window();\n  if (containerWindow && domElement && containerWindow.getComputedStyle) {\n    return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);\n  }\n};\n\nvar styfn$5 = {};\n\n// gets the rendered style for an element\nstyfn$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};\n\n// gets the raw style for an element\nstyfn$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    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      if (val != null) {\n        rstyle[prop.name] = val;\n        rstyle[dash2camel(prop.name)] = val;\n      }\n    }\n    return rstyle;\n  }\n};\nstyfn$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};\nstyfn$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    if (prop.alias) {\n      prop = prop.pointsTo;\n    }\n    var type = prop.type;\n    var styleProp = ele.pstyle(prop.name);\n    if (styleProp) {\n      var value = styleProp.value,\n        units = styleProp.units,\n        strValue = styleProp.strValue;\n      if (isRenderedVal && type.number && value != null && number$1(value)) {\n        var zoom = ele.cy().zoom();\n        var getRenderedValue = function getRenderedValue(val) {\n          return val * zoom;\n        };\n        var getValueStringWithUnits = function getValueStringWithUnits(val, units) {\n          return getRenderedValue(val) + units;\n        };\n        var isArrayValue = array(value);\n        var haveUnits = isArrayValue ? units.every(function (u) {\n          return u != null;\n        }) : units != null;\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    return null;\n  }\n};\nstyfn$5.getAnimationStartStyle = function (ele, aniProps) {\n  var rstyle = {};\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    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    if (styleProp) {\n      rstyle[name] = styleProp;\n    }\n  }\n  return rstyle;\n};\nstyfn$5.getPropsList = function (propsObj) {\n  var self = this;\n  var rstyle = [];\n  var style = propsObj;\n  var props = self.properties;\n  if (style) {\n    var names = Object.keys(style);\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      if (styleProp) {\n        rstyle.push(styleProp);\n      }\n    }\n  }\n  return rstyle;\n};\nstyfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {\n  var hash = seed.slice();\n  var name, val, strVal, chVal;\n  var i, j;\n  for (i = 0; i < propNames.length; i++) {\n    name = propNames[i];\n    val = ele.pstyle(name, false);\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      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  return hash;\n};\nstyfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;\n\nvar styfn$4 = {};\nstyfn$4.appendFromJson = function (json) {\n  var style = this;\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  return style;\n};\n\n// accessible cy.style() function\nstyfn$4.fromJson = function (json) {\n  var style = this;\n  style.resetToDefault();\n  style.appendFromJson(json);\n  return style;\n};\n\n// get json from cy.style() api\nstyfn$4.json = function () {\n  var json = [];\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    for (var j = 0; j < props.length; j++) {\n      var prop = props[j];\n      css[prop.name] = prop.strValue;\n    }\n    json.push({\n      selector: !selector ? 'core' : selector.toString(),\n      style: css\n    });\n  }\n  return json;\n};\n\nvar styfn$3 = {};\nstyfn$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;\n\n  // remove comments from the style string\n  remaining = remaining.replace(/[/][*](\\s|.)+?[*][/]/g, '');\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  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  for (;;) {\n    var nothingLeftToParse = remaining.match(/^\\s*$/);\n    if (nothingLeftToParse) {\n      break;\n    }\n    var selAndBlock = remaining.match(/^\\s*((?:.|\\s)+?)\\s*\\{((?:.|\\s)+?)\\}/);\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    selAndBlockStr = selAndBlock[0];\n\n    // parse the selector\n    var selectorStr = selAndBlock[1];\n    if (selectorStr !== 'core') {\n      var selector = new Selector(selectorStr);\n      if (selector.invalid) {\n        warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr);\n\n        // skip this selector and block\n        removeSelAndBlockFromRemaining();\n        continue;\n      }\n    }\n\n    // parse the block of properties and values\n    var blockStr = selAndBlock[2];\n    var invalidBlock = false;\n    blockRem = blockStr;\n    var props = [];\n    for (;;) {\n      var _nothingLeftToParse = blockRem.match(/^\\s*$/);\n      if (_nothingLeftToParse) {\n        break;\n      }\n      var propAndVal = blockRem.match(/^\\s*(.+?)\\s*:\\s*(.+?)(?:\\s*;|\\s*$)/);\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      propAndValStr = propAndVal[0];\n      var propStr = propAndVal[1];\n      var valStr = propAndVal[2];\n      var prop = self.properties[propStr];\n      if (!prop) {\n        warn('Skipping property: Invalid property name in: ' + propAndValStr);\n\n        // skip this property in the block\n        removePropAndValFromRem();\n        continue;\n      }\n      var parsedProp = style.parse(propStr, valStr);\n      if (!parsedProp) {\n        warn('Skipping property: Invalid property definition in: ' + propAndValStr);\n\n        // skip this property in the block\n        removePropAndValFromRem();\n        continue;\n      }\n      props.push({\n        name: propStr,\n        val: valStr\n      });\n      removePropAndValFromRem();\n    }\n    if (invalidBlock) {\n      removeSelAndBlockFromRemaining();\n      break;\n    }\n\n    // put the parsed block in the style\n    style.selector(selectorStr);\n    for (var i = 0; i < props.length; i++) {\n      var _prop = props[i];\n      style.css(_prop.name, _prop.val);\n    }\n    removeSelAndBlockFromRemaining();\n  }\n  return style;\n};\nstyfn$3.fromString = function (string) {\n  var style = this;\n  style.resetToDefault();\n  style.appendFromString(string);\n  return style;\n};\n\nvar styfn$2 = {};\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  var data = function data(prefix) {\n    return '^' + prefix + '\\\\s*\\\\(\\\\s*([\\\\w\\\\.]+)\\\\s*\\\\)$';\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  var urlRegexes = ['^url\\\\s*\\\\(\\\\s*[\\'\"]?(.+?)[\\'\"]?\\\\s*\\\\)$', '^(none)$', '^(.+)$'];\n\n  // each visual style property has a type and needs to be validated according to it\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    nonNegativeNumber: {\n      number: true,\n      min: 0,\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    linePosition: {\n      enums: ['center', 'inside', 'outside']\n    },\n    lineJoin: {\n      enums: ['round', 'bevel', 'miter']\n    },\n    borderStyle: {\n      enums: ['solid', 'dotted', 'dashed', 'double']\n    },\n    curveStyle: {\n      enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi', 'round-segments', 'round-taxi']\n    },\n    radiusType: {\n      enums: ['arc-radius', 'influence-radius'],\n      multiple: true\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    cornerRadius: {\n      number: true,\n      min: 0,\n      units: 'px|em',\n      implicitUnits: 'px',\n      enums: ['auto']\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    arrowWidth: {\n      number: true,\n      units: '%|px|em',\n      implicitUnits: 'px',\n      enums: ['match-line']\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', 'endpoints']\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          case 1:\n            // can be enum, deg, or rad only\n            return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';\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      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  };\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    triggersZOrder: diff.any\n  }, {\n    name: 'text-events',\n    type: t.bool,\n    triggersZOrder: diff.any\n  }];\n  var visibility = [{\n    name: 'display',\n    type: t.display,\n    triggersZOrder: diff.any,\n    triggersBounds: diff.any,\n    triggersBoundsOfConnectedEdges: diff.any,\n    triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue, ele) {\n      if (fromValue === toValue) {\n        return false;\n      }\n\n      // only if edge is bundled bezier (so as not to affect performance of other edges)\n      return ele.pstyle('curve-style').value === 'bezier';\n    }\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.number,\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    name: 'overlay-corner-radius',\n    type: t.cornerRadius\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    name: 'underlay-corner-radius',\n    type: t.cornerRadius\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  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  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: 'corner-radius',\n    type: t.cornerRadius\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    name: 'border-cap',\n    type: t.lineCap\n  }, {\n    name: 'border-join',\n    type: t.lineJoin\n  }, {\n    name: 'border-dash-pattern',\n    type: t.numbers\n  }, {\n    name: 'border-dash-offset',\n    type: t.number\n  }, {\n    name: 'border-position',\n    type: t.linePosition\n  }];\n  var nodeOutline = [{\n    name: 'outline-color',\n    type: t.color\n  }, {\n    name: 'outline-opacity',\n    type: t.zeroOneNumber\n  }, {\n    name: 'outline-width',\n    type: t.size,\n    triggersBounds: diff.any\n  }, {\n    name: 'outline-style',\n    type: t.borderStyle\n  }, {\n    name: 'outline-offset',\n    type: t.size,\n    triggersBounds: diff.any\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-outline-width',\n    type: t.size\n  }, {\n    name: 'line-outline-color',\n    type: t.color\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    triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue) {\n      if (fromValue === toValue) {\n        return false;\n      } // must have diff\n\n      return fromValue === 'bezier' ||\n      // remove from bundle\n      toValue === 'bezier'; // add to bundle\n    }\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: 'segment-radii',\n    type: t.numbers,\n    triggersBounds: diff.any\n  }, {\n    name: 'radius-type',\n    type: t.radiusType,\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: 'taxi-radius',\n    type: t.number,\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  }];\n\n  // pie backgrounds for nodes\n  var pie = [];\n  styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)\n  pie.push({\n    name: 'pie-size',\n    type: t.sizeMaybePercent\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  }\n\n  // edge arrows\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  }, {\n    name: 'arrow-width',\n    type: t.arrowWidth\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, nodeOutline, 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    nodeOutline: nodeOutline,\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  });\n\n  // define aliases\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: 'segment-distance',\n    pointsTo: 'segment-distances'\n  }, {\n    name: 'segment-weight',\n    pointsTo: 'segment-weights'\n  }, {\n    name: 'segment-radius',\n    pointsTo: 'segment-radii'\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  }];\n\n  // list of property names\n  styfn$2.propertyNames = props.map(function (p) {\n    return p.name;\n  });\n\n  // allow access of properties by name ( e.g. style.properties.height )\n  for (var _i = 0; _i < props.length; _i++) {\n    var prop = props[_i];\n    props[prop.name] = prop; // allow lookup by name\n  }\n\n  // map aliases\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    };\n\n    // add alias prop for parsing\n    props.push(aliasProp);\n    props[alias.name] = aliasProp; // allow lookup by name\n  }\n})();\nstyfn$2.getDefaultProperty = function (name) {\n  return this.getDefaultProperties()[name];\n};\nstyfn$2.getDefaultProperties = function () {\n  var _p = this._private;\n  if (_p.defaultProperties != null) {\n    return _p.defaultProperties;\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    'overlay-corner-radius': 'auto',\n    'underlay-opacity': 0,\n    'underlay-color': '#000',\n    'underlay-padding': 10,\n    'underlay-shape': 'round-rectangle',\n    'underlay-corner-radius': 'auto',\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    'border-dash-pattern': [4, 2],\n    'border-dash-offset': 0,\n    'border-cap': 'butt',\n    'border-join': 'miter',\n    'border-position': 'center',\n    'outline-color': '#999',\n    'outline-opacity': 1,\n    'outline-width': 0,\n    'outline-offset': 0,\n    'outline-style': 'solid',\n    'height': 30,\n    'width': 30,\n    'shape': 'ellipse',\n    'shape-polygon-points': '-1, -1,   1, -1,   1, 1,   -1, 1',\n    'corner-radius': 'auto',\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    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-outline-width': 0,\n    'line-outline-color': '#000',\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    'segment-radii': 15,\n    'radius-type': 'arc-radius',\n    'taxi-turn': '50%',\n    'taxi-radius': 15,\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  }, {\n    name: 'arrow-width',\n    value: 1\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  for (var i = 0; i < this.properties.length; i++) {\n    var prop = this.properties[i];\n    if (prop.pointsTo) {\n      continue;\n    }\n    var name = prop.name;\n    var val = rawProps[name];\n    var parsedProp = this.parse(name, val);\n    parsedProps[name] = parsedProp;\n  }\n  _p.defaultProperties = parsedProps;\n  return _p.defaultProperties;\n};\nstyfn$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\nvar styfn$1 = {};\n\n// a caching layer for property parsing\nstyfn$1.parse = function (name, value, propIsBypass, propIsFlat) {\n  var self = this;\n\n  // function values can't be cached in all cases, and there isn't much benefit of caching them anyway\n  if (fn$6(value)) {\n    return self.parseImplWarn(name, value, propIsBypass, propIsFlat);\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  if (!(ret = propCache[argHash])) {\n    ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);\n  }\n\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  if (propIsBypass || propIsFlat === 'mapping') {\n    // need a copy since props are mutated later in their lifecycles\n    ret = copy(ret);\n    if (ret) {\n      ret.value = copy(ret.value); // because it could be an array, e.g. colour\n    }\n  }\n  return ret;\n};\nstyfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {\n  var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);\n  if (!prop && value != null) {\n    warn(\"The style property `\".concat(name, \": \").concat(value, \"` is invalid\"));\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  return prop;\n};\n\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\nstyfn$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  if (!property) {\n    return null;\n  } // return null on property of unknown name\n  if (value === undefined) {\n    return null;\n  } // can't assign undefined\n\n  // the property may be an alias\n  if (property.alias) {\n    property = property.pointsTo;\n    name = property.name;\n  }\n  var valueIsString = string(value);\n  if (valueIsString) {\n    // trim the value to make parsing easier\n    value = value.trim();\n  }\n  var type = property.type;\n  if (!type) {\n    return null;\n  } // no type, no luck\n\n  // check if bypass is null or empty string (i.e. indication to delete bypass property)\n  if (propIsBypass && (value === '' || value === null)) {\n    return {\n      name: name,\n      value: value,\n      bypass: true,\n      deleteBypass: true\n    };\n  }\n\n  // check if value is a function used as a mapper\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  }\n\n  // check if value is mapped\n  var data, mapData;\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    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    if (type.multiple) {\n      return false;\n    } // impossible to map to num\n\n    var _mapped = types.mapData;\n\n    // we can map only if the type is a colour or a number\n    if (!(type.color || type.number)) {\n      return false;\n    }\n    var valueMin = this.parse(name, mapData[4]); // parse to validate\n    if (!valueMin || valueMin.mapped) {\n      return false;\n    } // can't be invalid or mapped\n\n    var valueMax = this.parse(name, mapData[5]); // parse to validate\n    if (!valueMax || valueMax.mapped) {\n      return false;\n    } // can't be invalid or mapped\n\n    // check if valueMin and valueMax are the same\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      && (\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      if (same) {\n        return false;\n      } // can't make a mapper without a range\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  if (type.multiple && propIsFlat !== 'multiple') {\n    var vals;\n    if (valueIsString) {\n      vals = value.split(/\\s+/);\n    } else if (array(value)) {\n      vals = value;\n    } else {\n      vals = [value];\n    }\n    if (type.evenMultiple && vals.length % 2 !== 0) {\n      return null;\n    }\n    var valArr = [];\n    var unitsArr = [];\n    var pfValArr = [];\n    var strVal = '';\n    var hasEnum = false;\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    if (type.validate && !type.validate(valArr, unitsArr)) {\n      return null;\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    return {\n      name: name,\n      value: valArr,\n      pfValue: pfValArr,\n      strValue: strVal,\n      bypass: propIsBypass,\n      units: unitsArr\n    };\n  }\n\n  // several types also allow enums\n  var checkEnums = function checkEnums() {\n    for (var _i = 0; _i < type.enums.length; _i++) {\n      var en = type.enums[_i];\n      if (en === value) {\n        return {\n          name: name,\n          value: value,\n          strValue: '' + value,\n          bypass: propIsBypass\n        };\n      }\n    }\n    return null;\n  };\n\n  // check the type and return the appropriate object\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    if (type.implicitUnits) {\n      implicitUnits = type.implicitUnits;\n    }\n    if (!type.unitless) {\n      if (valueIsString) {\n        var unitsRegex = 'px|em' + (type.allowPercent ? '|\\\\%' : '');\n        if (units) {\n          unitsRegex = units;\n        } // only allow explicit units if so set\n        var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');\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    value = parseFloat(value);\n\n    // if not a number and enums not allowed, then the value is invalid\n    if (isNaN(value) && type.enums === undefined) {\n      return null;\n    }\n\n    // check if this number type also accepts special keywords in place of numbers\n    // (i.e. `left`, `auto`, etc)\n    if (isNaN(value) && type.enums !== undefined) {\n      value = passedValue;\n      return checkEnums();\n    }\n\n    // check if value must be an integer\n    if (type.integer && !integer(value)) {\n      return null;\n    }\n\n    // check value is within range\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    var ret = {\n      name: name,\n      value: value,\n      strValue: '' + value + (units ? units : ''),\n      units: units,\n      bypass: propIsBypass\n    };\n\n    // normalise value in pixels\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    }\n\n    // normalise value in ms\n    if (units === 'ms' || units === 's') {\n      ret.pfValue = units === 'ms' ? value : 1000 * value;\n    }\n\n    // normalise value in rad\n    if (units === 'deg' || units === 'rad') {\n      ret.pfValue = units === 'rad' ? value : deg2rad(value);\n    }\n\n    // normalize value in %\n    if (units === '%') {\n      ret.pfValue = value / 100;\n    }\n    return ret;\n  } else if (type.propList) {\n    var props = [];\n    var propsStr = '' + value;\n    if (propsStr === 'none') ; else {\n      // go over each prop\n\n      var propsSplit = propsStr.split(/\\s*,\\s*|\\s+/);\n      for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {\n        var propName = propsSplit[_i2].trim();\n        if (self.properties[propName]) {\n          props.push(propName);\n        } else {\n          warn('`' + propName + '` is not a valid property name');\n        }\n      }\n      if (props.length === 0) {\n        return null;\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    if (!tuple) {\n      return null;\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      if (enumProp) {\n        return enumProp;\n      }\n    }\n    var regexes = type.regexes ? type.regexes : [type.regex];\n    for (var _i3 = 0; _i3 < regexes.length; _i3++) {\n      var regex = new RegExp(regexes[_i3]); // make a regex from the type string\n      var m = regex.exec(value);\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    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\nvar _Style = function Style(cy) {\n  if (!(this instanceof _Style)) {\n    return new _Style(cy);\n  }\n  if (!core(cy)) {\n    error('A style must have a core reference');\n    return;\n  }\n  this._private = {\n    cy: cy,\n    coreStyle: {}\n  };\n  this.length = 0;\n  this.resetToDefault();\n};\nvar styfn = _Style.prototype;\nstyfn.instanceString = function () {\n  return 'style';\n};\n\n// remove all contexts\nstyfn.clear = function () {\n  var _p = this._private;\n  var cy = _p.cy;\n  var eles = cy.elements();\n  for (var i = 0; i < this.length; i++) {\n    this[i] = undefined;\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};\nstyfn.resetToDefault = function () {\n  this.clear();\n  this.addDefaultStylesheet();\n  return this;\n};\n\n// builds a style object for the 'core' selector\nstyfn.core = function (propName) {\n  return this._private.coreStyle[propName] || this.getDefaultProperty(propName);\n};\n\n// create a new context from the specified selector string and switch to that context\nstyfn.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  this[i] = {\n    selector: selector,\n    properties: [],\n    mappedProperties: [],\n    index: i\n  };\n  return this; // chaining\n};\n\n// add one or many css rules to the current context\nstyfn.css = function () {\n  var self = this;\n  var args = arguments;\n  if (args.length === 1) {\n    var map = args[0];\n    for (var i = 0; i < self.properties.length; i++) {\n      var prop = self.properties[i];\n      var mapVal = map[prop.name];\n      if (mapVal === undefined) {\n        mapVal = map[dash2camel(prop.name)];\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  }\n\n  // do nothing if args are invalid\n\n  return this; // chaining\n};\nstyfn.style = styfn.css;\n\n// add a single css rule to the current context\nstyfn.cssRule = function (name, value) {\n  // name-value pair\n  var property = this.parse(name, value);\n\n  // add property to current context if valid\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    if (property.mapped) {\n      this[i].mappedProperties.push(property);\n    }\n\n    // add to core style if necessary\n    var currentSelectorIsCore = !this[i].selector;\n    if (currentSelectorIsCore) {\n      this._private.coreStyle[property.name] = property;\n    }\n  }\n  return this; // chaining\n};\nstyfn.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  return this;\n};\n\n// static function\n_Style.fromJson = function (cy, json) {\n  var style = new _Style(cy);\n  style.fromJson(json);\n  return style;\n};\n_Style.fromString = function (cy, string) {\n  return new _Style(cy).fromString(string);\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\nvar corefn$2 = {\n  style: function style(newStyle) {\n    if (newStyle) {\n      var s = this.setStyle(newStyle);\n      s.update();\n    }\n    return this._private.style;\n  },\n  setStyle: function setStyle(style) {\n    var _p = this._private;\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    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\nvar defaultSelectionType = 'single';\nvar 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    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    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    return this; // chaining\n  },\n  selectionType: function selectionType(selType) {\n    var _p = this._private;\n    if (_p.selectionType == null) {\n      _p.selectionType = defaultSelectionType;\n    }\n    if (selType !== undefined) {\n      if (selType === 'additive' || selType === 'single') {\n        _p.selectionType = selType;\n      }\n    } else {\n      return _p.selectionType;\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    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    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    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    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    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    switch (args.length) {\n      case 0:\n        // .pan()\n        return pan;\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          dims = args[0];\n          x = dims.x;\n          y = dims.y;\n          if (number$1(x)) {\n            pan.x = x;\n          }\n          if (number$1(y)) {\n            pan.y = y;\n          }\n          this.emit('pan viewport');\n        }\n        break;\n      case 2:\n        // .pan('x', 100)\n        if (!this._private.panningEnabled) {\n          return this;\n        }\n        dim = args[0];\n        val = args[1];\n        if ((dim === 'x' || dim === 'y') && number$1(val)) {\n          pan[dim] = val;\n        }\n        this.emit('pan viewport');\n        break;\n      // invalid\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    if (!this._private.panningEnabled) {\n      return this;\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          if (number$1(x)) {\n            pan.x += x;\n          }\n          if (number$1(y)) {\n            pan.y += y;\n          }\n          this.emit('pan viewport');\n        }\n        break;\n      case 2:\n        // .panBy('x', 100)\n        dim = arg0;\n        val = arg1;\n        if ((dim === 'x' || dim === 'y') && number$1(val)) {\n          pan[dim] += val;\n        }\n        this.emit('pan viewport');\n        break;\n      // invalid\n    }\n    this.notify('viewport');\n    return this; // chaining\n  },\n  gc: function gc() {\n    this.notify('gc');\n  },\n  fit: function fit(elements, padding) {\n    var viewportState = this.getFitViewport(elements, padding);\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    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    if (!this._private.panningEnabled || !this._private.zoomingEnabled) {\n      return;\n    }\n    var bb;\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    if (elementOrCollection(elements) && elements.empty()) {\n      return;\n    } // can't fit to nothing\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    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);\n\n      // crop zoom\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    return;\n  },\n  zoomRange: function zoomRange(min, max) {\n    var _p = this._private;\n    if (max == null) {\n      var opts = min;\n      min = opts.min;\n      max = opts.max;\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    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    var zoom;\n    var bail = false;\n    if (!_p.zoomingEnabled) {\n      // zooming disabled\n      bail = true;\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      if (params.position != null) {\n        pos = modelToRenderedPosition$1(params.position, currentZoom, currentPan);\n      } else if (params.renderedPosition != null) {\n        pos = params.renderedPosition;\n      }\n      if (pos != null && !_p.panningEnabled) {\n        // panning disabled\n        bail = true;\n      }\n    }\n\n    // crop zoom\n    zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;\n    zoom = zoom < _p.minZoom ? _p.minZoom : zoom;\n\n    // can't zoom with invalid params\n    if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {\n      return null;\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      if (vp == null || !vp.zoomed) {\n        return this;\n      }\n      _p.zoom = vp.zoom;\n      if (vp.panned) {\n        _p.pan.x = vp.pan.x;\n        _p.pan.y = vp.pan.y;\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    var zoomFailed = false;\n    var panFailed = false;\n    if (!opts) {\n      return this;\n    }\n    if (!number$1(opts.zoom)) {\n      zoomDefd = false;\n    }\n    if (!plainObject(opts.pan)) {\n      panDefd = false;\n    }\n    if (!zoomDefd && !panDefd) {\n      return this;\n    }\n    if (zoomDefd) {\n      var z = opts.zoom;\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    if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {\n      var p = opts.pan;\n      if (number$1(p.x)) {\n        _p.pan.x = p.x;\n        panFailed = false;\n      }\n      if (number$1(p.y)) {\n        _p.pan.y = p.y;\n        panFailed = false;\n      }\n      if (!panFailed) {\n        events.push('pan');\n      }\n    }\n    if (events.length > 0) {\n      events.push('viewport');\n      this.emit(events.join(' '));\n      this.notify('viewport');\n    }\n    return this; // chaining\n  },\n  center: function center(elements) {\n    var pan = this.getCenterPan(elements);\n    if (pan) {\n      this._private.pan = pan;\n      this.emit('pan viewport');\n      this.notify('viewport');\n    }\n    return this; // chaining\n  },\n  getCenterPan: function getCenterPan(elements, zoom) {\n    if (!this._private.panningEnabled) {\n      return;\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    if (elements.length === 0) {\n      return;\n    } // can't centre pan to nothing\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    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      var val = function val(name) {\n        return parseFloat(style.getPropertyValue(name));\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};\n\n// aliases\ncorefn$1.centre = corefn$1.center;\n\n// backwards compatibility\ncorefn$1.autolockNodes = corefn$1.autolock;\ncorefn$1.autoungrabifyNodes = corefn$1.autoungrabify;\n\nvar 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};\n\n// aliases\nfn.attr = fn.data;\nfn.removeAttr = fn.removeData;\n\nvar Core = function Core(opts) {\n  var cy = this;\n  opts = extend({}, opts);\n  var container = opts.container;\n\n  // allow for passing a wrapped jquery object\n  // e.g. cytoscape({ container: $('#cy') })\n  if (container && !htmlElement(container) && htmlElement(container[0])) {\n    container = container[0];\n  }\n  var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery\n  reg = reg || {};\n  if (reg && reg.cy) {\n    reg.cy.destroy();\n    reg = {}; // old instance => replace reg completely\n  }\n  var readies = reg.readies = reg.readies || [];\n  if (container) {\n    container._cyreg = reg;\n  } // make sure container assoc'd reg points to this cy\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  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  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  this.createEmitter();\n\n  // set selection type\n  this.selectionType(options.selectionType);\n\n  // init zoom bounds\n  this.zoomRange({\n    min: options.minZoom,\n    max: options.maxZoom\n  });\n  var loadExtData = function loadExtData(extData, next) {\n    var anyIsPromise = extData.some(promise);\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  };\n\n  // start with the default stylesheet so we have something before loading an external stylesheet\n  if (_p.styleEnabled) {\n    cy.setStyle([]);\n  }\n\n  // create the renderer\n  var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options\n  cy.initRenderer(rendererOptions);\n  var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {\n    cy.notifications(false);\n\n    // remove old elements\n    var oldEles = cy.mutableElements();\n    if (oldEles.length > 0) {\n      oldEles.remove();\n    }\n    if (elements != null) {\n      if (plainObject(elements) || array(elements)) {\n        cy.add(elements);\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  loadExtData([options.style, options.elements], function (thens) {\n    var initStyle = thens[0];\n    var initEles = thens[1];\n\n    // init style\n    if (_p.styleEnabled) {\n      cy.style().append(initStyle);\n    }\n\n    // initial load\n    setElesAndLayout(initEles, function () {\n      // onready\n      cy.startAnimationLoop();\n      _p.ready = true;\n\n      // if a ready callback is specified as an option, the bind it\n      if (fn$6(options.ready)) {\n        cy.on('ready', options.ready);\n      }\n\n      // bind all the ready handlers registered before creating this instance\n      for (var i = 0; i < readies.length; i++) {\n        var fn = readies[i];\n        cy.on('ready', fn);\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      cy.emit('ready');\n    }, options.done);\n  });\n};\nvar corefn = Core.prototype; // short alias\n\nextend(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    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    return this; // chaining\n  },\n  removeFromPool: function removeFromPool(eles) {\n    this._private.elements.unmerge(eles);\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    if (ownerDocument === undefined || ownerDocument == null) {\n      return _window;\n    }\n    return ownerDocument.defaultView || _window;\n  },\n  mount: function mount(container) {\n    if (container == null) {\n      return;\n    }\n    var cy = this;\n    var _p = cy._private;\n    var options = _p.options;\n    if (!htmlElement(container) && htmlElement(container[0])) {\n      container = container[0];\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    var getFreshRef = function getFreshRef(ele) {\n      return cy.getElementById(ele.id());\n    };\n    if (plainObject(obj)) {\n      // set\n\n      cy.startBatch();\n      if (obj.elements) {\n        var idInJson = {};\n        var updateEles = function updateEles(jsons, gr) {\n          var toAdd = [];\n          var toMod = [];\n          for (var i = 0; i < jsons.length; i++) {\n            var json = jsons[i];\n            if (!json.data.id) {\n              warn('cy.json() cannot handle elements without an ID attribute');\n              continue;\n            }\n            var id = '' + json.data.id; // id must be string\n            var ele = cy.getElementById(id);\n            idInJson[id] = true;\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          cy.add(toAdd);\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            _ele.json(_json);\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          for (var i = 0; i < grs.length; i++) {\n            var gr = grs[i];\n            var elements = obj.elements[gr];\n            if (array(elements)) {\n              updateEles(elements, gr);\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        });\n\n        // so that children are not removed w/parent\n        parentsToRemove.forEach(function (ele) {\n          return ele.children().move({\n            parent: null\n          });\n        });\n\n        // intermediate parents may be moved by prior line, so make sure we remove by fresh refs\n        parentsToRemove.forEach(function (ele) {\n          return getFreshRef(ele).remove();\n        });\n      }\n      if (obj.style) {\n        cy.style(obj.style);\n      }\n      if (obj.zoom != null && obj.zoom !== _p.zoom) {\n        cy.zoom(obj.zoom);\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      if (obj.data) {\n        cy.data(obj.data);\n      }\n      var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];\n      for (var _i2 = 0; _i2 < fields.length; _i2++) {\n        var f = fields[_i2];\n        if (obj[f] != null) {\n          cy[f](obj[f]);\n        }\n      }\n      cy.endBatch();\n      return this; // chaining\n    } else {\n      // get\n      var flat = !!obj;\n      var json = {};\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          if (!json.elements[group]) {\n            json.elements[group] = [];\n          }\n          json.elements[group].push(ele.json());\n        });\n      }\n      if (this._private.styleEnabled) {\n        json.style = cy.style().json();\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});\ncorefn.$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 */\nvar 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};\nvar 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\nvar getInfo = function getInfo(ele) {\n  return ele.scratch('breadthfirst');\n};\nvar setInfo = function setInfo(ele, obj) {\n  return ele.scratch('breadthfirst', obj);\n};\nfunction BreadthFirstLayout(options) {\n  this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);\n}\nBreadthFirstLayout.prototype.run = function () {\n  var options = this.options;\n  var cy = options.cy;\n  var eles = options.eles;\n  var nodes = eles.nodes().filter(function (n) {\n    return n.isChildless();\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 hasBoundingBox = !!options.boundingBox;\n  var cyExtent = cy.extent();\n  var bb = makeBoundingBox(hasBoundingBox ? options.boundingBox : {\n    x1: cyExtent.x1,\n    y1: cyExtent.y1,\n    w: cyExtent.w,\n    h: cyExtent.h\n  });\n  var roots;\n  if (elementOrCollection(options.roots)) {\n    roots = options.roots;\n  } else if (array(options.roots)) {\n    var rootsArray = [];\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    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      var _loop = function _loop() {\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      for (var _i = 0; _i < components.length; _i++) {\n        _loop();\n      }\n    }\n  }\n  var depths = [];\n  var foundByBfs = {};\n  var addToDepth = function addToDepth(ele, d) {\n    if (depths[d] == null) {\n      depths[d] = [];\n    }\n    var i = depths[d].length;\n    depths[d].push(ele);\n    setInfo(ele, {\n      index: i,\n      depth: d\n    });\n  };\n  var changeDepth = function changeDepth(ele, newDepth) {\n    var _getInfo = getInfo(ele),\n      depth = _getInfo.depth,\n      index = _getInfo.index;\n    depths[depth][index] = null;\n\n    // add only childless nodes\n    if (ele.isChildless()) addToDepth(ele, newDepth);\n  };\n\n  // find the depths of the nodes\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\n      // add only childless nodes\n      if (ele.isChildless()) addToDepth(ele, depth);\n      foundByBfs[id] = true;\n    }\n  });\n\n  // check for nodes not found by bfs\n  var orphanNodes = [];\n  for (var _i2 = 0; _i2 < nodes.length; _i2++) {\n    var _ele = nodes[_i2];\n    if (foundByBfs[_ele.id()]) {\n      continue;\n    } else {\n      orphanNodes.push(_ele);\n    }\n  }\n\n  // assign the nodes a depth and index\n  var assignDepthsAt = function assignDepthsAt(i) {\n    var eles = depths[i];\n    for (var j = 0; j < eles.length; j++) {\n      var _ele2 = eles[j];\n      if (_ele2 == null) {\n        eles.splice(j, 1);\n        j--;\n        continue;\n      }\n      setInfo(_ele2, {\n        depth: i,\n        index: j\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    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    if (eInfo.depth <= maxDepth) {\n      if (!options.acyclic && shifted[id]) {\n        return null;\n      }\n      var newDepth = maxDepth + 1;\n      changeDepth(ele, newDepth);\n      shifted[id] = newDepth;\n      return true;\n    }\n    return false;\n  };\n\n  // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)\n  if (directed && maximal) {\n    var Q = [];\n    var shifted = {};\n    var enqueue = function enqueue(n) {\n      return Q.push(n);\n    };\n    var dequeue = function dequeue() {\n      return Q.shift();\n    };\n    nodes.forEach(function (n) {\n      return Q.push(n);\n    });\n    while (Q.length > 0) {\n      var _ele3 = dequeue();\n      var didShift = adjustMaximally(_ele3, shifted);\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  // find min distance we need to leave between nodes\n  var minDistance = 0;\n  if (options.avoidOverlap) {\n    for (var _i3 = 0; _i3 < nodes.length; _i3++) {\n      var n = nodes[_i3];\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\n  // get the weighted percent for an element based on its connectivity to other levels\n  var cachedWeightedPercent = {};\n  var getWeightedPercent = function getWeightedPercent(ele) {\n    if (cachedWeightedPercent[ele.id()]) {\n      return cachedWeightedPercent[ele.id()];\n    }\n    var eleDepth = getInfo(ele).depth;\n    var neighbors = ele.neighborhood();\n    var percent = 0;\n    var samples = 0;\n    for (var _i4 = 0; _i4 < neighbors.length; _i4++) {\n      var neighbor = neighbors[_i4];\n      if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {\n        continue;\n      }\n      var bf = getInfo(neighbor);\n      if (bf == null) {\n        continue;\n      }\n      var index = bf.index;\n      var depth = bf.depth;\n\n      // unassigned neighbours shouldn't affect the ordering\n      if (index == null || depth == null) {\n        continue;\n      }\n      var nDepth = depths[depth].length;\n      if (depth < eleDepth) {\n        // only get influenced by elements above\n        percent += index / nDepth;\n        samples++;\n      }\n    }\n    samples = Math.max(1, samples);\n    percent = percent / samples;\n    if (samples === 0) {\n      // put lone nodes at the start\n      percent = 0;\n    }\n    cachedWeightedPercent[ele.id()] = percent;\n    return percent;\n  };\n\n  // rearrange the indices in each depth level based on connectivity\n  var sortFn = function sortFn(a, b) {\n    var apct = getWeightedPercent(a);\n    var bpct = getWeightedPercent(b);\n    var diff = apct - bpct;\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  if (options.depthSort !== undefined) {\n    sortFn = options.depthSort;\n  }\n  var depthsLen = depths.length;\n\n  // sort each level to make connected nodes closer\n  for (var _i5 = 0; _i5 < depthsLen; _i5++) {\n    depths[_i5].sort(sortFn);\n    assignDepthsAt(_i5);\n  }\n\n  // assign orphan nodes to a new top-level depth\n  var orphanDepth = [];\n  for (var _i6 = 0; _i6 < orphanNodes.length; _i6++) {\n    orphanDepth.push(orphanNodes[_i6]);\n  }\n  var assignDepths = function assignDepths() {\n    for (var _i7 = 0; _i7 < depthsLen; _i7++) {\n      assignDepthsAt(_i7);\n    }\n  };\n\n  // add a new top-level depth only when there are orphan nodes\n  if (orphanDepth.length) {\n    depths.unshift(orphanDepth);\n    depthsLen = depths.length;\n    assignDepths();\n  }\n  var biggestDepthSize = 0;\n  for (var _i8 = 0; _i8 < depthsLen; _i8++) {\n    biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);\n  }\n  var center = {\n    x: bb.x1 + bb.w / 2,\n    y: bb.y1 + bb.h / 2\n  };\n\n  // average node size\n  var aveNodeSize = nodes.reduce(function (acc, node) {\n    return function (box) {\n      return {\n        w: acc.w === -1 ? box.w : (acc.w + box.w) / 2,\n        h: acc.h === -1 ? box.h : (acc.h + box.h) / 2\n      };\n    }(node.boundingBox({\n      includeLabels: options.nodeDimensionsIncludeLabels\n    }));\n  }, {\n    w: -1,\n    h: -1\n  });\n  var distanceY = Math.max(\n  // only one depth\n  depthsLen === 1 ? 0 :\n  // inside a bounding box, no need for top & bottom padding\n  hasBoundingBox ? (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen - 1) : (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen + 1), minDistance);\n  var maxDepthSize = depths.reduce(function (max, eles) {\n    return Math.max(max, eles.length);\n  }, 0);\n  var getPosition = function getPosition(ele) {\n    var _getInfo2 = getInfo(ele),\n      depth = _getInfo2.depth,\n      index = _getInfo2.index;\n    if (options.circle) {\n      var radiusStepSize = Math.min(bb.w / 2 / depthsLen, bb.h / 2 / depthsLen);\n      radiusStepSize = Math.max(radiusStepSize, minDistance);\n      var radius = radiusStepSize * depth + radiusStepSize - (depthsLen > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);\n      var theta = 2 * Math.PI / depths[depth].length * index;\n      if (depth === 0 && depths[0].length === 1) {\n        radius = 1;\n      }\n      return {\n        x: center.x + radius * Math.cos(theta),\n        y: center.y + radius * Math.sin(theta)\n      };\n    } else {\n      var depthSize = depths[depth].length;\n      var distanceX = Math.max(\n      // only one depth\n      depthSize === 1 ? 0 :\n      // inside a bounding box, no need for left & right padding\n      hasBoundingBox ? (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) - 1) : (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) + 1), minDistance);\n      var epos = {\n        x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,\n        y: center.y + (depth + 1 - (depthsLen + 1) / 2) * distanceY\n      };\n      return epos;\n    }\n  };\n  eles.nodes().layoutPositions(this, options, getPosition);\n  return this; // chaining\n};\n\nvar 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};\nfunction CircleLayout(options) {\n  this.options = extend({}, defaults$6, options);\n}\nCircleLayout.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  if (options.sort) {\n    nodes = nodes.sort(options.sort);\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  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  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  }\n\n  // calculate the radius\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    r = Math.max(rMin, r);\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  eles.nodes().layoutPositions(this, options, getPos);\n  return this; // chaining\n};\n\nvar 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};\nfunction ConcentricLayout(options) {\n  this.options = extend({}, defaults$5, options);\n}\nConcentricLayout.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  var maxNodeSize = 0;\n  for (var i = 0; i < nodes.length; i++) {\n    var node = nodes[i];\n    var value = undefined;\n\n    // calculate the node value\n    value = options.concentric(node);\n    nodeValues.push({\n      value: value,\n      node: node\n    });\n\n    // for style mapping\n    node._private.scratch.concentric = value;\n  }\n\n  // in case we used the `concentric` in style\n  nodes.updateStyle();\n\n  // calculate max size now based on potentially updated mappers\n  for (var _i = 0; _i < nodes.length; _i++) {\n    var _node = nodes[_i];\n    var nbb = _node.layoutDimensions(options);\n    maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);\n  }\n\n  // sort node values in descreasing order\n  nodeValues.sort(function (a, b) {\n    return b.value - a.value;\n  });\n  var levelWidth = options.levelWidth(nodes);\n\n  // put the values into levels\n  var levels = [[]];\n  var currentLevel = levels[0];\n  for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {\n    var val = nodeValues[_i2];\n    if (currentLevel.length > 0) {\n      var diff = Math.abs(currentLevel[0].value - val.value);\n      if (diff >= levelWidth) {\n        currentLevel = [];\n        levels.push(currentLevel);\n      }\n    }\n    currentLevel.push(val);\n  }\n\n  // create positions from levels\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  }\n\n  // find the metrics for each level\n  var r = 0;\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);\n\n    // calculate the radius\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    level.r = r;\n    r += minDist;\n  }\n  if (options.equidistant) {\n    var rDeltaMax = 0;\n    var _r = 0;\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    _r = 0;\n    for (var _i5 = 0; _i5 < levels.length; _i5++) {\n      var _level2 = levels[_i5];\n      if (_i5 === 0) {\n        _r = _level2.r;\n      }\n      _level2.r = _r;\n      _r += rDeltaMax;\n    }\n  }\n\n  // calculate the node positions\n  var pos = {}; // id => position\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    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  }\n\n  // position the nodes\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/*\nThe CoSE layout was written by Gerardo Huck.\nhttps://www.linkedin.com/in/gerardohuck/\n\nBased on the following article:\nhttp://dl.acm.org/citation.cfm?id=1498047\n\nModifications tracked on Github.\n*/\n\nvar DEBUG;\n\n/**\n * @brief :  default layout options\n */\nvar 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/**\n * @brief       : constructor\n * @arg options : object containing layout options\n */\nfunction CoseLayout(options) {\n  this.options = extend({}, defaults$4, options);\n  this.options.layout = this;\n\n  // Exclude any edge that has a source or target node that is not in the set of passed-in nodes\n  var nodes = this.options.eles.nodes();\n  var edges = this.options.eles.edges();\n  var notEdges = edges.filter(function (e) {\n    var sourceId = e.source().data('id');\n    var targetId = e.target().data('id');\n    var hasSource = nodes.some(function (n) {\n      return n.data('id') === sourceId;\n    });\n    var hasTarget = nodes.some(function (n) {\n      return n.data('id') === targetId;\n    });\n    return !hasSource || !hasTarget;\n  });\n  this.options.eles = this.options.eles.not(notEdges);\n}\n\n/**\n * @brief : runs the layout\n */\nCoseLayout.prototype.run = function () {\n  var options = this.options;\n  var cy = options.cy;\n  var layout = this;\n  layout.stopped = false;\n  if (options.animate === true || options.animate === false) {\n    layout.emit({\n      type: 'layoutstart',\n      layout: layout\n    });\n  }\n\n  // Set DEBUG - Global variable\n  if (true === options.debug) {\n    DEBUG = true;\n  } else {\n    DEBUG = false;\n  }\n\n  // Initialize layout info\n  var layoutInfo = createLayoutInfo(cy, layout, options);\n\n  // Show LayoutInfo contents if debugging\n  if (DEBUG) {\n    printLayoutInfo(layoutInfo);\n  }\n\n  // If required, randomize node positions\n  if (options.randomize) {\n    randomizePositions(layoutInfo);\n  }\n  var startTime = performanceNow();\n  var refresh = function refresh() {\n    refreshPositions(layoutInfo, cy, options);\n\n    // Fit the graph if necessary\n    if (true === options.fit) {\n      cy.fit(options.padding);\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    }\n\n    // Do one step in the phisical simulation\n    step(layoutInfo, options);\n\n    // Update temperature\n    layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;\n    // 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    return true;\n  };\n  var done = function done() {\n    if (options.animate === true || options.animate === false) {\n      refresh();\n\n      // Layout has finished\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  var i = 0;\n  var loopRet = true;\n  if (options.animate === true) {\n    var _frame = function frame() {\n      var f = 0;\n      while (loopRet && f < options.refresh) {\n        loopRet = mainLoop(i);\n        i++;\n        f++;\n      }\n      if (!loopRet) {\n        // it's done\n        separateComponents(layoutInfo, options);\n        done();\n      } else {\n        var now = performanceNow();\n        if (now - startTime >= options.animationThreshold) {\n          refresh();\n        }\n        requestAnimationFrame(_frame);\n      }\n    };\n    _frame();\n  } else {\n    while (loopRet) {\n      loopRet = mainLoop(i);\n      i++;\n    }\n    separateComponents(layoutInfo, options);\n    done();\n  }\n  return this; // chaining\n};\n\n/**\n * @brief : called on continuous layouts to stop them before they finish\n */\nCoseLayout.prototype.stop = function () {\n  this.stopped = true;\n  if (this.thread) {\n    this.thread.stop();\n  }\n  this.emit('layoutstop');\n  return this; // chaining\n};\nCoseLayout.prototype.destroy = function () {\n  if (this.thread) {\n    this.thread.stop();\n  }\n  return this; // chaining\n};\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 */\nvar 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  for (var i = 0; i < components.length; i++) {\n    var component = components[i];\n    for (var j = 0; j < component.length; j++) {\n      var node = component[j];\n      id2cmptId[node.id()] = i;\n    }\n  }\n\n  // Iterate over all nodes, creating layout nodes\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'));\n\n    // forces\n    tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion;\n\n    // Add new node\n    layoutInfo.layoutNodes.push(tempNode);\n    // Add entry to id-index map\n    layoutInfo.idToIndex[tempNode.id] = i;\n  }\n\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  var end = -1; // Points to the end of the queue\n\n  var tempGraph = [];\n\n  // Second pass to add child information and\n  // initialize queue for hierarchical traversal\n  for (var i = 0; i < layoutInfo.nodeSize; i++) {\n    var n = layoutInfo.layoutNodes[i];\n    var p_id = n.parentId;\n    // Check if node n has a parent node\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  }\n\n  // Add root graph to graphSet\n  layoutInfo.graphSet.push(tempGraph);\n\n  // Traverse the graph, level by level,\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    if (children.length > 0) {\n      // Add children nodes as a new graph to graph set\n      layoutInfo.graphSet.push(children);\n      // Add children to que queue to be visited\n      for (var i = 0; i < children.length; i++) {\n        queue[++end] = children[i];\n      }\n    }\n  }\n\n  // Create indexToGraph map\n  for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n    var graph = layoutInfo.graphSet[i];\n    for (var j = 0; j < graph.length; j++) {\n      var index = layoutInfo.idToIndex[graph[j]];\n      layoutInfo.indexToGraph[index] = i;\n    }\n  }\n\n  // Iterate over all edges, creating Layout Edges\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');\n\n    // Compute ideal length\n    var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;\n    var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity;\n\n    // Check if it's an inter graph edge\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    if (sourceGraph != targetGraph) {\n      // Find lowest common graph ancestor\n      var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo);\n\n      // Compute sum of node depths, relative to lca graph\n      var lcaGraph = layoutInfo.graphSet[lca];\n      var depth = 0;\n\n      // Source depth\n      var tempNode = layoutInfo.layoutNodes[sourceIx];\n      while (-1 === lcaGraph.indexOf(tempNode.id)) {\n        tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];\n        depth++;\n      }\n\n      // Target depth\n      tempNode = layoutInfo.layoutNodes[targetIx];\n      while (-1 === lcaGraph.indexOf(tempNode.id)) {\n        tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];\n        depth++;\n      }\n\n      // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +\n      //  \". Index: \" + lca + \" Contents: \" + lcaGraph.toString() +\n      //  \". Depth: \" + depth);\n\n      // Update idealLength\n      idealLength *= depth * options.nestingFactor;\n    }\n    tempEdge.idealLength = idealLength;\n    tempEdge.elasticity = elasticity;\n    layoutInfo.layoutEdges.push(tempEdge);\n  }\n\n  // Finally, return layoutInfo object\n  return layoutInfo;\n};\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 */\nvar 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  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/**\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 */\nvar _findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {\n  var graph = layoutInfo.graphSet[graphIx];\n  // If both nodes belongs to graphIx\n  if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {\n    return {\n      count: 2,\n      graph: graphIx\n    };\n  }\n\n  // Make recursive calls for all subgraphs\n  var c = 0;\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;\n\n    // If the node has no child, skip it\n    if (0 === children.length) {\n      continue;\n    }\n    var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];\n    var result = _findLCA_aux(node1, node2, childGraphIx, layoutInfo);\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      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  return {\n    count: c,\n    graph: graphIx\n  };\n};\n\n/**\n * @brief: printsLayoutInfo into js console\n *         Only used for debbuging\n */\nvar printLayoutInfo; \n\n/**\n * @brief : Randomizes the position of all nodes\n */\nvar randomizePositions = function randomizePositions(layoutInfo, cy) {\n  var width = layoutInfo.clientWidth;\n  var height = layoutInfo.clientHeight;\n  for (var i = 0; i < layoutInfo.nodeSize; i++) {\n    var n = layoutInfo.layoutNodes[i];\n\n    // No need to randomize compound nodes or locked nodes\n    if (0 === n.children.length && !n.isLocked) {\n      n.positionX = Math.random() * width;\n      n.positionY = Math.random() * height;\n    }\n  }\n};\nvar 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  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  return function (ele, i) {\n    var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];\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/**\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 */\nvar refreshPositions = function refreshPositions(layoutInfo, cy, options) {\n  // var s = 'Refreshing positions';\n  // logDebug(s);\n\n  var layout = options.layout;\n  var nodes = options.eles.nodes();\n  var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);\n  nodes.positions(getScaledPos);\n\n  // Trigger layoutReady only on first call\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/**\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 */\nvar step = function step(layoutInfo, options, _step) {\n  // var s = \"\\n\\n###############################\";\n  // s += \"\\nSTEP: \" + step;\n  // s += \"\\n###############################\\n\";\n  // logDebug(s);\n\n  // Calculate node repulsions\n  calculateNodeForces(layoutInfo, options);\n  // Calculate edge forces\n  calculateEdgeForces(layoutInfo);\n  // Calculate gravity forces\n  calculateGravityForces(layoutInfo, options);\n  // Propagate forces from parent to child\n  propagateForces(layoutInfo);\n  // Update positions based on calculated forces\n  updatePositions(layoutInfo);\n};\n\n/**\n * @brief : Computes the node repulsion forces\n */\nvar 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;\n\n    // s = \"Set: \" + graph.toString();\n    // logDebug(s);\n\n    // Now get all the pairs of nodes\n    // Only get each pair once, (A, B) = (B, A)\n    for (var j = 0; j < numNodes; j++) {\n      var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];\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};\nvar randomDistance = function randomDistance(max) {\n  return -1 + 2 * max * Math.random();\n};\n\n/**\n * @brief : Compute the node repulsion forces between a pair of nodes\n */\nvar nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {\n  // var s = \"Node repulsion. Node1: \" + node1.id + \" Node2: \" + node2.id;\n\n  var cmptId1 = node1.cmptId;\n  var cmptId2 = node2.cmptId;\n  if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {\n    return;\n  }\n\n  // Get direction of line connecting both node centers\n  var directionX = node2.positionX - node1.positionX;\n  var directionY = node2.positionY - node1.positionY;\n  var maxRandDist = 1;\n  // s += \"\\ndirectionX: \" + directionX + \", directionY: \" + directionY;\n\n  // If both centers are the same, apply a random force\n  if (0 === directionX && 0 === directionY) {\n    directionX = randomDistance(maxRandDist);\n    directionY = randomDistance(maxRandDist);\n  }\n  var overlap = nodesOverlap(node1, node2, directionX, directionY);\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;\n\n    // Compute the module and components of the force vector\n    var distance = Math.sqrt(directionX * directionX + directionY * directionY);\n    // s += \"\\nDistance: \" + distance;\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\n    // Get clipping points for both nodes\n    var point1 = findClippingPoint(node1, directionX, directionY);\n    var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY);\n\n    // Use clipping points to compute distance\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);\n    // s += \"\\nDistance: \" + distance;\n\n    // Compute the module and components of the force vector\n    var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;\n    var forceX = force * distanceX / distance;\n    var forceY = force * distanceY / distance;\n  }\n\n  // Apply force\n  if (!node1.isLocked) {\n    node1.offsetX -= forceX;\n    node1.offsetY -= forceY;\n  }\n  if (!node2.isLocked) {\n    node2.offsetX += forceX;\n    node2.offsetY += forceY;\n  }\n\n  // s += \"\\nForceX: \" + forceX + \" ForceY: \" + forceY;\n  // logDebug(s);\n\n  return;\n};\n\n/**\n * @brief  : Determines whether two nodes overlap or not\n * @return : Amount of overlapping (0 => no overlap)\n */\nvar 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  if (dY > 0) {\n    var overlapY = node1.maxY - node2.minY;\n  } else {\n    var overlapY = node2.maxY - node1.minY;\n  }\n  if (overlapX >= 0 && overlapY >= 0) {\n    return Math.sqrt(overlapX * overlapX + overlapY * overlapY);\n  } else {\n    return 0;\n  }\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 */\nvar 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;\n\n  // var s = 'Computing clipping point of node ' + node.id +\n  //   \" . Height:  \" + H + \", Width: \" + W +\n  //   \"\\nDirection \" + dX + \", \" + dY;\n  //\n  // Compute intersection\n  var res = {};\n\n  // Case: Vertical direction (up)\n  if (0 === dX && 0 < dY) {\n    res.x = X;\n    // s += \"\\nUp direction\";\n    res.y = Y + H / 2;\n    return res;\n  }\n\n  // Case: Vertical direction (down)\n  if (0 === dX && 0 > dY) {\n    res.x = X;\n    res.y = Y + H / 2;\n    // s += \"\\nDown direction\";\n\n    return res;\n  }\n\n  // Case: Intersects the right border\n  if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {\n    res.x = X + W / 2;\n    res.y = Y + W * dY / 2 / dX;\n    // s += \"\\nRightborder\";\n\n    return res;\n  }\n\n  // Case: Intersects the left border\n  if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {\n    res.x = X - W / 2;\n    res.y = Y - W * dY / 2 / dX;\n    // s += \"\\nLeftborder\";\n\n    return res;\n  }\n\n  // Case: Intersects the top border\n  if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {\n    res.x = X + H * dX / 2 / dY;\n    res.y = Y + H / 2;\n    // s += \"\\nTop border\";\n\n    return res;\n  }\n\n  // Case: Intersects the bottom border\n  if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {\n    res.x = X - H * dX / 2 / dY;\n    res.y = Y - H / 2;\n    // s += \"\\nBottom border\";\n\n    return res;\n  }\n\n  // s += \"\\nClipping point found at \" + res.x + \", \" + res.y;\n  // logDebug(s);\n  return res;\n};\n\n/**\n * @brief : Calculates all edge forces\n */\nvar 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];\n\n    // Get direction of line connecting both node centers\n    var directionX = target.positionX - source.positionX;\n    var directionY = target.positionY - source.positionY;\n\n    // If both centers are the same, do nothing.\n    // A random force has already been applied as node repulsion\n    if (0 === directionX && 0 === directionY) {\n      continue;\n    }\n\n    // Get clipping points for both nodes\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    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    }\n\n    // Add this force to target and source nodes\n    if (!source.isLocked) {\n      source.offsetX += forceX;\n      source.offsetY += forceY;\n    }\n    if (!target.isLocked) {\n      target.offsetX -= forceX;\n      target.offsetY -= forceY;\n    }\n\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 */\nvar calculateGravityForces = function calculateGravityForces(layoutInfo, options) {\n  if (options.gravity === 0) {\n    return;\n  }\n  var distThreshold = 1;\n\n  // var s = 'calculateGravityForces';\n  // logDebug(s);\n  for (var i = 0; i < layoutInfo.graphSet.length; i++) {\n    var graph = layoutInfo.graphSet[i];\n    var numNodes = graph.length;\n\n    // s = \"Set: \" + graph.toString();\n    // logDebug(s);\n\n    // Compute graph center\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    }\n    // s = \"Center found at: \" + centerX + \", \" + centerY;\n    // logDebug(s);\n\n    // Apply force to all nodes in graph\n    for (var j = 0; j < numNodes; j++) {\n      var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];\n      // s = \"Node: \" + node.id;\n\n      if (node.isLocked) {\n        continue;\n      }\n      var dx = centerX - node.positionX;\n      var dy = centerY - node.positionY;\n      var d = Math.sqrt(dx * dx + dy * dy);\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;\n        // s += \": Applied force: \" + fx + \", \" + fy;\n      }\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 */\nvar 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  var end = -1; // Points to the end of the queue\n\n  // logDebug('propagateForces');\n\n  // Start by visiting the nodes in the root graph\n  queue.push.apply(queue, layoutInfo.graphSet[0]);\n  end += layoutInfo.graphSet[0].length;\n\n  // Traverse the graph, level by level,\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;\n\n    // We only need to process the node if it's compound\n    if (0 < children.length && !node.isLocked) {\n      var offX = node.offsetX;\n      var offY = node.offsetY;\n\n      // 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]]];\n        // Propagate offset\n        childNode.offsetX += offX;\n        childNode.offsetY += offY;\n        // Add children to queue to be visited\n        queue[++end] = children[i];\n      }\n\n      // Reset parent offsets\n      node.offsetX = 0;\n      node.offsetY = 0;\n    }\n  }\n};\n\n/**\n * @brief : Updates the layout model positions, based on\n *          the accumulated forces\n */\nvar updatePositions = function updatePositions(layoutInfo, options) {\n  // var s = 'Updating positions';\n  // logDebug(s);\n\n  // Reset boundaries for compound nodes\n  for (var i = 0; i < layoutInfo.nodeSize; i++) {\n    var n = layoutInfo.layoutNodes[i];\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  for (var i = 0; i < layoutInfo.nodeSize; i++) {\n    var n = layoutInfo.layoutNodes[i];\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    }\n    // s = \"Node: \" + n.id + \" Previous position: (\" +\n    // n.positionX + \", \" + n.positionY + \").\";\n\n    // Limit displacement in order to improve stability\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;\n    // s += \" New Position: (\" + n.positionX + \", \" + n.positionY + \").\";\n    // logDebug(s);\n\n    // Update ancestry boudaries\n    _updateAncestryBoundaries(n, layoutInfo);\n  }\n\n  // Update size, position of compund nodes\n  for (var i = 0; i < layoutInfo.nodeSize; i++) {\n    var n = layoutInfo.layoutNodes[i];\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;\n      // 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/**\n * @brief : Limits a force (forceX, forceY) to be not\n *          greater (in modulo) than max.\n 8          Preserves force direction.\n  */\nvar 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  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  }\n\n  // s += \".\\nResult: (\" + res.x + \", \" + res.y + \")\";\n  // logDebug(s);\n\n  return res;\n};\n\n/**\n * @brief : Function used for keeping track of compound node\n *          sizes, since they should bound all their subnodes.\n */\nvar _updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {\n  // var s = \"Propagating new position/size of node \" + node.id;\n  var parentId = node.parentId;\n  if (null == parentId) {\n    // If there's no parent, we are done\n    // s += \". No parent node.\";\n    // logDebug(s);\n    return;\n  }\n\n  // Get Parent Node\n  var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];\n  var flag = false;\n\n  // MaxX\n  if (null == p.maxX || node.maxX + p.padRight > p.maxX) {\n    p.maxX = node.maxX + p.padRight;\n    flag = true;\n    // s += \"\\nNew maxX for parent node \" + p.id + \": \" + p.maxX;\n  }\n\n  // MinX\n  if (null == p.minX || node.minX - p.padLeft < p.minX) {\n    p.minX = node.minX - p.padLeft;\n    flag = true;\n    // s += \"\\nNew minX for parent node \" + p.id + \": \" + p.minX;\n  }\n\n  // MaxY\n  if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {\n    p.maxY = node.maxY + p.padBottom;\n    flag = true;\n    // s += \"\\nNew maxY for parent node \" + p.id + \": \" + p.maxY;\n  }\n\n  // MinY\n  if (null == p.minY || node.minY - p.padTop < p.minY) {\n    p.minY = node.minY - p.padTop;\n    flag = true;\n    // s += \"\\nNew minY for parent node \" + p.id + \": \" + p.minY;\n  }\n\n  // If updated boundaries, propagate changes upward\n  if (flag) {\n    // logDebug(s);\n    return _updateAncestryBoundaries(p, layoutInfo);\n  }\n\n  // s += \". No changes in boundaries/position of parent node \" + p.id;\n  // logDebug(s);\n  return;\n};\nvar separateComponents = function separateComponents(layoutInfo, options) {\n  var nodes = layoutInfo.layoutNodes;\n  var components = [];\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  var totalA = 0;\n  for (var i = 0; i < components.length; i++) {\n    var c = components[i];\n    if (!c) {\n      continue;\n    }\n    c.x1 = Infinity;\n    c.x2 = -Infinity;\n    c.y1 = Infinity;\n    c.y2 = -Infinity;\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    c.w = c.x2 - c.x1;\n    c.h = c.y2 - c.y1;\n    totalA += c.w * c.h;\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  for (var i = 0; i < components.length; i++) {\n    var c = components[i];\n    if (!c) {\n      continue;\n    }\n    for (var j = 0; j < c.length; j++) {\n      var n = c[j];\n      if (!n.isLocked) {\n        n.positionX += x - c.x1;\n        n.positionY += y - c.y1;\n      }\n    }\n    x += c.w + options.componentSpacing;\n    usedW += c.w + options.componentSpacing;\n    rowH = Math.max(rowH, c.h);\n    if (usedW > maxRowW) {\n      y += rowH + options.componentSpacing;\n      x = 0;\n      usedW = 0;\n      rowH = 0;\n    }\n  }\n};\n\nvar 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};\nfunction GridLayout(options) {\n  this.options = extend({}, defaults$3, options);\n}\nGridLayout.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  if (options.sort) {\n    nodes = nodes.sort(options.sort);\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  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    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        if (min == rows) {\n          rows = val;\n        } else {\n          cols = val;\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        if (max == rows) {\n          rows = val;\n        } else {\n          cols = val;\n        }\n      }\n    };\n    var oRows = options.rows;\n    var oCols = options.cols != null ? options.cols : options.columns;\n\n    // if rows or columns were set in options, use those values\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    }\n\n    // otherwise use the automatic values and adjust accordingly\n\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();\n\n      // reducing the small side takes away the most cells, so try it first\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        var _lg = large();\n\n        // try to add to larger side first (adds less in multiplication)\n        if ((_lg + 1) * _sm >= cells) {\n          large(_lg + 1);\n        } else {\n          small(_sm + 1);\n        }\n      }\n    }\n    var cellWidth = bb.w / cols;\n    var cellHeight = bb.h / rows;\n    if (options.condense) {\n      cellWidth = 0;\n      cellHeight = 0;\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        if (pos.x == null || pos.y == null) {\n          // for bb\n          pos.x = 0;\n          pos.y = 0;\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    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    var use = function use(row, col) {\n      cellUsed['c-' + row + '-' + col] = true;\n    };\n\n    // to keep track of current cell position\n    var row = 0;\n    var col = 0;\n    var moveToNextCell = function moveToNextCell() {\n      col++;\n      if (col >= cols) {\n        col = 0;\n        row++;\n      }\n    };\n\n    // get a cache of all the manual positions\n    var id2manPos = {};\n    for (var _i = 0; _i < nodes.length; _i++) {\n      var _node = nodes[_i];\n      var rcPos = options.position(_node);\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        if (_pos.col === undefined) {\n          // find unused col\n          _pos.col = 0;\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          while (used(_pos.row, _pos.col)) {\n            _pos.row++;\n          }\n        }\n        id2manPos[_node.id()] = _pos;\n        use(_pos.row, _pos.col);\n      }\n    }\n    var getPos = function getPos(element, i) {\n      var x, y;\n      if (element.locked() || element.isParent()) {\n        return false;\n      }\n\n      // see if we have a manual position set\n      var rcPos = id2manPos[element.id()];\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\n        while (used(row, col)) {\n          moveToNextCell();\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      return {\n        x: x,\n        y: y\n      };\n    };\n    nodes.layoutPositions(this, options, getPos);\n  }\n  return this; // chaining\n};\n\n// default layout options\nvar defaults$2 = {\n  ready: function ready() {},\n  // on layoutready\n  stop: function stop() {} // on layoutstop\n};\n\n// constructor\n// options : object containing layout options\nfunction NullLayout(options) {\n  this.options = extend({}, defaults$2, options);\n}\n\n// runs the layout\nNullLayout.prototype.run = function () {\n  var options = this.options;\n  var eles = options.eles; // elements to consider in the layout\n  var layout = this;\n\n  // 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  options.cy;\n  layout.emit('layoutstart');\n\n  // puts all nodes at (0, 0)\n  // n.b. most layouts would use layoutPositions(), instead of positions() and manual events\n  eles.nodes().positions(function () {\n    return {\n      x: 0,\n      y: 0\n    };\n  });\n\n  // trigger layoutready when each node has had its position set at least once\n  layout.one('layoutready', options.ready);\n  layout.emit('layoutready');\n\n  // trigger layoutstop when the layout stops (e.g. finishes)\n  layout.one('layoutstop', options.stop);\n  layout.emit('layoutstop');\n  return this; // chaining\n};\n\n// called on continuous layouts to stop them before they finish\nNullLayout.prototype.stop = function () {\n  return this; // chaining\n};\n\nvar 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  spacingFactor: undefined,\n  // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up\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};\nfunction PresetLayout(options) {\n  this.options = extend({}, defaults$1, options);\n}\nPresetLayout.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  function getPosition(node) {\n    if (options.positions == null) {\n      return copyPosition(node.position());\n    }\n    if (posIsFn) {\n      return options.positions(node);\n    }\n    var pos = options.positions[node._private.data.id];\n    if (pos == null) {\n      return null;\n    }\n    return pos;\n  }\n  nodes.layoutPositions(this, options, function (node, i) {\n    var position = getPosition(node);\n    if (node.locked() || position == null) {\n      return false;\n    }\n    return position;\n  });\n  return this; // chaining\n};\n\nvar 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};\nfunction RandomLayout(options) {\n  this.options = extend({}, defaults, options);\n}\nRandomLayout.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  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  eles.nodes().layoutPositions(this, options, getPos);\n  return this; // chaining\n};\n\nvar 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\nfunction NullRenderer(options) {\n  this.options = options;\n  this.notifications = 0; // for testing\n}\nvar noop = function noop() {};\nvar throwImgErr = function throwImgErr() {\n  throw new Error('A headless instance can not render images');\n};\nNullRenderer.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\nvar BRp$f = {};\nBRp$f.arrowShapeWidth = 0.3;\nBRp$f.registerArrowShapes = function () {\n  var arrowShapes = this.arrowShapes = {};\n  var renderer = this;\n\n  // 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  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  var transformPoints = function transformPoints(pts, size, angle, translation) {\n    var retPts = [];\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    return retPts;\n  };\n  var pointsToArr = function pointsToArr(pts) {\n    var ret = [];\n    for (var i = 0; i < pts.length; i++) {\n      var p = pts[i];\n      ret.push(p.x, p.y);\n    }\n    return ret;\n  };\n  var standardGap = function standardGap(edge) {\n    return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;\n  };\n  var defineArrowShape = function defineArrowShape(name, defn) {\n    if (string(defn)) {\n      defn = arrowShapes[defn];\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  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,\n    // first half of the rectangle\n    -0.15, -0.4, 0.15, -0.4,\n    // 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\nvar BRp$e = {};\n\n// Project mouse\nBRp$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};\nBRp$e.findContainerClientCoords = function () {\n  if (this.containerBB) {\n    return this.containerBB;\n  }\n  var container = this.container;\n  var rect = container.getBoundingClientRect();\n  var style = this.cy.window().getComputedStyle(container);\n  var styleValue = function styleValue(name) {\n    return parseFloat(style.getPropertyValue(name));\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};\nBRp$e.invalidateContainerClientCoordsCache = function () {\n  this.containerBB = null;\n};\nBRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {\n  return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];\n};\nBRp$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  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  if (interactiveElementsOnly) {\n    eles = eles.interactive;\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    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  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    var cornerRadius = node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue;\n    var rs = node._private.rscratch;\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      if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y, cornerRadius, rs)) {\n        addEle(node, 0);\n        return true;\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    var widthSq = width * width;\n    var width2 = width * 2;\n    var src = _p.source;\n    var tgt = _p.target;\n    var sqDist;\n    if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {\n      var pts = rs.allpts;\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      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    }\n\n    // if we're close to the edge but didn't hit it, maybe we hit its arrows\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    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      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    }\n\n    // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)\n    if (hasCompounds && near.length > 0) {\n      checkNode(src);\n      checkNode(tgt);\n    }\n  }\n  function preprop(obj, name, pre) {\n    return getPrefixedProperty(obj, name, pre);\n  }\n  function checkLabel(ele, prefix) {\n    var _p = ele._private;\n    var th = labelThreshold;\n    var prefixDash;\n    if (prefix) {\n      prefixDash = prefix + '-';\n    } else {\n      prefixDash = '';\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    if (!eventsEnabled || !text) {\n      return;\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    var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)\n    var ly1 = bb.y1 - th - oy;\n    var ly2 = bb.y2 + th - oy;\n    if (theta) {\n      var cos = Math.cos(theta);\n      var sin = Math.sin(theta);\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      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 = [\n      // 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      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  for (var i = eles.length - 1; i >= 0; i--) {\n    // reverse order for precedence\n    var ele = eles[i];\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  return near;\n};\n\n// 'Give me everything from this box'\nBRp$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  for (var e = 0; e < eles.length; e++) {\n    var ele = eles[e];\n    if (ele.isNode()) {\n      var node = ele;\n      var nodeBb = node.boundingBox({\n        includeNodes: true,\n        includeEdges: false,\n        includeLabels: false\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      if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {\n        continue;\n      }\n      if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {\n        continue;\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        for (var i = 0; i < pts.length; i++) {\n          if (!pointInBoundingBox(boxBb, pts[i])) {\n            allInside = false;\n            break;\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  return box;\n};\n\nvar BRp$d = {};\nBRp$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';\n\n  // Displacement gives direction for arrowhead orientation\n  var dispX, dispY;\n  var startX, startY, endX, endY, midX, midY;\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  midX = rs.midX;\n  midY = rs.midY;\n\n  // 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  rs.srcArrowAngle = getAngleFromDisp(dispX, dispY);\n\n  // mid target\n  //\n\n  var midX = rs.midX;\n  var midY = rs.midY;\n  if (isHaystack) {\n    midX = (startX + endX) / 2;\n    midY = (startY + endY) / 2;\n  }\n  dispX = endX - startX;\n  dispY = endY - startY;\n  if (isSegments) {\n    var pts = rs.allpts;\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 if (rs.isRound) {\n      dispX = rs.midVector[1];\n      dispY = -rs.midVector[0];\n    } else {\n      var i2 = pts.length / 2 - 1;\n      var i1 = 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    if (cpts.length / 2 % 2 === 0) {\n      var p0 = pts.length / 2 - 1; // startpt\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      var p0 = ic - 2; // startpt\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    dispX = bp1x - bp0x;\n    dispY = bp1y - bp0y;\n  }\n  rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);\n  rs.midDispX = dispX;\n  rs.midDispY = dispY;\n\n  // mid source\n  //\n\n  dispX *= -1;\n  dispY *= -1;\n  if (isSegments) {\n    var pts = rs.allpts;\n    if (pts.length / 2 % 2 === 0) ; else if (!rs.isRound) {\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  rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY);\n\n  // 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  rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);\n};\nBRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {\n  var cache = this.arrowWidthCache = this.arrowWidthCache || {};\n  var cachedVal = cache[edgeWidth + ', ' + scale];\n  if (cachedVal) {\n    return cachedVal;\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/**\n * Explained by Blindman67 at https://stackoverflow.com/a/44856925/11028828\n */\n\n// Declare reused variable to avoid reallocating variables every time the function is called\nvar x,\n  y,\n  v1 = {},\n  v2 = {},\n  sinA,\n  sinA90,\n  radDirection,\n  drawDirection,\n  angle,\n  halfAngle,\n  cRadius,\n  lenOut,\n  radius,\n  limit;\nvar startX, startY, stopX, stopY;\nvar lastPoint;\n\n// convert 2 points into vector form, polar form, and normalised\nvar asVec = function asVec(p, pp, v) {\n  v.x = pp.x - p.x;\n  v.y = pp.y - p.y;\n  v.len = Math.sqrt(v.x * v.x + v.y * v.y);\n  v.nx = v.x / v.len;\n  v.ny = v.y / v.len;\n  v.ang = Math.atan2(v.ny, v.nx);\n};\nvar invertVec = function invertVec(originalV, invertedV) {\n  invertedV.x = originalV.x * -1;\n  invertedV.y = originalV.y * -1;\n  invertedV.nx = originalV.nx * -1;\n  invertedV.ny = originalV.ny * -1;\n  invertedV.ang = originalV.ang > 0 ? -(Math.PI - originalV.ang) : Math.PI + originalV.ang;\n};\nvar calcCornerArc = function calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius) {\n  //-----------------------------------------\n  // Part 1\n  previousPoint !== lastPoint ? asVec(currentPoint, previousPoint, v1) : invertVec(v2, v1); // Avoid recalculating vec if it is the invert of the last one calculated\n  asVec(currentPoint, nextPoint, v2);\n  sinA = v1.nx * v2.ny - v1.ny * v2.nx;\n  sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;\n  angle = Math.asin(Math.max(-1, Math.min(1, sinA)));\n  if (Math.abs(angle) < 1e-6) {\n    x = currentPoint.x;\n    y = currentPoint.y;\n    cRadius = radius = 0;\n    return;\n  }\n  //-----------------------------------------\n  radDirection = 1;\n  drawDirection = false;\n  if (sinA90 < 0) {\n    if (angle < 0) {\n      angle = Math.PI + angle;\n    } else {\n      angle = Math.PI - angle;\n      radDirection = -1;\n      drawDirection = true;\n    }\n  } else {\n    if (angle > 0) {\n      radDirection = -1;\n      drawDirection = true;\n    }\n  }\n  if (currentPoint.radius !== undefined) {\n    radius = currentPoint.radius;\n  } else {\n    radius = radiusMax;\n  }\n  //-----------------------------------------\n  // Part 2\n  halfAngle = angle / 2;\n  //-----------------------------------------\n\n  limit = Math.min(v1.len / 2, v2.len / 2);\n  if (isArcRadius) {\n    //-----------------------------------------\n    // Part 3\n    lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));\n\n    //-----------------------------------------\n    // Special part A\n    if (lenOut > limit) {\n      lenOut = limit;\n      cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));\n    } else {\n      cRadius = radius;\n    }\n  } else {\n    lenOut = Math.min(limit, radius);\n    cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));\n  }\n  //-----------------------------------------\n\n  //-----------------------------------------\n  // Part 4\n  stopX = currentPoint.x + v2.nx * lenOut;\n  stopY = currentPoint.y + v2.ny * lenOut;\n  //-----------------------------------------\n  // Part 5\n  x = stopX - v2.ny * cRadius * radDirection;\n  y = stopY + v2.nx * cRadius * radDirection;\n  //-----------------------------------------\n  // Additional Part : calculate start point E\n  startX = currentPoint.x + v1.nx * lenOut;\n  startY = currentPoint.y + v1.ny * lenOut;\n\n  // Save last point to avoid recalculating vector when not needed\n  lastPoint = currentPoint;\n};\n\n/**\n * Draw corner provided by {@link getRoundCorner}\n *\n * @param ctx :CanvasRenderingContext2D\n * @param roundCorner {{cx:number, cy:number, radius:number, endAngle: number, startAngle: number, counterClockwise: boolean}}\n */\nfunction drawPreparedRoundCorner(ctx, roundCorner) {\n  if (roundCorner.radius === 0) ctx.lineTo(roundCorner.cx, roundCorner.cy);else ctx.arc(roundCorner.cx, roundCorner.cy, roundCorner.radius, roundCorner.startAngle, roundCorner.endAngle, roundCorner.counterClockwise);\n}\n\n/**\n * Get round corner from a point and its previous and next neighbours in a path\n *\n * @param previousPoint {{x: number, y:number, radius: number?}}\n * @param currentPoint {{x: number, y:number, radius: number?}}\n * @param nextPoint {{x: number, y:number, radius: number?}}\n * @param radiusMax :number\n * @param isArcRadius :boolean\n * @return {{\n * cx:number, cy:number, radius:number,\n * startX:number, startY:number,\n * stopX:number, stopY: number,\n * endAngle: number, startAngle: number, counterClockwise: boolean\n * }}\n */\nfunction getRoundCorner(previousPoint, currentPoint, nextPoint, radiusMax) {\n  var isArcRadius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n  if (radiusMax === 0 || currentPoint.radius === 0) return {\n    cx: currentPoint.x,\n    cy: currentPoint.y,\n    radius: 0,\n    startX: currentPoint.x,\n    startY: currentPoint.y,\n    stopX: currentPoint.x,\n    stopY: currentPoint.y,\n    startAngle: undefined,\n    endAngle: undefined,\n    counterClockwise: undefined\n  };\n  calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius);\n  return {\n    cx: x,\n    cy: y,\n    radius: cRadius,\n    startX: startX,\n    startY: startY,\n    stopX: stopX,\n    stopY: stopY,\n    startAngle: v1.ang + Math.PI / 2 * radDirection,\n    endAngle: v2.ang - Math.PI / 2 * radDirection,\n    counterClockwise: drawDirection\n  };\n}\n\nvar BRp$c = {};\nBRp$c.findMidptPtsEtc = function (edge, pairInfo) {\n  var posPts = pairInfo.posPts,\n    intersectionPts = pairInfo.intersectionPts,\n    vectorNormInverse = pairInfo.vectorNormInverse;\n  var midptPts;\n\n  // n.b. assumes all edges in bezier bundle have same endpoints specified\n  var srcManEndpt = edge.pstyle('source-endpoint');\n  var tgtManEndpt = edge.pstyle('target-endpoint');\n  var haveManualEndPts = srcManEndpt.units != null && tgtManEndpt.units != null;\n  var recalcVectorNormInverse = function recalcVectorNormInverse(x1, y1, x2, y2) {\n    var dy = y2 - y1;\n    var dx = x2 - x1;\n    var l = Math.sqrt(dx * dx + dy * dy);\n    return {\n      x: -dy / l,\n      y: dx / l\n    };\n  };\n  var edgeDistances = edge.pstyle('edge-distances').value;\n  switch (edgeDistances) {\n    case 'node-position':\n      midptPts = posPts;\n      break;\n    case 'intersection':\n      midptPts = intersectionPts;\n      break;\n    case 'endpoints':\n      {\n        if (haveManualEndPts) {\n          var _this$manualEndptToPx = this.manualEndptToPx(edge.source()[0], srcManEndpt),\n            _this$manualEndptToPx2 = _slicedToArray(_this$manualEndptToPx, 2),\n            x1 = _this$manualEndptToPx2[0],\n            y1 = _this$manualEndptToPx2[1];\n          var _this$manualEndptToPx3 = this.manualEndptToPx(edge.target()[0], tgtManEndpt),\n            _this$manualEndptToPx4 = _slicedToArray(_this$manualEndptToPx3, 2),\n            x2 = _this$manualEndptToPx4[0],\n            y2 = _this$manualEndptToPx4[1];\n          var endPts = {\n            x1: x1,\n            y1: y1,\n            x2: x2,\n            y2: y2\n          };\n          vectorNormInverse = recalcVectorNormInverse(x1, y1, x2, y2);\n          midptPts = endPts;\n        } else {\n          warn(\"Edge \".concat(edge.id(), \" has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint.  Falling back on edge-distances:intersection (default).\"));\n          midptPts = intersectionPts; // back to default\n        }\n        break;\n      }\n  }\n  return {\n    midptPts: midptPts,\n    vectorNormInverse: vectorNormInverse\n  };\n};\nBRp$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    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    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;\n\n    // always override as haystack in case set to different type previously\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};\nBRp$c.findSegmentsPoints = function (edge, pairInfo) {\n  // Segments (multiple straight lines)\n\n  var rs = edge._private.rscratch;\n  var segmentWs = edge.pstyle('segment-weights');\n  var segmentDs = edge.pstyle('segment-distances');\n  var segmentRs = edge.pstyle('segment-radii');\n  var segmentTs = edge.pstyle('radius-type');\n  var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);\n  var lastRadius = segmentRs.pfValue[segmentRs.pfValue.length - 1];\n  var lastRadiusType = segmentTs.pfValue[segmentTs.pfValue.length - 1];\n  rs.edgeType = 'segments';\n  rs.segpts = [];\n  rs.radii = [];\n  rs.isArcRadius = [];\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 _this$findMidptPtsEtc = this.findMidptPtsEtc(edge, pairInfo),\n      midptPts = _this$findMidptPtsEtc.midptPts,\n      vectorNormInverse = _this$findMidptPtsEtc.vectorNormInverse;\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    rs.radii.push(segmentRs.pfValue[s] !== undefined ? segmentRs.pfValue[s] : lastRadius);\n    rs.isArcRadius.push((segmentTs.pfValue[s] !== undefined ? segmentTs.pfValue[s] : lastRadiusType) === 'arc-radius');\n  }\n};\nBRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {\n  // Self-edge\n\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  if (edgeIsUnbundled) {\n    j = 0;\n    loopDist = ctrlptDist;\n  }\n  var loopAngle = loopDir - Math.PI / 2;\n  var outAngle = loopAngle - loopSwp / 2;\n  var inAngle = loopAngle + loopSwp / 2;\n\n  // increase by step size for overlapping loops, keyed on direction and sweep values\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};\nBRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {\n  // Compound edge\n\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  if (edgeIsUnbundled) {\n    j = 0;\n    loopDist = ctrlptDist;\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  };\n\n  // avoids cases with impossible beziers\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};\nBRp$c.findStraightEdgePoints = function (edge) {\n  // Straight edge within bundle\n\n  edge._private.rscratch.edgeType = 'straight';\n};\nBRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {\n  var rs = edge._private.rscratch;\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];\n\n  // (Multi)bezier\n\n  var multi = edgeIsUnbundled;\n  rs.edgeType = multi ? 'multibezier' : 'bezier';\n  rs.ctrlpts = [];\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 = undefined;\n    var sign = signum(normctrlptDist);\n    if (multi) {\n      ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size\n      ctrlptWeight = ctrlptWs.value[b];\n    }\n    if (edgeIsUnbundled) {\n      // multi or single unbundled\n      manctrlptDist = ctrlptDist;\n    } else {\n      manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;\n    }\n    var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;\n    var w1 = 1 - ctrlptWeight;\n    var w2 = ctrlptWeight;\n    var _this$findMidptPtsEtc2 = this.findMidptPtsEtc(edge, pairInfo),\n      midptPts = _this$findMidptPtsEtc2.midptPts,\n      vectorNormInverse = _this$findMidptPtsEtc2.vectorNormInverse;\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};\nBRp$c.findTaxiPoints = function (edge, pairInfo) {\n  // Taxicab geometry with two turns maximum\n\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  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  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;\n\n  // take away the effective w/h from the magnitude of the delta value\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  var dx = subDWH(pdx, dw);\n  var dy = subDWH(pdy, dh);\n  var isExplicitDir = false;\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  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  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  var d;\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  var getIsTooClose = function getIsTooClose(d) {\n    return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);\n  };\n  var isTooCloseSrc = getIsTooClose(d);\n  var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));\n  var isTooClose = isTooCloseSrc || isTooCloseTgt;\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      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      var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;\n      if (_lShapeInsideSrc) {\n        // vertical Z-shape (direction not respected)\n        var _y = (posPts.y1 + posPts.y2) / 2;\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        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      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      var _y5 = posPts.y1,\n        _y6 = posPts.y2;\n      rs.segpts = [_x6, _y5, _x6, _y6];\n    }\n  }\n  if (rs.isRound) {\n    var radius = edge.pstyle('taxi-radius').value;\n    var isArcRadius = edge.pstyle('radius-type').value[0] === 'arc-radius';\n    rs.radii = new Array(rs.segpts.length / 2).fill(radius);\n    rs.isArcRadius = new Array(rs.segpts.length / 2).fill(isArcRadius);\n  }\n};\nBRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {\n  var rs = edge._private.rscratch;\n\n  // can only correct beziers for now...\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      srcCornerRadius = pairInfo.srcCornerRadius,\n      tgtCornerRadius = pairInfo.tgtCornerRadius,\n      srcRs = pairInfo.srcRs,\n      tgtRs = pairInfo.tgtRs;\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    if (badStart || badAStart || closeStartACp) {\n      overlapping = true;\n\n      // project control point along line from src centre to outside the src shape\n      // (otherwise intersection will yield nothing)\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      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, srcCornerRadius, srcRs);\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    if (badEnd || badAEnd || closeEndACp) {\n      overlapping = true;\n\n      // project control point along line from tgt centre to outside the tgt shape\n      // (otherwise intersection will yield nothing)\n      var _cpD = {\n        // delta\n        x: rs.ctrlpts[0] - tgtPos.x,\n        y: rs.ctrlpts[1] - tgtPos.y\n      };\n      var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line\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 tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0, tgtCornerRadius, tgtRs);\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    if (overlapping) {\n      // recalc endpts\n      this.findEndpoints(edge);\n    }\n  }\n};\nBRp$c.storeAllpts = function (edge) {\n  var rs = edge._private.rscratch;\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    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]);\n\n      // the midpt between ctrlpts as intermediate destination pts\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    rs.allpts.push(rs.endX, rs.endY);\n    var m, mt;\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];\n\n    // default midpt for labels etc\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    if (rs.isRound) {\n      rs.roundCorners = [];\n      for (var i = 2; i + 3 < rs.allpts.length; i += 2) {\n        var radius = rs.radii[i / 2 - 1];\n        var isArcRadius = rs.isArcRadius[i / 2 - 1];\n        rs.roundCorners.push(getRoundCorner({\n          x: rs.allpts[i - 2],\n          y: rs.allpts[i - 1]\n        }, {\n          x: rs.allpts[i],\n          y: rs.allpts[i + 1],\n          radius: radius\n        }, {\n          x: rs.allpts[i + 2],\n          y: rs.allpts[i + 3]\n        }, radius, isArcRadius));\n      }\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      if (!rs.isRound) {\n        rs.midX = rs.segpts[_i];\n        rs.midY = rs.segpts[_i + 1];\n      } else {\n        var point = {\n          x: rs.segpts[_i],\n          y: rs.segpts[_i + 1]\n        };\n        var corner = rs.roundCorners[_i / 2];\n        if (corner.radius === 0) {\n          // On collinear points\n          var nextPoint = {\n            x: rs.segpts[_i + 2],\n            y: rs.segpts[_i + 3]\n          };\n          rs.midX = point.x;\n          rs.midY = point.y;\n          rs.midVector = [point.y - nextPoint.y, nextPoint.x - point.x];\n        } else {\n          // On rounded points\n          var v = [point.x - corner.cx, point.y - corner.cy];\n          var factor = corner.radius / Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));\n          v = v.map(function (c) {\n            return c * factor;\n          });\n          rs.midX = corner.cx + v[0];\n          rs.midY = corner.cy + v[1];\n          rs.midVector = v;\n        }\n      }\n    }\n  }\n};\nBRp$c.checkForInvalidEdgeWarning = function (edge) {\n  var rs = edge[0]._private.rscratch;\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};\nBRp$c.findEdgeControlPoints = function (edges) {\n  var _this = this;\n  if (!edges || edges.length === 0) {\n    return;\n  }\n  var r = this;\n  var cy = r.cy;\n  var hasCompounds = cy.hasCompoundNodes();\n  var hashTable = new Map$1();\n  var getKey = function getKey(pairId, edgeIsUnbundled) {\n    return [].concat(_toConsumableArray(pairId), [edgeIsUnbundled ? 1 : 0]).join('-');\n  };\n  var pairIds = [];\n  var haystackEdges = [];\n\n  // create a table of edge (src, tgt) => list of edges between them\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;\n\n    // ignore edges who are not to be displayed\n    // they shouldn't take up space\n    if (edge.removed() || !edge.takesUpSpace()) {\n      continue;\n    }\n    if (curveStyle === 'haystack') {\n      haystackEdges.push(edge);\n      continue;\n    }\n    var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || curveStyle.endsWith('segments') || curveStyle === 'straight' || curveStyle === 'straight-triangle' || curveStyle.endsWith('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 key = getKey(pairId, edgeIsUnbundled);\n    var tableEntry = hashTable.get(key);\n    if (tableEntry == null) {\n      tableEntry = {\n        eles: []\n      };\n      pairIds.push({\n        pairId: pairId,\n        edgeIsUnbundled: edgeIsUnbundled\n      });\n      hashTable.set(key, tableEntry);\n    }\n    tableEntry.eles.push(edge);\n    if (edgeIsUnbundled) {\n      tableEntry.hasUnbundled = true;\n    }\n    if (edgeIsBezier) {\n      tableEntry.hasBezier = true;\n    }\n  }\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  var _loop = function _loop() {\n    var _pairIds$p = pairIds[p],\n      pairId = _pairIds$p.pairId,\n      edgeIsUnbundled = _pairIds$p.edgeIsUnbundled;\n    var key = getKey(pairId, edgeIsUnbundled);\n    var pairInfo = hashTable.get(key);\n    var swappedpairInfo;\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      });\n\n      // for each pair id, the edges should be sorted by index\n      pairInfo.eles.sort(function (edge1, edge2) {\n        return edge1.poolIndex() - edge2.poolIndex();\n      });\n    }\n    var firstEdge = pairInfo.eles[0];\n    var src = firstEdge.source();\n    var tgt = firstEdge.target();\n\n    // make sure src/tgt distinction is consistent w.r.t. pairId\n    if (src.poolIndex() > tgt.poolIndex()) {\n      var temp = src;\n      src = tgt;\n      tgt = temp;\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    var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];\n    var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];\n    var srcCornerRadius = pairInfo.srcCornerRadius = src.pstyle('corner-radius').value === 'auto' ? 'auto' : src.pstyle('corner-radius').pfValue;\n    var tgtCornerRadius = pairInfo.tgtCornerRadius = tgt.pstyle('corner-radius').value === 'auto' ? 'auto' : tgt.pstyle('corner-radius').pfValue;\n    var tgtRs = pairInfo.tgtRs = tgt._private.rscratch;\n    var srcRs = pairInfo.srcRs = src._private.rscratch;\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    for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {\n      var _edge = pairInfo.eles[_i2];\n      var rs = _edge[0]._private.rscratch;\n      var _curveStyle = _edge.pstyle('curve-style').value;\n      var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || _curveStyle.endsWith('segments') || _curveStyle.endsWith('taxi');\n\n      // whether the normalised pair order is the reverse of the edge's src-tgt order\n      var edgeIsSwapped = !src.same(_edge.source());\n      if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {\n        pairInfo.calculatedIntersection = true;\n\n        // pt outside src shape to calc distance/displacement from src to tgt\n        var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0, srcCornerRadius, srcRs);\n        var srcIntn = pairInfo.srcIntn = srcOutside;\n\n        // pt outside tgt shape to calc distance/displacement from src to tgt\n        var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0, tgtCornerRadius, tgtRs);\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        };\n\n        // if node shapes overlap, then no ctrl pts to draw\n        pairInfo.nodesOverlap = !number$1(l) || tgtShape.checkPoint(srcOutside[0], srcOutside[1], 0, tgtW, tgtH, tgtPos.x, tgtPos.y, tgtCornerRadius, tgtRs) || srcShape.checkPoint(tgtOutside[0], tgtOutside[1], 0, srcW, srcH, srcPos.x, srcPos.y, srcCornerRadius, srcRs);\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          srcRs: tgtRs,\n          tgtPos: srcPos,\n          tgtRs: srcRs,\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      var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;\n      rs.nodesOverlap = passedPairInfo.nodesOverlap;\n      rs.srcIntn = passedPairInfo.srcIntn;\n      rs.tgtIntn = passedPairInfo.tgtIntn;\n      rs.isRound = _curveStyle.startsWith('round');\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.endsWith('segments')) {\n        _this.findSegmentsPoints(_edge, passedPairInfo);\n      } else if (_curveStyle.endsWith('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      _this.findEndpoints(_edge);\n      _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);\n      _this.checkForInvalidEdgeWarning(_edge);\n      _this.storeAllpts(_edge);\n      _this.storeEdgeProjections(_edge);\n      _this.calculateArrowAngles(_edge);\n      _this.recalculateEdgeLabelProjections(_edge);\n      _this.calculateLabelAngles(_edge);\n    } // for pair edges\n  };\n  for (var p = 0; p < pairIds.length; p++) {\n    _loop();\n  } // for pair ids\n\n  // haystacks avoid the expense of pairInfo stuff (intersections etc.)\n  this.findHaystackPoints(haystackEdges);\n};\nfunction getPts(pts) {\n  var retPts = [];\n  if (pts == null) {\n    return;\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  return retPts;\n}\nBRp$c.getSegmentPoints = function (edge) {\n  var rs = edge[0]._private.rscratch;\n  this.recalculateRenderedStyle(edge);\n  var type = rs.edgeType;\n  if (type === 'segments') {\n    return getPts(rs.segpts);\n  }\n};\nBRp$c.getControlPoints = function (edge) {\n  var rs = edge[0]._private.rscratch;\n  this.recalculateRenderedStyle(edge);\n  var type = rs.edgeType;\n  if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {\n    return getPts(rs.ctrlpts);\n  }\n};\nBRp$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\nvar BRp$b = {};\nBRp$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  var rs = node._private.rscratch;\n  if (prop.value.length === 2) {\n    var p = [prop.pfValue[0], prop.pfValue[1]];\n    if (prop.units[0] === '%') {\n      p[0] = p[0] * w;\n    }\n    if (prop.units[1] === '%') {\n      p[1] = p[1] * h;\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, node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue, rs);\n  }\n};\nBRp$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 srcRs = source._private.rscratch;\n  var tgtRs = target._private.rscratch;\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 srcCornerRadius = source.pstyle('corner-radius').value === 'auto' ? 'auto' : source.pstyle('corner-radius').pfValue;\n  var tgtManEndpt = edge.pstyle('target-endpoint');\n  var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;\n  var tgtCornerRadius = target.pstyle('corner-radius').value === 'auto' ? 'auto' : target.pstyle('corner-radius').pfValue;\n  rs.srcManEndpt = srcManEndpt;\n  rs.tgtManEndpt = tgtManEndpt;\n  var p1; // last known point of edge on target side\n  var p2; // last known point of edge on source side\n\n  var p1_i; // point to intersect with target shape\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  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    intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0, tgtCornerRadius, tgtRs);\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      if (va === 'top') {\n        ly -= lh2;\n      } else if (va === 'bottom') {\n        ly += lh2;\n      }\n      var ha = target.pstyle('text-halign').value;\n      if (ha === 'left') {\n        lx -= lw2;\n      } else if (ha === 'right') {\n        lx += lw2;\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      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        if (labIntSqdist < intSqdist) {\n          intersect = labelIntersect;\n          minSqDist = labIntSqdist;\n        }\n        if (labelIntersect.length > 2) {\n          var labInt2SqDist = sqdist(refPt, {\n            x: labelIntersect[2],\n            y: labelIntersect[3]\n          });\n          if (labInt2SqDist < minSqDist) {\n            intersect = [labelIntersect[2], labelIntersect[3]];\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  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    intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0, srcCornerRadius, srcRs);\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      var _lw2 = _lw / 2;\n      var _lh2 = _lh / 2;\n      var _va = source.pstyle('text-valign').value;\n      if (_va === 'top') {\n        _ly -= _lh2;\n      } else if (_va === 'bottom') {\n        _ly += _lh2;\n      }\n      var _ha = source.pstyle('text-halign').value;\n      if (_ha === 'left') {\n        _lx -= _lw2;\n      } else if (_ha === 'right') {\n        _lx += _lw2;\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      if (_labelIntersect.length > 0) {\n        var _refPt = tgtPos;\n        var _intSqdist = sqdist(_refPt, array2point(intersect));\n        var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));\n        var _minSqDist = _intSqdist;\n        if (_labIntSqdist < _intSqdist) {\n          intersect = [_labelIntersect[0], _labelIntersect[1]];\n          _minSqDist = _labIntSqdist;\n        }\n        if (_labelIntersect.length > 2) {\n          var _labInt2SqDist = sqdist(_refPt, {\n            x: _labelIntersect[2],\n            y: _labelIntersect[3]\n          });\n          if (_labInt2SqDist < _minSqDist) {\n            intersect = [_labelIntersect[2], _labelIntersect[3]];\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  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};\nBRp$b.getSourceEndpoint = function (edge) {\n  var rs = edge[0]._private.rscratch;\n  this.recalculateRenderedStyle(edge);\n  switch (rs.edgeType) {\n    case 'haystack':\n      return {\n        x: rs.haystackPts[0],\n        y: rs.haystackPts[1]\n      };\n    default:\n      return {\n        x: rs.arrowStartX,\n        y: rs.arrowStartY\n      };\n  }\n};\nBRp$b.getTargetEndpoint = function (edge) {\n  var rs = edge[0]._private.rscratch;\n  this.recalculateRenderedStyle(edge);\n  switch (rs.edgeType) {\n    case 'haystack':\n      return {\n        x: rs.haystackPts[2],\n        y: rs.haystackPts[3]\n      };\n    default:\n      return {\n        x: rs.arrowEndX,\n        y: rs.arrowEndY\n      };\n  }\n};\n\nvar BRp$a = {};\nfunction pushBezierPts(r, edge, pts) {\n  var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {\n    return qbezierAt(p1, p2, p3, t);\n  };\n  var _p = edge._private;\n  var bpts = _p.rstyle.bezierPts;\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}\nBRp$a.storeEdgeProjections = function (edge) {\n  var _p = edge._private;\n  var rs = _p.rscratch;\n  var et = rs.edgeType;\n\n  // clear the cached points state\n  _p.rstyle.bezierPts = null;\n  _p.rstyle.linePts = null;\n  _p.rstyle.haystackPts = null;\n  if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {\n    _p.rstyle.bezierPts = [];\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    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  _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;\n};\nBRp$a.recalculateEdgeProjections = function (edges) {\n  this.findEdgeControlPoints(edges);\n};\n\nvar BRp$9 = {};\nBRp$9.recalculateNodeLabelProjection = function (node) {\n  var content = node.pstyle('label').strValue;\n  if (emptyString(content)) {\n    return;\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  switch (textHalign) {\n    case 'left':\n      textX = nodePos.x - nodeWidth / 2 - padding;\n      break;\n    case 'right':\n      textX = nodePos.x + nodeWidth / 2 + padding;\n      break;\n    default:\n      // e.g. center\n      textX = nodePos.x;\n  }\n  switch (textValign) {\n    case 'top':\n      textY = nodePos.y - nodeHeight / 2 - padding;\n      break;\n    case 'bottom':\n      textY = nodePos.y + nodeHeight / 2 + padding;\n      break;\n    default:\n      // e.g. middle\n      textY = nodePos.y;\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};\nvar lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {\n  var angle = Math.atan(dy / dx);\n  if (dx === 0 && angle < 0) {\n    angle = angle * -1;\n  }\n  return angle;\n};\nvar 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};\nvar 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};\nBRp$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  if (content.mid || content.source || content.target) ; else {\n    return; // no labels => no calcs\n  }\n\n  // add center point to style so bounding box calculations can use it\n  //\n  p = {\n    x: rs.midX,\n    y: rs.midY\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  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  var _createControlPointInfo = function createControlPointInfo() {\n    if (_createControlPointInfo.cache) {\n      return _createControlPointInfo.cache;\n    } // use cache so only 1x per edge\n\n    var ctrlpts = [];\n\n    // store each ctrlpt info init\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      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    var bpts = _p.rstyle.bezierPts;\n    var nProjs = r.bezierProjPcts.length;\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    }\n\n    // update each ctrlpt with segment info\n    for (var _i = 0; _i < ctrlpts.length; _i++) {\n      var cp = ctrlpts[_i];\n      var prevCp = ctrlpts[_i - 1];\n      if (prevCp) {\n        cp.startDist = prevCp.startDist + prevCp.length;\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      addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last\n    }\n    return _createControlPointInfo.cache = ctrlpts;\n  };\n  var calculateEndProjection = function calculateEndProjection(prefix) {\n    var angle;\n    var isSrc = prefix === 'source';\n    if (!content[prefix]) {\n      return;\n    }\n    var offset = edge.pstyle(prefix + '-text-offset').pfValue;\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;\n\n          // find the segment we're on\n          for (var i = 0; i < cps.length; i++) {\n            var _cp = cps[isSrc ? i : cps.length - 1 - i];\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              if (totalDist >= offset || lastSeg) {\n                selected = {\n                  cp: _cp,\n                  segment: _seg\n                };\n                break;\n              }\n            }\n            if (selected) {\n              break;\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      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          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            di = dist(p0, p1);\n            d0 = d;\n            d += di;\n            if (d >= offset) {\n              break;\n            }\n          }\n          var pD = offset - d0;\n          var _t = pD / di;\n          _t = bound(0, _t, 1);\n          p = lineAt(p0, p1, _t);\n          angle = lineAngle(p0, p1);\n          break;\n        }\n    }\n    setRs('labelX', prefix, p.x);\n    setRs('labelY', prefix, p.y);\n    setRs('labelAutoAngle', prefix, angle);\n  };\n  calculateEndProjection('source');\n  calculateEndProjection('target');\n  this.applyLabelDimensions(edge);\n};\nBRp$9.applyLabelDimensions = function (ele) {\n  this.applyPrefixedLabelDimensions(ele);\n  if (ele.isEdge()) {\n    this.applyPrefixedLabelDimensions(ele, 'source');\n    this.applyPrefixedLabelDimensions(ele, 'target');\n  }\n};\nBRp$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};\nBRp$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  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  };\n\n  // for empty text, skip all processing\n  if (!text) {\n    return '';\n  }\n  if (textTransform == 'none') ; else if (textTransform == 'uppercase') {\n    text = text.toUpperCase();\n  } else if (textTransform == 'lowercase') {\n    text = text.toLowerCase();\n  }\n  var wrapStyle = ele.pstyle('text-wrap').value;\n  if (wrapStyle === 'wrap') {\n    var labelKey = rscratch('labelKey');\n\n    // save recalc if the label is the same as before\n    if (labelKey != null && rscratch('labelWrapKey') === labelKey) {\n      return rscratch('labelWrapCachedText');\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 separatorRegex = /[\\s\\u200b]+|$/g; // Include end of string to add last word\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      if (overflowAny) {\n        var processedLine = line.split('').join(zwsp);\n        line = processedLine;\n      }\n      if (lineW > maxW) {\n        // line is too long\n        var separatorMatches = line.matchAll(separatorRegex);\n        var subline = '';\n        var previousIndex = 0;\n        // Add fake match\n        var _iterator = _createForOfIteratorHelper(separatorMatches),\n          _step;\n        try {\n          for (_iterator.s(); !(_step = _iterator.n()).done;) {\n            var separatorMatch = _step.value;\n            var wordSeparator = separatorMatch[0];\n            var word = line.substring(previousIndex, separatorMatch.index);\n            previousIndex = separatorMatch.index + wordSeparator.length;\n            var testLine = subline.length === 0 ? word : subline + word + wordSeparator;\n            var testDims = this.calculateLabelDimensions(ele, testLine);\n            var testW = testDims.width;\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              subline = word + wordSeparator;\n            }\n          }\n\n          // if there's remaining text, put it in a wrapped line\n        } catch (err) {\n          _iterator.e(err);\n        } finally {\n          _iterator.f();\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    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    if (this.calculateLabelDimensions(ele, text).width < _maxW) {\n      // the label already fits\n      return text;\n    }\n    for (var i = 0; i < text.length; i++) {\n      var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;\n      if (widthWithNextCh > _maxW) {\n        break;\n      }\n      ellipsized += text[i];\n      if (i === text.length - 1) {\n        incLastCh = true;\n      }\n    }\n    if (!incLastCh) {\n      ellipsized += ellipsis;\n    }\n    return ellipsized;\n  } // if ellipsize\n\n  return text;\n};\nBRp$9.getLabelJustification = function (ele) {\n  var justification = ele.pstyle('text-justification').strValue;\n  var textHalign = ele.pstyle('text-halign').strValue;\n  if (justification === 'auto') {\n    if (ele.isNode()) {\n      switch (textHalign) {\n        case 'left':\n          return 'right';\n        case 'right':\n          return 'left';\n        default:\n          return 'center';\n      }\n    } else {\n      return 'center';\n    }\n  } else {\n    return justification;\n  }\n};\nBRp$9.calculateLabelDimensions = function (ele, text) {\n  var r = this;\n  var containerWindow = r.cy.window();\n  var document = containerWindow.document;\n  var cacheKey = hashString(text, ele._private.labelDimsKey);\n  var cache = r.labelDimCache || (r.labelDimCache = []);\n  var existingVal = cache[cacheKey];\n  if (existingVal != null) {\n    return existingVal;\n  }\n  var padding = 0; // add padding around text dims, as the measurement isn't that accurate\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  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  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  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  width += padding;\n  height += padding;\n  return cache[cacheKey] = {\n    width: width,\n    height: height\n  };\n};\nBRp$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  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};\nBRp$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  if (isEdge) {\n    rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');\n    rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');\n  }\n};\n\nvar BRp$8 = {};\nvar TOO_SMALL_CUT_RECT = 28;\nvar warnedCutRect = false;\nBRp$8.getNodeShape = function (node) {\n  var r = this;\n  var shape = node.pstyle('shape').value;\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    return 'rectangle';\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  if (shape === 'polygon') {\n    var points = node.pstyle('shape-polygon-points').value;\n    return r.nodeShapes.makePolygon(points).name;\n  }\n  return shape;\n};\n\nvar BRp$7 = {};\nBRp$7.registerCalculationListeners = function () {\n  var cy = this.cy;\n  var elesToUpdate = cy.collection();\n  var r = this;\n  var enqueue = function enqueue(eles) {\n    var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n    elesToUpdate.merge(eles);\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  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  var updateEleCalcs = function updateEleCalcs(willDraw) {\n    if (willDraw) {\n      var fns = r.onUpdateEleCalcsFns;\n\n      // 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      elesToUpdate.cleanStyle();\n      for (var i = 0; i < elesToUpdate.length; i++) {\n        var ele = elesToUpdate[i];\n        var rstyle = ele._private.rstyle;\n        if (ele.isNode() && !rstyle.cleanConnected) {\n          enqueue(ele.connectedEdges());\n          rstyle.cleanConnected = true;\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      r.recalculateRenderedStyle(elesToUpdate);\n      elesToUpdate = cy.collection();\n    }\n  };\n  r.flushRenderedStyleQueue = function () {\n    updateEleCalcs(true);\n  };\n  r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);\n};\nBRp$7.onUpdateEleCalcs = function (fn) {\n  var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];\n  fns.push(fn);\n};\nBRp$7.recalculateRenderedStyle = function (eles, useCache) {\n  var isCleanConnected = function isCleanConnected(ele) {\n    return ele._private.rstyle.cleanConnected;\n  };\n  if (eles.length === 0) {\n    return;\n  }\n  var edges = [];\n  var nodes = [];\n\n  // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()\n  if (this.destroyed) {\n    return;\n  }\n\n  // use cache by default for perf\n  if (useCache === undefined) {\n    useCache = true;\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;\n\n    // 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    if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {\n      rstyle.clean = false;\n    }\n    if (ele.isEdge() && ele.isBundledBezier()) {\n      if (ele.parallelEdges().some(function (ele) {\n        return !ele._private.rstyle.clean && ele.isBundledBezier();\n      })) {\n        rstyle.clean = false;\n      }\n    }\n\n    // only update if dirty and in graph\n    if (useCache && rstyle.clean || ele.removed()) {\n      continue;\n    }\n\n    // only update if not display: none\n    if (ele.pstyle('display').value === 'none') {\n      continue;\n    }\n    if (_p.group === 'nodes') {\n      nodes.push(ele);\n    } else {\n      // edges\n      edges.push(ele);\n    }\n    rstyle.clean = true;\n  }\n\n  // update node data from projections\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    var pos = _ele.position();\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  this.recalculateEdgeProjections(edges);\n\n  // update edge data from projections\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;\n\n    // update rstyle positions\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\nvar BRp$6 = {};\nBRp$6.updateCachedGrabbedEles = function () {\n  var eles = this.cachedZSortedEles;\n  if (!eles) {\n    // just let this be recalculated on the next z sort tick\n    return;\n  }\n  eles.drag = [];\n  eles.nondrag = [];\n  var grabTargets = [];\n  for (var i = 0; i < eles.length; i++) {\n    var ele = eles[i];\n    var rs = ele._private.rscratch;\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  }\n\n  // put the grab target nodes last so it's on top of its neighbourhood\n  for (var i = 0; i < grabTargets.length; i++) {\n    var ele = grabTargets[i];\n    eles.drag.push(ele);\n  }\n};\nBRp$6.invalidateCachedZSortedEles = function () {\n  this.cachedZSortedEles = null;\n};\nBRp$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  return eles;\n};\n\nvar 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\nvar BRp$4 = {};\nBRp$4.getCachedImage = function (url, crossOrigin, onLoad) {\n  var r = this;\n  var imageCache = r.imageCache = r.imageCache || {};\n  var cache = imageCache[url];\n  if (cache) {\n    if (!cache.image.complete) {\n      cache.image.addEventListener('load', onLoad);\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    });\n\n    // #1582 safari doesn't load data uris with crossOrigin properly\n    // https://bugs.webkit.org/show_bug.cgi?id=123978\n    var dataUriPrefix = 'data:';\n    var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;\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    image.src = url;\n    return image;\n  }\n};\n\nvar BRp$3 = {};\n\n/* global document, ResizeObserver, MutationObserver */\n\nBRp$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  if (Array.isArray(target)) {\n    var res = [];\n    for (var i = 0; i < target.length; i++) {\n      var t = target[i];\n      if (t !== undefined) {\n        var b = this.binder(t);\n        res.push(b.on.apply(b, args));\n      }\n    }\n    return res;\n  }\n  var b = this.binder(target);\n  return b.on.apply(b, args);\n};\nBRp$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  if (r.supportsPassiveEvents == null) {\n    // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection\n    var supportsPassive = false;\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) {\n      // not supported\n    }\n    r.supportsPassiveEvents = supportsPassive;\n  }\n  var on = function on(event, handler, useCapture) {\n    var args = Array.prototype.slice.call(arguments);\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    r.bindings.push({\n      target: tgt,\n      args: args\n    });\n    (tgt.addEventListener || tgt.on).apply(tgt, args);\n    return this;\n  };\n  return {\n    on: on,\n    addEventListener: on,\n    addListener: on,\n    bind: on\n  };\n};\nBRp$3.nodeIsDraggable = function (node) {\n  return node && node.isNode() && !node.locked() && node.grabbable();\n};\nBRp$3.nodeIsGrabbable = function (node) {\n  return this.nodeIsDraggable(node) && node.interactive();\n};\nBRp$3.load = function () {\n  var r = this;\n  var containerWindow = r.cy.window();\n  var isSelected = function isSelected(ele) {\n    return ele.selected();\n  };\n  var getShadowRoot = function getShadowRoot(element) {\n    var rootNode = element.getRootNode();\n    // Check if the root node is a shadow root\n    if (rootNode && rootNode.nodeType === 11 && rootNode.host !== undefined) {\n      return rootNode;\n    }\n  };\n  var triggerEvents = function triggerEvents(target, names, e, position) {\n    if (target == null) {\n      target = r.cy;\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  var isMultSelKeyDown = function isMultSelKeyDown(e) {\n    return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey\n  };\n  var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {\n    var allowPassthrough = true;\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];\n\n        //if any parent node in event hierarchy isn't pannable, reject passthrough\n        if (down.isNode() && down.isParent() && !down.pannable()) {\n          allowPassthrough = false;\n          break;\n        }\n      }\n    } else {\n      allowPassthrough = true;\n    }\n    return allowPassthrough;\n  };\n  var setGrabbed = function setGrabbed(ele) {\n    ele[0]._private.grabbed = true;\n  };\n  var setFreed = function setFreed(ele) {\n    ele[0]._private.grabbed = false;\n  };\n  var setInDragLayer = function setInDragLayer(ele) {\n    ele[0]._private.rscratch.inDragLayer = true;\n  };\n  var setOutDragLayer = function setOutDragLayer(ele) {\n    ele[0]._private.rscratch.inDragLayer = false;\n  };\n  var setGrabTarget = function setGrabTarget(ele) {\n    ele[0]._private.rscratch.isGrabTarget = true;\n  };\n  var removeGrabTarget = function removeGrabTarget(ele) {\n    ele[0]._private.rscratch.isGrabTarget = false;\n  };\n  var addToDragList = function addToDragList(ele, opts) {\n    var list = opts.addToList;\n    var listHasEle = list.has(ele);\n    if (!listHasEle && ele.grabbable() && !ele.locked()) {\n      list.merge(ele);\n      setGrabbed(ele);\n    }\n  };\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  var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {\n    if (!node.cy().hasCompoundNodes()) {\n      return;\n    }\n    if (opts.inDragLayer == null && opts.addToList == null) {\n      return;\n    } // nothing to do\n\n    var innerNodes = node.descendants();\n    if (opts.inDragLayer) {\n      innerNodes.forEach(setInDragLayer);\n      innerNodes.connectedEdges().forEach(setInDragLayer);\n    }\n    if (opts.addToList) {\n      addToDragList(innerNodes, opts);\n    }\n  };\n\n  // adds the given nodes and its neighbourhood to the drag layer\n  var addNodesToDrag = function addNodesToDrag(nodes, opts) {\n    opts = opts || {};\n    var hasCompoundNodes = nodes.cy().hasCompoundNodes();\n    if (opts.inDragLayer) {\n      nodes.forEach(setInDragLayer);\n      nodes.neighborhood().stdFilter(function (ele) {\n        return !hasCompoundNodes || ele.isEdge();\n      }).forEach(setInDragLayer);\n    }\n    if (opts.addToList) {\n      nodes.forEach(function (ele) {\n        addToDragList(ele, opts);\n      });\n    }\n    addDescendantsToDrag(nodes, opts); // always add to drag\n\n    // also add nodes and edges related to the topmost ancestor\n    updateAncestorsInDragLayer(nodes, {\n      inDragLayer: opts.inDragLayer\n    });\n    r.updateCachedGrabbedEles();\n  };\n  var addNodeToDrag = addNodesToDrag;\n  var freeDraggedElements = function freeDraggedElements(grabbedEles) {\n    if (!grabbedEles) {\n      return;\n    }\n\n    // just go over all elements rather than doing a bunch of (possibly expensive) traversals\n    r.getCachedZSortedEles().forEach(function (ele) {\n      setFreed(ele);\n      setOutDragLayer(ele);\n      removeGrabTarget(ele);\n    });\n    r.updateCachedGrabbedEles();\n  };\n\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  var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {\n    if (opts.inDragLayer == null && opts.addToList == null) {\n      return;\n    } // nothing to do\n\n    if (!node.cy().hasCompoundNodes()) {\n      return;\n    }\n\n    // find top-level parent\n    var parent = node.ancestors().orphans();\n\n    // no parent node: no nodes to add to the drag layer\n    if (parent.same(node)) {\n      return;\n    }\n    var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());\n    var edges = nodes.connectedEdges();\n    if (opts.inDragLayer) {\n      edges.forEach(setInDragLayer);\n      nodes.forEach(setInDragLayer);\n    }\n    if (opts.addToList) {\n      nodes.forEach(function (ele) {\n        addToDragList(ele, opts);\n      });\n    }\n  };\n  var blurActiveDomElement = function blurActiveDomElement() {\n    if (document.activeElement != null && document.activeElement.blur != null) {\n      document.activeElement.blur();\n    }\n  };\n  var haveMutationsApi = typeof MutationObserver !== 'undefined';\n  var haveResizeObserverApi = typeof ResizeObserver !== 'undefined';\n\n  // watch for when the cy container is removed from the dom\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        if (rNodes) {\n          for (var j = 0; j < rNodes.length; j++) {\n            var rNode = rNodes[j];\n            if (rNode === r.container) {\n              r.destroy();\n              break;\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  var onResize = debounce(function () {\n    r.cy.resize();\n  }, 100);\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  }\n\n  // auto resize\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  var forEachUp = function forEachUp(domEle, fn) {\n    while (domEle != null) {\n      fn(domEle);\n      domEle = domEle.parentNode;\n    }\n  };\n  var invalidateCoords = function invalidateCoords() {\n    r.invalidateContainerClientCoordsCache();\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  });\n\n  // stop right click menu from appearing on cy\n  r.registerBinding(r.container, 'contextmenu', function (e) {\n    e.preventDefault();\n  });\n  var inBoxSelection = function inBoxSelection() {\n    return r.selection[4] !== 0;\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    for (var i = 0; i < positions.length; i++) {\n      var p = positions[i];\n      if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {\n        atLeastOnePosInside = true;\n        break;\n      }\n    }\n    if (!atLeastOnePosInside) {\n      return false;\n    }\n    var container = r.container;\n    var target = e.target;\n    var tParent = target.parentNode;\n    var containerIsTarget = false;\n    while (tParent) {\n      if (tParent === container) {\n        containerIsTarget = true;\n        break;\n      }\n      tParent = tParent.parentNode;\n    }\n    if (!containerIsTarget) {\n      return false;\n    } // if target is outisde cy container, then this event is not for us\n\n    return true;\n  };\n\n  // Primary key\n  r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {\n    if (!eventInContainer(e)) {\n      return;\n    }\n\n    // during left mouse button gestures, ignore other buttons\n    if (r.hoverData.which === 1 && e.which !== 1) {\n      return;\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    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          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    };\n\n    // Right click button\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      if (near) {\n        near.activate();\n        near.emit(cxtEvt);\n        r.hoverData.down = near;\n      } else {\n        cy.emit(cxtEvt);\n      }\n      r.hoverData.downTime = new Date().getTime();\n      r.hoverData.cxtDragged = false;\n\n      // Primary button\n    } else if (e.which == 1) {\n      if (near) {\n        near.activate();\n      }\n\n      // Element dragging\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            var triggerGrab = function triggerGrab(ele) {\n              ele.emit(makeEvent('grab'));\n            };\n            setGrabTarget(near);\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            r.redrawHint('eles', true);\n            r.redrawHint('drag', true);\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      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      checkForTaphold();\n    }\n\n    // Initialize selection box coordinates\n    select[0] = select[2] = pos[0];\n    select[1] = select[3] = pos[1];\n  }, false);\n  var shadowRoot = getShadowRoot(r.container);\n  r.registerBinding([containerWindow, shadowRoot], 'mousemove', function mousemoveHandler(e) {\n    // eslint-disable-line no-undef\n    var capture = r.hoverData.capture;\n    if (!capture && !eventInContainer(e)) {\n      return;\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    if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {\n      near = r.findNearestElement(pos[0], pos[1], true, false);\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    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    var multSelKeyDown = isMultSelKeyDown(e);\n    if (isOverThresholdDrag) {\n      r.hoverData.tapholdCancelled = true;\n    }\n    var updateDragDelta = function updateDragDelta() {\n      var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];\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    preventDefault = true;\n    triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {\n      x: pos[0],\n      y: pos[1]\n    });\n    var goIntoBoxMode = function goIntoBoxMode() {\n      r.data.bgActivePosistion = undefined;\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      select[4] = 1;\n      r.hoverData.selecting = true;\n      r.redrawHint('select', true);\n      r.redraw();\n    };\n\n    // trigger context drag if rmouse down\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        if (down) {\n          down.emit(cxtEvt);\n        } else {\n          cy.emit(cxtEvt);\n        }\n        r.hoverData.cxtDragged = true;\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          r.hoverData.cxtOver = near;\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      }\n\n      // Check if we are drag panning the entire graph\n    } else if (r.hoverData.dragging) {\n      preventDefault = true;\n      if (cy.panningEnabled() && cy.userPanningEnabled()) {\n        var deltaP;\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        cy.panBy(deltaP);\n        cy.emit('dragpan');\n        r.hoverData.dragged = true;\n      }\n\n      // Needs reproject due to pan changing viewport\n      pos = r.projectIntoViewport(e.clientX, e.clientY);\n\n      // 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          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        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      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        if (near) {\n          triggerEvents(near, ['mouseover', 'tapdragover'], e, {\n            x: pos[0],\n            y: pos[1]\n          });\n        }\n        r.hoverData.last = near;\n      }\n      if (down) {\n        if (isOverThresholdDrag) {\n          // then we can take action\n\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              if (r.dragData.didDrag) {\n                down.emit('dragfreeon');\n                draggedElements.emit('dragfree');\n              }\n            }\n            goIntoBoxMode();\n          } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {\n            // drag node\n            var justStartedDrag = !r.dragData.didDrag;\n            if (justStartedDrag) {\n              r.redrawHint('eles', true);\n            }\n            r.dragData.didDrag = true; // indicate that we actually did drag the node\n\n            // now, add the elements to the drag layer if not done already\n            if (!r.hoverData.draggingEles) {\n              addNodesToDrag(draggedElements, {\n                inDragLayer: true\n              });\n            }\n            var totalShift = {\n              x: 0,\n              y: 0\n            };\n            if (number$1(disp[0]) && number$1(disp[1])) {\n              totalShift.x += disp[0];\n              totalShift.y += disp[1];\n              if (justStartedDrag) {\n                var dragDelta = r.hoverData.dragDelta;\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            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      }\n\n      // prevent the dragging from triggering text selection on the page\n      preventDefault = true;\n    }\n    select[2] = pos[0];\n    select[3] = pos[1];\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    // during left mouse button gestures, ignore other buttons\n    if (r.hoverData.which === 1 && e.which !== 1 && r.hoverData.capture) {\n      return;\n    }\n    var capture = r.hoverData.capture;\n    if (!capture) {\n      return;\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    if (r.data.bgActivePosistion) {\n      r.redrawHint('select', true);\n      r.redraw();\n    }\n    r.hoverData.tapholdCancelled = true;\n    r.data.bgActivePosistion = undefined; // not active bg now\n\n    if (down) {\n      down.unactivate();\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      if (down) {\n        down.emit(cxtEvt);\n      } else {\n        cy.emit(cxtEvt);\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        if (down) {\n          down.emit(cxtTap);\n        } else {\n          cy.emit(cxtTap);\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      if (!r.dragData.didDrag &&\n      // didn't move a node around\n      !r.hoverData.dragged &&\n      // didn't pan\n      !r.hoverData.selecting &&\n      // 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        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      }\n\n      // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something\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        if (draggedElements.length > 0) {\n          r.redrawHint('eles', true);\n        }\n        r.dragData.possibleDragElements = draggedElements = cy.collection();\n      }\n\n      // Single selection\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          r.redrawHint('eles', true);\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        if (box.length > 0) {\n          r.redrawHint('eles', true);\n        }\n        cy.emit({\n          type: 'boxend',\n          originalEvent: e,\n          position: {\n            x: pos[0],\n            y: pos[1]\n          }\n        });\n        var eleWouldBeSelected = function eleWouldBeSelected(ele) {\n          return ele.selectable() && !ele.selected();\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          box.emit('box').stdFilter(eleWouldBeSelected).select().emit('boxselect');\n        }\n\n        // always need redraw in case eles unselectable\n        r.redraw();\n      }\n\n      // Cancel drag pan\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      if (!select[4]) {\n        r.redrawHint('drag', true);\n        r.redrawHint('eles', true);\n        var downWasGrabbed = down && down.grabbed();\n        freeDraggedElements(draggedElements);\n        if (downWasGrabbed) {\n          down.emit('freeon');\n          draggedElements.emit('free');\n          if (r.dragData.didDrag) {\n            down.emit('dragfreeon');\n            draggedElements.emit('dragfree');\n          }\n        }\n      }\n    } // else not right mouse\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    r.hoverData.which = null;\n  }, false);\n  var wheelHandler = function wheelHandler(e) {\n    if (r.scrollingPage) {\n      return;\n    } // while scrolling, ignore wheel-to-zoom\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    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    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      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      diff = diff * r.wheelSensitivity;\n      var needsWheelFix = e.deltaMode === 1;\n      if (needsWheelFix) {\n        // fixes slow wheel events on ff/linux and ff/windows\n        diff *= 33;\n      }\n      var newZoom = cy.zoom() * Math.pow(10, diff);\n      if (e.type === 'gesturechange') {\n        newZoom = r.gestureStartZoom * e.scale;\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  };\n\n  // Functions to help with whether mouse wheel should trigger zooming\n  // --\n  r.registerBinding(r.container, 'wheel', wheelHandler, true);\n\n  // 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);\n\n  // desktop safari pinch to zoom start\n  r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {\n    r.gestureStartZoom = r.cy.zoom();\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);\n\n  // Functions to help with handling mouseout/mouseover on the Cytoscape container\n  // Handle mouseout on Cytoscape container\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  var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom\n  var center1, modelCenter1; // center point on start pinch to zoom\n  var offsetLeft, offsetTop;\n  var containerWidth, containerHeight;\n  var twoFingersStartInside;\n  var distance = function distance(x1, y1, x2, y2) {\n    return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n  };\n  var distanceSq = function distanceSq(x1, y1, x2, y2) {\n    return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n  };\n  var touchstartHandler;\n  r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {\n    r.hasTouchStarted = true;\n    if (!eventInContainer(e)) {\n      return;\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    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    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    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    // record starting points for pinch-to-zoom\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];\n\n      // consider context tap\n      var cxtDistThreshold = 200;\n      var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;\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        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        if (r.touchData.start) {\n          r.touchData.start._private.grabbed = false;\n        }\n        r.touchData.cxt = true;\n        r.touchData.cxtDragged = false;\n        r.data.bgActivePosistion = undefined;\n        r.redraw();\n        return;\n      }\n    }\n    if (e.touches[2]) {\n      // ignore\n\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      if (near != null) {\n        near.activate();\n        r.touchData.start = near;\n        r.touchData.starts = nears;\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          if (near.selected()) {\n            // reset drag elements, since near will be added again\n\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          setGrabTarget(near);\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          near.emit(makeEvent('grabon'));\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      triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {\n        x: now[0],\n        y: now[1]\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      }\n\n      // Tap, taphold\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    if (e.touches.length >= 1) {\n      var sPos = r.touchData.startPosition = [null, null, null, null, null, null];\n      for (var i = 0; i < now.length; i++) {\n        sPos[i] = earlier[i] = now[i];\n      }\n      var touch0 = e.touches[0];\n      r.touchData.startGPosition = [touch0.clientX, touch0.clientY];\n    }\n  }, false);\n  var touchmoveHandler;\n  r.registerBinding(containerWindow, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {\n    // eslint-disable-line no-undef\n    var capture = r.touchData.capture;\n    if (!capture && !eventInContainer(e)) {\n      return;\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    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    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    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    var startGPos = r.touchData.startGPosition;\n    var isOverThresholdDrag;\n    if (capture && e.touches[0] && startGPos) {\n      var disp = [];\n      for (var j = 0; j < now.length; j++) {\n        disp[j] = now[j] - earlier[j];\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    }\n\n    // context swipe cancelling\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;\n      // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );\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;\n\n      // cancel ctx gestures if the distance b/t the fingers increases\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        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    }\n\n    // context swipe\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      if (r.touchData.start) {\n        r.touchData.start.emit(cxtEvt);\n      } else {\n        cy.emit(cxtEvt);\n      }\n      if (r.touchData.start) {\n        r.touchData.start._private.grabbed = false;\n      }\n      r.touchData.cxtDragged = true;\n      var near = r.findNearestElement(now[0], now[1], true, true);\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        r.touchData.cxtOver = near;\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      }\n\n      // box selection\n    } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {\n      e.preventDefault();\n      r.data.bgActivePosistion = undefined;\n      this.lastThreeTouch = +new Date();\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      r.touchData.selecting = true;\n      r.touchData.didSelect = true;\n      select[4] = 1;\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      r.redrawHint('select', true);\n      r.redraw();\n\n      // 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      if (draggedEles) {\n        r.redrawHint('drag', true);\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      var _start = r.touchData.start;\n\n      // (x2, y2) for fingers 1 and 2\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);\n      // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );\n      // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );\n      var factor = distance2 / distance1;\n      if (twoFingersStartInside) {\n        // delta finger1\n        var df1x = f1x2 - f1x1;\n        var df1y = f1y2 - f1y1;\n\n        // delta finger 2\n        var df2x = f2x2 - f2x1;\n        var df2y = f2y2 - f2y1;\n\n        // translation is the normalised vector of the two fingers movement\n        // i.e. so pinching cancels out and moving together pans\n        var tx = (df1x + df2x) / 2;\n        var ty = (df1y + df2y) / 2;\n\n        // now calculate the zoom\n        var zoom1 = cy.zoom();\n        var zoom2 = zoom1 * factor;\n        var pan1 = cy.pan();\n\n        // the model center point converted to the current rendered pos\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        };\n\n        // remove dragged eles\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          _start.unactivate().emit('freeon');\n          draggedEles.emit('free');\n          if (r.dragData.didDrag) {\n            _start.emit('dragfreeon');\n            draggedEles.emit('dragfree');\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      }\n\n      // Re-project\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      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      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      if (!r.hoverData.draggingEles && !r.swipePanning) {\n        near = r.findNearestElement(now[0], now[1], true, true);\n      }\n      if (capture && start != null) {\n        e.preventDefault();\n      }\n\n      // dragging nodes\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          if (justStartedDrag) {\n            addNodesToDrag(draggedEles, {\n              inDragLayer: true\n            });\n          }\n          r.dragData.didDrag = true;\n          var totalShift = {\n            x: 0,\n            y: 0\n          };\n          if (number$1(disp[0]) && number$1(disp[1])) {\n            totalShift.x += disp[0];\n            totalShift.y += disp[1];\n            if (justStartedDrag) {\n              r.redrawHint('eles', true);\n              var dragDelta = r.touchData.dragDelta;\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          r.hoverData.draggingEles = true;\n          draggedEles.silentShift(totalShift).emit('position drag');\n          r.redrawHint('drag', true);\n          if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {\n            r.redrawHint('eles', true);\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          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\n      // touchmove\n      {\n        triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {\n          x: now[0],\n          y: now[1]\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          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        r.touchData.last = near;\n      }\n\n      // check to cancel taphold\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      }\n\n      // panning\n      if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {\n        var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);\n        if (allowPassthrough) {\n          e.preventDefault();\n          if (!r.data.bgActivePosistion) {\n            r.data.bgActivePosistion = array2point(r.touchData.startPosition);\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            if (start) {\n              start.unactivate();\n              r.redrawHint('select', true);\n              r.touchData.start = null;\n            }\n          }\n        }\n\n        // Re-project\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    for (var j = 0; j < now.length; j++) {\n      earlier[j] = now[j];\n    }\n\n    // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning\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    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    if (capture) {\n      if (e.touches.length === 0) {\n        r.touchData.capture = false;\n      }\n      e.preventDefault();\n    } else {\n      return;\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    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    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    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    if (start) {\n      start.unactivate();\n    }\n    var ctxTapend;\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      if (start) {\n        start.emit(ctxTapend);\n      } else {\n        cy.emit(ctxTapend);\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        if (start) {\n          start.emit(ctxTap);\n        } else {\n          cy.emit(ctxTap);\n        }\n      }\n      if (r.touchData.start) {\n        r.touchData.start._private.grabbed = false;\n      }\n      r.touchData.cxt = false;\n      r.touchData.start = null;\n      r.redraw();\n      return;\n    }\n\n    // no more box selection if we don't have three fingers\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      var eleWouldBeSelected = function eleWouldBeSelected(ele) {\n        return ele.selectable() && !ele.selected();\n      };\n      box.emit('box').stdFilter(eleWouldBeSelected).select().emit('boxselect');\n      if (box.nonempty()) {\n        r.redrawHint('eles', true);\n      }\n      r.redraw();\n    }\n    if (start != null) {\n      start.unactivate();\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      if (start != null) {\n        var startWasGrabbed = start._private.grabbed;\n        freeDraggedElements(draggedEles);\n        r.redrawHint('drag', true);\n        r.redrawHint('eles', true);\n        if (startWasGrabbed) {\n          start.emit('freeon');\n          draggedEles.emit('free');\n          if (r.dragData.didDrag) {\n            start.emit('dragfreeon');\n            draggedEles.emit('dragfree');\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      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;\n\n      // Tap event, roughly same as mouse click event for touch\n      if (!r.touchData.singleTouchMoved) {\n        if (!start) {\n          cy.$(':selected').unselect(['tapunselect']);\n        }\n        triggerEvents(start, ['tap', 'vclick'], e, {\n          x: now[0],\n          y: now[1]\n        });\n        didDoubleTouch = false;\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      }\n\n      // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance\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        r.redrawHint('eles', true);\n      }\n      r.touchData.singleTouchMoved = true;\n    }\n    for (var j = 0; j < now.length; j++) {\n      earlier[j] = now[j];\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    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      r.pinching = false;\n      r.redrawHint('eles', true);\n      r.redraw();\n    }\n\n    //r.redraw();\n  }, false);\n\n  // fallback compatibility layer for ms pointer events\n  if (typeof TouchEvent === 'undefined') {\n    var pointers = [];\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    var makePointer = function makePointer(e) {\n      return {\n        event: e,\n        touch: makeTouch(e)\n      };\n    };\n    var addPointer = function addPointer(e) {\n      pointers.push(makePointer(e));\n    };\n    var removePointer = function removePointer(e) {\n      for (var i = 0; i < pointers.length; i++) {\n        var p = pointers[i];\n        if (p.event.pointerId === e.pointerId) {\n          pointers.splice(i, 1);\n          return;\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    var addTouchesToEvent = function addTouchesToEvent(e) {\n      e.touches = pointers.map(function (p) {\n        return p.touch;\n      });\n    };\n    var pointerIsMouse = function pointerIsMouse(e) {\n      return e.pointerType === 'mouse' || e.pointerType === 4;\n    };\n    r.registerBinding(r.container, 'pointerdown', function (e) {\n      if (pointerIsMouse(e)) {\n        return;\n      } // mouse already handled\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      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      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      e.preventDefault();\n      updatePointer(e);\n      addTouchesToEvent(e);\n      touchmoveHandler(e);\n    });\n  }\n};\n\nvar BRp$2 = {};\nBRp$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, cornerRadius) {\n      this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);\n    },\n    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\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, cornerRadius) {\n      return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);\n    }\n  };\n};\nBRp$2.generateEllipse = function () {\n  return this.nodeShapes['ellipse'] = {\n    renderer: this,\n    name: 'ellipse',\n    draw: function draw(context, centerX, centerY, width, height, cornerRadius) {\n      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n    },\n    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\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, cornerRadius) {\n      return checkInEllipse(x, y, width, height, centerX, centerY, padding);\n    }\n  };\n};\nBRp$2.generateRoundPolygon = function (name, points) {\n  return this.nodeShapes[name] = {\n    renderer: this,\n    name: name,\n    points: points,\n    getOrCreateCorners: function getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, field) {\n      if (rs[field] !== undefined && rs[field + '-cx'] === centerX && rs[field + '-cy'] === centerY) {\n        return rs[field];\n      }\n      rs[field] = new Array(points.length / 2);\n      rs[field + '-cx'] = centerX;\n      rs[field + '-cy'] = centerY;\n      var halfW = width / 2;\n      var halfH = height / 2;\n      cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(width, height) : cornerRadius;\n      var p = new Array(points.length / 2);\n      for (var _i = 0; _i < points.length / 2; _i++) {\n        p[_i] = {\n          x: centerX + halfW * points[_i * 2],\n          y: centerY + halfH * points[_i * 2 + 1]\n        };\n      }\n      var i,\n        p1,\n        p2,\n        p3,\n        len = p.length;\n      p1 = p[len - 1];\n      // for each point\n      for (i = 0; i < len; i++) {\n        p2 = p[i % len];\n        p3 = p[(i + 1) % len];\n        rs[field][i] = getRoundCorner(p1, p2, p3, cornerRadius);\n        p1 = p2;\n        p2 = p3;\n      }\n      return rs[field];\n    },\n    draw: function draw(context, centerX, centerY, width, height, cornerRadius, rs) {\n      this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'drawCorners'));\n    },\n    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius, rs) {\n      return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height, padding, this.getOrCreateCorners(nodeX, nodeY, width, height, cornerRadius, rs, 'corners'));\n    },\n    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius, rs) {\n      return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'corners'));\n    }\n  };\n};\nBRp$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, cornerRadius) {\n      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);\n    },\n    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n      return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);\n    },\n    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n      var halfWidth = width / 2;\n      var halfHeight = height / 2;\n      cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;\n      cornerRadius = Math.min(halfWidth, halfHeight, cornerRadius);\n      var diam = cornerRadius * 2;\n\n      // Check hBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {\n        return true;\n      }\n\n      // Check vBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {\n        return true;\n      }\n\n      // Check top left quarter circle\n      if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY - halfHeight + cornerRadius, padding)) {\n        return true;\n      }\n\n      // Check top right quarter circle\n      if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY - halfHeight + cornerRadius, padding)) {\n        return true;\n      }\n\n      // Check bottom right quarter circle\n      if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY + halfHeight - cornerRadius, padding)) {\n        return true;\n      }\n\n      // Check bottom left quarter circle\n      if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY + halfHeight - cornerRadius, padding)) {\n        return true;\n      }\n      return false;\n    }\n  };\n};\nBRp$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, cornerRadius) {\n      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, null, cornerRadius);\n    },\n    generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY, cornerRadius) {\n      var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;\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\n      // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]\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, cornerRadius) {\n      var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY, cornerRadius);\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, cornerRadius) {\n      var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;\n      // Check hBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * cl, [0, -1], padding)) {\n        return true;\n      }\n\n      // Check vBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * cl, height, [0, -1], padding)) {\n        return true;\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};\nBRp$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, cornerRadius) {\n      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);\n    },\n    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\n      // use two fixed t values for the bezier curve approximation\n\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      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      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;\n\n      // points are in clockwise order, inner (imaginary) control pt on [4, 5]\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, cornerRadius) {\n      var curveConstants = getBarrelCurveConstants(width, height);\n      var hOffset = curveConstants.heightOffset;\n      var wOffset = curveConstants.widthOffset;\n\n      // Check hBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {\n        return true;\n      }\n\n      // Check vBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {\n        return true;\n      }\n      var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);\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];\n        // var y1 = curvePts[ 3 ];\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        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          if (validRoots.length > 0) {\n            return validRoots[0];\n          }\n        }\n        return null;\n      };\n      var curveRegions = Object.keys(barrelCurvePts);\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        if (t == null) {\n          continue;\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        if (cornerPts.isTop && bezY <= y) {\n          return true;\n        }\n        if (cornerPts.isBottom && y <= bezY) {\n          return true;\n        }\n      }\n      return false;\n    }\n  };\n};\nBRp$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, cornerRadius) {\n      this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);\n    },\n    intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {\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      if (topIntersections.length > 0) {\n        return topIntersections;\n      }\n      return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);\n    },\n    checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {\n      cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;\n      var diam = 2 * cornerRadius;\n\n      // Check hBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {\n        return true;\n      }\n\n      // Check vBox\n      if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {\n        return true;\n      }\n\n      // check non-rounded top side\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      if (pointInsidePolygonPoints(x, y, points)) {\n        return true;\n      }\n\n      // Check bottom right quarter circle\n      if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n        return true;\n      }\n\n      // Check bottom left quarter circle\n      if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {\n        return true;\n      }\n      return false;\n    }\n  };\n};\nBRp$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);\n\n    // Outer radius is 1; inner radius of star is smaller\n    var innerRadius = 0.5 * (3 - Math.sqrt(5));\n    innerRadius *= 1.57;\n    for (var i = 0; i < innerPoints.length / 2; i++) {\n      innerPoints[i * 2] *= innerRadius;\n      innerPoints[i * 2 + 1] *= innerRadius;\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  nodeShapes.makePolygon = function (points) {\n    // use caching on user-specified polygons so they are as fast as native shapes\n\n    var key = points.join('$');\n    var name = 'polygon-' + key;\n    var shape;\n    if (shape = this[name]) {\n      // got cached shape\n      return shape;\n    }\n\n    // create and cache new shape\n    return renderer.generatePolygon(name, points);\n  };\n};\n\nvar BRp$1 = {};\nBRp$1.timeToRender = function () {\n  return this.redrawTotalTime / this.redrawCount;\n};\nBRp$1.redraw = function (options) {\n  options = options || staticEmptyObject();\n  var r = this;\n  if (r.averageRedrawTime === undefined) {\n    r.averageRedrawTime = 0;\n  }\n  if (r.lastRedrawTime === undefined) {\n    r.lastRedrawTime = 0;\n  }\n  if (r.lastDrawTime === undefined) {\n    r.lastDrawTime = 0;\n  }\n  r.requestedFrame = true;\n  r.renderOptions = options;\n};\nBRp$1.beforeRender = function (fn, priority) {\n  // the renderer can't add tick callbacks when destroyed\n  if (this.destroyed) {\n    return;\n  }\n  if (priority == null) {\n    error('Priority is not optional for beforeRender');\n  }\n  var cbs = this.beforeRenderCallbacks;\n  cbs.push({\n    fn: fn,\n    priority: priority\n  });\n\n  // higher priority callbacks executed first\n  cbs.sort(function (a, b) {\n    return b.priority - a.priority;\n  });\n};\nvar beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {\n  var cbs = r.beforeRenderCallbacks;\n  for (var i = 0; i < cbs.length; i++) {\n    cbs[i].fn(willDraw, startTime);\n  }\n};\nBRp$1.startRenderLoop = function () {\n  var r = this;\n  var cy = r.cy;\n  if (r.renderLoopStarted) {\n    return;\n  } else {\n    r.renderLoopStarted = true;\n  }\n  var _renderFn = function renderFn(requestTime) {\n    if (r.destroyed) {\n      return;\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      if (r.averageRedrawTime === undefined) {\n        r.averageRedrawTime = endTime - startTime;\n      }\n      if (r.redrawCount === undefined) {\n        r.redrawCount = 0;\n      }\n      r.redrawCount++;\n      if (r.redrawTotalTime === undefined) {\n        r.redrawTotalTime = 0;\n      }\n      var duration = endTime - startTime;\n      r.redrawTotalTime += duration;\n      r.lastRedrawTime = duration;\n\n      // use a weighted average with a bias from the previous average so we don't spike so easily\n      r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;\n      r.requestedFrame = false;\n    } else {\n      beforeRenderCallbacks(r, false, requestTime);\n    }\n    r.skipFrame = false;\n    requestAnimationFrame(_renderFn);\n  };\n  requestAnimationFrame(_renderFn);\n};\n\nvar BaseRenderer = function BaseRenderer(options) {\n  this.init(options);\n};\nvar BR = BaseRenderer;\nvar BRp = BR.prototype;\nBRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];\nBRp.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();\n\n  // prepend a stylesheet in the head such that\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    if (ctr.className.indexOf(className) < 0) {\n      ctr.className = (ctr.className || '') + ' ' + className;\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    var computedStyle = containerWindow.getComputedStyle(ctr);\n    var position = computedStyle.getPropertyValue('position');\n    if (position === 'static') {\n      warn('A Cytoscape container has style position:static and so can not use UI extensions properly');\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];\n\n  //--Pointer-related data\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.webgl = options.webgl;\n  r.hideEdgesOnViewport = options.hideEdgesOnViewport;\n  r.textureOnViewport = options.textureOnViewport;\n  r.wheelSensitivity = options.wheelSensitivity;\n  r.motionBlurEnabled = options.motionBlur; // on by default\n  r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;\n  r.motionBlur = options.motionBlur; // for initial kick off\n  r.motionBlurOpacity = options.motionBlurOpacity;\n  r.motionBlurTransparency = 1 - r.motionBlurOpacity;\n  r.motionBlurPxRatio = 1;\n  r.mbPxRBlurry = 1; //0.8;\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};\nBRp.notify = function (eventName, eles) {\n  var r = this;\n  var cy = r.cy;\n\n  // the renderer can't be notified after it's destroyed\n  if (this.destroyed) {\n    return;\n  }\n  if (eventName === 'init') {\n    r.load();\n    return;\n  }\n  if (eventName === 'destroy') {\n    r.destroy();\n    return;\n  }\n  if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {\n    r.invalidateCachedZSortedEles();\n  }\n  if (eventName === 'viewport') {\n    r.redrawHint('select', true);\n  }\n  if (eventName === 'gc') {\n    r.redrawHint('gc', true);\n  }\n  if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {\n    r.invalidateContainerClientCoordsCache();\n    r.matchCanvasSize(r.container);\n  }\n  r.redrawHint('eles', true);\n  r.redrawHint('drag', true);\n  this.startRenderLoop();\n  this.redraw();\n};\nBRp.destroy = function () {\n  var r = this;\n  r.destroyed = true;\n  r.cy.stopAnimationLoop();\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  r.bindings = [];\n  r.beforeRenderCallbacks = [];\n  r.onUpdateEleCalcsFns = [];\n  if (r.removeObserver) {\n    r.removeObserver.disconnect();\n  }\n  if (r.styleObserver) {\n    r.styleObserver.disconnect();\n  }\n  if (r.resizeObserver) {\n    r.resizeObserver.disconnect();\n  }\n  if (r.labelCalcDiv) {\n    try {\n      document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef\n    } catch (e) {\n      // ie10 issue #1014\n    }\n  }\n};\nBRp.isHeadless = function () {\n  return false;\n};\n[BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {\n  extend(BRp, props);\n});\n\nvar fullFpsTime = 1000 / 60; // assume 60 frames per second\n\nvar defs = {\n  setupDequeueing: function setupDequeueing(opts) {\n    return function setupDequeueingImpl() {\n      var self = this;\n      var r = this.renderer;\n      if (self.dequeueingSetup) {\n        return;\n      } else {\n        self.dequeueingSetup = true;\n      }\n      var queueRedraw = debounce(function () {\n        r.redrawHint('eles', true);\n        r.redrawHint('drag', true);\n        r.redraw();\n      }, opts.deqRedrawThreshold);\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();\n\n        // 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        if (!willDraw) {\n          r.flushRenderedStyleQueue();\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          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\n            var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);\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          var thisDeqd = opts.deq(self, pixelRatio, extent);\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        }\n\n        // callbacks on dequeue\n        if (deqd.length > 0) {\n          opts.onDeqd(self, deqd);\n          if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {\n            queueRedraw();\n          }\n        }\n      };\n      var priority = opts.priority || noop$1;\n      r.beforeRender(dequeue, priority(self));\n    };\n  }\n};\n\n// Allows lookups for (ele, lvl) => cache.\n// Uses keys so elements may share the same cache.\nvar ElementTextureCacheLookup = /*#__PURE__*/function () {\n  function ElementTextureCacheLookup(getKey) {\n    var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;\n    _classCallCheck(this, ElementTextureCacheLookup);\n    this.idsByKey = new Map$1();\n    this.keyForId = new Map$1();\n    this.cachesByLvl = new Map$1();\n    this.lvls = [];\n    this.getKey = getKey;\n    this.doesEleInvalidateKey = doesEleInvalidateKey;\n  }\n  return _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      var idsByKey = this.idsByKey;\n      var ids = this.idsByKey.get(key);\n      if (!ids) {\n        ids = new Set$1();\n        idsByKey.set(key, ids);\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      if (!caches) {\n        caches = new Map$1();\n        cachesByLvl.set(lvl, caches);\n        lvls.push(lvl);\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);\n\n      // getting for an element may need to add to the id list b/c eles can share keys\n      if (cache != null) {\n        this.updateKeyMappingFor(ele);\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      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      this.lvls.forEach(function (lvl) {\n        return _this.deleteCache(key, lvl);\n      });\n    }\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    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      if (entireKeyInvalidated) {\n        // clear mapping for current key\n        this.invalidateKey(key);\n      }\n      return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;\n    }\n  }]);\n}();\n\nvar minTxrH = 25; // the size of the texture cache for small height eles (special case)\nvar txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up\nvar minLvl$1 = -4; // when scaling smaller than that we don't need to re-render\nvar maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)\nvar maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used\nvar eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps\nvar defTxrWidth = 1024; // default/minimum texture width\nvar maxTxrW = 1024; // the maximum width of a texture\nvar maxTxrH = 1024; // the maximum height of a texture\nvar minUtility = 0.2; // if usage of texture is less than this, it is retired\nvar maxFullness = 0.8; // fullness of texture after which queue removal is checked\nvar maxFullnessChecks = 10; // dequeued after this many checks\nvar deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame\nvar deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time\nvar deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing\nvar deqFastCost$1 = 0.9; // % of frame time to be used when >60fps\nvar deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile\nvar maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch\n\nvar getTxrReasons = {\n  dequeue: 'dequeue',\n  downscale: 'downscale',\n  highQuality: 'highQuality'\n};\nvar 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});\nvar 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};\nvar ETCp = ElementTextureCache.prototype;\nETCp.reasons = getTxrReasons;\n\n// the list of textures in which new subtextures for elements can be placed\nETCp.getTextureQueue = function (txrH) {\n  var self = this;\n  self.eleImgCaches = self.eleImgCaches || {};\n  return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];\n};\n\n// the list of usused textures which can be recycled (in use in texture queue)\nETCp.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};\n\n// queue of element draw requests at different scale levels\nETCp.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};\n\n// queue of element draw requests at different scale levels (element id lookup)\nETCp.getElementKeyToQueue = function () {\n  var self = this;\n  var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};\n  return k2q;\n};\nETCp.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  if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {\n    return null;\n  }\n  if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {\n    return null;\n  }\n  if (lvl == null) {\n    lvl = Math.ceil(log2(zoom * pxRatio));\n  }\n  if (lvl < minLvl$1) {\n    lvl = minLvl$1;\n  } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {\n    return null;\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  if (!this.isVisible(ele, scaledLabelShown)) {\n    return null;\n  }\n  var eleCache = lookup.get(ele, lvl);\n\n  // if this get was on an unused/invalidated cache, then restore the texture usage metric\n  if (eleCache && eleCache.invalidated) {\n    eleCache.invalidated = false;\n    eleCache.texture.invalidatedWidth -= eleCache.width;\n  }\n  if (eleCache) {\n    return eleCache;\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  if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {\n    return null; // caching large elements is not efficient\n  }\n  var txrQ = self.getTextureQueue(txrH);\n\n  // first try the second last one in case it has space at the end\n  var txr = txrQ[txrQ.length - 2];\n  var addNewTxr = function addNewTxr() {\n    return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);\n  };\n\n  // try the last one if there is no second last one\n  if (!txr) {\n    txr = txrQ[txrQ.length - 1];\n  }\n\n  // if the last one doesn't exist, we need a first one\n  if (!txr) {\n    txr = addNewTxr();\n  }\n\n  // if there's no room in the current texture, we need a new one\n  if (txr.width - txr.usedWidth < eleScaledW) {\n    txr = addNewTxr();\n  }\n  var scalableFrom = function scalableFrom(otherCache) {\n    return otherCache && otherCache.scaledLabelShown === scaledLabelShown;\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  for (var l = lvl + 1; l <= maxLvl$1; l++) {\n    var c = lookup.get(ele, l);\n    if (c) {\n      higherCache = c;\n      break;\n    }\n  }\n  var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;\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  };\n\n  // reset ele area in texture\n  txr.context.setTransform(1, 0, 0, 1, 0, 0);\n  txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);\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\n    if (highQualityReq) {\n      for (var _l = higherCache.level; _l > lvl; _l--) {\n        oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);\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    if (!deqing && !highQualityReq && !downscaleReq) {\n      for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {\n        var _c = lookup.get(ele, _l2);\n        if (_c) {\n          lowerCache = _c;\n          break;\n        }\n      }\n    }\n    if (scalableFrom(lowerCache)) {\n      // then use the lower quality cache for now and queue the better one for later\n\n      self.queueElement(ele, lvl);\n      return lowerCache;\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  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};\nETCp.invalidateElements = function (eles) {\n  for (var i = 0; i < eles.length; i++) {\n    this.invalidateElement(eles[i]);\n  }\n};\nETCp.invalidateElement = function (ele) {\n  var self = this;\n  var lookup = self.lookup;\n  var caches = [];\n  var invalid = lookup.isInvalid(ele);\n  if (!invalid) {\n    return; // override the invalidation request if the element key has not changed\n  }\n  for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {\n    var cache = lookup.getForCachedKey(ele, lvl);\n    if (cache) {\n      caches.push(cache);\n    }\n  }\n  var noOtherElesUseCache = lookup.invalidate(ele);\n  if (noOtherElesUseCache) {\n    for (var i = 0; i < caches.length; i++) {\n      var _cache = caches[i];\n      var txr = _cache.texture;\n\n      // remove space from the texture it belongs to\n      txr.invalidatedWidth += _cache.width;\n\n      // mark the cache as invalidated\n      _cache.invalidated = true;\n\n      // retire the texture if its utility is low\n      self.checkTextureUtility(txr);\n    }\n  }\n\n  // remove from queue since the old req was for the old state\n  self.removeFromQueue(ele);\n};\nETCp.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};\nETCp.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\n  var self = this;\n  var txrQ = self.getTextureQueue(txr.height);\n  if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {\n    removeFromArray(txrQ, txr);\n  } else {\n    txr.fullnessChecks++;\n  }\n};\nETCp.retireTexture = function (txr) {\n  var self = this;\n  var txrH = txr.height;\n  var txrQ = self.getTextureQueue(txrH);\n  var lookup = this.lookup;\n\n  // retire the texture from the active / searchable queue:\n\n  removeFromArray(txrQ, txr);\n  txr.retired = true;\n\n  // remove the refs from the eles to the caches:\n\n  var eleCaches = txr.eleCaches;\n  for (var i = 0; i < eleCaches.length; i++) {\n    var eleCache = eleCaches[i];\n    lookup.deleteCache(eleCache.key, eleCache.level);\n  }\n  clearArray(eleCaches);\n\n  // 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};\nETCp.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};\nETCp.recycleTexture = function (txrH, minW) {\n  var self = this;\n  var txrQ = self.getTextureQueue(txrH);\n  var rtxtrQ = self.getRetiredTextureQueue(txrH);\n  for (var i = 0; i < rtxtrQ.length; i++) {\n    var txr = rtxtrQ[i];\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};\nETCp.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  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};\nETCp.dequeue = function (pxRatio /*, extent*/) {\n  var self = this;\n  var q = self.getElementQueue();\n  var k2q = self.getElementKeyToQueue();\n  var dequeued = [];\n  var lookup = self.lookup;\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      var cacheExists = lookup.hasCache(ele, req.level);\n\n      // clear out the key to req lookup\n      k2q[key] = null;\n\n      // dequeueing isn't necessary with an existing cache\n      if (cacheExists) {\n        continue;\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  return dequeued;\n};\nETCp.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  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};\nETCp.onDequeue = function (fn) {\n  this.onDequeues.push(fn);\n};\nETCp.offDequeue = function (fn) {\n  removeFromArray(this.onDequeues, fn);\n};\nETCp.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      for (var j = 0; j < eles.length; j++) {\n        var bb = eles[j].boundingBox();\n        if (boundingBoxesIntersect(bb, extent)) {\n          return true;\n        }\n      }\n    }\n    return false;\n  },\n  priority: function priority(self) {\n    return self.renderer.beforeRenderPriorities.eleTxrDeq;\n  }\n});\n\nvar defNumLayers = 1; // default number of layers to use\nvar minLvl = -4; // when scaling smaller than that we don't need to re-render\nvar maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)\nvar maxZoom = 3.99; // beyond this zoom level, layered textures are not used\nvar deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile\nvar refineEleDebounceTime = 50; // time to debounce sharper ele texture updates\nvar deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame\nvar deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time\nvar deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing\nvar deqFastCost = 0.9; // % of frame time to be used when >60fps\nvar maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch\nvar invalidThreshold = 250; // time threshold for disabling b/c of invalidations\nvar maxLayerArea = 4000 * 4000; // layers can't be bigger than this\nvar maxLayerDim = 32767; // maximum size for the width/height of layer canvases\nvar useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)\n\n// var log = function(){ console.log.apply( console, arguments ); };\n\nvar 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(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  var qSort = function qSort(a, b) {\n    return b.reqs - a.reqs;\n  };\n  self.layersQueue = new Heap(qSort);\n  self.setupDequeueing();\n};\nvar LTCp = LayeredTextureCache.prototype;\nvar layerIdPool = 0;\nvar MAX_INT = Math.pow(2, 53) - 1;\nLTCp.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  };\n\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;\n\n  // do the transform on creation to save cycles (it's the same for all eles)\n  cxt.scale(scale, scale);\n  cxt.translate(dx, dy);\n  return layer;\n};\nLTCp.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;\n\n  // 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    if (lvl < minLvl) {\n      lvl = minLvl;\n    } else if (zoom >= maxZoom || lvl > maxLvl) {\n      return null;\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  var checkTempLevels = function checkTempLevels() {\n    var canUseAsTmpLvl = function canUseAsTmpLvl(l) {\n      self.validateLayersElesOrdering(l, eles);\n      if (self.levelIsComplete(l, eles)) {\n        tmpLayers = layersByLvl[l];\n        return true;\n      }\n    };\n    var checkLvls = function checkLvls(dir) {\n      if (tmpLayers) {\n        return;\n      }\n      for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {\n        if (canUseAsTmpLvl(l)) {\n          break;\n        }\n      }\n    };\n    checkLvls(1);\n    checkLvls(-1);\n\n    // remove the invalid layers; they will be replaced as needed later in this function\n    for (var i = layers.length - 1; i >= 0; i--) {\n      var layer = layers[i];\n      if (layer.invalid) {\n        removeFromArray(layers, layer);\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\n    checkTempLevels();\n  } else {\n    // log('level complete, using existing layers\\n--');\n    return layers;\n  }\n  var getBb = function getBb() {\n    if (!bb) {\n      bb = makeBoundingBox();\n      for (var i = 0; i < eles.length; i++) {\n        updateBoundingBox(bb, eles[i].boundingBox());\n      }\n    }\n    return bb;\n  };\n  var makeLayer = function makeLayer(opts) {\n    opts = opts || {};\n    var after = opts.after;\n    getBb();\n    var w = Math.ceil(bb.w * scale);\n    var h = Math.ceil(bb.h * scale);\n    if (w > maxLayerDim || h > maxLayerDim) {\n      return null;\n    }\n    var area = w * h;\n    if (area > maxLayerArea) {\n      return null;\n    }\n    var layer = self.makeLayer(bb, lvl);\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    }\n\n    // if( tmpLayers ){\n    //self.queueLayer( layer );\n    // }\n\n    return layer;\n  };\n  if (self.skipping && !firstGet) {\n    // log('skip layers');\n    return null;\n  }\n\n  // log('do layers');\n\n  var layer = null;\n  var maxElesPerLayer = eles.length / defNumLayers;\n  var allowLazyQueueing = !firstGet;\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 || {};\n\n    // log('look at ele', ele.id());\n\n    var existingLayer = caches[lvl];\n    if (existingLayer) {\n      // reuse layer for later eles\n      // log('reuse layer for', ele.id());\n      layer = existingLayer;\n      continue;\n    }\n    if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {\n      // log('make new layer for ele %s', ele.id());\n\n      layer = makeLayer({\n        insert: true,\n        after: layer\n      });\n\n      // if now layer can be built then we can't use layers at this level\n      if (!layer) {\n        return null;\n      }\n\n      // log('new layer with id %s', layer.id);\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    layer.eles.push(ele);\n    caches[lvl] = layer;\n  }\n\n  // log('--');\n\n  if (tmpLayers) {\n    // then we only queued the current layerset and can't draw it yet\n    return tmpLayers;\n  }\n  if (allowLazyQueueing) {\n    // log('lazy queue level', lvl);\n    return null;\n  }\n  return layers;\n};\n\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\nLTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {\n  return lvl;\n};\nLTCp.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  if (bb.w === 0 || bb.h === 0 || !ele.visible()) {\n    return;\n  }\n  lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);\n  {\n    r.setImgSmoothing(context, false);\n  }\n  {\n    r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);\n  }\n  {\n    r.setImgSmoothing(context, true);\n  }\n};\nLTCp.levelIsComplete = function (lvl, eles) {\n  var self = this;\n  var layers = self.layersByLevel[lvl];\n  if (!layers || layers.length === 0) {\n    return false;\n  }\n  var numElesInLayers = 0;\n  for (var i = 0; i < layers.length; i++) {\n    var layer = layers[i];\n\n    // if there are any eles needed to be drawn yet, the level is not complete\n    if (layer.reqs > 0) {\n      return false;\n    }\n\n    // if the layer is invalid, the level is not complete\n    if (layer.invalid) {\n      return false;\n    }\n    numElesInLayers += layer.eles.length;\n  }\n\n  // we should have exactly the number of eles passed in to be complete\n  if (numElesInLayers !== eles.length) {\n    return false;\n  }\n  return true;\n};\nLTCp.validateLayersElesOrdering = function (lvl, eles) {\n  var layers = this.layersByLevel[lvl];\n  if (!layers) {\n    return;\n  }\n\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  for (var i = 0; i < layers.length; i++) {\n    var layer = layers[i];\n    var offset = -1;\n\n    // find the offset\n    for (var j = 0; j < eles.length; j++) {\n      if (layer.eles[0] === eles[j]) {\n        offset = j;\n        break;\n      }\n    }\n    if (offset < 0) {\n      // then the layer has nonexistent elements and is invalid\n      this.invalidateLayer(layer);\n      continue;\n    }\n\n    // the eles in the layer must be in the same continuous order, else the layer is invalid\n\n    var o = offset;\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\n        this.invalidateLayer(layer);\n        break;\n      }\n    }\n  }\n};\nLTCp.updateElementsInLayers = function (eles, update) {\n  var self = this;\n  var isEles = element(eles[0]);\n\n  // collect udpated elements (cascaded from the layers) and update each\n  // layer itself along the way\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    for (var l = minLvl; l <= maxLvl; l++) {\n      var layer = caches[l];\n      if (!layer) {\n        continue;\n      }\n\n      // if update is a request from the ele cache, then it affects only\n      // the matching level\n      if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {\n        continue;\n      }\n      update(layer, ele, req);\n    }\n  }\n};\nLTCp.haveLayers = function () {\n  var self = this;\n  var haveLayers = false;\n  for (var l = minLvl; l <= maxLvl; l++) {\n    var layers = self.layersByLevel[l];\n    if (layers && layers.length > 0) {\n      haveLayers = true;\n      break;\n    }\n  }\n  return haveLayers;\n};\nLTCp.invalidateElements = function (eles) {\n  var self = this;\n  if (eles.length === 0) {\n    return;\n  }\n  self.lastInvalidationTime = performanceNow();\n\n  // log('update invalidate layer time from eles');\n\n  if (eles.length === 0 || !self.haveLayers()) {\n    return;\n  }\n  self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {\n    self.invalidateLayer(layer);\n  });\n};\nLTCp.invalidateLayer = function (layer) {\n  // log('update invalidate layer time');\n\n  this.lastInvalidationTime = performanceNow();\n  if (layer.invalid) {\n    return;\n  } // save cycles\n\n  var lvl = layer.level;\n  var eles = layer.eles;\n  var layers = this.layersByLevel[lvl];\n\n  // log('invalidate layer', layer.id );\n\n  removeFromArray(layers, layer);\n  // layer.eles = [];\n\n  layer.elesQueue = [];\n  layer.invalid = true;\n  if (layer.replacement) {\n    layer.replacement.invalid = true;\n  }\n  for (var i = 0; i < eles.length; i++) {\n    var caches = eles[i]._private.rscratch.imgLayerCaches;\n    if (caches) {\n      caches[lvl] = null;\n    }\n  }\n};\nLTCp.refineElementTextures = function (eles) {\n  var self = this;\n\n  // log('refine', eles.length);\n\n  self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {\n    var rLyr = layer.replacement;\n    if (!rLyr) {\n      rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);\n      rLyr.replaces = layer;\n      rLyr.eles = layer.eles;\n\n      // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);\n    }\n    if (!rLyr.reqs) {\n      for (var i = 0; i < rLyr.eles.length; i++) {\n        self.queueLayer(rLyr, rLyr.eles[i]);\n      }\n\n      // log('queue replacement layer refinement', rLyr.id);\n    }\n  });\n};\nLTCp.enqueueElementRefinement = function (ele) {\n  this.eleTxrDeqs.merge(ele);\n  this.scheduleElementRefinement();\n};\nLTCp.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 || {};\n\n  // if a layer is going to be replaced, queuing is a waste of time\n  if (layer.replacement) {\n    return;\n  }\n  if (ele) {\n    if (hasId[ele.id()]) {\n      return;\n    }\n    elesQ.push(ele);\n    hasId[ele.id()] = true;\n  }\n  if (layer.reqs) {\n    layer.reqs++;\n    q.updateItem(layer);\n  } else {\n    layer.reqs = 1;\n    q.push(layer);\n  }\n};\nLTCp.dequeue = function (pxRatio) {\n  var self = this;\n  var q = self.layersQueue;\n  var deqd = [];\n  var eleDeqs = 0;\n  while (eleDeqs < maxDeqSize) {\n    if (q.size() === 0) {\n      break;\n    }\n    var layer = q.peek();\n\n    // if a layer has been or will be replaced, then don't waste time with it\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    }\n\n    // if this is a replacement layer that has been superceded, then forget it\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    if (layer.invalid) {\n      // log('replacement layer %s is invalid; dequeued', layer.id);\n      q.pop();\n      continue;\n    }\n    var ele = layer.elesQueue.shift();\n    if (ele) {\n      // log('dequeue layer %s', layer.id);\n\n      self.drawEleInLayer(layer, ele, layer.level, pxRatio);\n      eleDeqs++;\n    }\n    if (deqd.length === 0) {\n      // we need only one entry in deqd to queue redrawing etc\n      deqd.push(true);\n    }\n\n    // if the layer has all its eles done, then remove from the queue\n    if (layer.elesQueue.length === 0) {\n      q.pop();\n      layer.reqs = 0;\n\n      // log('dequeue of layer %s complete', layer.id);\n\n      // when a replacement layer is dequeued, it replaces the old layer in the level\n      if (layer.replaces) {\n        self.applyLayerReplacement(layer);\n      }\n      self.requestRedraw();\n    }\n  }\n  return deqd;\n};\nLTCp.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);\n\n  // 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  if (index < 0 || replaced.invalid) {\n    // log('replacement layer would have no effect', layer.id);\n    return;\n  }\n  layersInLevel[index] = layer; // replace level ref\n\n  // replace refs in eles\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    if (cache) {\n      cache[layer.level] = layer;\n    }\n  }\n\n  // log('apply replacement layer %s over %s', layer.id, replaced.id);\n\n  self.requestRedraw();\n};\nLTCp.requestRedraw = debounce(function () {\n  var r = this.renderer;\n  r.redrawHint('eles', true);\n  r.redrawHint('drag', true);\n  r.redraw();\n}, 100);\nLTCp.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\nvar CRp$b = {};\nvar impl;\nfunction 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}\nfunction triangleBackcurve(context, points, controlPoint) {\n  var firstPt;\n  for (var i = 0; i < points.length; i++) {\n    var pt = points[i];\n    if (i === 0) {\n      firstPt = pt;\n    }\n    context.lineTo(pt.x, pt.y);\n  }\n  context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);\n}\nfunction triangleTee(context, trianglePoints, teePoints) {\n  if (context.beginPath) {\n    context.beginPath();\n  }\n  var triPts = trianglePoints;\n  for (var i = 0; i < triPts.length; i++) {\n    var pt = triPts[i];\n    context.lineTo(pt.x, pt.y);\n  }\n  var teePts = teePoints;\n  var firstTeePt = teePoints[0];\n  context.moveTo(firstTeePt.x, firstTeePt.y);\n  for (var i = 1; i < teePts.length; i++) {\n    var pt = teePts[i];\n    context.lineTo(pt.x, pt.y);\n  }\n  if (context.closePath) {\n    context.closePath();\n  }\n}\nfunction circleTriangle(context, trianglePoints, rx, ry, r) {\n  if (context.beginPath) {\n    context.beginPath();\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  for (var i = 0; i < triPts.length; i++) {\n    var pt = triPts[i];\n    context.lineTo(pt.x, pt.y);\n  }\n  if (context.closePath) {\n    context.closePath();\n  }\n}\nfunction circle(context, rx, ry, r) {\n  context.arc(rx, ry, r, 0, Math.PI * 2, false);\n}\nCRp$b.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\nvar CRp$a = {};\nCRp$a.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {\n  var r = this;\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};\nCRp$a.drawElementOverlay = function (context, ele) {\n  var r = this;\n  if (ele.isNode()) {\n    r.drawNodeOverlay(context, ele);\n  } else {\n    r.drawEdgeOverlay(context, ele);\n  }\n};\nCRp$a.drawElementUnderlay = function (context, ele) {\n  var r = this;\n  if (ele.isNode()) {\n    r.drawNodeUnderlay(context, ele);\n  } else {\n    r.drawEdgeUnderlay(context, ele);\n  }\n};\nCRp$a.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {\n  var r = this;\n  var bb = eleTxrCache.getBoundingBox(ele);\n  if (bb.w === 0 || bb.h === 0) {\n    return;\n  } // ignore zero size case\n\n  var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);\n  if (eleCache != null) {\n    var opacity = getOpacity(r, ele);\n    if (opacity === 0) {\n      return;\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    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      if (!smooth) {\n        r.setImgSmoothing(context, true);\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    var oldGlobalAlpha;\n    if (opacity !== 1) {\n      oldGlobalAlpha = context.globalAlpha;\n      context.globalAlpha = oldGlobalAlpha * opacity;\n    }\n    context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);\n    if (opacity !== 1) {\n      context.globalAlpha = oldGlobalAlpha;\n    }\n    if (theta !== 0) {\n      context.rotate(-theta);\n      context.translate(-sx, -sy);\n      if (!smooth) {\n        r.setImgSmoothing(context, false);\n      }\n    }\n  } else {\n    eleTxrCache.drawElement(context, ele); // direct draw fallback\n  }\n};\nvar getZeroRotation = function getZeroRotation() {\n  return 0;\n};\nvar getLabelRotation = function getLabelRotation(r, ele) {\n  return r.getTextAngle(ele, null);\n};\nvar getSourceLabelRotation = function getSourceLabelRotation(r, ele) {\n  return r.getTextAngle(ele, 'source');\n};\nvar getTargetLabelRotation = function getTargetLabelRotation(r, ele) {\n  return r.getTextAngle(ele, 'target');\n};\nvar getOpacity = function getOpacity(r, ele) {\n  return ele.effectiveOpacity();\n};\nvar getTextOpacity = function getTextOpacity(e, ele) {\n  return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();\n};\nCRp$a.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  if (bb.w === 0 || bb.h === 0 || !ele.visible()) {\n    return;\n  }\n  if (!extent || boundingBoxesIntersect(bb, extent)) {\n    var isEdge = ele.isEdge();\n    var badLine = ele.element()._private.rscratch.badLine;\n    r.drawElementUnderlay(context, ele);\n    r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);\n    if (!isEdge || !badLine) {\n      r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);\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    r.drawElementOverlay(context, ele);\n  }\n};\nCRp$a.drawElements = function (context, eles) {\n  var r = this;\n  for (var i = 0; i < eles.length; i++) {\n    var ele = eles[i];\n    r.drawElement(context, ele);\n  }\n};\nCRp$a.drawCachedElements = function (context, eles, pxRatio, extent) {\n  var r = this;\n  for (var i = 0; i < eles.length; i++) {\n    var ele = eles[i];\n    r.drawCachedElement(context, ele, pxRatio, extent);\n  }\n};\nCRp$a.drawCachedNodes = function (context, eles, pxRatio, extent) {\n  var r = this;\n  for (var i = 0; i < eles.length; i++) {\n    var ele = eles[i];\n    if (!ele.isNode()) {\n      continue;\n    }\n    r.drawCachedElement(context, ele, pxRatio, extent);\n  }\n};\nCRp$a.drawLayeredElements = function (context, eles, pxRatio, extent) {\n  var r = this;\n  var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);\n  if (layers) {\n    for (var i = 0; i < layers.length; i++) {\n      var layer = layers[i];\n      var bb = layer.bb;\n      if (bb.w === 0 || bb.h === 0) {\n        continue;\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\nvar CRp$9 = {};\nCRp$9.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  if (shouldDrawOpacity && !edge.visible()) {\n    return;\n  }\n\n  // if bezier ctrl pts can not be calculated, then die\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  var bb;\n  if (shiftToOriginWithBb) {\n    bb = shiftToOriginWithBb;\n    context.translate(-bb.x1, -bb.y1);\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 lineOutlineWidth = edge.pstyle('line-outline-width').value;\n  var lineOutlineColor = edge.pstyle('line-outline-color').value;\n  var effectiveLineOpacity = opacity * lineOpacity;\n  // separate arrow opacity would require arrow-opacity property\n  var effectiveArrowOpacity = opacity * lineOpacity;\n  var drawLine = function drawLine() {\n    var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;\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  var drawLineOutline = function drawLineOutline() {\n    var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;\n    context.lineWidth = edgeWidth + lineOutlineWidth;\n    context.lineCap = lineCap;\n    if (lineOutlineWidth > 0) {\n      r.colorStrokeStyle(context, lineOutlineColor[0], lineOutlineColor[1], lineOutlineColor[2], strokeOpacity);\n    } else {\n      // do not draw any lineOutline\n      context.lineCap = 'butt'; // reset for other drawing functions\n      return;\n    }\n    if (curveStyle === 'straight-triangle') {\n      r.drawEdgeTrianglePath(edge, context, rs.allpts);\n    } else {\n      r.drawEdgePath(edge, context, rs.allpts, lineStyle);\n      context.lineCap = 'butt'; // reset for other drawing functions\n    }\n  };\n  var drawOverlay = function drawOverlay() {\n    if (!shouldDrawOverlay) {\n      return;\n    }\n    r.drawEdgeOverlay(context, edge);\n  };\n  var drawUnderlay = function drawUnderlay() {\n    if (!shouldDrawOverlay) {\n      return;\n    }\n    r.drawEdgeUnderlay(context, edge);\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  var drawText = function drawText() {\n    r.drawElementText(context, edge, null, drawLabel);\n  };\n  context.lineJoin = 'round';\n  var ghost = edge.pstyle('ghost').value === 'yes';\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  } else {\n    drawLineOutline();\n  }\n  drawUnderlay();\n  drawLine();\n  drawArrows();\n  drawOverlay();\n  drawText();\n  if (shiftToOriginWithBb) {\n    context.translate(bb.x1, bb.y1);\n  }\n};\nvar drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {\n  if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {\n    throw new Error('Invalid state');\n  }\n  return function (context, edge) {\n    if (!edge.visible()) {\n      return;\n    }\n    var opacity = edge.pstyle(\"\".concat(overlayOrUnderlay, \"-opacity\")).value;\n    if (opacity === 0) {\n      return;\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    if (rs.edgeType === 'self' && !usePaths) {\n      context.lineCap = 'butt';\n    } else {\n      context.lineCap = 'round';\n    }\n    r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);\n    r.drawEdgePath(edge, context, rs.allpts, 'solid');\n  };\n};\nCRp$9.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');\nCRp$9.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');\nCRp$9.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  if (usePaths) {\n    var pathCacheKey = pts.join('$');\n    var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;\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  if (canvasCxt.setLineDash) {\n    // for very outofdate browsers\n    switch (type) {\n      case 'dotted':\n        canvasCxt.setLineDash([1, 1]);\n        break;\n      case 'dashed':\n        canvasCxt.setLineDash(lineDashPattern);\n        canvasCxt.lineDashOffset = lineDashOffset;\n        break;\n      case 'solid':\n        canvasCxt.setLineDash([]);\n        break;\n    }\n  }\n  if (!pathCacheHit && !rs.badLine) {\n    if (context.beginPath) {\n      context.beginPath();\n    }\n    context.moveTo(pts[0], pts[1]);\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        break;\n      case 'straight':\n      case 'haystack':\n        for (var _i = 2; _i + 1 < pts.length; _i += 2) {\n          context.lineTo(pts[_i], pts[_i + 1]);\n        }\n        break;\n      case 'segments':\n        if (rs.isRound) {\n          var _iterator = _createForOfIteratorHelper(rs.roundCorners),\n            _step;\n          try {\n            for (_iterator.s(); !(_step = _iterator.n()).done;) {\n              var corner = _step.value;\n              drawPreparedRoundCorner(context, corner);\n            }\n          } catch (err) {\n            _iterator.e(err);\n          } finally {\n            _iterator.f();\n          }\n          context.lineTo(pts[pts.length - 2], pts[pts.length - 1]);\n        } else {\n          for (var _i2 = 2; _i2 + 1 < pts.length; _i2 += 2) {\n            context.lineTo(pts[_i2], pts[_i2 + 1]);\n          }\n        }\n        break;\n    }\n  }\n  context = canvasCxt;\n  if (usePaths) {\n    context.stroke(path);\n  } else {\n    context.stroke();\n  }\n\n  // reset any line dashes\n  if (context.setLineDash) {\n    // for very outofdate browsers\n    context.setLineDash([]);\n  }\n};\nCRp$9.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  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};\nCRp$9.drawArrowheads = function (context, edge, opacity) {\n  var rs = edge._private.rscratch;\n  var isHaystack = rs.edgeType === 'haystack';\n  if (!isHaystack) {\n    this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);\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  if (!isHaystack) {\n    this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);\n  }\n};\nCRp$9.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  var self = this;\n  var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;\n  if (arrowShape === 'none') {\n    return;\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 pArrowWidth = edge.pstyle(prefix + '-arrow-width');\n  var arrowWidth = pArrowWidth.value === 'match-line' ? edgeWidth : pArrowWidth.pfValue;\n  if (pArrowWidth.units === '%') arrowWidth *= edgeWidth;\n  var edgeOpacity = edge.pstyle('opacity').value;\n  if (opacity === undefined) {\n    opacity = edgeOpacity;\n  }\n  var gco = context.globalCompositeOperation;\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, arrowWidth, x, y, angle);\n    context.globalCompositeOperation = gco;\n  } // otherwise, the opaque arrow clears it for free :)\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, arrowWidth, x, y, angle);\n};\nCRp$9.drawArrowShape = function (edge, context, fill, edgeWidth, shape, shapeWidth, 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  if (usePaths) {\n    var cache = r.arrowPathCache = r.arrowPathCache || [];\n    var key = hashString(shape);\n    var cachedPath = cache[key];\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  if (!pathCacheHit) {\n    if (context.beginPath) {\n      context.beginPath();\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    if (context.closePath) {\n      context.closePath();\n    }\n  }\n  context = canvasContext;\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  if (fill === 'filled' || fill === 'both') {\n    if (usePaths) {\n      context.fill(path);\n    } else {\n      context.fill();\n    }\n  }\n  if (fill === 'hollow' || fill === 'both') {\n    context.lineWidth = shapeWidth / (usePaths ? size : 1);\n    context.lineJoin = 'miter';\n    if (usePaths) {\n      context.stroke(path);\n    } else {\n      context.stroke();\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\nvar CRp$8 = {};\nCRp$8.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  try {\n    context.drawImage(img, ix, iy, iw, ih, x, y, w, h);\n  } catch (e) {\n    warn(e);\n  }\n};\nCRp$8.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 cornerRadius = node.pstyle('corner-radius').value;\n  if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;\n  var imgW = img.width || img.cachedW;\n  var imgH = img.height || img.cachedH;\n\n  // workaround for broken browsers like ie\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  var w = imgW;\n  var h = imgH;\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  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  if (w === 0 || h === 0) {\n    return; // no point in drawing empty image (and chrome is broken in this case)\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  var x = nodeX - nodeTW / 2; // left\n  var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);\n  var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);\n  if (posXUnits === '%') {\n    x += (nodeTW - w) * posXPfVal;\n  } else {\n    x += posXPfVal;\n  }\n  var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);\n  var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);\n  if (offXUnits === '%') {\n    x += (nodeTW - w) * offXPfVal;\n  } else {\n    x += offXPfVal;\n  }\n  var y = nodeY - nodeTH / 2; // top\n  var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);\n  var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);\n  if (posYUnits === '%') {\n    y += (nodeTH - h) * posYPfVal;\n  } else {\n    y += posYPfVal;\n  }\n  var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);\n  var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);\n  if (offYUnits === '%') {\n    y += (nodeTH - h) * offYPfVal;\n  } else {\n    y += offYPfVal;\n  }\n  if (rs.pathCache) {\n    x -= nodeX;\n    y -= nodeY;\n    nodeX = 0;\n    nodeY = 0;\n  }\n  var gAlpha = context.globalAlpha;\n  context.globalAlpha = imgOpacity;\n  var smoothingEnabled = r.getImgSmoothing(context);\n  var isSmoothingSwitched = false;\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  if (repeat === 'no-repeat') {\n    if (shouldClip) {\n      context.save();\n      if (rs.pathCache) {\n        context.clip(rs.pathCache);\n      } else {\n        r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);\n        context.clip();\n      }\n    }\n    r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);\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, cornerRadius, rs);\n    context.translate(x, y);\n    context.fill();\n    context.translate(-x, -y);\n  }\n  context.globalAlpha = gAlpha;\n  if (isSmoothingSwitched) {\n    r.setImgSmoothing(context, smoothingEnabled);\n  }\n};\n\nvar CRp$7 = {};\nCRp$7.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  var computedSize = ele.pstyle('font-size').pfValue * scale;\n  var minSize = ele.pstyle('min-zoomed-font-size').pfValue;\n  if (computedSize < minSize) {\n    return false;\n  }\n  return true;\n};\nCRp$7.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {\n  var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;\n  var r = this;\n  if (force == null) {\n    if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {\n      return;\n    }\n  } else if (force === false) {\n    return;\n  }\n  if (ele.isNode()) {\n    var label = ele.pstyle('label');\n    if (!label || !label.value) {\n      return;\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    var _label = ele.pstyle('label');\n    var srcLabel = ele.pstyle('source-label');\n    var tgtLabel = ele.pstyle('target-label');\n    if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {\n      return;\n    }\n    context.textAlign = 'center';\n    context.textBaseline = 'bottom';\n  }\n  var applyRotation = !shiftToOriginWithBb;\n  var bb;\n  if (shiftToOriginWithBb) {\n    bb = shiftToOriginWithBb;\n    context.translate(-bb.x1, -bb.y1);\n  }\n  if (prefix == null) {\n    r.drawText(context, ele, null, applyRotation, useEleOpacity);\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  if (shiftToOriginWithBb) {\n    context.translate(bb.x1, bb.y1);\n  }\n};\nCRp$7.getFontCache = function (context) {\n  var cache;\n  this.fontCaches = this.fontCaches || [];\n  for (var i = 0; i < this.fontCaches.length; i++) {\n    cache = this.fontCaches[i];\n    if (cache.context === context) {\n      return cache;\n    }\n  }\n  cache = {\n    context: context\n  };\n  this.fontCaches.push(cache);\n  return cache;\n};\n\n// set up canvas context with font\n// returns transformed text string\nCRp$7.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};\n\n// TODO ensure re-used\nfunction roundRect(ctx, x, y, width, height) {\n  var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;\n  var stroke = arguments.length > 6 ? arguments[6] : undefined;\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  if (stroke) ctx.stroke();else ctx.fill();\n}\nCRp$7.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  if (rotation.strValue === 'autorotate') {\n    var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);\n    theta = ele.isEdge() ? textAngle : 0;\n  } else if (rotation.strValue === 'none') {\n    theta = 0;\n  } else {\n    theta = rotation.pfValue;\n  }\n  return theta;\n};\nCRp$7.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  if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {\n    return;\n  }\n\n  // use 'main' as an alias for the main label (i.e. null prefix)\n  if (prefix === 'main') {\n    prefix = null;\n  }\n  var textX = getPrefixedProperty(rscratch, 'labelX', prefix);\n  var textY = getPrefixedProperty(rscratch, 'labelY', prefix);\n  var orgTextX, orgTextY; // used for rotation\n  var text = this.getLabelText(ele, prefix);\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    if (isEdge) {\n      halign = 'center';\n      valign = 'center';\n    }\n    textX += marginX;\n    textY += marginY;\n    var theta;\n    if (!applyRotation) {\n      theta = 0;\n    } else {\n      theta = this.getTextAngle(ele, prefix);\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    switch (valign) {\n      case 'top':\n        break;\n      case 'center':\n        textY += textH / 2;\n        break;\n      case 'bottom':\n        textY += textH;\n        break;\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    var styleShape = ele.pstyle('text-background-shape').strValue;\n    var rounded = styleShape.indexOf('round') === 0;\n    var roundRadius = 2;\n    if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {\n      var bgX = textX - backgroundPadding;\n      switch (halign) {\n        case 'left':\n          bgX -= textW;\n          break;\n        case 'center':\n          bgX -= textW / 2;\n          break;\n      }\n      var bgY = textY - textH - backgroundPadding;\n      var bgW = textW + 2 * backgroundPadding;\n      var bgH = textH + 2 * backgroundPadding;\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        if (rounded) {\n          roundRect(context, bgX, bgY, bgW, bgH, roundRadius);\n        } else {\n          context.fillRect(bgX, bgY, bgW, bgH);\n        }\n        context.fillStyle = textFill;\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        if (context.setLineDash) {\n          // for very outofdate browsers\n          switch (textBorderStyle) {\n            case 'dotted':\n              context.setLineDash([1, 1]);\n              break;\n            case 'dashed':\n              context.setLineDash([4, 2]);\n              break;\n            case 'double':\n              context.lineWidth = textBorderWidth / 4; // 50% reserved for white between the two borders\n              context.setLineDash([]);\n              break;\n            case 'solid':\n              context.setLineDash([]);\n              break;\n          }\n        }\n        if (rounded) {\n          roundRect(context, bgX, bgY, bgW, bgH, roundRadius, 'stroke');\n        } else {\n          context.strokeRect(bgX, bgY, bgW, bgH);\n        }\n        if (textBorderStyle === 'double') {\n          var whiteWidth = textBorderWidth / 2;\n          if (rounded) {\n            roundRect(context, bgX + whiteWidth, bgY + whiteWidth, bgW - whiteWidth * 2, bgH - whiteWidth * 2, roundRadius, 'stroke');\n          } else {\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        context.lineWidth = textLineWidth;\n        context.strokeStyle = textStroke;\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    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      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      } 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      } 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      switch (valign) {\n        case 'top':\n          textY -= (lines.length - 1) * lineHeight;\n          break;\n        case 'center':\n        case 'bottom':\n          textY -= (lines.length - 1) * lineHeight;\n          break;\n      }\n      for (var l = 0; l < lines.length; l++) {\n        if (lineWidth > 0) {\n          context.strokeText(lines[l], textX, textY);\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      context.fillText(text, textX, textY);\n    }\n    if (theta !== 0) {\n      context.rotate(-theta);\n      context.translate(-orgTextX, -orgTextY);\n    }\n  }\n};\n\n/* global Path2D */\n\nvar CRp$6 = {};\nCRp$6.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  if (!number$1(pos.x) || !number$1(pos.y)) {\n    return; // can't draw node with undefined position\n  }\n  if (shouldDrawOpacity && !node.visible()) {\n    return;\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\n  //\n  // setup shift\n\n  var bb;\n  if (shiftToOriginWithBb) {\n    bb = shiftToOriginWithBb;\n    context.translate(-bb.x1, -bb.y1);\n  }\n\n  //\n  // load bg image\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  for (var i = 0; i < urls.length; i++) {\n    var url = urls[i];\n    var defd = urlDefined[i] = url != null && url !== 'none';\n    if (defd) {\n      var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);\n      numImages++;\n\n      // get image, and if not loaded then ask to redraw when later loaded\n      image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {\n        _p.backgroundTimestamp = Date.now();\n        node.emitAndNotify('background');\n      });\n    }\n  }\n\n  //\n  // setup styles\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 borderJoin = node.pstyle('border-join').value;\n  var borderCap = node.pstyle('border-cap').value;\n  var borderPosition = node.pstyle('border-position').value;\n  var borderPattern = node.pstyle('border-dash-pattern').pfValue;\n  var borderOffset = node.pstyle('border-dash-offset').pfValue;\n  var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;\n  var outlineWidth = node.pstyle('outline-width').pfValue;\n  var outlineColor = node.pstyle('outline-color').value;\n  var outlineStyle = node.pstyle('outline-style').value;\n  var outlineOpacity = node.pstyle('outline-opacity').value * eleOpacity;\n  var outlineOffset = node.pstyle('outline-offset').value;\n  var cornerRadius = node.pstyle('corner-radius').value;\n  if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;\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  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  var setupOutlineColor = function setupOutlineColor() {\n    var otlnOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : outlineOpacity;\n    r.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], otlnOpy);\n  };\n\n  //\n  // setup shape\n\n  var getPath = function getPath(width, height, shape, points) {\n    var pathCache = r.nodePathCache = r.nodePathCache || [];\n    var key = hashStrings(shape === 'polygon' ? shape + ',' + points.join(',') : shape, '' + height, '' + width, '' + cornerRadius);\n    var cachedPath = pathCache[key];\n    var path;\n    var cacheHit = false;\n    if (cachedPath != null) {\n      path = cachedPath;\n      cacheHit = true;\n      rs.pathCache = path;\n    } else {\n      path = new Path2D();\n      pathCache[key] = rs.pathCache = path;\n    }\n    return {\n      path: path,\n      cacheHit: cacheHit\n    };\n  };\n  var styleShape = node.pstyle('shape').strValue;\n  var shapePts = node.pstyle('shape-polygon-points').pfValue;\n  if (usePaths) {\n    context.translate(pos.x, pos.y);\n    var shapePath = getPath(nodeWidth, nodeHeight, styleShape, shapePts);\n    path = shapePath.path;\n    pathCacheHit = shapePath.cacheHit;\n  }\n  var drawShape = function drawShape() {\n    if (!pathCacheHit) {\n      var npos = pos;\n      if (usePaths) {\n        npos = {\n          x: 0,\n          y: 0\n        };\n      }\n      r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight, cornerRadius, rs);\n    }\n    if (usePaths) {\n      context.fill(path);\n    } else {\n      context.fill();\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    for (var _i = 0; _i < image.length; _i++) {\n      var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);\n      if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {\n        totalCompleted++;\n        continue;\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    _p.backgrounding = !(totalCompleted === numImages);\n    if (prevBging !== _p.backgrounding) {\n      // update style b/c :backgrounding state changed\n      node.updateStyle(false);\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    if (r.hasPie(node)) {\n      r.drawPie(context, node, pieOpacity);\n\n      // redraw/restore path if steps after pie need it\n      if (redrawShape) {\n        if (!usePaths) {\n          r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);\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    if (darkness !== 0) {\n      r.colorFillStyle(context, c, c, c, opacity);\n      if (usePaths) {\n        context.fill(path);\n      } else {\n        context.fill();\n      }\n    }\n  };\n  var drawBorder = function drawBorder() {\n    if (borderWidth > 0) {\n      context.lineWidth = borderWidth;\n      context.lineCap = borderCap;\n      context.lineJoin = borderJoin;\n      if (context.setLineDash) {\n        // for very outofdate browsers\n        switch (borderStyle) {\n          case 'dotted':\n            context.setLineDash([1, 1]);\n            break;\n          case 'dashed':\n            context.setLineDash(borderPattern);\n            context.lineDashOffset = borderOffset;\n            break;\n          case 'solid':\n          case 'double':\n            context.setLineDash([]);\n            break;\n        }\n      }\n      if (borderPosition !== 'center') {\n        context.save();\n        context.lineWidth *= 2;\n        if (borderPosition === 'inside') {\n          usePaths ? context.clip(path) : context.clip();\n        } else {\n          var region = new Path2D();\n          region.rect(-nodeWidth / 2 - borderWidth, -nodeHeight / 2 - borderWidth, nodeWidth + 2 * borderWidth, nodeHeight + 2 * borderWidth);\n          region.addPath(path);\n          context.clip(region, 'evenodd');\n        }\n        usePaths ? context.stroke(path) : context.stroke();\n        context.restore();\n      } else {\n        usePaths ? context.stroke(path) : context.stroke();\n      }\n      if (borderStyle === 'double') {\n        context.lineWidth = borderWidth / 3;\n        var gco = context.globalCompositeOperation;\n        context.globalCompositeOperation = 'destination-out';\n        if (usePaths) {\n          context.stroke(path);\n        } else {\n          context.stroke();\n        }\n        context.globalCompositeOperation = gco;\n      }\n\n      // reset in case we changed the border style\n      if (context.setLineDash) {\n        // for very outofdate browsers\n        context.setLineDash([]);\n      }\n    }\n  };\n  var drawOutline = function drawOutline() {\n    if (outlineWidth > 0) {\n      context.lineWidth = outlineWidth;\n      context.lineCap = 'butt';\n      if (context.setLineDash) {\n        // for very outofdate browsers\n        switch (outlineStyle) {\n          case 'dotted':\n            context.setLineDash([1, 1]);\n            break;\n          case 'dashed':\n            context.setLineDash([4, 2]);\n            break;\n          case 'solid':\n          case 'double':\n            context.setLineDash([]);\n            break;\n        }\n      }\n      var npos = pos;\n      if (usePaths) {\n        npos = {\n          x: 0,\n          y: 0\n        };\n      }\n      var shape = r.getNodeShape(node);\n      var bWidth = borderWidth;\n      if (borderPosition === 'inside') bWidth = 0;\n      if (borderPosition === 'outside') bWidth *= 2;\n      var scaleX = (nodeWidth + bWidth + (outlineWidth + outlineOffset)) / nodeWidth;\n      var scaleY = (nodeHeight + bWidth + (outlineWidth + outlineOffset)) / nodeHeight;\n      var sWidth = nodeWidth * scaleX;\n      var sHeight = nodeHeight * scaleY;\n      var points = r.nodeShapes[shape].points;\n      var _path;\n      if (usePaths) {\n        var outlinePath = getPath(sWidth, sHeight, shape, points);\n        _path = outlinePath.path;\n      }\n\n      // draw the outline path, either by using expanded points or by scaling \n      // the dimensions, depending on shape\n      if (shape === \"ellipse\") {\n        r.drawEllipsePath(_path || context, npos.x, npos.y, sWidth, sHeight);\n      } else if (['round-diamond', 'round-heptagon', 'round-hexagon', 'round-octagon', 'round-pentagon', 'round-polygon', 'round-triangle', 'round-tag'].includes(shape)) {\n        var sMult = 0;\n        var offsetX = 0;\n        var offsetY = 0;\n        if (shape === 'round-diamond') {\n          sMult = (bWidth + outlineOffset + outlineWidth) * 1.4;\n        } else if (shape === 'round-heptagon') {\n          sMult = (bWidth + outlineOffset + outlineWidth) * 1.075;\n          offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 35;\n        } else if (shape === 'round-hexagon') {\n          sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;\n        } else if (shape === 'round-pentagon') {\n          sMult = (bWidth + outlineOffset + outlineWidth) * 1.13;\n          offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 15;\n        } else if (shape === 'round-tag') {\n          sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;\n          offsetX = (bWidth / 2 + outlineWidth + outlineOffset) * .07;\n        } else if (shape === 'round-triangle') {\n          sMult = (bWidth + outlineOffset + outlineWidth) * (Math.PI / 2);\n          offsetY = -(bWidth + outlineOffset / 2 + outlineWidth) / Math.PI;\n        }\n        if (sMult !== 0) {\n          scaleX = (nodeWidth + sMult) / nodeWidth;\n          sWidth = nodeWidth * scaleX;\n          if (!['round-hexagon', 'round-tag'].includes(shape)) {\n            scaleY = (nodeHeight + sMult) / nodeHeight;\n            sHeight = nodeHeight * scaleY;\n          }\n        }\n        cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(sWidth, sHeight) : cornerRadius;\n        var halfW = sWidth / 2;\n        var halfH = sHeight / 2;\n        var radius = cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2;\n        var p = new Array(points.length / 2);\n        var corners = new Array(points.length / 2);\n        for (var _i2 = 0; _i2 < points.length / 2; _i2++) {\n          p[_i2] = {\n            x: npos.x + offsetX + halfW * points[_i2 * 2],\n            y: npos.y + offsetY + halfH * points[_i2 * 2 + 1]\n          };\n        }\n        var _i3,\n          p1,\n          p2,\n          p3,\n          len = p.length;\n        p1 = p[len - 1];\n        // for each point\n        for (_i3 = 0; _i3 < len; _i3++) {\n          p2 = p[_i3 % len];\n          p3 = p[(_i3 + 1) % len];\n          corners[_i3] = getRoundCorner(p1, p2, p3, radius);\n          p1 = p2;\n          p2 = p3;\n        }\n        r.drawRoundPolygonPath(_path || context, npos.x + offsetX, npos.y + offsetY, nodeWidth * scaleX, nodeHeight * scaleY, points, corners);\n      } else if (['roundrectangle', 'round-rectangle'].includes(shape)) {\n        cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;\n        r.drawRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);\n      } else if (['cutrectangle', 'cut-rectangle'].includes(shape)) {\n        cornerRadius = cornerRadius === 'auto' ? getCutRectangleCornerLength() : cornerRadius;\n        r.drawCutRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, null, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 4);\n      } else if (['bottomroundrectangle', 'bottom-round-rectangle'].includes(shape)) {\n        cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;\n        r.drawBottomRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);\n      } else if (shape === \"barrel\") {\n        r.drawBarrelPath(_path || context, npos.x, npos.y, sWidth, sHeight);\n      } else if (shape.startsWith(\"polygon\") || ['rhomboid', 'right-rhomboid', 'round-tag', 'tag', 'vee'].includes(shape)) {\n        var pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;\n        points = joinLines(expandPolygon(points, pad));\n        r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);\n      } else {\n        var _pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;\n        points = joinLines(expandPolygon(points, -_pad));\n        r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);\n      }\n      if (usePaths) {\n        context.stroke(_path);\n      } else {\n        context.stroke();\n      }\n      if (outlineStyle === 'double') {\n        context.lineWidth = bWidth / 3;\n        var gco = context.globalCompositeOperation;\n        context.globalCompositeOperation = 'destination-out';\n        if (usePaths) {\n          context.stroke(_path);\n        } else {\n          context.stroke();\n        }\n        context.globalCompositeOperation = gco;\n      }\n\n      // reset in case we changed the border style\n      if (context.setLineDash) {\n        // for very outofdate browsers\n        context.setLineDash([]);\n      }\n    }\n  };\n  var drawOverlay = function drawOverlay() {\n    if (shouldDrawOverlay) {\n      r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);\n    }\n  };\n  var drawUnderlay = function drawUnderlay() {\n    if (shouldDrawOverlay) {\n      r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);\n    }\n  };\n  var drawText = function drawText() {\n    r.drawElementText(context, node, null, drawLabel);\n  };\n  var ghost = node.pstyle('ghost').value === 'yes';\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    setupOutlineColor();\n    drawOutline();\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  if (usePaths) {\n    context.translate(-pos.x, -pos.y);\n  }\n  drawUnderlay();\n  if (usePaths) {\n    context.translate(pos.x, pos.y);\n  }\n  setupOutlineColor();\n  drawOutline();\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  if (usePaths) {\n    context.translate(-pos.x, -pos.y);\n  }\n  drawText();\n  drawOverlay();\n\n  //\n  // clean up shift\n\n  if (shiftToOriginWithBb) {\n    context.translate(bb.x1, bb.y1);\n  }\n};\nvar drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {\n  if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {\n    throw new Error('Invalid state');\n  }\n  return function (context, node, pos, nodeWidth, nodeHeight) {\n    var r = this;\n    if (!node.visible()) {\n      return;\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    var radius = node.pstyle(\"\".concat(overlayOrUnderlay, \"-corner-radius\")).value;\n    if (opacity > 0) {\n      pos = pos || node.position();\n      if (nodeWidth == null || nodeHeight == null) {\n        var _padding = node.padding();\n        nodeWidth = node.width() + 2 * _padding;\n        nodeHeight = node.height() + 2 * _padding;\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, radius);\n      context.fill();\n    }\n  };\n};\nCRp$6.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');\nCRp$6.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay');\n\n// does the node have at least one pie piece?\nCRp$6.hasPie = function (node) {\n  node = node[0]; // ensure ele ref\n\n  return node._private.hasPie;\n};\nCRp$6.drawPie = function (context, node, nodeOpacity, pos) {\n  node = node[0]; // ensure ele ref\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  var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]\n  var usePaths = this.usePaths();\n  if (usePaths) {\n    x = 0;\n    y = 0;\n  }\n  if (pieSize.units === '%') {\n    radius = radius * pieSize.pfValue;\n  } else if (pieSize.pfValue !== undefined) {\n    radius = pieSize.pfValue / 2;\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\n    // percent can't push beyond 1\n    if (percent + lastPercent > 1) {\n      percent = 1 - lastPercent;\n    }\n    var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise\n    var angleDelta = 2 * Math.PI * percent;\n    var angleEnd = angleStart + angleDelta;\n\n    // 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    if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {\n      continue;\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\nvar CRp$5 = {};\nvar motionBlurDelay = 100;\n\n// var isFirefox = typeof InstallTrigger !== 'undefined';\n\nCRp$5.getPixelRatio = function () {\n  var context = this.data.contexts[0];\n  if (this.forcedPixelRatio != null) {\n    return this.forcedPixelRatio;\n  }\n  var containerWindow = this.cy.window();\n  var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;\n  return (containerWindow.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef\n};\nCRp$5.paintCache = function (context) {\n  var caches = this.paintCaches = this.paintCaches || [];\n  var needToCreateCache = true;\n  var cache;\n  for (var i = 0; i < caches.length; i++) {\n    cache = caches[i];\n    if (cache.context === context) {\n      needToCreateCache = false;\n      break;\n    }\n  }\n  if (needToCreateCache) {\n    cache = {\n      context: context\n    };\n    caches.push(cache);\n  }\n  return cache;\n};\nCRp$5.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  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      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      var direction = ele.pstyle('background-gradient-direction').value;\n      switch (direction) {\n        case 'to-bottom':\n          gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);\n          break;\n        case 'to-top':\n          gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);\n          break;\n        case 'to-left':\n          gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);\n          break;\n        case 'to-right':\n          gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);\n          break;\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        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        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        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  if (!gradientStyle) return null; // invalid gradient style\n\n  var hasPositions = positions.length === colors.length;\n  var length = colors.length;\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  return gradientStyle;\n};\nCRp$5.gradientFillStyle = function (context, ele, fill, opacity) {\n  var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);\n  if (!gradientStyle) return null; // error\n  context.fillStyle = gradientStyle;\n};\nCRp$5.colorFillStyle = function (context, r, g, b, a) {\n  context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n  // turn off for now, seems context does its own caching\n\n  // var cache = this.paintCache(context);\n\n  // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n\n  // if( cache.fillStyle !== fillStyle ){\n  //   context.fillStyle = cache.fillStyle = fillStyle;\n  // }\n};\nCRp$5.eleFillStyle = function (context, ele, opacity) {\n  var backgroundFill = ele.pstyle('background-fill').value;\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};\nCRp$5.gradientStrokeStyle = function (context, ele, fill, opacity) {\n  var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);\n  if (!gradientStyle) return null; // error\n  context.strokeStyle = gradientStyle;\n};\nCRp$5.colorStrokeStyle = function (context, r, g, b, a) {\n  context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n  // turn off for now, seems context does its own caching\n\n  // var cache = this.paintCache(context);\n\n  // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n\n  // if( cache.strokeStyle !== strokeStyle ){\n  //   context.strokeStyle = cache.strokeStyle = strokeStyle;\n  // }\n};\nCRp$5.eleStrokeStyle = function (context, ele, opacity) {\n  var lineFill = ele.pstyle('line-fill').value;\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};\n\n// Resize canvas\nCRp$5.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  if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {\n    pixelRatio = mbPxRatio;\n  }\n  var canvasWidth = width * pixelRatio;\n  var canvasHeight = height * pixelRatio;\n  var canvas;\n  if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {\n    return; // save cycles if same\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  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  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  r.textureMult = 1;\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  r.canvasWidth = canvasWidth;\n  r.canvasHeight = canvasHeight;\n  r.pixelRatio = pixelRatio;\n};\nCRp$5.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};\nCRp$5.clearCanvas = function () {\n  var r = this;\n  var data = r.data;\n  function clear(context) {\n    context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);\n  }\n  clear(data.contexts[r.NODE]);\n  clear(data.contexts[r.DRAG]);\n};\nCRp$5.render = function (options) {\n  var r = this;\n  options = options || staticEmptyObject();\n  var cy = r.cy;\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 pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;\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  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    r.prevPxRatio = pixelRatio;\n  }\n  if (!forcedContext && r.motionBlurTimeout) {\n    clearTimeout(r.motionBlurTimeout);\n  }\n  if (motionBlur) {\n    if (r.mbFrames == null) {\n      r.mbFrames = 0;\n    }\n    r.mbFrames++;\n    if (r.mbFrames < 3) {\n      // need several frames before even high quality motionblur\n      motionBlurFadeEffect = false;\n    }\n\n    // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)\n    if (r.mbFrames > r.minMbLowQualFrames) {\n      //r.fullQualityMb = false;\n      r.motionBlurPxRatio = r.mbPxRBlurry;\n    }\n  }\n  if (r.clearingMotionBlur) {\n    r.motionBlurPxRatio = 1;\n  }\n\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  if (r.textureDrawLastFrame && !textureDraw) {\n    needDraw[r.NODE] = true;\n    needDraw[r.SELECT_BOX] = true;\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;\n\n  // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)\n  if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {\n    r.motionBlurPxRatio = 1;\n  }\n  if (forcedPan) {\n    effectivePan = forcedPan;\n  }\n\n  // apply pixel ratio\n\n  effectiveZoom *= pixelRatio;\n  effectivePan.x *= pixelRatio;\n  effectivePan.y *= pixelRatio;\n  var eles = r.getCachedZSortedEles();\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  function setContextTransform(context, clear) {\n    var ePan, eZoom, w, h;\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    context.setTransform(1, 0, 0, 1, 0, 0);\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    if (!drawAllLayers) {\n      context.translate(ePan.x, ePan.y);\n      context.scale(eZoom, eZoom);\n    }\n    if (forcedPan) {\n      context.translate(forcedPan.x, forcedPan.y);\n    }\n    if (forcedZoom) {\n      context.scale(forcedZoom, forcedZoom);\n    }\n  }\n  if (!textureDraw) {\n    r.textureDrawLastFrame = false;\n  }\n  if (textureDraw) {\n    r.textureDrawLastFrame = true;\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    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    if (motionBlur) {\n      mbclear(context, 0, 0, vp.width, vp.height);\n    } else {\n      context.clearRect(0, 0, vp.width, vp.height);\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  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  if (needMbClear[r.NODE]) {\n    r.clearedForMotionBlur[r.NODE] = true;\n  }\n  needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;\n  if (needMbClear[r.DRAG]) {\n    r.clearedForMotionBlur[r.DRAG] = true;\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    if (hideEdges) {\n      r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);\n    } else {\n      r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);\n    }\n    if (r.debug) {\n      r.drawDebugPoints(context, eles.nondrag);\n    }\n    if (!drawAllLayers && !motionBlur) {\n      needDraw[r.NODE] = false;\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    if (hideEdges) {\n      r.drawCachedNodes(context, eles.drag, pixelRatio, extent);\n    } else {\n      r.drawCachedElements(context, eles.drag, pixelRatio, extent);\n    }\n    if (r.debug) {\n      r.drawDebugPoints(context, eles.drag);\n    }\n    if (!drawAllLayers && !motionBlur) {\n      needDraw[r.DRAG] = false;\n    }\n  }\n  this.drawSelectionRectangle(options, setContextTransform);\n\n  // motionblur: blit rendered blurry frames\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    var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {\n      cxt.setTransform(1, 0, 0, 1, 0, 0);\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      var pxr = mbPxRatio;\n      cxt.drawImage(txt,\n      // img\n      0, 0,\n      // sx, sy\n      r.canvasWidth * pxr, r.canvasHeight * pxr,\n      // sw, sh\n      0, 0,\n      // x, y\n      r.canvasWidth, r.canvasHeight // w, h\n      );\n    };\n    if (needDraw[r.NODE] || needMbClear[r.NODE]) {\n      drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);\n      needDraw[r.NODE] = false;\n    }\n    if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {\n      drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);\n      needDraw[r.DRAG] = false;\n    }\n  }\n  r.prevViewport = vp;\n  if (r.clearingMotionBlur) {\n    r.clearingMotionBlur = false;\n    r.motionBlurCleared = true;\n    r.motionBlur = true;\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  if (!forcedContext) {\n    cy.emit('render');\n  }\n};\nvar fpsHeight;\nCRp$5.drawSelectionRectangle = function (options, setContextTransform) {\n  var r = this;\n  var cy = r.cy;\n  var data = r.data;\n  var style = cy.style();\n  var drawOnlyNodeLayer = options.drawOnlyNodeLayer;\n  var drawAllLayers = options.drawAllLayers;\n  var needDraw = data.canvasNeedsRedraw;\n  var forcedContext = options.forcedContext;\n  if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {\n    var context = forcedContext || data.contexts[r.SELECT_BOX];\n    setContextTransform(context);\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      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    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    var timeToRender = r.lastRedrawTime;\n    if (r.showFps && timeToRender) {\n      timeToRender = Math.round(timeToRender);\n      var fps = Math.round(1000 / timeToRender);\n      var text = '1 frame = ' + timeToRender + ' ms = ' + fps + ' fps';\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.font = '30px Arial';\n      if (!fpsHeight) {\n        var dims = context.measureText(text);\n        fpsHeight = dims.actualBoundingBoxAscent;\n      }\n      context.fillText(text, 0, fpsHeight);\n      var maxFps = 60;\n      context.strokeRect(0, fpsHeight + 10, 250, 20);\n      context.fillRect(0, fpsHeight + 10, 250 * Math.min(fps / maxFps, 1), 20);\n    }\n    if (!drawAllLayers) {\n      needDraw[r.SELECT_BOX] = false;\n    }\n  }\n};\n\n/**\n * Notes:\n * - All colors have premultiplied alpha. Very important for textues and \n *   blending to work correctly.\n */\n\nfunction compileShader(gl, type, source) {\n  var shader = gl.createShader(type);\n  gl.shaderSource(shader, source);\n  gl.compileShader(shader);\n  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n    throw new Error(gl.getShaderInfoLog(shader));\n  }\n  // console.log(gl.getShaderInfoLog(shader));\n  return shader;\n}\nfunction createProgram(gl, vertexSource, fragementSource) {\n  var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);\n  var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragementSource);\n  var program = gl.createProgram();\n  gl.attachShader(program, vertexShader);\n  gl.attachShader(program, fragmentShader);\n  gl.linkProgram(program);\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n    throw new Error('Could not initialize shaders');\n  }\n  return program;\n}\n\n/**\n * Creates an offscren canvas with a 2D context, for the\n * canvas renderer to use for drawing textures.\n */\nfunction createTextureCanvas(r, width, height) {\n  if (height === undefined) {\n    height = width;\n  }\n  var canvas = r.makeOffscreenCanvas(width, height);\n  var ctx = canvas.context = canvas.getContext('2d');\n  canvas.clear = function () {\n    return ctx.clearRect(0, 0, canvas.width, canvas.height);\n  };\n  canvas.clear();\n  return canvas;\n}\n\n/**\n * Returns the current pan & zoom values, scaled by the pixel ratio.\n */\nfunction getEffectivePanZoom(r) {\n  var pixelRatio = r.pixelRatio;\n  var zoom = r.cy.zoom();\n  var pan = r.cy.pan();\n  return {\n    zoom: zoom * pixelRatio,\n    pan: {\n      x: pan.x * pixelRatio,\n      y: pan.y * pixelRatio\n    }\n  };\n}\nfunction modelToRenderedPosition(r, pan, zoom, x, y) {\n  var rx = x * zoom + pan.x;\n  var ry = y * zoom + pan.y;\n  ry = Math.round(r.canvasHeight - ry); // adjust for webgl\n  return [rx, ry];\n}\n\n/**\n * Takes color & opacity style values and converts them to WebGL format. \n * Alpha is premultiplied.\n */\nfunction toWebGLColor(color, opacity, outArray) {\n  var r = color[0] / 255;\n  var g = color[1] / 255;\n  var b = color[2] / 255;\n  var a = opacity;\n  var arr = outArray || new Array(4);\n  arr[0] = r * a;\n  arr[1] = g * a;\n  arr[2] = b * a;\n  arr[3] = a;\n  return arr;\n}\nfunction indexToVec4(index, outArray) {\n  var arr = outArray || new Array(4);\n  arr[0] = (index >> 0 & 0xFF) / 0xFF;\n  arr[1] = (index >> 8 & 0xFF) / 0xFF;\n  arr[2] = (index >> 16 & 0xFF) / 0xFF;\n  arr[3] = (index >> 24 & 0xFF) / 0xFF;\n  return arr;\n}\nfunction vec4ToIndex(vec4) {\n  return vec4[0] + (vec4[1] << 8) + (vec4[2] << 16) + (vec4[3] << 24);\n}\nfunction createTexture(gl, debugID) {\n  var texture = gl.createTexture();\n  texture.buffer = function (offscreenCanvas) {\n    gl.bindTexture(gl.TEXTURE_2D, texture);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);\n\n    // very important, this tells webgl to premultiply colors by the alpha channel\n    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offscreenCanvas);\n    gl.generateMipmap(gl.TEXTURE_2D);\n    gl.bindTexture(gl.TEXTURE_2D, null);\n  };\n  texture.deleteTexture = function () {\n    gl.deleteTexture(texture);\n  };\n  return texture;\n}\nfunction getTypeInfo(gl, glslType) {\n  switch (glslType) {\n    case 'float':\n      return [1, gl.FLOAT, 4];\n    case 'vec2':\n      return [2, gl.FLOAT, 4];\n    case 'vec3':\n      return [3, gl.FLOAT, 4];\n    case 'vec4':\n      return [4, gl.FLOAT, 4];\n    case 'int':\n      return [1, gl.INT, 4];\n    case 'ivec2':\n      return [2, gl.INT, 4];\n  }\n}\nfunction createTypedArray(gl, glType, dataOrSize) {\n  switch (glType) {\n    case gl.FLOAT:\n      return new Float32Array(dataOrSize);\n    case gl.INT:\n      return new Int32Array(dataOrSize);\n  }\n}\nfunction createTypedArrayView(gl, glType, array, stride, size, i) {\n  switch (glType) {\n    case gl.FLOAT:\n      return new Float32Array(array.buffer, i * stride, size);\n    case gl.INT:\n      return new Int32Array(array.buffer, i * stride, size);\n  }\n}\n\n/** @param {WebGLRenderingContext} gl */\nfunction createBufferStaticDraw(gl, type, attributeLoc, dataArray) {\n  var _getTypeInfo = getTypeInfo(gl, type),\n    _getTypeInfo2 = _slicedToArray(_getTypeInfo, 2),\n    size = _getTypeInfo2[0],\n    glType = _getTypeInfo2[1];\n  var data = createTypedArray(gl, glType, dataArray);\n  var buffer = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);\n  if (glType === gl.FLOAT) {\n    gl.vertexAttribPointer(attributeLoc, size, glType, false, 0, 0);\n  } else if (glType === gl.INT) {\n    gl.vertexAttribIPointer(attributeLoc, size, glType, 0, 0);\n  }\n  gl.enableVertexAttribArray(attributeLoc);\n  gl.bindBuffer(gl.ARRAY_BUFFER, null);\n  return buffer;\n}\n\n/** \n * Creates a float buffer with gl.DYNAMIC_DRAW.\n * The returned buffer object contains functions to easily set instance data and buffer the data before a draw call.\n * @param {WebGLRenderingContext} gl \n */\nfunction createBufferDynamicDraw(gl, instances, type, attributeLoc) {\n  var _getTypeInfo3 = getTypeInfo(gl, type),\n    _getTypeInfo4 = _slicedToArray(_getTypeInfo3, 3),\n    size = _getTypeInfo4[0],\n    glType = _getTypeInfo4[1],\n    bytes = _getTypeInfo4[2];\n  var dataArray = createTypedArray(gl, glType, instances * size);\n  var stride = size * bytes;\n  var buffer = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n  gl.bufferData(gl.ARRAY_BUFFER, instances * stride, gl.DYNAMIC_DRAW);\n  gl.enableVertexAttribArray(attributeLoc);\n  if (glType === gl.FLOAT) {\n    gl.vertexAttribPointer(attributeLoc, size, glType, false, stride, 0);\n  } else if (glType === gl.INT) {\n    gl.vertexAttribIPointer(attributeLoc, size, glType, stride, 0);\n  }\n  gl.vertexAttribDivisor(attributeLoc, 1);\n  gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n  // use array views to set values directly into the buffer array\n  var views = new Array(instances);\n  for (var i = 0; i < instances; i++) {\n    views[i] = createTypedArrayView(gl, glType, dataArray, stride, size, i);\n  }\n  buffer.dataArray = dataArray;\n  buffer.stride = stride;\n  buffer.size = size;\n  buffer.getView = function (i) {\n    return views[i];\n  };\n  buffer.setPoint = function (i, x, y) {\n    var view = views[i];\n    view[0] = x;\n    view[1] = y;\n  };\n  buffer.bufferSubData = function (count) {\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n    if (count) {\n      gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray, 0, count * size);\n    } else {\n      gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray);\n    }\n  };\n  return buffer;\n}\n\n/** \n * Creates a buffer of 3x3 matrix data for use as attribute data.\n * @param {WebGLRenderingContext} gl \n */\nfunction create3x3MatrixBufferDynamicDraw(gl, instances, attributeLoc) {\n  var matrixSize = 9; // 3x3 matrix\n  var matrixData = new Float32Array(instances * matrixSize);\n\n  // use matrix views to set values directly into the matrixData array\n  var matrixViews = new Array(instances);\n  for (var i = 0; i < instances; i++) {\n    var byteOffset = i * matrixSize * 4; // 4 bytes per float\n    matrixViews[i] = new Float32Array(matrixData.buffer, byteOffset, matrixSize); // array view\n  }\n  var buffer = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n  gl.bufferData(gl.ARRAY_BUFFER, matrixData.byteLength, gl.DYNAMIC_DRAW);\n\n  // each row of the matrix needs to be a separate attribute\n  for (var _i = 0; _i < 3; _i++) {\n    var loc = attributeLoc + _i;\n    gl.enableVertexAttribArray(loc);\n    gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 3 * 12, _i * 12);\n    gl.vertexAttribDivisor(loc, 1);\n  }\n  gl.bindBuffer(gl.ARRAY_BUFFER, null);\n  buffer.getMatrixView = function (i) {\n    return matrixViews[i];\n  };\n\n  // TODO this is too slow, use getMatrixView and pass the view directly to the glmatrix library\n  buffer.setData = function (matrix, i) {\n    matrixViews[i].set(matrix, 0);\n  };\n  buffer.bufferSubData = function () {\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n    gl.bufferSubData(gl.ARRAY_BUFFER, 0, matrixData);\n  };\n  return buffer;\n}\n\n/** \n * Creates a Frame Buffer to use for offscreen rendering.\n * @param {WebGLRenderingContext} gl \n */\nfunction createPickingFrameBuffer(gl) {\n  // Create and bind the framebuffer\n  var fb = gl.createFramebuffer();\n  gl.bindFramebuffer(gl.FRAMEBUFFER, fb);\n\n  // Create a texture to render to\n  var targetTexture = gl.createTexture();\n  gl.bindTexture(gl.TEXTURE_2D, targetTexture);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n  // attach the texture as the first color attachment\n  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);\n  gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n  fb.setFramebufferAttachmentSizes = function (width, height) {\n    gl.bindTexture(gl.TEXTURE_2D, targetTexture);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n  };\n  return fb;\n}\n\n/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nvar ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nif (!Math.hypot) Math.hypot = function () {\n  var y = 0,\n      i = arguments.length;\n\n  while (i--) {\n    y += arguments[i] * arguments[i];\n  }\n\n  return Math.sqrt(y);\n};\n\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nfunction create() {\n  var out = new ARRAY_TYPE(9);\n\n  if (ARRAY_TYPE != Float32Array) {\n    out[1] = 0;\n    out[2] = 0;\n    out[3] = 0;\n    out[5] = 0;\n    out[6] = 0;\n    out[7] = 0;\n  }\n\n  out[0] = 1;\n  out[4] = 1;\n  out[8] = 1;\n  return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nfunction identity(out) {\n  out[0] = 1;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = 1;\n  out[5] = 0;\n  out[6] = 0;\n  out[7] = 0;\n  out[8] = 1;\n  return out;\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nfunction multiply(out, a, b) {\n  var a00 = a[0],\n      a01 = a[1],\n      a02 = a[2];\n  var a10 = a[3],\n      a11 = a[4],\n      a12 = a[5];\n  var a20 = a[6],\n      a21 = a[7],\n      a22 = a[8];\n  var b00 = b[0],\n      b01 = b[1],\n      b02 = b[2];\n  var b10 = b[3],\n      b11 = b[4],\n      b12 = b[5];\n  var b20 = b[6],\n      b21 = b[7],\n      b22 = b[8];\n  out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n  out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n  out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n  out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n  out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n  out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n  out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n  out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n  out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n  return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nfunction translate(out, a, v) {\n  var a00 = a[0],\n      a01 = a[1],\n      a02 = a[2],\n      a10 = a[3],\n      a11 = a[4],\n      a12 = a[5],\n      a20 = a[6],\n      a21 = a[7],\n      a22 = a[8],\n      x = v[0],\n      y = v[1];\n  out[0] = a00;\n  out[1] = a01;\n  out[2] = a02;\n  out[3] = a10;\n  out[4] = a11;\n  out[5] = a12;\n  out[6] = x * a00 + y * a10 + a20;\n  out[7] = x * a01 + y * a11 + a21;\n  out[8] = x * a02 + y * a12 + a22;\n  return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nfunction rotate(out, a, rad) {\n  var a00 = a[0],\n      a01 = a[1],\n      a02 = a[2],\n      a10 = a[3],\n      a11 = a[4],\n      a12 = a[5],\n      a20 = a[6],\n      a21 = a[7],\n      a22 = a[8],\n      s = Math.sin(rad),\n      c = Math.cos(rad);\n  out[0] = c * a00 + s * a10;\n  out[1] = c * a01 + s * a11;\n  out[2] = c * a02 + s * a12;\n  out[3] = c * a10 - s * a00;\n  out[4] = c * a11 - s * a01;\n  out[5] = c * a12 - s * a02;\n  out[6] = a20;\n  out[7] = a21;\n  out[8] = a22;\n  return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nfunction scale(out, a, v) {\n  var x = v[0],\n      y = v[1];\n  out[0] = x * a[0];\n  out[1] = x * a[1];\n  out[2] = x * a[2];\n  out[3] = y * a[3];\n  out[4] = y * a[4];\n  out[5] = y * a[5];\n  out[6] = a[6];\n  out[7] = a[7];\n  out[8] = a[8];\n  return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nfunction projection(out, width, height) {\n  out[0] = 2 / width;\n  out[1] = 0;\n  out[2] = 0;\n  out[3] = 0;\n  out[4] = -2 / height;\n  out[5] = 0;\n  out[6] = -1;\n  out[7] = 1;\n  out[8] = 1;\n  return out;\n}\n\nvar RENDER_TARGET = {\n  SCREEN: {\n    name: 'screen',\n    screen: true\n  },\n  PICKING: {\n    name: 'picking',\n    picking: true\n  }\n};\nvar atlasCollectionDefaults = defaults$g({\n  texRows: 24\n});\nvar renderDefaults = defaults$g({\n  collection: 'default',\n  getKey: null,\n  // since render types (eg node-body, node-overlay) can share an atlas collection, its importeant their style keys don't collide\n  drawElement: null,\n  getBoundingBox: null,\n  getRotation: null,\n  getRotationPoint: null,\n  getRotationOffset: null,\n  isVisible: function isVisible() {\n    return true;\n  },\n  // this is an extra check for visibility in addition to ele.visible()\n  getPadding: 0\n});\n\n// A \"texture atlas\" is a big image/canvas, and sections of it are used as textures for nodes/labels.\n\n/**\n * A single square texture atlas (also known as a \"sprite sheet\").\n */\nvar Atlas = /*#__PURE__*/function () {\n  function Atlas(r, texSize, texRows, createTextureCanvas) {\n    _classCallCheck(this, Atlas);\n    this.debugID = Math.floor(Math.random() * 10000);\n    this.r = r;\n    this.texSize = texSize;\n    this.texRows = texRows;\n    this.texHeight = Math.floor(texSize / texRows);\n    this.enableWrapping = true; // hardcoded for now, can be made an option\n\n    this.locked = false; // once an atlas is locked it can no longer be drawn to\n    this.texture = null; // WebGLTexture object\n    this.needsBuffer = true;\n\n    // a \"location\" is an object with a 'row' and 'x' fields\n    this.freePointer = {\n      x: 0,\n      row: 0\n    };\n\n    // map from the style key to the row/x where the texture starts\n    // if the texture wraps then there's a second location\n    this.keyToLocation = new Map(); // styleKey -> [ location, location ]\n\n    this.canvas = createTextureCanvas(r, texSize, texSize);\n    this.scratch = createTextureCanvas(r, texSize, this.texHeight, 'scratch');\n  }\n  return _createClass(Atlas, [{\n    key: \"lock\",\n    value: function lock() {\n      this.locked = true;\n    }\n  }, {\n    key: \"getKeys\",\n    value: function getKeys() {\n      return new Set(this.keyToLocation.keys());\n    }\n  }, {\n    key: \"getScale\",\n    value: function getScale(_ref) {\n      var w = _ref.w,\n        h = _ref.h;\n      var texHeight = this.texHeight,\n        maxTexWidth = this.texSize;\n      // try to fit to the height of a row\n      var scale = texHeight / h; // TODO what about pixelRatio?\n      var texW = w * scale;\n      var texH = h * scale;\n      // if the scaled width is too wide then scale to fit max width instead\n      if (texW > maxTexWidth) {\n        scale = maxTexWidth / w;\n        texW = w * scale;\n        texH = h * scale;\n      }\n      return {\n        scale: scale,\n        texW: texW,\n        texH: texH\n      };\n    }\n  }, {\n    key: \"draw\",\n    value: function draw(key, bb, doDrawing) {\n      var _this = this;\n      if (this.locked) throw new Error('can\\'t draw, atlas is locked');\n      var texSize = this.texSize,\n        texRows = this.texRows,\n        texHeight = this.texHeight;\n      var _this$getScale = this.getScale(bb),\n        scale = _this$getScale.scale,\n        texW = _this$getScale.texW,\n        texH = _this$getScale.texH;\n      var locations = [null, null];\n      var drawAt = function drawAt(location, canvas) {\n        if (doDrawing && canvas) {\n          var context = canvas.context;\n          var x = location.x,\n            row = location.row;\n          var xOffset = x;\n          var yOffset = texHeight * row;\n          context.save();\n          context.translate(xOffset, yOffset);\n          context.scale(scale, scale);\n          doDrawing(context, bb);\n          context.restore();\n        }\n      };\n      var drawNormal = function drawNormal() {\n        // don't need to wrap, draw directly on the canvas\n        drawAt(_this.freePointer, _this.canvas);\n        locations[0] = {\n          x: _this.freePointer.x,\n          y: _this.freePointer.row * texHeight,\n          w: texW,\n          h: texH\n        };\n        locations[1] = {\n          // indlude a second location with a width of 0, for convenience\n          x: _this.freePointer.x + texW,\n          y: _this.freePointer.row * texHeight,\n          w: 0,\n          h: texH\n        };\n\n        // move the pointer to the end of the texture\n        _this.freePointer.x += texW;\n        if (_this.freePointer.x == texSize) {\n          // move to the next row\n          // TODO what if there is no next row???\n          _this.freePointer.x = 0;\n          _this.freePointer.row++;\n        }\n      };\n      var drawWrapped = function drawWrapped() {\n        var scratch = _this.scratch,\n          canvas = _this.canvas;\n\n        // Draw to the scratch canvas\n        scratch.clear();\n        drawAt({\n          x: 0,\n          row: 0\n        }, scratch);\n        var firstTexW = texSize - _this.freePointer.x;\n        var secondTexW = texW - firstTexW;\n        var h = texHeight;\n        {\n          // copy first part of scratch to the first texture\n          var dx = _this.freePointer.x;\n          var dy = _this.freePointer.row * texHeight;\n          var w = firstTexW;\n          canvas.context.drawImage(scratch, 0, 0, w, h, dx, dy, w, h);\n          locations[0] = {\n            x: dx,\n            y: dy,\n            w: w,\n            h: texH\n          };\n        }\n        {\n          // copy second part of scratch to the second texture\n          var sx = firstTexW;\n          var _dy = (_this.freePointer.row + 1) * texHeight;\n          var _w = secondTexW;\n          if (canvas) {\n            canvas.context.drawImage(scratch, sx, 0, _w, h, 0, _dy, _w, h);\n          }\n          locations[1] = {\n            x: 0,\n            y: _dy,\n            w: _w,\n            h: texH\n          };\n        }\n        _this.freePointer.x = secondTexW;\n        _this.freePointer.row++;\n      };\n      var moveToStartOfNextRow = function moveToStartOfNextRow() {\n        _this.freePointer.x = 0;\n        _this.freePointer.row++;\n      };\n      if (this.freePointer.x + texW <= texSize) {\n        // There's enough space in the current row\n        drawNormal();\n      } else if (this.freePointer.row >= texRows - 1) {\n        // Need to move to the next row, but there are no more rows, atlas is full.\n        return false;\n      } else if (this.freePointer.x === texSize) {\n        // happen to be right at end of current row\n        moveToStartOfNextRow();\n        drawNormal();\n      } else if (this.enableWrapping) {\n        // draw part of the texture to the end of the curent row, then wrap to the next row\n        drawWrapped();\n      } else {\n        // move to the start of the next row, then draw normally\n        moveToStartOfNextRow();\n        drawNormal();\n      }\n      this.keyToLocation.set(key, locations);\n      this.needsBuffer = true;\n      return locations;\n    }\n  }, {\n    key: \"getOffsets\",\n    value: function getOffsets(key) {\n      return this.keyToLocation.get(key);\n    }\n  }, {\n    key: \"isEmpty\",\n    value: function isEmpty() {\n      return this.freePointer.x === 0 && this.freePointer.row === 0;\n    }\n  }, {\n    key: \"canFit\",\n    value: function canFit(bb) {\n      if (this.locked) return false;\n      var texSize = this.texSize,\n        texRows = this.texRows;\n      var _this$getScale2 = this.getScale(bb),\n        texW = _this$getScale2.texW;\n      if (this.freePointer.x + texW > texSize) {\n        // need to wrap\n        return this.freePointer.row < texRows - 1; // return true if there's a row to wrap to\n      }\n      return true;\n    }\n\n    // called on every frame\n  }, {\n    key: \"bufferIfNeeded\",\n    value: function bufferIfNeeded(gl) {\n      if (!this.texture) {\n        this.texture = createTexture(gl, this.debugID);\n      }\n      if (this.needsBuffer) {\n        this.texture.buffer(this.canvas);\n        this.needsBuffer = false;\n        if (this.locked) {\n          this.canvas = null;\n          this.scratch = null;\n        }\n      }\n    }\n  }, {\n    key: \"dispose\",\n    value: function dispose() {\n      if (this.texture) {\n        this.texture.deleteTexture();\n        this.texture = null;\n      }\n      this.canvas = null;\n      this.scratch = null;\n      this.locked = true;\n    }\n  }]);\n}();\n\n/**\n * A collection of texture atlases, all of the same \"render type\". \n * (Node body is an example of a render type.)\n * An AtlasCollection can also be notified when a texture is no longer needed, \n * and it can garbage collect the unused textures.\n */\nvar AtlasCollection = /*#__PURE__*/function () {\n  function AtlasCollection(r, texSize, texRows, createTextureCanvas) {\n    _classCallCheck(this, AtlasCollection);\n    this.r = r;\n    this.texSize = texSize;\n    this.texRows = texRows;\n    this.createTextureCanvas = createTextureCanvas;\n    this.atlases = [];\n    this.styleKeyToAtlas = new Map();\n    this.markedKeys = new Set(); // marked for garbage collection\n  }\n  return _createClass(AtlasCollection, [{\n    key: \"getKeys\",\n    value: function getKeys() {\n      return new Set(this.styleKeyToAtlas.keys());\n    }\n  }, {\n    key: \"_createAtlas\",\n    value: function _createAtlas() {\n      var r = this.r,\n        texSize = this.texSize,\n        texRows = this.texRows,\n        createTextureCanvas = this.createTextureCanvas;\n      return new Atlas(r, texSize, texRows, createTextureCanvas);\n    }\n  }, {\n    key: \"_getScratchCanvas\",\n    value: function _getScratchCanvas() {\n      if (!this.scratch) {\n        var r = this.r,\n          texSize = this.texSize,\n          texRows = this.texRows,\n          createTextureCanvas = this.createTextureCanvas;\n        var texHeight = Math.floor(texSize / texRows);\n        this.scratch = createTextureCanvas(r, texSize, texHeight, 'scratch');\n      }\n      return this.scratch;\n    }\n  }, {\n    key: \"draw\",\n    value: function draw(key, bb, doDrawing) {\n      var atlas = this.styleKeyToAtlas.get(key);\n      if (!atlas) {\n        // check for space at the end of the last atlas\n        atlas = this.atlases[this.atlases.length - 1];\n        if (!atlas || !atlas.canFit(bb)) {\n          if (atlas) atlas.lock();\n          // create a new atlas\n          atlas = this._createAtlas();\n          this.atlases.push(atlas);\n        }\n        atlas.draw(key, bb, doDrawing);\n        this.styleKeyToAtlas.set(key, atlas);\n      }\n      return atlas;\n    }\n  }, {\n    key: \"getAtlas\",\n    value: function getAtlas(key) {\n      return this.styleKeyToAtlas.get(key);\n    }\n  }, {\n    key: \"hasAtlas\",\n    value: function hasAtlas(key) {\n      return this.styleKeyToAtlas.has(key);\n    }\n  }, {\n    key: \"markKeyForGC\",\n    value: function markKeyForGC(key) {\n      this.markedKeys.add(key);\n    }\n  }, {\n    key: \"gc\",\n    value: function gc() {\n      var _this2 = this;\n      var markedKeys = this.markedKeys;\n      if (markedKeys.size === 0) {\n        console.log('nothing to garbage collect');\n        return;\n      }\n      var newAtlases = [];\n      var newStyleKeyToAtlas = new Map();\n      var newAtlas = null;\n      var _iterator = _createForOfIteratorHelper(this.atlases),\n        _step;\n      try {\n        var _loop = function _loop() {\n          var atlas = _step.value;\n          var keys = atlas.getKeys();\n          var keysToCollect = intersection(markedKeys, keys);\n          if (keysToCollect.size === 0) {\n            // this atlas can still be used\n            newAtlases.push(atlas);\n            keys.forEach(function (k) {\n              return newStyleKeyToAtlas.set(k, atlas);\n            });\n            return 1; // continue\n          }\n          if (!newAtlas) {\n            newAtlas = _this2._createAtlas();\n            newAtlases.push(newAtlas);\n          }\n          var _iterator2 = _createForOfIteratorHelper(keys),\n            _step2;\n          try {\n            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n              var key = _step2.value;\n              if (!keysToCollect.has(key)) {\n                var _atlas$getOffsets = atlas.getOffsets(key),\n                  _atlas$getOffsets2 = _slicedToArray(_atlas$getOffsets, 2),\n                  s1 = _atlas$getOffsets2[0],\n                  s2 = _atlas$getOffsets2[1];\n                if (!newAtlas.canFit({\n                  w: s1.w + s2.w,\n                  h: s1.h\n                })) {\n                  newAtlas.lock();\n                  newAtlas = _this2._createAtlas();\n                  newAtlases.push(newAtlas);\n                }\n                _this2._copyTextureToNewAtlas(key, atlas, newAtlas);\n                newStyleKeyToAtlas.set(key, newAtlas);\n              }\n            }\n          } catch (err) {\n            _iterator2.e(err);\n          } finally {\n            _iterator2.f();\n          }\n          atlas.dispose();\n        };\n        for (_iterator.s(); !(_step = _iterator.n()).done;) {\n          if (_loop()) continue;\n        }\n      } catch (err) {\n        _iterator.e(err);\n      } finally {\n        _iterator.f();\n      }\n      this.atlases = newAtlases;\n      this.styleKeyToAtlas = newStyleKeyToAtlas;\n      this.markedKeys = new Set();\n    }\n  }, {\n    key: \"_copyTextureToNewAtlas\",\n    value: function _copyTextureToNewAtlas(key, oldAtlas, newAtlas) {\n      var _oldAtlas$getOffsets = oldAtlas.getOffsets(key),\n        _oldAtlas$getOffsets2 = _slicedToArray(_oldAtlas$getOffsets, 2),\n        s1 = _oldAtlas$getOffsets2[0],\n        s2 = _oldAtlas$getOffsets2[1];\n      if (s2.w === 0) {\n        // the texture does not wrap, draw directly to new atlas\n        newAtlas.draw(key, s1, function (context) {\n          context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);\n        });\n      } else {\n        // the texture wraps, first draw both parts to a scratch canvas\n        var scratch = this._getScratchCanvas();\n        scratch.clear();\n        scratch.context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);\n        scratch.context.drawImage(oldAtlas.canvas, s2.x, s2.y, s2.w, s2.h, s1.w, 0, s2.w, s2.h);\n\n        // now draw the scratch to the new atlas\n        var w = s1.w + s2.w;\n        var h = s1.h;\n        newAtlas.draw(key, {\n          w: w,\n          h: h\n        }, function (context) {\n          context.drawImage(scratch, 0, 0, w, h, 0, 0, w, h // the destination context has already been translated to the correct position\n          );\n        });\n      }\n    }\n  }, {\n    key: \"getCounts\",\n    value: function getCounts() {\n      return {\n        keyCount: this.styleKeyToAtlas.size,\n        atlasCount: new Set(this.styleKeyToAtlas.values()).size\n      };\n    }\n  }]);\n}();\nfunction intersection(set1, set2) {\n  // TODO why no Set.intersection in node 16???\n  if (set1.intersection) return set1.intersection(set2);else return new Set(_toConsumableArray(set1).filter(function (x) {\n    return set2.has(x);\n  }));\n}\n\n/**\n * Used to manage batches of Atlases for drawing nodes and labels.\n * Supports different types of AtlasCollections for different render types (or 'texture groups'),\n * for example 'node body' and 'node label' would be different render types.\n * Render types are kept separate because they will likely need to be garbage collected\n * separately and its not entierly guaranteed that their style keys won't collide.\n */\nvar AtlasManager = /*#__PURE__*/function () {\n  function AtlasManager(r, globalOptions) {\n    _classCallCheck(this, AtlasManager);\n    this.r = r;\n    this.globalOptions = globalOptions;\n    this.atlasSize = globalOptions.webglTexSize;\n    this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;\n    this.renderTypes = new Map(); // renderType:string -> renderTypeOptions\n    this.collections = new Map(); // collectionName:string -> AtlasCollection\n\n    this.typeAndIdToKey = new Map(); // [renderType,id] => style key\n\n    this.batchAtlases = [];\n  }\n  return _createClass(AtlasManager, [{\n    key: \"getAtlasSize\",\n    value: function getAtlasSize() {\n      return this.atlasSize;\n    }\n  }, {\n    key: \"getMaxAtlasesPerBatch\",\n    value: function getMaxAtlasesPerBatch() {\n      return this.maxAtlasesPerBatch;\n    }\n  }, {\n    key: \"addAtlasCollection\",\n    value: function addAtlasCollection(collectionName, atlasCollectionOptions) {\n      var _this$globalOptions = this.globalOptions,\n        webglTexSize = _this$globalOptions.webglTexSize,\n        createTextureCanvas = _this$globalOptions.createTextureCanvas;\n      var texRows = atlasCollectionOptions.texRows;\n      var cachedCreateTextureCanvas = this._cacheScratchCanvas(createTextureCanvas);\n      var atlasCollection = new AtlasCollection(this.r, webglTexSize, texRows, cachedCreateTextureCanvas);\n      this.collections.set(collectionName, atlasCollection);\n    }\n  }, {\n    key: \"addRenderType\",\n    value: function addRenderType(type, renderTypeOptions) {\n      var collection = renderTypeOptions.collection;\n      if (!this.collections.has(collection)) throw new Error(\"invalid atlas collection name '\".concat(collection, \"'\"));\n      var atlasCollection = this.collections.get(collection);\n      var opts = extend({\n        type: type,\n        atlasCollection: atlasCollection\n      }, renderTypeOptions);\n      this.renderTypes.set(type, opts);\n    }\n  }, {\n    key: \"getRenderTypeOpts\",\n    value: function getRenderTypeOpts(type) {\n      return this.renderTypes.get(type);\n    }\n  }, {\n    key: \"getAtlasCollection\",\n    value: function getAtlasCollection(name) {\n      return this.collections.get(name);\n    }\n  }, {\n    key: \"_cacheScratchCanvas\",\n    value: function _cacheScratchCanvas(createTextureCanvas) {\n      // all scratch canvases for the same render type will have the same width and height (ie webglTexRows option)\n      // but we'll keep track of the width and height just to be safe\n      var prevW = -1;\n      var prevH = -1;\n      var scratchCanvas = null;\n      return function (r, w, h, scratch) {\n        if (scratch) {\n          if (!scratchCanvas || w != prevW || h != prevH) {\n            prevW = w;\n            prevH = h;\n            scratchCanvas = createTextureCanvas(r, w, h);\n          }\n          return scratchCanvas;\n        } else {\n          return createTextureCanvas(r, w, h);\n        }\n      };\n    }\n  }, {\n    key: \"_key\",\n    value: function _key(renderType, id) {\n      return \"\".concat(renderType, \"-\").concat(id); // TODO not very efficient\n    }\n\n    /** Marks textues associated with the element for garbage collection. */\n  }, {\n    key: \"invalidate\",\n    value: function invalidate(eles) {\n      var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n        _ref2$forceRedraw = _ref2.forceRedraw,\n        forceRedraw = _ref2$forceRedraw === undefined ? false : _ref2$forceRedraw,\n        _ref2$filterEle = _ref2.filterEle,\n        filterEle = _ref2$filterEle === undefined ? function () {\n          return true;\n        } : _ref2$filterEle,\n        _ref2$filterType = _ref2.filterType,\n        filterType = _ref2$filterType === undefined ? function () {\n          return true;\n        } : _ref2$filterType;\n      var needGC = false;\n      var runGCNow = false;\n      var _iterator3 = _createForOfIteratorHelper(eles),\n        _step3;\n      try {\n        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n          var ele = _step3.value;\n          if (filterEle(ele)) {\n            var _iterator4 = _createForOfIteratorHelper(this.renderTypes.values()),\n              _step4;\n            try {\n              for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n                var opts = _step4.value;\n                var renderType = opts.type;\n                if (filterType(renderType)) {\n                  var styleKey = opts.getKey(ele);\n                  var atlasCollection = this.collections.get(opts.collection);\n\n                  // when a node's background image finishes loading, the style key doesn't change but still needs to be redrawn\n                  if (forceRedraw) {\n                    atlasCollection.markKeyForGC(styleKey);\n                    runGCNow = true; // run GC to remove the old texture right now, that way we don't need to remember for the next gc \n                  } else {\n                    var id = opts.getID ? opts.getID(ele) : ele.id();\n                    var mapKey = this._key(renderType, id);\n                    var oldStyleKey = this.typeAndIdToKey.get(mapKey);\n                    if (oldStyleKey !== undefined && oldStyleKey !== styleKey) {\n                      this.typeAndIdToKey[\"delete\"](mapKey);\n                      atlasCollection.markKeyForGC(oldStyleKey);\n                      needGC = true;\n                    }\n                  }\n                }\n              }\n            } catch (err) {\n              _iterator4.e(err);\n            } finally {\n              _iterator4.f();\n            }\n          }\n        }\n      } catch (err) {\n        _iterator3.e(err);\n      } finally {\n        _iterator3.f();\n      }\n      if (runGCNow) {\n        this.gc();\n        needGC = false;\n      }\n      return needGC;\n    }\n\n    /** Garbage collect */\n  }, {\n    key: \"gc\",\n    value: function gc() {\n      var _iterator5 = _createForOfIteratorHelper(this.collections.values()),\n        _step5;\n      try {\n        for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n          var collection = _step5.value;\n          collection.gc();\n        }\n      } catch (err) {\n        _iterator5.e(err);\n      } finally {\n        _iterator5.f();\n      }\n    }\n  }, {\n    key: \"getOrCreateAtlas\",\n    value: function getOrCreateAtlas(ele, type, bb) {\n      var opts = this.renderTypes.get(type);\n      var styleKey = opts.getKey(ele);\n      if (!bb) bb = opts.getBoundingBox(ele);\n      var atlasCollection = this.collections.get(opts.collection);\n\n      // draws the texture only if needed\n      var drawn = false;\n      var atlas = atlasCollection.draw(styleKey, bb, function (context) {\n        opts.drawElement(context, ele, bb, true, true);\n        drawn = true;\n      });\n      if (drawn) {\n        var id = opts.getID ? opts.getID(ele) : ele.id(); // for testing\n        var mapKey = this._key(type, id);\n        this.typeAndIdToKey.set(mapKey, styleKey);\n      }\n      return atlas;\n    }\n  }, {\n    key: \"startBatch\",\n    value: function startBatch() {\n      this.batchAtlases = [];\n    }\n  }, {\n    key: \"getAtlasCount\",\n    value: function getAtlasCount() {\n      return this.batchAtlases.length;\n    }\n  }, {\n    key: \"getAtlases\",\n    value: function getAtlases() {\n      return this.batchAtlases;\n    }\n  }, {\n    key: \"canAddToCurrentBatch\",\n    value: function canAddToCurrentBatch(ele, type) {\n      if (this.batchAtlases.length === this.maxAtlasesPerBatch) {\n        // batch is full, is the atlas already part of this batch?\n        var opts = this.renderTypes.get(type);\n        var styleKey = opts.getKey(ele);\n        var atlasCollection = this.collections.get(opts.collection);\n        var atlas = atlasCollection.getAtlas(styleKey);\n        // return true if there is an atlas and it is part of this batch already\n        return Boolean(atlas) && this.batchAtlases.includes(atlas);\n      }\n      return true; // not full\n    }\n  }, {\n    key: \"getAtlasIndexForBatch\",\n    value: function getAtlasIndexForBatch(atlas) {\n      var atlasID = this.batchAtlases.indexOf(atlas);\n      if (atlasID < 0) {\n        if (this.batchAtlases.length === this.maxAtlasesPerBatch) {\n          return;\n        }\n        this.batchAtlases.push(atlas);\n        atlasID = this.batchAtlases.length - 1;\n      }\n      return atlasID;\n    }\n  }, {\n    key: \"getIndexArray\",\n    value: function getIndexArray() {\n      return Array.from({\n        length: this.maxAtlasesPerBatch\n      }, function (v, i) {\n        return i;\n      });\n    }\n  }, {\n    key: \"getAtlasInfo\",\n    value: function getAtlasInfo(ele, type) {\n      var opts = this.renderTypes.get(type);\n      var bb = opts.getBoundingBox(ele);\n      var atlas = this.getOrCreateAtlas(ele, type, bb);\n      var index = this.getAtlasIndexForBatch(atlas);\n      if (index === undefined) {\n        return undefined; // batch is full\n      }\n      var styleKey = opts.getKey(ele);\n      var _atlas$getOffsets3 = atlas.getOffsets(styleKey),\n        _atlas$getOffsets4 = _slicedToArray(_atlas$getOffsets3, 2),\n        tex1 = _atlas$getOffsets4[0],\n        tex2 = _atlas$getOffsets4[1];\n      // This object may be passed back to setTransformMatrix()\n      return {\n        index: index,\n        tex1: tex1,\n        tex2: tex2,\n        bb: bb\n      };\n    }\n\n    /**\n     * matrix is expected to be a 9 element array\n     * this function follows same pattern as CRp.drawCachedElementPortion(...)\n     */\n  }, {\n    key: \"setTransformMatrix\",\n    value: function setTransformMatrix(ele, matrix, type, atlasInfo) {\n      var first = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n      var opts = this.getRenderTypeOpts(type);\n      var padding = opts.getPadding ? opts.getPadding(ele) : 0;\n      if (atlasInfo) {\n        // we've already computed the bb and tex bounds for a texture\n        var bb = atlasInfo.bb,\n          tex1 = atlasInfo.tex1,\n          tex2 = atlasInfo.tex2;\n\n        // wrapped textures need separate matrix for each part\n        var ratio = tex1.w / (tex1.w + tex2.w);\n        if (!first) {\n          // first = true means its the first part of the wrapped texture\n          ratio = 1 - ratio;\n        }\n        var adjBB = this.getAdjustedBB(bb, padding, first, ratio);\n        this._applyTransformMatrix(matrix, adjBB, opts, ele);\n      } else {\n        // we don't have a texture yet, or we want to avoid creating a texture for simple shapes\n        var _bb = opts.getBoundingBox(ele);\n        var _adjBB = this.getAdjustedBB(_bb, padding, true, 1);\n        this._applyTransformMatrix(matrix, _adjBB, opts, ele);\n      }\n    }\n  }, {\n    key: \"_applyTransformMatrix\",\n    value: function _applyTransformMatrix(matrix, adjBB, opts, ele) {\n      var x, y;\n      identity(matrix);\n      var theta = opts.getRotation ? opts.getRotation(ele) : 0;\n      if (theta !== 0) {\n        var _opts$getRotationPoin = opts.getRotationPoint(ele),\n          sx = _opts$getRotationPoin.x,\n          sy = _opts$getRotationPoin.y;\n        translate(matrix, matrix, [sx, sy]);\n        rotate(matrix, matrix, theta);\n        var offset = opts.getRotationOffset(ele);\n        x = offset.x + adjBB.xOffset;\n        y = offset.y;\n      } else {\n        x = adjBB.x1;\n        y = adjBB.y1;\n      }\n      translate(matrix, matrix, [x, y]);\n      scale(matrix, matrix, [adjBB.w, adjBB.h]);\n    }\n\n    /**\n     * Adjusts a node or label BB to accomodate padding and split for wrapped textures.\n     * @param bb - the original bounding box\n     * @param padding - the padding to add to the bounding box\n     * @param first - whether this is the first part of a wrapped texture\n     * @param ratio - the ratio of the texture width of part of the text to the entire texture\n     */\n  }, {\n    key: \"getAdjustedBB\",\n    value: function getAdjustedBB(bb, padding, first, ratio) {\n      var x1 = bb.x1,\n        y1 = bb.y1,\n        w = bb.w,\n        h = bb.h;\n      if (padding) {\n        x1 -= padding;\n        y1 -= padding;\n        w += 2 * padding;\n        h += 2 * padding;\n      }\n      var xOffset = 0;\n      var adjW = w * ratio;\n      if (first && ratio < 1) {\n        w = adjW;\n      } else if (!first && ratio < 1) {\n        xOffset = w - adjW;\n        x1 += xOffset;\n        w = adjW;\n      }\n      return {\n        x1: x1,\n        y1: y1,\n        w: w,\n        h: h,\n        xOffset: xOffset\n      };\n    }\n  }, {\n    key: \"getDebugInfo\",\n    value: function getDebugInfo() {\n      var debugInfo = [];\n      var _iterator6 = _createForOfIteratorHelper(this.collections),\n        _step6;\n      try {\n        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {\n          var _step6$value = _slicedToArray(_step6.value, 2),\n            name = _step6$value[0],\n            collection = _step6$value[1];\n          var _collection$getCounts = collection.getCounts(),\n            keyCount = _collection$getCounts.keyCount,\n            atlasCount = _collection$getCounts.atlasCount;\n          debugInfo.push({\n            type: name,\n            keyCount: keyCount,\n            atlasCount: atlasCount\n          });\n        }\n      } catch (err) {\n        _iterator6.e(err);\n      } finally {\n        _iterator6.f();\n      }\n      return debugInfo;\n    }\n  }]);\n}();\n\n// Vertex types\nvar TEXTURE = 0;\nvar EDGE_STRAIGHT = 1;\nvar EDGE_CURVE_SEGMENT = 2;\nvar EDGE_ARROW = 3;\nvar RECTANGLE = 4;\nvar ElementDrawingWebGL = /*#__PURE__*/function () {\n  /** \n   * @param {WebGLRenderingContext} gl \n   */\n  function ElementDrawingWebGL(r, gl, opts) {\n    _classCallCheck(this, ElementDrawingWebGL);\n    this.r = r;\n    this.gl = gl;\n    this.maxInstances = opts.webglBatchSize;\n    this.atlasSize = opts.webglTexSize;\n    this.bgColor = opts.bgColor;\n    this.debug = opts.webglDebug;\n    this.batchDebugInfo = [];\n    opts.enableWrapping = true;\n    opts.createTextureCanvas = createTextureCanvas; // Unit tests mock this\n    this.atlasManager = new AtlasManager(r, opts);\n    this.program = this.createShaderProgram(RENDER_TARGET.SCREEN);\n    this.pickingProgram = this.createShaderProgram(RENDER_TARGET.PICKING);\n    this.vao = this.createVAO();\n  }\n  return _createClass(ElementDrawingWebGL, [{\n    key: \"addAtlasCollection\",\n    value: function addAtlasCollection(groupName, opts) {\n      this.atlasManager.addAtlasCollection(groupName, opts);\n    }\n  }, {\n    key: \"addAtlasRenderType\",\n    value: function addAtlasRenderType(typeName, opts) {\n      this.atlasManager.addRenderType(typeName, opts);\n    }\n  }, {\n    key: \"invalidate\",\n    value: function invalidate(eles) {\n      var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n        type = _ref.type;\n      var atlasManager = this.atlasManager;\n      if (type) {\n        return atlasManager.invalidate(eles, {\n          filterType: function filterType(t) {\n            return t === type;\n          },\n          forceRedraw: true\n        });\n      } else {\n        return atlasManager.invalidate(eles);\n      }\n    }\n  }, {\n    key: \"gc\",\n    value: function gc() {\n      this.atlasManager.gc();\n    }\n  }, {\n    key: \"createShaderProgram\",\n    value: function createShaderProgram(renderTarget) {\n      var gl = this.gl;\n\n      // compute texture coordinates in the shader, becase we are using instanced drawing\n      var vertexShaderSource = \"#version 300 es\\n      precision highp float;\\n\\n      uniform mat3 uPanZoomMatrix;\\n      uniform int  uAtlasSize;\\n      \\n      // instanced\\n      in vec2 aPosition; \\n\\n      in mat3 aTransform;\\n\\n      // what are we rendering?\\n      in int aVertType;\\n\\n      // for picking\\n      in vec4 aIndex;\\n      \\n      // For textures\\n      in int aAtlasId; // which shader unit/atlas to use\\n      in vec4 aTex; // x/y/w/h of texture in atlas\\n\\n      // for edges\\n      in vec4 aPointAPointB;\\n      in vec4 aPointCPointD;\\n      in float aLineWidth;\\n      in vec4 aColor;\\n\\n      out vec2 vTexCoord;\\n      out vec4 vColor;\\n      flat out int vAtlasId;\\n      flat out vec4 vIndex;\\n      flat out int vVertType;\\n\\n      void main(void) {\\n        int vid = gl_VertexID;\\n        vec2 position = aPosition;\\n\\n        if(aVertType == \".concat(TEXTURE, \") {\\n          float texX = aTex.x;\\n          float texY = aTex.y;\\n          float texW = aTex.z;\\n          float texH = aTex.w;\\n\\n          int vid = gl_VertexID;\\n\\n          if(vid == 1 || vid == 2 || vid == 4) {\\n            texX += texW;\\n          }\\n          if(vid == 2 || vid == 4 || vid == 5) {\\n            texY += texH;\\n          }\\n\\n          float d = float(uAtlasSize);\\n          vTexCoord = vec2(texX / d, texY / d); // tex coords must be between 0 and 1\\n\\n          gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\\n        }\\n        else if(aVertType == \").concat(RECTANGLE, \") {\\n          gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\\n          vColor = aColor;\\n        }\\n        else if(aVertType == \").concat(EDGE_STRAIGHT, \") {\\n          vec2 source = aPointAPointB.xy;\\n          vec2 target = aPointAPointB.zw;\\n\\n          // adjust the geometry so that the line is centered on the edge\\n          position.y = position.y - 0.5;\\n\\n          vec2 xBasis = target - source;\\n          vec2 yBasis = normalize(vec2(-xBasis.y, xBasis.x));\\n          vec2 point = source + xBasis * position.x + yBasis * aLineWidth * position.y;\\n\\n          gl_Position = vec4(uPanZoomMatrix * vec3(point, 1.0), 1.0);\\n          vColor = aColor;\\n        } \\n        else if(aVertType == \").concat(EDGE_CURVE_SEGMENT, \") {\\n          vec2 pointA = aPointAPointB.xy;\\n          vec2 pointB = aPointAPointB.zw;\\n          vec2 pointC = aPointCPointD.xy;\\n          vec2 pointD = aPointCPointD.zw;\\n\\n          // adjust the geometry so that the line is centered on the edge\\n          position.y = position.y - 0.5;\\n\\n          vec2 p0 = pointA;\\n          vec2 p1 = pointB;\\n          vec2 p2 = pointC;\\n          vec2 pos = position;\\n          if(position.x == 1.0) {\\n            p0 = pointD;\\n            p1 = pointC;\\n            p2 = pointB;\\n            pos = vec2(0.0, -position.y);\\n          }\\n\\n          vec2 p01 = p1 - p0;\\n          vec2 p12 = p2 - p1;\\n          vec2 p21 = p1 - p2;\\n\\n          // Find the normal vector.\\n          vec2 tangent = normalize(normalize(p12) + normalize(p01));\\n          vec2 normal = vec2(-tangent.y, tangent.x);\\n\\n          // Find the vector perpendicular to p0 -> p1.\\n          vec2 p01Norm = normalize(vec2(-p01.y, p01.x));\\n\\n          // Determine the bend direction.\\n          float sigma = sign(dot(p01 + p21, normal));\\n          float width = aLineWidth;\\n\\n          if(sign(pos.y) == -sigma) {\\n            // This is an intersecting vertex. Adjust the position so that there's no overlap.\\n            vec2 point = 0.5 * width * normal * -sigma / dot(normal, p01Norm);\\n            gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0);\\n          } else {\\n            // This is a non-intersecting vertex. Treat it like a mitre join.\\n            vec2 point = 0.5 * width * normal * sigma * dot(normal, p01Norm);\\n            gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0);\\n          }\\n\\n          vColor = aColor;\\n        } \\n        else if(aVertType == \").concat(EDGE_ARROW, \" && vid < 3) {\\n          // massage the first triangle into an edge arrow\\n          if(vid == 0)\\n            position = vec2(-0.15, -0.3);\\n          if(vid == 1)\\n            position = vec2( 0.0,   0.0);\\n          if(vid == 2)\\n            position = vec2( 0.15, -0.3);\\n\\n          gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\\n          vColor = aColor;\\n        }\\n        else {\\n          gl_Position = vec4(2.0, 0.0, 0.0, 1.0); // discard vertex by putting it outside webgl clip space\\n        }\\n\\n        vAtlasId = aAtlasId;\\n        vIndex = aIndex;\\n        vVertType = aVertType;\\n      }\\n    \");\n      var idxs = this.atlasManager.getIndexArray();\n      var fragmentShaderSource = \"#version 300 es\\n      precision highp float;\\n\\n      // define texture unit for each node in the batch\\n      \".concat(idxs.map(function (i) {\n        return \"uniform sampler2D uTexture\".concat(i, \";\");\n      }).join('\\n\\t'), \"\\n\\n      uniform vec4 uBGColor;\\n\\n      in vec2 vTexCoord;\\n      in vec4 vColor;\\n      flat in int vAtlasId;\\n      flat in vec4 vIndex;\\n      flat in int vVertType;\\n\\n      out vec4 outColor;\\n\\n      void main(void) {\\n        if(vVertType == \").concat(TEXTURE, \") {\\n          \").concat(idxs.map(function (i) {\n        return \"if(vAtlasId == \".concat(i, \") outColor = texture(uTexture\").concat(i, \", vTexCoord);\");\n      }).join('\\n\\telse '), \"\\n        } else if(vVertType == \").concat(EDGE_ARROW, \") {\\n          // blend arrow color with background (using premultiplied alpha)\\n          outColor.rgb = vColor.rgb + (uBGColor.rgb * (1.0 - vColor.a)); \\n          outColor.a = 1.0; // make opaque, masks out line under arrow\\n        } else {\\n          outColor = vColor;\\n        }\\n\\n        \").concat(renderTarget.picking ? \"if(outColor.a == 0.0) discard;\\n             else outColor = vIndex;\" : '', \"\\n      }\\n    \");\n      var program = createProgram(gl, vertexShaderSource, fragmentShaderSource);\n\n      // instance geometry\n      program.aPosition = gl.getAttribLocation(program, 'aPosition');\n\n      // attributes\n      program.aIndex = gl.getAttribLocation(program, 'aIndex');\n      program.aVertType = gl.getAttribLocation(program, 'aVertType');\n      program.aTransform = gl.getAttribLocation(program, 'aTransform');\n      program.aAtlasId = gl.getAttribLocation(program, 'aAtlasId');\n      program.aTex = gl.getAttribLocation(program, 'aTex');\n      program.aPointAPointB = gl.getAttribLocation(program, 'aPointAPointB');\n      program.aPointCPointD = gl.getAttribLocation(program, 'aPointCPointD');\n      program.aLineWidth = gl.getAttribLocation(program, 'aLineWidth');\n      program.aColor = gl.getAttribLocation(program, 'aColor');\n\n      // uniforms\n      program.uPanZoomMatrix = gl.getUniformLocation(program, 'uPanZoomMatrix');\n      program.uAtlasSize = gl.getUniformLocation(program, 'uAtlasSize');\n      program.uBGColor = gl.getUniformLocation(program, 'uBGColor');\n      program.uTextures = [];\n      for (var i = 0; i < this.atlasManager.getMaxAtlasesPerBatch(); i++) {\n        program.uTextures.push(gl.getUniformLocation(program, \"uTexture\".concat(i)));\n      }\n      return program;\n    }\n  }, {\n    key: \"createVAO\",\n    value: function createVAO() {\n      var instanceGeometry = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1];\n      this.vertexCount = instanceGeometry.length / 2;\n      var n = this.maxInstances;\n      var gl = this.gl,\n        program = this.program;\n      var vao = gl.createVertexArray();\n      gl.bindVertexArray(vao);\n      createBufferStaticDraw(gl, 'vec2', program.aPosition, instanceGeometry);\n\n      // Create buffers for all the attributes\n      this.transformBuffer = create3x3MatrixBufferDynamicDraw(gl, n, program.aTransform);\n      this.indexBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aIndex);\n      this.vertTypeBuffer = createBufferDynamicDraw(gl, n, 'int', program.aVertType);\n      this.atlasIdBuffer = createBufferDynamicDraw(gl, n, 'int', program.aAtlasId);\n      this.texBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aTex);\n      this.pointAPointBBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointAPointB);\n      this.pointCPointDBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointCPointD);\n      this.lineWidthBuffer = createBufferDynamicDraw(gl, n, 'float', program.aLineWidth);\n      this.colorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aColor);\n      gl.bindVertexArray(null);\n      return vao;\n    }\n  }, {\n    key: \"buffers\",\n    get: function get() {\n      var _this = this;\n      if (!this._buffers) {\n        this._buffers = Object.keys(this).filter(function (k) {\n          return k.endsWith('Buffer');\n        }).map(function (k) {\n          return _this[k];\n        });\n      }\n      return this._buffers;\n    }\n  }, {\n    key: \"startFrame\",\n    value: function startFrame(panZoomMatrix) {\n      var renderTarget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : RENDER_TARGET.SCREEN;\n      this.panZoomMatrix = panZoomMatrix;\n      this.renderTarget = renderTarget;\n      this.batchDebugInfo = [];\n      this.wrappedCount = 0; // TODO this should be in the AtlasManager\n      this.rectangleCount = 0;\n      this.startBatch();\n    }\n  }, {\n    key: \"startBatch\",\n    value: function startBatch() {\n      this.instanceCount = 0;\n      this.atlasManager.startBatch();\n    }\n  }, {\n    key: \"endFrame\",\n    value: function endFrame() {\n      this.endBatch();\n    }\n  }, {\n    key: \"getTempMatrix\",\n    value: function getTempMatrix() {\n      return this.tempMatrix = this.tempMatrix || create();\n    }\n  }, {\n    key: \"drawTexture\",\n    value: function drawTexture(ele, eleIndex, type) {\n      var atlasManager = this.atlasManager;\n      if (!ele.visible()) {\n        return;\n      }\n      if (!atlasManager.getRenderTypeOpts(type).isVisible(ele)) {\n        return;\n      }\n      if (!atlasManager.canAddToCurrentBatch(ele, type)) {\n        this.endBatch(); // draws then starts a new batch\n      }\n      if (this.instanceCount + 1 >= this.maxInstances) {\n        this.endBatch(); // make sure there's space for at least two instances, wrapped textures need two instances\n      }\n      var instance = this.instanceCount;\n      this.vertTypeBuffer.getView(instance)[0] = TEXTURE;\n      var indexView = this.indexBuffer.getView(instance);\n      indexToVec4(eleIndex, indexView);\n      var atlasInfo = atlasManager.getAtlasInfo(ele, type);\n      var index = atlasInfo.index,\n        tex1 = atlasInfo.tex1,\n        tex2 = atlasInfo.tex2;\n      if (tex2.w > 0) this.wrappedCount++;\n      var first = true;\n      for (var _i = 0, _arr = [tex1, tex2]; _i < _arr.length; _i++) {\n        var tex = _arr[_i];\n        if (tex.w != 0) {\n          var _instance = this.instanceCount;\n          this.vertTypeBuffer.getView(_instance)[0] = TEXTURE;\n          var _indexView = this.indexBuffer.getView(_instance);\n          indexToVec4(eleIndex, _indexView);\n\n          // Set values in the buffers using Typed Array Views for performance.\n          var atlasIdView = this.atlasIdBuffer.getView(_instance);\n          atlasIdView[0] = index;\n\n          // we have two sets of texture coordinates and transforms because textures can wrap in the atlas\n          var texView = this.texBuffer.getView(_instance);\n          texView[0] = tex.x;\n          texView[1] = tex.y;\n          texView[2] = tex.w;\n          texView[3] = tex.h;\n          var matrixView = this.transformBuffer.getMatrixView(_instance);\n          atlasManager.setTransformMatrix(ele, matrixView, type, atlasInfo, first);\n          this.instanceCount++;\n        }\n        first = false;\n      }\n      if (this.instanceCount >= this.maxInstances) {\n        this.endBatch();\n      }\n    }\n  }, {\n    key: \"drawSimpleRectangle\",\n    value: function drawSimpleRectangle(ele, eleIndex, type) {\n      if (!ele.visible()) {\n        return;\n      }\n      var atlasManager = this.atlasManager;\n      var instance = this.instanceCount;\n      this.vertTypeBuffer.getView(instance)[0] = RECTANGLE;\n      var indexView = this.indexBuffer.getView(instance);\n      indexToVec4(eleIndex, indexView);\n      var color = ele.pstyle('background-color').value;\n      var opacity = ele.pstyle('background-opacity').value;\n      var colorView = this.colorBuffer.getView(instance);\n      toWebGLColor(color, opacity, colorView);\n      var matrixView = this.transformBuffer.getMatrixView(instance);\n      atlasManager.setTransformMatrix(ele, matrixView, type);\n      this.rectangleCount++;\n      this.instanceCount++;\n      if (this.instanceCount >= this.maxInstances) {\n        this.endBatch();\n      }\n    }\n  }, {\n    key: \"drawEdgeArrow\",\n    value: function drawEdgeArrow(edge, eleIndex, prefix) {\n      if (!edge.visible()) {\n        return;\n      }\n      // Edge points and arrow angles etc are calculated by the base renderer and cached in the rscratch object.\n      var rs = edge._private.rscratch;\n      var x, y, angle;\n      if (prefix === 'source') {\n        x = rs.arrowStartX;\n        y = rs.arrowStartY;\n        angle = rs.srcArrowAngle;\n      } else {\n        x = rs.arrowEndX;\n        y = rs.arrowEndY;\n        angle = rs.tgtArrowAngle;\n      }\n\n      // taken from CRp.drawArrowhead\n      if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {\n        return;\n      }\n\n      // check shape after the x/y check because pstyle() is a bit slow\n      var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;\n      if (arrowShape === 'none') {\n        return;\n      }\n      var color = edge.pstyle(prefix + '-arrow-color').value;\n      var baseOpacity = edge.pstyle('opacity').value;\n      var lineOpacity = edge.pstyle('line-opacity').value;\n      var opacity = baseOpacity * lineOpacity;\n      var lineWidth = edge.pstyle('width').pfValue;\n      var scale$1 = edge.pstyle('arrow-scale').value;\n      var size = this.r.getArrowWidth(lineWidth, scale$1);\n      var instance = this.instanceCount;\n      var transform = this.transformBuffer.getMatrixView(instance);\n      identity(transform);\n      translate(transform, transform, [x, y]);\n      scale(transform, transform, [size, size]);\n      rotate(transform, transform, angle);\n      this.vertTypeBuffer.getView(instance)[0] = EDGE_ARROW;\n      var indexView = this.indexBuffer.getView(instance);\n      indexToVec4(eleIndex, indexView);\n      var colorView = this.colorBuffer.getView(instance);\n      toWebGLColor(color, opacity, colorView);\n      this.instanceCount++;\n      if (this.instanceCount >= this.maxInstances) {\n        this.endBatch();\n      }\n    }\n  }, {\n    key: \"drawEdgeLine\",\n    value: function drawEdgeLine(edge, eleIndex) {\n      if (!edge.visible()) {\n        return;\n      }\n      var points = this.getEdgePoints(edge);\n      if (!points) {\n        return;\n      }\n\n      // line style\n      var baseOpacity = edge.pstyle('opacity').value;\n      var lineOpacity = edge.pstyle('line-opacity').value;\n      var width = edge.pstyle('width').pfValue;\n      var color = edge.pstyle('line-color').value;\n      var opacity = baseOpacity * lineOpacity;\n      if (points.length / 2 + this.instanceCount > this.maxInstances) {\n        this.endBatch();\n      }\n      if (points.length == 4) {\n        // straight line\n        var instance = this.instanceCount;\n        this.vertTypeBuffer.getView(instance)[0] = EDGE_STRAIGHT;\n        var indexView = this.indexBuffer.getView(instance);\n        indexToVec4(eleIndex, indexView);\n        var colorView = this.colorBuffer.getView(instance);\n        toWebGLColor(color, opacity, colorView);\n        var lineWidthBuffer = this.lineWidthBuffer.getView(instance);\n        lineWidthBuffer[0] = width;\n        var sourceTargetView = this.pointAPointBBuffer.getView(instance);\n        sourceTargetView[0] = points[0]; // source x\n        sourceTargetView[1] = points[1]; // source y\n        sourceTargetView[2] = points[2]; // target x\n        sourceTargetView[3] = points[3]; // target y\n\n        this.instanceCount++;\n        if (this.instanceCount >= this.maxInstances) {\n          this.endBatch();\n        }\n      } else {\n        // curved line\n        for (var i = 0; i < points.length - 2; i += 2) {\n          var _instance2 = this.instanceCount;\n          this.vertTypeBuffer.getView(_instance2)[0] = EDGE_CURVE_SEGMENT;\n          var _indexView2 = this.indexBuffer.getView(_instance2);\n          indexToVec4(eleIndex, _indexView2);\n          var _colorView = this.colorBuffer.getView(_instance2);\n          toWebGLColor(color, opacity, _colorView);\n          var _lineWidthBuffer = this.lineWidthBuffer.getView(_instance2);\n          _lineWidthBuffer[0] = width;\n          var pAx = points[i - 2],\n            pAy = points[i - 1];\n          var pBx = points[i],\n            pBy = points[i + 1];\n          var pCx = points[i + 2],\n            pCy = points[i + 3];\n          var pDx = points[i + 4],\n            pDy = points[i + 5];\n\n          // make phantom points for the first and last segments\n          // TODO adding 0.001 to avoid division by zero in the shader (I think), need a better solution\n          if (i == 0) {\n            pAx = 2 * pBx - pCx + 0.001;\n            pAy = 2 * pBy - pCy + 0.001;\n          }\n          if (i == points.length - 4) {\n            pDx = 2 * pCx - pBx + 0.001;\n            pDy = 2 * pCy - pBy + 0.001;\n          }\n          var pointABView = this.pointAPointBBuffer.getView(_instance2);\n          pointABView[0] = pAx;\n          pointABView[1] = pAy;\n          pointABView[2] = pBx;\n          pointABView[3] = pBy;\n          var pointCDView = this.pointCPointDBuffer.getView(_instance2);\n          pointCDView[0] = pCx;\n          pointCDView[1] = pCy;\n          pointCDView[2] = pDx;\n          pointCDView[3] = pDy;\n          this.instanceCount++;\n          if (this.instanceCount >= this.maxInstances) {\n            this.endBatch();\n          }\n        }\n      }\n    }\n  }, {\n    key: \"getEdgePoints\",\n    value: function getEdgePoints(edge) {\n      var rs = edge._private.rscratch;\n\n      // if bezier ctrl pts can not be calculated, then die\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      var controlPoints = rs.allpts;\n      if (controlPoints.length == 4) {\n        return controlPoints;\n      }\n      var numSegments = this.getNumSegments(edge);\n      return this.getCurveSegmentPoints(controlPoints, numSegments);\n    }\n  }, {\n    key: \"getNumSegments\",\n    value: function getNumSegments(edge) {\n      // TODO Need a heuristic that decides how many segments to use. Factors to consider:\n      // - edge width/length\n      // - edge curvature (the more the curvature, the more segments)\n      // - zoom level (more segments when zoomed in)\n      // - number of visible edges (more segments when there are fewer edges)\n      // - performance (fewer segments when performance is a concern)\n      // - user configurable option(s)\n      // note: number of segments should be less than the max number of instances\n      // note: segments don't need to be evenly spaced out, it might make sense to have shorter segments nearer to the control points\n      var numSegments = 15;\n      return Math.min(Math.max(numSegments, 5), this.maxInstances);\n    }\n  }, {\n    key: \"getCurveSegmentPoints\",\n    value: function getCurveSegmentPoints(controlPoints, segments) {\n      if (controlPoints.length == 4) {\n        return controlPoints; // straight line\n      }\n      var curvePoints = Array((segments + 1) * 2);\n      for (var i = 0; i <= segments; i++) {\n        // the first and last points are the same as the first and last control points\n        if (i == 0) {\n          curvePoints[0] = controlPoints[0];\n          curvePoints[1] = controlPoints[1];\n        } else if (i == segments) {\n          curvePoints[i * 2] = controlPoints[controlPoints.length - 2];\n          curvePoints[i * 2 + 1] = controlPoints[controlPoints.length - 1];\n        } else {\n          var t = i / segments; // segments have equal length, its not strictly necessary to do it this way\n          // pass in curvePoints to set the values in the array directly\n          this.setCurvePoint(controlPoints, t, curvePoints, i * 2);\n        }\n      }\n      return curvePoints;\n    }\n  }, {\n    key: \"setCurvePoint\",\n    value: function setCurvePoint(points, t, curvePoints, cpi) {\n      if (points.length <= 2) {\n        curvePoints[cpi] = points[0];\n        curvePoints[cpi + 1] = points[1];\n      } else {\n        var newpoints = Array(points.length - 2);\n        for (var i = 0; i < newpoints.length; i += 2) {\n          var x = (1 - t) * points[i] + t * points[i + 2];\n          var y = (1 - t) * points[i + 1] + t * points[i + 3];\n          newpoints[i] = x;\n          newpoints[i + 1] = y;\n        }\n        return this.setCurvePoint(newpoints, t, curvePoints, cpi);\n      }\n    }\n  }, {\n    key: \"endBatch\",\n    value: function endBatch() {\n      var gl = this.gl,\n        vao = this.vao,\n        vertexCount = this.vertexCount,\n        count = this.instanceCount;\n      if (count === 0) return;\n      var program = this.renderTarget.picking ? this.pickingProgram : this.program;\n      gl.useProgram(program);\n      gl.bindVertexArray(vao);\n\n      // buffer the attribute data\n      var _iterator = _createForOfIteratorHelper(this.buffers),\n        _step;\n      try {\n        for (_iterator.s(); !(_step = _iterator.n()).done;) {\n          var buffer = _step.value;\n          buffer.bufferSubData(count);\n        }\n      } catch (err) {\n        _iterator.e(err);\n      } finally {\n        _iterator.f();\n      }\n      var atlases = this.atlasManager.getAtlases();\n      // must buffer before activating texture units\n      for (var i = 0; i < atlases.length; i++) {\n        atlases[i].bufferIfNeeded(gl);\n      }\n      // Activate all the texture units that we need\n      for (var _i2 = 0; _i2 < atlases.length; _i2++) {\n        gl.activeTexture(gl.TEXTURE0 + _i2);\n        gl.bindTexture(gl.TEXTURE_2D, atlases[_i2].texture);\n        gl.uniform1i(program.uTextures[_i2], _i2);\n      }\n\n      // Set the uniforms\n      gl.uniformMatrix3fv(program.uPanZoomMatrix, false, this.panZoomMatrix);\n      gl.uniform1i(program.uAtlasSize, this.atlasManager.getAtlasSize());\n      // set background color, needed for edge arrow color blending\n      var webglBgColor = toWebGLColor(this.bgColor, 1);\n      gl.uniform4fv(program.uBGColor, webglBgColor);\n\n      // draw!\n      gl.drawArraysInstanced(gl.TRIANGLES, 0, vertexCount, count);\n      gl.bindVertexArray(null);\n      gl.bindTexture(gl.TEXTURE_2D, null); // TODO is this right when having multiple texture units?\n\n      if (this.debug) {\n        this.batchDebugInfo.push({\n          count: count,\n          // instance count\n          atlasCount: atlases.length\n        });\n      }\n\n      // start the next batch, even if not needed\n      this.startBatch();\n    }\n  }, {\n    key: \"getDebugInfo\",\n    value: function getDebugInfo() {\n      var atlasInfo = this.atlasManager.getDebugInfo();\n      var totalAtlases = atlasInfo.reduce(function (count, info) {\n        return count + info.atlasCount;\n      }, 0);\n      var batchInfo = this.batchDebugInfo;\n      var totalInstances = batchInfo.reduce(function (count, info) {\n        return count + info.count;\n      }, 0);\n      return {\n        atlasInfo: atlasInfo,\n        totalAtlases: totalAtlases,\n        wrappedCount: this.wrappedCount,\n        rectangleCount: this.rectangleCount,\n        batchCount: batchInfo.length,\n        batchInfo: batchInfo,\n        totalInstances: totalInstances\n      };\n    }\n  }]);\n}();\n\nfunction fillStyle(color, opacity) {\n  return \"rgba(\".concat(color[0], \", \").concat(color[1], \", \").concat(color[2], \", \").concat(opacity, \")\");\n}\nvar OverlayUnderlayRenderer = /*#__PURE__*/function () {\n  function OverlayUnderlayRenderer(r) {\n    _classCallCheck(this, OverlayUnderlayRenderer);\n    this.r = r;\n  }\n  return _createClass(OverlayUnderlayRenderer, [{\n    key: \"getStyleKey\",\n    value: function getStyleKey(type, node) {\n      var _this$getStyle = this.getStyle(type, node),\n        shape = _this$getStyle.shape,\n        opacity = _this$getStyle.opacity,\n        color = _this$getStyle.color;\n      if (!shape) return null;\n      var w = node.width();\n      var h = node.height();\n      var c = fillStyle(color, opacity);\n      return hashString(\"\".concat(shape, \"-\").concat(w, \"-\").concat(h, \"-\").concat(c)); // TODO hack, not very efficient\n    }\n  }, {\n    key: \"isVisible\",\n    value: function isVisible(type, node) {\n      var opacity = node.pstyle(\"\".concat(type, \"-opacity\")).value;\n      return opacity > 0;\n    }\n  }, {\n    key: \"getStyle\",\n    value: function getStyle(type, node) {\n      var opacity = node.pstyle(\"\".concat(type, \"-opacity\")).value;\n      var color = node.pstyle(\"\".concat(type, \"-color\")).value;\n      var shape = node.pstyle(\"\".concat(type, \"-shape\")).value;\n      return {\n        opacity: opacity,\n        color: color,\n        shape: shape\n      }; // TODO need to add radius at some point\n    }\n  }, {\n    key: \"getPadding\",\n    value: function getPadding(type, node) {\n      return node.pstyle(\"\".concat(type, \"-padding\")).pfValue;\n    }\n  }, {\n    key: \"draw\",\n    value: function draw(type, context, node, bb) {\n      if (!this.isVisible(type, node)) return;\n      var r = this.r;\n      var w = bb.w;\n      var h = bb.h;\n      var x = w / 2;\n      var y = h / 2;\n      var _this$getStyle2 = this.getStyle(type, node),\n        shape = _this$getStyle2.shape,\n        color = _this$getStyle2.color,\n        opacity = _this$getStyle2.opacity;\n      context.save();\n      context.fillStyle = fillStyle(color, opacity);\n      if (shape === 'round-rectangle' || shape === 'roundrectangle') {\n        r.drawRoundRectanglePath(context, x, y, w, h, 'auto');\n      } else if (shape === 'ellipse') {\n        r.drawEllipsePath(context, x, y, w, h);\n      }\n      context.fill();\n      context.restore();\n    }\n  }]);\n}();\n\nvar CRp$4 = {};\nCRp$4.initWebgl = function (opts, fns) {\n  var r = this;\n  var gl = r.data.contexts[r.WEBGL];\n  opts.bgColor = getBGColor(r);\n  opts.webglTexSize = Math.min(opts.webglTexSize, gl.getParameter(gl.MAX_TEXTURE_SIZE));\n  opts.webglTexRows = Math.min(opts.webglTexRows, 54);\n  opts.webglTexRowsNodes = Math.min(opts.webglTexRowsNodes, 54);\n  opts.webglBatchSize = Math.min(opts.webglBatchSize, 16384);\n  opts.webglTexPerBatch = Math.min(opts.webglTexPerBatch, gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS));\n  r.webglDebug = opts.webglDebug;\n  r.webglDebugShowAtlases = opts.webglDebugShowAtlases;\n\n  // for offscreen rendering when render target is PICKING\n  r.pickingFrameBuffer = createPickingFrameBuffer(gl);\n  r.pickingFrameBuffer.needsDraw = true;\n  var getLabelRotation = function getLabelRotation(prop) {\n    return function (ele) {\n      return r.getTextAngle(ele, prop);\n    };\n  };\n  var isLabelVisible = function isLabelVisible(prop) {\n    return function (ele) {\n      var label = ele.pstyle(prop);\n      return label && label.value;\n    };\n  };\n  r.drawing = new ElementDrawingWebGL(r, gl, opts);\n  var our = new OverlayUnderlayRenderer(r);\n  r.drawing.addAtlasCollection('node', atlasCollectionDefaults({\n    texRows: opts.webglTexRowsNodes\n  }));\n  r.drawing.addAtlasCollection('label', atlasCollectionDefaults({\n    texRows: opts.webglTexRows\n  }));\n  r.drawing.addAtlasRenderType('node-body', renderDefaults({\n    collection: 'node',\n    getKey: fns.getStyleKey,\n    getBoundingBox: fns.getElementBox,\n    drawElement: fns.drawElement\n  }));\n  r.drawing.addAtlasRenderType('label', renderDefaults({\n    // node label or edge mid label\n    collection: 'label',\n    getKey: fns.getLabelKey,\n    getBoundingBox: fns.getLabelBox,\n    drawElement: fns.drawLabel,\n    getRotation: getLabelRotation(null),\n    getRotationPoint: fns.getLabelRotationPoint,\n    getRotationOffset: fns.getLabelRotationOffset,\n    isVisible: isLabelVisible('label')\n  }));\n  r.drawing.addAtlasRenderType('node-overlay', renderDefaults({\n    collection: 'node',\n    getBoundingBox: fns.getElementBox,\n    getKey: function getKey(ele) {\n      return our.getStyleKey('overlay', ele);\n    },\n    drawElement: function drawElement(ctx, ele, bb) {\n      return our.draw('overlay', ctx, ele, bb);\n    },\n    isVisible: function isVisible(ele) {\n      return our.isVisible('overlay', ele);\n    },\n    getPadding: function getPadding(ele) {\n      return our.getPadding('overlay', ele);\n    }\n  }));\n  r.drawing.addAtlasRenderType('node-underlay', renderDefaults({\n    collection: 'node',\n    getBoundingBox: fns.getElementBox,\n    getKey: function getKey(ele) {\n      return our.getStyleKey('underlay', ele);\n    },\n    drawElement: function drawElement(ctx, ele, bb) {\n      return our.draw('underlay', ctx, ele, bb);\n    },\n    isVisible: function isVisible(ele) {\n      return our.isVisible('underlay', ele);\n    },\n    getPadding: function getPadding(ele) {\n      return our.getPadding('underlay', ele);\n    }\n  }));\n  r.drawing.addAtlasRenderType('edge-source-label', renderDefaults({\n    collection: 'label',\n    getKey: fns.getSourceLabelKey,\n    getBoundingBox: fns.getSourceLabelBox,\n    drawElement: fns.drawSourceLabel,\n    getRotation: getLabelRotation('source'),\n    getRotationPoint: fns.getSourceLabelRotationPoint,\n    getRotationOffset: fns.getSourceLabelRotationOffset,\n    isVisible: isLabelVisible('source-label')\n  }));\n  r.drawing.addAtlasRenderType('edge-target-label', renderDefaults({\n    collection: 'label',\n    getKey: fns.getTargetLabelKey,\n    getBoundingBox: fns.getTargetLabelBox,\n    drawElement: fns.drawTargetLabel,\n    getRotation: getLabelRotation('target'),\n    getRotationPoint: fns.getTargetLabelRotationPoint,\n    getRotationOffset: fns.getTargetLabelRotationOffset,\n    isVisible: isLabelVisible('target-label')\n  }));\n\n  // this is a very simplistic way of triggering garbage collection\n  var setGCFlag = debounce(function () {\n    console.log('garbage collect flag set');\n    r.data.gc = true;\n  }, 10000);\n  r.onUpdateEleCalcs(function (willDraw, eles) {\n    var gcNeeded = false;\n    if (eles && eles.length > 0) {\n      gcNeeded |= r.drawing.invalidate(eles);\n    }\n    if (gcNeeded) {\n      setGCFlag();\n    }\n  });\n\n  // \"Override\" certain functions in canvas and base renderer\n  overrideCanvasRendererFunctions(r);\n};\nfunction getBGColor(r) {\n  var container = r.cy.container();\n  var cssColor = container && container.style && container.style.backgroundColor || 'white';\n  return color2tuple(cssColor);\n}\n\n/**\n * Plug into the canvas renderer to use webgl for rendering.\n */\nfunction overrideCanvasRendererFunctions(r) {\n  {\n    // Override the render function to call the webgl render function if the zoom level is appropriate\n    var renderCanvas = r.render;\n    r.render = function (options) {\n      options = options || {};\n      var cy = r.cy;\n      if (r.webgl) {\n        // if the zoom level is greater than the max zoom level, then disable webgl\n        if (cy.zoom() > maxZoom$1) {\n          clearWebgl(r);\n          renderCanvas.call(r, options);\n        } else {\n          clearCanvas(r);\n          renderWebgl(r, options, RENDER_TARGET.SCREEN);\n        }\n      }\n    };\n  }\n  {\n    // Override the matchCanvasSize function to update the picking frame buffer size\n    var baseFunc = r.matchCanvasSize;\n    r.matchCanvasSize = function (container) {\n      baseFunc.call(r, container);\n      r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth, r.canvasHeight);\n      r.pickingFrameBuffer.needsDraw = true;\n    };\n  }\n  {\n    // Override function to call the webgl version\n    r.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {\n      // the canvas version of this function is very slow on large graphs\n      return findNearestElementsWebgl(r, x, y);\n    };\n  }\n\n  // Don't override the selction box picking, its not accurate enough with webgl\n  // { // Override function to call the webgl version\n  //   r.getAllInBox = function(x1, y1, x2, y2) {\n  //     return getAllInBoxWebgl(r, x1, y1, x2, y2);\n  //   }\n  // }\n\n  {\n    // need to know when the cached elements have changed so we can invalidate our caches\n    var _baseFunc = r.invalidateCachedZSortedEles;\n    r.invalidateCachedZSortedEles = function () {\n      _baseFunc.call(r);\n      r.pickingFrameBuffer.needsDraw = true;\n    };\n  }\n  {\n    // need to know when the cached elements have changed so we can invalidate our caches\n    var _baseFunc2 = r.notify;\n    r.notify = function (eventName, eles) {\n      _baseFunc2.call(r, eventName, eles);\n      if (eventName === 'viewport' || eventName === 'bounds') {\n        r.pickingFrameBuffer.needsDraw = true;\n      } else if (eventName === 'background') {\n        // background image finished loading, need to redraw\n        r.drawing.invalidate(eles, {\n          type: 'node-body'\n        });\n      }\n    };\n  }\n}\nfunction clearWebgl(r) {\n  var gl = r.data.contexts[r.WEBGL];\n  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\nfunction clearCanvas(r) {\n  // the CRp.clearCanvas() function doesn't take the transform into account\n  var clear = function clear(context) {\n    context.save();\n    context.setTransform(1, 0, 0, 1, 0, 0);\n    context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);\n    context.restore();\n  };\n  clear(r.data.contexts[r.NODE]);\n  clear(r.data.contexts[r.DRAG]);\n}\nfunction createPanZoomMatrix(r) {\n  var width = r.canvasWidth;\n  var height = r.canvasHeight;\n  var _util$getEffectivePan = getEffectivePanZoom(r),\n    pan = _util$getEffectivePan.pan,\n    zoom = _util$getEffectivePan.zoom;\n  var transform = create();\n  translate(transform, transform, [pan.x, pan.y]);\n  scale(transform, transform, [zoom, zoom]);\n  var projection$1 = create();\n  projection(projection$1, width, height);\n  var product = create();\n  multiply(product, projection$1, transform);\n  return product;\n}\nfunction setContextTransform(r, context) {\n  var width = r.canvasWidth;\n  var height = r.canvasHeight;\n  var _util$getEffectivePan2 = getEffectivePanZoom(r),\n    pan = _util$getEffectivePan2.pan,\n    zoom = _util$getEffectivePan2.zoom;\n  context.setTransform(1, 0, 0, 1, 0, 0);\n  context.clearRect(0, 0, width, height);\n  context.translate(pan.x, pan.y);\n  context.scale(zoom, zoom);\n}\nfunction drawSelectionRectangle(r, options) {\n  r.drawSelectionRectangle(options, function (context) {\n    return setContextTransform(r, context);\n  });\n}\n\n// eslint-disable-next-line no-unused-vars\nfunction drawAxes(r) {\n  // for debgging\n  var context = r.data.contexts[r.NODE];\n  context.save();\n  setContextTransform(r, context);\n  context.strokeStyle = 'rgba(0, 0, 0, 0.3)';\n  context.beginPath();\n  context.moveTo(-1e3, 0);\n  context.lineTo(1000, 0);\n  context.stroke();\n  context.beginPath();\n  context.moveTo(0, -1e3);\n  context.lineTo(0, 1000);\n  context.stroke();\n  context.restore();\n}\nfunction drawAtlases(r) {\n  // For debugging the atlases\n  var draw = function draw(drawing, name, row) {\n    var collection = drawing.atlasManager.getAtlasCollection(name);\n    var context = r.data.contexts[r.NODE];\n    var scale = 0.125;\n    var atlases = collection.atlases;\n    for (var _i = 0; _i < atlases.length; _i++) {\n      var atlas = atlases[_i];\n      var canvas = atlas.canvas;\n      if (canvas) {\n        var w = canvas.width;\n        var h = canvas.height;\n        var x = w * _i;\n        var y = canvas.height * row;\n        context.save();\n        context.scale(scale, scale);\n        context.drawImage(canvas, x, y);\n        context.strokeStyle = 'black';\n        context.rect(x, y, w, h);\n        context.stroke();\n        context.restore();\n      }\n    }\n  };\n  var i = 0;\n  draw(r.drawing, 'node', i++);\n  draw(r.drawing, 'label', i++);\n}\n\n/**\n * Arguments are in model coordinates.\n * (x1, y1) is top left corner\n * (x2, y2) is bottom right corner (optional)\n * Returns a Set of indexes.\n */\nfunction getPickingIndexes(r, mX1, mY1, mX2, mY2) {\n  var x, y, w, h;\n  var _util$getEffectivePan3 = getEffectivePanZoom(r),\n    pan = _util$getEffectivePan3.pan,\n    zoom = _util$getEffectivePan3.zoom;\n  {\n    var _util$modelToRendered = modelToRenderedPosition(r, pan, zoom, mX1, mY1),\n      _util$modelToRendered2 = _slicedToArray(_util$modelToRendered, 2),\n      cX1 = _util$modelToRendered2[0],\n      cY1 = _util$modelToRendered2[1];\n    var t = 6; // should be even\n    x = cX1 - t / 2;\n    y = cY1 - t / 2;\n    w = t;\n    h = t;\n  }\n  if (w === 0 || h === 0) {\n    return [];\n  }\n  var gl = r.data.contexts[r.WEBGL];\n  gl.bindFramebuffer(gl.FRAMEBUFFER, r.pickingFrameBuffer);\n  if (r.pickingFrameBuffer.needsDraw) {\n    // Draw element z-indexes to the picking framebuffer\n    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);\n    renderWebgl(r, null, RENDER_TARGET.PICKING);\n    r.pickingFrameBuffer.needsDraw = false;\n  }\n  var n = w * h; // number of pixels to read\n  // eslint-disable-next-line no-undef\n  var data = new Uint8Array(n * 4); // 4 bytes per pixel\n  gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, data);\n  gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n  var indexes = new Set();\n  for (var i = 0; i < n; i++) {\n    var pixel = data.slice(i * 4, i * 4 + 4);\n    var index = vec4ToIndex(pixel) - 1; // The framebuffer is cleared with 0s, so z-indexes are offset by 1\n    if (index >= 0) {\n      indexes.add(index);\n    }\n  }\n  return indexes;\n}\n\n/**\n * Cy.js: model coordinate y axis goes down\n */\nfunction findNearestElementsWebgl(r, x, y) {\n  // model coordinates\n  var indexes = getPickingIndexes(r, x, y);\n  var eles = r.getCachedZSortedEles();\n  var node, edge;\n  var _iterator = _createForOfIteratorHelper(indexes),\n    _step;\n  try {\n    for (_iterator.s(); !(_step = _iterator.n()).done;) {\n      var index = _step.value;\n      var ele = eles[index];\n      if (!node && ele.isNode()) {\n        node = ele;\n      }\n      if (!edge && ele.isEdge()) {\n        edge = ele;\n      }\n      if (node && edge) {\n        break;\n      }\n    }\n  } catch (err) {\n    _iterator.e(err);\n  } finally {\n    _iterator.f();\n  }\n  return [node, edge].filter(Boolean);\n}\n\n// TODO: Is constantly checking this slower than just rendering a texture?\n// Maybe this should be cached as a flag on each node.\nfunction isSimpleRectangle(node) {\n  return node.pstyle('shape').value === 'rectangle' && node.pstyle('background-fill').value === 'solid' && node.pstyle('border-width').pfValue === 0 && node.pstyle('background-image').strValue === 'none';\n}\nfunction drawEle(r, index, ele) {\n  var drawing = r.drawing;\n  index += 1; // 0 is used to clear the background, need to offset all z-indexes by one\n  if (ele.isNode()) {\n    drawing.drawTexture(ele, index, 'node-underlay');\n    if (isSimpleRectangle(ele)) {\n      drawing.drawSimpleRectangle(ele, index, 'node-body');\n    } else {\n      drawing.drawTexture(ele, index, 'node-body');\n    }\n    drawing.drawTexture(ele, index, 'label');\n    drawing.drawTexture(ele, index, 'node-overlay');\n  } else {\n    drawing.drawEdgeLine(ele, index);\n    drawing.drawEdgeArrow(ele, index, 'source');\n    drawing.drawEdgeArrow(ele, index, 'target');\n    drawing.drawTexture(ele, index, 'label');\n    drawing.drawTexture(ele, index, 'edge-source-label');\n    drawing.drawTexture(ele, index, 'edge-target-label');\n  }\n}\nfunction renderWebgl(r, options, renderTarget) {\n  var start;\n  if (r.webglDebug) {\n    start = performance.now(); // eslint-disable-line no-undef\n  }\n  var drawing = r.drawing;\n  var eleCount = 0;\n  if (renderTarget.screen) {\n    if (r.data.canvasNeedsRedraw[r.SELECT_BOX]) {\n      drawSelectionRectangle(r, options);\n    }\n  }\n\n  // see drawing-elements.js drawCachedElement()\n  if (r.data.canvasNeedsRedraw[r.NODE] || renderTarget.picking) {\n    var gl = r.data.contexts[r.WEBGL];\n    if (renderTarget.screen) {\n      gl.clearColor(0, 0, 0, 0); // background color\n      gl.enable(gl.BLEND); // enable alpha blending of textures\n      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // we are using premultiplied alpha\n    } else {\n      gl.disable(gl.BLEND);\n    }\n    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);\n    var panZoomMatrix = createPanZoomMatrix(r);\n    var eles = r.getCachedZSortedEles();\n    eleCount = eles.length;\n    drawing.startFrame(panZoomMatrix, renderTarget);\n    if (renderTarget.screen) {\n      for (var i = 0; i < eles.nondrag.length; i++) {\n        drawEle(r, i, eles.nondrag[i]);\n      }\n      for (var _i2 = 0; _i2 < eles.drag.length; _i2++) {\n        drawEle(r, _i2, eles.drag[_i2]);\n      }\n    } else if (renderTarget.picking) {\n      for (var _i3 = 0; _i3 < eles.length; _i3++) {\n        drawEle(r, _i3, eles[_i3]);\n      }\n    }\n    drawing.endFrame();\n    if (renderTarget.screen && r.webglDebugShowAtlases) {\n      drawAxes(r);\n      drawAtlases(r);\n    }\n    r.data.canvasNeedsRedraw[r.NODE] = false;\n    r.data.canvasNeedsRedraw[r.DRAG] = false;\n  }\n  if (r.webglDebug) {\n    // eslint-disable-next-line no-undef\n    var end = performance.now();\n    var compact = false;\n    var time = Math.ceil(end - start);\n    var debugInfo = drawing.getDebugInfo();\n    var report = [\"\".concat(eleCount, \" elements\"), \"\".concat(debugInfo.totalInstances, \" instances\"), \"\".concat(debugInfo.batchCount, \" batches\"), \"\".concat(debugInfo.totalAtlases, \" atlases\"), \"\".concat(debugInfo.wrappedCount, \" wrapped textures\"), \"\".concat(debugInfo.rectangleCount, \" simple rectangles\")].join(', ');\n    if (compact) {\n      console.log(\"WebGL (\".concat(renderTarget.name, \") - time \").concat(time, \"ms, \").concat(report));\n    } else {\n      console.log(\"WebGL (\".concat(renderTarget.name, \") - frame time \").concat(time, \"ms\"));\n      console.log('Totals:');\n      console.log(\"  \".concat(report));\n      console.log('Texture Atlases Used:');\n      var atlasInfo = debugInfo.atlasInfo;\n      var _iterator3 = _createForOfIteratorHelper(atlasInfo),\n        _step3;\n      try {\n        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n          var info = _step3.value;\n          console.log(\"  \".concat(info.type, \": \").concat(info.keyCount, \" keys, \").concat(info.atlasCount, \" atlases\"));\n        }\n      } catch (err) {\n        _iterator3.e(err);\n      } finally {\n        _iterator3.f();\n      }\n      console.log('');\n    }\n  }\n  if (r.data.gc) {\n    console.log('Garbage Collect!');\n    r.data.gc = false;\n    drawing.gc();\n  }\n}\n\nvar CRp$3 = {};\n\n// @O Polygon drawing\nCRp$3.drawPolygonPath = function (context, x, y, width, height, points) {\n  var halfW = width / 2;\n  var halfH = height / 2;\n  if (context.beginPath) {\n    context.beginPath();\n  }\n  context.moveTo(x + halfW * points[0], y + halfH * points[1]);\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  context.closePath();\n};\nCRp$3.drawRoundPolygonPath = function (context, x, y, width, height, points, corners) {\n  corners.forEach(function (corner) {\n    return drawPreparedRoundCorner(context, corner);\n  });\n  context.closePath();\n};\n\n// Round rectangle drawing\nCRp$3.drawRoundRectanglePath = function (context, x, y, width, height, radius) {\n  var halfWidth = width / 2;\n  var halfHeight = height / 2;\n  var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : Math.min(radius, halfHeight, halfWidth);\n  if (context.beginPath) {\n    context.beginPath();\n  }\n\n  // Start at top middle\n  context.moveTo(x, y - halfHeight);\n  // Arc from middle top to right side\n  context.arcTo(x + halfWidth, y - halfHeight, x + halfWidth, y, cornerRadius);\n  // Arc from right side to bottom\n  context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);\n  // Arc from bottom to left side\n  context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);\n  // Arc from left side to topBorder\n  context.arcTo(x - halfWidth, y - halfHeight, x, y - halfHeight, cornerRadius);\n  // Join line\n  context.lineTo(x, y - halfHeight);\n  context.closePath();\n};\nCRp$3.drawBottomRoundRectanglePath = function (context, x, y, width, height, radius) {\n  var halfWidth = width / 2;\n  var halfHeight = height / 2;\n  var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;\n  if (context.beginPath) {\n    context.beginPath();\n  }\n\n  // Start at top middle\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};\nCRp$3.drawCutRectanglePath = function (context, x, y, width, height, points, corners) {\n  var halfWidth = width / 2;\n  var halfHeight = height / 2;\n  var cornerLength = corners === 'auto' ? getCutRectangleCornerLength() : corners;\n  if (context.beginPath) {\n    context.beginPath();\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};\nCRp$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  if (context.beginPath) {\n    context.beginPath();\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};\nvar sin0 = Math.sin(0);\nvar cos0 = Math.cos(0);\nvar sin = {};\nvar cos = {};\nvar ellipseStepSize = Math.PI / 40;\nfor (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {\n  sin[i] = Math.sin(i);\n  cos[i] = Math.cos(i);\n}\nCRp$3.drawEllipsePath = function (context, centerX, centerY, width, height) {\n  if (context.beginPath) {\n    context.beginPath();\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    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      if (i === 0) {\n        context.moveTo(xPos, yPos);\n      } else {\n        context.lineTo(xPos, yPos);\n      }\n    }\n  }\n  context.closePath();\n};\n\n/* global atob, ArrayBuffer, Uint8Array, Blob */\n\nvar CRp$2 = {};\nCRp$2.createBuffer = function (w, h) {\n  var buffer = document.createElement('canvas'); // eslint-disable-line no-undef\n  buffer.width = w;\n  buffer.height = h;\n  return [buffer, buffer.getContext('2d')];\n};\nCRp$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  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    if (number$1(options.maxWidth)) {\n      maxScaleW = scale * options.maxWidth / width;\n    }\n    if (number$1(options.maxHeight)) {\n      maxScaleH = scale * options.maxHeight / height;\n    }\n    scale = Math.min(maxScaleW, maxScaleH);\n    width *= scale;\n    height *= scale;\n  }\n  if (!specdMaxDims) {\n    width *= pxRatio;\n    height *= pxRatio;\n    scale *= pxRatio;\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');\n\n  // Rasterize the layers, but only if container has nonzero size\n  if (width > 0 && height > 0) {\n    buffCxt.clearRect(0, 0, width, height);\n    buffCxt.globalCompositeOperation = 'source-over';\n    var zsortedEles = this.getCachedZSortedEles();\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    }\n\n    // need to fill bg at end like this in order to fill cleared transparent pixels in jpgs\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  return buffCanvas;\n};\nfunction b64ToBlob(b64, mimeType) {\n  var bytes = atob(b64);\n  var buff = new ArrayBuffer(bytes.length);\n  var buffUint8 = new Uint8Array(buff);\n  for (var i = 0; i < bytes.length; i++) {\n    buffUint8[i] = bytes.charCodeAt(i);\n  }\n  return new Blob([buff], {\n    type: mimeType\n  });\n}\nfunction b64UriToB64(b64uri) {\n  var i = b64uri.indexOf(',');\n  return b64uri.substr(i + 1);\n}\nfunction output(options, canvas, mimeType) {\n  var getB64Uri = function getB64Uri() {\n    return canvas.toDataURL(mimeType, options.quality);\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    case 'blob':\n      return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);\n    case 'base64':\n      return b64UriToB64(getB64Uri());\n    case 'base64uri':\n    default:\n      return getB64Uri();\n  }\n}\nCRp$2.png = function (options) {\n  return output(options, this.bufferCanvasImage(options), 'image/png');\n};\nCRp$2.jpg = function (options) {\n  return output(options, this.bufferCanvasImage(options), 'image/jpeg');\n};\n\nvar CRp$1 = {};\nCRp$1.nodeShapeImpl = function (name, context, centerX, centerY, width, height, points, corners) {\n  switch (name) {\n    case 'ellipse':\n      return this.drawEllipsePath(context, centerX, centerY, width, height);\n    case 'polygon':\n      return this.drawPolygonPath(context, centerX, centerY, width, height, points);\n    case 'round-polygon':\n      return this.drawRoundPolygonPath(context, centerX, centerY, width, height, points, corners);\n    case 'roundrectangle':\n    case 'round-rectangle':\n      return this.drawRoundRectanglePath(context, centerX, centerY, width, height, corners);\n    case 'cutrectangle':\n    case 'cut-rectangle':\n      return this.drawCutRectanglePath(context, centerX, centerY, width, height, points, corners);\n    case 'bottomroundrectangle':\n    case 'bottom-round-rectangle':\n      return this.drawBottomRoundRectanglePath(context, centerX, centerY, width, height, corners);\n    case 'barrel':\n      return this.drawBarrelPath(context, centerX, centerY, width, height);\n  }\n};\n\nvar CR = CanvasRenderer;\nvar CRp = CanvasRenderer.prototype;\nCRp.CANVAS_LAYERS = 3;\n//\nCRp.SELECT_BOX = 0;\nCRp.DRAG = 1;\nCRp.NODE = 2;\nCRp.WEBGL = 3;\nCRp.CANVAS_TYPES = ['2d', '2d', '2d', 'webgl2'];\nCRp.BUFFER_COUNT = 3;\n//\nCRp.TEXTURE_BUFFER = 0;\nCRp.MOTIONBLUR_BUFFER_NODE = 1;\nCRp.MOTIONBLUR_BUFFER_DRAG = 2;\nfunction CanvasRenderer(options) {\n  var r = this;\n  var containerWindow = r.cy.window();\n  var document = containerWindow.document;\n  if (options.webgl) {\n    CRp.CANVAS_LAYERS = r.CANVAS_LAYERS = 4;\n    console.log('webgl rendering enabled');\n  }\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  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  if (ms()) {\n    styleMap['-ms-touch-action'] = 'none';\n    styleMap['touch-action'] = 'none';\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    var type = CRp.CANVAS_TYPES[i];\n    r.data.contexts[i] = canvas.getContext(type);\n    if (!r.data.contexts[i]) {\n      error('Could not create canvas of type ' + type);\n    }\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  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  if (r.data.canvases[CRp.WEBGL]) {\n    r.data.canvases[CRp.WEBGL].setAttribute('data-id', 'layer' + CRp.WEBGL + '-webgl');\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    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';\n    //r.data.canvasContainer.appendChild(r.data.bufferCanvases[i]);\n  }\n  r.pathsEnabled = true;\n  var emptyBb = makeBoundingBox();\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  var getCenterOffset = function getCenterOffset(bb) {\n    return {\n      x: -bb.w / 2,\n      y: -bb.h / 2\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  var getStyleKey = function getStyleKey(ele) {\n    return ele[0]._private.nodeKey;\n  };\n  var getLabelKey = function getLabelKey(ele) {\n    return ele[0]._private.labelStyleKey;\n  };\n  var getSourceLabelKey = function getSourceLabelKey(ele) {\n    return ele[0]._private.sourceLabelStyleKey;\n  };\n  var getTargetLabelKey = function getTargetLabelKey(ele) {\n    return ele[0]._private.targetLabelStyleKey;\n  };\n  var drawElement = function drawElement(context, ele, bb, scaledLabelShown, useEleOpacity) {\n    return r.drawElement(context, ele, bb, false, false, useEleOpacity);\n  };\n  var drawLabel = function drawLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {\n    return r.drawElementText(context, ele, bb, scaledLabelShown, 'main', useEleOpacity);\n  };\n  var drawSourceLabel = function drawSourceLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {\n    return r.drawElementText(context, ele, bb, scaledLabelShown, 'source', useEleOpacity);\n  };\n  var drawTargetLabel = function drawTargetLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {\n    return r.drawElementText(context, ele, bb, scaledLabelShown, 'target', useEleOpacity);\n  };\n  var getElementBox = function getElementBox(ele) {\n    ele.boundingBox();\n    return ele[0]._private.bodyBounds;\n  };\n  var getLabelBox = function getLabelBox(ele) {\n    ele.boundingBox();\n    return ele[0]._private.labelBounds.main || emptyBb;\n  };\n  var getSourceLabelBox = function getSourceLabelBox(ele) {\n    ele.boundingBox();\n    return ele[0]._private.labelBounds.source || emptyBb;\n  };\n  var getTargetLabelBox = function getTargetLabelBox(ele) {\n    ele.boundingBox();\n    return ele[0]._private.labelBounds.target || emptyBb;\n  };\n  var isLabelVisibleAtScale = function isLabelVisibleAtScale(ele, scaledLabelShown) {\n    return scaledLabelShown;\n  };\n  var getElementRotationPoint = function getElementRotationPoint(ele) {\n    return getBoxCenter(getElementBox(ele));\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  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  var getLabelRotationPoint = function getLabelRotationPoint(ele) {\n    return addTextMargin('', getRsPt(ele, 'labelX', 'labelY'), ele);\n  };\n  var getSourceLabelRotationPoint = function getSourceLabelRotationPoint(ele) {\n    return addTextMargin('source', getRsPt(ele, 'sourceLabelX', 'sourceLabelY'), ele);\n  };\n  var getTargetLabelRotationPoint = function getTargetLabelRotationPoint(ele) {\n    return addTextMargin('target', getRsPt(ele, 'targetLabelX', 'targetLabelY'), ele);\n  };\n  var getElementRotationOffset = function getElementRotationOffset(ele) {\n    return getCenterOffset(getElementBox(ele));\n  };\n  var getSourceLabelRotationOffset = function getSourceLabelRotationOffset(ele) {\n    return getCenterOffset(getSourceLabelBox(ele));\n  };\n  var getTargetLabelRotationOffset = function getTargetLabelRotationOffset(ele) {\n    return getCenterOffset(getTargetLabelBox(ele));\n  };\n  var getLabelRotationOffset = function getLabelRotationOffset(ele) {\n    var bb = getLabelBox(ele);\n    var p = getCenterOffset(getLabelBox(ele));\n    if (ele.isNode()) {\n      switch (ele.pstyle('text-halign').value) {\n        case 'left':\n          p.x = -bb.w - (bb.leftPad || 0);\n          break;\n        case 'right':\n          p.x = -(bb.rightPad || 0);\n          break;\n      }\n      switch (ele.pstyle('text-valign').value) {\n        case 'top':\n          p.y = -bb.h - (bb.topPad || 0);\n          break;\n        case 'bottom':\n          p.y = -(bb.botPad || 0);\n          break;\n      }\n    }\n    return p;\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);\n\n    // any change invalidates the layers\n    lyrTxrCache.invalidateElements(eles);\n\n    // update the old bg timestamp so diffs can be done in the ele txr caches\n    for (var _i = 0; _i < eles.length; _i++) {\n      var _p = eles[_i]._private;\n      _p.oldBackgroundTimestamp = _p.backgroundTimestamp;\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  eleTxrCache.onDequeue(refineInLayers);\n  lblTxrCache.onDequeue(refineInLayers);\n  slbTxrCache.onDequeue(refineInLayers);\n  tlbTxrCache.onDequeue(refineInLayers);\n  if (options.webgl) {\n    r.initWebgl(options, {\n      getStyleKey: getStyleKey,\n      getLabelKey: getLabelKey,\n      getSourceLabelKey: getSourceLabelKey,\n      getTargetLabelKey: getTargetLabelKey,\n      drawElement: drawElement,\n      drawLabel: drawLabel,\n      drawSourceLabel: drawSourceLabel,\n      drawTargetLabel: drawTargetLabel,\n      getElementBox: getElementBox,\n      getLabelBox: getLabelBox,\n      getSourceLabelBox: getSourceLabelBox,\n      getTargetLabelBox: getTargetLabelBox,\n      getElementRotationPoint: getElementRotationPoint,\n      getElementRotationOffset: getElementRotationOffset,\n      getLabelRotationPoint: getLabelRotationPoint,\n      getSourceLabelRotationPoint: getSourceLabelRotationPoint,\n      getTargetLabelRotationPoint: getTargetLabelRotationPoint,\n      getLabelRotationOffset: getLabelRotationOffset,\n      getSourceLabelRotationOffset: getSourceLabelRotationOffset,\n      getTargetLabelRotationOffset: getTargetLabelRotationOffset\n    });\n  }\n}\nCRp.redrawHint = function (group, bool) {\n  var r = this;\n  switch (group) {\n    case 'eles':\n      r.data.canvasNeedsRedraw[CRp.NODE] = bool;\n      break;\n    case 'drag':\n      r.data.canvasNeedsRedraw[CRp.DRAG] = bool;\n      break;\n    case 'select':\n      r.data.canvasNeedsRedraw[CRp.SELECT_BOX] = bool;\n      break;\n    case 'gc':\n      r.data.gc = true;\n      break;\n  }\n};\n\n// whether to use Path2D caching for drawing\nvar pathsImpld = typeof Path2D !== 'undefined';\nCRp.path2dEnabled = function (on) {\n  if (on === undefined) {\n    return this.pathsEnabled;\n  }\n  this.pathsEnabled = on ? true : false;\n};\nCRp.usePaths = function () {\n  return pathsImpld && this.pathsEnabled;\n};\nCRp.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};\nCRp.getImgSmoothing = function (context) {\n  if (context.imageSmoothingEnabled != null) {\n    return context.imageSmoothingEnabled;\n  } else {\n    return context.webkitImageSmoothingEnabled || context.mozImageSmoothingEnabled || context.msImageSmoothingEnabled;\n  }\n};\nCRp.makeOffscreenCanvas = function (width, height) {\n  var canvas;\n  if ((typeof OffscreenCanvas === \"undefined\" ? \"undefined\" : _typeof(OffscreenCanvas)) !== (\"undefined\" )) {\n    canvas = new OffscreenCanvas(width, height);\n  } else {\n    var containerWindow = this.cy.window();\n    var document = containerWindow.document;\n    canvas = document.createElement('canvas'); // eslint-disable-line no-undef\n    canvas.width = width;\n    canvas.height = height;\n  }\n  return canvas;\n};\n[CRp$b, 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\nvar renderer = [{\n  name: 'null',\n  impl: NullRenderer\n}, {\n  name: 'base',\n  impl: BR\n}, {\n  name: 'canvas',\n  impl: CR\n}];\n\nvar incExts = [{\n  type: 'layout',\n  extensions: layout\n}, {\n  type: 'renderer',\n  extensions: renderer\n}];\n\n// registered extensions to cytoscape, indexed by name\nvar extensions = {};\n\n// registered modules for extensions, indexed by name\nvar modules = {};\nfunction setExtension(type, name, registrant) {\n  var ext = registrant;\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  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\n    var Layout = function Layout(options) {\n      this.options = options;\n      registrant.call(this, options);\n\n      // make sure layout has _private for use w/ std apis like .on()\n      if (!plainObject(this._private)) {\n        this._private = {};\n      }\n      this._private.cy = options.cy;\n      this._private.listeners = [];\n      this.createEmitter();\n    };\n    var layoutProto = Layout.prototype = Object.create(registrant.prototype);\n    var optLayoutFns = [];\n    for (var i = 0; i < optLayoutFns.length; i++) {\n      var fnName = optLayoutFns[i];\n      layoutProto[fnName] = layoutProto[fnName] || function () {\n        return this;\n      };\n    }\n\n    // either .start() or .run() is defined, so autogen the other\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    var regStop = registrant.prototype.stop;\n    layoutProto.stop = function () {\n      var opts = this.options;\n      if (opts && opts.animate) {\n        var anis = this.animations;\n        if (anis) {\n          for (var _i = 0; _i < anis.length; _i++) {\n            anis[_i].stop();\n          }\n        }\n      }\n      if (regStop) {\n        regStop.call(this);\n      } else {\n        this.emit('layoutstop');\n      }\n      return this;\n    };\n    if (!layoutProto.destroy) {\n      layoutProto.destroy = function () {\n        return this;\n      };\n    }\n    layoutProto.cy = function () {\n      return this._private.cy;\n    };\n    var getCy = function getCy(layout) {\n      return layout._private.cy;\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\n    var BaseRenderer = getExtension('renderer', 'base');\n    var bProto = BaseRenderer.prototype;\n    var RegistrantRenderer = registrant;\n    var rProto = registrant.prototype;\n    var Renderer = function Renderer() {\n      BaseRenderer.apply(this, arguments);\n      RegistrantRenderer.apply(this, arguments);\n    };\n    var proto = Renderer.prototype;\n    for (var pName in bProto) {\n      var pVal = bProto[pName];\n      var existsInR = rProto[pName] != null;\n      if (existsInR) {\n        return overrideErr(pName);\n      }\n      proto[pName] = pVal; // take impl from base\n    }\n    for (var _pName in rProto) {\n      proto[_pName] = rProto[_pName]; // take impl from registrant\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  return setMap({\n    map: extensions,\n    keys: [type, name],\n    value: ext\n  });\n}\nfunction getExtension(type, name) {\n  return getMap({\n    map: extensions,\n    keys: [type, name]\n  });\n}\nfunction setModule(type, name, moduleType, moduleName, registrant) {\n  return setMap({\n    map: modules,\n    keys: [type, name, moduleType, moduleName],\n    value: registrant\n  });\n}\nfunction getModule(type, name, moduleType, moduleName) {\n  return getMap({\n    map: modules,\n    keys: [type, name, moduleType, moduleName]\n  });\n}\nvar extension = function extension() {\n  // e.g. extension('renderer', 'svg')\n  if (arguments.length === 2) {\n    return getExtension.apply(null, arguments);\n  }\n\n  // e.g. extension('renderer', 'svg', { ... })\n  else if (arguments.length === 3) {\n    return setExtension.apply(null, arguments);\n  }\n\n  // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse')\n  else if (arguments.length === 4) {\n    return getModule.apply(null, arguments);\n  }\n\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};\n\n// allows a core instance to access extensions internally\nCore.prototype.extension = extension;\n\n// included extensions\nincExts.forEach(function (group) {\n  group.extensions.forEach(function (ext) {\n    setExtension(group.type, ext.name, ext.impl);\n  });\n});\n\n// a dummy stylesheet object that doesn't need a reference to the core\n// (useful for init)\nvar _Stylesheet = function Stylesheet() {\n  if (!(this instanceof _Stylesheet)) {\n    return new _Stylesheet();\n  }\n  this.length = 0;\n};\nvar sheetfn = _Stylesheet.prototype;\nsheetfn.instanceString = function () {\n  return 'stylesheet';\n};\n\n// just store the selector to be parsed later\nsheetfn.selector = function (selector) {\n  var i = this.length++;\n  this[i] = {\n    selector: selector,\n    properties: []\n  };\n  return this; // chaining\n};\n\n// just store the property to be parsed later\nsheetfn.css = function (name, value) {\n  var i = this.length - 1;\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    for (var j = 0; j < propNames.length; j++) {\n      var key = propNames[j];\n      var mapVal = map[key];\n      if (mapVal == null) {\n        continue;\n      }\n      var prop = _Style.properties[key] || _Style.properties[dash2camel(key)];\n      if (prop == null) {\n        continue;\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  return this; // chaining\n};\nsheetfn.style = sheetfn.css;\n\n// generate a real style object from the dummy stylesheet\nsheetfn.generateStyle = function (cy) {\n  var style = new _Style(cy);\n  return this.appendToStyle(style);\n};\n\n// append a dummy stylesheet object on a real style object\nsheetfn.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  return style;\n};\n\nvar version = \"3.31.1\";\n\nvar cytoscape = function cytoscape(options) {\n  // if no options specified, use default\n  if (options === undefined) {\n    options = {};\n  }\n\n  // create instance\n  if (plainObject(options)) {\n    return new Core(options);\n  }\n\n  // allow for registration of extensions\n  else if (string(options)) {\n    return extension.apply(extension, arguments);\n  }\n};\n\n// e.g. cytoscape.use( require('cytoscape-foo'), bar )\ncytoscape.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};\ncytoscape.warnings = function (bool) {\n  return warnings(bool);\n};\n\n// replaced by build system\ncytoscape.version = version;\n\n// expose public apis (mostly for extensions)\ncytoscape.stylesheet = cytoscape.Stylesheet = _Stylesheet;\n\n\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/cytoscape/dist/cytoscape.esm.mjs?");

/***/ })

}]);