How to delete the parent node without deleting the children nodes - cytoscape.js

This is the code sample that I am using in reactjs.
const node = graph.$(`#${selectedNode.id()}`);
graph.remove(node);
selectedNode.id is the id of the parent node but it deletes all the children nodes inside this parent node.
How can I delete the parent node only and not its descendants?
This question is similar to this on here Remove/hide compound node without removing/hiding descendants but I will appreciate it if some code samples are provided because in the doc here http://js.cytoscape.org/#collection/graph-manipulation/eles.move we have a shallow code example of edges but I am interested in nodes.
Thanks

You can delete a parent node by first moving its children to the parent's parent (if it exist, otherwise you should assig a null value) and then removing the parent node. Select a parent node and click on the delete button in the below example.
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
layout: {name: 'grid', rows: 2},
style: [{
selector: 'node',
css: {
'label': 'data(id)'
}
}
],
elements: {
nodes: [{
data: {
id: 'n0',
parent: 'n1'
}
},
{
data: {
id: 'n1',
parent: 'n2'
}
},
{
data: {
id: 'n2'
}
},
{
data: {
id: 'n3'
}
}
],
edges: [
{
data: {
id: 'n2n3',
source: 'n2',
target: 'n3',
weight: 7
}
}
]
}
});
document.getElementById("deleteButton").addEventListener("click", function() {
let selected = cy.nodes(':selected')[0];
selected.children().move({parent : (selected.parent().id() ? selected.parent().id() : null)});
selected.remove();
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#button {
z-index = 1000;
}
#cy {
height: 95%;
width: 95%;
left: 0;
top: 50;
z-index = 900;
position: absolute;
}
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<script src="https://unpkg.com/cytoscape#3.10.0/dist/cytoscape.min.js">
</script>
</head>
<body>
<button id="deleteButton" type="button">Delete selected</button>
<div id="cy"></div>
</body>
</html>

Related

How can I make the label of an edge displayed just in the middle position?

I'm trying to make the label displayed in the middle position, say source --<sometext>--> target.
I'm reading the official document but I can't find an answer.
Can this be implemented?
as you can see here, there is a simple solution to this provided by cytoscape:
window.cy = cytoscape({
container: document.getElementById('cy'),
layout: {
name: 'grid',
cols: 2
},
style: [{
"selector": "node[label]",
"style": {
"label": "data(label)"
}
},
{
"selector": "edge[label]",
"style": {
"label": "data(label)",
"width": 3,
"text-background-opacity": 1,
"text-background-color": "#fff"
}
},
{
"selector": ".autorotate",
"style": {
"edge-text-rotation": "autorotate",
}
}
],
elements: [{
data: {
id: 'one'
}
},
{
data: {
id: 'two'
}
}, {
data: {
source: 'one',
target: 'two',
label: 'autorotate (move my nodes)'
},
classes: 'autorotate'
}
]
});
body {
font-family: helvetica, sans-serif;
font-size: 14px;
}
#cy {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 999;
}
<html>
<head>
<title>Labels demo</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape#3.3.0/dist/cytoscape.min.js"></script>
</head>
<body>
<div id="cy"></div>
</body>
</html>

Show and hide node info on mouseover in cytoscape

I am working on a cytoscape.js graph in browser. I want to show some information of nodes (e.g. node label) as the mouse hovers over the nodes in a cytoscape graph. The following code is working for console.log() but I want to show the information in the browser:
cy.on('mouseover', 'node', function(evt){
var node = evt.target;
console.log( 'mouse on node' + node.data('label') );
});
Please help !
Cytoscape.js has popper.js with tippy. I can give you a working exapmle for popper.js:
popper with tippy:
document.addEventListener("DOMContentLoaded", function() {
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
style: [{
selector: "node",
style: {
content: "data(id)"
}
},
{
selector: "edge",
style: {
"curve-style": "bezier",
"target-arrow-shape": "triangle"
}
}
],
elements: {
nodes: [{
data: {
id: "a"
}
}, {
data: {
id: "b"
}
}],
edges: [{
data: {
id: "ab",
source: "a",
target: "b"
}
}]
},
layout: {
name: "grid"
}
}));
function makePopper(ele) {
let ref = ele.popperRef(); // used only for positioning
ele.tippy = tippy(ref, { // tippy options:
content: () => {
let content = document.createElement('div');
content.innerHTML = ele.id();
return content;
},
trigger: 'manual' // probably want manual mode
});
}
cy.ready(function() {
cy.elements().forEach(function(ele) {
makePopper(ele);
});
});
cy.elements().unbind('mouseover');
cy.elements().bind('mouseover', (event) => event.target.tippy.show());
cy.elements().unbind('mouseout');
cy.elements().bind('mouseout', (event) => event.target.tippy.hide());
});
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px
}
#cy {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 1;
}
h1 {
opacity: 0.5;
font-size: 1em;
font-weight: bold;
}
<head>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/popper.js#1.14.7/dist/umd/popper.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-popper#1.0.4/cytoscape-popper.min.js"></script>
<script src="https://unpkg.com/tippy.js#4.0.1/umd/index.all.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/tippy.js#4.0.1/index.css" />
</head>
<body>
<div id="cy"></div>
</body>
Hi guys the Stephan's answer won't work using module based code like in React.js so I'm giving you an alternative without tippy
popper.css // popper style
.popper-div { // fill free to modify as you prefer
position: relative;
background-color: #333;
color: #fff;
border-radius: 4px;
font-size: 14px;
line-height: 1.4;
outline: 0;
padding: 5px 9px;
}
App.js
import cytoscape from "cytoscape";
import popper from "cytoscape-popper"; // you have to install it
import "./popper.css";
cytoscape.use(popper);
const cy = cytoscape({....});
cy.elements().unbind("mouseover");
cy.elements().bind("mouseover", (event) => {
event.target.popperRefObj = event.target.popper({
content: () => {
let content = document.createElement("div");
content.classList.add("popper-div");
content.innerHTML = event.target.id();
document.body.appendChild(content);
return content;
},
});
});
cy.elements().unbind("mouseout");
cy.elements().bind("mouseout", (event) => {
if (event.target.popper) {
event.target.popperRefObj.state.elements.popper.remove();
event.target.popperRefObj.destroy();
}
});

Cytoscape.js: Overlapping edge labels in multigraph

There are several posts about edge or edge label overlaps in Cytoscape.js but the answers given there, like smaller labels and more spaced out nodes, don't help for a multigraph, i.e. a graph where two nodes can have multiple edges between them.
Is there a way to spread out edge labels even if they all belong to edges between the same two nodes? The edge pairs occur both in the same direction and in the reverse one.
As my graph is verly large, I would prefer a solution with haystack edges as the performance is already low.
Well you can rotate the text with "text-rotation": "autorotate" in the labels css. You can also define the "text-margin-x/y" for each node itself, but how do you plan on defining the position for each and every label? Lets assume, you did that perfectly: you would still need to do a reposition event after moving just one node, because the offsets will be off by then:
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
boxSelectionEnabled: false,
autounselectify: true,
style: [{
selector: "node",
css: {
content: "data(id)",
"text-valign": "center",
"text-halign": "center",
height: "60px",
width: "60px",
"border-color": "black",
"border-opacity": "1",
"border-width": "10px"
}
},
{
selector: "$node > node",
css: {
"padding-top": "10px",
"padding-left": "10px",
"padding-bottom": "10px",
"padding-right": "10px",
"text-valign": "top",
"text-halign": "center",
"background-color": "#bbb"
}
},
{
selector: "edge",
css: {
"target-arrow-shape": "triangle"
}
},
{
selector: "edge[label]",
css: {
"label": "data(label)",
"text-rotation": "autorotate",
"text-margin-x": "data(xalign)",
"text-margin-y": "data(yalign)"
}
},
{
selector: ":selected",
css: {
"background-color": "black",
"line-color": "black",
"target-arrow-color": "black",
"source-arrow-color": "black"
}
}
],
layout: {
name: "circle"
}
}));
var info = [{
name: "Peter",
next_op_name: "Claire"
},
{
name: "Claire",
next_op_name: "Mike"
},
{
name: "Mike",
next_op_name: "Rosa"
},
{
name: "Rosa",
next_op_name: "Peter"
}
];
cy.ready(function() {
var array = [];
// iterate over info once
for (var i = 0; i < info.length; i++) {
array.push({
group: "nodes",
data: {
id: info[i].name, // id is name!!!
label: info[i].name
}
});
array.push({
group: "edges",
data: {
id: "e" + i,
source: info[i].name,
target: info[i].next_op_name,
label: "e" + i,
xalign: (i == 0 || i == 1 ? '15px' : '-15px'),
yalign: (i == 0 || i == 3 ? '15px' : '-15px')
}
});
}
cy.add(array);
cy.layout({
name: "circle"
}).run();
});
cy.on("mouseover", "node", function(event) {
var node = event.target;
node.qtip({
content: "hello",
show: {
event: event.type,
ready: true
},
hide: {
event: "mouseout unfocus"
}
},
event
);
});
cy.on("tapdrag", "node", function(event) {
// update all relevant labels
var labels = event.target.connectedEdges();
for (var i = 0; i < labels.length; i++) {
// render with the right positions?
}
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 75%;
position: absolute;
left: 0;
top: 0;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.2.17/cytoscape.min.js"></script>
<!-- qtip imports -->
<script src="https://unpkg.com/jquery#3.3.1/dist/jquery.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-qtip/2.7.0/cytoscape-qtip.js"></script>
<!-- dagre imports -->
<script src="https://unpkg.com/dagre#0.7.4/dist/dagre.js"></script>
<script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-dagre/1.5.0/cytoscape-dagre.js"></script>
</head>
<body>
<div id="cy"></div>
</body>
</html>
The problem breaks down to this: the task seems simple, but keeping track of the positions of all nodes and the edges aaaaand your rendered labels is a sisyphean task.

How to set QTip to always show tooltips in Cytoscape.js

I'm looking for a way of getting QTip to concurrently display tooltips for each node in a Cytoscape.js graph, such that they are always displayed and anchored to the nodes in the graph without the user having to click or mouseover the node.
I got close with the code below:
$(document).ready(function(){
cy.nodes().qtip({
content: function(){ return 'Station: ' + this.id() +
'</br> Next Train: ' + this.data('nextTrain') +
'</br> Connections: ' + this.degree();
},
hide: false,
show: {
when: false,
ready: true
}
})
})
The above code displays tooltips on $(document).ready, but they are all located at one node in the Cytoscape graph and they disappear when I zoom in or pan at all.
The goal is to have tooltips anchored to each node in my graph such that when I zoom in and pan around they remain fixed to that node. I'm not sure if there is an easier way to do this just using Cytoscape (i.e., multi-feature labelling).
I'm using Qtip2, jQuery-2.0.3 and the most recent release of cytoscape.js
Any help is much appreciated.
EDIT: If you want to create these elements automatically, use a function and a loop to iterate over cy.nodes():
var makeTippy = function (nodeTemp, node) {
return tippy(node.popperRef(), {
html: (function () {
let div = document.createElement('div');
// do things in div
return div;
})(),
trigger: 'manual',
arrow: true,
placement: 'right',
hideOnClick: false,
multiple: true,
sticky: true
}).tooltips[0];
};
var nodes = cy.nodes();
for (var i = 0; i < nodes.length; i++) {
var tippy = makeTippy(nodes[i]);
tippy.show();
}
If you want a sticky qTip, I would instead recommend the cytoscape extension for popper.js and specificly the tippy version (sticky divs):
document.addEventListener('DOMContentLoaded', function() {
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
style: [{
selector: 'node',
style: {
'content': 'data(id)'
}
},
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle'
}
}
],
elements: {
nodes: [{
data: {
id: 'a'
}
},
{
data: {
id: 'b'
}
}
],
edges: [{
data: {
source: 'a',
target: 'b'
}
}]
},
layout: {
name: 'grid'
}
});
var a = cy.getElementById('a');
var b = cy.getElementById('b');
var makeTippy = function(node, text) {
return tippy(node.popperRef(), {
html: (function() {
var div = document.createElement('div');
div.innerHTML = text;
return div;
})(),
trigger: 'manual',
arrow: true,
placement: 'bottom',
hideOnClick: false,
multiple: true,
sticky: true
}).tooltips[0];
};
var tippyA = makeTippy(a, 'foo');
tippyA.show();
var tippyB = makeTippy(b, 'bar');
tippyB.show();
});
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px
}
#cy {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 1;
}
h1 {
opacity: 0.5;
font-size: 1em;
font-weight: bold;
}
/* makes sticky faster; disable if you want animated tippies */
.tippy-popper {
transition: none !important;
}
<!DOCTYPE>
<html>
<head>
<title>Tippy > qTip</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/popper.js"></script>
<script src="cytoscape-popper.js"></script>
<script src="https://unpkg.com/tippy.js#2.0.9/dist/tippy.all.js"></script>
<link rel="stylesheet" href="https://unpkg.com/tippy.js#2.0.9/dist/tippy.css" />
<script src="https://cdn.jsdelivr.net/npm/cytoscape-popper#1.0.2/cytoscape-popper.js"></script>
</head>
<body>
<h1>cytoscape-popper tippy demo</h1>
<div id="cy"></div>
</body>
</html>
I think popper is just easier to handle when having the divs 'stick around'

dagre with cytoscape wont work

How to use dagre layout in cytoscape.js to draw a simple tree. I am putting layout{ name: ‘dagre’} and added dagre.js but not works.With arbor.js it works but I would like to use dagre to see the tree results. I'm newbie with javascript. Many thanks and sorry for my Englihs! My code:
<!DOCTYPE html>
<!--
-->
<meta name="robots" content="noindex">
<html>
<head>
<meta name="description" content="[An example of getting started with Cytoscape.js]" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Cytoscape.js initialisation</title>
<script src="http://cytoscape.github.io/cytoscape.js/api/cytoscape.js-latest/cytoscape.min.js"></script>
<script src="http://cytoscape.github.io/cytoscape.js/api/cytoscape.js-latest/arbor.js"></script>
<script src="http://cytoscape.github.io/cytoscape.js/api/cytoscape.js-latest/springy.js"></script>
<script src="C:/Users/USER/Downloads/dagre.js"></script>
<style id="jsbin-css">
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="cy"></div>
<script id="jsbin-javascript">
var options = {
name: 'dagre',
// dagre algo options, uses default value on undefined
nodeSep: undefined, // the separation between adjacent nodes in the same rank
edgeSep: undefined, // the separation between adjacent edges in the same rank
rankSep: undefined, // the separation between adjacent nodes in the same rank
rankDir: undefined, // 'TB' for top to bottom flow, 'LR' for left to right
minLen: function( edge ){ return 1; }, // number of ranks to keep between the source and target of the edge
edgeWeight: function( edge ){ return 1; }, // higher weight edges are generally made shorter and straighter than lower weight edges
// general layout options
fit: true, // whether to fit to viewport
padding: 30, // fit padding
animate: false, // whether to transition the node positions
animationDuration: 500, // duration of animation in ms if enabled
boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
ready: function(){}, // on layoutready
stop: function(){} // on layoutstop
};
$('#cy').cytoscape({
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'text-valign': 'center',
'color': 'white',
'text-outline-width': 2,
'text-outline-color': '#888'
})
.selector('edge')
.css({
'target-arrow-shape': 'triangle'
})
.selector(':selected')
.css({
'background-color': 'black',
'line-color': 'black',
'target-arrow-color': 'black',
'source-arrow-color': 'black'
})
.selector('.faded')
.css({
'opacity': 0.25,
'text-opacity': 0
}),
elements: {
nodes: [
{ data: { id:'job.000.174.479.001.sh', name: '479' } },
{ data: { id:'job.000.174.822.001.sh', name: '822' } },
..............
] ,
edges: [
{ data: { source: 'DUM_DWH_000_VANTIVE', target: 'job.000.174.773.001.sh' } },
{ data: { source: 'job.000.174.800.001.sh', target: 'job.000.174.806.001.sh' } },
............
]
},
ready: function(){
window.cy = this;
// giddy up...
cy.elements().unselectify();
cy.layout( options );
cy.on('tap', 'node', function(e){
var node = e.cyTarget;
var neighborhood = node.neighborhood().add(node);
cy.elements().addClass('faded');
neighborhood.removeClass('faded');
});
cy.on('tap', function(e){
if( e.cyTarget === cy ){
cy.elements().removeClass('faded');
}
});
}
});
</script>
</body>
</html>
(1) You shouldn't reference your JS file from your local drive. Use a http:// or https:// URL.
(2) You haven't specified 'dagre' to run at init. Set layout: { ... }.