jsPlumb-1.3.2-RC1.js 131 KB

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