Expand and Collapse

How to implement the expanding and collapsing of entities

Introduction

This tutorial covers how to use the Expand Manager in Thinkmap to manage the incremental expansion and collapse of entities in a graph.

This expand and collapse example allows centering, expanding, and collapsing. You can center an entity by "Shift-clicking". You can expand any entity by clicking it. If an entity is expanded, it will then be collapsed. This example also uses a history manager so you can undo the expand and collapses by using the back and forward buttons.

All of the source code for this example is contained in the expand.js file. This example will only exclusively focus on how to use expand and collapse. The example won't cover details of a double tree, display, history, queries and futures, all of which are described in other examples.

Declaring the needed graphs and trees

This example builds off the trees and graphs template which uses two trees that move in opposite directions

		// build three graphs
	    var graph = new thinkmap.graph.Graph();
	    var display = new thinkmap.display.Display(document.getElementById('map'));
	    
	    // attach a datasource to the main graph
	    graph.datasource('/moviedb.tas');
	    
	    // define a root variable which will be the root of the two trees 
	    var root = null;
	    // create a right tree which will store movies and people	
	    var rightTree = new thinkmap.graph.Tree();
	    // create a left tree which will store movies and genres
	    var leftTree = new thinkmap.graph.Tree();
	    // create a left layout that is bound to the left tree
	    var leftLayout = thinkmap.layout.treeLayout(display)
	    								.tree(leftTree)
	    								.spacing(-200);
	    // create a right layout that is bound to the right tree
	    var rightLayout = thinkmap.layout.treeLayout(display)
	    								 .tree(rightTree)
	    								 .spacing(200);
	      	

Now we create the history manager and two expand managers for each respective side of the graph

	        // construct a history manager (this is optional but a nice feature)
		    var historyManager = new thinkmap.graph.history.HistoryManager(graph)
		    							.add(display).add(leftTree).add(rightTree);
		    
		    // make two expands - one for each direction, pass in the history manager
		    // so the expanders will become history aware
		    var expandRight = new thinkmap.graph.expand.ExpandManager(graph,historyManager)
		    							.add(display).add(rightTree);
		    var expandLeft = new thinkmap.graph.expand.ExpandManager(graph,historyManager)
		    							.add(display).add(leftTree);
	      	

For most examples, we don't need two expand managers. However, because this example uses two trees that move in opposite directions and work on different entities, two of them are needed.

Calling Expand

The way the ExpandManager works is you pass the entity that has been expanded and a graph the represents the entities that are part of the expand. The general order of operations is you run a query, and with the results of the query, you call expand(entity,results)

	       	graph.query(...).execute(entity)	
	       		.onresult(display.add)
	       		.onresult(tree.add)
	       		.oncomplete(function(results){
	       			// expand	
	       			expandManager.expand(entity, results);	
	       			// create a history state
	       			historyManager.pushState();
	       		}); 
	       	

Now the above works for both centering and expanding an entity. The entry point is always the expand method. However, when you wish to start over, such as in centering we clear the expanded entities for the manager. Here is how we implement the makeCenter function for our example:

	function makeCenter(entity) {
    	// return if entity is undefined or equal to the current root or not
    	// a movie
        if (!entity || root === entity || !entity.isType('movie')) return;
        // set the root to the new entity
        root = entity;
        // Setting the NEW root on the two trees will remove all nodes
        // in those trees and will be left with just the single root.
        leftTree.root(root);
        rightTree.root(root);
        // add the root to the display
        display.add(root);
        
        // clear both expand managers when centering 
        // because we want to start from scratch
        expandLeft.clear();
        expandRight.clear();

        // Because the two queries are run asynchronously, we can't
        // remove entities from the display until both queries complete. 
        // Since both queries return a future, we wrap them into a single
        // future. When both queries are complete, our wrapped future completes
        // and we cleanup the display and then focus on the root entity
        thinkmap.async.all(
	        // both queries return a future
		    leftQuery(entity), rightQuery(entity)
        )
        .then(function(leftResults, rightResults){

        	// call expand on each expand manager with the appropriate results
        	expandLeft.expand(entity, leftResults);
        	expandRight.expand(entity, rightResults);
        	
        	display.retainOnly(leftResults.select().union(rightResults.select()));
        	
        	// create a history state
        	historyManager.pushState();
        
        })
        .then(focusEntity);
    }
	       	

Notice that before we execute the query, we clear the expandLeft and expandRight managers. Then we call the expand methods with their respective arguments.

Expand and Collapse

Expanding and collapsing an entity can be done in just a couple of lines of code

First, to check if an entity is expanded

expandManager.isExpanded(entity);

When expanding an entity, we pass the entity AND THE RESULTS from a query representing the expand

expandManager.expand(entity, results);

Collapsing an entity is simple

expandManager.collapse(entity);

In its more complete form, and expand and collapse would look like this

	   	// can't expand a center
	   	if (entity === center) return;
	   	if(!expandManager.isExpanded(entity)) {
	   		var size = display.size();
	   		graph.query(....).execute(entity)
	   			 .onresult(display.add)	
	   			 .onresult(tree.add)	
	   			 .oncomplete(function(results) {
	   				if (display.size() > size) { //new results were added
	   					//mark the expansion for the entity and results	
	   					expandManager.expand(entity, results); 
	   					// we use a history manager for undoing expand/collapse
	   					// so push a history state	
	   					historyManager.pushState();
	   				}	
	   			 });	
	   	
	   	} else {
	   		//entity is expanded	
	   		expandManager.collapse(entity);
	   		//push a history state
	   		historyManager.pushState(entity);
	   	}
	   	

Putting it all together

The example is a little more complicated because we need two expand managers because we have two trees moving in opposite directions that use different queries and entities.

Therefore, the expand needs to verify which tree the given entity is contained in, and then work out the expand and collapse code. Here is the expand method:

	 // depending on what tree the expanded node is in, we 
	// call doExpand with the appropriate expander and query
    function expand(entity) {
    	// don't allow expansion of the center entity
    	if (entity === root) return;
    	if (rightTree.contains(entity)){
    		doExpand(entity, expandRight, rightQuery);
    	} else {
    		doExpand(entity, expandLeft, leftQuery);
    	}
    }
    
    function doExpand(entity, expander, query) {
    	// collapse if already expanded
    	if(expander.isExpanded(entity)) {
    		expander.collapse(entity);
    		display.layout();
    		historyManager.pushState();
    	} else {
    		var size = display.size();
    		query(entity).then(function(results){
    		// else, mark an expand after doing the query
    		// only if the size changed (new results were added to the display)
    			if (display.size() > size) {
    				expander.expand(entity,results);
    				historyManager.pushState();
    			}
    		});
    	}
    }
	    

Now all that is needed to do is add the appropriate display listeners that call the center and expand functions.

	   	display.addEventListener('click',function(evt) {
            var entity = evt.entity;
            if (entity.isType('edge')) return;
            if (evt.button == 0) {
                if (evt.shiftKey) {
                    makeCenter(entity);
                } else {
                	expand(entity);
                }
            }
        });