All versions of this documentation
X

TypeScript

If you wish to use Ogma within a TypeScript application, assuming your files ogma.min.js and ogma.min.d.ts are in the same location:

import Ogma from '/path/to/ogma.min';

let ogma = new Ogma();
ogma.graph.addNode({id: 0});

You can import some other interfaces from the file if you wish to use them in your code, e.g:

import Ogma, {Node, Color} from '/path/to/ogma.min';

function getColor(node: Node) : Color {
  return node.color;
}

let ogma = new Ogma();
var node = ogma.graph.addNode({id: 0, color: 'blue'});

console.log(getColor(node));

WebPack

Ogma has some optional external dependencies to make some of its features work. For example, it requires the neo4j-driver library to connect to a a Neo4j database and use it to populate the graph.

Ogma fetches its optional external dependencies dynamically by looking at the global scope (window) or through require. If you're using WebPack there is a good chance that none of these methods will work for you:

  • WebPack avoids polluting the global scope
  • Calls to require are replaced at compilation, that's why Ogma does not call require directly: to avoid having to include heavy external libraries that may not be useful to the user

If you wish to use features that require external dependencies, you need to declare them by extending the Ogma.libraries object:

Ogma.libraries[moduleName] = library;

For example, assuming you need to use the Neo4J connector and the XLSX export:

let Ogma = require('path/to/ogma.min.js');
Ogma.libraries.xlsx = require('xlsx');
Ogma.libraries['neo4j-driver'] = require('neo4j-driver');

SystemJS

Example on how to use Ogma with SystemJS:

SystemJS.import('ogma.min.js').then(Ogma => {
  var ogma = new Ogma({
    graph: {
      nodes: [{id: 0, color: 'blue'}]
    }
  });

  console.log(ogma.graph.getNode(0).color);
});

To use external libraries used for plugins:

SystemJS.import('ogma.min.js').then(Ogma => {
  SystemJS.import('neo4j-driver').then(neo4j => {
    Ogma.libraries['neo4j-driver'] = neo4j;

    var ogma = new Ogma({plugins: ['neo4j']});
    // code
  });
});

Browserify

To use with browserify, there is nothing special to do. Example:

main.js:

var Ogma = require('path/to/ogma.min');

var ogma = new Ogma({graph: {nodes: [{id: 0, color: 'blue'}]}});
console.log(ogma.graph.getNode(0).color);

In the command line:

$ browserify main.js > bundle.js

RequireJS

Example of usage with requireJS:

<script src="require.js"></script>
<script>
  requirejs(['path/to/ogma-min'], function (Ogma) {
    var ogma = new Ogma({graph: {nodes: [{id: 0, color: 'blue'}]}});
    console.log(ogma.graph.getNode(0).color);
  });
</script>

React

Follow this rule: initialize your Ogma instance in your top-level component, and pass the instance to the sub-components through their properties.

Let's write a quick React application that has the following components:

  • a text that indicates the current number of nodes in the graph
  • two buttons to add and remove a node
  • a component that displays the instance of Ogma

The root component, which initializes Ogma and contains all of of the three components:

class App extends Component {
  constructor(props) {
    super(props);

    // Create the instance of Ogma
    this.ogma = new Ogma({settings: {render: {backgroundColor: 'rgb(220, 220, 220)'}}});
  }

  render() {
    // We pass the instance of Ogma as a property to each child component

    return (
      <div style={{margin: '5px', textAlign: 'center'}}>
        <InfoPanel ogma={this.ogma} />
        <ControlPanel ogma={this.ogma} />
        <Container ogma={this.ogma} />
      </div>
    );
  }
}

InfoPanel, which displays the number of nodes in the graph:

class InfoPanel extends Component {
  constructor(props) {
    super(props);

    // The state contains the number of nodes
    this.state = {nbNodes: 0};
    this.updateNbNodes = this.updateNbNodes.bind(this);
  }

  updateNbNodes() {
    this.setState({nbNodes: this.props.ogma.graph.nodes.length})
  }

  componentDidMount() {
    // When the component is mount, subscribe to events that change its state

    this.updateNbNodes();
    this.props.ogma.events.bind('graph.addNodes', this.updateNbNodes);
    this.props.ogma.events.bind('graph.removeNodes', this.updateNbNodes);
  }

  componentWillUnmount() {
    // When the component is unmounted, there is no need to listen to these events anymore

    this.props.ogma.events.unbind('graph.addNodes', this.updateNbNodes);
    this.props.ogma.events.unbind('graph.removeNodes', this.updateNbNodes);
  }

  render() {
    // The component will be re-rendered when its state is modified, aka when some
    // nodes are added or removed
    return (
      <p>Number of nodes: {this.state.nbNodes}</p>
    );
  }
}

ControlPanel, which provides the two buttons to add/remove nodes:

class ControlPanel extends Component {
  constructor(props) {
    super(props);
    this.counter = 0;
  }

  addNode() {
    let ogma = this.props.ogma;

    ogma.graph.addNode({id: this.counter++, x: Math.random() * 100, y: Math.random() * 100});
    ogma.locate.center();
  }

  removeNode() {
    let ogma = this.props.ogma;

    if (ogma.graph.nodes.length > 0) {
      ogma.graph.removeNode(ogma.graph.nodes[0].id);
      ogma.locate.center();
    }
  }

  render() {
    // The buttons interact with the Ogma instance passed as a property
    return (
      <div>
        <button style={{margin: '5px'}} onClick={() => this.addNode()}>Add node</button>
        <button style={{margin: '5px'}} onClick={() => this.removeNode()}>Remove node</button>
      </div>
    );
  }
}

Container, which displays the Ogma instance:

class Container extends Component {
  componentDidMount() {
    // When the component is mounted, set the rendered HTML as the container of Ogma
    // 'ogma-react' is the id of the HTML element that has been rendererd by the component
    this.props.ogma.render.setContainer('ogma-react');
  }

  componentWillUnmount() {
    // When the component is unmounted, set Ogma as headless
    this.props.ogma.render.setContainer(null);
  }

  render() {
    // Render a div that will act as the Ogma container

    return (
      <div id='ogma-react' style={{width: '1280px', height: '800px'}}></div>
    );
  }
}

The result:

Ogma React

Angular2

To use Ogma in an Angular2 framework, follow those rules: initialize your Ogma instance in a service, declare this service as a provider for your application, then inject it into the components to display visualizations.

Let's write a quick Angular2 application that has the following components:

  • a button to add a node
  • a component that displays the instance of Ogma

Ogma Service

import { Injectable } from '@angular/core';

// Import the library.
import { default as Ogma } from '../../assets/ogma.min';

const OGMA_SETTINGS = {
  settings: {
    render            : {
      backgroundColor: 'rgb(220,220,220)'
    }
  }
};

@Injectable()
export class OgmaService extends Ogma {

  // Create an instance of ogma with the given settings.
  constructor() {
    // Create the instance of Ogma.
    super(OGMA_SETTINGS);
    // Bind events captured by Ogma.
    this.events.bind({
      'captor.doubleClickBackground'  : (x, y) => {
         console.log('Event: double click background : ', x, y);
       }
    });
  }

  // Add a node to the graph.
  public addNodeRandom(){
    // Generate a random position.
    let x :number = Math.floor(Math.random()*100);
    let y :number = Math.floor(Math.random()*100);
    // Retrieve an unused node id.
    let id = this.graph.unusedNodeId();
    this.graph.addNode({id:id, x:x, y:y, text:this.graph.nodes.length.toString()});
    // Center the view to display all nodes.
    this.locate.center();
  }
}

Provide Ogma Service

Declare the Ogma Service in your App Module so it is available to all components.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { OgmaService } from './ogma.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [OgmaService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add Ogma to a Component

Inject the OgmaService into your component. Initialize the OgmaService in the OnInit() function to bind Ogma to the component's container.

import { Component, OnInit } from '@angular/core';
import { OgmaService } from './ogma.service';

@Component({
  selector: 'app-root',
  template: `
    <h1>title</h1>
    <div>
      <button (click)="ogmaService.addNodeRandom()">Add a node</button>
      <div class="graph" id="graph-container"></div>
    </div>`,
  styles: ['.graph {width: 800px;height:600px;border: solid black 2px;}']
})
export class AppComponent implements OnInit {
  title = 'Ogma + Angular2 Hello World!';

  // Inject OgmaService into this component.
  constructor ( private ogmaService: OgmaService ){};

  // Assign Ogma to the graph-container.
  ngOnInit (): void {
    this.ogmaService.render.setContainer('graph-container');
  }
}

The result:

Ogma Angular2JS

Extending Ogma

Ogma is made of modules. When Ogma is initialized, all of its modules are initialized in an order that respects their dependencies.

Each module has three components:

  • dependencies
  • settings
  • events

Here is an example on how to create a module that changes the color of a node when the user right-clicks on it. We will call this module 'example'.

This color will be defined by a setting, and the module will emit an 'example.colorChanged' event when it changes the color of a node, providing the node as parameter.

The module will also provide some methods to enable or disable it.

function ExampleModule(ogma, parameters) {
  // Constructor of the module:
  // `ogma` is the instance of ogma
  // `parameters` is the object passed to Ogma at initialization (containing `settings`, `graph`, etc. Can be used to handle custom parameters).

  var self = this;

  // Get the settings for this module. The second argument ensures the retrieved object will be updated if the user changes the settings of this module
  this._settings = ogma.settings.get('example', true);

  // Create an event. `ogma.events.create` returns a function that trigger the event.
  this._colorChanged = ogma.events.create('example.colorChanged');

  // The module is enabled by default
  this._enabled = true;

  ogma.events.bind('captor.rightClickNode', function (node) {
    if (self._enabled) {
      node.color = self._settings.color;    // Change the color of the node
      self._colorChanged(node);             // Trigger the event
    }
  });
}

// Declare the module dependencies, it relies on three other modules: settings, events and captor
ExampleModule.dependencies = ['settings', 'events', 'captor'];

// Declare the module's settings.
ExampleModule.settings = {
  color: {default: 'blue', type: 'color'}
};

ExampleModule.prototype.enable = function () {
  this._enabled = true;
};

ExampleModule.prototype.disable = function () {
  this._enabled = false;
};

// Add the module to the definition of Ogma
Ogma.modules.example = ExampleModule;

Each property of the settings object must be an object with the following properties:

  • default: the default value for the setting
  • type: the type of the setting. Valid values are 'number', 'positive' (number >= 0), 'string', 'boolean', 'color'
  • check: alternatively to type, check can be a function that check the setting value. This function must return null if the value is ok, or a string describing the error if the value doesn't match the expected format
  • values: additionally to type, values can be an array of values that are valid regardless of the type. For example if you wish to accept a color or null, you can specify 'color' in type and [null] in values

Here is short sample of code that make use of the new module (the previous code must be included before the instance of Ogma is created):

// include code above

var ogma = new Ogma();

// display something when the module changes the color of a node
ogma.events.bind('example.colorChanged', function (node) {
  console.log('color of node ' + node.id + ' changed!');
});

// disable the module
ogma.example.disable();

// enable the module again
ogma.example.enable();