Is it possible to have two different context menu using div in go.js diagram

Hi,
I am using go.js to create a visual interface as follows

I have associated the context menu for the square node, whereas I need a different context menu for parallelogram (target) node. In my case, whatever I am associated the context menu for square node is coming same for parallelogram node also.

Is it possible to have two different context menu (one for square node) and another one for parellelogram node? If so how to do it.

Regards,
R.Venkades (IDS software)

Yes, you can. First, I assume you have studied and adapted the custom context menu sample, http://gojs.net/latest/samples/customContextMenu.html.

Note how the overridden ContextMenuTool.showContextMenu method ( http://gojs.net/latest/api/symbols/ContextMenuTool.html#showContextMenu ) takes a second argument that is the GraphObject for which the context menu is being shown. That is probably the node in both your cases, because you have set the GraphObject.contextMenu in both of your node templates.

So that method can look at the Node or its data ( by obj.data ) to decide which context menu commands to show.

Hi Walter,
Thank you for the response. I have tried to override the showContextMenu, but couldn’t get it.
Do you have any sample source or example available to have two different context menu. Please share it. It will be helpful to me.

Regards,
R.Venkades

What did you try? It would help if you could be specific in what you do not understand.

Hi Walter,
Here’s what I have tried, but not sure what I am missing.

Div tag in html:
"<div id=“targetcontextMenu” style="display:none;>









"
Defining the template nodes:
myDiagram.nodeTemplateMap.add(“RuleNode”,
$$(go.Node, go.Panel.Auto,
{
isShadowed: true,
selectionObjectName: “Body1”,
doubleClick: showCommentsWindow,
fromSpot: go.Spot.Left,
toSpot: go.Spot.Right,
contextMenu: $$(go.Adornment, go.Panel.Horizontal)
        },

myDiagram.nodeTemplateMap.add(“TargetNode”,
$$(go.Node, go.Panel.Spot,
{
locationSpot: go.Spot.Center,
isShadowed: true,
selectionObjectName: “Body”,
// doubleClick: showPropertiesModalWindow,
fromSpot: go.Spot.Left,
toSpot: go.Spot.Right,
contextMenu: $$(go.Adornment, go.Panel.Horizontal)
},

Here the code to assign the custom context menu.

cxMenu = myDiagram.toolManager.contextMenuTool;
//getting the div id for target context menu
var cxTargetElement = document.getElementById("targetcontextMenu");
//adding the even listener
cxTargetElement.addEventListener('targetcontextMenu', function (e) { e.preventDefault(); return false; }, false);
cxTargetElement.addEventListener('blur', function (e) { cxMenu.stopTool(); }, false);
//getting the div id for context menu
var cxElement = document.getElementById("contextMenu");
cxElement.addEventListener('contextmenu',function(e){e.preventDefault();return false;},false);
cxElement.addEventListener('blur',function(e){cxMenu.stopTool();}, false);
cxShow = function (contextmenu, obj) {
	var diagram = this.diagram;
	if (diagram === null) return;
	var mousePt = diagram.lastInput.viewPoint;
	if (contextmenu !== this.currentContextMenu) {
		this.hideContextMenu();
	}

	if (obj !== null) {
	    CommentsButton.display="block";
	} else {
	    CommentsButton.display ="none";
	}
	//if it is RuleNode
	if (obj.selectionObjectName == "Body1") {
	    cxElement.style.display = "block";
	    cxElement.style.left = mousePt.x + "px";
	    cxElement.style.top = mousePt.y + "px";
	}
	else {
	    cxTargetElement.style.display = "block";
	    cxTargetElement.style.left = mousePt.x + "px";
	    cxTargetElement.style.top = mousePt.y + "px";
	}
	    this.currentContextMenu = contextmenu;
	myContextMenu= this;
}

cxHide = function() {
	if (this.currentContextMenu === null) return;
	cxElement.style.display = "none";
	cxTargetElement.style.display = "none";
	this.currentContextMenu = null;
	myContextMenu = null
}
cxMenu.showContextMenu=cxShow;
cxMenu.hideContextMenu=cxHide;

Please note that only the div id with name as “contextMenu” is coming correctly and not the “targetcontextMenu”

Kindly let me know what I am missing, it will be great.

Regards,
R.Venkades

I’ll see if I can adapt the Custom Context Menu sample for you, hopefully this afternoon.

Thanks Walter. In my case one custom context menu is coming correctly without any issues. But when i try to attach the second one, the issue is. Kindly do the needful.

I modified the existing Custom Context Menu sample by adding a second context menu in HTML and by setting the class of both context menu elements to be “contextMenu”, and by registering “contextmenu” and “blur” event handlers on both context menus.

Then I modified the showContextMenu function to look at the Part.data of the object that was context-clicked and decide which context menu HTML element should become visible.

<!DOCTYPE html>
<html>
<head>
<title>HTML Context Menu</title>
<meta name="description" content="Context menus implemented in HTML rather than as GoJS objects." />
<!-- Copyright 1998-2016 by Northwoods Software Corporation. -->
<meta charset="UTF-8">
<style type="text/css">
  /* CSS for the traditional context menu */
  .contextMenu {
    z-index: 300;
    position: absolute;
    left: 5px;
    border: 1px solid #444;
    background-color: #F5F5F5;
    display: none;
    box-shadow: 0 0 10px rgba( 0, 0, 0, .4 );
    font-size: 12px;
    font-family: sans-serif;
    font-weight:bold;
  }

  .contextMenu ul {
    list-style: none;
    top: 0;
    left: 0;
    margin: 0;
    padding: 0;
  }

  .contextMenu li {
    position: relative;
    min-width: 60px;
    color: #444;
    display: inline-block;
    padding: 6px;
    text-decoration: none;
    cursor: default;
  }

  .contextMenu li:hover { background: #444; }

  .contextMenu li:hover { color: #EEE; }
</style>

<script src="go.js"></script>
<link href="../assets/css/goSamples.css" rel="stylesheet" type="text/css" />  <!-- you don't need to use this -->
<script src="goSamples.js"></script>  <!-- this is only for the GoJS Samples framework -->
<script id="code">

var myDiagram = null;

function init() {
  if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
  var $ = go.GraphObject.make;  // for conciseness in defining templates

  myDiagram =
    $(go.Diagram, "myDiagramDiv",  // create a Diagram for the DIV HTML element
      { initialContentAlignment: go.Spot.Center, "undoManager.isEnabled": true });

  // define a simple Node template (but use the default Link template)
  myDiagram.nodeTemplate =
    $(go.Node, "Auto",
      // We make a dummy context menu so that the contextMenuTool will activate,
      // but we don't use this adornment
      { contextMenu: $(go.Adornment) },
      $(go.Shape, "RoundedRectangle",
        // Shape.fill is bound to Node.data.color
        new go.Binding("fill", "color")),
      $(go.TextBlock,
        { margin: 3 },  // some room around the text
        // TextBlock.text is bound to Node.data.key
        new go.Binding("text", "key"))
    );

  // create the model data that will be represented by Nodes and Links
  myDiagram.model = new go.GraphLinksModel(
  [
    { key: "Alpha", color: "lightblue" },
    { key: "Beta", color: "orange" },
    { key: "Gamma", color: "lightgreen" },
    { key: "Delta", color: "pink" }
  ],
  [
    { from: "Alpha", to: "Beta" },
    { from: "Alpha", to: "Gamma" },
    { from: "Beta", to: "Beta" },
    { from: "Gamma", to: "Delta" },
    { from: "Delta", to: "Alpha" }
  ]);

  // This is a dummy context menu for the whole Diagram:
  myDiagram.contextMenu = $(go.Adornment);

  // Override the ContextMenuTool.showContextMenu and hideContextMenu methods
  // in order to modify the HTML appropriately.
  var cxTool = myDiagram.toolManager.contextMenuTool;

  // This is the override of ContextMenuTool.showContextMenu:
  // This does not not need to call the base method.
  cxTool.showContextMenu = function(contextmenu, obj) {
    var diagram = this.diagram;
    if (diagram === null) return;

    // Hide any other existing context menu
    if (contextmenu !== this.currentContextMenu) {
      this.hideContextMenu();
    }

    // Show only the relevant buttons given the current state.
    var cmd = diagram.commandHandler;
    var objExists = obj !== null;
    document.getElementById("cut").style.display = objExists && cmd.canCutSelection() ? "block" : "none";
    document.getElementById("copy").style.display = objExists && cmd.canCopySelection() ? "block" : "none";
    document.getElementById("paste1").style.display = cmd.canPasteSelection() ? "block" : "none";
    document.getElementById("paste2").style.display = cmd.canPasteSelection() ? "block" : "none";
    document.getElementById("delete").style.display = objExists && cmd.canDeleteSelection() ? "block" : "none";
    document.getElementById("color").style.display = objExists ? "block" : "none";

    if (objExists && obj.part.data.color === "orange") {
      // Now show the whole context menu element
      cxElement1.style.display = "block";
      // we don't bother overriding positionContextMenu, we just do it here:
      var mousePt = diagram.lastInput.viewPoint;
      cxElement1.style.left = mousePt.x + "px";
      cxElement1.style.top = mousePt.y + "px";
    } else {
      // Now show the whole context menu element
      cxElement2.style.display = "block";
      // we don't bother overriding positionContextMenu, we just do it here:
      var mousePt = diagram.lastInput.viewPoint;
      cxElement2.style.left = mousePt.x + "px";
      cxElement2.style.top = mousePt.y + "px";
    }

    // Remember that there is now a context menu showing
    this.currentContextMenu = contextmenu;
  }

  // This is the corresponding override of ContextMenuTool.hideContextMenu:
  // This does not not need to call the base method.
  cxTool.hideContextMenu = function() {
    if (this.currentContextMenu === null) return;
    cxElement1.style.display = "none";
    cxElement2.style.display = "none";
    this.currentContextMenu = null;
  }

  function oncontextmenu(e) {
    this.focus();
    e.preventDefault();
    return false;
  }

  function onblur(e) {
    cxTool.stopTool();
    // maybe start another context menu
    if (cxTool.canStart()) {
      myDiagram.currentTool = cxTool;
      cxTool.doMouseUp();
    }
  }

  // This is the actual HTML context menu:
  var cxElement1 = document.getElementById("contextMenu1");
  // We don't want the div acting as a context menu to have a (browser) context menu!
  cxElement1.addEventListener("contextmenu", oncontextmenu, false);
  cxElement1.addEventListener("blur", onblur, false);
  cxElement1.tabIndex = "1";

  // This is the actual HTML context menu:
  var cxElement2 = document.getElementById("contextMenu2");
  // We don't want the div acting as a context menu to have a (browser) context menu!
  cxElement2.addEventListener("contextmenu", oncontextmenu, false);
  cxElement2.addEventListener("blur", onblur, false);
  cxElement2.tabIndex = "1";
}

// This is the general menu command handler, parameterized by the name of the command.
function cxcommand(val) {
  var diagram = myDiagram;
  if (!(diagram.currentTool instanceof go.ContextMenuTool)) return;
  switch (val) {
    case "Cut": diagram.commandHandler.cutSelection(); break;
    case "Copy": diagram.commandHandler.copySelection(); break;
    case "Paste": diagram.commandHandler.pasteSelection(diagram.lastInput.documentPoint); break;
    case "Delete": diagram.commandHandler.deleteSelection(); break;
    case "Color": changeColor(diagram); break;
  }
  diagram.currentTool.stopTool();
}

// A custom command, for changing the color of the selected node(s).
function changeColor(diagram) {
  // the object with the context menu, in this case a Node, is accessible as:
  var cmObj = diagram.toolManager.contextMenuTool.currentObject;
  // but this function operates on all selected Nodes, not just the one at the mouse pointer.

  // Always make changes in a transaction, except when initializing the diagram.
  diagram.startTransaction("change color");
  diagram.selection.each(function(node) {
    if (node instanceof go.Node) {  // ignore any selected Links and simple Parts
      // Examine and modify the data, not the Node directly.
      var data = node.data;
      if (data.color === "red") {
        // Call setDataProperty to support undo/redo as well as
        // automatically evaluating any relevant bindings.
        diagram.model.setDataProperty(data, "color", go.Brush.randomColor());
      } else {
        diagram.model.setDataProperty(data, "color", "red");
      }
    }
  });
  diagram.commitTransaction("change color");
}
</script>
</head>
<body onload="init()">
<div id="sample">
  <p>HTML Context menu <b>GoJS</b> Sample</p>

  <div style="display: inline-block;">
    <!-- We make a div to contain both the Diagram div and the context menu (such that they are siblings)
         so that absolute positioning works easily.
         This DIV containing both MUST have a non-static CSS position (we use position: relative)
         so that our context menu's absolute coordinates work correctly. -->
    <div style="position: relative;"  >
      <div id="myDiagramDiv" style="border: solid 1px black; width:400px; height:400px"></div>
      <div id="contextMenu1" class="contextMenu">
        <ul>
          <li id="cut" onclick="cxcommand(this.textContent)">Cut</li>
          <li id="copy" onclick="cxcommand(this.textContent)">Copy</li>
          <li id="paste1" onclick="cxcommand(this.textContent)">Paste</li>
          <li id="delete" onclick="cxcommand(this.textContent)">Delete</li>
        </ul>
      </div>
      <div id="contextMenu2" class="contextMenu">
        <ul>
          <li id="paste2" onclick="cxcommand(this.textContent)">Paste</li>
          <li id="color" onclick="cxcommand('Color')">Color</li>
        </ul>
      </div>
    </div>

    <div id="description">
    </div>
  </div>
</div>
</body>
</html>

Thanks Walter. It worked. Now I am able to get two different context menu. Have a nice day…