Commit 85046fcc authored by Kazuhiko Shiozaki's avatar Kazuhiko Shiozaki

cleanup HTML and unify jsPlumb related javascript files.

parent d99462ff
<!doctype html>
<html>
<head>
<title>Dream Simulation</title>
<link rel="stylesheet" href="css/demo-new.css">
<link rel="stylesheet" href="css/flowchartDemo.css">
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/jsoneditor.css">
</head>
<body data-demo-id="flowchartConnectorsDemo" data-library="jquery">
<div id="headerWrapper"><div id="header"></div></div>
<div id="tools">
Tools
</div>
<div id="simulation_controls">
Simulation Parameters
<div title="Configure">
<form>
<fieldset id="general-fieldset">
</fieldset>
<a id="run_simulation">Run Simulation</a>
<a id="layout_graph">Layout Graph</a>
</form>
</div>
</div>
<div id="main">
<div id="render"></div>
</div>
<head>
<title>Dream Simulation</title>
<link rel="stylesheet" href="css/demo-new.css">
<link rel="stylesheet" href="css/flowchartDemo.css">
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/jsoneditor.css">
</head>
<div id="graph_zone">
<div>Stations Utilization</div>
<div id="graph"> </div>
</div>
<body data-demo-id="flowchartConnectorsDemo" data-library="jquery">
<div id="headerWrapper">
<div id="header"></div>
</div>
<div id="sidebar">
<table>
<tr>
<td>Input</td>
<td>Result</td>
</tr>
<tr>
<td>
<textarea rows="20" cols="47" id="json_output" style="align:left">
</textarea></td>
<td>
<textarea rows="20" cols="47" id="json_result" style="align:right">
</textarea></td>
</table>
<div id="tools">
Tools
</div>
<div id="simulation_controls">
Simulation Parameters
<div title="Configure">
<form>
<fieldset id="general-fieldset">
</fieldset>
<a id="run_simulation">Run Simulation</a>
<a id="layout_graph">Layout Graph</a>
</form>
</div>
</div>
</div>
<!-- DEP -->
<script type="text/javascript" src="lib/jquery-1.8.1-min.js"></script>
<script type="text/javascript" src="lib/jquery-ui-1.8.23-min.js"></script>
<script type="text/javascript" src="lib/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="lib/md5.js"></script>
<script type="text/javascript" src="lib/jio.js"></script>
<script type="text/javascript" src="lib/jio.localstorage.js"></script>
<script type="text/javascript" src="lib/pubsub.js"></script>
<!-- /DEP -->
<!-- JS -->
<!-- support lib for bezier stuff -->
<script src="lib/jsBezier-0.5.js"></script>
<!-- jsplumb util -->
<script src="lib/jsPlumb/jsPlumb-util.js"></script>
<!-- base DOM adapter -->
<script src="lib/jsPlumb/jsPlumb-dom-adapter.js"></script>
<!-- main jsplumb engine -->
<script src="lib/jsPlumb/jsPlumb.js"></script>
<!-- anchors -->
<script src="lib/jsPlumb/jsPlumb-anchors.js"></script>
<!-- endpoint -->
<script src="lib/jsPlumb/jsPlumb-endpoint.js"></script>
<!-- connection -->
<script src="lib/jsPlumb/jsPlumb-connection.js"></script>
<!-- connector editors -->
<script src="lib/jsPlumb/jsPlumb-connector-editors.js"></script>
<!-- connectors, endpoint and overlays -->
<script src="lib/jsPlumb/jsPlumb-defaults.js"></script>
<!-- state machine connectors -->
<script src="lib/jsPlumb/jsPlumb-connectors-statemachine.js"></script>
<!-- flowchart connectors -->
<script src="lib/jsPlumb/jsPlumb-connectors-flowchart.js"></script>
<!-- SVG renderer -->
<script src="lib/jsPlumb/jsPlumb-renderers-svg.js"></script>
<!-- canvas renderer -->
<script src="lib/jsPlumb/jsPlumb-renderers-canvas.js"></script>
<!-- vml renderer -->
<script src="lib/jsPlumb/jsPlumb-renderers-vml.js"></script>
<!-- jquery jsPlumb adapter -->
<script src="lib/jsPlumb/jquery.jsPlumb.js"></script>
<!-- /JS -->
<!-- flot -->
<script src="lib/jquery.flot.js"></script>
<script src="lib/jquery.flot.stack.js"></script>
<script src="lib/jquery.jsoneditor.js"></script>
<div id="main">
<div id="render"></div>
</div>
<div id="dialog-form" title="Configure">
<form>
<fieldset id="dialog-fieldset">
</fieldset>
</form>
</div>
<div id="graph_zone">
<div>Stations Utilization</div>
<div id="graph"></div>
</div>
<div id="sidebar">
<table>
<tr>
<td>Input</td>
<td>Result</td>
</tr>
<tr>
<td>
<textarea rows="20" cols="47" id="json_output" style="align:left">
</textarea>
</td>
<td>
<textarea rows="20" cols="47" id="json_result" style="align:right">
</textarea>
</td>
</table>
</div>
<!-- DEP -->
<script type="text/javascript" src="lib/jquery-1.8.1-min.js"></script>
<script type="text/javascript" src="lib/jquery-ui-1.8.23-min.js"></script>
<script type="text/javascript" src="lib/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="lib/md5.js"></script>
<script type="text/javascript" src="lib/jio.js"></script>
<script type="text/javascript" src="lib/jio.localstorage.js"></script>
<script type="text/javascript" src="lib/pubsub.js"></script>
<script type="text/javascript" src="lib/jquery.jsPlumb-1.5.3-min.js"></script>
<!-- /DEP -->
<!-- flot -->
<script type="text/javascript" src="lib/jquery.flot.js"></script>
<script type="text/javascript" src="lib/jquery.flot.stack.js"></script>
<script type="text/javascript" src="lib/jquery.jsoneditor.js"></script>
<div id="dialog-form" title="Configure">
<form>
<fieldset id="dialog-fieldset">
</fieldset>
</form>
</div>
<!-- demo code -->
<script type="text/javascript" src="src/dream.js"></script>
<script type="text/javascript" src="src/jsonPlumb.js"></script>
<script type="text/javascript" src="src/dream_launcher.js"></script>
</body>
<!-- demo code -->
<script src="src/dream.js"></script>
<script src="src/jsonPlumb.js"></script>
<script src="src/dream_launcher.js"></script>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
......@@ -9,58 +10,24 @@
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.js"></script>
<script type="text/javascript" src="lib/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="lib/md5.js"></script>
<script type="text/javascript" src="lib/jio.js"></script>
<script type="text/javascript" src="lib/jio.localstorage.js"></script>
<script type="text/javascript" src="lib/pubsub.js"></script>
<!-- JS plumb -->
<!-- support lib for bezier stuff -->
<script src="lib/jsBezier-0.5.js"></script>
<!-- jsplumb util -->
<script src="lib/jsPlumb/jsPlumb-util.js"></script>
<!-- base DOM adapter -->
<script src="lib/jsPlumb/jsPlumb-dom-adapter.js"></script>
<!-- main jsplumb engine -->
<script src="lib/jsPlumb/jsPlumb.js"></script>
<!-- anchors -->
<script src="lib/jsPlumb/jsPlumb-anchors.js"></script>
<!-- endpoint -->
<script src="lib/jsPlumb/jsPlumb-endpoint.js"></script>
<!-- connection -->
<script src="lib/jsPlumb/jsPlumb-connection.js"></script>
<!-- connector editors -->
<script src="lib/jsPlumb/jsPlumb-connector-editors.js"></script>
<!-- connectors, endpoint and overlays -->
<script src="lib/jsPlumb/jsPlumb-defaults.js"></script>
<!-- state machine connectors -->
<script src="lib/jsPlumb/jsPlumb-connectors-statemachine.js"></script>
<!-- flowchart connectors -->
<script src="lib/jsPlumb/jsPlumb-connectors-flowchart.js"></script>
<!-- SVG renderer -->
<script src="lib/jsPlumb/jsPlumb-renderers-svg.js"></script>
<!-- canvas renderer -->
<script src="lib/jsPlumb/jsPlumb-renderers-canvas.js"></script>
<!-- vml renderer -->
<script src="lib/jsPlumb/jsPlumb-renderers-vml.js"></script>
<!-- jquery jsPlumb adapter -->
<script src="lib/jsPlumb/jquery.jsPlumb.js"></script>
<!-- /JS -->
<script src="http://raw.github.com/DavidDurman/FlexiJsonEditor/master/jquery.jsoneditor.js"></script>
<script src="src/dream2.js"></script>
<script type="text/javascript" src="lib/jquery.jsPlumb-1.5.3-min.js"></script>
<script type="text/javascript" src="lib/jquery.jsoneditor.js"></script>
<script type="text/javascript" src="src/dream2.js"></script>
</head>
<body>
<!--
<!--
<div class="content-secondary">
<div data-role="collapsible" data-collapsed="true" data-theme="b" data-content-theme="d">
<h3>Controls<h3>
<h3>Controls</h3>
<ul data-role="listview" data-theme="c">
<li><a href="menu-general.html">General</a></li>
<li><a href="menu-palette.html">Node</a></li>
......@@ -70,124 +37,128 @@
</div>
-->
<div data-role="page" class="ui-responsive-panel">
<div data-role="header" data-theme="f">
<h1>DREAM</h1>
<a href="#nav-panel" data-icon="bars" data-iconpos="notext">Menu</a>
<a href="#add-form" data-icon="plus" data-iconpos="notext">Add</a>
</div><!-- /header -->
<div data-role="content">
<h2>Panel: Menu + form</h2>
<p>This is a typical page that has two buttons in the header bar that open panels. The left button opens a left menu with the reveal display mode. The right button opens a form in a right overlay panel.</p>
<div class="ui-grid-a">
<div class="ui-block-a"><strong>I'm Block A</strong> and text inside will
wrap
<div id="main"> </div>
</div>
<div class="ui-block-b"><strong>I'm Block B</strong> and text inside will
wrap
<div>
<label for="node_id">Node ID:</label>
<input id="node_id"/>
<label for="node_top">Node Top:</label>
<input type="range" name="node_top" id="node_top" value="" min="0" max="100" />
<label for="node_left">Node Left:</label>
<input type="range" name="node_left" id="node_left" value="" min="0" max="100" />
<button id="move_node">Move Node</button>
</div>
<div data-role="page" class="ui-responsive-panel">
<div data-role="header" data-theme="f">
<h1>DREAM</h1>
<a href="#nav-panel" data-icon="bars" data-iconpos="notext">Menu</a>
<a href="#add-form" data-icon="plus" data-iconpos="notext">Add</a>
</div>
<!-- /header -->
<div data-role="content">
<h2>Panel: Menu + form</h2>
<p>This is a typical page that has two buttons in the header bar that open panels. The left button opens a left menu with the reveal display mode. The right button opens a form in a right overlay panel.</p>
<div class="ui-grid-a">
<div class="ui-block-a"><strong>I'm Block A</strong> and text inside will wrap
<div id="main"></div>
</div>
<div class="ui-block-b"><strong>I'm Block B</strong> and text inside will wrap
<div>
<label for="node_id">Node ID:</label>
<input id="node_id" />
<label for="node_top">Node Top:</label>
<input type="range" name="node_top" id="node_top" value="" min="0" max="100" />
<label for="node_left">Node Left:</label>
<input type="range" name="node_left" id="node_left" value="" min="0" max="100" />
<button id="move_node">Move Node</button>
</div>
<div>
<textarea rows="20" cols="47" id="debug_zone" style="align:left"></textarea>
<button id="load_json">Load JSON</button>
</div>
</div>
</div>
<!-- /grid-a -->
<p>Since the panel links are in the top bar, there really isn't a need for the fixed positioning feature on the panel since you will always be scrolled to the top of the page. The fixed positioning impacts animation smoothness so it's off in this demo
(
<code>data-position-fixed="false"</code>) and the panel will scroll with the page.</p>
<p>To make this responsive, the left panel stays open and causes the page to re-flow at wider widths. This allows both the menu and page to be used together when more space is available. This behavior is controlled by CSS media queries. You can create
a custom one for a specific breakpoint or use the breakpoint preset by adding the <code> class="ui-responsive-panel"</code> to the page container.</p>
</div>
<!-- /content -->
<div data-role="panel" data-position="left" data-position-fixed="false" data-display="reveal" id="nav-panel" data-theme="a">
<!-- good style: -->
<div data-role="collapsible" data-collapsed="true" data-theme="b" data-content-theme="d">
<h3>Controls</h3>
<ul data-role="listview" data-theme="c">
<li><a href="menu-general.html">General</a>
</li>
<li><a href="menu-palette.html">Node</a>
</li>
<li><a href="menu-runsimulation.html">Run Simulation</a>
</li>
</ul>
</div>
<!-- from example: -->
<ul data-role="listview" data-theme="a" data-divider-theme="a" style="margin-top:-16px;" class="nav-search">
<li data-icon="delete" style="background-color:#111;">
<a href="#" data-rel="close">Close menu</a>
</li>
<li data-filtertext="wai-aria voiceover accessibility screen reader">
<a href="../about/accessibility.html">Accessibility</a>
</li>
<li data-filtertext="accordions collapsible set collapsible-set collapsed">
<a href="../content/content-collapsible-set.html">Accordions</a>
</li>
<li data-filtertext="ajax navigation model">
<a href="../pages/page-navmodel.html">Ajax navigation model</a>
</li>
<li data-filtertext="anatomy of page viewport">
<a href="../pages/page-anatomy.html">Anatomy of a page</a>
</li>
<li data-filtertext="events api animationComplete transition css">
<a href="../api/events.html">Animation events</a>
</li>
<li data-filtertext="listview autodivider">
<a href="../lists/lists-autodividers.html">Automatic listview dividers</a>
</li>
<li data-filtertext="button link submit cancel image reset mini buttonmarkup enable disable">
<a href="../buttons/buttons-types.html">Buttons</a>
</li>
<li data-filtertext="button icon">
<a href="../buttons/buttons-icons.html">Button icons</a>
</li>
<li data-filtertext="data-prefetch loadpage domCache data-dom-cache size clear cleanup pagehide lazyload spinner loader">
<a href="../pages/page-cache.html">Caching pages</a>
</li>
<li data-filtertext="input forms multi select checkbox checks grouped horizontal toggle legend">
<a href="../forms/checkboxes/">Checkbox</a>
</li>
<li data-filtertext="button icon">
<a href="buttons/buttons-icons.html">Button icons</a>
</li>
<li data-filtertext="data-prefetch loadpage domCache data-dom-cache size clear cleanup pagehide lazyload spinner loader">
<a href="../pages/page-cache.html">Caching pages</a>
</li>
<li data-filtertext="input forms multi select checkbox checks grouped horizontal toggle legend">
<a href="../forms/checkboxes/">Checkbox</a>
</li>
</ul>
<!-- panel content goes here -->
</div>
<!-- /panel -->
<div>
<textarea rows="20" cols="47" id="debug_zone" style="align:left"> </textarea>
<button id="load_json">Load JSON</button>
</div>
</div>
</div><!-- /grid-a -->
<p>Since the panel links are in the top bar, there really isn't a need for the fixed positioning feature on the panel since you will always be scrolled to the top of the page. The fixed positioning impacts animation smoothness so it's off in this demo (<code>data-position-fixed="false"</code>) and the panel will scroll with the page.</p>
<p>To make this responsive, the left panel stays open and causes the page to re-flow at wider widths. This allows both the menu and page to be used together when more space is available. This behavior is controlled by CSS media queries. You can create a custom one for a specific breakpoint or use the breakpoint preset by adding the <code> class="ui-responsive-panel"</code> to the page container.</p>
</div><!-- /content -->
<div data-role="panel" data-position="left" data-position-fixed="false" data-display="reveal" id="nav-panel" data-theme="a">
<!-- good style: -->
<div data-role="collapsible" data-collapsed="true" data-theme="b" data-content-theme="d">
<h3>Controls<h3>
<ul data-role="listview" data-theme="c">
<li><a href="menu-general.html">General</a></li>
<li><a href="menu-palette.html">Node</a></li>
<li><a href="menu-runsimulation.html">Run Simulation</a></li>
</ul>
</div>
<!-- from example: -->
<ul data-role="listview" data-theme="a" data-divider-theme="a" style="margin-top:-16px;" class="nav-search">
<li data-icon="delete" style="background-color:#111;">
<a href="#" data-rel="close">Close menu</a>
</li>
<li data-filtertext="wai-aria voiceover accessibility screen reader">
<a href="../about/accessibility.html">Accessibility</a>
</li>
<li data-filtertext="accordions collapsible set collapsible-set collapsed">
<a href="../content/content-collapsible-set.html">Accordions</a>
</li>
<li data-filtertext="ajax navigation model">
<a href="../pages/page-navmodel.html">Ajax navigation model</a>
</li>
<li data-filtertext="anatomy of page viewport">
<a href="../pages/page-anatomy.html">Anatomy of a page</a>
</li>
<li data-filtertext="events api animationComplete transition css">
<a href="../api/events.html">Animation events</a>
</li>
<li data-filtertext="listview autodivider">
<a href="../lists/lists-autodividers.html">Automatic listview dividers</a>
</li>
<li data-filtertext="button link submit cancel image reset mini buttonmarkup enable disable">
<a href="../buttons/buttons-types.html">Buttons</a>
</li>
<li data-filtertext="button icon">
<a href="../buttons/buttons-icons.html">Button icons</a>
</li>
<li data-filtertext="data-prefetch loadpage domCache data-dom-cache size clear cleanup pagehide lazyload spinner loader">
<a href="../pages/page-cache.html">Caching pages</a>
</li>
<li data-filtertext="input forms multi select checkbox checks grouped horizontal toggle legend">
<a href="../forms/checkboxes/">Checkbox</a>
</li>
<li data-filtertext="button icon">
<a href="buttons/buttons-icons.html">Button icons</a>
</li>
<li data-filtertext="data-prefetch loadpage domCache data-dom-cache size clear cleanup pagehide lazyload spinner loader">
<a href="../pages/page-cache.html">Caching pages</a>
</li>
<li data-filtertext="input forms multi select checkbox checks grouped horizontal toggle legend">
<a href="../forms/checkboxes/">Checkbox</a>
</li>
</ul>
<!-- panel content goes here -->
</div><!-- /panel -->
</div><!-- /page -->
<div data-role="page" data-url="dialog.html" id="dialog">
<div data-role="header">
<h1>Dialog</h1>
</div>
<div data-role="content">
<p>Is this an answer?</p>
<!-- /page -->
<div data-role="page" data-url="dialog.html" id="dialog">
<div data-role="header">
<h1>Dialog</h1>
</div>
<div data-role="content">
<p>Is this an answer?</p>
</div>
</div>
</div>
</body>
</html>
</html>
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
* jsBezier-0.5
*
* Copyright (c) 2010 - 2011 Simon Porritt (simon.porritt@gmail.com)
*
* licensed under the MIT license.
*
* a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier
* curves of arbitrary degree.
*
* - functions are all in the 'jsBezier' namespace.
*
* - all input points should be in the format {x:.., y:..}. all output points are in this format too.
*
* - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ]
*
* - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length
* of the curve. location as output has the same format and meaning.
*
*
* Function List:
* --------------
*
* distanceFromCurve(point, curve)
*
* Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier,
* so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values
* of the curve and the point - it will most likely be pixels.
*
* gradientAtPoint(curve, location)
*
* Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive.
*
* gradientAtPointAlongCurveFrom (curve, location)
*
* Calculates the gradient at the point on the given curve that is 'distance' units from location.
*
* nearestPointOnCurve(point, curve)
*
* Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the
*point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }.
*
* pointOnCurve(curve, location)
*
* Calculates the coordinates of the point on the given Bezier curve at the given location.
*
* pointAlongCurveFrom(curve, location, distance)
*
* Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
* space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
*
* locationAlongCurveFrom(curve, location, distance)
*
* Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
* space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
*
* perpendicularToCurveAt(curve, location, length, distance)
*
* Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered
* on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of
* the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ].
*
*
*/
(function() {
if(typeof Math.sgn == "undefined") {
Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; };
}
var Vectors = {
subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; },
dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); },
square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); },
scale : function(v, s) { return {x:v.x * s, y:v.y * s }; }
},
maxRecursion = 64,
flatnessTolerance = Math.pow(2.0,-maxRecursion-1);
/**
* Calculates the distance that the point lies from the curve.
*
* @param point a point in the form {x:567, y:3342}
* @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently
* hardcoded to assume cubiz beziers, but would be better off supporting any degree.
* @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location
* argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from
* the point to the curve.
*/
var _distanceFromCurve = function(point, curve) {
var candidates = [],
w = _convertToBezier(point, curve),
degree = curve.length - 1, higherDegree = (2 * degree) - 1,
numSolutions = _findRoots(w, higherDegree, candidates, 0),
v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0;
for (var i = 0; i < numSolutions; i++) {
v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null));
var newDist = Vectors.square(v);
if (newDist < dist) {
dist = newDist;
t = candidates[i];
}
}
v = Vectors.subtract(point, curve[degree]);
newDist = Vectors.square(v);
if (newDist < dist) {
dist = newDist;
t = 1.0;
}
return {location:t, distance:dist};
};
/**
* finds the nearest point on the curve to the given point.
*/
var _nearestPointOnCurve = function(point, curve) {
var td = _distanceFromCurve(point, curve);
return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location};
};
var _convertToBezier = function(point, curve) {
var degree = curve.length - 1, higherDegree = (2 * degree) - 1,
c = [], d = [], cdTable = [], w = [],
z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ];
for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point);
for (var i = 0; i <= degree - 1; i++) {
d[i] = Vectors.subtract(curve[i+1], curve[i]);
d[i] = Vectors.scale(d[i], 3.0);
}
for (var row = 0; row <= degree - 1; row++) {
for (var column = 0; column <= degree; column++) {
if (!cdTable[row]) cdTable[row] = [];
cdTable[row][column] = Vectors.dotProduct(d[row], c[column]);
}
}
for (i = 0; i <= higherDegree; i++) {
if (!w[i]) w[i] = [];
w[i].y = 0.0;
w[i].x = parseFloat(i) / higherDegree;
}
var n = degree, m = degree-1;
for (var k = 0; k <= n + m; k++) {
var lb = Math.max(0, k - m),
ub = Math.min(k, n);
for (i = lb; i <= ub; i++) {
j = k - i;
w[i+j].y += cdTable[j][i] * z[j][i];
}
}
return w;
};
/**
* counts how many roots there are.
*/
var _findRoots = function(w, degree, t, depth) {
var left = [], right = [],
left_count, right_count,
left_t = [], right_t = [];
switch (_getCrossingCount(w, degree)) {
case 0 : {
return 0;
}
case 1 : {
if (depth >= maxRecursion) {
t[0] = (w[0].x + w[degree].x) / 2.0;
return 1;
}
if (_isFlatEnough(w, degree)) {
t[0] = _computeXIntercept(w, degree);
return 1;
}
break;
}
}
_bezier(w, degree, 0.5, left, right);
left_count = _findRoots(left, degree, left_t, depth+1);
right_count = _findRoots(right, degree, right_t, depth+1);
for (var i = 0; i < left_count; i++) t[i] = left_t[i];
for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i];
return (left_count+right_count);
};
var _getCrossingCount = function(curve, degree) {
var n_crossings = 0, sign, old_sign;
sign = old_sign = Math.sgn(curve[0].y);
for (var i = 1; i <= degree; i++) {
sign = Math.sgn(curve[i].y);
if (sign != old_sign) n_crossings++;
old_sign = sign;
}
return n_crossings;
};
var _isFlatEnough = function(curve, degree) {
var error,
intercept_1, intercept_2, left_intercept, right_intercept,
a, b, c, det, dInv, a1, b1, c1, a2, b2, c2;
a = curve[0].y - curve[degree].y;
b = curve[degree].x - curve[0].x;
c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y;
var max_distance_above = max_distance_below = 0.0;
for (var i = 1; i < degree; i++) {
var value = a * curve[i].x + b * curve[i].y + c;
if (value > max_distance_above)
max_distance_above = value;
else if (value < max_distance_below)
max_distance_below = value;
}
a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b;
c2 = c - max_distance_above;
det = a1 * b2 - a2 * b1;
dInv = 1.0/det;
intercept_1 = (b1 * c2 - b2 * c1) * dInv;
a2 = a; b2 = b; c2 = c - max_distance_below;
det = a1 * b2 - a2 * b1;
dInv = 1.0/det;
intercept_2 = (b1 * c2 - b2 * c1) * dInv;
left_intercept = Math.min(intercept_1, intercept_2);
right_intercept = Math.max(intercept_1, intercept_2);
error = right_intercept - left_intercept;
return (error < flatnessTolerance)? 1 : 0;
};
var _computeXIntercept = function(curve, degree) {
var XLK = 1.0, YLK = 0.0,
XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y,
XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0,
det = XNM*YLK - YNM*XLK, detInv = 1.0/det,
S = (XNM*YMK - YNM*XMK) * detInv;
return 0.0 + XLK * S;
};
var _bezier = function(curve, degree, t, left, right) {
var temp = [[]];
for (var j =0; j <= degree; j++) temp[0][j] = curve[j];
for (var i = 1; i <= degree; i++) {
for (var j =0 ; j <= degree - i; j++) {
if (!temp[i]) temp[i] = [];
if (!temp[i][j]) temp[i][j] = {};
temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x;
temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y;
}
}
if (left != null)
for (j = 0; j <= degree; j++) left[j] = temp[j][0];
if (right != null)
for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j];
return (temp[degree][0]);
};
var _curveFunctionCache = {};
var _getCurveFunctions = function(order) {
var fns = _curveFunctionCache[order];
if (!fns) {
fns = [];
var f_term = function() { return function(t) { return Math.pow(t, order); }; },
l_term = function() { return function(t) { return Math.pow((1-t), order); }; },
c_term = function(c) { return function(t) { return c; }; },
t_term = function() { return function(t) { return t; }; },
one_minus_t_term = function() { return function(t) { return 1-t; }; },
_termFunc = function(terms) {
return function(t) {
var p = 1;
for (var i = 0; i < terms.length; i++) p = p * terms[i](t);
return p;
};
};
fns.push(new f_term()); // first is t to the power of the curve order
for (var i = 1; i < order; i++) {
var terms = [new c_term(order)];
for (var j = 0 ; j < (order - i); j++) terms.push(new t_term());
for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term());
fns.push(new _termFunc(terms));
}
fns.push(new l_term()); // last is (1-t) to the power of the curve order
_curveFunctionCache[order] = fns;
}
return fns;
};
/**
* calculates a point on the curve, for a Bezier of arbitrary order.
* @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points.
* @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive.
*/
var _pointOnPath = function(curve, location) {
var cc = _getCurveFunctions(curve.length - 1),
_x = 0, _y = 0;
for (var i = 0; i < curve.length ; i++) {
_x = _x + (curve[i].x * cc[i](location));
_y = _y + (curve[i].y * cc[i](location));
}
return {x:_x, y:_y};
};
var _dist = function(p1,p2) {
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
};
/**
* finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also
* its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the
* point.
*/
var _pointAlongPath = function(curve, location, distance) {
var prev = _pointOnPath(curve, location),
tally = 0,
curLoc = location,
direction = distance > 0 ? 1 : -1,
cur = null;
while (tally < Math.abs(distance)) {
curLoc += (0.005 * direction);
cur = _pointOnPath(curve, curLoc);
tally += _dist(cur, prev);
prev = cur;
}
return {point:cur, location:curLoc};
};
var _length = function(curve) {
var prev = _pointOnPath(curve, 0),
tally = 0,
curLoc = 0,
direction = 1,
cur = null;
while (curLoc < 1) {
curLoc += (0.005 * direction);
cur = _pointOnPath(curve, curLoc);
tally += _dist(cur, prev);
prev = cur;
}
return tally;
};
/**
* finds the point that is 'distance' along the path from 'location'.
*/
var _pointAlongPathFrom = function(curve, location, distance) {
return _pointAlongPath(curve, location, distance).point;
};
/**
* finds the location that is 'distance' along the path from 'location'.
*/
var _locationAlongPathFrom = function(curve, location, distance) {
return _pointAlongPath(curve, location, distance).location;
};
/**
* returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive.
*
* thanks // http://bimixual.org/AnimationLibrary/beziertangents.html
*/
var _gradientAtPoint = function(curve, location) {
var p1 = _pointOnPath(curve, location),
p2 = _pointOnPath(curve.slice(0, curve.length - 1), location),
dy = p2.y - p1.y, dx = p2.x - p1.x;
return dy == 0 ? Infinity : Math.atan(dy / dx);
};
/**
returns the gradient of the curve at the point which is 'distance' from the given location.
if this point is greater than location 1, the gradient at location 1 is returned.
if this point is less than location 0, the gradient at location 0 is returned.
*/
var _gradientAtPointAlongPathFrom = function(curve, location, distance) {
var p = _pointAlongPath(curve, location, distance);
if (p.location > 1) p.location = 1;
if (p.location < 0) p.location = 0;
return _gradientAtPoint(curve, p.location);
};
/**
* calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location.
* if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero).
*/
var _perpendicularToPathAt = function(curve, location, length, distance) {
distance = distance == null ? 0 : distance;
var p = _pointAlongPath(curve, location, distance),
m = _gradientAtPoint(curve, p.location),
_theta2 = Math.atan(-1 / m),
y = length / 2 * Math.sin(_theta2),
x = length / 2 * Math.cos(_theta2);
return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}];
};
var jsBezier = window.jsBezier = {
distanceFromCurve : _distanceFromCurve,
gradientAtPoint : _gradientAtPoint,
gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom,
nearestPointOnCurve : _nearestPointOnCurve,
pointOnCurve : _pointOnPath,
pointAlongCurveFrom : _pointAlongPathFrom,
perpendicularToCurveAt : _perpendicularToPathAt,
locationAlongCurveFrom:_locationAlongPathFrom,
getLength:_length
};
})();
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the jQuery adapter.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
/*
* the library specific functions, such as find offset, get id, get attribute, extend etc.
* the full list is:
*
* addClass adds a class to the given element
* animate calls the underlying library's animate functionality
* appendElement appends a child element to a parent element.
* bind binds some event to an element
* dragEvents a dictionary of event names
* extend extend some js object with another. probably not overly necessary; jsPlumb could just do this internally.
* getAttribute gets some attribute from an element
* getDragObject gets the object that is being dragged, by extracting it from the arguments passed to a drag callback
* getDragScope gets the drag scope for a given element.
* getDropScope gets the drop scope for a given element.
* getElementObject turns an id or dom element into an element object of the underlying library's type.
* getOffset gets an element's offset
* getOriginalEvent gets the original browser event from some wrapper event
* getPageXY gets the page event's xy location.
* getParent gets the parent of some element.
* getScrollLeft gets an element's scroll left. TODO: is this actually used? will it be?
* getScrollTop gets an element's scroll top. TODO: is this actually used? will it be?
* getSize gets an element's size.
* getUIPosition gets the position of some element that is currently being dragged, by extracting it from the arguments passed to a drag callback.
* hasClass returns whether or not the given element has the given class.
* initDraggable initializes an element to be draggable
* initDroppable initializes an element to be droppable
* isDragSupported returns whether or not drag is supported for some element.
* isDropSupported returns whether or not drop is supported for some element.
* removeClass removes a class from a given element.
* removeElement removes some element completely from the DOM.
* setAttribute sets an attribute on some element.
* setDragFilter sets a filter for some element that indicates areas of the element that should not respond to dragging.
* setDraggable sets whether or not some element should be draggable.
* setDragScope sets the drag scope for a given element.
* setOffset sets the offset of some element.
* trigger triggers some event on an element.
* unbind unbinds some listener from some element.
*/
(function($) {
//var getBoundingClientRectSupported = "getBoundingClientRect" in document.documentElement;
var _getElementObject = function(el) {
return typeof(el) == "string" ? $("#" + el) : $(el);
};
jsPlumb.CurrentLibrary = {
/**
* adds the given class to the element object.
*/
addClass : function(el, clazz) {
el = _getElementObject(el);
try {
if (el[0].className.constructor == SVGAnimatedString) {
jsPlumbUtil.svg.addClass(el[0], clazz);
}
}
catch (e) {
// SVGAnimatedString not supported; no problem.
}
try {
el.addClass(clazz);
}
catch (e) {
// you probably have jQuery 1.9 and Firefox.
}
},
/**
* animates the given element.
*/
animate : function(el, properties, options) {
el.animate(properties, options);
},
/**
* appends the given child to the given parent.
*/
appendElement : function(child, parent) {
_getElementObject(parent).append(child);
},
/**
* executes an ajax call.
*/
ajax : function(params) {
params = params || {};
params.type = params.type || "get";
$.ajax(params);
},
/**
* event binding wrapper. it just so happens that jQuery uses 'bind' also. yui3, for example,
* uses 'on'.
*/
bind : function(el, event, callback) {
el = _getElementObject(el);
el.bind(event, callback);
},
/**
* mapping of drag events for jQuery
*/
dragEvents : {
'start':'start', 'stop':'stop', 'drag':'drag', 'step':'step',
'over':'over', 'out':'out', 'drop':'drop', 'complete':'complete'
},
/**
* wrapper around the library's 'extend' functionality (which it hopefully has.
* otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
* instead. it's not like its hard.
*/
extend : function(o1, o2) {
return $.extend(o1, o2);
},
/**
* gets the named attribute from the given element object.
*/
getAttribute : function(el, attName) {
return el.attr(attName);
},
getClientXY : function(eventObject) {
return [eventObject.clientX, eventObject.clientY];
},
/**
* takes the args passed to an event function and returns you an object representing that which is being dragged.
*/
getDragObject : function(eventArgs) {
return eventArgs[1].draggable || eventArgs[1].helper;
},
getDragScope : function(el) {
return el.draggable("option", "scope");
},
getDropEvent : function(args) {
return args[0];
},
getDropScope : function(el) {
return el.droppable("option", "scope");
},
/**
* gets a DOM element from the given input, which might be a string (in which case we just do document.getElementById),
* a selector (in which case we return el[0]), or a DOM element already (we assume this if it's not either of the other
* two cases). this is the opposite of getElementObject below.
*/
getDOMElement : function(el) {
if (typeof(el) == "string") return document.getElementById(el);
else if (el.context || el.length != null) return el[0];
else return el;
},
/**
* gets an "element object" from the given input. this means an object that is used by the
* underlying library on which jsPlumb is running. 'el' may already be one of these objects,
* in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
* function is used to find the element, using the given String as the element's id.
*
*/
getElementObject : _getElementObject,
/**
* gets the offset for the element object. this should return a js object like this:
*
* { left:xxx, top: xxx }
*/
getOffset : function(el) {
return el.offset();
},
getOriginalEvent : function(e) {
return e.originalEvent;
},
getPageXY : function(eventObject) {
return [eventObject.pageX, eventObject.pageY];
},
getParent : function(el) {
return _getElementObject(el).parent();
},
getScrollLeft : function(el) {
return el.scrollLeft();
},
getScrollTop : function(el) {
return el.scrollTop();
},
getSelector : function(context, spec) {
if (arguments.length == 2)
return _getElementObject(context).find(spec);
else
return $(context);
},
/**
* gets the size for the element object, in an array : [ width, height ].
*/
getSize : function(el) {
return [el.outerWidth(), el.outerHeight()];
},
getTagName : function(el) {
var e = _getElementObject(el);
return e.length > 0 ? e[0].tagName : null;
},
/**
* takes the args passed to an event function and returns you an object that gives the
* position of the object being moved, as a js object with the same params as the result of
* getOffset, ie: { left: xxx, top: xxx }.
*
* different libraries have different signatures for their event callbacks.
* see getDragObject as well
*/
getUIPosition : function(eventArgs, zoom) {
zoom = zoom || 1;
// this code is a workaround for the case that the element being dragged has a margin set on it. jquery UI passes
// in the wrong offset if the element has a margin (it doesn't take the margin into account). the getBoundingClientRect
// method, which is in pretty much all browsers now, reports the right numbers. but it introduces a noticeable lag, which
// i don't like.
/*if ( getBoundingClientRectSupported ) {
var r = eventArgs[1].helper[0].getBoundingClientRect();
return { left : r.left, top: r.top };
} else {*/
if (eventArgs.length == 1) {
ret = { left: eventArgs[0].pageX, top:eventArgs[0].pageY };
}
else {
var ui = eventArgs[1],
_offset = ui.offset;
ret = _offset || ui.absolutePosition;
// adjust ui position to account for zoom, because jquery ui does not do this.
ui.position.left /= zoom;
ui.position.top /= zoom;
}
return { left:ret.left / zoom, top: ret.top / zoom };
},
hasClass : function(el, clazz) {
return el.hasClass(clazz);
},
/**
* initialises the given element to be draggable.
*/
initDraggable : function(el, options, isPlumbedComponent, _jsPlumb) {
options = options || {};
/*
// css3 transforms
// http://gungfoo.wordpress.com/2013/02/15/jquery-ui-resizabledraggable-with-transform-scale-set/
options.start = _jsPlumb.wrap(options["start"], function(e, ui) {
// TODO why is this 0?
ui.position.left = 0;
ui.position.top = 0;
});
options.drag = _jsPlumb.wrap(options["drag"], function(e, ui) {
console.log("original", ui.originalPosition.left, ui.originalPosition.top);
console.log("current", ui.position.left, ui.position.top);
//var changeLeft = ui.position.left - ui.originalPosition.left; // find change in left
//var newLeft = ui.originalPosition.left + (changeLeft * _jsPlumb.getZoom()); // adjust new left by our zoomScale
//var changeTop = ui.position.top - ui.originalPosition.top; // find change in top
//var newTop = ui.originalPosition.top + (changeTop * _jsPlumb.getZoom()); // adjust new top by our zoomScale
//ui.position.left = newLeft;
//ui.position.top = newTop;
ui.position.left *= _jsPlumb.getZoom();
ui.position.top *= _jsPlumb.getZoom();
});
*/
// remove helper directive if present and no override
if (!options.doNotRemoveHelper)
options.helper = null;
if (isPlumbedComponent)
options['scope'] = options['scope'] || jsPlumb.Defaults.Scope;
el.draggable(options);
},
/**
* initialises the given element to be droppable.
*/
initDroppable : function(el, options) {
options['scope'] = options['scope'] || jsPlumb.Defaults.Scope;
el.droppable(options);
},
isAlreadyDraggable : function(el) {
return _getElementObject(el).hasClass("ui-draggable");
},
/**
* returns whether or not drag is supported (by the library, not whether or not it is disabled) for the given element.
*/
isDragSupported : function(el, options) {
return el.draggable;
},
/**
* returns whether or not drop is supported (by the library, not whether or not it is disabled) for the given element.
*/
isDropSupported : function(el, options) {
return el.droppable;
},
/**
* removes the given class from the element object.
*/
removeClass : function(el, clazz) {
el = _getElementObject(el);
try {
if (el[0].className.constructor == SVGAnimatedString) {
jsPlumbUtil.svg.removeClass(el[0], clazz);
return;
}
}
catch (e) {
// SVGAnimatedString not supported; no problem.
}
el.removeClass(clazz);
},
removeElement : function(element) {
_getElementObject(element).remove();
},
setAttribute : function(el, attName, attValue) {
el.attr(attName, attValue);
},
setDragFilter : function(el, filter) {
if (jsPlumb.CurrentLibrary.isAlreadyDraggable(el))
el.draggable("option", "cancel", filter);
},
setDraggable : function(el, draggable) {
el.draggable("option", "disabled", !draggable);
},
setDragScope : function(el, scope) {
el.draggable("option", "scope", scope);
},
setOffset : function(el, o) {
_getElementObject(el).offset(o);
},
/**
* note that jquery ignores the name of the event you wanted to trigger, and figures it out for itself.
* the other libraries do not. yui, in fact, cannot even pass an original event. we have to pull out stuff
* from the originalEvent to put in an options object for YUI.
* @param el
* @param event
* @param originalEvent
*/
trigger : function(el, event, originalEvent) {
var h = jQuery._data(_getElementObject(el)[0], "handle");
h(originalEvent);
},
unbind : function(el, event, callback) {
el = _getElementObject(el);
el.unbind(event, callback);
}
};
$(document).ready(jsPlumb.init);
})(jQuery);
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the code for creating and manipulating anchors.
*
* Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
//
// manages anchors for all elements.
//
jsPlumb.AnchorManager = function(params) {
var _amEndpoints = {},
continuousAnchors = {},
continuousAnchorLocations = {},
userDefinedContinuousAnchorLocations = {},
continuousAnchorOrientations = {},
Orientation = { HORIZONTAL : "horizontal", VERTICAL : "vertical", DIAGONAL : "diagonal", IDENTITY:"identity" },
connectionsByElementId = {},
self = this,
anchorLists = {},
jsPlumbInstance = params.jsPlumbInstance,
jpcl = jsPlumb.CurrentLibrary,
floatingConnections = {},
// TODO this functions uses a crude method of determining orientation between two elements.
// 'diagonal' should be chosen when the angle of the line between the two centers is around
// one of 45, 135, 225 and 315 degrees. maybe +- 15 degrees.
// used by AnchorManager.redraw
calculateOrientation = function(sourceId, targetId, sd, td, sourceAnchor, targetAnchor) {
if (sourceId === targetId) return {
orientation:Orientation.IDENTITY,
a:["top", "top"]
};
var theta = Math.atan2((td.centery - sd.centery) , (td.centerx - sd.centerx)),
theta2 = Math.atan2((sd.centery - td.centery) , (sd.centerx - td.centerx)),
h = ((sd.left <= td.left && sd.right >= td.left) || (sd.left <= td.right && sd.right >= td.right) ||
(sd.left <= td.left && sd.right >= td.right) || (td.left <= sd.left && td.right >= sd.right)),
v = ((sd.top <= td.top && sd.bottom >= td.top) || (sd.top <= td.bottom && sd.bottom >= td.bottom) ||
(sd.top <= td.top && sd.bottom >= td.bottom) || (td.top <= sd.top && td.bottom >= sd.bottom)),
possiblyTranslateEdges = function(edges) {
// this function checks to see if either anchor is Continuous, and if so, runs the suggested edge
// through the anchor: Continuous anchors can say which faces they support, and they get to choose
// whether a certain face is honoured, or, if not, which face to replace it with. the behaviour when
// choosing an alternate face is to try for the opposite face first, then the next one clockwise, and then
// the opposite of that one.
return [
sourceAnchor.isContinuous ? sourceAnchor.verifyEdge(edges[0]) : edges[0],
targetAnchor.isContinuous ? targetAnchor.verifyEdge(edges[1]) : edges[1]
];
},
out = {
orientation:Orientation.DIAGONAL,
theta:theta,
theta2:theta2
};
if (! (h || v)) {
if (td.left > sd.left && td.top > sd.top)
out.a = ["right", "top"];
else if (td.left > sd.left && sd.top > td.top)
out.a = [ "top", "left"];
else if (td.left < sd.left && td.top < sd.top)
out.a = [ "top", "right"];
else if (td.left < sd.left && td.top > sd.top)
out.a = ["left", "top" ];
}
else if (h) {
out.orientation = Orientation.HORIZONTAL;
out.a = sd.top < td.top ? ["bottom", "top"] : ["top", "bottom"];
}
else {
out.orientation = Orientation.VERTICAL;
out.a = sd.left < td.left ? ["right", "left"] : ["left", "right"];
}
out.a = possiblyTranslateEdges(out.a);
return out;
},
// used by placeAnchors function
placeAnchorsOnLine = function(desc, elementDimensions, elementPosition,
connections, horizontal, otherMultiplier, reverse) {
var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
for (var i = 0; i < connections.length; i++) {
var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
if (reverse)
val = elementDimensions[horizontal ? 0 : 1] - val;
var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
}
return a;
},
// used by edgeSortFunctions
currySort = function(reverseAngles) {
return function(a,b) {
var r = true;
if (reverseAngles) {
/*if (a[0][0] < b[0][0])
r = true;
else
r = a[0][1] > b[0][1];*/
r = a[0][0] < b[0][0];
}
else {
/*if (a[0][0] > b[0][0])
r= true;
else
r =a[0][1] > b[0][1];
*/
r = a[0][0] > b[0][0];
}
return r === false ? -1 : 1;
};
},
// used by edgeSortFunctions
leftSort = function(a,b) {
// first get adjusted values
var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
if (p1 > p2) return 1;
else return a[0][1] > b[0][1] ? 1 : -1;
},
// used by placeAnchors
edgeSortFunctions = {
"top":function(a, b) { return a[0] > b[0] ? 1 : -1 },
"right":currySort(true),
"bottom":currySort(true),
"left":leftSort
},
// used by placeAnchors
_sortHelper = function(_array, _fn) { return _array.sort(_fn); },
// used by AnchorManager.redraw
placeAnchors = function(elementId, _anchorLists) {
var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o,
placeSomeAnchors = function(desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) {
if (unsortedConnections.length > 0) {
var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
reverse = desc === "right" || desc === "top",
anchors = placeAnchorsOnLine(desc, elementDimensions,
elementPosition, sc,
isHorizontal, otherMultiplier, reverse );
// takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
var _setAnchorLocation = function(endpoint, anchorPos) {
var a = jsPlumbInstance.adjustForParentOffsetAndScroll([anchorPos[0], anchorPos[1]], endpoint.canvas);
continuousAnchorLocations[endpoint.id] = [ a[0], a[1], anchorPos[2], anchorPos[3] ];
continuousAnchorOrientations[endpoint.id] = orientation;
};
for (var i = 0; i < anchors.length; i++) {
var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
if (weAreSource)
_setAnchorLocation(c.endpoints[0], anchors[i]);
else if (weAreTarget)
_setAnchorLocation(c.endpoints[1], anchors[i]);
}
}
};
placeSomeAnchors("bottom", sS, [sO.left,sO.top], _anchorLists.bottom, true, 1, [0,1]);
placeSomeAnchors("top", sS, [sO.left,sO.top], _anchorLists.top, true, 0, [0,-1]);
placeSomeAnchors("left", sS, [sO.left,sO.top], _anchorLists.left, false, 0, [-1,0]);
placeSomeAnchors("right", sS, [sO.left,sO.top], _anchorLists.right, false, 1, [1,0]);
};
this.reset = function() {
_amEndpoints = {};
connectionsByElementId = {};
anchorLists = {};
};
this.addFloatingConnection = function(key, conn) {
floatingConnections[key] = conn;
};
this.removeFloatingConnection = function(key) {
delete floatingConnections[key];
};
this.newConnection = function(conn) {
var sourceId = conn.sourceId, targetId = conn.targetId,
ep = conn.endpoints,
doRegisterTarget = true,
registerConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) {
if ((sourceId == targetId) && otherAnchor.isContinuous){
// remove the target endpoint's canvas. we dont need it.
jpcl.removeElement(ep[1].canvas);
doRegisterTarget = false;
}
jsPlumbUtil.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor == jsPlumb.DynamicAnchor]);
};
registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
if (doRegisterTarget)
registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
};
var removeEndpointFromAnchorLists = function(endpoint) {
(function(list, eId) {
if (list) { // transient anchors dont get entries in this list.
var f = function(e) { return e[4] == eId; };
jsPlumbUtil.removeWithFunction(list["top"], f);
jsPlumbUtil.removeWithFunction(list["left"], f);
jsPlumbUtil.removeWithFunction(list["bottom"], f);
jsPlumbUtil.removeWithFunction(list["right"], f);
}
})(anchorLists[endpoint.elementId], endpoint.id);
};
this.connectionDetached = function(connInfo) {
var connection = connInfo.connection || connInfo,
sourceId = connInfo.sourceId,
targetId = connInfo.targetId,
ep = connection.endpoints,
removeConnection = function(otherIndex, otherEndpoint, otherAnchor, elId, c) {
if (otherAnchor.constructor == jsPlumb.FloatingAnchor) {
// no-op
}
else {
jsPlumbUtil.removeWithFunction(connectionsByElementId[elId], function(_c) {
return _c[0].id == c.id;
});
}
};
removeConnection(1, ep[1], ep[1].anchor, sourceId, connection);
removeConnection(0, ep[0], ep[0].anchor, targetId, connection);
// remove from anchorLists
removeEndpointFromAnchorLists(connection.endpoints[0]);
removeEndpointFromAnchorLists(connection.endpoints[1]);
self.redraw(connection.sourceId);
self.redraw(connection.targetId);
};
this.add = function(endpoint, elementId) {
jsPlumbUtil.addToList(_amEndpoints, elementId, endpoint);
};
this.changeId = function(oldId, newId) {
connectionsByElementId[newId] = connectionsByElementId[oldId];
_amEndpoints[newId] = _amEndpoints[oldId];
delete connectionsByElementId[oldId];
delete _amEndpoints[oldId];
};
this.getConnectionsFor = function(elementId) {
return connectionsByElementId[elementId] || [];
};
this.getEndpointsFor = function(elementId) {
return _amEndpoints[elementId] || [];
};
this.deleteEndpoint = function(endpoint) {
jsPlumbUtil.removeWithFunction(_amEndpoints[endpoint.elementId], function(e) {
return e.id == endpoint.id;
});
removeEndpointFromAnchorLists(endpoint);
};
this.clearFor = function(elementId) {
delete _amEndpoints[elementId];
_amEndpoints[elementId] = [];
};
// updates the given anchor list by either updating an existing anchor's info, or adding it. this function
// also removes the anchor from its previous list, if the edge it is on has changed.
// all connections found along the way (those that are connected to one of the faces this function
// operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
// them wthout having to calculate anything else about them.
var _updateAnchorList = function(lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
// first try to find the exact match, but keep track of the first index of a matching element id along the way.s
var exactIdx = -1,
firstMatchingElIdx = -1,
endpoint = conn.endpoints[idx],
endpointId = endpoint.id,
oIdx = [1,0][idx],
values = [ [ theta, order ], conn, aBoolean, otherElId, endpointId ],
listToAddTo = lists[edgeId],
listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null;
if (listToRemoveFrom) {
var rIdx = jsPlumbUtil.findWithFunction(listToRemoveFrom, function(e) { return e[4] == endpointId });
if (rIdx != -1) {
listToRemoveFrom.splice(rIdx, 1);
// get all connections from this list
for (var i = 0; i < listToRemoveFrom.length; i++) {
jsPlumbUtil.addWithFunction(connsToPaint, listToRemoveFrom[i][1], function(c) { return c.id == listToRemoveFrom[i][1].id });
jsPlumbUtil.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function(e) { return e.id == listToRemoveFrom[i][1].endpoints[idx].id });
jsPlumbUtil.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function(e) { return e.id == listToRemoveFrom[i][1].endpoints[oIdx].id });
}
}
}
for (var i = 0; i < listToAddTo.length; i++) {
if (params.idx == 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx == -1)
firstMatchingElIdx = i;
jsPlumbUtil.addWithFunction(connsToPaint, listToAddTo[i][1], function(c) { return c.id == listToAddTo[i][1].id });
jsPlumbUtil.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function(e) { return e.id == listToAddTo[i][1].endpoints[idx].id });
jsPlumbUtil.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function(e) { return e.id == listToAddTo[i][1].endpoints[oIdx].id });
}
if (exactIdx != -1) {
listToAddTo[exactIdx] = values;
}
else {
var insertIdx = reverse ? firstMatchingElIdx != -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
listToAddTo.splice(insertIdx, 0, values);
}
// store this for next time.
endpoint._continuousAnchorEdge = edgeId;
};
this.redraw = function(elementId, ui, timestamp, offsetToUI, clearEdits) {
if (!jsPlumbInstance.isSuspendDrawing()) {
// get all the endpoints for this element
var ep = _amEndpoints[elementId] || [],
endpointConnections = connectionsByElementId[elementId] || [],
connectionsToPaint = [],
endpointsToPaint = [],
anchorsToUpdate = [];
timestamp = timestamp || jsPlumbInstance.timestamp();
// offsetToUI are values that would have been calculated in the dragManager when registering
// an endpoint for an element that had a parent (somewhere in the hierarchy) that had been
// registered as draggable.
offsetToUI = offsetToUI || {left:0, top:0};
if (ui) {
ui = {
left:ui.left + offsetToUI.left,
top:ui.top + offsetToUI.top
}
}
// valid for one paint cycle.
var myOffset = jsPlumbInstance.updateOffset( { elId : elementId, offset : ui, recalc : false, timestamp : timestamp }),
orientationCache = {};
// actually, first we should compute the orientation of this element to all other elements to which
// this element is connected with a continuous anchor (whether both ends of the connection have
// a continuous anchor or just one)
for (var i = 0; i < endpointConnections.length; i++) {
var conn = endpointConnections[i][0],
sourceId = conn.sourceId,
targetId = conn.targetId,
sourceContinuous = conn.endpoints[0].anchor.isContinuous,
targetContinuous = conn.endpoints[1].anchor.isContinuous;
if (sourceContinuous || targetContinuous) {
var oKey = sourceId + "_" + targetId,
oKey2 = targetId + "_" + sourceId,
o = orientationCache[oKey],
oIdx = conn.sourceId == elementId ? 1 : 0;
if (sourceContinuous && !anchorLists[sourceId]) anchorLists[sourceId] = { top:[], right:[], bottom:[], left:[] };
if (targetContinuous && !anchorLists[targetId]) anchorLists[targetId] = { top:[], right:[], bottom:[], left:[] };
if (elementId != targetId) jsPlumbInstance.updateOffset( { elId : targetId, timestamp : timestamp });
if (elementId != sourceId) jsPlumbInstance.updateOffset( { elId : sourceId, timestamp : timestamp });
var td = jsPlumbInstance.getCachedData(targetId),
sd = jsPlumbInstance.getCachedData(sourceId);
if (targetId == sourceId && (sourceContinuous || targetContinuous)) {
// here we may want to improve this by somehow determining the face we'd like
// to put the connector on. ideally, when drawing, the face should be calculated
// by determining which face is closest to the point at which the mouse button
// was released. for now, we're putting it on the top face.
_updateAnchorList(
anchorLists[sourceId],
-Math.PI / 2,
0,
conn,
false,
targetId,
0, false, "top", sourceId, connectionsToPaint, endpointsToPaint);
}
else {
if (!o) {
o = calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor);
orientationCache[oKey] = o;
// this would be a performance enhancement, but the computed angles need to be clamped to
//the (-PI/2 -> PI/2) range in order for the sorting to work properly.
/* orientationCache[oKey2] = {
orientation:o.orientation,
a:[o.a[1], o.a[0]],
theta:o.theta + Math.PI,
theta2:o.theta2 + Math.PI
};*/
}
if (sourceContinuous) _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
if (targetContinuous) _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
}
if (sourceContinuous) jsPlumbUtil.addWithFunction(anchorsToUpdate, sourceId, function(a) { return a === sourceId; });
if (targetContinuous) jsPlumbUtil.addWithFunction(anchorsToUpdate, targetId, function(a) { return a === targetId; });
jsPlumbUtil.addWithFunction(connectionsToPaint, conn, function(c) { return c.id == conn.id; });
if ((sourceContinuous && oIdx == 0) || (targetContinuous && oIdx == 1))
jsPlumbUtil.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function(e) { return e.id == conn.endpoints[oIdx].id; });
}
}
// place Endpoints whose anchors are continuous but have no Connections
for (var i = 0; i < ep.length; i++) {
if (ep[i].connections.length == 0 && ep[i].anchor.isContinuous) {
if (!anchorLists[elementId]) anchorLists[elementId] = { top:[], right:[], bottom:[], left:[] };
_updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints:[ep[i], ep[i]], paint:function(){}}, false, elementId, 0, false, "top", elementId, connectionsToPaint, endpointsToPaint)
jsPlumbUtil.addWithFunction(anchorsToUpdate, elementId, function(a) { return a === elementId; })
}
}
// now place all the continuous anchors we need to;
for (var i = 0; i < anchorsToUpdate.length; i++) {
placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]);
}
// now that continuous anchors have been placed, paint all the endpoints for this element
// TODO performance: add the endpoint ids to a temp array, and then when iterating in the next
// loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way.
for (var i = 0; i < ep.length; i++) {
ep[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myOffset.s });
}
// ... and any other endpoints we came across as a result of the continuous anchors.
for (var i = 0; i < endpointsToPaint.length; i++) {
var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId);
endpointsToPaint[i].paint( { timestamp : timestamp, offset : cd, dimensions : cd.s });
}
// paint all the standard and "dynamic connections", which are connections whose other anchor is
// static and therefore does need to be recomputed; we make sure that happens only one time.
// TODO we could have compiled a list of these in the first pass through connections; might save some time.
for (var i = 0; i < endpointConnections.length; i++) {
var otherEndpoint = endpointConnections[i][1];
if (otherEndpoint.anchor.constructor == jsPlumb.DynamicAnchor) {
otherEndpoint.paint({ elementWithPrecedence:elementId });
jsPlumbUtil.addWithFunction(connectionsToPaint, endpointConnections[i][0], function(c) { return c.id == endpointConnections[i][0].id; });
// all the connections for the other endpoint now need to be repainted
for (var k = 0; k < otherEndpoint.connections.length; k++) {
if (otherEndpoint.connections[k] !== endpointConnections[i][0])
jsPlumbUtil.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function(c) { return c.id == otherEndpoint.connections[k].id; });
}
} else if (otherEndpoint.anchor.constructor == jsPlumb.Anchor) {
jsPlumbUtil.addWithFunction(connectionsToPaint, endpointConnections[i][0], function(c) { return c.id == endpointConnections[i][0].id; });
}
}
// paint current floating connection for this element, if there is one.
var fc = floatingConnections[elementId];
if (fc)
fc.paint({timestamp:timestamp, recalc:false, elId:elementId});
// paint all the connections
for (var i = 0; i < connectionsToPaint.length; i++) {
connectionsToPaint[i].paint({elId:elementId, timestamp:timestamp, recalc:false, clearEdits:clearEdits});
}
}
};
this.rehomeEndpoint = function(currentId, element) {
var eps = _amEndpoints[currentId] || [],
elementId = jsPlumbInstance.getId(element);
if (elementId !== currentId) {
for (var i = 0; i < eps.length; i++) {
self.add(eps[i], elementId);
}
eps.splice(0, eps.length);
}
};
var ContinuousAnchor = function(anchorParams) {
jsPlumbUtil.EventGenerator.apply(this);
this.type = "Continuous";
this.isDynamic = true;
this.isContinuous = true;
var faces = anchorParams.faces || ["top", "right", "bottom", "left"],
clockwise = !(anchorParams.clockwise === false),
availableFaces = { },
opposites = { "top":"bottom", "right":"left","left":"right","bottom":"top" },
clockwiseOptions = { "top":"right", "right":"bottom","left":"top","bottom":"left" },
antiClockwiseOptions = { "top":"left", "right":"top","left":"bottom","bottom":"right" },
secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions,
lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions,
cssClass = anchorParams.cssClass || "";
for (var i = 0; i < faces.length; i++) { availableFaces[faces[i]] = true; }
// if the given edge is suported, returns it. otherwise looks for a substitute that _is_
// supported. if none supported we also return the request edge.
this.verifyEdge = function(edge) {
if (availableFaces[edge]) return edge;
else if (availableFaces[opposites[edge]]) return opposites[edge];
else if (availableFaces[secondBest[edge]]) return secondBest[edge];
else if (availableFaces[lastChoice[edge]]) return lastChoice[edge];
return edge; // we have to give them something.
};
this.compute = function(params) {
return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0,0];
};
this.getCurrentLocation = function(endpoint) {
return userDefinedContinuousAnchorLocations[endpoint.id] || continuousAnchorLocations[endpoint.id] || [0,0];
};
this.getOrientation = function(endpoint) {
return continuousAnchorOrientations[endpoint.id] || [0,0];
};
this.clearUserDefinedLocation = function() {
delete userDefinedContinuousAnchorLocations[anchorParams.elementId];
};
this.setUserDefinedLocation = function(loc) {
userDefinedContinuousAnchorLocations[anchorParams.elementId] = loc;
};
this.getCssClass = function() { return cssClass; };
this.setCssClass = function(c) { cssClass = c; };
};
// continuous anchors
jsPlumbInstance.continuousAnchorFactory = {
get:function(params) {
var existing = continuousAnchors[params.elementId];
if (!existing) {
existing = new ContinuousAnchor(params);
continuousAnchors[params.elementId] = existing;
}
return existing;
}
};
};
/**
* Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user
* was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"),
* or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the
* creation of Anchors without user intervention.
*/
jsPlumb.Anchor = function(params) {
var self = this;
this.x = params.x || 0;
this.y = params.y || 0;
this.elementId = params.elementId;
jsPlumbUtil.EventGenerator.apply(this);
var orientation = params.orientation || [ 0, 0 ],
jsPlumbInstance = params.jsPlumbInstance,
lastTimestamp = null, lastReturnValue = null, userDefinedLocation = null,
cssClass = params.cssClass || "";
this.getCssClass = function() { return cssClass; };
this.offsets = params.offsets || [ 0, 0 ];
self.timestamp = null;
this.compute = function(params) {
var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
if(params.clearUserDefinedLocation)
userDefinedLocation = null;
if (timestamp && timestamp === self.timestamp)
return lastReturnValue;
if (userDefinedLocation != null) {
lastReturnValue = userDefinedLocation;
}
else {
lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
// adjust loc if there is an offsetParent
lastReturnValue = jsPlumbInstance.adjustForParentOffsetAndScroll(lastReturnValue, element.canvas);
}
self.timestamp = timestamp;
return lastReturnValue;
};
this.getOrientation = function(_endpoint) { return orientation; };
this.equals = function(anchor) {
if (!anchor) return false;
var ao = anchor.getOrientation();
var o = this.getOrientation();
return this.x == anchor.x && this.y == anchor.y
&& this.offsets[0] == anchor.offsets[0]
&& this.offsets[1] == anchor.offsets[1]
&& o[0] == ao[0] && o[1] == ao[1];
};
this.getCurrentLocation = function() { return lastReturnValue; };
this.getUserDefinedLocation = function() {
return userDefinedLocation;
};
this.setUserDefinedLocation = function(l) {
userDefinedLocation = l;
};
this.clearUserDefinedLocation = function() {
userDefinedLocation = null;
};
};
/**
* An Anchor that floats. its orientation is computed dynamically from
* its position relative to the anchor it is floating relative to. It is used when creating
* a connection through drag and drop.
*
* TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
*/
jsPlumb.FloatingAnchor = function(params) {
jsPlumb.Anchor.apply(this, arguments);
// this is the anchor that this floating anchor is referenced to for
// purposes of calculating the orientation.
var ref = params.reference,
jpcl = jsPlumb.CurrentLibrary,
jsPlumbInstance = params.jsPlumbInstance,
// the canvas this refers to.
refCanvas = params.referenceCanvas,
size = jpcl.getSize(jpcl.getElementObject(refCanvas)),
// these are used to store the current relative position of our
// anchor wrt the reference anchor. they only indicate
// direction, so have a value of 1 or -1 (or, very rarely, 0). these
// values are written by the compute method, and read
// by the getOrientation method.
xDir = 0, yDir = 0,
// temporary member used to store an orientation when the floating
// anchor is hovering over another anchor.
orientation = null,
_lastResult = null;
// set these to 0 each; they are used by certain types of connectors in the loopback case,
// when the connector is trying to clear the element it is on. but for floating anchor it's not
// very important.
this.x = 0; this.y = 0;
this.isFloating = true;
this.compute = function(params) {
var xy = params.xy, element = params.element,
result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
// adjust loc if there is an offsetParent
result = jsPlumbInstance.adjustForParentOffsetAndScroll(result, element.canvas);
_lastResult = result;
return result;
};
this.getOrientation = function(_endpoint) {
if (orientation) return orientation;
else {
var o = ref.getOrientation(_endpoint);
// here we take into account the orientation of the other
// anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
// up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
return [ Math.abs(o[0]) * xDir * -1,
Math.abs(o[1]) * yDir * -1 ];
}
};
/**
* notification the endpoint associated with this anchor is hovering
* over another anchor; we want to assume that anchor's orientation
* for the duration of the hover.
*/
this.over = function(anchor) {
orientation = anchor.getOrientation();
};
/**
* notification the endpoint associated with this anchor is no
* longer hovering over another anchor; we should resume calculating
* orientation as we normally do.
*/
this.out = function() { orientation = null; };
this.getCurrentLocation = function() { return _lastResult; };
};
/*
* A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
* through at compute time to find the one that is located closest to
* the center of the target element, and returns that Anchor's compute
* method result. this causes endpoints to follow each other with
* respect to the orientation of their target elements, which is a useful
* feature for some applications.
*
*/
jsPlumb.DynamicAnchor = function(params) {
jsPlumb.Anchor.apply(this, arguments);
this.isSelective = true;
this.isDynamic = true;
var _anchors = [], self = this,
_convert = function(anchor) {
return anchor.constructor == jsPlumb.Anchor ? anchor: params.jsPlumbInstance.makeAnchor(anchor, params.elementId, params.jsPlumbInstance);
};
for (var i = 0; i < params.anchors.length; i++)
_anchors[i] = _convert(params.anchors[i]);
this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
this.getAnchors = function() { return _anchors; };
this.locked = false;
var _curAnchor = _anchors.length > 0 ? _anchors[0] : null,
_curIndex = _anchors.length > 0 ? 0 : -1,
_lastAnchor = _curAnchor,
self = this,
// helper method to calculate the distance between the centers of the two elements.
_distance = function(anchor, cx, cy, xy, wh) {
var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]),
acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2);
return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) +
Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2)));
},
// default method uses distance between element centers. you can provide your own method in the dynamic anchor
// constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
// xy - xy loc of the anchor's element
// wh - anchor's element's dimensions
// txy - xy loc of the element of the other anchor in the connection
// twh - dimensions of the element of the other anchor in the connection.
// anchors - the list of selectable anchors
_anchorSelector = params.selector || function(xy, wh, txy, twh, anchors) {
var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
var minIdx = -1, minDist = Infinity;
for ( var i = 0; i < anchors.length; i++) {
var d = _distance(anchors[i], cx, cy, xy, wh);
if (d < minDist) {
minIdx = i + 0;
minDist = d;
}
}
return anchors[minIdx];
};
this.compute = function(params) {
var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
if(params.clearUserDefinedLocation)
userDefinedLocation = null;
var udl = self.getUserDefinedLocation();
if (udl != null) {
return udl;
}
// if anchor is locked or an opposite element was not given, we
// maintain our state. anchor will be locked
// if it is the source of a drag and drop.
if (self.locked || txy == null || twh == null)
return _curAnchor.compute(params);
else
params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
_curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
self.x = _curAnchor.x;
self.y = _curAnchor.y;
if (_curAnchor != _lastAnchor)
self.fire("anchorChanged", _curAnchor);
_lastAnchor = _curAnchor;
return _curAnchor.compute(params);
};
this.getCurrentLocation = function() {
return self.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation() : null);
};
this.getOrientation = function(_endpoint) { return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ]; };
this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
this.getCssClass = function() { return (_curAnchor && _curAnchor.getCssClass()) || ""; };
};
// -------- basic anchors ------------------
var _curryAnchor = function(x, y, ox, oy, type, fnInit) {
jsPlumb.Anchors[type] = function(params) {
var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
a.type = type;
if (fnInit) fnInit(a, params);
return a;
};
};
_curryAnchor(0.5, 0, 0,-1, "TopCenter");
_curryAnchor(0.5, 1, 0, 1, "BottomCenter");
_curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
_curryAnchor(1, 0.5, 1, 0, "RightMiddle");
// from 1.4.1: Top, Right, Bottom, Left
_curryAnchor(0.5, 0, 0,-1, "Top");
_curryAnchor(0.5, 1, 0, 1, "Bottom");
_curryAnchor(0, 0.5, -1, 0, "Left");
_curryAnchor(1, 0.5, 1, 0, "Right");
_curryAnchor(0.5, 0.5, 0, 0, "Center");
_curryAnchor(1, 0, 0,-1, "TopRight");
_curryAnchor(1, 1, 0, 1, "BottomRight");
_curryAnchor(0, 0, 0, -1, "TopLeft");
_curryAnchor(0, 1, 0, 1, "BottomLeft");
// ------- dynamic anchors -------------------
// default dynamic anchors chooses from Top, Right, Bottom, Left
jsPlumb.Defaults.DynamicAnchors = function(params) {
return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
};
// default dynamic anchors bound to name 'AutoDefault'
jsPlumb.Anchors["AutoDefault"] = function(params) {
var a = params.jsPlumbInstance.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors(params));
a.type = "AutoDefault";
return a;
};
// ------- continuous anchors -------------------
var _curryContinuousAnchor = function(type, faces) {
jsPlumb.Anchors[type] = function(params) {
var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces:faces }], params.elementId, params.jsPlumbInstance);
a.type = type;
return a;
};
};
jsPlumb.Anchors["Continuous"] = function(params) {
return params.jsPlumbInstance.continuousAnchorFactory.get(params);
};
_curryContinuousAnchor("ContinuousLeft", ["left"]);
_curryContinuousAnchor("ContinuousTop", ["top"]);
_curryContinuousAnchor("ContinuousBottom", ["bottom"]);
_curryContinuousAnchor("ContinuousRight", ["right"]);
// ------- position assign anchors -------------------
// this anchor type lets you assign the position at connection time.
jsPlumb.Anchors["Assign"] = _curryAnchor(0, 0, 0, 0, "Assign", function(anchor, params) {
// find what to use as the "position finder". the user may have supplied a String which represents
// the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
// position finder as a function. we find out what to use and then set it on the anchor.
var pf = params.position || "Fixed";
anchor.positionFinder = pf.constructor == String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf;
// always set the constructor params; the position finder might need them later (the Grid one does,
// for example)
anchor.constructorParams = params;
});
// these are the default anchor positions finders, which are used by the makeTarget function. supplying
// a position finder argument to that function allows you to specify where the resulting anchor will
// be located
jsPlumb.AnchorPositionFinders = {
"Fixed": function(dp, ep, es, params) {
return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
},
"Grid":function(dp, ep, es, params) {
var dx = dp.left - ep.left, dy = dp.top - ep.top,
gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]),
mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
}
};
// ------- perimeter anchors -------------------
jsPlumb.Anchors["Perimeter"] = function(params) {
params = params || {};
var anchorCount = params.anchorCount || 60,
shape = params.shape;
if (!shape) throw new Error("no shape supplied to Perimeter Anchor type");
var _circle = function() {
var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = [];
for (var i = 0; i < anchorCount; i++) {
var x = r + (r * Math.sin(current)),
y = r + (r * Math.cos(current));
a.push( [ x, y, 0, 0 ] );
current += step;
}
return a;
},
_path = function(segments) {
var anchorsPerFace = anchorCount / segments.length, a = [],
_computeFace = function(x1, y1, x2, y2, fractionalLength) {
anchorsPerFace = anchorCount * fractionalLength;
var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace;
for (var i = 0; i < anchorsPerFace; i++) {
a.push( [
x1 + (dx * i),
y1 + (dy * i),
0,
0
]);
}
};
for (var i = 0; i < segments.length; i++)
_computeFace.apply(null, segments[i]);
return a;
},
_shape = function(faces) {
var s = [];
for (var i = 0; i < faces.length; i++) {
s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]);
}
return _path(s);
},
_rectangle = function() {
return _shape([
[ 0, 0, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ]
]);
};
var _shapes = {
"Circle":_circle,
"Ellipse":_circle,
"Diamond":function() {
return _shape([
[ 0.5, 0, 1, 0.5 ], [ 1, 0.5, 0.5, 1 ], [ 0.5, 1, 0, 0.5 ], [ 0, 0.5, 0.5, 0 ]
]);
},
"Rectangle":_rectangle,
"Square":_rectangle,
"Triangle":function() {
return _shape([
[ 0.5, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0.5, 0]
]);
},
"Path":function(params) {
var points = params.points, p = [], tl = 0;
for (var i = 0; i < points.length - 1; i++) {
var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1]));
tl += l;
p.push([points[i][0], points[i][1], points[i+1][0], points[i+1][1], l]);
}
for (var i = 0; i < p.length; i++) {
p[i][4] = p[i][4] / tl;
}
return _path(p);
}
},
_rotate = function(points, amountInDegrees) {
var o = [], theta = amountInDegrees / 180 * Math.PI ;
for (var i = 0; i < points.length; i++) {
var _x = points[i][0] - 0.5,
_y = points[i][1] - 0.5;
o.push([
0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))),
0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))),
points[i][2],
points[i][3]
]);
}
return o;
};
if (!_shapes[shape]) throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type");
var da = _shapes[shape](params);
if (params.rotation) da = _rotate(da, params.rotation);
var a = params.jsPlumbInstance.makeDynamicAnchor(da);
a.type = "Perimeter";
return a;
};
})();
\ No newline at end of file
// ---------------- JSPLUMB ----------------------------------------
/**
* Class: jsPlumb
* The jsPlumb engine, of which there is one instance registered as a static object in the window. You
* can use the jsPlumb.getInstance function to get a new instance of jsPlumb. This object contains all of the methods you will use to create and maintain Connections and Endpoints.
*/
/*
* Function: bind(event, callback)
* Bind to an event on jsPlumb.
*
* Parameters:
* event - the event to bind. Available events on jsPlumb are:
* - *connection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
* - *connectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
* - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
* - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
* - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
* - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
* - *beforeDrop* : notification that a Connection is about to be dropped. Returning false from this method cancels the drop. jsPlumb passes { sourceId, targetId, scope, connection, dropEndpoint } to your callback. For more information, refer to the jsPlumb documentation.
* - *beforeDetach* : notification that a Connection is about to be detached. Returning false from this method cancels the detach. jsPlumb passes the Connection to your callback. For more information, refer to the jsPlumb documentation.
* - *connectionDrag* : notification that an existing Connection is being dragged. jsPlumb passes the Connection to your callback function.
* - *connectionDragStop* : notification that the drag of an existing Connection has ended. jsPlumb passes the Connection to your callback function.
*
* callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
*/
/*
* Function: importDefaults(defaults)
* Imports all the given defaults into this instance of jsPlumb.
*
* Parameters:
* defaults - The defaults to import
*/
/*
* Function: restoreDefaults()
* Restores the default settings to "factory" values.
*/
/*
* Function: unbind([event])
* Clears either all listeners, or listeners for some specific event.
*
* Parameters:
* event - optional. constrains the clear to just listeners for this event.
*/
/*
* Function: addClass(el, clazz)
* Add class(es) to some element(s).
*
* Parameters:
* el - element id, dom element, or selector representing the element(s) to add class(es) to.
* clazz - string representing the class(es) to add. may contain multiple classes separated by spaces.
*/
/*
* Function: registerConnectionType(typeId, type)
* Registers the given connection type on this instance of jsPlumb.
*
* Parameters:
* typeId - id of the type
* type - a JS object containing the type specifications.
*/
/*
* Function: registerConnectionTypes(types)
* Registers the given map of Connection types on this instance of jsPlumb.
*
* Parameters:
* types - a JS object whose keys are type ids and whose values are type specifications.
*/
/*
* Function: registerEndpointType(typeId, type)
* Registers the given endpoint type on this instance of jsPlumb.
*
* Parameters:
* typeId - id of the type
* type - a JS object containing the type specifications.
*/
/*
* Function: getType(id, typeDescriptor)
* Gets the given type's specification.
*
* Parameters:
* id - id of the type to retrieve
* typeDescriptor - "endpoint" or "connection"
*/
/*
* Function: getInstanceIndex()
* Returns:
* The "instance index" for this instance of jsPlumb. Probably not something you will need very often.
*/
/*
* Function: registerEndpointTypes(types)
* Registers the given map of Endpoint types on this instance of jsPlumb.
*
* Parameters:
* types - a JS object whose keys are type ids and whose values are type specifications.
*/
/*
* Function: removeClass(el, clazz)
* Remove class from some element(s).
*
* Parameters:
* el - element id, dom element, or selector representing the element(s) to remove a class from.
* clazz - string representing the class to remove.
*/
/*
* Function: hasClass(el, clazz)
* Checks if an element has some class.
*
* Parameters:
* el - element id, dom element, or selector representing the element to test. If the selector matches multiple elements, we return the test for the first element in the selector only.
* clazz - string representing the class to test for.
*/
/*
Function: addEndpoint (el, [params], [referenceParams])
Adds an <Endpoint> to a given element or elements.
Parameters:
el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
this object are anything that 'params' can contain. See <Endpoint>.
Returns:
The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
See Also:
<addEndpoints>
*/
/*
Function: addEndpoints(target, endpoints, [referenceParams])
Adds a list of <Endpoint>s to a given element or elements.
Parameters:
target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some shared parameters that you wanted to reuse when you added Endpoints to a number of elements.
Returns:
List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
See Also:
<addEndpoint>
*/
/*
Function: animate
This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
the 'step' function if necessary). This only supports the two-arg version of the animate call in jQuery, the one that takes an 'options' object as
the second arg. MooTools has only one method, a two arg one. Which is handy. YUI has a one-arg method, so jsPlumb merges 'properties' and 'options' together for YUI.
Parameters:
el - Element to animate. Either an id, or a selector representing the element.
properties - The 'properties' argument you want passed to the library's animate call.
options - The 'options' argument you want passed to the library's animate call.
*/
/*
Function: connect (params, [referenceParams])
Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
Parameters:
params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
Returns:
The newly created <Connection>.
*/
/*
Function: deleteEndpoint(object)
Deletes an <Endpoint> and removes all <Connection>s it has (which removes the Connections from the other Endpoints involved too)
Parameters:
object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
Returns:
The jsPlumb instance
*/
/*
Function: deleteEveryEndpoint()
Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
between this method and jsPlumb.reset).
Returns:
The jsPlumb instance
*/
/*
Function: detach(connection, [params])
Detaches and then removes a <Connection>.
Parameters:
connection - the <Connection> to detach
params - optional parameters to the detach call. valid values here are
fireEvent : defaults to false; indicates you want jsPlumb to fire a connection
detached event. The thinking behind this is that if you made a programmatic
call to detach an event, you probably don't need the callback.
forceDetach : defaults to false. allows you to override any beforeDetach listeners that may be registered.
Returns:
true if successful, false if not.
*/
/*
Function: detachAllConnections(el, [params])
Removes all an element's Connections.
Parameters:
el - either the id of the element, or a selector for the element.
params - optional parameters. alowed values:
fireEvent : defaults to true, whether or not to fire the detach event.
Returns:
The jsPlumb instance.
*/
/*
Function: detachEveryConnection([params])
Remove all Connections from all elements, but leaves Endpoints in place.
Parameters:
params - optional params object containing:
fireEvent : whether or not to fire detach events. defaults to true.
Returns:
The jsPlumbInstance
See Also:
<deleteEveryEndpoint>
*/
/*
Function: draggable(el, [options])
Initialises the draggability of some element or elements. You should use this instead of your
library's draggable method so that jsPlumb can setup the appropriate callbacks. Your
underlying library's drag method is always called from this method.
Parameters:
el - either an element id, a list of element ids, or a selector.
options - options to pass through to the underlying library
Returns:
The jsPlumb instance.
*/
/*
Function: extend(o1, o2)
Wraps the underlying library's extend functionality.
Parameters:
o1 - object to extend
o2 - object to extend o1 with
Returns:
o1, extended with all properties from o2.
*/
/*
* Function: getDefaultEndpointType()
* Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
* you would make a call like this in your class's constructor:
*
* : jsPlumb.getDefaultEndpointType().apply(this, arguments);
*
*
* Returns:
* the default Endpoint function used by jsPlumb.
*/
/*
* Function: getDefaultConnectionType()
* Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
* you would make a call like this in your class's constructor:
*
* : jsPlumb.getDefaultConnectionType().apply(this, arguments);
*
* Returns:
* the default Connection function used by jsPlumb.
*/
/*
* Function: getConnections(params)
* Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
* the result will be a list of connections having that scope (passing in no scope at all will result in jsPlumb assuming you want the
* default scope).
*
* If multiple scopes are passed in, the return value will be a map of
*
* : { scope -> [ connection... ] }
*
* Parameters:
* scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
* of connections that are in the given scope. use '*' for all scopes.
* options - if the argument is a JS object, you can specify a finer-grained filter:
*
* - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes. Also may have the value '*', indicating any scope.
* - *source* either a string representing an element id, a selector, or an array of ids. Also may have the value '*', indicating any source. Constrains the result to connections having this/these element(s) as source.
* - *target* either a string representing an element id, a selector, or an array of ids. Also may have the value '*', indicating any target. Constrains the result to connections having this/these element(s) as target.
* flat - return results in a flat array (don't return an object whose keys are scopes and whose values are lists per scope).
*
* Returns:
* If only one scope was requested, a list of Connections that match the criteria. Otherwise, a map of [scope->connection lists].
*/
/*
* Function: select(params)
* Selects a set of Connections, using the filter options from the getConnections method, and returns an object
* that allows you to perform an operation on all of the Connections at once.
*
* The return value from any of these operations is the original list of Connections, allowing operations to be
* chained (for 'setter' type operations). 'getter' type operations return an array of values, where each entry is
* of the form:
*
* : [ Connection, return value ]
*
* Parameters:
* scope - see getConnections
* source - see getConnections
* target - see getConnections
* connections - an existing list of Connections. If you supply this, 'source' and 'target' will be ignored.
*
* Returns:
* A list of Connections on which operations may be executed. 'Setter' type operations can be chained; 'getter' type operations
* return an array of [Connection, value] pairs, one entry for each Connection in the list returned. The full list of operations
* is as follows (where not specified, the operation's effect or return value is the same as the corresponding method on Connection) :
*
* - addClass
* - addOverlay
* - addType
* - detach : detaches all the connections in the list. not chainable and does not return anything.
* - each(function(connection)...) : allows you to specify your own function to execute; this function is chainable.
* - get(index) : returns the Connection at 'index' in the list.
* - getHoverPaintStyle
* - getLabel
* - getOverlay
* - getPaintStyle
* - getParameter
* - getParameters
* - getType
* - getZIndex
* - hasType
* - hideOverlay
* - hideOverlays
* - isDetachable
* - isHover
* - isReattach
* - isVisible
* - length : returns the length of the list.
* - removeAllOverlays
* - removeClass
* - removeOverlay
* - removeOverlays
* - removeType
* - repaint
* - setConnector
* - setDetachable
* - setHover
* - setHoverPaintStyle
* - setLabel
* - setPaintStyle
* - setParameter
* - setParameters
* - setReattach
* - setType
* - showOverlay
* - showOverlays
*/
/*
* Function: selectEndpoints(params)
* Selects a set of Endpoints and returns an object that allows you to execute various different methods on them at once. The return
* value from any of these operations is the original list of Endpoints, allowing operations to be chained (for 'setter' type
* operations). 'getter' type operations return an array of values, where each entry is of the form:
*
* : [ Endpoint, return value ]
*
* Parameters:
* scope - either a string or an array of strings.
* source - either a string, a dom element, or a selector, or an array of any mix of these. limits returned endpoints to those that are declared as a source endpoint on any elements identified.
* target - either a string, a dom element, or a selector, or an array of any mix of these. limits returned endpoints to those that are declared as a target endpoint on any elements identified.
* element - either a string, a dom element, or a selector, or an array of any mix of these. limits returned endpoints to those that are declared as either a source OR a target endpoint on any elements identified.
*
* Returns:
* A list of Endpoints on which operations may be executed. 'Setter' type operations can be chained; 'getter' type operations
* return an array of [Endpoint, value] pairs, one entry for each Endpoint in the list returned.
*
* The full list of operations is as follows (where not specified, the operation's effect or return value is the
* same as the corresponding method on Endpoint) :
*
* - setHover
* - removeAllOverlays
* - setLabel
* - addClass
* - addOverlay
* - removeClass
* - removeOverlay
* - removeOverlays
* - showOverlay
* - hideOverlay
* - showOverlays
* - hideOverlays
* - setPaintStyle
* - setHoverPaintStyle
* - setParameter
* - setParameters
* - setAnchor
* - getLabel
* - getOverlay
* - isHover
* - isDetachable
* - getParameter
* - getParameters
* - getPaintStyle
* - getHoverPaintStyle
* - detachAll : Detaches all the Connections from every Endpoint in the list. not chainable and does not return anything.
* - delete : Deletes every Endpoint in the list. not chainable and does not return anything.
* - length : returns the length of the list.
* - get(index) : returns the Endpoint at 'index' in the list.
* - each(function(endpoint)...) : allows you to specify your own function to execute; this function is chainable.
*/
/*
* Property: Defaults
*
* These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
* to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
* by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
*
* Properties:
* - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
* - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
* - *ConnectionsDetachable* Whether or not connections are detachable by default (using the mouse). Defaults to true.
* - *ConnectionOverlays* The default overlay definitions for Connections. Defaults to an empty list.
* - *Connector* The default connector definition to use for all connections. Default is "Bezier".
* - *Container* Optional selector or element id that instructs jsPlumb to append elements it creates to a specific element.
* - *DoNotThrowErrors* Defaults to false; whether or not to throw errors if a user specifies an unknown anchor, endpoint or connector type.
* - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
* - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
* - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
* - *EndpointOverlays* The default overlay definitions for Endpoints. Defaults to an empty list.
* - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
* - *EndpointStyle* The default style definition to use for all endpoints. Default is fillStyle:"#456".
* - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
* - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
* - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
* - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
* - *LabelStyle* The default style to use for label overlays on connections.
* - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
* - *Overlays* The default overlay definitions (for both Connections and Endpoint). Defaults to an empty list.
* - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
* - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
* - *ReattachConnections* Whether or not to reattach Connections that a user has detached with the mouse and then dropped. Default is false.
* - *RenderMode* What mode to use to paint with. If you're on IE<9, you don't really get to choose this. You'll just get VML. Otherwise, the jsPlumb default is to use SVG.
* - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
*/
/*
* Function: getAllConnections()
* Returns:
* All connections, as a map of the form:
*
* { scope -> [ connection... ] }
*/
/*
* Function: getDefaultScope()
* Gets the default scope for connections and endpoints.
*
* A scope defines a type of endpoint/connection; supplying a
* scope to an Endpoint or Connection allows you to support different
* types of connections in the same UI. but if you're only interested in
* one type of connection, you don't need to supply a scope. this method
* will probably be used by very few people; it's good for testing
* though.
*/
/**
* Function: getEndpoints(el)
* Gets the list of Endpoints for a given element.
*
* Parameters:
* el - element id, dom element, or selector.
*
* Returns:
* An array of Endpoints for the specified element.
*/
/*
Function: getEndpoint(uuid)
Gets an Endpoint by UUID
Parameters:
uuid - the UUID for the Endpoint
Returns:
Endpoint with the given UUID, null if nothing found.
*/
/*
* Function: getSelector([context], spec)
* This method takes the given selector spec and, using the current underlying library, turns it into
* a selector from that library. This method exists really as a helper function for those applications
* where you're writing jsPlumb code that will target more than one library (such as in the case of the
* jsPlumb demo pages).
*
* Parameters:
* context - an element to search from. may be omitted (not null: omitted. as in you only pass one argument to the function)
* spec - a valid selector string.
*
*/
/*
* Function: isHoverSuspended()
* Returns:
* whether or not hover effects are currently suspended.
*/
/*
* Function: setHoverSuspended(s)
* Sets whether or not hover effects should be suspended. jsPlumb uses this internally during various
* drag/drop operations, and it is exposed because it might also be useful for you too.
* Parameters:
* s - whether or not to set hover suspended.
*/
/*
Function: hide (el, [changeEndpoints])
Sets an element's connections to be hidden.
Parameters:
el - either the id of the element, or a selector for the element.
changeEndpoints - whether not to also hide endpoints on the element. by default this is false.
Returns:
The jsPlumb instance.
*/
/**
* Function: makeTarget(el, [params])
* Makes some DOM element a Connection target, allowing you to drag connections to it
* without having to register any Endpoints on it first. When a Connection is established,
* the endpoint spec that was passed in to this method is used to create a suitable
* Endpoint (the default will be used if you do not provide one).
*
* Parameters:
* el - string id or element selector for the element to make a target.
* params - JS object containing parameters:
* - *endpoint* optional. specification of an Endpoint to create when a Connection is established.
* - *scope* optional. scope for the drop zone.
* - *dropOptions* optional. same stuff as you would pass to dropOptions of an Endpoint definition.
* - *deleteEndpointsOnDetach* optional, defaults to true. whether or not to delete
* any Endpoints created by a connection to this target if
* the connection is subsequently detached. this will not
* remove Endpoints that have had more Connections attached
* to them after they were created.
* - *maxConnections* optional. Specifies the maximum number of Connections that can be made to this element as a target. Default is no limit.
* - *onMaxConnections* optional. Function to call when user attempts to drop a connection but the limit has been reached.
* The callback is passed two arguments: a JS object with:
* : { element, connection, maxConnection }
* ...and the original event.
*/
/*
* Function: unmakeTarget(el)
* Sets the given element to no longer be a connection target.
*
* Parameters:
* el - a string id, a dom element, or a selector representing the element.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: makeTargets(els, [params], [referenceParams])
* Makes all elements in some array or a selector connection targets.
*
* Parameters:
* els - either an array of ids or a selector
* params - parameters to configure each element as a target with
* referenceParams - extra parameters to configure each element as a target with.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: makeSource(el, [params])
* Makes some DOM element a Connection source, allowing you to drag connections from it
* without having to register any Endpoints on it first. When a Connection is established,
* the endpoint spec that was passed in to this method is used to create a suitable
* Endpoint (the default will be used if you do not provide one).
*
* Parameters:
* el - string id or element selector for the element to make a source.
* params - JS object containing parameters:
* - *endpoint* optional. specification of an endpoint to create when a connection is created.
* - *parent* optional. the element to add Endpoints to when a Connection is established. if you omit this,
* Endpoints will be added to 'el'.
* - *scope* optional. scope for the connections dragged from this element.
* - *dragOptions* optional. same stuff as you would pass to dragOptions of an Endpoint definition.
* - *deleteEndpointsOnDetach* optional, defaults to false. whether or not to delete
* any Endpoints created by a connection from this source if
* the connection is subsequently detached. this will not
* remove Endpoints that have had more Connections attached
* to them after they were created.
* - *filter* - optional function to call when the user presses the mouse button to start a drag. This function is passed the original
* event and the element on which the associated makeSource call was made. If it returns anything other than false,
* the drag begins as usual. But if it returns false (the boolean false, not just something falsey), the drag is aborted.
*/
/*
* Function: unmakeSource(el)
* Sets the given element to no longer be a connection source.
*
* Parameters:
* el - a string id, a dom element, or a selector representing the element.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: unmakeEverySource()
* Resets all elements in this instance of jsPlumb so that none of them are connection sources.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: unmakeEveryTarget()
* Resets all elements in this instance of jsPlumb so that none of them are connection targets.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: makeSources(els, [params], [referenceParams])
* Makes all elements in some array or a selector connection sources.
*
* Parameters:
* els - either an array of ids or a selector
* params - parameters to configure each element as a source with
* referenceParams - extra parameters to configure each element as a source with.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: setSourceEnabled(el, state)
* Sets the enabled state of one or more elements that were previously made a connection source with the makeSource
* method.
*
* Parameters:
* el - either a string representing some element's id, or an array of ids, or a selector.
* state - true to enable the element(s), false to disable it.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: toggleSourceEnabled(el)
* Toggles the source enabled state of the given element or elements.
*
* Parameters:
* el - either a string representing some element's id, or an array of ids, or a selector.
*
* Returns:
* The current enabled state of the source.
*/
/*
* Function: isSource(el)
* Returns whether or not the given element is registered as a connection source.
*
* Parameters:
* el - a string id, a dom element, or a selector representing a single element.
*
* Returns:
* True if source, false if not.
*/
/*
* Function: isSourceEnabled(el)
* Returns whether or not the given connection source is enabled.
*
* Parameters:
* el - a string id, a dom element, or a selector representing a single element.
*
* Returns:
* True if enabled, false if not.
*/
/*
* Function: setTargetEnabled(el, state)
* Sets the enabled state of one or more elements that were previously made a connection target with the makeTarget method.
* method.
*
* Parameters:
* el - either a string representing some element's id, or an array of ids, or a selector.
* state - true to enable the element(s), false to disable it.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: toggleTargetEnabled(el)
* Toggles the target enabled state of the given element or elements.
*
* Parameters:
* el - either a string representing some element's id, or an array of ids, or a selector.
*
* Returns:
* The current enabled state of the target.
*/
/*
Function: isTarget(el)
Returns whether or not the given element is registered as a connection target.
Parameters:
el - a string id, a dom element, or a selector representing a single element.
Returns:
True if source, false if not.
*/
/*
Function: isTargetEnabled(el)
Returns whether or not the given connection target is enabled.
Parameters:
el - a string id, a dom element, or a selector representing a single element.
Returns:
True if enabled, false if not.
*/
/*
* Function: ready(fn)
* Helper method to bind a function to jsPlumb's ready event. You should use this method instead of your
* library's equivalent, to ensure that jsPlumb has loaded properly before you start to use it. This is
* particularly true in the case of YUI, because of the asynchronous nature of the module loading process.
*
* Parameters:
* fn - function to call once the instance is ready.
*/
/*
* Function: repaint (el)
* Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
*
* Parameters:
* el - id of the element, a dom element, or a selector representing the element.
*
* Returns:
* The current jsPlumb instance.
*
* See Also:
* <repaintEverything>
*/
/*
* Function: repaintEverything()
* Repaints all connections and endpoints.
*
* Returns:
* The current jsPlumb instance.
*
* See Also:
* <repaint>
*/
/*
* Function: removeAllEndpoints(el, [recurse])
* Removes all Endpoints associated with a given element.
* Also removes all Connections associated with each Endpoint it removes. jsPlumb expects
* that the element referenced here exists in the DOM. If it does not, or you are uncertain
* whether it will exist or not, use jsPlumb.remove.
*
* Parameters:
* el - either an element id, or a selector for an element.
* recurse - whether or not to recurse down through this elements children and remove their endpoints too. defaults to false.
*
* Returns:
* The current jsPlumb instance.
*
* See Also:
* <deleteEndpoint>
*/
/*
* Function: remove(el)
* Removes the given element from the DOM, along with all Endpoints associated with it,
* and their connections. This is present in jsPlumb since version 1.4.1.
*
* Parameters:
* el - either an element id, a DOM element, or a selector for the element.
*/
/*
* Function:reset()
* Removes all endpoints and connections and clears the listener list. To keep listeners call
* : jsPlumb.deleteEveryEndpoint()
* instead of this.
*/
/*
* Function: setDefaultScope(scope)
* Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
* scope to an Endpoint or Connection allows you to support different
* types of Connections in the same UI. If you're only interested in
* one type of Connection, you don't need to supply a scope. This method
* will probably be used by very few people; it just instructs jsPlumb
* to use a different key for the default scope.
*
* Parameters:
* scope - scope to set as default.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: setDraggable(el, draggable)
* Sets whether or not a given element is
* draggable, regardless of what any jsPlumb command may request.
*
* Parameters:
* el - either the id for the element, or a selector representing the element.
* draggable - whether or not the element should be draggable.
*
* Returns:
* void
*/
/*
* Function: setId(el, newId, [doNotSetAttribute])
* Changes the id of some element, adjusting all connections and endpoints
*
* Parameters:
* el - a selector, a DOM element, or a string.
* newId - string.
* doNotSetAttributes - defaults to false; if true, the id on the DOM element wont be changed.
*/
/*
* Function: setIdChanged(oldId, newId)
* Notify jsPlumb that the element with oldId has had its id changed to newId.
*
* This method is equivalent to what jsPlumb does itself in the second step of the setId method above.
*
* Parameters:
* oldId - previous element id
* newId - element's new id
*
* See Also:
* <setId>
*/
/*
* Function: setSuspendDrawing(val, [repaintAfterwards])
* Suspends drawing operations. This can (and should!) be used when you have a lot of connections to make or endpoints to register;
* it will save you a lot of time.
*
* Parameters:
* val - boolean indicating whether to suspend or not
* repaintAfterwards - optional boolean instructing jsPlumb to do a full repaint after changing the suspension
* state. defaults to false.
*/
/*
* Function: isSuspendDrawing()
* Returns:
* Whether or not drawing is currently suspended.
*/
/*
* Function: doWhileSuspended(fn, [doNotRepaintAfterwards])
* Suspends drawing, runs the given function, then re-enables drawing (and repaints, unless
* you set 'doNotRepaintAfterwards' to true)
*/
/*
* Function: show(el, [changeEndpoints])
* Sets an element's connections to be visible.
*
* Parameters:
* el - either the id of the element, or a selector for the element.
* changeEndpoints - whether or not to also change the visible state of the endpoints on the element. this also has a bearing on
* other connections on those endpoints: if their other endpoint is also visible, the connections are made visible.
*
* Returns:
* The current jsPlumb instance.
*/
/*
* Function: toggleVisible(el, [changeEndpoints])
* Toggles visibility of an element's Connections.
*
* Parameters:
* el - either the element's id, or a selector representing the element.
* changeEndpoints - whether or not to also toggle the endpoints on the element.
*
* Returns:
* void, but should be updated to return the current state
*/
/*
* Function: toggleDraggable(el)
* Toggles draggability (sic?) of an element's Connections.
*
* Parameters:
* el - either the element's id, or a selector representing the element.
*
* Returns:
* The current draggable state.
*/
/*
* Function: recalculateOffsets(el)
* Recalculates the offsets of all child elements of some element. If you have Endpoints registered on the
* descendants of some element and you make changes to that element's markup, it is possible that the location
* of each Endpooint relative to the origin of the element may have changed. So you call this to tell jsPlumb to
* recalculate. You need to do this because, for performance reasons, jsplumb won't calculate these offsets on
* the fly.
*
* Parameters:
* el - either a string id, or a selector.
*/
/*
* Property: connectorClass
* The CSS class to set on Connection elements. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: hoverClass
* The CSS class to set on Connection or Endpoint elements when hovering. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: endpointClass
* The CSS class to set on Endpoint elements. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: endpointConnectedClass
* The CSS class to set on an Endpoint element when its Endpoint has at least one connection. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: endpointFullClass
* The CSS class to set on a full Endpoint element. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: endpointDropAllowedClass
* The CSS class to set on an Endpoint on which a drop will be allowed (during drag and drop). This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: endpointDropForbiddenClass
* The CSS class to set on an Endpoint on which a drop will be forbidden (during drag and drop). This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: overlayClass
* The CSS class to set on an Overlay that is an HTML element. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: draggingClass
* The CSS class to set on connections that are being dragged. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: elementDraggingClass
* The CSS class to set on connections whose source or target element is being dragged, and
* on their endpoints too. This value is a String and can have multiple classes; the entire String is appended as-is.
*/
/*
* Property: endpointAnchorClassPrefix
* The prefix for the CSS class to set on endpoints that have dynamic anchors whose individual locations
* have declared an associated CSS class. This value is a String and, unlike the other classes, is expected
* to contain a single value, as it is used as a prefix for the final class: '_***' is appended,
* where "***" is the CSS class associated with the current dynamic anchor location.
*/
/*
* Property: Anchors.Top
* An Anchor that is located at the top center of the element.
*/
/*
* Property: Anchors.Bottom
* An Anchor that is located at the bottom center of the element.
*/
/*
* Property: Anchors.Left
* An Anchor that is located at the left middle of the element.
*/
/*
* Property: Anchors.Right
* An Anchor that is located at the right middle of the element.
*/
/*
* Property: Anchors.Center
* An Anchor that is located at the center of the element.
*/
/*
* Property: Anchors.TopRight
* An Anchor that is located at the top right corner of the element.
*/
/*
* Property: Anchors.BottomRight
* An Anchor that is located at the bottom right corner of the element.
*/
/*
* Property: Anchors.TopLeft
* An Anchor that is located at the top left corner of the element.
*/
/*
* Property: Anchors.BottomLeft
* An Anchor that is located at the bototm left corner of the element.
*/
/*
* Property: Anchors.AutoDefault
* Default DynamicAnchors - chooses from TopCenter, RightMiddle, BottomCenter, LeftMiddle.
*/
/*
* Property: Anchors.Assign
* An Anchor whose location is assigned at connection time, through an AnchorPositionFinder. Used in conjunction
* with the 'makeTarget' function. jsPlumb has two of these - 'Fixed' and 'Grid', and you can also write your own.
*/
/*
* Property: Anchors.Continuous
* An Anchor that tracks the other element in the connection, choosing the closest face.
*/
/*
* Property: Anchors.ContinuousLeft
* A continuous anchor that uses only the left edge of the element.
*/
/*
* Property: Anchors.ContinuousTop
* A continuous anchor that uses only the top edge of the element.
*/
/*
* Property: Anchors.ContinuousBottom
* A continuous anchor that uses only the bottom edge of the element.
*/
/*
* Property: Anchors.ContinuousRight
* A continuous anchor that uses only the right edge of the element.
*/
/*
* Property: Anchors.Perimeter
* An Anchor that tracks the perimeter of some shape, approximating it with a given number of dynamically
* positioned locations.
*
* Parameters:
*
* anchorCount - optional number of anchors to use to approximate the perimeter. default is 60.
* shape - required. the name of the shape. valid values are 'rectangle', 'square', 'ellipse', 'circle', 'triangle' and 'diamond'
* rotation - optional rotation, in degrees, to apply.
*/
// ---------------- ENDPOINT -----------------------------------------------------
/*
* Class: Endpoint
*
* Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
* to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
* actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
* do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
* 'target' Endpoints for Connections.
*
* You never need to create one of these directly; jsPlumb will create them as needed.
*
*
*/
/*
* Property: canvas
* The Endpoint's drawing area.
*/
/*
* Property: connections
* List of Connections this Endpoint is attached to.
*/
/*
* Property: scope
* Scope descriptor for this Endpoint.
*/
/*
* Property: overlays
* List of Overlays for this Endpoint.
*/
/*
* Function: Endpoint
*
* Endpoint constructor.
*
* Parameters:
* anchor - definition of the Anchor for the endpoint. You can include one or more Anchor definitions here; if you include more than one, jsPlumb creates a 'dynamic' Anchor, ie. an Anchor which changes position relative to the other elements in a Connection. Each Anchor definition can be either a string nominating one of the basic Anchors provided by jsPlumb (eg. "TopCenter"), or a four element array that designates the Anchor's location and orientation (eg, and this is equivalent to TopCenter, [ 0.5, 0, 0, -1 ]). To provide more than one Anchor definition just put them all in an array. You can mix string definitions with array definitions.
* endpoint - optional Endpoint definition. This takes the form of either a string nominating one of the basic Endpoints provided by jsPlumb (eg. "Rectangle"), or an array containing [name,params] for those cases where you don't wish to use the default values, eg. [ "Rectangle", { width:5, height:10 } ].
* enabled - optional, defaults to true. Indicates whether or not the Endpoint should be enabled for mouse events (drag/drop).
* paintStyle - endpoint style, a js object. may be null.
* hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
* cssClass - optional CSS class to set on the display element associated with this Endpoint.
* hoverClass - optional CSS class to set on the display element associated with this Endpoint when it is in hover state.
* source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
* canvas - canvas element to use. may be, and most often is, null.
* container - optional id or selector instructing jsPlumb where to attach the element it creates for this endpoint. you should read the documentation for a full discussion of this.
* connections - optional list of Connections to configure the Endpoint with.
* isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
* maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
* dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
* connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
* connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
* connector - optional Connector type to use. Like 'endpoint', this may be either a single string nominating a known Connector type (eg. "Bezier", "Straight"), or an array containing [name, params], eg. [ "Bezier", { curviness:160 } ].
* connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
* connectorClass - optional CSS class to set on Connections emanating from this Endpoint.
* connectorHoverClass - optional CSS class to set on to set on Connections emanating from this Endpoint when they are in hover state.
* connectionsDetachable - optional, defaults to true. Sets whether connections to/from this Endpoint should be detachable or not.
* isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
* dropOptions - if isTarget is set to true, you can supply arguments for the underlying library's drop method with this parameter. Optional; defaults to null.
* reattach - optional boolean that determines whether or not the Connections reattach after they have been dragged off an Endpoint and left floating. defaults to false: Connections dropped in this way will just be deleted.
* parameters - Optional JS object containing parameters to set on the Endpoint. These parameters are then available via the getParameter method. When a connection is made involving this Endpoint, the parameters from this Endpoint are copied into that Connection. Source Endpoint parameters override target Endpoint parameters if they both have a parameter with the same name.
* connector-pointer-events - Optional. a value for the 'pointer-events' property of any SVG elements that are created to render connections from this endoint.
*/
/*
* Function: addConnection(connection)
* Adds a Connection to this Endpoint.
*
* Parameters:
* connection - the Connection to add.
*/
/*
* Function: addOverlay(overlaySpec)
* Adds an Overlay to the Endpoint.
*
* Parameters:
* overlaySpec - Overlay to add. This is not an Overlay object but rather a specification in the format that jsPlumb uses.
*/
/*
* Function: addType(typeId)
* Adds the specified type to the Endpoint. Types are registered using registerEndpointType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to add.
*/
/*
* Function: bind(event, callback)
* Bind to an event on the Endpoint.
*
* Parameters:
* event - the event to bind. Available events on an Endpoint are:
* - *click* : notification that a Endpoint was clicked.
* - *dblclick* : notification that a Endpoint was double clicked.
* - *mouseenter* : notification that the mouse is over a Endpoint.
* - *mouseexit* : notification that the mouse exited a Endpoint.
* - *contextmenu* : notification that the user right-clicked on the Endpoint.
*
* callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
*/
/*
* Function: detach(connection, [ignoreTarget])
* Detaches the given Connection from this Endpoint.
*
* Parameters:
* connection - the Connection to detach.
* ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
*/
/*
* Function: detachAll([fireEvent])
* Detaches all Connections this Endpoint has.
*
* Parameters:
* fireEvent - whether or not to fire the detach event. defaults to false.
*/
/*
* Function: detachFrom(targetEndpoint, [fireEvent])
* Removes any connections from this Endpoint that are connected to the given target endpoint.
*
* Parameters:
* targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
* fireEvent - whether or not to fire the detach event. defaults to false.
*/
/*
* Function: detachFromConnection(connection)
* Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
*
* Parameters:
* connection - Connection to detach from.
*/
/*
* Function: getElement()
*
* Returns:
* The DOM element this Endpoint is attached to.
*/
/*
* Function: getLabel()
* Returns:
* The label text for this Endpoint (or a function if you are labelling with a function).
* This does not return the overlay itself; this is a convenience method which is a pair with
* setLabel; together they allow you to add and access a Label Overlay without having to create the
* Overlay object itself. For access to the underlying label overlay that jsPlumb has created,
* use getLabelOverlay.
*/
/*
* Function: getLabelOverlay()
* Returns:
* The underlying internal label overlay, which will exist if you specified a label on
* an addEndpoint call, or have called setLabel at any stage.
*/
/*
* Function: getPaintStyle()
* Returns:
* The Endpoint's paint style. This is not necessarily the paint style in use at the time;
* this is the paint style for the Endpoint when the mouse it not hovering over it.
*/
/*
* Function: getOverlay(overlayId)
* Gets an overlay, by ID. Note: by ID. You would pass an 'id' parameter
* in to the Overlay's constructor arguments, and then use that to retrieve
* it via this method.
*
* Parameters:
* overlayId - String id for the overlay.
*
* Returns:
* an Overlay or null if no overlay with that id is registered.
*/
/*
* Function: getOverlays()
* Returns:
* An array of all Overlays for the component.
*/
/*
* Function: getParameter(key)
* Gets the named parameter; returns null if no parameter with that name is set. Parameters may have been set on the Endpoint in the 'addEndpoint' call, or they may have been set with the setParameter function.
*
* Parameters:
* key - Parameter name.
*
* Returns:
* The value stored against the given parameter name, null if not found.
*/
/*
* Function: getParameters()
* Returns:
* All of the Endpoint's parameters. Note that you can edit the return value of this method and this will change the parameters on the Endpoint.
*/
/*
* Function: getType()
* Returns:
* The Endpoint's current type(s)
*/
/*
* Function: getUuid()
* Returns:
* The UUID for this Endpoint, if there is one. Otherwise returns null.
*/
/*
* Function: hasType(typeId)
* Returns:
* Whether or not the Endpoint has the given type.
*/
/*
* Function: hideOverlay(overlayId)
* Hides the overlay specified by the given id.
*
* Parameters:
* overlayId - id of the overlay to hide.
*/
/*
* Function: hideOverlays()
* Hides all Overlays
*/
/*
* Function: isConnectedTo(endpoint)
*
* Parameters:
* endpoint - Endpoint to test.
*
* Returns:
* True if connected to the given Endpoint, false otherwise.
*/
/*
* Function: isEnabled()
* Returns:
* True if the Endpoint is enabled for drag/drop connections enabled, false otherwise.
*/
/*
* Function: isFull()
* Returns:
* True if the Endpoint cannot accept any more Connections, false otherwise.
*/
/*
* Function: isVisible()
* Returns:
* Whether or not the Endpoint is currently visible.
*/
/*
* Function: paint(params)
* Paints the Endpoint, recalculating offset and anchor positions if necessary. This does NOT paint
* any of the Endpoint's connections. NOTE: the arguments to this method should be in a js object, not
* individual arguments.
*
* Parameters:
* timestamp - optional timestamp advising the Endpoint of the current paint time; if it has painted already once for this timestamp, it will not paint again.
* canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
* connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
*/
/*
* Function: reapplyTypes(data, [doNotRepaint])
* Reapplies all of the current types, but with the given data.
*
* Parameters:
* data - data to use for parameterised types
* doNotRepaint - if true, dont repaint after reapplying types.
*/
/*
* Function: removeAllOverlays()
* Removes all overlays from the Endpoint, and then repaints.
*/
/*
* Function: removeOverlay(overlayId)
* Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
*
* Parameters:
* overlayId - id of the overlay to remove.
*/
/*
* Function: removeOverlays(overlayIds...)
* Removes a set of overlays by ID. Note: by ID. this is a string you set in the overlay spec.
*
* Parameters:
* overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
*/
/*
* Function: removeType(typeId)
* Removes the specified type from the Endpoint. Types are registered using registerEndpointType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to remove.
*/
/*
* Function: setAnchor(anchorParams, [doNotRepaint])
* Sets the Endpoint's anchor. This takes an anchor in any supported form in a jsPlumb.connect
* or jsPlumb.addEndpoint call.
*
* Parameters:
* anchorParams - anchor spec
* doNotRepaint - optional, defaults to false.
*/
/*
* Function: setDragAllowedWhenFull(allowed)
* Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
* which you're going to provide some other way of breaking connections, if you need to break them at all. This property
* is by default true; use it in conjunction with the 'reattach' option on a connect call.
*
* Parameters:
* allowed - whether drag is allowed or not when the Endpoint is full.
*/
/*
* Function: setElement(el, [container])
* Sets the DOM element this Endpoint is attached to.
*
* Parameters:
* el - dom element or selector
* container - optional, specifies the actual parent element to use as the parent for this Endpoint's visual representation.
* See the jsPlumb documentation for a discussion about this.
*/
/*
* Function: setEnabled(enabled)
* Sets whether or not the Endpoint is enabled for drag/drop connections.
*
* Parameters:
* enabled - whether or not the Endpoint is enabled.
*/
/*
* Function: setEndpoint(endpointSpec)
* Sets the Endpoint's visual representation and behaviour. The format of the value you pass to
* this method is the same as you use for the second argument to a jsPlumb.addEndpoint call.
*
* Parameters:
* endpointSpec - endpoint spec
*/
/*
* Function: setHover(hover, [ignoreAttachedElements])
* Sets/unsets the hover state of this Endpoint.
*
* Parameters:
* hover - hover state boolean
* ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
*/
/*
* Function: setHoverPaintStyle(style, [doNotRepaint])
* Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
* The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
* it. This is because people will most likely want to change just one thing when hovering, say the
* color for example, but leave the rest of the appearance the same.
*
* Parameters:
* style - Style to use when the mouse is hovering.
* doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
*/
/*
* Function: setLabel(label)
* Sets the Endpoint's label.
*
* Parameters:
* label - label to set. May be a String, a Function that returns a String, or a params object containing { "label", "labelStyle", "location", "cssClass" }. Note that this uses innerHTML on the label div, so keep
* that in mind if you need escaped HTML.
*/
/*
* Function: setPaintStyle(style)
* Sets the Endpoint's paint style and then repaints the Endpoint.
*
* Parameters:
* style - Style to use.
*/
/*
* Function: setParameter(key, value)
* Sets the named parameter to the given value.
*
* Parameters:
* key - Parameter name.
* value - Parameter value.
*/
/*
* Function: setParameters(parameters)
* Sets the Endpoint's parameters.
*
* Parameters:
* params - JS object containing [key,value] pairs.
*/
/*
* Function: setType(typeId)
* Sets the specified type of the Endpoint. This replaces all existing types. Types are registered using registerEndpointType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to set on the Endpoint.
*/
/*
* Function: setVisible(visible, [doNotChangeConnections], [doNotNotifyOtherEndpoint])
* Sets whether or not the Endpoint is currently visible.
*
* Parameters:
* visible - whether or not the Endpoint should be visible.
* doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
* doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
*/
/*
* Function: showOverlay(overlayId)
* Shows the overlay specified by the given id.
*
* Parameters:
* overlayId - id of the overlay to show.
*/
/*
* Function: showOverlays()
* Shows all Overlays
*/
/*
* Function: toggleType(typeId)
* Toggles the specified type on the Endpoint. Types are registered using registerEndpointType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to toggle.
*/
// ---------------- / ENDPOINT -----------------------------------------------------
// --------------- CONNECTION ----------------------
/*
* Class: Connection
* The connecting line between two elements. A Connection consists of two Endpoints and a Connector.
*/
/*
* Property: sourceId
* Id of the source element in the connection.
*/
/*
* Property: targetId
* Id of the target element in the connection.
*/
/*
* Property: scope
* Optional scope descriptor for the connection.
*/
/*
* Property: endpoints
* Array of Endpoints.
*/
/*
* Property: source
* The source element for this Connection.
*/
/*
* Property: target
* The target element for this Connection.
*/
/*
* Property: overlays
* List of Overlays for this component.
*/
/*
* Function: Connection
* Connection constructor. You should not ever create one of these directly. If you make a call to jsPlumb.connect, all of
* the parameters that you pass in to that function will be passed to the Connection constructor; if your UI
* uses the various Endpoint-centric methods like addEndpoint/makeSource/makeTarget, along with drag and drop,
* then the parameters you set on those functions are translated and passed in to the Connection constructor. So
* you should check the documentation for each of those methods.
*
* Parameters:
* source - either an element id, a selector for an element, or an Endpoint.
* target - either an element id, a selector for an element, or an Endpoint
* scope - scope descriptor for this connection. optional.
* container - optional id or selector instructing jsPlumb where to attach all the elements it creates for this connection. you should read the documentation for a full discussion of this.
* detachable - optional, defaults to true. Defines whether or not the connection may be detached using the mouse.
* reattach - optional, defaults to false. Defines whether not the connection should be retached if it was dragged off an Endpoint and then dropped in whitespace.
* endpoint - Optional. Endpoint definition to use for both ends of the connection.
* endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
* endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
* endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
* paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
* hoverPaintStyle - Parameters defining the appearance of the Connection when the mouse is hovering over it. Optional; jsPlumb will use the defaults if you supply nothing here (note that the default hoverPaintStyle is null).
* cssClass - optional CSS class to set on the display element associated with this Connection.
* hoverClass - optional CSS class to set on the display element associated with this Connection when it is in hover state.
* overlays - Optional array of Overlay definitions to appear on this Connection.
* drawEndpoints - if false, instructs jsPlumb to not draw the endpoints for this Connection. Be careful with this: it only really works when you tell jsPlumb to attach elements to the document body. Read the documentation for a full discussion of this.
* parameters - Optional JS object containing parameters to set on the Connection. These parameters are then available via the getParameter method.
*/
/*
* Function: addOverlay(overlaySpec)
* Adds an Overlay to the Connection.
*
* Parameters:
* overlaySpec - specification of the Overlay to add.
*/
/*
* Function: addType(typeId)
* Adds the specified type to the Connection. Types are registered using registerConnectionType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to add.
*/
/*
* Function: bind(event, callback)
* Bind to an event on the Connection.
*
* Parameters:
* event - the event to bind. Available events on a Connection are:
* - *click* : notification that a Connection was clicked.
* - *dblclick* : notification that a Connection was double clicked.
* - *mouseenter* : notification that the mouse is over a Connection.
* - *mouseexit* : notification that the mouse exited a Connection.
* - *contextmenu* : notification that the user right-clicked on the Connection.
*
* callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
*/
/*
* Function: getConnector()
* Gets The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
*/
/*
* Function: getLabel()
* Returns the label text for this Connection (or a function if you are labelling with a function).
*
* This does not return the overlay itself; this is a convenience method which is a pair with
* <setLabel>; together they allow you to add and access a Label Overlay without having to create the
* Overlay object itself. For access to the underlying label overlay that jsPlumb has created,
* use <getLabelOverlay>.
*
* See Also:
* <getOverlay>
* <getLabelOverlay>
*/
/*
* Function: getLabelOverlay()
* Returns:
* The underlying internal label overlay, which will exist if you specified a label on
* a connect call, or have called setLabel at any stage.
*/
/*
* Function: getOverlay(overlayId)
* Gets an overlay, by ID. Note: by ID. You would pass an 'id' parameter
* in to the Overlay's constructor arguments, and then use that to retrieve
* it via this method.
*
* Parameters:
* overlayId - id of the overlay to retrieve.
*
* Returns:
* The overlay stored against the given id, null if not found.
*/
/*
* Function: getOverlays()
* Gets all the overlays for this component.
*/
/*
* Function: getPaintStyle()
* Gets the Connection's paint style. This is not necessarily the paint style in use at the time;
* this is the paint style for the connection when the mouse it not hovering over it.
* Returns:
* The current non-hover paint style.
*/
/*
* Function: getParameter(key)
* Gets the named parameter; returns null if no parameter with that name is set. Parameter values may have been supplied to a 'connect' or 'addEndpoint' call (connections made with the mouse get a copy of all parameters set on each of their Endpoints), or the parameter value may have been set with setParameter.
*
* Parameters:
* key - Parameter name.
*
* Returns:
* a value stored against the given key, or null if none found.
*/
/*
* Function: getParameters()
* Gets all parameters for the Connection
*
* Returns:
* All of the Connection's parameters. Note that you can edit the return value of this method and this will change the parameters on the Connection.
*/
/*
* Function: getType()
* Returns:
* The Endpoint's current type(s)
*/
/*
* Function: hasType(typeId)
* Returns:
* Whether or not the Endpoint has the given type.
*/
/*
* Function: hideOverlay(overlayId)
* Hides the overlay specified by the given id.
*
* Parameters:
* overlayId - id of the overlay to hide.
*/
/*
* Function: hideOverlays()
* Hides all Overlays
*/
/*
* Function: isDetachable()
* Returns whether or not this connection can be detached from its target/source endpoint. by default this
* is false; use it in conjunction with the 'reattach' parameter.
*/
/*
* Function: isEditable()
* Returns whether or not the Connection is editable.
*/
/*
* Function: isReattach()
* Returns whether or not this connection will be reattached after having been detached via the mouse and dropped. by default this
* is false; use it in conjunction with the 'detachable' parameter.
*/
/*
* Function: isVisible()
* Returns whether or not the Connection is currently visible.
*/
/*
* Function: reapplyTypes(data, [doNotRepaint])
* Reapplies all of the current types, but with the given data.
*
* Parameters:
* data - data to use for parameterised types
* doNotRepaint - if true, dont repaint after reapplying types.
*/
/*
* Function: removeAllOverlays()
* Removes all overlays from the Connection, and then repaints.
*/
/*
* Function: removeOverlay(overlayId)
* Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
*
* Parameters:
* overlayId - id of the overlay to remove.
*/
/*
* Function: removeOverlays(overlayIds...)
* Removes a set of overlays by ID. Note: by ID. this is a string you set in the overlay spec.
*
* Parameters:
* overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
*/
/*
* Function: removeType(typeId)
* Removes the specified type from the Connection. Types are registered using registerConnectionType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to remove.
*/
/*
* Function: setConnector(connector)
* Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method, the same
* thing that you would set as the 'connector' property on a jsPlumb.connect call.
*
* Parameters:
* connector - Connector definition
*/
/*
* Function: setDetachable(detachable)
* Sets whether or not this connection is detachable.
*
* Parameters:
* detachable - whether or not to set the Connection to be detachable.
*/
/*
* Function: setEditable(editable)
* Sets whether or not the Connection is editable. This will only be honoured if
* the underlying Connector is editable - not all types are.
*
* Parameters:
* editable - whether or not to set the Connection to be editable
*/
/*
* Function: setHover(hover, [ignoreAttachedElements])
* Sets/unsets the hover state of this Connection.
*
* Parameters:
* hover - hover state boolean
* ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
*/
/*
* Function: setHoverPaintStyle(style, [doNotRepaint])
* Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
* The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
* it. This is because people will most likely want to change just one thing when hovering, say the
* color for example, but leave the rest of the appearance the same.
*
* Parameters:
* style - Style to use when the mouse is hovering.
* doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
*/
/*
* Function: setLabel(label)
* Sets the Connection's label.
*
* Parameters:
* label - label to set. May be a String, a Function that returns a String, or a params object containing { "label", "labelStyle", "location", "cssClass" }. Note that this uses innerHTML on the label div, so keep
* that in mind if you need escaped HTML.
*/
/*
* Function: setPaintStyle(style)
* Sets the Connection's paint style and then repaints the Connection.
*
* Parameters:
* style - Style to use.
*/
/*
* Function: setParameter(key, value)
* Sets the named parameter to the given value.
*
* Parameters:
* key - Parameter name.
* value - Parameter value.
*/
/*
* Function: setParameters(parameters)
* Sets the Connection's parameters.
*
* Parameters:
* params - JS object containing [key,value] pairs.
*/
/*
* Function: setReattach(reattach)
* Sets whether or not this connection will reattach after having been detached via the mouse and dropped.
*
* Parameters:
* reattach - whether or not to set the Connection to reattach after drop in whitespace.
*/
/*
* Function: setType(typeId)
* Sets the type of the Connection. This replaces all existing types. Types are registered using registerConnectionType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to set.
*/
/*
* Function: setVisible(visible)
* Sets whether or not the Connection should be visible.
*
* Parameters:
* visible - boolean indicating desired visible state.
*/
/*
* Function: showOverlay(overlayId)
* Shows the overlay specified by the given id.
*
* Parameters:
* overlayId - id of the overlay to show.
*/
/*
* Function: showOverlays()
* Shows all Overlays
*/
/*
* Function: toggleType(typeId)
* Toggles the specified type on the Connection. Types are registered using registerConnectionType on the associated jsPlumb instance. See the wiki page for a full discussion.
*
* Parameters:
* typeId - Id of the type to toggle.
*/
/*
* Class: jsPlumb.Connectors.Flowchart
* The Flowchart connector.
*/
/*
* Function: Constructor
*
* Parameters:
* stub - minimum length for the stub at each end of the connector. This can be an integer, giving a value for both ends of the connections,
* or an array of two integers, giving separate values for each end. The default is an integer with value 30 (pixels).
* gap - gap to leave between the end of the connector and the element on which the endpoint resides. if you make this larger than stub then you will see some odd looking behaviour.
* Like stub, this can be an array or a single value. defaults to 0 pixels for each end.
* cornerRadius - optional, defines the radius of corners between segments. defaults to 0 (hard edged corners).
* alwaysRespectStubs - defaults to false. whether or not the connectors should always draw the stub, or, if the two elements
* are in close proximity to each other (closer than the sum of the two stubs), to adjust the stubs.
*/
/*
* Function: getPath
* Gets the path inscribed by the connector, as a series of [x,y] points.
*/
/**
* Class: jsPlumb.Connectors.StateMachine
* Provides 'state machine' connectors.
*/
/*
* Function: Constructor
*
* Parameters:
* curviness - measure of how "curvy" the connectors will be. this is translated as the distance that the
* Bezier curve's control point is from the midpoint of the straight line connecting the two
* endpoints, and does not mean that the connector is this wide. The Bezier curve never reaches
* its control points; they act as gravitational masses. defaults to 10.
* margin - distance from element to start and end connectors, in pixels. defaults to 5.
* proximityLimit - sets the distance beneath which the elements are consider too close together to bother
* with fancy curves. by default this is 80 pixels.
* loopbackRadius - the radius of a loopback connector. optional; defaults to 25.
* showLoopback - If set to false this tells the connector that it is ok to paint connections whose source and target is the same element with a connector running through the element. The default value for this is true; the connector always makes a loopback connection loop around the element rather than passing through it.
* orientation - defaults to "clockwise"; valid values are "clockwise" and "anticlockwise". Indicates in which direction a loopback connection should be considered to be travelling.
*/
/**
* Class: jsPlumb.Connectors.Straight
* The Straight connector draws a simple straight line between the two anchor points.
*
* Parameters:
* stub - optional distance to travel from each endpoint before making the connection between the two. defaults to 0.
* sourceStub - optional stub for the source endpoint only.
* targetStub - optional stub for the target endpoint only.
* gap - optional gap to leave between the endpoints and the start of the connector.
* sourceGap - optional gap for the source endpoint only.
* targetGap - optional gap for the target endpoint only.
*/
;(function() {
jsPlumb.Connection = function(params) {
var self = this, visible = true, _internalHover, _superClassHover,
_jsPlumb = params["_jsPlumb"],
jpcl = jsPlumb.CurrentLibrary,
_att = jpcl.getAttribute,
_gel = jpcl.getElementObject,
_ju = jsPlumbUtil,
_getOffset = jpcl.getOffset,
_newConnection = params.newConnection,
_newEndpoint = params.newEndpoint,
connector = null;
self.idPrefix = "_jsplumb_c_";
self.defaultLabelLocation = 0.5;
self.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
this.parent = params.parent;
overlayCapableJsPlumbUIComponent.apply(this, arguments);
// ************** get the source and target and register the connection. *******************
// VISIBILITY
this.isVisible = function() { return visible; };
this.setVisible = function(v) {
visible = v;
self[v ? "showOverlays" : "hideOverlays"]();
if (connector && connector.canvas) connector.canvas.style.display = v ? "block" : "none";
self.repaint();
};
// END VISIBILITY
// EDITABLE
var editable = params.editable === true;
this.setEditable = function(e) {
if (connector && connector.isEditable())
editable = e;
return editable;
};
this.isEditable = function() { return editable; };
this.editStarted = function() {
self.fire("editStarted", {
path:connector.getPath()
});
_jsPlumb.setHoverSuspended(true);
};
this.editCompleted = function() {
self.fire("editCompleted", {
path:connector.getPath()
});
self.setHover(false);
_jsPlumb.setHoverSuspended(false);
};
this.editCanceled = function() {
self.fire("editCanceled", {
path:connector.getPath()
});
self.setHover(false);
_jsPlumb.setHoverSuspended(false);
};
// END EDITABLE
// ADD CLASS/REMOVE CLASS - override to support adding/removing to/from endpoints
var _ac = this.addClass, _rc = this.removeClass;
this.addClass = function(c, informEndpoints) {
_ac(c);
if (informEndpoints) {
self.endpoints[0].addClass(c);
self.endpoints[1].addClass(c);
}
};
this.removeClass = function(c, informEndpoints) {
_rc(c);
if (informEndpoints) {
self.endpoints[0].removeClass(c);
self.endpoints[1].removeClass(c);
}
};
// TYPE
this.getTypeDescriptor = function() { return "connection"; };
this.getDefaultType = function() {
return {
parameters:{},
scope:null,
detachable:self._jsPlumb.Defaults.ConnectionsDetachable,
rettach:self._jsPlumb.Defaults.ReattachConnections,
paintStyle:self._jsPlumb.Defaults.PaintStyle || jsPlumb.Defaults.PaintStyle,
connector:self._jsPlumb.Defaults.Connector || jsPlumb.Defaults.Connector,
hoverPaintStyle:self._jsPlumb.Defaults.HoverPaintStyle || jsPlumb.Defaults.HoverPaintStyle,
overlays:self._jsPlumb.Defaults.ConnectorOverlays || jsPlumb.Defaults.ConnectorOverlays
};
};
var superAt = this.applyType;
this.applyType = function(t, doNotRepaint) {
superAt(t, doNotRepaint);
if (t.detachable != null) self.setDetachable(t.detachable);
if (t.reattach != null) self.setReattach(t.reattach);
if (t.scope) self.scope = t.scope;
editable = t.editable;
self.setConnector(t.connector, doNotRepaint);
};
// END TYPE
// HOVER
// override setHover to pass it down to the underlying connector
_superClassHover = self.setHover;
self.setHover = function(state) {
connector.setHover.apply(connector, arguments);
_superClassHover.apply(self, arguments);
};
_internalHover = function(state) {
if (!_jsPlumb.isConnectionBeingDragged()) {
self.setHover(state, false);
}
};
// END HOVER
var makeConnector = function(renderMode, connectorName, connectorArgs) {
var c = new Object();
if (!_jsPlumb.Defaults.DoNotThrowErrors && jsPlumb.Connectors[connectorName] == null)
throw { msg:"jsPlumb: unknown connector type '" + connectorName + "'" };
jsPlumb.Connectors[connectorName].apply(c, [connectorArgs]);
jsPlumb.ConnectorRenderers[renderMode].apply(c, [connectorArgs]);
return c;
};
this.setConnector = function(connectorSpec, doNotRepaint) {
if (connector != null) _ju.removeElements(connector.getDisplayElements());
var connectorArgs = {
_jsPlumb:self._jsPlumb,
parent:params.parent,
cssClass:params.cssClass,
container:params.container,
tooltip:self.tooltip,
"pointer-events":params["pointer-events"]
},
renderMode = _jsPlumb.getRenderMode();
if (_ju.isString(connectorSpec))
connector = makeConnector(renderMode, connectorSpec, connectorArgs); // lets you use a string as shorthand.
else if (_ju.isArray(connectorSpec)) {
if (connectorSpec.length == 1)
connector = makeConnector(renderMode, connectorSpec[0], connectorArgs);
else
connector = makeConnector(renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs));
}
// binds mouse listeners to the current connector.
self.bindListeners(connector, self, _internalHover);
self.canvas = connector.canvas;
if (editable && jsPlumb.ConnectorEditors != null && jsPlumb.ConnectorEditors[connector.type] && connector.isEditable()) {
new jsPlumb.ConnectorEditors[connector.type]({
connector:connector,
connection:self,
params:params.editorParams || { }
});
}
else {
editable = false;
}
if (!doNotRepaint) self.repaint();
};
this.getConnector = function() { return connector; };
// INITIALISATION CODE
this.source = _gel(params.source);
this.target = _gel(params.target);
// sourceEndpoint and targetEndpoint override source/target, if they are present. but
// source is not overridden if the Endpoint has declared it is not the final target of a connection;
// instead we use the source that the Endpoint declares will be the final source element.
if (params.sourceEndpoint) this.source = params.sourceEndpoint.endpointWillMoveTo || params.sourceEndpoint.getElement();
if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
// if a new connection is the result of moving some existing connection, params.previousConnection
// will have that Connection in it. listeners for the jsPlumbConnection event can look for that
// member and take action if they need to.
self.previousConnection = params.previousConnection;
this.sourceId = _att(this.source, "id");
this.targetId = _att(this.target, "id");
this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints.
this.endpoints = [];
this.endpointStyles = [];
// wrapped the main function to return null if no input given. this lets us cascade defaults properly.
var _makeAnchor = function(anchorParams, elementId) {
return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null;
},
prepareEndpoint = function(existing, index, params, element, elementId, connectorPaintStyle, connectorHoverPaintStyle) {
var e;
if (existing) {
self.endpoints[index] = existing;
existing.addConnection(self);
} else {
if (!params.endpoints) params.endpoints = [ null, null ];
var ep = params.endpoints[index]
|| params.endpoint
|| _jsPlumb.Defaults.Endpoints[index]
|| jsPlumb.Defaults.Endpoints[index]
|| _jsPlumb.Defaults.Endpoint
|| jsPlumb.Defaults.Endpoint;
if (!params.endpointStyles) params.endpointStyles = [ null, null ];
if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
// Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
if (es.fillStyle == null && connectorPaintStyle != null)
es.fillStyle = connectorPaintStyle.strokeStyle;
// TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
//*
if (es.outlineColor == null && connectorPaintStyle != null)
es.outlineColor = connectorPaintStyle.outlineColor;
if (es.outlineWidth == null && connectorPaintStyle != null)
es.outlineWidth = connectorPaintStyle.outlineWidth;
//*/
var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
// endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
if (connectorHoverPaintStyle != null) {
if (ehs == null) ehs = {};
if (ehs.fillStyle == null) {
ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
}
}
var a = params.anchors ? params.anchors[index] :
params.anchor ? params.anchor :
_makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId) ||
_makeAnchor(jsPlumb.Defaults.Anchors[index], elementId) ||
_makeAnchor(_jsPlumb.Defaults.Anchor, elementId) ||
_makeAnchor(jsPlumb.Defaults.Anchor, elementId),
u = params.uuids ? params.uuids[index] : null;
e = _newEndpoint({
paintStyle : es, hoverPaintStyle:ehs, endpoint : ep, connections : [ self ],
uuid : u, anchor : a, source : element, scope : params.scope, container:params.container,
reattach:params.reattach || _jsPlumb.Defaults.ReattachConnections,
detachable:params.detachable || _jsPlumb.Defaults.ConnectionsDetachable
});
self.endpoints[index] = e;
if (params.drawEndpoints === false) e.setVisible(false, true, true);
}
return e;
};
var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source,
self.sourceId, params.paintStyle, params.hoverPaintStyle);
if (eS) _ju.addToList(params.endpointsByElement, this.sourceId, eS);
var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target,
self.targetId, params.paintStyle, params.hoverPaintStyle);
if (eT) _ju.addToList(params.endpointsByElement, this.targetId, eT);
// if scope not set, set it to be the scope for the source endpoint.
if (!this.scope) this.scope = this.endpoints[0].scope;
// if delete endpoints on detach, keep a record of just exactly which endpoints they are.
self.endpointsToDeleteOnDetach = [null, null];
if (params.deleteEndpointsOnDetach) {
if (params.sourceIsNew) self.endpointsToDeleteOnDetach[0] = self.endpoints[0];
if (params.targetIsNew) self.endpointsToDeleteOnDetach[1] = self.endpoints[1];
}
// or if the endpoints were supplied, use them.
if (params.endpointsToDeleteOnDetach)
self.endpointsToDeleteOnDetach = params.endpointsToDeleteOnDetach;
// TODO these could surely be refactored into some method that tries them one at a time until something exists
self.setConnector(this.endpoints[0].connector ||
this.endpoints[1].connector ||
params.connector ||
_jsPlumb.Defaults.Connector ||
jsPlumb.Defaults.Connector, true);
if (params.path)
connector.setPath(params.path);
this.setPaintStyle(this.endpoints[0].connectorStyle ||
this.endpoints[1].connectorStyle ||
params.paintStyle ||
_jsPlumb.Defaults.PaintStyle ||
jsPlumb.Defaults.PaintStyle, true);
this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
this.endpoints[1].connectorHoverStyle ||
params.hoverPaintStyle ||
_jsPlumb.Defaults.HoverPaintStyle ||
jsPlumb.Defaults.HoverPaintStyle, true);
this.paintStyleInUse = this.getPaintStyle();
var _suspendedAt = _jsPlumb.getSuspendedAt();
_jsPlumb.updateOffset( { elId : this.sourceId, timestamp:_suspendedAt });
_jsPlumb.updateOffset( { elId : this.targetId, timestamp:_suspendedAt });
if(!_jsPlumb.isSuspendDrawing()) {
// paint the endpoints
var myInfo = _jsPlumb.getCachedData(this.sourceId),
myOffset = myInfo.o, myWH = myInfo.s,
otherInfo = _jsPlumb.getCachedData(this.targetId),
otherOffset = otherInfo.o,
otherWH = otherInfo.s,
initialTimestamp = _suspendedAt || _jsPlumb.timestamp(),
anchorLoc = this.endpoints[0].anchor.compute( {
xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
elementId:this.endpoints[0].elementId,
txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1],
timestamp:initialTimestamp
});
this.endpoints[0].paint( { anchorLoc : anchorLoc, timestamp:initialTimestamp });
anchorLoc = this.endpoints[1].anchor.compute( {
xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
elementId:this.endpoints[1].elementId,
txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0],
timestamp:initialTimestamp
});
this.endpoints[1].paint({ anchorLoc : anchorLoc, timestamp:initialTimestamp });
}
// END INITIALISATION CODE
// DETACHABLE
var _detachable = _jsPlumb.Defaults.ConnectionsDetachable;
if (params.detachable === false) _detachable = false;
if(self.endpoints[0].connectionsDetachable === false) _detachable = false;
if(self.endpoints[1].connectionsDetachable === false) _detachable = false;
this.isDetachable = function() {
return _detachable === true;
};
this.setDetachable = function(detachable) {
_detachable = detachable === true;
};
// END DETACHABLE
// REATTACH
var _reattach = params.reattach ||
self.endpoints[0].reattachConnections ||
self.endpoints[1].reattachConnections ||
_jsPlumb.Defaults.ReattachConnections;
this.isReattach = function() {
return _reattach === true;
};
this.setReattach = function(reattach) {
_reattach = reattach === true;
};
// END REATTACH
// COST + DIRECTIONALITY
// if cost not supplied, try to inherit from source endpoint
var _cost = params.cost || self.endpoints[0].getConnectionCost();
self.getCost = function() { return _cost; };
self.setCost = function(c) { _cost = c; };
var directed = params.directed;
// inherit directed flag if set no source endpoint
if (params.directed == null) directed = self.endpoints[0].areConnectionsDirected();
self.isDirected = function() { return directed === true; };
// END COST + DIRECTIONALITY
// PARAMETERS
// merge all the parameters objects into the connection. parameters set
// on the connection take precedence; then target endpoint params, then
// finally source endpoint params.
// TODO jsPlumb.extend could be made to take more than two args, and it would
// apply the second through nth args in order.
var _p = jsPlumb.extend({}, this.endpoints[0].getParameters());
jsPlumb.extend(_p, this.endpoints[1].getParameters());
jsPlumb.extend(_p, self.getParameters());
self.setParameters(_p);
// END PARAMETERS
// MISCELLANEOUS
this.getAttachedElements = function() {
return self.endpoints;
};
//
// changes the parent element of this connection to newParent. not exposed for the public API.
//
this.moveParent = function(newParent) {
var jpcl = jsPlumb.CurrentLibrary, curParent = jpcl.getParent(connector.canvas);
if (connector.bgCanvas) {
jpcl.removeElement(connector.bgCanvas);
jpcl.appendElement(connector.bgCanvas, newParent);
}
jpcl.removeElement(connector.canvas);
jpcl.appendElement(connector.canvas, newParent);
// this only applies for DOMOverlays
for (var i = 0; i < self.overlays.length; i++) {
if (self.overlays[i].isAppendedAtTopLevel) {
jpcl.removeElement(self.overlays[i].canvas);
jpcl.appendElement(self.overlays[i].canvas, newParent);
if (self.overlays[i].reattachListeners)
self.overlays[i].reattachListeners(connector);
}
}
if (connector.reattachListeners) // this is for SVG/VML; change an element's parent and you have to reinit its listeners.
connector.reattachListeners(); // the Canvas implementation doesn't have to care about this
};
// END MISCELLANEOUS
// PAINTING
/*
* Paints the Connection. Not exposed for public usage.
*
* Parameters:
* elId - Id of the element that is in motion.
* ui - current library's event system ui object (present if we came from a drag to get here).
* recalc - whether or not to recalculate all anchors etc before painting.
* timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
*/
var lastPaintedAt = null;
this.paint = function(params) {
if (visible) {
params = params || {};
var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp,
// if the moving object is not the source we must transpose the two references.
swap = false,
tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
if (timestamp == null || timestamp != lastPaintedAt) {
var sourceInfo = _jsPlumb.updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp }).o,
targetInfo = _jsPlumb.updateOffset( { elId : tId, timestamp : timestamp }).o, // update the target if this is a forced repaint. otherwise, only the source has been moved.
sE = this.endpoints[sIdx], tE = this.endpoints[tIdx];
if (params.clearEdits) {
sE.anchor.clearUserDefinedLocation();
tE.anchor.clearUserDefinedLocation();
connector.setEdited(false);
}
var sAnchorP = sE.anchor.getCurrentLocation(sE),
tAnchorP = tE.anchor.getCurrentLocation(tE);
connector.resetBounds();
connector.compute({
sourcePos:sAnchorP,
targetPos:tAnchorP,
sourceEndpoint:this.endpoints[sIdx],
targetEndpoint:this.endpoints[tIdx],
lineWidth:self.paintStyleInUse.lineWidth,
sourceInfo:sourceInfo,
targetInfo:targetInfo,
clearEdits:params.clearEdits === true
});
var overlayExtents = {
minX:Infinity,
minY:Infinity,
maxX:-Infinity,
maxY:-Infinity
};
// compute overlays. we do this first so we can get their placements, and adjust the
// container if needs be (if an overlay would be clipped)
for ( var i = 0; i < self.overlays.length; i++) {
var o = self.overlays[i];
if (o.isVisible()) {
self.overlayPlacements[i] = o.draw(connector, self.paintStyleInUse);
overlayExtents.minX = Math.min(overlayExtents.minX, self.overlayPlacements[i].minX);
overlayExtents.maxX = Math.max(overlayExtents.maxX, self.overlayPlacements[i].maxX);
overlayExtents.minY = Math.min(overlayExtents.minY, self.overlayPlacements[i].minY);
overlayExtents.maxY = Math.max(overlayExtents.maxY, self.overlayPlacements[i].maxY);
}
}
var lineWidth = parseFloat(self.paintStyleInUse.lineWidth || 1) / 2,
outlineWidth = parseFloat(self.paintStyleInUse.lineWidth || 0),
extents = {
xmin : Math.min(connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX),
ymin : Math.min(connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY),
xmax : Math.max(connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX),
ymax : Math.max(connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY)
};
// paint the connector.
connector.paint(self.paintStyleInUse, null, extents);
// and then the overlays
for ( var i = 0; i < self.overlays.length; i++) {
var o = self.overlays[i];
if (o.isVisible()) {
o.paint(self.overlayPlacements[i], extents);
}
}
}
lastPaintedAt = timestamp;
}
};
/*
* Function: repaint
* Repaints the Connection. No parameters exposed to public API.
*/
this.repaint = function(params) {
params = params || {};
var recalc = !(params.recalc === false);
this.paint({ elId : this.sourceId, recalc : recalc, timestamp:params.timestamp, clearEdits:params.clearEdits });
};
// the very last thing we do is check to see if a 'type' was supplied in the params
var _type = params.type || self.endpoints[0].connectionType || self.endpoints[1].connectionType;
if (_type)
self.addType(_type, params.data, _jsPlumb.isSuspendDrawing());
// END PAINTING
}; // END Connection class
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the jsPlumb connector editors. It is not deployed wth the released versions of jsPlumb; you need to
* include it as an extra script.
*
* Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
var AbstractEditor = function(params) {
var self = this;
};
// TODO: this is for a Straight segment.it would be better to have these all available somewjere, keyed
// by segment type
var findClosestPointOnPath = function(seg, x, y, i) {
var m = seg[0] == seg[2] ? Infinity : 0,
m2 = -1 / m,
out = { s:seg, m:m, i:i, x:-1, y:-1, d:Infinity };
if (m == 0) {
// a horizontal line. if x is in the range of this line then distance is delta y. otherwise we consider it to be
// infinity.
if ( (seg[0] <= x && x <= seg[2]) || (seg[2] <= x && x <= seg[0])) {
out.x = x,
out.y = seg[1];
out.d = Math.abs(y - seg[1]);
}
}
else if (m == Infinity || m == -Infinity) {
// a vertical line. if y is in the range of this line then distance is delta x. otherwise we consider it to be
// infinity.
if ((seg[1] <= y && y <= seg[3]) || (seg[3] <= y && y <= seg[1])){
out.x = seg[0];
out.y = y;
out.d = Math.abs(x - seg[0]);
}
}
else {
// closest point lies on normal from given point to this line.
var b = seg[1] - (m * seg[0]),
b2 = y - (m2 * x),
// now we know that
// y1 = m.x1 + b and y1 = m2.x1 + b2
// so: m.x1 + b = m2.x1 + b2
// x1(m - m2) = b2 - b
// x1 = (b2 - b) / (m - m2)
_x1 = (b2 -b) / (m - m2),
_y1 = (m * _x1) + b,
d = jsPlumbUtil.lineLength([ x, y ], [ _x1, _y1 ]),
fractionInSegment = jsPlumbUtil.lineLength([ _x1, _y1 ], [ seg[0], seg[1] ]);
out.d = d;
out.x = _x1;
out.y = _y1;
out.l = fractionInSegment / length;
}
return out;
};
jsPlumb.ConnectorEditors = {
/*
Function: FlowchartConnectorEditor
lets you drag the segments of a flowchart connection around.
*/
"Flowchart":function(params) {
AbstractEditor.apply(this, arguments);
var jpcl = jsPlumb.CurrentLibrary,
documentMouseUp = function(e) {
e.stopPropagation();
e.preventDefault();
jpcl.unbind(document, "mouseup", documentMouseUp);
jpcl.unbind(document, "mousemove", documentMouseMove);
downAt = null;
currentSegments = null;
selectedSegment = null;
segmentCoords = null;
params.connection.setHover(false);
params.connector.setSuspendEvents(false);
params.connection.endpoints[0].setSuspendEvents(false);
params.connection.endpoints[1].setSuspendEvents(false);
params.connection.editCompleted();
},
downAt = null,
currentSegments = null,
selectedSegment = null,
segmentCoords = null,
anchorsMoveable = params.params.anchorsMoveable,
sgn = function(p1, p2) {
if (p1[0] == p2[0])
return p1[1] < p2[1] ? 1 : -1;
else
return p1[0] < p2[0] ? 1 : -1;
},
// collapses currentSegments by joining subsequent segments that are in the
// same axis. we do this because it doesn't matter about stubs any longer once a user
// is editing a connector. so it is best to reduce the number of segments to the
// minimum.
_collapseSegments = function() {
var _last = null, _lastAxis = null, s = [];
for (var i = 0; i < currentSegments.length; i++) {
var seg = currentSegments[i], axis = seg[4], axisIndex = (axis == "v" ? 3 : 2);
if (_last != null && _lastAxis === axis) {
_last[axisIndex] = seg[axisIndex];
}
else {
s.push(seg);
_last = seg;
_lastAxis = seg[4];
}
}
currentSegments = s;
},
// attempt to shift anchor
_shiftAnchor = function(endpoint, horizontal, value) {
var elementSize = jpcl.getSize(endpoint.element),
sizeValue = elementSize[horizontal ? 1 : 0],
off = jpcl.getOffset(endpoint.element),
cc = jpcl.getElementObject(params.connector.canvas.parentNode),
co = jpcl.getOffset(cc),
offValue = off[horizontal ? "top" : "left"] - co[horizontal ? "top" : "left"],
ap = endpoint.anchor.getCurrentLocation(),
desiredLoc = horizontal ? params.connector.y + value : params.connector.x + value;
if (anchorsMoveable) {
if (offValue < desiredLoc && desiredLoc < offValue + sizeValue) {
// if still on the element, okay to move.
var udl = [ ap[0], ap[1] ];
ap[horizontal ? 1 : 0] = desiredLoc;
endpoint.anchor.setUserDefinedLocation(ap);
return value;
}
else {
// otherwise, clamp to element edge
var edgeVal = desiredLoc < offValue ? offValue : offValue + sizeValue;
return edgeVal - (horizontal ? params.connector.y: params.connector.x);
}
}
else {
// otherwise, return the current anchor point.
return ap[horizontal ? 1 : 0] - params.connector[horizontal ? "y" : "x"];
}
},
_updateSegmentOrientation = function(seg) {
if (seg[0] != seg[2]) seg[5] = (seg[0] < seg[2]) ? 1 : -1;
if (seg[1] != seg[3]) seg[6] = (seg[1] < seg[3]) ? 1 : -1;
},
documentMouseMove = function(e) {
if (selectedSegment != null) {
var m = selectedSegment.m, s = selectedSegment.s,
x = (e.pageX || e.page.x), y = (e.pageY || e.page.y),
dx = m == 0 ? 0 : x - downAt[0], dy = m == 0 ? y - downAt[1] : 0,
newX1 = segmentCoords[0] + dx,
newY1 = segmentCoords[1] + dy,
newX2 = segmentCoords[2] + dx,
newY2 = segmentCoords[3] + dy,
horizontal = s[4] == "h";
// so here we know the new x,y values we would like to set for the start
// and end of this segment. but we may not be able to set these values: if this
// is the first segment, for example, then we are constrained by how far the anchor
// can move (before it slides off its element). same thing goes if this is the last
// segment. if this is not the first or last segment then there are other considerations.
// we know, from having run collapse segments, that there will never be two
// consecutive segments that are not at right angles to each other, so what we need to
// know is whether we can adjust the endpoint of the previous segment to the values we
// want, and the same question for the start values of the next segment. the answer to
// that is whether or not the segment in question would be rendered too small by such
// a change. if that is the case (and the same goes for anchors) then we want to know
// what an agreeable value is, and we use that.
if (selectedSegment.i == 0) {
var anchorLoc = _shiftAnchor(params.connection.endpoints[0], horizontal, horizontal ? newY1 : newX1);
if (horizontal)
newY1 = newY2 = anchorLoc;
else
newX1 = newX2 = anchorLoc;
currentSegments[1][0] = newX2;
currentSegments[1][1] = newY2;
_updateSegmentOrientation(currentSegments[1]);
}
else if (selectedSegment.i == currentSegments.length - 1) {
var anchorLoc = _shiftAnchor(params.connection.endpoints[1], horizontal, horizontal ? newY1 : newX1);
if (horizontal)
newY1 = newY2 = anchorLoc;
else
newX1 = newX2 = anchorLoc;
currentSegments[currentSegments.length - 2][2] = newX1;
currentSegments[currentSegments.length - 2][3] = newY1;
_updateSegmentOrientation(currentSegments[currentSegments.length - 2]);
}
else {
if (!horizontal) {
currentSegments[selectedSegment.i - 1][2] = newX1;
currentSegments[selectedSegment.i + 1][0] = newX2;
}
else {
currentSegments[selectedSegment.i - 1][3] = newY1;
currentSegments[selectedSegment.i + 1][1] = newY2;
}
_updateSegmentOrientation(currentSegments[selectedSegment.i + 1]);
_updateSegmentOrientation(currentSegments[selectedSegment.i - 1]);
}
s[0] = newX1;
s[1] = newY1;
s[2] = newX2;
s[3] = newY2;
params.connector.setSegments(currentSegments);
params.connection.repaint();
params.connection.endpoints[0].repaint();
params.connection.endpoints[1].repaint();
params.connector.setEdited(true);
}
};
// bind to mousedown and mouseup, for editing
params.connector.bind("mousedown", function(c, e) {
var x = (e.pageX || e.page.x),
y = (e.pageY || e.page.y),
oe = jpcl.getElementObject(params.connection.getConnector().canvas),
o = jpcl.getOffset(oe),
minD = Infinity;
params.connection.setHover(true);
params.connector.setSuspendEvents(true);
params.connection.endpoints[0].setSuspendEvents(true);
params.connection.endpoints[1].setSuspendEvents(true);
currentSegments = params.connector.getOriginalSegments();
_collapseSegments();
for (var i = 0; i < currentSegments.length; i++) {
var _s = findClosestPointOnPath(currentSegments[i], x - o.left, y - o.top, i);
if (_s.d < minD) {
selectedSegment = _s;
segmentCoords = [ _s.s[0], _s.s[1], _s.s[2], _s.s[3] ]; // copy the coords at mousedown
minD = _s.d;
}
}
downAt = [ x, y ];
jpcl.bind(document, "mouseup", documentMouseUp);
jpcl.bind(document, "mousemove", documentMouseMove);
if (selectedSegment != null) {
params.connection.editStarted();
}
});
}
};
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
*
* Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
/**
* Function: Constructor
*
* Parameters:
* stub - minimum length for the stub at each end of the connector. This can be an integer, giving a value for both ends of the connections,
* or an array of two integers, giving separate values for each end. The default is an integer with value 30 (pixels).
* gap - gap to leave between the end of the connector and the element on which the endpoint resides. if you make this larger than stub then you will see some odd looking behaviour.
Like stub, this can be an array or a single value. defaults to 0 pixels for each end.
* cornerRadius - optional, defines the radius of corners between segments. defaults to 0 (hard edged corners).
* alwaysRespectStubs - defaults to false. whether or not the connectors should always draw the stub, or, if the two elements
are in close proximity to each other (closer than the sum of the two stubs), to adjust the stubs.
*/
jsPlumb.Connectors.Flowchart = function(params) {
this.type = "Flowchart";
params = params || {};
params.stub = params.stub || 30;
var self = this,
_super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments),
midpoint = params.midpoint || 0.5,
points = [], segments = [],
grid = params.grid,
alwaysRespectStubs = params.alwaysRespectStubs,
userSuppliedSegments = null,
lastx = null, lasty = null, lastOrientation,
cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0,
sgn = function(n) { return n < 0 ? -1 : n == 0 ? 0 : 1; },
/**
* helper method to add a segment.
*/
addSegment = function(segments, x, y, paintInfo) {
if (lastx == x && lasty == y) return;
var lx = lastx == null ? paintInfo.sx : lastx,
ly = lasty == null ? paintInfo.sy : lasty,
o = lx == x ? "v" : "h",
sgnx = sgn(x - lx),
sgny = sgn(y - ly);
lastx = x;
lasty = y;
segments.push([lx, ly, x, y, o, sgnx, sgny]);
},
segLength = function(s) {
return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2));
},
_cloneArray = function(a) { var _a = []; _a.push.apply(_a, a); return _a;},
updateMinMax = function(a1) {
self.bounds.minX = Math.min(self.bounds.minX, a1[2]);
self.bounds.maxX = Math.max(self.bounds.maxX, a1[2]);
self.bounds.minY = Math.min(self.bounds.minY, a1[3]);
self.bounds.maxY = Math.max(self.bounds.maxY, a1[3]);
},
writeSegments = function(segments, paintInfo) {
var current, next;
for (var i = 0; i < segments.length - 1; i++) {
current = current || _cloneArray(segments[i]);
next = _cloneArray(segments[i + 1]);
if (cornerRadius > 0 && current[4] != next[4]) {
var radiusToUse = Math.min(cornerRadius, segLength(current), segLength(next));
// right angle. adjust current segment's end point, and next segment's start point.
current[2] -= current[5] * radiusToUse;
current[3] -= current[6] * radiusToUse;
next[0] += next[5] * radiusToUse;
next[1] += next[6] * radiusToUse;
var ac = (current[6] == next[5] && next[5] == 1) ||
((current[6] == next[5] && next[5] == 0) && current[5] != next[6]) ||
(current[6] == next[5] && next[5] == -1),
sgny = next[1] > current[3] ? 1 : -1,
sgnx = next[0] > current[2] ? 1 : -1,
sgnEqual = sgny == sgnx,
cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2],
cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1];
_super.addSegment("Straight", {
x1:current[0], y1:current[1], x2:current[2], y2:current[3]
});
_super.addSegment("Arc", {
r:radiusToUse,
x1:current[2],
y1:current[3],
x2:next[0],
y2:next[1],
cx:cx,
cy:cy,
ac:ac
});
}
else {
// dx + dy are used to adjust for line width.
var dx = (current[2] == current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2),
dy = (current[3] == current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2);
_super.addSegment("Straight", {
x1:current[0]- dx, y1:current[1]-dy, x2:current[2] + dx, y2:current[3] + dy
});
}
current = next;
}
// last segment
_super.addSegment("Straight", {
x1:next[0], y1:next[1], x2:next[2], y2:next[3]
});
};
this.setSegments = function(s) {
userSuppliedSegments = s;
};
this.isEditable = function() { return true; };
/*
Function: getOriginalSegments
Gets the segments before the addition of rounded corners. This is used by the flowchart
connector editor, since it only wants to concern itself with the original segments.
*/
this.getOriginalSegments = function() {
return userSuppliedSegments || segments;
};
this._compute = function(paintInfo, params) {
if (params.clearEdits)
userSuppliedSegments = null;
if (userSuppliedSegments != null) {
writeSegments(userSuppliedSegments, paintInfo);
return;
}
segments = [];
lastx = null; lasty = null;
lastOrientation = null;
var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint),
midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint);
var findClearedLine = function(start, mult, anchorPos, dimension) {
return start + (mult * (( 1 - anchorPos) * dimension) + _super.maxStub);
},
orientations = { x:[ 0, 1 ], y:[ 1, 0 ] },
commonStubCalculator = function(axis) {
return [ paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY ];
},
stubCalculators = {
perpendicular:commonStubCalculator,
orthogonal:commonStubCalculator,
opposite:function(axis) {
var pi = paintInfo,
idx = axis == "x" ? 0 : 1,
areInProximity = {
"x":function() {
return ( (pi.so[idx] == 1 && (
( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) ||
( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) ||
( (pi.so[idx] == -1 && (
( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) ||
( (pi.sx < pi.endStubX) && (pi.tx < pi.sx)))));
},
"y":function() {
return ( (pi.so[idx] == 1 && (
( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) ||
( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) ||
( (pi.so[idx] == -1 && (
( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) ||
( (pi.sy < pi.endStubY) && (pi.ty < pi.sy)))));
}
};
if (!alwaysRespectStubs && areInProximity[axis]()) {
return {
"x":[(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY],
"y":[paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2]
}[axis];
}
else {
return [ paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY ];
}
}
},
lineCalculators = {
perpendicular : function(axis, ss, oss, es, oes) {
with (paintInfo) {
var sis = {
x:[ [ [ 1,2,3,4 ], null, [ 2,1,4,3 ] ], null, [ [ 4,3,2,1 ], null, [ 3,4,1,2 ] ] ],
y:[ [ [ 3,2,1,4 ], null, [ 2,3,4,1 ] ], null, [ [ 4,1,2,3 ], null, [ 1,4,3,2 ] ] ]
},
stubs = {
x:[ [ startStubX, endStubX ] , null, [ endStubX, startStubX ] ],
y:[ [ startStubY, endStubY ] , null, [ endStubY, startStubY ] ]
},
midLines = {
x:[ [ midx, startStubY ], [ midx, endStubY ] ],
y:[ [ startStubX, midy ], [ endStubX, midy ] ]
},
linesToEnd = {
x:[ [ endStubX, startStubY ] ],
y:[ [ startStubX, endStubY ] ]
},
startToEnd = {
x:[ [ startStubX, endStubY ], [ endStubX, endStubY ] ],
y:[ [ endStubX, startStubY ], [ endStubX, endStubY ] ]
},
startToMidToEnd = {
x:[ [ startStubX, midy ], [ endStubX, midy ], [ endStubX, endStubY ] ],
y:[ [ midx, startStubY ], [ midx, endStubY ], [ endStubX, endStubY ] ]
},
otherStubs = {
x:[ startStubY, endStubY ],
y:[ startStubX, endStubX ]
},
soIdx = orientations[axis][0], toIdx = orientations[axis][1],
_so = so[soIdx] + 1,
_to = to[toIdx] + 1,
otherFlipped = (to[toIdx] == -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (to[toIdx] == 1 && (otherStubs[axis][1] > otherStubs[axis][0])),
stub1 = stubs[axis][_so][0],
stub2 = stubs[axis][_so][1],
segmentIndexes = sis[axis][_so][_to];
if (segment == segmentIndexes[3] || (segment == segmentIndexes[2] && otherFlipped)) {
return midLines[axis];
}
else if (segment == segmentIndexes[2] && stub2 < stub1) {
return linesToEnd[axis];
}
else if ((segment == segmentIndexes[2] && stub2 >= stub1) || (segment == segmentIndexes[1] && !otherFlipped)) {
return startToMidToEnd[axis];
}
else if (segment == segmentIndexes[0] || (segment == segmentIndexes[1] && otherFlipped)) {
return startToEnd[axis];
}
}
},
orthogonal : function(axis, startStub, otherStartStub, endStub, otherEndStub) {
var pi = paintInfo,
extent = {
"x":pi.so[0] == -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub),
"y":pi.so[1] == -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub)
}[axis];
return {
"x":[ [ extent, otherStartStub ],[ extent, otherEndStub ], [ endStub, otherEndStub ] ],
"y":[ [ otherStartStub, extent ], [ otherEndStub, extent ], [ otherEndStub, endStub ] ]
}[axis];
},
opposite : function(axis, ss, oss, es, oes) {
var pi = paintInfo,
otherAxis = {"x":"y","y":"x"}[axis],
dim = {"x":"height","y":"width"}[axis],
comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"];
if (params.sourceEndpoint.elementId == params.targetEndpoint.elementId) {
var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub;
return {
"x":[ [ ss, _val ], [ es, _val ] ],
"y":[ [ _val, ss ], [ _val, es ] ]
}[axis];
}
else if (!comparator || (pi.so[idx] == 1 && ss > es)
|| (pi.so[idx] == -1 && ss < es)) {
return {
"x":[[ ss, midy ], [ es, midy ]],
"y":[[ midx, ss ], [ midx, es ]]
}[axis];
}
else if ((pi.so[idx] == 1 && ss < es) || (pi.so[idx] == -1 && ss > es)) {
return {
"x":[[ midx, pi.sy ], [ midx, pi.ty ]],
"y":[[ pi.sx, midy ], [ pi.tx, midy ]]
}[axis];
}
}
};
var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis),
idx = paintInfo.sourceAxis == "x" ? 0 : 1,
oidx = paintInfo.sourceAxis == "x" ? 1 : 0,
ss = stubs[idx],
oss = stubs[oidx],
es = stubs[idx + 2],
oes = stubs[oidx + 2];
// add the start stub segment.
addSegment(segments, stubs[0], stubs[1], paintInfo);
// compute the rest of the line
var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes);
if (p) {
for (var i = 0; i < p.length; i++) {
addSegment(segments, p[i][0], p[i][1], paintInfo);
}
}
// line to end stub
addSegment(segments, stubs[2], stubs[3], paintInfo);
// end stub to end
addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo);
writeSegments(segments, paintInfo);
};
this.getPath = function() {
var _last = null, _lastAxis = null, s = [], segs = userSuppliedSegments || segments;
for (var i = 0; i < segs.length; i++) {
var seg = segs[i], axis = seg[4], axisIndex = (axis == "v" ? 3 : 2);
if (_last != null && _lastAxis === axis) {
_last[axisIndex] = seg[axisIndex];
}
else {
if (seg[0] != seg[2] || seg[1] != seg[3]) {
s.push({
start:[ seg[0], seg[1] ],
end:[ seg[2], seg[3] ]
});
_last = seg;
_lastAxis = seg[4];
}
}
}
return s;
};
this.setPath = function(path) {
userSuppliedSegments = [];
for (var i = 0; i < path.length; i++) {
var lx = path[i].start[0],
ly = path[i].start[1],
x = path[i].end[0],
y = path[i].end[1],
o = lx == x ? "v" : "h",
sgnx = sgn(x - lx),
sgny = sgn(y - ly);
userSuppliedSegments.push([lx, ly, x, y, o, sgnx, sgny]);
}
};
};
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the state machine connectors.
*
* Thanks to Brainstorm Mobile Solutions for supporting the development of these.
*
* Copyright (c) 2010 - 2013 Simon Porritt (simon.porritt@gmail.com)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
var Line = function(x1, y1, x2, y2) {
this.m = (y2 - y1) / (x2 - x1);
this.b = -1 * ((this.m * x1) - y1);
this.rectIntersect = function(x,y,w,h) {
var results = [];
// try top face
// the equation of the top face is y = (0 * x) + b; y = b.
var xInt = (y - this.b) / this.m;
// test that the X value is in the line's range.
if (xInt >= x && xInt <= (x + w)) results.push([ xInt, (this.m * xInt) + this.b ]);
// try right face
var yInt = (this.m * (x + w)) + this.b;
if (yInt >= y && yInt <= (y + h)) results.push([ (yInt - this.b) / this.m, yInt ]);
// bottom face
var xInt = ((y + h) - this.b) / this.m;
// test that the X value is in the line's range.
if (xInt >= x && xInt <= (x + w)) results.push([ xInt, (this.m * xInt) + this.b ]);
// try left face
var yInt = (this.m * x) + this.b;
if (yInt >= y && yInt <= (y + h)) results.push([ (yInt - this.b) / this.m, yInt ]);
if (results.length == 2) {
var midx = (results[0][0] + results[1][0]) / 2, midy = (results[0][1] + results[1][1]) / 2;
results.push([ midx,midy ]);
// now calculate the segment inside the rectangle where the midpoint lies.
var xseg = midx <= x + (w / 2) ? -1 : 1,
yseg = midy <= y + (h / 2) ? -1 : 1;
results.push([xseg, yseg]);
return results;
}
return null;
};
},
_segment = function(x1, y1, x2, y2) {
if (x1 <= x2 && y2 <= y1) return 1;
else if (x1 <= x2 && y1 <= y2) return 2;
else if (x2 <= x1 && y2 >= y1) return 3;
return 4;
},
// the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the
// two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they
// are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the
// center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and
// direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element
// lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left.
//
// sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are:
//
// 0 - absolute x
// 1 - absolute y
// 2 - proportional x in element (0 is left edge, 1 is right edge)
// 3 - proportional y in element (0 is top edge, 1 is bottom edge)
//
_findControlPoint = function(midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) {
// TODO (maybe)
// - if anchor pos is 0.5, make the control point take into account the relative position of the elements.
if (distance <= proximityLimit) return [midx, midy];
if (segment === 1) {
if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
else return [ midx + (-1 * dx) , midy + (-1 * dy) ];
}
else if (segment === 2) {
if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
else return [ midx + (1 * dx) , midy + (-1 * dy) ];
}
else if (segment === 3) {
if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
else return [ midx + (-1 * dx) , midy + (-1 * dy) ];
}
else if (segment === 4) {
if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
else return [ midx + (1 * dx) , midy + (-1 * dy) ];
}
};
/**
* Class: Connectors.StateMachine
* Provides 'state machine' connectors.
*/
/*
* Function: Constructor
*
* Parameters:
* curviness - measure of how "curvy" the connectors will be. this is translated as the distance that the
* Bezier curve's control point is from the midpoint of the straight line connecting the two
* endpoints, and does not mean that the connector is this wide. The Bezier curve never reaches
* its control points; they act as gravitational masses. defaults to 10.
* margin - distance from element to start and end connectors, in pixels. defaults to 5.
* proximityLimit - sets the distance beneath which the elements are consider too close together to bother
* with fancy curves. by default this is 80 pixels.
* loopbackRadius - the radius of a loopback connector. optional; defaults to 25.
* showLoopback - If set to false this tells the connector that it is ok to paint connections whose source and target is the same element with a connector running through the element. The default value for this is true; the connector always makes a loopback connection loop around the element rather than passing through it.
*/
jsPlumb.Connectors.StateMachine = function(params) {
params = params || {};
this.type = "StateMachine";
var self = this,
_super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments),
curviness = params.curviness || 10,
margin = params.margin || 5,
proximityLimit = params.proximityLimit || 80,
clockwise = params.orientation && params.orientation === "clockwise",
loopbackRadius = params.loopbackRadius || 25,
showLoopback = params.showLoopback !== false;
this._compute = function(paintInfo, params) {
var w = Math.abs(params.sourcePos[0] - params.targetPos[0]),
h = Math.abs(params.sourcePos[1] - params.targetPos[1]),
x = Math.min(params.sourcePos[0], params.targetPos[0]),
y = Math.min(params.sourcePos[1], params.targetPos[1]);
if (!showLoopback || (params.sourceEndpoint.elementId !== params.targetEndpoint.elementId)) {
var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w,
_sy = params.sourcePos[1] < params.targetPos[1] ? 0:h,
_tx = params.sourcePos[0] < params.targetPos[0] ? w : 0,
_ty = params.sourcePos[1] < params.targetPos[1] ? h : 0;
// now adjust for the margin
if (params.sourcePos[2] === 0) _sx -= margin;
if (params.sourcePos[2] === 1) _sx += margin;
if (params.sourcePos[3] === 0) _sy -= margin;
if (params.sourcePos[3] === 1) _sy += margin;
if (params.targetPos[2] === 0) _tx -= margin;
if (params.targetPos[2] === 1) _tx += margin;
if (params.targetPos[3] === 0) _ty -= margin;
if (params.targetPos[3] === 1) _ty += margin;
//
// these connectors are quadratic bezier curves, having a single control point. if both anchors
// are located at 0.5 on their respective faces, the control point is set to the midpoint and you
// get a straight line. this is also the case if the two anchors are within 'proximityLimit', since
// it seems to make good aesthetic sense to do that. outside of that, the control point is positioned
// at 'curviness' pixels away along the normal to the straight line connecting the two anchors.
//
// there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes
// in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node,
// for example, we might increase the distance the control point is away from the midpoint in a bid to
// steer it around that node. this will work within limits, but i think those limits would also be the likely
// limits for, once again, aesthetic good sense in the layout of a chart using these connectors.
//
// the second possible change is actually two possible changes: firstly, it is possible we should gradually
// decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some
// point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors
// with respect to how far their anchor is from the center of its respective face. this could either look cool,
// or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time.
//
var _midx = (_sx + _tx) / 2, _midy = (_sy + _ty) / 2,
m2 = (-1 * _midx) / _midy, theta2 = Math.atan(m2),
dy = (m2 == Infinity || m2 == -Infinity) ? 0 : Math.abs(curviness / 2 * Math.sin(theta2)),
dx = (m2 == Infinity || m2 == -Infinity) ? 0 : Math.abs(curviness / 2 * Math.cos(theta2)),
segment = _segment(_sx, _sy, _tx, _ty),
distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)),
// calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it
// will work by extending the control point to force the curve to be, um, curvier.
_controlPoint = _findControlPoint(_midx,
_midy,
segment,
params.sourcePos,
params.targetPos,
curviness, curviness,
distance,
proximityLimit);
_super.addSegment("Bezier", {
x1:_tx, y1:_ty, x2:_sx, y2:_sy,
cp1x:_controlPoint[0], cp1y:_controlPoint[1],
cp2x:_controlPoint[0], cp2y:_controlPoint[1]
});
}
else {
// a loopback connector. draw an arc from one anchor to the other.
var x1 = params.sourcePos[0], x2 = params.sourcePos[0], y1 = params.sourcePos[1] - margin, y2 = params.sourcePos[1] - margin,
cx = x1, cy = y1 - loopbackRadius;
// canvas sizing stuff, to ensure the whole painted area is visible.
w = 2 * loopbackRadius,
h = 2 * loopbackRadius,
x = cx - loopbackRadius,
y = cy - loopbackRadius;
paintInfo.points[0] = x;
paintInfo.points[1] = y;
paintInfo.points[2] = w;
paintInfo.points[3] = h;
// ADD AN ARC SEGMENT.
_super.addSegment("Arc", {
x1:(x1-x) + 4,
y1:y1-y,
startAngle:0,
endAngle: 2 * Math.PI,
r:loopbackRadius,
ac:!clockwise,
x2:(x1-x) - 4,
y2:y1-y,
cx:cx-x,
cy:cy-y
});
}
};
};
})();
/*
// a possible rudimentary avoidance scheme, old now, perhaps not useful.
// if (avoidSelector) {
// var testLine = new Line(sourcePos[0] + _sx,sourcePos[1] + _sy,sourcePos[0] + _tx,sourcePos[1] + _ty);
// var sel = jsPlumb.getSelector(avoidSelector);
// for (var i = 0; i < sel.length; i++) {
// var id = jsPlumb.getId(sel[i]);
// if (id != sourceEndpoint.elementId && id != targetEndpoint.elementId) {
// o = jsPlumb.getOffset(id), s = jsPlumb.getSize(id);
//
// if (o && s) {
// var collision = testLine.rectIntersect(o.left,o.top,s[0],s[1]);
// if (collision) {
// set the control point to be a certain distance from the midpoint of the two points that
// the line crosses on the rectangle.
// TODO where will this 75 number come from?
// _controlX = collision[2][0] + (75 * collision[3][0]);
// / _controlY = collision[2][1] + (75 * collision[3][1]);
// }
// }
// }
// }
//}
*/
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the default Connectors, Endpoint and Overlay definitions.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
/**
*
* Helper class to consume unused mouse events by components that are DOM elements and
* are used by all of the different rendering modes.
*
*/
jsPlumb.DOMElementComponent = function(params) {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
// when render mode is canvas, these functions may be called by the canvas mouse handler.
// this component is safe to pipe this stuff to /dev/null.
this.mousemove =
this.dblclick =
this.click =
this.mousedown =
this.mouseup = function(e) { };
};
jsPlumb.Segments = {
/*
* Class: AbstractSegment
* A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc',
* 'Bezier'. This is new from 1.4.1, and gives us a lot more flexibility when drawing connections: things such
* as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are
* much easier to do now.
*
* A Segment is responsible for providing coordinates for painting it, and also must be able to report its length.
*
*/
AbstractSegment : function(params) {
this.params = params;
/**
* Function: findClosestPointOnPath
* Finds the closest point on this segment to the given [x, y],
* returning both the x and y of the point plus its distance from
* the supplied point, and its location along the length of the
* path inscribed by the segment. This implementation returns
* Infinity for distance and null values for everything else;
* subclasses are expected to override.
*/
this.findClosestPointOnPath = function(x, y) {
return {
d:Infinity,
x:null,
y:null,
l:null
};
};
this.getBounds = function() {
return {
minX:Math.min(params.x1, params.x2),
minY:Math.min(params.y1, params.y2),
maxX:Math.max(params.x1, params.x2),
maxY:Math.max(params.y1, params.y2)
};
};
},
Straight : function(params) {
var self = this,
_super = jsPlumb.Segments.AbstractSegment.apply(this, arguments),
length, m, m2, x1, x2, y1, y2,
_recalc = function() {
length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
m = jsPlumbUtil.gradient({x:x1, y:y1}, {x:x2, y:y2});
m2 = -1 / m;
};
this.type = "Straight";
self.getLength = function() { return length; };
self.getGradient = function() { return m; };
this.getCoordinates = function() {
return { x1:x1,y1:y1,x2:x2,y2:y2 };
};
this.setCoordinates = function(coords) {
x1 = coords.x1; y1 = coords.y1; x2 = coords.x2; y2 = coords.y2;
_recalc();
};
this.setCoordinates({x1:params.x1, y1:params.y1, x2:params.x2, y2:params.y2});
this.getBounds = function() {
return {
minX:Math.min(x1, x2),
minY:Math.min(y1, y2),
maxX:Math.max(x1, x2),
maxY:Math.max(y1, y2)
};
};
/**
* returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive. for the straight line segment this is simple maths.
*/
this.pointOnPath = function(location, absolute) {
if (location == 0 && !absolute)
return { x:x1, y:y1 };
else if (location == 1 && !absolute)
return { x:x2, y:y2 };
else {
var l = absolute ? location > 0 ? location : length + location : location * length;
return jsPlumbUtil.pointOnLine({x:x1, y:y1}, {x:x2, y:y2}, l);
}
};
/**
* returns the gradient of the segment at the given point - which for us is constant.
*/
this.gradientAtPoint = function(_) {
return m;
};
/**
* returns the point on the segment's path that is 'distance' along the length of the path from 'location', where
* 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
* this hands off to jsPlumbUtil to do the maths, supplying two points and the distance.
*/
this.pointAlongPathFrom = function(location, distance, absolute) {
var p = self.pointOnPath(location, absolute),
farAwayPoint = location == 1 ? {
x:x1 + ((x2 - x1) * 10),
y:y1 + ((y1 - y2) * 10)
} : distance <= 0 ? {x:x1, y:y1} : {x:x2, y:y2 };
if (distance <= 0 && Math.abs(distance) > 1) distance *= -1;
return jsPlumbUtil.pointOnLine(p, farAwayPoint, distance);
};
/**
Function: findClosestPointOnPath
Finds the closest point on this segment to [x,y]. See
notes on this method in AbstractSegment.
*/
this.findClosestPointOnPath = function(x, y) {
if (m == 0) {
return {
x:x,
y:y1,
d:Math.abs(y - y1)
};
}
else if (m == Infinity || m == -Infinity) {
return {
x:x1,
y:y,
d:Math.abs(x - 1)
};
}
else {
// closest point lies on normal from given point to this line.
var b = y1 - (m * x1),
b2 = y - (m2 * x),
// y1 = m.x1 + b and y1 = m2.x1 + b2
// so m.x1 + b = m2.x1 + b2
// x1(m - m2) = b2 - b
// x1 = (b2 - b) / (m - m2)
_x1 = (b2 -b) / (m - m2),
_y1 = (m * _x1) + b,
d = jsPlumbUtil.lineLength([ x, y ], [ _x1, _y1 ]),
fractionInSegment = jsPlumbUtil.lineLength([ _x1, _y1 ], [ x1, y1 ]);
return { d:d, x:_x1, y:_y1, l:fractionInSegment / length};
}
};
},
/*
Arc Segment. You need to supply:
r - radius
cx - center x for the arc
cy - center y for the arc
ac - whether the arc is anticlockwise or not. default is clockwise.
and then either:
startAngle - startAngle for the arc.
endAngle - endAngle for the arc.
or:
x1 - x for start point
y1 - y for start point
x2 - x for end point
y2 - y for end point
*/
Arc : function(params) {
var self = this,
_super = jsPlumb.Segments.AbstractSegment.apply(this, arguments),
_calcAngle = function(_x, _y) {
return jsPlumbUtil.theta([params.cx, params.cy], [_x, _y]);
},
_calcAngleForLocation = function(location) {
if (self.anticlockwise) {
var sa = self.startAngle < self.endAngle ? self.startAngle + TWO_PI : self.startAngle,
s = Math.abs(sa - self.endAngle);
return sa - (s * location);
}
else {
var ea = self.endAngle < self.startAngle ? self.endAngle + TWO_PI : self.endAngle,
s = Math.abs (ea - self.startAngle);
return self.startAngle + (s * location);
}
},
TWO_PI = 2 * Math.PI;
this.radius = params.r;
this.anticlockwise = params.ac;
this.type = "Arc";
if (params.startAngle && params.endAngle) {
this.startAngle = params.startAngle;
this.endAngle = params.endAngle;
this.x1 = params.cx + (self.radius * Math.cos(params.startAngle));
this.y1 = params.cy + (self.radius * Math.sin(params.startAngle));
this.x2 = params.cx + (self.radius * Math.cos(params.endAngle));
this.y2 = params.cy + (self.radius * Math.sin(params.endAngle));
}
else {
this.startAngle = _calcAngle(params.x1, params.y1);
this.endAngle = _calcAngle(params.x2, params.y2);
this.x1 = params.x1;
this.y1 = params.y1;
this.x2 = params.x2;
this.y2 = params.y2;
}
if (this.endAngle < 0) this.endAngle += TWO_PI;
if (this.startAngle < 0) this.startAngle += TWO_PI;
// segment is used by vml
this.segment = jsPlumbUtil.segment([this.x1, this.y1], [this.x2, this.y2]);
// we now have startAngle and endAngle as positive numbers, meaning the
// absolute difference (|d|) between them is the sweep (s) of this arc, unless the
// arc is 'anticlockwise' in which case 's' is given by 2PI - |d|.
var ea = self.endAngle < self.startAngle ? self.endAngle + TWO_PI : self.endAngle;
self.sweep = Math.abs (ea - self.startAngle);
if (self.anticlockwise) self.sweep = TWO_PI - self.sweep;
var circumference = 2 * Math.PI * self.radius,
frac = self.sweep / TWO_PI,
length = circumference * frac;
this.getLength = function() {
return length;
};
this.getBounds = function() {
return {
minX:params.cx - params.r,
maxX:params.cx + params.r,
minY:params.cy - params.r,
maxY:params.cy + params.r
}
};
var VERY_SMALL_VALUE = 0.0000000001,
gentleRound = function(n) {
var f = Math.floor(n), r = Math.ceil(n);
if (n - f < VERY_SMALL_VALUE)
return f;
else if (r - n < VERY_SMALL_VALUE)
return r;
return n;
};
/**
* returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive.
*/
this.pointOnPath = function(location, absolute) {
if (location == 0) {
return { x:self.x1, y:self.y1, theta:self.startAngle };
}
else if (location == 1) {
return { x:self.x2, y:self.y2, theta:self.endAngle };
}
if (absolute) {
location = location / length;
}
var angle = _calcAngleForLocation(location),
_x = params.cx + (params.r * Math.cos(angle)),
_y = params.cy + (params.r * Math.sin(angle));
return { x:gentleRound(_x), y:gentleRound(_y), theta:angle };
};
/**
* returns the gradient of the segment at the given point.
*/
this.gradientAtPoint = function(location, absolute) {
var p = self.pointOnPath(location, absolute);
var m = jsPlumbUtil.normal( [ params.cx, params.cy ], [p.x, p.y ] );
if (!self.anticlockwise && (m == Infinity || m == -Infinity)) m *= -1;
return m;
};
this.pointAlongPathFrom = function(location, distance, absolute) {
var p = self.pointOnPath(location, absolute),
arcSpan = distance / circumference * 2 * Math.PI,
dir = self.anticlockwise ? -1 : 1,
startAngle = p.theta + (dir * arcSpan),
startX = params.cx + (self.radius * Math.cos(startAngle)),
startY = params.cy + (self.radius * Math.sin(startAngle));
return {x:startX, y:startY};
};
},
Bezier : function(params) {
var self = this,
_super = jsPlumb.Segments.AbstractSegment.apply(this, arguments),
curve = [
{ x:params.x1, y:params.y1},
{ x:params.cp1x, y:params.cp1y },
{ x:params.cp2x, y:params.cp2y },
{ x:params.x2, y:params.y2 }
],
// although this is not a strictly rigorous determination of bounds
// of a bezier curve, it works for the types of curves that this segment
// type produces.
bounds = {
minX:Math.min(params.x1, params.x2, params.cp1x, params.cp2x),
minY:Math.min(params.y1, params.y2, params.cp1y, params.cp2y),
maxX:Math.max(params.x1, params.x2, params.cp1x, params.cp2x),
maxY:Math.max(params.y1, params.y2, params.cp1y, params.cp2y)
};
this.type = "Bezier";
var _translateLocation = function(_curve, location, absolute) {
if (absolute)
location = jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location);
return location;
};
/**
* returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive.
*/
this.pointOnPath = function(location, absolute) {
location = _translateLocation(curve, location, absolute);
return jsBezier.pointOnCurve(curve, location);
};
/**
* returns the gradient of the segment at the given point.
*/
this.gradientAtPoint = function(location, absolute) {
location = _translateLocation(curve, location, absolute);
return jsBezier.gradientAtPoint(curve, location);
};
this.pointAlongPathFrom = function(location, distance, absolute) {
location = _translateLocation(curve, location, absolute);
return jsBezier.pointAlongCurveFrom(curve, location, distance);
};
this.getLength = function() {
return jsBezier.getLength(curve);
};
this.getBounds = function() {
return bounds;
};
}
};
/*
Class: AbstractComponent
Superclass for AbstractConnector and AbstractEndpoint.
*/
var AbstractComponent = function() {
var self = this;
self.resetBounds = function() {
self.bounds = { minX:Infinity, minY:Infinity, maxX:-Infinity, maxY:-Infinity };
};
self.resetBounds();
};
/*
* Class: AbstractConnector
* Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it
* can be accessed from other files. You should not try to instantiate one of these directly.
*
* When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch
* that request to. This is done by keeping track of the total connector length as segments are added, and also
* their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching
* the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.)
*/
jsPlumb.Connectors.AbstractConnector = function(params) {
AbstractComponent.apply(this, arguments);
var self = this,
segments = [],
editing = false,
totalLength = 0,
segmentProportions = [],
segmentProportionalLengths = [],
stub = params.stub || 0,
sourceStub = jsPlumbUtil.isArray(stub) ? stub[0] : stub,
targetStub = jsPlumbUtil.isArray(stub) ? stub[1] : stub,
gap = params.gap || 0,
sourceGap = jsPlumbUtil.isArray(gap) ? gap[0] : gap,
targetGap = jsPlumbUtil.isArray(gap) ? gap[1] : gap,
userProvidedSegments = null,
edited = false,
paintInfo = null;
// subclasses should override.
this.isEditable = function() { return false; };
this.setEdited = function(ed) {
edited = ed;
};
// to be overridden by subclasses.
this.getPath = function() { };
this.setPath = function(path) { };
/**
* Function: findSegmentForPoint
* Returns the segment that is closest to the given [x,y],
* null if nothing found. This function returns a JS
* object with:
*
* d - distance from segment
* l - proportional location in segment
* x - x point on the segment
* y - y point on the segment
* s - the segment itself.
*/
this.findSegmentForPoint = function(x, y) {
var out = { d:Infinity, s:null, x:null, y:null, l:null };
for (var i = 0; i < segments.length; i++) {
var _s = segments[i].findClosestPointOnPath(x, y);
if (_s.d < out.d) {
out.d = _s.d;
out.l = _s.l;
out.x = _s.x;
out.y = _s.y;
out.s = segments[i];
}
}
return out;
};
var _updateSegmentProportions = function() {
var curLoc = 0;
for (var i = 0; i < segments.length; i++) {
var sl = segments[i].getLength();
segmentProportionalLengths[i] = sl / totalLength;
segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ];
}
},
/**
* returns [segment, proportion of travel in segment, segment index] for the segment
* that contains the point which is 'location' distance along the entire path, where
* 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
* are made up of a list of segments, each of which contributes some fraction to
* the total length.
* From 1.3.10 this also supports the 'absolute' property, which lets us specify a location
* as the absolute distance in pixels, rather than a proportion of the total path.
*/
_findSegmentForLocation = function(location, absolute) {
if (absolute) {
location = location > 0 ? location / totalLength : (totalLength + location) / totalLength;
}
var idx = segmentProportions.length - 1, inSegmentProportion = 1;
//if (location < 1) {
for (var i = 0; i < segmentProportions.length; i++) {
if (segmentProportions[i][1] >= location) {
idx = i;
// todo is this correct for all connector path types?
inSegmentProportion = location == 1 ? 1 : location == 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
break;
}
}
//}
return { segment:segments[idx], proportion:inSegmentProportion, index:idx };
},
_addSegment = function(type, params) {
var s = new jsPlumb.Segments[type](params);
segments.push(s);
totalLength += s.getLength();
self.updateBounds(s);
},
_clearSegments = function() {
totalLength = 0;
segments.splice(0, segments.length);
segmentProportions.splice(0, segmentProportions.length);
segmentProportionalLengths.splice(0, segmentProportionalLengths.length);
};
this.setSegments = function(_segs) {
userProvidedSegments = [];
totalLength = 0;
for (var i = 0; i < _segs.length; i++) {
userProvidedSegments.push(_segs[i]);
totalLength += _segs[i].getLength();
}
};
var _prepareCompute = function(params) {
self.lineWidth = params.lineWidth;
var segment = jsPlumbUtil.segment(params.sourcePos, params.targetPos),
swapX = params.targetPos[0] < params.sourcePos[0],
swapY = params.targetPos[1] < params.sourcePos[1],
lw = params.lineWidth || 1,
so = params.sourceEndpoint.anchor.orientation || params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint),
to = params.targetEndpoint.anchor.orientation || params.targetEndpoint.anchor.getOrientation(params.targetEndpoint),
x = swapX ? params.targetPos[0] : params.sourcePos[0],
y = swapY ? params.targetPos[1] : params.sourcePos[1],
w = Math.abs(params.targetPos[0] - params.sourcePos[0]),
h = Math.abs(params.targetPos[1] - params.sourcePos[1]);
// if either anchor does not have an orientation set, we derive one from their relative
// positions. we fix the axis to be the one in which the two elements are further apart, and
// point each anchor at the other element. this is also used when dragging a new connection.
if (so[0] == 0 && so[1] == 0 || to[0] == 0 && to[1] == 0) {
var index = w > h ? 0 : 1, oIndex = [1,0][index];
so = []; to = [];
so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1;
to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1;
so[oIndex] = 0; to[oIndex] = 0;
}
var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0],
sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1],
tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]),
ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]),
oProduct = ((so[0] * to[0]) + (so[1] * to[1]));
var result = {
sx:sx, sy:sy, tx:tx, ty:ty, lw:lw,
xSpan:Math.abs(tx - sx),
ySpan:Math.abs(ty - sy),
mx:(sx + tx) / 2,
my:(sy + ty) / 2,
so:so, to:to, x:x, y:y, w:w, h:h,
segment : segment,
startStubX : sx + (so[0] * sourceStub),
startStubY : sy + (so[1] * sourceStub),
endStubX : tx + (to[0] * targetStub),
endStubY : ty + (to[1] * targetStub),
isXGreaterThanStubTimes2 : Math.abs(sx - tx) > (sourceStub + targetStub),
isYGreaterThanStubTimes2 : Math.abs(sy - ty) > (sourceStub + targetStub),
opposite:oProduct == -1,
perpendicular:oProduct == 0,
orthogonal:oProduct == 1,
sourceAxis : so[0] == 0 ? "y" : "x",
points:[x, y, w, h, sx, sy, tx, ty ]
};
result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular";
return result;
};
this.getSegments = function() { return segments; };
self.updateBounds = function(segment) {
var segBounds = segment.getBounds();
self.bounds.minX = Math.min(self.bounds.minX, segBounds.minX);
self.bounds.maxX = Math.max(self.bounds.maxX, segBounds.maxX);
self.bounds.minY = Math.min(self.bounds.minY, segBounds.minY);
self.bounds.maxY = Math.max(self.bounds.maxY, segBounds.maxY);
};
var dumpSegmentsToConsole = function() {
console.log("SEGMENTS:");
for (var i = 0; i < segments.length; i++) {
console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]);
}
};
this.pointOnPath = function(location, absolute) {
//console.log("point on path", location);
var seg = _findSegmentForLocation(location, absolute);
//console.log("point on path", location, seg);
return seg.segment.pointOnPath(seg.proportion, absolute);
};
this.gradientAtPoint = function(location) {
var seg = _findSegmentForLocation(location, absolute);
return seg.segment.gradientAtPoint(seg.proportion, absolute);
};
this.pointAlongPathFrom = function(location, distance, absolute) {
var seg = _findSegmentForLocation(location, absolute);
// TODO what happens if this crosses to the next segment?
return seg.segment.pointAlongPathFrom(seg.proportion, distance, false);
};
this.compute = function(params) {
if (!edited)
paintInfo = _prepareCompute(params);
_clearSegments();
this._compute(paintInfo, params);
self.x = paintInfo.points[0];
self.y = paintInfo.points[1];
self.w = paintInfo.points[2];
self.h = paintInfo.points[3];
self.segment = paintInfo.segment;
_updateSegmentProportions();
};
return {
addSegment:_addSegment,
prepareCompute:_prepareCompute,
sourceStub:sourceStub,
targetStub:targetStub,
maxStub:Math.max(sourceStub, targetStub),
sourceGap:sourceGap,
targetGap:targetGap,
maxGap:Math.max(sourceGap, targetGap)
};
};
/**
* Class: Connectors.Straight
* The Straight connector draws a simple straight line between the two anchor points. It does not have any constructor parameters.
*/
jsPlumb.Connectors.Straight = function() {
this.type = "Straight";
var _super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments);
this._compute = function(paintInfo, _) {
_super.addSegment("Straight", {x1:paintInfo.sx, y1:paintInfo.sy, x2:paintInfo.startStubX, y2:paintInfo.startStubY});
_super.addSegment("Straight", {x1:paintInfo.startStubX, y1:paintInfo.startStubY, x2:paintInfo.endStubX, y2:paintInfo.endStubY});
_super.addSegment("Straight", {x1:paintInfo.endStubX, y1:paintInfo.endStubY, x2:paintInfo.tx, y2:paintInfo.ty});
};
};
/**
* Class:Connectors.Bezier
* This Connector draws a Bezier curve with two control points. You can provide a 'curviness' value which gets applied to jsPlumb's
* internal voodoo machine and ends up generating locations for the two control points. See the constructor documentation below.
*/
/**
* Function:Constructor
*
* Parameters:
* curviness - How 'curvy' you want the curve to be! This is a directive for the placement of control points, not endpoints of the curve, so your curve does not
* actually touch the given point, but it has the tendency to lean towards it. The larger this value, the greater the curve is pulled from a straight line.
* Optional; defaults to 150.
* stub - optional value for a distance to travel from the connector's endpoint before beginning the Bezier curve. defaults to 0.
*
*/
jsPlumb.Connectors.Bezier = function(params) {
params = params || {};
var self = this,
_super = jsPlumb.Connectors.AbstractConnector.apply(this, arguments),
stub = params.stub || 50,
majorAnchor = params.curviness || 150,
minorAnchor = 10;
this.type = "Bezier";
this.getCurviness = function() { return majorAnchor; };
this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint) {
// determine if the two anchors are perpendicular to each other in their orientation. we swap the control
// points around if so (code could be tightened up)
var soo = sourceEndpoint.anchor.getOrientation(sourceEndpoint),
too = targetEndpoint.anchor.getOrientation(targetEndpoint),
perpendicular = soo[0] != too[0] || soo[1] == too[1],
p = [];
if (!perpendicular) {
if (soo[0] == 0) // X
p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
else p.push(point[0] - (majorAnchor * soo[0]));
if (soo[1] == 0) // Y
p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
else p.push(point[1] + (majorAnchor * too[1]));
}
else {
if (too[0] == 0) // X
p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
else p.push(point[0] + (majorAnchor * too[0]));
if (too[1] == 0) // Y
p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
else p.push(point[1] + (majorAnchor * soo[1]));
}
return p;
};
this._compute = function(paintInfo, p) {
var sp = p.sourcePos,
tp = p.targetPos,
_w = Math.abs(sp[0] - tp[0]),
_h = Math.abs(sp[1] - tp[1]),
_sx = sp[0] < tp[0] ? _w : 0,
_sy = sp[1] < tp[1] ? _h : 0,
_tx = sp[0] < tp[0] ? 0 : _w,
_ty = sp[1] < tp[1] ? 0 : _h,
_CP = self._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint),
_CP2 = self._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint);
_super.addSegment("Bezier", {
x1:_sx, y1:_sy, x2:_tx, y2:_ty,
cp1x:_CP[0], cp1y:_CP[1], cp2x:_CP2[0], cp2y:_CP2[1]
});
};
};
// ********************************* END OF CONNECTOR TYPES *******************************************************************
// ********************************* ENDPOINT TYPES *******************************************************************
jsPlumb.Endpoints.AbstractEndpoint = function(params) {
AbstractComponent.apply(this, arguments);
var self = this;
this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var out = self._compute.apply(self, arguments);
self.x = out[0];
self.y = out[1];
self.w = out[2];
self.h = out[3];
self.bounds.minX = self.x;
self.bounds.minY = self.y;
self.bounds.maxX = self.x + self.w;
self.bounds.maxY = self.y + self.h;
return out;
};
return {
compute:self.compute,
cssClass:params.cssClass
};
};
/**
* Class: Endpoints.Dot
* A round endpoint, with default radius 10 pixels.
*/
/**
* Function: Constructor
*
* Parameters:
*
* radius - radius of the endpoint. defaults to 10 pixels.
*/
jsPlumb.Endpoints.Dot = function(params) {
this.type = "Dot";
var self = this,
_super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments);
params = params || {};
this.radius = params.radius || 10;
this.defaultOffset = 0.5 * this.radius;
this.defaultInnerRadius = this.radius / 3;
this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
self.radius = endpointStyle.radius || self.radius;
var x = anchorPoint[0] - self.radius,
y = anchorPoint[1] - self.radius,
w = self.radius * 2,
h = self.radius * 2;
if (endpointStyle.strokeStyle) {
var lw = endpointStyle.lineWidth || 1;
x -= lw;
y -= lw;
w += (lw * 2);
h += (lw * 2);
}
return [ x, y, w, h, self.radius ];
};
};
/**
* Class: Endpoints.Rectangle
* A Rectangular Endpoint, with default size 20x20.
*/
/**
* Function: Constructor
*
* Parameters:
*
* width - width of the endpoint. defaults to 20 pixels.
* height - height of the endpoint. defaults to 20 pixels.
*/
jsPlumb.Endpoints.Rectangle = function(params) {
this.type = "Rectangle";
var self = this,
_super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments);
params = params || {};
this.width = params.width || 20;
this.height = params.height || 20;
this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var width = endpointStyle.width || self.width,
height = endpointStyle.height || self.height,
x = anchorPoint[0] - (width/2),
y = anchorPoint[1] - (height/2);
return [ x, y, width, height];
};
};
var DOMElementEndpoint = function(params) {
jsPlumb.DOMElementComponent.apply(this, arguments);
var self = this;
var displayElements = [ ];
this.getDisplayElements = function() {
return displayElements;
};
this.appendDisplayElement = function(el) {
displayElements.push(el);
};
};
/**
* Class: Endpoints.Image
* Draws an image as the Endpoint.
*/
/**
* Function: Constructor
*
* Parameters:
*
* src - location of the image to use.
*/
jsPlumb.Endpoints.Image = function(params) {
this.type = "Image";
DOMElementEndpoint.apply(this, arguments);
var self = this,
_super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments),
initialized = false,
deleted = false,
widthToUse = params.width,
heightToUse = params.height,
_onload = null,
_endpoint = params.endpoint;
this.img = new Image();
self.ready = false;
this.img.onload = function() {
self.ready = true;
widthToUse = widthToUse || self.img.width;
heightToUse = heightToUse || self.img.height;
if (_onload) {
_onload(self);
}
};
/*
Function: setImage
Sets the Image to use in this Endpoint.
Parameters:
img - may be a URL or an Image object
onload - optional; a callback to execute once the image has loaded.
*/
_endpoint.setImage = function(img, onload) {
var s = img.constructor == String ? img : img.src;
_onload = onload;
self.img.src = img;
if (self.canvas != null)
self.canvas.setAttribute("src", img);
};
_endpoint.setImage(params.src || params.url, params.onload);
this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
self.anchorPoint = anchorPoint;
if (self.ready) return [anchorPoint[0] - widthToUse / 2, anchorPoint[1] - heightToUse / 2,
widthToUse, heightToUse];
else return [0,0,0,0];
};
self.canvas = document.createElement("img"), initialized = false;
self.canvas.style["margin"] = 0;
self.canvas.style["padding"] = 0;
self.canvas.style["outline"] = 0;
self.canvas.style["position"] = "absolute";
var clazz = params.cssClass ? " " + params.cssClass : "";
self.canvas.className = jsPlumb.endpointClass + clazz;
if (widthToUse) self.canvas.setAttribute("width", widthToUse);
if (heightToUse) self.canvas.setAttribute("height", heightToUse);
jsPlumb.appendElement(self.canvas, params.parent);
self.attachListeners(self.canvas, self);
self.cleanup = function() {
deleted = true;
};
var actuallyPaint = function(d, style, anchor) {
if (!deleted) {
if (!initialized) {
self.canvas.setAttribute("src", self.img.src);
self.appendDisplayElement(self.canvas);
initialized = true;
}
var x = self.anchorPoint[0] - (widthToUse / 2),
y = self.anchorPoint[1] - (heightToUse / 2);
jsPlumb.sizeCanvas(self.canvas, x, y, widthToUse, heightToUse);
}
};
this.paint = function(style, anchor) {
if (self.ready) {
actuallyPaint(style, anchor);
}
else {
window.setTimeout(function() {
self.paint(style, anchor);
}, 200);
}
};
};
/*
* Class: Endpoints.Blank
* An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints.
*/
jsPlumb.Endpoints.Blank = function(params) {
var self = this,
_super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments);
this.type = "Blank";
DOMElementEndpoint.apply(this, arguments);
this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
return [anchorPoint[0], anchorPoint[1],10,0];
};
self.canvas = document.createElement("div");
self.canvas.style.display = "block";
self.canvas.style.width = "1px";
self.canvas.style.height = "1px";
self.canvas.style.background = "transparent";
self.canvas.style.position = "absolute";
self.canvas.className = self._jsPlumb.endpointClass;
jsPlumb.appendElement(self.canvas, params.parent);
this.paint = function(style, anchor) {
jsPlumb.sizeCanvas(self.canvas, self.x, self.y, self.w, self.h);
};
};
/*
* Class: Endpoints.Triangle
* A triangular Endpoint.
*/
/*
* Function: Constructor
*
* Parameters:
*
* width - width of the triangle's base. defaults to 55 pixels.
* height - height of the triangle from base to apex. defaults to 55 pixels.
*/
jsPlumb.Endpoints.Triangle = function(params) {
this.type = "Triangle";
var self = this,
_super = jsPlumb.Endpoints.AbstractEndpoint.apply(this, arguments);
params = params || { };
params.width = params.width || 55;
params.height = params.height || 55;
this.width = params.width;
this.height = params.height;
this._compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var width = endpointStyle.width || self.width,
height = endpointStyle.height || self.height,
x = anchorPoint[0] - (width/2),
y = anchorPoint[1] - (height/2);
return [ x, y, width, height ];
};
};
// ********************************* END OF ENDPOINT TYPES *******************************************************************
// ********************************* OVERLAY DEFINITIONS ***********************************************************************
var AbstractOverlay = jsPlumb.Overlays.AbstractOverlay = function(params) {
var visible = true, self = this;
this.isAppendedAtTopLevel = true;
this.component = params.component;
this.loc = params.location == null ? 0.5 : params.location;
this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation;
this.setVisible = function(val) {
visible = val;
self.component.repaint();
};
this.isVisible = function() { return visible; };
this.hide = function() { self.setVisible(false); };
this.show = function() { self.setVisible(true); };
this.incrementLocation = function(amount) {
self.loc += amount;
self.component.repaint();
};
this.setLocation = function(l) {
self.loc = l;
self.component.repaint();
};
this.getLocation = function() {
return self.loc;
};
};
/*
* Class: Overlays.Arrow
*
* An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length
* of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
* of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line
* across the tail.
*/
/*
* Function: Constructor
*
* Parameters:
*
* length - distance in pixels from head to tail baseline. default 20.
* width - width in pixels of the tail baseline. default 20.
* fillStyle - style to use when filling the arrow. defaults to "black".
* strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
* lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null.
* foldback - distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
* direction - indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
*/
jsPlumb.Overlays.Arrow = function(params) {
this.type = "Arrow";
AbstractOverlay.apply(this, arguments);
this.isAppendedAtTopLevel = false;
params = params || {};
var self = this, _ju = jsPlumbUtil;
this.length = params.length || 20;
this.width = params.width || 20;
this.id = params.id;
var direction = (params.direction || 1) < 0 ? -1 : 1,
paintStyle = params.paintStyle || { lineWidth:1 },
// how far along the arrow the lines folding back in come to. default is 62.3%.
foldback = params.foldback || 0.623;
this.computeMaxSize = function() { return self.width * 1.5; };
this.cleanup = function() { }; // nothing to clean up for Arrows
this.draw = function(component, currentConnectionPaintStyle) {
var hxy, mid, txy, tail, cxy;
if (component.pointAlongPathFrom) {
if (_ju.isString(self.loc) || self.loc > 1 || self.loc < 0) {
var l = parseInt(self.loc);
hxy = component.pointAlongPathFrom(l, direction * self.length / 2, true),
mid = component.pointOnPath(l, true),
txy = _ju.pointOnLine(hxy, mid, self.length);
}
else if (self.loc == 1) {
hxy = component.pointOnPath(self.loc);
mid = component.pointAlongPathFrom(self.loc, -(self.length));
txy = _ju.pointOnLine(hxy, mid, self.length);
if (direction == -1) {
var _ = txy;
txy = hxy;
hxy = _;
}
}
else if (self.loc == 0) {
txy = component.pointOnPath(self.loc);
mid = component.pointAlongPathFrom(self.loc, self.length);
hxy = _ju.pointOnLine(txy, mid, self.length);
if (direction == -1) {
var _ = txy;
txy = hxy;
hxy = _;
}
}
else {
hxy = component.pointAlongPathFrom(self.loc, direction * self.length / 2),
mid = component.pointOnPath(self.loc),
txy = _ju.pointOnLine(hxy, mid, self.length);
}
tail = _ju.perpendicularLineTo(hxy, txy, self.width);
cxy = _ju.pointOnLine(hxy, txy, foldback * self.length);
var d = { hxy:hxy, tail:tail, cxy:cxy },
strokeStyle = paintStyle.strokeStyle || currentConnectionPaintStyle.strokeStyle,
fillStyle = paintStyle.fillStyle || currentConnectionPaintStyle.strokeStyle,
lineWidth = paintStyle.lineWidth || currentConnectionPaintStyle.lineWidth,
info = {
component:component,
d:d,
lineWidth:lineWidth,
strokeStyle:strokeStyle,
fillStyle:fillStyle,
minX:Math.min(hxy.x, tail[0].x, tail[1].x),
maxX:Math.max(hxy.x, tail[0].x, tail[1].x),
minY:Math.min(hxy.y, tail[0].y, tail[1].y),
maxY:Math.max(hxy.y, tail[0].y, tail[1].y)
};
return info;
}
else return {component:component, minX:0,maxX:0,minY:0,maxY:0};
};
};
/*
* Class: Overlays.PlainArrow
*
* A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some
* point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
* a 'call' to Arrow with foldback set appropriately.
*/
/*
* Function: Constructor
* See <Overlays.Arrow> for allowed parameters for this overlay.
*/
jsPlumb.Overlays.PlainArrow = function(params) {
params = params || {};
var p = jsPlumb.extend(params, {foldback:1});
jsPlumb.Overlays.Arrow.call(this, p);
this.type = "PlainArrow";
};
/*
* Class: Overlays.Diamond
*
* A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
* happens that in this case, that point is greater than the length of the the arrow.
*
* this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
* center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
* stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
* would be -l/4 in this case - move along one quarter of the total length.
*/
/*
* Function: Constructor
* See <Overlays.Arrow> for allowed parameters for this overlay.
*/
jsPlumb.Overlays.Diamond = function(params) {
params = params || {};
var l = params.length || 40,
p = jsPlumb.extend(params, {length:l/2, foldback:2});
jsPlumb.Overlays.Arrow.call(this, p);
this.type = "Diamond";
};
// abstract superclass for overlays that add an element to the DOM.
var AbstractDOMOverlay = function(params) {
jsPlumb.DOMElementComponent.apply(this, arguments);
AbstractOverlay.apply(this, arguments);
var self = this, initialised = false, jpcl = jsPlumb.CurrentLibrary;
params = params || {};
this.id = params.id;
var div;
var makeDiv = function() {
div = params.create(params.component);
div = jpcl.getDOMElement(div);
div.style["position"] = "absolute";
var clazz = params["_jsPlumb"].overlayClass + " " +
(self.cssClass ? self.cssClass :
params.cssClass ? params.cssClass : "");
div.className = clazz;
params["_jsPlumb"].appendElement(div, params.component.parent);
params["_jsPlumb"].getId(div);
self.attachListeners(div, self);
self.canvas = div;
};
this.getElement = function() {
if (div == null) {
makeDiv();
}
return div;
};
this.getDimensions = function() {
return jpcl.getSize(jpcl.getElementObject(self.getElement()));
};
var cachedDimensions = null,
_getDimensions = function(component) {
if (cachedDimensions == null)
cachedDimensions = self.getDimensions();
return cachedDimensions;
};
/*
* Function: clearCachedDimensions
* Clears the cached dimensions for the label. As a performance enhancement, label dimensions are
* cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but
* there are other reasons why the text dimensions might change - if you make a change through CSS, for
* example, you might change the font size. in that case you should explicitly call this method.
*/
this.clearCachedDimensions = function() {
cachedDimensions = null;
};
this.computeMaxSize = function() {
var td = _getDimensions();
return Math.max(td[0], td[1]);
};
//override setVisible
var osv = self.setVisible;
self.setVisible = function(state) {
osv(state); // call superclass
div.style.display = state ? "block" : "none";
};
this.cleanup = function() {
if (div != null) jpcl.removeElement(div);
};
this.paint = function(params, containerExtents) {
if (!initialised) {
self.getElement();
params.component.appendDisplayElement(div);
self.attachListeners(div, params.component);
initialised = true;
}
div.style.left = (params.component.x + params.d.minx) + "px";
div.style.top = (params.component.y + params.d.miny) + "px";
};
this.draw = function(component, currentConnectionPaintStyle) {
var td = _getDimensions();
if (td != null && td.length == 2) {
var cxy = {x:0,y:0};
if (component.pointOnPath) {
var loc = self.loc, absolute = false;
if (jsPlumbUtil.isString(self.loc) || self.loc < 0 || self.loc > 1) {
loc = parseInt(self.loc);
absolute = true;
}
cxy = component.pointOnPath(loc, absolute); // a connection
}
else {
var locToUse = self.loc.constructor == Array ? self.loc : self.endpointLoc;
cxy = { x:locToUse[0] * component.w,
y:locToUse[1] * component.h };
}
var minx = cxy.x - (td[0] / 2),
miny = cxy.y - (td[1] / 2);
return {
component:component,
d:{ minx:minx, miny:miny, td:td, cxy:cxy },
minX:minx,
maxX:minx + td[0],
minY:miny,
maxY:miny + td[1]
};
}
else return {minX:0,maxX:0,minY:0,maxY:0};
};
this.reattachListeners = function(connector) {
if (div) {
self.reattachListenersForElement(div, self, connector);
}
};
};
/*
* Class: Overlays.Custom
* A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it.
* The 'create' function is passed a Connection or Endpoint.
*/
/*
* Function: Constructor
*
* Parameters:
* create - function for jsPlumb to call that returns a DOM element.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
* id - optional id to use for later retrieval of this overlay.
*
*/
jsPlumb.Overlays.Custom = function(params) {
this.type = "Custom";
AbstractDOMOverlay.apply(this, arguments);
};
jsPlumb.Overlays.GuideLines = function() {
var self = this;
self.length = 50;
self.lineWidth = 5;
this.type = "GuideLines";
AbstractOverlay.apply(this, arguments);
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
this.draw = function(connector, currentConnectionPaintStyle) {
var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
mid = connector.pointOnPath(self.loc),
tail = jsPlumbUtil.pointOnLine(head, mid, self.length),
tailLine = jsPlumbUtil.perpendicularLineTo(head, tail, 40),
headLine = jsPlumbUtil.perpendicularLineTo(tail, head, 20);
return {
connector:connector,
head:head,
tail:tail,
headLine:headLine,
tailLine:tailLine,
minX:Math.min(head.x, tail.x, headLine[0].x, headLine[1].x),
minY:Math.min(head.y, tail.y, headLine[0].y, headLine[1].y),
maxX:Math.max(head.x, tail.x, headLine[0].x, headLine[1].x),
maxY:Math.max(head.y, tail.y, headLine[0].y, headLine[1].y)
};
};
this.cleanup = function() { }; // nothing to clean up for GuideLines
};
/*
* Class: Overlays.Label
* A Label overlay. For all different renderer types (SVG/Canvas/VML), jsPlumb draws a Label overlay as a styled DIV. Version 1.3.0 of jsPlumb
* introduced the ability to set css classes on the label; this is now the preferred way for you to style a label. The 'labelStyle' parameter
* is still supported in 1.3.0 but its usage is deprecated. Under the hood, jsPlumb just turns that object into a bunch of CSS directive that it
* puts on the Label's 'style' attribute, so the end result is the same.
*/
/*
* Function: Constructor
*
* Parameters:
* cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
* defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
* label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your
* label function returns null. empty strings _will_ be painted.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
* id - optional id to use for later retrieval of this overlay.
*
*/
jsPlumb.Overlays.Label = function(params) {
var self = this;
this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle;
this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null;
params.create = function() {
return document.createElement("div");
};
jsPlumb.Overlays.Custom.apply(this, arguments);
this.type = "Label";
var label = params.label || "",
self = this,
labelText = null;
/*
* Function: setLabel
* sets the label's, um, label. you would think i'd call this function
* 'setText', but you can pass either a Function or a String to this, so
* it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep
* that in mind if you need escaped HTML.
*/
this.setLabel = function(l) {
label = l;
labelText = null;
self.clearCachedDimensions();
_update();
self.component.repaint();
};
var _update = function() {
if (typeof label == "function") {
var lt = label(self);
self.getElement().innerHTML = lt.replace(/\r\n/g, "<br/>");
}
else {
if (labelText == null) {
labelText = label;
self.getElement().innerHTML = labelText.replace(/\r\n/g, "<br/>");
}
}
};
this.getLabel = function() {
return label;
};
var superGD = this.getDimensions;
this.getDimensions = function() {
_update();
return superGD();
};
};
// ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the base functionality for DOM type adapters.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
var canvasAvailable = !!document.createElement('canvas').getContext,
svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"),
// http://stackoverflow.com/questions/654112/how-do-you-detect-support-for-vml-or-svg-in-a-browser
vmlAvailable = function() {
if (vmlAvailable.vml == undefined) {
var a = document.body.appendChild(document.createElement('div'));
a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
var b = a.firstChild;
b.style.behavior = "url(#default#VML)";
vmlAvailable.vml = b ? typeof b.adj == "object": true;
a.parentNode.removeChild(a);
}
return vmlAvailable.vml;
};
/**
Manages dragging for some instance of jsPlumb.
*/
var DragManager = function(_currentInstance) {
var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {},
// elementids mapped to the draggable to which they belong.
_draggablesForElements = {};
/**
register some element as draggable. right now the drag init stuff is done elsewhere, and it is
possible that will continue to be the case.
*/
this.register = function(el) {
var jpcl = jsPlumb.CurrentLibrary;
el = jpcl.getElementObject(el);
var id = _currentInstance.getId(el),
domEl = jpcl.getDOMElement(el),
parentOffset = jpcl.getOffset(el);
if (!_draggables[id]) {
_draggables[id] = el;
_dlist.push(el);
_delements[id] = {};
}
// look for child elements that have endpoints and register them against this draggable.
var _oneLevel = function(p, startOffset) {
if (p) {
for (var i = 0; i < p.childNodes.length; i++) {
if (p.childNodes[i].nodeType != 3 && p.childNodes[i].nodeType != 8) {
var cEl = jpcl.getElementObject(p.childNodes[i]),
cid = _currentInstance.getId(cEl, null, true);
if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) {
var cOff = jpcl.getOffset(cEl);
_delements[id][cid] = {
id:cid,
offset:{
left:cOff.left - parentOffset.left,
top:cOff.top - parentOffset.top
}
};
_draggablesForElements[cid] = id;
}
_oneLevel(p.childNodes[i]);
}
}
}
};
_oneLevel(domEl);
};
// refresh the offsets for child elements of this element.
this.updateOffsets = function(elId) {
var jpcl = jsPlumb.CurrentLibrary,
el = jpcl.getElementObject(elId),
id = _currentInstance.getId(el),
children = _delements[id],
parentOffset = jpcl.getOffset(el);
if (children) {
for (var i in children) {
var cel = jpcl.getElementObject(i),
cOff = jpcl.getOffset(cel);
_delements[id][i] = {
id:i,
offset:{
left:cOff.left - parentOffset.left,
top:cOff.top - parentOffset.top
}
};
_draggablesForElements[i] = id;
}
}
};
/**
notification that an endpoint was added to the given el. we go up from that el's parent
node, looking for a parent that has been registered as a draggable. if we find one, we add this
el to that parent's list of elements to update on drag (if it is not there already)
*/
this.endpointAdded = function(el) {
var jpcl = jsPlumb.CurrentLibrary, b = document.body, id = _currentInstance.getId(el), c = jpcl.getDOMElement(el),
p = c.parentNode, done = p == b;
_elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1;
while (p != null && p != b) {
var pid = _currentInstance.getId(p, null, true);
if (pid && _draggables[pid]) {
var idx = -1, pEl = jpcl.getElementObject(p), pLoc = jpcl.getOffset(pEl);
if (_delements[pid][id] == null) {
var cLoc = jsPlumb.CurrentLibrary.getOffset(el);
_delements[pid][id] = {
id:id,
offset:{
left:cLoc.left - pLoc.left,
top:cLoc.top - pLoc.top
}
};
_draggablesForElements[id] = pid;
}
break;
}
p = p.parentNode;
}
};
this.endpointDeleted = function(endpoint) {
if (_elementsWithEndpoints[endpoint.elementId]) {
_elementsWithEndpoints[endpoint.elementId]--;
if (_elementsWithEndpoints[endpoint.elementId] <= 0) {
for (var i in _delements) {
if (_delements[i]) {
delete _delements[i][endpoint.elementId];
delete _draggablesForElements[endpoint.elementId];
}
}
}
}
};
this.changeId = function(oldId, newId) {
_delements[newId] = _delements[oldId];
_delements[oldId] = {};
_draggablesForElements[newId] = _draggablesForElements[oldId];
_draggablesForElements[oldId] = null;
};
this.getElementsForDraggable = function(id) {
return _delements[id];
};
this.elementRemoved = function(elementId) {
var elId = _draggablesForElements[elementId];
if (elId) {
delete _delements[elId][elementId];
delete _draggablesForElements[elementId];
}
};
this.reset = function() {
_draggables = {};
_dlist = [];
_delements = {};
_elementsWithEndpoints = {};
};
};
// for those browsers that dont have it. they still don't have it! but at least they won't crash.
if (!window.console)
window.console = { time:function(){}, timeEnd:function(){}, group:function(){}, groupEnd:function(){}, log:function(){} };
window.jsPlumbAdapter = {
headless:false,
appendToRoot : function(node) {
document.body.appendChild(node);
},
getRenderModes : function() {
return [ "canvas", "svg", "vml" ]
},
isRenderModeAvailable : function(m) {
return {
"canvas":canvasAvailable,
"svg":svgAvailable,
"vml":vmlAvailable()
}[m];
},
getDragManager : function(_jsPlumb) {
return new DragManager(_jsPlumb);
},
setRenderMode : function(mode) {
var renderMode;
if (mode) {
mode = mode.toLowerCase();
var canvasAvailable = this.isRenderModeAvailable("canvas"),
svgAvailable = this.isRenderModeAvailable("svg"),
vmlAvailable = this.isRenderModeAvailable("vml");
// now test we actually have the capability to do this.
if (mode === "svg") {
if (svgAvailable) renderMode = "svg"
else if (canvasAvailable) renderMode = "canvas"
else if (vmlAvailable) renderMode = "vml"
}
else if (mode === "canvas" && canvasAvailable) renderMode = "canvas";
else if (vmlAvailable) renderMode = "vml";
}
return renderMode;
}
};
})();
\ No newline at end of file
/*
* this is experimental and probably will not be used. solutions exist for most libraries. but of course if
* i want to support multiple scopes at some stage then i will have to do dragging inside jsPlumb.
*/
;(function() {
window.jsPlumbDrag = function(_jsPlumb) {
var ta = new TouchAdapter();
this.draggable = function(selector) {
var el, elId, da = [], elo, d = false,
isInSelector = function(el) {
if (typeof selector == "string")
return selector === _jsPlumb.getId(el);
for (var i = 0; i < selector.length; i++) {
var _sel = jsPlumb.CurrentLibrary.getDOMElement(selector[i]);
if (_sel == el) return true;
}
return false;
};
ta.bind(document, "mousedown", function(e) {
var target = e.target || e.srcElement;
if (isInSelector(target)) {
el = jsPlumb.CurrentLibrary.getElementObject(target);
elId = _jsPlumb.getId(el);
elo = jsPlumb.CurrentLibrary.getOffset(el);
da = [e.pageX, e.pageY];
d = true;
}
});
ta.bind(document, "mousemove", function(e) {
if (d) {
var dx = e.pageX - da[0],
dy = e.pageY - da[1];
jsPlumb.CurrentLibrary.setOffset(el, {
left:elo.left + dx,
top:elo.top + dy
});
_jsPlumb.repaint(elId);
e.preventDefault();
e.stopPropagation();
}
});
ta.bind(document, "mouseup", function(e) {
el = null;
d = false;
});
};
var isIOS = ((/iphone|ipad/gi).test(navigator.appVersion));
if (isIOS)
_jsPlumb.draggable = this.draggable;
};
})();
\ No newline at end of file
;(function() {
// create the drag handler for a connection
var _makeConnectionDragHandler = function(placeholder, _jsPlumb) {
var stopped = false;
return {
drag : function() {
if (stopped) {
stopped = false;
return true;
}
var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments, _jsPlumb.getZoom());
if (placeholder.element) {
jsPlumb.CurrentLibrary.setOffset(placeholder.element, _ui);
_jsPlumb.repaint(placeholder.element, _ui);
}
},
stopDrag : function() {
stopped = true;
}
};
};
// creates a placeholder div for dragging purposes, adds it to the DOM, and pre-computes its offset.
var _makeDraggablePlaceholder = function(placeholder, parent, _jsPlumb) {
var n = document.createElement("div");
n.style.position = "absolute";
var placeholderDragElement = jsPlumb.CurrentLibrary.getElementObject(n);
jsPlumb.CurrentLibrary.appendElement(n, parent);
var id = _jsPlumb.getId(placeholderDragElement);
_jsPlumb.updateOffset( { elId : id });
// create and assign an id, and initialize the offset.
placeholder.id = id;
placeholder.element = placeholderDragElement;
};
// create a floating endpoint (for drag connections)
var _makeFloatingEndpoint = function(paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint) {
var floatingAnchor = new jsPlumb.FloatingAnchor( { reference : referenceAnchor, referenceCanvas : referenceCanvas, jsPlumbInstance:_jsPlumb });
//setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
// adding the floating endpoint as a droppable. that makes more sense anyway!
return _newEndpoint({ paintStyle : paintStyle, endpoint : endpoint, anchor : floatingAnchor, source : sourceElement, scope:"__floating" });
};
var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays",
"connector", "connectionType", "connectorClass", "connectorHoverClass" ];
jsPlumb.Endpoint = function(params) {
var self = this,
_jsPlumb = params["_jsPlumb"],
jpcl = jsPlumb.CurrentLibrary,
_att = jpcl.getAttribute,
_gel = jpcl.getElementObject,
_ju = jsPlumbUtil,
_getOffset = jpcl.getOffset,
_newConnection = params.newConnection,
_newEndpoint = params.newEndpoint,
_finaliseConnection = params.finaliseConnection,
_fireDetachEvent = params.fireDetachEvent,
floatingConnections = params.floatingConnections;
self.idPrefix = "_jsplumb_e_";
self.defaultLabelLocation = [ 0.5, 0.5 ];
self.defaultOverlayKeys = ["Overlays", "EndpointOverlays"];
this.parent = params.parent;
overlayCapableJsPlumbUIComponent.apply(this, arguments);
params = params || {};
// TYPE
this.getTypeDescriptor = function() { return "endpoint"; };
this.getDefaultType = function() {
return {
parameters:{},
scope:null,
maxConnections:self._jsPlumb.Defaults.MaxConnections,
paintStyle:self._jsPlumb.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle,
endpoint:self._jsPlumb.Defaults.Endpoint || jsPlumb.Defaults.Endpoint,
hoverPaintStyle:self._jsPlumb.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle,
overlays:self._jsPlumb.Defaults.EndpointOverlays || jsPlumb.Defaults.EndpointOverlays,
connectorStyle:params.connectorStyle,
connectorHoverStyle:params.connectorHoverStyle,
connectorClass:params.connectorClass,
connectorHoverClass:params.connectorHoverClass,
connectorOverlays:params.connectorOverlays,
connector:params.connector,
connectorTooltip:params.connectorTooltip
};
};
var superAt = this.applyType;
this.applyType = function(t, doNotRepaint) {
superAt(t, doNotRepaint);
if (t.maxConnections != null) _maxConnections = t.maxConnections;
if (t.scope) self.scope = t.scope;
_ju.copyValues(typeParameters, t, self);
};
// END TYPE
var visible = true, __enabled = !(params.enabled === false);
this.isVisible = function() { return visible; };
this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
visible = v;
if (self.canvas) self.canvas.style.display = v ? "block" : "none";
self[v ? "showOverlays" : "hideOverlays"]();
if (!doNotChangeConnections) {
for (var i = 0; i < self.connections.length; i++) {
self.connections[i].setVisible(v);
if (!doNotNotifyOtherEndpoint) {
var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
// only change the other endpoint if this is its only connection.
if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
}
}
}
};
this.isEnabled = function() { return __enabled; };
this.setEnabled = function(e) { __enabled = e; };
var _element = params.source, _uuid = params.uuid, floatingEndpoint = null, inPlaceCopy = null;
if (_uuid) params.endpointsByUUID[_uuid] = self;
var _elementId = _att(_element, "id");
this.elementId = _elementId;
this.element = _element;
self.setElementId = function(_elId) {
_elementId = _elId;
self.elementId = _elId;
self.anchor.elementId = _elId
};
self.setReferenceElement = function(_el) {
_element = _el;
self.element = _el;
};
var _connectionCost = params.connectionCost;
this.getConnectionCost = function() { return _connectionCost; };
this.setConnectionCost = function(c) {
_connectionCost = c;
};
var _connectionsDirected = params.connectionsDirected;
this.areConnectionsDirected = function() { return _connectionsDirected; };
this.setConnectionsDirected = function(b) { _connectionsDirected = b; };
var _currentAnchorClass = "",
_updateAnchorClass = function() {
jpcl.removeClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
self.removeClass(_jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
_currentAnchorClass = self.anchor.getCssClass();
self.addClass(_jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
jpcl.addClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
};
this.setAnchor = function(anchorParams, doNotRepaint) {
self.anchor = _jsPlumb.makeAnchor(anchorParams, _elementId, _jsPlumb);
_updateAnchorClass();
self.anchor.bind("anchorChanged", function(currentAnchor) {
self.fire("anchorChanged", {endpoint:self, anchor:currentAnchor});
_updateAnchorClass();
});
if (!doNotRepaint)
_jsPlumb.repaint(_elementId);
};
this.cleanup = function() {
jpcl.removeClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
};
var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top");
self.setAnchor(anchorParamsToUse, true);
// ANCHOR MANAGER
if (!params._transient) // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted.
_jsPlumb.anchorManager.add(self, _elementId);
var _endpoint = null, originalEndpoint = null;
this.setEndpoint = function(ep) {
var _e = function(t, p) {
var rm = _jsPlumb.getRenderMode();
if (jsPlumb.Endpoints[rm][t]) return new jsPlumb.Endpoints[rm][t](p);
if (!_jsPlumb.Defaults.DoNotThrowErrors)
throw { msg:"jsPlumb: unknown endpoint type '" + t + "'" };
};
var endpointArgs = {
_jsPlumb:self._jsPlumb,
cssClass:params.cssClass,
parent:params.parent,
container:params.container,
tooltip:params.tooltip,
connectorTooltip:params.connectorTooltip,
endpoint:self
};
if (_ju.isString(ep))
_endpoint = _e(ep, endpointArgs);
else if (_ju.isArray(ep)) {
endpointArgs = _ju.merge(ep[1], endpointArgs);
_endpoint = _e(ep[0], endpointArgs);
}
else {
_endpoint = ep.clone();
}
// assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
// and the clone is left in its place while the original one goes off on a magical journey.
// the copy is to get around a closure problem, in which endpointArgs ends up getting shared by
// the whole world.
var argsForClone = jsPlumb.extend({}, endpointArgs);
_endpoint.clone = function() {
var o = new Object();
_endpoint.constructor.apply(o, [argsForClone]);
return o;
};
self.endpoint = _endpoint;
self.type = self.endpoint.type;
};
this.setEndpoint(params.endpoint || _jsPlumb.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot");
originalEndpoint = _endpoint;
// override setHover to pass it down to the underlying endpoint
var _sh = self.setHover;
self.setHover = function() {
self.endpoint.setHover.apply(self.endpoint, arguments);
_sh.apply(self, arguments);
};
// endpoint delegates to first connection for hover, if there is one.
var internalHover = function(state) {
if (self.connections.length > 0)
self.connections[0].setHover(state, false);
else
self.setHover(state);
};
// bind listeners from endpoint to self, with the internal hover function defined above.
self.bindListeners(self.endpoint, self, internalHover);
this.setPaintStyle(params.paintStyle ||
params.style ||
_jsPlumb.Defaults.EndpointStyle ||
jsPlumb.Defaults.EndpointStyle, true);
this.setHoverPaintStyle(params.hoverPaintStyle ||
_jsPlumb.Defaults.EndpointHoverStyle ||
jsPlumb.Defaults.EndpointHoverStyle, true);
this.paintStyleInUse = this.getPaintStyle();
var originalPaintStyle = this.getPaintStyle();
_ju.copyValues(typeParameters, params, this);
this.isSource = params.isSource || false;
this.isTarget = params.isTarget || false;
var _maxConnections = params.maxConnections || _jsPlumb.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
this.getAttachedElements = function() {
return self.connections;
};
this.canvas = this.endpoint.canvas;
// add anchor class (need to do this on construction because we set anchor first)
self.addClass(_jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
jpcl.addClass(_element, _jsPlumb.endpointAnchorClassPrefix + "_" + _currentAnchorClass);
this.connections = params.connections || [];
this.connectorPointerEvents = params["connector-pointer-events"];
this.scope = params.scope || _jsPlumb.getDefaultScope();
this.timestamp = null;
self.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections;
self.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable;
if (params.connectionsDetachable === false || params.detachable === false)
self.connectionsDetachable = false;
var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
if (params.onMaxConnections)
self.bind("maxConnections", params.onMaxConnections);
this.computeAnchor = function(params) {
return self.anchor.compute(params);
};
this.addConnection = function(connection) {
self.connections.push(connection);
self[(self.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
self[(self.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
};
this.detach = function(connection, ignoreTarget, forceDetach, fireEvent, originalEvent) {
var idx = _ju.findWithFunction(self.connections, function(c) { return c.id == connection.id}),
actuallyDetached = false;
fireEvent = (fireEvent !== false);
if (idx >= 0) {
// 1. does the connection have a before detach (note this also checks jsPlumb's bound
// detach handlers; but then Endpoint's check will, too, hmm.)
if (forceDetach || connection._forceDetach || connection.isDetachable() || connection.isDetachAllowed(connection)) {
// get the target endpoint
var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
if (forceDetach || connection._forceDetach || (self.isDetachAllowed(connection) /*&& t.isDetachAllowed(connection)*/)) {
self.connections.splice(idx, 1);
// avoid circular loop
if (!ignoreTarget) {
t.detach(connection, true, forceDetach);
// check connection to see if we want to delete the endpoints associated with it.
// we only detach those that have just this connection; this scenario is most
// likely if we got to this bit of code because it is set by the methods that
// create their own endpoints, like .connect or .makeTarget. the user is
// not likely to have interacted with those endpoints.
if (connection.endpointsToDeleteOnDetach){
for (var i = 0; i < connection.endpointsToDeleteOnDetach.length; i++) {
var cde = connection.endpointsToDeleteOnDetach[i];
if (cde && cde.connections.length == 0)
_jsPlumb.deleteEndpoint(cde);
}
}
}
if (connection.getConnector() != null)
_ju.removeElements(connection.getConnector().getDisplayElements(), connection.parent);
_ju.removeWithFunction(params.connectionsByScope[connection.scope], function(c) {
return c.id == connection.id;
});
self[(self.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
self[(self.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
actuallyDetached = true;
_fireDetachEvent(connection, (!ignoreTarget && fireEvent), originalEvent);
}
}
}
return actuallyDetached;
};
this.detachAll = function(fireEvent, originalEvent) {
while (self.connections.length > 0) {
self.detach(self.connections[0], false, true, fireEvent, originalEvent);
}
return self;
};
this.detachFrom = function(targetEndpoint, fireEvent, originalEvent) {
var c = [];
for ( var i = 0; i < self.connections.length; i++) {
if (self.connections[i].endpoints[1] == targetEndpoint
|| self.connections[i].endpoints[0] == targetEndpoint) {
c.push(self.connections[i]);
}
}
for ( var i = 0; i < c.length; i++) {
if (self.detach(c[i], false, true, fireEvent, originalEvent))
c[i].setHover(false, false);
}
return self;
};
this.detachFromConnection = function(connection) {
var idx = _ju.findWithFunction(self.connections, function(c) { return c.id == connection.id});
if (idx >= 0) {
self.connections.splice(idx, 1);
self[(self.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
self[(self.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
}
};
this.getElement = function() {
return _element;
};
this.setElement = function(el, container) {
var parentId = _jsPlumb.getId(el);
// remove the endpoint from the list for the current endpoint's element
_ju.removeWithFunction(params.endpointsByElement[self.elementId], function(e) {
return e.id == self.id;
});
_element = _gel(el);
_elementId = _jsPlumb.getId(_element);
self.elementId = _elementId;
// need to get the new parent now
var newParentElement = params.getParentFromParams({source:parentId, container:container}),
curParent = jpcl.getParent(self.canvas);
jpcl.removeElement(self.canvas, curParent);
jpcl.appendElement(self.canvas, newParentElement);
// now move connection(s)...i would expect there to be only one but we will iterate.
for (var i = 0; i < self.connections.length; i++) {
self.connections[i].moveParent(newParentElement);
self.connections[i].sourceId = _elementId;
self.connections[i].source = _element;
}
_ju.addToList(params.endpointsByElement, parentId, self);
};
this.getUuid = function() {
return _uuid;
};
/**
* private but must be exposed.
*/
self.makeInPlaceCopy = function() {
var loc = self.anchor.getCurrentLocation(self),
o = self.anchor.getOrientation(self),
acc = self.anchor.getCssClass(),
inPlaceAnchor = {
bind:function() { },
compute:function() { return [ loc[0], loc[1] ]},
getCurrentLocation : function() { return [ loc[0], loc[1] ]},
getOrientation:function() { return o; },
getCssClass:function() { return acc; }
};
return _newEndpoint( {
anchor : inPlaceAnchor,
source : _element,
paintStyle : this.getPaintStyle(),
endpoint : params.hideOnDrag ? "Blank" : _endpoint,
_transient:true,
scope:self.scope
});
};
this.isConnectedTo = function(endpoint) {
var found = false;
if (endpoint) {
for ( var i = 0; i < self.connections.length; i++) {
if (self.connections[i].endpoints[1] == endpoint) {
found = true;
break;
}
}
}
return found;
};
/**
* private but needs to be exposed.
*/
this.isFloating = function() {
return floatingEndpoint != null;
};
/**
* returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
*/
this.connectorSelector = function() {
var candidate = self.connections[0];
if (self.isTarget && candidate) return candidate;
else {
return (self.connections.length < _maxConnections) || _maxConnections == -1 ? null : candidate;
}
};
this.isFull = function() {
return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
};
this.setDragAllowedWhenFull = function(allowed) {
dragAllowedWhenFull = allowed;
};
this.setStyle = self.setPaintStyle;
/**
* a deep equals check. everything must match, including the anchor,
* styles, everything. TODO: finish Endpoint.equals
*/
this.equals = function(endpoint) {
return this.anchor.equals(endpoint.anchor);
};
// a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
// or no connection to it is found, we return the first connection in our list.
var findConnectionToUseForDynamicAnchor = function(elementWithPrecedence) {
var idx = 0;
if (elementWithPrecedence != null) {
for (var i = 0; i < self.connections.length; i++) {
if (self.connections[i].sourceId == elementWithPrecedence || self.connections[i].targetId == elementWithPrecedence) {
idx = i;
break;
}
}
}
return self.connections[idx];
};
this.paint = function(params) {
params = params || {};
var timestamp = params.timestamp, recalc = !(params.recalc === false);
if (!timestamp || self.timestamp !== timestamp) {
var info = _jsPlumb.updateOffset({ elId:_elementId, timestamp:timestamp, recalc:recalc });
var xy = params.offset ? params.offset.o : info.o;
if(xy) {
var ap = params.anchorPoint,connectorPaintStyle = params.connectorPaintStyle;
if (ap == null) {
var wh = params.dimensions || info.s;
if (xy == null || wh == null) {
info = _jsPlumb.updateOffset( { elId : _elementId, timestamp : timestamp });
xy = info.o;
wh = info.s;
}
var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
if (recalc && self.anchor.isDynamic && self.connections.length > 0) {
var c = findConnectionToUseForDynamicAnchor(params.elementWithPrecedence),
oIdx = c.endpoints[0] == self ? 1 : 0,
oId = oIdx == 0 ? c.sourceId : c.targetId,
oInfo = _jsPlumb.getCachedData(oId),
oOffset = oInfo.o, oWH = oInfo.s;
anchorParams.txy = [ oOffset.left, oOffset.top ];
anchorParams.twh = oWH;
anchorParams.tElement = c.endpoints[oIdx];
}
ap = self.anchor.compute(anchorParams);
}
_endpoint.compute(ap, self.anchor.getOrientation(self), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
_endpoint.paint(self.paintStyleInUse, self.anchor);
self.timestamp = timestamp;
// paint overlays
for ( var i = 0; i < self.overlays.length; i++) {
var o = self.overlays[i];
if (o.isVisible()) {
self.overlayPlacements[i] = o.draw(self.endpoint, self.paintStyleInUse);
o.paint(self.overlayPlacements[i]);
}
}
}
}
};
this.repaint = this.paint;
// is this a connection source? we make it draggable and have the
// drag listener maintain a connection with a floating endpoint.
if (jpcl.isDragSupported(_element)) {
var placeholderInfo = { id:null, element:null },
jpc = null,
existingJpc = false,
existingJpcParams = null,
_dragHandler = _makeConnectionDragHandler(placeholderInfo, _jsPlumb);
var start = function() {
// drag might have started on an endpoint that is not actually a source, but which has
// one or more connections.
jpc = self.connectorSelector();
var _continue = true;
// if not enabled, return
if (!self.isEnabled()) _continue = false;
// if no connection and we're not a source, return.
if (jpc == null && !params.isSource) _continue = false;
// otherwise if we're full and not allowed to drag, also return false.
if (params.isSource && self.isFull() && !dragAllowedWhenFull) _continue = false;
// if the connection was setup as not detachable or one of its endpoints
// was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
// is set to false...
if (jpc != null && !jpc.isDetachable()) _continue = false;
if (_continue === false) {
// this is for mootools and yui. returning false from this causes jquery to stop drag.
// the events are wrapped in both mootools and yui anyway, but i don't think returning
// false from the start callback would stop a drag.
if (jpcl.stopDrag) jpcl.stopDrag();
_dragHandler.stopDrag();
return false;
}
self.addClass("endpointDrag");
// if we're not full but there was a connection, make it null. we'll create a new one.
if (jpc && !self.isFull() && params.isSource) jpc = null;
_jsPlumb.updateOffset( { elId : _elementId });
inPlaceCopy = self.makeInPlaceCopy();
inPlaceCopy.referenceEndpoint = self;
inPlaceCopy.paint();
_makeDraggablePlaceholder(placeholderInfo, self.parent, _jsPlumb);
// set the offset of this div to be where 'inPlaceCopy' is, to start with.
// TODO merge this code with the code in both Anchor and FloatingAnchor, because it
// does the same stuff.
var ipcoel = _gel(inPlaceCopy.canvas),
ipco = _getOffset(ipcoel, _jsPlumb),
po = _jsPlumb.adjustForParentOffsetAndScroll([ipco.left, ipco.top], inPlaceCopy.canvas),
canvasElement = _gel(self.canvas);
jpcl.setOffset(placeholderInfo.element, {left:po[0], top:po[1]});
// when using makeSource and a parent, we first draw the source anchor on the source element, then
// move it to the parent. note that this happens after drawing the placeholder for the
// first time.
if (self.parentAnchor) self.anchor = _jsPlumb.makeAnchor(self.parentAnchor, self.elementId, _jsPlumb);
// store the id of the dragging div and the source element. the drop function will pick these up.
jpcl.setAttribute(canvasElement, "dragId", placeholderInfo.id);
jpcl.setAttribute(canvasElement, "elId", _elementId);
floatingEndpoint = _makeFloatingEndpoint(self.getPaintStyle(), self.anchor, _endpoint, self.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint);
self.canvas.style.visibility = "hidden";
if (jpc == null) {
self.anchor.locked = true;
self.setHover(false, false);
// create a connection. one end is this endpoint, the other is a floating endpoint.
jpc = _newConnection({
sourceEndpoint : self,
targetEndpoint : floatingEndpoint,
source : self.endpointWillMoveTo || _element, // for makeSource with parent option. ensure source element is represented correctly.
target : placeholderInfo.element,
anchors : [ self.anchor, floatingEndpoint.anchor ],
paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
hoverPaintStyle:params.connectorHoverStyle,
connector : params.connector, // this can also be null. Connection will use the default.
overlays : params.connectorOverlays,
type:self.connectionType,
cssClass:self.connectorClass,
hoverClass:self.connectorHoverClass
});
jpc.addClass(_jsPlumb.draggingClass);
floatingEndpoint.addClass(_jsPlumb.draggingClass);
// fire an event that informs that a connection is being dragged
_jsPlumb.fire("connectionDrag", jpc);
} else {
existingJpc = true;
jpc.setHover(false);
// if existing connection, allow to be dropped back on the source endpoint (issue 51).
_initDropTarget(ipcoel, false, true);
// new anchor idx
var anchorIdx = jpc.endpoints[0].id == self.id ? 0 : 1;
jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
// store the original scope (issue 57)
var dragScope = jsPlumb.CurrentLibrary.getDragScope(canvasElement);
jpcl.setAttribute(canvasElement, "originalScope", dragScope);
// now we want to get this endpoint's DROP scope, and set it for now: we can only be dropped on drop zones
// that have our drop scope (issue 57).
var dropScope = jpcl.getDropScope(canvasElement);
jpcl.setDragScope(canvasElement, dropScope);
// now we replace ourselves with the temporary div we created above:
if (anchorIdx == 0) {
existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
jpc.source = placeholderInfo.element;
jpc.sourceId = placeholderInfo.id;
} else {
existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
jpc.target = placeholderInfo.element;
jpc.targetId = placeholderInfo.id;
}
// lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
// store the original endpoint and assign the new floating endpoint for the drag.
jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
// PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39)
jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement();
jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId;
jpc.suspendedElementType = anchorIdx == 0 ? "source" : "target";
jpc.suspendedEndpoint.setHover(false);
floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint;
jpc.endpoints[anchorIdx] = floatingEndpoint;
jpc.addClass(_jsPlumb.draggingClass);
floatingEndpoint.addClass(_jsPlumb.draggingClass);
// fire an event that informs that a connection is being dragged
_jsPlumb.fire("connectionDrag", jpc);
}
// register it and register connection on it.
floatingConnections[placeholderInfo.id] = jpc;
_jsPlumb.anchorManager.addFloatingConnection(placeholderInfo.id, jpc);
floatingEndpoint.addConnection(jpc);
// only register for the target endpoint; we will not be dragging the source at any time
// before this connection is either discarded or made into a permanent connection.
_ju.addToList(params.endpointsByElement, placeholderInfo.id, floatingEndpoint);
// tell jsplumb about it
_jsPlumb.currentlyDragging = true;
};
var dragOptions = params.dragOptions || {},
defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
startEvent = jpcl.dragEvents["start"],
stopEvent = jpcl.dragEvents["stop"],
dragEvent = jpcl.dragEvents["drag"];
dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
dragOptions.scope = dragOptions.scope || self.scope;
dragOptions[startEvent] = _jsPlumb.wrap(dragOptions[startEvent], start);
// extracted drag handler function so can be used by makeSource
dragOptions[dragEvent] = _jsPlumb.wrap(dragOptions[dragEvent], _dragHandler.drag);
dragOptions[stopEvent] = _jsPlumb.wrap(dragOptions[stopEvent],
function() {
var originalEvent = jpcl.getDropEvent(arguments);
_ju.removeWithFunction(params.endpointsByElement[placeholderInfo.id], function(e) {
return e.id == floatingEndpoint.id;
});
_ju.removeElement(inPlaceCopy.canvas, _element);
_jsPlumb.anchorManager.clearFor(placeholderInfo.id);
var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
// commented out pending decision on drag proxy stuff.
// self.setPaintStyle(originalPaintStyle); // reset to original; may have been changed by drag proxy.
if (jpc.endpoints[idx] == floatingEndpoint) {
// if the connection was an existing one:
if (existingJpc && jpc.suspendedEndpoint) {
// fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
// floating endpoint has been replaced.
if (idx == 0) {
jpc.source = existingJpcParams[0];
jpc.sourceId = existingJpcParams[1];
} else {
jpc.target = existingJpcParams[0];
jpc.targetId = existingJpcParams[1];
}
// restore the original scope (issue 57)
jpcl.setDragScope(existingJpcParams[2], existingJpcParams[3]);
jpc.endpoints[idx] = jpc.suspendedEndpoint;
if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc, false, false, true, originalEvent)) {
jpc.setHover(false);
jpc.floatingAnchorIndex = null;
jpc.suspendedEndpoint.addConnection(jpc);
_jsPlumb.repaint(existingJpcParams[1]);
}
jpc._forceDetach = null;
jpc._forceReattach = null;
} else {
// TODO this looks suspiciously kind of like an Endpoint.detach call too.
// i wonder if this one should post an event though. maybe this is good like this.
_ju.removeElements(jpc.getConnector().getDisplayElements(), self.parent);
self.detachFromConnection(jpc);
}
}
// remove floating endpoint _after_ checking beforeDetach
_ju.removeElements( [ placeholderInfo.element[0], floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
_jsPlumb.dragManager.elementRemoved(floatingEndpoint.elementId);
self.canvas.style.visibility = "visible";
self.anchor.locked = false;
self.paint({recalc:false});
jpc.removeClass(_jsPlumb.draggingClass);
floatingEndpoint.removeClass(_jsPlumb.draggingClass);
_jsPlumb.fire("connectionDragStop", jpc);
jpc = null;
inPlaceCopy = null;
delete params.endpointsByElement[floatingEndpoint.elementId];
floatingEndpoint.anchor = null;
floatingEndpoint = null;
_jsPlumb.currentlyDragging = false;
});
var i = _gel(self.canvas);
jpcl.initDraggable(i, dragOptions, true, _jsPlumb);
}
// pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
// back onto the endpoint you detached it from.
var _initDropTarget = function(canvas, forceInit, isTransient, endpoint) {
if ((params.isTarget || forceInit) && jpcl.isDropSupported(_element)) {
var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
dropOptions = jsPlumb.extend( {}, dropOptions);
dropOptions.scope = dropOptions.scope || self.scope;
var dropEvent = jpcl.dragEvents['drop'],
overEvent = jpcl.dragEvents['over'],
outEvent = jpcl.dragEvents['out'],
drop = function() {
self["removeClass"](_jsPlumb.endpointDropAllowedClass);
self["removeClass"](_jsPlumb.endpointDropForbiddenClass);
var originalEvent = jpcl.getDropEvent(arguments),
draggable = _gel(jpcl.getDragObject(arguments)),
id = _att(draggable, "dragId"),
elId = _att(draggable, "elId"),
scope = _att(draggable, "originalScope"),
jpc = floatingConnections[id];
// if this is a drop back where the connection came from, mark it force rettach and
// return; the stop handler will reattach. without firing an event.
var redrop = jpc.suspendedEndpoint && (jpc.suspendedEndpoint.id == self.id ||
self.referenceEndpoint && jpc.suspendedEndpoint.id == self.referenceEndpoint.id) ;
if (redrop) {
jpc._forceReattach = true;
return;
}
if (jpc != null) {
var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
// restore the original scope if necessary (issue 57)
if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
var endpointEnabled = endpoint != null ? endpoint.isEnabled() : true;
if (self.isFull()) {
self.fire("maxConnections", {
endpoint:self,
connection:jpc,
maxConnections:_maxConnections
}, originalEvent);
}
if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget) && endpointEnabled) {
var _doContinue = true;
// the second check here is for the case that the user is dropping it back
// where it came from.
if (jpc.suspendedEndpoint && jpc.suspendedEndpoint.id != self.id) {
if (idx == 0) {
jpc.source = jpc.suspendedEndpoint.element;
jpc.sourceId = jpc.suspendedEndpoint.elementId;
} else {
jpc.target = jpc.suspendedEndpoint.element;
jpc.targetId = jpc.suspendedEndpoint.elementId;
}
if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc))
_doContinue = false;
}
// these have to be set before testing for beforeDrop.
if (idx == 0) {
jpc.source = self.element;
jpc.sourceId = self.elementId;
} else {
jpc.target = self.element;
jpc.targetId = self.elementId;
}
// ------------ wrap the execution path in a function so we can support asynchronous beforeDrop
// we want to execute this regardless.
var commonFunction = function() {
jpc.floatingAnchorIndex = null;
};
var continueFunction = function() {
// remove this jpc from the current endpoint
jpc.endpoints[idx].detachFromConnection(jpc);
if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
jpc.endpoints[idx] = self;
self.addConnection(jpc);
// copy our parameters in to the connection:
var params = self.getParameters();
for (var aParam in params)
jpc.setParameter(aParam, params[aParam]);
if (!jpc.suspendedEndpoint) {
if (params.draggable)
jsPlumb.CurrentLibrary.initDraggable(self.element, dragOptions, true, _jsPlumb);
}
else {
var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
// fire a detach event
_fireDetachEvent({
source : idx == 0 ? suspendedElement : jpc.source,
target : idx == 1 ? suspendedElement : jpc.target,
sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
targetId : idx == 1 ? suspendedElementId : jpc.targetId,
sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
connection : jpc
}, true, originalEvent);
}
// mark endpoints to delete on detach
if (jpc.endpoints[0].addedViaMouse) jpc.endpointsToDeleteOnDetach[0] = jpc.endpoints[0];
if (jpc.endpoints[1].addedViaMouse) jpc.endpointsToDeleteOnDetach[1] = jpc.endpoints[1];
// finalise will inform the anchor manager and also add to
// connectionsByScope if necessary.
_finaliseConnection(jpc, null, originalEvent);
commonFunction();
};
var dontContinueFunction = function() {
// otherwise just put it back on the endpoint it was on before the drag.
if (jpc.suspendedEndpoint) {
jpc.endpoints[idx] = jpc.suspendedEndpoint;
jpc.setHover(false);
jpc._forceDetach = true;
if (idx == 0) {
jpc.source = jpc.suspendedEndpoint.element;
jpc.sourceId = jpc.suspendedEndpoint.elementId;
} else {
jpc.target = jpc.suspendedEndpoint.element;
jpc.targetId = jpc.suspendedEndpoint.elementId;;
}
jpc.suspendedEndpoint.addConnection(jpc);
jpc.endpoints[0].repaint();
jpc.repaint();
_jsPlumb.repaint(jpc.sourceId);
jpc._forceDetach = false;
}
commonFunction();
};
// --------------------------------------
// now check beforeDrop. this will be available only on Endpoints that are setup to
// have a beforeDrop condition (although, secretly, under the hood all Endpoints and
// the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
// it only makes sense to have it on a target endpoint.
_doContinue = _doContinue && self.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, self);
if (_doContinue) {
continueFunction();
}
else {
dontContinueFunction();
}
//commonFunction();
}
_jsPlumb.currentlyDragging = false;
delete floatingConnections[id];
_jsPlumb.anchorManager.removeFloatingConnection(id);
}
};
dropOptions[dropEvent] = _jsPlumb.wrap(dropOptions[dropEvent], drop);
dropOptions[overEvent] = _jsPlumb.wrap(dropOptions[overEvent], function() {
var draggable = jpcl.getDragObject(arguments),
id = _att( _gel(draggable), "dragId"),
_jpc = floatingConnections[id];
if (_jpc != null) {
var idx = _jpc.floatingAnchorIndex == null ? 1 : _jpc.floatingAnchorIndex;
// here we should fire the 'over' event if we are a target and this is a new connection,
// or we are the same as the floating endpoint.
var _cont = (self.isTarget && _jpc.floatingAnchorIndex != 0) || (_jpc.suspendedEndpoint && self.referenceEndpoint && self.referenceEndpoint.id == _jpc.suspendedEndpoint.id);
if (_cont) {
var bb = _jsPlumb.checkCondition("checkDropAllowed", {
sourceEndpoint:_jpc.endpoints[idx],
targetEndpoint:self,
connection:_jpc
});
self[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass);
self[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass);
_jpc.endpoints[idx].anchor.over(self.anchor);
}
}
});
dropOptions[outEvent] = _jsPlumb.wrap(dropOptions[outEvent], function() {
var draggable = jpcl.getDragObject(arguments),
id = _att( _gel(draggable), "dragId"),
_jpc = floatingConnections[id];
if (_jpc != null) {
var idx = _jpc.floatingAnchorIndex == null ? 1 : _jpc.floatingAnchorIndex;
var _cont = (self.isTarget && _jpc.floatingAnchorIndex != 0) || (_jpc.suspendedEndpoint && self.referenceEndpoint && self.referenceEndpoint.id == _jpc.suspendedEndpoint.id);
if (_cont) {
self["removeClass"](_jsPlumb.endpointDropAllowedClass);
self["removeClass"](_jsPlumb.endpointDropForbiddenClass);
_jpc.endpoints[idx].anchor.out();
}
}
});
jpcl.initDroppable(canvas, dropOptions, true, isTransient);
}
};
// initialise the endpoint's canvas as a drop target. this will be ignored if the endpoint is not a target or drag is not supported.
_initDropTarget(_gel(self.canvas), true, !(params._transient || self.anchor.isFloating), self);
// finally, set type if it was provided
if (params.type)
self.addType(params.type, params.data, _jsPlumb.isSuspendDrawing());
return self;
};
})();
\ No newline at end of file
// this is really just a test overlay, so its undocumented and doesnt take any parameters. but i was loth to delete it.
jsPlumb.Overlays.GuideLines = function() {
var self = this;
self.length = 50;
self.lineWidth = 5;
this.type = "GuideLines";
AbstractOverlay.apply(this, arguments);
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
mid = connector.pointOnPath(self.loc),
tail = jsPlumbUtil.pointOnLine(head, mid, self.length),
tailLine = jsPlumbUtil.perpendicularLineTo(head, tail, 40),
headLine = jsPlumbUtil.perpendicularLineTo(tail, head, 20);
self.paint(connector, [head, tail, tailLine, headLine], self.lineWidth, "red", null, connectorDimensions);
return [Math.min(head.x, tail.x), Math.min(head.y, tail.y), Math.max(head.x, tail.x), Math.max(head.y,tail.y)];
};
this.computeMaxSize = function() { return 50; };
this.cleanup = function() { }; // nothing to clean up for GuideLines
};
// a test
jsPlumb.Overlays.svg.GuideLines = function() {
var path = null, self = this, path2 = null, p1_1, p1_2;
jsPlumb.Overlays.GuideLines.apply(this, arguments);
this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
if (path == null) {
path = _node("path");
connector.svg.appendChild(path);
self.attachListeners(path, connector);
self.attachListeners(path, self);
p1_1 = _node("path");
connector.svg.appendChild(p1_1);
self.attachListeners(p1_1, connector);
self.attachListeners(p1_1, self);
p1_2 = _node("path");
connector.svg.appendChild(p1_2);
self.attachListeners(p1_2, connector);
self.attachListeners(p1_2, self);
}
_attr(path, {
"d" : makePath(d[0], d[1]),
stroke : "red",
fill : null
});
_attr(p1_1, {
"d" : makePath(d[2][0], d[2][1]),
stroke : "blue",
fill : null
});
_attr(p1_2, {
"d" : makePath(d[3][0], d[3][1]),
stroke : "green",
fill : null
});
};
var makePath = function(d1, d2) {
return "M " + d1.x + "," + d1.y +
" L" + d2.x + "," + d2.y;
};
};
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the HTML5 canvas renderers. Support for canvas was dropped in 1.4.1.
* This is being kept around because canvas might make a comeback as a single-page solution
* that also supports node rendering.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
// event binding from jsplumb. canvas no longer supported. but it may make a comeback in
// the form of a single-page canvas.
/*var bindOne = function(event) {
jsPlumb.CurrentLibrary.bind(document, event, function(e) {
if (!_currentInstance.currentlyDragging && renderMode == jsPlumb.CANVAS) {
// try connections first
for (var scope in connectionsByScope) {
var c = connectionsByScope[scope];
for (var i = 0, ii = c.length; i < ii; i++) {
var t = c[i].getConnector()[event](e);
if (t) return;
}
}
for (var el in endpointsByElement) {
var ee = endpointsByElement[el];
for (var i = 0, ii = ee.length; i < ii; i++) {
if (ee[i].endpoint[event](e)) return;
}
}
}
});
};
bindOne("click");bindOne("dblclick");bindOne("mousemove");bindOne("mousedown");bindOne("mouseup");bindOne("contextmenu");
*/
// ********************************* CANVAS RENDERERS FOR CONNECTORS AND ENDPOINTS *******************************************************************
// TODO refactor to renderer common script. put a ref to jsPlumb.sizeCanvas in there too.
var _connectionBeingDragged = null,
_hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
_getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
_getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
_pageXY = function(el) { return jsPlumb.CurrentLibrary.getPageXY(el); },
_clientXY = function(el) { return jsPlumb.CurrentLibrary.getClientXY(el); };
/*
* Class:CanvasMouseAdapter
* Provides support for mouse events on canvases.
*/
var CanvasMouseAdapter = function() {
var self = this;
self.overlayPlacements = [];
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
jsPlumbUtil.EventGenerator.apply(this, arguments);
/**
* returns whether or not the given event is ojver a painted area of the canvas.
*/
this._over = function(e) {
var o = _getOffset(_getElementObject(self.canvas)),
pageXY = _pageXY(e),
x = pageXY[0] - o.left, y = pageXY[1] - o.top;
if (x > 0 && y > 0 && x < self.canvas.width && y < self.canvas.height) {
// first check overlays
for ( var i = 0; i < self.overlayPlacements.length; i++) {
var p = self.overlayPlacements[i];
if (p && (p[0] <= x && p[1] >= x && p[2] <= y && p[3] >= y))
return true;
}
// then the canvas
var d = self.canvas.getContext("2d").getImageData(parseInt(x, 10), parseInt(y, 10), 1, 1);
return d.data[0] !== 0 || d.data[1] !== 0 || d.data[2] !== 0 || d.data[3] !== 0;
}
return false;
};
var _mouseover = false, _mouseDown = false, _posWhenMouseDown = null, _mouseWasDown = false,
_nullSafeHasClass = function(el, clazz) {
return el !== null && _hasClass(el, clazz);
};
this.mousemove = function(e) {
var pageXY = _pageXY(e), clientXY = _clientXY(e),
ee = document.elementFromPoint(clientXY[0], clientXY[1]),
eventSourceWasOverlay = _nullSafeHasClass(ee, "_jsPlumb_overlay");
var _continue = _connectionBeingDragged === null && (_nullSafeHasClass(ee, "_jsPlumb_endpoint") || _nullSafeHasClass(ee, "_jsPlumb_connector"));
if (!_mouseover && _continue && self._over(e)) {
_mouseover = true;
self.fire("mouseenter", self, e);
return true;
}
// TODO here there is a remote chance that the overlay the mouse moved onto
// is actually not an overlay for the current component. a more thorough check would
// be to ensure the overlay belonged to the current component.
else if (_mouseover && (!self._over(e) || !_continue) && !eventSourceWasOverlay) {
_mouseover = false;
self.fire("mouseexit", self, e);
}
self.fire("mousemove", self, e);
};
this.click = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("click", self, e);
_mouseWasDown = false;
};
this.dblclick = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("dblclick", self, e);
_mouseWasDown = false;
};
this.mousedown = function(e) {
if(self._over(e) && !_mouseDown) {
_mouseDown = true;
_posWhenMouseDown = _getOffset(_getElementObject(self.canvas));
self.fire("mousedown", self, e);
}
};
this.mouseup = function(e) {
_mouseDown = false;
self.fire("mouseup", self, e);
};
this.contextmenu = function(e) {
if (_mouseover && self._over(e) && !_mouseWasDown)
self.fire("contextmenu", self, e);
_mouseWasDown = false;
};
};
var _newCanvas = function(params) {
var canvas = document.createElement("canvas");
params["_jsPlumb"].appendElement(canvas, params.parent);
canvas.style.position = "absolute";
if (params["class"]) canvas.className = params["class"];
// set an id. if no id on the element and if uuid was supplied it
// will be used, otherwise we'll create one.
params["_jsPlumb"].getId(canvas, params.uuid);
if (params.tooltip) canvas.setAttribute("title", params.tooltip);
return canvas;
};
var CanvasComponent = function(params) {
CanvasMouseAdapter.apply(this, arguments);
var displayElements = [ ];
this.getDisplayElements = function() { return displayElements; };
this.appendDisplayElement = function(el) { displayElements.push(el); };
};
var segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ];
var maybeMakeGradient = function(ctx, style, gradientFunction) {
if (style.gradient) {
var g = gradientFunction();
for ( var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.strokeStyle = g;
}
};
var segmentRenderer = function(segment, ctx, style, dx, dy) {
({
"Straight":function(segment, ctx, style, dx, dy) {
var d = segment.params;
maybeMakeGradient(ctx, style, function() { return ctx.createLinearGradient(d.x1, d.y1, d.x2, d.y2); });
ctx.beginPath();
ctx.translate(dx/2, dy/2);
if (style.dashstyle && style.dashstyle.split(" ").length === 2) {
// only a very simple dashed style is supported - having two values, which define the stroke length
// (as a multiple of the stroke width) and then the space length (also as a multiple of stroke width).
var ds = style.dashstyle.split(" ");
if (ds.length !== 2) ds = [2, 2];
var dss = [ ds[0] * style.lineWidth, ds[1] * style.lineWidth ],
m = (d.x2- d.x1) / (d.y2 - d.y1),
s = jsPlumbUtil.segment([d.x1, d.y1], [ d.x2, d.y2 ]),
sm = segmentMultipliers[s],
theta = Math.atan(m),
l = Math.sqrt(Math.pow(d.x2 - d.x1, 2) + Math.pow(d.y2 - d.y1, 2)),
repeats = Math.floor(l / (dss[0] + dss[1])),
curPos = [d.x1, d.y1];
// TODO: the question here is why could we not support this in all connector types? it's really
// just a case of going along and asking jsPlumb for the next point on the path a few times, until it
// reaches the end. every type of connector supports that method, after all. but right now its only the
// bezier connector that gives you back the new location on the path along with the x,y coordinates, which
// we would need. we'd start out at loc=0 and ask for the point along the path that is dss[0] pixels away.
// we then ask for the point that is (dss[0] + dss[1]) pixels away; and from that one we need not just the
// x,y but the location, cos we're gonna plug that location back in in order to find where that dash ends.
//
// it also strikes me that it should be trivial to support arbitrary dash styles (having more or less than two
// entries). you'd just iterate that array using a step size of 2, and generify the (rss[0] + rss[1])
// computation to be sum(rss[0]..rss[n]).
for (var i = 0; i < repeats; i++) {
ctx.moveTo(curPos[0], curPos[1]);
var nextEndX = curPos[0] + (Math.abs(Math.sin(theta) * dss[0]) * sm[0]),
nextEndY = curPos[1] + (Math.abs(Math.cos(theta) * dss[0]) * sm[1]),
nextStartX = curPos[0] + (Math.abs(Math.sin(theta) * (dss[0] + dss[1])) * sm[0]),
nextStartY = curPos[1] + (Math.abs(Math.cos(theta) * (dss[0] + dss[1])) * sm[1]);
ctx.lineTo(nextEndX, nextEndY);
curPos = [nextStartX, nextStartY];
}
// now draw the last bit
ctx.moveTo(curPos[0], curPos[1]);
ctx.lineTo(d.x2, d.y2);
}
else {
ctx.moveTo(d.x1, d.y1);
ctx.lineTo(d.x2, d.y2);
}
ctx.stroke();
},
"Bezier":function(segment, ctx, style, dx, dy) {
var d = segment.params;
maybeMakeGradient(ctx, style, function() { return ctx.createLinearGradient(d.x2 + dx, d.y2 + dy, d.x1 + dx, d.y1 + dy); });
ctx.beginPath();
ctx.translate(dx, dy);
ctx.moveTo(d.x1, d.y1);
ctx.bezierCurveTo(d.cp1x, d.cp1y, d.cp2x, d.cp2y, d.x2, d.y2);
ctx.stroke();
},
"Arc":function(segment, ctx, style, dx, dy) {
var d = segment.params;
ctx.beginPath();
// arcTo is supported in most browsers i think; this is what we will use once the arc segment is a little more clever.
// right now its up to the connector to figure out the geometry. well, maybe that's ok.
//ctx.moveTo(d.x1, d.y1);
//ctx.arcTo((d.x1 + d.x2) / 2, (d.y1 + d.y2) / 2, d.r);
ctx.translate(dx, dy);
ctx.arc(d.cx, d.cy, d.r, d.startAngle, d.endAngle, d.c);
ctx.stroke();
}
})[segment.type](segment, ctx, style, dx, dy);
};
/**
* Class:CanvasConnector
* Superclass for Canvas Connector renderers.
*/
var CanvasConnector = jsPlumb.ConnectorRenderers.canvas = function(params) {
var self = this;
CanvasComponent.apply(this, arguments);
var _paintOneStyle = function(aStyle, dx, dy) {
self.ctx.save();
jsPlumb.extend(self.ctx, aStyle);
var segments = self.getSegments();
for (var i = 0; i < segments.length; i++) {
segmentRenderer(segments[i], self.ctx, aStyle, dx, dy);
}
self.ctx.restore();
};
var self = this,
clazz = self._jsPlumb.connectorClass + " " + (params.cssClass || "");
self.canvas = _newCanvas({
"class":clazz,
_jsPlumb:self._jsPlumb,
parent:params.parent
});
self.ctx = self.canvas.getContext("2d");
self.appendDisplayElement(self.canvas);
self.paint = function(style, anchor, extents) {
if (style != null) {
var xy = [ self.x, self.y ], wh = [ self.w, self.h ], p,
dx = 0, dy = 0;
if (extents != null) {
if (extents.xmin < 0) {
xy[0] += extents.xmin;
dx = -extents.xmin;
}
if (extents.ymin < 0) {
xy[1] += extents.ymin;
dy = -extents.ymin;
}
wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0);
wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0);
}
self.translateX = dx;
self.translateY = dy;
jsPlumb.sizeCanvas(self.canvas, xy[0], xy[1], wh[0], wh[1]);
if (style.outlineColor != null) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
outlineStyle = {
strokeStyle:style.outlineColor,
lineWidth:outlineStrokeWidth
};
_paintOneStyle(outlineStyle, dx, dy);
}
_paintOneStyle(style, dx, dy);
}
};
};
/**
* Class:CanvasEndpoint
* Superclass for Canvas Endpoint renderers.
*/
var CanvasEndpoint = function(params) {
var self = this;
CanvasComponent.apply(this, arguments);
var clazz = self._jsPlumb.endpointClass + " " + (params.cssClass || ""),
canvasParams = {
"class":clazz,
_jsPlumb:self._jsPlumb,
parent:params.parent,
tooltip:self.tooltip
};
self.canvas = _newCanvas(canvasParams);
self.ctx = self.canvas.getContext("2d");
self.appendDisplayElement(self.canvas);
this.paint = function(style, anchor, extents) {
jsPlumb.sizeCanvas(self.canvas, self.x, self.y, self.w, self.h);
if (style.outlineColor != null) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
var outlineStyle = {
strokeStyle:style.outlineColor,
lineWidth:outlineStrokeWidth
};
}
self._paint.apply(this, arguments);
};
};
jsPlumb.Endpoints.canvas.Dot = function(params) {
jsPlumb.Endpoints.Dot.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
var self = this,
parseValue = function(value) {
try { return parseInt(value); }
catch(e) {
if (value.substring(value.length - 1) == '%')
return parseInt(value.substring(0, value - 1));
}
},
calculateAdjustments = function(gradient) {
var offsetAdjustment = self.defaultOffset, innerRadius = self.defaultInnerRadius;
gradient.offset && (offsetAdjustment = parseValue(gradient.offset));
gradient.innerRadius && (innerRadius = parseValue(gradient.innerRadius));
return [offsetAdjustment, innerRadius];
};
this._paint = function(style) {
if (style != null) {
var ctx = self.canvas.getContext('2d'),
orientation = params.endpoint.anchor.getOrientation(params.endpoint);
jsPlumb.extend(ctx, style);
if (style.gradient) {
var adjustments = calculateAdjustments(style.gradient),
yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0],
xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0],
g = ctx.createRadialGradient(self.radius, self.radius, self.radius, self.radius + xAdjust, self.radius + yAdjust, adjustments[1]);
for (var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.fillStyle = g;
}
ctx.beginPath();
ctx.arc(self.radius, self.radius, self.radius, 0, Math.PI*2, true);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
}
};
};
jsPlumb.Endpoints.canvas.Rectangle = function(params) {
var self = this;
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
this._paint = function(style) {
var ctx = self.canvas.getContext("2d"),
orientation = params.endpoint.anchor.getOrientation(params.endpoint);
jsPlumb.extend(ctx, style);
/* canvas gradient */
if (style.gradient) {
// first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
var y1 = orientation[1] == 1 ? self.h : orientation[1] == 0 ? self.h / 2 : 0;
var y2 = orientation[1] == -1 ? self.h : orientation[1] == 0 ? self.h / 2 : 0;
var x1 = orientation[0] == 1 ? self.w : orientation[0] == 0 ? self.w / 2 : 0;
var x2 = orientation[0] == -1 ? self.w : orientation[0] == 0 ? self.w / 2 : 0;
var g = ctx.createLinearGradient(x1,y1,x2,y2);
for (var i = 0; i < style.gradient.stops.length; i++)
g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
ctx.fillStyle = g;
}
ctx.beginPath();
ctx.rect(0, 0, self.w, self.h);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
};
};
jsPlumb.Endpoints.canvas.Triangle = function(params) {
var self = this;
jsPlumb.Endpoints.Triangle.apply(this, arguments);
CanvasEndpoint.apply(this, arguments);
this._paint = function(style)
{
var ctx = self.canvas.getContext('2d'),
offsetX = 0, offsetY = 0, angle = 0,
orientation = params.endpoint.anchor.getOrientation(params.endpoint);
if( orientation[0] == 1 ) {
offsetX = self.width;
offsetY = self.height;
angle = 180;
}
if( orientation[1] == -1 ) {
offsetX = self.width;
angle = 90;
}
if( orientation[1] == 1 ) {
offsetY = self.height;
angle = -90;
}
ctx.fillStyle = style.fillStyle;
ctx.translate(offsetX, offsetY);
ctx.rotate(angle * Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(self.width/2, self.height/2);
ctx.lineTo(0, self.height);
ctx.closePath();
if (style.fillStyle || style.gradient) ctx.fill();
if (style.strokeStyle) ctx.stroke();
};
};
/*
* Canvas Image Endpoint: uses the default version, which creates an <img> tag.
*/
jsPlumb.Endpoints.canvas.Image = jsPlumb.Endpoints.Image;
/*
* Blank endpoint in all renderers is just the default Blank endpoint.
*/
jsPlumb.Endpoints.canvas.Blank = jsPlumb.Endpoints.Blank;
/*
* Canvas Bezier Connector. Draws a Bezier curve onto a Canvas element.
*/
jsPlumb.Connectors.canvas.Bezier = function() {
jsPlumb.Connectors.Bezier.apply(this, arguments);
CanvasConnector.apply(this, arguments);
};
/*
* Canvas straight line Connector. Draws a straight line onto a Canvas element.
*/
jsPlumb.Connectors.canvas.Straight = function() {
jsPlumb.Connectors.Straight.apply(this, arguments);
CanvasConnector.apply(this, arguments);
};
jsPlumb.Connectors.canvas.Flowchart = function() {
jsPlumb.Connectors.Flowchart.apply(this, arguments);
CanvasConnector.apply(this, arguments);
};
// ********************************* END OF CANVAS RENDERERS *******************************************************************
jsPlumb.Overlays.canvas.Label = jsPlumb.Overlays.Label;
jsPlumb.Overlays.canvas.Custom = jsPlumb.Overlays.Custom;
/**
* a placeholder right now, really just exists to mirror the fact that there are SVG and VML versions of this.
*/
var CanvasOverlay = function() {
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
};
var AbstractCanvasArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
CanvasOverlay.apply(this, originalArgs);
this.paint = function(params, containerExtents) {
var ctx = params.component.ctx, d = params.d;
if (d) {
ctx.lineWidth = params.lineWidth;
ctx.beginPath();
ctx.translate(params.component.translateX, params.component.translateY);
ctx.moveTo(d.hxy.x, d.hxy.y);
ctx.lineTo(d.tail[0].x, d.tail[0].y);
ctx.lineTo(d.cxy.x, d.cxy.y);
ctx.lineTo(d.tail[1].x, d.tail[1].y);
ctx.lineTo(d.hxy.x, d.hxy.y);
ctx.closePath();
if (params.strokeStyle) {
ctx.strokeStyle = params.strokeStyle;
ctx.stroke();
}
if (params.fillStyle) {
ctx.fillStyle = params.fillStyle;
ctx.fill();
}
}
};
};
jsPlumb.Overlays.canvas.Arrow = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.canvas.PlainArrow = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.canvas.Diamond = function() {
AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the SVG renderers.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
/**
* SVG support for jsPlumb.
*
* things to investigate:
*
* gradients: https://developer.mozilla.org/en/svg_in_html_introduction
* css:http://tutorials.jenkov.com/svg/svg-and-css.html
* text on a path: http://www.w3.org/TR/SVG/text.html#TextOnAPath
* pointer events: https://developer.mozilla.org/en/css/pointer-events
*
* IE9 hover jquery: http://forum.jquery.com/topic/1-6-2-broke-svg-hover-events
*
*/
;(function() {
// ************************** SVG utility methods ********************************************
var svgAttributeMap = {
"joinstyle":"stroke-linejoin",
"stroke-linejoin":"stroke-linejoin",
"stroke-dashoffset":"stroke-dashoffset",
"stroke-linecap":"stroke-linecap"
},
STROKE_DASHARRAY = "stroke-dasharray",
DASHSTYLE = "dashstyle",
LINEAR_GRADIENT = "linearGradient",
RADIAL_GRADIENT = "radialGradient",
FILL = "fill",
STOP = "stop",
STROKE = "stroke",
STROKE_WIDTH = "stroke-width",
STYLE = "style",
NONE = "none",
JSPLUMB_GRADIENT = "jsplumb_gradient_",
LINE_WIDTH = "lineWidth",
ns = {
svg:"http://www.w3.org/2000/svg",
xhtml:"http://www.w3.org/1999/xhtml"
},
_attr = function(node, attributes) {
for (var i in attributes)
node.setAttribute(i, "" + attributes[i]);
},
_node = function(name, attributes) {
var n = document.createElementNS(ns.svg, name);
attributes = attributes || {};
attributes["version"] = "1.1";
attributes["xmlns"] = ns.xhtml;
_attr(n, attributes);
return n;
},
_pos = function(d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; },
_clearGradient = function(parent) {
for (var i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes[i].tagName == LINEAR_GRADIENT || parent.childNodes[i].tagName == RADIAL_GRADIENT)
parent.removeChild(parent.childNodes[i]);
}
},
_updateGradient = function(parent, node, style, dimensions, uiComponent) {
var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.idstamp();
// first clear out any existing gradient
_clearGradient(parent);
// this checks for an 'offset' property in the gradient, and in the absence of it, assumes
// we want a linear gradient. if it's there, we create a radial gradient.
// it is possible that a more explicit means of defining the gradient type would be
// better. relying on 'offset' means that we can never have a radial gradient that uses
// some default offset, for instance.
// issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would
// not show gradients when the line was perfectly horizontal or vertical.
var g;
if (!style.gradient.offset) {
g = _node(LINEAR_GRADIENT, {id:id, gradientUnits:"userSpaceOnUse"});
}
else {
g = _node(RADIAL_GRADIENT, {
id:id
});
}
parent.appendChild(g);
// the svg radial gradient seems to treat stops in the reverse
// order to how canvas does it. so we want to keep all the maths the same, but
// iterate the actual style declarations in reverse order, if the x indexes are not in order.
for (var i = 0; i < style.gradient.stops.length; i++) {
var styleToUse = uiComponent.segment == 1 || uiComponent.segment == 2 ? i: style.gradient.stops.length - 1 - i,
stopColor = jsPlumbUtil.convertStyle(style.gradient.stops[styleToUse][1], true),
s = _node(STOP, {"offset":Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color":stopColor});
g.appendChild(s);
}
var applyGradientTo = style.strokeStyle ? STROKE : FILL;
node.setAttribute(STYLE, applyGradientTo + ":url(#" + id + ")");
},
_applyStyles = function(parent, node, style, dimensions, uiComponent) {
if (style.gradient) {
_updateGradient(parent, node, style, dimensions, uiComponent);
}
else {
// make sure we clear any existing gradient
_clearGradient(parent);
node.setAttribute(STYLE, "");
}
node.setAttribute(FILL, style.fillStyle ? jsPlumbUtil.convertStyle(style.fillStyle, true) : NONE);
node.setAttribute(STROKE, style.strokeStyle ? jsPlumbUtil.convertStyle(style.strokeStyle, true) : NONE);
if (style.lineWidth) {
node.setAttribute(STROKE_WIDTH, style.lineWidth);
}
// in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
// the syntax in VML but is actually kind of nasty: values are given in the pixel
// coordinate space, whereas in VML they are multiples of the width of the stroked
// line, which makes a lot more sense. for that reason, jsPlumb is supporting both
// the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
// VML, which will be the preferred method. the code below this converts a dashstyle
// attribute given in terms of stroke width into a pixel representation, by using the
// stroke's lineWidth.
if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) {
var sep = style[DASHSTYLE].indexOf(",") == -1 ? " " : ",",
parts = style[DASHSTYLE].split(sep),
styleToUse = "";
parts.forEach(function(p) {
styleToUse += (Math.floor(p * style.lineWidth) + sep);
});
node.setAttribute(STROKE_DASHARRAY, styleToUse);
}
else if(style[STROKE_DASHARRAY]) {
node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]);
}
// extra attributes such as join type, dash offset.
for (var i in svgAttributeMap) {
if (style[i]) {
node.setAttribute(svgAttributeMap[i], style[i]);
}
}
},
_decodeFont = function(f) {
var r = /([0-9].)(p[xt])\s(.*)/,
bits = f.match(r);
return {size:bits[1] + bits[2], font:bits[3]};
},
_classManip = function(el, add, clazz) {
var classesToAddOrRemove = clazz.split(" "),
className = el.className,
curClasses = className.baseVal.split(" ");
for (var i = 0; i < classesToAddOrRemove.length; i++) {
if (add) {
if (curClasses.indexOf(classesToAddOrRemove[i]) == -1)
curClasses.push(classesToAddOrRemove[i]);
}
else {
var idx = curClasses.indexOf(classesToAddOrRemove[i]);
if (idx != -1)
curClasses.splice(idx, 1);
}
}
el.className.baseVal = curClasses.join(" ");
},
_addClass = function(el, clazz) { _classManip(el, true, clazz); },
_removeClass = function(el, clazz) { _classManip(el, false, clazz); },
_appendAtIndex = function(svg, path, idx) {
if (svg.childNodes.length > idx) {
svg.insertBefore(path, svg.childNodes[idx]);
}
else svg.appendChild(path);
};
/**
utility methods for other objects to use.
*/
jsPlumbUtil.svg = {
addClass:_addClass,
removeClass:_removeClass,
node:_node,
attr:_attr,
pos:_pos
};
// ************************** / SVG utility methods ********************************************
/*
* Base class for SVG components.
*/
var SvgComponent = function(params) {
var self = this,
pointerEventsSpec = params.pointerEventsSpec || "all",
renderer = {};
jsPlumb.jsPlumbUIComponent.apply(this, params.originalArgs);
self.canvas = null, self.path = null, self.svg = null;
var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""),
svgParams = {
"style":"",
"width":0,
"height":0,
"pointer-events":pointerEventsSpec,
"position":"absolute"
};
self.svg = _node("svg", svgParams);
if (params.useDivWrapper) {
self.canvas = document.createElement("div");
self.canvas.style["position"] = "absolute";
jsPlumb.sizeCanvas(self.canvas,0,0,1,1);
self.canvas.className = clazz;
}
else {
_attr(self.svg, { "class":clazz });
self.canvas = self.svg;
}
params._jsPlumb.appendElement(self.canvas, params.originalArgs[0]["parent"]);
if (params.useDivWrapper) self.canvas.appendChild(self.svg);
// TODO this displayElement stuff is common between all components, across all
// renderers. would be best moved to jsPlumbUIComponent.
var displayElements = [ self.canvas ];
this.getDisplayElements = function() {
return displayElements;
};
this.appendDisplayElement = function(el) {
displayElements.push(el);
};
this.paint = function(style, anchor, extents) {
if (style != null) {
var xy = [ self.x, self.y ], wh = [ self.w, self.h ], p;
if (extents != null) {
if (extents.xmin < 0) xy[0] += extents.xmin;
if (extents.ymin < 0) xy[1] += extents.ymin;
wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0);
wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0);
}
if (params.useDivWrapper) {
jsPlumb.sizeCanvas(self.canvas, xy[0], xy[1], wh[0], wh[1]);
xy[0] = 0, xy[1] = 0;
p = _pos([ 0, 0 ]);
}
else
p = _pos([ xy[0], xy[1] ]);
renderer.paint.apply(this, arguments);
_attr(self.svg, {
"style":p,
"width": wh[0],
"height": wh[1]
});
}
};
return {
renderer:renderer
};
};
/*
* Base class for SVG connectors.
*/
var SvgConnector = jsPlumb.ConnectorRenderers.svg = function(params) {
var self = this,
_super = SvgComponent.apply(this, [ {
cssClass:params["_jsPlumb"].connectorClass,
originalArgs:arguments,
pointerEventsSpec:"none",
_jsPlumb:params["_jsPlumb"]
} ]);
_super.renderer.paint = function(style, anchor, extents) {
var segments = self.getSegments(), p = "", offset = [0,0];
if (extents.xmin < 0) offset[0] = -extents.xmin;
if (extents.ymin < 0) offset[1] = -extents.ymin;
// create path from segments.
for (var i = 0; i < segments.length; i++) {
p += jsPlumb.Segments.svg.SegmentRenderer.getPath(segments[i]);
p += " ";
}
var a = {
d:p,
transform:"translate(" + offset[0] + "," + offset[1] + ")",
"pointer-events":params["pointer-events"] || "visibleStroke"
},
outlineStyle = null,
d = [self.x,self.y,self.w,self.h];
// outline style. actually means drawing an svg object underneath the main one.
if (style.outlineColor) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
outlineStyle = jsPlumb.CurrentLibrary.extend({}, style);
outlineStyle.strokeStyle = jsPlumbUtil.convertStyle(style.outlineColor);
outlineStyle.lineWidth = outlineStrokeWidth;
if (self.bgPath == null) {
self.bgPath = _node("path", a);
_appendAtIndex(self.svg, self.bgPath, 0);
self.attachListeners(self.bgPath, self);
}
else {
_attr(self.bgPath, a);
}
_applyStyles(self.svg, self.bgPath, outlineStyle, d, self);
}
if (self.path == null) {
self.path = _node("path", a);
_appendAtIndex(self.svg, self.path, style.outlineColor ? 1 : 0);
self.attachListeners(self.path, self);
}
else {
_attr(self.path, a);
}
_applyStyles(self.svg, self.path, style, d, self);
};
this.reattachListeners = function() {
if (self.bgPath) self.reattachListenersForElement(self.bgPath, self);
if (self.path) self.reattachListenersForElement(self.path, self);
};
};
// ******************************* svg segment renderer *****************************************************
jsPlumb.Segments.svg = {
SegmentRenderer : {
getPath : function(segment) {
return ({
"Straight":function() {
var d = segment.getCoordinates();
return "M " + d.x1 + " " + d.y1 + " L " + d.x2 + " " + d.y2;
},
"Bezier":function() {
var d = segment.params;
return "M " + d.x1 + " " + d.y1 +
" C " + d.cp1x + " " + d.cp1y + " " + d.cp2x + " " + d.cp2y + " " + d.x2 + " " + d.y2;
},
"Arc":function() {
var d = segment.params,
laf = segment.sweep > Math.PI ? 1 : 0,
sf = segment.anticlockwise ? 0 : 1;
return "M" + segment.x1 + " " + segment.y1 + " A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2;
}
})[segment.type]();
}
}
};
// ******************************* /svg segments *****************************************************
/*
* Base class for SVG endpoints.
*/
var SvgEndpoint = window.SvgEndpoint = function(params) {
var self = this,
_super = SvgComponent.apply(this, [ {
cssClass:params["_jsPlumb"].endpointClass,
originalArgs:arguments,
pointerEventsSpec:"all",
useDivWrapper:true,
_jsPlumb:params["_jsPlumb"]
} ]);
_super.renderer.paint = function(style) {
var s = jsPlumb.extend({}, style);
if (s.outlineColor) {
s.strokeWidth = s.outlineWidth;
s.strokeStyle = jsPlumbUtil.convertStyle(s.outlineColor, true);
}
if (self.node == null) {
self.node = self.makeNode(s);
self.svg.appendChild(self.node);
self.attachListeners(self.node, self);
}
else if (self.updateNode != null) {
self.updateNode(self.node);
}
_applyStyles(self.svg, self.node, s, [ self.x, self.y, self.w, self.h ], self);
_pos(self.node, [ self.x, self.y ]);
};
this.reattachListeners = function() {
if (self.node) self.reattachListenersForElement(self.node, self);
};
};
/*
* SVG Dot Endpoint
*/
jsPlumb.Endpoints.svg.Dot = function() {
jsPlumb.Endpoints.Dot.apply(this, arguments);
SvgEndpoint.apply(this, arguments);
this.makeNode = function(style) {
return _node("circle", {
"cx" : this.w / 2,
"cy" : this.h / 2,
"r" : this.radius
});
};
this.updateNode = function(node) {
_attr(node, {
"cx":this.w / 2,
"cy":this.h / 2,
"r":this.radius
});
};
};
/*
* SVG Rectangle Endpoint
*/
jsPlumb.Endpoints.svg.Rectangle = function() {
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
SvgEndpoint.apply(this, arguments);
this.makeNode = function(style) {
return _node("rect", {
"width" : this.w,
"height" : this.h
});
};
this.updateNode = function(node) {
_attr(node, {
"width":this.w,
"height":this.h
});
};
};
/*
* SVG Image Endpoint is the default image endpoint.
*/
jsPlumb.Endpoints.svg.Image = jsPlumb.Endpoints.Image;
/*
* Blank endpoint in svg renderer is the default Blank endpoint.
*/
jsPlumb.Endpoints.svg.Blank = jsPlumb.Endpoints.Blank;
/*
* Label overlay in svg renderer is the default Label overlay.
*/
jsPlumb.Overlays.svg.Label = jsPlumb.Overlays.Label;
/*
* Custom overlay in svg renderer is the default Custom overlay.
*/
jsPlumb.Overlays.svg.Custom = jsPlumb.Overlays.Custom;
var AbstractSvgArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
this.isAppendedAtTopLevel = false;
var self = this, path = null;
this.paint = function(params, containerExtents) {
// only draws on connections, not endpoints.
if (params.component.svg && containerExtents) {
if (path == null) {
path = _node("path", {
"pointer-events":"all"
});
params.component.svg.appendChild(path);
self.attachListeners(path, params.component);
self.attachListeners(path, self);
}
var clazz = originalArgs && (originalArgs.length == 1) ? (originalArgs[0].cssClass || "") : "",
offset = [0,0];
if (containerExtents.xmin < 0) offset[0] = -containerExtents.xmin;
if (containerExtents.ymin < 0) offset[1] = -containerExtents.ymin;
_attr(path, {
"d" : makePath(params.d),
"class" : clazz,
stroke : params.strokeStyle ? params.strokeStyle : null,
fill : params.fillStyle ? params.fillStyle : null,
transform : "translate(" + offset[0] + "," + offset[1] + ")"
});
}
};
var makePath = function(d) {
return "M" + d.hxy.x + "," + d.hxy.y +
" L" + d.tail[0].x + "," + d.tail[0].y +
" L" + d.cxy.x + "," + d.cxy.y +
" L" + d.tail[1].x + "," + d.tail[1].y +
" L" + d.hxy.x + "," + d.hxy.y;
};
this.reattachListeners = function() {
if (path) self.reattachListenersForElement(path, self);
};
this.cleanup = function() {
if (path != null) jsPlumb.CurrentLibrary.removeElement(path);
};
};
jsPlumb.Overlays.svg.Arrow = function() {
AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.svg.PlainArrow = function() {
AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.svg.Diamond = function() {
AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
// a test
jsPlumb.Overlays.svg.GuideLines = function() {
var path = null, self = this, p1_1, p1_2;
jsPlumb.Overlays.GuideLines.apply(this, arguments);
this.paint = function(params, containerExtents) {
if (path == null) {
path = _node("path");
params.connector.svg.appendChild(path);
self.attachListeners(path, params.connector);
self.attachListeners(path, self);
p1_1 = _node("path");
params.connector.svg.appendChild(p1_1);
self.attachListeners(p1_1, params.connector);
self.attachListeners(p1_1, self);
p1_2 = _node("path");
params.connector.svg.appendChild(p1_2);
self.attachListeners(p1_2, params.connector);
self.attachListeners(p1_2, self);
}
var offset =[0,0];
if (containerExtents.xmin < 0) offset[0] = -containerExtents.xmin;
if (containerExtents.ymin < 0) offset[1] = -containerExtents.ymin;
_attr(path, {
"d" : makePath(params.head, params.tail),
stroke : "red",
fill : null,
transform:"translate(" + offset[0] + "," + offset[1] + ")"
});
_attr(p1_1, {
"d" : makePath(params.tailLine[0], params.tailLine[1]),
stroke : "blue",
fill : null,
transform:"translate(" + offset[0] + "," + offset[1] + ")"
});
_attr(p1_2, {
"d" : makePath(params.headLine[0], params.headLine[1]),
stroke : "green",
fill : null,
transform:"translate(" + offset[0] + "," + offset[1] + ")"
});
};
var makePath = function(d1, d2) {
return "M " + d1.x + "," + d1.y +
" L" + d2.x + "," + d2.y;
};
};
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the VML renderers.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
// http://ajaxian.com/archives/the-vml-changes-in-ie-8
// http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/
// http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
var vmlAttributeMap = {
"stroke-linejoin":"joinstyle",
"joinstyle":"joinstyle",
"endcap":"endcap",
"miterlimit":"miterlimit"
},
jsPlumbStylesheet = null;
if (document.createStyleSheet && document.namespaces) {
var ruleClasses = [
".jsplumb_vml", "jsplumb\\:textbox", "jsplumb\\:oval", "jsplumb\\:rect",
"jsplumb\\:stroke", "jsplumb\\:shape", "jsplumb\\:group"
],
rule = "behavior:url(#default#VML);position:absolute;";
jsPlumbStylesheet = document.createStyleSheet();
for (var i = 0; i < ruleClasses.length; i++)
jsPlumbStylesheet.addRule(ruleClasses[i], rule);
// in this page it is also mentioned that IE requires the extra arg to the namespace
// http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
// but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either.
// var iev = document.documentMode;
//if (!iev || iev < 8)
document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml");
//else
// document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML");
}
jsPlumb.vml = {};
var scale = 1000,
_groupMap = {},
_getGroup = function(container, connectorClass) {
var id = jsPlumb.getId(container),
g = _groupMap[id];
if(!g) {
g = _node("group", [0,0,scale, scale], {"class":connectorClass});
//g.style.position=absolute;
//g["coordsize"] = "1000,1000";
g.style.backgroundColor="red";
_groupMap[id] = g;
jsPlumb.appendElement(g, container); // todo if this gets reinstated, remember to use the current jsplumb instance.
//document.body.appendChild(g);
}
return g;
},
_atts = function(o, atts) {
for (var i in atts) {
// IE8 fix: setattribute does not work after an element has been added to the dom!
// http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
//o.setAttribute(i, atts[i]);
/*There is an additional problem when accessing VML elements by using get/setAttribute. The simple solution is following:
if (document.documentMode==8) {
ele.opacity=1;
} else {
ele.setAttribute(‘opacity’,1);
}
*/
o[i] = atts[i];
}
},
_node = function(name, d, atts, parent, _jsPlumb, deferToJsPlumbContainer) {
atts = atts || {};
var o = document.createElement("jsplumb:" + name);
if (deferToJsPlumbContainer)
_jsPlumb.appendElement(o, parent);
else
jsPlumb.CurrentLibrary.appendElement(o, parent);
o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml";
_pos(o, d);
_atts(o, atts);
return o;
},
_pos = function(o,d, zIndex) {
o.style.left = d[0] + "px";
o.style.top = d[1] + "px";
o.style.width= d[2] + "px";
o.style.height= d[3] + "px";
o.style.position = "absolute";
if (zIndex)
o.style.zIndex = zIndex;
},
_conv = jsPlumb.vml.convertValue = function(v) {
return Math.floor(v * scale);
},
// tests if the given style is "transparent" and then sets the appropriate opacity node to 0 if so,
// or 1 if not. TODO in the future, support variable opacity.
_maybeSetOpacity = function(styleToWrite, styleToCheck, type, component) {
if ("transparent" === styleToCheck)
component.setOpacity(type, "0.0");
else
component.setOpacity(type, "1.0");
},
_applyStyles = function(node, style, component, _jsPlumb) {
var styleToWrite = {};
if (style.strokeStyle) {
styleToWrite["stroked"] = "true";
var strokeColor = jsPlumbUtil.convertStyle(style.strokeStyle, true);
styleToWrite["strokecolor"] = strokeColor;
_maybeSetOpacity(styleToWrite, strokeColor, "stroke", component);
styleToWrite["strokeweight"] = style.lineWidth + "px";
}
else styleToWrite["stroked"] = "false";
if (style.fillStyle) {
styleToWrite["filled"] = "true";
var fillColor = jsPlumbUtil.convertStyle(style.fillStyle, true);
styleToWrite["fillcolor"] = fillColor;
_maybeSetOpacity(styleToWrite, fillColor, "fill", component);
}
else styleToWrite["filled"] = "false";
if(style["dashstyle"]) {
if (component.strokeNode == null) {
component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] }, node, _jsPlumb);
}
else
component.strokeNode.dashstyle = style["dashstyle"];
}
else if (style["stroke-dasharray"] && style["lineWidth"]) {
var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",",
parts = style["stroke-dasharray"].split(sep),
styleToUse = "";
for(var i = 0; i < parts.length; i++) {
styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep);
}
if (component.strokeNode == null) {
component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse }, node, _jsPlumb);
}
else
component.strokeNode.dashstyle = styleToUse;
}
_atts(node, styleToWrite);
},
/*
* Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent.
*/
VmlComponent = function() {
var self = this, renderer = {};
jsPlumb.jsPlumbUIComponent.apply(this, arguments);
this.opacityNodes = {
"stroke":null,
"fill":null
};
this.initOpacityNodes = function(vml) {
self.opacityNodes["stroke"] = _node("stroke", [0,0,1,1], {opacity:"0.0"}, vml, self._jsPlumb);
self.opacityNodes["fill"] = _node("fill", [0,0,1,1], {opacity:"0.0"}, vml, self._jsPlumb);
};
this.setOpacity = function(type, value) {
var node = self.opacityNodes[type];
if (node) node["opacity"] = "" + value;
};
var displayElements = [ ];
this.getDisplayElements = function() {
return displayElements;
};
this.appendDisplayElement = function(el, doNotAppendToCanvas) {
if (!doNotAppendToCanvas) self.canvas.parentNode.appendChild(el);
displayElements.push(el);
};
},
/*
* Base class for Vml connectors. extends VmlComponent.
*/
VmlConnector = jsPlumb.ConnectorRenderers.vml = function(params) {
var self = this;
self.strokeNode = null;
self.canvas = null;
var _super = VmlComponent.apply(this, arguments);
var clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : "");
this.paint = function(style) {
if (style !== null) {
var segments = self.getSegments(), p = { "path":"" },
d = [self.x,self.y,self.w,self.h];
// create path from segments.
for (var i = 0; i < segments.length; i++) {
p.path += jsPlumb.Segments.vml.SegmentRenderer.getPath(segments[i]);
p.path += " ";
}
//*
if (style.outlineColor) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.lineWidth + (2 * outlineWidth),
outlineStyle = {
strokeStyle : jsPlumbUtil.convertStyle(style.outlineColor),
lineWidth : outlineStrokeWidth
};
for (var aa in vmlAttributeMap) outlineStyle[aa] = style[aa];
if (self.bgCanvas == null) {
p["class"] = clazz;
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
self.bgCanvas = _node("shape", d, p, params.parent, self._jsPlumb, true);
_pos(self.bgCanvas, d);
self.appendDisplayElement(self.bgCanvas, true);
self.attachListeners(self.bgCanvas, self);
self.initOpacityNodes(self.bgCanvas, ["stroke"]);
}
else {
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
_pos(self.bgCanvas, d);
_atts(self.bgCanvas, p);
}
_applyStyles(self.bgCanvas, outlineStyle, self);
}
//*/
if (self.canvas == null) {
p["class"] = clazz;
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
self.canvas = _node("shape", d, p, params.parent, self._jsPlumb, true);
//var group = _getGroup(params.parent); // test of append everything to a group
//group.appendChild(self.canvas); // sort of works but not exactly;
//params["_jsPlumb"].appendElement(self.canvas, params.parent); //before introduction of groups
self.appendDisplayElement(self.canvas, true);
self.attachListeners(self.canvas, self);
self.initOpacityNodes(self.canvas, ["stroke"]);
}
else {
p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
_pos(self.canvas, d);
_atts(self.canvas, p);
}
_applyStyles(self.canvas, style, self, self._jsPlumb);
}
};
this.reattachListeners = function() {
if (self.canvas) self.reattachListenersForElement(self.canvas, self);
};
},
/*
*
* Base class for Vml Endpoints. extends VmlComponent.
*
*/
VmlEndpoint = window.VmlEndpoint = function(params) {
VmlComponent.apply(this, arguments);
var vml = null, self = this, opacityStrokeNode = null, opacityFillNode = null;
self.canvas = document.createElement("div");
self.canvas.style["position"] = "absolute";
var clazz = self._jsPlumb.endpointClass + (params.cssClass ? (" " + params.cssClass) : "");
// TODO vml endpoint adds class to VML at constructor time. but the addClass method adds VML
// to the enclosing DIV. what to do? seems like it would be better to just target the div.
// HOWEVER...vml connection has no containing div. why not? it feels like it should.
//var group = _getGroup(params.parent);
//group.appendChild(self.canvas);
params["_jsPlumb"].appendElement(self.canvas, params.parent);
this.paint = function(style, anchor) {
var p = { };
jsPlumb.sizeCanvas(self.canvas, self.x, self.y, self.w, self.h);
if (vml == null) {
p["class"] = clazz;
vml = self.getVml([0,0, self.w, self.h], p, anchor, self.canvas, self._jsPlumb);
self.attachListeners(vml, self);
self.appendDisplayElement(vml, true);
self.appendDisplayElement(self.canvas, true);
self.initOpacityNodes(vml, ["fill"]);
}
else {
_pos(vml, [0,0, self.w, self.h]);
_atts(vml, p);
}
_applyStyles(vml, style, self);
};
this.reattachListeners = function() {
if (vml) self.reattachListenersForElement(vml, self);
};
};
// ******************************* vml segments *****************************************************
jsPlumb.Segments.vml = {
SegmentRenderer : {
getPath : function(segment) {
return ({
"Straight":function(segment) {
var d = segment.params;
return "m" + _conv(d.x1) + "," + _conv(d.y1) + " l" + _conv(d.x2) + "," + _conv(d.y2) + " e";
},
"Bezier":function(segment) {
var d = segment.params;
return "m" + _conv(d.x1) + "," + _conv(d.y1) +
" c" + _conv(d.cp1x) + "," + _conv(d.cp1y) + "," + _conv(d.cp2x) + "," + _conv(d.cp2y) + "," + _conv(d.x2) + "," + _conv(d.y2) + " e";
},
"Arc":function(segment) {
var d = segment.params,
xmin = Math.min(d.x1, d.x2),
xmax = Math.max(d.x1, d.x2),
ymin = Math.min(d.y1, d.y2),
ymax = Math.max(d.y1, d.y2),
sf = segment.anticlockwise ? 1 : 0,
pathType = (segment.anticlockwise ? "at " : "wa "),
makePosString = function() {
var xy = [
null,
[ function() { return [xmin, ymin ];}, function() { return [xmin - d.r, ymin - d.r ];}],
[ function() { return [xmin - d.r, ymin ];}, function() { return [xmin, ymin - d.r ];}],
[ function() { return [xmin - d.r, ymin - d.r ];}, function() { return [xmin, ymin ];}],
[ function() { return [xmin, ymin - d.r ];}, function() { return [xmin - d.r, ymin ];}]
][segment.segment][sf]();
return _conv(xy[0]) + "," + _conv(xy[1]) + "," + _conv(xy[0] + (2*d.r)) + "," + _conv(xy[1] + (2*d.r));
};
return pathType + makePosString() + "," + _conv(d.x1) + ","
+ _conv(d.y1) + "," + _conv(d.x2) + "," + _conv(d.y2) + " e";
}
})[segment.type](segment);
}
}
};
// ******************************* /vml segments *****************************************************
// ******************************* vml endpoints *****************************************************
jsPlumb.Endpoints.vml.Dot = function() {
jsPlumb.Endpoints.Dot.apply(this, arguments);
VmlEndpoint.apply(this, arguments);
this.getVml = function(d, atts, anchor, parent, _jsPlumb) { return _node("oval", d, atts, parent, _jsPlumb); };
};
jsPlumb.Endpoints.vml.Rectangle = function() {
jsPlumb.Endpoints.Rectangle.apply(this, arguments);
VmlEndpoint.apply(this, arguments);
this.getVml = function(d, atts, anchor, parent, _jsPlumb) { return _node("rect", d, atts, parent, _jsPlumb); };
};
/*
* VML Image Endpoint is the same as the default image endpoint.
*/
jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image;
/**
* placeholder for Blank endpoint in vml renderer.
*/
jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank;
// ******************************* /vml endpoints *****************************************************
// ******************************* vml overlays *****************************************************
/**
* VML Label renderer. uses the default label renderer (which adds an element to the DOM)
*/
jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label;
/**
* VML Custom renderer. uses the default Custom renderer (which adds an element to the DOM)
*/
jsPlumb.Overlays.vml.Custom = jsPlumb.Overlays.Custom;
/**
* Abstract VML arrow superclass
*/
var AbstractVmlArrowOverlay = function(superclass, originalArgs) {
superclass.apply(this, originalArgs);
VmlComponent.apply(this, originalArgs);
var self = this, path = null;
self.canvas = null;
self.isAppendedAtTopLevel = true;
var getPath = function(d) {
return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) +
" l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) +
" " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) +
" " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) +
" x e";
};
this.paint = function(params, containerExtents) {
var p = {}, d = params.d, connector = params.component;
if (params.strokeStyle) {
p["stroked"] = "true";
p["strokecolor"] = jsPlumbUtil.convertStyle(params.strokeStyle, true);
}
if (params.lineWidth) p["strokeweight"] = params.lineWidth + "px";
if (params.fillStyle) {
p["filled"] = "true";
p["fillcolor"] = params.fillStyle;
}
var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
w = Math.abs(xmax - xmin),
h = Math.abs(ymax - ymin),
dim = [xmin, ymin, w, h];
// for VML, we create overlays using shapes that have the same dimensions and
// coordsize as their connector - overlays calculate themselves relative to the
// connector (it's how it's been done since the original canvas implementation, because
// for canvas that makes sense).
p["path"] = getPath(d);
p["coordsize"] = (connector.w * scale) + "," + (connector.h * scale);
dim[0] = connector.x;
dim[1] = connector.y;
dim[2] = connector.w;
dim[3] = connector.h;
if (self.canvas == null) {
var overlayClass = connector._jsPlumb.overlayClass || "";
var clazz = originalArgs && (originalArgs.length == 1) ? (originalArgs[0].cssClass || "") : "";
p["class"] = clazz + " " + overlayClass;
self.canvas = _node("shape", dim, p, connector.canvas.parentNode, connector._jsPlumb, true);
connector.appendDisplayElement(self.canvas, true);
self.attachListeners(self.canvas, connector);
self.attachListeners(self.canvas, self);
}
else {
_pos(self.canvas, dim);
_atts(self.canvas, p);
}
};
this.reattachListeners = function() {
if (self.canvas) self.reattachListenersForElement(self.canvas, self);
};
this.cleanup = function() {
if (self.canvas != null) jsPlumb.CurrentLibrary.removeElement(self.canvas);
};
};
jsPlumb.Overlays.vml.Arrow = function() {
AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
};
jsPlumb.Overlays.vml.PlainArrow = function() {
AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
};
jsPlumb.Overlays.vml.Diamond = function() {
AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
};
// ******************************* /vml overlays *****************************************************
})();
\ No newline at end of file
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG or VML.
*
* This file contains the util functions
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
var pointHelper = function(p1, p2, fn) {
p1 = jsPlumbUtil.isArray(p1) ? p1 : [p1.x, p1.y];
p2 = jsPlumbUtil.isArray(p2) ? p2 : [p2.x, p2.y];
return fn(p1, p2);
};
jsPlumbUtil = {
isArray : function(a) {
return Object.prototype.toString.call(a) === "[object Array]";
},
isNumber : function(n) {
return Object.prototype.toString.call(n) === "[object Number]";
},
isString : function(s) {
return typeof s === "string";
},
isBoolean: function(s) {
return typeof s === "boolean";
},
isNull : function(s) { return s == null; },
isObject : function(o) {
return o == null ? false : Object.prototype.toString.call(o) === "[object Object]";
},
isDate : function(o) {
return Object.prototype.toString.call(o) === "[object Date]";
},
isFunction: function(o) {
return Object.prototype.toString.call(o) === "[object Function]";
},
clone : function(a) {
if (this.isString(a)) return "" + a;
else if (this.isBoolean(a)) return !!a;
else if (this.isDate(a)) return new Date(a.getTime());
else if (this.isFunction(a)) return a;
else if (this.isArray(a)) {
var b = [];
for (var i = 0; i < a.length; i++)
b.push(this.clone(a[i]));
return b;
}
else if (this.isObject(a)) {
var b = {};
for (var i in a)
b[i] = this.clone(a[i]);
return b;
}
else return a;
},
merge : function(a, b) {
var c = this.clone(a);
for (var i in b) {
if (c[i] == null || this.isString(b[i]) || this.isBoolean(b[i]))
c[i] = b[i];
else {
if (this.isArray(b[i])/* && this.isArray(c[i])*/) {
var ar = [];
// if c's object is also an array we can keep its values.
if (this.isArray(c[i])) ar.push.apply(ar, c[i]);
ar.push.apply(ar, b[i]);
c[i] = ar;
}
else if(this.isObject(b[i])) {
// overwite c's value with an object if it is not already one.
if (!this.isObject(c[i]))
c[i] = {};
for (var j in b[i])
c[i][j] = b[i][j];
}
}
}
return c;
},
copyValues:function(names, from, to) {
for (var i = 0; i < names.length; i++)
to[names[i]] = from[names[i]];
},
//
// chain a list of functions, supplied by [ object, method name, args ], and return on the first
// one that returns the failValue. if none return the failValue, return the successValue.
//
functionChain : function(successValue, failValue, fns) {
for (var i = 0; i < fns.length; i++) {
var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]);
if (o === failValue) {
return o;
}
}
return successValue;
},
// take the given model and expand out any parameters.
populate : function(model, values) {
// for a string, see if it has parameter matches, and if so, try to make the substitutions.
var getValue = function(fromString) {
var matches = fromString.match(/(\${.*?})/g);
if (matches != null) {
for (var i = 0; i < matches.length; i++) {
var val = values[matches[i].substring(2, matches[i].length - 1)];
if (val != null) {
fromString = fromString.replace(matches[i], val);
}
}
}
return fromString;
},
// process one entry.
_one = function(d) {
if (d != null) {
if (jsPlumbUtil.isString(d)) {
return getValue(d);
}
else if (jsPlumbUtil.isArray(d)) {
var r = [];
for (var i = 0; i < d.length; i++)
r.push(_one(d[i]));
return r;
}
else if (jsPlumbUtil.isObject(d)) {
var r = {};
for (var i in d) {
r[i] = _one(d[i]);
}
return r;
}
else {
return d;
}
}
};
return _one(model);
},
convertStyle : function(s, ignoreAlpha) {
// TODO: jsPlumb should support a separate 'opacity' style member.
if ("transparent" === s) return s;
var o = s,
pad = function(n) { return n.length == 1 ? "0" + n : n; },
hex = function(k) { return pad(Number(k).toString(16)); },
pattern = /(rgb[a]?\()(.*)(\))/;
if (s.match(pattern)) {
var parts = s.match(pattern)[2].split(",");
o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
if (!ignoreAlpha && parts.length == 4)
o = o + hex(parts[3]);
}
return o;
},
gradient : function(p1, p2) {
return pointHelper(p1, p2, function(_p1, _p2) {
if (_p2[0] == _p1[0])
return _p2[1] > _p1[1] ? Infinity : -Infinity;
else if (_p2[1] == _p1[1])
return _p2[0] > _p1[0] ? 0 : -0;
else
return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]);
});
},
normal : function(p1, p2) {
return -1 / this.gradient(p1, p2);
},
lineLength : function(p1, p2) {
return pointHelper(p1, p2, function(_p1, _p2) {
return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2));
});
},
segment : function(p1, p2) {
return pointHelper(p1, p2, function(_p1, _p2) {
if (_p2[0] > _p1[0]) {
return (_p2[1] > _p1[1]) ? 2 : 1;
}
else if (_p2[0] == _p1[0]) {
return _p2[1] > _p1[1] ? 2 : 1;
}
else {
return (_p2[1] > _p1[1]) ? 3 : 4;
}
});
},
theta : function(p1, p2) {
return pointHelper(p1, p2, function(_p1, _p2) {
var m = jsPlumbUtil.gradient(_p1, _p2),
t = Math.atan(m),
s = jsPlumbUtil.segment(_p1, _p2);
if ((s == 4 || s== 3)) t += Math.PI;
if (t < 0) t += (2 * Math.PI);
return t;
});
},
intersects : function(r1, r2) {
var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h;
return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) ||
( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) );
},
segmentMultipliers : [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
inverseSegmentMultipliers : [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
pointOnLine : function(fromPoint, toPoint, distance) {
var m = jsPlumbUtil.gradient(fromPoint, toPoint),
s = jsPlumbUtil.segment(fromPoint, toPoint),
segmentMultiplier = distance > 0 ? jsPlumbUtil.segmentMultipliers[s] : jsPlumbUtil.inverseSegmentMultipliers[s],
theta = Math.atan(m),
y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
return { x:fromPoint.x + x, y:fromPoint.y + y };
},
/**
* calculates a perpendicular to the line fromPoint->toPoint, that passes through toPoint and is 'length' long.
* @param fromPoint
* @param toPoint
* @param length
*/
perpendicularLineTo : function(fromPoint, toPoint, length) {
var m = jsPlumbUtil.gradient(fromPoint, toPoint),
theta2 = Math.atan(-1 / m),
y = length / 2 * Math.sin(theta2),
x = length / 2 * Math.cos(theta2);
return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
},
findWithFunction : function(a, f) {
if (a)
for (var i = 0; i < a.length; i++) if (f(a[i])) return i;
return -1;
},
clampToGrid : function(x, y, grid, dontClampX, dontClampY) {
var _gridClamp = function(n, g) {
var e = n % g,
f = Math.floor(n / g),
inc = e >= (g / 2) ? 1 : 0;
return (f + inc) * g;
};
return [
dontClampX || grid == null ? x : _gridClamp(x, grid[0]),
dontClampY || grid == null ? y : _gridClamp(y, grid[1])
];
},
indexOf : function(l, v) {
return jsPlumbUtil.findWithFunction(l, function(_v) { return _v == v; });
},
removeWithFunction : function(a, f) {
var idx = jsPlumbUtil.findWithFunction(a, f);
if (idx > -1) a.splice(idx, 1);
return idx != -1;
},
remove : function(l, v) {
var idx = jsPlumbUtil.indexOf(l, v);
if (idx > -1) l.splice(idx, 1);
return idx != -1;
},
// TODO support insert index
addWithFunction : function(list, item, hashFunction) {
if (jsPlumbUtil.findWithFunction(list, hashFunction) == -1) list.push(item);
},
addToList : function(map, key, value) {
var l = map[key];
if (l == null) {
l = [], map[key] = l;
}
l.push(value);
return l;
},
/**
* EventGenerator
* Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
*/
EventGenerator : function() {
var _listeners = {}, self = this, eventsSuspended = false;
// this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to
// jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
// listeners to bring down jsPlumb - or do we. i can't make up my mind about this, but i know i want to hear about it if the "ready"
// event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
// to hear what other people think.
var eventsToDieOn = [ "ready" ];
/*
* Binds a listener to an event.
*
* Parameters:
* event - name of the event to bind to.
* listener - function to execute.
*/
this.bind = function(event, listener) {
jsPlumbUtil.addToList(_listeners, event, listener);
return self;
};
/*
* Fires an update for the given event.
*
* Parameters:
* event - event to fire
* value - value to pass to the event listener(s).
* originalEvent - the original event from the browser
*/
this.fire = function(event, value, originalEvent) {
if (!eventsSuspended && _listeners[event]) {
for ( var i = 0; i < _listeners[event].length; i++) {
// doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
// method will have the whole call stack available in the debugger.
if (jsPlumbUtil.findWithFunction(eventsToDieOn, function(e) { return e === event}) != -1)
_listeners[event][i](value, originalEvent);
else {
// for events we don't want to die on, catch and log.
try {
_listeners[event][i](value, originalEvent);
} catch (e) {
jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e);
}
}
}
}
return self;
};
/*
* Clears either all listeners, or listeners for some specific event.
*
* Parameters:
* event - optional. constrains the clear to just listeners for this event.
*/
this.unbind = function(event) {
if (event)
delete _listeners[event];
else {
_listeners = {};
}
return self;
};
this.getListener = function(forEvent) {
return _listeners[forEvent];
};
this.setSuspendEvents = function(val) {
eventsSuspended = val;
};
this.isSuspendEvents = function() {
return eventsSuspended;
};
},
logEnabled : true,
log : function() {
if (jsPlumbUtil.logEnabled && typeof console != "undefined") {
try {
var msg = arguments[arguments.length - 1];
console.log(msg);
}
catch (e) {}
}
},
group : function(g) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.group(g); },
groupEnd : function(g) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.groupEnd(g); },
time : function(t) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.time(t); },
timeEnd : function(t) { if (jsPlumbUtil.logEnabled && typeof console != "undefined") console.timeEnd(t); },
/**
* helper to remove an element from the DOM.
*/
removeElement : function(element) {
if (element != null && element.parentNode != null) {
element.parentNode.removeChild(element);
}
},
/**
* helper to remove a list of elements from the DOM.
*/
removeElements : function(elements) {
for ( var i = 0; i < elements.length; i++)
jsPlumbUtil.removeElement(elements[i]);
}
};
})();
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the MooTools adapter.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
/*
* overrides the FX class to inject 'step' functionality, which MooTools does not
* offer, and which makes me sad. they don't seem keen to add it, either, despite
* the fact that it could be useful:
*
* https://mootools.lighthouseapp.com/projects/2706/tickets/668
*
*/
var jsPlumbMorph = new Class({
Extends:Fx.Morph,
onStep : null,
initialize : function(el, options) {
this.parent(el, options);
if (options['onStep']) {
this.onStep = options['onStep'];
}
},
step : function(now) {
this.parent(now);
if (this.onStep) {
try { this.onStep(); }
catch(e) { }
}
}
});
var _droppables = {},
_droppableOptions = {},
_draggablesByScope = {},
_draggablesById = {},
_droppableScopesById = {};
/*
*
*/
var _executeDroppableOption = function(el, dr, event, originalEvent) {
if (dr) {
var id = dr.get("id");
if (id) {
var options = _droppableOptions[id];
if (options) {
if (options[event]) {
options[event](el, dr, originalEvent);
}
}
}
}
};
var _checkHover = function(el, entering) {
if (el) {
var id = el.get("id");
if (id) {
var options = _droppableOptions[id];
if (options) {
if (options['hoverClass']) {
if (entering) el.addClass(options['hoverClass']);
else el.removeClass(options['hoverClass']);
}
}
}
}
};
/**
* adds the given value to the given list, with the given scope. creates the scoped list
* if necessary.
* used by initDraggable and initDroppable.
*/
var _add = function(list, _scope, value) {
var l = list[_scope];
if (!l) {
l = [];
list[_scope] = l;
}
l.push(value);
};
/*
* gets an "element object" from the given input. this means an object that is used by the
* underlying library on which jsPlumb is running. 'el' may already be one of these objects,
* in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
* function is used to find the element, using the given String as the element's id.
*/
var _getElementObject = function(el) {
return $(el);
};
jsPlumb.CurrentLibrary = {
/**
* adds the given class to the element object.
*/
addClass : function(el, clazz) {
el = jsPlumb.CurrentLibrary.getElementObject(el)
try {
if (el.className.constructor == SVGAnimatedString) {
jsPlumbUtil.svg.addClass(el, clazz);
}
else el.addClass(clazz);
}
catch (e) {
// SVGAnimatedString not supported; no problem.
el.addClass(clazz);
}
},
animate : function(el, properties, options) {
var m = new jsPlumbMorph(el, options);
m.start(properties);
},
appendElement : function(child, parent) {
_getElementObject(parent).grab(child);
},
bind : function(el, event, callback) {
el = _getElementObject(el);
el.addEvent(event, callback);
},
dragEvents : {
'start':'onStart', 'stop':'onComplete', 'drag':'onDrag', 'step':'onStep',
'over':'onEnter', 'out':'onLeave','drop':'onDrop', 'complete':'onComplete'
},
/*
* wrapper around the library's 'extend' functionality (which it hopefully has.
* otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
* instead. it's not like its hard.
*/
extend : function(o1, o2) {
return $extend(o1, o2);
},
/**
* gets the named attribute from the given element object.
*/
getAttribute : function(el, attName) {
return el.get(attName);
},
getClientXY : function(eventObject) {
return [eventObject.event.clientX, eventObject.event.clientY];
},
getDragObject : function(eventArgs) {
return eventArgs[0];
},
getDragScope : function(el) {
var id = jsPlumb.getId(el),
drags = _draggablesById[id];
return drags[0].scope;
},
getDropEvent : function(args) {
return args[2];
},
getDropScope : function(el) {
var id = jsPlumb.getId(el);
return _droppableScopesById[id];
},
getDOMElement : function(el) {
// MooTools just decorates the DOM elements. so we have either an ID or an Element here.
return typeof(el) == "String" ? document.getElementById(el) : el;
},
getElementObject : _getElementObject,
/*
gets the offset for the element object. this should return a js object like this:
{ left:xxx, top: xxx}
*/
getOffset : function(el) {
var p = el.getPosition();
return { left:p.x, top:p.y };
},
getOriginalEvent : function(e) {
return e.event;
},
getPageXY : function(eventObject) {
return [eventObject.event.pageX, eventObject.event.pageY];
},
getParent : function(el) {
return jsPlumb.CurrentLibrary.getElementObject(el).getParent();
},
getScrollLeft : function(el) {
return null;
},
getScrollTop : function(el) {
return null;
},
getSelector : function(context, spec) {
if (arguments.length == 2) {
return jsPlumb.CurrentLibrary.getElementObject(context).getElements(spec);
}
else
return $$(context);
},
getSize : function(el) {
var s = el.getSize();
return [s.x, s.y];
},
getTagName : function(el) {
var e = jsPlumb.CurrentLibrary.getElementObject(el);
return e != null ? e.tagName : null;
},
/*
* takes the args passed to an event function and returns you an object that gives the
* position of the object being moved, as a js object with the same params as the result of
* getOffset, ie: { left: xxx, top: xxx }.
*/
getUIPosition : function(eventArgs, zoom) {
var ui = eventArgs[0],
el = jsPlumb.CurrentLibrary.getElementObject(ui),
p = el.getPosition();
zoom = zoom || 1;
return { left:p.x / zoom, top:p.y / zoom};
},
hasClass : function(el, clazz) {
return el.hasClass(clazz);
},
initDraggable : function(el, options, isPlumbedComponent, _jsPlumb) {
var id = jsPlumb.getId(el);
var drag = _draggablesById[id];
if (!drag) {
var originalZIndex = 0,
originalCursor = null,
dragZIndex = jsPlumb.Defaults.DragOptions.zIndex || 2000;
options['onStart'] = jsPlumb.wrap(options['onStart'], function() {
originalZIndex = this.element.getStyle('z-index');
this.element.setStyle('z-index', dragZIndex);
drag.originalZIndex = originalZIndex;
if (jsPlumb.Defaults.DragOptions.cursor) {
originalCursor = this.element.getStyle('cursor');
this.element.setStyle('cursor', jsPlumb.Defaults.DragOptions.cursor);
}
});
options['onComplete'] = jsPlumb.wrap(options['onComplete'], function() {
this.element.setStyle('z-index', originalZIndex);
if (originalCursor) {
this.element.setStyle('cursor', originalCursor);
}
});
// DROPPABLES - only relevant if this is a plumbed component, ie. not just the result of the user making some DOM element
// draggable. this is the only library adapter that has to care about this parameter.
var scope = "" + (options["scope"] || jsPlumb.Defaults.Scope),
filterFunc = function(entry) {
return entry.get("id") != el.get("id");
},
droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
if (isPlumbedComponent) {
options['droppables'] = droppables;
options['onLeave'] = jsPlumb.wrap(options['onLeave'], function(el, dr) {
if (dr) {
_checkHover(dr, false);
_executeDroppableOption(el, dr, 'onLeave');
}
});
options['onEnter'] = jsPlumb.wrap(options['onEnter'], function(el, dr) {
if (dr) {
_checkHover(dr, true);
_executeDroppableOption(el, dr, 'onEnter');
}
});
options['onDrop'] = function(el, dr, event) {
if (dr) {
_checkHover(dr, false);
_executeDroppableOption(el, dr, 'onDrop', event);
}
};
}
else
options["droppables"] = [];
drag = new Drag.Move(el, options);
drag.scope = scope;
drag.originalZIndex = originalZIndex;
_add(_draggablesById, el.get("id"), drag);
// again, only keep a record of this for scope stuff if this is a plumbed component (an endpoint)
if (isPlumbedComponent) {
_add(_draggablesByScope, scope, drag);
}
// test for disabled.
if (options.disabled) drag.detach();
}
return drag;
},
initDroppable : function(el, options, isPlumbedComponent, isPermanent) {
var scope = options["scope"];
_add(_droppables, scope, el);
var id = jsPlumb.getId(el);
el.setAttribute("_isPermanentDroppable", isPermanent); // we use this to clear out droppables on drag complete.
_droppableOptions[id] = options;
_droppableScopesById[id] = scope;
var filterFunc = function(entry) { return entry.element != el; },
draggables = _draggablesByScope[scope] ? _draggablesByScope[scope].filter(filterFunc) : [];
for (var i = 0; i < draggables.length; i++) {
draggables[i].droppables.push(el);
}
},
isAlreadyDraggable : function(el) {
return _draggablesById[jsPlumb.getId(el)] != null;
},
isDragSupported : function(el, options) {
return typeof Drag != 'undefined' ;
},
/*
* you need Drag.Move imported to make drop work.
*/
isDropSupported : function(el, options) {
return (typeof Drag != undefined && typeof Drag.Move != undefined);
},
/**
* removes the given class from the element object.
*/
removeClass : function(el, clazz) {
el = jsPlumb.CurrentLibrary.getElementObject(el);
try {
if (el.className.constructor == SVGAnimatedString) {
jsPlumbUtil.svg.removeClass(el, clazz);
}
else el.removeClass(clazz);
}
catch (e) {
// SVGAnimatedString not supported; no problem.
el.removeClass(clazz);
}
},
removeElement : function(element, parent) {
var el = _getElementObject(element);
if (el) el.dispose(); // ??
},
/**
* sets the named attribute on the given element object.
*/
setAttribute : function(el, attName, attValue) {
el.set(attName, attValue);
},
setDragFilter : function(el, filter) {
jsPlumb.log("NOT IMPLEMENTED: setDragFilter")
},
setDraggable : function(el, draggable) {
var draggables = _draggablesById[el.get("id")];
if (draggables) {
draggables.each(function(d) {
if (draggable) d.attach(); else d.detach();
});
}
},
setDragScope : function(el, scope) {
var drag = _draggablesById[el.get("id")];
var filterFunc = function(entry) {
return entry.get("id") != el.get("id");
};
var droppables = _droppables[scope] ? _droppables[scope].filter(filterFunc) : [];
drag[0].droppables = droppables;
},
setOffset : function(el, o) {
_getElementObject(el).setPosition({x:o.left, y:o.top});
},
stopDrag : function() {
for (var i in _draggablesById) {
for (var j = 0; j < _draggablesById[i].length; j++) {
var d = _draggablesById[i][j];
d.stop();
if (d.originalZIndex != 0)
d.element.setStyle("z-index", d.originalZIndex);
}
}
},
/**
* note that jquery ignores the name of the event you wanted to trigger, and figures it out for itself.
* the other libraries do not. yui, in fact, cannot even pass an original event. we have to pull out stuff
* from the originalEvent to put in an options object for YUI.
* @param el
* @param event
* @param originalEvent
*/
trigger : function(el, event, originalEvent) {
originalEvent.stopPropagation();
_getElementObject(el).fireEvent(event, originalEvent);
},
unbind : function(el, event, callback) {
el = _getElementObject(el);
el.removeEvent(event, callback);
}
};
window.addEvent('domready', jsPlumb.init);
})();
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the YUI3 adapter.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
/**
* addClass adds a class to the given element
* animate calls the underlying library's animate functionality
* appendElement appends a child element to a parent element.
* bind binds some event to an element
* dragEvents a dictionary of event names
* extend extend some js object with another. probably not overly necessary; jsPlumb could just do this internally.
* getAttribute gets some attribute from an element
* getDragObject gets the object that is being dragged, by extracting it from the arguments passed to a drag callback
* getDragScope gets the drag scope for a given element.
* getElementObject turns an id or dom element into an element object of the underlying library's type.
* getOffset gets an element's offset
* getOriginalEvent gets the original browser event from some wrapper event.
* getScrollLeft gets an element's scroll left. TODO: is this actually used? will it be?
* getScrollTop gets an element's scroll top. TODO: is this actually used? will it be?
* getSize gets an element's size.
* getUIPosition gets the position of some element that is currently being dragged, by extracting it from the arguments passed to a drag callback.
* initDraggable initializes an element to be draggable
* initDroppable initializes an element to be droppable
* isDragSupported returns whether or not drag is supported for some element.
* isDropSupported returns whether or not drop is supported for some element.
* removeClass removes a class from a given element.
* removeElement removes some element completely from the DOM.
* setAttribute sets an attribute on some element.
* setDraggable sets whether or not some element should be draggable.
* setDragScope sets the drag scope for a given element.
* setOffset sets the offset of some element.
*/
(function() {
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function( v, b, s ) {
for( var i = +b || 0, l = this.length; i < l; i++ ) {
if( this[i]===v || s && this[i]==v ) { return i; }
}
return -1;
};
}
var Y;
YUI().use('node', 'dd', 'dd-constrain', 'anim', 'node-event-simulate', function(_Y) {
Y = _Y;
Y.on("domready", function() { jsPlumb.init(); });
});
/**
* adds the given value to the given list, with the given scope. creates the scoped list
* if necessary.
* used by initDraggable and initDroppable.
*/
var _add = function(list, scope, value) {
var l = list[scope];
if (!l) {
l = [];
list[scope] = l;
}
l.push(value);
},
ddEvents = [ "drag:mouseDown", "drag:afterMouseDown", "drag:mouseup",
"drag:align", "drag:removeHandle", "drag:addHandle", "drag:removeInvalid", "drag:addInvalid",
"drag:start", "drag:end", "drag:drag", "drag:over", "drag:enter",
"drag:exit", "drag:drophit", "drag:dropmiss", "drop:over", "drop:enter", "drop:exit", "drop:hit"
],
animEvents = [ "tween" ],
/**
* helper function to curry callbacks for some element.
*/
_wrapper = function(fn) {
return function() {
try {
return fn.apply(this, arguments);
}
catch (e) { }
};
},
/**
* extracts options from the given options object, leaving out event handlers.
*/
_getDDOptions = function(options) {
var o = {};
for (var i in options) if (ddEvents.indexOf(i) == -1) o[i] = options[i];
return o;
},
/**
* attaches all event handlers found in options to the given dragdrop object, and registering
* the given el as the element of interest.
*/
_attachListeners = function(dd, options, eventList) {
for (var ev in options) {
if (eventList.indexOf(ev) != -1) {
var w = _wrapper(options[ev]);
dd.on(ev, w);
}
}
},
_droppables = {},
_droppableOptions = {},
_draggablesByScope = {},
_draggablesById = {},
_droppableScopesById = {},
_checkHover = function(el, entering) {
if (el) {
var id = el.get("id");
if (id) {
var options = _droppableOptions[id];
if (options) {
if (options['hoverClass']) {
if (entering) el.addClass(options['hoverClass']);
else el.removeClass(options['hoverClass']);
}
}
}
}
},
_lastDragObject = null,
_extend = function(o1, o2) {
for (var i in o2)
o1[i] = o2[i];
return o1;
},
_getAttribute = function(el, attributeId) {
return el.getAttribute(attributeId);
},
_getElementObject = function(el) {
if (el == null) return null;
var eee = null;
eee = typeof el == 'string' ? Y.one('#' + el) : el._node ? el : Y.one(el);
return eee;
};
jsPlumb.CurrentLibrary = {
addClass : function(el, clazz) {
jsPlumb.CurrentLibrary.getElementObject(el).addClass(clazz);
},
/**
* animates the given element.
*/
animate : function(el, properties, options) {
var o = _extend({node:el, to:properties}, options),
id = _getAttribute(el, "id");
o["tween"] = jsPlumb.wrap(properties["tween"], function() {
// TODO should use a current instance.
jsPlumb.repaint(id);
});
var a = new Y.Anim(o);
_attachListeners(a, o, animEvents);
a.run();
},
appendElement : function(child, parent) {
_getElementObject (parent).append(child);
},
/**
* event binding wrapper.
*/
bind : function(el, event, callback) {
_getElementObject(el).on(event, callback);
},
dragEvents : {
"start":"drag:start", "stop":"drag:end", "drag":"drag:drag", "step":"step",
"over":"drop:enter", "out":"drop:exit", "drop":"drop:hit"
},
extend : _extend,
getAttribute : _getAttribute,
getClientXY : function(eventObject) {
return [eventObject.clientX, eventObject.clientY];
},
/**
* takes the args passed to an event function and returns you an object representing that which is being dragged.
*/
getDragObject : function(eventArgs) {
// this is a workaround for the unfortunate fact that in YUI3, the 'drop:exit' event does
// not contain a reference to the drag that just exited. single-threaded js to the
// rescue: we'll just keep it for ourselves.
if (eventArgs[0].drag) _lastDragObject = eventArgs[0].drag.el;
return _lastDragObject;
},
getDragScope : function(el) {
var id = jsPlumb.getId(el),
dd = _draggablesById[id];
return dd.scope;
},
getDropEvent : function(args) {
return args[0];
},
getDropScope : function(el) {
var id = jsPlumb.getId(el);
return _droppableScopesById[id];
},
getDOMElement : function(el) {
if (typeof(el) == "String")
return document.getElementById(el);
else if (el._node)
return el._node;
else return el;
},
getElementObject : _getElementObject,
getOffset : function(el) {
var o = Y.DOM.getXY(el._node);
return {left:o[0], top:o[1]};
},
getOriginalEvent : function(e) {
return e._event;
},
getPageXY : function(eventObject) {
return [eventObject.pageX, eventObject.pageY];
},
getParent : function(el) {
return jsPlumb.CurrentLibrary.getElementObject(el).get("parentNode");
},
getScrollLeft : function(el) {
return 0;
},
getScrollTop : function(el) {
return 0;
},
getSelector : function(context, spec) {
var _convert = function(s) { return s && s ._nodes ? s._nodes : []; };
if (arguments.length == 2) {
return _convert(jsPlumb.CurrentLibrary.getElementObject(context).all(spec));
}
else {
return _convert(Y.all(context));
}
},
getSize : function(el) {
return [ el._node.offsetWidth, el._node.offsetHeight ];
},
getTagName : function(el) {
var e = jsPlumb.CurrentLibrary.getElementObject(el);
return e != null && e._node != null ? e._node.tagName : null;
},
getUIPosition : function(args, zoom) {
zoom = zoom || 1;
var n = args[0].currentTarget.el._node,
o = Y.DOM.getXY(n);
return {left:o[0] / zoom, top:o[1] / zoom};
},
hasClass : function(el, clazz) {
return el.hasClass(clazz);
},
initDraggable : function(el, options, isPlumbedComponent, _jsPlumb) {
var _opts = _getDDOptions(options),
id = _jsPlumb.getId(el);
_opts.node = "#" + id;
var dd = new Y.DD.Drag(_opts),
containment = options.constrain2node || options.containment;
dd.el = el;
if (containment) {
dd.plug(Y.Plugin.DDConstrained, {
constrain2node: containment
});
}
if (isPlumbedComponent) {
var scope = options['scope'] || _jsPlumb.Defaults.Scope;
dd.scope = scope;
_add(_draggablesByScope, scope, dd);
}
_draggablesById[id] = dd;
_attachListeners(dd, options, ddEvents);
},
initDroppable : function(el, options) {
var _opts = _getDDOptions(options),
id = jsPlumb.getId(el);
_opts.node = "#" + id;
var dd = new Y.DD.Drop(_opts);
_droppableOptions[id] = options;
options = _extend({}, options);
var scope = options['scope'] || jsPlumb.Defaults.Scope;
_droppableScopesById[id] = scope;
options["drop:enter"] = jsPlumb.wrap(options["drop:enter"], function(e) {
if (e.drag.scope !== scope) return true;
_checkHover(el, true);
}, true);
options["drop:exit"] = jsPlumb.wrap(options["drop:exit"], function(e) {
_checkHover(el, false);
});
options["drop:hit"] = jsPlumb.wrap(options["drop:hit"], function(e) {
if (e.drag.scope !== scope) return true;
_checkHover(el, false);
}, true);
_attachListeners(dd, options, ddEvents);
},
isAlreadyDraggable : function(el) {
el = _getElementObject(el);
return el.hasClass("yui3-dd-draggable");
},
isDragSupported : function(el) { return true; },
isDropSupported : function(el) { return true; },
removeClass : function(el, clazz) {
jsPlumb.CurrentLibrary.getElementObject(el).removeClass(clazz);
},
removeElement : function(el) { _getElementObject(el).remove(); },
setAttribute : function(el, attributeName, attributeValue) {
el.setAttribute(attributeName, attributeValue);
},
setDragFilter : function(el, filter) {
jsPlumb.log("NOT IMPLEMENTED: setDragFilter")
},
/**
* sets the draggable state for the given element
*/
setDraggable : function(el, draggable) {
var id = jsPlumb.getId(el),
dd = _draggablesById[id];
if (dd) dd.set("lock", !draggable);
},
setDragScope : function(el, scope) {
var id = jsPlumb.getId(el),
dd = _draggablesById[id];
if (dd) dd.scope = scope;
},
setOffset : function(el, o) {
el = _getElementObject(el);
el.set("top", o.top);
el.set("left", o.left);
},
stopDrag : function() {
Y.DD.DDM.stopDrag();
},
trigger : function(el, event, originalEvent) {
originalEvent.stopPropagation();
_getElementObject(el).simulate(event, {
pageX:originalEvent.pageX,
pageY:originalEvent.pageY,
clientX:originalEvent.clientX,
clientY:originalEvent.clientY
});
},
/**
* event unbinding wrapper.
*/
unbind : function(el, event, callback) {
_getElementObject(el).detach(event, callback);
}
};
})();
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment