# Diagram Layouts

In general terms, a "layout" is a way of sizing and positioning a collection of objects. HTML has its own layouts for its HTML elements. In GoJS you have already seen many examples of Panel layout, such as Auto or Table, which sizes and positions GraphObjects within a Panel. GoJS also provides Diagram layouts, which position Nodes and route Links within a Diagram or a Group.

Naturally the principal purpose of each diagram Layout is to position nodes, typically by calling Part.move. But layouts also may also result in custom routing of the links, by setting properties on each Link. For example TreeLayout also ensures that links are routed in the expected direction by setting Link.fromSpot and Link.toSpot depending on the TreeLayout.angle. (However, that behavior can be disabled by setting TreeLayout.setsPortSpot and TreeLayout.setsChildPortSpot. The same is true for some other layouts.)

Diagram layouts can be accomplished in several manners. Manual layouts occur because the user moves nodes, thereby establishing new positions for those nodes. Such layouts might be saved in some persistent data format and later loaded using data binding or assignments in code. Programmatic layouts happen when some code executes to set the Part position or location. Automatic layouts are programmatic layouts that are implemented by the Layout class or its subclasses.

## Default Layout

The value of Diagram.layout defaults to an instance of Layout. This kind of layout is unlike all of the other layout subclasses, in that it only sets the position of nodes that do not already have a position -- i.e. where the X or Y of the GraphObject.actualBounds is NaN. It leaves unmodified all nodes that do have a defined position, and it ignores all links.

Many of the examples you have seen so far do not set Diagram.layout and thus use the default layout. Some of the examples data bind the Part.location or GraphObject.position to a data property. Those examples are basically using manual layout, but with the node positions coming from the node data rather than from arrangement by the user.

However many of the examples just allow the standard behavior of the Layout class to assign positions to the nodes in the order in which they are seen by the layout. Those examples are exhibiting automatic layout behavior.

## Automatic Layouts

GoJS offers several kinds of automatic layouts, including:

- GridLayout
- TreeLayout
- ForceDirectedLayout
- LayeredDigraphLayout
- CircularLayout

There are samples for each of these layouts, demonstrating the effects of setting various detailed layout properties:

- GridLayout Sample
- TreeLayout Sample
- ForceDirectedLayout Sample
- LayeredDigraphLayout Sample
- CircularLayout Sample

In the introduction pages and samples you will see many examples that make use of automatic layout by setting the Diagram.layout property. Search the sources of the samples for many more examples.

### Layout Usage

You can set Diagram.layout in a JavaScript statement:

    diagram.layout = new go.ForceDirectedLayout();

Or you can initialize that property using GraphObject,make:

    var diagram = $(go.Diagram, "myDiagramDiv",
                    {
                      layout: $(go.TreeLayout,
                                { angle: 90, nodeSpacing: 10, layerSpacing: 30 })
                    });

We recommend using GraphObject.make whenever you can because of the error checking that it does for property names.

### Grid Layout

A simple layout for placing Nodes in a grid-like arrangement.

        diagram.layout = $(go.GridLayout);
        diagram.contentAlignment = go.Spot.Center;

        // define a simple Node template
        diagram.nodeTemplate =
          $(go.Node, "Spot",  // the Shape will go around the TextBlock
            $(go.Shape, "Ellipse",
              { fill: 'palegreen', stroke: '#333', strokeWidth: 3, width: 40, height: 40 }
              ),
            $(go.TextBlock,
              { margin: 3, font: 'bold 14px sans-serif', stroke: '#333' },  // some room around the text
              // TextBlock.text is bound to Node.data.key
              new go.Binding("text", "key"))
          );

    diagram.linkTemplate =
      $(go.Link,
        // Default routing is go.Link.Normal
        // Default corner is 0
        { corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#333" })
        );

        // create the model data that will be represented by Nodes and Links
        diagram.model = new go.GraphLinksModel(
        [
          { key: "1" },
          { key: "2" },
          { key: "3" },
          { key: "4" },
          { key: "5" },
          { key: "6" },
          { key: "7" },
          { key: "8" },
          { key: "9" },
          { key: "10" },
          { key: "11" },
        ],
        [
        ]);

See the GridLayout Sample for a demonstration of layout options. The Swim Lanes sample demonstrates a customization of GridLayout. See more samples that make use of GridLayout in the samples index.

Tree Layout

This layout positions nodes of a tree-structured graph in layers (rows or columns).

        diagram.layout = $(go.TreeLayout);
        diagram.contentAlignment = go.Spot.Center;

        // define a simple Node template
        diagram.nodeTemplate =
          $(go.Node, "Spot",  // the Shape will go around the TextBlock
            $(go.Shape, "Ellipse",
              { fill: 'palegreen', stroke: '#333', strokeWidth: 3, width: 40, height: 40 }
              ),
            $(go.TextBlock,
              { margin: 3, font: 'bold 14px sans-serif', stroke: '#333' },  // some room around the text
              // TextBlock.text is bound to Node.data.key
              new go.Binding("text", "key"))
          );

    diagram.linkTemplate =
      $(go.Link,
        // Default routing is go.Link.Normal
        // Default corner is 0
        { corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#333" })
        );

        // create the model data that will be represented by Nodes and Links
        diagram.model = new go.GraphLinksModel(
        [
          { key: "1" },
          { key: "2" },
          { key: "3" },
          { key: "4" },
          { key: "5" },
          { key: "6" }
        ],
        [
          { from: "1", to: "2" },
          { from: "1", to: "3" },
          { from: "3", to: "4" },
          { from: "3", to: "5" },
          { from: "3", to: "6" }
        ]);

See the TreeLayout sample for a demonstration of layout options. The Org Chart Editor, Parse Tree, Layer Bands, and Virtualized Tree samples demonstrate customization of TreeLayout. See more samples that make use of TreeLayout in the samples index.

### Force-Directed Layout

Force-directed layout treats the graph as if it were a system of physical bodies with forces acting on them and between them.

        diagram.layout = $(go.ForceDirectedLayout);
        diagram.initialAutoScale = go.Diagram.Uniform;
        diagram.contentAlignment = go.Spot.Center;

        // define a simple Node template
        diagram.nodeTemplate =
          $(go.Node, "Spot",  // the Shape will go around the TextBlock
            $(go.Shape, "Ellipse",
              { fill: 'palegreen', stroke: '#333', strokeWidth: 3, width: 40, height: 40 }
              ),
            $(go.TextBlock,
              { margin: 3, font: 'bold 14px sans-serif', stroke: '#333' },  // some room around the text
              // TextBlock.text is bound to Node.data.key
              new go.Binding("text", "key"))
          );

    diagram.linkTemplate =
      $(go.Link,
        // Default routing is go.Link.Normal
        // Default corner is 0
        { corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#333" })
        );

        // create the model data that will be represented by Nodes and Links
        diagram.model = new go.GraphLinksModel(
        [
          { key: "1" },
          { key: "2" },
          { key: "3" },
          { key: "4" },
          { key: "5" },
          { key: "6" },
          { key: "7" },
          { key: "8" },
          { key: "9" },
          { key: "10" },
          { key: "11" },
        ],
        [
          { from: "6", to: "2" },
          { from: "3", to: "4" },
          { from: "3", to: "5" },
          { from: "3", to: "6" },
          { from: "6", to: "1" },
          { from: "6", to: "7" },
          { from: "4", to: "8" },
          { from: "4", to: "9" },
          { from: "4", to: "10" },
          { from: "4", to: "11" },
        ]);

See the ForceDirectedLayout sample for a demonstration of layout options. That sample also demonstrates a simple customization of ForceDirectedLayout. The Virtualized Force Directed sample demonstrates a more complicated customization of ForceDirectedLayout. See more samples that make use of ForceDirectedLayout in the samples index.

### Layered Digraph Layout

This arranges nodes of directed graphs into layers (rows or columns).

        diagram.layout = $(go.LayeredDigraphLayout);
        diagram.contentAlignment = go.Spot.Center;

        // define a simple Node template
        diagram.nodeTemplate =
          $(go.Node, "Spot",  // the Shape will go around the TextBlock
            $(go.Shape, "Ellipse",
              { fill: 'palegreen', stroke: '#333', strokeWidth: 3, width: 40, height: 40 }
              ),
            $(go.TextBlock,
              { margin: 3, font: 'bold 14px sans-serif', stroke: '#333' },  // some room around the text
              // TextBlock.text is bound to Node.data.key
              new go.Binding("text", "key"))
          );

    diagram.linkTemplate =
      $(go.Link,
        // Default routing is go.Link.Normal
        // Default corner is 0
        { corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#333" })
        );

        // create the model data that will be represented by Nodes and Links
        diagram.model = new go.GraphLinksModel(
        [
          { key: "1" },
          { key: "2" },
          { key: "3" },
          { key: "4" },
          { key: "5" },
          { key: "6" },
          { key: "7" },
        ],
        [
          { from: "1", to: "2" },
          { from: "1", to: "3" },
          { from: "3", to: "4" },
          { from: "3", to: "5" },
          { from: "3", to: "6" },
          { from: "2", to: "5" },
          { from: "1", to: "5" },
          { from: "1", to: "7" },
          { from: "6", to: "7" },
        ]);

See the LayeredDigraphLayout sample for a demonstration of layout options. The Genogram sample demonstrates a complex customization of LayeredDigraphLayout. See more samples that make use of LayeredDigraphLayout in the samples index.

### Circular Layout

This layout positions nodes in a circular or elliptical arrangement.

        diagram.layout = $(go.CircularLayout);
        diagram.contentAlignment = go.Spot.Center;

        // define a simple Node template
        diagram.nodeTemplate =
          $(go.Node, "Spot",  // the Shape will go around the TextBlock
            $(go.Shape, "Ellipse",
              { fill: 'palegreen', stroke: '#333', strokeWidth: 3, width: 40, height: 40 }
              ),
            $(go.TextBlock,
              { margin: 3, font: 'bold 14px sans-serif', stroke: '#333' },  // some room around the text
              // TextBlock.text is bound to Node.data.key
              new go.Binding("text", "key"))
          );

    diagram.linkTemplate =
      $(go.Link,
        // Default routing is go.Link.Normal
        // Default corner is 0
        { corner: 5 },
        $(go.Shape, { strokeWidth: 3, stroke: "#333" })
        );

        // create the model data that will be represented by Nodes and Links
        diagram.model = new go.GraphLinksModel(
        [
          { key: "1" },
          { key: "2" },
          { key: "3" },
          { key: "4" },
          { key: "5" },
          { key: "6" },
          { key: "7" },
        ],
        [
          { from: "1", to: "2" },
          { from: "1", to: "3" },
          { from: "3", to: "4" },
          { from: "3", to: "5" },
          { from: "3", to: "6" },
          { from: "2", to: "5" },
          { from: "1", to: "5" },
          { from: "1", to: "7" },
          { from: "6", to: "7" },
        ]);

See the CircularLayout sample for a demonstration of layout options. The Friend Wheel sample demonstrates a simple customization of CircularLayout. See more samples that make use of CircularLayout in the samples index.

### Custom Layouts

GoJS allows for the creation of custom layouts. The intro page on GoJS extensions gives a simple example of a custom layout. See more samples that make use of custom layouts in the samples index.

There are also many layouts that are extensions -- not predefined in the `go.js` or `go-debug.js` library, but available as source code in one of the three extension directories, with some documentation, and with corresponding samples.

- DoubleTreeLayout: sample at DoubleTreeLayout Sample, defined in DoubleTreeLayout.js
- FishboneLayout: sample at FishboneLayout Sample, defined in FishboneLayout.js
- PackedLayout: sample at PackedLayout Sample, defined in PackedLayout.js
- ParallelLayout: sample at ParallelLayout Sample, defined in ParallelLayout.js
- SepentineLayout: sample at SerpentineLayout Sample, defined in SerpentineLayout.js
- SpiralLayout: sample at SpiralLayout Sample, defined in SpiralLayout.js
- SwimLaneLayout: sample at SwimLaneLayout Sample, defined in SwimLaneLayout.js
- TableLayout: sample at TableLayout Sample, defined in TableLayout.js
- TreeMapLayout: sample at TreeMapLayout Sample, defined in TreeMapLayout.js

## Layout Invalidation

A layout is considered "valid" when it has performed its positioning of its nodes and perhaps routed its links. However some kinds of changes cause a layout to become "invalid", thereby causing it to be performed again in the near future. Because layouts can be computationally expensive, automatic layouts are not performed as soon as a layout is invalidated. Instead they are typically performed at the end of a transaction.

The most common reasons for a layout to be invalidated are because a node or a link has been added or removed from the collection of nodes and links that a layout is responsible for, or because a node or a link has changed visibility, or because a node has changed size. If you do not want an automatic layout to happen when such a change occurs, it may be easiest to set Layout.isOngoing to false.

Another common situation is where you have set Diagram.layout to some kind of layout but you want to load a diagram (model) that contains manually positioned or adjusted node locations. The Binding of Part.location to the model data is effective, but the locations are lost when a layout is performed immediately after loading. This situation can be avoided by setting Layout.isInitial to false. After the initial layout the layout might still be invalidated by adding or removing or changing the visibility of a node or a link or by a change in node size, unless you have also set Layout.isOngoing to false. When both Layout.isInitial and Layout.isOngoing are false, you can still explicitly cause a layout to happen by either calling Layout.invalidateLayout or by calling Diagram.layoutDiagram with a `true` argument.

For example, in editors it is commonplace to have TwoWay Bindings on Node.location to save manually adjusted node locations. This means that saved models will have saved locations for all of the nodes. But if you create a new model without all of the node data objects having real locations, you will want a layout to be performed initially when the model is loaded. You can accomplish this by setting Layout.isInitial to false (and optionally Layout.isOngoing to false, if that is what you want when users add or remove nodes or links) and then implementing an "InitialLayoutCompleted" DiagramEvent listener that decides whether a layout is needed. The decision could be to look at a flag that you add to the Model.modelData. Or you could look at all of the nodes to make sure their locations have real values:

    $(go.Diagram, . . .,
      {
        . . .,
        layout: $(go.TreeLayout, { isInitial: false, isOngoing: false }, . . .),
        "InitialLayoutCompleted": function(e) {
          // if not all Nodes have real locations, force a layout to happen
          if (!e.diagram.nodes.all(function(n) { return n.location.isReal(); })) {
            e.diagram.layoutDiagram(true);
          }
        }
      })

But if you do not want a change to a particular Node or Link to cause an automatic layout, yet you do want that invalidation for other Nodes or Links, you can set the Part.layoutConditions property to the combination of Part "Layout..." flags that suits your needs. It is most common to not want a layout for the Part,LayoutNodeSized condition:

      $(go.Node, . . .,
        { layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized },
        . . .
      )

Parts that remain not visible or that are in layers that are Layer.isTemporary also never invalidate any Layout.

Finally, you can set Part.isLayoutPositioned to false in order for the Layout to completely ignore that Part. But you will have to make sure that that Part does have a real Part.location, since no layout will set it for you. Without a real location the part will not be visible anywhere in the diagram. Furthermore if a node has isLayoutPositioned set to false, Layouts will not only ignore that node but also all links connecting with that node. Because the node will not be moved by the layout, it might overlap with the laid-out nodes and links. You can also set or bind Part.isLayoutPositioned to false on Links in order to have the layout ignore those links. This is demonstrated in Org Chart Extras.