forcegraph.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. if (!d.o.vpn)
  187. return (d.source.x > screenRect.left && d.source.x < screenRect.right &&
  188. d.source.y > screenRect.top && d.source.y < screenRect.bottom) ||
  189. (d.target.x > screenRect.left && d.target.x < screenRect.right &&
  190. d.target.y > screenRect.top && d.target.y < screenRect.bottom)
  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 (d.clients === 0)
  225. return
  226. var distance = 16
  227. var radius = 3
  228. var a = 1.2
  229. var startAngle = Math.PI
  230. var angle = startAngle
  231. for (var i = 0; i < clients; i++) {
  232. if ((angle - startAngle) > 2 * Math.PI) {
  233. angle = startAngle
  234. distance += 2 * radius * a
  235. }
  236. var x = d.x + distance * Math.cos(angle)
  237. var y = d.y + distance * Math.sin(angle)
  238. ctx.moveTo(x, y)
  239. ctx.arc(x, y, radius, 0, 2 * Math.PI)
  240. var n = Math.floor((Math.PI * distance) / (a * radius))
  241. var angleDelta = 2 * Math.PI / n
  242. angle += angleDelta
  243. }
  244. })
  245. ctx.fillStyle = "#73A7CC"
  246. ctx.fill()
  247. if (highlightedLinks.length) {
  248. ctx.save()
  249. ctx.lineWidth = 10
  250. ctx.strokeStyle = "#FFD486"
  251. highlightedLinks.forEach(function (d) {
  252. ctx.beginPath()
  253. ctx.moveTo(d.source.x, d.source.y)
  254. ctx.lineTo(d.target.x, d.target.y)
  255. ctx.stroke()
  256. })
  257. ctx.restore()
  258. }
  259. ctx.save()
  260. links.forEach(function (d) {
  261. ctx.beginPath()
  262. ctx.moveTo(d.source.x, d.source.y)
  263. ctx.lineTo(d.target.x, d.target.y)
  264. ctx.strokeStyle = d.color
  265. ctx.globalAlpha = d.o.vpn ? 0.1 : 1
  266. ctx.lineWidth = d.o.vpn ? 1.5 : 2.5
  267. ctx.stroke()
  268. })
  269. ctx.restore()
  270. if (scale > 0.9)
  271. intNodes.filter(visibleNodes).forEach(drawLabel, scale)
  272. ctx.beginPath()
  273. unknownNodes.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 = "#d00000"
  278. ctx.fillStyle = "#ffffff"
  279. ctx.lineWidth = 2.5
  280. ctx.fill()
  281. ctx.stroke()
  282. ctx.beginPath()
  283. nodes.filter(visibleNodes).forEach(function (d) {
  284. ctx.moveTo(d.x + 8, d.y)
  285. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  286. })
  287. ctx.strokeStyle = "#AEC7E8"
  288. ctx.fillStyle = "#ffffff"
  289. ctx.fill()
  290. ctx.stroke()
  291. if (highlightedNodes.length) {
  292. ctx.save()
  293. ctx.strokeStyle = "#FFD486"
  294. ctx.fillStyle = "orange"
  295. ctx.lineWidth = 6
  296. highlightedNodes.forEach(function (d) {
  297. ctx.beginPath()
  298. ctx.moveTo(d.x + 8, d.y)
  299. ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI)
  300. ctx.fill()
  301. ctx.stroke()
  302. })
  303. ctx.restore()
  304. }
  305. ctx.restore()
  306. }
  307. function tickEvent() {
  308. redraw()
  309. }
  310. function resizeCanvas() {
  311. var r = window.devicePixelRatio
  312. canvas.width = el.offsetWidth * r
  313. canvas.height = el.offsetHeight * r
  314. canvas.style.width = el.offsetWidth + "px"
  315. canvas.style.height = el.offsetHeight + "px"
  316. ctx.resetTransform()
  317. ctx.scale(r, r)
  318. requestAnimationFrame(redraw)
  319. }
  320. function distance(a, b) {
  321. return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)
  322. }
  323. function distancePoint(a, b) {
  324. return Math.sqrt(distance(a, b))
  325. }
  326. function distanceLink(p, a, b) {
  327. /* http://stackoverflow.com/questions/849211 */
  328. var l2 = distance(a, b)
  329. if (l2 === 0)
  330. return distance(p, a)
  331. var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2
  332. if (t < 0)
  333. return distance(p, a)
  334. if (t > 1)
  335. return distance(p, b)
  336. return Math.sqrt(distance(p, { x: a.x + t * (b.x - a.x),
  337. y: a.y + t * (b.y - a.y) }))
  338. }
  339. function translateXY(d) {
  340. var translate = zoomBehavior.translate()
  341. var scale = zoomBehavior.scale()
  342. return {x: (d[0] - translate[0]) / scale,
  343. y: (d[1] - translate[1]) / scale
  344. }
  345. }
  346. function onClick() {
  347. if (d3.event.defaultPrevented)
  348. return
  349. var e = translateXY(d3.mouse(el))
  350. var nodes = intNodes.filter(function (d) {
  351. return distancePoint(e, d) < NODE_RADIUS
  352. })
  353. if (nodes.length > 0) {
  354. router.node(nodes[0].o.node)()
  355. return
  356. }
  357. var links = intLinks.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. e.color = linkScale(d.tq).hex()
  431. return e
  432. })
  433. linksDict = {}
  434. nodesDict = {}
  435. intNodes.forEach(function (d) {
  436. d.neighbours = {}
  437. if (d.o.node)
  438. nodesDict[d.o.node.nodeinfo.node_id] = d
  439. var name = nodeName(d)
  440. var offset = 8
  441. var lineWidth = 3
  442. var buffer = document.createElement("canvas")
  443. var r = window.devicePixelRatio
  444. var bctx = buffer.getContext("2d")
  445. bctx.font = "11px Roboto"
  446. var width = bctx.measureText(name).width
  447. var scale = zoomBehavior.scaleExtent()[1] * r
  448. buffer.width = (width + 2 * lineWidth) * scale
  449. buffer.height = (16 + 2 * lineWidth) * scale
  450. bctx.scale(scale, scale)
  451. bctx.textBaseline = "middle"
  452. bctx.textAlign = "center"
  453. bctx.lineWidth = lineWidth
  454. bctx.lineCap = "round"
  455. bctx.strokeStyle = "rgba(255, 255, 255, 0.8)"
  456. bctx.fillStyle = "rgba(0, 0, 0, 0.6)"
  457. bctx.miterLimit = 2
  458. bctx.strokeText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  459. bctx.fillText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  460. d.label = buffer
  461. d.labelWidth = buffer.width / scale
  462. d.labelHeight = buffer.height / scale
  463. d.labelA = offset + buffer.width / (2 * scale)
  464. d.labelB = offset + buffer.height / (2 * scale)
  465. })
  466. intLinks.forEach(function (d) {
  467. d.source.neighbours[d.target.o.id] = {node: d.target, link: d}
  468. d.target.neighbours[d.source.o.id] = {node: d.source, link: d}
  469. if (d.o.source.node && d.o.target.node)
  470. linksDict[d.o.id] = d
  471. })
  472. intNodes.forEach(function (d) {
  473. d.neighbours = Object.keys(d.neighbours).map(function (k) {
  474. return d.neighbours[k]
  475. })
  476. })
  477. nodes = intNodes.filter(function (d) { return d.o.node })
  478. unknownNodes = intNodes.filter(function (d) { return !d.o.node })
  479. if (localStorageTest()) {
  480. var save = JSON.parse(localStorage.getItem("graph/nodeposition"))
  481. if (save) {
  482. var nodePositions = {}
  483. save.forEach( function (d) {
  484. nodePositions[d.id] = d
  485. })
  486. intNodes.forEach( function (d) {
  487. if (nodePositions[d.o.id] && (d.x === undefined || d.y === undefined)) {
  488. d.x = nodePositions[d.o.id].x
  489. d.y = nodePositions[d.o.id].y
  490. }
  491. })
  492. }
  493. }
  494. var diameter = graphDiameter(intNodes)
  495. force.nodes(intNodes)
  496. .links(intLinks)
  497. .size([diameter, diameter])
  498. updateHighlight(true)
  499. force.start()
  500. resizeCanvas()
  501. }
  502. self.resetView = function () {
  503. highlight = undefined
  504. updateHighlight()
  505. doAnimation = true
  506. }
  507. self.gotoNode = function (d) {
  508. highlight = {type: "node", o: d}
  509. updateHighlight()
  510. doAnimation = true
  511. }
  512. self.gotoLink = function (d) {
  513. highlight = {type: "link", o: d}
  514. updateHighlight()
  515. doAnimation = true
  516. }
  517. self.destroy = function () {
  518. force.stop()
  519. canvas.remove()
  520. force = null
  521. }
  522. return self
  523. }
  524. })