I figured I should try what I suggested. I did so with two separate approaches: the traditional modification of the data as well as the immutable data approach that calls Model.merge…. I have appended my code that tested both approaches, which each seem to work as I expected.
<!DOCTYPE html>
<html>
<head>
<title>Minimal GoJS Sample</title>
<!-- Copyright 1998-2021 by Northwoods Software Corporation. -->
<script src="https://unpkg.com/gojs"></script>
<script id="code">
function init() {
var $ = go.GraphObject.make;
myDiagram =
$(go.Diagram, "myDiagramDiv",
{
"undoManager.isEnabled": true,
"ModelChanged": function(e) { // just for demonstration purposes,
if (e.isTransactionFinished) { // show the model data in the page's TextArea
document.getElementById("mySavedModel").textContent = e.model.toJson();
}
}
});
myDiagram.nodeTemplate =
$(go.Node, "Auto",
$(go.Shape,
{ fill: "white", portId: "", fromLinkable: true, toLinkable: true, cursor: "pointer" },
new go.Binding("fill", "color")),
$(go.TextBlock,
{ margin: 8, editable: true },
new go.Binding("text").makeTwoWay())
);
myDiagram.model = new go.GraphLinksModel(
[
{ key: 1, text: "Alpha", color: "lightblue" },
{ key: 2, text: "Beta", color: "orange" },
{ key: 3, text: "Gamma", color: "lightgreen" },
{ key: 4, text: "Delta", color: "pink" }
],
[
{ from: 1, to: 2 },
{ from: 1, to: 3 },
{ from: 2, to: 2 },
{ from: 3, to: 4 },
{ from: 4, to: 1 }
]);
}
// by modifying the data
function test() {
myDiagram.model.commit(m => {
m.removeNodeData(m.findNodeDataForKey(2));
});
}
function test2() {
myDiagram.model.commit(m => {
m.addNodeData({ key: 2, isGroup: true, text: "Omega", color: "green" });
m.setGroupKeyForNodeData(m.findNodeDataForKey(3), 2);
m.setGroupKeyForNodeData(m.findNodeDataForKey(4), 2);
});
}
// using merge (i.e. immutable data)
function testm() {
myDiagram.model.commit(m => {
const a = m.nodeDataArray.slice();
a.splice(a.indexOf(m.findNodeDataForKey(2)), 1);
m.mergeNodeDataArray(a);
});
}
function testm2() {
myDiagram.model.commit(m => {
// assume immutable data, so copy the whole nodeDataArray
const a = m.nodeDataArray.slice();
a.push({ key: 2, isGroup: true, text: "Omega", color: "green" });
// and copy any nodes that need to belong to the new group
const o3 = m.findNodeDataForKey(3);
const n3 = Object.assign({ group: 2 }, o3);
a[a.indexOf(o3)] = n3; // including replacing the reference in the new Array
const o4 = m.findNodeDataForKey(4);
const n4 = Object.assign({ group: 2 }, o4);
a[a.indexOf(o4)] = n4;
m.mergeNodeDataArray(a);
});
}
</script>
</head>
<body onload="init()">
<div id="myDiagramDiv" style="border: solid 1px black; width:100%; height:600px"></div>
<!--<button onclick="test()">Test Modify</button>
<button onclick="test2()">Test Modify 2</button>-->
<button onclick="testm()">Test Merge</button>
<button onclick="testm2()">Test Merge 2</button>
<textarea id="mySavedModel" style="width:100%;height:250px"></textarea>
</body>
</html>