forcegraph.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. define(["d3"], function (d3) {
  2. return function (config, linkScale, sidebar, router) {
  3. var self = this
  4. var svg, vis, link, node, label
  5. var nodesDict, linksDict
  6. var zoomBehavior
  7. var force
  8. var el
  9. var doAnimation = false
  10. var intNodes = []
  11. var intLinks = []
  12. var highlight
  13. var LINK_DISTANCE = 70
  14. function graphDiameter(nodes) {
  15. return Math.sqrt(nodes.length / Math.PI) * LINK_DISTANCE * 1.41
  16. }
  17. function savePositions() {
  18. if (!localStorageTest())
  19. return
  20. var save = intNodes.map( function (d) {
  21. return { id: d.o.id, x: d.x, y: d.y }
  22. })
  23. localStorage.setItem("graph/nodeposition", JSON.stringify(save))
  24. }
  25. function nodeName(d) {
  26. if (d.o.node && d.o.node.nodeinfo)
  27. return d.o.node.nodeinfo.hostname
  28. else
  29. return d.o.id
  30. }
  31. function dragstart(d) {
  32. d3.event.sourceEvent.stopPropagation()
  33. d.fixed |= 2
  34. }
  35. function dragmove(d) {
  36. d.px = d3.event.x
  37. d.py = d3.event.y
  38. force.resume()
  39. }
  40. function dragend(d) {
  41. d3.event.sourceEvent.stopPropagation()
  42. d.fixed &= 1
  43. }
  44. var draggableNode = d3.behavior.drag()
  45. .on("dragstart", dragstart)
  46. .on("drag", dragmove)
  47. .on("dragend", dragend)
  48. function animatePanzoom(translate, scale) {
  49. zoomBehavior.scale(scale)
  50. zoomBehavior.translate(translate)
  51. var el = vis
  52. if (doAnimation)
  53. el = el.transition().duration(500)
  54. el.attr("transform", "translate(" + translate + ") " +
  55. "scale(" + scale + ")")
  56. }
  57. function panzoom() {
  58. var translate = zoomBehavior.translate()
  59. var scale = zoomBehavior.scale()
  60. vis.attr("transform", "translate(" + translate + ") " +
  61. "scale(" + scale + ")")
  62. }
  63. function getSize() {
  64. var sidebarWidth = sidebar.getWidth()
  65. var width = el.offsetWidth - sidebarWidth
  66. var height = el.offsetHeight
  67. return [width, height]
  68. }
  69. function panzoomTo(a, b) {
  70. var sidebarWidth = sidebar.getWidth()
  71. var size = getSize()
  72. var targetWidth = Math.max(1, b[0] - a[0])
  73. var targetHeight = Math.max(1, b[1] - a[1])
  74. var scaleX = size[0] / targetWidth
  75. var scaleY = size[1] / targetHeight
  76. var scaleMax = zoomBehavior.scaleExtent()[1]
  77. var scale = 0.5 * Math.min(scaleMax, Math.min(scaleX, scaleY))
  78. var centroid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]
  79. var x = -centroid[0] * scale + size[0] / 2
  80. var y = -centroid[1] * scale + size[1] / 2
  81. var translate = [x + sidebarWidth, y]
  82. animatePanzoom(translate, scale)
  83. }
  84. function updateHighlight(nopanzoom) {
  85. if (highlight !== undefined)
  86. if (highlight.type === "node") {
  87. var n = nodesDict[highlight.o.nodeinfo.node_id]
  88. if (n) {
  89. link.classed("highlight", false)
  90. node.classed("highlight", function (e) {
  91. return e.o.node === n.o.node && n.o.node !== undefined
  92. })
  93. if (!nopanzoom)
  94. panzoomTo([n.x, n.y], [n.x, n.y])
  95. }
  96. return
  97. } else if (highlight.type === "link") {
  98. var l = linksDict[highlight.o.id]
  99. if (l) {
  100. node.classed("highlight", false)
  101. link.classed("highlight", function (e) {
  102. return e.o === l.o && l.o !== undefined
  103. })
  104. if (!nopanzoom) {
  105. var x = d3.extent([l.source, l.target], function (d) { return d.x })
  106. var y = d3.extent([l.source, l.target], function (d) { return d.y })
  107. panzoomTo([x[0], y[0]], [x[1], y[1]])
  108. }
  109. }
  110. return
  111. }
  112. node.classed("highlight", false)
  113. link.classed("highlight", false)
  114. if (!nopanzoom)
  115. panzoomTo([0, 0], force.size())
  116. }
  117. function updateLinks(vis, data) {
  118. var link = vis.selectAll("g.link")
  119. .data(data, function (d) { return d.o.id })
  120. link.exit().remove()
  121. var linkEnter = link.enter().append("g")
  122. .attr("class", "link")
  123. .on("click", function (d) {
  124. if (!d3.event.defaultPrevented)
  125. router.link(d.o)()
  126. })
  127. linkEnter.append("line")
  128. .append("title")
  129. link.selectAll("line")
  130. .style("stroke", function (d) { return linkScale(d.o.tq).hex() })
  131. link.selectAll("title").text(function (d) { return showTq(d.o) })
  132. return link
  133. }
  134. function updateNodes(vis, data) {
  135. var node = vis.selectAll(".node")
  136. .data(data, function(d) { return d.o.id })
  137. node.exit().remove()
  138. node.enter().append("circle")
  139. .attr("r", 8)
  140. .on("click", function (d) {
  141. if (!d3.event.defaultPrevented)
  142. router.node(d.o.node)()
  143. })
  144. .call(draggableNode)
  145. node.attr("class", function (d) {
  146. var s = ["node"]
  147. if (!d.o.node)
  148. s.push("unknown")
  149. return s.join(" ")
  150. })
  151. return node
  152. }
  153. function updateLabels(vis, data) {
  154. var label = vis.selectAll("text")
  155. .data(data, function(d) { return d.o.id })
  156. label.exit().remove()
  157. var labelEnter = label.enter().append("text")
  158. label.text(nodeName)
  159. .each(function (d) {
  160. var bbox = this.getBBox()
  161. d.labelHeight = bbox.height
  162. d.labelWidth = bbox.width
  163. })
  164. labelEnter.each(function (d) {
  165. d.labelAngle = Math.PI / 2
  166. })
  167. return label
  168. }
  169. function positionLabels() {
  170. label.attr("transform", function(d) {
  171. var neighbours = d.neighbours.map(function (n) {
  172. var dx = n.x - d.x
  173. var dy = n.y - d.y
  174. return (2 * Math.PI + Math.atan2(dy, dx)) % (2 * Math.PI)
  175. })
  176. var sumCos = neighbours.reduce(function (a, b) {
  177. return a + Math.cos(b)
  178. }, 0)
  179. var sumSin = neighbours.reduce(function (a, b) {
  180. return a + Math.sin(b)
  181. }, 0)
  182. if (neighbours.length > 0)
  183. d.labelAngle = Math.PI + Math.atan2(sumSin, sumCos)
  184. var offset = 10
  185. var a = offset + d.labelWidth / 2
  186. var b = offset + d.labelHeight / 2
  187. var cos = Math.cos(d.labelAngle)
  188. var sin = Math.sin(d.labelAngle)
  189. var x = d.x + a * Math.pow(Math.abs(cos), 2 / 5) * Math.sign(cos)
  190. var y = d.y + b * Math.pow(Math.abs(sin), 2 / 5) * Math.sign(sin)
  191. return "translate(" + x + "," + y + ")"
  192. })
  193. }
  194. function tickEvent() {
  195. link.selectAll("line")
  196. .attr("x1", function(d) { return d.source.x })
  197. .attr("y1", function(d) { return d.source.y })
  198. .attr("x2", function(d) { return d.target.x })
  199. .attr("y2", function(d) { return d.target.y })
  200. node.attr("cx", function (d) { return d.x })
  201. .attr("cy", function (d) { return d.y })
  202. positionLabels()
  203. }
  204. el = document.createElement("div")
  205. el.classList.add("graph")
  206. self.div = el
  207. zoomBehavior = d3.behavior.zoom()
  208. .scaleExtent([1 / 3, 3])
  209. .on("zoom", panzoom)
  210. .translate([sidebar.getWidth(), 0])
  211. svg = d3.select(el).append("svg")
  212. .attr("pointer-events", "all")
  213. .call(zoomBehavior)
  214. vis = svg.append("g")
  215. var visLinks = vis.append("g").attr("class", "links")
  216. var visLabels = vis.append("g").attr("class", "labels")
  217. var visNodes = vis.append("g").attr("class", "nodes")
  218. force = d3.layout.force()
  219. .charge(-80)
  220. .gravity(0.01)
  221. .chargeDistance(8 * LINK_DISTANCE)
  222. .linkDistance(LINK_DISTANCE)
  223. .linkStrength(function (d) {
  224. return Math.max(0.5, 1 / d.o.tq)
  225. })
  226. .on("tick", tickEvent)
  227. .on("end", savePositions)
  228. panzoom()
  229. self.setData = function (data) {
  230. var oldNodes = {}
  231. intNodes.forEach( function (d) {
  232. oldNodes[d.o.id] = d
  233. })
  234. intNodes = data.graph.nodes.map( function (d) {
  235. var e
  236. if (d.id in oldNodes)
  237. e = oldNodes[d.id]
  238. else
  239. e = {}
  240. e.o = d
  241. return e
  242. })
  243. var newNodesDict = {}
  244. intNodes.forEach( function (d) {
  245. newNodesDict[d.o.id] = d
  246. })
  247. var oldLinks = {}
  248. intLinks.forEach( function (d) {
  249. oldLinks[d.o.id] = d
  250. })
  251. intLinks = data.graph.links.filter( function (d) {
  252. return !d.vpn
  253. }).map( function (d) {
  254. var e
  255. if (d.id in oldLinks)
  256. e = oldLinks[d.id]
  257. else
  258. e = {}
  259. e.o = d
  260. e.source = newNodesDict[d.source.id]
  261. e.target = newNodesDict[d.target.id]
  262. return e
  263. })
  264. intNodes.forEach(function (d) {
  265. d.neighbours = {}
  266. })
  267. intLinks.forEach(function (d) {
  268. d.source.neighbours[d.target.o.id] = d.target
  269. d.target.neighbours[d.source.o.id] = d.source
  270. })
  271. intNodes.forEach(function (d) {
  272. d.neighbours = Object.keys(d.neighbours).map(function (k) {
  273. return d.neighbours[k]
  274. })
  275. })
  276. link = updateLinks(visLinks, intLinks)
  277. node = updateNodes(visNodes, intNodes)
  278. label = updateLabels(visLabels, intNodes)
  279. linksDict = {}
  280. link.each( function (d) {
  281. if (d.o.source.node && d.o.target.node)
  282. linksDict[d.o.id] = d
  283. })
  284. nodesDict = {}
  285. node.each( function (d) {
  286. if (d.o.node)
  287. nodesDict[d.o.node.nodeinfo.node_id] = d
  288. })
  289. if (localStorageTest()) {
  290. var save = JSON.parse(localStorage.getItem("graph/nodeposition"))
  291. if (save) {
  292. var nodePositions = {}
  293. save.forEach( function (d) {
  294. nodePositions[d.id] = d
  295. })
  296. node.each( function (d) {
  297. if (nodePositions[d.o.id] && (d.x === undefined || d.y === undefined)) {
  298. d.x = nodePositions[d.o.id].x
  299. d.y = nodePositions[d.o.id].y
  300. }
  301. })
  302. }
  303. }
  304. var diameter = graphDiameter(intNodes)
  305. force.nodes(intNodes)
  306. .links(intLinks)
  307. .size([diameter, diameter])
  308. updateHighlight(true)
  309. if (node.enter().size() + link.enter().size() > 0)
  310. force.start()
  311. }
  312. self.resetView = function () {
  313. highlight = undefined
  314. updateHighlight()
  315. doAnimation = true
  316. }
  317. self.gotoNode = function (d) {
  318. highlight = {type: "node", o: d}
  319. updateHighlight()
  320. doAnimation = true
  321. }
  322. self.gotoLink = function (d) {
  323. highlight = {type: "link", o: d}
  324. updateHighlight()
  325. doAnimation = true
  326. }
  327. self.destroy = function () {
  328. force.stop()
  329. node.remove()
  330. link.remove()
  331. svg.remove()
  332. force = null
  333. svg = null
  334. vis = null
  335. link = null
  336. node = null
  337. }
  338. return self
  339. }
  340. })