4
0

router.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 false
  37. if (!s.startsWith("#!"))
  38. return false
  39. var args = s.slice(2).split(":")
  40. if (args[0] === "n") {
  41. var id = args[1]
  42. if (id in objects.nodes) {
  43. gotoNode(objects.nodes[id])
  44. return true
  45. }
  46. }
  47. if (args[0] === "l") {
  48. var id = args[1]
  49. if (id in objects.links) {
  50. gotoLink(objects.links[id])
  51. return true
  52. }
  53. }
  54. return false
  55. }
  56. self.start = function () {
  57. if (!loadState(window.location.hash))
  58. resetView(false)
  59. window.onpopstate = function (d) {
  60. if (!loadState(d.state))
  61. resetView(false)
  62. }
  63. }
  64. self.node = function (d) {
  65. return function () {
  66. gotoNode(d)
  67. saveState({ node: d })
  68. return false
  69. }
  70. }
  71. self.link = function (d) {
  72. return function () {
  73. gotoLink(d)
  74. saveState({ link: d })
  75. return false
  76. }
  77. }
  78. self.reset = function () {
  79. resetView()
  80. saveState()
  81. }
  82. self.addMarkers = function (d) {
  83. markers = d
  84. }
  85. self.addTarget = function (d) { targets.push(d) }
  86. self.setData = function (nodes, links) {
  87. objects.nodes = {}
  88. objects.links = {}
  89. nodes.forEach( function (d) {
  90. objects.nodes[d.nodeinfo.node_id] = d
  91. })
  92. links.forEach( function (d) {
  93. objects.links[linkId(d)] = d
  94. })
  95. }
  96. return self
  97. }
  98. })