forcegraph.js 17 KB

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