meshviewer/lib/router.js

124 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-03-25 19:25:41 +00:00
define(function () {
2015-03-29 14:14:10 +00:00
return function () {
2015-03-25 19:25:41 +00:00
var objects = { nodes: {}, links: {} }
var targets = []
var self = this
2015-03-29 14:14:10 +00:00
function saveState(d) {
var s = "#!"
if (d) {
if ("node" in d)
s += "n:" + d.node.nodeinfo.node_id
if ("link" in d)
s += "l:" + linkId(d.link)
}
window.history.pushState(s, undefined, s)
}
2015-03-25 19:25:41 +00:00
function resetView(push) {
push = trueDefault(push)
targets.forEach( function (t) {
t.resetView()
})
if (push)
saveState()
}
2015-03-25 19:55:49 +00:00
function gotoNode(d) {
2015-03-25 19:25:41 +00:00
targets.forEach( function (t) {
t.gotoNode(d)
})
}
2015-03-25 19:55:49 +00:00
function gotoLink(d) {
2015-03-25 19:25:41 +00:00
targets.forEach( function (t) {
t.gotoLink(d)
})
}
function loadState(s) {
if (!s)
2015-03-27 21:25:28 +00:00
return false
2015-03-25 19:25:41 +00:00
if (!s.startsWith("#!"))
2015-03-27 21:25:28 +00:00
return false
2015-03-25 19:25:41 +00:00
var args = s.slice(2).split(":")
2015-03-29 14:14:10 +00:00
var id
2015-03-25 19:25:41 +00:00
if (args[0] === "n") {
2015-03-29 14:14:10 +00:00
id = args[1]
2015-03-25 19:25:41 +00:00
2015-03-27 21:25:28 +00:00
if (id in objects.nodes) {
2015-03-25 19:55:49 +00:00
gotoNode(objects.nodes[id])
2015-03-27 21:25:28 +00:00
return true
}
2015-03-25 19:25:41 +00:00
}
if (args[0] === "l") {
2015-03-29 14:14:10 +00:00
id = args[1]
2015-03-25 19:25:41 +00:00
2015-03-27 21:25:28 +00:00
if (id in objects.links) {
2015-03-25 19:55:49 +00:00
gotoLink(objects.links[id])
2015-03-27 21:25:28 +00:00
return true
}
}
return false
}
self.start = function () {
if (!loadState(window.location.hash))
resetView(false)
window.onpopstate = function (d) {
if (!loadState(d.state))
resetView(false)
2015-03-25 19:25:41 +00:00
}
}
2015-03-25 19:55:49 +00:00
self.node = function (d) {
return function () {
gotoNode(d)
saveState({ node: d })
return false
}
}
self.link = function (d) {
return function () {
gotoLink(d)
saveState({ link: d })
return false
}
}
self.reset = function () {
resetView()
saveState()
}
2015-03-25 19:25:41 +00:00
self.addTarget = function (d) { targets.push(d) }
2015-03-29 15:48:25 +00:00
self.setData = function (data) {
2015-03-25 19:25:41 +00:00
objects.nodes = {}
objects.links = {}
2015-03-29 15:48:25 +00:00
data.nodes.all.forEach( function (d) {
2015-03-25 19:25:41 +00:00
objects.nodes[d.nodeinfo.node_id] = d
})
2015-03-29 15:48:25 +00:00
data.links.forEach( function (d) {
2015-03-25 19:25:41 +00:00
objects.links[linkId(d)] = d
})
}
return self
}
})