forcegraph.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. draggedNode.px = draggedNode.x
  52. draggedNode.py = draggedNode.y
  53. }
  54. function dragmove() {
  55. if (draggedNode) {
  56. var e = translateXY(d3.mouse(el))
  57. draggedNode.px = e.x
  58. draggedNode.py = e.y
  59. force.resume()
  60. }
  61. }
  62. function dragend() {
  63. if (draggedNode) {
  64. d3.event.sourceEvent.stopPropagation()
  65. d3.event.sourceEvent.preventDefault()
  66. draggedNode.fixed &= ~2
  67. draggedNode = undefined
  68. }
  69. }
  70. var draggableNode = d3.behavior.drag()
  71. .on("dragstart", dragstart)
  72. .on("drag", dragmove)
  73. .on("dragend", dragend)
  74. function animatePanzoom(translate, scale) {
  75. var translateP = zoomBehavior.translate()
  76. var scaleP = zoomBehavior.scale()
  77. if (!doAnimation) {
  78. zoomBehavior.translate(translate)
  79. zoomBehavior.scale(scale)
  80. panzoom()
  81. } else {
  82. var start = {x: translateP[0], y: translateP[1], scale: scaleP}
  83. var end = {x: translate[0], y: translate[1], scale: scale}
  84. var interpolate = d3.interpolateObject(start, end)
  85. var duration = 500
  86. var ease = d3.ease("cubic-in-out")
  87. d3.timer(function (t) {
  88. if (t >= duration)
  89. return true
  90. var v = interpolate(ease(t / duration))
  91. zoomBehavior.translate([v.x, v.y])
  92. zoomBehavior.scale(v.scale)
  93. panzoom()
  94. return false
  95. })
  96. }
  97. }
  98. function onPanZoom() {
  99. savedPanZoom = {translate: zoomBehavior.translate(),
  100. scale: zoomBehavior.scale()}
  101. panzoom()
  102. }
  103. function panzoom() {
  104. var translate = zoomBehavior.translate()
  105. var scale = zoomBehavior.scale()
  106. panzoomReal(translate, scale)
  107. }
  108. function panzoomReal(translate, scale) {
  109. screenRect = {left: -translate[0] / scale, top: -translate[1] / scale,
  110. right: (canvas.width - translate[0]) / scale,
  111. bottom: (canvas.height - translate[1]) / scale}
  112. requestAnimationFrame(redraw)
  113. }
  114. function getSize() {
  115. var sidebarWidth = sidebar()
  116. var width = el.offsetWidth - sidebarWidth
  117. var height = el.offsetHeight
  118. return [width, height]
  119. }
  120. function panzoomTo(a, b) {
  121. var sidebarWidth = sidebar()
  122. var size = getSize()
  123. var targetWidth = Math.max(1, b[0] - a[0])
  124. var targetHeight = Math.max(1, b[1] - a[1])
  125. var scaleX = size[0] / targetWidth
  126. var scaleY = size[1] / targetHeight
  127. var scaleMax = zoomBehavior.scaleExtent()[1]
  128. var scale = 0.5 * Math.min(scaleMax, Math.min(scaleX, scaleY))
  129. var centroid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]
  130. var x = -centroid[0] * scale + size[0] / 2
  131. var y = -centroid[1] * scale + size[1] / 2
  132. var translate = [x + sidebarWidth, y]
  133. animatePanzoom(translate, scale)
  134. }
  135. function updateHighlight(nopanzoom) {
  136. highlightedNodes = []
  137. highlightedLinks = []
  138. if (highlight !== undefined)
  139. if (highlight.type === "node") {
  140. var n = nodesDict[highlight.o.nodeinfo.node_id]
  141. if (n) {
  142. highlightedNodes = [n]
  143. if (!nopanzoom)
  144. panzoomTo([n.x, n.y], [n.x, n.y])
  145. }
  146. return
  147. } else if (highlight.type === "link") {
  148. var l = linksDict[highlight.o.id]
  149. if (l) {
  150. highlightedLinks = [l]
  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. ctx.save()
  201. ctx.setTransform(1, 0, 0, 1, 0, 0)
  202. ctx.clearRect(0, 0, canvas.width, canvas.height)
  203. ctx.restore()
  204. ctx.save()
  205. ctx.translate(translate[0], translate[1])
  206. ctx.scale(scale, scale)
  207. var clientColor = "rgba(230, 50, 75, 1.0)"
  208. var unknownColor = "#D10E2A"
  209. var nodeColor = "#F2E3C6"
  210. var highlightColor = "rgba(252, 227, 198, 0.15)"
  211. var nodeRadius = 6
  212. // -- draw links --
  213. ctx.save()
  214. links.forEach(function (d) {
  215. var dx = d.target.x - d.source.x
  216. var dy = d.target.y - d.source.y
  217. var a = Math.sqrt(dx * dx + dy * dy)
  218. dx /= a
  219. dy /= a
  220. ctx.beginPath()
  221. ctx.moveTo(d.source.x + dx * nodeRadius, d.source.y + dy * nodeRadius)
  222. ctx.lineTo(d.target.x - dx * nodeRadius, d.target.y - dy * nodeRadius)
  223. ctx.strokeStyle = d.color
  224. ctx.globalAlpha = d.o.vpn ? 0.1 : 0.8
  225. ctx.lineWidth = d.o.vpn ? 1.5 : 2.5
  226. ctx.stroke()
  227. })
  228. ctx.restore()
  229. // -- draw unknown nodes --
  230. ctx.beginPath()
  231. unknownNodes.filter(visibleNodes).forEach(function (d) {
  232. ctx.moveTo(d.x + nodeRadius, d.y)
  233. ctx.arc(d.x, d.y, nodeRadius, 0, 2 * Math.PI)
  234. })
  235. ctx.strokeStyle = unknownColor
  236. ctx.lineWidth = nodeRadius
  237. ctx.stroke()
  238. // -- draw nodes --
  239. ctx.beginPath()
  240. nodes.filter(visibleNodes).forEach(function (d) {
  241. ctx.moveTo(d.x + nodeRadius, d.y)
  242. ctx.arc(d.x, d.y, nodeRadius, 0, 2 * Math.PI)
  243. })
  244. ctx.strokeStyle = nodeColor
  245. ctx.lineWidth = nodeRadius
  246. ctx.stroke()
  247. // -- draw clients --
  248. ctx.save()
  249. ctx.beginPath()
  250. nodes.filter(visibleNodes).forEach(function (d) {
  251. var clients = d.o.node.statistics.clients
  252. if (clients === 0)
  253. return
  254. var startDistance = 16
  255. var radius = 3
  256. var a = 1.2
  257. var startAngle = Math.PI
  258. for (var orbit = 0, i = 0; i < clients; orbit++) {
  259. var distance = startDistance + orbit * 2 * radius * a
  260. var n = Math.floor((Math.PI * distance) / (a * radius))
  261. var delta = clients - i
  262. for (var j = 0; j < Math.min(delta, n); i++, j++) {
  263. var angle = 2 * Math.PI / n * j
  264. var x = d.x + distance * Math.cos(angle + startAngle)
  265. var y = d.y + distance * Math.sin(angle + startAngle)
  266. ctx.moveTo(x, y)
  267. ctx.arc(x, y, radius, 0, 2 * Math.PI)
  268. }
  269. }
  270. })
  271. ctx.fillStyle = clientColor
  272. ctx.globalCompositeOperation = "overlay"
  273. ctx.fill()
  274. ctx.restore()
  275. // -- draw node highlights --
  276. if (highlightedNodes.length) {
  277. ctx.save()
  278. ctx.shadowColor = "rgba(255, 255, 255, 1.0)"
  279. ctx.shadowBlur = 10 * nodeRadius
  280. ctx.shadowOffsetX = 0
  281. ctx.shadowOffsetY = 0
  282. ctx.globalCompositeOperation = "lighten"
  283. ctx.fillStyle = highlightColor
  284. highlightedNodes.forEach(function (d) {
  285. ctx.beginPath()
  286. ctx.moveTo(d.x + 5 * nodeRadius, d.y)
  287. ctx.arc(d.x, d.y, 5 * nodeRadius, 0, 2 * Math.PI)
  288. ctx.fill()
  289. ctx.restore()
  290. })
  291. ctx.restore()
  292. }
  293. // -- draw link highlights --
  294. if (highlightedLinks.length) {
  295. ctx.save()
  296. ctx.lineWidth = 2 * 5 * nodeRadius
  297. ctx.shadowColor = "rgba(255, 255, 255, 1.0)"
  298. ctx.shadowBlur = 10 * nodeRadius
  299. ctx.shadowOffsetX = 0
  300. ctx.shadowOffsetY = 0
  301. ctx.globalCompositeOperation = "lighten"
  302. ctx.strokeStyle = highlightColor
  303. ctx.lineCap = "round"
  304. highlightedLinks.forEach(function (d) {
  305. ctx.beginPath()
  306. ctx.moveTo(d.source.x, d.source.y)
  307. ctx.lineTo(d.target.x, d.target.y)
  308. ctx.stroke()
  309. })
  310. ctx.restore()
  311. }
  312. // -- draw labels --
  313. if (scale > 0.9)
  314. intNodes.filter(visibleNodes).forEach(drawLabel, scale)
  315. ctx.restore()
  316. }
  317. function tickEvent() {
  318. redraw()
  319. }
  320. function resizeCanvas() {
  321. var r = window.devicePixelRatio
  322. canvas.width = el.offsetWidth * r
  323. canvas.height = el.offsetHeight * r
  324. canvas.style.width = el.offsetWidth + "px"
  325. canvas.style.height = el.offsetHeight + "px"
  326. ctx.setTransform(1, 0, 0, 1, 0, 0)
  327. ctx.scale(r, r)
  328. requestAnimationFrame(redraw)
  329. }
  330. function distance(a, b) {
  331. return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)
  332. }
  333. function distancePoint(a, b) {
  334. return Math.sqrt(distance(a, b))
  335. }
  336. function distanceLink(p, a, b) {
  337. /* http://stackoverflow.com/questions/849211 */
  338. var l2 = distance(a, b)
  339. if (l2 === 0)
  340. return distance(p, a)
  341. var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2
  342. if (t < 0)
  343. return distance(p, a)
  344. if (t > 1)
  345. return distance(p, b)
  346. return Math.sqrt(distance(p, { x: a.x + t * (b.x - a.x),
  347. y: a.y + t * (b.y - a.y) }))
  348. }
  349. function translateXY(d) {
  350. var translate = zoomBehavior.translate()
  351. var scale = zoomBehavior.scale()
  352. return {x: (d[0] - translate[0]) / scale,
  353. y: (d[1] - translate[1]) / scale
  354. }
  355. }
  356. function onClick() {
  357. if (d3.event.defaultPrevented)
  358. return
  359. var e = translateXY(d3.mouse(el))
  360. var nodes = intNodes.filter(function (d) {
  361. return distancePoint(e, d) < NODE_RADIUS
  362. })
  363. if (nodes.length > 0) {
  364. router.node(nodes[0].o.node)()
  365. return
  366. }
  367. var links = intLinks.filter(function (d) {
  368. return !d.o.vpn
  369. }).filter(function (d) {
  370. return distanceLink(e, d.source, d.target) < LINE_RADIUS
  371. })
  372. if (links.length > 0) {
  373. router.link(links[0].o)()
  374. return
  375. }
  376. }
  377. function zoom(z, scale) {
  378. var size = getSize()
  379. var newSize = [size[0] / scale, size[1] / scale]
  380. var sidebarWidth = sidebar()
  381. var delta = [size[0] - newSize[0], size[1] - newSize[1]]
  382. var translate = z.translate()
  383. var translateNew = [sidebarWidth + (translate[0] - sidebarWidth - delta[0] / 2) * scale, (translate[1] - delta[1] / 2) * scale]
  384. animatePanzoom(translateNew, z.scale() * scale)
  385. }
  386. function keyboardZoom(z) {
  387. return function () {
  388. var e = d3.event
  389. if (e.altKey || e.ctrlKey || e.metaKey)
  390. return
  391. if (e.keyCode === 43)
  392. zoom(z, 1.41)
  393. if (e.keyCode === 45)
  394. zoom(z, 1 / 1.41)
  395. }
  396. }
  397. el = document.createElement("div")
  398. el.classList.add("graph")
  399. zoomBehavior = d3.behavior.zoom()
  400. .scaleExtent([1 / 3, 3])
  401. .on("zoom", onPanZoom)
  402. .translate([sidebar(), 0])
  403. canvas = d3.select(el)
  404. .attr("tabindex", 1)
  405. .on("keypress", keyboardZoom(zoomBehavior))
  406. .call(zoomBehavior)
  407. .append("canvas")
  408. .on("click", onClick)
  409. .call(draggableNode)
  410. .node()
  411. ctx = canvas.getContext("2d")
  412. force = d3.layout.force()
  413. .charge(-250)
  414. .gravity(0.1)
  415. .linkDistance(function (d) {
  416. if (d.o.vpn)
  417. return 0
  418. else
  419. return LINK_DISTANCE
  420. })
  421. .linkStrength(function (d) {
  422. if (d.o.vpn)
  423. return 0
  424. else
  425. return Math.max(0.5, 1 / d.o.tq)
  426. })
  427. .on("tick", tickEvent)
  428. .on("end", savePositions)
  429. window.addEventListener("resize", resizeCanvas)
  430. panzoom()
  431. self.setData = function (data) {
  432. var oldNodes = {}
  433. intNodes.forEach( function (d) {
  434. oldNodes[d.o.id] = d
  435. })
  436. intNodes = data.graph.nodes.map( function (d) {
  437. var e
  438. if (d.id in oldNodes)
  439. e = oldNodes[d.id]
  440. else
  441. e = {}
  442. e.o = d
  443. return e
  444. })
  445. var newNodesDict = {}
  446. intNodes.forEach( function (d) {
  447. newNodesDict[d.o.id] = d
  448. })
  449. var oldLinks = {}
  450. intLinks.forEach( function (d) {
  451. oldLinks[d.o.id] = d
  452. })
  453. intLinks = data.graph.links.map( function (d) {
  454. var e
  455. if (d.id in oldLinks)
  456. e = oldLinks[d.id]
  457. else
  458. e = {}
  459. e.o = d
  460. e.source = newNodesDict[d.source.id]
  461. e.target = newNodesDict[d.target.id]
  462. if (d.vpn)
  463. e.color = "rgba(255, 255, 255, " + (0.6 / d.tq) + ")"
  464. else
  465. e.color = linkScale(d.tq).hex()
  466. return e
  467. })
  468. linksDict = {}
  469. nodesDict = {}
  470. intNodes.forEach(function (d) {
  471. d.neighbours = {}
  472. if (d.o.node)
  473. nodesDict[d.o.node.nodeinfo.node_id] = d
  474. var name = nodeName(d)
  475. var offset = 5
  476. var lineWidth = 3
  477. var buffer = document.createElement("canvas")
  478. var r = window.devicePixelRatio
  479. var bctx = buffer.getContext("2d")
  480. bctx.font = "11px Roboto"
  481. var width = bctx.measureText(name).width
  482. var scale = zoomBehavior.scaleExtent()[1] * r
  483. buffer.width = (width + 2 * lineWidth) * scale
  484. buffer.height = (16 + 2 * lineWidth) * scale
  485. bctx.scale(scale, scale)
  486. bctx.textBaseline = "middle"
  487. bctx.textAlign = "center"
  488. bctx.fillStyle = "rgba(242, 227, 198, 1.0)"
  489. bctx.shadowColor = "rgba(0, 0, 0, 1)"
  490. bctx.shadowBlur = 5
  491. bctx.fillText(name, buffer.width / (2 * scale), buffer.height / (2 * scale))
  492. d.label = buffer
  493. d.labelWidth = buffer.width / scale
  494. d.labelHeight = buffer.height / scale
  495. d.labelA = offset + buffer.width / (2 * scale)
  496. d.labelB = offset + buffer.height / (2 * scale)
  497. })
  498. intLinks.forEach(function (d) {
  499. d.source.neighbours[d.target.o.id] = {node: d.target, link: d}
  500. d.target.neighbours[d.source.o.id] = {node: d.source, link: d}
  501. if (d.o.source.node && d.o.target.node)
  502. linksDict[d.o.id] = d
  503. })
  504. intNodes.forEach(function (d) {
  505. d.neighbours = Object.keys(d.neighbours).map(function (k) {
  506. return d.neighbours[k]
  507. })
  508. })
  509. nodes = intNodes.filter(function (d) { return d.o.node })
  510. unknownNodes = intNodes.filter(function (d) { return !d.o.node })
  511. if (localStorageTest()) {
  512. var save = JSON.parse(localStorage.getItem("graph/nodeposition"))
  513. if (save) {
  514. var nodePositions = {}
  515. save.forEach( function (d) {
  516. nodePositions[d.id] = d
  517. })
  518. intNodes.forEach( function (d) {
  519. if (nodePositions[d.o.id] && (d.x === undefined || d.y === undefined)) {
  520. d.x = nodePositions[d.o.id].x
  521. d.y = nodePositions[d.o.id].y
  522. }
  523. })
  524. }
  525. }
  526. var diameter = graphDiameter(intNodes)
  527. force.nodes(intNodes)
  528. .links(intLinks)
  529. .size([diameter, diameter])
  530. updateHighlight(true)
  531. force.start()
  532. resizeCanvas()
  533. }
  534. self.resetView = function () {
  535. highlight = undefined
  536. updateHighlight()
  537. doAnimation = true
  538. }
  539. self.gotoNode = function (d) {
  540. highlight = {type: "node", o: d}
  541. updateHighlight()
  542. doAnimation = true
  543. }
  544. self.gotoLink = function (d) {
  545. highlight = {type: "link", o: d}
  546. updateHighlight()
  547. doAnimation = true
  548. }
  549. self.destroy = function () {
  550. force.stop()
  551. canvas.remove()
  552. force = null
  553. if (el.parentNode)
  554. el.parentNode.removeChild(el)
  555. }
  556. self.render = function (d) {
  557. d.appendChild(el)
  558. resizeCanvas()
  559. updateHighlight()
  560. }
  561. return self
  562. }
  563. })