jsPlumb-1.3.3-RC1.js 132 KB

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