GoJS Pipe Example Add TextBlock - javascript

It is not apparent to me how to edit the GoJS Pipes example here so that I can display text within the "pipes" without messing up the layout. I am trying to apply the answer to the same question given here but it's so old that it could be out of date, or maybe it's just not explicit enough for me to make sense of it properly with my limited knowledge of this lib.
I have started a hardcoded pipeline that looks like so:
The pipeline code:
const base = 15;
const minLen = base * 2;
const maxLen = base * 6;
const minInc1 = minLen + base;
const minInc2 = minLen * 2;
const minInc3 = minLen + (base * 3);
interface IShapeParams {
angle?: number
text?: string
key: number
}
const createShapeI = (params: IShapeParams): ObjectData => ({
geo: `F1 M0 0 L${minLen} 0 ${minLen} ${maxLen} 0 ${maxLen}z`,
ports: [
{ id: "U1", spot: "0.5 0 0 0.5" },
{ id: "U2", spot: "0.5 1 0 -0.5" }
],
...params
});
const startHorz = 0;
const startVert = 0;
export const pipeline = {
"class": "go.GraphLinksModel",
"copiesArrays": true,
"copiesArrayObjects": true,
"linkFromPortIdProperty": "fid",
"linkToPortIdProperty": "tid",
"nodeDataArray": [
{
...createShapeI({ key: 1, text: "Pipe 1", angle: 90 }),
"loc": `${startHorz} ${startVert}`
},
{
...createShapeI({ key: 2, text: "Pipe 2", angle: 90 }),
"loc": `${startHorz - maxLen} ${startVert}`
}
],
"linkDataArray": [
{ "from": 1, "to": 2, "fid": "U2", "tid": "U1" }
]
};
The original nodeTemplate from the Pipe source code:
myDiagram.nodeTemplate =
$(go.Node, "Spot",
{
locationObjectName: "SHAPE",
locationSpot: go.Spot.Center,
selectionAdorned: false, // use a Binding on the Shape.stroke to show selection
itemTemplate:
// each port is an "X" shape whose alignment spot and port ID are given by the item data
$(go.Panel,
new go.Binding("portId", "id"),
new go.Binding("alignment", "spot", go.Spot.parse),
$(go.Shape, "XLine",
{ width: 6, height: 6, background: "transparent", fill: null, stroke: "gray" },
new go.Binding("figure", "id", portFigure), // portFigure converter is defined below
new go.Binding("angle", "angle"))
),
// hide a port when it is connected
linkConnected: (node, link, port) => {
if (link.category === "") {
port.visible = false;
}
},
linkDisconnected: (node, link, port) => {
if (link.category === "") {
port.visible = true;
}
}
},
// this creates the variable number of ports for this Spot Panel, based on the data
new go.Binding("itemArray", "ports"),
// remember the location of this Node
new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
// remember the angle of this Node
new go.Binding("angle", "angle").makeTwoWay(),
// move a selected part into the Foreground layer, so it isn't obscured by any non-selected parts
new go.Binding("layerName", "isSelected", function(s) {
return s ? "Foreground" : "";
}).ofObject(),
$(go.Shape,
{
name: "SHAPE",
// the following are default values;
// actual values may come from the node data object via data binding
geometryString: "F1 M0 0 L20 0 20 20 0 20 z",
fill: "rgba(128, 128, 128, 0.5)"
},
// this determines the actual shape of the Shape
new go.Binding("geometryString", "geo"),
// selection causes the stroke to be blue instead of black
new go.Binding("stroke", "isSelected", (s) => {
return s ? "dodgerblue" : "black";
}).ofObject())
);
Now when I try to apply the solution given on the referenced thread I end up with the nodeTemplate like so:
myDiagram.nodeTemplate =
$(go.Node, "Spot",
{
locationObjectName: "SHAPE",
locationSpot: go.Spot.Center,
selectionAdorned: false, // use a Binding on the Shape.stroke to show selection
// hide a port when it is connected
linkConnected: (node, link, port) => {
if (link.category === "") {
port.visible = false;
}
},
linkDisconnected: (node, link, port) => {
if (link.category === "") {
port.visible = true;
}
}
},
$(go.Panel, "Spot",
{
itemTemplate:
// each port is an "X" shape whose alignment spot and port ID are given by the item data
$(go.Panel,
new go.Binding("portId", "id"),
new go.Binding("alignment", "spot", go.Spot.parse),
$(go.Shape, "XLine",
{ width: 6, height: 6, background: "transparent", fill: null, stroke: "gray" },
new go.Binding("figure", "id", portFigure), // portFigure converter is defined below
new go.Binding("angle", "angle"))
)
},
// this creates the variable number of ports for this Spot Panel, based on the data
new go.Binding("itemArray", "ports"),
// remember the location of this Node
new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
// remember the angle of this Node
new go.Binding("angle", "angle").makeTwoWay(),
// move a selected part into the Foreground layer, so it isn't obscured by any non-selected parts
new go.Binding("layerName", "isSelected", function(s) {
return s ? "Foreground" : "";
}).ofObject(),
$(go.Shape,
{
name: "SHAPE",
// the following are default values;
// actual values may come from the node data object via data binding
geometryString: "F1 M0 0 L20 0 20 20 0 20 z",
fill: "rgba(128, 128, 128, 0.5)"
},
// this determines the actual shape of the Shape
new go.Binding("geometryString", "geo"),
// selection causes the stroke to be blue instead of black
new go.Binding("stroke", "isSelected", (s) => {
return s ? "dodgerblue" : "black";
}).ofObject())
),
$(go.TextBlock, { margin: 5 }, new go.Binding("text", "text"))
);
This renders the text correctly, but it completely breaks the layout as the ports have switched sides, I have no idea why. On top of that, the space seen in between the pipes now I cannot reconcile at all by trying to alter the loc strings on the pipeline, in fact nothing I do to the loc properties does anything at all now. See below image:
How can I just add text blocks to these shapes while keeping the same layout and functionality?

So the pipe template is currently structured like this:
Node (that is a Spot Panel)
- 1st child: Shape
- 2nd-nth child: Item array of x's
Spot panels have one main element (usually the first child unless you specify it), and then N other elements that are positioned based on it. So at the very minimum you want a structure like this:
Node (that is a Spot Panel)
- 1st child: Panel (another Spot panel)
- Shape
- TextBlock
- 2nd-nth child: Item array of x's
So you are swapping out the Shape for a Panel (a container with lots of stuff) that will contain that shape. This will work as long as that Panel is exactly the same size as the shape it would be replacing. If its larger, for instance if the text is larger than the shape, then you're in trouble.
How to solve that problem really depends on what you want the result to look like. The simplest way would be to force the TextBlock to stretch: go.GraphObject.Fill, so that it always sizes itself identical to the shape, so that the Panel (Shape+TextBlock) is always identical in size to the Shape it replaced.
Separately you probably want the TextBlock, which will assume the entire area of the gray shape, to be centered vertically, so you'd want to add verticalAlignment: go.Spot.Center
Like this:
myDiagram.nodeTemplate =
$(go.Node, "Spot",
{
locationObjectName: "SHAPE",
locationSpot: go.Spot.Center,
selectionAdorned: false, // use a Binding on the Shape.stroke to show selection
itemTemplate:
// each port is an "X" shape whose alignment spot and port ID are given by the item data
$(go.Panel,
new go.Binding("portId", "id"),
new go.Binding("alignment", "spot", go.Spot.parse),
$(go.Shape, "XLine",
{ width: 6, height: 6, background: "transparent", fill: null, stroke: "gray" },
new go.Binding("figure", "id", portFigure), // portFigure converter is defined below
new go.Binding("angle", "angle"))
),
// hide a port when it is connected
linkConnected: function(node, link, port) {
if (link.category === "") port.visible = false;
},
linkDisconnected: function(node, link, port) {
if (link.category === "") port.visible = true;
}
},
// this creates the variable number of ports for this Spot Panel, based on the data
new go.Binding("itemArray", "ports"),
// remember the location of this Node
new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
// remember the angle of this Node
new go.Binding("angle", "angle").makeTwoWay(),
// move a selected part into the Foreground layer, so it isn't obscured by any non-selected parts
new go.Binding("layerName", "isSelected", function(s) { return s ? "Foreground" : ""; }).ofObject(),
// Everything except the ports: (the pipe body, and pipe text)
$(go.Panel, "Spot",
$(go.Shape,
{
name: "SHAPE",
// the following are default values;
// actual values may come from the node data object via data binding
geometryString: "F1 M0 0 L20 0 20 20 0 20 z",
fill: "rgba(128, 128, 128, 0.5)"
},
// this determines the actual shape of the Shape
new go.Binding("geometryString", "geo"),
// selection causes the stroke to be blue instead of black
new go.Binding("stroke", "isSelected", function(s) { return s ? "dodgerblue" : "black"; }).ofObject()),
$(go.TextBlock, "Some text")
)
);
Here is that modification live: https://codepen.io/simonsarris/pen/RwrKqrq?editors=1010

Related

Cesium polygon callback using javascript

I am trying to edit the change the edit or redraw the polygon. this is my code.
Error
An error occurred while rendering. Rendering has stopped.
TypeError: this._callback is not a function
TypeError: this._callback is not a function
using pickedObject.id i got the exect polygon i want to reposition, but call back issue.
var points = [-95.8079865631313, 30.24038650541154, -
60.10509002138564, 23.526593580490083, -59.06372427570612, 2.245934026097194, -
117.00668212362282, 3.938434130034481
];
function loadPoly(points) {
redPolygon = viewer.entities.add({
id: "myArray",
name: "myArray",
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
material: Cesium.Color.fromBytes(221, 240, 235, 160)
}
});
polygonCollection.push(redPolygon);
adding_billboard(-95.8079865631313, 30.24038650541154, "A", "-95.8079865631313, 30.24038650541154");
adding_billboard(-60.10509002138564, 23.526593580490083, "A", "-60.10509002138564, 23.526593580490083");
adding_billboard(-59.06372427570612, 2.245934026097194, "A", "-59.06372427570612, 2.245934026097194");
adding_billboard(-117.00668212362282, 3.938434130034481, "A", "-117.00668212362282, 3.938434130034481");
viewer.flyTo(redPolygon);
}
function adding_billboard(lon, lat, name, popup) {
var entity = viewer.entities.add({
name: name,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 2000),
billboard: {
image: 'https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-512.png',
show: true, // default
pixelOffset: new Cesium.Cartesian2(0, -20), // default: (0, 0)
eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0), // default
horizontalOrigin: Cesium.HorizontalOrigin.bottom, // default
alignedAxis: Cesium.Cartesian3.ZERO, // default
width: 20, // default: undefined
height: 25, // default: undefined
//disableDepthTestDistance: Number.POSITIVE_INFINITY, // draws the label in front of terrain
// on ground show
},
label: {
text: popup,
font: "7pt sans-serif",
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BASELINE,
fillColor: Cesium.Color.BLACK,
showBackground: true,
backgroundColor: new Cesium.Color(1, 1, 1, 0.7),
backgroundPadding: new Cesium.Cartesian2(8, 4),
disableDepthTestDistance: Number
.POSITIVE_INFINITY, // draws the label in front of terrain
},
});
pointsCollection.push(entity);
}
var coordinates = [76.82071632075994, 33.4134542888633, 77.83750798568438, 33.39276536442791, 77.32892923803021,
32.93547457354476
];
var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function(click) {
var pickedObject = scene.pick(click.position);
if (Cesium.defined(pickedObject)) {
console.log("Second ");
console.log("pickedObject.id.id ", pickedObject.id.id);
console.log("pickedObject.id.name ", pickedObject.id.name);
console.log("pickedObject.id..polygon.hierarchy ", pickedObject.id.polygon.hierarchy.valueOf());
var data = pickedObject.id.polygon.hierarchy.valueOf();
console.log("data ", data.positions.valueOf());
pickedObject.id.polygon = {
hierarchy: new Cesium.CallbackProperty(new Cesium.Cartesian3.fromDegreesArray(coordinates),
false),
material: Cesium.Color.fromBytes(221, 240, 235, 160)
//pickedObject.id = redPolygon;// tried this but dailed due to same id then i removed it.
if (pickedObject.id.name == 'C') {
// $('#modal-activity').modal('show');
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
i want to shift polygon to some other coordiante but unable to use call back properly can some one guild me how can I do ?
i did some google searches which are given below but my issues not solved.
here i was trying to make polygon points dynamic but line disappers in tarrains. fist time it was ok after moving point it disappers.
https://sandcastle.cesium.com/?#c=zVTRbpswFP2VK14gEjMhWTaJ0Whd0odpnVpl0vZQ+uDCTWvN2Mg2yVjVf5/BkKRZ1VV9mnjhHp9zfH2uYUMVbBhuUcEJCNzCAjWrS/K9wwI/78qFFIYygcoffchE+2ysDoVhpomt0DmQDmCoCS2K4D4TAKxIwP+8jP2wrQQtESywwgLOOGeVRpACdK3WNEfHqaS2HlIkMLSyoMrYNyqmZK1kucRbhaiDN3E8I+MQpu/JeNRLmTAJdBvbiv1C/o39xgSm49BhueRSJTvjtiKrs2W/KmvD7SEXT5A+nZ8uvjym/WCFuUsgJrMWfsjEg8tmn8zkBclMXpPMP4N52wXz7v8Lpl1/LpVK8qbl7JvtD62Tw9t52aOXSlaoTHOqFG2CKyeBQ+YK16hQ5DhQg6O9w/5+whX4w2Y+XMMofLXb5Am3wex677t1Oc12QEkNKkb50VFdIhcu3K89Z9fA/aB+foQvHuLxGCdujHaQo8NxeqGXatNwnLvVj6yspDJQKx4QEhksK25b1dFNnf9EQ3KtW1kaDaK0YBv7EZxk3tEvJvMg51Rru7KueXdRM2+eRpb/SMYlLZi4vdig4rRpKXfx/NyBhJA0suXfKiMlv6HqwPEP
second :Dynamically change polygon position in cesium
it also gives error because i don't know where to use callback.
please guild me. thank you.
Here's Sandcastle link.
const {
Cartesian3,
CallbackProperty,
Color,
defined,
ScreenSpaceEventHandler,
ScreenSpaceEventType,
Viewer
} = window.Cesium;
const viewer = new Viewer("cesiumContainer");
let redPolygon;
const polygonCollection = [];
const pointsCollection = [];
const polygonId = "myArray";
let polygonPoints = [
-95.8079865631313, 30.24038650541154, -60.10509002138564, 23.526593580490083, -59.06372427570612,
2.245934026097194, -117.00668212362282, 3.938434130034481
];
function loadPoly() {
redPolygon = viewer.entities.add({
id: polygonId,
name: "myArray",
polygon: {
hierarchy: new CallbackProperty(() => {
return {
positions: Cartesian3.fromDegreesArray(polygonPoints)
};
}, false),
material: Color.fromBytes(221, 240, 235, 160)
}
});
polygonCollection.push(redPolygon);
adding_billboard(-95.8079865631313, 30.24038650541154, "A", "-95.8079865631313, 30.24038650541154");
adding_billboard(-60.10509002138564, 23.526593580490083, "A", "-60.10509002138564, 23.526593580490083");
adding_billboard(-59.06372427570612, 2.245934026097194, "A", "-59.06372427570612, 2.245934026097194");
adding_billboard(-117.00668212362282, 3.938434130034481, "A", "-117.00668212362282, 3.938434130034481");
viewer.flyTo(redPolygon);
}
function adding_billboard(lon, lat, name, popup) {
const entity = viewer.entities.add({
name: name,
position: Cartesian3.fromDegrees(lon, lat, 2000),
billboard: {
image: "https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678111-map-marker-512.png",
show: true, // default
pixelOffset: new Cesium.Cartesian2(0, -20), // default: (0, 0)
eyeOffset: new Cartesian3(0.0, 0.0, 0.0), // default
horizontalOrigin: Cesium.HorizontalOrigin.bottom, // default
alignedAxis: Cesium.Cartesian3.ZERO, // default
width: 20, // default: undefined
height: 25 // default: undefined
//disableDepthTestDistance: Number.POSITIVE_INFINITY, // draws the label in front of terrain
// on ground show
},
label: {
text: popup,
font: "7pt sans-serif",
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BASELINE,
fillColor: Color.BLACK,
showBackground: true,
backgroundColor: new Color(1, 1, 1, 0.7),
backgroundPadding: new Cesium.Cartesian2(8, 4),
disableDepthTestDistance: Number.POSITIVE_INFINITY // draws the label in front of terrain
}
});
pointsCollection.push(entity);
}
loadPoly();
const scene = viewer.scene;
const handler = new ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function (click) {
const pickedObject = scene.pick(click.position);
if (defined(pickedObject) && pickedObject.id && pickedObject.id.id === polygonId) {
const newPolygonPoints = [
76.82071632075994, 33.4134542888633, 77.83750798568438, 33.39276536442791, 77.32892923803021,
32.93547457354476
];
polygonPoints = newPolygonPoints;
viewer.camera.flyTo({
destination: Cartesian3.fromDegrees(76.82071632075994, 33.4134542888633, 1000)
});
}
}, ScreenSpaceEventType.LEFT_CLICK);

Issue in creating ports with GoJS

I am testing the GoJS library for Javascript.
I'm looking to create ports on the sides of a group.
I attach an executable extract from the program.
When I create a new object from the palette, right-click on the object, and select "Add left port", the debugging message shows that the variable "arr" is declared "undefined" at execution. (program lines 111 and 112).
Thank you for your help.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamic Ports</title>
<meta name="description" content="Nodes with varying lists of ports on each of four sides." />
<!-- Copyright 1998-2017 by Northwoods Software Corporation. -->
<meta charset="UTF-8">
<script src="../release/go-debug.js"></script>
<script src="../assets/js/goSamples.js"></script> <!-- this is only for the GoJS Samples framework -->
<!-- LL <script>goCode("diagramEvents", 600, 200)</script>-->
<script src="/Users/leonlevy/gojs/site/extensionsTS/ResizeMultipleScript.js"></script>
<span id="diagramEventsMsg" style="color: red"></span>
<span id="changeMethodsMsg" style="color: red"></span>
<span id="BackgroundDoubleClicked" style="color: red"></span>
<p>
<script id="code">
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 node templates
myDiagram =
$(go.Diagram, "myDiagramDiv",
{
allowDrop: true, // from Palette
// what to do when a drag-drop occurs in the Diagram's background
mouseDrop: function(e) { finishDrop(e, null); },
// layout: null, // Diagram has no layout
/* $(go.GridLayout,
{ wrappingWidth: Infinity, alignment: go.GridLayout.Position, cellSize: new go.Size(1, 1) }),*/
initialContentAlignment: go.Spot.Center,
"commandHandler.archetypeGroupData": { isGroup: true, category: "OfGroups" },
"undoManager.isEnabled": true
});
// LL
function showMessage(s) {
document.getElementById("diagramEventsMsg").textContent = s;
}
// when the document is modified, add a "*" to the title and enable the "Save" button
myDiagram.addDiagramListener("Modified", function(e) {
var button = document.getElementById("SaveButton");
if (button) button.disabled = !myDiagram.isModified;
var idx = document.title.indexOf("*");
if (myDiagram.isModified) {
if (idx < 0) document.title += "*";
} else {
if (idx >= 0) document.title = document.title.substr(0, idx);
}
});
myDiagram.addDiagramListener("ObjectSingleClicked",
function(e) {
var part = e.subject.part;
var heightPart = part.actualBounds.height;
var widthPart = part.actualBounds.width;
var xPart = part.actualBounds.position.x;
var yPart = part.actualBounds.position.y;
var xMouseClic = myDiagram.lastInput.documentPoint.x;
var yMouseClic = myDiagram.lastInput.documentPoint.y;
var xPartMiddle = xPart+ widthPart/2;
var side = xMouseClic<= xPartMiddle ? "Left" : "Right";
if (!(part instanceof go.Link)) {console.log("hello leon");}
});
myDiagram.addDiagramListener("BackgroundSingleClicked",
function(e) {
showMessage("Clicked on background " + myDiagram.lastInput.documentPoint);
//console.log("hello leon");}
});
myDiagram.addDiagramListener("BackgroundDoubleClicked", // LL KO
function(e) {
showMessage("Double-clicked at " );//+ e.myDiagram.lastInput.documentPoint);
//showMessage("Clicked on " + myDiagram.lastInput.documentPoint);
});
myDiagram.addDiagramListener("ClipboardPasted",
function(e) { showMessage("Pasted " + e.myDiagram.selection.count + " parts"); });
// LL end
// To simplify this code we define a function for creating a context menu button:
function makeButton(text, action, visiblePredicate) {
return $("ContextMenuButton",
$(go.TextBlock, text),
{ click: action },
//{showMessage( "button: " + myDiagram.lastInput.button);
// don't bother with binding GraphObject.visible if there's no predicate
visiblePredicate ? new go.Binding("visible", "", function(o, e) { return o.myDiagram ? visiblePredicate(o, e) : false; }).ofObject() : {});
//}
}
var nodeMenu = // context menu for each Node
$(go.Adornment, "Horizontal",
makeButton("Add left port",
function (e, obj) { addPort("left"); }),
makeButton("Add right port",
function (e, obj) { addPort("right"); }),
); //Leon end nodeM
// Add a port to the specified side of the selected nodes.
function addPort(side) {
myDiagram.startTransaction("addPort");
myDiagram.selection.each(function(node) {
// skip any selected Links
if (!(node instanceof go.Node)) return;
// compute the next available index number for the side
var i = 0;
while (node.findPort(side + i.toString()) !== node) i++;
// now this new port name is unique within the whole Node because of the side prefix
var name = side + i.toString();
// get the Array of port data to be modified
var arr = node.data[side + "Array"];
showMessage ("node: " + node + "; name: " + name + ";arr: " + arr + ";node.data: " + node.data);
if (arr) {
// create a new port data object
var newportdata = {
portId: name,
portColor: go.Brush.randomColor()
// if you add port data properties here, you should copy them in copyPortData above
};
// and add it to the Array of port data
myDiagram.model.insertArrayItem(arr, -1, newportdata);
}
});
myDiagram.commitTransaction("addPort");
}
var portSize = new go.Size(8, 8);
// this function is used to highlight a Group that the selection may be dropped into
function highlightGroup(e, grp, show) {
if (!grp) return; showMessage("ok")
e.handled = true;
if (show) {
// cannot depend on the grp.diagram.selection in the case of external drag-and-drops;
// instead depend on the DraggingTool.draggedParts or .copiedParts
var tool = grp.diagram.toolManager.draggingTool;
var map = tool.draggedParts || tool.copiedParts; // this is a Map
// now we can check to see if the Group will accept membership of the dragged Parts
if (grp.canAddMembers(map.toKeySet())) {
grp.isHighlighted = true;
return;
}
}
grp.isHighlighted = false;
}
// Upon a drop onto a Group, we try to add the selection as members of the Group.
// Upon a drop onto the background, or onto a top-level Node, make selection top-level.
// If this is OK, we're done; otherwise we cancel the operation to rollback everything.
function finishDrop(e, grp) {
var ok = (grp !== null
? grp.addMembers(grp.diagram.selection, true)
: e.diagram.commandHandler.addTopLevelParts(e.diagram.selection, true));
if (!ok) e.diagram.currentTool.doCancel();
}
var portMenu = // context menu for each port
$(go.Adornment, "Vertical",
makeButton("Remove port",
// in the click event handler, the obj.part is the Adornment;
// its adornedObject is the port
function (e, obj) { removePort(obj.part.adornedObject); }),
makeButton("Change color",
function (e, obj) { changeColor(obj.part.adornedObject); }),
makeButton("Remove side ports",
function (e, obj) { removeAll(obj.part.adornedObject); })
);
// support double-clicking in the background to add a copy of this data as a node
myDiagram.toolManager.clickCreatingTool.archetypeNodeData = {
name: "Unit",
leftArray: [],
rightArray: [],
topArray: [],
bottomArray: []
};
myDiagram.groupTemplateMap.add("OfGroups",
$(go.Group, "Table",
{ locationObjectName: "BODY",
locationSpot: go.Spot.Center,
selectionObjectName: "BODY",
contextMenu: nodeMenu
},
{
background: "transparent",
resizable: true,
// highlight when dragging into the Group
mouseDragEnter: function(e, grp, prev) { highlightGroup(e, grp, true); },
mouseDragLeave: function(e, grp, next) { highlightGroup(e, grp, false); },
//computesBoundsAfterDrag: true,
mouseDrop: finishDrop,
resizable: true, resizeObjectName: "SHAPE"
//, minSize: new go.Size(36, 46)
},
new go.Binding("background", "isHighlighted", function(h) { return h ? "rgba(0,0,255,0.)" : "transparent"; }).ofObject(),
// save the modified size in the model node data
new go.Binding("desiredSize", "size", go.Size.parse).makeTwoWay(go.Size.stringify),
new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
$(go.Shape, "Rectangle",
{ fill: null, stroke: "rgba(0,50,255,1)", strokeWidth: 3, name: "SHAPE"}),
$(go.Panel, "Vertical", {alignment: go.Spot.Top},// title above Placeholder
$(go.Panel, "Horizontal", // button next to TextBlock
{ stretch: go.GraphObject.Horizontal, background: "rgba(0,0,255,0.1)" },
$("SubGraphExpanderButton",
{ alignment: go.Spot.Right, margin: 5 }),
$(go.TextBlock,
{ //text: "verticalAlignment: Top", verticalAlignment: go.Spot.Top,
alignment: go.Spot.Left,
editable: true,
margin: 5,
font: "bold 18px sans-serif",
opacity: 0.75,
stroke: "#404040"
},
new go.Binding("text", "text").makeTwoWay())
), // end Horizontal Panel
$(go.Placeholder,
{ padding: 5, alignment: go.Spot.TopLeft })
), // end Vertical Panel
// the Panel holding the left port elements, which are themselves Panels,
// created for each item in the itemArray, bound to data.leftArray
$(go.Panel, "Vertical",
new go.Binding("itemArray", "leftArray"),
{ row: 1, column: 0,
itemTemplate:
$(go.Panel,
{ _side: "left", // internal property to make it easier to tell which side it's on
fromSpot: go.Spot.Left, toSpot: go.Spot.Left,
fromLinkable: true, toLinkable: true, cursor: "pointer",
contextMenu: portMenu },
new go.Binding("portId", "portId"),
$(go.Shape, "Rectangle",
{ stroke: null, strokeWidth: 0,
desiredSize: portSize,
margin: new go.Margin(1,0) },
new go.Binding("fill", "portColor"))
) // end itemTemplate
}
), // end Vertical Panel
// the Panel holding the right port elements, which are themselves Panels,
// created for each item in the itemArray, bound to data.rightArray
$(go.Panel, "Vertical",
new go.Binding("itemArray", "rightArray"),
{ row: 1, column: 2,
itemTemplate:
$(go.Panel,
{ _side: "right",
fromSpot: go.Spot.Right, toSpot: go.Spot.Right,
fromLinkable: true, toLinkable: true, cursor: "pointer",
contextMenu: portMenu },
new go.Binding("portId", "portId"),
$(go.Shape, "Rectangle",
{ stroke: null, strokeWidth: 0,
desiredSize: portSize,
margin: new go.Margin(1, 0) },
new go.Binding("fill", "portColor"))
) // end itemTemplate
}
), // end Vertical Panel
)
); // end groupTemplateMap.add("OfGroups"
// initialize the Palette and its contents
myPalette =
$(go.Palette, "myPaletteDiv",
{
groupTemplateMap: myDiagram.groupTemplateMap,
layout: $(go.GridLayout, { wrappingColumn: 1, alignment: go.GridLayout.Position })
});
myPalette.nodeTemplate =
$(go.Node, "Horizontal",
$(go.Shape,
{ width: 10, height: 10, fill: "white" },
new go.Binding("fill", "color")),
$(go.TextBlock,
new go.Binding("text", "color"))
);
myPalette.model = new go.GraphLinksModel([
{ key: 101, text: 'UNIT', isGroup: true, isSubProcess: true,
category: "OfGroups", isAdHoc: true, loc: '0 0' },
]);
}
</script>
</head>
<body onload="init()">
<!-- LL -->
<body onload="goIntro()">
<div id="container" class="container-fluid">
<div id="content">
<div id="sample">
<div style="width: 100%; display: flex; justify-content: space-between">
<div id="myPaletteDiv" style="width: 100px; margin-right: 2px; background-color: whitesmoke; border: solid 1px black"></div>
<div id="myDiagramDiv" style="flex-grow: 1; height: 480px; border: solid 1px black"></div>
</div>
<p>
See the Ports Intro page for an explanation of GoJS ports.
</p>
<textarea id="mySavedModel" style="width:100%;height:250px">
</textarea>
</div>
</div>
</body>
</html>
You need to make sure that the node is bound to the correct data. In particular, the data object should have a leftArray property that is an Array holding port descriptor objects. (And it seems to expect a rightArray property too.) You can determine the expected properties for each Node by looking at the source property names of each of the Bindings that are in the node template.
You can determine the expected properties for each of the port descriptors in either data Array by looking at the properties that the Panel.itemTemplate uses in its data Bindings.

Links label are overlapped between each other

I have created two square shapes and connect them with links by their ports. But when I create more than two links, their link labels starting overlap (You can see this in screenshot below).
Is GoJS has some options to correctly align or separate labels?
I think the problem might be that you are using multiple ports. Assuming the ports are positioned along a side of a node, there isn't much choice for where links could connect with the node.
Instead, the default behavior for a node with a single port might be what you are looking for:
function init() {
var $ = go.GraphObject.make;
myDiagram =
$(go.Diagram, "myDiagramDiv");
myDiagram.nodeTemplate =
$(go.Node, "Auto",
new go.Binding("location"),
$(go.Shape,
{ fill: "white", portId: "" },
new go.Binding("fill", "color")),
$(go.TextBlock,
{ margin: 8 },
new go.Binding("text"))
);
myDiagram.linkTemplate =
$(go.Link,
//{ curve: go.Link.Bezier },
$(go.Shape),
$(go.Shape, { toArrow: "OpenTriangle" }),
$(go.TextBlock, { background: "white" },
new go.Binding("text"))
);
myDiagram.model = new go.GraphLinksModel(
[
{ key: 1, text: "Alpha", color: "lightblue", location: new go.Point(0, 0) },
{ key: 2, text: "Beta", color: "orange", location: new go.Point(200, 50) },
{ key: 3, text: "Gamma", color: "lightgreen", location: new go.Point(50, 200) }
],
[
{ from: 1, to: 2, text: "12" },
{ from: 1, to: 2, text: "a long label" },
{ from: 2, to: 1, text: "345" },
{ from: 1, to: 3, text: "13" },
{ from: 1, to: 3, text: "short" },
{ from: 3, to: 1, text: "34567890" }
]);
}
produces:
Or if you specify Bezier curve links:
Move the nodes around and you can see how the distance between the links changes based on the breadth of the link labels, since the labels are not circular.

Define custom icon based on key?

I have model data which contains several keys for each entry, of interest is color.
I would like to specify a custom icon based on the value in color but am having troubles getting that value.
This is how my model looks:
{ key: "legendVendor", geo: "Vendor", color: vendorColor },
{ key: "legendFactory", geo: "Factory", color: factoryColor },
{ key: "legendVendorFactory", geo: "Vendor Factory", color: vendorFactoryColor },
{ key: "legendSupplier", geo: "Supplier", color: supplierColor },
This is how my color constant are defined:
var vendorColor = "#C8DA2B";
var factoryColor = "#800080";
var supplierColor = "#CCD1D1";
var supplyChainColor = "#FFD700";
var vendorFactoryColor = "#34c0eb";
This is how I am setting the shape based on color:
function geoFunc(geoname, color) {
var geo = icons[geoname];
// var color = icons[color];
if (geo === undefined) geo = icons["cloud"]; // use this for an unknown icon name
if (typeof geo === "string") {
geo = icons[geoname] = go.Geometry.parse(geo, true); // fill each geometry
}
switch(color) {
case vendorColor:
// code block
geo = icons["heart"]
geo = icons[geoname] = go.Geometry.parse(geo, true);
break;
default:
// code block
}
return geo;
}
And this is how I am calling that function:
myDiagram.nodeTemplate =
$(go.Node, "Auto",
{isTreeExpanded:false},
{doubleClick: function(e, node) {node.expandTree(1);}},
$(go.TextBlock, {text:"Text",width:100,height:100,textAlign:"center",font:"12pt sans-serif",margin:3,wrap: go.TextBlock.WrapDesiredSize,alignment:go.Spot.BottomCenter},new go.Binding("text", "geo")),
$(go.Shape,
{ margin: 3, fill: colors["white"], strokeWidth: 0 },
new go.Binding("geometry", "geo", "color", geoFunc), // magic happens here <--------
new go.Binding("fill", "color")),
How can I pass along the value of color to the function geoFunc?
You should be getting a run-time error because "color" is not a conversion function. It might help to use go-debug.js to get more error or warning messages.
If you delete the "geo" argument to the Binding constructor, you will have a valid call to the constructor, and then the geoFunc function will be called and passed the value of data.color.

Swimlane - GoJS library

I would like to ask, if anyone knows how to convert the orientation of the diagram of swimlanes in GOjs library from being top-level to a single row orientation, it is because I want to have a diagram that connects a node to another from a different group.
And also is it possible to add attributes to each node, like onmouseover, class, id, name, and etc.?
Currently I have this copied and paste code:
<!DOCTYPE html>
<html>
<head>
<title>Swimlane</title>
<!-- Copyright 1998-2014 by Northwoods Software Corporation. -->
<link href="goSamples.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="go.js"></script>
<script id="code">
// These parameters need to be set before defining the templates.
// this controls whether the swimlanes are horizontal stacked vertically, or the other way:
var HORIZONTAL = true;
// this controls the minimum length of any swimlane
var MINLENGTH = 200;
// this controls the minimum breadth of any swimlane
var MINBREADTH = 100;
// compute the minimum length needed to hold all of the subgraphs
function computeMinPlaceholderSize(diagram) {
var len = MINLENGTH;
for (var it = diagram.nodes; it.next(); ) {
var group = it.value;
if (!(group instanceof go.Group)) continue;
var holder = group.placeholder;
if (holder !== null) {
var sz = holder.actualBounds;
len = Math.max(len, (HORIZONTAL ? sz.width : sz.height));
}
}
return (HORIZONTAL ? new go.Size(len, NaN) : new go.Size(NaN, len));
}
// get the minimum placeholder size for a particular Group;
// when group is null, return the minimum size
function computePlaceholderSize(group) {
if (group instanceof go.Group) {
var holder = group.placeholder;
if (holder !== null) {
return holder.actualBounds.size;
}
}
return (HORIZONTAL ? new go.Size(MINLENGTH, MINBREADTH) : new go.Size(MINBREADTH, MINLENGTH));
}
// define a custom ResizingTool to limit how far one can shrink a Group
function GroupResizingTool() {
go.ResizingTool.call(this);
}
go.Diagram.inherit(GroupResizingTool, go.ResizingTool);
GroupResizingTool.prototype.isLengthening = function() {
return (this.handle.alignment === (HORIZONTAL ? go.Spot.Right : go.Spot.Bottom));
};
GroupResizingTool.prototype.computeMinSize = function() {
var msz = computePlaceholderSize(null); // get the minimum size
if (this.isLengthening()) { // compute the minimum length of all lanes
var sz = computeMinPlaceholderSize(this.diagram);
if (HORIZONTAL) {
msz.width = Math.max(msz.width, sz.width);
} else {
msz.height = Math.max(msz.height, sz.height);
}
} else { // find the minimum size of this single lane
var sz = computePlaceholderSize(this.adornedObject.part);
msz.width = Math.max(msz.width, sz.width);
msz.height = Math.max(msz.height, sz.height);
}
return msz;
};
GroupResizingTool.prototype.resize = function(newr) {
if (this.isLengthening()) { // changing the length of all of the lanes
for (var it = myDiagram.nodes; it.next(); ) {
var group = it.value;
if (!(group instanceof go.Group)) continue;
var shape = group.findObject("SHAPE");
if (shape !== null) { // set its desiredSize, but leave the other direction alone
if (HORIZONTAL) {
shape.width = newr.width;
} else {
shape.height = newr.height;
}
}
}
} else { // changing the breadth and length of a single lane
go.ResizingTool.prototype.resize.call(this, newr);
}
};
// end GroupResizingTool class
// define a custom grid layout that makes sure the length of each lane is the same
// and that each lane is broad enough to hold its subgraph
function StackLayout() {
go.GridLayout.call(this);
}
go.Diagram.inherit(StackLayout, go.GridLayout);
StackLayout.prototype.doLayout = function(coll) {
var diagram = this.diagram;
if (diagram === null) return;
diagram.startTransaction("StackLayout");
// make sure all of the Group Shapes are big enough
var minsize = computeMinPlaceholderSize(diagram);
for (var it = diagram.nodes; it.next(); ) {
var group = it.value;
if (!(group instanceof go.Group)) continue;
var shape = group.findObject("SHAPE");
if (shape !== null) { // change the desiredSize to be big enough in both directions
var sz = computePlaceholderSize(group);
if (HORIZONTAL) {
shape.width = (isNaN(shape.width) ? minsize.width : Math.max(shape.width, minsize.width));
if (!isNaN(shape.height)) shape.height = Math.max(shape.height, sz.height);
} else {
if (!isNaN(shape.width)) shape.width = Math.max(shape.width, sz.width);
shape.height = (isNaN(shape.height) ? minsize.height : Math.max(shape.height, minsize.height));
}
var cell = group.resizeCellSize;
if (!isNaN(shape.width) && !isNaN(cell.width) && cell.width > 0) shape.width = Math.ceil(shape.width / cell.width) * cell.width;
if (!isNaN(shape.height) && !isNaN(cell.height) && cell.height > 0) shape.height = Math.ceil(shape.height / cell.height) * cell.height;
}
}
// now do all of the usual stuff, according to whatever properties have been set on this GridLayout
go.GridLayout.prototype.doLayout.call(this, coll);
diagram.commitTransaction("StackLayout");
};
// end StackLayout class
function init() {
if (window.goSamples) goSamples(); // init for these samples -- you don't need to call this
var $ = go.GraphObject.make;
myDiagram =
$(go.Diagram, "myDiagram",
{
// use a custom ResizingTool (along with a custom ResizeAdornment on each Group)
resizingTool: new GroupResizingTool(),
// use a simple layout that ignores links to stack the top-level Groups on top of each other
layout:
$(StackLayout,
{
cellSize: new go.Size(1, 1),
spacing: new go.Size(0, 0),
wrappingColumn: (HORIZONTAL ? 1 : Infinity),
wrappingWidth: Infinity,
isViewportSized: false
}),
// don't allow dropping onto the diagram's background
mouseDrop: function(e) { e.diagram.currentTool.doCancel(); },
// a clipboard copied node is pasted into the original node's group (i.e. lane).
"commandHandler.copiesGroupKey": true
});
// When a Node has been moved, make sure all of the top-level Groups get laid out again in a stack
function relayoutDiagramStack(e) {
myDiagram.layout.invalidateLayout(); // but don't invalidate all Layouts that are in Groups
myDiagram.layoutDiagram();
}
myDiagram.addDiagramListener("SelectionMoved", relayoutDiagramStack);
myDiagram.addDiagramListener("SelectionCopied", relayoutDiagramStack);
// this is a Part.dragComputation function for limiting where a Node may be dragged
function stayInGroup(part, pt, gridpt) {
// don't constrain top-level nodes
var grp = part.containingGroup;
if (grp === null) return pt;
// try to stay within the background Shape of the Group
var back = grp.findObject("SHAPE");
if (back === null) return pt;
// allow dragging a Node out of a Group if the Shift key is down
if (part.diagram.lastInput.shift) return pt;
var b = part.actualBounds;
var p1 = back.getDocumentPoint(go.Spot.TopLeft);
var p2 = back.getDocumentPoint(go.Spot.BottomRight);
// find the padding inside the group's placeholder that is around the member parts
var m = grp.placeholder.padding;
// now limit the location appropriately
var x = Math.max(p1.x + m.left, Math.min(pt.x, p2.x - m.right - b.width - 1));
var y = Math.max(p1.y + m.top, Math.min(pt.y, p2.y - m.bottom - b.height - 1));
return new go.Point(x, y);
}
myDiagram.nodeTemplate =
$(go.Node, "Auto",
$(go.Shape, "Rectangle",
{ fill: "white", portId: "", cursor: "pointer", fromLinkable: true, toLinkable: true }),
$(go.TextBlock, { margin: 5 },
new go.Binding("text", "key")),
// limit dragging of Nodes to stay within the containing Group, defined above
{
dragComputation: stayInGroup,
mouseDrop: function (e, node) { // dropping a copy of some Nodes and Links onto this Node adds them to this Node's Group
if (!e.shift && !e.control) return; // cannot change groups with an unmodified drag-and-drop
var grp = node.containingGroup;
if (grp !== null) {
var ok = grp.addMembers(node.diagram.selection, true);
if (!ok) grp.diagram.currentTool.doCancel();
}
},
layoutConditions: go.Part.LayoutAdded | go.Part.LayoutNodeSized
}
);
// each Group is a "swimlane" with a header on the left and a resizable lane on the right
myDiagram.groupTemplate =
$(go.Group, HORIZONTAL ? "Horizontal" : "Vertical",
{
movable: false, copyable: false, deletable: false, // can't move or copy or delete lanes
avoidable: false,
selectionObjectName: "SHAPE", // selecting a lane causes the body of the lane to be highlit, not the label
resizable: true, resizeObjectName: "SHAPE", // allow lanes to be resized, but the custom resizeAdornmentTemplate only permits one kind of resizing
layout: $(go.LayeredDigraphLayout, // automatically lay out the lane's subgraph
{ direction: HORIZONTAL ? 0 : 90, columnSpacing: 10, layeringOption: go.LayeredDigraphLayout.LayerLongestPathSource }),
computesBoundsAfterDrag: true, // needed to prevent recomputing Group.placeholder bounds too soon
computesBoundsIncludingLinks: false,
computesBoundsIncludingLocation: true,
mouseDrop: function (e, grp) { // dropping a copy of some Nodes and Links onto this Group adds them to this Group
if (!e.shift && !e.control) return; // cannot change groups with an unmodified drag-and-drop
var ok = grp.addMembers(grp.diagram.selection, true);
if (!ok) grp.diagram.currentTool.doCancel();
}
},
// the lane header consisting of a Shape and a TextBlock
$(go.Panel, "Horizontal",
{ angle: HORIZONTAL ? 270 : 0, // maybe rotate the header to read sideways going up
alignment: go.Spot.Center },
$(go.Shape, "Diamond",
{ width: 8, height: 8 },
new go.Binding("fill", "color")),
$(go.TextBlock, // the lane label
{ font: "bold 16pt sans-serif" },
new go.Binding("text", "key"))
), // end Horizontal Panel
$(go.Panel, "Auto", // the lane consisting of a background Shape and a Placeholder representing the subgraph
$(go.Shape, "Rectangle",
{ name: "SHAPE", fill: "white", minSize: computePlaceholderSize(null) },
new go.Binding("fill", "color")),
$(go.Placeholder,
{ padding: 10, alignment: go.Spot.TopLeft })
) // end Auto Panel
); // end Group
// define a custom resize adornment that only has a single resize handle
myDiagram.groupTemplate.resizeAdornmentTemplate =
$(go.Adornment, "Spot",
$(go.Placeholder),
$(go.Shape, // for changing the length of a lane
{
alignment: HORIZONTAL ? go.Spot.Right: go.Spot.Bottom,
desiredSize: HORIZONTAL ? new go.Size(7, 50) : new go.Size(50, 7),
fill: "lightblue", stroke: "dodgerblue",
cursor: HORIZONTAL ? "col-resize" : "row-resize"
}),
$(go.Shape, // for changing the breadth of a lane
{
alignment: HORIZONTAL ? go.Spot.Bottom : go.Spot.Right,
desiredSize: HORIZONTAL ? new go.Size(50, 7) : new go.Size(7, 50),
fill: "lightblue", stroke: "dodgerblue",
cursor: HORIZONTAL ? "row-resize" : "col-resize"
})
);
myDiagram.linkTemplate =
$(go.Link,
{ routing: go.Link.AvoidsNodes, corner: 5 },
{ relinkableFrom: true, relinkableTo: true },
$(go.Shape),
$(go.Shape, { toArrow: "Standard" }),
{
mouseDrop: function (e, link) { // dropping a copy of some Nodes and Links onto this Link adds them to this Link's Group
if (!e.shift && !e.control) return; // cannot change groups with an unmodified drag-and-drop
var grp = link.containingGroup;
if (grp !== null) {
var ok = grp.addMembers(link.diagram.selection, true);
if (!ok) grp.diagram.currentTool.doCancel();
}
},
layoutConditions: go.Part.LayoutAdded
}
);
// define some sample graphs in some of the lanes
myDiagram.model = new go.GraphLinksModel(
[ // node data
{ key: "Lane1", isGroup: true, color: "lightblue" },
{ key: "Lane2", isGroup: true, color: "lightgreen" },
{ key: "Lane3", isGroup: true, color: "lightyellow" },
{ key: "Lane4", isGroup: true, color: "orange" },
{ key: "oneA", group: "Lane1" },
{ key: "oneB", group: "Lane1" },
{ key: "oneC", group: "Lane1" },
{ key: "oneD", group: "Lane1" },
{ key: "twoA", group: "Lane2" },
{ key: "twoB", group: "Lane2" },
{ key: "twoC", group: "Lane2" },
{ key: "twoD", group: "Lane2" },
{ key: "twoE", group: "Lane2" },
{ key: "twoF", group: "Lane2" },
{ key: "twoG", group: "Lane2" },
{ key: "fourA", group: "Lane4" },
{ key: "fourB", group: "Lane4" },
{ key: "fourC", group: "Lane4" },
{ key: "fourD", group: "Lane4" },
],
[ // link data
{ from: "oneA", to: "oneB" },
{ from: "oneA", to: "oneC" },
{ from: "oneB", to: "oneD" },
{ from: "oneC", to: "oneD" },
{ from: "twoA", to: "twoB" },
{ from: "twoA", to: "twoC" },
{ from: "twoA", to: "twoF" },
{ from: "twoB", to: "twoD" },
{ from: "twoC", to: "twoD" },
{ from: "twoD", to: "twoG" },
{ from: "twoE", to: "twoG" },
{ from: "twoF", to: "twoG" },
{ from: "fourA", to: "fourB" },
{ from: "fourB", to: "fourC" },
{ from: "fourC", to: "fourD" }
]);
myDiagram.model.undoManager.isEnabled = true;
}
</script>
</head>
<body onload="init()">
<div id="sample">
<div id="myDiagram" style="border: solid 1px blue; width:100%; height:600px;"></div>
</div>
</body>
</html>
I've tried setting
var HORIZONTAL = true;
to
var HORIZONTAL = false;
I may have the correct orientation though, but the flow is changed. I wonder if the column could just be horizontal and the flow runs like the top-level view.
The "flow" is changed because setting HORIZONTAL = false also changes the Group's layout that it users for its members:
myDiagram.groupTemplate =
$(go.Group, HORIZONTAL ? "Horizontal" : "Vertical",
{
...
layout: $(go.LayeredDigraphLayout, // automatically lay out the lane's subgraph
{ direction: HORIZONTAL ? 0 : 90, columnSpacing: 10, layeringOption: go.LayeredDigraphLayout.LayerLongestPathSource }),
So you're going to have to modify that direction: HORIZONTAL ? 0 : 90 to your liking if you don't want it to change when HORIZONTAL does.
It is not possible to add HTML attributes to each node, but you can store any arbitrary data for each node in the node data itself.

Categories

Resources