Qtip not working with jquery and ajax in Cytoscape.js - javascript

I am trying to dynamically load a Cytoscape JSON elements file and display qtip text when a node in the network is clicked. This exact same code works when I hard code the network in the code so there is nothing wrong with the cyjs file or the qtip part of the code. Somehow the qtip is not working with ajax and jquery.
Any help would be appreciated! Thank you!
$(function() {
$.get('demo.cyjs', function( data ) {
$('#cy').cytoscape({
layout: {
name: 'concentric',
concentric: function( node ){
return node.degree();
},
levelWidth: function( nodes ){
return 2;
}
},
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'text-valign': 'bottom',
'color': 'white',
'font-size': 10,
'background-color': 'data(faveColor)'
})
.selector('edge')
.css({
'target-arrow-shape': 'none',
'curve-style':'haystack',
'line-color':'data(faveColor)',
'line-style': 'data(style)',
'haystack-radius': 0,
'width':'data(Ratio)'
})
.selector(':selected')
.css({
'background-color': 'grey',
'target-arrow-color': 'grey',
'source-arrow-color': 'grey',
'border-width': 3,
'border-color': '#333'
})
.selector('.faded')
.css({
'opacity': 1,
'text-opacity': 0
}),
elements : JSON.parse(data),
});
})
cy.nodes().forEach(function(n){
var a = n.data('ensembl_id');
var p=n.data('primes_id');
var e=n.data('ncbi_id');
var u=n.data('uniprot_id');
n.qtip({
content: [
{
name: 'ENSEMBL',
url: 'http://www.ensembl.org/Homo_sapiens/Gene/Summary?db=core;g='+ a
},
{
name: 'UniProt',
url: 'http://www.uniprot.org/uniprot/'+ u
},
{
name: 'NCBI',
url: 'https://www.ncbi.nlm.nih.gov/gene/' + e
}
].map(function( link ){
return '<a target="_blank" href="' + link.url + '">' + link.name + '</a>';
}).join('<br />\n'),
position: {
my: 'top center',
at: 'bottom center'
},
style: {
classes: 'qtip-bootstrap',
tip: {
width: 16,
height: 8
}
}
});
});
$('#config-toggle').on('click', function(){
$('body').toggleClass('config-closed');
cy.resize();
});
});
This is my updated code. I have initialised cy element in the body tag
<div id="cy"></div>
$(function() {
let toJson = res => res.json();
let cy = new cytoscape({
layout: {
name: 'concentric',
concentric: function( node ){
return node.degree();
},
levelWidth: function( nodes ){
return 2;
}
},
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'text-valign': 'bottom',
'color': 'white',
'font-size': 10,
'background-color': 'data(faveColor)'
})
.selector('edge')
.css({
'target-arrow-shape': 'none',
'curve-style':'haystack',
'line-color':'data(faveColor)',
'line-style': 'data(style)',
'haystack-radius': 0,
'width':'data(Ratio)'
})
.selector(':selected')
.css({
'background-color': 'grey',
'target-arrow-color': 'grey',
'source-arrow-color': 'grey',
'border-width': 3,
'border-color': '#333'
})
.selector('.faded')
.css({
'opacity': 1,
'text-opacity': 0
}),
elements: fetch('demo.cyjs').then( toJson ),
});
cy.ready( () => {
var a = n.data('ensembl_id');
var p=n.data('primes_id');
var e=n.data('ncbi_id');
var u=n.data('uniprot_id');
n.qtip({
content: [
{
name:'PrimesDB',
url:'http://primesdb.org/molecules/view/'+ p
},
{
name: 'ENSEMBL',
url: 'http://www.ensembl.org/Homo_sapiens/Gene/Summary?db=core;g='+ a
},
{
name: 'UniProt',
url: 'http://www.uniprot.org/uniprot/'+ u
},
{
name: 'NCBI',
url: 'https://www.ncbi.nlm.nih.gov/gene/' + e
}
].map(function( link ){
return '<a target="_blank" href="' + link.url + '">' + link.name + '</a>';
}).join('<br />\n'),
position: {
my: 'top center',
at: 'bottom center'
},
style: {
classes: 'qtip-bootstrap',
tip: {
width: 16,
height: 8
}
}
});
});
$('#config-toggle').on('click', function(){
$('body').toggleClass('config-closed');
cy.resize();
});
});

Structure your init like this:
let toJson = res => res.json();
let cy = new Cytoscape({
elements: fetch('some/cytoscape/elements.json').then( toJson ),
style: fetch('some/cytoscape/style.json').then( toJson ),
// ...
});
cy.ready( () => {
// specify qtips here, after the external data is loaded
} );
// or if you prefer promises, you can use a ready promise
// let readyPromise = new Promise( resolve => cy.ready(resolve) );
You're not waiting for the elements to load from your JSON file, so there are no elements in the graph when you do your forEach(). It's often easier to let Cytoscape handle the loading of the elements and the stylesheet for you. Just specify promises in place of in-line objects/JSON.
I also don't see any cy variable in your code.
Anything in the cy.ready() callback will execute only after the data from init has loaded properly. A side benefit is that you can easily separate your stylesheet into a new JSON file, keeping your code shorter and making it easier to switch between stylesheets.

Related

Node max size in cytoscape.js dagre layout?

A major part of the project I'm building involves allowing users to create and edit DAGs fluidly. I'm using React, cytoscape.js, cytoscape edgehandles, and the dagre layout to accomplish this, and it's working pretty well, except for one annoying problem. When the graph only has a few nodes, the nodes are huge!
This is because I have fit set to true (the default) in the layout options. I need to keep this setting, because as the graphs grow I want them to zoom out to fit unless the user chooses to zoom in. I just don't want the first 1 - 4 nodes to be huge! Is there any way to define a max height/width for the nodes, or control the zoom level, or something, so that the nodes start off at a reasonable size and only start getting smaller when they have to?
Here's my layout:
cy.layout({
name: 'dagre',
ranker: 'longest-path',
padding: 15
}).run();
And here's my style settings:
const cyConfig = {
elements: [],
style: [
{
selector: 'node',
style: {
'label': 'data(name)',
'color': '#2C2029',
'text-valign':'center',
'text-halign': 'center',
'font-size': '25px',
'font-family': 'Nixie One, cursive',
'shape': 'roundrectangle',
'background-color': 'mapData(inDegree, 1, 8, rgba(163, 154, 164), rgba(240, 146, 60))',
'background-opacity': 'mapData(inDegree, 1, 8, .3, 1)',
'border-color': 'transparent',
'width': 'label',
'height': 'label',
'padding': '7px'
}
}, {
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle',
'target-arrow-fill': 'hollow',
'target-arrow-color': '#2C2029',
'width': '1px',
'color': '#2C2029',
}
}
]
};
You can always define your nodes like this:
style: [
{
selector: 'node',
style: {
'shape': 'data(faveShape)',
'content': 'data(DisplayName)',
'height': 'data(faveHeight)',
'width': 'data(faveWidth)',
'background-color': 'data(faveColor)',
'line-color': '#a8eae5',
'font-family': 'Segoe UI',
'font-size': '15px',
}
}
]
If you do so, you can check how many nodes you want to add to your cytoscape window and then define their width and height properties according to the number of nodes you want to add:
jsonNew.push({
data: {
id: yourId,
parent: '',
faveShape: 'yourShape',
faveHeight: ((nodes.length > 7) ? nodes.length * 3 : nodes.length * 6),
faveWidth: ((nodes.length > 7) ? nodes.length * 5 : nodes.length * 10),
faveColor: '#ffffff'
},
position: {
x: '',
y: ''
},
parents: '',
group: 'nodes',
removed: false,
selected: false,
selectable: true,
locked: false,
grabbable: true,
classes: ''
});

Cytoscape.js - draw edges below compound node

I have a set of nodes grouped inside a parent (compound) node. I would like to display the edges from the "outer" nodes (those outside the compound node) to the "inner" nodes (those inside the compound node) below the compound node.
(Approximately like this demo.)
Thus far, I've tried setting the z-index property like this, with z-index-compare set to manual, but it doesn't work:
style: [
{
selector: 'node',
style: {
'z-index-compare': 'manual',
'width': 10,
'height': 10,
'background-color': '#46A',
'z-index': 3
}
},
{
selector: ':parent',
style: {
'z-index-compare': 'manual',
'background-color': '#CDF',
'z-index': 9
}
},
{
selector: 'edge',
style: {
'z-index-compare': 'manual',
'width': 1,
'line-color': '#BCE',
'z-index': 1
}
},
{
selector: '.dense',
style: {
'z-index-compare': 'manual',
'width': 0.5,
'z-index': 1
}
}
]
The documentation for Cytoscape.js says nothing about where to specify the z-index-compare property, so maybe there's an error in my CSS.
One solution I found was to remove the z-index tags and use z-compound-depth on the :parent selector, like this:
style: [
{
selector: 'node',
style: {
'width': 10,
'height': 10,
'background-color': '#46A'
}
},
{
selector: ':parent',
style: {
'z-compound-depth': 'top',
'background-color': '#CDF'
}
},
{
selector: 'edge',
style: {
'width': 1,
'line-color': '#BCE'
}
},
{
selector: '.dense',
style: {
'width': 0.5
}
}
]

How do I use the Jquery Name Badge /text avatar plugin with angular JS

I am trying to generate name badges/ text avater in an angular JS, ionic app.
.controller("myCtrl",function($scope, userService){
userService.getUsers().then(function(users){
$scope.users = users.data;
$(function(){
$('.name').nameBadge({
// boder options
border: {
color: '#ddd',
width: 3
},
// an array of background colors.
colors: ['#a3a948', '#edb92e', '#f85931', '#ce1836', '#009989'],
// text color
text: '#fff',
// avatar size
size: 48,
// avatar margin
margin: 5,
// disable middle name
middlename: true,
// force uppercase
uppercase: false
});
});
});
})
my view looks like this :
<ion-item class="item-avatar " collection-repeat="item in users">
<div class="name">{{item.username}}</div>
</ion-item>
The problem is, It is showing iu which is the initials of item and username, rather than returning extracting the initials of the real username.
The Jquery namebadge Plugin is :
(function ($) {
$.fn.nameBadge = function (options) {
var settings = $.extend({
border: {
color: '#ddd',
width: 3
},
colors: ['#a3a948', '#edb92e', '#f85931', '#ce1836', '#009989'],
text: '#fff',
size: 72,
margin: 5,
middlename: true,
uppercase: false
}, options);
return this.each(function () {
var elementText = $(this).text();
var initialLetters = elementText.match(settings.middlename ? /\b(\w)/g : /^\w|\b\w(?=\S+$)/g);
var initials = initialLetters.join('');
$(this).text(initials);
$(this).css({
'color': settings.text,
'background-color': settings.colors[Math.floor(Math.random() * settings.colors.length)],
'border': settings.border.width + 'px solid ' + settings.border.color,
'display': 'inline-block',
'font-family': 'Arial, \'Helvetica Neue\', Helvetica, sans-serif',
'font-size': settings.size * 0.4,
'border-radius': settings.size + 'px',
'width': settings.size + 'px',
'height': settings.size + 'px',
'line-height': settings.size + 'px',
'margin': settings.margin + 'px',
'text-align': 'center',
'text-transform' : settings.uppercase ? 'uppercase' : ''
});
});
};
}(jQuery));
Any help will be appreciated . Thanks
Try this: Move your plugin code into and angular directive (look here for how to do that https://docs.angularjs.org/guide/directive).
Then use this angular dependency ( https://docs.angularjs.org/api/ng/service/$interpolate ), $interpolate, to get the value of what is inside the divs. Use it on this line of the plugin: var elementText = $(this).text();
Do not forget to inject $interpolate inside your directive.

How can I change the attrs of a custom object in JointJS?

I created a custom element with the JointJS library . The object have two nested Rectangles with two associated Texts.
I want to change his atributtes inside de Model... I only get through JQUERY change his attributes and css, through its ids.
I want to change the attrs in the model and then, update the node to show his new look.
Sorry if I can not explain it well enough, I leave a jsFiddle ->
http://jsfiddle.net/y9ucn/
If you need additional information, please ask.
Thank you.
Here's the class who defines my custom object and on the jsfiddle you can play an example:
MyRect = joint.shapes.basic.Generic.extend({
markup: [
'<g class="rotatable">',
'<g class="scalable">',
'<rect class="firstRect"/><rect class="secondRect"/>',
'</g>',
'<text class="textFirstRect"/><text class="textSecondRect"/>',
'</g>'].join(''),
defaults: joint.util.deepSupplement({
type: 'basic.MyRect',
attrs: {
'.firstRect': {
'stroke': '#0A1317',
'stroke-width': 1,
'fill': '#DBF024',
'width': 100,
'height': 30,
},
'.secondRect': {
'stroke': '#0A1317',
'stroke-width': 1,
'fill': '#DBF024',
'width': 100,
'height': 30,
},
'.textFirstRect': {
'ref': '.firstRect',
'ref-x': .5,
'ref-y': .5,
'y-alignment': 'middle',
'x-alignment': 'middle',
'fill': '#333',
'font-size': 12,
'font-family': 'Calibri,Arial',
},
'.textSecondRect': {
'ref': '.secondRect',
'ref-y': .5,
'ref-x': .5,
'y-alignment': 'middle',
'x-alignment': 'middle',
'fill': '#333',
'font-size': 12,
'font-family': 'Calibri,Arial'
}
}
}, joint.shapes.basic.Generic.prototype.defaults),
initialize: function () {
_.bindAll(this, 'format');
this.format();
joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
},
format: function () {
var attrs = this.get('attrs');
attrs['.secondRect'].transform = 'translate(0,30)';
}
});
You can use the attr() method:
cellView.model.attr('.textSecondRect/text', 'foo');
See the API reference: http://jointjs.com/api#joint.dia.Element:attr.

Deleting a view from a ScrollView

Developing in Titanium Mobile.
I need to remove a view from a scrollView when a delete button is clicked. I have a custom event firing when my button is clicked, which the scrollView listens for. My question is, how do I reference the view that needs to be deleted? These views are added to the scrollView dynamically, and there is no unique information about the view. I tried passing the view itself when firing the custom event, but this does not work. How do I tell the scrollView which view to delete?
When you have a delete button inside the view - that's a piece of cake :) Just get its' parent and delete it - scrollView.remove(e.source.parent);
Here I created a demo page:
var scrollView = Titanium.UI.createScrollView({
contentWidth: 'auto',
contentHeight: 'auto',
top: 0,
showVerticalScrollIndicator: true,
showHorizontalScrollIndicator: true,
layout: 'vertical'
});
var colors = ['red', 'green', 'blue', 'orange', 'purple', 'yellow'];
for (var i = 0; i < 6; i++) {
var view = Ti.UI.createView({
backgroundColor: colors[i],
borderRadius: 10,
width: 300,
height: 200,
top: 10,
id: i
});
scrollView.add(view);
var deleteButton = Ti.UI.createButton({
borderRadius: 3,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
backgroundGradient: {
type: 'linear',
colors: [ '#c7c7c7', '#686868' ],
startPoint: { x: 0, y: 0 },
endPoint: { x: 0, y: 30 },
backFillStart: false
},
title: 'Delete view ' + i,
font: { fontSize: 12, fontWeight: 'bold' },
color: '#fff',
width: 120,
height: 30
});
view.add(deleteButton);
deleteButton.addEventListener('click', function(e) {
Ti.API.info(e.source.id); // use this ID
scrollView.remove(e.source.parent);
});
}
Ti.UI.currentWindow.add(scrollView);

Categories