Selection

Selection is a mechanism that provides the ability for the user to operate commands or tools on a subset of the Parts in a Diagram. GoJS provides built-in appearances and behaviors for selection. Although this page describes how those built-in appearances and behaviors can be customized, if you want a more general highlighting capability with no built-in appearances or behaviors, please read the page on Highlighting.

Users normally select Parts manually by clicking on them and they deselect them by clicking in the background. This behavior is implemented by the ClickSelectingTool. Users can also deselect all Parts by pressing the Esc key.

Users can also drag in the background in order to select the Parts that are within a rectangular area, via the DragSelectingTool. Read more about that in the Introduction to Tools at DragSelectingTool.

You can select parts programmatically by setting Part.isSelected or calling one of several Diagram methods such as Diagram.select, Diagram.selectCollection, and Diagram.clearSelection.

The Diagram keeps a collection of selected parts, Diagram.selection. That collection is read-only -- the only way to add or remove a Part in the Diagram.selection collection is by setting its Part.isSelected property. You can limit how many parts the user may select by setting Diagram.maxSelectionCount. Prevent all selection by the user by setting Diagram.allowSelect to false. Or prevent a particular Part from being selected by setting or binding its Part.selectable property to false.

You can show that a part is selected by either or both of two general techniques: adding Adornments or changing the appearance of some of the elements in the visual tree of the selected Part.

Selection Adornments

It is common to display that a Part is selected by having it show a selection Adornment when the Part is selected. For nodes this is normally a blue rectangle surrounding the whole Node. This is the default behavior; if you do not want such an adornment, you can set Part.selectionAdorned to false.


diagram.nodeTemplate =
  new go.Node("Vertical", {
      // the location is the center of the Shape, not the center of the whole Node
      locationSpot: go.Spot.Center, locationObjectName: "ICON"
    })
    .bind("location", "loc", go.Point.parse)
    .add(
      new go.Shape({
          name: "ICON",
          width: 40, height: 40,
          fill: "gray",
          portId: ""  // the port is this Shape, not the whole Node
        })
        .bind("figure"),
      new go.TextBlock({ margin: new go.Margin(5, 0, 0, 0) })
        .bind("text")
    );

const nodeDataArray = [
  { key: 1, text: "Alpha", figure: "Club", loc: "0 0" },
  { key: 2, text: "Beta", figure: "Spade", loc: "200 50" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.commandHandler.selectAll();

By default an Adornment will apply to the whole Node. What if you want attention to be drawn only to the main piece of a node? You can accomplish that by naming that object and setting Part.selectionObjectName to that name.


diagram.nodeTemplate =
  new go.Node("Vertical", {
      selectionObjectName: "ICON",  // added this property!
      // the location is the center of the Shape, not the center of the whole Node
      locationSpot: go.Spot.Center, locationObjectName: "ICON"
    })
    .bind("location", "loc", go.Point.parse)
    .add(
      new go.Shape({
          name: "ICON",
          width: 40, height: 40,
          fill: "gray",
          portId: ""  // the port is this Shape, not the whole Node
        })
        .bind("figure"),
      new go.TextBlock({ margin: new go.Margin(5, 0, 0, 0) })
        .bind("text")
    );

const nodeDataArray = [
  { key: 1, text: "Alpha", figure: "Club", loc: "0 0" },
  { key: 2, text: "Beta", figure: "Spade", loc: "200 50" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.selectCollection(diagram.nodes);

Note how the Part.selectionObjectName property is similar to the Part.locationObjectName in helping to treat a node as if only one piece of it really matters.

Custom Selection Adornments

If you do want a selection adornment but want something different than the standard one, you can customize it. Such customization can be done by setting the Part.selectionAdornmentTemplate. In this example, nodes get thick blue rounded rectangles surrounding the selected node, and links get thick blue lines following the selected link's path.


diagram.nodeTemplate =
  new go.Node("Auto", {
      selectionAdornmentTemplate:
        new go.Adornment("Auto")
          .add(
            new go.Shape("RoundedRectangle", {
                fill: null, stroke: "dodgerblue", strokeWidth: 8
              }),
            new go.Placeholder()
          )  // end Adornment
    })
    .bind("location", "loc", go.Point.parse)
    .add(
      new go.Shape("RoundedRectangle", { fill: "lightgray" }),
      new go.TextBlock({ margin: 5 })
        .bind("text")
    );

diagram.linkTemplate =
  new go.Link({
      selectionAdornmentTemplate:
        new go.Adornment()
          .add(
            new go.Shape({ isPanelMain: true, stroke: "dodgerblue", strokeWidth: 8 }),
            new go.Shape({ toArrow: "Standard", fill: "dodgerblue", stroke: null, scale: 2.5 })
          )  // end Adornment
    })
    .add(
      new go.Shape({ strokeWidth: 2 }),
      new go.Shape({ toArrow: "Standard" })
    );

const nodeDataArray = [
  { key: 1, text: "Alpha", loc: "0 0" },
  { key: 2, text: "Beta", loc: "200 50" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.commandHandler.selectAll();

Note that an Adornment is just a Part. Adornments for nodes must contain a Placeholder in their visual tree. The Placeholder gets positioned where the selected object is.

Adornments for links are assumed to be panels of Panel.type that is Panel.Link. Hence the main element may be a Shape that gets the geometry of the selected Link's path shape, and the other elements of the adornment may be positioned on or near the segments of the link route just as for a regular Link.

More Complex Adornments

The custom Adornment for a Node need not be only a simple Shape outlining the selected node. Here is an adornment that adds a button to the adornment which inserts a node and a link to that new node.


function addNodeAndLink(e, b) {
  // take a button panel in an Adornment, get its Adornment, and then get its adorned Node
  const node = b.part.adornedPart;
  // we are modifying the model, so conduct a transaction
  const diagram = node.diagram;
  diagram.startTransaction("add node and link");
  // have the Model add the node data
  const newnode = { text: "N" + diagram.model.nodeDataArray.length };
  diagram.model.addNodeData(newnode);
  // locate the node initially where the parent node is
  diagram.findNodeForData(newnode).location = node.location;
  // and then add a link data connecting the original node with the new one
  const newlink = { from: node.data.key, to: newnode.key };
  diagram.model.addLinkData(newlink);
  // finish the transaction -- will automatically perform a layout
  diagram.commitTransaction("add node and link");
}

diagram.nodeTemplate =
  new go.Node("Auto", {
      selectionAdornmentTemplate:
        new go.Adornment("Spot")
          .add(
            new go.Panel("Auto")
              .add(
                // this Adornment has a rectangular blue Shape around the selected node
                new go.Shape({ fill: null, stroke: "dodgerblue", strokeWidth: 3 }),
                new go.Placeholder()
              ),
            // and this Adornment has a Button to the right of the selected node
            go.GraphObject.make("Button", {
                alignment: go.Spot.Right, alignmentFocus: go.Spot.Left,
                click: addNodeAndLink
              })  // define click behavior for Button in Adornment
              .add(
                new go.TextBlock("ADD",  // the Button content
                    { stroke: "blue", font: "bold 8pt sans-serif" })
              )
          )  // end Adornment
    })
    .add(
      new go.Shape("RoundedRectangle", { fill: "lightgray" }),
      new go.TextBlock({ margin: 5 })
        .bind("text")
    );

diagram.layout = new go.TreeLayout();

const nodeDataArray = [
  { key: 1, text: "Alpha" },
  { key: 2, text: "Beta" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.select(diagram.findNodeForKey("Beta"));

Select any node and click the "ADD" button. Note how the diagram is automatically laid out as a tree.

Data Binding

Like all Parts, Adornments support data binding. If the adorned Part has a data binding (i.e. if Part.data is non-null), all adornments for that part will also be bound to the same data object.


diagram.nodeTemplate =
  new go.Node("Auto", {
      selectionAdornmentTemplate:
        new go.Adornment("Auto")
          .add(
            new go.Shape("Diamond", { fill: null, stroke: "dodgerblue", strokeWidth: 6 })
              .bind("stroke", "color"),
            new go.Placeholder()
          )  // end Adornment
    })
    .bind("location", "loc", go.Point.parse)
    .add(
      new go.Shape("RoundedRectangle", { fill: "lightgray", strokeWidth: 2 })
        .bind("stroke", "color"),
      new go.TextBlock({ margin: 5 })
        .bind("text")
    );

const nodeDataArray = [
  { key: 1, text: "Alpha", loc: "0 0", color: "blue" },
  { key: 2, text: "Beta", loc: "200 50", color: "red" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.selectCollection(diagram.nodes);

Notice how each Adornment has the same color as the selected node's data.color.

Selection Appearance changes

Adding a selection adornment is not the only way to indicate visually that a Part is selected. You can also modify the appearance of one or more objects in your Part.

One way to do this is with data binding. Here we data bind the Shape.fill to the Part.isSelected property with a converter function that converts the boolean value to a color string or brush. We also turn off the regular rectangular blue selection adornment.


diagram.nodeTemplate =
  new go.Node("Auto", { selectionAdorned: false })  // don't bother with any selection adornment
    .bind("location", "loc", go.Point.parse)
    .add(
      new go.Shape("RoundedRectangle", { fill: "lightgray", strokeWidth: 2 })
        // when this Part.isSelected changes value, change this Shape.fill value:
        .bindObject("fill", "isSelected", sel => {
            if (sel) return "cyan"; else return "lightgray";
          }), // The object named "" is the root visual element, the Node itself
      new go.TextBlock({ margin: 5 })
        .bind("text")
    );

const nodeDataArray = [
  { key: 1, text: "Alpha", loc: "0 0", color: "blue" },
  { key: 2, text: "Beta", loc: "200 50", color: "red" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.select(diagram.findNodeForKey(2));

Here the "Beta" node is selected initially. Now when you select a node its background color changes to cyan.

More generally you can execute code to modify the Part when Part.isSelected has changed value. In this example we will have the same side effects as the previous example.


function onSelectionChanged(node) {
  const icon = node.findObject("ICON");
  if (icon !== null) {
    if (node.isSelected)
      icon.fill = "cyan";
    else
      icon.fill = "lightgray";
  }
}

diagram.nodeTemplate =
  new go.Node("Auto", {
      selectionAdorned: false,  // don't bother with any selection adornment
      selectionChanged: onSelectionChanged
    })
    .bind("location", "loc", go.Point.parse)
    .add(
      new go.Shape("RoundedRectangle", { fill: "lightgray", strokeWidth: 2 })
        // when this Part.isSelected changes value, change this Shape.fill value:
        .bindObject("fill", "isSelected", sel => {
            if (sel) return "cyan"; else return "lightgray";
          }), // The object named "" is the root visual element, the Node itself
      new go.TextBlock({ margin: 5 })
        .bind("text")
    );

const nodeDataArray = [
  { key: 1, text: "Alpha", loc: "0 0", color: "blue" },
  { key: 2, text: "Beta", loc: "200 50", color: "red" }
];
const linkDataArray = [
  { from: 1, to: 2 }
];
diagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

diagram.select(diagram.findNodeForKey(2));

This basically has the same effect as the GraphObject.bindObject binding of the previous example, but the possible changes you could make to that node are much greater and probably simpler than trying to use Bindings.

There are some restrictions on what you can do in such an event handler: you should not select or deselect any parts, and you should not add or remove any parts from the diagram.