forcegraph.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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 (clients === 0)
  225. return
  226. var startDistance = 16
  227. var radius = 3
  228. var a = 1.2
  229. var startAngle = Math.PI
  230. for (var orbit = 0, i = 0; i < clients; orbit++) {
  231. var distance = startDistance + orbit * 2 * radius * a
  232. var n = Math.floor((Math.PI * distance) / (a * radius))
  233. var delta = clients - i
  234. for (var j = 0; j < Math.min(delta, n); i++, j++) {
  235. var angle = 2 * Math.PI / n * j
  236. var x = d.x + distance * Math.cos(angle + startAngle)
  237. var y = d.y + distance * Math.sin(angle + startAngle)
  238. ctx.moveTo(x, y)
  239. ctx.arc(x, y, radius, 0, 2 * Math.PI)
  240. }
  241. }
  242. })
  243. var clientColor = "#E6324B"
  244. var hilightColor = "#FA940F"
  245. var unknownColor = "#353634"
  246. var nodeColor = "#F2E3C6"
  247. ctx.fillStyle = clientColor
  248. ctx.fill()
  249. if (highlightedLinks.length) {
  250. ctx.save()
  251. ctx.lineWidth = 10
  252. ctx.strokeStyle = hilightColor
  253. highlightedLinks.forEach(function (d) {
  254. ctx.beginPath()
  255. ctx.moveTo(d.source.x, d.source.y)
  256. ctx.lineTo(d.target.x, d.target.y)
  257. ctx.stroke()
  258. })
  259. ctx.restore()
  260. }
  261. ctx.save()
  262. links.forEach(function (d) {
  263. ctx.beginPath()
  264. ctx.moveTo(d.source.x, d.source.y)
  265. ctx.lineTo(d.target.x, d.target.y)
  266. ctx.strokeStyle = d.color
  267. ctx.globalAlpha = d.o.vpn ? 0.1 : 1
  268. ctx.lineWidth = d.o.vpn ? 1.5 : 2.5
  269. ctx.stroke()
  270. })
  271. ctx.restore()
  272. if (scale > 0.9)
  273. intNodes.filter(visibleNodes).forEach(drawLabel, scale)
  274. ctx.beginPath()
  275. unknownNodes.filter(visibleNodes).forEach(function (d) {
  276. ctx.moveTo(d.x + 8, d.y)
  277. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  278. })
  279. ctx.fillStyle = unknownColor
  280. ctx.fill()
  281. ctx.beginPath()
  282. nodes.filter(visibleNodes).forEach(function (d) {
  283. ctx.moveTo(d.x + 8, d.y)
  284. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  285. })
  286. ctx.fillStyle = nodeColor
  287. ctx.fill()
  288. if (highlightedNodes.length) {
  289. ctx.save()
  290. ctx.strokeStyle = hilightColor
  291. ctx.fillStyle = nodeColor
  292. ctx.lineWidth = 6
  293. highlightedNodes.forEach(function (d) {
  294. ctx.beginPath()
  295. ctx.moveTo(d.x + 8, d.y)
  296. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  297. ctx.fill()
  298. ctx.stroke()
  299. })
  300. ctx.restore()
  301. }
  302. ctx.restore()
  303. }
  304. function tickEvent() {
  305. redraw()
  306. }
  307. function resizeCanvas() {
  308. var r = window.devicePixelRatio
  309. canvas.width = el.offsetWidth * r
  310. canvas.height = el.offsetHeight * r
  311. canvas.style.width = el.offsetWidth + "px"
  312. canvas.style.height = el.offsetHeight + "px"
  313. ctx.resetTransform()
  314. ctx.scale(r, r)
  315. requestAnimationFrame(redraw)
  316. }
  317. function distance(a, b) {
  318. return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)
  319. }
  320. function distancePoint(a, b) {
  321. return Math.sqrt(distance(a, b))
  322. }
  323. function distanceLink(p, a, b) {
  324. /* http://stackoverflow.com/questions/849211 */
  325. var l2 = distance(a, b)
  326. if (l2 === 0)
  327. return distance(p, a)
  328. var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2
  329. if (t < 0)
  330. return distance(p, a)
  331. if (t > 1)
  332. return distance(p, b)
  333. return Math.sqrt(distance(p, { x: a.x + t * (b.x - a.x),
  334. y: a.y + t * (b.y - a.y) }))
  335. }
  336. function translateXY(d) {
  337. var translate = zoomBehavior.translate()
  338. var scale = zoomBehavior.scale()
  339. return {x: (d[0] - translate[0]) / scale,
  340. y: (d[1] - translate[1]) / scale
  341. }
  342. }
  343. function onClick() {
  344. if (d3.event.defaultPrevented)
  345. return
  346. var e = translateXY(d3.mouse(el))
  347. var nodes = intNodes.filter(function (d) {
  348. return distancePoint(e, d) < NODE_RADIUS
  349. })
  350. if (nodes.length > 0) {
  351. router.node(nodes[0].o.node)()
  352. return
  353. }
  354. var links = intLinks.filter(function (d) {
  355. return !d.o.vpn
  356. }).filter(function (d) {
  357. return distanceLink(e, d.source, d.target) < LINE_RADIUS
  358. })
  359. if (links.length > 0) {
  360. router.link(links[0].o)()
  361. return
  362. }
  363. }
  364. function keyboardZoom(z) {
  365. return function () {
  366. var e = d3.event
  367. if (e.altKey || e.ctrlKey || e.metaKey)
  368. return
  369. if (e.keyCode === 43)
  370. animatePanzoom(z.translate(), z.scale() * 1.41)
  371. if (e.keyCode === 45)
  372. animatePanzoom(z.translate(), z.scale() / 1.41)
  373. }
  374. }
  375. el = document.createElement("div")
  376. el.classList.add("graph")
  377. self.div = el
  378. zoomBehavior = d3.behavior.zoom()
  379. .scaleExtent([1 / 3, 3])
  380. .on("zoom", onPanZoom)
  381. .translate([sidebar.getWidth(), 0])
  382. canvas = d3.select(el)
  383. .attr("tabindex", 1)
  384. .on("keypress", keyboardZoom(zoomBehavior))
  385. .call(zoomBehavior)
  386. .append("canvas")
  387. .on("click", onClick)
  388. .call(draggableNode)
  389. .node()
  390. ctx = canvas.getContext("2d")
  391. force = d3.layout.force()
  392. .charge(-250)
  393. .gravity(0.1)
  394. .linkDistance(function (d) {
  395. if (d.o.vpn)
  396. return 0
  397. else
  398. return LINK_DISTANCE
  399. })
  400. .linkStrength(function (d) {
  401. if (d.o.vpn)
  402. return 0
  403. else
  404. return Math.max(0.5, 1 / d.o.tq)
  405. })
  406. .on("tick", tickEvent)
  407. .on("end", savePositions)
  408. window.addEventListener("resize", resizeCanvas)
  409. panzoom()
  410. self.setData = function (data) {
  411. var oldNodes = {}
  412. intNodes.forEach( function (d) {
  413. oldNodes[d.o.id] = d
  414. })
  415. intNodes = data.graph.nodes.map( function (d) {
  416. var e
  417. if (d.id in oldNodes)
  418. e = oldNodes[d.id]
  419. else
  420. e = {}
  421. e.o = d
  422. return e
  423. })
  424. var newNodesDict = {}
  425. intNodes.forEach( function (d) {
  426. newNodesDict[d.o.id] = d
  427. })
  428. var oldLinks = {}
  429. intLinks.forEach( function (d) {
  430. oldLinks[d.o.id] = d
  431. })
  432. intLinks = data.graph.links.map( function (d) {
  433. var e
  434. if (d.id in oldLinks)
  435. e = oldLinks[d.id]
  436. else
  437. e = {}
  438. e.o = d
  439. e.source = newNodesDict[d.source.id]
  440. e.target = newNodesDict[d.target.id]
  441. if (d.vpn)
  442. e.color = "rgba(255, 255, 255, " + (0.6 / d.tq) + ")"
  443. else
  444. e.color = linkScale(d.tq).hex()
  445. return e
  446. })
  447. linksDict = {}
  448. nodesDict = {}
  449. intNodes.forEach(function (d) {
  450. d.neighbours = {}
  451. if (d.o.node)
  452. nodesDict[d.o.node.nodeinfo.node_id] = d
  453. var name = nodeName(d)
  454. var offset = 8
  455. var lineWidth = 3
  456. var buffer = document.createElement("canvas")
  457. var r = window.devicePixelRatio
  458. var bctx = buffer.getContext("2d")
  459. bctx.font = "11px Roboto"
  460. var width = bctx.measureText(name).width
  461. var scale = zoomBehavior.scaleExtent()[1] * r
  462. buffer.width = (width + 2 * lineWidth) * scale
  463. buffer.height = (16 + 2 * lineWidth) * scale
  464. bctx.scale(scale, scale)
  465. bctx.textBaseline = "middle"
  466. bctx.textAlign = "center"
  467. bctx.lineWidth = lineWidth
  468. bctx.lineCap = "round"
  469. bctx.strokeStyle = "rgba(53, 54, 52, 0.1)"
  470. bctx.fillStyle = "rgba(242, 227, 198, 0.8)"
  471. bctx.miterLimit = 2
  472. bctx.strokeText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  473. bctx.fillText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  474. d.label = buffer
  475. d.labelWidth = buffer.width / scale
  476. d.labelHeight = buffer.height / scale
  477. d.labelA = offset + buffer.width / (2 * scale)
  478. d.labelB = offset + buffer.height / (2 * scale)
  479. })
  480. intLinks.forEach(function (d) {
  481. d.source.neighbours[d.target.o.id] = {node: d.target, link: d}
  482. d.target.neighbours[d.source.o.id] = {node: d.source, link: d}
  483. if (d.o.source.node && d.o.target.node)
  484. linksDict[d.o.id] = d
  485. })
  486. intNodes.forEach(function (d) {
  487. d.neighbours = Object.keys(d.neighbours).map(function (k) {
  488. return d.neighbours[k]
  489. })
  490. })
  491. nodes = intNodes.filter(function (d) { return d.o.node })
  492. unknownNodes = intNodes.filter(function (d) { return !d.o.node })
  493. if (localStorageTest()) {
  494. var save = JSON.parse(localStorage.getItem("graph/nodeposition"))
  495. if (save) {
  496. var nodePositions = {}
  497. save.forEach( function (d) {
  498. nodePositions[d.id] = d
  499. })
  500. intNodes.forEach( function (d) {
  501. if (nodePositions[d.o.id] && (d.x === undefined || d.y === undefined)) {
  502. d.x = nodePositions[d.o.id].x
  503. d.y = nodePositions[d.o.id].y
  504. }
  505. })
  506. }
  507. }
  508. var diameter = graphDiameter(intNodes)
  509. force.nodes(intNodes)
  510. .links(intLinks)
  511. .size([diameter, diameter])
  512. updateHighlight(true)
  513. force.start()
  514. resizeCanvas()
  515. }
  516. self.resetView = function () {
  517. highlight = undefined
  518. updateHighlight()
  519. doAnimation = true
  520. }
  521. self.gotoNode = function (d) {
  522. highlight = {type: "node", o: d}
  523. updateHighlight()
  524. doAnimation = true
  525. }
  526. self.gotoLink = function (d) {
  527. highlight = {type: "link", o: d}
  528. updateHighlight()
  529. doAnimation = true
  530. }
  531. self.destroy = function () {
  532. force.stop()
  533. canvas.remove()
  534. force = null
  535. }
  536. return self
  537. }
  538. })