jsPlumb-1.3.1-RC1.js 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290
  1. /*
  2. * jsPlumb
  3. *
  4. * Title:jsPlumb 1.3.0
  5. *
  6. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  7. * elements, or VML.
  8. *
  9. * This file contains the jsPlumb core code.
  10. *
  11. * Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
  12. *
  13. * http://jsplumb.org
  14. * http://code.google.com/p/jsPlumb
  15. *
  16. * Triple licensed under the MIT, GPL2 and Beer licenses.
  17. */
  18. ;(function() {
  19. /**
  20. * Class:jsPlumb
  21. * The jsPlumb engine, registered as a static object in the window. This object contains all of the methods you will use to
  22. * create and maintain Connections and Endpoints.
  23. */
  24. var ie = !!!document.createElement('canvas').getContext;
  25. var canvasAvailable = !!document.createElement('canvas').getContext;
  26. var svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
  27. // TODO what is a good test for VML availability? aside from just assuming its there because nothing else is.
  28. var vmlAvailable = !(canvasAvailable | svgAvailable);
  29. var _findIndex = function(a, v, b, s) {
  30. var _eq = function(o1, o2) {
  31. if (o1 === o2)
  32. return true;
  33. else if (typeof o1 == "object" && typeof o2 == "object") {
  34. var same = true;
  35. for ( var propertyName in o1) {
  36. if (!_eq(o1[propertyName], o2[propertyName])) {
  37. same = false;
  38. break;
  39. }
  40. }
  41. for ( var propertyName in o2) {
  42. if (!_eq(o2[propertyName], o1[propertyName])) {
  43. same = false;
  44. break;
  45. }
  46. }
  47. return same;
  48. }
  49. };
  50. for ( var i = +b || 0, l = a.length; i < l; i++) {
  51. if (_eq(a[i], v))
  52. return i;
  53. }
  54. return -1;
  55. };
  56. /**
  57. * helper method to add an item to a list, creating the list if it does
  58. * not yet exist.
  59. */
  60. var _addToList = function(map, key, value) {
  61. var l = map[key];
  62. if (l == null) {
  63. l = [];
  64. map[key] = l;
  65. }
  66. l.push(value);
  67. return l;
  68. };
  69. var _connectionBeingDragged = null;
  70. var _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); };
  71. var _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); };
  72. var _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); };
  73. var _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); };
  74. var _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); };
  75. var _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); };
  76. var _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); };
  77. var _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); };
  78. var _log = function(jsp, msg) {
  79. if (jsp.logEnabled && typeof console != "undefined")
  80. console.log(msg);
  81. };
  82. /**
  83. * EventGenerator
  84. * Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
  85. */
  86. var EventGenerator = function() {
  87. var _listeners = {}, self = this;
  88. // 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
  89. // jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
  90. // 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"
  91. // event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
  92. // to hear what other people think.
  93. var eventsToDieOn = [ "ready" ];
  94. /*
  95. * Binds a listener to an event.
  96. *
  97. * Parameters:
  98. * event - name of the event to bind to.
  99. * listener - function to execute.
  100. */
  101. this.bind = function(event, listener) {
  102. _addToList(_listeners, event, listener);
  103. };
  104. /*
  105. * Fires an update for the given event.
  106. *
  107. * Parameters:
  108. * event - event to fire
  109. * value - value to pass to the event listener(s).
  110. * o riginalEvent - the original event from the browser
  111. */
  112. this.fire = function(event, value, originalEvent) {
  113. if (_listeners[event]) {
  114. for ( var i = 0; i < _listeners[event].length; i++) {
  115. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  116. // method will have the whole call stack available in the debugger.
  117. if (_findIndex(eventsToDieOn, event) != -1)
  118. _listeners[event][i](value, originalEvent);
  119. else {
  120. // for events we don't want to die on, catch and log.
  121. try {
  122. _listeners[event][i](value, originalEvent);
  123. } catch (e) {
  124. _log("jsPlumb: fire failed for event " + event + " : " + e);
  125. }
  126. }
  127. }
  128. }
  129. };
  130. /*
  131. * Clears either all listeners, or listeners for some specific event.
  132. *
  133. * Parameters:
  134. * event - optional. constrains the clear to just listeners for this event.
  135. */
  136. this.clearListeners = function(event) {
  137. if (event) {
  138. delete _listeners[event];
  139. } else {
  140. delete _listeners;
  141. _listeners = {};
  142. }
  143. };
  144. };
  145. /*
  146. * Class:jsPlumbUIComponent
  147. * Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle,
  148. * and also extends EventGenerator to provide the bind and fire methods.
  149. */
  150. var jsPlumbUIComponent = function(params) {
  151. var self = this, a = arguments, _hover = false;
  152. self._jsPlumb = params["_jsPlumb"];
  153. //self.parent = params["parent"];
  154. // all components can generate events
  155. EventGenerator.apply(this);
  156. // all components get this clone function.
  157. this.clone = function() {
  158. var o = new Object();
  159. self.constructor.apply(o, a);
  160. return o;
  161. };
  162. this.overlayPlacements = [],
  163. this.paintStyle = null,
  164. this.hoverPaintStyle = null;
  165. // helper method to update the hover style whenever it, or paintStyle, changes.
  166. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  167. // top.
  168. var _updateHoverStyle = function() {
  169. if (self.paintStyle && self.hoverPaintStyle) {
  170. var mergedHoverStyle = {};
  171. jsPlumb.extend(mergedHoverStyle, self.paintStyle);
  172. jsPlumb.extend(mergedHoverStyle, self.hoverPaintStyle);
  173. delete self.hoverPaintStyle;
  174. // we want the fillStyle of paintStyle to override a gradient, if possible.
  175. if (mergedHoverStyle.gradient && self.paintStyle.fillStyle)
  176. delete mergedHoverStyle.gradient;
  177. self.hoverPaintStyle = mergedHoverStyle;
  178. }
  179. };
  180. /*
  181. * Sets the paint style and then repaints the element.
  182. *
  183. * Parameters:
  184. * style - Style to use.
  185. */
  186. this.setPaintStyle = function(style, doNotRepaint) {
  187. self.paintStyle = style;
  188. self.paintStyleInUse = self.paintStyle;
  189. _updateHoverStyle();
  190. if (!doNotRepaint) self.repaint();
  191. };
  192. /*
  193. * Sets the paint style to use when the mouse is hovering over the element. This is null by default.
  194. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  195. * it. This is because people will most likely want to change just one thing when hovering, say the
  196. * color for example, but leave the rest of the appearance the same.
  197. *
  198. * Parameters:
  199. * style - Style to use when the mouse is hovering.
  200. * doNotRepaint - if true, the component will not be repainted. useful when setting things up initially.
  201. */
  202. this.setHoverPaintStyle = function(style, doNotRepaint) {
  203. self.hoverPaintStyle = style;
  204. _updateHoverStyle();
  205. if (!doNotRepaint) self.repaint();
  206. };
  207. /*
  208. * sets/unsets the hover state of this element.
  209. *
  210. * Parameters:
  211. * hover - hover state boolean
  212. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  213. */
  214. this.setHover = function(hover, ignoreAttachedElements) {
  215. _hover = hover;
  216. if (self.hoverPaintStyle != null) {
  217. self.paintStyleInUse = hover ? self.hoverPaintStyle : self.paintStyle;
  218. self.repaint();
  219. // get the list of other affected elements. for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  220. if (!ignoreAttachedElements)
  221. _updateAttachedElements(hover);
  222. }
  223. };
  224. this.isHover = function() {
  225. return _hover;
  226. };
  227. this.attachListeners = function(o, c) {
  228. var jpcl = jsPlumb.CurrentLibrary,
  229. events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup" ],
  230. eventFilters = { "mouseout":"mouseexit" },
  231. bindOne = function(evt) {
  232. var filteredEvent = eventFilters[evt] || evt;
  233. jpcl.bind(o, evt, function(ee) {
  234. c.fire(filteredEvent, c, ee);
  235. });
  236. };
  237. for (var i = 0; i < events.length; i++) {
  238. bindOne(events[i]);
  239. }
  240. };
  241. var _updateAttachedElements = function(state) {
  242. var affectedElements = self.getAttachedElements(); // implemented in subclasses
  243. if (affectedElements) {
  244. for (var i = 0; i < affectedElements.length; i++) {
  245. affectedElements[i].setHover(state, true); // tell the attached elements not to inform their own attached elements.
  246. }
  247. }
  248. };
  249. };
  250. var jsPlumbInstance = function(_defaults) {
  251. /*
  252. * Property: Defaults
  253. *
  254. * These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
  255. * to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
  256. * by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
  257. *
  258. * Properties:
  259. * - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
  260. * - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
  261. * - *Connector* The default connector definition to use for all connections. Default is "Bezier".
  262. * - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  263. * - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  264. * - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
  265. * - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
  266. * - *EndpointStyle* The default style definition to use for all endpoints. Default is empty.
  267. * - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
  268. * - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
  269. * - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
  270. * - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
  271. * - *LabelStyle* The default style to use for label overlays on connections.
  272. * - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
  273. * - *Overlays* The default overlay definitions. Defaults to an empty list.
  274. * - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
  275. * - *MouseEventsEnabled* Whether or not mouse events are enabled when using the canvas renderer. Defaults to true.
  276. * The idea of this is just to give people a way to prevent all the mouse listeners from activating if they know they won't need mouse events.
  277. * - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
  278. * - *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 Canvas elements.
  279. * - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
  280. */
  281. this.Defaults = {
  282. Anchor : "BottomCenter",
  283. Anchors : [ null, null ],
  284. Connector : "Bezier",
  285. DragOptions : { },
  286. DropOptions : { },
  287. Endpoint : "Dot",
  288. Endpoints : [ null, null ],
  289. EndpointStyle : { fillStyle : null },
  290. EndpointStyles : [ null, null ],
  291. EndpointHoverStyle : null,
  292. EndpointHoverStyles : [ null, null ],
  293. HoverPaintStyle : null,
  294. LabelStyle : { color : "black" },
  295. LogEnabled : false,
  296. Overlays : [ ],
  297. MaxConnections : 1,
  298. MouseEventsEnabled : true,
  299. PaintStyle : { lineWidth : 8, strokeStyle : "#456" },
  300. RenderMode : "canvas",
  301. Scope : "_jsPlumb_DefaultScope"
  302. };
  303. if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
  304. this.logEnabled = this.Defaults.LogEnabled;
  305. EventGenerator.apply(this);
  306. var _bb = this.bind;
  307. this.bind = function(event, fn) {
  308. if ("ready" === event && initialized) fn();
  309. else _bb(event, fn);
  310. };
  311. var _currentInstance = this,
  312. log = null,
  313. repaintFunction = function() {
  314. jsPlumb.repaintEverything();
  315. },
  316. automaticRepaint = true,
  317. repaintEverything = function() {
  318. if (automaticRepaint)
  319. repaintFunction();
  320. },
  321. resizeTimer = null,
  322. initialized = false,
  323. connectionsByScope = {},
  324. /**
  325. * map of element id -> endpoint lists. an element can have an arbitrary
  326. * number of endpoints on it, and not all of them have to be connected
  327. * to anything.
  328. */
  329. endpointsByElement = {},
  330. endpointsByUUID = {},
  331. offsets = {},
  332. offsetTimestamps = {},
  333. floatingConnections = {},
  334. draggableStates = {},
  335. _mouseEventsEnabled = this.Defaults.MouseEventsEnabled,
  336. _draggableByDefault = true,
  337. canvasList = [],
  338. sizes = [],
  339. listeners = {}, // a map: keys are event types, values are lists of listeners.
  340. DEFAULT_SCOPE = this.Defaults.Scope,
  341. renderMode = null, // will be set in init()
  342. /**
  343. * helper method to add an item to a list, creating the list if it does
  344. * not yet exist.
  345. */
  346. _addToList = function(map, key, value) {
  347. var l = map[key];
  348. if (l == null) {
  349. l = [];
  350. map[key] = l;
  351. }
  352. l.push(value);
  353. return l;
  354. },
  355. /**
  356. * appends an element to the given parent, or the document body if no
  357. * parent given.
  358. */
  359. _appendElement = function(el, parent) {
  360. if (!parent)
  361. document.body.appendChild(el);
  362. else
  363. jsPlumb.CurrentLibrary.appendElement(el, parent);
  364. },
  365. /**
  366. * creates a timestamp, using milliseconds since 1970, but as a string.
  367. */
  368. _timestamp = function() { return "" + (new Date()).getTime(); },
  369. /**
  370. * YUI, for some reason, put the result of a Y.all call into an object that contains
  371. * a '_nodes' array, instead of handing back an array-like object like the other
  372. * libraries do.
  373. */
  374. _convertYUICollection = function(c) {
  375. return c._nodes ? c._nodes : c;
  376. },
  377. /**
  378. * Draws an endpoint and its connections.
  379. *
  380. * @param element element to draw (of type library specific element object)
  381. * @param ui UI object from current library's event system. optional.
  382. * @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  383. */
  384. _draw = function(element, ui, timestamp) {
  385. var id = _getAttribute(element, "id");
  386. var endpoints = endpointsByElement[id];
  387. if (!timestamp) timestamp = _timestamp();
  388. if (endpoints) {
  389. _updateOffset( { elId : id, offset : ui, recalc : false, timestamp : timestamp }); // timestamp is checked against last update cache; it is
  390. // valid for one paint cycle.
  391. var myOffset = offsets[id], myWH = sizes[id];
  392. for ( var i = 0; i < endpoints.length; i++) {
  393. endpoints[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  394. var l = endpoints[i].connections;
  395. for ( var j = 0; j < l.length; j++) {
  396. l[j].paint( { elId : id, ui : ui, recalc : false, timestamp : timestamp }); // ...paint each connection.
  397. // then, check for dynamic endpoint; need to repaint it.
  398. var oIdx = l[j].endpoints[0] == endpoints[i] ? 1 : 0;
  399. if (l[j].endpoints[oIdx].anchor.isDynamic && !l[j].endpoints[oIdx].isFloating()) {
  400. var oId = oIdx == 0 ? l[j].sourceId : l[j].targetId,
  401. oOffset = offsets[oId], oWH = sizes[oId],
  402. // TODO i still want to make this faster.
  403. anchorLoc = l[j].endpoints[oIdx].anchor.compute( {
  404. xy : [ oOffset.left, oOffset.top ],
  405. wh : oWH,
  406. element : l[j].endpoints[oIdx],
  407. txy : [ myOffset.left, myOffset.top ],
  408. twh : myWH,
  409. tElement : endpoints[i]
  410. });
  411. l[j].endpoints[oIdx].paint({ anchorLoc : anchorLoc });
  412. }
  413. }
  414. }
  415. }
  416. },
  417. /**
  418. * executes the given function against the given element if the first
  419. * argument is an object, or the list of elements, if the first argument
  420. * is a list. the function passed in takes (element, elementId) as
  421. * arguments.
  422. */
  423. _elementProxy = function(element, fn) {
  424. var retVal = null;
  425. if (element.constructor == Array) {
  426. retVal = [];
  427. for ( var i = 0; i < element.length; i++) {
  428. var el = _getElementObject(element[i]), id = _getAttribute(el, "id");
  429. retVal.push(fn(el, id)); // append return values to what we will return
  430. }
  431. } else {
  432. var el = _getElementObject(element), id = _getAttribute(el, "id");
  433. retVal = fn(el, id);
  434. }
  435. return retVal;
  436. },
  437. /**
  438. * gets an Endpoint by uuid.
  439. */
  440. _getEndpoint = function(uuid) { return endpointsByUUID[uuid]; },
  441. /**
  442. * inits a draggable if it's not already initialised.
  443. */
  444. _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  445. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  446. if (draggable) {
  447. if (jsPlumb.CurrentLibrary.isDragSupported(element) && !jsPlumb.CurrentLibrary.isAlreadyDraggable(element)) {
  448. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  449. options = jsPlumb.extend( {}, options); // make a copy.
  450. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  451. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  452. options[dragEvent] = _wrap(options[dragEvent], function() {
  453. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  454. _draw(element, ui);
  455. _addClass(element, "jsPlumb_dragged");
  456. });
  457. options[stopEvent] = _wrap(options[stopEvent], function() {
  458. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  459. _draw(element, ui);
  460. _removeClass(element, "jsPlumb_dragged");
  461. });
  462. var draggable = draggableStates[_getId(element)];
  463. options.disabled = draggable == null ? false : !draggable;
  464. jsPlumb.CurrentLibrary.initDraggable(element, options);
  465. }
  466. }
  467. },
  468. _newConnection = function(params) {
  469. var connectionFunc = jsPlumb.Defaults.ConnectionType || Connection,
  470. endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint,
  471. parent = jsPlumb.CurrentLibrary.getParent;
  472. if (params.sourceEndpoint)
  473. params["parent"] = params.sourceEndpoint.parent;
  474. else if (params.source.constructor == endpointFunc)
  475. params["parent"] = params.source.parent;
  476. else params["parent"] = parent(params.source);
  477. params["_jsPlumb"] = _currentInstance;
  478. var con = new connectionFunc(params);
  479. _eventFireProxy("click", "click", con);
  480. _eventFireProxy("dblclick", "dblclick", con);
  481. return con;
  482. },
  483. _eventFireProxy = function(event, proxyEvent, obj) {
  484. obj.bind(event, function(e) {
  485. _currentInstance.fire(proxyEvent, obj, e);
  486. });
  487. },
  488. _newEndpoint = function(params) {
  489. var endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint;
  490. params["parent"] = jsPlumb.CurrentLibrary.getParent(params.source);
  491. params["_jsPlumb"] = _currentInstance,
  492. ep = new endpointFunc(params);
  493. _eventFireProxy("click", "endpointClick", ep);
  494. _eventFireProxy("dblclick", "endpointDblClick", ep);
  495. return ep;
  496. },
  497. /**
  498. * performs the given function operation on all the connections found
  499. * for the given element id; this means we find all the endpoints for
  500. * the given element, and then for each endpoint find the connectors
  501. * connected to it. then we pass each connection in to the given
  502. * function.
  503. */
  504. _operation = function(elId, func) {
  505. var endpoints = endpointsByElement[elId];
  506. if (endpoints && endpoints.length) {
  507. for ( var i = 0; i < endpoints.length; i++) {
  508. for ( var j = 0; j < endpoints[i].connections.length; j++) {
  509. var retVal = func(endpoints[i].connections[j]);
  510. // if the function passed in returns true, we exit.
  511. // most functions return false.
  512. if (retVal) return;
  513. }
  514. }
  515. }
  516. },
  517. /**
  518. * perform an operation on all elements.
  519. */
  520. _operationOnAll = function(func) {
  521. for ( var elId in endpointsByElement) {
  522. _operation(elId, func);
  523. }
  524. },
  525. /**
  526. * helper to remove an element from the DOM.
  527. */
  528. _removeElement = function(element, parent) {
  529. if (element != null && element.parentNode != null) {
  530. element.parentNode.removeChild(element);
  531. }
  532. },
  533. /**
  534. * helper to remove a list of elements from the DOM.
  535. */
  536. _removeElements = function(elements, parent) {
  537. for ( var i = 0; i < elements.length; i++)
  538. _removeElement(elements[i], parent);
  539. },
  540. /**
  541. * helper method to remove an item from a list.
  542. */
  543. _removeFromList = function(map, key, value) {
  544. if (key != null) {
  545. var l = map[key];
  546. if (l != null) {
  547. var i = _findIndex(l, value);
  548. if (i >= 0) {
  549. delete (l[i]);
  550. l.splice(i, 1);
  551. return true;
  552. }
  553. }
  554. }
  555. return false;
  556. },
  557. /**
  558. * Sets whether or not the given element(s) should be draggable,
  559. * regardless of what a particular plumb command may request.
  560. *
  561. * @param element
  562. * May be a string, a element objects, or a list of
  563. * strings/elements.
  564. * @param draggable
  565. * Whether or not the given element(s) should be draggable.
  566. */
  567. _setDraggable = function(element, draggable) {
  568. return _elementProxy(element, function(el, id) {
  569. draggableStates[id] = draggable;
  570. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  571. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  572. }
  573. });
  574. },
  575. /**
  576. * private method to do the business of hiding/showing.
  577. *
  578. * @param el
  579. * either Id of the element in question or a library specific
  580. * object for the element.
  581. * @param state
  582. * String specifying a value for the css 'display' property
  583. * ('block' or 'none').
  584. */
  585. _setVisible = function(el, state) {
  586. _operation(_getAttribute(el, "id"), function(jpc) {
  587. jpc.canvas.style.display = state;
  588. });
  589. },
  590. /**
  591. * toggles the draggable state of the given element(s).
  592. *
  593. * @param el
  594. * either an id, or an element object, or a list of
  595. * ids/element objects.
  596. */
  597. _toggleDraggable = function(el) {
  598. return _elementProxy(el, function(el, elId) {
  599. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  600. state = !state;
  601. draggableStates[elId] = state;
  602. jsPlumb.CurrentLibrary.setDraggable(el, state);
  603. return state;
  604. });
  605. },
  606. /**
  607. * private method to do the business of toggling hiding/showing.
  608. *
  609. * @param elId
  610. * Id of the element in question
  611. */
  612. _toggleVisible = function(elId) {
  613. _operation(elId, function(jpc) {
  614. var state = ('none' == jpc.canvas.style.display);
  615. jpc.canvas.style.display = state ? "block" : "none";
  616. });
  617. // todo this should call _elementProxy, and pass in the
  618. // _operation(elId, f) call as a function. cos _toggleDraggable does
  619. // that.
  620. },
  621. /**
  622. * updates the offset and size for a given element, and stores the
  623. * values. if 'offset' is not null we use that (it would have been
  624. * passed in from a drag call) because it's faster; but if it is null,
  625. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  626. */
  627. _updateOffset = function(params) {
  628. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId;
  629. if (!recalc) {
  630. if (timestamp && timestamp === offsetTimestamps[elId])
  631. return offsets[elId];
  632. }
  633. if (recalc || offset == null) { // if forced repaint or no offset
  634. // available, we recalculate.
  635. // get the current size and offset, and store them
  636. var s = _getElementObject(elId);
  637. if (s != null) {
  638. sizes[elId] = _getSize(s);
  639. offsets[elId] = _getOffset(s);
  640. offsetTimestamps[elId] = timestamp;
  641. }
  642. } else {
  643. offsets[elId] = offset;
  644. }
  645. return offsets[elId];
  646. },
  647. /**
  648. * gets an id for the given element, creating and setting one if
  649. * necessary.
  650. */
  651. _getId = function(element, uuid) {
  652. var ele = _getElementObject(element);
  653. var id = _getAttribute(ele, "id");
  654. if (!id || id == "undefined") {
  655. // check if fixed uuid parameter is given
  656. if (arguments.length == 2 && arguments[1] != undefined)
  657. id = uuid;
  658. else
  659. id = "jsPlumb_" + _timestamp();
  660. _setAttribute(ele, "id", id);
  661. }
  662. return id;
  663. },
  664. /**
  665. * wraps one function with another, creating a placeholder for the
  666. * wrapped function if it was null. this is used to wrap the various
  667. * drag/drop event functions - to allow jsPlumb to be notified of
  668. * important lifecycle events without imposing itself on the user's
  669. * drag/drop functionality. TODO: determine whether or not we should
  670. * support an error handler concept, if one of the functions fails.
  671. *
  672. * @param wrappedFunction original function to wrap; may be null.
  673. * @param newFunction function to wrap the original with.
  674. * @param returnOnThisValue Optional. Indicates that the wrappedFunction should
  675. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  676. * note that this is a simple comparison and only works for primitives right now.
  677. */
  678. _wrap = function(wrappedFunction, newFunction, returnOnThisValue) {
  679. wrappedFunction = wrappedFunction || function() { };
  680. newFunction = newFunction || function() { };
  681. return function() {
  682. var r = null;
  683. try {
  684. r = newFunction.apply(this, arguments);
  685. } catch (e) {
  686. _log(_currentInstance, 'jsPlumb function failed : ' + e);
  687. }
  688. if (returnOnThisValue == null || (r !== returnOnThisValue)) {
  689. try {
  690. wrappedFunction.apply(this, arguments);
  691. } catch (e) {
  692. _log(_currentInstance, 'wrapped function failed : ' + e);
  693. }
  694. }
  695. return r;
  696. };
  697. };
  698. /*
  699. * Property: connectorClass
  700. * 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.
  701. */
  702. this.connectorClass = "_jsPlumb_connector";
  703. /*
  704. * Property: endpointClass
  705. * 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.
  706. */
  707. this.endpointClass = "_jsPlumb_endpoint";
  708. /*
  709. * Property: overlayClass
  710. * 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.
  711. */
  712. this.overlayClass = "_jsPlumb_overlay";
  713. this.Anchors = {};
  714. this.Connectors = {
  715. "canvas":{},
  716. "svg":{},
  717. "vml":{}
  718. };
  719. this.Endpoints = {
  720. "canvas":{},
  721. "svg":{},
  722. "vml":{}
  723. };
  724. this.Overlays = {
  725. "canvas":{},
  726. "svg":{},
  727. "vml":{}
  728. };
  729. // ************************ PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS *****************************************
  730. /*
  731. * Function: bind
  732. * Bind to an event on jsPlumb.
  733. *
  734. * Parameters:
  735. * event - the event to bind. Available events on jsPlumb are:
  736. * - *jsPlumbConnection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
  737. * - *jsPlumbConnectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
  738. * - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
  739. * - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
  740. * - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
  741. * - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
  742. *
  743. * callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
  744. */
  745. /*
  746. * Function: clearListeners
  747. * Clears either all listeners, or listeners for some specific event.
  748. *
  749. * Parameters:
  750. * event - optional. constrains the clear to just listeners for this event.
  751. */
  752. // *************** END OF PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS ***********************************************************
  753. /*
  754. Function: addEndpoint
  755. Adds an <Endpoint> to a given element or elements.
  756. Parameters:
  757. el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  758. params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
  759. referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
  760. shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
  761. this object are anything that 'params' can contain. See <Endpoint>.
  762. Returns:
  763. The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
  764. See Also:
  765. <addEndpoints>
  766. */
  767. this.addEndpoint = function(el, params, referenceParams) {
  768. referenceParams = referenceParams || {};
  769. var p = jsPlumb.extend({}, referenceParams);
  770. jsPlumb.extend(p, params);
  771. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
  772. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  773. // YUI wrapper
  774. el = _convertYUICollection(el);
  775. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  776. for (var i = 0; i < inputs.length; i++) {
  777. var _el = _getElementObject(inputs[i]), id = _getId(_el);
  778. p.source = _el;
  779. _updateOffset({ elId : id });
  780. var e = _newEndpoint(p);
  781. _addToList(endpointsByElement, id, e);
  782. var myOffset = offsets[id], myWH = sizes[id];
  783. var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e });
  784. e.paint({ anchorLoc : anchorLoc });
  785. results.push(e);
  786. }
  787. return results.length == 1 ? results[0] : results;
  788. };
  789. /*
  790. Function: addEndpoints
  791. Adds a list of <Endpoint>s to a given element or elements.
  792. Parameters:
  793. target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  794. endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
  795. 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.
  796. Returns:
  797. List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
  798. See Also:
  799. <addEndpoint>
  800. */
  801. this.addEndpoints = function(el, endpoints, referenceParams) {
  802. var results = [];
  803. for ( var i = 0; i < endpoints.length; i++) {
  804. var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
  805. if (e.constructor == Array)
  806. Array.prototype.push.apply(results, e);
  807. else results.push(e);
  808. }
  809. return results;
  810. };
  811. /*
  812. Function: animate
  813. This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
  814. 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
  815. 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.
  816. Parameters:
  817. el - Element to animate. Either an id, or a selector representing the element.
  818. properties - The 'properties' argument you want passed to the library's animate call.
  819. options - The 'options' argument you want passed to the library's animate call.
  820. Returns:
  821. void
  822. */
  823. this.animate = function(el, properties, options) {
  824. var ele = _getElementObject(el), id = _getAttribute(el, "id");
  825. options = options || {};
  826. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  827. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  828. options[stepFunction] = _wrap(options[stepFunction], function() {
  829. _currentInstance.repaint(id);
  830. });
  831. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  832. options[completeFunction] = _wrap(options[completeFunction],
  833. function() {
  834. _currentInstance.repaint(id);
  835. });
  836. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  837. };
  838. /*
  839. Function: connect
  840. Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
  841. Parameters:
  842. params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
  843. referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
  844. Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
  845. Returns:
  846. The newly created <Connection>.
  847. */
  848. this.connect = function(params, referenceParams) {
  849. var _p = jsPlumb.extend( {}, params);
  850. if (referenceParams) jsPlumb.extend(_p, referenceParams);
  851. if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source;
  852. if (_p.source && _p.target.endpoint) _p.targetEndpoint = _p.target;
  853. // test for endpoint uuids to connect
  854. if (params.uuids) {
  855. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  856. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  857. }
  858. // now ensure that if we do have Endpoints already, they're not full.
  859. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  860. _log(_currentInstance, "could not add connection; source endpoint is full");
  861. return;
  862. }
  863. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  864. _log(_currentInstance, "could not add connection; target endpoint is full");
  865. return;
  866. }
  867. // dynamic anchors. backwards compatibility here: from 1.2.6 onwards you don't need to specify "dynamicAnchors". the fact that some anchor consists
  868. // of multiple definitions is enough to tell jsPlumb you want it to be dynamic.
  869. if (_p.dynamicAnchors) {
  870. // these can either be an array of anchor coords, which we will use for both source and target, or an object with {source:[anchors], target:[anchors]}, in which
  871. // case we will use a different set for each element.
  872. var a = _p.dynamicAnchors.constructor == Array;
  873. var sa = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.source));
  874. var ta = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.target));
  875. _p.anchors = [sa,ta];
  876. }
  877. var jpc = _newConnection(_p);
  878. // add to list of connections (by scope).
  879. _addToList(connectionsByScope, jpc.scope, jpc);
  880. // fire an event
  881. _currentInstance.fire("jsPlumbConnection", {
  882. connection:jpc,
  883. source : jpc.source, target : jpc.target,
  884. sourceId : jpc.sourceId, targetId : jpc.targetId,
  885. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  886. });
  887. // force a paint
  888. _draw(jpc.source);
  889. return jpc;
  890. };
  891. /*
  892. Function: deleteEndpoint
  893. Deletes an Endpoint and removes all Connections it has (which removes the Connections from the other Endpoints involved too)
  894. Parameters:
  895. object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
  896. Returns:
  897. void
  898. */
  899. this.deleteEndpoint = function(object) {
  900. var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object;
  901. if (endpoint) {
  902. var uuid = endpoint.getUuid();
  903. if (uuid) endpointsByUUID[uuid] = null;
  904. endpoint.detachAll();
  905. _removeElement(endpoint.canvas, endpoint.parent);
  906. // remove from endpointsbyElement
  907. for (var e in endpointsByElement) {
  908. var endpoints = endpointsByElement[e];
  909. if (endpoints) {
  910. var newEndpoints = [];
  911. for (var i = 0; i < endpoints.length; i++)
  912. if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
  913. endpointsByElement[e] = newEndpoints;
  914. }
  915. }
  916. delete endpoint;
  917. }
  918. };
  919. /*
  920. Function: deleteEveryEndpoint
  921. Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
  922. between this method and jsPlumb.reset).
  923. Returns:
  924. void
  925. */
  926. this.deleteEveryEndpoint = function() {
  927. for ( var id in endpointsByElement) {
  928. var endpoints = endpointsByElement[id];
  929. if (endpoints && endpoints.length) {
  930. for ( var i = 0; i < endpoints.length; i++) {
  931. _currentInstance.deleteEndpoint(endpoints[i]);
  932. }
  933. }
  934. }
  935. delete endpointsByElement;
  936. endpointsByElement = {};
  937. delete endpointsByUUID;
  938. endpointsByUUID = {};
  939. };
  940. var fireDetachEvent = function(jpc) {
  941. _currentInstance.fire("jsPlumbConnectionDetached", {
  942. connection:jpc,
  943. source : jpc.source, target : jpc.target,
  944. sourceId : jpc.sourceId, targetId : jpc.targetId,
  945. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  946. });
  947. };
  948. /*
  949. Function: detach
  950. Detaches and then removes a <Connection>. Takes either (source, target) (the old way, maintained for backwards compatibility), or a params
  951. object with various possible values.
  952. Parameters:
  953. source - id or element object of the first element in the Connection.
  954. target - id or element object of the second element in the Connection.
  955. params - a JS object containing the same parameters as you pass to jsPlumb.connect. If this is present then neither source nor
  956. target should be present; it should be the only argument to the method. See the docs for <Connection>'s constructor for information
  957. about the parameters allowed in the params object.
  958. Returns:
  959. true if successful, false if not.
  960. */
  961. this.detach = function(source, target) {
  962. if (arguments.length == 2) {
  963. var s = _getElementObject(source), sId = _getId(s);
  964. var t = _getElementObject(target), tId = _getId(t);
  965. _operation(sId, function(jpc) {
  966. if ((jpc.sourceId == sId && jpc.targetId == tId) || (jpc.targetId == sId && jpc.sourceId == tId)) {
  967. _removeElements(jpc.connector.getDisplayElements(), jpc.parent);
  968. jpc.endpoints[0].removeConnection(jpc);
  969. jpc.endpoints[1].removeConnection(jpc);
  970. _removeFromList(connectionsByScope, jpc.scope, jpc);
  971. }
  972. });
  973. }
  974. // this is the new version of the method, taking a JS object like
  975. // the connect method does.
  976. else if (arguments.length == 1) {
  977. // TODO investigate whether or not this code still works when a user has supplied their own subclass of Connection. i suspect it may not.
  978. if (arguments[0].constructor == Connection) {
  979. arguments[0].endpoints[0].detachFrom(arguments[0].endpoints[1]);
  980. }
  981. else if (arguments[0].connection) {
  982. arguments[0].connection.endpoints[0].detachFrom(arguments[0].connection.endpoints[1]);
  983. }
  984. else {
  985. var _p = jsPlumb.extend( {}, source); // a backwards compatibility hack: source should be thought of as 'params' in this case.
  986. // test for endpoint uuids to detach
  987. if (_p.uuids) {
  988. _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]));
  989. } else if (_p.sourceEndpoint && _p.targetEndpoint) {
  990. _p.sourceEndpoint.detachFrom(_p.targetEndpoint);
  991. } else {
  992. var sourceId = _getId(_p.source);
  993. var targetId = _getId(_p.target);
  994. _operation(sourceId, function(jpc) {
  995. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  996. _removeElements(jpc.connector.getDisplayElements(), jpc.parent);
  997. jpc.endpoints[0].removeConnection(jpc);
  998. jpc.endpoints[1].removeConnection(jpc);
  999. _removeFromList(connectionsByScope, jpc.scope, jpc);
  1000. }
  1001. });
  1002. }
  1003. }
  1004. }
  1005. };
  1006. /*
  1007. Function: detachAll
  1008. Removes all an element's Connections.
  1009. Parameters:
  1010. el - either the id of the element, or a selector for the element.
  1011. Returns:
  1012. void
  1013. */
  1014. this.detachAllConnections = function(el) {
  1015. var id = _getAttribute(el, "id");
  1016. var endpoints = endpointsByElement[id];
  1017. if (endpoints && endpoints.length) {
  1018. for ( var i = 0; i < endpoints.length; i++) {
  1019. endpoints[i].detachAll();
  1020. }
  1021. }
  1022. };
  1023. /**
  1024. * @deprecated Use detachAllConnections instead. this will be removed in jsPlumb 1.3.
  1025. */
  1026. this.detachAll = this.detachAllConnections;
  1027. /*
  1028. Function: detachEveryConnection
  1029. Remove all Connections from all elements, but leaves Endpoints in place.
  1030. Returns:
  1031. void
  1032. See Also:
  1033. <removeEveryEndpoint>
  1034. */
  1035. this.detachEveryConnection = function() {
  1036. for ( var id in endpointsByElement) {
  1037. var endpoints = endpointsByElement[id];
  1038. if (endpoints && endpoints.length) {
  1039. for ( var i = 0; i < endpoints.length; i++) {
  1040. endpoints[i].detachAll();
  1041. }
  1042. }
  1043. }
  1044. delete connectionsByScope;
  1045. connectionsByScope = {};
  1046. };
  1047. /**
  1048. * @deprecated use detachEveryConnection instead. this will be removed in jsPlumb 1.3.
  1049. */
  1050. this.detachEverything = this.detachEveryConnection;
  1051. /*
  1052. Function: draggable
  1053. Initialises the draggability of some element or elements. You should use this instead of you library's draggable method so that jsPlumb can setup the appropriate callbacks. Your underlying library's drag method is always called from this method.
  1054. Parameters:
  1055. el - either an element id, a list of element ids, or a selector.
  1056. options - options to pass through to the underlying library
  1057. Returns:
  1058. void
  1059. */
  1060. this.draggable = function(el, options) {
  1061. if (typeof el == 'object' && el.length) {
  1062. for ( var i = 0; i < el.length; i++) {
  1063. var ele = _getElementObject(el[i]);
  1064. if (ele) _initDraggableIfNecessary(ele, true, options);
  1065. }
  1066. }
  1067. else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced
  1068. // into the library adapters (for jquery and mootools aswell)
  1069. for ( var i = 0; i < el._nodes.length; i++) {
  1070. var ele = _getElementObject(el._nodes[i]);
  1071. if (ele) _initDraggableIfNecessary(ele, true, options);
  1072. }
  1073. }
  1074. else {
  1075. var ele = _getElementObject(el);
  1076. if (ele) _initDraggableIfNecessary(ele, true, options);
  1077. }
  1078. };
  1079. /*
  1080. Function: extend
  1081. Wraps the underlying library's extend functionality.
  1082. Parameters:
  1083. o1 - object to extend
  1084. o2 - object to extend o1 with
  1085. Returns:
  1086. o1, extended with all properties from o2.
  1087. */
  1088. this.extend = function(o1, o2) {
  1089. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1090. };
  1091. /*
  1092. * Function: getDefaultEndpointType
  1093. * Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
  1094. * you would make a call like this in your class's constructor:
  1095. * jsPlumb.getDefaultEndpointType().apply(this, arguments);
  1096. *
  1097. * Returns:
  1098. * the default Endpoint function used by jsPlumb.
  1099. */
  1100. this.getDefaultEndpointType = function() {
  1101. return Endpoint;
  1102. };
  1103. /*
  1104. * Function: getDefaultConnectionType
  1105. * Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
  1106. * you would make a call like this in your class's constructor:
  1107. * jsPlumb.getDefaultConnectionType().apply(this, arguments);
  1108. *
  1109. * Returns:
  1110. * the default Connection function used by jsPlumb.
  1111. */
  1112. this.getDefaultConnectionType = function() {
  1113. return Connection;
  1114. };
  1115. /*
  1116. * Function: getConnections
  1117. * Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
  1118. * 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
  1119. * default scope). If multiple scopes are passed in, the return value will be a map of { scope -> [ connection... ] }.
  1120. *
  1121. * Parameters
  1122. * scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
  1123. * of connections that are in the given scope.
  1124. * options - if the argument is a JS object, you can specify a finer-grained filter:
  1125. *
  1126. * - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes.
  1127. * - *source* either a string representing an element id, or a selector. constrains the result to connections having this source.
  1128. * - *target* either a string representing an element id, or a selector. constrains the result to connections having this target.
  1129. *
  1130. */
  1131. this.getConnections = function(options) {
  1132. if (!options) {
  1133. options = {};
  1134. } else if (options.constructor == String) {
  1135. options = { "scope": options };
  1136. }
  1137. var prepareList = function(input) {
  1138. var r = [];
  1139. if (input) {
  1140. if (typeof input == 'string')
  1141. r.push(input);
  1142. else
  1143. r = input;
  1144. }
  1145. return r;
  1146. };
  1147. var scope = options.scope || jsPlumb.getDefaultScope(),
  1148. scopes = prepareList(scope),
  1149. sources = prepareList(options.source),
  1150. targets = prepareList(options.target),
  1151. filter = function(list, value) {
  1152. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1153. },
  1154. results = scopes.length > 1 ? {} : [],
  1155. _addOne = function(scope, obj) {
  1156. if (scopes.length > 1) {
  1157. var ss = results[scope];
  1158. if (ss == null) {
  1159. ss = []; results[scope] = ss;
  1160. }
  1161. ss.push(obj);
  1162. } else results.push(obj);
  1163. };
  1164. for ( var i in connectionsByScope) {
  1165. if (filter(scopes, i)) {
  1166. for ( var j = 0; j < connectionsByScope[i].length; j++) {
  1167. var c = connectionsByScope[i][j];
  1168. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1169. _addOne(i, c);
  1170. }
  1171. }
  1172. }
  1173. return results;
  1174. };
  1175. /*
  1176. * Function: getAllConnections
  1177. * Gets all connections, as a map of { scope -> [ connection... ] }.
  1178. */
  1179. this.getAllConnections = function() {
  1180. return connectionsByScope;
  1181. };
  1182. /*
  1183. * Function: getDefaultScope
  1184. * Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a
  1185. * scope to an endpoint or connection allows you to support different
  1186. * types of connections in the same UI. but if you're only interested in
  1187. * one type of connection, you don't need to supply a scope. this method
  1188. * will probably be used by very few people; it's good for testing
  1189. * though.
  1190. */
  1191. this.getDefaultScope = function() {
  1192. return DEFAULT_SCOPE;
  1193. };
  1194. /*
  1195. Function: getEndpoint
  1196. Gets an Endpoint by UUID
  1197. Parameters:
  1198. uuid - the UUID for the Endpoint
  1199. Returns:
  1200. Endpoint with the given UUID, null if nothing found.
  1201. */
  1202. this.getEndpoint = _getEndpoint;
  1203. /**
  1204. * Function:getEndpoints
  1205. * Gets the list of Endpoints for a given selector, or element id.
  1206. * @param el
  1207. * @return
  1208. */
  1209. this.getEndpoints = function(el) {
  1210. return endpointsByElement[_getId(el)];
  1211. };
  1212. /*
  1213. * Gets an element's id, creating one if necessary. really only exposed
  1214. * for the lib-specific functionality to access; would be better to pass
  1215. * the current instance into the lib-specific code (even though this is
  1216. * a static call. i just don't want to expose it to the public API).
  1217. */
  1218. this.getId = _getId;
  1219. this.appendElement = _appendElement;
  1220. /*
  1221. Function: hide
  1222. Sets an element's connections to be hidden.
  1223. Parameters:
  1224. el - either the id of the element, or a selector for the element.
  1225. Returns:
  1226. void
  1227. */
  1228. this.hide = function(el) {
  1229. _setVisible(el, "none");
  1230. };
  1231. /**
  1232. * callback from the current library to tell us to prepare ourselves (attach
  1233. * mouse listeners etc; can't do that until the library has provided a bind method)
  1234. * @return
  1235. */
  1236. this.init = function() {
  1237. if (!initialized) {
  1238. _currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run.
  1239. var _bind = function(event) {
  1240. jsPlumb.CurrentLibrary.bind(document, event, function(e) {
  1241. if (!_currentInstance.currentlyDragging && _mouseEventsEnabled && renderMode == jsPlumb.CANVAS) {
  1242. // try connections first
  1243. for (var scope in connectionsByScope) {
  1244. var c = connectionsByScope[scope];
  1245. for (var i = 0; i < c.length; i++) {
  1246. var t = c[i].connector[event](e);
  1247. if (t) return;
  1248. }
  1249. }
  1250. for (var el in endpointsByElement) {
  1251. var ee = endpointsByElement[el];
  1252. for (var i = 0; i < ee.length; i++) {
  1253. if (ee[i].endpoint[event](e)) return;
  1254. }
  1255. }
  1256. }
  1257. });
  1258. };
  1259. _bind("click");
  1260. _bind("dblclick");
  1261. _bind("mousemove");
  1262. _bind("mousedown");
  1263. _bind("mouseup");
  1264. initialized = true;
  1265. _currentInstance.fire("ready");
  1266. }
  1267. };
  1268. this.jsPlumbUIComponent = jsPlumbUIComponent;
  1269. this.EventGenerator = EventGenerator;
  1270. /*
  1271. * Creates an anchor with the given params.
  1272. *
  1273. * You do not need to use this method. It is exposed because of the way jsPlumb is
  1274. * split into three scripts; this will change in the future.
  1275. *
  1276. * x - the x location of the anchor as a fraction of the
  1277. * total width. y - the y location of the anchor as a fraction of the
  1278. * total height. xOrientation - value indicating the general direction a
  1279. * connection from the anchor should go in, in the x direction.
  1280. * yOrientation - value indicating the general direction a connection
  1281. * from the anchor should go in, in the y direction. xOffset - a fixed
  1282. * offset that should be applied in the x direction that should be
  1283. * applied after the x position has been figured out. optional. defaults
  1284. * to 0. yOffset - a fixed offset that should be applied in the y
  1285. * direction that should be applied after the y position has been
  1286. * figured out. optional. defaults to 0.
  1287. * -- OR --
  1288. *
  1289. * params - {x:..., y:..., xOrientation etc }
  1290. * -- OR FROM 1.2.4 ---
  1291. *
  1292. * name - the name of some Anchor in the _currentInstance.Anchors array.
  1293. * -- OR FROM 1.2.4 ---
  1294. *
  1295. * coords - a list of coords for the anchor, like you would pass to
  1296. * jsPlumb.makeAnchor (eg [0.5,0.5,0,-1] - an anchor in the center of
  1297. * some element, oriented towards the top of the screen)
  1298. * -- OR FROM 1.2.4 ---
  1299. *
  1300. * anchor - an existing anchor. just gets passed back. it's handy
  1301. * internally to have this functionality.
  1302. *
  1303. * Returns: The newly created Anchor.
  1304. */
  1305. this.makeAnchor = function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1306. // backwards compatibility here. we used to require an object passed
  1307. // in but that makes the call very verbose. easier to use
  1308. // by just passing in four/six values. but for backwards
  1309. // compatibility if we are given only one value we assume it's a
  1310. // call in the old form.
  1311. if (arguments.length == 0) return null;
  1312. var params = {};
  1313. if (arguments.length == 1) {
  1314. var specimen = arguments[0];
  1315. // if it appears to be an anchor already...
  1316. if (specimen.compute && specimen.getOrientation) return specimen;
  1317. // is it the name of an anchor type?
  1318. else if (typeof specimen == "string") return _currentInstance.Anchors[arguments[0]]();
  1319. // is it an array of coordinates?
  1320. else if (specimen.constructor == Array) {
  1321. if (specimen[0].constructor == Array || specimen[0].constructor == String)
  1322. return new DynamicAnchor(specimen);
  1323. else
  1324. return jsPlumb.makeAnchor.apply(this, specimen);
  1325. }
  1326. // last we try the backwards compatibility stuff.
  1327. else if (typeof arguments[0] == "object") jsPlumb.extend(params, x);
  1328. } else {
  1329. params = { x : x, y : y };
  1330. if (arguments.length >= 4) params.orientation = [ arguments[2], arguments[3] ];
  1331. if (arguments.length == 6) params.offsets = [ arguments[4], arguments[5] ];
  1332. }
  1333. var a = new Anchor(params);
  1334. a.clone = function() {
  1335. return new Anchor(params);
  1336. };
  1337. return a;
  1338. };
  1339. /**
  1340. * makes a list of anchors from the given list of types or coords, eg
  1341. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  1342. */
  1343. this.makeAnchors = function(types) {
  1344. var r = [];
  1345. for ( var i = 0; i < types.length; i++)
  1346. if (typeof types[i] == "string")
  1347. r.push(_currentInstance.Anchors[types[i]]());
  1348. else if (types[i].constructor == Array)
  1349. r.push(jsPlumb.makeAnchor(types[i]));
  1350. return r;
  1351. };
  1352. /**
  1353. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  1354. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  1355. * not need to provide this - i think).
  1356. */
  1357. this.makeDynamicAnchor = function(anchors, anchorSelector) {
  1358. return new DynamicAnchor(anchors, anchorSelector);
  1359. };
  1360. /**
  1361. * Function: makeTarget
  1362. * Makes some DOM element a Connection target, allowing you to drag connections to it
  1363. * without having to register any Endpoints on it first. When a Connection is established,
  1364. * the endpoint spec that was passed in to this method is used to create a suitable
  1365. * Endpoint (the default will be used if you do not provide one).
  1366. *
  1367. * Parameters:
  1368. * el - string id or element selector for the element to make a target.
  1369. * params - JS object containing parameters:
  1370. * endpoint optional. specification of an endpoint to create when a connection is created.
  1371. * scope optional. scope for the drop zone.
  1372. * dropOptions optional. same stuff as you would pass to dropOptions of an Endpoint definition.
  1373. * deleteEndpointsOnDetach optional, defaults to false. whether or not to delete
  1374. * any Endpoints created by a connection to this target if
  1375. * the connection is subsequently detached. this will not
  1376. * remove Endpoints that have had more Connections attached
  1377. * to them after they were created.
  1378. *
  1379. *
  1380. */
  1381. this.makeTarget = function(el, params, referenceParams) {
  1382. var p = jsPlumb.extend({}, referenceParams);
  1383. jsPlumb.extend(p, params);
  1384. var jpcl = jsPlumb.CurrentLibrary,
  1385. scope = p.scope || _currentInstance.Defaults.Scope,
  1386. deleteEndpointsOnDetach = p.deleteEndpointsOnDetach || false,
  1387. _doOne = function(_el) {
  1388. var dropOptions = jsPlumb.extend({}, p.dropOptions || {});
  1389. var _drop = function() {
  1390. var draggable = _getElementObject(jpcl.getDragObject(arguments)),
  1391. id = _getAttribute(draggable, "dragId"),
  1392. // restore the original scope if necessary (issue 57)
  1393. scope = _getAttribute(draggable, "originalScope");
  1394. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  1395. // get the connection, to then get its endpoint
  1396. var jpc = floatingConnections[id],
  1397. source = jpc.endpoints[0],
  1398. _endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : null,
  1399. // make a new Endpoint
  1400. newEndpoint = jsPlumb.addEndpoint(_el, _endpoint);
  1401. var c = jsPlumb.connect({
  1402. source:source,
  1403. target:newEndpoint,
  1404. scope:scope
  1405. });
  1406. if (deleteEndpointsOnDetach)
  1407. c.endpointToDeleteOnDetach = newEndpoint;
  1408. };
  1409. var dropEvent = jpcl.dragEvents['drop'];
  1410. dropOptions["scope"] = dropOptions["scope"] || scope;
  1411. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop);
  1412. jpcl.initDroppable(_el, dropOptions);
  1413. };
  1414. el = _convertYUICollection(el);
  1415. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  1416. for (var i = 0; i < inputs.length; i++) {
  1417. _doOne(_getElementObject(inputs[i]));
  1418. }
  1419. };
  1420. /**
  1421. * helper method to make a list of elements drop targets.
  1422. * @param els
  1423. * @param params
  1424. * @param referenceParams
  1425. * @return
  1426. */
  1427. this.makeTargets = function(els, params, referenceParams) {
  1428. for ( var i = 0; i < els.length; i++) {
  1429. _currentInstance.makeTarget(els[i], params, referenceParams);
  1430. }
  1431. };
  1432. /*
  1433. Function: repaint
  1434. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1435. Parameters:
  1436. el - either the id of the element or a selector representing the element.
  1437. Returns:
  1438. void
  1439. See Also:
  1440. <repaintEverything>
  1441. */
  1442. this.repaint = function(el) {
  1443. var _processElement = function(el) { _draw(_getElementObject(el)); };
  1444. // support both lists...
  1445. if (typeof el == 'object')
  1446. for ( var i = 0; i < el.length; i++) _processElement(el[i]);
  1447. else // ...and single strings.
  1448. _processElement(el);
  1449. };
  1450. /*
  1451. Function: repaintEverything
  1452. Repaints all connections.
  1453. Returns:
  1454. void
  1455. See Also:
  1456. <repaint>
  1457. */
  1458. this.repaintEverything = function() {
  1459. var timestamp = _timestamp();
  1460. for ( var elId in endpointsByElement) {
  1461. _draw(_getElementObject(elId), null, timestamp);
  1462. }
  1463. };
  1464. /*
  1465. Function: removeAllEndpoints
  1466. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1467. Parameters:
  1468. el - either an element id, or a selector for an element.
  1469. Returns:
  1470. void
  1471. See Also:
  1472. <removeEndpoint>
  1473. */
  1474. this.removeAllEndpoints = function(el) {
  1475. var elId = _getAttribute(el, "id");
  1476. var ebe = endpointsByElement[elId];
  1477. for ( var i in ebe)
  1478. _currentInstance.deleteEndpoint(ebe[i]);
  1479. endpointsByElement[elId] = [];
  1480. };
  1481. /*
  1482. Removes every Endpoint in this instance of jsPlumb.
  1483. @deprecated use deleteEveryEndpoint instead
  1484. */
  1485. this.removeEveryEndpoint = this.deleteEveryEndpoint;
  1486. /*
  1487. Removes the given Endpoint from the given element.
  1488. @deprecated Use jsPlumb.deleteEndpoint instead (and note you dont need to supply the element. it's irrelevant).
  1489. */
  1490. this.removeEndpoint = function(el, endpoint) {
  1491. _currentInstance.deleteEndpoint(endpoint);
  1492. };
  1493. /*
  1494. Function:reset
  1495. Removes all endpoints and connections and clears the listener list. To keep listeners call jsPlumb.deleteEveryEndpoint instead of this.
  1496. */
  1497. this.reset = function() {
  1498. this.deleteEveryEndpoint();
  1499. this.clearListeners();
  1500. };
  1501. /*
  1502. Function: setAutomaticRepaint
  1503. Sets/unsets automatic repaint on window resize.
  1504. Parameters:
  1505. value - whether or not to automatically repaint when the window is resized.
  1506. Returns: void
  1507. */
  1508. this.setAutomaticRepaint = function(value) {
  1509. automaticRepaint = value;
  1510. };
  1511. /*
  1512. * Function: setDefaultScope
  1513. * Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
  1514. * scope to an Endpoint or Connection allows you to support different
  1515. * types of Connections in the same UI. If you're only interested in
  1516. * one type of Connection, you don't need to supply a scope. This method
  1517. * will probably be used by very few people; it just instructs jsPlumb
  1518. * to use a different key for the default scope.
  1519. *
  1520. * Parameters:
  1521. * scope - scope to set as default.
  1522. */
  1523. this.setDefaultScope = function(scope) {
  1524. DEFAULT_SCOPE = scope;
  1525. };
  1526. /*
  1527. * Function: setDraggable
  1528. * Sets whether or not a given element is
  1529. * draggable, regardless of what any jsPlumb command may request.
  1530. *
  1531. * Parameters:
  1532. * el - either the id for the element, or a selector representing the element.
  1533. *
  1534. * Returns:
  1535. * void
  1536. */
  1537. this.setDraggable = _setDraggable;
  1538. /*
  1539. * Function: setDraggableByDefault
  1540. * Sets whether or not elements are draggable by default. Default for this is true.
  1541. *
  1542. * Parameters:
  1543. * draggable - value to set
  1544. *
  1545. * Returns:
  1546. * void
  1547. */
  1548. this.setDraggableByDefault = function(draggable) {
  1549. _draggableByDefault = draggable;
  1550. };
  1551. this.setDebugLog = function(debugLog) {
  1552. log = debugLog;
  1553. };
  1554. /*
  1555. * Function: setRepaintFunction
  1556. * Sets the function to fire when the window size has changed and a repaint was fired.
  1557. *
  1558. * Parameters:
  1559. * f - Function to execute.
  1560. *
  1561. * Returns: void
  1562. */
  1563. this.setRepaintFunction = function(f) {
  1564. repaintFunction = f;
  1565. };
  1566. /*
  1567. * Function: setMouseEventsEnabled
  1568. * Sets whether or not mouse events are enabled. Default is true.
  1569. *
  1570. * Parameters:
  1571. * enabled - whether or not mouse events should be enabled.
  1572. *
  1573. * Returns:
  1574. * void
  1575. */
  1576. this.setMouseEventsEnabled = function(enabled) {
  1577. _mouseEventsEnabled = enabled;
  1578. };
  1579. /*
  1580. * Constant for use with the setRenderMode method
  1581. */
  1582. this.CANVAS = "canvas";
  1583. /*
  1584. * Constant for use with the setRenderMode method
  1585. */
  1586. this.SVG = "svg";
  1587. this.VML = "vml";
  1588. /*
  1589. * Function: setRenderMode
  1590. * Sets render mode: jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that
  1591. * what you asked for is not supported (and that VML is). If you asked for VML but the browser does
  1592. * not support it, jsPlumb uses SVG.
  1593. *
  1594. * Returns:
  1595. * the render mode that jsPlumb set, which of course may be different from that requested.
  1596. */
  1597. this.setRenderMode = function(mode) {
  1598. if (mode)
  1599. mode = mode.toLowerCase();
  1600. else
  1601. return;
  1602. if (mode !== jsPlumb.CANVAS && mode !== jsPlumb.SVG && mode !== jsPlumb.VML) throw new Error("render mode must be one of jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML");
  1603. // now test we actually have the capability to do this.
  1604. if (mode === jsPlumb.CANVAS && canvasAvailable)
  1605. renderMode = jsPlumb.CANVAS;
  1606. else if (mode === jsPlumb.SVG && svgAvailable)
  1607. renderMode = jsPlumb.SVG;
  1608. else if (vmlAvailable)
  1609. renderMode = jsPlumb.VML;
  1610. return renderMode;
  1611. };
  1612. this.getRenderMode = function() { return renderMode; };
  1613. /*
  1614. * Function: show
  1615. * Sets an element's connections to be visible.
  1616. *
  1617. * Parameters:
  1618. * el - either the id of the element, or a selector for the element.
  1619. *
  1620. * Returns:
  1621. * void
  1622. */
  1623. this.show = function(el) {
  1624. _setVisible(el, "block");
  1625. };
  1626. /*
  1627. * Function: sizeCanvas
  1628. * Helper to size a canvas. You would typically use
  1629. * this when writing your own Connector or Endpoint implementation.
  1630. *
  1631. * Parameters:
  1632. * x - [int] x position for the Canvas origin
  1633. * y - [int] y position for the Canvas origin
  1634. * w - [int] width of the canvas
  1635. * h - [int] height of the canvas
  1636. *
  1637. * Returns:
  1638. * void
  1639. */
  1640. this.sizeCanvas = function(canvas, x, y, w, h) {
  1641. if (canvas) {
  1642. canvas.style.height = h + "px";
  1643. canvas.height = h;
  1644. canvas.style.width = w + "px";
  1645. canvas.width = w;
  1646. canvas.style.left = x + "px";
  1647. canvas.style.top = y + "px";
  1648. }
  1649. };
  1650. /**
  1651. * gets some test hooks. nothing writable.
  1652. */
  1653. this.getTestHarness = function() {
  1654. return {
  1655. endpointsByElement : endpointsByElement,
  1656. endpointCount : function(elId) {
  1657. var e = endpointsByElement[elId];
  1658. return e ? e.length : 0;
  1659. },
  1660. connectionCount : function(scope) {
  1661. scope = scope || DEFAULT_SCOPE;
  1662. var c = connectionsByScope[scope];
  1663. return c ? c.length : 0;
  1664. },
  1665. findIndex : _findIndex,
  1666. getId : _getId,
  1667. makeAnchor:self.makeAnchor,
  1668. makeDynamicAnchor:self.makeDynamicAnchor
  1669. };
  1670. };
  1671. /**
  1672. * Toggles visibility of an element's connections. kept for backwards
  1673. * compatibility
  1674. */
  1675. this.toggle = _toggleVisible;
  1676. /*
  1677. * Function: toggleVisible
  1678. * Toggles visibility of an element's Connections.
  1679. *
  1680. * Parameters:
  1681. * el - either the element's id, or a selector representing the element.
  1682. *
  1683. * Returns:
  1684. * void, but should be updated to return the current state
  1685. */
  1686. // TODO: update this method to return the current state.
  1687. this.toggleVisible = _toggleVisible;
  1688. /*
  1689. * Function: toggleDraggable
  1690. * Toggles draggability (sic?) of an element's Connections.
  1691. *
  1692. * Parameters:
  1693. * el - either the element's id, or a selector representing the element.
  1694. *
  1695. * Returns:
  1696. * The current draggable state.
  1697. */
  1698. this.toggleDraggable = _toggleDraggable;
  1699. /*
  1700. * Function: unload
  1701. * Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element.
  1702. *
  1703. * Returns:
  1704. * void
  1705. */
  1706. this.unload = function() {
  1707. delete endpointsByElement;
  1708. delete endpointsByUUID;
  1709. delete offsets;
  1710. delete sizes;
  1711. delete floatingConnections;
  1712. delete draggableStates;
  1713. delete canvasList;
  1714. };
  1715. /*
  1716. * Helper method to wrap an existing function with one of
  1717. * your own. This is used by the various implementations to wrap event
  1718. * callbacks for drag/drop etc; it allows jsPlumb to be transparent in
  1719. * its handling of these things. If a user supplies their own event
  1720. * callback, for anything, it will always be called.
  1721. */
  1722. this.wrap = _wrap;
  1723. this.addListener = this.bind;
  1724. /**
  1725. * 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
  1726. * 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"),
  1727. * 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
  1728. * creation of Anchors without user intervention.
  1729. */
  1730. var Anchor = function(params) {
  1731. var self = this;
  1732. this.x = params.x || 0;
  1733. this.y = params.y || 0;
  1734. var orientation = params.orientation || [ 0, 0 ];
  1735. var lastTimestamp = null, lastReturnValue = null;
  1736. this.offsets = params.offsets || [ 0, 0 ];
  1737. self.timestamp = null;
  1738. this.compute = function(params) {
  1739. var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
  1740. if (timestamp && timestamp === self.timestamp) {
  1741. return lastReturnValue;
  1742. }
  1743. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  1744. if (element.canvas) {
  1745. var po = element.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(element.canvas.offsetParent);
  1746. lastReturnValue[0] = lastReturnValue[0] - po.left;
  1747. lastReturnValue[1] = lastReturnValue[1] - po.top;
  1748. }
  1749. self.timestamp = timestamp;
  1750. return lastReturnValue;
  1751. };
  1752. this.getOrientation = function() { return orientation; };
  1753. this.equals = function(anchor) {
  1754. if (!anchor) return false;
  1755. var ao = anchor.getOrientation();
  1756. var o = this.getOrientation();
  1757. return this.x == anchor.x && this.y == anchor.y
  1758. && this.offsets[0] == anchor.offsets[0]
  1759. && this.offsets[1] == anchor.offsets[1]
  1760. && o[0] == ao[0] && o[1] == ao[1];
  1761. };
  1762. this.getCurrentLocation = function() { return lastReturnValue; };
  1763. };
  1764. /**
  1765. * An Anchor that floats. its orientation is computed dynamically from
  1766. * its position relative to the anchor it is floating relative to. It is used when creating
  1767. * a connection through drag and drop.
  1768. *
  1769. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  1770. */
  1771. var FloatingAnchor = function(params) {
  1772. // this is the anchor that this floating anchor is referenced to for
  1773. // purposes of calculating the orientation.
  1774. var ref = params.reference;
  1775. // the canvas this refers to.
  1776. var refCanvas = params.referenceCanvas;
  1777. var size = _getSize(_getElementObject(refCanvas));
  1778. // these are used to store the current relative position of our
  1779. // anchor wrt the reference anchor. they only indicate
  1780. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  1781. // values are written by the compute method, and read
  1782. // by the getOrientation method.
  1783. var xDir = 0, yDir = 0;
  1784. // temporary member used to store an orientation when the floating
  1785. // anchor is hovering over another anchor.
  1786. var orientation = null;
  1787. var _lastResult = null;
  1788. this.compute = function(params) {
  1789. var xy = params.xy, element = params.element;
  1790. var 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.
  1791. if (element.canvas) {
  1792. var po = element.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(element.canvas.offsetParent);
  1793. result[0] = result[0] - po.left;
  1794. result[1] = result[1] - po.top;
  1795. }
  1796. _lastResult = result;
  1797. return result;
  1798. };
  1799. this.getOrientation = function() {
  1800. if (orientation) return orientation;
  1801. else {
  1802. var o = ref.getOrientation();
  1803. // here we take into account the orientation of the other
  1804. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  1805. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  1806. return [ Math.abs(o[0]) * xDir * -1,
  1807. Math.abs(o[1]) * yDir * -1 ];
  1808. }
  1809. };
  1810. /**
  1811. * notification the endpoint associated with this anchor is hovering
  1812. * over another anchor; we want to assume that anchor's orientation
  1813. * for the duration of the hover.
  1814. */
  1815. this.over = function(anchor) { orientation = anchor.getOrientation(); };
  1816. /**
  1817. * notification the endpoint associated with this anchor is no
  1818. * longer hovering over another anchor; we should resume calculating
  1819. * orientation as we normally do.
  1820. */
  1821. this.out = function() { orientation = null; };
  1822. this.getCurrentLocation = function() { return _lastResult; };
  1823. };
  1824. /*
  1825. * A DynamicAnchors is an Anchor that contains a list of other Anchors, which it cycles
  1826. * through at compute time to find the one that is located closest to
  1827. * the center of the target element, and returns that Anchor's compute
  1828. * method result. this causes endpoints to follow each other with
  1829. * respect to the orientation of their target elements, which is a useful
  1830. * feature for some applications.
  1831. *
  1832. */
  1833. var DynamicAnchor = function(anchors, anchorSelector) {
  1834. this.isSelective = true;
  1835. this.isDynamic = true;
  1836. var _anchors = [];
  1837. var _convert = function(anchor) { return anchor.constructor == Anchor ? anchor: jsPlumb.makeAnchor(anchor); };
  1838. for (var i = 0; i < anchors.length; i++) _anchors[i] = _convert(anchors[i]);
  1839. this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
  1840. this.getAnchors = function() { return _anchors; };
  1841. var _curAnchor = _anchors.length > 0 ? _anchors[0] : null;
  1842. var _curIndex = _anchors.length > 0 ? 0 : -1;
  1843. this.locked = false;
  1844. var self = this;
  1845. // helper method to calculate the distance between the centers of the two elements.
  1846. var _distance = function(anchor, cx, cy, xy, wh) {
  1847. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
  1848. return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
  1849. };
  1850. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  1851. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  1852. // xy - xy loc of the anchor's element
  1853. // wh - anchor's element's dimensions
  1854. // txy - xy loc of the element of the other anchor in the connection
  1855. // twh - dimensions of the element of the other anchor in the connection.
  1856. // anchors - the list of selectable anchors
  1857. var _anchorSelector = anchorSelector || function(xy, wh, txy, twh, anchors) {
  1858. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  1859. var minIdx = -1, minDist = Infinity;
  1860. for ( var i = 0; i < anchors.length; i++) {
  1861. var d = _distance(anchors[i], cx, cy, xy, wh);
  1862. if (d < minDist) {
  1863. minIdx = i + 0;
  1864. minDist = d;
  1865. }
  1866. }
  1867. return anchors[minIdx];
  1868. };
  1869. this.compute = function(params) {
  1870. var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
  1871. // if anchor is locked or an opposite element was not given, we
  1872. // maintain our state. anchor will be locked
  1873. // if it is the source of a drag and drop.
  1874. if (self.locked || txy == null || twh == null)
  1875. return _curAnchor.compute(params);
  1876. else
  1877. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  1878. _curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
  1879. var pos = _curAnchor.compute(params);
  1880. return pos;
  1881. };
  1882. this.getCurrentLocation = function() {
  1883. var cl = _curAnchor != null ? _curAnchor.getCurrentLocation() : null;
  1884. return cl;
  1885. };
  1886. this.getOrientation = function() { return _curAnchor != null ? _curAnchor.getOrientation() : [ 0, 0 ]; };
  1887. this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
  1888. this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
  1889. };
  1890. /*
  1891. * Class: Connection
  1892. * The connecting line between two Endpoints.
  1893. */
  1894. /*
  1895. * Function: Connection
  1896. * Connection constructor.
  1897. *
  1898. * Parameters:
  1899. * source - either an element id, a selector for an element, or an Endpoint.
  1900. * target - either an element id, a selector for an element, or an Endpoint
  1901. * scope - scope descriptor for this connection. optional.
  1902. * endpoint - Optional. Endpoint definition to use for both ends of the connection.
  1903. * endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  1904. * endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
  1905. * endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  1906. * paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
  1907. * 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).
  1908. * overlays - Optional array of Overlay definitions to appear on this Connection.
  1909. */
  1910. var Connection = function(params) {
  1911. jsPlumbUIComponent.apply(this, arguments);
  1912. // ************** get the source and target and register the connection. *******************
  1913. var self = this;
  1914. var visible = true;
  1915. /**
  1916. Function:isVisible
  1917. Returns whether or not the Connection is currently visible.
  1918. */
  1919. this.isVisible = function() { return visible; };
  1920. /**
  1921. Function: setVisible
  1922. Sets whether or not the Connection should be visible.
  1923. Parameters:
  1924. visible - boolean indicating desired visible state.
  1925. */
  1926. this.setVisible = function(v) {
  1927. visible = v;
  1928. if (self.connector && self.connector.canvas) self.connector.canvas.style.display = v ? "block" : "none";
  1929. };
  1930. var id = new String('_jsplumb_c_' + (new Date()).getTime());
  1931. this.getId = function() { return id; };
  1932. this.parent = params.parent;
  1933. /**
  1934. Property: source
  1935. The source element for this Connection.
  1936. */
  1937. this.source = _getElementObject(params.source);
  1938. /**
  1939. Property:target
  1940. The target element for this Connection.
  1941. */
  1942. this.target = _getElementObject(params.target);
  1943. // sourceEndpoint and targetEndpoint override source/target, if they are present.
  1944. if (params.sourceEndpoint) this.source = params.sourceEndpoint.getElement();
  1945. if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
  1946. /*
  1947. * Property: sourceId
  1948. * Id of the source element in the connection.
  1949. */
  1950. this.sourceId = _getAttribute(this.source, "id");
  1951. /*
  1952. * Property: targetId
  1953. * Id of the target element in the connection.
  1954. */
  1955. this.targetId = _getAttribute(this.target, "id");
  1956. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  1957. /**
  1958. * implementation of abstract method in EventGenerator
  1959. * @return list of attached elements. in our case, a list of Endpoints.
  1960. */
  1961. this.getAttachedElements = function() {
  1962. return self.endpoints;
  1963. };
  1964. /**
  1965. * implementation of abstract method in EventGenerator
  1966. */
  1967. var srcWhenMouseDown = null, targetWhenMouseDown = null;
  1968. this.savePosition = function() {
  1969. srcWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.source));
  1970. targetWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.target));
  1971. };
  1972. /*
  1973. * Property: scope
  1974. * Optional scope descriptor for the connection.
  1975. */
  1976. 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.
  1977. /*
  1978. * Property: endpoints
  1979. * Array of [source, target] Endpoint objects.
  1980. */
  1981. this.endpoints = [];
  1982. this.endpointStyles = [];
  1983. // wrapped the main function to return null if no input given. this lets us cascade defaults properly.
  1984. var _makeAnchor = function(anchorParams) {
  1985. if (anchorParams)
  1986. return jsPlumb.makeAnchor(anchorParams);
  1987. };
  1988. var prepareEndpoint = function(existing, index, params, element, connectorPaintStyle, connectorHoverPaintStyle) {
  1989. if (existing) {
  1990. self.endpoints[index] = existing;
  1991. existing.addConnection(self);
  1992. } else {
  1993. if (!params.endpoints) params.endpoints = [ null, null ];
  1994. var ep = params.endpoints[index]
  1995. || params.endpoint
  1996. || _currentInstance.Defaults.Endpoints[index]
  1997. || jsPlumb.Defaults.Endpoints[index]
  1998. || _currentInstance.Defaults.Endpoint
  1999. || jsPlumb.Defaults.Endpoint;
  2000. if (!params.endpointStyles) params.endpointStyles = [ null, null ];
  2001. if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
  2002. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  2003. // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
  2004. if (es.fillStyle == null && connectorPaintStyle != null)
  2005. es.fillStyle = connectorPaintStyle.strokeStyle;
  2006. // TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
  2007. //*
  2008. if (es.outlineColor == null && connectorPaintStyle != null)
  2009. es.outlineColor = connectorPaintStyle.outlineColor;
  2010. if (es.outlineWidth == null && connectorPaintStyle != null)
  2011. es.outlineWidth = connectorPaintStyle.outlineWidth;
  2012. //*/
  2013. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _currentInstance.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
  2014. // endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
  2015. if (connectorHoverPaintStyle != null) {
  2016. if (ehs == null) ehs = {};
  2017. if (ehs.fillStyle == null) {
  2018. ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
  2019. }
  2020. }
  2021. var a = params.anchors ? params.anchors[index] : _makeAnchor(_currentInstance.Defaults.Anchors[index]) || _makeAnchor(jsPlumb.Defaults.Anchors[index]) || _makeAnchor(_currentInstance.Defaults.Anchor) || _makeAnchor(jsPlumb.Defaults.Anchor);
  2022. var u = params.uuids ? params.uuids[index] : null;
  2023. var e = _newEndpoint( { paintStyle : es, hoverPaintStyle:ehs, endpoint : ep, connections : [ self ], uuid : u, anchor : a, source : element });
  2024. self.endpoints[index] = e;
  2025. if (params.drawEndpoints === false) e.setVisible(false, true, true);
  2026. return e;
  2027. }
  2028. };
  2029. var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source, params.paintStyle, params.hoverPaintStyle);
  2030. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  2031. var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target, params.paintStyle, params.hoverPaintStyle);
  2032. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  2033. // if scope not set, set it to be the scope for the source endpoint.
  2034. if (!this.scope) this.scope = this.endpoints[0].scope;
  2035. /*
  2036. * Function: setConnector
  2037. * Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method - the same
  2038. * thing that you would set as the 'connector' property on a jsPlumb.connect call.
  2039. *
  2040. * Parameters:
  2041. * connector - Connector definition
  2042. */
  2043. this.setConnector = function(connector, doNotRepaint) {
  2044. if (self.connector != null) _removeElements(self.connector.getDisplayElements(), self.parent);
  2045. var connectorArgs = { _jsPlumb:self._jsPlumb, parent:params.parent, cssClass:params.cssClass };
  2046. if (connector.constructor == String)
  2047. this.connector = new jsPlumb.Connectors[renderMode][connector](connectorArgs); // lets you use a string as shorthand.
  2048. else if (connector.constructor == Array)
  2049. this.connector = new jsPlumb.Connectors[renderMode][connector[0]](jsPlumb.extend(connector[1], connectorArgs));
  2050. this.canvas = this.connector.canvas;
  2051. var _mouseDown = false, _mouseWasDown = false, _mouseDownAt = null;
  2052. // add mouse events
  2053. this.connector.bind("click", function(con, e) {
  2054. _mouseWasDown = false;
  2055. self.fire("click", self, e);
  2056. });
  2057. this.connector.bind("dblclick", function(con, e) { _mouseWasDown = false;self.fire("dblclick", self, e); });
  2058. this.connector.bind("mouseenter", function(con, e) {
  2059. if (!self.isHover()) {
  2060. if (_connectionBeingDragged == null) {
  2061. self.setHover(true);
  2062. }
  2063. self.fire("mouseenter", self, e);
  2064. }
  2065. });
  2066. this.connector.bind("mouseexit", function(con, e) {
  2067. if (self.isHover()) {
  2068. if (_connectionBeingDragged == null) {
  2069. self.setHover(false);
  2070. }
  2071. self.fire("mouseexit", self, e);
  2072. }
  2073. });
  2074. this.connector.bind("mousedown", function(con, e) {
  2075. _mouseDown = true;
  2076. _mouseDownAt = jsPlumb.CurrentLibrary.getPageXY(e);
  2077. self.savePosition();
  2078. });
  2079. this.connector.bind("mouseup", function(con, e) {
  2080. _mouseDown = false;
  2081. if (self.connector == _connectionBeingDragged) _connectionBeingDragged = null;
  2082. });
  2083. if (!doNotRepaint) self.repaint();
  2084. };
  2085. /*
  2086. * Property: connector
  2087. * The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
  2088. */
  2089. self.setConnector(this.endpoints[0].connector ||
  2090. this.endpoints[1].connector ||
  2091. params.connector ||
  2092. _currentInstance.Defaults.Connector ||
  2093. jsPlumb.Defaults.Connector, true);
  2094. this.setPaintStyle(this.endpoints[0].connectorStyle ||
  2095. this.endpoints[1].connectorStyle ||
  2096. params.paintStyle ||
  2097. _currentInstance.Defaults.PaintStyle ||
  2098. jsPlumb.Defaults.PaintStyle, true);
  2099. this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
  2100. this.endpoints[1].connectorHoverStyle ||
  2101. params.hoverPaintStyle ||
  2102. _currentInstance.Defaults.HoverPaintStyle ||
  2103. jsPlumb.Defaults.HoverPaintStyle, true);
  2104. this.paintStyleInUse = this.paintStyle;
  2105. /*
  2106. * Property: overlays
  2107. * List of Overlays for this Connection.
  2108. */
  2109. this.overlays = [];
  2110. var _overlays = params.overlays || _currentInstance.Defaults.Overlays;
  2111. if (_overlays) {
  2112. for (var i = 0; i < _overlays.length; i++) {
  2113. var o = _overlays[i], _newOverlay = null, _overlayEvents = null;
  2114. if (o.constructor == Array) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  2115. // there's also a three arg version:
  2116. // ["Arrow", { width:50 }, {location:0.7}]
  2117. // which merges the 3rd arg into the 2nd.
  2118. var type = o[0];
  2119. var p = jsPlumb.CurrentLibrary.extend({connection:self, _jsPlumb:_currentInstance}, o[1]); // make a copy of the object so as not to mess up anyone else's reference...
  2120. if (o.length == 3) jsPlumb.CurrentLibrary.extend(p, o[2]);
  2121. _newOverlay = new jsPlumb.Overlays[renderMode][type](p);
  2122. if (p.events) {
  2123. for (var evt in p.events) {
  2124. _newOverlay.bind(evt, p.events[evt]);
  2125. }
  2126. }
  2127. } else if (o.constructor == String) {
  2128. _newOverlay = new jsPlumb.Overlays[renderMode][o]({connection:self, _jsPlumb:_currentInstance});
  2129. } else {
  2130. _newOverlay = o;
  2131. }
  2132. this.overlays.push(_newOverlay);
  2133. }
  2134. }
  2135. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2136. /*
  2137. * Function: bind
  2138. * Bind to an event on the Connection.
  2139. *
  2140. * Parameters:
  2141. * event - the event to bind. Available events on a Connection are:
  2142. * - *click* : notification that a Connection was clicked.
  2143. * - *dblclick* : notification that a Connection was double clicked.
  2144. * - *mouseenter* : notification that the mouse is over a Connection.
  2145. * - *mouseexit* : notification that the mouse exited a Connection.
  2146. *
  2147. * callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
  2148. */
  2149. /*
  2150. * Function: setPaintStyle
  2151. * Sets the Connection's paint style and then repaints the Connection.
  2152. *
  2153. * Parameters:
  2154. * style - Style to use.
  2155. */
  2156. /*
  2157. * Function: setHoverPaintStyle
  2158. * Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
  2159. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  2160. * it. This is because people will most likely want to change just one thing when hovering, say the
  2161. * color for example, but leave the rest of the appearance the same.
  2162. *
  2163. * Parameters:
  2164. * style - Style to use when the mouse is hovering.
  2165. * doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
  2166. */
  2167. /*
  2168. * Function: setHover
  2169. * Sets/unsets the hover state of this Connection.
  2170. *
  2171. * Parameters:
  2172. * hover - hover state boolean
  2173. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  2174. */
  2175. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2176. /*
  2177. * Function: addOverlay
  2178. * Adds an Overlay to the Connection.
  2179. *
  2180. * Parameters:
  2181. * overlay - Overlay to add.
  2182. */
  2183. this.addOverlay = function(overlay) { self.overlays.push(overlay); };
  2184. /**
  2185. * Function: removeAllOverlays
  2186. * Removes all overlays from the Connection, and then repaints.
  2187. */
  2188. this.removeAllOverlays = function() {
  2189. self.overlays.splice(0, self.overlays.length);
  2190. self.repaint();
  2191. };
  2192. /**
  2193. * Function:removeOverlay
  2194. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  2195. * Parameters:
  2196. * overlayId - id of the overlay to remove.
  2197. */
  2198. this.removeOverlay = function(overlayId) {
  2199. var idx = -1;
  2200. for (var i = 0; i < self.overlays.length; i++) {
  2201. if (overlayId === self.overlays[i].id) {
  2202. idx = i;
  2203. break;
  2204. }
  2205. }
  2206. if (idx != -1) self.overlays.splice(idx, 1);
  2207. };
  2208. /**
  2209. * Function:removeOverlay
  2210. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  2211. * Parameters:
  2212. * overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
  2213. */
  2214. this.removeOverlays = function() {
  2215. for (var i = 0; i < arguments.length; i++)
  2216. self.removeOverlay(arguments[i]);
  2217. };
  2218. // this is a shortcut helper method to let people add a label as
  2219. // overlay.
  2220. this.labelStyle = params.labelStyle || _currentInstance.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;
  2221. this.label = params.label;
  2222. if (this.label) {
  2223. this.overlays.push(new jsPlumb.Overlays[renderMode].Label( {
  2224. cssClass:params.cssClass,
  2225. labelStyle : this.labelStyle,
  2226. label : this.label,
  2227. connection:self,
  2228. _jsPlumb:_currentInstance
  2229. }));
  2230. }
  2231. _updateOffset( { elId : this.sourceId });
  2232. _updateOffset( { elId : this.targetId });
  2233. /*
  2234. * Function: setLabel
  2235. * Sets the Connection's label.
  2236. *
  2237. * Parameters:
  2238. * l - label to set. May be a String or a Function that returns a String.
  2239. */
  2240. this.setLabel = function(l) {
  2241. self.label = l;
  2242. _currentInstance.repaint(self.source);
  2243. };
  2244. // paint the endpoints
  2245. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  2246. var otherOffset = offsets[this.targetId];
  2247. var otherWH = sizes[this.targetId];
  2248. var anchorLoc = this.endpoints[0].anchor.compute( {
  2249. xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
  2250. txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1]
  2251. });
  2252. this.endpoints[0].paint( { anchorLoc : anchorLoc });
  2253. anchorLoc = this.endpoints[1].anchor.compute( {
  2254. xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
  2255. txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0]
  2256. });
  2257. this.endpoints[1].paint({ anchorLoc : anchorLoc });
  2258. /*
  2259. * Paints the Connection. Not exposed for public usage.
  2260. *
  2261. * Parameters:
  2262. * elId - Id of the element that is in motion.
  2263. * ui - current library's event system ui object (present if we came from a drag to get here).
  2264. * recalc - whether or not to recalculate all anchors etc before painting.
  2265. * timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
  2266. */
  2267. this.paint = function(params) {
  2268. params = params || {};
  2269. var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp;
  2270. var fai = self.floatingAnchorIndex;
  2271. // if the moving object is not the source we must transpose the two references.
  2272. var swap = false;
  2273. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  2274. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  2275. var el = swap ? this.target : this.source;
  2276. _updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp });
  2277. _updateOffset( { elId : tId, timestamp : timestamp }); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  2278. var sAnchorP = this.endpoints[sIdx].anchor.getCurrentLocation();
  2279. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  2280. var tAnchorP = this.endpoints[tIdx].anchor.getCurrentLocation();
  2281. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  2282. /* paint overlays*/
  2283. var maxSize = 0;
  2284. for ( var i = 0; i < self.overlays.length; i++) {
  2285. var o = self.overlays[i];
  2286. var s = o.computeMaxSize(self.connector);
  2287. if (s > maxSize)
  2288. maxSize = s;
  2289. }
  2290. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, self.paintStyleInUse.lineWidth, maxSize);
  2291. self.connector.paint(dim, self.paintStyleInUse);
  2292. /* paint overlays*/
  2293. for ( var i = 0; i < self.overlays.length; i++) {
  2294. var o = self.overlays[i];
  2295. self.overlayPlacements[i] = o.draw(self.connector, self.paintStyleInUse, dim);
  2296. }
  2297. };
  2298. /*
  2299. * Function: repaint
  2300. * Repaints the Connection.
  2301. */
  2302. this.repaint = function() {
  2303. this.paint({ elId : this.sourceId, recalc : true });
  2304. };
  2305. _initDraggableIfNecessary(self.source, params.draggable, params.dragOptions);
  2306. _initDraggableIfNecessary(self.target, params.draggable, params.dragOptions);
  2307. // resizing (using the jquery.ba-resize plugin). todo: decide
  2308. // whether to include or not.
  2309. if (this.source.resize) {
  2310. this.source.resize(function(e) {
  2311. jsPlumb.repaint(self.sourceId);
  2312. });
  2313. }
  2314. // just to make sure the UI gets initialised fully on all browsers.
  2315. self.repaint();
  2316. };
  2317. /*
  2318. * Class: Endpoint
  2319. *
  2320. * Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
  2321. * to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
  2322. * actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
  2323. * do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
  2324. * 'target' Endpoints for Connections.
  2325. *
  2326. *
  2327. */
  2328. /*
  2329. * Function: Endpoint
  2330. *
  2331. * Endpoint constructor.
  2332. *
  2333. * Parameters:
  2334. * 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.
  2335. * 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 } ].
  2336. * paintStyle - endpoint style, a js object. may be null.
  2337. * hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
  2338. * source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
  2339. * canvas - canvas element to use. may be, and most often is, null.
  2340. * connections - optional list of Connections to configure the Endpoint with.
  2341. * isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
  2342. * maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
  2343. * dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
  2344. * connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
  2345. * connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
  2346. * 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 } ].
  2347. * connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
  2348. * isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
  2349. * 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.
  2350. * 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.
  2351. */
  2352. var Endpoint = function(params) {
  2353. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  2354. params = params || {};
  2355. var self = this;
  2356. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2357. /*
  2358. * Function: bind
  2359. * Bind to an event on the Endpoint.
  2360. *
  2361. * Parameters:
  2362. * event - the event to bind. Available events on an Endpoint are:
  2363. * - *click* : notification that a Endpoint was clicked.
  2364. * - *dblclick* : notification that a Endpoint was double clicked.
  2365. * - *mouseenter* : notification that the mouse is over a Endpoint.
  2366. * - *mouseexit* : notification that the mouse exited a Endpoint.
  2367. *
  2368. * callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
  2369. */
  2370. /*
  2371. * Function: setPaintStyle
  2372. * Sets the Endpoint's paint style and then repaints the Endpoint.
  2373. *
  2374. * Parameters:
  2375. * style - Style to use.
  2376. */
  2377. /*
  2378. * Function: setHoverPaintStyle
  2379. * Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
  2380. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  2381. * it. This is because people will most likely want to change just one thing when hovering, say the
  2382. * color for example, but leave the rest of the appearance the same.
  2383. *
  2384. * Parameters:
  2385. * style - Style to use when the mouse is hovering.
  2386. * doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
  2387. */
  2388. /*
  2389. * Function: setHover
  2390. * Sets/unsets the hover state of this Endpoint.
  2391. *
  2392. * Parameters:
  2393. * hover - hover state boolean
  2394. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  2395. */
  2396. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2397. var visible = true;
  2398. /*
  2399. Function: isVisible
  2400. Returns whether or not the Endpoint is currently visible.
  2401. */
  2402. this.isVisible = function() { return visible; };
  2403. /*
  2404. Function: setVisible
  2405. Sets whether or not the Endpoint is currently visible.
  2406. Parameters:
  2407. visible - whether or not the Endpoint should be visible.
  2408. doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
  2409. doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
  2410. */
  2411. this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  2412. visible = v;
  2413. if (self.canvas) self.canvas.style.display = v ? "block" : "none";
  2414. if (!doNotChangeConnections) {
  2415. for (var i = 0; i < self.connections.length; i++) {
  2416. self.connections[i].setVisible(v);
  2417. if (!doNotNotifyOtherEndpoint) {
  2418. var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
  2419. // only change the other endpoint if this is its only connection.
  2420. if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
  2421. }
  2422. }
  2423. }
  2424. };
  2425. var id = new String('_jsplumb_e_' + (new Date()).getTime());
  2426. this.getId = function() { return id; };
  2427. if (params.dynamicAnchors)
  2428. self.anchor = new DynamicAnchor(jsPlumb.makeAnchors(params.dynamicAnchors));
  2429. else
  2430. self.anchor = params.anchor ? jsPlumb.makeAnchor(params.anchor) : params.anchors ? jsPlumb.makeAnchor(params.anchors) : jsPlumb.makeAnchor("TopCenter");
  2431. var _endpoint = params.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot",
  2432. endpointArgs = { _jsPlumb:self._jsPlumb, parent:params.parent };
  2433. if (_endpoint.constructor == String)
  2434. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint](endpointArgs);
  2435. else if (_endpoint.constructor == Array)
  2436. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint[0]](jsPlumb.extend(_endpoint[1], endpointArgs ));
  2437. else _endpoint = _endpoint.clone();
  2438. self.endpoint = _endpoint;
  2439. this.endpoint.bind("click", function(e) { self.fire("click", self, e); });
  2440. this.endpoint.bind("dblclick", function(e) { self.fire("dblclick", self, e); });
  2441. this.setPaintStyle(params.paintStyle ||
  2442. params.style ||
  2443. _currentInstance.Defaults.EndpointStyle ||
  2444. jsPlumb.Defaults.EndpointStyle, true);
  2445. this.setHoverPaintStyle(params.hoverPaintStyle ||
  2446. _currentInstance.Defaults.EndpointHoverStyle ||
  2447. jsPlumb.Defaults.EndpointHoverStyle, true);
  2448. this.paintStyleInUse = this.paintStyle;
  2449. this.connectorStyle = params.connectorStyle;
  2450. this.connectorHoverStyle = params.connectorHoverStyle;
  2451. this.connectorOverlays = params.connectorOverlays;
  2452. this.connector = params.connector;
  2453. this.parent = params.parent;
  2454. this.isSource = params.isSource || false;
  2455. this.isTarget = params.isTarget || false;
  2456. var _element = params.source,
  2457. _uuid = params.uuid,
  2458. floatingEndpoint = null,
  2459. inPlaceCopy = null;
  2460. if (_uuid) endpointsByUUID[_uuid] = self;
  2461. var _elementId = _getAttribute(_element, "id");
  2462. this.elementId = _elementId;
  2463. this.element = _element;
  2464. var _maxConnections = params.maxConnections || _currentInstance.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
  2465. this.getAttachedElements = function() {
  2466. return self.connections;
  2467. };
  2468. /*
  2469. * Property: canvas
  2470. * The Endpoint's Canvas.
  2471. */
  2472. this.canvas = this.endpoint.canvas;
  2473. /*
  2474. * Property: connections
  2475. * List of Connections this Endpoint is attached to.
  2476. */
  2477. this.connections = params.connections || [];
  2478. /*
  2479. * Property: scope
  2480. * Scope descriptor for this Endpoint.
  2481. */
  2482. this.scope = params.scope || DEFAULT_SCOPE;
  2483. this.timestamp = null;
  2484. var _reattach = params.reattach || false;
  2485. var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
  2486. this.computeAnchor = function(params) {
  2487. return self.anchor.compute(params);
  2488. };
  2489. /*
  2490. * Function: addConnection
  2491. * Adds a Connection to this Endpoint.
  2492. *
  2493. * Parameters:
  2494. * connection - the Connection to add.
  2495. */
  2496. this.addConnection = function(connection) {
  2497. self.connections.push(connection);
  2498. };
  2499. /*
  2500. * Function: detach
  2501. * Detaches the given Connection from this Endpoint.
  2502. *
  2503. * Parameters:
  2504. * connection - the Connection to detach.
  2505. * ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
  2506. */
  2507. this.detach = function(connection, ignoreTarget) {
  2508. var idx = _findIndex(self.connections, connection);
  2509. if (idx >= 0) {
  2510. self.connections.splice(idx, 1);
  2511. // this avoids a circular loop
  2512. if (!ignoreTarget) {
  2513. var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
  2514. t.detach(connection, true);
  2515. // check connection to see if we want to delete the other endpoint.
  2516. // if the user uses makeTarget to make some element a target for connections,
  2517. // it is possible that they will have set 'endpointToDeleteOnDetach': when
  2518. // you make a connection to an element that acts as a target (note: NOT an
  2519. // Endpoint; just some div as a target), Endpoints are created for that
  2520. // connection. so if you then delete that Connection, it is feasible you
  2521. // will want these auto-generated endpoints to be removed.
  2522. if (connection.endpointToDeleteOnDetach && connection.endpointToDeleteOnDetach.connections.length == 0)
  2523. jsPlumb.deleteEndpoint(connection.endpointToDeleteOnDetach);
  2524. }
  2525. _removeElements(connection.connector.getDisplayElements(), connection.parent);
  2526. _removeFromList(connectionsByScope, connection.scope, connection);
  2527. if(!ignoreTarget) fireDetachEvent(connection);
  2528. }
  2529. };
  2530. /*
  2531. * Function: detachAll
  2532. * Detaches all Connections this Endpoint has.
  2533. */
  2534. this.detachAll = function() {
  2535. while (self.connections.length > 0) {
  2536. self.detach(self.connections[0]);
  2537. }
  2538. };
  2539. /*
  2540. * Function: detachFrom
  2541. * Removes any connections from this Endpoint that are connected to the given target endpoint.
  2542. *
  2543. * Parameters:
  2544. * targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
  2545. */
  2546. this.detachFrom = function(targetEndpoint) {
  2547. var c = [];
  2548. for ( var i = 0; i < self.connections.length; i++) {
  2549. if (self.connections[i].endpoints[1] == targetEndpoint
  2550. || self.connections[i].endpoints[0] == targetEndpoint) {
  2551. c.push(self.connections[i]);
  2552. }
  2553. }
  2554. for ( var i = 0; i < c.length; i++) {
  2555. c[i].setHover(false);
  2556. self.detach(c[i]);
  2557. }
  2558. };
  2559. /*
  2560. * Function: detachFromConnection
  2561. * Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
  2562. *
  2563. * Parameters:
  2564. * connection - Connection to detach from.
  2565. */
  2566. this.detachFromConnection = function(connection) {
  2567. var idx = _findIndex(self.connections, connection);
  2568. if (idx >= 0) {
  2569. self.connections.splice(idx, 1);
  2570. }
  2571. };
  2572. /*
  2573. * Function: getElement
  2574. * Returns the DOM element this Endpoint is attached to.
  2575. */
  2576. this.getElement = function() {
  2577. return _element;
  2578. };
  2579. /*
  2580. * Function: getUuid
  2581. * Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
  2582. */
  2583. this.getUuid = function() {
  2584. return _uuid;
  2585. };
  2586. /**
  2587. * private but must be exposed.
  2588. */
  2589. this.makeInPlaceCopy = function() {
  2590. return _newEndpoint( { anchor : self.anchor, source : _element, paintStyle : this.paintStyle, endpoint : _endpoint });
  2591. };
  2592. /*
  2593. * Function: isConnectedTo
  2594. * Returns whether or not this endpoint is connected to the given Endpoint.
  2595. *
  2596. * Parameters:
  2597. * endpoint - Endpoint to test.
  2598. */
  2599. this.isConnectedTo = function(endpoint) {
  2600. var found = false;
  2601. if (endpoint) {
  2602. for ( var i = 0; i < self.connections.length; i++) {
  2603. if (self.connections[i].endpoints[1] == endpoint) {
  2604. found = true;
  2605. break;
  2606. }
  2607. }
  2608. }
  2609. return found;
  2610. };
  2611. /**
  2612. * private but needs to be exposed.
  2613. */
  2614. this.isFloating = function() {
  2615. return floatingEndpoint != null;
  2616. };
  2617. /**
  2618. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  2619. */
  2620. this.connectorSelector = function() {
  2621. return (self.connections.length < _maxConnections) ? null : self.connections[0];
  2622. };
  2623. /*
  2624. * Function: isFull
  2625. * Returns whether or not the Endpoint can accept any more Connections.
  2626. */
  2627. this.isFull = function() {
  2628. return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
  2629. };
  2630. /*
  2631. * Function: setDragAllowedWhenFull
  2632. * Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
  2633. * which you're going to provide some other way of breaking connections, if you need to break them at all. This property
  2634. * is by default true; use it in conjunction with the 'reattach' option on a connect call.
  2635. *
  2636. * Parameters:
  2637. * allowed - whether drag is allowed or not when the Endpoint is full.
  2638. */
  2639. this.setDragAllowedWhenFull = function(allowed) {
  2640. dragAllowedWhenFull = allowed;
  2641. };
  2642. /*
  2643. * Function: setStyle
  2644. * Sets the paint style of the Endpoint. This is a JS object of the same form you supply to a jsPlumb.addEndpoint or jsPlumb.connect call.
  2645. * TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
  2646. * setStyle and deprecate it if so.
  2647. *
  2648. * Parameters:
  2649. * style - Style object to set, for example {fillStyle:"blue"}.
  2650. *
  2651. * @deprecated use setPaintStyle instead.
  2652. */
  2653. this.setStyle = self.setPaintStyle;
  2654. /**
  2655. * a deep equals check. everything must match, including the anchor,
  2656. * styles, everything. TODO: finish Endpoint.equals
  2657. */
  2658. this.equals = function(endpoint) {
  2659. return this.anchor.equals(endpoint.anchor);
  2660. };
  2661. /*
  2662. * Function: paint
  2663. * Paints the Endpoint, recalculating offset and anchor positions if necessary.
  2664. *
  2665. * Parameters:
  2666. * 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.
  2667. * canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
  2668. * connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
  2669. */
  2670. this.paint = function(params) {
  2671. params = params || {};
  2672. var timestamp = params.timestamp;
  2673. if (!timestamp || self.timestamp !== timestamp) {
  2674. var ap = params.anchorPoint, canvas = params.canvas, connectorPaintStyle = params.connectorPaintStyle;
  2675. if (ap == null) {
  2676. var xy = params.offset || offsets[_elementId];
  2677. var wh = params.dimensions || sizes[_elementId];
  2678. if (xy == null || wh == null) {
  2679. _updateOffset( { elId : _elementId, timestamp : timestamp });
  2680. xy = offsets[_elementId];
  2681. wh = sizes[_elementId];
  2682. }
  2683. var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
  2684. if (self.anchor.isDynamic) {
  2685. if (self.connections.length > 0) {
  2686. var c = self.connections[0];
  2687. var oIdx = c.endpoints[0] == self ? 1 : 0;
  2688. var oId = oIdx == 0 ? c.sourceId : c.targetId;
  2689. var oOffset = offsets[oId], oWH = sizes[oId];
  2690. anchorParams.txy = [ oOffset.left, oOffset.top ];
  2691. anchorParams.twh = oWH;
  2692. anchorParams.tElement = c.endpoints[oIdx];
  2693. }
  2694. }
  2695. ap = self.anchor.compute(anchorParams);
  2696. }
  2697. var d = _endpoint.compute(ap, self.anchor.getOrientation(), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
  2698. _endpoint.paint(d, self.paintStyleInUse, self.anchor);
  2699. self.timestamp = timestamp;
  2700. }
  2701. };
  2702. this.repaint = this.paint;
  2703. /**
  2704. * @deprecated
  2705. */
  2706. this.removeConnection = this.detach; // backwards compatibility
  2707. // is this a connection source? we make it draggable and have the
  2708. // drag listener maintain a connection with a floating endpoint.
  2709. if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  2710. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  2711. var start = function() {
  2712. jpc = self.connectorSelector();
  2713. if (self.isFull() && !dragAllowedWhenFull) return false;
  2714. _updateOffset( { elId : _elementId });
  2715. inPlaceCopy = self.makeInPlaceCopy();
  2716. inPlaceCopy.paint();
  2717. n = document.createElement("div");
  2718. n.style.position = "absolute";
  2719. var nE = _getElementObject(n);
  2720. _appendElement(n, self.parent);
  2721. // create and assign an id, and initialize the offset.
  2722. var id = _getId(nE);
  2723. // set the offset of this div to be where 'inPlaceCopy' is, to start with.
  2724. var ipcoel = _getElementObject(inPlaceCopy.canvas),
  2725. ipco = jsPlumb.CurrentLibrary.getOffset(ipcoel),
  2726. po = inPlaceCopy.canvas.offsetParent.tagName.toLowerCase() === "body" ? {left:0,top:0} : _getOffset(inPlaceCopy.canvas.offsetParent);
  2727. jsPlumb.CurrentLibrary.setOffset(n, {left:ipco.left - po.left, top:ipco.top-po.top});
  2728. _updateOffset( { elId : id });
  2729. // store the id of the dragging div and the source element. the drop function will pick these up.
  2730. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  2731. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  2732. // create a floating anchor
  2733. var floatingAnchor = new FloatingAnchor( { reference : self.anchor, referenceCanvas : self.canvas });
  2734. floatingEndpoint = _newEndpoint({ paintStyle : self.paintStyle, endpoint : _endpoint, anchor : floatingAnchor, source : nE });
  2735. if (jpc == null) {
  2736. self.anchor.locked = true;
  2737. // create a connection. one end is this endpoint, the
  2738. // other is a floating endpoint.
  2739. jpc = _newConnection({
  2740. sourceEndpoint : self,
  2741. targetEndpoint : floatingEndpoint,
  2742. source : _getElementObject(_element),
  2743. target : _getElementObject(n),
  2744. anchors : [ self.anchor, floatingAnchor ],
  2745. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  2746. hoverPaintStyle:params.connectorHoverStyle,
  2747. connector : params.connector, // this can also be null. Connection will use the default.
  2748. overlays : params.connectorOverlays
  2749. });
  2750. // TODO determine whether or not we wish to do de-select hover when dragging a connection.
  2751. // it may be the case that we actually want to set it, since it provides a good
  2752. // visual cue.
  2753. jpc.connector.setHover(false);
  2754. } else {
  2755. existingJpc = true;
  2756. // TODO determine whether or not we wish to do de-select hover when dragging a connection.
  2757. // it may be the case that we actually want to set it, since it provides a good
  2758. // visual cue.
  2759. jpc.connector.setHover(false);
  2760. // if existing connection, allow to be dropped back on the source endpoint (issue 51).
  2761. _initDropTarget(_getElementObject(inPlaceCopy.canvas));
  2762. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1; // are we the source or the target?
  2763. jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
  2764. self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
  2765. // store the original scope (issue 57)
  2766. var c = _getElementObject(self.canvas);
  2767. var dragScope = jsPlumb.CurrentLibrary.getDragScope(c);
  2768. _setAttribute(c, "originalScope", dragScope);
  2769. // get a new, temporary scope, to use (issue 57)
  2770. var newScope = "scope_" + (new Date()).getTime();
  2771. // now we replace ourselves with the temporary div we created above:
  2772. if (anchorIdx == 0) {
  2773. existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
  2774. jpc.source = _getElementObject(n);
  2775. jpc.sourceId = id;
  2776. } else {
  2777. existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
  2778. jpc.target = _getElementObject(n);
  2779. jpc.targetId = id;
  2780. }
  2781. // set the new, temporary scope (issue 57)
  2782. jsPlumb.CurrentLibrary.setDragScope(i, newScope);
  2783. // lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
  2784. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
  2785. // store the original endpoint and assign the new floating endpoint for the drag.
  2786. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  2787. jpc.endpoints[anchorIdx] = floatingEndpoint;
  2788. }
  2789. // register it.
  2790. floatingConnections[id] = jpc;
  2791. // TODO unregister on stop? or will floating endpoint's
  2792. // destruction be assured.
  2793. floatingEndpoint.addConnection(jpc);
  2794. // only register for the target endpoint; we will not be
  2795. // dragging the source at any time
  2796. // before this connection is either discarded or made into a
  2797. // permanent connection.
  2798. _addToList(endpointsByElement, id, floatingEndpoint);
  2799. // tell jsplumb about it
  2800. _currentInstance.currentlyDragging = true;
  2801. };
  2802. var jpcl = jsPlumb.CurrentLibrary,
  2803. dragOptions = params.dragOptions || {},
  2804. defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
  2805. startEvent = jpcl.dragEvents['start'],
  2806. stopEvent = jpcl.dragEvents['stop'],
  2807. dragEvent = jpcl.dragEvents['drag'];
  2808. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  2809. dragOptions.scope = dragOptions.scope || self.scope;
  2810. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  2811. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent],
  2812. function() {
  2813. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  2814. jsPlumb.CurrentLibrary.setOffset(n, _ui);
  2815. _draw(_getElementObject(n), _ui);
  2816. });
  2817. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  2818. function() {
  2819. _removeFromList(endpointsByElement, id, floatingEndpoint);
  2820. _removeElements( [ n, floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
  2821. _removeElement(inPlaceCopy.canvas, _element);
  2822. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2823. jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
  2824. if (jpc.endpoints[idx] == floatingEndpoint) {
  2825. // if the connection was an existing one:
  2826. if (existingJpc && jpc.suspendedEndpoint) {
  2827. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  2828. // floating endpoint has been replaced.
  2829. if (idx == 0) {
  2830. jpc.source = existingJpcParams[0];
  2831. jpc.sourceId = existingJpcParams[1];
  2832. } else {
  2833. jpc.target = existingJpcParams[0];
  2834. jpc.targetId = existingJpcParams[1];
  2835. }
  2836. // restore the original scope (issue 57)
  2837. jsPlumb.CurrentLibrary.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  2838. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  2839. if (_reattach) {
  2840. jpc.floatingAnchorIndex = null;
  2841. jpc.suspendedEndpoint.addConnection(jpc);
  2842. jsPlumb.repaint(existingJpcParams[1]);
  2843. } else {
  2844. jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc); // the main endpoint will inform the floating endpoint
  2845. // to disconnect, and also post the detached event.
  2846. }
  2847. } else {
  2848. // TODO this looks suspiciously kind of like an Endpoint.detach call too.
  2849. // i wonder if this one should post an event though. maybe this is good like this.
  2850. _removeElements(jpc.connector.getDisplayElements(), self.parent);
  2851. self.detachFromConnection(jpc);
  2852. }
  2853. }
  2854. self.anchor.locked = false;
  2855. self.paint();
  2856. jpc.setHover(false);
  2857. jpc.repaint();
  2858. jpc = null;
  2859. delete inPlaceCopy;
  2860. delete endpointsByElement[floatingEndpoint.elementId];
  2861. floatingEndpoint = null;
  2862. delete floatingEndpoint;
  2863. _currentInstance.currentlyDragging = false;
  2864. });
  2865. var i = _getElementObject(self.canvas);
  2866. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
  2867. }
  2868. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  2869. // back onto the endpoint you detached it from.
  2870. var _initDropTarget = function(canvas) {
  2871. if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  2872. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  2873. dropOptions = jsPlumb.extend( {}, dropOptions);
  2874. dropOptions.scope = dropOptions.scope || self.scope;
  2875. var originalAnchor = null;
  2876. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
  2877. var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
  2878. var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
  2879. var drop = function() {
  2880. var draggable = _getElementObject(jsPlumb.CurrentLibrary.getDragObject(arguments));
  2881. var id = _getAttribute(draggable, "dragId");
  2882. var elId = _getAttribute(draggable, "elId");
  2883. // restore the original scope if necessary (issue 57)
  2884. var scope = _getAttribute(draggable, "originalScope");
  2885. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  2886. var jpc = floatingConnections[id];
  2887. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
  2888. if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
  2889. if (idx == 0) {
  2890. jpc.source = _element;
  2891. jpc.sourceId = _elementId;
  2892. } else {
  2893. jpc.target = _element;
  2894. jpc.targetId = _elementId;
  2895. }
  2896. // todo test that the target is not full.
  2897. // remove this jpc from the current endpoint
  2898. jpc.endpoints[idx].detachFromConnection(jpc);
  2899. if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
  2900. jpc.endpoints[idx] = self;
  2901. self.addConnection(jpc);
  2902. if (!jpc.suspendedEndpoint) {
  2903. _addToList(connectionsByScope, jpc.scope, jpc);
  2904. _initDraggableIfNecessary(_element, params.draggable, {});
  2905. }
  2906. else {
  2907. var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
  2908. // fire a detach event
  2909. _currentInstance.fire("jsPlumbConnectionDetached", {
  2910. source : idx == 0 ? suspendedElement : jpc.source,
  2911. target : idx == 1 ? suspendedElement : jpc.target,
  2912. sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
  2913. targetId : idx == 1 ? suspendedElementId : jpc.targetId,
  2914. sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  2915. targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  2916. connection : jpc
  2917. });
  2918. }
  2919. jsPlumb.repaint(elId);
  2920. _currentInstance.fire("jsPlumbConnection", {
  2921. source : jpc.source, target : jpc.target,
  2922. sourceId : jpc.sourceId, targetId : jpc.targetId,
  2923. sourceEndpoint : jpc.endpoints[0],
  2924. targetEndpoint : jpc.endpoints[1],
  2925. connection:jpc
  2926. });
  2927. }
  2928. _currentInstance.currentlyDragging = false;
  2929. delete floatingConnections[id];
  2930. };
  2931. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], drop);
  2932. dropOptions[overEvent] = _wrap(dropOptions[overEvent],
  2933. function() {
  2934. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  2935. var id = _getAttribute( _getElementObject(draggable), "dragId");
  2936. var jpc = floatingConnections[id];
  2937. if (jpc != null) {
  2938. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2939. jpc.endpoints[idx].anchor.over(self.anchor);
  2940. }
  2941. });
  2942. dropOptions[outEvent] = _wrap(dropOptions[outEvent],
  2943. function() {
  2944. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  2945. id = _getAttribute(_getElementObject(draggable), "dragId"),
  2946. jpc = floatingConnections[id];
  2947. if (jpc != null) {
  2948. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2949. jpc.endpoints[idx].anchor.out();
  2950. }
  2951. });
  2952. jsPlumb.CurrentLibrary.initDroppable(canvas, dropOptions);
  2953. }
  2954. };
  2955. // 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.
  2956. _initDropTarget(_getElementObject(self.canvas));
  2957. return self;
  2958. };
  2959. };
  2960. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  2961. jsPlumb.getInstance = function(_defaults) {
  2962. var j = new jsPlumbInstance(_defaults);
  2963. //if (_defaults) jsPlumb.extend(j.Defaults, _defaults);
  2964. return j;
  2965. };
  2966. var _curryAnchor = function(x,y,ox,oy) {
  2967. return function() {
  2968. return jsPlumb.makeAnchor(x,y,ox,oy);
  2969. };
  2970. };
  2971. jsPlumb.Anchors["TopCenter"] = _curryAnchor(0.5, 0, 0,-1);
  2972. jsPlumb.Anchors["BottomCenter"] = _curryAnchor(0.5, 1, 0, 1);
  2973. jsPlumb.Anchors["LeftMiddle"] = _curryAnchor(0, 0.5, -1, 0);
  2974. jsPlumb.Anchors["RightMiddle"] = _curryAnchor(1, 0.5, 1, 0);
  2975. jsPlumb.Anchors["Center"] = _curryAnchor(0.5, 0.5, 0, 0);
  2976. jsPlumb.Anchors["TopRight"] = _curryAnchor(1, 0, 0,-1);
  2977. jsPlumb.Anchors["BottomRight"] = _curryAnchor(1, 1, 0, 1);
  2978. jsPlumb.Anchors["TopLeft"] = _curryAnchor(0, 0, 0, -1);
  2979. jsPlumb.Anchors["BottomLeft"] = _curryAnchor(0, 1, 0, 1);
  2980. jsPlumb.Defaults.DynamicAnchors = function() {
  2981. return jsPlumb.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"]);
  2982. };
  2983. jsPlumb.Anchors["AutoDefault"] = function() { return jsPlumb.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors()); };
  2984. })();