神刀安全网

Build Interactive Diagrams with GoJS

GoJS is a JavaScript library for building interactive diagrams. This tutorial covers the essentails of using GoJS by building an org chart diagram from scratch.

Kinds of Diagrams

A diagram is any visual representation of a structure, or a process, or simply data with relationships. They are used to convey the meaning in an intuitive way. Diagrams and graphs are diverse: there are strongly-linked graphs like flowcharts, family trees, genograms, organizational charts, decision trees, and so on. Diagrams may also be visual representations of real-world objects such as shelves (planograms) or shop floors, or room layouts. They can also display kanbans and work-item graphs, graphs atop maps, or more abstract data representations such as plots for statistical visualizations.

Diagrams are commonly graph-like in nature, containing Nodes and Links, organized manually or by Layouts and Groups (which may also act as sub-graphs). These concepts are all classes in GoJS, and come with a host of convenience methods for traversing and organizing your diagram structures, allowing users to manipulate those structures, and enforcing interactivity rules.

GoJS makes it easy to form representations from model data, and allows users to interact with them. GoJS adds keyboard, mouse, and touch support, the ability to create, link and edit data, move and rotate objects, copy and paste, save and load, undo and redo, and whatever else your users may need. GoJS allows you to create any kind of diagram, from flowcharts to floorplans.

Build Interactive Diagrams with GoJS

Some diagrams built with GoJS, taken from the GoJS Samples

This is what we’ll be building:

Creating a Diagram

You can download the latest version of GoJS here .

If you use Node.js you could download the latest GoJS with npm, npm install gojs , and reference GoJS in the package:

<script src="node_modules/gojs/release/go-debug.js"></script>

For getting-started convenience you could link straight to the GoJS provided by CDNJS , but this is likely to be out of date and I recommend always using the latest version of GoJS:

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

GoJS diagrams are contained in an HTML <div> element in your 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 the area. --> <div id="myDiagramDiv" style="width:400px; height:150px; background-color: #DAE4E4;"></div>

Pass the <div> ‘s id to GoJS to make a Diagram:

    var $ = go.GraphObject.make; // We use $ for conciseness, but you can use anything, $, GO, MAKE, etc     var myDiagram = $(go.Diagram, "myDiagramDiv");

This produces an empty diagram, so not much to look at yet:

See the Pen pymgLO by Simon Sarris ( @simonsarris ) on CodePen .

This article shows by example how to use go.GraphObject.make to build GoJS objects. For more detail, see Building Objects in GoJS . Using $ as an abbreviation for go.GraphObject.make is handy and 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 .

GoJS uses go as 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. .

Diagrams and Models

Diagram parts such as Nodes and Links are visualizations of data that is managed by a Model. In GoJS, Models hold the data (arrays of JavaScript objects) that describe Parts, and Diagrams act as views to visualize this data using actual Node and Link objects. Models, not Diagrams, are what you save and load.

Here’s an example of a Model and Diagram, followed by the diagram it creates:

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 model data, each node is represented by a JavaScript object: myModel.nodeDataArray = [   { key: "Alpha" },   { key: "Beta" },   { key: "Gamma" } ]; myDiagram.model = myModel;

See the Pen zqQvvd by Simon Sarris ( @simonsarris ) on CodePen .

The diagram displays the three nodes that are in the model. Since there was no location information given, GoJS automatically assigns them locations in a grid-like fashion using the default layout. Some interaction is already possible:

  • Click and drag the background to pan the view.
  • Click a node to select it. Click and drag a node to move it around.
  • Click and hold on the background, then start dragging, and a selection box will appear.
  • 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.
  • Since the undo manager was enabled, CTRL-Z and CTRL-Y will undo and redo moves and copies and deletions.
  • Read about more Keyboard Commands .

Styling Nodes

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

  • Shape , to display a geometry (pre-defined or custom) with colors
  • TextBlock , to display (potentially editable) text
  • 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 automatically 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 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 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 . 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"))   );

The result is a node that will display the key in the model data object, as we saw with the diagram above.

Nesting can be arbitrarily deep, and every class has its own unique set of properties to explore. 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"))   );

Now let’s 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 Node template myDiagram.nodeTemplate =   $(go.Node, "Horizontal",     // the entire node will have an orange background     { background: "#DD4814" },     $(go.Picture,       // Pictures are best off having an explicit width and height.       // Adding a red background ensures something is visible when there is no source set       { 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); // each node data object holds whatever properties it needs, // for this app we add the "name" and "source" properties model.nodeDataArray = [   { name: "Don Meow", source: "cat1.png" },   { name: "Toulouse", source: "cat2.png" },   { name: "Roquefort",  source: "cat3.png" },   { } // we left this last node data empty! ]; myDiagram.model = model;

This produces the diagram:

See the Pen jqobMq by Simon Sarris ( @simonsarris ) on CodePen .

A good Node template will help users visually parse data, even when some of that data is missing. 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 well-designed node templates can work perfectly well without any of the properties on the bound data.

Kinds of Models

Perhaps we want to show more than just nodes. By adding some Links to show the relationship between individual nodes and a Layout to automatically position the nodes, we can show that Don Meow is really the leader of a cat cartel.

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 a node having multiple parents. Our organizational diagram is a simple hierarchical tree-like structure, so we can use the simpler TreeModel.

First, we will complete the data by adding a few more nodes, using a TreeModel, and specifying key and parent fields 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: "#DD4814" },     $(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: "Roquefort",    source: "cat2.png" },   { key: "3", parent: "1", name: "Toulouse",   source: "cat3.png" },   { key: "4", parent: "3", name: "Peppo", source: "cat4.png" },   { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },   { key: "6", parent: "2", name: "Berlioz", source: "cat6.png" } ]; myDiagram.model = model;

See the Pen JXqYRL by Simon Sarris ( @simonsarris ) on CodePen .

Diagram Layouts: Who’s the boss?

As you can see the TreeModel automatically creates the necessary Links to associate the Nodes, but with the default layout, it’s hard to tell whose tree 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 in our case, the easier solution is to 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: "#DD4814" },     $(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: "Roquefort",    source: "cat2.png" },   { key: "3", parent: "1", name: "Toulouse",   source: "cat3.png" },   { key: "4", parent: "3", name: "Peppo", source: "cat4.png" },   { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },   { key: "6", parent: "2", name: "Berlioz", source: "cat6.png" } ]; myDiagram.model = model;

See the Pen GZapjL by Simon Sarris ( @simonsarris ) on CodePen .

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

Link Templates

We can create new Link template that will better suit our wide, boxy nodes. A Link is a different kind of Part, and there are some special considerations. The main element of a Link is the Link’s shape, and this Shape will have its geometry computed dynamically by GoJS. For the sake of simplicity, our link is going to consist of just this shape, with its stroke a little thicker than normal and its color set to dark gray instead of black. Unlike the default link template we will not have an arrowhead, because hte visual layout of the graph already implies a direction. 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 finished code and 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: "#DD4814" },     $(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: "Roquefort",    source: "cat2.png" },   { key: "3", parent: "1", name: "Toulouse",   source: "cat3.png" },   { key: "4", parent: "3", name: "Peppo", source: "cat4.png" },   { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },   { key: "6", parent: "2", name: "Berlioz", source: "cat6.png" } ]; myDiagram.model = model;

See the Pen pymjNE by Simon Sarris ( @simonsarris ) on CodePen .

Now that you are familiar with some of the basics of GoJS, consider viewing 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.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Build Interactive Diagrams with GoJS

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址