router.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. define(function () {
  2. return function (config) {
  3. var objects = { nodes: {}, links: {} }
  4. var targets = []
  5. var self = this
  6. function resetView(push) {
  7. push = trueDefault(push)
  8. targets.forEach( function (t) {
  9. t.resetView()
  10. })
  11. if (push)
  12. saveState()
  13. }
  14. function gotoNode(d) {
  15. targets.forEach( function (t) {
  16. t.gotoNode(d)
  17. })
  18. }
  19. function gotoLink(d) {
  20. targets.forEach( function (t) {
  21. t.gotoLink(d)
  22. })
  23. }
  24. function saveState(d) {
  25. var s = "#!"
  26. if (d) {
  27. if ("node" in d)
  28. s += "n:" + d.node.nodeinfo.node_id
  29. if ("link" in d)
  30. s += "l:" + linkId(d.link)
  31. }
  32. window.history.pushState(s, undefined, s)
  33. }
  34. function loadState(s) {
  35. if (!s)
  36. return
  37. if (!s.startsWith("#!"))
  38. return
  39. var args = s.slice(2).split(":")
  40. if (args.length == 1 && args[0] == "")
  41. resetView(false)
  42. if (args[0] === "n") {
  43. var id = args[1]
  44. if (id in objects.nodes)
  45. gotoNode(objects.nodes[id])
  46. }
  47. if (args[0] === "l") {
  48. var id = args[1]
  49. if (id in objects.links)
  50. gotoLink(objects.links[id])
  51. }
  52. }
  53. self.node = function (d) {
  54. return function () {
  55. gotoNode(d)
  56. saveState({ node: d })
  57. return false
  58. }
  59. }
  60. self.link = function (d) {
  61. return function () {
  62. gotoLink(d)
  63. saveState({ link: d })
  64. return false
  65. }
  66. }
  67. self.reset = function () {
  68. resetView()
  69. saveState()
  70. }
  71. self.addMarkers = function (d) {
  72. markers = d
  73. }
  74. self.addTarget = function (d) { targets.push(d) }
  75. self.loadState = loadState
  76. self.setData = function (nodes, links) {
  77. objects.nodes = {}
  78. objects.links = {}
  79. nodes.forEach( function (d) {
  80. objects.nodes[d.nodeinfo.node_id] = d
  81. })
  82. links.forEach( function (d) {
  83. objects.links[linkId(d)] = d
  84. })
  85. }
  86. window.onpopstate = function (d) { loadState(d.state) }
  87. return self
  88. }
  89. })