jquery.jsPlumb-1.1.1-RC1.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. /*
  2. * jsPlumb 1.1.1-RC1
  3. *
  4. * Provides a way to visually connect elements on an HTML page.
  5. *
  6. * 1.1.1 contains bugfixes and API additions on 1.1.0.
  7. *
  8. *
  9. * http://morrisonpitt.com/jsPlumb/demo.html
  10. * http://code.google.com/p/jsPlumb
  11. *
  12. */
  13. (function() {
  14. var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
  15. var log = null;
  16. var repaintFunction = function() { jsPlumb.repaintEverything(); };
  17. var automaticRepaint = true;
  18. function repaintEverything() {
  19. if (automaticRepaint)
  20. repaintFunction();
  21. };
  22. var resizeTimer = null;
  23. /*TODO: abstract this out from jQuery too! but how...because jsPlumb is not loaded yet.
  24. $(window).bind('resize', function() {
  25. if (resizeTimer) clearTimeout(resizeTimer);
  26. resizeTimer = setTimeout(repaintEverything, 100);
  27. });*/
  28. /**
  29. * map of element id -> endpoint lists. an element can have an arbitrary number of endpoints on it,
  30. * and not all of them have to be connected to anything.
  31. */
  32. var endpointsByElement = {};
  33. var offsets = [];
  34. var floatingConnections = {};
  35. var draggableStates = {};
  36. var _draggableByDefault = true;
  37. var sizes = [];
  38. var DEFAULT_NEW_CANVAS_SIZE = 1200; // only used for IE; a canvas needs a size before the init call to excanvas (for some reason. no idea why.)
  39. var _findIndex = function( a, v, b, s ) {
  40. var _eq = function(o1, o2) {
  41. if (o1 === o2) return true;
  42. else if (typeof o1 == 'object' && typeof o2 == 'object') {
  43. var same = true;
  44. for(var propertyName in o1) {
  45. if(!_eq(o1[propertyName], o2[propertyName])) {
  46. same = false;
  47. break;
  48. }
  49. }
  50. for(var propertyName in o2) {
  51. if(!_eq(o2[propertyName], o1[propertyName])) {
  52. same = false;
  53. break;
  54. }
  55. }
  56. return same;
  57. }
  58. };
  59. for( var i = +b || 0, l = a.length; i < l; i++ ) {
  60. if( _eq(a[i], v)) return i;
  61. }
  62. return -1;
  63. };
  64. /**
  65. * helper method to add an item to a list, creating the list if it does not yet exist.
  66. */
  67. var _addToList = function(map, key, value) {
  68. var l = map[key];
  69. if (l == null) {
  70. l = [];
  71. map[key] = l;
  72. }
  73. l.push(value);
  74. };
  75. /**
  76. * Handles the dragging of an element.
  77. * @param element jQuery element
  78. * @param ui UI object from current library's event system
  79. */
  80. var _draw = function(element, ui) {
  81. var id = _getAttribute(element, "id");
  82. var endpoints = endpointsByElement[id];
  83. if (endpoints) {
  84. _updateOffset(id, ui);
  85. var myOffset = offsets[id];
  86. var myWH = sizes[id];
  87. // loop through endpoints for this element
  88. for (var i = 0; i < endpoints.length; i++) {
  89. var e = endpoints[i];
  90. var anchorLoc = endpoints[i].anchor.compute([myOffset.left, myOffset.top], myWH);
  91. e.paint(anchorLoc);
  92. var l = e.connections;
  93. for (var j = 0; j < l.length; j++)
  94. l[j].paint(id, ui); // ...and paint them.
  95. }
  96. }
  97. };
  98. /**
  99. * helper function: the second argument is a function taking two args - the first is a
  100. * jquery element, and the second is the element's id.
  101. *
  102. * the first argument may be one of three things:
  103. *
  104. * 1. a string, in the form "window1", for example. an element's id. if your id starts with a
  105. * hash then jsPlumb does not append its own hash too...
  106. * 2. a jquery element, already resolved using $(...).
  107. * 3. a list of strings/jquery elements.
  108. */
  109. var _elementProxy = function(element, fn) {
  110. var retVal = null;
  111. if (typeof element == 'object' && element.length) {
  112. retVal = [];
  113. for (var i = 0; i < element.length; i++) {
  114. var el = _getElementObject(element[i]);
  115. var id = _getAttribute(el, "id");
  116. retVal.push(fn(el, id)); // append return values to what we will return
  117. }
  118. }
  119. else {
  120. var el = _getElementObject(element);
  121. var id = _getAttribute(el, "id");
  122. retVal = fn(el, id);
  123. }
  124. return retVal;
  125. };
  126. /**
  127. * gets the named attribute from the given element (id or element object)
  128. */
  129. var _getAttribute = function(el, attName) {
  130. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  131. return jsPlumb.CurrentLibrary.getAttribute(ele, attName);
  132. };
  133. var _setAttribute = function(el, attName, attValue) {
  134. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  135. jsPlumb.CurrentLibrary.setAttribute(ele, attName, attValue);
  136. };
  137. var _addClass = function(el, clazz) {
  138. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  139. jsPlumb.CurrentLibrary.addClass(ele, clazz);
  140. };
  141. var _getElementObject = function(elId) {
  142. return jsPlumb.CurrentLibrary.getElementObject(elId);
  143. };
  144. var _getOffset = function(el) {
  145. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  146. return jsPlumb.CurrentLibrary.getOffset(ele);
  147. };
  148. var _getSize = function(el) {
  149. var ele = jsPlumb.CurrentLibrary.getElementObject(el);
  150. return jsPlumb.CurrentLibrary.getSize(ele);
  151. };
  152. var _initDraggable = function(el, options) {
  153. return jsPlumb.CurrentLibrary.initDraggable(el, options);
  154. };
  155. var _isDragSupported = function(el) {
  156. return jsPlumb.CurrentLibrary.isDragSupported(el);
  157. };
  158. var _initDroppable = function(el, options) {
  159. return jsPlumb.CurrentLibrary.initDroppable(el, options);
  160. };
  161. var _isDropSupported = function(el) {
  162. return jsPlumb.CurrentLibrary.isDropSupported(el);
  163. };
  164. var _animate= function(el, properties, options) {
  165. return jsPlumb.CurrentLibrary.animate(el, properties, options);
  166. };
  167. var _appendCanvas = function(canvas) {
  168. document.body.appendChild(canvas);
  169. };
  170. /**
  171. * gets an id for the given element, creating and setting one if necessary.
  172. */
  173. var _getId = function(element) {
  174. var id = _getAttribute(element, "id");
  175. if (!id) {
  176. id = "_jsPlumb_" + new String((new Date()).getTime());
  177. _setAttribute(element, "id", id);
  178. }
  179. return id;
  180. };
  181. /**
  182. * inits a draggable if it's not already initialised.
  183. * todo: if the element was draggable already, like from some non-jsPlumb call, wrap the drag function.
  184. */
  185. var _initDraggableIfNecessary = function(element, elementId, isDraggable, dragOptions) {
  186. // dragging
  187. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  188. if (draggable && _isDragSupported(element)) {
  189. var options = dragOptions || jsPlumb.Defaults.DragOptions;
  190. options = jsPlumb.extend({}, options); // make a copy.
  191. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  192. var initDrag = function(element, elementId, dragFunc) {
  193. options[dragEvent] = _wrap(options[dragEvent], dragFunc);
  194. var draggable = draggableStates[elementId];
  195. options.disabled = draggable == null ? false : !draggable;
  196. _initDraggable(element, options);
  197. };
  198. initDrag(element, elementId, function() {
  199. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  200. _draw(element, ui);
  201. _addClass(element, "jsPlumb_dragged");
  202. });
  203. }
  204. };
  205. var _log = function(msg) {
  206. // not implemented. yet.
  207. }
  208. /**
  209. * helper to create a canvas.
  210. * @param clazz optional class name for the canvas.
  211. */
  212. var _newCanvas = function(clazz) {
  213. var canvas = document.createElement("canvas");
  214. _appendCanvas(canvas);
  215. canvas.style.position="absolute";
  216. if (clazz) { canvas.className=clazz; }
  217. _getId(canvas); // set an id.
  218. if (ie) {
  219. // for IE we have to set a big canvas size. actually you can override this, too, if 1200 pixels
  220. // is not big enough for the biggest connector/endpoint canvas you have at startup.
  221. jsPlumb.sizeCanvas(canvas, 0, 0, DEFAULT_NEW_CANVAS_SIZE, DEFAULT_NEW_CANVAS_SIZE);
  222. canvas = G_vmlCanvasManager.initElement(canvas);
  223. }
  224. return canvas;
  225. };
  226. /**
  227. * performs the given function operation on all the connections found for the given element
  228. * id; this means we find all the endpoints for the given element, and then for each endpoint
  229. * find the connectors connected to it. then we pass each connection in to the given
  230. * function.
  231. */
  232. var _operation = function(elId, func) {
  233. var endpoints = endpointsByElement[elId];
  234. if (endpoints && endpoints.length) {
  235. for (var i = 0; i < endpoints.length; i++) {
  236. for (var j = 0; j < endpoints[i].connections.length; j++) {
  237. var retVal = func(endpoints[i].connections[j]);
  238. // if the function passed in returns true, we exit.
  239. // most functions return false.
  240. if (retVal) return;
  241. }
  242. }
  243. }
  244. };
  245. /**
  246. * perform an operation on all elements.
  247. */
  248. var _operationOnAll = function(func) {
  249. for (var elId in endpointsByElement) {
  250. _operation(elId, func);
  251. }
  252. };
  253. /**
  254. * helper to remove an element from the DOM.
  255. */
  256. var _removeElement = function(element) {
  257. if (element != null) {
  258. try { document.body.removeChild(element); }
  259. catch (e) { }
  260. }
  261. };
  262. /**
  263. * helper to remove a list of elements from the DOM.
  264. */
  265. var _removeElements = function(elements) {
  266. for (var i in elements)
  267. _removeElement(elements[i]);
  268. };
  269. /**
  270. * helper method to remove an item from a list.
  271. */
  272. var _removeFromList = function(map, key, value) {
  273. var l = map[key];
  274. if (l != null) {
  275. var i = _findIndex(l, value);
  276. if (i >= 0) {
  277. delete( l[i] );
  278. l.splice( i, 1 );
  279. return true;
  280. }
  281. }
  282. return false;
  283. };
  284. /**
  285. * Sets whether or not the given element(s) should be draggable, regardless of what a particular
  286. * plumb command may request.
  287. *
  288. * @param element May be a string, a jQuery elements, or a list of strings/jquery elements.
  289. * @param draggable Whether or not the given element(s) should be draggable.
  290. */
  291. var _setDraggable = function(element, draggable) {
  292. var _helper = function(el, id) {
  293. draggableStates[id] = draggable;
  294. if (_isDragSupported(el)) {
  295. // TODO: not library agnostic yet.
  296. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  297. //el.draggable("option", "disabled", !draggable);
  298. }
  299. };
  300. return _elementProxy(element, _helper);
  301. };
  302. /**
  303. * private method to do the business of hiding/showing.
  304. * @param el either Id of the element in question or a jquery object for the element.
  305. * @param state String specifying a value for the css 'display' property ('block' or 'none').
  306. */
  307. var _setVisible = function(el, state) {
  308. var elId = _getAttribute(el, "id");
  309. var f = function(jpc) {
  310. jpc.canvas.style.display = state;
  311. };
  312. _operation(elId, f);
  313. };
  314. /**
  315. * toggles the draggable state of the given element(s).
  316. * @param el either an id, or a jquery object, or a list of ids/jquery objects.
  317. */
  318. var _toggleDraggable = function(el) {
  319. var fn = function(el, elId) {
  320. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  321. state = !state;
  322. draggableStates[elId] = state;
  323. //el.draggable("option", "disabled", !state);
  324. jsPlumb.CurrentLibrary.setDraggable(el, state);
  325. return state;
  326. };
  327. return _elementProxy(el, fn);
  328. };
  329. /**
  330. * private method to do the business of toggling hiding/showing.
  331. * @param elId Id of the element in question
  332. */
  333. var _toggleVisible = function(elId) {
  334. var f = function(jpc) {
  335. var state = ('none' == jpc.canvas.style.display);
  336. jpc.canvas.style.display = state ? "block" : "none";
  337. };
  338. _operation(elId, f);
  339. //todo this should call _elementProxy, and pass in the _operation(elId, f) call as a function. cos _toggleDraggable does that.
  340. };
  341. /**
  342. * updates the offset and size for a given element, and stores the values.
  343. * if 'offset' is not null we use that (it would have been passed in from a drag call) because it's faster; but if it is null,
  344. * or if 'recalc' is true in order to force a recalculation, we use the offset, outerWidth and outerHeight methods to get
  345. * the current values.
  346. */
  347. var _updateOffset = function(elId, offset, recalc) {
  348. if (recalc || offset == null) { // if forced repaint or no offset available, we recalculate.
  349. // get the current size and offset, and store them
  350. var s = _getElementObject(elId);
  351. sizes[elId] = _getSize(elId);
  352. offsets[elId] = _getOffset(elId);
  353. } else {
  354. offsets[elId] = offset;
  355. }
  356. };
  357. /**
  358. * wraps one function with another, creating a placeholder for the wrapped function
  359. * if it was null. this is used to wrap the various drag/drop event functions - to allow
  360. * jsPlumb to be notified of important lifecycle events without imposing itself on the user's
  361. * drap/drop functionality.
  362. * TODO: determine whether or not we should try/catch the plumb function, so that the cascade function is always executed.
  363. */
  364. var _wrap = function(cascadeFunction, plumbFunction) {
  365. cascadeFunction = cascadeFunction || function() { };
  366. return function() {
  367. plumbFunction.apply(this, arguments);
  368. cascadeFunction.apply(this, arguments);
  369. };
  370. }
  371. /*
  372. Class: Anchor
  373. Models a position relative to the origin of some element that an Endpoint can be located.
  374. */
  375. /*
  376. Function: Anchor
  377. Constructor for the Anchor class
  378. Parameters:
  379. params - Anchor parameters. This should contain three values, and may optionally have an 'offsets' argument:
  380. - x : the x location of the anchor as a fraction of the total width.
  381. - y : the y location of the anchor as a fraction of the total height.
  382. - orientation : an [x,y] array indicating the general direction a connection from the anchor should go in. for more info on this, see the documentation, or the docs in jquery-jsPlumb-defaults-XXX.js for the default Anchors.
  383. - offsets : an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out. may be null.
  384. */
  385. var Anchor = function(params) {
  386. var self = this;
  387. this.x = params.x || 0; this.y = params.y || 0;
  388. var orientation = params.orientation || [0,0];
  389. this.offsets = params.offsets || [0,0];
  390. this.compute = function(xy, wh, txy, twh) {
  391. return [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  392. }
  393. this.getOrientation = function() { return orientation; };
  394. };
  395. /**
  396. * An Anchor that floats. its orientation is computed dynamically from its position relative to the anchor it is floating relative to.
  397. *
  398. */
  399. var FloatingAnchor = function(params) {
  400. // this is the anchor that this floating anchor is referenced to for purposes of calculating the orientation.
  401. var ref = params.reference;
  402. // these are used to store the current relative position of our anchor wrt the reference anchor. they only indicate
  403. // direction, so have a value of 1 or -1 (or, very rarely, 0). these values are written by the compute method, and read
  404. // by the getOrientation method.
  405. var xDir = 0, yDir = 0;
  406. // temporary member used to store an orientation when the floating anchor is hovering over another anchor.
  407. var orientation = null;
  408. this.compute = function(xy, wh, txy, twh) {
  409. // set these for the getOrientation method to use.
  410. xDir = 0;//xy[0] < txy[0] ? -1 : xy[0] == txy[0] ? 0 : 1;
  411. yDir = 0;//xy[1] < txy[1] ? -1 : xy[1] == txy[1] ? 0 : 1;
  412. return [xy[0], xy[1]]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
  413. };
  414. this.getOrientation = function() {
  415. if (orientation) return orientation;
  416. else {
  417. var o = ref.getOrientation();
  418. // here we take into account the orientation of the other anchor: if it declares zero for some direction, we declare zero too.
  419. // 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
  420. // like it makes sense. maybe this wont make sense.
  421. return [Math.abs(o[0]) * xDir * -1, Math.abs(o[1]) * yDir * -1];
  422. }
  423. };
  424. /**
  425. * notification the endpoint associated with this anchor is hovering over another anchor;
  426. * we want to assume that anchor's orientation for the duration of the hover.
  427. */
  428. this.over = function(anchor) {
  429. orientation = anchor.getOrientation();
  430. };
  431. /**
  432. * notification the endpoint associated with this anchor is no longer hovering
  433. * over another anchor; we should resume calculating orientation as we normally do.
  434. */
  435. this.out = function() {
  436. orientation = null;
  437. };
  438. };
  439. // ************** connection
  440. // ****************************************
  441. /**
  442. * allowed params:
  443. * source: source element (string or a jQuery element) (required)
  444. * target: target element (string or a jQuery element) (required)
  445. *
  446. * anchors: optional array of anchor placements. defaults to BottomCenter for source
  447. * and TopCenter for target.
  448. */
  449. var Connection = function(params) {
  450. // ************** get the source and target and register the connection. *******************
  451. var self = this;
  452. // get source and target as jQuery objects
  453. this.source = _getElementObject(params.source);
  454. this.target = _getElementObject(params.target);
  455. this.sourceId = _getAttribute(this.source, "id");
  456. this.targetId = _getAttribute(this.target, "id");
  457. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  458. // init endpoints
  459. this.endpoints = [];
  460. this.endpointStyles = [];
  461. var prepareEndpoint = function(existing, index, params) {
  462. if (existing) self.endpoints[index] = existing;
  463. else {
  464. if(!params.endpoints) params.endpoints = [null,null];
  465. var ep = params.endpoints[index] || params.endpoint || jsPlumb.Defaults.Endpoints[index] || jsPlumb.Defaults.Endpoint|| new jsPlumb.Endpoints.Dot();
  466. if (!params.endpointStyles) params.endpointStyles = [null,null];
  467. var es = params.endpointStyles[index] || params.endpointStyle || jsPlumb.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyle;
  468. var a = params.anchors ? params.anchors[index] : jsPlumb.Defaults.Anchors[index] || jsPlumb.Anchors.BottomCenter;
  469. self.endpoints[index] = new Endpoint({style:es, endpoint:ep, connections:[self], anchor:a });
  470. }
  471. };
  472. prepareEndpoint(params.sourceEndpoint, 0, params);
  473. prepareEndpoint(params.targetEndpoint, 1, params);
  474. this.connector = this.endpoints[0].connector || this.endpoints[1].connector || params.connector || jsPlumb.Defaults.Connector || new jsPlumb.Connectors.Bezier();
  475. this.paintStyle = this.endpoints[0].connectionStyle || this.endpoints[1].connectionStyle || params.paintStyle || jsPlumb.Defaults.PaintStyle;
  476. _updateOffset(this.sourceId);
  477. _updateOffset(this.targetId);
  478. // paint the endpoints
  479. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  480. var anchorLoc = this.endpoints[0].anchor.compute([myOffset.left, myOffset.top], myWH);
  481. this.endpoints[0].paint(anchorLoc);
  482. myOffset = offsets[this.targetId]; myWH = sizes[this.targetId];
  483. anchorLoc = this.endpoints[1].anchor.compute([myOffset.left, myOffset.top], myWH);
  484. this.endpoints[1].paint(anchorLoc);
  485. // *************** create canvas on which the connection will be drawn ************
  486. var canvas = _newCanvas(jsPlumb.connectorClass);
  487. this.canvas = canvas;
  488. /**
  489. * paints the connection.
  490. * @param elId Id of the element that is in motion
  491. * @param ui current library's event system ui object (present if we came from a drag to get here)
  492. * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
  493. */
  494. this.paint = function(elId, ui, recalc) {
  495. if (log) log.debug("Painting Connection; element in motion is " + elId + "; ui is [" + ui + "]; recalc is [" + recalc + "]");
  496. var fai = self.floatingAnchorIndex;
  497. // if the moving object is not the source we must transpose the two references.
  498. var swap = !(elId == this.sourceId);
  499. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  500. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  501. var el = swap ? this.target : this.source;
  502. if (this.canvas.getContext) {
  503. _updateOffset(elId, ui, recalc);
  504. if (recalc) _updateOffset(tId); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  505. var myOffset = offsets[elId];
  506. var otherOffset = offsets[tId];
  507. var myWH = sizes[elId];
  508. var otherWH = sizes[tId];
  509. var ctx = canvas.getContext('2d');
  510. var sAnchorP = this.endpoints[sIdx].anchor.compute([myOffset.left, myOffset.top], myWH, [otherOffset.left, otherOffset.top], otherWH);
  511. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  512. var tAnchorP = this.endpoints[tIdx].anchor.compute([otherOffset.left, otherOffset.top], otherWH, [myOffset.left, myOffset.top], myWH);
  513. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  514. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, this.paintStyle.lineWidth);
  515. jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
  516. jsPlumb.extend(ctx, this.paintStyle);
  517. if (this.paintStyle.gradient && !ie) {
  518. var g = swap ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  519. for (var i = 0; i < this.paintStyle.gradient.stops.length; i++)
  520. g.addColorStop(this.paintStyle.gradient.stops[i][0],this.paintStyle.gradient.stops[i][1]);
  521. ctx.strokeStyle = g;
  522. }
  523. this.connector.paint(dim, ctx);
  524. }
  525. };
  526. this.repaint = function() {
  527. this.paint(this.sourceId, null, true);
  528. };
  529. _initDraggableIfNecessary(self.source, self.sourceId, params.draggable, params.dragOptions);
  530. _initDraggableIfNecessary(self.target, self.targetId, params.draggable, params.dragOptions);
  531. // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
  532. if (this.source.resize) {
  533. this.source.resize(function(e) {
  534. jsPlumb.repaint(self.sourceId);
  535. });
  536. }
  537. };
  538. /*
  539. Class: Endpoint
  540. Models an endpoint. Can have one to N connections emanating from it (although how to handle that in the UI is
  541. a very good question). also has a Canvas and paint style.
  542. */
  543. /*
  544. Function: Endpoint
  545. This is the Endpoint class constructor.
  546. Parameters:
  547. anchor - anchor for the endpoint, of type jsPlumb.Anchor. may be null.
  548. endpoint - endpoint object, of type jsPlumb.Endpoint. may be null.
  549. style - endpoint style, a js object. may be null.
  550. source - element the endpoint is attached to, of type jquery object. Required.
  551. canvas - canvas element to use. may be, and most often is, null.
  552. connections - optional list of connections to configure the endpoint with.
  553. isSource - boolean. indicates the endpoint can act as a source of new connections. optional.
  554. dragOptions - if isSource is set to true, you can supply arguments for the jquery draggable method. optional.
  555. connectionStyle - if isSource is set to true, this is the paint style for connections from this endpoint. optional.
  556. connector - optional connector type to use.
  557. isTarget - boolean. indicates the endpoint can act as a target of new connections. optional.
  558. dropOptions - if isTarget is set to true, you can supply arguments for the jquery droppable method. optional.
  559. reattach - optional boolean that determines whether or not the connections reattach after they
  560. have been dragged off an endpoint and left floating. defaults to false: connections
  561. dropped in this way will just be deleted.
  562. */
  563. var Endpoint = function(params) {
  564. params = params || {};
  565. // make a copy. then we can use the wrapper function.
  566. jsPlumb.extend({}, params);
  567. var self = this;
  568. self.anchor = params.anchor || jsPlumb.Anchors.TopCenter;
  569. var _endpoint = params.endpoint || new jsPlumb.Endpoints.Dot();
  570. var _style = params.style || jsPlumb.Defaults.EndpointStyle;
  571. this.connectionStyle = params.connectionStyle;
  572. this.connector = params.connector;
  573. var _element = params.source;
  574. var _elementId = _getAttribute(_element, "id");
  575. var _maxConnections = params.maxConnections || 1; // maximum number of connections this endpoint can be the source of.
  576. this.canvas = params.canvas || _newCanvas(jsPlumb.endpointClass);
  577. this.connections = params.connections || [];
  578. var _reattach = params.reattach || false;
  579. var floatingEndpoint = null;
  580. this.addConnection = function(connection) {
  581. self.connections.push(connection);
  582. };
  583. this.removeConnection = function(connection) {
  584. var idx = _findIndex(self.connections, connection);
  585. if (idx >= 0)
  586. self.connections.splice(idx, 1);
  587. };
  588. /**
  589. * returns whether or not this endpoint is connected to the given endpoint.
  590. * @param endpoint Endpoint to test.
  591. * @since 1.1.1
  592. *
  593. * todo: needs testing. will this work if the endpoint passed in is the source?
  594. */
  595. this.isConnectedTo = function(endpoint) {
  596. var found = false;
  597. if (endpoint) {
  598. for (var i = 0; i < self.connections.length; i++) {
  599. if (self.connections[i].endpoints[1] == endpoint) {
  600. found = true;
  601. break;
  602. }
  603. }
  604. }
  605. return found;
  606. };
  607. this.isFloating = function() { return floatingEndpoint != null; };
  608. /**
  609. * first pass at default ConnectorSelector: returns the first connection, if we have any.
  610. * modified a little, 5/10/2010: now it only returns a connector if we have not got equal to or more than _maxConnector connectors
  611. * attached. otherwise it is assumed a new connector is ok. but note with this setup we can't select any other connection than the first
  612. * one. what if this could return a list? that implies everything should work with a list - dragging etc. could be nasty. could also
  613. * be cool.
  614. */
  615. var connectorSelector = function() {
  616. return self.connections.length == 0 || self.connections.length < _maxConnections ? null : self.connections[0];
  617. };
  618. this.isFull = function() { return _maxConnections < 1 ? false : (self.connections.length >= _maxConnections); };
  619. /**
  620. * paints the Endpoint, recalculating offset and anchor positions if necessary.
  621. */
  622. this.paint = function(anchorPoint, connectorPaintStyle, canvas) {
  623. if (log) log.debug("Painting Endpoint with elementId [" + _elementId + "]; anchorPoint is [" + anchorPoint + "]");
  624. if (anchorPoint == null) {
  625. // do we always want to force a repaint here? i dont think so!
  626. var xy = offsets[_elementId];
  627. var wh = sizes[_elementId];
  628. if (xy == null || wh == null) {
  629. _updateOffset(_elementId);
  630. xy = offsets[_elementId];
  631. wh = sizes[_elementId];
  632. }
  633. anchorPoint = self.anchor.compute([xy.left, xy.top], wh);
  634. }
  635. _endpoint.paint(anchorPoint, self.anchor.getOrientation(), canvas || self.canvas, _style, connectorPaintStyle || _style);
  636. };
  637. // is this a connection source? we make it draggable and have the drag listener
  638. // maintain a connection with a floating endpoint.
  639. if (params.isSource && _isDragSupported(_element)) {
  640. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  641. // first the question is, how many connections are on this endpoint? if it's only one, then excellent. otherwise we will either need a way
  642. // to select one connection from the list, or drag them all. if we had a pluggable 'ConnectorSelector' interface we could probably
  643. // provide a way for people to implement their own UI components to do the connector selection. the question in that particular case would be how much
  644. // information the interface needs from jsPlumb at execution time. if, however, we leave out the connector selection, and drag them all,
  645. // that wouldn't be too hard to organise. perhaps that behaviour would be on a switch for the endpoint, or perhaps the ConnectorSelector
  646. // interface returns a List, with the default implementation just returning everything. i think i like that.
  647. //
  648. // let's say for now that there is just one endpoint, cos we need to get this going before we can consider a list of them anyway.
  649. // the major difference between that case and the case of a new endpoint is actually quite small - it's a question of where the
  650. // Connection comes from. for a new one, we create a new one. obviously. otherwise we just get the jpc from the Endpoint
  651. // (remember we're only assuming one connection right now). so all of the UI stuff we do to create the floating endpoint etc
  652. // will still be valid, but when we stop dragging, we'll have to do something different. if we stop with a valid drop i think it will
  653. // be the same process. but if we stop with an invalid drop we have to reset the Connection to how it was when we got it.
  654. var start = function() {
  655. n = document.createElement("div");
  656. _appendCanvas(n);
  657. // create and assign an id, and initialize the offset.
  658. var id = "" + new String(new Date().getTime());
  659. _setAttribute(_getElementObject(n), "id", id);
  660. _updateOffset(id);
  661. // store the id of the dragging div and the source element. the drop function
  662. // will pick these up.
  663. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  664. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  665. // create a floating anchor
  666. var floatingAnchor = new FloatingAnchor({reference:self.anchor});
  667. floatingEndpoint = new Endpoint({
  668. style:_style,
  669. endpoint:_endpoint,
  670. anchor:floatingAnchor,
  671. source:n
  672. });
  673. jpc = connectorSelector();
  674. if (jpc == null) {
  675. // create a connection. one end is this endpoint, the other is a floating endpoint.
  676. jpc = new Connection({
  677. sourceEndpoint:self,
  678. targetEndpoint:floatingEndpoint,
  679. source:_getElementObject(_element),
  680. target:_getElementObject(n),
  681. anchors:[self.anchor, floatingAnchor],
  682. paintStyle : params.connectionStyle, // this can be null. Connection will use the default.
  683. connector: params.connector
  684. });
  685. // todo ...unregister on stop
  686. self.addConnection(jpc);
  687. } else {
  688. existingJpc = true;
  689. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1;
  690. jpc.floatingAnchorIndex = anchorIdx;
  691. // probably we should remove the connection? and add it back if the user
  692. // does not drop it somewhere proper.
  693. self.removeConnection(jpc);
  694. if (anchorIdx == 0){
  695. existingJpcParams = [jpc.source, jpc.sourceId];
  696. jpc.source = _getElementObject(n);
  697. jpc.sourceId = id;
  698. }else {
  699. existingJpcParams = [jpc.target, jpc.targetId];
  700. jpc.target = _getElementObject(n);
  701. jpc.targetId = id;
  702. }
  703. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  704. jpc.endpoints[anchorIdx] = floatingEndpoint;
  705. }
  706. // register it.
  707. floatingConnections[id] = jpc;
  708. // todo unregister on stop
  709. floatingEndpoint.addConnection(jpc);
  710. // only register for the target endpoint; we will not be dragging the source at any time
  711. // before this connection is either discarded or made into a permanent connection.
  712. _addToList(endpointsByElement, id, floatingEndpoint);
  713. };
  714. var dragOptions = params.dragOptions || { };
  715. var defaultOpts = jsPlumb.extend({}, jsPlumb.CurrentLibrary.defaultDragOptions);
  716. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  717. var startEvent = jsPlumb.CurrentLibrary.dragEvents['start'];
  718. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  719. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  720. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  721. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent], function() {
  722. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  723. _draw(_getElementObject(n), _ui);
  724. });
  725. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  726. function() {
  727. _removeFromList(endpointsByElement, id, floatingEndpoint);
  728. _removeElements([floatingEndpoint.canvas, n]);
  729. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  730. if (jpc.endpoints[idx] == floatingEndpoint) {
  731. // if the connection was an existing one:
  732. if (existingJpc && jpc.suspendedEndpoint) {
  733. if (_reattach) {
  734. jpc.floatingAnchorIndex = null;
  735. if (idx == 0) {
  736. jpc.source = existingJpcParams[0];
  737. jpc.sourceId = existingJpcParams[1];
  738. } else {
  739. jpc.target = existingJpcParams[0];
  740. jpc.targetId = existingJpcParams[1];
  741. }
  742. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  743. jpc.suspendedEndpoint.addConnection(jpc);
  744. jsPlumb.repaint(existingJpcParams[1]);
  745. }
  746. else {
  747. jpc.endpoints[0].removeConnection(jpc);
  748. jpc.endpoints[1].removeConnection(jpc);
  749. _removeElement(jpc.canvas);
  750. }
  751. } else {
  752. _removeElement(jpc.canvas);
  753. self.removeConnection(jpc);
  754. }
  755. }
  756. jpc = null;
  757. delete floatingEndpoint;
  758. }
  759. );
  760. var i = _getElementObject(self.canvas);
  761. _initDraggable(i, dragOptions);
  762. };
  763. // connector target
  764. if (params.isTarget && _isDropSupported(_element)) {
  765. var dropOptions = params.dropOptions || jsPlumb.Defaults.DropOptions;
  766. dropOptions = jsPlumb.extend({}, dropOptions);
  767. var originalAnchor = null;
  768. dropOptions.drop = _wrap(dropOptions.drop, function() {
  769. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  770. var id = _getAttribute(_getElementObject(draggable), "dragId");
  771. var elId = _getAttribute(_getElementObject(draggable),"elId");
  772. var jpc = floatingConnections[id];
  773. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  774. if (idx == 0) {
  775. jpc.source = _element;
  776. jpc.sourceId = _elementId;
  777. } else {
  778. jpc.target = _element;
  779. jpc.targetId = _elementId;
  780. }
  781. // remove this jpc from the current endpoint
  782. jpc.endpoints[idx].removeConnection(jpc);
  783. if (jpc.suspendedEndpoint)
  784. jpc.suspendedEndpoint.removeConnection(jpc);
  785. jpc.endpoints[idx] = self;
  786. self.addConnection(jpc);
  787. _initDraggableIfNecessary(_element, _elementId, params.draggable, {});
  788. jsPlumb.repaint(elId);
  789. delete floatingConnections[id];
  790. });
  791. // what to do when something is dropped.
  792. // 1. find the jpc that is being dragged. the target endpoint of the jpc will be the
  793. // one that is being dragged.
  794. // 2. arrange for the floating endpoint to be replaced with this endpoint; make sure
  795. // everything gets registered ok etc.
  796. // 3. arrange for the floating endpoint to be deleted.
  797. // 4. make sure that the stop method of the drag does not cause the jpc to be cleaned up. we want to keep it now.
  798. // other considerations: when in the hover mode, we should switch the floating endpoint's
  799. // orientation to be the same as the drop target. this will cause the connector to snap
  800. // into the shape it will take if the user drops at that point.
  801. dropOptions.over = _wrap(dropOptions.over, function() {
  802. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  803. var id = _getAttribute(_getElementObject(draggable),"dragId");
  804. var jpc = floatingConnections[id];
  805. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  806. jpc.endpoints[idx].anchor.over(self.anchor);
  807. });
  808. dropOptions.out = _wrap(dropOptions.out, function() {
  809. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  810. var id = _getAttribute(_getElementObject(draggable),"dragId");
  811. var jpc = floatingConnections[id];
  812. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  813. jpc.endpoints[idx].anchor.out();
  814. });
  815. _initDroppable(_getElementObject(self.canvas), dropOptions);
  816. }
  817. return self;
  818. };
  819. /*
  820. Class: jsPlumb
  821. This is the main entry point to jsPlumb. There are a bunch of static methods you can
  822. use to connect/disconnect etc. Some methods are also added to jQuery's "$.fn" object itself, but
  823. in general jsPlumb is moving away from that model, preferring instead the static class
  824. approach. One of the reasons for this is that with no methods added to the jQuery $.fn object,
  825. it will be easier to provide support for other libraries such as MooTools.
  826. */
  827. var jsPlumb = window.jsPlumb = {
  828. /*
  829. Property: Defaults
  830. These are the default settings for jsPlumb, that is what will be used if you do not supply specific pieces of information
  831. 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
  832. somewhere after the jsPlumb include, but before you make any calls to jsPlumb, for instance in this example we set the PaintStyle to be
  833. a blue line of 27 pixels:
  834. > jsPlumb.Defaults.PaintStyle = { lineWidth:27, strokeStyle:'blue' }
  835. */
  836. Defaults : {
  837. Anchors : [ null, null ],
  838. Connector : null,
  839. DragOptions: { },
  840. DropOptions: { },
  841. Endpoint : null,
  842. Endpoints : [ null, null ],
  843. EndpointStyle : { fillStyle : null },
  844. EndpointStyles : [ null, null ],
  845. MaxConnections : null,
  846. PaintStyle : { lineWidth : 10, strokeStyle : 'red' }
  847. },
  848. /*
  849. Property: connectorClass
  850. The CSS class to set on Connection canvas elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  851. */
  852. connectorClass : '_jsPlumb_connector',
  853. /*
  854. Property: endpointClass
  855. The CSS class to set on Endpoint canvas elements. This value is a String and can have multiple classes; the entire String is appended as-is.
  856. */
  857. endpointClass : '_jsPlumb_endpoint',
  858. /*
  859. Property: Anchors
  860. Default jsPlumb Anchors. These are supplied in the file jquery.jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  861. to form jquery.jsPlumb-all-x.x.x.js. You can provide your own Anchors by supplying them in a script that is loaded after jsPlumb, for instance:
  862. > jsPlumb.Anchors.MyAnchor = { ....anchor code here. see the documentation. }
  863. */
  864. Anchors : {},
  865. /*
  866. Property: Connectors
  867. Default jsPlumb Connectors. These are supplied in the file jquery.jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  868. to form jquery.jsPlumb-all-x.x.x.js. You can provide your own Connectors by supplying them in a script that is loaded after jsPlumb, for instance:
  869. > jsPlumb.Connectors.MyConnector = { ....connector code here. see the documentation. }
  870. */
  871. Connectors : {},
  872. /*
  873. Property: Endpoints
  874. Default jsPlumb Endpoints. These are supplied in the file jquery.jsPlumb-defaults-x.x.x.js, which is merged in with the main jsPlumb script
  875. to form jquery.jsPlumb-all-x.x.x.js. You can provide your own Endpoints by supplying them in a script that is loaded after jsPlumb, for instance:
  876. > jsPlumb.Endpoints.MyEndpoint = { ....endpoint code here. see the documentation. }
  877. */
  878. Endpoints : {},
  879. /*
  880. Function: addEndpoint
  881. Adds an Endpoint to a given element.
  882. Parameters:
  883. target - Element to add the endpoint to. either an element id, or a jQuery object representing some element.
  884. params - Object containing Endpoint options (more info required)
  885. Returns:
  886. The newly created Endpoint.
  887. See Also:
  888. <addEndpoints>
  889. */
  890. addEndpoint : function(target, params) {
  891. params = jsPlumb.extend({}, params);
  892. var el = _getElementObject(target);
  893. var id = _getAttribute(target,"id");
  894. params.source = el;
  895. _updateOffset(id);
  896. var e = new Endpoint(params);
  897. _addToList(endpointsByElement, id, e);
  898. var myOffset = offsets[id];
  899. var myWH = sizes[id];
  900. var anchorLoc = e.anchor.compute([myOffset.left, myOffset.top], myWH);
  901. e.paint(anchorLoc);
  902. return e;
  903. },
  904. /*
  905. Function: addEndpoint
  906. Adds a list of Endpoints to a given element.
  907. Parameters:
  908. target - element to add the endpoint to. either an element id, or a jQuery object representing some element.
  909. endpoints - List of objects containing Endpoint options. one Endpoint is created for each entry in this list.
  910. Returns:
  911. List of newly created Endpoints, one for each entry in the 'endpoints' argument.
  912. See Also:
  913. <addEndpoint>
  914. */
  915. addEndpoints : function(target, endpoints) {
  916. var results = [];
  917. for (var i = 0; i < endpoints.length; i++) {
  918. results.push(jsPlumb.addEndpoint(target, endpoints[i]));
  919. }
  920. return results;
  921. },
  922. /*
  923. Function: animate
  924. Wrapper around standard jQuery animate function; injects a call to jsPlumb in the 'step' function (creating it if necessary).
  925. This only supports the two-arg version of the animate call in jQuery - the one that takes an 'options' object as the second arg.
  926. Parameters:
  927. el - Element to animate. Either an id, or a jQuery object representing the element.
  928. properties - The 'properties' argument you want passed to the standard jQuery animate call.
  929. options - The 'options' argument you want passed to the standard jQuery animate call.
  930. Returns:
  931. void
  932. */
  933. animate : function(el, properties, options) {
  934. var ele = _getElementObject(el);
  935. var id = _getAttribute(el,"id");
  936. options = options || {};
  937. options.step = _wrap(options.step, function() { jsPlumb.repaint(id); });
  938. _animate(ele, properties, options);
  939. },
  940. /*
  941. Function: connect
  942. Establishes a connection between two elements.
  943. Parameters:
  944. params - Object containing setup for the connection. see documentation.
  945. Returns:
  946. The newly created Connection.
  947. */
  948. connect : function(params) {
  949. if (params.sourceEndpoint && params.sourceEndpoint.isFull()) {
  950. _log("could not add connection; source endpoint is full");
  951. return;
  952. }
  953. if (params.targetEndpoint && params.targetEndpoint.isFull()) {
  954. _log("could not add connection; target endpoint is full");
  955. return;
  956. }
  957. var jpc = new Connection(params);
  958. // register endpoints for the element. todo: is the test below sufficient? or should we test if the endpoint is already in the list,
  959. // and add it only then? perhaps _addToList could be overloaded with a a 'test for existence first' parameter?
  960. //_addToList(endpointsByElement, jpc.sourceId, jpc.endpoints[0]);
  961. //_addToList(endpointsByElement, jpc.targetId, jpc.endpoints[1]);
  962. if (!params.sourceEndpoint) _addToList(endpointsByElement, jpc.sourceId, jpc.endpoints[0]);
  963. if (!params.targetEndpoint) _addToList(endpointsByElement, jpc.targetId, jpc.endpoints[1]);
  964. jpc.endpoints[0].addConnection(jpc);
  965. jpc.endpoints[1].addConnection(jpc);
  966. // force a paint
  967. _draw(jpc.source);
  968. return jpc;
  969. },
  970. /**
  971. * not implemented yet. params object will have sourceEndpoint and targetEndpoint members; these will be Endpoints.
  972. connectEndpoints : function(params) {
  973. var jpc = Connection(params);
  974. },*/
  975. /*
  976. Function: detach
  977. Removes a connection.
  978. Parameters:
  979. sourceId - Id of the first element in the connection. A String.
  980. targetId - iI of the second element in the connection. A String.
  981. Returns:
  982. true if successful, false if not.
  983. */
  984. detach : function(sourceId, targetId) {
  985. var f = function(jpc) {
  986. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  987. _removeElement(jpc.canvas);
  988. jpc.endpoints[0].removeConnection(jpc);
  989. jpc.endpoints[1].removeConnection(jpc);
  990. return true;
  991. }
  992. };
  993. // todo: how to cleanup the actual storage? a third arg to _operation?
  994. _operation(sourceId, f);
  995. },
  996. /*
  997. Function: detachAll
  998. Removes all an element's connections.
  999. Parameters:
  1000. el - either the id of the element, or a jQuery object for the element.
  1001. Returns:
  1002. void
  1003. */
  1004. detachAll : function(el) {
  1005. var id = _getAttribute(el, "id");
  1006. var f = function(jpc) {
  1007. // todo replace with _cleanupConnection call here.
  1008. _removeElement(jpc.canvas);
  1009. jpc.endpoints[0].removeConnection(jpc);
  1010. jpc.endpoints[1].removeConnection(jpc);
  1011. };
  1012. _operation(id, f);
  1013. //delete endpointsByElement[id]; ??
  1014. },
  1015. /*
  1016. Function: detachEverything
  1017. Remove all Connections from all elements, but leaves Endpoints in place.
  1018. Returns:
  1019. void
  1020. See Also:
  1021. <removeAllEndpoints>
  1022. */
  1023. detachEverything : function() {
  1024. var f = function(jpc) {
  1025. _removeElement(jpc.canvas);
  1026. jpc.endpoints[0].removeConnection(jpc);
  1027. jpc.endpoints[1].removeConnection(jpc);
  1028. };
  1029. _operationOnAll(f);
  1030. /*delete endpointsByElement; //??
  1031. endpointsByElement = {};*/ //??
  1032. },
  1033. extend : function(o1, o2) {
  1034. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1035. },
  1036. /*
  1037. Function: hide
  1038. Sets an element's connections to be hidden.
  1039. Parameters:
  1040. el - either the id of the element, or a jQuery object for the element.
  1041. Returns:
  1042. void
  1043. */
  1044. hide : function(el) {
  1045. _setVisible(el, "none");
  1046. },
  1047. /*
  1048. Function: makeAnchor
  1049. Creates an anchor with the given params.
  1050. Parameters:
  1051. x - the x location of the anchor as a fraction of the total width.
  1052. y - the y location of the anchor as a fraction of the total height.
  1053. xOrientation - value indicating the general direction a connection from the anchor should go in, in the x direction.
  1054. yOrientation - value indicating the general direction a connection from the anchor should go in, in the y direction.
  1055. xOffset - a fixed offset that should be applied in the x direction that should be applied after the x position has been figured out. optional. defaults to 0.
  1056. yOffset - a fixed offset that should be applied in the y direction that should be applied after the y position has been figured out. optional. defaults to 0.
  1057. Returns:
  1058. The newly created Anchor.
  1059. */
  1060. makeAnchor : function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1061. // backwards compatibility here. we used to require an object passed in but that makes the call very verbose. easier to use
  1062. // by just passing in four/six values. but for backwards compatibility if we are given only one value we assume it's a call in the old form.
  1063. var params = {};
  1064. if (arguments.length == 1) jsPlumb.extend(params, x);
  1065. else {
  1066. params = {x:x, y:y};
  1067. if (arguments.length >= 4) {
  1068. params.orientation = [arguments[2], arguments[3]];
  1069. }
  1070. if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
  1071. }
  1072. return new Anchor(params);
  1073. },
  1074. /*
  1075. Function: repaint
  1076. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1077. Parameters:
  1078. el - either the id of the element or a jQuery object representing the element.
  1079. Returns:
  1080. void
  1081. See Also:
  1082. <repaintEverything>
  1083. */
  1084. repaint : function(el) {
  1085. var _processElement = function(el) {
  1086. var ele = _getElementObject(el);
  1087. _draw(ele);
  1088. };
  1089. // TODO: support a jQuery result object too!
  1090. // support both lists...
  1091. if (typeof el =='object') {
  1092. for (var i = 0; i < el.length; i++)
  1093. _processElement(el[i]);
  1094. } // ...and single strings.
  1095. else _processElement(el);
  1096. },
  1097. /*
  1098. Function: repaintEverything
  1099. Repaints all connections.
  1100. Returns:
  1101. void
  1102. See Also:
  1103. <repaint>
  1104. */
  1105. repaintEverything : function() {
  1106. for (var elId in endpointsByElement) {
  1107. _draw(_getElementObject(elId));
  1108. }
  1109. },
  1110. /*
  1111. Function: removeAllEndpoints
  1112. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1113. Parameters:
  1114. el - either an element id, or a jQuery object for an element.
  1115. Returns:
  1116. void
  1117. See Also:
  1118. <removeEndpoint>
  1119. */
  1120. removeAllEndpoints : function(el) {
  1121. var elId = _getAttribute(el, "id");
  1122. // first remove all Connections.
  1123. jsPlumb.detachAll(elId);
  1124. var ebe = endpointsByElement[elId];
  1125. for (var i in ebe) {
  1126. _removeElement(ebe[i].canvas);
  1127. }
  1128. endpointsByElement[elId] = [];
  1129. },
  1130. /*
  1131. Function: removeEndpoint
  1132. Removes the given Endpoint from the given element.
  1133. Parameters:
  1134. el - either an element id, or a jQuery object for an element.
  1135. endpoint - Endpoint to remove. this is an Endpoint object, such as would have been returned from a call to addEndpoint.
  1136. Returns:
  1137. void
  1138. See Also:
  1139. <removeAllEndpoints>
  1140. */
  1141. removeEndpoint : function(el, endpoint) {
  1142. var elId = _getAttribute(el, "id");
  1143. var ebe = endpointsByElement[elId];
  1144. if (ebe) {
  1145. if(_removeFromList(endpointsByElement, elId, endpoint))
  1146. _removeElement(endpoint.canvas);
  1147. }
  1148. },
  1149. /*
  1150. Function: setAutomaticRepaint
  1151. Sets/unsets automatic repaint on window resize.
  1152. Parameters:
  1153. value - whether or not to automatically repaint when the window is resized.
  1154. Returns:
  1155. void
  1156. */
  1157. setAutomaticRepaint : function(value) {
  1158. automaticRepaint = value;
  1159. },
  1160. /*
  1161. Function: setDefaultNewCanvasSize
  1162. Sets the default size jsPlumb will use for a new canvas (we create a square canvas so one value is all that is required).
  1163. This is a hack for IE, because ExplorerCanvas seems to need for a canvas to be larger than what you are going to draw on
  1164. it at initialisation time. The default value of this is 1200 pixels, which is quite large, but if for some reason you're
  1165. drawing connectors that are bigger, you should adjust this value appropriately.
  1166. Parameters:
  1167. size - The default size to use. jsPlumb will use a square canvas so you need only supply one value.
  1168. Returns:
  1169. void
  1170. */
  1171. setDefaultNewCanvasSize : function(size) {
  1172. DEFAULT_NEW_CANVAS_SIZE = size;
  1173. },
  1174. /*
  1175. Function: setDraggable
  1176. Sets whether or not a given element is draggable, regardless of what any plumb command may request.
  1177. Parameters:
  1178. el - either the id for the element, or a jQuery object representing the element.
  1179. Returns:
  1180. void
  1181. */
  1182. setDraggable: _setDraggable,
  1183. /*
  1184. Function: setDraggableByDefault
  1185. Sets whether or not elements are draggable by default. Default for this is true.
  1186. Parameters:
  1187. draggable - value to set
  1188. Returns:
  1189. void
  1190. */
  1191. setDraggableByDefault: function(draggable) {
  1192. _draggableByDefault = draggable;
  1193. },
  1194. setDebugLog: function(debugLog) {
  1195. log = debugLog;
  1196. },
  1197. /*
  1198. Function: setRepaintFunction
  1199. Sets the function to fire when the window size has changed and a repaint was fired.
  1200. Parameters:
  1201. f - Function to execute.
  1202. Returns:
  1203. void
  1204. */
  1205. setRepaintFunction : function(f) {
  1206. repaintFunction = f;
  1207. },
  1208. /*
  1209. Function: show
  1210. Sets an element's connections to be visible.
  1211. Parameters:
  1212. el - either the id of the element, or a jQuery object for the element.
  1213. Returns:
  1214. void
  1215. */
  1216. show : function(el) {
  1217. _setVisible(el, "block");
  1218. },
  1219. /*
  1220. Function: sizeCanvas
  1221. Helper to size a canvas. You would typically use this when writing your own Connector or Endpoint implementation.
  1222. Parameters:
  1223. x - [int] x position for the Canvas origin
  1224. y - [int] y position for the Canvas origin
  1225. w - [int] width of the canvas
  1226. h - [int] height of the canvas
  1227. Returns:
  1228. void
  1229. */
  1230. sizeCanvas : function(canvas, x, y, w, h) {
  1231. if (canvas) {
  1232. canvas.style.height = h + "px"; canvas.height = h;
  1233. canvas.style.width = w + "px"; canvas.width = w;
  1234. canvas.style.left = x + "px"; canvas.style.top = y + "px";
  1235. }
  1236. },
  1237. /**
  1238. * gets some test hooks. nothing writable.
  1239. */
  1240. getTestHarness : function() {
  1241. return {
  1242. endpointCount : function(elId) {
  1243. var e = endpointsByElement[elId];
  1244. return e ? e.length : 0;
  1245. }
  1246. };
  1247. },
  1248. /**
  1249. * Toggles visibility of an element's connections. kept for backwards compatibility
  1250. */
  1251. toggle : _toggleVisible,
  1252. /*
  1253. Function: toggleVisible
  1254. Toggles visibility of an element's connections.
  1255. Parameters:
  1256. el - either the element's id, or a jQuery object representing the element.
  1257. Returns:
  1258. void, but should be updated to return the current state
  1259. */
  1260. //TODO: update this method to return the current state.
  1261. toggleVisible : _toggleVisible,
  1262. /*
  1263. Function: toggleDraggable
  1264. Toggles draggability (sic) of an element's connections.
  1265. Parameters:
  1266. el - either the element's id, or a jQuery object representing the element.
  1267. Returns:
  1268. The current draggable state.
  1269. */
  1270. toggleDraggable : _toggleDraggable,
  1271. /*
  1272. Function: unload
  1273. Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element
  1274. Returns:
  1275. void
  1276. */
  1277. unload : function() {
  1278. delete endpointsByElement;
  1279. delete offsets;
  1280. delete sizes;
  1281. delete floatingConnections;
  1282. delete draggableStates;
  1283. }
  1284. };
  1285. })();
  1286. // jQuery plugin code
  1287. (function($){
  1288. /**
  1289. * plumbs the results of the selector to some target, using the given options if supplied,
  1290. * or the defaults otherwise. this is DEPRECATED. just use jsPlumb.connect(..) instead.
  1291. * @deprecated
  1292. */
  1293. $.fn.plumb = function(options) {
  1294. var options = $.extend({}, options);
  1295. return this.each(function()
  1296. {
  1297. var params = $.extend({source:$(this)}, options);
  1298. jsPlumb.connect(params);
  1299. });
  1300. };
  1301. /**
  1302. * detaches the results of the selector from the given target or list of targets - 'target'
  1303. * may be a String or a List.
  1304. */
  1305. $.fn.detach = function(target) {
  1306. return this.each(function()
  1307. {
  1308. var id = $(this).attr("id");
  1309. if (typeof target == 'string') target = [target];
  1310. for (var i = 0; i < target.length; i++)
  1311. jsPlumb.detach(id, target[i]);
  1312. });
  1313. };
  1314. /**
  1315. * detaches the results from the selector from all connections.
  1316. */
  1317. $.fn.detachAll = function() {
  1318. return this.each(function()
  1319. {
  1320. var id = $(this).attr("id");
  1321. jsPlumb.detachAll(id);
  1322. });
  1323. };
  1324. /**
  1325. * adds an endpoint to the elements resulting from the selector. options may be null,
  1326. * in which case jsPlumb will use the default options. see documentation.
  1327. */
  1328. $.fn.addEndpoint = function(options) {
  1329. var addedEndpoints = [];
  1330. this.each(function()
  1331. {
  1332. addedEndpoints.push(jsPlumb.addEndpoint($(this).attr("id"), options));
  1333. });
  1334. return addedEndpoints[0];
  1335. };
  1336. /**
  1337. * adds a list of endpoints to the elements resulting from the selector. options may be null,
  1338. * in which case jsPlumb will use the default options. see documentation.
  1339. */
  1340. $.fn.addEndpoints = function(endpoints) {
  1341. var addedEndpoints = [];
  1342. return this.each(function()
  1343. {
  1344. var e = jsPlumb.addEndpoints($(this).attr("id"), endpoints);
  1345. for (var i = 0; i < e.length; i++) addedEndpoints.push(e[i]);
  1346. });
  1347. return addedEndpoints;
  1348. };
  1349. /**
  1350. * remove the endpoint, if it exists, deleting its UI elements etc.
  1351. */
  1352. $.fn.removeEndpoint = function(endpoint) {
  1353. this.each(function()
  1354. {
  1355. jsPlumb.removeEndpoint($(this).attr("id"), endpoint);
  1356. });
  1357. };
  1358. })(jQuery);
  1359. /* the library agnostic functions, such as find offset, get id, get attribute, extend etc. currently
  1360. hardcoded to jQuery here; will be extracted to separate impls for different libraries.
  1361. * much more work needs to be done on this. some things that spring to mind: animation, drag, drop.
  1362. *
  1363. * you should _never_ call these methods directly. jsPlumb uses them when it needs them.
  1364. *
  1365. */
  1366. (function() {
  1367. jsPlumb.CurrentLibrary = {
  1368. /**
  1369. * mapping of drag events for jQuery
  1370. */
  1371. dragEvents : {
  1372. 'start':'start', 'stop':'stop', 'drag':'drag'
  1373. },
  1374. /**
  1375. * default drag options for jQuery.
  1376. */
  1377. defaultDragOptions : { opacity:0.5, revert:true, helper:'clone' },
  1378. /**
  1379. * wrapper around the library's 'extend' functionality (which it hopefully has.
  1380. * otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
  1381. * instead. it's not like its hard.
  1382. */
  1383. extend : function(o1, o2) {
  1384. return $.extend(o1, o2);
  1385. },
  1386. /**
  1387. * gets an "element object" from the given input. this means an object that is used by the
  1388. * underlying library on which jsPlumb is running. 'el' may already be one of these objects,
  1389. * in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
  1390. * function is used to find the element, using the given String as the element's id.
  1391. */
  1392. getElementObject : function(el) {
  1393. return typeof(el)=='string' ? $("#" + el) : $(el);
  1394. },
  1395. /**
  1396. * gets the offset for the element object. this should return a js object like this:
  1397. *
  1398. * { left:xxx, top: xxx }
  1399. */
  1400. getOffset : function(el) {
  1401. return el.offset();
  1402. },
  1403. /**
  1404. * gets the size for the element object, in an array : [ width, height ].
  1405. */
  1406. getSize : function(el) {
  1407. return [el.outerWidth(), el.outerHeight()];
  1408. },
  1409. /**
  1410. * gets the named attribute from the given element object.
  1411. */
  1412. getAttribute : function(el, attName) {
  1413. return el.attr(attName);
  1414. },
  1415. /**
  1416. * sets the named attribute on the given element object.
  1417. */
  1418. setAttribute : function(el, attName, attValue) {
  1419. el.attr(attName, attValue);
  1420. },
  1421. /**
  1422. * adds the given class to the element object.
  1423. */
  1424. addClass : function(el, clazz) {
  1425. el.addClass(clazz);
  1426. },
  1427. /**
  1428. * initialises the given element to be draggable.
  1429. */
  1430. initDraggable : function(el, options) {
  1431. if (el.length > 1) alert('poo');
  1432. el.draggable(options);
  1433. },
  1434. /**
  1435. * returns whether or not drag is supported (by the library, not whether or not it is disabled) for the given element.
  1436. */
  1437. isDragSupported : function(el, options) {
  1438. return el.draggable;
  1439. },
  1440. /**
  1441. * sets the draggable state for the given element
  1442. */
  1443. setDraggable : function(el, draggable) {
  1444. el.draggable("option", "disabled", !draggable);
  1445. },
  1446. /**
  1447. * initialises the given element to be droppable.
  1448. */
  1449. initDroppable : function(el, options) {
  1450. el.droppable(options);
  1451. },
  1452. /**
  1453. * returns whether or not drop is supported (by the library, not whether or not it is disabled) for the given element.
  1454. */
  1455. isDropSupported : function(el, options) {
  1456. return el.droppable;
  1457. },
  1458. /**
  1459. * animates the given element.
  1460. */
  1461. animate : function(el, properties, options) {
  1462. el.animate(properties, options);
  1463. },
  1464. /**
  1465. * takes the args passed to an event function and returns you an object that gives the
  1466. * position of the object being moved, as a js object with the same params as the result of
  1467. * getOffset, ie: { left: xxx, top: xxx }.
  1468. *
  1469. * different libraries have different signatures for their event callbacks.
  1470. * see getDragObject as well
  1471. */
  1472. getUIPosition : function(eventArgs) {
  1473. var ui = eventArgs[1];
  1474. return ui.absolutePosition || ui.offset;
  1475. },
  1476. /**
  1477. * takes the args passed to an event function and returns you an object representing that which is being dragged.
  1478. */
  1479. getDragObject : function(eventArgs) {
  1480. return eventArgs[1].draggable;
  1481. }
  1482. };
  1483. })();