forcegraph.js 17 KB

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