forcegraph.js 17 KB

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