how to automove any node in cytoscape js - cytoscape.js

I use cytoscape js automove extention, I can move two node together:
cy.automove({
nodesMatching: cy.$('#a'),
reposition: 'drag',
dragWith: cy.$('#b')
});
But I must specify the node #a and #b, now I need whenever I move any node, its neighborhood move together, not a special node.
So I try this:
<style>
#cy{
width:600px;
height:800px
}
</style>
<script src="cytoscape.js"></script>
<script src="cytoscape-automove.js"></script>
<div id="cy"></div>
<script>
var cy = cytoscape({
container: document.getElementById('cy'), // container to render in
elements: [ // list of graph elements to start with
{ // node a
data: { id: 'a' }
},
{ // node b
data: { id: 'b' }
},
{ // node c
data: { id: 'c' }
},
{ // node d
data: { id: 'd' }
},
{ // edge ab
data: { id: 'ab', source: 'a', target: 'b' }
},
{ // edge cd
data: { id: 'cd', source: 'c', target: 'd' }
}
],
style: [ // the stylesheet for the graph
{
selector: 'node',
style: {
'background-color': '#566',
'label': 'data(id)'
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#bcc',
'target-arrow-shape': 'triangle'
}
}
],
layout: {
name: 'grid',
rows: 1
},
boxSelectionEnabled:true,
panningEnabled: true,
selectionType:"additive"
});
cy.on("drag",function(evt){
var node=evt.target;
cy.automove({
nodesMatching: node.neighbourhood().nodes(),
reposition: 'drag',
dragWith: node
});
});
</script>
The result is once I move node #a, node #b will not move together.But I move the node #a again, #b is moved but the position is wrong, it is too far.
So does the dragWith must be a special one? What if I want to move any one?

How about this:
var i = 0;
cy.unbind("tapdrag");
cy.unbind("tapend");
cy.bind("tapdrag", "node", function(evt){
if (i = 0) {
i = 1;
var node = evt.target;
var target = cy.edges("[source = '" + node.id() + "']").target();
cy.automove({
nodesMatching: target,
reposition: 'drag',
dragWith: node
});
}
});
cy.bind("tapend", "node", function(evt) {
i = 0;
});

Related

badge position for nodes

I'm trying to add badges to my cytoscape.js nodes. Badges are HTML elements. I'm using bootstrap badges
Here are elements with badges. (the colors of the badges are irrelevant)
When I zoom out, the position of the badges is not set correctly. They go down and right a bit. WHY IS THAT?
Here is my code to set the positions. I but badges to to top left of the node. But I remove width of the HTML element to make it look like inside the node
let z1 = cy.zoom() / 2; // badges look too big with normal size so I downscale them
// e is cytoscape.js element, a node
const p = e.renderedPosition();
const eW = e.renderedWidth() / 2;
const eH = e.renderedHeight() / 2;
// div is an HTML element which is the badge
const w = div.clientWidth;
div.style.transform = `translate(${p.x + eW - w * z1}px, ${p.y - eH}px) scale(${z1})`;
I would personally prefer a solution using cytoscape.js resources/extensions, namely the popper.js extension.
As far as I understand your problem, you add bootstrap elements to cytoscape.js in some way (you didn't specify this, so I have to guess).
Nomrally, a sticky popper div does the trick for this problem:
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
style: [{
selector: "node",
css: {
content: "data(id)",
"text-valign": "center",
"text-halign": "center",
height: "60px",
width: "160px",
shape: "round-rectangle"
}
},
{
selector: "edge",
css: {
"target-arrow-shape": "triangle"
}
}
],
elements: {
nodes: [{
data: {
id: "n0"
}
},
{
data: {
id: "n1"
}
},
{
data: {
id: "n2"
}
},
{
data: {
id: "n3"
}
},
{
data: {
id: "n4"
}
},
{
data: {
id: "n5"
}
},
{
data: {
id: "n6"
}
},
{
data: {
id: "n7"
}
},
{
data: {
id: "n8"
}
},
{
data: {
id: "n9"
}
},
{
data: {
id: "n10"
}
},
{
data: {
id: "n11"
}
},
{
data: {
id: "n12"
}
},
{
data: {
id: "n13"
}
},
{
data: {
id: "n14"
}
},
{
data: {
id: "n15"
}
},
{
data: {
id: "n16"
}
}
],
edges: [{
data: {
source: "n0",
target: "n1"
}
},
{
data: {
source: "n1",
target: "n2"
}
},
{
data: {
source: "n1",
target: "n3"
}
},
{
data: {
source: "n4",
target: "n5"
}
},
{
data: {
source: "n4",
target: "n6"
}
},
{
data: {
source: "n6",
target: "n7"
}
},
{
data: {
source: "n6",
target: "n8"
}
},
{
data: {
source: "n8",
target: "n9"
}
},
{
data: {
source: "n8",
target: "n10"
}
},
{
data: {
source: "n11",
target: "n12"
}
},
{
data: {
source: "n12",
target: "n13"
}
},
{
data: {
source: "n13",
target: "n14"
}
},
{
data: {
source: "n13",
target: "n15"
}
}
]
},
layout: {
name: "dagre",
padding: 5,
rankSep: 100
}
}));
var makeTippy = function(node, text) {
var ref = node.popperRef();
var dummyDomEle = document.createElement("div");
var tip = tippy(dummyDomEle, {
onCreate: function(instance) {
instance.popperInstance.reference = ref;
},
lazy: false, // mandatory
trigger: "manual", // mandatory
// dom element inside the tippy:
content: function() {
var div = document.createElement("div");
div.innerHTML = text;
return div;
},
// your own preferences:
arrow: false,
placement: 'top-end',
hideOnClick: false,
multiple: true,
sticky: true
});
return tip;
};
cy.ready(function() {
cy.zoom(0.75);
cy.center();
cy.ready(function() {
let nodes = cy.nodes();
nodes.each(function(node) {
let tippy = makeTippy(node, node.id());
tippy.show();
});
});
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
}
.tippy-popper {
transition: none !important;
}
<html>
<head>
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/dagre#0.7.4/dist/dagre.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-dagre#2.1.0/cytoscape-dagre.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-popper#1.0.6/cytoscape-popper.min.js"></script>
<script src="https://unpkg.com/tippy.js#5.1.3/dist/tippy-bundle.iife.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/tippy.js#5.1.3/dist/tippy.css" />
</head>
<body>
<div id="cy"></div>
</body>
</html>
This snippet cuts some of the container off, so try this in your application for better results and take a look at the extensions used here
The problem stems from CSS scale. When I scale the element, the center point of the element remains invariant. The below sample shows What I mean
div {
position: absolute;
}
span {
font-size: 64px;
}
.s1 {
transform: scale(1);
background: red;
}
.s2 {
transform: scale(0.5);
background: blue;
}
<div class="s1"><span>00</span></div>
<div class="s2"><span>00</span></div>
So I have to consider the center point of the div. Below code does that
let z1 = this._g.cy.zoom() / 2;
const bb = e.renderedBoundingBox({ includeLabels: false, includeOverlays: false });
const w = div.clientWidth;
const h = div.clientHeight;
const deltaW4Scale = (1 - z1) * w / 2;
const deltaH4Scale = (1 - z1) * h / 2;
div.style.transform = `translate(${bb.x2 - deltaW4Scale - w * z1}px, ${bb.y1 - deltaH4Scale}px) scale(${z1})`;

Cytoscape js - Call a function whenever a node is clicked

I initialized the cytoscape like this:
var cy = cytoscape({
container: document.getElementById('cy'),
elements: [
{ data: { id: 'a' } },
{ data: { id: 'b' } },
{ data: { id: 'c' } },
{
data: {
id: 'ab',
source: 'a',
target: 'b'
}
},
{
data: {
id: 'ac',
source: 'a',
target: 'c'
}
}
]
});
Then I added a function which adds a new node whenever the user double clicks on the viewport.
var nid = 1;
document.getElementById("cy").ondblclick = function(e) {
cy.add({ data: { id: nid }, renderedPosition: { x: e.x, y: e.y } });
nid++;
};
Then I wrote this function which should be called whenever user clicks a node. It works whenever user clicks on a node which I added manually when initializing the cytoscape but the problem is its not working for the nodes which user added by double clicking.
cy.$('node').on('click', function (e) {
console.log('node clicked: ', e.target.id());
});
Any idea what am I doing wrong?
I have a working version of your code here:
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
boxSelectionEnabled: false,
autounselectify: true,
style: [{
selector: "node",
css: {
"label": "data(id)",
"text-valign": "center",
"text-halign": "center",
"background-color": "data(faveColor)"
}
},
{
selector: "edge",
css: {
"curve-style": "bezier",
"control-point-step-size": 40,
"target-arrow-shape": "triangle"
}
}
],
elements: {
nodes: [{
data: {
id: "a",
faveColor: "#2763c4"
}
},
{
data: {
id: "b",
faveColor: "#37a32d"
}
},
{
data: {
id: "c",
faveColor: "#37a32d"
}
}
],
edges: [{
data: {
source: "a",
target: "b"
}
},
{
data: {
source: "a",
target: "c"
}
}
]
},
layout: {
name: "dagre"
}
}));
cy.ready(function() {
cy.dblclick();
});
var nid = 0;
cy.bind('dblclick', function(evt) {
cy.add({
group: 'nodes',
data: {
id: nid,
faveColor: 'red'
},
position: {
x: evt.x,
y: evt.y
}
});
nid++;
});
cy.bind('click', 'node', function(evt) {
console.log('node clicked: ', evt.target.id());
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
float: right;
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.3.0/dist/cytoscape.min.js">
</script>
<!-- cyposcape dagre -->
<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>
<script src="https://unpkg.com/cytoscape-dblclick/dist/index.js"></script>
</head>
<body>
<div id="cy"></div>
</body>
</html>
I used the cy.on()/cy.bind() method, that seems to work with newly added nodes :)

How to get nodes, connected to the edge is being deleted?

What do I have: graph network with edges.
What do I want: I want to know, which nodes were connected to the certain edge I just deleted.
My code:
var nodes = new vis.DataSet([{
id: 1,
label: 'Node 1'
},
{
id: 2,
label: 'Node 2'
},
{
id: 3,
label: 'Node 3'
},
{
id: 4,
label: 'Node 4'
},
{
id: 5,
label: 'Node 5'
}
])
// create an array with edges
var edges = new vis.DataSet([{
from: 1,
to: 3
},
{
from: 1,
to: 2
},
{
from: 2,
to: 4
},
{
from: 2,
to: 5
},
{
from: 3,
to: 3
}
])
// create a network
var container = document.getElementById('mynetwork')
var data = {
nodes: nodes,
edges: edges
};
var options = {
interaction: {
hover: true
},
manipulation: {
enabled: true,
deleteEdge: function(edge, callback) {
callback(edge)
console.log(edge)
}
}
}
var network = new vis.Network(container, data, options)
network.on("click", function(params) {
params.event = "[original event]"
document.getElementById('eventSpan').innerHTML = '<h2>Click event:</h2>' + JSON.stringify(params, null, 4)
console.log('click event, getNodeAt returns: ' + this.getNodeAt(params.pointer.DOM))
})
<style>#mynetwork {
width: 600px;
height: 400px;
border: 1px solid lightgray;
}
</style>
<link href="https://unpkg.com/vis-network#latest/dist/vis-network.min.css" rel="stylesheet" />
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vis-network#latest/dist/vis-network.min.js"></script>
<div id="mynetwork"></div>
<pre id="eventSpan"></pre>
Steps to reproduce:
Click "Edit"
Click on any edge, connected with two different nodes
Click "Delete selected"
Problem: edge object in console.log(edge) contains Nodes array, but it's empty. I expect it might contain array of two Nodes.
It doesn't contain nodes because no nodes were deleted. After you deleted the edge the information is lost so you have to do it before you delete it. There is network.getConnectedNodes(edgeId) method for this.

With cytoscape.js how to automatically expand the height of the container of a graph?

Is it possible to automatically expand the height of the container of a graph, according to the size of the graph?
I want to display lots of graphs of different sizes on a web page, without having to specify the height of each DOM container.
Does it make sense?
Answer:
It is not the best solution to change anything regarding the container of cytoscape.
Alternative for you:
It is far better to work with the padding of the graph in order to display the graph in a dynamic/suitable way. The easiest way to do that, is to add your nodes and run your layout and then, when the layout is loaded, you can call cy.fit(cy.elements(), yourPadding).
In cytoscape, padding is handled exactly the same way as in css, so you just calculate (based on the number of nodes maybe?) the appropriate padding for your graph and fit it to the viewport.
Additionally, you can always wrap things up with a slick ease-in animation to top things off.
Code:
Snippet works when you click on edit the above snippet and run it in the snippet editor, here the function does not work due to the size limitation and I can't be bothered to adjust it without seeing the outcome in the editor.
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
boxSelectionEnabled: false,
autounselectify: true,
style: [
{
selector: "node",
css: {
content: "data(id)",
"text-valign": "bottom",
"text-halign": "center",
height: "60px",
width: "60px",
"border-color": "black",
"border-opacity": "1",
"background-image":
"https://farm8.staticflickr.com/7272/7633179468_3e19e45a0c_b.jpg"
}
},
{
selector: "edge",
css: {
"target-arrow-shape": "triangle"
}
},
{
selector: ":selected",
css: {
"background-color": "black",
"line-color": "black",
"target-arrow-color": "black",
"source-arrow-color": "black"
}
}
],
elements: {
nodes: [
{ data: { id: "n0" } },
{ data: { id: "n1" } },
{ data: { id: "n2" } },
{ data: { id: "n3" } },
{ data: { id: "n4" } },
{ data: { id: "n5" } },
{ data: { id: "n6" } },
{ data: { id: "n7" } },
{ data: { id: "n8" } },
{ data: { id: "n9" } },
{ data: { id: "n10" } },
{ data: { id: "n11" } },
{ data: { id: "n12" } },
{ data: { id: "n13" } },
{ data: { id: "n14" } },
{ data: { id: "n15" } },
{ data: { id: "n16" } }
],
edges: [
{ data: { source: "n0", target: "n1" } },
{ data: { source: "n1", target: "n2" } },
{ data: { source: "n1", target: "n3" } },
{ data: { source: "n2", target: "n7" } },
{ data: { source: "n2", target: "n11" } },
{ data: { source: "n2", target: "n16" } },
{ data: { source: "n3", target: "n4" } },
{ data: { source: "n3", target: "n16" } },
{ data: { source: "n4", target: "n5" } },
{ data: { source: "n4", target: "n6" } },
{ data: { source: "n6", target: "n8" } },
{ data: { source: "n8", target: "n9" } },
{ data: { source: "n8", target: "n10" } },
{ data: { source: "n11", target: "n12" } },
{ data: { source: "n12", target: "n13" } },
{ data: { source: "n13", target: "n14" } },
{ data: { source: "n13", target: "n15" } }
]
},
layout: {
name: "dagre",
padding: 5
}
}));
cy.unbind("click");
cy.bind("click", "node", function(event) { // just for demonstration purposes here
var coll = cy.$(event.target).successors(); // get all outgoing nodes
coll = coll.add(event.target); // add their source
var removed = cy.remove(cy.elements().not(coll)); // remove all other elements
var len = cy.nodes().length;
var pad = (len < 10 ? (len < 5 ? (len < 3 ? (len < 2 ? 150 : 100 ) : 75 ) : 50 ) : 25); // custom padding function here
cy.animate({
fit: {
eles: cy.elements(),
padding: pad
}
}, {
duration: 500,
easing: 'ease-in'
});
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
float: left;
}
<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>
<script src="https://unpkg.com/jquery#3.3.1/dist/jquery.js"></script>
<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>

Drilldown in Map with Vue.js

I'm trying to use the Drilldown in Map (vue-Highchart), but cannot get it working.
like this: https://www.highcharts.com/maps/demo/map-drilldown
Anyone have any examples of this in Vue.js? Please.
Tks.
Here is simple example of drilldown functionality(with vue-highcharts) which provides drilldown and drillup event from Vue-instance:
Vue.use(VueHighcharts, { Highcharts: Highcharts });
// helper script to load external script
let loadScript = function(url, onLoad){
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.onload = onLoad;
scriptTag.onreadystatechange = onLoad;
document.body.appendChild(scriptTag);
};
// simple chart options
var options = {
chart: {},
title: {
text: 'Highcharts-Vue Map Drilldown Example'
},
subtitle: {
text: '',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'plotBox',
position: {
x: 70,
y: 280
}
}
},
series: [{
data: Highcharts.geojson(Highcharts.maps['countries/us/us-all']).map((d, i) => {
d.drilldown = true;
// set value just for example
d.value = i;
return d;
}),
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}]
};
let vm = new Vue({
el: '#app',
data: {
isLoading: false,
options: options
},
created() {
// prepare events for chart from Vue instance
this.options.chart.events = {
drilldown: this.drilldown.bind(this),
drillup: this.drillup.bind(this)
}
},
methods: {
drilldown(e) {
let { chart } = this.$refs.highcharts;
if (!e.seriesOptions) {
mapKey = 'countries/us/' + e.point.properties['hc-key'] + '-all';
if (Highcharts.maps[mapKey]) {
this.prepareDrilldownData(mapKey, e.point);
return;
}
this.isLoading = true;
loadScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', () => {
this.isLoading = false;
this.prepareDrilldownData(mapKey, e.point);
});
}
chart.setTitle(null, { text: e.point.name });
},
drillup(e) {
let { chart } = this.$refs.highcharts;
chart.setTitle(null, { text: '' });
},
prepareDrilldownData(mapKey, point) {
let { chart } = this.$refs.highcharts;
data = Highcharts.geojson(Highcharts.maps[mapKey]).map((d, i) => {
// set value just for example
d.value = i;
return d;
});
chart.addSeriesAsDrilldown(point, {
name: point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-highcharts/dist/vue-highcharts.min.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<div id="app">
<highmaps ref="highcharts" :options="options"></highmaps>
<div v-if="isLoading" style="text-align: center; margin-top: 15px; font-size: 20px;">Loading...</div>
</div>
There is also jsfiddle if you want.