Flowchart with jsPlumb - javascript

I'm trying to create a flowchart with jsPlumb. I have two elements and I want to connect them with a line. I want a line, but not a huge dot as I currently have. I've tried setting the radius of the dot everywhere I can, but it seems unaffected and remains at the default 20px. What am I doing wrong?
<div id="start">Start</div>
<div id="msgtype">Lorem ipsum dolor sit amet</div>
jsPlumb.importDefaults({
Endpoints : [ [ 'Dot', {radius:1} ], [ 'Dot', { radius:1 } ]]
});
var connectorPaintStyle = {
lineWidth:4,
fillStyle:'#333333',
joinstyle:'round',
outlineWidth:0,
radius: 1,
}
var eleStart = jsPlumb.addEndpoint('start', {
isSource:true,
isTarget:false
});
var eleMsgtypeTop = jsPlumb.addEndpoint('msgtype', {
isTarget:true,
parameters:{
endpoint:'dot',
radius: 1
},
anchor: 'TopCenter',
radius: 1,
connectorStyle:connectorPaintStyle
});
jsPlumb.connect({ source:eleStart,
target:eleMsgtypeTop,
connectorStyle:connectorPaintStyle,
endpoint:[ 'Dot', { radius:1, hoverClass:'myEndpointHover' }],
connectorStyle:connectorPaintStyle
});
Producing this:
JSFiddle Demo

Try this: http://jsfiddle.net/GT884/1/
;(function () {
window.jsPlumbDemo = {
init: function () {
jsPlumb.importDefaults({
DragOptions: {
cursor: "pointer",
zIndex: 2000
},
HoverClass: "connector-hover"
});
var connectorStrokeColor = "rgba(50, 50, 200, 1)",
connectorHighlightStrokeColor = "rgba(180, 180, 200, 1)",
hoverPaintStyle = {
strokeStyle: "#7ec3d9"
};
var connection1 = jsPlumb.connect({
source: "start",
target: "msgtype",
connector: "Bezier",
cssClass: "c1",
endpoint: "Blank",
endpointClass: "c1Endpoint",
anchors: ["BottomCenter", [0.75, 0, 0, -1]],
paintStyle: {
lineWidth: 6,
strokeStyle: "#a7b04b",
outlineWidth: 1,
outlineColor: "#666"
},
endpointStyle: {
fillStyle: "#a7b04b"
},
hoverPaintStyle: hoverPaintStyle
});
// make all .window divs draggable
jsPlumb.draggable(jsPlumb.getSelector(".window"));
}
};
})();
jsPlumb.bind("ready", function () {
jsPlumb.init();
// chrome fix.
document.onselectstart = function () {
return false;
};
// render mode
var resetRenderMode = function (desiredMode) {
var newMode = jsPlumb.setRenderMode(desiredMode);
$(".rmode").removeClass("selected");
$(".rmode[mode='" + newMode + "']").addClass("selected");
$(".rmode[mode='canvas']").attr("disabled", !jsPlumb.isCanvasAvailable());
$(".rmode[mode='svg']").attr("disabled", !jsPlumb.isSVGAvailable());
$(".rmode[mode='vml']").attr("disabled", !jsPlumb.isVMLAvailable());
//var disableList = (newMode === jsPlumb.VML) ? ",.rmode[mode='svg']" : ".rmode[mode='vml']";
// $(disableList).attr("disabled", true);
jsPlumbDemo.init();
};
$(".rmode").bind("click", function () {
var desiredMode = $(this).attr("mode");
if (jsPlumbDemo.reset) jsPlumbDemo.reset();
jsPlumb.reset();
resetRenderMode(desiredMode);
});
// explanation div is draggable
$("#explanation,.renderMode").draggable();
resetRenderMode(jsPlumb.SVG);
});

The full, final solution was:
;(function () {
window.plumbify = {
init: function () {
jsPlumb.importDefaults({
DragOptions: {
cursor: 'pointer',
zIndex: 2000
},
HoverClass: 'connector-hover'
});
var connectorStrokeColor = 'rgba(50, 50, 200, 1)',
connectorHighlightStrokeColor = 'rgba(180, 180, 200, 1)',
paintStyle = {
lineWidth: 3,
strokeStyle: '#a7b04b',
outlineWidth: 1,
outlineColor: '#666'
},
hoverPaintStyle = {
strokeStyle: '#7ec3d9'
};
var connection1 = jsPlumb.connect({
source: 'start',
target: 'msgtype',
connector: 'Bezier',
cssClass: 'c1',
endpoint: 'Blank',
anchors: [[0.25, 1, 0, 0.5], [0.75, 0, 0, -0.5]],
paintStyle: paintStyle,
endpointStyle: {
fillStyle: '#a7b04b'
},
overlays:[
[ 'Arrow', { width:20, length:30, location:0.5, paintStyle: paintStyle } ],
],
hoverPaintStyle: hoverPaintStyle
});
// make all .window divs draggable
jsPlumb.draggable(jsPlumb.getSelector('.window'));
}
};
})();
jsPlumb.bind('ready', function () {
jsPlumb.init();
// chrome fix.
document.onselectstart = function () {
return false;
};
// render mode
var resetRenderMode = function (desiredMode) {
var newMode = jsPlumb.setRenderMode(desiredMode);
plumbify.init();
};
resetRenderMode(jsPlumb.SVG);
});
Resulting in:

jsPlumb.addEndpoint(element.id,{
...
paintStyle:{radius:1};
});

Related

JsPlumb, How to save connector labels?

Could someone help me out with what I am missing?
The scenario is: there are several nodes. Among them, one node can connect with 3 other nodes and those connections should be labeled.
The codes are connecting multiple nodes with labels, but on save it doesn't save the labels. On page load, it shows the connections but not the labels.
Here are my codes.
let connector = [
"EditableBezier",
{
cornerRadius: 0,
curviness: 30,
},
];
let paintStyle = {
strokeWidth: 2,
stroke: "rgb(217,217,217)",
outlineWidth: 3,
outlineStroke: "transparent",
};
let paintStyle = {
strokeWidth: 2,
stroke: "rgb(217,217,217)",
outlineWidth: 3,
outlineStroke: "transparent",
};
let hoverStyle = {
strokeWidth: 2,
stroke: "rgb(67,67,67)",
};
let abLabelCounter = 1;
function abSplitConnections(params) {
var source = params.connection.source;
var target = params.connection.target;
if (source.id === target.id) return false;
var conn = jsPlumb.getInstance();
let c = conn.connect({
source: source,
target: target,
editable: true,
anchor: "AutoDefault",
endpoint: "Blank",
connector: connector,
paintStyle: paintStyle,
hoverPaintStyle: hoverStyle,
overlays: [
[
"Arrow",
{
location: 1,
width: 10,
length: 10,
},
],
[
"Label",
{
location: 0.5,
label: () => {
if (abLabelCounter === 1) {
abLabelCounter++;
return "A";
}
if (abLabelCounter === 2) {
abLabelCounter++;
return "B";
}
if (abLabelCounter === 3) {
abLabelCounter = 1;
return "C";
}
},
id: "partition",
},
],
],
});
}

Highcharts: Value will not be updated

i have the next problem with Highcharts. This is a new Highchart for an other site.
See here: https://imgur.com/a/VQQLU
The arrow show to -3 Megawatts but the value at the bottom shows another value. At the first pageload the values are identical, but there comes all 5 seconds new values. And they are not updated at the bottom.
Edit: The tolltip will be updated correctly.
My code:
$(function () {
$.getJSON('jsonlive.php', function(chartData) {
var ADatum; var Eheit; var AktL; var MinL; var MaxL; var chartValue; var i;
ADatum = chartData[0].AktDatum;
Eheit = chartData[0].Einheit;
AktL = chartData[0].AktuelleLeistung;
MinL = chartData[0].MinLeistung;
MaxL = chartData[0].MaxLeistung;
var tMin = (MinL*-1); var tMax = MaxL;
var ttt = new Array();
if (tMin < tMax) { chartValue = tMax; } else if (tMin > tMax) { chartValue = tMin; } // Ermitteln ob neg/pos Zahl die größere ist.
ttt[0] = (chartValue*-1); // Skala mit Zahlen beschriften
for (i = 1; i < chartValue; i++) { ttt[i] = (i*-1); }
var tz = ttt.length ;
for (i = 0; i < chartValue; i++) { ttt[(tz+i)] = i; }
ttt[ttt.length] = chartValue;
var gaugeOptions = {
chart:{ events: {
load: function () { setInterval(function () {
$.getJSON('jsonlive.php', function(chartData) {
ADatum = chartData[0].AktDatum;
AktL = chartData[0].AktuelleLeistung;
var point = $('#inhalt').highcharts().series[0].setData([AktL], true);
});}, 5000);}
}, type: 'gauge' },
title: null,
pane: {
center: ['50%', '85%'], size: '140%', startAngle: -90, endAngle: 90,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [[0, '#00fb00'],[1, '#003f00']]},
borderWidth: 2,
outerRadius: '109%',
innerRadius: '102%', shape: 'arc' }]
},
series: [{
data: [AktL],
dataLabels: { borderWidth: 0,align: 'center',x: 0,y: 110,
format: '<div style="text-align:center;font-size:24px;color:black">'+AktL+' ' +Eheit+'</span></div>'
}
}],
tooltip: {
formatter: function () { return 'Datum: <b>' + (new Date(ADatum).toLocaleString("de-DE", { timeZone: 'UTC' })) +
'</b> <br>Leistung <b>' + AktL + ' ' + Eheit + '</b>';}, enabled: true },
yAxis: {lineWidth: 10, minorTickInterval: null, tickPixelInterval: 100, tickWidth: 5, title: { y: -250 }, labels: { y: 2 }}
};
// Anzeige
$('#inhalt').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: (chartValue*-1),max: chartValue,tickPositions: ttt,tickColor: '#666',minorTickColor: '#666',
plotBands: [{ // optionaler Bereich, zeigt von 0-1 grün, 1 bis hälfte maximum gelb, und hälfte max bis max rot
from: 0, to: -1, color: '#55BF3B' }, { // green
from: -1, to: ((chartValue*-1)/2), color: '#DDDF0D' }, { // yellow
from: ((chartValue*-1)/2),to: (chartValue*-1),color: '#DF5353' }, { // red
from: 0,to: 1,color: '#55BF3B' }, { // green
from: 1,to: (chartValue/2),color: '#DDDF0D' }, { // yellow
from: (chartValue/2),to: chartValue,color: '#DF5353' }],// red
title: { style: { color: 'black', fontWeight: 'bold', fontSize: '24px' }, text: 'Leistung in '+Eheit },
labels: { formatter: function () { return this.value; }}},
credits: { enabled: false } // Link auf highcharts rechts unten an/aus
}));
});
});
</script>
The problem here is that you use a hard-coded value (AktL) in your dataLabels.format. In your example format is just a string that's used all the time.
Use {point.y} to have the label updated on every setData():
series: [{
data: [val],
dataLabels: {
// format: val // WONT WORK
format: '{point.y}'
}
}],
Live demo: http://jsfiddle.net/BlackLabel/v28q5n09/

JQuery Flot - Grid lines not showing through filled lines

I'm trying to create one real-time flot and my problem is that I can't get to see the flot grid through the filling of my data's lines..
If you have any idea to get my filling a bit transparent like the picture below, I'd like to apply it as well on my Fiddle!
What I'm trying to achieve is something like that:
Picture of what I try to get
Here is the Fiddle on what I'm working:
My flot on Fiddle
Code:
$(function () {
getRandomData = function(){
var rV = [];
for (var i = 0; i < 10; i++){
rV.push([i,Math.random() * 10]);
}
return rV;
}
getRandomDataa = function(){
var rV = [];
for (var i = 0; i < 10; i++){
rV.push([i,Math.random() * 10 + 5]);
}
return rV;
}
getSeriesObj = function() {
return [
{
data: getRandomDataa(),
lines: {
show: true,
fill: true,
lineWidth: 5,
fillColor: { colors: [ "#b38618", "#b38618" ] },
tickColor: "#FFFFFF",
tickLength: 5
}
}, {
data: getRandomData(),
lines: {
show: true,
lineWidth: 0,
fill: true,
fillColor: { colors: [ "#1A508B", "#1A508B" ] },
tickColor: "#FFFFFF",
tickLength: 5
}
}];
}
update = function(){
plot.setData(getSeriesObj());
plot.draw();
setTimeout(update, 1000);
}
var flotOptions = {
series: {
shadowSize: 0, // Drawing is faster without shadows
tickColor: "#FFFFFF"
},
yaxis: {
min: 0,
autoscaleMargin: 0,
position: "right",
transform: function (v) { return -v; }, /* Invert data on Y axis */
inverseTransform: function (v) { return -v; },
font: { color: "#FFFFFF" },
tickColor: "#FFFFFF"
},
grid: {
backgroundColor: { colors: [ "#EDC240", "#EDC240" ], opacity: 0.5 }, // "Ground" color (May be a color gradient)
show: true,
borderWidth: 1,
borderColor: "#FFFFFF",
verticalLines: true,
horizontalLines: true,
tickColor: "#FFFFFF"
}
};
var plot = $.plot("#placeholder", getSeriesObj(), flotOptions);
setTimeout(update, 1000);
});
Thanks a lot!
You can use the rgba() color specification with flot to specify the fill color and alpha level (transparency):
fillColor: { colors: [ "rgba(179, 134, 24, .2)", "rgba(179, 134, 24, .2)" ] },
An alpha value of 0 is fully transparent, while an alpha value of 1 is fully opaque.

JointJS creating links from magnet not working

I managed to create a diagram with elements, in port, and multiple out ports.
All the elements are connected using links from the in port to an out port.
When I try to play with the links I already have (loaded from JSON), it works properly.
For some reason when I try to create a new link by pressing the ports, it drags the element instead.
How can I make the ports create new links when I press on them?
joint.shapes.Question = joint.shapes.basic.Generic.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
markup: '<g class="rotatable">' +
'<g class=""><g class="inPorts" /><rect class="question-wrapper" /><rect class="question-title" /><rect class="options-body" /><g class="outPorts" /></g>' +
'<text class="question" /><g class="options" />' +
'</g>',
portMarkup: '<g class="port port-<%= port.type %> port-<%= port.id %>"><circle class="port-body" /><text class="port-label" /></g>',
optionMarkup: '<g class="option-wrapper"><text class="option"/></g>',
defaults: joint.util.deepSupplement({
type: 'Question',
minWidth: 200,
optionHeight: 25,
inPorts: [{"id": "in", "label": "IN"}],
attrs: {
'.': {
magnet: false
},
'.question-wrapper': {
width: 200,
height: 95,
fill: '#f2f2f2',
rx: 10,
ry: 10,
ref: '.paper'
},
'.question-title': {
height: 30,
fill: '#ffffff',
rx: 5,
ry: 5,
ref: '.question-wrapper',
'ref-x': 5,
'ref-y': 5,
'ref-width': -10
},
'.question': {
fill: '#000000',
'font-size': 14,
'y-alignment': 'middle',
'x-alignment': 'middle',
ref: '.question-title',
'ref-x': .5,
'ref-y': .5,
},
'.options-body': {
height: 50,
fill: '#ffffff',
rx: 5,
ry: 5,
ref: '.question-wrapper',
'ref-x': 5,
'ref-y': 40,
'ref-width': -10
},
'.options': {
ref: '.options-body',
'ref-x': 5,
'ref-y': 5
},
'.option-wrapper': {
ref: '.options'
},
'.option': {
fill: '#000000',
'font-size': 14
},
'.port-in': {
ref: '.question-wrapper',
'ref-y': 0,
'ref-x': .5,
magnet: true,
type: 'in'
},
'.port-in .port-body': {
r: 15,
fill: '#75caeb',
ref: '.port-in'
},
'.port-in .port-label': {
'font-size': 10,
fill: '#ffffff',
'x-alignment': 'middle',
'y-alignment': -10,
ref: '.port-in .port-body'
},
'.port-out': {
ref: '.question-wrapper',
magnet: true,
type: 'out'
},
'.port-out .port-body': {
r: 10,
ref: '.question-wrapper',
'ref-dy': 15,
'ref-x': .5,
fill: '#158cba',
'y-alignment': 'middle'
},
'.port-out .port-label': {
'text': 'R',
'font-size': 10,
'y-alignment': 'middle',
'x-alignment': 'middle',
fill: '#ffffff',
ref: '.port-out .port-body',
'ref-x': .5,
'ref-y': 15,
'pointer-events': 'none'
}
}
}, joint.shapes.basic.Generic.prototype.defaults),
initialize: function () {
this.attr('.question/text', this.get('question'), {silent: true});
this.onChangePosition();
this.onChangeOptions();
joint.shapes.basic.PortsModelInterface.initialize.apply(this, arguments);
},
onChangePosition: function () {
var timer;
var timer_interval = 500;
this.on('change:position', function (cellView, position) {
clearTimeout(timer);
timer = setTimeout(function () {
$.ajax({
url: routes.questionPosition.replace(':question', cellView.id),
data: position,
method: 'post',
headers: {'X-CSRF-TOKEN': $('[name="csrf_token"]').attr('content')}
});
}, timer_interval);
});
},
onChangeOptions: function () {
var options = this.get('options');
var size = this.get('size');
var optionHeight = this.get('optionHeight');
// First clean up the previously set attrs for the old options object.
// We mark every new attribute object with the `dynamic` flag set to `true`.
// This is how we recognize previously set attributes.
var attrs = this.get('attrs');
_.each(attrs, function (attrs, selector) {
if (attrs.dynamic) {
// Remove silently because we're going to update `attrs`
// later in this method anyway.
this.removeAttr(selector, {silent: true});
}
}, this);
// Collect new attrs for the new options.
var offsetY = 0;
var attrsUpdate = {};
_.each(options, function (option) {
var selector = '.option-' + option.id;
attrsUpdate[selector] = {transform: 'translate(0, ' + offsetY + ')', dynamic: true};
attrsUpdate[selector + ' .option'] = {text: option.text, dynamic: true};
offsetY += optionHeight;
}, this);
this.attr(attrsUpdate);
this.autoresize();
},
autoresize: function () {
var options = this.get('options') || [];
var gap = this.get('paddingBottom') || 15;
var height = options.length * this.get('optionHeight');
var wrapperHeight = height + this.attr('.question-title/height') + gap;
var width = joint.util.measureText(this.get('question'), {
fontSize: this.attr('.question/font-size')
}).width + (this.attr('.question-title/rx') * 6);
this.attr('.options-body/height', height);
this.resize(Math.max(this.get('minWidth'), width), wrapperHeight);
this.attr('.question-wrapper/width', width);
this.attr('.question-wrapper/height', wrapperHeight);
},
getPortAttrs: function (port, index, total, selector, type) {
var attrs = {};
var portSelector = selector + ' .port-' + type;
attrs[portSelector + ' .port-label'] = {text: port.label};
attrs[portSelector + ' .port-body'] = {
port: {
id: port.id,
type: type
}
};
if (selector === '.outPorts') {
attrs[portSelector] = {'ref-x': ((total / 2) * 30 * -1) + (index * 30) + 15};
}
return attrs;
}
}));
joint.shapes.QuestionView = joint.dia.ElementView.extend(_.extend({}, joint.shapes.basic.PortsViewInterface, {
initialize: function () {
joint.shapes.basic.PortsViewInterface.initialize.apply(this, arguments);
},
renderMarkup: function () {
joint.dia.ElementView.prototype.renderMarkup.apply(this, arguments);
// A holder for all the options.
this.$options = this.$('.options');
// Create an SVG element representing one option. This element will
// be cloned in order to create more options.
this.elOption = V(this.model.optionMarkup);
this.renderOptions();
},
renderOptions: function () {
this.$options.empty();
_.each(this.model.get('options'), function (option, index) {
var className = 'option-' + option.id;
var elOption = this.elOption.clone().addClass(className);
elOption.attr('option-id', option.id);
this.$options.append(elOption.node);
}, this);
// Apply `attrs` to the newly created SVG elements.
this.update();
}
}));

jsPlumb: Unable to make windows draggable

I am trying to add a node to a jsPlumb canvas using a button event on my form. This is the code that I have modified from the source of the original file-
var _addEndpoints;
var idCount=5;
function addNode(){
idCount = idCount+1;
console.log($('#selector').find(":selected").text());
console.log("flowchartWindow"+idCount);
var new_item = '<div class="window jtk-node jsplumb-endpoint-anchor jsplumb-draggable jsplumb-connected" '
+'id="flowchartWindow'+idCount+'">'+
'<strong>'+$('#selector').find(":selected").text()+'</strong><br><br>'
+'</div>'
$("#canvas").append(new_item);
_addEndpoints("Window"+idCount);
// instance.draggable(jsPlumb.getSelector(".flowchart-demo .window"), { grid: [20, 20] });
}
jsPlumb.ready(function () {
instance = window.jsp = jsPlumb.getInstance({
// default drag options
DragOptions: { cursor: 'pointer', zIndex: 2000 },
// the overlays to decorate each connection with. note that the label overlay uses a function to generate the label text; in this
// case it returns the 'labelText' member that we set on each connection in the 'init' method below.
ConnectionOverlays: [
[ "Arrow", {
location: 1,
visible:true,
id:"ARROW",
events:{
click:function() { alert("you clicked on the arrow overlay")}
}
} ],
[ "Label", {
location: 0.1,
id: "label",
cssClass: "aLabel",
events:{
tap:function() { alert("You 'tap'ed an a label"); }
}
}]
],
Container: "canvas"
});
var basicType = {
connector: "StateMachine",
paintStyle: { strokeStyle: "red", lineWidth: 4 },
hoverPaintStyle: { strokeStyle: "blue" },
overlays: [
"Arrow"
]
};
instance.registerConnectionType("basic", basicType);
// this is the paint style for the connecting lines..
var connectorPaintStyle = {
lineWidth: 4,
strokeStyle: "#61B7CF",
joinstyle: "round",
outlineColor: "white",
outlineWidth: 2
},
// .. and this is the hover style.
connectorHoverStyle = {
lineWidth: 6,
strokeStyle: "#216477",
outlineWidth: 2,
outlineColor: "white"
},
endpointHoverStyle = {
fillStyle: "yellow",
strokeStyle: "black"
},
// the definition of source endpoints (the small blue ones)
sourceEndpoint = {
endpoint: "Dot",
paintStyle: {
strokeStyle: "#7AB02C",
fillStyle: "transparent",
radius: 7,
lineWidth: 3
},
isSource: true,
connector: [ "Flowchart", { stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true } ],
connectorStyle: connectorPaintStyle,
hoverPaintStyle: endpointHoverStyle,
connectorHoverStyle: connectorHoverStyle,
dragOptions: {},
overlays: [
[ "Label", {
location: [0.5, 1.5],
label: "Drag",
cssClass: "endpointSourceLabel",
visible:false
} ]
]
},
// the definition of target endpoints (will appear when the user drags a connection)
targetEndpoint = {
endpoint: "Dot",
paintStyle: { fillStyle: "#7AB02C", radius: 11 },
hoverPaintStyle: endpointHoverStyle,
maxConnections: -1,
dropOptions: { hoverClass: "hover", activeClass: "active" },
isTarget: true,
overlays: [
[ "Label", { location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel", visible:false } ]
]
},
init = function (connection) {
connection.getOverlay("label").setLabel(connection.sourceId.substring(15) + "-" + connection.targetId.substring(15));
};
var sourceAnchors = ["BottomCenter","LeftMiddle", "RightMiddle"];
var targetAnchors = ["TopCenter"];
_addEndpoints = function (toId) {
for (var i = 0; i < sourceAnchors.length; i++) {
var sourceUUID = toId + sourceAnchors[i];
instance.addEndpoint("flowchart" + toId, sourceEndpoint, {
anchor: sourceAnchors[i], uuid: sourceUUID
});
}
for (var j = 0; j < targetAnchors.length; j++) {
var targetUUID = toId + targetAnchors[j];
instance.addEndpoint("flowchart" + toId, targetEndpoint, {
anchor: targetAnchors[j], uuid: targetUUID });
}
};
// suspend drawing and initialise.
instance.batch(function () {
_addEndpoints("Window4");
_addEndpoints("Window3");
_addEndpoints("Window2");
_addEndpoints("Window1");
// listen for new connections; initialise them the same way we initialise the connections at startup.
instance.bind("connection", function (connInfo, originalEvent) {
init(connInfo.connection);
});
// make all the window divs draggable
instance.draggable(jsPlumb.getSelector(".flowchart-demo .window"), { grid: [20, 20] });
// THIS DEMO ONLY USES getSelector FOR CONVENIENCE. Use your library's appropriate selector
// method, or document.querySelectorAll:
//jsPlumb.draggable(document.querySelectorAll(".window"), { grid: [20, 20] });
// connect a few up
instance.connect({uuids: ["Window2BottomCenter", "Window3TopCenter"], editable: true});
instance.connect({uuids: ["Window2LeftMiddle", "Window4TopCenter"], editable: true});
instance.connect({uuids: ["Window4LeftMiddle", "Window4TopCenter"], editable: true});
instance.connect({uuids: ["Window3RightMiddle", "Window2TopCenter"], editable: true});
instance.connect({uuids: ["Window4BottomCenter", "Window1TopCenter"], editable: true});
instance.connect({uuids: ["Window3BottomCenter", "Window1TopCenter"], editable: true});
//
//
// listen for clicks on connections, and offer to delete connections on click.
//
instance.bind("click", function (conn, originalEvent) {
// if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
// instance.detach(conn);
conn.toggleType("basic");
});
instance.bind("dblclick", function (conn, originalEvent) {
// if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
// instance.detach(conn);
instance.detach(conn);
});
// instance.bind("endpointClick", function (endpoint, originalEvent) {
// // if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
// // instance.detach(conn);
// alert("Shit");
// });
instance.bind("connectionDrag", function (connection) {
console.log("connection " + connection.id + " is being dragged. suspendedElement is ", connection.suspendedElement, " of type ", connection.suspendedElementType);
});
instance.bind("connectionDragStop", function (connection) {
console.log("connection " + connection.id + " was dragged");
});
instance.bind("connectionMoved", function (params) {
console.log("connection " + params.connection.id + " was moved");
});
});
jsPlumb.fire("jsPlumbDemoLoaded", instance);
});
The original demo is here: https://jsplumbtoolkit.com/community/demo/flowchart/index.html
And the related js file which I have edited is this.
The node gets added and the endPoint elements are also added, but it is not draggable.
I got it working by making instance a global variable and calling it's draggable instead of the jsPlumb class.
Here's the modification:
var _addEndpoints;
var instance;
var idCount=5;
function addNode(){
idCount = idCount+1;
console.log($('#selector').find(":selected").text());
console.log("flowchartWindow"+idCount);
var new_item = '<div class="window jtk-node jsplumb-endpoint-anchor jsplumb-draggable jsplumb-connected" '
+'id="flowchartWindow'+idCount+'">'+
'<strong>'+$('#selector').find(":selected").text()+'</strong><br><br>'
+'</div>'
$("#canvas").append(new_item);
_addEndpoints("Window"+idCount);
instance.draggable(document.querySelectorAll(".flowchart-demo .window"), { grid: [20, 20] })
}
jsPlumb.ready(function () {
instance = window.jsp = jsPlumb.getInstance({
// default drag options
DragOptions: { cursor: 'pointer', zIndex: 2000 },
// the overlays to decorate each connection with. note that the label overlay uses a function to generate the label text; in this
// case it returns the 'labelText' member that we set on each connection in the 'init' method below.
ConnectionOverlays: [
[ "Arrow", {
location: 1,
visible:true,
id:"ARROW",
events:{
click:function() { alert("you clicked on the arrow overlay")}
}
} ],
[ "Label", {
location: 0.1,
id: "label",
cssClass: "aLabel",
events:{
tap:function() { alert("You 'tap'ed an a label"); }
}
}]
],
Container: "canvas"
});
var basicType = {
connector: "StateMachine",
paintStyle: { strokeStyle: "red", lineWidth: 4 },
hoverPaintStyle: { strokeStyle: "blue" },
overlays: [
"Arrow"
]
};
instance.registerConnectionType("basic", basicType);
// this is the paint style for the connecting lines..
var connectorPaintStyle = {
lineWidth: 4,
strokeStyle: "#61B7CF",
joinstyle: "round",
outlineColor: "white",
outlineWidth: 2
},
// .. and this is the hover style.
connectorHoverStyle = {
lineWidth: 6,
strokeStyle: "#216477",
outlineWidth: 2,
outlineColor: "white"
},
endpointHoverStyle = {
fillStyle: "yellow",
strokeStyle: "black"
},
// the definition of source endpoints (the small blue ones)
sourceEndpoint = {
endpoint: "Dot",
paintStyle: {
strokeStyle: "#7AB02C",
fillStyle: "transparent",
radius: 7,
lineWidth: 3
},
isSource: true,
connector: [ "Flowchart", { stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true } ],
connectorStyle: connectorPaintStyle,
hoverPaintStyle: endpointHoverStyle,
connectorHoverStyle: connectorHoverStyle,
dragOptions: {},
overlays: [
[ "Label", {
location: [0.5, 1.5],
label: "Drag",
cssClass: "endpointSourceLabel",
visible:false
} ]
]
},
// the definition of target endpoints (will appear when the user drags a connection)
targetEndpoint = {
endpoint: "Dot",
paintStyle: { fillStyle: "#7AB02C", radius: 11 },
hoverPaintStyle: endpointHoverStyle,
maxConnections: -1,
dropOptions: { hoverClass: "hover", activeClass: "active" },
isTarget: true,
overlays: [
[ "Label", { location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel", visible:false } ]
]
},
init = function (connection) {
connection.getOverlay("label").setLabel(connection.sourceId.substring(15) + "-" + connection.targetId.substring(15));
};
var sourceAnchors = ["BottomCenter","LeftMiddle", "RightMiddle"];
var targetAnchors = ["TopCenter"];
_addEndpoints = function (toId) {
for (var i = 0; i < sourceAnchors.length; i++) {
var sourceUUID = toId + sourceAnchors[i];
instance.addEndpoint("flowchart" + toId, sourceEndpoint, {
anchor: sourceAnchors[i], uuid: sourceUUID
});
}
for (var j = 0; j < targetAnchors.length; j++) {
var targetUUID = toId + targetAnchors[j];
instance.addEndpoint("flowchart" + toId, targetEndpoint, {
anchor: targetAnchors[j], uuid: targetUUID });
}
};
// suspend drawing and initialise.
instance.batch(function () {
_addEndpoints("Window4");
_addEndpoints("Window3");
_addEndpoints("Window2");
_addEndpoints("Window1");
// listen for new connections; initialise them the same way we initialise the connections at startup.
instance.bind("connection", function (connInfo, originalEvent) {
init(connInfo.connection);
});
// make all the window divs draggable
instance.draggable(jsPlumb.getSelector(".flowchart-demo .window"), { grid: [20, 20] });
// THIS DEMO ONLY USES getSelector FOR CONVENIENCE. Use your library's appropriate selector
// method, or document.querySelectorAll:
//jsPlumb.draggable(document.querySelectorAll(".window"), { grid: [20, 20] });
// connect a few up
instance.connect({uuids: ["Window2BottomCenter", "Window3TopCenter"], editable: true});
instance.connect({uuids: ["Window2LeftMiddle", "Window4TopCenter"], editable: true});
instance.connect({uuids: ["Window4LeftMiddle", "Window4TopCenter"], editable: true});
instance.connect({uuids: ["Window3RightMiddle", "Window2TopCenter"], editable: true});
instance.connect({uuids: ["Window4BottomCenter", "Window1TopCenter"], editable: true});
instance.connect({uuids: ["Window3BottomCenter", "Window1TopCenter"], editable: true});
//
//
// listen for clicks on connections, and offer to delete connections on click.
//
instance.bind("click", function (conn, originalEvent) {
// if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
// instance.detach(conn);
conn.toggleType("basic");
});
instance.bind("dblclick", function (conn, originalEvent) {
// if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
// instance.detach(conn);
instance.detach(conn);
});
// instance.bind("endpointClick", function (endpoint, originalEvent) {
// // if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
// // instance.detach(conn);
// alert("Shit");
// });
instance.bind("connectionDrag", function (connection) {
console.log("connection " + connection.id + " is being dragged. suspendedElement is ", connection.suspendedElement, " of type ", connection.suspendedElementType);
});
instance.bind("connectionDragStop", function (connection) {
console.log("connection " + connection.id + " was dragged");
});
instance.bind("connectionMoved", function (params) {
console.log("connection " + params.connection.id + " was moved");
});
});
jsPlumb.fire("jsPlumbDemoLoaded", instance);
});

Categories