# Get Started with GoJS

GoJS is a JavaScript library for implementing interactive diagrams. This page will show you the essentials of using GoJS.

Because GoJS is a JavaScript library that depends on HTML5 features, you will need to make sure that your page declares that it is an HTML5 document. And of course you need to load the library:

    <!DOCTYPE html>  <!-- HTML5 document type -->
    <html>
    <head>
      <!-- use go-debug.js when developing and go.js when deploying -->
      <script src="go-debug.js"></script>
      . . .

You can download GoJS (and all the samples) here. Alternatively you can link straight to the GoJS provided by CDNJS:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/gojs/1.6.7/go-debug.js"></script>

Each GoJS diagram is contained in an HTML `<div>` element in your HTML page that you give an explicit size:

    <!-- The DIV for a Diagram needs an explicit size or else we will not see anything.
         In this case we also add a background color so we can see that area. -->
    <div id="myDiagramDiv"
         style="width:400px; height:150px; background-color: #DAE4E4;"></div>

In JavaScript code you pass the `<div>`'s `id` when making a Diagram:

    var $ = go.GraphObject.make;
    var myDiagram =
      $(go.Diagram, "myDiagramDiv");

Together, this creates an empty diagram:

Notice that `go` is the "namespace" in which all GoJS types reside. All code uses of GoJS classes such as Diagram or Node or Panel or Shape or TextBlock will be prefixed with "`go.`".

This article will show you by example how to use `go.GraphObject.make` to build GoJS objects. For more detail, read Building Objects in GoJS. Using `$` as an abbreviation for `go.GraphObject.make` is so handy that we will assume its use from now on. If you use `$` for something else in your code, you can always pick a different short variable name, such as `$$` or `MAKE` or `GO`.

## Diagrams and Models

The Nodes and Links of a Diagram are visualizations of data that is managed by a Model. GoJS has a model-view architecture, where Models hold the data (arrays of JavaScript objects) that describe nodes and links, and Diagrams act as views to visualize this data using actual Node and Link objects. Models, not Diagrams, are what you load and then save after editing. You add whatever properties you need for your app on the data objects in the model; you do not add properties to or modify the prototype of the Diagram and GraphObject classes.

Here's an example of a Model and Diagram, followed by the actual diagram it generates:

    var $ = go.GraphObject.make;
    var myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center, // center Diagram contents
          "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo
        });

    var myModel = $(go.Model);
    // in the model data, each node is represented by a JavaScript object:
    myModel.nodeDataArray = [
      { key: "Alpha" },
      { key: "Beta" },
      { key: "Gamma" }
    ];
    myDiagram.model = myModel;

The diagram displays the three nodes that are in the model. Some interaction is already possible:

- Click and drag the background in the above diagram to pan the view.
- Click a node to select it, or press down on and drag a node to move it around.
- To create a selection box, click and hold on the background, then start dragging.
- Use CTRL-C and CTRL-V, or control-drag-and-drop, to make a copy of the selection.
- Press the Delete key to delete selected nodes. (Read about more Keyboard Commands.)
- Since the undo manager was enabled, CTRL-Z and CTRL-Y will undo and redo moves and copies and deletions.

## Styling Nodes

Nodes are styled by creating templates consisting of GraphObjects and setting properties on those objects. To create a Node, we have several building block classes at our disposal:

- Shape, to display pre-defined or custom geometry with colors
- TextBlock, to display (potentially editable) text in various fonts
- Picture, to display images
- Panel, containers to hold a collection of other objects that can be positioned and sized in different manners according to the type of the Panel (like tables, vertical stacks, and stretching containers)

All of these building blocks are derived from the `GraphObject` class, so we casually refer to them as GraphObjects or objects or elements.

We want the model data properties to affect our Nodes, and this is done by way of data bindings. Data bindings allow us to change the appearance and behavior of GraphObjects in Nodes by automatically setting properties on those GraphObjects to values that are taken from the model data. The model data objects are plain JavaScript objects. You can choose to use whatever property names you like on the node data in the model.

The default Node template is simple: A Node which contains one TextBlock. There is a data binding between a TextBlock's `text` property and the model data's `key` property. In code, the template looks like this:

    myDiagram.nodeTemplate =
      $(go.Node,
        $(go.TextBlock,
          // TextBlock.text is bound to Node.data.key
          new go.Binding("text", "key"))
      );

Note that there is no `Node.key` property. But you can get the key for a Node via `someNode.data.key`.

TextBlocks, Shapes, and Pictures are the primitive building blocks of GoJS. TextBlocks cannot contain images; Shapes cannot contain text. If you want your node to show some text, you must use a TextBlock. If you want to draw or fill some geometrical figures, you must use a Shape.

More generally, the skeleton of a Node template will look something like this:

    myDiagram.nodeTemplate =
      $(go.Node, "Vertical" // second argument of a Node/Panel can be a Panel type
        { /* set Node properties here */ },
        // example Node binding sets Node.location to the value of Node.data.loc
        new go.Binding("location", "loc"),

        // GraphObjects contained within the Node
        // this Shape will be vertically above the TextBlock
        $(go.Shape,
          "RoundedRectangle", // string argument can name a predefined figure
          { /* set Shape properties here */ },
          // example Shape binding sets Shape.figure to the value of Node.data.fig
          new go.Binding("figure", "fig")),

        $(go.TextBlock,
          "default text",  // string argument can be initial text string
          { /* set TextBlock properties here */ },
          // example TextBlock binding sets TextBlock.text to the value of Node.data.key
          new go.Binding("text", "key"))
      );

Nesting can be arbitrarily deep, and every class has its own unique set of properties to explore, but this shows the general idea.

Now that we have seen how to make a Node template, let's see a live example. We will make a simple template commonly seen in organizational diagrams — an image next to a name. Consider the following Node template:

- A Node of "Horizontal" Panel type, meaning that its elements will be laid out horizontally side-by-side. It has two elements:
  - A Picture for the portrait, with the image source data bound
  - A TextBlock for the name, with the text data bound

    var $ = go.GraphObject.make;
    var myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center, // center Diagram contents
          "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo
        });

    // define a simple Node template
    myDiagram.nodeTemplate =
      $(go.Node, "Horizontal",
        // the entire node will have a light-blue background
        { background: "#44CCFF" },
        $(go.Picture,
          // Pictures should normally have an explicit width and height.
          // This picture has a red background, only visible when there is no source set
          // or when the image is partially transparent.
          { margin: 10, width: 50, height: 50, background: "red" },
          // Picture.source is data bound to the "source" attribute of the model data
          new go.Binding("source")),
        $(go.TextBlock,
          "Default Text",  // the initial value for TextBlock.text
          // some room around the text, a larger font, and a white stroke:
          { margin: 12, stroke: "white", font: "bold 16px sans-serif" },
          // TextBlock.text is data bound to the "name" attribute of the model data
          new go.Binding("text", "name"))
      );

    var model = $(go.Model);
    model.nodeDataArray =
    [ // note that each node data object holds whatever properties it needs;
      // for this app we add the "name" and "source" properties
      { name: "Don Meow", source: "cat1.png" },
      { name: "Copricat", source: "cat2.png" },
      { name: "Demeter",  source: "cat3.png" },
      { /* Empty node data */  }
    ];
    myDiagram.model = model;

That code produces this diagram:

We may want to show some "default" state when not all information is present, for instance when an image does not load or when a name is not known. The "empty" node data in this example is used to show that node templates can work perfectly well without any of the properties on the bound data.

## Kinds of Models

With a custom node template our diagram is becoming a pretty sight, but perhaps we want to show more. Perhaps we want an organizational chart to show that Don Meow is really the boss of a cat cartel. So we will create a complete organization chart diagram by adding some Links to show the relationship between individual nodes and a Layout to automatically position the nodes.

In order to get links into our diagram, the basic `Model` is not going to cut it. We are going to have to pick one of the other two models in GoJS, both of which support Links. These are `GraphLinksModel` and `TreeModel`. (Read more about models here.)

In GraphLinksModel, we have `model.linkDataArray` in addition to the `model.nodeDataArray`. It holds an array of JavaScript objects, each describing a link by specifying the "to" and "from" node keys. Here's an example where node A links to node B and where node B links to node C:

    var model = $(go.GraphLinksModel);
    model.nodeDataArray =
    [
      { key: "A" },
      { key: "B" },
      { key: "C" }
    ];
    model.linkDataArray =
    [
      { from: "A", to: "B" },
      { from: "B", to: "C" }
    ];
    myDiagram.model = model;

A GraphLinksModel allows you to have any number of links between nodes, going in any direction. There could be ten links running from A to B, and three more running the opposite way, from B to A.

A TreeModel works a little differently. Instead of maintaining a separate array of link data, the links in a tree model are created by specifying a "parent" for a node data. Links are then created from this association. Here's the same example done as a TreeModel, with node A linking to node B and node B linking to node C:

    var model = $(go.TreeModel);
    model.nodeDataArray =
    [
      { key: "A" },
      { key: "B", parent: "A" },
      { key: "C", parent: "B" }
    ];
    myDiagram.model = model;

TreeModel is simpler than GraphLinksModel, but it cannot make arbitrary link relationships, such as multiple links between the same two nodes, or having multiple parents. Our organizational diagram is a simple hierarchical tree-like structure, so we will choose TreeModel for this example.

First, we will complete the data by adding a few more nodes, using a TreeModel, and specifying keys and parents in the data.

    var $ = go.GraphObject.make;
    var myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center, // center Diagram contents
          "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo
        });

    // the template we defined earlier
    myDiagram.nodeTemplate =
      $(go.Node, "Horizontal",
        { background: "#44CCFF" },
        $(go.Picture,
          { margin: 10, width: 50, height: 50, background: "red" },
          new go.Binding("source")),
        $(go.TextBlock, "Default Text",
          { margin: 12, stroke: "white", font: "bold 16px sans-serif" },
          new go.Binding("text", "name"))
      );

    var model = $(go.TreeModel);
    model.nodeDataArray =
    [ // the "key" and "parent" property names are required,
      // but you can add whatever data properties you need for your app
      { key: "1",              name: "Don Meow",   source: "cat1.png" },
      { key: "2", parent: "1", name: "Demeter",    source: "cat2.png" },
      { key: "3", parent: "1", name: "Copricat",   source: "cat3.png" },
      { key: "4", parent: "3", name: "Jellylorum", source: "cat4.png" },
      { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },
      { key: "6", parent: "2", name: "Munkustrap", source: "cat6.png" }
    ];
    myDiagram.model = model;

## Diagram Layouts

As you can see the TreeModel automatically creates the necessary Links to associate the Nodes, but it's hard to tell whose parent is who.

Diagrams have a default layout which takes all nodes that do not have a location and gives them locations, arranging them in a grid. We could explicitly give each of our nodes a location to sort out this organizational mess, but as an easier solution in our case, we will use a layout that gives us good locations automatically.

We want to show a hierarchy, and are already using a TreeModel, so the most natural layout choice is TreeLayout. TreeLayout defaults to flowing from left to right, so to get it to flow from top to bottom (as is common in organizational diagrams), we will set the `angle` property to 90.

Using layouts in GoJS is usually simple. Each kind of layout has a number of properties that affect the results. There are samples for each layout (like TreeLayout Demo) that showcase its properties.

    // define a TreeLayout that flows from top to bottom
    myDiagram.layout =
      $(go.TreeLayout,
        { angle: 90, layerSpacing: 35 });

GoJS has several other layouts, which you can read about here.

Adding the layout to the diagram and model so far, we can see our results:

    var $ = go.GraphObject.make;
    var myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center, // center Diagram contents
          "undoManager.isEnabled": true, // enable Ctrl-Z to undo and Ctrl-Y to redo
          layout: $(go.TreeLayout, // specify a Diagram.layout that arranges trees
                    { angle: 90, layerSpacing: 35 })
        });

    // the template we defined earlier
    myDiagram.nodeTemplate =
      $(go.Node, "Horizontal",
        { background: "#44CCFF" },
        $(go.Picture,
          { margin: 10, width: 50, height: 50, background: "red" },
          new go.Binding("source")),
        $(go.TextBlock, "Default Text",
          { margin: 12, stroke: "white", font: "bold 16px sans-serif" },
          new go.Binding("text", "name"))
      );

    var model = $(go.TreeModel);
    model.nodeDataArray =
    [
      { key: "1",              name: "Don Meow",   source: "cat1.png" },
      { key: "2", parent: "1", name: "Demeter",    source: "cat2.png" },
      { key: "3", parent: "1", name: "Copricat",   source: "cat3.png" },
      { key: "4", parent: "3", name: "Jellylorum", source: "cat4.png" },
      { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },
      { key: "6", parent: "2", name: "Munkustrap", source: "cat6.png" }
    ];
    myDiagram.model = model;

Our diagram is starting to look like a proper organization chart, but we could do better with the links.

## Link Templates

We will construct a new Link template that will better suit our wide, boxy nodes. A Link is a different kind of Part, not like a Node. The main element of a Link is the Link's shape, and must be a Shape that will have its geometry computed dynamically by GoJS. Our link is going to consist of just this shape, with its stroke a little thicker than normal and dark gray instead of black. Unlike the default link template we will not have an arrowhead. And we will change the Link `routing` property from Normal to Orthogonal, and give it a `corner` value so that right-angle turns are rounded.

    // define a Link template that routes orthogonally, with no arrowhead
    myDiagram.linkTemplate =
      $(go.Link,
        // default routing is go.Link.Normal
        // default corner is 0
        { routing: go.Link.Orthogonal, corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#555" }) // the link shape

        // if we wanted an arrowhead we would also add another Shape with toArrow defined:
        // $(go.Shape, { toArrow: "Standard", stroke: null }
        );

Combining our Link template with our Node template, TreeModel, and TreeLayout, we finally have a full organization diagram. The complete code and result diagram are as follows:

    var $ = go.GraphObject.make;

    var myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center, // center Diagram contents
          "undoManager.isEnabled": true, // enable Ctrl-Z to undo and Ctrl-Y to redo
          layout: $(go.TreeLayout, // specify a Diagram.layout that arranges trees
                    { angle: 90, layerSpacing: 35 })
        });

    // the template we defined earlier
    myDiagram.nodeTemplate =
      $(go.Node, "Horizontal",
        { background: "#44CCFF" },
        $(go.Picture,
          { margin: 10, width: 50, height: 50, background: "red" },
          new go.Binding("source")),
        $(go.TextBlock, "Default Text",
          { margin: 12, stroke: "white", font: "bold 16px sans-serif" },
          new go.Binding("text", "name"))
      );

    // define a Link template that routes orthogonally, with no arrowhead
    myDiagram.linkTemplate =
      $(go.Link,
        { routing: go.Link.Orthogonal, corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#555" })); // the link shape

    var model = $(go.TreeModel);
    model.nodeDataArray =
    [
      { key: "1",              name: "Don Meow",   source: "cat1.png" },
      { key: "2", parent: "1", name: "Demeter",    source: "cat2.png" },
      { key: "3", parent: "1", name: "Copricat",   source: "cat3.png" },
      { key: "4", parent: "3", name: "Jellylorum", source: "cat4.png" },
      { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },
      { key: "6", parent: "2", name: "Munkustrap", source: "cat6.png" }
    ];
    myDiagram.model = model;

Now that you are familiar with some of the basics of GoJS, consider perusing the samples to see some of the diagrams possible with GoJS, or read the technical introduction to get an in-depth look at the components of GoJS.