forcegraph.js 16 KB

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