Spacetree.js

Implements the ST class and other derived classes.

Description

The main idea of the spacetree algorithm is to take the most common tree layout, and to expand nodes that are “context-related” .i.e lying on the path between the root node and a selected node.  Useful animations to contract and expand nodes are also included.

Inspired by

SpaceTree: Supporting Exploration in Large Node Link Tree, Design Evolution and Empirical Evaluation (Catherine Plaisant, Jesse Grosjean, Benjamin B.  Bederson)

http://hcil.cs.umd.edu/trs/2002-05/2002-05.pdf

Disclaimer

This visualization was built from scratch, taking only the paper as inspiration, and only shares some features with the Spacetree.

Summary
Spacetree.jsImplements the ST class and other derived classes.
STThe main ST class
Functions
plotPlots the tree.
switchPositionSwitches the tree orientation.
switchAlignmentSwitches the tree alignment.
addNodeInPathAdds a node to the current path as selected node.
clearNodesInPathRemoves all nodes tagged as selected by the ST.addNodeInPath method.
refreshComputes nodes’ positions and replots the tree.
computeComputes nodes’ positions.
setRootSwitches the current root node.
addSubtreeAdds a subtree, performing optionally an animation.
removeSubtreeRemoves a subtree, performing optionally an animation.
selectSelects a sepecific node in the Spacetree without performing an animation.
onClickThis method is called when clicking on a tree node.
ST.OpPerforms advanced operations on trees and graphs.
ST.GeomPerforms low level geometrical computations.
Functions
translateApplies a translation to the tree.
getEdgeReturns a Complex instance with the begin or end position of the edge to be plotted.
treeFitsInCanvasReturns a Boolean if the current subtree fits in canvas.
ST.PlotPerforms plotting operations.
Functions
placeLabelOverrides abstract method placeLabel in Graph.Plot.
ST.Plot.NodeTypesHere are implemented all kinds of node rendering functions.
ST.Plot.EdgeTypesHere are implemented all kinds of edge rendering functions.

ST

The main ST class

Extends

Loader

Parameters

canvasA Canvas Class
configA configuration/controller object.

Configuration

The configuration object can have the following properties (all properties are optional and have a default value)

General

  • levelsToShow Depth of the plotted tree.  The plotted tree will be pruned in order to fit the specified depth if constrained=true.  Default’s 2.
  • constrained If true, the algorithm will try to plot only the part of the tree that fits the Canvas.
  • subtreeOffset Separation offset between subtrees.  Default’s 8.
  • siblingOffset Separation offset between siblings.  Default’s 5.
  • levelDistance Distance between levels.  Default’s 30.
  • orientation Sets the orientation layout.  Implemented orientations are left (the root node will be placed on the left side of the screen), top (the root node will be placed on top of the screen), bottom and right.  Default’s “left”.
  • align Whether the tree alignment is left, center or right.
  • indent Used when alignment is left or right and shows an indentation between parent and children.  Default’s 10.
  • withLabels Whether the visualization should use/create labels or not.  Default’s true.

Node

Customize the visualization nodes’ shape, color, and other style properties.

  • Node

This object has as properties

  • overridable Determine whether or not nodes properties can be overriden by a particular node.  Default’s false.

If given a JSON tree or graph, a node data property contains properties which are the same as defined here but prefixed with a dollar sign (i.e $), the node properties will override the global node properties.

  • type Node type (shape).  Possible options are “none”, “square”, “rectangle”, “ellipse” and “circle”.  Default’s “rectangle”.
  • color Node color.  Default’s ‘#ccb’.
  • lineWidth Line width.  If nodes aren’t drawn with strokes then this property won’t be of any use.  Default’s 1.
  • height Node height.  Used for plotting rectangular nodes.  Width and height properties are also used as bounding box for nodes of different shapes.  This means that for all shapes you’d have to make sure that the node’s shape is contained in the bounding box defined by width and height parameters.  Default’s 20.
  • width Node width.  Used for plotting rectangular nodes and for calculating a node’s bounding box.  Default’s 90.
  • dim An extra parameter used by other complex shapes such as square and circle to determine the shape’s diameter.  Please notice that even if these complex shapes (square, circle) only use dim for calculating it’s diameter property, the complex shape must be contained in the bounding box calculated with the width and height parameters.  Default’s 15.
  • align Defines a node’s alignment.  Possible values are “center”, “left”, “right”.  Default’s “center”.

Edge

Customize the visualization edges’ shape, color, and other style properties.

  • Edge

This object has as properties

  • overridable Determine whether or not edges properties can be overriden by a particular edge object.  Default’s false.

If given a JSON complex graph (defined in Loader.loadJSON), an adjacency data property contains properties which are the same as defined here but prefixed with a dollar sign (i.e $), the adjacency properties will override the global edge properties.

  • type Edge type (shape).  Possible options are “none”, “line”, “quadratic:begin”, “quadratic:end”, “bezier” and “arrow”.  Default’s “line”.
  • color Edge color.  Default’s ‘#ccb’.
  • lineWidth Line width.  If edges aren’t drawn with strokes then this property won’t be of any use.  Default’s 1.
  • dim An extra parameter used by other complex shapes such as quadratic, arrow and bezier to determine the shape’s diameter.

Animations

  • duration Duration of the animation in milliseconds.  Default’s 700.
  • fps Frames per second.  Default’s 25.
  • transition One of the transitions defined in the Animation class.  Default’s Quart.easeInOut.
  • clearCanvas Whether to clear canvas on each animation frame or not.  Default’s true.

Controller options

You can also implement controller functions inside the configuration object.  This functions are

  • onBeforeCompute(node) This method is called right before performing all computation and animations to the JIT visualization.
  • onAfterCompute() This method is triggered right after all animations or computations for the JIT visualizations ended.
  • onCreateLabel(domElement, node) This method receives the label dom element as first parameter, and the corresponding Graph.Node as second parameter.  This method will only be called on label creation.  Note that a Graph.Node is a node from the input tree/graph you provided to the visualization.  If you want to know more about what kind of JSON tree/graph format is used to feed the visualizations, you can take a look at Loader.loadJSON.  This method proves useful when adding events to the labels used by the JIT.
  • onPlaceLabel(domElement, node) This method receives the label dom element as first parameter and the corresponding Graph.Node as second parameter.  This method is called each time a label has been placed on the visualization, and thus it allows you to update the labels properties, such as size or position.  Note that onPlaceLabel will be triggered after updating the labels positions.  That means that, for example, the left and top css properties are already updated to match the nodes positions.
  • onBeforePlotNode(node) This method is triggered right before plotting a given node.  The node parameter is the Graph.Node to be plotted.  This method is useful for changing a node style right before plotting it.
  • onAfterPlotNode(node) This method is triggered right after plotting a given node.  The node parameter is the Graph.Node plotted.
  • onBeforePlotLine(adj) This method is triggered right before plotting an edge.  The adj parameter is a Graph.Adjacence object.  This method is useful for adding some styles to a particular edge before being plotted.
  • onAfterPlotLine(adj) This method is triggered right after plotting an edge.  The adj parameter is the Graph.Adjacence plotted.
  • request(nodeId, level, onComplete) This method is used for buffering information into the visualization.  When clicking on an empty node, the visualization will make a request for this node’s subtree, specifying a given level for this subtree.  Once this request is completed the onComplete object must be called with the given result.

Example

Here goes a complete example.  In most cases you won’t be forced to implement all properties and methods.  In fact, all configuration properties have the default value assigned.

I won’t be instanciating a Canvas class here.  If you want to know more about instanciating a Canvas class please take a look at the Canvas class documentation.

var st = new ST(canvas, {
  orientation: "left",
  levelsToShow: 2,
  subtreeOffset: 8,
  siblingOffset: 5,
  levelDistance: 30,
  withLabels: true,
  align: "center",
  multitree: false,
  indent: 10,
  Node: {
    overridable: false,
    type: 'rectangle',
    color: '#ccb',
    lineWidth: 1,
    height: 20,
    width: 90,
    dim: 15,
    align: "center"
  },
  Edge: {
    overridable: false,
    type: 'line',
    color: '#ccc',
    dim: 15,
    lineWidth: 1
  },
  duration: 700,
  fps: 25,
  transition: Trans.Quart.easeInOut,
  clearCanvas: true,

  onBeforeCompute: function(node) {
    //do something onBeforeCompute
  },
  onAfterCompute:  function () {
    //do something onAfterCompute
  },
  onCreateLabel:   function(domElement, node) {
    //do something onCreateLabel
  },
  onPlaceLabel:    function(domElement, node) {
    //do something onPlaceLabel
  },
  onBeforePlotNode:function(node) {
    //do something onBeforePlotNode
  },
  onAfterPlotNode: function(node) {
    //do something onAfterPlotNode
  },
  onBeforePlotLine:function(adj) {
    //do something onBeforePlotLine
  },
  onAfterPlotLine: function(adj) {
    //do something onAfterPlotLine
  },
  request:         false

});

Instance Properties

  • graph Access a Graph instance.
  • op Access a ST.Op instance.
  • fx Access a ST.Plot instance.
Summary
Functions
plotPlots the tree.
switchPositionSwitches the tree orientation.
switchAlignmentSwitches the tree alignment.
addNodeInPathAdds a node to the current path as selected node.
clearNodesInPathRemoves all nodes tagged as selected by the ST.addNodeInPath method.
refreshComputes nodes’ positions and replots the tree.
computeComputes nodes’ positions.
setRootSwitches the current root node.
addSubtreeAdds a subtree, performing optionally an animation.
removeSubtreeRemoves a subtree, performing optionally an animation.
selectSelects a sepecific node in the Spacetree without performing an animation.
onClickThis method is called when clicking on a tree node.

Functions

plot

plot: function()

Plots the tree.  Usually this method is called right after computing nodes’ positions.

switchPosition

switchPosition: function(pos,
method,
onComplete)

Switches the tree orientation.

Parameters

posThe new tree orientation.  Possible values are “top”, “left”, “right” and “bottom”.
methodSet this to “animate” if you want to animate the tree when switching its position.  You can also set this parameter to “replot” to just replot the subtree.
onCompleteoptional This callback is called once the “switching” animation is complete.

Example

st.switchPosition("right", "animate", {
 onComplete: function() {
   alert('completed!');
 }
});

switchAlignment

switchAlignment: function(align,
method,
onComplete)

Switches the tree alignment.

Parameters

alignThe new tree alignment.  Possible values are “left”, “center” and “right”.
methodSet this to “animate” if you want to animate the tree after aligning its position.  You can also set this parameter to “replot” to just replot the subtree.
onCompleteoptional This callback is called once the “switching” animation is complete.

Example

st.switchAlignment("right", "animate", {
 onComplete: function() {
   alert('completed!');
 }
});

addNodeInPath

addNodeInPath: function(id)

Adds a node to the current path as selected node.  This node will be visible (as in non-collapsed) at all times.

Parameters

idA Graph.Node id.

Example

st.addNodeInPath("somenodeid");

clearNodesInPath

clearNodesInPath: function(id)

Removes all nodes tagged as selected by the ST.addNodeInPath method.

See also

ST.addNodeInPath

Example

st.clearNodesInPath();

refresh

refresh: function()

Computes nodes’ positions and replots the tree.

compute

compute: function (property,
computeLevels)

Computes nodes’ positions.

setRoot

setRoot: function(id,
method,
onComplete)

Switches the current root node.

Parameters

idThe id of the node to be set as root.
methodSet this to “animate” if you want to animate the tree after adding the subtree.  You can also set this parameter to “replot” to just replot the subtree.
onCompleteoptional An action to perform after the animation (if any).

Example

st.setRoot('my_node_id', 'animate', {
   onComplete: function() {
     alert('complete!');
   }
});

addSubtree

addSubtree: function(subtree,
method,
onComplete)

Adds a subtree, performing optionally an animation.

Parameters

subtreeA JSON Tree object.  See also Loader.loadJSON.
methodSet this to “animate” if you want to animate the tree after adding the subtree.  You can also set this parameter to “replot” to just replot the subtree.
onCompleteoptional An action to perform after the animation (if any).

Example

st.addSubtree(json, 'animate', {
   onComplete: function() {
     alert('complete!');
   }
});

removeSubtree

removeSubtree: function(id,
removeRoot,
method,
onComplete)

Removes a subtree, performing optionally an animation.

Parameters

idThe id of the subtree to be removed.
removeRootRemove the root of the subtree or only its subnodes.
methodSet this to “animate” if you want to animate the tree after removing the subtree.  You can also set this parameter to “replot” to just replot the subtree.
onCompleteoptional An action to perform after the animation (if any).

Example

st.removeSubtree('idOfSubtreeToBeRemoved', false, 'animate', {
  onComplete: function() {
    alert('complete!');
  }
});

select

select: function(id,
onComplete)

Selects a sepecific node in the Spacetree without performing an animation.  Useful when selecting nodes which are currently hidden or deep inside the tree.

Parameters

idThe id of the node to select.
onCompleteoptional onComplete callback.

Example

st.select('mynodeid', {
  onComplete: function() {
    alert('complete!');
  }
});

onClick

onClick: function (id,
options)

This method is called when clicking on a tree node.  It mainly performs all calculations and the animation of contracting, translating and expanding pertinent nodes.

Parameters

idA node id.
optionsA group of options and callbacks such as
  • onComplete an object callback called when the animation finishes.
  • Move an object that has as properties offsetX or offsetY for adding some offset position to the centered node.

Example

st.onClick('mynodeid', {
    Move: {
      enable: true,
      offsetX: 30,
      offsetY: 5
    },
    onComplete: function() {
        alert('yay!');
    }
});

ST.Op

Performs advanced operations on trees and graphs.

Extends

All Graph.Op methods

Access

This instance can be accessed with the op parameter of the st instance created.

Example

var st = new ST(canvas, config);
st.op.morph //or can also call any other <Graph.Op> method

ST.Geom

Performs low level geometrical computations.

Access

This instance can be accessed with the geom parameter of the st instance created.

Example

var st = new ST(canvas, config);
st.geom.translate //or can also call any other <ST.Geom> method
Summary
Functions
translateApplies a translation to the tree.
getEdgeReturns a Complex instance with the begin or end position of the edge to be plotted.
treeFitsInCanvasReturns a Boolean if the current subtree fits in canvas.

Functions

translate

translate: function(pos,
prop)

Applies a translation to the tree.

Parameters

posA Complex number specifying translation vector.
propA Graph.Node position property (‘pos’, ‘startPos’ or ‘endPos’).

Example

st.geom.translate(new Complex(300, 100), 'endPos');

getEdge

getEdge: function(node,
type,
s)

Returns a Complex instance with the begin or end position of the edge to be plotted.

Parameters

nodeA Graph.Node that is connected to this edge.
typeReturns the begin or end edge position.  Possible values are ‘begin’ or ‘end’.

Returns

A Complex number specifying the begin or end position.

treeFitsInCanvas

treeFitsInCanvas: function(node,
canvas,
level)

Returns a Boolean if the current subtree fits in canvas.

Parameters

nodeA Graph.Node which is the current root of the subtree.
canvasThe Canvas object.
levelThe depth of the subtree to be considered.

ST.Plot

Performs plotting operations.

Extends

All Graph.Plot methods

Access

This instance can be accessed with the fx parameter of the st instance created.

Example

var st = new ST(canvas, config);
st.fx.placeLabel //or can also call any other <ST.Plot> method
Summary
Functions
placeLabelOverrides abstract method placeLabel in Graph.Plot.

Functions

placeLabel

placeLabel: function(tag,
node,
controller)

Overrides abstract method placeLabel in Graph.Plot.

Parameters

tagA DOM label element.
nodeA Graph.Node.
controllerA configuration/controller object passed to the visualization.

ST.Plot.NodeTypes

Here are implemented all kinds of node rendering functions.  Rendering functions implemented are ‘none’, ‘circle’, ‘ellipse’, ‘rectangle’ and ‘square’.

You can add new Node types by implementing a new method in this class

Example

ST.Plot.NodeTypes.implement({
  'newnodetypename': function(node, canvas) {
    //Render my node here.
  }
});

ST.Plot.EdgeTypes

Here are implemented all kinds of edge rendering functions.  Rendering functions implemented are ‘none’, ‘line’, ‘quadratic:begin’, ‘quadratic:end’, ‘bezier’ and ‘arrow’.

You can add new Edge types by implementing a new method in this class

Example

ST.Plot.EdgeTypes.implement({
  'newedgetypename': function(adj, canvas) {
    //Render my edge here.
  }
});
The main ST class
plot: function()
Plots the tree.
switchPosition: function(pos,
method,
onComplete)
Switches the tree orientation.
switchAlignment: function(align,
method,
onComplete)
Switches the tree alignment.
addNodeInPath: function(id)
Adds a node to the current path as selected node.
clearNodesInPath: function(id)
Removes all nodes tagged as selected by the ST.addNodeInPath method.
refresh: function()
Computes nodes’ positions and replots the tree.
compute: function (property,
computeLevels)
Computes nodes’ positions.
setRoot: function(id,
method,
onComplete)
Switches the current root node.
addSubtree: function(subtree,
method,
onComplete)
Adds a subtree, performing optionally an animation.
removeSubtree: function(id,
removeRoot,
method,
onComplete)
Removes a subtree, performing optionally an animation.
select: function(id,
onComplete)
Selects a sepecific node in the Spacetree without performing an animation.
onClick: function (id,
options)
This method is called when clicking on a tree node.
translate: function(pos,
prop)
Applies a translation to the tree.
getEdge: function(node,
type,
s)
Returns a Complex instance with the begin or end position of the edge to be plotted.
treeFitsInCanvas: function(node,
canvas,
level)
Returns a Boolean if the current subtree fits in canvas.
placeLabel: function(tag,
node,
controller)
Overrides abstract method placeLabel in Graph.Plot.
Generic Graph rendering and animation methods.
Provides static methods for loading JSON data.
A multi-purpose Canvas Class.
loadJSON: function(json,
i)
Loads a JSON structure to the visualization.
A Class that can perform animations for generic objects.
A Graph node.
A Graph adjacence (or edge).
A generic Graph class.
Performs advanced operations on trees and graphs.
Performs plotting operations.
Generic Graph Operations.
A multi-purpose Complex Class with common methods.
Close