Introduction
In this tutorial, we will discuss how to manage history in Thinkmap.
This example saves history for different types of graph actions, such as centering and expanding on entities. Moreover, this example uses history to manage other types of events not directly related to graphs, such as layout changes and the current center selection. You can see this in action by changing the layout, expanding entities with a left click, and centering on entities via 'shift-click'. Pressing the back and forward buttons will restore the previous state up until the user navigates away from the page.
How it works
History in Thinkmap works by taking "snapshots" of graphs which are registered with the Thinkmap history manager. These snapshots are just that, a frozen picture in time of the entities belonging to a series of graphs.
Yet there are some limitations with these types of snapshots. Thinkmap only saves history from once the page is loaded until the user navigates away to another site. If the user navigates back to Thinkmap from another site via the browser's history, the graphs are not restored. Since most Thinkmap applications rely on a remote datasource that is loaded asynchronously, snapshots would require serializing this data directly to the client or firing hundreds of queries to restore the graph state. Because of the serious design considerations including memory, security, and stale data, Thinkmap only manages history for when the user is currently using Thinkmap. Once the user navigates away, that history is lost and cannot be restored.
Thinkmap builds upon the history object of HTML5 for managing the different changes that occur to graphs, such as adding and removing entities. As such, it is a good idea to understand the basic API of the HTML5 history object as well as some of its limitations. For a good overview of the history object, please consult the Mozilla Developer Network
Getting Started - Creating a history manager
If you view the source of this page, you will notice that we are linking to two important source files:
The first file is the thinkmap.js file for your project. The second file history-tutorial.js contains
the code for this example, which we will now discuss.
We start first by creating a few graphs and attaching a datasource.
// build three graphs
var graph = new thinkmap.graph.Graph();
var tree = new thinkmap.graph.Tree();
var display = new thinkmap.display.Display(document.getElementById('map'));
// attach a datasource to the main graph
graph.datasource('/moviedb.tas');
The Thinkmap SDK has a history manager which is used to manage all history events in Thinkmap. To create one, we need to pass it a source graph. The source graph is the root graph of an application that is queried directly and typically has a datasource associated with it. In this case, that is the graph variable.
// create the history manager that uses the graph as the source graph and
// manages state for both the display and tree
var historyManager = thinkmap.graph.history.historyManager(graph);
From there, we add graphs that the history manager should manage. We can add any type of graph, even trees - just make sure to not add the source graph by accident.
// add the display to the history manager. This means the displays graph
// state will be saved each time we save history.
historyManager.add(display);
// add the tree as well so it's state will also be saved
historyManager.add(tree);
So let's explain when to add graphs. In most Thinkmap applications, there is almost always a display that visualizes the result of a query. In addition, there can be other graphs that could be of importance, such as trees for maintainting tree layouts for example. As is often the case, these graphs are intertwined (for instance, adding results from a query to both the display and the tree). Since these graphs are directly related, we want their history to be captured at the same time. Hence we add them directly to the history manager, so when we create snapshots, both of their snapshots will be taken at the exact same time.
Creating History States
The most simple way generate a history event for a Thinkmap application is to call historyManager.pushState()
This method is analagous to the history.pushState() method of HTML5 with the exception that Thinkmap does some extra plumbing behind the scenes for graphs.
Although the historyManager.pushState() method can be called at any time, it is typically only called during the .oncomplete() event of a query like so:
graph.query(['node','edge','node'])
.execute(entity)
.onresult(display.add)
.onresult(tree.add)
.oncomplete(function() {
historyManager.pushState();
});
In this case, during the query we are adding results to both the display and the tree. However, we only want to save the state once the query completes.
For this example, rather than call historyManager.pushState, we have a function called createHistory that is called for any type of history event we want to save. This allows us
to manage what is saved during history in a central place and will make more sense later. With that said, here are the two methods for centering and expanding:
function makeCenter(ent) {
......
.....
return graph.query({$choice:[
['movie','edge','person'],
['person','edge','movie']
]})
.execute(entity)
.onresult(display.add) // add results to the display
.onresult(tree.add) // also add results to the tree
.oncomplete(function(results) {
// remove everything but the results
display.retainOnly(results);
// make the display layout
display.layout();
// scroll to the entity so it is in the center
display.transition().scrollTo(entity);
// create a history event
createHistory();
});
}
// handles expanding when nodes are clicked
function expand(entity) {
// store the current size of the display
var originalSize = display.size();
graph.query({$choice:[
['movie','edge','person'],
['person','edge','movie']
]})
.execute(entity)
.onresult(display.add)
.onresult(tree.add)
.onresult(display.layout)
.oncomplete(function(results) {
// only create a history state if the expand actually
// resulted in new entities being added
if(display.size() > originalSize) {
createHistory();
}
});
}
Adding additional state information
We covered the most simple case for saving basic snapshots of graph. In the example above, these snapshots can be navigated with the back and forward buttons until the user navigates away from the page.
Now what if we want to save some extra information, such as what is the center entity and the current layout? This is done via an optional state object passed to the historyManager.pushState method.
var state = {};
state.someHistoryProperty = ...
historyManager.pushState(state);
This state object can store any type of data as long as its key/values can be serialized as strings, as this is a requirement from the Browser when saving history. In our example, we use this state object when creating history states to save our center entity and layout.
// creates a history state
function createHistory() {
// This is an optional state object which will store some
// extra history information. In this case, we want to store
// the center entity's id and the current layout so we can
// adjust the display correctly each time a history
// event is created.
var state = {};
// store the layout and the center entity in the state object
state.layout = treeLayout.enabled() ? 'tree' : 'spider';
state.centerEntityId = centerSelection.first().id;
//push the history state
historyManager.pushState(state);
}
Because we save this additional history information, we can call the createHistory function in other places, like when we change layouts for instance.
// changes the layout - this pushes a history state event
function changeLayout() {
// get the values of the select menus
var layoutStyle = document.getElementById('layoutStyle').value;
// sets the layout
setLayout(layoutStyle);
// create a history state each time we change the layout
createHistory();
// call layout so the new layout will be recognized
display.layout();
}
Now that we are storing this additional history information, we need to actually restore it as well.
Restoring Custom History data
Any time we wish to restore any data that is not related specifically to graph snapshots, we need to register a popstate listener on our history manager.
// add an event listener for when states are restored so we can do
// some extra work
historyManager.addEventListener('popstate', restoreHistory);
By registering a restoreHistory function, we can access the state object we saved earlier in our createHistory method.
// this function is called each time a history state
// is restored via the history popstate event
// listener we registered earlier
function restoreHistory(data){
// get the state object that has our additional state
// information
var state = data.state;
// get the stored layout in the state object
var storedLayout = state.layout;
// get the stored center entity of the state object
var storedCenter = display.byId(state.centerEntityId);
// set the layout to the stored layout
setLayout(storedLayout);
// If the stored center doesn't match the current center
// than create a new center selection and scroll
// to the entity.
if (!centerSelection.contains(storedCenter)) {
centerSelection.release();
centerSelection = display.select(storedCenter).freeze();
display.transition().scrollTo(storedCenter);
}
display.layout();
}
Notice that for the center entity, we stored the id and not the actual entity. This gets back to how the state object can only serialize strings. Trying to store the entity in the state object will result in an error. Therefore, we use the id to get the entity from the display when trying to restore the center selection.
Best Practices - not creating history from history
When looking over the code for changing layouts and restoring history, you may have noticed that both functions call a separate function setLayout. However, why not just have
restore history call changeLayout directly? Why the need for a separate function?
The reason for two functions that call a single setLayout function is because we want one method changeLayout to generate a history event but we don't want a new history
event to be created each time we do a restore. This is a common design paradigm when using history in a Thinkmap application. Here is the setLayout method:
// sets the layout and changes the displays edge style depending on
// which layout is chosen
function setLayout(layout) {
// choose the correct edge style based on the edgeStyle value
if (layout == 'spider' && treeLayout.enabled()) {
spiderLayout.enabled(true);
treeLayout.enabled(false);
display.template('edge').as(thinkmap.display.edgestyle.linear());
} else if (layout == 'tree' && spiderLayout.enabled()) {
treeLayout.enabled(true);
spiderLayout.enabled(false);
display.template('edge').as(thinkmap.display.edgestyle.curved());
}
// Ensure that the value of the layoutstyle is set. This is a bit
// redundant but because this method is also called when restoring
// history, we need to make sure the value is set correctly.
document.getElementById('layoutStyle').value = layout;
}
Notice that we are also changing the layoutStyle's value as well so it matches the layout. This allows our UI elements to also reflect the change in history. Without doing this, our UI and our model would not be in a consistent state.
Summary
That concludes this tutorial. To summarize, we covered how to manage history for graphs in Thinkmap. Moreover, we covered how to leverage Thinkmap's history for other types of events not directly related to graphs.