Cytoscape content style function not working when being generated dynamically - javascript

I'm using Cytoscape 2.5.0.
Here's the basic working code:
var elements = [
{ group: "nodes", data: { id: "n0", type: "foo"}, position: { x: 100, y: 100 } },
{ group: "nodes", data: { id: "n1", type: "bar"}, position: { x: 200, y: 200 } },
{ group: "nodes", data: { id: "n2", type: "foo"}, position: { x: 300, y: 300 } },
{ group: "nodes", data: { id: "n3", type: "biz"}, position: { x: 400, y: 400 } },
{ group: "edges", data: { id: "e0", source: "n0", target: "n1" } }
];
var style = cytoscape.stylesheet()
.selector('node[type = "foo"]').css({
'background-color': 'red',
'content': function(ele){
return "Is a foo: " + ele.data().id;
}
})
.selector('node[type = "bar"]').css({
'background-color': 'blue',
'content':function(ele){
return "Is a bar: " + ele.data().id;
}
})
.selector('node[type = "biz"]').css({
'background-color': 'green',
'content': function(ele){
return ele.data().id;
}
})
;
var dom = $('#graph');
var cy = cytoscape({
container: dom,
elements: elements,
style: style
});
As you can see we have nodes of three different types: foo, bar, and biz.
We've assigned selectors to color them differently, and display a custom label depending on the node type.
This code works fine:
But now I want to abstract the assignment of styling, to avoid that repeatition of code on assigning the selectors and styling.
To do this, I create a Config object.
var Config = function(type, color, message){
this.color = color;
this.fn = function(ele){
var eleMessage = (message)? message + ele.data().id : ele.data().id;
return eleMessage;
};
this.selector = 'node[type = "' + type + '"]';
}
var configs = [
new Config("foo", "red", "this is foo"),
new Config("bar", "blue", "this is bar"),
new Config("biz", "green")
];
for (var i in configs){
var config = configs[i];
style.selector(config.selector)
.css({'background-color': config.color, 'content': config.fn});
}
The code now stops working. The color styling works fine, but the label function is the same for all of them.
I thought this might be an issue with Javascript closures, so I wrapped the function in an IIFE, but that doesn't solve it either.
var Config = function(type, color, message){
this.color = color;
this.fn = (function(message) {return function(ele){
var eleMessage = (message)? message + ele.data().id : ele.data().id;
return eleMessage;
};})(message);
this.selector = 'node[type = "' + type + '"]';
}
Any suggestions for solving this?

Related

How do you apply Smart Routing on links with ports on JointJS?

I am trying to apply smart routing of links with the use of ports using JointJS. This documentation shows the one I am trying to achieve. The example on the docs though shows only the programmatic way of adding Link from point A to point B. How do you do this with the use of ports?
Here's my code: JSFiddle.
HTML:
<html>
<body>
<button id="btnAdd">Add Table</button>
<div id="dbLookupCanvas"></div>
</body>
</html>
JS
$(document).ready(function() {
$('#btnAdd').on('click', function() {
AddTable();
});
InitializeCanvas();
// Adding of two sample tables on first load
AddTable(50, 50);
AddTable(250, 50);
});
var graph;
var paper
var selectedElement;
var namespace;
function InitializeCanvas() {
let canvasContainer = $('#dbLookupCanvas').parent();
namespace = joint.shapes;
graph = new joint.dia.Graph({}, {
cellNamespace: namespace
});
paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
}
});
//Dragging navigation on canvas
var dragStartPosition;
paper.on('blank:pointerdown',
function(event, x, y) {
dragStartPosition = {
x: x,
y: y
};
}
);
paper.on('cell:pointerup blank:pointerup', function(cellView, x, y) {
dragStartPosition = null;
});
$("#dbLookupCanvas")
.mousemove(function(event) {
if (dragStartPosition)
paper.translate(
event.offsetX - dragStartPosition.x,
event.offsetY - dragStartPosition.y);
});
// Remove links not connected to anything
paper.model.on('batch:stop', function() {
var links = paper.model.getLinks();
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
if (source.id === undefined || target.id === undefined) {
link.remove();
}
});
});
paper.on('cell:pointerdown', function(elementView) {
resetAll(this);
let isElement = elementView.model.isElement();
if (isElement) {
var currentElement = elementView.model;
currentElement.attr('body/stroke', 'orange');
selectedElement = elementView.model;
} else
selectedElement = null;
});
paper.on('blank:pointerdown', function(elementView) {
resetAll(this);
});
$('#dbLookupCanvas')
.attr('tabindex', 0)
.on('mouseover', function() {
this.focus();
})
.on('keydown', function(e) {
if (e.keyCode == 46)
if (selectedElement) selectedElement.remove();
});
}
function AddTable(xCoord = undefined, yCoord = undefined) {
// This is a sample database data here
let data = [
{columnName: "radomData1"},
{columnName: "radomData2"}
];
if (xCoord == undefined && yCoord == undefined)
{
xCoord = 50;
yCoord = 50;
}
const rect = new joint.shapes.standard.Rectangle({
position: {
x: xCoord,
y: yCoord
},
size: {
width: 150,
height: 200
},
ports: {
groups: {
'a': {},
'b': {}
}
}
});
$.each(data, (i, v) => {
const port = {
group: 'a',
args: {}, // Extra arguments for the port layout function, see `layout.Port` section
label: {
position: {
name: 'right',
args: {
y: 6
} // Extra arguments for the label layout function, see `layout.PortLabel` section
},
markup: [{
tagName: 'text',
selector: 'label'
}]
},
attrs: {
body: {
magnet: true,
width: 16,
height: 16,
x: -8,
y: -4,
stroke: 'red',
fill: 'gray'
},
label: {
text: v.columnName,
fill: 'black'
}
},
markup: [{
tagName: 'rect',
selector: 'body'
}]
};
rect.addPort(port);
});
rect.resize(150, data.length * 40);
graph.addCell(rect);
}
function resetAll(paper) {
paper.drawBackground({
color: 'white'
});
var elements = paper.model.getElements();
for (var i = 0, ii = elements.length; i < ii; i++) {
var currentElement = elements[i];
currentElement.attr('body/stroke', 'black');
}
var links = paper.model.getLinks();
for (var j = 0, jj = links.length; j < jj; j++) {
var currentLink = links[j];
currentLink.attr('line/stroke', 'black');
currentLink.label(0, {
attrs: {
body: {
stroke: 'black'
}
}
});
}
}
Any help would be appreciated. Thanks!
The default link created when you draw a link from a port is joint.dia.Link.
To change this you can use the defaultLink paper option, and configure the router you would like.
defaultLink documentation reference
const paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
},
defaultLink: () => new joint.shapes.standard.Link({
router: { name: 'manhattan' },
connector: { name: 'rounded' },
})
});
You could also provide several default options in the paper.
defaultLink: () => new joint.shapes.standard.Link(),
defaultRouter: { name: 'manhattan' },
defaultConnector: { name: 'rounded' }

How to set different background depending on hotspot hover

How would like to modify this codepen https://codepen.io/varcharles/pen/qNQpRv
When hovering a red dot the box on right should change is background related on which hotspot is selected. So, four different images related to 4 different hotspots.
const dataField = document.querySelector('.data');
const points = [
{
x: '30px',
y: '50px',
data: 'Targeting Lasers',
},
{
x: '460px',
y: '210px',
data: 'Targeting Lasers'
},
{
x: '250px',
y: '350px',
data: 'Sheild Generators'
},
{
x: '3890px',
y: '550px',
data: 'Sensor Array'
}
];
points.forEach((point) => {
let img = document.createElement('img');
img.style.left = point.x;
img.style.top = point.y;
img.title = point.data;
img.className= 'overlay-image';
img.src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/544303/Target_Logo.svg"
overlay.appendChild(img);
img.data = point.data;
img.addEventListener('mouseenter', handleMouseEnter);
img.addEventListener('mouseleave', handleMouseLeave);
});
function handleMouseEnter(event) {
dataField.innerHTML = event.currentTarget.data;
}
function handleMouseLeave(event) {
dataField.innerHTML = ' ';
}
Can someone please help me? Thank you a lot for your attention
You can just add more data and assign each data object to the images. The following will change the background image when hovering the hotspot.
const overlay = document.querySelector('.image-overlay');
const dataField = document.querySelector('.data');
const points = [
{
x: '320px',
y: '50px',
data: {
title: 'Extended Cockpit',
image: "url('https://dummyimage.com/320x320/ff0000/fff')",
}
},
{
x: '460px',
y: '210px',
data: {
title: 'Targeting Lasers',
image: "url('https://dummyimage.com/320x320/00ff00/fff')",
}
},
{
x: '250px',
y: '350px',
data: {
title: 'Sheild Generators',
image: "url('https://dummyimage.com/320x320/0000ff/fff')",
}
},
{
x: '3890px',
y: '550px',
data: {
title: 'Sensor Array',
image: "url('https://dummyimage.com/320x320/000000/fff')",
}
}
];
points.forEach((point) => {
let img = document.createElement('img');
img.style.left = point.x;
img.style.top = point.y;
img.title = point.data.title;
img.className= 'overlay-image';
img.src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/544303/Target_Logo.svg"
overlay.appendChild(img);
// Sets title and image data attributes
img.data = point.data;
img.addEventListener('mouseenter', handleMouseEnter);
img.addEventListener('mouseleave', handleMouseLeave);
});
function handleMouseEnter(event) {
// Set title and background image based on data set in target
dataField.innerHTML = event.currentTarget.data.title;
dataField.style.backgroundImage = event.currentTarget.data.image;
}
function handleMouseLeave(event) {
// Reset
dataField.innerHTML = ' ';
dataField.style.backgroundImage = 'none';
}

Changing xaxis label from echarts library

var data = [];
var dataCount = 10;
var startTime = +new Date();
var categories = ['categoryA', 'categoryB', 'categoryC'];
var types = [
{name: 'JS Heap', color: '#7b9ce1'},
{name: 'Documents', color: '#bd6d6c'},
{name: 'Nodes', color: '#75d874'},
{name: 'Listeners', color: '#e0bc78'},
{name: 'GPU Memory', color: '#dc77dc'},
{name: 'GPU', color: '#72b362'}
];
// Generate mock data
echarts.util.each(categories, function (category, index) {
var baseTime = startTime;
for (var i = 0; i < dataCount; i++) {
var typeItem = types[Math.round(Math.random() * (types.length - 1))];
var duration = Math.round(Math.random() * 10000);
data.push({
name: typeItem.name,
value: [
index,
baseTime,
baseTime += duration,
duration
],
itemStyle: {
normal: {
color: typeItem.color
}
}
});
baseTime += Math.round(Math.random() * 2000);
}
});
function renderItem(params, api) {
var categoryIndex = api.value(0);
var start = api.coord([api.value(1), categoryIndex]);
var end = api.coord([api.value(2), categoryIndex]);
var height = api.size([0, 1])[1] * 0.6;
var rectShape = echarts.graphic.clipRectByRect({
x: start[0],
y: start[1] - height / 2,
width: end[0] - start[0],
height: height
}, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
});
return rectShape && {
type: 'rect',
shape: rectShape,
style: api.style()
};
}
option = {
tooltip: {
formatter: function (params) {
return params.marker + params.name + ': ' + params.value[3] + ' ms';
}
},
title: {
text: 'Profile',
left: 'center'
},
dataZoom: [{
type: 'slider',
filterMode: 'weakFilter',
showDataShadow: false,
top: 400,
height: 10,
borderColor: 'transparent',
backgroundColor: '#e2e2e2',
handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
handleSize: 20,
handleStyle: {
shadowBlur: 6,
shadowOffsetX: 1,
shadowOffsetY: 2,
shadowColor: '#aaa'
},
labelFormatter: ''
}, {
type: 'inside',
filterMode: 'weakFilter'
}],
grid: {
height:300
},
xAxis: {
min: startTime,
scale: true,
axisLabel: {
formatter: function (val) {
return Math.max(0, val - startTime) + ' ms';
}
}
},
yAxis: {
data: categories
},
series: [{
type: 'custom',
renderItem: renderItem,
itemStyle: {
normal: {
opacity: 0.8
}
},
encode: {
x: [1, 2],
y: 0
},
data: data
}]
};
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
First, create an array of dates like
var dates = ['2019-11-5','2019-10-3','2019-2-2','2019-1-4','2019-12-5'];
then in xAxis -> axisLabel return date
axisLabel: {
formatter: function (val,index) {
return dates[index];
}
}

"Play with this data!" not showing up for my plotly.js plot

I was under the assumption the "Play with this data!" link was supposed the show up by default. Any ideas on why it may not appear? I am just working with a basic scatter plot.
Note that this code below is not standalone as is, it is just the excerpt that does the plotly work.
var xData = [];
var yData = [];
var h = results;
for(var k in h) {
var localdate = k;
var plotdate = moment(localdate).format('YYYY-MM-DD HH:mm:ss');
xData.push(plotdate);
if (currentPort === "t") {
yData.push(CtoF(h[k]));
} else {
yData.push(h[k]);
};
}
var plotdata = [
{
x: xData,
y: yData,
type: 'scatter',
mode: 'markers+lines',
line: {
'color': HELIUM_BLUE
},
marker: {
'symbol': 'circle',
'color': HELIUM_PINK,
'maxdisplayed': 50
}
}
];
var layout = {
title: currentData,
xaxis: {
'title': 'Date / Time'
},
yaxis: {
'title': title
}
};
Plotly.newPlot(plotHolder, plotdata, layout);
You would need to add {showLink: true} as the fourth argument (after layout). I guess the default value changed from true to false.
If you want to change the caption of the button, use {showLink: true, "linkText": "Play with this data"}
var xData = [1, 2, 3, 4, 5];
var yData = [10, 1, 25, 12, 9];
var plotdata = [
{
x: xData,
y: yData,
type: 'scatter',
mode: 'markers+lines',
}
];
var layout = {
title: 'Edit me',
xaxis: {
'title': 'x'
},
yaxis: {
'title': 'y'
}
};
Plotly.newPlot(plotHolder, plotdata, layout, {showLink: true, "linkText": "Play with this data"});
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='plotHolder'>
</div>

javascript infovis toolkit: individal level distance for each level

how do i set individual levelDistance for each level in spacetree
when i set node.data.$width and label.style.width tree drawn with no equal edge
How to set levelDistance for each node level in the spacetree. For instance, I want to change the 'levelDistance' for node level 3. Thank you
function init(){
//init data
json = {
id: "node0",
name: "zvet",
data: {},
children: [{
id: "node0rrrrrr1",
name: "1.3",
data: {$orn:'left'},
children: [{
id: "fvwerr1",
name: "w33",
data: {$orn:'left'},
}]
},
{
id: "node02",
name: "qwe",
data: {$orn:'left'}
} ,{
id: "node03",
name: "bnm",
data: {$orn:'left'}
} ,{
id: "node04",
name: "1.3",
data: {$orn:"right",kk:"kk"}
},
{
id: "vwer",
name: "vfsewrg",
data: {$orn:"right",kk:"kk"}
},
{
id: "vweq33e",
name: "vvvserser",
data: {$orn:"right",kk:"kk"},
children: [{
id: "r345345",
name: "w33",
data: {$orn:'right'}
},
{
id: "u786786",
name: "w33",
data: {$orn:'right'}
},
{
id: "p809456",
name: "w33",
data: {$orn:'right'},
children: [{
id: "weqr232344",
name: "w33",
data: {$orn:'right',kk:"kk"},
children: [{
id: "weqoooooppp",
name: "w33",
data: {$orn:'right'}
}]
}]
}
]
}
]
};
//end
//init Spacetree
//Create a new ST instance
st = new $jit.ST({
//id of viz container element
injectInto: 'infovis',
Canvas:{
type: '2D'} ,
background:true,
//set duration for the animation
duration: 800,
//set animation transition type
transition: $jit.Trans.Quart.easeInOut,
//set distance between node and its children
levelDistance: 100,
levelsToShow:5,
multitree: true,
//enable panning
Navigation: {
enable:true,
panning:true
},
//set node and edge styles
//set overridable=true for styling individual
//nodes or edges
Node: {
height: 20,
width: 150,
type: 'rectangle',
color:'transparent',
overridable: true,
autoWidth:false ,
CanvasStyles: {
fillStyle: 'transparent'
}
},
Edge: {
type: 'bezier',
overridable: true
},
onBeforeCompute: function(node){
Log.write("loading " + node.name);
},
onAfterCompute: function(){
Log.write("done");
},
//This method is called on DOM label creation.
//Use this method to add event handlers and styles to
//your node.
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.innerHTML='<div style="position:relative;">'+node.name+'</div>';
label.onclick = function(){
if(normal.checked) {
st.onClick(node.id);
//st.setRoot(node.id, 'animate');
st.selectedNodeId=node.id;
$("#"+node.id+" div").animate({"bottom":"+=10px"},"slow");
//st.addNodeInPath("1234");
} else {
st.setRoot(node.id, 'animate');
}
};
//set label styles
var style = label.style;
style.width = 150 + 'px';
style.height = 17 + 'px';
style.cursor = 'pointer';
style.color = '#fff';
style.backgroundColor = '#6257DD';
style.borderradius='14px';
style.boxshadow='0 0 16px #FFFFFF';
style.fontSize = '0.8em';
style.textAlign= 'center';
style.paddingTop = '3px';
if(node.data.kk=="kk")
{
style.width = 60+ 'px';
}
},
onPlaceLabel: function(label, node) {
} ,
//This method is called right before plotting
//a node. It's useful for changing an individual node
//style properties before plotting it.
//The data properties prefixed with a dollar
//sign will override the global node style properties.
onBeforePlotNode: function(node){
if(node.data.kk=="kk")
{
node.data.$width = 60;
}
//add some color to the nodes in the path between the
//root node and the selected node.
if (node.selected) {
node.data.$color = "#000000";
$("#"+node.id).css("background-color","red");
}
else {
delete node.data.$color;
$("#"+node.id).css("background-color","#6257DD");
//if the node belongs to the last plotted level
if(!node.anySubnode("exist")) {
//count children number
var count = 0;
node.eachSubnode(function(n) { count++; });
//assign a node color based on
//how many children it has
node.data.$color = ['#aaa', '#baa', '#caa', '#daa', '#eaa', '#faa'][count];
}
}
},
//This method is called right before plotting
//an edge. It's useful for changing an individual edge
//style properties before plotting it.
//Edge data proprties prefixed with a dollar sign will
//override the Edge global style properties.
onBeforePlotLine: function(adj){
if (adj.nodeFrom.selected && adj.nodeTo.selected) {
adj.data.$color = "#eed";
adj.data.$lineWidth = 3;
}
else {
delete adj.data.$color;
delete adj.data.$lineWidth;
}
}
});
//load json data
//end
//Add event handlers to switch spacetree orientation.
var top = $jit.id('r-top'),
left = $jit.id('r-left'),
bottom = $jit.id('r-bottom'),
right = $jit.id('r-right'),
normal = $jit.id('s-normal');
function changeHandler() {
if(this.checked) {
top.disabled = bottom.disabled = right.disabled = left.disabled = true;
st.switchPosition(this.value, "animate", {
onComplete: function(){
top.disabled = bottom.disabled = right.disabled = left.disabled = false;
}
});
}
};
st.loadJSON(json);
//compute node positions and layout
st.compute();
//optional: make a translation of the tree
st.geom.translate(new $jit.Complex(-200, 0), "current");
//emulate a click on the root node.
st.onClick(st.root);
st.select(st.root);
top.onchange = left.onchange = bottom.onchange = right.onchange = changeHandler;
//end
}
It is not possible to have different distances for different levels.
What you can do is to change the node.data.$size of the level, so it displays smaller or bigger than the other leaves.
Think the distance as an allocated space for the node to be placed in. If you create a node with a size smaller than the distance, you will get a gap, which can be seeing as a "border" (just visually) at the external part of it.

Categories

Resources