forcegraph.js 18 KB

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