All versions of this documentation
X

Initializing Ogma

Ogma methods

  • ogma.clear()

    Reset all modules to their original state.

  • ogma.kill()

    Kill the Ogma instance, releasing the used memory.

Ogma method aliases

Ogma attribute aliases

Data structures

Each section indicates the name of a data structure, and its architecture.

animations module

Module in charge of handling animations.

var animations = ogma.animations;

animations methods

  • play(func, [options])

    Start playing an animation.

    Arguments

    • func (EasingFunction):

      Function that will be called at each frame. It takes one argument: a number from 0 to 1, indicating the progression of the animation (0 = begin, 1 = end).

    • options (optional, object)
      • duration (optional, number, default: 0):

        Duration in milliseconds of the animation. If 0, func is immediately called with a parameter of 1.

      • easing (optional, EasingFunction|string, default: 'linear'):

        Easing function, or string referencing a registered one. See the easing section to have the full list.

      • callback (optional, function(): void):

        Function that will be called when the animation finishes.

      • startAfter (optional, number, default: 0):

        Progression (from 0 to 1) after which the animation must be started. For example, specifying 0.5 would cause the animation to start after half of its total duration, and to be played two times faster as a consequence.

    Returns

    • (AnimationHandler):

      An object identifying the animation (can be used by animations.end).

    Example

    This code shows how to animate the movement of a node over 300ms:

    const START_X = 10, END_X = 100; 
    var node = ogma.graph.addNode({id: 0, x: START_X, y: 0}); 
    ogma.animations.play(function (ratio) { node.x = START_X + (END_X - START_X) * ratio; });
  • end(animationObject, [callCallback])

    Ends an animation, effectively calling the associated function with a ratio of 1.

    Arguments

    • animationObject (AnimationHandler):

      Object identifying the animation (returned by animations.play).

    • callCallback (optional, boolean):

      Indicates if the callback of the animation must be called.

    Example

    var a = ogma.animations.play(function (ratio) { console.log(ratio); }); 
     ogma.animations.end(a); // Display "1"
  • addEasingFunction(name, func)

    Add an easing function.

    Arguments

    • name (string):

      Name of the function.

    • func (EasingFunction):

      Takes a number from 0 to 1, and returns a number from 0 to 1.

    Example

    ogma.animations.addEasingFunction('myEasing', function (x) { return Math.sqrt(x); });
  • getEasingFunction(name)

    Retrieve an easing function by its name

    Arguments

    • name (string)

    Returns

    • (EasingFunction|null)

Default easing functions

  • linear
  • quadraticIn
  • quadraticOut
  • quadraticInOut
  • cubicIn
  • cubicOut
  • cubicInOut

badges module

Module in charge of drawing the badges.

Examples

badges settings

NameTypeDefault valueDescription
scalenumber0.45

Badge's size relative to the node's size.

positionScalenumber0.9

Distance between the node's center and the badge's center, relative to the node's size.

defaultColorColor'white'

Badge's background color.

defaultTextColorColor'black'

Badge's text color.

defaultStrokeColorColor'grey'

Badge's stroke color.

strokeWidthnumber2

Badge's stroke width, in pixels.

defaultFontstring'Arial'

Badge's text font.

fontStylestring'none'

Badge's text font style ('bold', 'italic' or 'none').

fontScalenumber1

Badge's text size relative to the badge's size.

textThresholdnumber6

If a badge's size in pixels is under this value, its text will not be displayed.

thresholdnumber1

If a node's size in pixels is under this value, its badges will not be displayed.

hideStrokeOnHiddenContentbooleanfalse

Indicates if a badge's stroke must be hidden if its content is not displayed due to the badge size.

drawBadgesbooleantrue

If false, no badges will be displayed.

brand module

Allows to display a HTML element on one of the corner.

// Specify the brand at initialization 
 var ogma = new Ogma({ 
   brand: '<p>Powered by MyCompany</p>' 
 }); 
 
 // Set the brand later 
 ogma.brand.set('<p>Powered by MyOtherCompany</p>');

Examples

Important note

If the brand shows in one of the corner of the page instead of the Ogma container, change the css "position" attribute of the container to "relative".

brand methods

  • set(html, [className])

    Set the HTML element.

    Arguments

    • html (string)
    • className (optional, string):

      If specified, the specified HTML class will be added to the DOM element.

  • remove()

    Remove the brand.

brand settings

NameTypeDefault valueDescription
positionstring'bottom-right'

Position of the brand. Valid values: 'top-left', 'top-right', 'bottom-left', 'bottom-right'

horizontalMarginnumber0

Left or right margin (in pixels), depending on the position.

verticalMarginnumber0

Top or bottom margin (in pixels), depending on the position.

camera module

Manages zoom, rotation and view.

Examples

camera methods

  • setCenter(x, y, [options])

    Set the center of the camera

    Arguments

    • x (number):

      X coordinate of the center (graph coordinate)

    • y (number):

      Y coordinate of the center (graph coordinate)

    • options (optional, object)
      • duration (optional, number, default: 0):

        Duration of movement.

      • callback (optional, function(): void):

        Function to be called once the movement finishes.

      • easing (optional, string, default: 'linear'):

        Easing function to use (if duration > 0).

      • noEndOfAnimation (optional, boolean, default: false):

        If animating, indicates if the end of the animation should be treated as such.

    Returns

    • (Camera)
  • move(offsetX, offsetY, [options])

    Move the camera by a specified offset.

    Arguments

    • offsetX (number):

      X coordinate of the offset (graph coordinate)

    • offsetY (number):

      Y coordinate of the offset (graph coordinate)

    • options (optional, object)
      • duration (optional, number, default: 0):

        Duration of movement (default: 0)

      • callback (optional, function(): void):

        Function to be called once the movement finishes.

      • easing (optional, string, default: 'linear'):

        Easing function to use (if duration > 0). Full list at easing.

      • noEndOfAnimation (optional, boolean, default: false):

        If animating, indicates if the end of the animation should be treated as such.

      • screenCoordinates (optional, boolean, default: true):

        Indicates of offsetX and offsetY are expressed in screen coordinates (pixels) or graph coordinates.

    Returns

    • (Camera)
  • setZoom(zoom, [options])

    Set the level of zoom of the camera.

    Arguments

    • zoom (number):

      Desired final zoom.

    • options (optional, object)
      • duration (optional, number, default: 0):

        Duration of zoom.

      • callback (optional, function(): void):

        Function to be called once the zoom finishes.

      • easing (optional, string, default: 'linear'):

        Easing function to use (if duration > 0). Full list at easing.

      • refX (optional, number, default: screen width / 2):

        X coordinate (on screen) of the origin of the zoom.

      • refY (optional, number, default: screen height / 2):

        Y coordinate (on screen) of the origin of the zoom.

      • noEndOfAnimation (optional, boolean, default: false):

        If animating, indicates if the end of the animation should be treated as such.

    Returns

    • (Camera)
  • zoomIn([options])

    Set the level of zoom of the camera by multiplying the current zoom.

    Arguments

    • options (optional, object)
      • duration (optional, number, default: 0):

        Duration of zoom.

      • callback (optional, function(): void):

        Function to be called once the zoom finishes.

      • easing (optional, string, default: 'linear'):

        Easing function to use (if duration > 0). Full list at easing.

      • zoomModifier (optional, number):

        Zoom multiplier (default: settings).

      • refX (optional, number, default: screen width / 2):

        X coordinate (on screen) of the origin of the zoom.

      • refY (optional, number, default: screen height / 2):

        Y coordinate (on screen) of the origin of the zoom.

      • noEndOfAnimation (optional, boolean, default: false):

        If animating, indicates if the end of the animation should be treated as such.

    Returns

    • (Camera)
  • zoomOut([options])

    Set the level of zoom of the camera by dividing the current zoom.

    Arguments

    • options (optional, object)
      • duration (optional, number, default: 0):

        Duration of zoom.

      • callback (optional, function(): void):

        Function to be called once the zoom finishes.

      • easing (optional, string, default: 'linear'):

        Easing function to use (if duration > 0). Full list at easing.

      • zoomModifier (optional, number):

        Zoom divider (default: settings).

      • refX (optional, number, default: screen width / 2):

        X coordinate (on screen) of the origin of the zoom.

      • refY (optional, number, default: screen height / 2):

        Y coordinate (on screen) of the origin of the zoom.

      • noEndOfAnimation (optional, boolean, default: false):

        If animating, indicates if the end of the animation should be treated as such.

    Returns

    • (Camera)
  • getAbsolutePosition(screenX, screenY)

    Given a point on the screen, returns the graph coordinates of this points taking into account the zoom, rotation and center of the camera.

    Arguments

    • screenX (number):

      X coordinate of the screen position.

    • screenY (number):

      Y coordinate of the screen position.

    Returns

    • (Point)
  • getPositionOnScreen(absoluteX, absoluteY)

    Given a point in graph coordinate, returns its coordinates on the screen, taking into account the zoom, rotation and center.

    Arguments

    • absoluteX (number):

      X coordinate.

    • absoluteY (number):

      Y coordinate.

    Returns

    • (Point):

      Relative coordinates.

  • getSizeOnScreen(size)

    Given a size in graph space, returns the corresponding size on the screen, taking the zoom into account.

    Arguments

    • size (number)

    Returns

    • (number)
  • saveConfig()

    Save the current camera configuration (position, angle, zoom).

    Returns

    • (CameraConfig):

      Camera configuration

  • loadConfig(config)

    Load a configuration saved with saveConfig.

    Arguments

    • config (CameraConfig):

      Camera configuration

    Example

    var config = ogma.camera.saveConfig(); 
     ogma.camera.loadConfig(config);

camera attributes

NameTypeDescription
xnumber

X coordinate in graph coordinate.

ynumber

Y coordinate in graph coordinate.

zoomnumber

Level of zoom. Indicates the multiplier of the "graph size" of the nodes and edges. For example, with a zoom of 2, a node of size 3 will be displayed with a radius of 6 pixels.

anglenumber

Rotation angle of the camera, in radians.

camera settings

NameTypeDefault valueDescription
maxZoomnumber1000

Maximum number by which the elements can be zoomed.

minZoomnumber0.01

Minimum number by which the elements can be zoomed.

defaultZoomModifiernumber1.8

Default zoom modifier for zoomIn and zoomOut.

defaultEasingstring'linear'

Default easing to be used in case of animated movement, rotation or zoom (see the animations module for the complete list).

camera events

NameTypeDescription
camera.moveboolean

Triggered when the camera position, angle or zoom changes. The parameter indicates if the camera is currently being animated.

camera.zoomboolean

Triggered when the camera zoom changes. The parameter indicates if the camera is currently being animated.

camera.rotateboolean

Triggered when the camera angle changes. The parameter indicates if the camera is currently being animated.

cameraInteractions module

Define the interactions the user can have that implies the camera:

  • Camera dragging
  • Camera rotation
  • Zooming using the mouse wheel
  • Zooming by double clicking the background
var cameraInteractions = ogma.cameraInteractions;

cameraInteractions settings

NameTypeDefault valueDescription
zoomDurationnumber150

Duration of a zoom when double clicking or using the mouse wheel, in milliseconds.

zoomModifiernumber|undefinedundefined

Modifier applied to the zoom level of the camera when zooming. If undefined, uses the default camera modifier (see camera settings).

zoomEnabledbooleantrue

Indicates if zooming with the mouse should be enabled.

panningEnabledbooleantrue

Indicates weather to enable the graph panning or not.

rotationEnabledbooleantrue

Indicates weather to enable the graph rotation or not.

skipNodeDrawingWhileZoomingbooleanfalse

If true, nodes will not be displayed while zooming with the mouse.

skipEdgeDrawingWhileZoomingbooleanfalse

If true, edges will not be displayed while zooming with the mouse.

skipNodeTextDrawingWhileZoomingbooleanfalse

If true, nodes' text will not be displayed while zooming with the mouse.

skipEdgeTextDrawingWhileZoomingbooleanfalse

If true, edges' text will not be displayed while zooming with the mouse.

skipNodeDrawingWhilePanningbooleanfalse

If true, nodes will not be displayed while dragging the graph with the mouse.

skipEdgeDrawingWhilePanningbooleanfalse

If true, edges will not be displayed while dragging the graph with the mouse.

skipNodeTextDrawingWhilePanningbooleanfalse

If true, nodes' text will not be displayed while dragging the graph with the mouse.

skipEdgeTextDrawingWhilePanningbooleanfalse

If true, edges' text will not be displayed while dragging the graph with the mouse.

skipNodeDrawingWhileRotatingbooleanfalse

If true, nodes will not be displayed while rotating the graph with the mouse.

skipEdgeDrawingWhileRotatingbooleanfalse

If true, edges will not be displayed while rotating the graph with the mouse.

skipNodeTextDrawingWhileRotatingbooleanfalse

If true, nodes' text will not be displayed while rotating the graph with the mouse.

skipEdgeTextDrawingWhileRotatingbooleanfalse

If true, edges' text will not be displayed while rotating the graph with the mouse.

skipNodeDrawingWhileGesturebooleanfalse

If true, nodes will not be displayed while manipulating the graph with fingers.

skipEdgeDrawingWhileGesturebooleanfalse

If true, edges will not be displayed while manipulating the graph with fingers.

skipNodeTextDrawingWhileGesturebooleanfalse

If true, nodes' text will not be displayed while manipulating the graph with fingers.

skipEdgeTextDrawingWhileGesturebooleanfalse

If true, edges' text will not be displayed while manipulating the graph with fingers.

captor module

Provides various events to indicate when nodes and edges are clicked, dragged or hovered. It takes both the mouse and touch events in account.

Examples

captor methods

  • pointedElement()

    Returns the node or edge pointed by the mouse.

    Returns

    • (Node|Edge|null):

      The node or edge, or null if no node or edge is pointed.

  • draggedElement()

    Returns the node or edge that is currently dragged.

    Returns

    • (Node|Edge|null):

      The node or edge, or null if no node or edge is dragged.

captor settings

NameTypeDefault valueDescription
nodesbooleantrue

Indicates if the detection of nodes should be enabled.

edgesbooleantrue

Indicates if the detection of edges should be enabled.

nodeTextsbooleantrue

Indicates if the detection of node texts should be enabled.

edgeTextsbooleantrue

Indicates if the detection of edge texts should be enabled.

nodeErrorMarginnumber5

How far of the detect a node can be and still be detected, in pixels.

edgeErrorMarginnumber7

How far of the detect an edge can be and still be detected, in pixels.

captor events

NameTypeDescription
movenumber, number
downnumber, number
upnumber, number
clicknumber, number
rightDownnumber, number
rightUpnumber, number
rightClicknumber, number
doubleClicknumber, number
hoverNodeNode, number, number
unhoverNodeNode, number, number
clickNodeNode, number, number
doubleClickNodeNode, number, number
rightClickNodeNode, number, number
startDragNodeNode, number, number
dragNodeNode, number, number
endDragNodeNode, number, number
startRightDragNodeNode, number, number
rightDragNodeNode, number, number
endRightDragNodeNode, number, number
hoverEdgeEdge, number, number
unhoverEdgeEdge, number, number
clickEdgeEdge, number, number
doubleClickEdgeEdge, number, number
rightClickEdgeEdge, number, number
startDragEdgeEdge, number, number
dragEdgeEdge, number, number
endDragEdgeEdge, number, number
startRightDragEdgeEdge, number, number
rightDragEdgeEdge, number, number
endRightDragEdgeEdge, number, number
clickBackgroundnumber, number
doubleClickBackgroundnumber, number
rightClickBackgroundnumber, number
startDragBackgroundnumber, number
dragBackgroundnumber, number
endDragBackgroundnumber, number
startRightDragBackgroundnumber, number
rightDragBackgroundnumber, number
endRightDragBackgroundnumber, number

coalescence module

This module uses the groups module to keep some nodes grouped together. The user specifies a criteria of grouping (using a function or a DSL expression), and the modules ensures that nodes (or edges) for which the criteria returns the same value are grouped together.

Examples

coalescence methods

  • groupNodes(parameters)

    Group together all nodes for which the expression returns the same value. Nodes for which the return value is undefined are not grouped. The groups continue to be updated as elements are added, removed or updated.

    Arguments

    • parameters (object)
      • method (NodeGroupFunction):

        This function takes one parameter: the list of nodes that belong to the same group. It must return the "meta node" that will be added to the graph. If no id is specified for this meta node, it will be given a random id.

      • expression (Expression):

        Function or DSL expression that will be applied to nodes

      • duration (optional, number, default: 0):

        Duration of the grouping animation

      • callback (optional, function):

        Function triggered whenever one or more groups change.

    Example

    This example shows how to group nodes that have the same data.location property:

    ogma.coalescence.groupNodes({ 
      expression: function (node) { return node.data && node.data.location; }, 
      method: function (nodeList) { 
        var size = 0, x = 0, y = 0; 
    
        for (var i = 0; i < nodeList.length; ++i) { 
          var node = nodeList[i]; 
          size += node.size; 
          x += node.x; 
          y += node.y; 
        } 
    
        x /= nodeList.length; 
        y /= nodeList.length; 
    
        return {x: x, y: y, size: size}; 
      } 
    }); 
    
    // This code groups all the nodes that have the same `data.location` property into a single node 
    // that will have the combined size of all nodes, and be at the center of the grouped nodes.
  • groupEdges(parameters)

    Group together every edge that have the same direction, between each pair of nodes.

    Arguments

    • parameters (object)
      • method (EdgeGroupFunction):

        This function takes a list of edges as parameter, and must return the meta edge. If no id is specified, it will be given a random id.

      • expression (optional, Expression):

        If specified, multiple groups will be created for each of the two direction: edges for which the expression returns the same values are grouped together. Edges which return the value undefined are not grouped together.

      • duration (optional, number, default: 0):

        Duration of the grouping animation

      • callback (optional, function):

        Function triggered whenever one or more groups change.

    Examples

    Group every set of parallel edges into an edge for which the size is the sum of every "sub"-edge::

    ogma.coalescence.groupEdges({ 
      method: function (edgeList) { 
        return { 
          size: edgeList.reduce(function (edge, size) { return edge.size + size; }, 0) 
        }; 
      } 
    });

    Same as above, but only groups the edges that have the same data.quality property::

    ogma.groups.groupEdges({ 
      expression: function (edge) { return edge.data && edge.data.quality; }, 
      method: function (edgeList) { 
        return { 
          size: edgeList.reduce(function (edge, size) { return edge.size + size; }, 0) 
        }; 
      } 
    });
  • ungroupNodes([parameters])

    Removes all meta nodes, and stop grouping nodes.

    Arguments

    • parameters (optional, object)
      • duration (optional, number, default: 0):

        Duration of the ungrouping animation

      • callback (optional, function):

        Called at the end of the animation

  • ungroupEdges([parameters])

    Removes all meta edges, and stop grouping edges.

    Arguments

    • parameters (optional, object)
      • duration (optional, number, default: 0):

        Duration of the ungrouping animation

      • callback (optional, function):

        Called at the end of the animation

  • reset()

    Removes all meta nodes and meta edges, and stop grouping nodes and edges.

connectNodes module

This behavior is responsible for connecting nodes by drawing an edge from one node to another

var ogma = new Ogma({ 
   graph: { ... } 
 }); 
 ogma.connectNodes.enable();

Examples

connectNodes methods

  • enable()

    Enables the connection mode

  • disable()

    Disables the connection mode

  • setCondition(condition)

    Sets a custom condition to allow or disallow connection of two nodes

    Arguments

    • condition (function(node1: Node, node2: Node):boolean)

    Returns

    • (ConnectNodes)

    Example

    ogma.connectNodes.setCondition(function (n1, n2) { 
       return n1.data.type === n2.data.type; 
     });

connectNodes settings

NameTypeDefault valueDescription
strokeColorColor'black'

Drawing line stroke color

strokeWidthnumber1

Drawing line stroke width

cursorStylestring'cell'

Cursor style when the drawing is active

continueDrawingbooleanfalse

Stay in the drawing mode after the link is created

createNodesbooleantrue

Weather to create a new node if no end node was selected.

design module

Provides a way to change the following visual variables based on node or edge properties (usually contained in the data property):

  • for nodes: color, size, text, shape, icons, images
  • for edges: color, size, text, shape

Color every node depending on their data.quality property. Nodes for which the value of the data.quality property do not match the scheme keys (in this case: 'good', 'medium' and 'bad') are ignored and are assigned the default node color:

ogma.design.setNodeStyle('color', { 
  variable: 'data.quality', 
  scheme: { 
    'good': 'blue', 
    'medium': 'yellow', 
    'bad': 'red' 
  } 
});

Set the size of the nodes depending on their data.nbEmployees property. The size of the node with the smallest data.nbEmployees property will be assigned to 2, the size of the node with the largest data.nbEmployees property will be assigned to 15, other sizes are interpolated between the min and max. The bins property indicates the number of different sizes that can be assigned (in this case, we can have 7 different sizes). Nodes for which data.nbEmployees is not a number are ignored and are assigned the default size 1:

ogma.design.setNodeSize({variable: 'data.nbEmployees', min: 2, max: 15, bins: 7});

Set the text of all edges based on their location and age:

ogma.design.setEdgeText(function (edge) { return edge.data.location + ' - ' + edge.data.age; });

Change the color of nodes by specifying a range for each color:

ogma.design.setNodeColor({ 
    variable: 'data.altitude', 
    scheme: ['blue', 'green', 'brown'], 
    stops: [0, 10] 
  } 
); 
// Every node with an altitude less than 0 will be blue, nodes with an altitude between 0 and 10 will be green, nodes with an altitude greater than 10 will be brown.

Change the node size by specifying a range for each size:

ogma.design.setNodeSize({ 
    variable: 'data.nbEmployees', 
    sizes: [1, 5, 10, 100], 
    stops: [10, 100, 1000] 
  } 
); 
// Every node with a number of employees less than 10 will be of size 1, nodes with a number of employees between 10 and 100 will have a size of 5, nodes with a number of employees between 100 and 1000 will have a size of 10, other nodes will have a size of 100

Examples

design methods

  • setStyles(styles)

    Set multiple styles at once for both nodes and edges

    Arguments

    • styles ({nodes: AllNodeStyles, edges: AllEdgeStyles})

    Example

    ogma.design.setStyles({ 
       nodes: { 
         color: {variable: 'data.quality', scheme: { 'good': 'blue', 'medium': 'yellow', 'bad': 'red' } }, 
         size: {variable: 'data.quantity', min: 1, max: 3} 
       }, edges: { 
         shape: {variable: 'data.type', scheme: { 'A': 'arrow', 'B': 'tapered' } } 
       } 
     });
  • getStyles()

    Get the full list of styles for both nodes and edges

    Returns

    • ({nodes: AllNodeStyles, edges: AllEdgeStyles})
  • reset()

    Remove every node & edge style.

  • setNodeColor(parameters)

    Indicates how the color of each node must be assigned. In case of a quantitative mapping, nodes for which the specified property is not a number are given the default color.

    Arguments

    • parameters (QualitativeColorStyle|QuantitativeColorStyle|function(node: Node): Color)
  • setEdgeColor(parameters)

    Indicates how the color of each edge must be assigned.

    Arguments

    • parameters (QualitativeColorStyle|QuantitativeColorStyle|function(edge: Edge): Color)
  • setNodeShape(parameters)

    Indicates how the shape of each node must be assigned.

    Arguments

    • parameters (ShapeStyle|function(node: Node): string)
  • setEdgeShape(parameters)

    Indicates how the shape of each edge must be assigned.

    Arguments

    • parameters (ShapeStyle|function(edge: Edge): string)
  • setNodeIcon(parameters)

    Indicates how the icon of each node must be assigned.

    Arguments

    • parameters (IconStyle|function(node: Node): Icon|string)
  • setNodeImage(parameters)

    Indicates how the image of each node must be assigned.

    Arguments

    • parameters (IconStyle|function(node: Node): Image|string)
  • setNodeSize(parameters)

    Indicates how the size of each node must be assigned. Nodes for which the specified property is not a number are given the default size.

    Arguments

    • parameters (SizeStyle|function(node: Node): number)
  • setEdgeSize(parameters)

    Indicates how the size of each edge must be assigned. Edges for which the specified property is not a number are given the default size.

    Arguments

    • parameters (SizeStyle|function(edge: Edge): number)
  • setNodeText(f)

    Indicates how the text of each node must be assigned.

    Arguments

    • f (function(node: Node): string)
  • setEdgeText(f)

    Indicates how the text of each edge must be assigned.

    Arguments

    • f (function(edge: Edge): string)
  • resetNodeColor()

    Restore the original color of all nodes.

  • resetEdgeColor()

    Restore the original color of all edges.

  • resetNodeShape()

    Restore the original shape of all nodes.

  • resetEdgeShape()

    Restore the original shape of all edges.

  • resetNodeIcon()

    Restore the original icon of all nodes.

  • resetNodeImage()

    Restore the original image of all nodes.

  • resetNodeSize()

    Restore the original size of all nodes.

  • resetEdgeSize()

    Restore the original size of all edges.

  • resetNodeText()

    Restore the original text of all nodes.

  • resetEdgeText()

    Restore the original text of all edges.

  • getNodeColor()

    Returns the parameters used to compute the color of nodes. Returns null if no color style was set.

    Returns

    • (null|QualitativeColorStyle|QuantitativeColorStyle|function(node: Node): Color)
  • getEdgeColor()

    Returns the parameters used to compute the color of edges. Returns null if no color style was set.

    Returns

    • (null|QualitativeColorStyle|QuantitativeColorStyle|function(edge: Edge): Color)
  • getNodeShape()

    Returns the parameters used to compute the shape of nodes. Returns null if no shape style was set.

    Returns

    • (null|ShapeStyle|function(node: Node): string)
  • getEdgeShape()

    Returns the parameters used to compute the shape of edges. Returns null if no shape style was set.

    Returns

    • (null|ShapeStyle|function(edge: Edge): string)
  • getNodeIcon()

    Returns the parameters used to compute the icon of nodes. Returns null if no icon style was set.

    Returns

    • (null|IconStyle|function(node: Node): Icon|string)
  • getNodeImage()

    Returns the parameters used to compute the image of nodes. Returns null if no image style was set.

    Returns

    • (null|ImageStyle|function(node: Node): Image|string)
  • getNodeSize()

    Returns the parameters used to compute the size of nodes. Returns null if no size style was set.

    Returns

    • (null|SizeStyle|function(node: Node): number)
  • getEdgeSize()

    Returns the parameters used to compute the size of edges. Returns null if no size style was set.

    Returns

    • (null|SizeStyle|function(edge: Edge): number)
  • getNodeText()

    Returns the parameters used to compute the text of nodes. Returns null if no text style was set.

    Returns

    • (null|function(node: Node): string)
  • getEdgeText()

    Returns the parameters used to compute the text of edges. Returns null if no text style was set.

    Returns

    • (null|function(edge: Edge): string)
  • setNodeReserveColors(colors)

    Set reserve colors for nodes. Reserve colors are used when a color scheme doesn't contain enough colors for all values.

    Arguments

    • colors (Array<Color>)

    Example

    ogma.setNodeReserveColors(['yellow', 'green']); 
     ogma.setNodeColor({variable: 'data.location', scheme: {'US': 'blue', 'EU': 'red'}}); 
     // The first value encountered that is neither 'US' nor 'EU' will be assigned the color 'yellow' instead of the default color. 
     // The second different will be assigned the color 'green'. 
     // Then it goes in a loop: the third different will be assigned the color 'yellow', etc
  • setEdgeReserveColors(colors)

    Set reserve colors for edges. Reserve colors are used when a color scheme doesn't contain enough colors for all values.

    Arguments

    • colors (Array<Color>)
  • getNodeColorMapping()

    Returns the color mapping for nodes, taking into accounts the scheme and the reserve colors.

    Returns

    • (Object<string, string>)
  • getEdgeColorMapping()

    Returns the color mapping for edges, taking into accounts the scheme and the reserve colors.

    Returns

    • (Object<string, string>)

design settings

NameTypeDefault valueDescription
defaultSizeBinsnumber7

Default number of different sizes.

drag module

drag methods

  • nodes(nodes, dx, dy, screenCoordinates)

    Move the specified nodes.

    Arguments

    • nodes (Array<Node>):

      Nodes to move

    • dx (number)
    • dy (number)
    • screenCoordinates (boolean, default: false):

      Indicates if dx and dy are expressed in screen coordinates or graph coordinates.

drag settings

NameTypeDefault valueDescription
manualbooleantrue

Indicates if dragging nodes with the mouse should be enabled.

drag events

NameTypeDescription
drag.startArray<Node>

Emitted when some nodes start being dragged are dragged.

drag.progressArray<Node>, number, number

Emitted when some nodes are dragged. The second and third argument indicates the offset between the last and the new position of the nodes.

drag.endArray<Node>, number, number

Emitted when some nodes are dragged. The second and third argument indicates the offset between the original (when the drag started) and the final position of the nodes.

drawing module

In charge of drawing the nodes and edges.

The animations module allows to make general purpose animations. But in the case of simple graphics animations (color, size or position change), the drawing module allows to make way more efficient animations by using directly WebGL (when available) instead of doing all computations in Javascript

var node = ogma.graph.addNode({id: 0, x: 0, y: 0}); 
 ogma.drawing.animate(function () { node.x = 300; }, 500); 
 // The node will move on the right during the next 500 ms

Examples

drawing methods

  • animate(f, duration, [callback])

    Animate a graphics change (position, size or color change). All graphics change that occurs within f will be animated over duration ms.

    Arguments

    • f (function(): void):

      Animation function.

    • duration (number):

      Duration of the animation.

    • callback (optional, function(): void):

      Function to call when the animation is finished.

  • stopAnimations(callCallback)

    Stop all ongoing animations.

    Arguments

    • callCallback (boolean, default: true):

      Indicates if the callback of the stopped animatins should be called.

  • isAnimating()

    Indicates if there is at least one animation currently running.

    Returns

    • (boolean)
  • addVisibilityCondition(isNode, condition)

    Add a visibility condition for nodes or edges. Elements that do not satisfy this condition are hidden.

    Arguments

    • isNode (boolean):

      Indicates if the condition applies to nodes or edges.

    • condition (function(): void):

      Takes one parameter, the node or edge, and returns a boolean.

    Example

    Hide all nodes with a size under 10.:

    ogma.drawing.addVisibilityCondition(true, function (node) { return node.size > 10; });
  • addCommonVisibilityCondition(condition)

    Add a visibility condition for both nodes and edges. Elements that do not satisfy this condition are hidden.

    Arguments

    • condition (function):

      Takes one parameter, the node or edge, and returns a boolean.

  • addNodeVisibilityCondition(condition)

    Add a visibility condition for nodes. Nodes that do not satisfy this condition are hidden.

    Arguments

    • condition (function):

      Takes one parameter, the node, and returns a boolean.

  • addEdgeVisibilityCondition(condition)

    Add a visibility condition for edges. Edges that do not satisfy this condition are hidden.

    Arguments

    • condition (function):

      Takes one parameter, the edge, and returns a boolean.

  • setNodeDrawing(value)

    Enable or disable the drawing of nodes.

    Arguments

    • value (boolean)
  • setEdgeDrawing(value)

    Enable or disable the drawing of edges.

    Arguments

    • value (boolean)

drawing settings

NameTypeDefault valueDescription
defaultNodeSizenumber5

Default node size.

defaultEdgeSizenumber1

Default edge size.

edgeClippingbooleantrue

Hide edges if none of their extremity is in the screen.

edgeClippingPaddingnumber100

Tolerance in pixels.

dsl module

This module provides a DSL (Domain Specific Language) to write expressions that can be applied to nodes or edges. An expression can also be applied to a node's adjacent elements (nodes or edges). The main purpose of these expressions is that they can be serialized with a simple JSON.stringify(). They are functions that can be serialized and parsed without using eval.

These expressions can be used in other modules of Ogma instead of regular functions, in particular the partitions module.

If you have no interest in serialization, just use regular functions.

Examples:

ogma.dsl.computeExpression('color', node); 
 
 // equivalent to 
 
 node.color;
ogma.dsl.computeExpression(['data.location', '===', {value: 'Europe'}], node); 
 
 // equivalent to 
 
 node.data.location === 'Europe'
ogma.dsl.registerOperator('isIdEven', function (node) { return node.id % 2 === 0; }); 
 ogma.dsl.computeExpression(['.', 'isIdEven']); 
 
 // equivalent to 
 
 node.id % 2 === 0;
ogma.dsl.registerAggregator('meanValue', function (adjacentNodeValues) { 
  var meanValue = 0; 
  for (var i = 0; i < adjacentNodeValues.length; ++i) 
    meanValue += adjacentNodeValues[i]; 
 
  meanValue /= adjacentNodeValues.length; 
 
  return meanValue; 
}); 
 
 ogma.dsl.computeExpression(['data.age', null, null, {nodes: 'meanValue'}], node); 
 
 // equivalent to 
 
 var adjacentNodes = ogma.topology.getAdjacentElements(node, {type: 'nodes'}); 
 var meanValue = 0; 
 for (var i = 0; i < adjacentNodes.length; ++i) 
   meanValue += adjacentNodes[i].data.age; 
 
 meanValue /= adjacentNodes.length;

Formal definition

An expression is an array of size 1, 2, 3 or 4. The format is:

var expression = [leftOperand, operatorName, rightOperand, aggregator]; 

Except for the left operand, every value is optional.

Operands

An operand can be:

  • A string: the operand refers to the property of the element (for example: 'color' means "the property color of the element") (reminder: the element is the second argument that we pass to the dsl.computeExpression function). The string can be is more a path than a name: for example, 'a.b.c' will be interpreted as element.a.b.c rather than element['a.b.c']. Lastly, the string can be '.', in which case if refers to the whole element.
  • An object: this object will be passed to the operator.
  • Another expression.

Operators

An operator is a string referring to a function previously registered with dsl.registerOperator. These functions take one or two arguments. Some basic operators are already registered (see the operator section). If the operator is not specified, the right operand is ignored.

Aggregators

When an aggregator is specified, the expression will be computed for each adjacent element of the specified node (an aggregator cannot be applied to an edge), instead of being applied to the node. But since an expression needs to return a single value, we need a way to "merge" all these results: this is the role of the aggregator function.

An aggregator function takes an array of values as parameter and return a single value.

To determine which kinds of adjacent elements we are referring to, the aggregator function is preceded by one of the following keys: 'nodes', 'inNodes', 'outNodes', 'edges', 'inEdges', 'outEdges'.

Example:

var graph = { 
  nodes: [{id:0}, {id:1}, {id:2}], 
  edges: [{id:0, source: 0, target: 1}, {id:1, source: 1, target: 2}, {id:2, source: 2, target: 0}] 
}; 
var ogma = new Ogma({graph: graph}); 

ogma.dsl.registerAggregator('sumLargerThan2', function (valueList) { 
var sum = 0; 
for (var i = 0; i < valueList.length; ++i) { 
  sum += valueList[i]; 
} 

  return sum > 2; 
}); 

var node = ogma.graph.getNode(0); 
ogma.dsl.computeExpression(['id', null, null, {nodes: 'sumLargerThan2'}], node); // true 
ogma.dsl.computeExpression(['id', null, null, {outNodes: 'sumLargerThan2'}], node); // false 

Shortcut

An expression can be a single string. In such case, the string is treated as the first value of the array, and every other argument is treated as undefined. Example:

dsl.computeExpression('data.age'); 
// equivalent to 
dsl.computeExpression(['data.age']); 

Passing specific values to operators

If you want to pass a specific value to an operator, you must wrap it in an object. The reason is that if an operand is a string, it will be treated as a property path, not as a string.

For example, the two following lines are equivalent:

ogma.dsl.computeExpression(['data.location', '===', 'Europe'], node); 
node.data.location === node.data.Europe; // This is not what we want 

These lines are equivalent:

ogma.dsl.computeExpression(['data.location', '===', {value: 'Europe'}], node); 
node.data.location === 'Europe'; // This is what we want 

dsl methods

  • computeExpression(elt, expression, [ignoreUndefined])

    Compute the result of an expression.

    Arguments

    • elt (Node|Edge):

      Element from which the expression must be computed.

    • expression (Expression)
    • ignoreUndefined (optional, boolean, default: false):

      If true, operators will always return undefined if at least one operand is undefined.

    Returns

    • (any)
  • checkExpressionFormat(expression)

    Check weather an expression is valid or not.

    Arguments

    • expression (Expression)

    Returns

    • (string|null):

      If the expression is not valid, returns a string that describes the error. If the expression is valid, returns null.

  • expressionDepth(expression)

    Compute the "neighborhood depth" of the expression, i.e how many levels of neighborhood the expression has to process to be computed.

    Arguments

    • expression (Expression)

    Returns

    • (number)
  • registerOperator(name, func, [override])

    Register an operator.

    Arguments

    • name (string):

      Name of the operator

    • func (DslOperator):

      Operator body

    • override (optional, boolean, default: false):

      Indicates if the operator should be overridden if the operator already exists.

  • registerAggregator(name, func, [override])

    Register an aggregator.

    Arguments

    • name (string):

      Name of the aggregator.

    • func (DslAggregator):

      Aggregator body.

    • override (optional, boolean, default: false):

      Indicates if the aggregator should be overridden if the operator already exists.

  • operators()

    Returns the list of registered operators.

    Returns

    • (Object<string, DslOperator>):

      key = operator name, value = associated operator function

  • aggregators()

    Returns the list of registered aggregators.

    Returns

    • (Object<string, DslAggregator>):

      key = operator name, value = associated aggregator function

Built-in operators

  • ===
  • ==
  • !==
  • !=
  • >
  • <
  • >=
  • <=
  • &&
  • ||
  • +
  • -
  • *
  • /
  • !
  • not

    same as '!'

  • includes

    Returns true if the two operands are equals (===), or if the first operand is an array that contains the second operand

events module

Most of Ogma's module fire events. It is possible to listen to these events and react to them. It is also possible to create its own events.

Note that all modules' events are prefixed with the name of the module; this is a convention, not an obligation.

ogma.events.bind('graph.addNodes', function (nodes) { 
   console.log(nodes.length + ' nodes have just been added.'); 
 }); 
 
 ogma.graph.addNodes([ 
   {id: 0}, 
   {id: 1} 
 ]); 
 // Displays: "2 nodes have just been added"

events methods

  • bind(name, handler)

    Bind a function to an event. The function will be called when the event is emitted.

    Arguments

    • name (string):

      Name of the event.

    • handler (function(...args : any[]): void):

      Function that will be called.

  • bind(events)

    Binds several events.

    Arguments

    • events ({ [key: string] : function(...args : any[]): void }):

      Keys: event names, values: handler function

    Example

    ogma.events.bind({ 
       'graph.addNodes': function (nodes) { console.log(`${nodes.length} nodes added`); }, 
       'drag.nodes': function (nodes) { console.log(`${nodes.length} nodes dragged`); } 
     }); 
     // equivalent to 
     ogma.events.bind('graph.addNodes', function (nodes) { console.log(`${nodes.length} nodes added`); }); 
     ogma.events.bind('drag.nodes', function (nodes) { console.log(`${nodes.length} nodes dragged`); });
  • unbind(name, handler)

    Unbind a function from an event.

    Arguments

    • name (string):

      Name of the event.

    • handler (function(...args : any[]): void):

      Function that was passed as the second argument of bind.

    Returns

    • (boolean):

      true if the function was successfully unbound, false if the function was not bound.

  • create(name, [reverseOrder])

    Create an event. Throws an exception if an event with the same name already exists.

    Arguments

    • name (string):

      Name of the event.

    • reverseOrder (optional, boolean, default: false):

      By default, bound functions are called in the order they were bound. if reverseOrder is true, they will be called in reverse order (last bound called first).

    Returns

    • (function(...args : any[]): void):

      Function to call to fire the event.

    Example

    var evt = ogma.events.create('dummy'); 
     ogma.events.bind('dummy', function (value) { return console.log(value); }); 
     evt(42); // Displays "42"

exports module

Manages the exports.

ogma.exports.to('png', {clip: true, filename: 'myGraph'});

Examples

exports methods

  • to(format, [parameters])

    Export a graph into an external file, using the specified format.

    Arguments

    • format (string):

      Format to which export. See the export section to have the list of exports.

    • parameters (optional, object|function(exportContent: any): void):

      Parameters that will be passed to the exporter. filename and download are common to all exporters, but other parameters depend on the exporter. If this is a function, it indicates the callback property.

      • download (optional, boolean):

        If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

      • filename (optional, string, default: 'graph'):

        If download is true, the default name for the downloaded file.

      • callback (optional, function(exportContent: any): void):

        Called when the export is done. Takes the result of the export as parameter.

    Returns

    • (Promise<any>)

Exporters

  • csv

    When download is false or the platform is Node.js, returns a string.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • what (string):

      Indicates what kind of elements to export. Can be 'nodes' or 'edges'. This field is mandatory.

    • which (optional, Array<Id>):

      Ids of nodes or edges to export. If omitted, exports all nodes or edges.

    • separator (optional, string, default: ','):

      Column separator

    • textSeparator (optional, string, default: '"'):

      String used to surround strings. Can only be " or '

    • categoriesName (optional, string, default: 'categories')

    Returns

    • (string)
  • gexf

    When download is false or the platform is Node.js, returns a XML string. In Node.js, requires the xmldom package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • creator (optional, string):

      Creator of the graph

    • description (optional, string):

      Description of the graph

    Returns

    • (string)
  • graphml

    When download is false or the platform is Node.js, returns a XML string. In Node.js, requires the xmldom package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • graphId (optional, string, default: 'G'):

      id of the graph

    • directedEdges (optional, boolean, default: true):

      Indicates if the graph is directed

    Returns

    • (string)
  • json

    When download is false or the platform is Node.js, returns a JSON string.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • nodeFields (optional, Array<string>):

      If specified, only exports the specified node properties.

    • edgeFields (optional, Array<string>):

      If specified, only exports the specified edge properties.

    • pretty (optional, boolean, default: false):

      Indicates if the output should be properly indented.

    Returns

    • (string)

    Example

    ogma.exports.to('json', {nodeFields: ['id'], edgeFields: ['id', 'source', 'target']});
  • png

    When download is false or the platform is Node.js, returns a dataURL. In Node.js, requires the node-canvas package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • clip (boolean):

      Indicates if clip

    • margin (optional, number, default: 10):

      Blank space between the edge of the image and its content

    • width (optional, number):

      If specified along with height, specifies the dimensions of the exported image.

    • height (optional, number):

      If specified along with width, specifies the dimensions of the exported image.

    • size (optional, number):

      Specifies both the width and height parameter.

    • clip (optional, boolean, default: false):

      If true, only exports the currently visible part of the graph.

    • background (optional, Color):

      Indicates the background color for the exported image. Transparent by default.

    • texts (optional, boolean, default: true):

      Indicates if texts should be exported.

    • map (optional, boolean, default: true):

      If the geographical mode is active, indicates if the map should also be exported.

    • textWatermark (optional, object|string):

      Parameter of the text watermark. If it is a string, it indicates the content parameter.

      • content (string):

        Text to display.

      • fontSize (optional, string, default: 48):

        Size (in pixels) of the text to display

      • fontStyle (optional, string):

        Style of the text ('bold' or 'italic')

      • fontColor (optional, Color):

        Color of the text

      • repeat (optional, boolean, default: false):

        Indicates if the text should be replicated all over the image

      • angle (optional, number, default: 0):

        Angle of the text (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the text (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the text

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the image.

    • imageWatermark (optional, object):

      Parameter of the image watermark.

      • content (string):

        Image URL to display.

      • width (number):

        Width of the image.

      • height (number):

        Height of the image.

      • repeat (optional, boolean, default: false):

        Indicates if the image should be replicated all over the exported image.

      • angle (optional, number, default: 0):

        Angle of the image (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the image (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the image

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the exported image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the exported image.

    Returns

    • (string)

    Examples

    var watermarkImage = new Image(); 
     watermarkImage.src = 'url/to/image.jpg'; 
     watermarkImage.onload = function () { 
       ogma.exports.to('png', {clip: true, filename: 'myGraph', imageWatermark: { 
         content: img, 
         height: 100, 
         width: 200 
       }}); 
     }

    Exporting to PNG on Node.js (make sure to install the node-canvas package):

    var base64Img = ogma.exports.to('png').replace(/^data:image\/png;base64,/,""); 
    fs.writeFileSync('/path/to/image.png', base64Img, 'base64');
  • jpg

    When download is false or the platform is Node.js, returns a dataURL. In Node.js, requires the node-canvas package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • clip (boolean):

      Indicates if clip

    • margin (optional, number, default: 10):

      Blank space between the edge of the image and its content

    • width (optional, number):

      If specified along with height, specifies the dimensions of the exported image.

    • height (optional, number):

      If specified along with width, specifies the dimensions of the exported image.

    • size (optional, number):

      Specifies both the width and height parameter.

    • clip (optional, boolean, default: false):

      If true, only exports the currently visible part of the graph.

    • background (optional, Color):

      Indicates the background color for the exported image. Transparent by default.

    • texts (optional, boolean, default: true):

      Indicates if texts should be exported.

    • map (optional, boolean, default: true):

      If the geographical mode is active, indicates if the map should also be exported.

    • textWatermark (optional, object|string):

      Parameter of the text watermark. If it is a string, it indicates the content parameter.

      • content (string):

        Text to display.

      • fontSize (optional, string, default: 48):

        Size (in pixels) of the text to display

      • fontStyle (optional, string):

        Style of the text ('bold' or 'italic')

      • fontColor (optional, Color):

        Color of the text

      • repeat (optional, boolean, default: false):

        Indicates if the text should be replicated all over the image

      • angle (optional, number, default: 0):

        Angle of the text (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the text (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the text

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the image.

    • imageWatermark (optional, object):

      Parameter of the image watermark.

      • content (string):

        Image URL to display.

      • width (number):

        Width of the image.

      • height (number):

        Height of the image.

      • repeat (optional, boolean, default: false):

        Indicates if the image should be replicated all over the exported image.

      • angle (optional, number, default: 0):

        Angle of the image (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the image (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the image

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the exported image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the exported image.

    Returns

    • (string)
  • tiff

    When download is false or the platform is Node.js, returns a dataURL. In Node.js, requires the node-canvas package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • clip (boolean):

      Indicates if clip

    • margin (optional, number, default: 10):

      Blank space between the edge of the image and its content

    • width (optional, number):

      If specified along with height, specifies the dimensions of the exported image.

    • height (optional, number):

      If specified along with width, specifies the dimensions of the exported image.

    • size (optional, number):

      Specifies both the width and height parameter.

    • clip (optional, boolean, default: false):

      If true, only exports the currently visible part of the graph.

    • background (optional, Color):

      Indicates the background color for the exported image. Transparent by default.

    • texts (optional, boolean, default: true):

      Indicates if texts should be exported.

    • map (optional, boolean, default: true):

      If the geographical mode is active, indicates if the map should also be exported.

    • textWatermark (optional, object|string):

      Parameter of the text watermark. If it is a string, it indicates the content parameter.

      • content (string):

        Text to display.

      • fontSize (optional, string, default: 48):

        Size (in pixels) of the text to display

      • fontStyle (optional, string):

        Style of the text ('bold' or 'italic')

      • fontColor (optional, Color):

        Color of the text

      • repeat (optional, boolean, default: false):

        Indicates if the text should be replicated all over the image

      • angle (optional, number, default: 0):

        Angle of the text (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the text (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the text

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the image.

    • imageWatermark (optional, object):

      Parameter of the image watermark.

      • content (string):

        Image URL to display.

      • width (number):

        Width of the image.

      • height (number):

        Height of the image.

      • repeat (optional, boolean, default: false):

        Indicates if the image should be replicated all over the exported image.

      • angle (optional, number, default: 0):

        Angle of the image (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the image (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the image

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the exported image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the exported image.

    Returns

    • (string)
  • gif

    When download is false or the platform is Node.js, returns a dataURL. In Node.js, requires the node-canvas package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • clip (boolean):

      Indicates if clip

    • margin (optional, number, default: 10):

      Blank space between the edge of the image and its content

    • width (optional, number):

      If specified along with height, specifies the dimensions of the exported image.

    • height (optional, number):

      If specified along with width, specifies the dimensions of the exported image.

    • size (optional, number):

      Specifies both the width and height parameter.

    • clip (optional, boolean, default: false):

      If true, only exports the currently visible part of the graph.

    • background (optional, Color):

      Indicates the background color for the exported image. Transparent by default.

    • texts (optional, boolean, default: true):

      Indicates if texts should be exported.

    • map (optional, boolean, default: true):

      If the geographical mode is active, indicates if the map should also be exported.

    • textWatermark (optional, object|string):

      Parameter of the text watermark. If it is a string, it indicates the content parameter.

      • content (string):

        Text to display.

      • fontSize (optional, string, default: 48):

        Size (in pixels) of the text to display

      • fontStyle (optional, string):

        Style of the text ('bold' or 'italic')

      • fontColor (optional, Color):

        Color of the text

      • repeat (optional, boolean, default: false):

        Indicates if the text should be replicated all over the image

      • angle (optional, number, default: 0):

        Angle of the text (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the text (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the text

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the image.

    • imageWatermark (optional, object):

      Parameter of the image watermark.

      • content (string):

        Image URL to display.

      • width (number):

        Width of the image.

      • height (number):

        Height of the image.

      • repeat (optional, boolean, default: false):

        Indicates if the image should be replicated all over the exported image.

      • angle (optional, number, default: 0):

        Angle of the image (degrees)

      • alpha (optional, number, default: 0.65):

        Transparency of the image (1 = opaque, 0 = transparent)

      • space (optional, number, default: 50):

        When repeat is true, space in pixels between the repetitions of the image

      • x (optional, number):

        X coordinate of the center of the text. Default to the middle of the exported image.

      • y (optional, number):

        Y coordinate of the center of the text. Default to the middle of the exported image.

    Returns

    • (string)
  • svg

    When download is false or the platform is Node.js, returns a XML string. In Node.js, requires the xmldom package to be installed.

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • clip (boolean):

      Indicates if clip

    • margin (optional, number, default: 10):

      Blank space between the edge of the image and its content

    • width (optional, number):

      If specified along with height, specifies the dimensions of the exported image.

    • height (optional, number):

      If specified along with width, specifies the dimensions of the exported image.

    • size (optional, number):

      Specifies both the width and height parameter.

    • clip (optional, boolean, default: false):

      If true, only exports the currently visible part of the graph.

    • background (optional, Color):

      Indicates the background color for the exported image. Transparent by default.

    • texts (optional, boolean, default: true):

      Indicates if texts should be exported.

    Returns

    • (string)

    Example

    var img = new Image(); 
     img.src = 'url/to/image.jpg'; 
     img.onload = function () { 
       ogma.exports.to('png', {clip: true, filename: 'myGraph'}); 
     }
  • xlsx

    When download is false or the platform is Node.js, returns a Blob. This export require the xlsx library to be included (if browser) or to be available through 'require' (if Node.js)

    Arguments

    • download (optional, boolean):

      If true, the user will be prompted a modal window so he can download the exported graph. If callback is not defined, is true by default. If callback is not defined, is false by default.

    • filename (optional, string, default: 'graph'):

      If download is true, the default name for the downloaded file.

    • callback (optional, function(exportContent: any): void):

      Called when the export is done. Takes the result of the export as parameter.

    • what (string):

      Indicates what to export. Must be 'nodes' or 'edges'.

    • which (optional, Array<Id>):

      List of nodes or edges to export (depending on the what parameter). By default, export everything.

filter module

This module allows to select the nodes and edges that must be displayed, by providing a predicate. The visibility of nodes and edges continues to be updated as nodes or edges are added, modified or removed. This module is based on the partitions module. The predicates can either be regular functions or DSL expressions.

This module modifies the hidden variable of nodes and edges.

Only one node filter can be active at a time (for example, calling show two times override the first call).

Using regular function:

ogma.filter.showNodes(function (node) { return node.data.age >= 18; });

Using DSL:

ogma.filter.showNodes(['data.age', '>=', {value: 18}]);

Examples

filter methods

  • showNodes(predicate, [ignoreUndefined])

    Shows every node that satisfy a predicate, and hides the other nodes. Nodes continue to be updated as they are added, removed or updated.

    Arguments

    • predicate (Expression)
    • ignoreUndefined (optional, boolean, default: true):

      If true, if the predicate is a DSL expression, it will return undefined if one of its operand returns undefined.

  • hideNodes(predicate, [ignoreUndefined])

    Hides every node that satisfy a predicate, and shows the other nodes. Nodes continue to be updated as they are added, removed or updated.

    Arguments

    • predicate (Expression)
    • ignoreUndefined (optional, boolean, default: true):

      If true, if the predicate is a DSL expression, it will return undefined if one of its operand returns undefined.

  • showEdges(predicate, [ignoreUndefined])

    Shows every edge that satisfy a predicate, and hides the other edges. Nodes continue to be updated as they are added, removed or updated.

    Arguments

    • predicate (Expression)
    • ignoreUndefined (optional, boolean, default: true):

      If true, if the predicate is a DSL expression, it will return undefined if one of its operand returns undefined.

  • hideEdges(predicate, [ignoreUndefined])

    Hides every edge that satisfy a predicate, and shows the other edges. Nodes continue to be updated as they are added, removed or updated.

    Arguments

    • predicate (Expression)
    • ignoreUndefined (optional, boolean, default: true):

      If true, if the predicate is a DSL expression, it will return undefined if one of its operand returns undefined.

  • removeNodeFilter()

    Removes the filter applied to nodes and restores their original visibility.

  • removeEdgeFilter()

    Removes the filter applied to edges and restores their original visibility.

  • reset()

    Removes the filter applied to both nodes and edges and restores their original visibility.

fps module

Displays the FPS on the top-left corner. Warning: this enabling this feature makes the graph refresh constantly, even when nothing happens. It should only be used for test purposes.

FPS is disabled by default. To enable it:

var ogma = new Ogma({ 
  fps: true 
});

fps settings

NameTypeDefault valueDescription
averagebooleanfalse

Indicates if the average FPS should also be displayed.

generators module

Provides functions to generate graphs.

Examples

generators methods

  • load(generatorName, parameters, [callback])

    Clear the current graph and generate a graph of the selected type.

    Arguments

    • generatorName (string):

      Type of the graph to generate. See the generator section to have the full list.

    • parameters (object):

      Depends on the type of graph.

    • callback (optional, function(): void):

      Called when the graph has been loaded.

    Returns

    • (Promise<void>)

    Example

    ogma.generators.load('random', {nbNodes: 50, nbEdges: 50}).then(function () { console.log('Graph loaded!'); });

generators settings

NameTypeDefault valueDescription
webWorkerbooleantrue

Indicates if the graphs must be generated inside a web worker. Takes more time, but does not freeze the main thread.

Generators

  • balancedTree

    Generates a simple balanced tree. Source: https://github.com/gka/randomgraph.js (license: public domain)

    Arguments

    • nbChildren (number):

      The number of children each node has.

    • height (number):

      The height of the tree.

    Example

    ogma.generators.load('balancedTree', {nbChildren: 2, height: 3}, function () { 
       console.log('Done!'); 
     });
  • barabasiAlbert

    Generates a Barabási–Albert graph. Source: https://github.com/gka/randomgraph.js (license: public domain)

    Arguments

    • nbNodes (number):

      The total number of nodes N > 0

    • m0 (number):

      m0 > 0 && m0 < N

    • m (number):

      M > 0 && M <= m0

  • erdosRenyi

    Generates an Erdős–Rényi graph. Call it with options (n,p) or (n,m). Source: https://github.com/gka/randomgraph.js (license: public domain)

    Arguments

    • nbNodes (number):

      The number of nodes.

    • p (optional, number):

      The probability [0..1] of a edge between any two nodes.

    • nbEdges (optional, number):

      The number of edges.

  • grid

    Generates a grid with n rows and m columns. Source: https://github.com/anvaka/ngraph.generators (license: MIT)

    Arguments

    • n (number):

      The number of rows in the graph.

    • m (number):

      The number of columns in the graph.

    • hsep (optional, number):

      The number of pixels between columns.

    • vsep (optional, number):

      The number of pixels between rows.

  • path

    Generates a path. Source: https://github.com/anvaka/ngraph.generators (license: MIT)

    Arguments

    • length (number):

      The number of nodes.

  • random

    Generates a random graph.

    Arguments

    • nbNodes (number):

      The number of nodes.

    • nbEdges (number):

      The number of edges.

    • nbEdges (boolean, default: true):

      Indicates if the 'text' property should be assigned

geo module

Allows to display nodes which have geographical coordinates (latitude and longitude) on a map.

This module adds two properties to nodes: latitude and longitude. Valid values for geographical zooms can be found here.

The projection model used is Spherical Mercator.

Initializing a small graph:

var ogma = new Ogma({ 
  graph: { 
    nodes: [ 
      {id: 'Paris', lat: 48.858838, long: 2.343436, size: 8}, 
      {id: 'London', lat: 51.509615, long: -0.134514, size: 10} 
    ] 
  }, 
  settings: { 
    geo: { 
      latitudePath: 'lat',           // indicates that the latitude is located in the 'lat' property of nodes 
      longitudePath: 'long',         // indicates that the longitude is located in the 'long' property of nodes 
      tileUrlTemplate: 'http://{s}.myTileProvider.com/{z}/{x}/{y}.png' // indicates from which server the tiles must be retrieved 
      sizeZoomReferential: 5         // Paris will be displayed with a radius of 8 pixels on the screen if the geographical zoom is 5 
    } 
  } 
}); 

ogma.geo.enable(); // Switch to geographical mode

Examples

geo methods

  • enable([callback], [context])

    Enable the geographical mode.

    Arguments

    • callback (optional, Function):

      Callback to execute after full initialization

    • context (optional, object):

      Optional this context for the callback

    Returns

    • (Promise<any>)
  • disable([callback], [context])

    Disable the geographical mode.

    Arguments

    • callback (optional, Function):

      Callback to execute after geo-mode is fully dismissed

    • context (optional, object):

      Optional this context for the callback

    Returns

    • (Promise<any>)
  • isEnabled()

    Indicates if the geographical mode is currently enabled

    Returns

    • (boolean)
  • toggle([context])

    Toggle the geographical mode. * param {Function} [callback] Callback to execute after geo-mode is fully initialized or dismissed

    Arguments

    • context (optional, object):

      Optional this context for the callback

    Returns

    • (Promise<any>)
  • resetCoordinates()

    Restore the longitude and latitude of nodes to their initial longitude and latitude (when the mode was enabled).

  • setView(latitude, longitude, zoom)

    Change the camera position and zoom based on a latitude, longitude, and geographical zoom.

    Arguments

    • latitude (number)
    • longitude (number)
    • zoom (number):

      Value between 0 and the maximum zoom specified in the settings

  • setCenter(latitude, longitude)

    Change the camera position based on a latitude and longitude.

    Arguments

    • latitude (number)
    • longitude (number)
  • setZoom(zoom)

    Change the camera zoom based on a geographical zoom.

    Arguments

    • zoom (number):

      Value between 0 and the maximum zoom specified in the settings

  • getView()

    Returns the current latitude and longitude of the center of the camera, and the geographical zoom.

    Returns

    • ({latitude: number, longitude: number, zoom: number})
  • getCenter()

    Returns the latitude and longitude of the center of the camera

    Returns

    • ({latitude: number, longitude: number})
  • getZoom()

    Returns the current geographical zoom.

    Returns

    • (number)
  • exportBackground(canvas, callback, [cameraConfig])

    Display the map on the specified canvas, for a given camera configuration. The drawing is asynchronous.

    Arguments

    • canvas (object):

      HTML5 canvas on which to display the map

    • callback (function):

      Called after the drawing is done.

    • cameraConfig (optional, {x: number, y: number, zoom: number}):

      Camera information used to draw the map. If omitted, default to the current Ogma camera.

  • whenReady(fn, [context])

    Perform the passed callback immediately, if the geo layout is initialized, or wait for it to be ready otherwise.

    Arguments

    • fn (Function):

      Callback

    • context (optional, object):

      Optional this context for the callback

geo settings

NameTypeDefault valueDescription
latitudePathstring'latitude'

Node path which contains the latitude.

longitudePathstring'longitude'

Node path which contains the longitude.

sizeZoomReferentialnumber5

Indicates at which geo-spatial zoom level the nodes and edges size on screen must be the same as their graph size.

maxZoomLevelnumber17

Maximum geo-spatial zoom.

tileUrlTemplatestring'https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png'

Format of the URL used to search for tiles. Must contain '{z}' (zoom level of the tile), '{x}' and '{y}' (coordinates of the tile). Possible '{s}' (replaced by one of the characters in the tileUrlSubdomains setting).

tileUrlSubdomainsstring'abc'

Values with which the '{s}' string in the URL can be replaced.

tileBuffernumber1

Number of extra tiles to be downloaded around the viewport bounds, to make the panning smoother.

attributionstringnull

HTML string that will be displayed on the corner, indicates the source of the tiles

backgroundColorColor'silver'

Color of the map background (color of the missing tiles).

opacitynumber1

Map baselayer opacity

transitionDurationColor0

Duration of the transition when swapping mode.

backgroundFadingDurationColor500

Duration of the background fading when the geographical mode is disabled

detectRetinabooleanfalse

If user is on a retina display, tiles of deeper zoom level will be requested to utilize the high resolution.

geo events

NameTypeDescription
enabled

Emitted when the geographical mode is enabled

disabled

Emitted when the geographical mode is disabled

loaded

Emitted when the tiles are loaded

ready

Emitted when the transition of the graph to geo mode is complete and you can start manipulating it

graph module

Manages the addition and removal of nodes and edges. When adding nodes or edges, the data is copied into an internal class, which means:

  • the objects provided to addNodes or addEdges are not modified
  • the objects returned by getNode and getEdge are not the same as the objects provided to addNodes and addEdges.

    The id of nodes and edges can be specified as string or number, but internally they are all converted as strings. This means it is not possible to add a node with id "4" if a node with id 4 was previously added.

    The only exception to that is the data property. When existing, this property is shallow copied to the new node or edge.

    This module make the following read-only properties available for nodes and edges:

  • for nodes:

    • id: id of the node
    • edges: list of adjacent edges
    • isNode: true
  • for edges:

    • id: id of the edge
    • source: id of the source node
    • target: id of the target node
    • isNode: false

      In this documentation, the word 'element' means 'node or edge'.

Iterating on nodes and edges:

ogma.graph.nodes.forEach(function (node) { console.log(node.id); }); 
ogma.graph.edges.forEach(function (edge) { console.log(edge.id); });

Creating a read-only property to retrieve the number of adjacent edges::

ogma.graph.addNodeReadOnlyProperty('nbEdges', function (node) { return node.edges.length; }); 

var node = ogma.graph.getNode(myNodeId); 
console.log(node.nbEdges); // Displays the number of adjacent edges of the node
ogma.graph.addProperty(true, 'foo', {type: 'number'}, 2, function (node, value) { console.log(`New 'foo' value for ${node.id}: ${value}`); }); 
 var node = ogma.graph.addNode({id: 'myNode'}); 
 console.log(node.foo); // Displays "2" 
 node.foo = 8;          // Displays "New 'foo' value for myNode: 8" 
 console.log(node.foo); // Displays "8" 
 node.foo = 'bar';      // Raises an exception

Examples

Displaying the content of a node or edge

All properties (except data) of nodes and edges are setter/getter that point to a value stored internally. This is why doing console.log(node) in Node.js will output an empty object. If you want to display the content of a node or edge, use JSON.stringify(node).

Important note about performance

The module provides two methods for adding nodes: addNode and addNodes. When adding several nodes, it is much more efficient to use the addNodes method one time instead of the addNode method several time (same for edges).

The same applies for removeNodes vs removeNode (and same for edges).

graph methods

  • init(nodes, edges)

    Initialize the graph with the specified nodes and edges. Raises an exception if the graph is not empty.

    Arguments

    • nodes (Array<NodeData>):

      Nodes to add.

    • edges (Array<EdgeData>):

      Edges to add.

  • clear()

    Clear the graph, removing every node and edge.

  • addNodes(nodesToAdd)

    Add several nodes at once. Nodes must be objects that have at least one property id, which can either be a string or a number. This id must not be used by another node in the graph.

    The data property, if existing, will be copied to the new object.

    Arguments

    • nodesToAdd (Array<NodeData>):

      List of nodes to add.

    Returns

    • (Array<Node>):

      List of nodes that have been added.

  • addEdges(edgesToAdd)

    Add several edges at once. Edges must be objects that have at least the following properties:

    • id: unique string or number among other edges
    • source: string or number indicating the id of the source node
    • target: string or number indicating the id of the target node

      The data property, if existing, will be copied to the new object.

    Arguments

    • edgesToAdd (Array<EdgeData>):

      List of edges to add

    Returns

    • (Array<Edge>):

      List of edges that have been added

  • removeNodes(nodeIds)

    Remove several nodes from the graph. If a node has adjacent edges, they are removed first.

    Arguments

    • nodeIds (Array<NodeId>):

      Ids of the nodes to remove.

  • removeEdges(edgeIds)

    Remove several edges from the graph.

    Arguments

    • edgeIds (Array<EdgeId>):

      Ids of the edges to remove.

  • addNode(node)

    Add a single node to the graph.

    Arguments

    • node (NodeData)

    Returns

    • (Node):

      Added node.

  • addEdge(edge)

    Add a single edge to the graph.

    Arguments

    • edge (EdgeData)

    Returns

    • (Edge):

      Added edge.

  • removeNode(nodeId)

    Remove a single node from the graph.

    Arguments

    • nodeId (NodeId):

      Id of the node to remove.

  • removeEdge(edgeId)

    Removes a single edge from the graph

    Arguments

    • edgeId (EdgeId):

      Id of the edge to remove.

  • unusedNodeId()

    Returns an id that is not use by any node.

    Returns

    • (string)
  • unusedEdgeId()

    Returns an id that is not use by any edge.

    Returns

    • (string)
  • notifyNodeDataChange(ids)

    Notify the module that the data property of some nodes have changed.

    Arguments

    • ids (Array<NodeId>):

      Ids of the nodes that have changed.

  • notifyEdgeDataChange(ids)

    Notify the module that the data property of some edges have changed.

    Arguments

    • ids (Array<EdgeId>):

      Ids of the nodes that have changed.

  • getNode(nodeId, [throwExceptionIfNotFound])

    Retrieve a node that has a given id.

    Arguments

    • nodeId (NodeId):

      Id of the node.

    • throwExceptionIfNotFound (optional, boolean, default: false):

      Indicates if an exception should be thrown if the node does not exist.

    Returns

    • (Node):

      If exists, returns the node. Else, returns undefined.

  • getEdge(edgeId, [throwExceptionIfNotFound])

    Retrieve a edge that has a given id.

    Arguments

    • edgeId (EdgeId):

      Id of the edge.

    • throwExceptionIfNotFound (optional, boolean, default: false):

      Indicates if an exception should be thrown if the edge does not exist.

    Returns

    • (Edge):

      If exists, returns the edge. Else, returns undefined.

  • cloneNode(node)

    Return a deep copy of a node. Only the properties specified by addProperty are cloned. data is also copied (shallow copy).

    Arguments

    • node (Node):

      Node to clone.

    Returns

    • (NodeData):

      Copy of the node.

  • cloneEdge(edge)

    Return a deep copy of a edge. Only the properties specified by addProperty are cloned. data is also copied (shallow copy).

    Arguments

    • edge (Edge):

      Edge to clone.

    Returns

    • (EdgeData):

      Copy of the edge.

  • getNodeIdList()

    Returns the list of node ids.

    Returns

    • (Array<NodeId>)
  • getEdgeIdList()

    Returns the list of edge ids.

    Returns

    • (Array<EdgeId>)
  • getNodeList([ids])

    Returns some nodes based on ids.

    Arguments

    • ids (optional, Array<string|number|Node>):

      Returns the nodes that match the specified ids. If undefined, returns all nodes.

    Returns

    • (Array<Node>)
  • getEdgeList([ids])

    Returns some edges based on ids.

    Arguments

    • ids (optional, Array<string|number|Edge>):

      Returns the edges that match the specified ids. If undefined, returns all edges.

    Returns

    • (Array<Edge>)

graph attributes

NameTypeDescription
nodesArray<Node>

List of nodes. This property is semantically read-only (you can, but should NOT modify it).

edgesArray<Edge>

List of edges. This property is semantically read-only (you can, but should NOT modify it).

graph events

NameTypeDescription
startInit

Emitted before initialization (the first time nodes or edges are added).

endInit

Emitted after initialization (the first time nodes or edges are added).

clear

Emitted when the graph is cleared (the clear method has been called).

addNodesArray<Node>

Emitted when one or several nodes are added.

addEdgesArray<Edge>

Emitted when one or several edges are added.

removeNodesArray<Node>

Emitted when one or several nodes are removed.

removeEdgesArray<Edge>

Emitted when one or several edges are removed.

nodeDataChangeArray<Node>

Emitted when the data property of one or several nodes change.

edgeDataChangeArray<Edge>

Emitted when the data property of one or several edges change.

groups module

Allows to group multiple nodes together, and multiple edges together. "meta node" (and "meta edge") refer to the node (or edge) that represent the grouping of several other nodes (or edges).

When some nodes or edges are grouped, they still exist in the graph, but are hidden.

This module adds two read-only properties for both nodes and edges:

  • parent: if the node or edge is grouped with other nodes or edges, this property refers to the meta node (or meta edge). Else, it's null.
  • children: if the node or edge is a meta element, this returns the list of "sub-elements" that are part of them

Examples

Groups vs Coalescence

The groups module allows you to create meta-nodes and meta-edges from a list of nodes/edges.

If you wish to have groups managed automatically given a criteria (e.g groups nodes by country), have a look at the coalescence module.

groups methods

  • getMetaNodes()

    Returns the list of meta nodes.

    Returns

    • (Array<Node>)
  • getMetaEdges()

    Returns the list of meta edges.

    Returns

    • (Array<Edge>)
  • getNonMetaNodes()

    Returns the list of non-meta nodes

    Returns

    • (Array<Node>)
  • getNonMetaEdges()

    Returns the list of non-meta edges

    Returns

    • (Array<Edge>)
  • isMetaNode(node)

    Indicates if a node is a meta node.

    Arguments

    • node (Node)

    Returns

    • (boolean)
  • isMetaNode(edge)

    Indicates if a node is a meta edge.

    Arguments

    • edge (Edge)

    Returns

    • (boolean)
  • groupNodes(nodes, method, [animationDuration], [callback])

    Group the specified nodes together. If one of the specified nodes if a meta node, it is removed, and all of its sub-nodes are used instead. If one of the specified nodes is already part of another group, it is removed from the other group before.

    Arguments

    • nodes (Array<Node>):

      Array of nodes that must be grouped together. Objects or ids are accepted.

    • method (function(nodes: Array<Node>): NodeData):

      Function that, given a list of nodes, must return a meta node.

    • animationDuration (optional, number):

      Duration of the grouping animation.

    • callback (optional, function(): void):

      Function called after the grouping animation is finished.

    Returns

    • (Node):

      Meta node that has been added.

  • groupEdges(edges, method, [animationDuration], [callback])

    Group the specified edges together. If one of the specified edges is a meta edge, it is removed, and all of its sub-edges are used instead. If one of the specified edges is already part of another group, it is removed from the other group before.

    Arguments

    • edges (Array<Edge>):

      Array of edges that must be grouped together. Objects or ids are accepted.

    • method (function(edges: Array<Edge>): EdgeData):

      Function that, given a list of edges, must return a meta edge.

    • animationDuration (optional, number):

      Duration of the grouping animation.

    • callback (optional, function(): void):

      Function called after the grouping animation is finished.

    Returns

    • (Edge):

      Meta edge that has been added.

  • ungroupNodes(nodes, [animationDuration], [callback])

    Remove the specified nodes from their group. If meta-nodes are specified, they are removed.

    Arguments

    • nodes (Array<Node>):

      Array of nodes to remove from their group. Objects or ids are accepted.

    • animationDuration (optional, number):

      Duration of the un-grouping animation.

    • callback (optional, function(): void):

      Function called after the animation is finished.

  • ungroupEdges(edges, [animationDuration], [callback])

    Remove the specified edges from their group. If meta-edges are specified, they are removed.

    Arguments

    • edges (Array<Edge>):

      Array of edges to remove from their group. Objects or ids are accepted.

    • animationDuration (optional, number):

      Duration of the un-grouping animation.

    • callback (optional, function(): void):

      Function called after the animation is finished.

  • reset()

    Ungroup all nodes and edges, and removes every meta node and meta edge.

halos module

This module adds the possibility for nodes and edges to have a surrounding halo, if their halo property is true.

Examples

halos settings

NameTypeDefault valueDescription
nodeColorColor'white'

Color of node halos

nodeSizenumber50

Radius in pixels of node halos

nodeStrokeColorColor|undefinedundefined

Color of node halos stroke (undefined = no stroke)

nodeStrokeWidthnumber1

Size in pixels of the node halo stroke

nodeClusteringbooleanfalse

Indicates if node halos that intersects should be merged into a single, bigger halo

nodeClusteringMaxRadiusnumber1000

Radius in pixels of the maximum size a node halo cluster can have

edgeColorColor'white'

Color of the edge halos

edgeSizenumber10

Size in pixels of edge halos

hover module

In charge of highlighting the nodes hovered by the mouse.

Examples

hover settings

NameTypeDefault valueDescription
nodeOuterStrokeColorColor|'inherit'|null'red'

Color of an hovered node's outer stroke. 'inherit' refers to the main node color.

edgeColorColor|'inherit'|null'red'

Color of an hovered edge. 'inherit' refers to the main edge color.

highlightEdgeExtremitiesbooleantrue

If true, also highlights an hovered edge's source and target.

nodeCursorStylestring'pointer'

CSS cursor value when a node is hovered.

edgeCursorStylestring'pointer'

CSS cursor value when an edge is hovered.

nodeTextBackgroundColorColor|null'rgb(220, 220, 220)'

Color of an hovered node's text's background.

edgeTextBackgroundColorColor|null'rgb(220, 220, 220)'

Color of an hovered edge's text's background.

nodeTextFontStylestring|null|undefinedundefined

'italic', 'bold' or 'none'.

edgeTextFontStylestring|null|undefinedundefined

'italic', 'bold' or 'none'.

nodeTextFontColorColor|undefinedundefined

Font color of a hovered node.

edgeTextFontColorColor|undefinedundefined

Font color of a hovered edge.

outlinebooleantrue

Specifies if the hovered elements should be outlined.

nodesbooleantrue

Indicates weather or not hovered nodes must be highlighted.

edgesbooleantrue

Indicates weather or not hovered edges must be highlighted.

delaynumber20

Delay in milliseconds after which nodes and edges are highlighted when hovered.

icons module

Manages node icons.

Icons have the following properties:

  • font (string): font to use for displaying the icon
  • content (string): string to display
  • scale (number): size of the font relative to the node
  • color (color): color of the icon

Add a node with an icon (icon fields that are not specified will use the default values as specified in the settings):

ogma.graph.addNode({ 
  id: 'n0', 
  icon: { 
    content: '+', 
    color: 'blue' 
  } 
});

Change the color of an icon::

ogma.graph.getNode('n0').icon.color = 'red';

Examples

icons settings

NameTypeDefault valueDescription
defaultFontstring'Arial'

Default font to use to display icons.

defaultScalenumber1.4

Default scaling to use for the font size relative to the node size.

defaultColorstring'black'

Default color to use to display icons.

thresholdnumber10

A node's icon is not displayed if the node's size on screen (in pixels) is less than the threshold.

images module

Manages images of nodes.

Images have the following properties:

  • url (string): url of the image
  • scale (number): size of the image relative to the node size (number between 0 and 1)
  • rescale (boolean): indicates if the image should be rescaled to fit the node size
  • duplicate (boolean): if rescale is false, specifies if the image should be duplicated to fill the node

Adding a node with a image:

ogma.graph.addNode({ 
  id: 'myNode', 
  image: { 
    url: 'resources/images/cute_little_cat.jpg', 
    rescale: true 
  } 
});

Modifying an image url:

ogma.graph.getNode('myNode').url = 'resources/images/cute_little_dog.jpg';

Examples

images settings

NameTypeDefault valueDescription
defaultScalenumber1

Default scale to use

defaultRescalebooleantrue

Indicates if images should be rescale by default

defaultDuplicatebooleanfalse

Indicates if images should be duplicated by default

thresholdnumber1

A node's image is not displayed if the node's size on screen (in pixels) is less than the threshold.

imports module

Allows to import graph from external files.

Examples

imports methods

  • from(format, file, [parameters])

    Download a remote file and parse it according to the specified format. It their is no error during the download and parsing, it clears the graph and fills it with the data contained in the file.

    Arguments

    • format (string):

      Format of the file. See the import section to have the list of available formats.

    • file (string):

      Url of the file to download

    • parameters (optional, object|function(success: boolean): void):

      If this is a function, it corresponds to the onEnd parameter.

      • batchSize (optional, number):

        Indicates the maximum number of elements that can be loaded at once. The lowest the value is, the longer the graph will take to be imported, but the less frozen the thread will be. 0 loads everything at once. Default value: see settings.

      • onEnd (optional, function(success: boolean): void):

        Function called once the file has been parsed. Takes one argument: true if everything worked correctly, false otherwise.

      • preProcess (optional, function(graph: {nodes: Array<NodeData>, edges: Array<EdgeData>}): void):

        Called after the file is parsed, but before it is added to Ogma. Takes a graph as parameter.

    Returns

    • (Promise<void>)

    Example

    Simple example:

    ogma.imports.from('files/graph.gexf', 'gexf').then(function () { 
      console.log('Graph imported!'); 
    }).catch(function (error) { 
      console.log(`Error during parsing: ${error}`); 
    });

imports settings

NameTypeDefault valueDescription
webWorkerbooleantrue

Indicates if the imports should be done with a web worker (longer, but doesn't freeze the main thread). The gexf parser does not support this option.

batchSizenumber0

If greater than 0, the nodes and edges will by default be added by packs instead of everything at the same time. This allows the main thread not to be frozen for too long, but increases the total time spent loading the graph.

keyboard module

Manages the states of the keys and allow to call functions when some given combination of keys is pressed.

Note on how to identify a key:

  • Letters and numbers are identified with themselves (for example, if you want to refer to the key 'A', use the string 'a') (use lowercase)
  • Other keys: 'shift', 'ctrl', 'alt', 'space'

    Notice that in Ogma, 'ctrl' also references the cmd key on Mac.

Displaying any key that is pressed in the console:

ogma.events.bind('keyboard.keyDown', function (key) { 
  console.log(key); 
});

keyboard methods

  • bind(keys, handler)

    Bind a key or a combination of key to an action. See the module documentation to know how to reference keys with a string.

    Arguments

    • keys (string|number|Array<string|number>):

      List of space separated keys to bind OR key code identifying the key to bind, OR array of string or number representing the keys to bind

    • handler (function):

      Function to call when the specified keys are pressed.

    Examples

    Displaying a message when the user presses 's'::

    // By specifying the key as a string (key identifier) 
    ogma.keyboard.bind('s', function () { console.log('S was pressed.'); }); 
    
    // By specifying the JavaScript key code 
    ogma.keyboard.bind(83, function () { console.log('S was pressed.'); });

    Displaying a message when the user pressed ctrl + s::

    // By specifying a space-separated list of key identifiers 
    ogma.keyboard.bind('ctrl s', function () { console.log('CTRL + S pressed.'); }); 
    
    // By specifying an array of key identifiers 
    ogma.keyboard.bind(['ctrl', 's'], function () { console.log('CTRL + S pressed.'); }); 
    
    // By specifying an array of JavaScript codes 
    ogma.keyboard.bind([17, 83], function () { console.log('CTRL + S pressed.'); });
  • isPressed(key)

    Indicates if a key is pressed.

    Arguments

    • key (string|number):

      Key to check (key identifier of key code).

    Returns

    • (boolean)

keyboard events

NameTypeDescription
keyboard.keyDownstring, number

Emitted when the user presses a key. First argument is the string representation of the key, second argument is the JavaScript code of the key.

keyboard.keyUpstring, number

Emitted when the user releases a key. First argument is the string representation of the key, second argument is the JavaScript code of the key.

lasso module

Allows the user to select nodes by drawing a circle around them.

Enable it with ogma.lasso.start(). Then:

  • by default, the surrounded nodes will replace the selection
  • if the user presses the ctrl (or cmd) key, surrounded nodes will be added to the selection
  • if the user presses the alt key, surrounded nodes will be removed from the selection

Examples

lasso methods

  • start()

    Start the lasso mode.

  • stop()

    Stop the lasso mode.

  • isActive()

    Indicates if the lasso is active.

    Returns

    • (boolean)

lasso settings

NameTypeDefault valueDescription
strokeColorColor'black'

Lasso stroke color

strokeWidthnumber1

Lasso stroke width

cursorStylestring'cell'

Cursor style when the lasso is active

addKeystring|null'ctrl'

If the specified key is pressed when the mouse is released, the nodes will be added to the selection instead of replacing it.

removeKeystring|null'alt'

If the specified key is pressed when the mouse is released, the nodes will be removed from the selection instead of replacing it.

layouts module

In charge of managing the layouts. The full list of layouts can be found in the layout section.

Examples

Layouts in Node.js

Node.js doesn't provide native web workers. If you want to run a web worker in the background in Node.js, you need to install the webworker-threads package.

layouts methods

  • start(layoutName, [layoutParams], [syncParameters])

    Starts the specified layout algorithm. Fails if another layout is already running. The algorithm will run in the background and update the nodes' position when it is finished. The valid layout names and the corresponding parameters can be found in the layout section.

    Arguments

    • layoutName (string):

      Name of the layout

    • layoutParams (optional, object):

      Layout parameters, depends on the layout algorithm.

    • syncParameters (optional, object)
      • duration (optional, number):

        Duration of the animation when the graph is updated

      • onSync (optional, function(): void):

        Function called every time the graph is updated

      • onEnd (optional, function(): void):

        Function called after the last graph update

      • useWebWorker (optional, boolean):

        Indicates if the layout should be computed inside a web worker. Default: see settings.

    Returns

    • (Promise<void>)

    Example

    ogma.layouts.start('concentric', { centralNode: 'myNode' }).then(function () { console.log('Layout done!'); });
  • stop()

    Stops the current layout.

  • isRunning()

    Indicates if a layout is currently running.

    Returns

    • (boolean)

layouts settings

NameTypeDefault valueDescription
defaultSyncDurationnumber500

Indicates the default duration (in ms) of the animation when the graph is updated (the movement of the nodes).

skipTextDrawingbooleantrue

If true, texts will not be displayed during the graph update animation.

useWebWorkerbooleantrue

If true, the layout will be computed within a web worker.

layouts events

NameTypeDescription
layouts.start

{layoutName: string, ids: Array<NodeId>}

layouts.end

{layoutName: string, newPosition: {x: Array<number>, y: Array<number>}, previousPosition: {x: Array<number>, y: Array<number>}, ids: Array<NodeId>}

Available layouts

  • concentric

    Concentric layout. This layout takes a base node as parameter and organizes the graph so the nodes close to the selected node are close to it spatially.

    Arguments

    • centralNode (Id):

      Id of the central node

    • nodes (optional, Array<Id>):

      List of ids of nodes on which the layout must be applied. If omitted, the layout is applied to all nodes.

    • centerX (optional, number):

      X coordinate where the central node must be moved, if different from the central node X

    • centerY (optional, number):

      Y coordinate where the central node must be moved, if different from the central node Y

    • sortBy (optional, string):

      Indicates the property from which the nodes must be sorted, or 'random'.

    • clockWise (optional, boolean, default: true):

      Specifies if the nodes must be ordered clockwise.

    • allowOverlap (optional, boolean, default: false):

      Specifies if nodes are allowed to overlap.

    • circleHopRatio (optional, number, default: 5):

      If allowOverlap is false, specified the space between each ring, relative to the highest node size.

    Example

    ogma.layouts.start('concentric', { centralNode: 'n0', sortBy: 'degree' });
  • forceLink

    Force link layout.

    Arguments

    • nodes (optional, Array<Node|NodeId>):

      List of ids of nodes on which the layout must be applied. If omitted, tha layout is applied to all nodes.

    • scalingRatio (optional, number, default: 100):

      Distance factor between nodes. A greater value increases the distance.

    • gravity (optional, number, default: 1):

      Force which attracts nodes to the center of the graph. A greater value makes the graph more compact.

    • adjustSizes (optional, boolean, default: false):

      Avoid node overlapping if true by taking node size into account. Decreases the performance of the algorithm.

    • edgeWeightInfluence (optional, number, default: 0):

      Increase attraction force between nodes connected with edges of positive weights. Disabled by default. Values are the power of edge weight, 0 (default) means treating all weights as equal, 1 means using the weight value as the factor.

    • linLogMode (optional, boolean, default: false):

      Alternative energy model with linear repulsion force and logarithmic attraction force.

    • outboundAttractionDistribution (optional, boolean, default: false):

      Attract super-nodes (with many edges) to the outside.

    • strongGravityMode (optional, boolean, default: true):

      Enable a gravity formula to have a strong effect.

    • slowDown (optional, number, default: 1):

      Reduces the speed of node displacements as the number of iterations increases.

    • alignNodeSiblings (optional, boolean, default: true):

      Align nodes that are linked to the same two nodes only. It enhances readability. This operation is performed once the main layout is finished.

    • nodeSiblingsScale (optional, number, default: 5):

      Distance multiplier between the aligned nodes.

    • nodeSiblingsAngleMin (optional, number, default: 0):

      Force a minimal angle between aligned nodes (from 0 to PI / 2). Node labels may indeed overlap on horizontally aligned nodes.

    • autoStop (optional, boolean, default: true):

      The layout stops automatically if true.

    • maxIterations (optional, number, default: 1000):

      Set a limit to the number of iterations if autoStop: true.

    • avgDistanceThreshold (optional, number, default: 0.01):

      This is the normal stopping condition of autoStop: true. When the average displacements of nodes is below this threshold, the layout stops.

    • startingIterations (optional, number, default: 10):

      Number of iterations to be run before the first update of the graph visualization.

    • iterationsPerRender (optional, number, default: 10):

      Number of iterations to be run before each update of the graph visualization.

    • barnesHutOptimize (optional, boolean, default: false):

      Should we use the algorithm's Barnes-Hut to improve repulsion's scalability (O(n²) to O(nlog(n)))? This is useful for large graphs (5000+ nodes) but harmful to small ones.

    • barnesHutTheta (optional, number, default: 0.5):

      Theta parameter of the Barnes-Hut optimization.

    • nodeMass (optional, function(node:Node):number):

      Function that reads the node masses. If nothing is provided, node degree + 1 will be used as the weight.

    • edgeWeight (optional, function(edge:Edge):number):

      Function that reads the edge weights. If nothing is provided, 1 will be used for all nodes.

    Example

    ogma.layouts.start('forceLink', { 
       barnesHutOptimize: false 
     }, { 
       duration: 500 
     });
  • grid

    Arrange the nodes in a grid.

    Arguments

    • nbRows (number):

      Indicates the desired number of rows. If neither nbRows or nbCols are specified, the layout will attempt to make a square.

    • nbCols (number):

      Indicates the desired number of cols. If neither nbRows or nbCols are specified, the layout will attempt to make a square.

    • nodes (optional, Array<Id>):

      List of ids of nodes on which the layout must be applied. If omitted, tha layout is applied to all nodes.

    • sortBy (optional, string):

      Indicates the property from which the nodes must be sorted. Can also be 'random', in which case the node order is randomized.

    • reverse (optional, boolean, default: false):

      If true, the nodes will be sorted in reverse order.

    Example

    Arrange the nodes in 3 rows, sorting them from the largest to the smallest.:

    ogma.layouts.start('grid', { sortBy: 'size', reverse: true, nbRows: 3 });
  • radial

    Radial (concentric) layout positions nodes around the selected one based on their graph-theoretical distance (shortest path in the graph, connecting them). If there are subgraphs or nodes not reachable from the central node, they will be pushed outwards, but still placed around the layout in a readable way.

    Arguments

    • centralNode (Id):

      Id of the central node

    • nodes (optional, Array<Id>):

      Ids of nodes to run the layout on.

    • centerX (optional, number):

      X coordinate where the central node must be moved, if different from the central node X

    • centerY (optional, number):

      Y coordinate where the central node must be moved, if different from the central node Y

    • allowOverlap (optional, boolean, default: false):

      Specifies if nodes are allowed to overlap.

    • repulsion (optional, number, default: 1):

      Increase or decrease the repulsion force between the nodes on the same levels. Values smaller than 1 will result in more compact placement along the layers.

    • radiusDelta (optional, number, default: 0):

      You can specify a constant distance between the layout layers, in this case radiusRatio will be ignored

    • radiusRatio (optional, number, default: Math.SQRT2):

      Ratio between the radii of adjacent concentric layers: R[n+1] = R[n] × ratio

    • nodeGap (optional, number, default: 10):

      Additional gap between the nodes that belong to one layer

    • maxIterations (optional, number, default: 100):

      Maximum number of layout sweeps

    • iterationsPerRender (optional, number, default: 20):

      Layout iterations per update.

    • renderSteps (optional, boolean, default: false):

      Render intermediate results, before the algorithm converges. That means sending the calculated positions every iterationsPerRender iterations.

    • epsilon (optional, number, default: 0.001):

      Layout precision. Smaller number means better precision but longer computation time

    Example

    ogma.layouts.start('radial', { centralNode: 'n0', radiusDelta: 200 });
  • hierarchical

    Dagre layout. This layout is NOT available through the layouts module. See the dagre module.

legend module

Displays a legend based on the design module.

The word "widget" refers to a box that describe the meaning of a visual variable (e.g: node color, edge size, etc).

The legend is disabled by default. To enable it:

var ogma = new Ogma({ 
  settings: { 
    legend: { 
      enabled: true 
    } 
  } 
});

Examples

legend methods

  • reload()

    Reload the legend

  • setTitleFunction(f)

    Set the method that determines the title of the widgets.

    Arguments

    • f (null|function(propertyPath: string, elementType: string): string):

      Must return a string, takes 2 parameters: the full path of the property (e.g: 'data.properties.fundingtotal') and the type of elements ('node' or 'edge') If null is specified, it will use the default function (the last part of the property name is returned, e.g 'fundingtotal').

    Example

    ogma.legend.setTitleFunction(function (propertyPath) { 
       return propertyPath.split('.').pop().toUpperCase(); // FUNDING_TOTAL 
     });
  • setVisible(visible)

    Show or hide the legend..

    Arguments

    • visible (boolean)
  • isVisible()

    Indicates if the legend is visible.

    Returns

    • (boolean)

legend settings

NameTypeDefault valueDescription
enabledbooleanfalse

Indicates if the legend is enabled

widgetWidthnumber130

Width (in pixels) of the widget

fontFamilystring'Arial'

Font used for displaying text

fontSizenumber10
fontColorstring'black'
titleFontSizenumber12
titleFontColorstring'black'
titleMaxLengthnumber20

Title that have more characters that this vlaue are truncated

titleTextAlignstring'left'
shapeColorstring'grey'
backgroundColorstring'white'
borderColorstring'black'
borderRadiusnumber0
borderWidthnumber1
innerMarginnumber10
outerMarginnumber5
circleStrokeWidthnumber5
positionstring

One of: 'top', 'bottom', 'left', 'right'

locate module

Localization module. Its main feature is to center the screen on the graph.

locate methods

  • center([parameters])

    Centers the camera on the graph, adjusting its position and zoom.

    Arguments

    • parameters (optional, object)
      • duration (optional, number, default: 0):

        Duration of the camera movement, in milliseconds.

      • callback (optional, function(): void):

        Function to call once the camera has been centered.

      • finalZoom (optional, number):

        If specified, indicates which zoom the camera is expected to have (ignores padding).

      • easing (optional, string):

        Easing function. List of available values in the easing section.

      • padding (optional, object)
        • top (optional, number):

          Top padding (in pixels).

        • bottom (optional, number):

          Bottom padding (in pixels).

        • left (optional, number):

          Left padding (in pixels).

        • right (optional, number):

          Right padding (in pixels).

    Returns

    • (Locate):

      Locate module

  • nodes(nodes, [parameters])

    Locate a set of nodes

    Arguments

    • nodes (Array<Node|NodeId>|undefined):

      Set of ids of the nodes to locate. If undefined, locate all nodes.

    • parameters (optional, object)
      • duration (optional, number, default: 0):

        Duration of the camera movement, in milliseconds.

      • callback (optional, function(): void):

        Function to call once the camera has been centered.

      • finalZoom (optional, number):

        If specified, indicates which zoom the camera is expected to have (ignores padding).

      • easing (optional, string):

        Easing function. List of available values in the easing section.

      • padding (optional, object)
        • top (optional, number):

          Top padding (in pixels).

        • bottom (optional, number):

          Bottom padding (in pixels).

        • left (optional, number):

          Left padding (in pixels).

        • right (optional, number):

          Right padding (in pixels).

    Returns

    • (Locate):

      Locate module

  • edges(edges, [parameters])

    Locate a set of edges

    Arguments

    • edges (Array<Edge|EdgeId>|undefined):

      Set of ids of the edges to locate. If undefined, locate all edges.

    • parameters (optional, object)
      • duration (optional, number, default: 0):

        Duration of the camera movement, in milliseconds.

      • callback (optional, function(): void):

        Function to call once the camera has been centered.

      • finalZoom (optional, number):

        If specified, indicates which zoom the camera is expected to have (ignores padding).

      • easing (optional, string):

        Easing function. List of available values in the easing section.

      • padding (optional, object)
        • top (optional, number):

          Top padding (in pixels).

        • bottom (optional, number):

          Bottom padding (in pixels).

        • left (optional, number):

          Left padding (in pixels).

        • right (optional, number):

          Right padding (in pixels).

    Returns

    • (Locate):

      Locate module

  • nodesBoundingBox([nodes])

    Returns the bounding box of a set of nodes.

    Arguments

    • nodes (optional, Array<Node>):

      Set of nodes. If omitted, uses all nodes of the graph.

    Returns

    • ({minX: number, minY: number, maxX: number, maxY: number, cx: number, cy: number, width: number, height: number, maxSize: number})
  • edgesBoundingBox([edges])

    Returns the bounding box of a set of edges.

    Arguments

    • edges (optional, Array<Edge>):

      Set of edges. If omitted, uses all edges of the graph.

    Returns

    • ({minX: number, minY: number, maxX: number, maxY: number, cx: number, cy: number, width: number, height: number, maxSize: number})
  • graphInCamera()

    Indicates if at least one node is inside the camera.

    Returns

    • (boolean)

locate settings

NameTypeDefault valueDescription
centerOnResizebooleanfalse

Indicates if the camera should be centered on the graph when the window is re-sized.

centerAtInitbooleantrue

Indicates if the camera should be centered on the graph at initialization.

defaultLeftPaddingnumber0

Size of the empty space (in pixels) to leave on the left of the screen when centering the camera.

defaultRightPaddingnumber40

Size of the empty space (in pixels) to leave on the right of the screen when centering the camera.

defaultTopPaddingnumber0

Size of the empty space (in pixels) to leave on the top of the screen when centering the camera.

defaultBottomPaddingnumber0

Size of the empty space (in pixels) to leave on the bottom of the screen when centering the camera.

defaultEasingstring'quadraticInOut'

Default easing to use when moving the camera. The list of available values can be found in the easing section.

maxNodeSizeOnScreennumber|null100

The camera will stop zooming if a node size on the screen reaches this value (in pixels). null disables this feature.

mouse module

Manages the mouse.

Displaying the mouse coordinates when the user left click:

ogma.events.bind('mouse.click', function (x, y, button) { 
  if (button === 'left') { 
    console.log('x = ' + x + ', y = ' + ogma.mouse.y); 
  } 
});

Examples

mouse attributes

NameTypeDescription
xnumber

X coordinate of the mouse.

ynumber

Y coordinate of the mouse.

leftboolean

Indicates if the left button of the mouse is currently pressed.

rightboolean

Indicates if the right button of the mouse is currently pressed.

middleboolean

Indicates if the middle button of the mouse is currently pressed.

mouse settings

NameTypeDefault valueDescription
enabledbooleantrue

Indicates if the mouse should be enabled.

doubleClickTimernumber200

Maximum number of milliseconds than can pass between two click so the second one is treated as a double click.

eventRatenumber15

Minimum amount of milliseconds that must pass before the same event is emitted a second time.

wheelEnabledbooleantrue

Indicates if the mouse's wheel events should be enabled.

disableWheelUntilMouseDownbooleanfalse

If true, disables the mouse.wheel event until the user clicks on the DOM element.

mouse events

NameTypeDescription
mouse.downnumber, number, string

Emitted when the user presses a button. The first two parameters indicates the mouse coordinates, the third indicates the button ('left', 'middle' or 'right').

mouse.upnumber, number, string

Emitted when the user releases a button. The first two parameters indicates the mouse coordinates, the third indicates the button ('left', 'middle' or 'right').

mouse.clicknumber, number, string

Emitted when a after a mouse.down and mouse.up events are emitted, if the mouse has not moved. The first two parameters indicates the mouse coordinates, the third indicates the button ('left', 'middle' or 'right').

mouse.doubleClicknumber, number, string

Emitted when a after a mouse.down and mouse.up events are emitted two times, if the mouse has not moved. The first two parameters indicates the mouse coordinates, the third indicates the button ('left', 'middle' or 'right').

mouse.movenumber, number

Emitted when a mouse movement or touch movement is performed by the user. The two parameters indicates the mouse coordinates.

mouse.leave

Emitted when the mouse leaves the DOM element

mouse.wheelnumber

Emitted when the mouse wheel is used, or when the user moves their fingers in opposite directions. The value is 1 or -1 depending on the wheel direction.

outlines module

Add the possibility to have a shadow effect on nodes and edges. Adds a outline property to both nodes and edges: each node or edge that have this property set to true will have an outline displayed.

Examples

outlines settings

NameTypeDefault valueDescription
nodeThresholdnumber|undefinedundefined

Size of a node (in pixels) under which the outline is not displayed. If undefined, default to the nodeInnerStrokeThreshold setting of the shapes module.

edgeThresholdnumber5

Size of an edge (in pixels) under which the outline is not displayed.

nodeRelativeSizenumber1.1

Size (radius) of the outline relative to a node size.

nodeAbsoluteSizenumber0

Additional node outline radius in pixels.

nodeRelativeOffsetYnumber0.15

Offset on the Y coordinate relative to the node size.

nodeAbsoluteOffsetYnumber1

Offset on the Y coordinate in pixels.

edgeRelativeSizenumber1.1

Size (width) of the outline relative to an edge size.

edgeAbsoluteSizenumber2

Additional edge outline width in pixels.

edgeRelativeOffsetYnumber0.15

Offset on the Y coordinate relative to the edge size.

edgeAbsoluteOffsetYnumber1

Offset on the Y coordinate in pixels.

colorColor'rgba(0, 0, 0, 0.36)'

Color of the outline.

partitions module

Allows to split nodes and edges into multiple lists, based on expressions. These lists are updated as elements are added, updated and removed.

This example shows how to group nodes according to their data.location property:

var ogma = new Ogma({ 
  graph: { 
    nodes: [ 
      {id: 0, data: {location: 'France'}}, 
      {id: 1, data: {location: 'USA'}}, 
      {id: 2, data: {location: 'Russia'}}, 
      {id: 3, data: {location: 'USA'}}, 
    ] 
  } 
}); 

var partitionList = ogma.partitions.nodes(function (node) { return node.data.location; }); // Put all the nodes that have the same location in the same partition 
console.log(Object.keys(partitionList.partitions));                    // "France,USA,Russia" 
console.log(partitionList.partitions['USA'].map(function (node) { return node.id; });      // "1,3" 

ogma.graph.addNode({id: 4, data: {location: 'USA'}}); 
console.log(partitionList.partitions['USA'].map(function (node) { return node.id; });      // "1,3,4" 

ogma.graph.getNode(1).data.location = 'France'; 
ogma.graph.notifyNodeDataChange(1);                                    // Notify Ogma that some data has changed for the node "1" 
console.log(partitionList.partitions['USA'].map(function (node) { return node.id; });      // "3,4" 
console.log(partitionList.partitions['France'].map(function (node) { return node.id; });   // "0,1" 

partitionList.kill();  // Stop updating the list

partitions methods

  • nodes(expression, [options], [ignoreUndefined])

    Creates a PartitionList of nodes.

    Arguments

    • expression (Expression):

      Function or DSL expression that will be applied to nodes. This function takes a node as parameter and must returns a string indicating the partition id the node belongs to.

    • options (optional, object)
      • onPartitionChange (optional, function(node: Node, partitionId: string, previousPartitionId: string|undefined): void):

        Called when a node is added, or changes partition. Takes three arguments:

        • The node
        • The new partition id the node belongs to
        • The previous partition id the node was belonging to, or undefined if the node has just been added to the graph (or if the partition list has just been created)
      • onAdd (optional, function(node: Node): void):

        Called when a node is added to the graph, or when the PartitionList is created (called for every node). Takes one argument:

        • The added node
      • onRemove (optional, function(node: Node, partitionId: string): void):

        Called when a node is removed from the graph, or when the PartitionList is killed (called for every node). Takes two arguments:

        • The removed node
        • The partition id it belonged to
      • onKill (optional, function(): void):

        Called when the PartitionList is killed. Takes no argument.

    • ignoreUndefined (optional, boolean, default: false):

      If true, if expression is a DSL expression, it will return undefined if one of its operand returns undefined.

    Returns

    • (PartitionList):

      Object that has a partitions field and kill method.

  • edges(expression, [options], [ignoreUndefined])

    Creates a PartitionList of edges.

    Arguments

    • expression (Expression):

      Function or DSL expression that will be applied to edges. This function takes a edge as parameter and must returns a string indicating the partition id the edge belongs to.

    • options (optional, object)
      • onPartitionChange (optional, function(): void):

        Called when a edge is added, or changes partition. Takes three arguments:

        • The edge
        • The new partition id the edge belongs to
        • The previous partition id the edge was belonging to, or undefined if the edge has just been added to the graph (or if the partition list has just been created)
      • onAdd (optional, function(): void):

        Called when a edge is added to the graph, or when the PartitionList is created (called for every edge). Takes one argument:

        • The added edge
      • onRemove (optional, function(): void):

        Called when a edge is removed from the graph, or when the PartitionList is killed (called for every edge). Takes two arguments:

        • The removed edge
        • The partition id it belonged to
      • onKill (optional, function(): void):

        Called when the PartitionList is killed. Takes no argument.

    • ignoreUndefined (optional, boolean, default: false):

      If true, if expression is a DSL expression, it will return undefined if one of its operand returns undefined.

    Returns

    • (PartitionList):

      Object that has a partitions field and kill method.

pathfinding module

Provides several methods to find the shortest path between two nodes.

Examples

pathfinding methods

  • astar(sourceId, targetId, [options])

    Compute the shortest path between two nodes using the A* algorithm.

    Arguments

    • sourceId (Id):

      Id of the source node.

    • targetId (Id):

      Id of the target node.

    • options (optional, object)
      • pathLengthFunction (optional, function(node1: Node, node2: Node): number):

        Takes two connected nodes as parameters, and returns the distance between them. Default: returns the euclidian distance between the two nodes.

      • heuristicLengthFunction (optional, function(node1: Node, node2: Node): number):

        Takes two nodes as parameters, and returns the heuristic distance between them, Default: returns the euclidian distance between the two nodes.

    Returns

    • (Array<Node>):

      Ordered list of nodes indicating the shortest path, including the source and target nodes.

  • dijkstra(sourceId, targetId, [options])

    Compute the shortest path between two nodes using the dijkstra algorithm.

    Arguments

    • sourceId (Id):

      Id of the source node.

    • targetId (Id):

      Id of the target node.

    • options (optional, object)
      • pathLengthFunction (optional, function(node1: Node, node2: Node): number):

        Takes two connected nodes as parameter, and returns the distance between them. Default: always returns 1.

    Returns

    • (Array<Node>):

      Ordered list of nodes indicating the shortest path, including the source and target nodes.

pieCharts module

Adds the possibility for nodes to have multiple colors, displayed under the form of pie charts. To use it, set the colors property of nodes.

At initialization:

var ogma = new Ogma({ 
  graph: { 
    nodes: [ 
      {id: 'myNode', colors: ['blue', 'white', 'red']} 
    ] 
  } 
});

By modifying a node directly:

ogma.graph.getNode('myNode').colors = ['black', 'white', 'red'];

Set this property to undefined to remove it:

ogma.graph.getNode('myNode').colors = undefined;

Examples

pinning module

Manages the pinned property of nodes. This property is used by certain layout algorithms.

var ogma = new Ogma({ 
   graph: { 
     nodes: [ 
       {id: 0, pinned: true}, 
       {id: 1} 
     ] 
   } 
 }); 
 
 console.log(ogma.pinning.list().map(function (node) { return node.id; }); // "0" 
 
 ogma.graph.getNode(1).pinned = true; 
 
 console.log(ogma.pinning.list().map(function (node) { return node.id; }); // "0,1"

pinning methods

  • getPinnedNodes()

    Returns the list of pinned nodes.

    Returns

    • (Array<Node>)
  • getUnpinnedNodes()

    Returns the list of unpinned nodes.

    Returns

    • (Array<Node>)

pulses module

Provides the ability to highlight nodes and edges by displaying pulsing circle around them.

Display pulsing circles around the nodes 'n0' and 'n1':

ogma.pulses.nodes(['n0', 'n1']);

Examples

pulses methods

  • nodes(nodes, [options])

    Highlights a single node or a group of nodes.

    Arguments

    • nodes (Node|Id|Array<Node|NodeId>):

      Single node or list of nodes to be highlighted.

    • options (optional, object)
      • nbPulses (optional, number):

        Number of pulses

      • pulseDuration (optional, number):

        Duration of a pulse (in ms)

      • pulseInterval (optional, number):

        Duration between two pulses

      • startColor (optional, Color):

        Starting color of the pulse

      • endColor (optional, Color):

        Ending color of the pulse

  • edges(edges, [options])

    Highlights a single edge or a group of edges.

    Arguments

    • edges (Edge|Id|Array<Edge|EdgeId>):

      Single edge or list of edges to be highlighted.

    • options (optional, object)
      • nbPulses (optional, number):

        Number of pulses

      • pulseDuration (optional, number):

        Duration of a pulse (in ms)

      • pulseInterval (optional, number):

        Duration between two pulses

      • startColor (optional, Color):

        Starting color of the pulse

      • endColor (optional, Color):

        Ending color of the pulse

pulses settings

NameTypeDefault valueDescription
pulseDurationnumber1000

Duration of a pulse.

pulseIntervalnumber300

Interval of time between two pulses.

numberOfPulsesnumber3

Number of pulses.

nodePulseWidthnumber50

Stroke width of node pulses.

nodePulseStartRationumber1

Radius of a node pulse when it spawns, relative to the node size.

nodePulseEndRationumber2

Radius of a node pulse when it dies, relative to the node size.

nodePulseStartColorColor'rgba(0,0,0,0.6)'

Starting color of node pulses.

nodePulseEndColorColor'rgba(0,0,0,0)'

End color of node pulses.

edgePulseWidthnumber10

Stroke width of edge pulses.

edgePulseStartRationumber1

Width ratio of an edge pulse when it spawns, relative to the edge size.

edgePulseEndRationumber2

Width ratio of an edge pulse when it dies, relative to the edge size.

edgePulseStartColorColor'rgba(0,0,0,0.6)'

Starting color of edge pulses.

edgePulseEndColorColor'rgba(0,0,0,0)'

End color of edge pulses.

render module

Low-level module managing the rendering of graphical objects. This module abstracts the way things are rendered: it is used the same way weather the type of rendering is WebGL, canvas or SVG.

By default, it will try to use WebGL if it is available. If it's not, it fallback to canvas. If you want to specify the type of rendering to use, you can specify a render parameter at initialization. If you want to disable rendering (for example if you run the library in Node.js, you can set this value to null.

The 4 acceptable values are: 'webgl', 'canvas', 'svg' and null.

It is not possible to change the rendering method after initialization.

Examples:

Use WebGL renderer, and fails to initialize if it is not available:

 var ogma = new Ogma({render: 'webgl'}); 

Use WebGL if available, and fallback to SVG if unavailable:

 var ogma = new Ogma({render: ['webgl', 'svg']}); 

Disable rendering:

 var ogma = new Ogma({render: null}); 
 

Examples

A word about external fonts

When using an external font (that requires downloading a file), most of the time Ogma will be initialized before the fonts are loaded. When using WebGL it will lead to characters being improperly displayed. To avoid that, you must call the reloadFonts() method when the external fonts are loaded. For example, using the document.fonts.ready promise:

var ogma = new Ogma(); 

document.fonts.ready.then(function () { 
  ogma.render.reloadFonts(); 
}); 

render methods

  • setContainer(DOMElement)

    Set the DOM element used by this Ogma instance. If a string is specified, the element will be lookup up with document.getElementById(). If the argument is null, then Ogma is removed from the current container.

    Arguments

    • DOMElement (HTMLElement|string|null)
  • getContainer()

    Returns the DOM element used by this Ogma instance.

    Returns

    • (HTMLElement|null)
  • getCanvas()

    Returns the DOM canvas element used to display nodes.

    Returns

    • (HTMLElement|null)
  • resize()

    Force the canvas to be re-sized according to the container.

  • atNextFrame(f)

    The specified function will be called at the next frame.

    Arguments

    • f (function(): void):

      Function to call

  • reloadFonts()

    Indicates that the DOM has finished loading fonts.

  • setCursorStyle(style)

    Set the cursor's style.

    Arguments

    • style (string):

      A valid DOM cursor style value.

  • removeCursorStyle(style)

    Removes a cursor style.

    Arguments

    • style (string):

      Style value to remove.

  • fullScreen([value])

    Set the full screen mode.

    Arguments

    • value (optional, boolean):

      Indicates weather to set or remove the full-screen mode. If no value is specified, toggle the full screen mode.

  • isFullScreen()

    Indicates if the instance of Ogma is full screen.

    Returns

    • (boolean)
  • setBackgroundColor(color)

    Set the background color.

    Arguments

    • color (Color|null):

      The desired color, or null for a transparent background.

    Returns

    • (Color|null):

      The previous background color.

  • getBackgroundColor()

    Get the background color.

    Returns

    • (Color|null)

render settings

NameTypeDefault valueDescription
imgCrossOriginstring|null'anonymous'

Indicates the value of the crossOrigin field for DOM images. Valid value: null, 'anonymous', 'use-credentials'.

backgroundColorstring'white'

Background color. Set to null to have a transparent background.

defaultCursorStylestring'default'

Default CSS cursor style.

defaultFontstring'Arial'

Default font to use for the text when no font is specified

webGLAntiAliasingstring'super-sampling'

Indicates the type of anti-aliasing to use when using WebGL. Possible values:

  • 'super-sampling': gives the best results, but slowest method.
  • 'native': use the native anti-aliasing method from the browser. A bit faster than super-sampling (~20%), but circles are not anti-aliased.
  • 'none': disables anti-aliasing, providing a huge performance boost.
webGLFontSamplingSizenumber64

Size in pixels of each font character in WebGL. Higher values will produce better looking texts, but will take more time to be generated and more graphics memory. It is recommended to use a power of 2.

webGLMinimumSVGSizenumbernull

Minimum width and height of internal representation of SVG images in WebGL. SVG images that are smaller than that value will be up-scaled (without quality loss). If null, SVG images are never up-scaled. Setting a high value will ensure that all SVG images are smooth even zoomed-in, but will take more graphics memory.

render events

NameTypeDescription
setContainerHTMLElement|null, HTMLElement|null

Emitted when the container changes. The first argument is the new container, the second argument is the previous container.

selection module

Manages the selection and drag & drop of nodes.

This module adds the active property to nodes and edges, which indicates if the element is currently selected. You can set this property to add a node or edge to the selection.

ogma.graph.getNode('myNode').active = true; // Adds 'myNode' to the selection

Examples

selection methods

  • clear([clearType])

    Clear the selection.

    Arguments

    • clearType (optional, string):

      Clear the selection. 'nodes' or 'edges' can be specified to clear only the appropriate elements.

  • addNodes([nodes])

    Removes all edges from the selection and adds the specified nodes to the selection.

    Arguments

    • nodes (optional, Array<Node|NodeId>):

      Nodes to add to the selection. If not specified, add all nodes to the selection.

  • addEdges([edges])

    Removes all nodes from the selection and adds the specified edges to the selection.

    Arguments

    • edges (optional, Array<Edge|EdgeId>):

      Edges to add to the selection. If not specified, add all edges to the selection.

  • dropNodes([nodes])

    Remove the specified nodes from the selection.

    Arguments

    • nodes (optional, Array<Node|NodeId>):

      Nodes to remove from the selection. If not specified, remove all nodes form the selection.

  • dropEdges([edges])

    Remove the specified edges from the selection.

    Arguments

    • edges (optional, Array<Edge|EdgeId>):

      Edges to remove from the selection. If not specified, remove all edges form the selection.

  • nodes()

    Returns the list of currently selected nodes.

    Returns

    • (Array<Node>)
  • edges()

    Returns the list of currently selected edges.

    Returns

    • (Array<Edge>)
  • nbNodes()

    Returns the number of currently selected nodes.

    Returns

    • (number)
  • nbEdges()

    Returns the number of currently selected edges.

    Returns

    • (number)
  • addNeighbors()

    Add the neighbors of every selected node to the selection.

  • setNodesBy(predicate)

    Set the node selection using a predicate. Nodes that satisfy the predicate will be added to the selection, other will be removed from it.

    Arguments

    • predicate (function(node: Node): boolean)
  • setEdgesBy(predicate)

    Set the edge selection using a predicate. Edges that satisfy the predicate will be added to the selection, other will be removed from it.

    Arguments

    • predicate (function(edge: Edge): boolean)
  • invertNodes([nodes])

    Add to the selection every non-selected node, and removes from the selection every selected node.

    Arguments

    • nodes (optional, Array<Node|NodeId>):

      Nodes to add or remove from the selection. If omitted, applies to every node.

  • invertEdges([edges])

    Add to the selection every non-selected edge, and removes from the selection every selected edge.

    Arguments

    • edges (optional, Array<Edge|EdgeId>):

      Edges to add or remove from the selection. If omitted, applies to every edge.

selection settings

NameTypeDefault valueDescription
nodeOuterStrokeColorColor|'inherit'|null'red'

Outer stroke color of active nodes. 'inherit' refers to the main node color.

nodeTextFontStyle'none'|'italic'|'bold'|undefinedundefined

Font style of selected nodes text. undefined doesn't change their font style.

nodeTextFontColorColor|undefinedundefined

Color of selected nodes' text. undefined doesn't change the color.

nodeTextBackgroundColorColor|undefined|null'rgb(220, 220, 220)'

Color of selected nodes' text background. undefined doesn't change it, null disables the text background.

edgeColorColor|'inherit'|null'red'

Color of selected edges. 'inherit' refers to the edge node color.

edgeTextFontStyle'none'|'italic'|'bold'|undefinedundefined

Font style of selected edges text. undefined doesn't change their font style.

edgeTextFontColorColor|undefinedundefined

Color of selected edges' text. undefined doesn't change the color.

edgeTextBackgroundColorColor|undefined|null'rgb(220, 220, 220)'

Color of selected edges' text background. undefined doesn't change it, null disables the text background.

outlinebooleantrue

Specifies if the selected nodes and edges should be outlined (shadow effect).

manualbooleantrue

Indicates if the nodes and edges should be selectable with the mouse

multiSelectionKeystring|null'ctrl'

If this key is pressed while clicking on a node, the selection is not cleared.

selection events

NameTypeDescription
nodesSelectedArray<Node>

Emitted when some nodes are selected.

nodesUnselectedArray<Node>

Emitted when some nodes are unselected.

edgesSelectedArray<Edge>

Emitted when some edges are selected.

edgesUnselectedArray<Edge>

Emitted when some edges are unselected.

settings module

Manages the settings of modules.

Examples

settings methods

  • get(moduleName, [autoUpdate])

    Get a copy of the current settings of a module.

    Arguments

    • moduleName (string)
    • autoUpdate (optional, boolean, default: false):

      If true, the returned object will be updated when the settings are changed.

    Returns

    • (object)
  • update(moduleName, [settings])

    Update the specified settings of a module.

    Arguments

    • moduleName (string)
    • settings (optional, object):

      Settings to update (if empty of not specified, does nothing).

    Example

    var ogma = new Ogma({ 
       settings: { 
         shapes: { 
           defaultNodeShape: 'square' 
         } 
       } 
     }); 
     
     var s = ogma.settings.get('shapes'); 
     s.defaultNodeShape; // "square" 
     s.defaultEdgeShape; // "line" (default value) 
     
     ogma.settings.update('shapes', { 
       defaultEdgeShape: 'arrow' 
     }); 
     
     s = ogma.settings.get('shapes'); 
     s.defaultNodeShape; // "square" 
     s.defaultEdgeShape; // "arrow";
  • reset(moduleName, [settings])

    Reset a module's settings. Every non-specified setting is given its default value.

    Arguments

    • moduleName (string)
    • settings (optional, object):

      Settings values (if not specified, reset all settings to their default value).

    Example

    var ogma = new Ogma({ 
       settings: { 
         shapes: { 
           defaultNodeShape: 'square' 
         } 
       } 
     }); 
     
     var s = ogma.settings.get('shapes'); 
     s.defaultNodeShape; // "square" 
     s.defaultEdgeShape; // "line" (default value) 
     
     ogma.settings.reset('shapes', { 
       defaultEdgeShape: 'arrow' 
     }); 
     
     s = ogma.settings.get('shapes'); 
     s.defaultNodeShape; // "circle" (back to the default value) 
     s.defaultEdgeShape; // "arrow";

shapes module

Manage the shapes and colors of nodes and edges. Also manages the curvature of edges.

Assigning a shape to nodes and edges at initialization:

var ogma = new Ogma({graph: { 
  nodes: [ 
    {id: 0, shape: 'square'}, 
    {id: 1, shape: 'star'} 
  ], 
  edges: [ 
    {id: 0, source: 0, target: 1, shape: 'arrow'} 
  ] 
}});

Modifying an edge's shape::

ogma.graph.getEdge(0).shape = 'tapered';

Examples

shapes settings

NameTypeDefault valueDescription
defaultNodeShapestringcircle

Default node shape (when a node's shape is not specified or available).

defaultEdgeShapestringline

Default edge shape (when an edge's shape is not specified or available).

defaultNodeColorstring'grey'

Default node color.

nodeInnerStrokeColorstring'white'

Color of nodes' inner stroke.

nodeInnerStrokeWidthnumber2

Width of nodes' inner stroke (pixels).

nodeOuterStrokeWidthnumber5

Width of nodes' outer stroke (pixels).

nodeInnerStrokeThresholdnumber|undefined5

If a node's size (on screen) is under this threshold, its inner stroke is not displayed (undefined = feature disabled).

defaultEdgeColorstring'grey'

Default edge color.

overrideEdgeColorstring|undefinedundefined

Specified weather an edge's color should be overridden by its source or target. Valid values: 'source', 'target' or undefined (not overridden).

edgeStrokeWidthnumber0

Width of edges' stroke in pixels (when selected or hovered for example).

edgesAlwaysCurvybooleanfalse

If true, every edge will be curved.

directedEdgesbooleanfalse

Indicates if parallel edges should be separated.

edgeThresholdnumber|undefinedundefined

If an edge's size (on screen) is under this threshold, it will not be displayed (undefined = feature disabled).

Node shapes

  • circle
  • cross
  • diamond
  • equilateral
  • square
  • star

Edge shapes

  • arrow
  • dashed
  • dotted
  • line
  • tapered

texts module

Manages the text of nodes and edges. It adds a text property to nodes and edges, which indicates the text to display alongside the node or edge.

Specifying text at initialization:

var ogma = new Ogma({graph: {nodes: [ 
  {id: 0, text: 'I am an example node'} 
]}});

Modifying the text after initialization:

ogma.graph.getNode(0).text = 'Text changed';

Removing a text:

ogma.graph.getNode(0).text = undefined;

Examples

texts methods

  • setNodeTextDrawing(value)

    Enable or disable the display of node texts.

    Arguments

    • value (boolean):

      Specifies weather it should be enabled or not.

  • setEdgeTextDrawing(value)

    Enable or disable the display of edge texts.

    Arguments

    • value (boolean):

      Specifies weather it should be enabled or not.

  • setTextDrawing(value)

    Enable or disable the display of both node and edge texts.

    Arguments

    • value (boolean):

      Specifies weather it should be enabled or not.

  • isNodeTextDrawingEnabled()

    Indicates if node texts are enabled.

    Returns

    • (boolean)
  • isEdgeTextDrawingEnabled()

    Indicates if edge texts are enabled.

    Returns

    • (boolean)

texts settings

NameTypeDefault valueDescription
enabledbooleantrue

Indicates if texts should be enabled

preventOverlapbooleantrue

Indicates if overlapping texts must be hidden.

fontFamilystring'Arial'

Font used to display the texts.

nodesbooleantrue

Indicates if the text of nodes must be displayed.

nodeFontColorColor'black'

Font color of node texts.

nodeFontStyle'none'|'bold'|'italic''none'

Font style of node texts.

nodeFontSizeFunction'fixed'|'ratio''fixed'

Indicates if the node text size should be fixed or relative to the node size.

nodeFontSizenumber12

Font size of node texts. Ignored if nodeFontSizeFunction is not 'fixed'

nodeFontSizeRationumber0.2

Font size of node texts relative to the node size. Ignored if nodeFontSizeFunction is not 'ratio'

nodeBackgroundColorColor|null|'inherit''rgba(255,255,255,0.66)'

Node text background color (null = no text background, 'inherit' = same color as the node color).

nodeTextAlignment'right'|'left'|'top'|'bottom'|'center''bottom'

Position of the node texts relative to the node.

nodeSizeThresholdnumber12

If a node size on the screen in pixels is less than this value, the text is not displayed.

nodeMaxTextLengthnumber|undefinedundefined

Node texts that have more characters than this value will be truncated. undefined disables this feature.

nodeBackgroundMarginnumber1

Space (in pixels) between the edge of the text background and the start of the text.

nodeTextOffsetnumber0

Offset (in pixels) of node texts. If null is passed, node outer stroke is going to be taken into account.

nodeMaxTextLineLengthnumber15

If a node text has more characters than this value, it will be split in multiple lines. 0 disables this feature.

backgroundArrowBasenumber6

Size (in pixels) of the text indicator (triangle between the node and text).

nodeOuterStrokeOffsetbooleantrue

Whether or

edgesbooleantrue

Indicates if the text of edges must be displayed.

edgeFontColorColor'black'

Font color of edge texts.

edgeFontStyle'none'|'bold'|'italic''none'

Font style of edge texts.

edgeFontSizeFunction'fixed'|'ratio''fixed'

Indicates if the edge text size should be fixed or relative to the edge size.

edgeFontSizenumber12

Font size of edge texts. Ignored if edgeFontSizeFunction is not 'fixed'

edgeFontSizeRationumber0.1

Font size of edge texts relative to the edge size. Ignored if edgeFontSizeFunction is not 'ratio'

edgeBackgroundColorColor|null|'inherit''rgba(255,255,255,0.33)'

Edge text background color (null = no text background, 'inherit' = same color as the edge color).

edgeSizeThresholdnumber6

If a edge size on the screen in pixels is less than this value, the text is not displayed.

edgeMaxTextLengthnumber|undefinedundefined

Edge texts that have more characters than this value will be truncated. undefined disables this feature.

edgeBackgroundMarginnumber5

Space (in pixels) between the edge of the text background and the start of the text.

edgeTextOffsetnumber4

Offset (in pixels) of edge texts

edgeMaxTextLineLengthnumber0

If an edge text has more characters than this value, it will be split in multiple lines. 0 disables this feature.

tooltip module

Provides the ability to display a tooltip (HTML element) at the mouse position when some specific events occur.

Display a tooltip with a link when the user right click a node:

ogma.tooltip.onRightClickNode(function (node, x, y) { 
  console.log(node.id, 'clicked at', x, y); 
  return '<a href="' + node.data.url + '">Link to node</a>'; 
});

Examples

tooltip methods

  • onNodeHover(f)

    Indicates the tooltip to display when a node is hovered.

    Arguments

    • f (function(node: Node, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the node, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onEdgeHover(f)

    Indicates the tooltip to display when an edge is hovered.

    Arguments

    • f (function(edge: Edge, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the edge, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onNodeClick(f)

    Indicates the tooltip to display when a node is left clicked or touched.

    Arguments

    • f (function(node: Node, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the node, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onEdgeClick(f)

    Indicates the tooltip to display when an edge is left clicked or touched.

    Arguments

    • f (function(edge: Edge, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the edge, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onBackgroundClick(f)

    Indicates the tooltip to display when the background is left clicked or touched.

    Arguments

    • f (function(x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onNodeRightClick(f)

    Indicates the tooltip to display when a node is right clicked.

    Arguments

    • f (function(node: Node, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the node, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onEdgeRightClick(f)

    Indicates the tooltip to display when an edge is right clicked.

    Arguments

    • f (function(edge: Edge, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the edge, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onBackgroundRightClick(f)

    Indicates the tooltip to display when the background is right clicked.

    Arguments

    • f (function(x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onNodeDoubleClick(f)

    Indicates the tooltip to display when a node is double clicked or double tapped.

    Arguments

    • f (function(node: Node, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the node, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onEdgeDoubleClick(f)

    Indicates the tooltip to display when an edge is double clicked or double tapped.

    Arguments

    • f (function(edge: Edge, x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes the edge, x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • onBackgroundDoubleClick(f)

    Indicates the tooltip to display when the background is double clicked or double tapped.

    Arguments

    • f (function(x: number, y: number): (HTMLElement|string|Promise<HTMLElement|string>)):

      Takes x, y as parameters and must return a DOM element or a string. If it is a string, it will be wrapped as the inner HTML of a div.

  • hide()

    Hide the tooltip.

  • isShown()

    Indicates if the tooltip is visible.

    Returns

    • (boolean)

tooltip settings

NameTypeDefault valueDescription
positionstring'top'

Position of the tooltip relative to the mouse. Valid values: 'top', 'bottom', 'right', 'left', 'center'.

autoAdjustbooleantrue

When the mouse if at the edge of the screen, indicates if the tooltip position should be corrected so it fits in the screen.

hoverDelaynumber100

Delay in milliseconds before hover tooltips are shown when a node or edge is hovered.

classNamestringnull

If specified, this class is added to all tooltip DOM elements.

tooltip events

NameTypeDescription
tooltip.showHTMLElement

Emitted when the tooltip is shown.

tooltip.hideHTMLElement

Emitted when the tooltip is hidden.

topology module

Keeps track of the neighborhood and degree of every node.

This module adds the following read-only properties to nodes:

  • degree: number of neighbors
  • inDegree: number of neighbors that are connected to the node by an inbound edge
  • outDegree: number of neighbors that are connected to the node by an outbound edge

topology methods

  • getAdjacentNodes(sourceNodes, [options])

    Returns the list of one or multiple nodes' adjacent nodes.

    Arguments

    • sourceNodes (Node|NodeId|Array<Node|NodeId>):

      List of source nodes

    • options (optional, object)
      • depth (optional, number, default: 1):

        If depth = 1, returns only the adjacent elements. If depth > 1, the function is recursively called with depth - 1 for each adjacent elements (e.g: depth = 2 means "adjacent elements of adjacent elements")

      • direction (optional, string, default: 'both'):

        One of the following: 'in', 'out' or 'both'. Will only follow edges that match this direction.

      • includeSources (optional, boolean, default: false):

        Specifies weather or not the source node(s) must be included.

    Returns

    • (Array<Node>)
  • getAdjacentEdges(sourceNodes, [options])

    Returns the list of one or multiple nodes' adjacent edges.

    Arguments

    • sourceNodes (Node|NodeId|Array<Node|NodeId>):

      List of source nodes

    • options (optional, object)
      • depth (optional, number, default: 1):

        If depth = 1, returns only the adjacent elements. If depth > 1, the function is recursively called with depth - 1 for each adjacent elements (e.g: depth = 2 means "adjacent elements of adjacent elements")

      • direction (optional, string, default: 'both'):

        One of the following: 'in', 'out' or 'both'. Will only include edges that match this direction.

    Returns

    • (Array<Edge>)
  • getAdjacentElements(sourceNodes, [options])

    Returns the list of one or multiple nodes' adjacent elements.

    Arguments

    • sourceNodes (Node|NodeId|Array<Node|NodeId>):

      List of source nodes

    • options (optional, object)
      • type (optional, string, default: 'nodes'):

        Type of adjacent elements. Valid values: 'nodes' or 'edges'.

      • depth (optional, number, default: 1):

        If depth = 1, returns only the adjacent elements. If depth > 1, the function is recursively called with depth - 1 for each adjacent elements (e.g: depth = 2 means "adjacent elements of adjacent elements")

      • direction (optional, string, default: 'both'):

        One of the following: 'in', 'out' or 'both'. Will only follow or include edges that match this direction.

      • includeSources (optional, boolean, default: false):

        If type is 'nodes', specifies weather or not the source node(s) must be included.

    Returns

    • (Array<Node|Edge>)
  • getConnectedComponents([returnIds])

    Returns weakly connected components of the graph. Can return ids or actual nodes

    Arguments

    • returnIds (optional, boolean, default: false):

      Return ids instead of nodes

  • getConnectedComponentByNode(node, [returnIds])

    Returns a weakly connected component of the graph to which the node belongs.

    Arguments

    • node (Node|NodeId)
    • returnIds (optional, boolean, default: false):

      Return ids instead of nodes

touch module

Manages the touch events.

Displaying the finger coordinates when the user touches the screen.:

ogma.events.bind('touch.click', function (x, y) { 
  console.log('x = ' + x + ', y = ' + y); 
});

touch attributes

NameTypeDescription
xnumber

X coordinate of the finger.

ynumber

Y coordinate of the finger.

pressedboolean

Indicates if user is currently touching the screen.

touch settings

NameTypeDefault valueDescription
enabledbooleantrue

Indicates if the touch events should be enabled.

doubleTapTimernumber200

Maximum number of milliseconds between two taps so the second is considered a double tap.

eventRatenumber15

Minimum amount of milliseconds that must pass before the same event is emitted a second time.

touch events

NameTypeDescription
touch.downnumber, number

Emitted when the user presses the screen. The two parameters indicates the finger coordinates (x, y).

touch.upnumber, number

Emitted when the user stops pressing. The two parameters indicates the finger coordinates (x, y).

touch.tapnumber, number

Emitted when a after a touch.down and mouse.up events are emitted, if the finger has not moved. The two parameters indicates the finger coordinates (x, y).

touch.doubleTapnumber, number

Emitted when a after a touch.down and touch.up events are emitted two times, if the mouse has not moved. The two parameters indicates the finger coordinates (x, y).

touch.movenumber, number

Emitted when a touch movement is performed by the user. The two parameters indicates the finger coordinates (x, y).

touch.startGesture

Emitted when the users starts a gesture with two fingers.

touch.gesture{dx: number, dy: number, rotation: number, scale: number}, number, number

Emitted when the user moves two fingers. The first parameter gives some information relative to the previous state of the two fingers, the second and third are the coordinates of the first finger pressed.

touch.endGesture

Emitted when the users ends a gesture with two fingers.

dagre plugin

Dagre layout algorithm.

The plugin requires the dagre library to be in the global scope (window) or available through require('dagre'). If your setup prevents the library from being used in both ways (e.g WebPack), you can explicitly declare the dagre library by doing:

 Ogma.libraries.dagre = dagre; // `dagre` must be the dagre library object 
 

Include the dagre plugin to an Ogma instance:

var ogma = new Ogma({ 
  plugins: ['dagre'] 
});

Examples

dagre methods

  • start([options], [layoutOptions])

    Starts the algorithm.

    Arguments

    • options (optional, object)
      • directed (optional, boolean)
      • multigraph (optional, boolean)
      • compound (optional, boolean)
      • rankdir (optional, string):

        Valid values: 'TB', 'BT', 'LR', 'RL'

    • layoutOptions (optional, object)
      • duration (optional, number):

        Duration of the animation

      • onEnd (optional, function(): void):

        Function called when the layout is finished.

    Returns

    • (boolean):

      true if the layout was successfully executed, false if the layout was already running.

  • stop()

    Stop the dagre layout.

dagre settings

NameTypeDefault valueDescription
defaultDirectedbooleantrue
defaultMultigraphbooleantrue
defaultCompoundbooleanfalse
defaultRankDirstring'TB'

Valid values: 'TB', 'BT', 'LR', 'RL'

defaultDurationnumber0

Default duration of the nodes movement animation.

maxNbNodesnumber500

Maximum allowed number of nodes for the algorithm to start (0 means no maximum).

maxNbEdgesnumber500

Maximum allowed number of edges for the algorithm to start (0 means no maximum).

neo4J plugin

Neo4J connector based on the Bolt protocol. Allows to communicate with Neo4J database.

This plugin relies on the Bolt connector provided by Neo4J (package neo4j-driver).

var ogma = new Ogma({ 
   plugins: ['neo4j'], 
   neo4j: { 
     url: 'localhost:7687', 
     username: 'user', 
     password: 'myPassword' 
   } 
 }); 
 
 ogma.neo4j.query('MATCH (n) OPTIONAL MATCH (n)-[r]-() RETURN n,r LIMIT 100').then( (result) => { 
   console.log('Neo4j records added to the graph: result); 
   ogma.locate.center(); 
 });

Examples

neo4J methods

  • connect(url, auth)

    Connect to a Neo4J database. This method must be called before calling query. It is possible to connect when Ogma is initialized by specifying a neo4j parameter containing three properties url, username and password.

    Arguments

    • url (string):

      The URL for the Neo4j database, for instance "bolt://localhost"

    • auth (Object):

      Authentication credentials.

      • username (string)
      • password (string)
  • query(statement, parameters, [callback])

    Sends a query to the database and add the retrieved nodes and edges to the graph.

    Arguments

    • statement (string):

      Cypher statement to execute

    • parameters (Object):

      Map with parameters to use in statement

    • callback (optional, function(queryResult: any): void):

      Called if the query succeeds. Takes the query result as parameter.

    Returns

    • (Promise<any>)