forcegraph.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. define(["d3"], function (d3) {
  2. var margin = 200
  3. var NODE_RADIUS = 15
  4. var LINE_RADIUS = 12
  5. return function (config, linkScale, sidebar, router) {
  6. var self = this
  7. var canvas, ctx, screenRect
  8. var nodesDict, linksDict
  9. var zoomBehavior
  10. var force
  11. var el
  12. var doAnimation = false
  13. var intNodes = []
  14. var intLinks = []
  15. var highlight
  16. var highlightedNodes = []
  17. var highlightedLinks = []
  18. var nodes = []
  19. var unknownNodes = []
  20. var draggedNode
  21. var LINK_DISTANCE = 70
  22. function graphDiameter(nodes) {
  23. return Math.sqrt(nodes.length / Math.PI) * LINK_DISTANCE * 1.41
  24. }
  25. function savePositions() {
  26. if (!localStorageTest())
  27. return
  28. var save = intNodes.map( function (d) {
  29. return { id: d.o.id, x: d.x, y: d.y }
  30. })
  31. localStorage.setItem("graph/nodeposition", JSON.stringify(save))
  32. }
  33. function nodeName(d) {
  34. if (d.o.node && d.o.node.nodeinfo)
  35. return d.o.node.nodeinfo.hostname
  36. else
  37. return d.o.id
  38. }
  39. function dragstart() {
  40. var e = translateXY(d3.mouse(el))
  41. var nodes = intNodes.filter(function (d) {
  42. return distancePoint(e, d) < NODE_RADIUS
  43. })
  44. if (nodes.length === 0)
  45. return
  46. draggedNode = nodes[0]
  47. d3.event.sourceEvent.stopPropagation()
  48. d3.event.sourceEvent.preventDefault()
  49. draggedNode.fixed |= 2
  50. }
  51. function dragmove() {
  52. if (draggedNode) {
  53. var e = translateXY(d3.mouse(el))
  54. draggedNode.px = e.x
  55. draggedNode.py = e.y
  56. force.resume()
  57. }
  58. }
  59. function dragend() {
  60. if (draggedNode) {
  61. d3.event.sourceEvent.stopPropagation()
  62. d3.event.sourceEvent.preventDefault()
  63. draggedNode.fixed &= 1
  64. draggedNode = undefined
  65. }
  66. }
  67. var draggableNode = d3.behavior.drag()
  68. .on("dragstart", dragstart)
  69. .on("drag", dragmove)
  70. .on("dragend", dragend)
  71. function animatePanzoom(translate, scale) {
  72. var translateP = zoomBehavior.translate()
  73. var scaleP = zoomBehavior.scale()
  74. if (!doAnimation) {
  75. zoomBehavior.translate(translate)
  76. zoomBehavior.scale(scale)
  77. panzoom()
  78. } else {
  79. var start = {x: translateP[0], y: translateP[1], scale: scaleP}
  80. var end = {x: translate[0], y: translate[1], scale: scale}
  81. var interpolate = d3.interpolateObject(start, end)
  82. var duration = 500
  83. var ease = d3.ease("cubic-in-out")
  84. d3.timer(function (t) {
  85. if (t >= duration)
  86. return true
  87. var v = interpolate(ease(t / duration))
  88. zoomBehavior.translate([v.x, v.y])
  89. zoomBehavior.scale(v.scale)
  90. panzoom()
  91. return false
  92. })
  93. }
  94. }
  95. var translateP, scaleP
  96. function panzoom() {
  97. var translate = zoomBehavior.translate()
  98. var scale = zoomBehavior.scale()
  99. panzoomReal(translate, scale)
  100. translateP = translate
  101. scaleP = scale
  102. }
  103. function panzoomReal(translate, scale) {
  104. screenRect = {left: -translate[0] / scale, top: -translate[1] / scale,
  105. right: (canvas.width - translate[0]) / scale,
  106. bottom: (canvas.height - translate[1]) / scale}
  107. redraw()
  108. }
  109. function getSize() {
  110. var sidebarWidth = sidebar.getWidth()
  111. var width = el.offsetWidth - sidebarWidth
  112. var height = el.offsetHeight
  113. return [width, height]
  114. }
  115. function panzoomTo(a, b) {
  116. var sidebarWidth = sidebar.getWidth()
  117. var size = getSize()
  118. var targetWidth = Math.max(1, b[0] - a[0])
  119. var targetHeight = Math.max(1, b[1] - a[1])
  120. var scaleX = size[0] / targetWidth
  121. var scaleY = size[1] / targetHeight
  122. var scaleMax = zoomBehavior.scaleExtent()[1]
  123. var scale = 0.5 * Math.min(scaleMax, Math.min(scaleX, scaleY))
  124. var centroid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]
  125. var x = -centroid[0] * scale + size[0] / 2
  126. var y = -centroid[1] * scale + size[1] / 2
  127. var translate = [x + sidebarWidth, y]
  128. animatePanzoom(translate, scale)
  129. }
  130. function updateHighlight(nopanzoom) {
  131. highlightedNodes = []
  132. highlightedLinks = []
  133. if (highlight !== undefined)
  134. if (highlight.type === "node") {
  135. var n = nodesDict[highlight.o.nodeinfo.node_id]
  136. if (n) {
  137. highlightedNodes = [n]
  138. if (!nopanzoom)
  139. panzoomTo([n.x, n.y], [n.x, n.y])
  140. }
  141. return
  142. } else if (highlight.type === "link") {
  143. var l = linksDict[highlight.o.id]
  144. if (l) {
  145. highlightedLinks = [l]
  146. highlightedNodes = [l.source, l.target]
  147. if (!nopanzoom) {
  148. var x = d3.extent([l.source, l.target], function (d) { return d.x })
  149. var y = d3.extent([l.source, l.target], function (d) { return d.y })
  150. panzoomTo([x[0], y[0]], [x[1], y[1]])
  151. }
  152. }
  153. return
  154. }
  155. if (!nopanzoom)
  156. panzoomTo([0, 0], force.size())
  157. }
  158. function drawLabel(d) {
  159. var sum = d.neighbours.reduce(function (a, b) {
  160. return [a[0] + b.x, a[1] + b.y]
  161. }, [0, 0])
  162. var sumCos = sum[0] - d.x * d.neighbours.length
  163. var sumSin = sum[1] - d.y * d.neighbours.length
  164. var angle = Math.PI / 2
  165. if (d.neighbours.length > 0)
  166. angle = Math.PI + Math.atan2(sumSin, sumCos)
  167. var cos = Math.cos(angle)
  168. var sin = Math.sin(angle)
  169. var width = d.labelWidth
  170. var height = d.labelHeight
  171. var x = d.x + d.labelA * Math.pow(Math.abs(cos), 2 / 5) * Math.sign(cos) - width / 2
  172. var y = d.y + d.labelB * Math.pow(Math.abs(sin), 2 / 5) * Math.sign(sin) - height / 2
  173. ctx.drawImage(d.label, x, y, width, height)
  174. }
  175. function visibleLinks(d) {
  176. return (d.source.x > screenRect.left && d.source.x < screenRect.right &&
  177. d.source.y > screenRect.top && d.source.y < screenRect.bottom) ||
  178. (d.target.x > screenRect.left && d.target.x < screenRect.right &&
  179. d.target.y > screenRect.top && d.target.y < screenRect.bottom)
  180. }
  181. function visibleNodes(d) {
  182. return d.x + margin > screenRect.left && d.x - margin < screenRect.right &&
  183. d.y + margin > screenRect.top && d.y - margin < screenRect.bottom
  184. }
  185. function redraw() {
  186. var translate = zoomBehavior.translate()
  187. var scale = zoomBehavior.scale()
  188. var links = intLinks.filter(visibleLinks)
  189. var xExtent = d3.extent(intNodes, function (d) { return d.px })
  190. var yExtent = d3.extent(intNodes, function (d) { return d.py })
  191. if (translateP) {
  192. ctx.save()
  193. ctx.translate(translateP[0], translateP[1])
  194. ctx.scale(scaleP, scaleP)
  195. ctx.clearRect(xExtent[0] - margin, yExtent[0] - margin,
  196. xExtent[1] - xExtent[0] + 2 * margin,
  197. yExtent[1] - yExtent[0] + 2 * margin)
  198. ctx.restore()
  199. }
  200. ctx.save()
  201. ctx.translate(translate[0], translate[1])
  202. ctx.scale(scale, scale)
  203. if (!translateP)
  204. ctx.clearRect(xExtent[0] - margin, yExtent[0] - margin,
  205. xExtent[1] - xExtent[0] + 2 * margin,
  206. yExtent[1] - yExtent[0] + 2 * margin)
  207. ctx.beginPath()
  208. nodes.filter(visibleNodes).forEach(function (d) {
  209. var clients = d.o.node.statistics.clients
  210. if (d.clients === 0)
  211. return
  212. var distance = 16
  213. var radius = 3
  214. var a = 1.2
  215. var startAngle = Math.PI
  216. var angle = startAngle
  217. for (var i = 0; i < clients; i++) {
  218. if ((angle - startAngle) > 2 * Math.PI) {
  219. angle = startAngle
  220. distance += 2 * radius * a
  221. }
  222. var x = d.x + distance * Math.cos(angle)
  223. var y = d.y + distance * Math.sin(angle)
  224. ctx.moveTo(x, y)
  225. ctx.arc(x, y, radius, 0, 2 * Math.PI)
  226. var n = Math.floor((Math.PI * distance) / (a * radius))
  227. var angleDelta = 2 * Math.PI / n
  228. angle += angleDelta
  229. }
  230. })
  231. ctx.fillStyle = "#73A7CC"
  232. ctx.fill()
  233. if (highlightedLinks.length) {
  234. ctx.save()
  235. ctx.lineWidth = 10
  236. ctx.strokeStyle = "#FFD486"
  237. highlightedLinks.forEach(function (d) {
  238. ctx.beginPath()
  239. ctx.moveTo(d.source.x, d.source.y)
  240. ctx.lineTo(d.target.x, d.target.y)
  241. ctx.stroke()
  242. })
  243. ctx.restore()
  244. }
  245. ctx.lineWidth = 2.5
  246. links.forEach(function (d) {
  247. ctx.beginPath()
  248. ctx.moveTo(d.source.x, d.source.y)
  249. ctx.lineTo(d.target.x, d.target.y)
  250. ctx.strokeStyle = d.color
  251. ctx.stroke()
  252. })
  253. if (scale > 0.9)
  254. intNodes.filter(visibleNodes).forEach(drawLabel, scale)
  255. ctx.beginPath()
  256. unknownNodes.filter(visibleNodes).forEach(function (d) {
  257. ctx.moveTo(d.x + 8, d.y)
  258. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  259. })
  260. ctx.strokeStyle = "#d00000"
  261. ctx.fillStyle = "#ffffff"
  262. ctx.fill()
  263. ctx.stroke()
  264. ctx.beginPath()
  265. nodes.filter(visibleNodes).forEach(function (d) {
  266. ctx.moveTo(d.x + 8, d.y)
  267. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  268. })
  269. ctx.strokeStyle = "#AEC7E8"
  270. ctx.fillStyle = "#ffffff"
  271. ctx.fill()
  272. ctx.stroke()
  273. if (highlightedNodes.length) {
  274. ctx.save()
  275. ctx.strokeStyle = "#FFD486"
  276. ctx.fillStyle = "orange"
  277. ctx.lineWidth = 6
  278. highlightedNodes.forEach(function (d) {
  279. ctx.beginPath()
  280. ctx.moveTo(d.x + 8, d.y)
  281. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  282. ctx.fill()
  283. ctx.stroke()
  284. })
  285. ctx.restore()
  286. }
  287. ctx.restore()
  288. }
  289. function tickEvent() {
  290. redraw()
  291. }
  292. function resizeCanvas() {
  293. var r = window.devicePixelRatio
  294. canvas.width = el.offsetWidth * r
  295. canvas.height = el.offsetHeight * r
  296. canvas.style.width = el.offsetWidth + "px"
  297. canvas.style.height = el.offsetHeight + "px"
  298. ctx.resetTransform()
  299. ctx.scale(r, r)
  300. redraw()
  301. }
  302. function distance(a, b) {
  303. return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)
  304. }
  305. function distancePoint(a, b) {
  306. return Math.sqrt(distance(a, b))
  307. }
  308. function distanceLink(p, a, b) {
  309. /* http://stackoverflow.com/questions/849211 */
  310. var l2 = distance(a, b)
  311. if (l2 === 0)
  312. return distance(p, a)
  313. var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2
  314. if (t < 0)
  315. return distance(p, a)
  316. if (t > 1)
  317. return distance(p, b)
  318. return Math.sqrt(distance(p, { x: a.x + t * (b.x - a.x),
  319. y: a.y + t * (b.y - a.y) }))
  320. }
  321. function translateXY(d) {
  322. var translate = zoomBehavior.translate()
  323. var scale = zoomBehavior.scale()
  324. return {x: (d[0] - translate[0]) / scale,
  325. y: (d[1] - translate[1]) / scale
  326. }
  327. }
  328. function onClick() {
  329. if (d3.event.defaultPrevented)
  330. return
  331. var e = translateXY(d3.mouse(el))
  332. var nodes = intNodes.filter(function (d) {
  333. return distancePoint(e, d) < NODE_RADIUS
  334. })
  335. if (nodes.length > 0) {
  336. router.node(nodes[0].o.node)()
  337. return
  338. }
  339. var links = intLinks.filter(function (d) {
  340. return distanceLink(e, d.source, d.target) < LINE_RADIUS
  341. })
  342. if (links.length > 0) {
  343. router.link(links[0].o)()
  344. return
  345. }
  346. }
  347. el = document.createElement("div")
  348. el.classList.add("graph")
  349. self.div = el
  350. zoomBehavior = d3.behavior.zoom()
  351. .scaleExtent([1 / 3, 3])
  352. .on("zoom", panzoom)
  353. .translate([sidebar.getWidth(), 0])
  354. canvas = d3.select(el)
  355. .call(zoomBehavior)
  356. .append("canvas")
  357. .attr("pointer-events", "all")
  358. .on("click", onClick)
  359. .call(draggableNode)
  360. .node()
  361. ctx = canvas.getContext("2d")
  362. force = d3.layout.force()
  363. .charge(-80)
  364. .gravity(0.01)
  365. .chargeDistance(8 * LINK_DISTANCE)
  366. .linkDistance(LINK_DISTANCE)
  367. .linkStrength(function (d) {
  368. return Math.max(0.5, 1 / d.o.tq)
  369. })
  370. .on("tick", tickEvent)
  371. .on("end", savePositions)
  372. window.addEventListener("resize", resizeCanvas)
  373. panzoom()
  374. self.setData = function (data) {
  375. var oldNodes = {}
  376. intNodes.forEach( function (d) {
  377. oldNodes[d.o.id] = d
  378. })
  379. intNodes = data.graph.nodes.map( function (d) {
  380. var e
  381. if (d.id in oldNodes)
  382. e = oldNodes[d.id]
  383. else
  384. e = {}
  385. e.o = d
  386. return e
  387. })
  388. var newNodesDict = {}
  389. intNodes.forEach( function (d) {
  390. newNodesDict[d.o.id] = d
  391. })
  392. var oldLinks = {}
  393. intLinks.forEach( function (d) {
  394. oldLinks[d.o.id] = d
  395. })
  396. intLinks = data.graph.links.filter( function (d) {
  397. return !d.vpn
  398. }).map( function (d) {
  399. var e
  400. if (d.id in oldLinks)
  401. e = oldLinks[d.id]
  402. else
  403. e = {}
  404. e.o = d
  405. e.source = newNodesDict[d.source.id]
  406. e.target = newNodesDict[d.target.id]
  407. e.color = linkScale(d.tq).hex()
  408. return e
  409. })
  410. linksDict = {}
  411. nodesDict = {}
  412. intNodes.forEach(function (d) {
  413. d.neighbours = {}
  414. if (d.o.node)
  415. nodesDict[d.o.node.nodeinfo.node_id] = d
  416. var name = nodeName(d)
  417. ctx.font = "11px Roboto"
  418. var offset = 8
  419. var lineWidth = 3
  420. var width = ctx.measureText(name).width
  421. var buffer = document.createElement("canvas")
  422. var r = window.devicePixelRatio
  423. var bctx = buffer.getContext("2d")
  424. var scale = zoomBehavior.scaleExtent()[1] * r
  425. buffer.width = (width + 2 * lineWidth) * scale
  426. buffer.height = (16 + 2 * lineWidth) * scale
  427. bctx.scale(scale, scale)
  428. bctx.textBaseline = "middle"
  429. bctx.textAlign = "center"
  430. bctx.font = ctx.font
  431. bctx.lineWidth = lineWidth
  432. bctx.lineCap = "round"
  433. bctx.strokeStyle = "rgba(255, 255, 255, 0.8)"
  434. bctx.fillStyle = "rgba(0, 0, 0, 0.6)"
  435. bctx.strokeText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  436. bctx.fillText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  437. d.label = buffer
  438. d.labelWidth = buffer.width / scale
  439. d.labelHeight = buffer.height / scale
  440. d.labelA = offset + buffer.width / (2 * scale)
  441. d.labelB = offset + buffer.height / (2 * scale)
  442. })
  443. intLinks.forEach(function (d) {
  444. d.source.neighbours[d.target.o.id] = d.target
  445. d.target.neighbours[d.source.o.id] = d.source
  446. if (d.o.source.node && d.o.target.node)
  447. linksDict[d.o.id] = d
  448. })
  449. intNodes.forEach(function (d) {
  450. d.neighbours = Object.keys(d.neighbours).map(function (k) {
  451. return d.neighbours[k]
  452. })
  453. })
  454. nodes = intNodes.filter(function (d) { return d.o.node })
  455. unknownNodes = intNodes.filter(function (d) { return !d.o.node })
  456. if (localStorageTest()) {
  457. var save = JSON.parse(localStorage.getItem("graph/nodeposition"))
  458. if (save) {
  459. var nodePositions = {}
  460. save.forEach( function (d) {
  461. nodePositions[d.id] = d
  462. })
  463. intNodes.forEach( function (d) {
  464. if (nodePositions[d.o.id] && (d.x === undefined || d.y === undefined)) {
  465. d.x = nodePositions[d.o.id].x
  466. d.y = nodePositions[d.o.id].y
  467. }
  468. })
  469. }
  470. }
  471. var diameter = graphDiameter(intNodes)
  472. force.nodes(intNodes)
  473. .links(intLinks)
  474. .size([diameter, diameter])
  475. updateHighlight(true)
  476. force.start()
  477. resizeCanvas()
  478. }
  479. self.resetView = function () {
  480. highlight = undefined
  481. updateHighlight()
  482. doAnimation = true
  483. }
  484. self.gotoNode = function (d) {
  485. highlight = {type: "node", o: d}
  486. updateHighlight()
  487. doAnimation = true
  488. }
  489. self.gotoLink = function (d) {
  490. highlight = {type: "link", o: d}
  491. updateHighlight()
  492. doAnimation = true
  493. }
  494. self.destroy = function () {
  495. force.stop()
  496. canvas.remove()
  497. force = null
  498. }
  499. return self
  500. }
  501. })