jquery.jsPlumb-1.3.0-all.js 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653
  1. /*
  2. * jsPlumb
  3. *
  4. * Title:jsPlumb 1.3.0
  5. *
  6. * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
  7. * elements, or VML.
  8. *
  9. * This file contains the jsPlumb core code.
  10. *
  11. * Copyright (c) 2010 - 2011 Simon Porritt (http://jsplumb.org)
  12. *
  13. * http://jsplumb.org
  14. * http://code.google.com/p/jsPlumb
  15. *
  16. * Triple licensed under the MIT, GPL2 and Beer licenses.
  17. */
  18. ;(function() {
  19. /**
  20. * Class:jsPlumb
  21. * The jsPlumb engine, registered as a static object in the window. This object contains all of the methods you will use to
  22. * create and maintain Connections and Endpoints.
  23. */
  24. var ie = !!!document.createElement('canvas').getContext;
  25. var canvasAvailable = !!document.createElement('canvas').getContext;
  26. var svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
  27. // TODO what is a good test for VML availability? aside from just assuming its there because nothing else is.
  28. var vmlAvailable = !(canvasAvailable | svgAvailable);
  29. var _findIndex = function(a, v, b, s) {
  30. var _eq = function(o1, o2) {
  31. if (o1 === o2)
  32. return true;
  33. else if (typeof o1 == "object" && typeof o2 == "object") {
  34. var same = true;
  35. for ( var propertyName in o1) {
  36. if (!_eq(o1[propertyName], o2[propertyName])) {
  37. same = false;
  38. break;
  39. }
  40. }
  41. for ( var propertyName in o2) {
  42. if (!_eq(o2[propertyName], o1[propertyName])) {
  43. same = false;
  44. break;
  45. }
  46. }
  47. return same;
  48. }
  49. };
  50. for ( var i = +b || 0, l = a.length; i < l; i++) {
  51. if (_eq(a[i], v))
  52. return i;
  53. }
  54. return -1;
  55. };
  56. /**
  57. * helper method to add an item to a list, creating the list if it does
  58. * not yet exist.
  59. */
  60. var _addToList = function(map, key, value) {
  61. var l = map[key];
  62. if (l == null) {
  63. l = [];
  64. map[key] = l;
  65. }
  66. l.push(value);
  67. return l;
  68. };
  69. var _connectionBeingDragged = null;
  70. var _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); };
  71. var _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); };
  72. var _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); };
  73. var _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); };
  74. var _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); };
  75. var _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); };
  76. var _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); };
  77. var _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); };
  78. var _log = function(jsp, msg) {
  79. if (jsp.logEnabled && typeof console != "undefined")
  80. console.log(msg);
  81. };
  82. /**
  83. * EventGenerator
  84. * Superclass for objects that generate events - jsPlumb extends this, as does jsPlumbUIComponent, which all the UI elements extend.
  85. */
  86. var EventGenerator = function() {
  87. var _listeners = {}, self = this;
  88. // this is a list of events that should re-throw any errors that occur during their dispatch. as of 1.3.0 this is private to
  89. // jsPlumb, but it seems feasible that people might want to manipulate this list. the thinking is that we don't want event
  90. // listeners to bring down jsPlumb - or do we. i can't make up my mind about this, but i know i want to hear about it if the "ready"
  91. // event fails, because then my page has most likely not initialised. so i have this halfway-house solution. it will be interesting
  92. // to hear what other people think.
  93. var eventsToDieOn = [ "ready" ];
  94. /*
  95. * Binds a listener to an event.
  96. *
  97. * Parameters:
  98. * event - name of the event to bind to.
  99. * listener - function to execute.
  100. */
  101. this.bind = function(event, listener) {
  102. _addToList(_listeners, event, listener);
  103. };
  104. /*
  105. * Fires an update for the given event.
  106. *
  107. * Parameters:
  108. * event - event to fire
  109. * value - value to pass to the event listener(s).
  110. * o riginalEvent - the original event from the browser
  111. */
  112. this.fire = function(event, value, originalEvent) {
  113. if (_listeners[event]) {
  114. for ( var i = 0; i < _listeners[event].length; i++) {
  115. // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
  116. // method will have the whole call stack available in the debugger.
  117. if (_findIndex(eventsToDieOn, event) != -1)
  118. _listeners[event][i](value, originalEvent);
  119. else {
  120. // for events we don't want to die on, catch and log.
  121. try {
  122. _listeners[event][i](value, originalEvent);
  123. } catch (e) {
  124. _log("jsPlumb: fire failed for event " + event + " : " + e);
  125. }
  126. }
  127. }
  128. }
  129. };
  130. /*
  131. * Clears either all listeners, or listeners for some specific event.
  132. *
  133. * Parameters:
  134. * event - optional. constrains the clear to just listeners for this event.
  135. */
  136. this.clearListeners = function(event) {
  137. if (event) {
  138. delete _listeners[event];
  139. } else {
  140. delete _listeners;
  141. _listeners = {};
  142. }
  143. };
  144. };
  145. /*
  146. * Class:jsPlumbUIComponent
  147. * Abstract superclass for UI components Endpoint and Connection. Provides the abstraction of paintStyle/hoverPaintStyle,
  148. * and also extends EventGenerator to provide the bind and fire methods.
  149. */
  150. var jsPlumbUIComponent = function(params) {
  151. var self = this, a = arguments, _hover = false;
  152. self._jsPlumb = params["_jsPlumb"];
  153. //self.parent = params["parent"];
  154. // all components can generate events
  155. EventGenerator.apply(this);
  156. // all components get this clone function.
  157. this.clone = function() {
  158. var o = new Object();
  159. self.constructor.apply(o, a);
  160. return o;
  161. };
  162. this.overlayPlacements = [],
  163. this.paintStyle = null,
  164. this.hoverPaintStyle = null;
  165. // helper method to update the hover style whenever it, or paintStyle, changes.
  166. // we use paintStyle as the foundation and merge hoverPaintStyle over the
  167. // top.
  168. var _updateHoverStyle = function() {
  169. if (self.paintStyle && self.hoverPaintStyle) {
  170. var mergedHoverStyle = {};
  171. jsPlumb.extend(mergedHoverStyle, self.paintStyle);
  172. jsPlumb.extend(mergedHoverStyle, self.hoverPaintStyle);
  173. delete self.hoverPaintStyle;
  174. // we want the fillStyle of paintStyle to override a gradient, if possible.
  175. if (mergedHoverStyle.gradient && self.paintStyle.fillStyle)
  176. delete mergedHoverStyle.gradient;
  177. self.hoverPaintStyle = mergedHoverStyle;
  178. }
  179. };
  180. /*
  181. * Sets the paint style and then repaints the element.
  182. *
  183. * Parameters:
  184. * style - Style to use.
  185. */
  186. this.setPaintStyle = function(style, doNotRepaint) {
  187. self.paintStyle = style;
  188. self.paintStyleInUse = self.paintStyle;
  189. _updateHoverStyle();
  190. if (!doNotRepaint) self.repaint();
  191. };
  192. /*
  193. * Sets the paint style to use when the mouse is hovering over the element. This is null by default.
  194. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  195. * it. This is because people will most likely want to change just one thing when hovering, say the
  196. * color for example, but leave the rest of the appearance the same.
  197. *
  198. * Parameters:
  199. * style - Style to use when the mouse is hovering.
  200. * doNotRepaint - if true, the component will not be repainted. useful when setting things up initially.
  201. */
  202. this.setHoverPaintStyle = function(style, doNotRepaint) {
  203. self.hoverPaintStyle = style;
  204. _updateHoverStyle();
  205. if (!doNotRepaint) self.repaint();
  206. };
  207. /*
  208. * sets/unsets the hover state of this element.
  209. *
  210. * Parameters:
  211. * hover - hover state boolean
  212. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  213. */
  214. this.setHover = function(hover, ignoreAttachedElements) {
  215. _hover = hover;
  216. if (self.hoverPaintStyle != null) {
  217. self.paintStyleInUse = hover ? self.hoverPaintStyle : self.paintStyle;
  218. self.repaint();
  219. // get the list of other affected elements. for a connection, its the endpoints. for an endpoint, its the connections! surprise.
  220. if (!ignoreAttachedElements)
  221. _updateAttachedElements(hover);
  222. }
  223. };
  224. this.isHover = function() {
  225. return _hover;
  226. };
  227. this.attachListeners = function(o, c) {
  228. var jpcl = jsPlumb.CurrentLibrary,
  229. events = [ "click", "dblclick", "mouseenter", "mouseout", "mousemove", "mousedown", "mouseup" ],
  230. eventFilters = { "mouseout":"mouseexit" },
  231. bindOne = function(evt) {
  232. var filteredEvent = eventFilters[evt] || evt;
  233. jpcl.bind(o, evt, function(ee) {
  234. c.fire(filteredEvent, c, ee);
  235. });
  236. };
  237. for (var i = 0; i < events.length; i++) {
  238. bindOne(events[i]);
  239. }
  240. };
  241. var _updateAttachedElements = function(state) {
  242. var affectedElements = self.getAttachedElements(); // implemented in subclasses
  243. if (affectedElements) {
  244. for (var i = 0; i < affectedElements.length; i++) {
  245. affectedElements[i].setHover(state, true); // tell the attached elements not to inform their own attached elements.
  246. }
  247. }
  248. };
  249. };
  250. var jsPlumbInstance = function(_defaults) {
  251. /*
  252. * Property: Defaults
  253. *
  254. * These are the default settings for jsPlumb. They are what will be used if you do not supply specific pieces of information
  255. * to the various API calls. A convenient way to implement your own look and feel can be to override these defaults
  256. * by including a script somewhere after the jsPlumb include, but before you make any calls to jsPlumb.
  257. *
  258. * Properties:
  259. * - *Anchor* The default anchor to use for all connections (both source and target). Default is "BottomCenter".
  260. * - *Anchors* The default anchors to use ([source, target]) for all connections. Defaults are ["BottomCenter", "BottomCenter"].
  261. * - *Connector* The default connector definition to use for all connections. Default is "Bezier".
  262. * - *DragOptions* The default drag options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  263. * - *DropOptions* The default drop options to pass in to connect, makeTarget and addEndpoint calls. Default is empty.
  264. * - *Endpoint* The default endpoint definition to use for all connections (both source and target). Default is "Dot".
  265. * - *Endpoints* The default endpoint definitions ([ source, target ]) to use for all connections. Defaults are ["Dot", "Dot"].
  266. * - *EndpointStyle* The default style definition to use for all endpoints. Default is empty.
  267. * - *EndpointStyles* The default style definitions ([ source, target ]) to use for all endpoints. Defaults are empty.
  268. * - *EndpointHoverStyle* The default hover style definition to use for all endpoints. Default is null.
  269. * - *EndpointHoverStyles* The default hover style definitions ([ source, target ]) to use for all endpoints. Defaults are null.
  270. * - *HoverPaintStyle* The default hover style definition to use for all connections. Defaults are null.
  271. * - *LabelStyle* The default style to use for label overlays on connections.
  272. * - *LogEnabled* Whether or not the jsPlumb log is enabled. defaults to false.
  273. * - *Overlays* The default overlay definitions. Defaults to an empty list.
  274. * - *MaxConnections* The default maximum number of connections for an Endpoint. Defaults to 1.
  275. * - *MouseEventsEnabled* Whether or not mouse events are enabled when using the canvas renderer. Defaults to true.
  276. * The idea of this is just to give people a way to prevent all the mouse listeners from activating if they know they won't need mouse events.
  277. * - *PaintStyle* The default paint style for a connection. Default is line width of 8 pixels, with color "#456".
  278. * - *RenderMode* What mode to use to paint with. If you're on IE<9, you don't really get to choose this. You'll just get VML. Otherwise, the jsPlumb default is to use Canvas elements.
  279. * - *Scope* The default "scope" to use for connections. Scope lets you assign connections to different categories.
  280. */
  281. this.Defaults = {
  282. Anchor : "BottomCenter",
  283. Anchors : [ null, null ],
  284. Connector : "Bezier",
  285. DragOptions : { },
  286. DropOptions : { },
  287. Endpoint : "Dot",
  288. Endpoints : [ null, null ],
  289. EndpointStyle : { fillStyle : null },
  290. EndpointStyles : [ null, null ],
  291. EndpointHoverStyle : null,
  292. EndpointHoverStyles : [ null, null ],
  293. HoverPaintStyle : null,
  294. LabelStyle : { color : "black" },
  295. LogEnabled : false,
  296. Overlays : [ ],
  297. MaxConnections : 1,
  298. MouseEventsEnabled : true,
  299. PaintStyle : { lineWidth : 8, strokeStyle : "#456" },
  300. RenderMode : "canvas",
  301. Scope : "_jsPlumb_DefaultScope"
  302. };
  303. if (_defaults) jsPlumb.extend(this.Defaults, _defaults);
  304. this.logEnabled = this.Defaults.LogEnabled;
  305. EventGenerator.apply(this);
  306. var _bb = this.bind;
  307. this.bind = function(event, fn) {
  308. if ("ready" === event && initialized) fn();
  309. else _bb(event, fn);
  310. };
  311. var _currentInstance = this,
  312. log = null,
  313. repaintFunction = function() {
  314. jsPlumb.repaintEverything();
  315. },
  316. automaticRepaint = true,
  317. repaintEverything = function() {
  318. if (automaticRepaint)
  319. repaintFunction();
  320. },
  321. resizeTimer = null,
  322. initialized = false,
  323. connectionsByScope = {},
  324. /**
  325. * map of element id -> endpoint lists. an element can have an arbitrary
  326. * number of endpoints on it, and not all of them have to be connected
  327. * to anything.
  328. */
  329. endpointsByElement = {},
  330. endpointsByUUID = {},
  331. offsets = {},
  332. offsetTimestamps = {},
  333. floatingConnections = {},
  334. draggableStates = {},
  335. _mouseEventsEnabled = this.Defaults.MouseEventsEnabled,
  336. _draggableByDefault = true,
  337. canvasList = [],
  338. sizes = [],
  339. listeners = {}, // a map: keys are event types, values are lists of listeners.
  340. DEFAULT_SCOPE = this.Defaults.Scope,
  341. renderMode = null, // will be set in init()
  342. /**
  343. * helper method to add an item to a list, creating the list if it does
  344. * not yet exist.
  345. */
  346. _addToList = function(map, key, value) {
  347. var l = map[key];
  348. if (l == null) {
  349. l = [];
  350. map[key] = l;
  351. }
  352. l.push(value);
  353. return l;
  354. },
  355. /**
  356. * appends an element to the given parent, or the document body if no
  357. * parent given.
  358. */
  359. _appendElement = function(el, parent) {
  360. if (!parent)
  361. document.body.appendChild(el);
  362. else
  363. jsPlumb.CurrentLibrary.appendElement(el, parent);
  364. },
  365. /**
  366. * creates a timestamp, using milliseconds since 1970, but as a string.
  367. */
  368. _timestamp = function() { return "" + (new Date()).getTime(); },
  369. /**
  370. * YUI, for some reason, put the result of a Y.all call into an object that contains
  371. * a '_nodes' array, instead of handing back an array-like object like the other
  372. * libraries do.
  373. */
  374. _convertYUICollection = function(c) {
  375. return c._nodes ? c._nodes : c;
  376. },
  377. /**
  378. * Draws an endpoint and its connections.
  379. *
  380. * @param element element to draw (of type library specific element object)
  381. * @param ui UI object from current library's event system. optional.
  382. * @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
  383. */
  384. _draw = function(element, ui, timestamp) {
  385. var id = _getAttribute(element, "id");
  386. var endpoints = endpointsByElement[id];
  387. if (!timestamp) timestamp = _timestamp();
  388. if (endpoints) {
  389. _updateOffset( { elId : id, offset : ui, recalc : false, timestamp : timestamp }); // timestamp is checked against last update cache; it is
  390. // valid for one paint cycle.
  391. var myOffset = offsets[id], myWH = sizes[id];
  392. for ( var i = 0; i < endpoints.length; i++) {
  393. endpoints[i].paint( { timestamp : timestamp, offset : myOffset, dimensions : myWH });
  394. var l = endpoints[i].connections;
  395. for ( var j = 0; j < l.length; j++) {
  396. l[j].paint( { elId : id, ui : ui, recalc : false, timestamp : timestamp }); // ...paint each connection.
  397. // then, check for dynamic endpoint; need to repaint it.
  398. var oIdx = l[j].endpoints[0] == endpoints[i] ? 1 : 0;
  399. if (l[j].endpoints[oIdx].anchor.isDynamic && !l[j].endpoints[oIdx].isFloating()) {
  400. var oId = oIdx == 0 ? l[j].sourceId : l[j].targetId,
  401. oOffset = offsets[oId], oWH = sizes[oId],
  402. // TODO i still want to make this faster.
  403. anchorLoc = l[j].endpoints[oIdx].anchor.compute( {
  404. xy : [ oOffset.left, oOffset.top ],
  405. wh : oWH,
  406. element : l[j].endpoints[oIdx],
  407. txy : [ myOffset.left, myOffset.top ],
  408. twh : myWH,
  409. tElement : endpoints[i]
  410. });
  411. l[j].endpoints[oIdx].paint({ anchorLoc : anchorLoc });
  412. }
  413. }
  414. }
  415. }
  416. },
  417. /**
  418. * executes the given function against the given element if the first
  419. * argument is an object, or the list of elements, if the first argument
  420. * is a list. the function passed in takes (element, elementId) as
  421. * arguments.
  422. */
  423. _elementProxy = function(element, fn) {
  424. var retVal = null;
  425. if (element.constructor == Array) {
  426. retVal = [];
  427. for ( var i = 0; i < element.length; i++) {
  428. var el = _getElementObject(element[i]), id = _getAttribute(el, "id");
  429. retVal.push(fn(el, id)); // append return values to what we will return
  430. }
  431. } else {
  432. var el = _getElementObject(element), id = _getAttribute(el, "id");
  433. retVal = fn(el, id);
  434. }
  435. return retVal;
  436. },
  437. /**
  438. * gets an Endpoint by uuid.
  439. */
  440. _getEndpoint = function(uuid) { return endpointsByUUID[uuid]; },
  441. /**
  442. * inits a draggable if it's not already initialised.
  443. */
  444. _initDraggableIfNecessary = function(element, isDraggable, dragOptions) {
  445. var draggable = isDraggable == null ? _draggableByDefault : isDraggable;
  446. if (draggable) {
  447. if (jsPlumb.CurrentLibrary.isDragSupported(element) && !jsPlumb.CurrentLibrary.isAlreadyDraggable(element)) {
  448. var options = dragOptions || _currentInstance.Defaults.DragOptions || jsPlumb.Defaults.DragOptions;
  449. options = jsPlumb.extend( {}, options); // make a copy.
  450. var dragEvent = jsPlumb.CurrentLibrary.dragEvents['drag'];
  451. var stopEvent = jsPlumb.CurrentLibrary.dragEvents['stop'];
  452. options[dragEvent] = _wrap(options[dragEvent], function() {
  453. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  454. _draw(element, ui);
  455. _addClass(element, "jsPlumb_dragged");
  456. });
  457. options[stopEvent] = _wrap(options[stopEvent], function() {
  458. var ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  459. _draw(element, ui);
  460. _removeClass(element, "jsPlumb_dragged");
  461. });
  462. var draggable = draggableStates[_getId(element)];
  463. options.disabled = draggable == null ? false : !draggable;
  464. jsPlumb.CurrentLibrary.initDraggable(element, options);
  465. }
  466. }
  467. },
  468. _newConnection = function(params) {
  469. var connectionFunc = jsPlumb.Defaults.ConnectionType || Connection,
  470. endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint,
  471. parent = jsPlumb.CurrentLibrary.getParent;
  472. if (params.sourceEndpoint)
  473. params["parent"] = params.sourceEndpoint.parent;
  474. else if (params.source.constructor == endpointFunc)
  475. params["parent"] = params.source.parent;
  476. else params["parent"] = parent(params.source);
  477. params["_jsPlumb"] = _currentInstance;
  478. var con = new connectionFunc(params);
  479. _eventFireProxy("click", "click", con);
  480. _eventFireProxy("dblclick", "dblclick", con);
  481. return con;
  482. },
  483. _eventFireProxy = function(event, proxyEvent, obj) {
  484. obj.bind(event, function(e) {
  485. _currentInstance.fire(proxyEvent, obj, e);
  486. });
  487. },
  488. _newEndpoint = function(params) {
  489. var endpointFunc = jsPlumb.Defaults.EndpointType || Endpoint;
  490. params["parent"] = jsPlumb.CurrentLibrary.getParent(params.source);
  491. params["_jsPlumb"] = _currentInstance,
  492. ep = new endpointFunc(params);
  493. _eventFireProxy("click", "endpointClick", ep);
  494. _eventFireProxy("dblclick", "endpointDblClick", ep);
  495. return ep;
  496. },
  497. /**
  498. * performs the given function operation on all the connections found
  499. * for the given element id; this means we find all the endpoints for
  500. * the given element, and then for each endpoint find the connectors
  501. * connected to it. then we pass each connection in to the given
  502. * function.
  503. */
  504. _operation = function(elId, func) {
  505. var endpoints = endpointsByElement[elId];
  506. if (endpoints && endpoints.length) {
  507. for ( var i = 0; i < endpoints.length; i++) {
  508. for ( var j = 0; j < endpoints[i].connections.length; j++) {
  509. var retVal = func(endpoints[i].connections[j]);
  510. // if the function passed in returns true, we exit.
  511. // most functions return false.
  512. if (retVal) return;
  513. }
  514. }
  515. }
  516. },
  517. /**
  518. * perform an operation on all elements.
  519. */
  520. _operationOnAll = function(func) {
  521. for ( var elId in endpointsByElement) {
  522. _operation(elId, func);
  523. }
  524. },
  525. /**
  526. * helper to remove an element from the DOM.
  527. */
  528. _removeElement = function(element, parent) {
  529. if (element != null && element.parentNode != null) {
  530. element.parentNode.removeChild(element);
  531. }
  532. },
  533. /**
  534. * helper to remove a list of elements from the DOM.
  535. */
  536. _removeElements = function(elements, parent) {
  537. for ( var i = 0; i < elements.length; i++)
  538. _removeElement(elements[i], parent);
  539. },
  540. /**
  541. * helper method to remove an item from a list.
  542. */
  543. _removeFromList = function(map, key, value) {
  544. if (key != null) {
  545. var l = map[key];
  546. if (l != null) {
  547. var i = _findIndex(l, value);
  548. if (i >= 0) {
  549. delete (l[i]);
  550. l.splice(i, 1);
  551. return true;
  552. }
  553. }
  554. }
  555. return false;
  556. },
  557. /**
  558. * Sets whether or not the given element(s) should be draggable,
  559. * regardless of what a particular plumb command may request.
  560. *
  561. * @param element
  562. * May be a string, a element objects, or a list of
  563. * strings/elements.
  564. * @param draggable
  565. * Whether or not the given element(s) should be draggable.
  566. */
  567. _setDraggable = function(element, draggable) {
  568. return _elementProxy(element, function(el, id) {
  569. draggableStates[id] = draggable;
  570. if (jsPlumb.CurrentLibrary.isDragSupported(el)) {
  571. jsPlumb.CurrentLibrary.setDraggable(el, draggable);
  572. }
  573. });
  574. },
  575. /**
  576. * private method to do the business of hiding/showing.
  577. *
  578. * @param el
  579. * either Id of the element in question or a library specific
  580. * object for the element.
  581. * @param state
  582. * String specifying a value for the css 'display' property
  583. * ('block' or 'none').
  584. */
  585. _setVisible = function(el, state) {
  586. _operation(_getAttribute(el, "id"), function(jpc) {
  587. jpc.canvas.style.display = state;
  588. });
  589. },
  590. /**
  591. * toggles the draggable state of the given element(s).
  592. *
  593. * @param el
  594. * either an id, or an element object, or a list of
  595. * ids/element objects.
  596. */
  597. _toggleDraggable = function(el) {
  598. return _elementProxy(el, function(el, elId) {
  599. var state = draggableStates[elId] == null ? _draggableByDefault : draggableStates[elId];
  600. state = !state;
  601. draggableStates[elId] = state;
  602. jsPlumb.CurrentLibrary.setDraggable(el, state);
  603. return state;
  604. });
  605. },
  606. /**
  607. * private method to do the business of toggling hiding/showing.
  608. *
  609. * @param elId
  610. * Id of the element in question
  611. */
  612. _toggleVisible = function(elId) {
  613. _operation(elId, function(jpc) {
  614. var state = ('none' == jpc.canvas.style.display);
  615. jpc.canvas.style.display = state ? "block" : "none";
  616. });
  617. // todo this should call _elementProxy, and pass in the
  618. // _operation(elId, f) call as a function. cos _toggleDraggable does
  619. // that.
  620. },
  621. /**
  622. * updates the offset and size for a given element, and stores the
  623. * values. if 'offset' is not null we use that (it would have been
  624. * passed in from a drag call) because it's faster; but if it is null,
  625. * or if 'recalc' is true in order to force a recalculation, we get the current values.
  626. */
  627. _updateOffset = function(params) {
  628. var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId;
  629. if (!recalc) {
  630. if (timestamp && timestamp === offsetTimestamps[elId])
  631. return;
  632. }
  633. if (recalc || offset == null) { // if forced repaint or no offset
  634. // available, we recalculate.
  635. // get the current size and offset, and store them
  636. var s = _getElementObject(elId);
  637. if (s != null) {
  638. sizes[elId] = _getSize(s);
  639. offsets[elId] = _getOffset(s);
  640. offsetTimestamps[elId] = timestamp;
  641. }
  642. } else {
  643. offsets[elId] = offset;
  644. }
  645. },
  646. /**
  647. * gets an id for the given element, creating and setting one if
  648. * necessary.
  649. */
  650. _getId = function(element, uuid) {
  651. var ele = _getElementObject(element);
  652. var id = _getAttribute(ele, "id");
  653. if (!id || id == "undefined") {
  654. // check if fixed uuid parameter is given
  655. if (arguments.length == 2 && arguments[1] != undefined)
  656. id = uuid;
  657. else
  658. id = "jsPlumb_" + _timestamp();
  659. _setAttribute(ele, "id", id);
  660. }
  661. return id;
  662. },
  663. /**
  664. * wraps one function with another, creating a placeholder for the
  665. * wrapped function if it was null. this is used to wrap the various
  666. * drag/drop event functions - to allow jsPlumb to be notified of
  667. * important lifecycle events without imposing itself on the user's
  668. * drag/drop functionality. TODO: determine whether or not we should
  669. * support an error handler concept, if one of the functions fails.
  670. *
  671. * @param wrappedFunction original function to wrap; may be null.
  672. * @param newFunction function to wrap the original with.
  673. * @param returnOnThisValue Optional. Indicates that the wrappedFunction should
  674. * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
  675. * note that this is a simple comparison and only works for primitives right now.
  676. */
  677. _wrap = function(wrappedFunction, newFunction, returnOnThisValue) {
  678. wrappedFunction = wrappedFunction || function() { };
  679. newFunction = newFunction || function() { };
  680. return function() {
  681. var r = null;
  682. try {
  683. r = newFunction.apply(this, arguments);
  684. } catch (e) {
  685. _log(_currentInstance, 'jsPlumb function failed : ' + e);
  686. }
  687. if (returnOnThisValue == null || (r !== returnOnThisValue)) {
  688. try {
  689. wrappedFunction.apply(this, arguments);
  690. } catch (e) {
  691. _log(_currentInstance, 'wrapped function failed : ' + e);
  692. }
  693. }
  694. return r;
  695. };
  696. };
  697. /*
  698. * Property: connectorClass
  699. * 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.
  700. */
  701. this.connectorClass = "_jsPlumb_connector";
  702. /*
  703. * Property: endpointClass
  704. * 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.
  705. */
  706. this.endpointClass = "_jsPlumb_endpoint";
  707. /*
  708. * Property: overlayClass
  709. * 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.
  710. */
  711. this.overlayClass = "_jsPlumb_overlay";
  712. this.Anchors = {};
  713. this.Connectors = {
  714. "canvas":{},
  715. "svg":{},
  716. "vml":{}
  717. };
  718. this.Endpoints = {
  719. "canvas":{},
  720. "svg":{},
  721. "vml":{}
  722. };
  723. this.Overlays = {
  724. "canvas":{},
  725. "svg":{},
  726. "vml":{}
  727. };
  728. // ************************ PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS *****************************************
  729. /*
  730. * Function: bind
  731. * Bind to an event on jsPlumb.
  732. *
  733. * Parameters:
  734. * event - the event to bind. Available events on jsPlumb are:
  735. * - *jsPlumbConnection* : notification that a new Connection was established. jsPlumb passes the new Connection to the callback.
  736. * - *jsPlumbConnectionDetached* : notification that a Connection was detached. jsPlumb passes the detached Connection to the callback.
  737. * - *click* : notification that a Connection was clicked. jsPlumb passes the Connection that was clicked to the callback.
  738. * - *dblclick* : notification that a Connection was double clicked. jsPlumb passes the Connection that was double clicked to the callback.
  739. * - *endpointClick* : notification that an Endpoint was clicked. jsPlumb passes the Endpoint that was clicked to the callback.
  740. * - *endpointDblClick* : notification that an Endpoint was double clicked. jsPlumb passes the Endpoint that was double clicked to the callback.
  741. *
  742. * callback - function to callback. This function will be passed the Connection/Endpoint that caused the event, and also the original event.
  743. */
  744. /*
  745. * Function: clearListeners
  746. * Clears either all listeners, or listeners for some specific event.
  747. *
  748. * Parameters:
  749. * event - optional. constrains the clear to just listeners for this event.
  750. */
  751. // *************** END OF PLACEHOLDER DOC ENTRIES FOR NATURAL DOCS ***********************************************************
  752. /*
  753. Function: addEndpoint
  754. Adds an <Endpoint> to a given element or elements.
  755. Parameters:
  756. el - Element to add the endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  757. params - Object containing Endpoint constructor arguments. For more information, see <Endpoint>.
  758. referenceParams - Object containing more Endpoint constructor arguments; it will be merged with params by jsPlumb. You would use this if you had some
  759. shared parameters that you wanted to reuse when you added Endpoints to a number of elements. The allowed values in
  760. this object are anything that 'params' can contain. See <Endpoint>.
  761. Returns:
  762. The newly created <Endpoint>, if el referred to a single element. Otherwise, an array of newly created <Endpoint>s.
  763. See Also:
  764. <addEndpoints>
  765. */
  766. this.addEndpoint = function(el, params, referenceParams) {
  767. referenceParams = referenceParams || {};
  768. var p = jsPlumb.extend({}, referenceParams);
  769. jsPlumb.extend(p, params);
  770. p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
  771. p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  772. // YUI wrapper
  773. el = _convertYUICollection(el);
  774. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  775. for (var i = 0; i < inputs.length; i++) {
  776. var _el = _getElementObject(inputs[i]), id = _getId(_el);
  777. p.source = _el;
  778. _updateOffset({ elId : id });
  779. var e = _newEndpoint(p);
  780. _addToList(endpointsByElement, id, e);
  781. var myOffset = offsets[id], myWH = sizes[id];
  782. var anchorLoc = e.anchor.compute( { xy : [ myOffset.left, myOffset.top ], wh : myWH, element : e });
  783. e.paint({ anchorLoc : anchorLoc });
  784. results.push(e);
  785. }
  786. return results.length == 1 ? results[0] : results;
  787. };
  788. /*
  789. Function: addEndpoints
  790. Adds a list of <Endpoint>s to a given element or elements.
  791. Parameters:
  792. target - element to add the Endpoint to. Either an element id, a selector representing some element(s), or an array of either of these.
  793. endpoints - List of objects containing Endpoint constructor arguments. one Endpoint is created for each entry in this list. See <Endpoint>'s constructor documentation.
  794. 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.
  795. Returns:
  796. List of newly created <Endpoint>s, one for each entry in the 'endpoints' argument.
  797. See Also:
  798. <addEndpoint>
  799. */
  800. this.addEndpoints = function(el, endpoints, referenceParams) {
  801. var results = [];
  802. for ( var i = 0; i < endpoints.length; i++) {
  803. Array.prototype.push.apply(results, _currentInstance.addEndpoint(el, endpoints[i], referenceParams));
  804. }
  805. return results;
  806. };
  807. /*
  808. Function: animate
  809. This is a wrapper around the supporting library's animate function; it injects a call to jsPlumb in the 'step' function (creating
  810. 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
  811. 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.
  812. Parameters:
  813. el - Element to animate. Either an id, or a selector representing the element.
  814. properties - The 'properties' argument you want passed to the library's animate call.
  815. options - The 'options' argument you want passed to the library's animate call.
  816. Returns:
  817. void
  818. */
  819. this.animate = function(el, properties, options) {
  820. var ele = _getElementObject(el), id = _getAttribute(el, "id");
  821. options = options || {};
  822. var stepFunction = jsPlumb.CurrentLibrary.dragEvents['step'];
  823. var completeFunction = jsPlumb.CurrentLibrary.dragEvents['complete'];
  824. options[stepFunction] = _wrap(options[stepFunction], function() {
  825. _currentInstance.repaint(id);
  826. });
  827. // onComplete repaints, just to make sure everything looks good at the end of the animation.
  828. options[completeFunction] = _wrap(options[completeFunction],
  829. function() {
  830. _currentInstance.repaint(id);
  831. });
  832. jsPlumb.CurrentLibrary.animate(ele, properties, options);
  833. };
  834. /*
  835. Function: connect
  836. Establishes a <Connection> between two elements (or <Endpoint>s, which are themselves registered to elements).
  837. Parameters:
  838. params - Object containing constructor arguments for the Connection. See <Connection>'s constructor documentation.
  839. referenceParams - Optional object containing more constructor arguments for the Connection. Typically you would pass in data that a lot of
  840. Connections are sharing here, such as connector style etc, and then use the main params for data specific to this Connection.
  841. Returns:
  842. The newly created <Connection>.
  843. */
  844. this.connect = function(params, referenceParams) {
  845. var _p = jsPlumb.extend( {}, params);
  846. if (referenceParams) jsPlumb.extend(_p, referenceParams);
  847. if (_p.source && _p.source.endpoint) _p.sourceEndpoint = _p.source;
  848. if (_p.source && _p.target.endpoint) _p.targetEndpoint = _p.target;
  849. // test for endpoint uuids to connect
  850. if (params.uuids) {
  851. _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
  852. _p.targetEndpoint = _getEndpoint(params.uuids[1]);
  853. }
  854. // now ensure that if we do have Endpoints already, they're not full.
  855. if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
  856. _log(_currentInstance, "could not add connection; source endpoint is full");
  857. return;
  858. }
  859. if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
  860. _log(_currentInstance, "could not add connection; target endpoint is full");
  861. return;
  862. }
  863. // dynamic anchors. backwards compatibility here: from 1.2.6 onwards you don't need to specify "dynamicAnchors". the fact that some anchor consists
  864. // of multiple definitions is enough to tell jsPlumb you want it to be dynamic.
  865. if (_p.dynamicAnchors) {
  866. // 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
  867. // case we will use a different set for each element.
  868. var a = _p.dynamicAnchors.constructor == Array;
  869. var sa = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.source));
  870. var ta = a ? new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors)) : new DynamicAnchor(jsPlumb.makeAnchors(_p.dynamicAnchors.target));
  871. _p.anchors = [sa,ta];
  872. }
  873. var jpc = _newConnection(_p);
  874. // add to list of connections (by scope).
  875. _addToList(connectionsByScope, jpc.scope, jpc);
  876. // fire an event
  877. _currentInstance.fire("jsPlumbConnection", {
  878. connection:jpc,
  879. source : jpc.source, target : jpc.target,
  880. sourceId : jpc.sourceId, targetId : jpc.targetId,
  881. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  882. });
  883. // force a paint
  884. _draw(jpc.source);
  885. return jpc;
  886. };
  887. /*
  888. Function: deleteEndpoint
  889. Deletes an Endpoint and removes all Connections it has (which removes the Connections from the other Endpoints involved too)
  890. Parameters:
  891. object - either an <Endpoint> object (such as from an addEndpoint call), or a String UUID.
  892. Returns:
  893. void
  894. */
  895. this.deleteEndpoint = function(object) {
  896. var endpoint = (typeof object == "string") ? endpointsByUUID[object] : object;
  897. if (endpoint) {
  898. var uuid = endpoint.getUuid();
  899. if (uuid) endpointsByUUID[uuid] = null;
  900. endpoint.detachAll();
  901. _removeElement(endpoint.canvas, endpoint.parent);
  902. // remove from endpointsbyElement
  903. for (var e in endpointsByElement) {
  904. var endpoints = endpointsByElement[e];
  905. if (endpoints) {
  906. var newEndpoints = [];
  907. for (var i = 0; i < endpoints.length; i++)
  908. if (endpoints[i] != endpoint) newEndpoints.push(endpoints[i]);
  909. endpointsByElement[e] = newEndpoints;
  910. }
  911. }
  912. delete endpoint;
  913. }
  914. };
  915. /*
  916. Function: deleteEveryEndpoint
  917. Deletes every <Endpoint>, and their associated <Connection>s, in this instance of jsPlumb. Does not unregister any event listeners (this is the only difference
  918. between this method and jsPlumb.reset).
  919. Returns:
  920. void
  921. */
  922. this.deleteEveryEndpoint = function() {
  923. for ( var id in endpointsByElement) {
  924. var endpoints = endpointsByElement[id];
  925. if (endpoints && endpoints.length) {
  926. for ( var i = 0; i < endpoints.length; i++) {
  927. _currentInstance.deleteEndpoint(endpoints[i]);
  928. }
  929. }
  930. }
  931. delete endpointsByElement;
  932. endpointsByElement = {};
  933. delete endpointsByUUID;
  934. endpointsByUUID = {};
  935. };
  936. var fireDetachEvent = function(jpc) {
  937. _currentInstance.fire("jsPlumbConnectionDetached", {
  938. connection:jpc,
  939. source : jpc.source, target : jpc.target,
  940. sourceId : jpc.sourceId, targetId : jpc.targetId,
  941. sourceEndpoint : jpc.endpoints[0], targetEndpoint : jpc.endpoints[1]
  942. });
  943. };
  944. /*
  945. Function: detach
  946. Detaches and then removes a <Connection>. Takes either (source, target) (the old way, maintained for backwards compatibility), or a params
  947. object with various possible values.
  948. Parameters:
  949. source - id or element object of the first element in the Connection.
  950. target - id or element object of the second element in the Connection.
  951. params - a JS object containing the same parameters as you pass to jsPlumb.connect. If this is present then neither source nor
  952. target should be present; it should be the only argument to the method. See the docs for <Connection>'s constructor for information
  953. about the parameters allowed in the params object.
  954. Returns:
  955. true if successful, false if not.
  956. */
  957. this.detach = function(source, target) {
  958. if (arguments.length == 2) {
  959. var s = _getElementObject(source), sId = _getId(s);
  960. var t = _getElementObject(target), tId = _getId(t);
  961. _operation(sId, function(jpc) {
  962. if ((jpc.sourceId == sId && jpc.targetId == tId) || (jpc.targetId == sId && jpc.sourceId == tId)) {
  963. _removeElements(jpc.connector.getDisplayElements(), jpc.parent);
  964. jpc.endpoints[0].removeConnection(jpc);
  965. jpc.endpoints[1].removeConnection(jpc);
  966. _removeFromList(connectionsByScope, jpc.scope, jpc);
  967. }
  968. });
  969. }
  970. // this is the new version of the method, taking a JS object like
  971. // the connect method does.
  972. else if (arguments.length == 1) {
  973. // TODO investigate whether or not this code still works when a user has supplied their own subclass of Connection. i suspect it may not.
  974. if (arguments[0].constructor == Connection) {
  975. arguments[0].endpoints[0].detachFrom(arguments[0].endpoints[1]);
  976. }
  977. else if (arguments[0].connection) {
  978. arguments[0].connection.endpoints[0].detachFrom(arguments[0].connection.endpoints[1]);
  979. }
  980. else {
  981. var _p = jsPlumb.extend( {}, source); // a backwards compatibility hack: source should be thought of as 'params' in this case.
  982. // test for endpoint uuids to detach
  983. if (_p.uuids) {
  984. _getEndpoint(_p.uuids[0]).detachFrom(_getEndpoint(_p.uuids[1]));
  985. } else if (_p.sourceEndpoint && _p.targetEndpoint) {
  986. _p.sourceEndpoint.detachFrom(_p.targetEndpoint);
  987. } else {
  988. var sourceId = _getId(_p.source);
  989. var targetId = _getId(_p.target);
  990. _operation(sourceId, function(jpc) {
  991. if ((jpc.sourceId == sourceId && jpc.targetId == targetId) || (jpc.targetId == sourceId && jpc.sourceId == targetId)) {
  992. _removeElements(jpc.connector.getDisplayElements(), jpc.parent);
  993. jpc.endpoints[0].removeConnection(jpc);
  994. jpc.endpoints[1].removeConnection(jpc);
  995. _removeFromList(connectionsByScope, jpc.scope, jpc);
  996. }
  997. });
  998. }
  999. }
  1000. }
  1001. };
  1002. /*
  1003. Function: detachAll
  1004. Removes all an element's Connections.
  1005. Parameters:
  1006. el - either the id of the element, or a selector for the element.
  1007. Returns:
  1008. void
  1009. */
  1010. this.detachAllConnections = function(el) {
  1011. var id = _getAttribute(el, "id");
  1012. var endpoints = endpointsByElement[id];
  1013. if (endpoints && endpoints.length) {
  1014. for ( var i = 0; i < endpoints.length; i++) {
  1015. endpoints[i].detachAll();
  1016. }
  1017. }
  1018. };
  1019. /**
  1020. * @deprecated Use detachAllConnections instead. this will be removed in jsPlumb 1.3.
  1021. */
  1022. this.detachAll = this.detachAllConnections;
  1023. /*
  1024. Function: detachEveryConnection
  1025. Remove all Connections from all elements, but leaves Endpoints in place.
  1026. Returns:
  1027. void
  1028. See Also:
  1029. <removeEveryEndpoint>
  1030. */
  1031. this.detachEveryConnection = function() {
  1032. for ( var id in endpointsByElement) {
  1033. var endpoints = endpointsByElement[id];
  1034. if (endpoints && endpoints.length) {
  1035. for ( var i = 0; i < endpoints.length; i++) {
  1036. endpoints[i].detachAll();
  1037. }
  1038. }
  1039. }
  1040. delete connectionsByScope;
  1041. connectionsByScope = {};
  1042. };
  1043. /**
  1044. * @deprecated use detachEveryConnection instead. this will be removed in jsPlumb 1.3.
  1045. */
  1046. this.detachEverything = this.detachEveryConnection;
  1047. /*
  1048. Function: draggable
  1049. 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.
  1050. Parameters:
  1051. el - either an element id, a list of element ids, or a selector.
  1052. options - options to pass through to the underlying library
  1053. Returns:
  1054. void
  1055. */
  1056. this.draggable = function(el, options) {
  1057. if (typeof el == 'object' && el.length) {
  1058. for ( var i = 0; i < el.length; i++) {
  1059. var ele = _getElementObject(el[i]);
  1060. if (ele) _initDraggableIfNecessary(ele, true, options);
  1061. }
  1062. }
  1063. else if (el._nodes) { // TODO this is YUI specific; really the logic should be forced
  1064. // into the library adapters (for jquery and mootools aswell)
  1065. for ( var i = 0; i < el._nodes.length; i++) {
  1066. var ele = _getElementObject(el._nodes[i]);
  1067. if (ele) _initDraggableIfNecessary(ele, true, options);
  1068. }
  1069. }
  1070. else {
  1071. var ele = _getElementObject(el);
  1072. if (ele) _initDraggableIfNecessary(ele, true, options);
  1073. }
  1074. };
  1075. /*
  1076. Function: extend
  1077. Wraps the underlying library's extend functionality.
  1078. Parameters:
  1079. o1 - object to extend
  1080. o2 - object to extend o1 with
  1081. Returns:
  1082. o1, extended with all properties from o2.
  1083. */
  1084. this.extend = function(o1, o2) {
  1085. return jsPlumb.CurrentLibrary.extend(o1, o2);
  1086. };
  1087. /*
  1088. * Function: getDefaultEndpointType
  1089. * Returns the default Endpoint type. Used when someone wants to subclass Endpoint and have jsPlumb return instances of their subclass.
  1090. * you would make a call like this in your class's constructor:
  1091. * jsPlumb.getDefaultEndpointType().apply(this, arguments);
  1092. *
  1093. * Returns:
  1094. * the default Endpoint function used by jsPlumb.
  1095. */
  1096. this.getDefaultEndpointType = function() {
  1097. return Endpoint;
  1098. };
  1099. /*
  1100. * Function: getDefaultConnectionType
  1101. * Returns the default Connection type. Used when someone wants to subclass Connection and have jsPlumb return instances of their subclass.
  1102. * you would make a call like this in your class's constructor:
  1103. * jsPlumb.getDefaultConnectionType().apply(this, arguments);
  1104. *
  1105. * Returns:
  1106. * the default Connection function used by jsPlumb.
  1107. */
  1108. this.getDefaultConnectionType = function() {
  1109. return Connection;
  1110. };
  1111. /*
  1112. * Function: getConnections
  1113. * Gets all or a subset of connections currently managed by this jsPlumb instance. If only one scope is passed in to this method,
  1114. * 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
  1115. * default scope). If multiple scopes are passed in, the return value will be a map of { scope -> [ connection... ] }.
  1116. *
  1117. * Parameters
  1118. * scope - if the only argument to getConnections is a string, jsPlumb will treat that string as a scope filter, and return a list
  1119. * of connections that are in the given scope.
  1120. * options - if the argument is a JS object, you can specify a finer-grained filter:
  1121. *
  1122. * - *scope* may be a string specifying a single scope, or an array of strings, specifying multiple scopes.
  1123. * - *source* either a string representing an element id, or a selector. constrains the result to connections having this source.
  1124. * - *target* either a string representing an element id, or a selector. constrains the result to connections having this target.
  1125. *
  1126. */
  1127. this.getConnections = function(options) {
  1128. if (!options) {
  1129. options = {};
  1130. } else if (options.constructor == String) {
  1131. options = { "scope": options };
  1132. }
  1133. var prepareList = function(input) {
  1134. var r = [];
  1135. if (input) {
  1136. if (typeof input == 'string')
  1137. r.push(input);
  1138. else
  1139. r = input;
  1140. }
  1141. return r;
  1142. };
  1143. var scope = options.scope || jsPlumb.getDefaultScope(),
  1144. scopes = prepareList(scope),
  1145. sources = prepareList(options.source),
  1146. targets = prepareList(options.target),
  1147. filter = function(list, value) {
  1148. return list.length > 0 ? _findIndex(list, value) != -1 : true;
  1149. },
  1150. results = scopes.length > 1 ? {} : [],
  1151. _addOne = function(scope, obj) {
  1152. if (scopes.length > 1) {
  1153. var ss = results[scope];
  1154. if (ss == null) {
  1155. ss = []; results[scope] = ss;
  1156. }
  1157. ss.push(obj);
  1158. } else results.push(obj);
  1159. };
  1160. for ( var i in connectionsByScope) {
  1161. if (filter(scopes, i)) {
  1162. for ( var j = 0; j < connectionsByScope[i].length; j++) {
  1163. var c = connectionsByScope[i][j];
  1164. if (filter(sources, c.sourceId) && filter(targets, c.targetId))
  1165. _addOne(i, c);
  1166. }
  1167. }
  1168. }
  1169. return results;
  1170. };
  1171. /*
  1172. * Function: getAllConnections
  1173. * Gets all connections, as a map of { scope -> [ connection... ] }.
  1174. */
  1175. this.getAllConnections = function() {
  1176. return connectionsByScope;
  1177. };
  1178. /*
  1179. * Function: getDefaultScope
  1180. * Gets the default scope for connections and endpoints. a scope defines a type of endpoint/connection; supplying a
  1181. * scope to an endpoint or connection allows you to support different
  1182. * types of connections in the same UI. but if you're only interested in
  1183. * one type of connection, you don't need to supply a scope. this method
  1184. * will probably be used by very few people; it's good for testing
  1185. * though.
  1186. */
  1187. this.getDefaultScope = function() {
  1188. return DEFAULT_SCOPE;
  1189. };
  1190. /*
  1191. Function: getEndpoint
  1192. Gets an Endpoint by UUID
  1193. Parameters:
  1194. uuid - the UUID for the Endpoint
  1195. Returns:
  1196. Endpoint with the given UUID, null if nothing found.
  1197. */
  1198. this.getEndpoint = _getEndpoint;
  1199. /**
  1200. * Function:getEndpoints
  1201. * Gets the list of Endpoints for a given selector, or element id.
  1202. * @param el
  1203. * @return
  1204. */
  1205. this.getEndpoints = function(el) {
  1206. return endpointsByElement[_getId(el)];
  1207. };
  1208. /*
  1209. * Gets an element's id, creating one if necessary. really only exposed
  1210. * for the lib-specific functionality to access; would be better to pass
  1211. * the current instance into the lib-specific code (even though this is
  1212. * a static call. i just don't want to expose it to the public API).
  1213. */
  1214. this.getId = _getId;
  1215. this.appendElement = _appendElement;
  1216. /*
  1217. Function: hide
  1218. Sets an element's connections to be hidden.
  1219. Parameters:
  1220. el - either the id of the element, or a selector for the element.
  1221. Returns:
  1222. void
  1223. */
  1224. this.hide = function(el) {
  1225. _setVisible(el, "none");
  1226. };
  1227. /**
  1228. * callback from the current library to tell us to prepare ourselves (attach
  1229. * mouse listeners etc; can't do that until the library has provided a bind method)
  1230. * @return
  1231. */
  1232. this.init = function() {
  1233. if (!initialized) {
  1234. _currentInstance.setRenderMode(_currentInstance.Defaults.RenderMode); // calling the method forces the capability logic to be run.
  1235. var _bind = function(event) {
  1236. jsPlumb.CurrentLibrary.bind(document, event, function(e) {
  1237. if (!_currentInstance.currentlyDragging && _mouseEventsEnabled && renderMode == jsPlumb.CANVAS) {
  1238. // try connections first
  1239. for (var scope in connectionsByScope) {
  1240. var c = connectionsByScope[scope];
  1241. for (var i = 0; i < c.length; i++) {
  1242. var t = c[i].connector[event](e);
  1243. if (t) return;
  1244. }
  1245. }
  1246. for (var el in endpointsByElement) {
  1247. var ee = endpointsByElement[el];
  1248. for (var i = 0; i < ee.length; i++) {
  1249. if (ee[i].endpoint[event](e)) return;
  1250. }
  1251. }
  1252. }
  1253. });
  1254. };
  1255. _bind("click");
  1256. _bind("dblclick");
  1257. _bind("mousemove");
  1258. _bind("mousedown");
  1259. _bind("mouseup");
  1260. initialized = true;
  1261. _currentInstance.fire("ready");
  1262. }
  1263. };
  1264. this.jsPlumbUIComponent = jsPlumbUIComponent;
  1265. this.EventGenerator = EventGenerator;
  1266. /*
  1267. * Creates an anchor with the given params.
  1268. *
  1269. * You do not need to use this method. It is exposed because of the way jsPlumb is
  1270. * split into three scripts; this will change in the future.
  1271. *
  1272. * x - the x location of the anchor as a fraction of the
  1273. * total width. y - the y location of the anchor as a fraction of the
  1274. * total height. xOrientation - value indicating the general direction a
  1275. * connection from the anchor should go in, in the x direction.
  1276. * yOrientation - value indicating the general direction a connection
  1277. * from the anchor should go in, in the y direction. xOffset - a fixed
  1278. * offset that should be applied in the x direction that should be
  1279. * applied after the x position has been figured out. optional. defaults
  1280. * to 0. yOffset - a fixed offset that should be applied in the y
  1281. * direction that should be applied after the y position has been
  1282. * figured out. optional. defaults to 0.
  1283. * -- OR --
  1284. *
  1285. * params - {x:..., y:..., xOrientation etc }
  1286. * -- OR FROM 1.2.4 ---
  1287. *
  1288. * name - the name of some Anchor in the _currentInstance.Anchors array.
  1289. * -- OR FROM 1.2.4 ---
  1290. *
  1291. * coords - a list of coords for the anchor, like you would pass to
  1292. * jsPlumb.makeAnchor (eg [0.5,0.5,0,-1] - an anchor in the center of
  1293. * some element, oriented towards the top of the screen)
  1294. * -- OR FROM 1.2.4 ---
  1295. *
  1296. * anchor - an existing anchor. just gets passed back. it's handy
  1297. * internally to have this functionality.
  1298. *
  1299. * Returns: The newly created Anchor.
  1300. */
  1301. this.makeAnchor = function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
  1302. // backwards compatibility here. we used to require an object passed
  1303. // in but that makes the call very verbose. easier to use
  1304. // by just passing in four/six values. but for backwards
  1305. // compatibility if we are given only one value we assume it's a
  1306. // call in the old form.
  1307. if (arguments.length == 0) return null;
  1308. var params = {};
  1309. if (arguments.length == 1) {
  1310. var specimen = arguments[0];
  1311. // if it appears to be an anchor already...
  1312. if (specimen.compute && specimen.getOrientation) return specimen;
  1313. // is it the name of an anchor type?
  1314. else if (typeof specimen == "string") return _currentInstance.Anchors[arguments[0]]();
  1315. // is it an array of coordinates?
  1316. else if (specimen.constructor == Array) {
  1317. if (specimen[0].constructor == Array || specimen[0].constructor == String)
  1318. return new DynamicAnchor(specimen);
  1319. else
  1320. return jsPlumb.makeAnchor.apply(this, specimen);
  1321. }
  1322. // last we try the backwards compatibility stuff.
  1323. else if (typeof arguments[0] == "object") jsPlumb.extend(params, x);
  1324. } else {
  1325. params = { x : x, y : y };
  1326. if (arguments.length >= 4) params.orientation = [ arguments[2], arguments[3] ];
  1327. if (arguments.length == 6) params.offsets = [ arguments[4], arguments[5] ];
  1328. }
  1329. var a = new Anchor(params);
  1330. a.clone = function() {
  1331. return new Anchor(params);
  1332. };
  1333. return a;
  1334. };
  1335. /**
  1336. * makes a list of anchors from the given list of types or coords, eg
  1337. * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
  1338. */
  1339. this.makeAnchors = function(types) {
  1340. var r = [];
  1341. for ( var i = 0; i < types.length; i++)
  1342. if (typeof types[i] == "string")
  1343. r.push(_currentInstance.Anchors[types[i]]());
  1344. else if (types[i].constructor == Array)
  1345. r.push(jsPlumb.makeAnchor(types[i]));
  1346. return r;
  1347. };
  1348. /**
  1349. * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
  1350. * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
  1351. * not need to provide this - i think).
  1352. */
  1353. this.makeDynamicAnchor = function(anchors, anchorSelector) {
  1354. return new DynamicAnchor(anchors, anchorSelector);
  1355. };
  1356. /**
  1357. * Function: makeTarget
  1358. * Makes some DOM element a Connection target, allowing you to drag connections to it
  1359. * without having to register any Endpoints on it first. When a Connection is established,
  1360. * the endpoint spec that was passed in to this method is used to create a suitable
  1361. * Endpoint (the default will be used if you do not provide one).
  1362. *
  1363. * Parameters:
  1364. * el - string id or element selector for the element to make a target.
  1365. * params - JS object containing parameters:
  1366. * endpoint optional. specification of an endpoint to create when a connection is created.
  1367. * scope optional. scope for the drop zone.
  1368. * dropOptions optional. same stuff as you would pass to dropOptions of an Endpoint definition.
  1369. * deleteEndpointsOnDetach optional, defaults to false. whether or not to delete
  1370. * any Endpoints created by a connection to this target if
  1371. * the connection is subsequently detached. this will not
  1372. * remove Endpoints that have had more Connections attached
  1373. * to them after they were created.
  1374. *
  1375. *
  1376. */
  1377. this.makeTarget = function(el, params, referenceParams) {
  1378. var p = jsPlumb.extend({}, referenceParams);
  1379. jsPlumb.extend(p, params);
  1380. var jpcl = jsPlumb.CurrentLibrary,
  1381. scope = p.scope || _currentInstance.Defaults.Scope,
  1382. deleteEndpointsOnDetach = p.deleteEndpointsOnDetach || false,
  1383. _doOne = function(_el) {
  1384. var dropOptions = jsPlumb.extend({}, p.dropOptions || {});
  1385. var _drop = function() {
  1386. var draggable = _getElementObject(jpcl.getDragObject(arguments)),
  1387. id = _getAttribute(draggable, "dragId"),
  1388. // restore the original scope if necessary (issue 57)
  1389. scope = _getAttribute(draggable, "originalScope");
  1390. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  1391. // get the connection, to then get its endpoint
  1392. var jpc = floatingConnections[id],
  1393. source = jpc.endpoints[0],
  1394. _endpoint = p.endpoint ? jsPlumb.extend({}, p.endpoint) : null,
  1395. // make a new Endpoint
  1396. newEndpoint = jsPlumb.addEndpoint(_el, _endpoint);
  1397. var c = jsPlumb.connect({
  1398. source:source,
  1399. target:newEndpoint,
  1400. scope:scope
  1401. });
  1402. if (deleteEndpointsOnDetach)
  1403. c.endpointToDeleteOnDetach = newEndpoint;
  1404. };
  1405. var dropEvent = jpcl.dragEvents['drop'];
  1406. dropOptions["scope"] = dropOptions["scope"] || scope;
  1407. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], _drop);
  1408. jpcl.initDroppable(_el, dropOptions);
  1409. };
  1410. el = _convertYUICollection(el);
  1411. var results = [], inputs = el.length && el.constructor != String ? el : [ el ];
  1412. for (var i = 0; i < inputs.length; i++) {
  1413. _doOne(_getElementObject(inputs[i]));
  1414. }
  1415. };
  1416. /**
  1417. * helper method to make a list of elements drop targets.
  1418. * @param els
  1419. * @param params
  1420. * @param referenceParams
  1421. * @return
  1422. */
  1423. this.makeTargets = function(els, params, referenceParams) {
  1424. for ( var i = 0; i < els.length; i++) {
  1425. _currentInstance.makeTarget(els[i], params, referenceParams);
  1426. }
  1427. };
  1428. /*
  1429. Function: repaint
  1430. Repaints an element and its connections. This method gets new sizes for the elements before painting anything.
  1431. Parameters:
  1432. el - either the id of the element or a selector representing the element.
  1433. Returns:
  1434. void
  1435. See Also:
  1436. <repaintEverything>
  1437. */
  1438. this.repaint = function(el) {
  1439. var _processElement = function(el) { _draw(_getElementObject(el)); };
  1440. // support both lists...
  1441. if (typeof el == 'object')
  1442. for ( var i = 0; i < el.length; i++) _processElement(el[i]);
  1443. else // ...and single strings.
  1444. _processElement(el);
  1445. };
  1446. /*
  1447. Function: repaintEverything
  1448. Repaints all connections.
  1449. Returns:
  1450. void
  1451. See Also:
  1452. <repaint>
  1453. */
  1454. this.repaintEverything = function() {
  1455. var timestamp = _timestamp();
  1456. for ( var elId in endpointsByElement) {
  1457. _draw(_getElementObject(elId), null, timestamp);
  1458. }
  1459. };
  1460. /*
  1461. Function: removeAllEndpoints
  1462. Removes all Endpoints associated with a given element. Also removes all Connections associated with each Endpoint it removes.
  1463. Parameters:
  1464. el - either an element id, or a selector for an element.
  1465. Returns:
  1466. void
  1467. See Also:
  1468. <removeEndpoint>
  1469. */
  1470. this.removeAllEndpoints = function(el) {
  1471. var elId = _getAttribute(el, "id");
  1472. var ebe = endpointsByElement[elId];
  1473. for ( var i in ebe)
  1474. _currentInstance.deleteEndpoint(ebe[i]);
  1475. endpointsByElement[elId] = [];
  1476. };
  1477. /*
  1478. Removes every Endpoint in this instance of jsPlumb.
  1479. @deprecated use deleteEveryEndpoint instead
  1480. */
  1481. this.removeEveryEndpoint = this.deleteEveryEndpoint;
  1482. /*
  1483. Removes the given Endpoint from the given element.
  1484. @deprecated Use jsPlumb.deleteEndpoint instead (and note you dont need to supply the element. it's irrelevant).
  1485. */
  1486. this.removeEndpoint = function(el, endpoint) {
  1487. _currentInstance.deleteEndpoint(endpoint);
  1488. };
  1489. /*
  1490. Function:reset
  1491. Removes all endpoints and connections and clears the listener list. To keep listeners call jsPlumb.deleteEveryEndpoint instead of this.
  1492. */
  1493. this.reset = function() {
  1494. this.deleteEveryEndpoint();
  1495. this.clearListeners();
  1496. };
  1497. /*
  1498. Function: setAutomaticRepaint
  1499. Sets/unsets automatic repaint on window resize.
  1500. Parameters:
  1501. value - whether or not to automatically repaint when the window is resized.
  1502. Returns: void
  1503. */
  1504. this.setAutomaticRepaint = function(value) {
  1505. automaticRepaint = value;
  1506. };
  1507. /*
  1508. * Function: setDefaultScope
  1509. * Sets the default scope for Connections and Endpoints. A scope defines a type of Endpoint/Connection; supplying a
  1510. * scope to an Endpoint or Connection allows you to support different
  1511. * types of Connections in the same UI. If you're only interested in
  1512. * one type of Connection, you don't need to supply a scope. This method
  1513. * will probably be used by very few people; it just instructs jsPlumb
  1514. * to use a different key for the default scope.
  1515. *
  1516. * Parameters:
  1517. * scope - scope to set as default.
  1518. */
  1519. this.setDefaultScope = function(scope) {
  1520. DEFAULT_SCOPE = scope;
  1521. };
  1522. /*
  1523. * Function: setDraggable
  1524. * Sets whether or not a given element is
  1525. * draggable, regardless of what any jsPlumb command may request.
  1526. *
  1527. * Parameters:
  1528. * el - either the id for the element, or a selector representing the element.
  1529. *
  1530. * Returns:
  1531. * void
  1532. */
  1533. this.setDraggable = _setDraggable;
  1534. /*
  1535. * Function: setDraggableByDefault
  1536. * Sets whether or not elements are draggable by default. Default for this is true.
  1537. *
  1538. * Parameters:
  1539. * draggable - value to set
  1540. *
  1541. * Returns:
  1542. * void
  1543. */
  1544. this.setDraggableByDefault = function(draggable) {
  1545. _draggableByDefault = draggable;
  1546. };
  1547. this.setDebugLog = function(debugLog) {
  1548. log = debugLog;
  1549. };
  1550. /*
  1551. * Function: setRepaintFunction
  1552. * Sets the function to fire when the window size has changed and a repaint was fired.
  1553. *
  1554. * Parameters:
  1555. * f - Function to execute.
  1556. *
  1557. * Returns: void
  1558. */
  1559. this.setRepaintFunction = function(f) {
  1560. repaintFunction = f;
  1561. };
  1562. /*
  1563. * Function: setMouseEventsEnabled
  1564. * Sets whether or not mouse events are enabled. Default is true.
  1565. *
  1566. * Parameters:
  1567. * enabled - whether or not mouse events should be enabled.
  1568. *
  1569. * Returns:
  1570. * void
  1571. */
  1572. this.setMouseEventsEnabled = function(enabled) {
  1573. _mouseEventsEnabled = enabled;
  1574. };
  1575. /*
  1576. * Constant for use with the setRenderMode method
  1577. */
  1578. this.CANVAS = "canvas";
  1579. /*
  1580. * Constant for use with the setRenderMode method
  1581. */
  1582. this.SVG = "svg";
  1583. this.VML = "vml";
  1584. /*
  1585. * Function: setRenderMode
  1586. * Sets render mode: jsPlumb.CANVAS, jsPlumb.SVG or jsPlumb.VML. jsPlumb will fall back to VML if it determines that
  1587. * what you asked for is not supported (and that VML is). If you asked for VML but the browser does
  1588. * not support it, jsPlumb uses SVG.
  1589. *
  1590. * Returns:
  1591. * the render mode that jsPlumb set, which of course may be different from that requested.
  1592. */
  1593. this.setRenderMode = function(mode) {
  1594. if (mode)
  1595. mode = mode.toLowerCase();
  1596. else
  1597. return;
  1598. 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");
  1599. // now test we actually have the capability to do this.
  1600. if (mode === jsPlumb.CANVAS && canvasAvailable)
  1601. renderMode = jsPlumb.CANVAS;
  1602. else if (mode === jsPlumb.SVG && svgAvailable)
  1603. renderMode = jsPlumb.SVG;
  1604. else if (vmlAvailable)
  1605. renderMode = jsPlumb.VML;
  1606. return renderMode;
  1607. };
  1608. this.getRenderMode = function() { return renderMode; };
  1609. /*
  1610. * Function: show
  1611. * Sets an element's connections to be visible.
  1612. *
  1613. * Parameters:
  1614. * el - either the id of the element, or a selector for the element.
  1615. *
  1616. * Returns:
  1617. * void
  1618. */
  1619. this.show = function(el) {
  1620. _setVisible(el, "block");
  1621. };
  1622. /*
  1623. * Function: sizeCanvas
  1624. * Helper to size a canvas. You would typically use
  1625. * this when writing your own Connector or Endpoint implementation.
  1626. *
  1627. * Parameters:
  1628. * x - [int] x position for the Canvas origin
  1629. * y - [int] y position for the Canvas origin
  1630. * w - [int] width of the canvas
  1631. * h - [int] height of the canvas
  1632. *
  1633. * Returns:
  1634. * void
  1635. */
  1636. this.sizeCanvas = function(canvas, x, y, w, h) {
  1637. if (canvas) {
  1638. canvas.style.height = h + "px";
  1639. canvas.height = h;
  1640. canvas.style.width = w + "px";
  1641. canvas.width = w;
  1642. canvas.style.left = x + "px";
  1643. canvas.style.top = y + "px";
  1644. }
  1645. };
  1646. /**
  1647. * gets some test hooks. nothing writable.
  1648. */
  1649. this.getTestHarness = function() {
  1650. return {
  1651. endpointsByElement : endpointsByElement,
  1652. endpointCount : function(elId) {
  1653. var e = endpointsByElement[elId];
  1654. return e ? e.length : 0;
  1655. },
  1656. connectionCount : function(scope) {
  1657. scope = scope || DEFAULT_SCOPE;
  1658. var c = connectionsByScope[scope];
  1659. return c ? c.length : 0;
  1660. },
  1661. findIndex : _findIndex,
  1662. getId : _getId,
  1663. makeAnchor:self.makeAnchor,
  1664. makeDynamicAnchor:self.makeDynamicAnchor
  1665. };
  1666. };
  1667. /**
  1668. * Toggles visibility of an element's connections. kept for backwards
  1669. * compatibility
  1670. */
  1671. this.toggle = _toggleVisible;
  1672. /*
  1673. * Function: toggleVisible
  1674. * Toggles visibility of an element's Connections.
  1675. *
  1676. * Parameters:
  1677. * el - either the element's id, or a selector representing the element.
  1678. *
  1679. * Returns:
  1680. * void, but should be updated to return the current state
  1681. */
  1682. // TODO: update this method to return the current state.
  1683. this.toggleVisible = _toggleVisible;
  1684. /*
  1685. * Function: toggleDraggable
  1686. * Toggles draggability (sic?) of an element's Connections.
  1687. *
  1688. * Parameters:
  1689. * el - either the element's id, or a selector representing the element.
  1690. *
  1691. * Returns:
  1692. * The current draggable state.
  1693. */
  1694. this.toggleDraggable = _toggleDraggable;
  1695. /*
  1696. * Function: unload
  1697. * Unloads jsPlumb, deleting all storage. You should call this from an onunload attribute on the <body> element.
  1698. *
  1699. * Returns:
  1700. * void
  1701. */
  1702. this.unload = function() {
  1703. delete endpointsByElement;
  1704. delete endpointsByUUID;
  1705. delete offsets;
  1706. delete sizes;
  1707. delete floatingConnections;
  1708. delete draggableStates;
  1709. delete canvasList;
  1710. };
  1711. /*
  1712. * Helper method to wrap an existing function with one of
  1713. * your own. This is used by the various implementations to wrap event
  1714. * callbacks for drag/drop etc; it allows jsPlumb to be transparent in
  1715. * its handling of these things. If a user supplies their own event
  1716. * callback, for anything, it will always be called.
  1717. */
  1718. this.wrap = _wrap;
  1719. this.addListener = this.bind;
  1720. /**
  1721. * 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
  1722. * 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"),
  1723. * 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
  1724. * creation of Anchors without user intervention.
  1725. */
  1726. var Anchor = function(params) {
  1727. var self = this;
  1728. this.x = params.x || 0;
  1729. this.y = params.y || 0;
  1730. var orientation = params.orientation || [ 0, 0 ];
  1731. var lastTimestamp = null, lastReturnValue = null;
  1732. this.offsets = params.offsets || [ 0, 0 ];
  1733. self.timestamp = null;
  1734. this.compute = function(params) {
  1735. var xy = params.xy, wh = params.wh, element = params.element, timestamp = params.timestamp;
  1736. if (timestamp && timestamp === self.timestamp) {
  1737. return lastReturnValue;
  1738. }
  1739. lastReturnValue = [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
  1740. //*
  1741. var container = element ? element.parent : null;
  1742. if (container != null) {
  1743. var parentPosition = element.canvas.parentNode.style.position;
  1744. var parentIsPositioned = parentPosition != null && parentPosition != "" && parentPosition != "static";
  1745. if (parentIsPositioned) {
  1746. console.log("positioning");
  1747. var o = _getOffset(element.canvas.parentNode);
  1748. lastReturnValue[0] = lastReturnValue[0] - o.left;
  1749. lastReturnValue[1] = lastReturnValue[1] - o.top;
  1750. }
  1751. }
  1752. //*/
  1753. self.timestamp = timestamp;
  1754. return lastReturnValue;
  1755. };
  1756. this.getOrientation = function() { return orientation; };
  1757. this.equals = function(anchor) {
  1758. if (!anchor) return false;
  1759. var ao = anchor.getOrientation();
  1760. var o = this.getOrientation();
  1761. return this.x == anchor.x && this.y == anchor.y
  1762. && this.offsets[0] == anchor.offsets[0]
  1763. && this.offsets[1] == anchor.offsets[1]
  1764. && o[0] == ao[0] && o[1] == ao[1];
  1765. };
  1766. this.getCurrentLocation = function() { return lastReturnValue; };
  1767. };
  1768. /**
  1769. * An Anchor that floats. its orientation is computed dynamically from
  1770. * its position relative to the anchor it is floating relative to. It is used when creating
  1771. * a connection through drag and drop.
  1772. *
  1773. * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
  1774. */
  1775. var FloatingAnchor = function(params) {
  1776. // this is the anchor that this floating anchor is referenced to for
  1777. // purposes of calculating the orientation.
  1778. var ref = params.reference;
  1779. // the canvas this refers to.
  1780. var refCanvas = params.referenceCanvas;
  1781. var size = _getSize(_getElementObject(refCanvas));
  1782. // these are used to store the current relative position of our
  1783. // anchor wrt the reference anchor. they only indicate
  1784. // direction, so have a value of 1 or -1 (or, very rarely, 0). these
  1785. // values are written by the compute method, and read
  1786. // by the getOrientation method.
  1787. var xDir = 0, yDir = 0;
  1788. // temporary member used to store an orientation when the floating
  1789. // anchor is hovering over another anchor.
  1790. var orientation = null;
  1791. var _lastResult = null;
  1792. this.compute = function(params) {
  1793. var xy = params.xy, element = params.element;
  1794. 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.
  1795. //*
  1796. var container = element ? element.parent : null;
  1797. if (container != null) {
  1798. var parentPosition = element.canvas.parentNode.style.position;
  1799. var parentIsPositioned = parentPosition != null && parentPosition != "" && parentPosition != "static";
  1800. if (parentIsPositioned) {
  1801. var o = _getOffset(element.canvas.parentNode);
  1802. result[0] = result[0] - o.left;
  1803. result[1] = result[1] - o.top;
  1804. }
  1805. }
  1806. //*/
  1807. _lastResult = result;
  1808. return result;
  1809. };
  1810. this.getOrientation = function() {
  1811. if (orientation) return orientation;
  1812. else {
  1813. var o = ref.getOrientation();
  1814. // here we take into account the orientation of the other
  1815. // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
  1816. // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
  1817. return [ Math.abs(o[0]) * xDir * -1,
  1818. Math.abs(o[1]) * yDir * -1 ];
  1819. }
  1820. };
  1821. /**
  1822. * notification the endpoint associated with this anchor is hovering
  1823. * over another anchor; we want to assume that anchor's orientation
  1824. * for the duration of the hover.
  1825. */
  1826. this.over = function(anchor) { orientation = anchor.getOrientation(); };
  1827. /**
  1828. * notification the endpoint associated with this anchor is no
  1829. * longer hovering over another anchor; we should resume calculating
  1830. * orientation as we normally do.
  1831. */
  1832. this.out = function() { orientation = null; };
  1833. this.getCurrentLocation = function() { return _lastResult; };
  1834. };
  1835. /*
  1836. * A DynamicAnchors is an Anchor that contains a list of other Anchors, which it cycles
  1837. * through at compute time to find the one that is located closest to
  1838. * the center of the target element, and returns that Anchor's compute
  1839. * method result. this causes endpoints to follow each other with
  1840. * respect to the orientation of their target elements, which is a useful
  1841. * feature for some applications.
  1842. *
  1843. */
  1844. var DynamicAnchor = function(anchors, anchorSelector) {
  1845. this.isSelective = true;
  1846. this.isDynamic = true;
  1847. var _anchors = [];
  1848. var _convert = function(anchor) { return anchor.constructor == Anchor ? anchor: jsPlumb.makeAnchor(anchor); };
  1849. for (var i = 0; i < anchors.length; i++) _anchors[i] = _convert(anchors[i]);
  1850. this.addAnchor = function(anchor) { _anchors.push(_convert(anchor)); };
  1851. this.getAnchors = function() { return _anchors; };
  1852. var _curAnchor = _anchors.length > 0 ? _anchors[0] : null;
  1853. var _curIndex = _anchors.length > 0 ? 0 : -1;
  1854. this.locked = false;
  1855. var self = this;
  1856. // helper method to calculate the distance between the centers of the two elements.
  1857. var _distance = function(anchor, cx, cy, xy, wh) {
  1858. var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]);
  1859. return Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2));
  1860. };
  1861. // default method uses distance between element centers. you can provide your own method in the dynamic anchor
  1862. // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
  1863. // xy - xy loc of the anchor's element
  1864. // wh - anchor's element's dimensions
  1865. // txy - xy loc of the element of the other anchor in the connection
  1866. // twh - dimensions of the element of the other anchor in the connection.
  1867. // anchors - the list of selectable anchors
  1868. var _anchorSelector = anchorSelector || function(xy, wh, txy, twh, anchors) {
  1869. var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
  1870. var minIdx = -1, minDist = Infinity;
  1871. for ( var i = 0; i < anchors.length; i++) {
  1872. var d = _distance(anchors[i], cx, cy, xy, wh);
  1873. if (d < minDist) {
  1874. minIdx = i + 0;
  1875. minDist = d;
  1876. }
  1877. }
  1878. return anchors[minIdx];
  1879. };
  1880. this.compute = function(params) {
  1881. var xy = params.xy, wh = params.wh, timestamp = params.timestamp, txy = params.txy, twh = params.twh;
  1882. // if anchor is locked or an opposite element was not given, we
  1883. // maintain our state. anchor will be locked
  1884. // if it is the source of a drag and drop.
  1885. if (self.locked || txy == null || twh == null)
  1886. return _curAnchor.compute(params);
  1887. else
  1888. params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
  1889. _curAnchor = _anchorSelector(xy, wh, txy, twh, _anchors);
  1890. var pos = _curAnchor.compute(params);
  1891. return pos;
  1892. };
  1893. this.getCurrentLocation = function() {
  1894. var cl = _curAnchor != null ? _curAnchor.getCurrentLocation() : null;
  1895. return cl;
  1896. };
  1897. this.getOrientation = function() { return _curAnchor != null ? _curAnchor.getOrientation() : [ 0, 0 ]; };
  1898. this.over = function(anchor) { if (_curAnchor != null) _curAnchor.over(anchor); };
  1899. this.out = function() { if (_curAnchor != null) _curAnchor.out(); };
  1900. };
  1901. /*
  1902. * Class: Connection
  1903. * The connecting line between two Endpoints.
  1904. */
  1905. /*
  1906. * Function: Connection
  1907. * Connection constructor.
  1908. *
  1909. * Parameters:
  1910. * source - either an element id, a selector for an element, or an Endpoint.
  1911. * target - either an element id, a selector for an element, or an Endpoint
  1912. * scope - scope descriptor for this connection. optional.
  1913. * endpoint - Optional. Endpoint definition to use for both ends of the connection.
  1914. * endpoints - Optional. Array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  1915. * endpointStyle - Optional. Endpoint style definition to use for both ends of the Connection.
  1916. * endpointStyles - Optional. Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  1917. * paintStyle - Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
  1918. * 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).
  1919. * overlays - Optional array of Overlay definitions to appear on this Connection.
  1920. */
  1921. var Connection = function(params) {
  1922. jsPlumbUIComponent.apply(this, arguments);
  1923. // ************** get the source and target and register the connection. *******************
  1924. var self = this;
  1925. var visible = true;
  1926. /**
  1927. Function:isVisible
  1928. Returns whether or not the Connection is currently visible.
  1929. */
  1930. this.isVisible = function() { return visible; };
  1931. /**
  1932. Function: setVisible
  1933. Sets whether or not the Connection should be visible.
  1934. Parameters:
  1935. visible - boolean indicating desired visible state.
  1936. */
  1937. this.setVisible = function(v) {
  1938. visible = v;
  1939. if (self.connector && self.connector.canvas) self.connector.canvas.style.display = v ? "block" : "none";
  1940. };
  1941. var id = new String('_jsplumb_c_' + (new Date()).getTime());
  1942. this.getId = function() { return id; };
  1943. this.parent = params.parent;
  1944. /**
  1945. Property: source
  1946. The source element for this Connection.
  1947. */
  1948. this.source = _getElementObject(params.source);
  1949. /**
  1950. Property:target
  1951. The target element for this Connection.
  1952. */
  1953. this.target = _getElementObject(params.target);
  1954. // sourceEndpoint and targetEndpoint override source/target, if they are present.
  1955. if (params.sourceEndpoint) this.source = params.sourceEndpoint.getElement();
  1956. if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();
  1957. /*
  1958. * Property: sourceId
  1959. * Id of the source element in the connection.
  1960. */
  1961. this.sourceId = _getAttribute(this.source, "id");
  1962. /*
  1963. * Property: targetId
  1964. * Id of the target element in the connection.
  1965. */
  1966. this.targetId = _getAttribute(this.target, "id");
  1967. this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;
  1968. /**
  1969. * implementation of abstract method in EventGenerator
  1970. * @return list of attached elements. in our case, a list of Endpoints.
  1971. */
  1972. this.getAttachedElements = function() {
  1973. return self.endpoints;
  1974. };
  1975. /**
  1976. * implementation of abstract method in EventGenerator
  1977. */
  1978. var srcWhenMouseDown = null, targetWhenMouseDown = null;
  1979. this.savePosition = function() {
  1980. srcWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.source));
  1981. targetWhenMouseDown = jsPlumb.CurrentLibrary.getOffset(jsPlumb.CurrentLibrary.getElementObject(self.target));
  1982. };
  1983. /*
  1984. * Property: scope
  1985. * Optional scope descriptor for the connection.
  1986. */
  1987. 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.
  1988. /*
  1989. * Property: endpoints
  1990. * Array of [source, target] Endpoint objects.
  1991. */
  1992. this.endpoints = [];
  1993. this.endpointStyles = [];
  1994. // wrapped the main function to return null if no input given. this lets us cascade defaults properly.
  1995. var _makeAnchor = function(anchorParams) {
  1996. if (anchorParams)
  1997. return jsPlumb.makeAnchor(anchorParams);
  1998. };
  1999. var prepareEndpoint = function(existing, index, params, element, connectorPaintStyle, connectorHoverPaintStyle) {
  2000. if (existing) {
  2001. self.endpoints[index] = existing;
  2002. existing.addConnection(self);
  2003. } else {
  2004. if (!params.endpoints) params.endpoints = [ null, null ];
  2005. var ep = params.endpoints[index]
  2006. || params.endpoint
  2007. || _currentInstance.Defaults.Endpoints[index]
  2008. || jsPlumb.Defaults.Endpoints[index]
  2009. || _currentInstance.Defaults.Endpoint
  2010. || jsPlumb.Defaults.Endpoint;
  2011. if (!params.endpointStyles) params.endpointStyles = [ null, null ];
  2012. if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
  2013. var es = params.endpointStyles[index] || params.endpointStyle || _currentInstance.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _currentInstance.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
  2014. // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
  2015. if (es.fillStyle == null && connectorPaintStyle != null)
  2016. es.fillStyle = connectorPaintStyle.strokeStyle;
  2017. // TODO: decide if the endpoint should derive the connection's outline width and color. currently it does:
  2018. //*
  2019. if (es.outlineColor == null && connectorPaintStyle != null)
  2020. es.outlineColor = connectorPaintStyle.outlineColor;
  2021. if (es.outlineWidth == null && connectorPaintStyle != null)
  2022. es.outlineWidth = connectorPaintStyle.outlineWidth;
  2023. //*/
  2024. var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _currentInstance.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _currentInstance.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
  2025. // endpoint hover fill style is derived from connector's hover stroke style. TODO: do we want to do this by default? for sure?
  2026. if (connectorHoverPaintStyle != null) {
  2027. if (ehs == null) ehs = {};
  2028. if (ehs.fillStyle == null) {
  2029. ehs.fillStyle = connectorHoverPaintStyle.strokeStyle;
  2030. }
  2031. }
  2032. 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);
  2033. var u = params.uuids ? params.uuids[index] : null;
  2034. var e = _newEndpoint( { paintStyle : es, hoverPaintStyle:ehs, endpoint : ep, connections : [ self ], uuid : u, anchor : a, source : element });
  2035. self.endpoints[index] = e;
  2036. if (params.drawEndpoints === false) e.setVisible(false, true, true);
  2037. return e;
  2038. }
  2039. };
  2040. var eS = prepareEndpoint(params.sourceEndpoint, 0, params, self.source, params.paintStyle, params.hoverPaintStyle);
  2041. if (eS) _addToList(endpointsByElement, this.sourceId, eS);
  2042. var eT = prepareEndpoint(params.targetEndpoint, 1, params, self.target, params.paintStyle, params.hoverPaintStyle);
  2043. if (eT) _addToList(endpointsByElement, this.targetId, eT);
  2044. // if scope not set, set it to be the scope for the source endpoint.
  2045. if (!this.scope) this.scope = this.endpoints[0].scope;
  2046. /*
  2047. * Function: setConnector
  2048. * Sets the Connection's connector (eg "Bezier", "Flowchart", etc). You pass a Connector definition into this method - the same
  2049. * thing that you would set as the 'connector' property on a jsPlumb.connect call.
  2050. *
  2051. * Parameters:
  2052. * connector - Connector definition
  2053. */
  2054. this.setConnector = function(connector, doNotRepaint) {
  2055. if (self.connector != null) _removeElements(self.connector.getDisplayElements(), self.parent);
  2056. var connectorArgs = { _jsPlumb:self._jsPlumb, parent:params.parent, cssClass:params.cssClass };
  2057. if (connector.constructor == String)
  2058. this.connector = new jsPlumb.Connectors[renderMode][connector](connectorArgs); // lets you use a string as shorthand.
  2059. else if (connector.constructor == Array)
  2060. this.connector = new jsPlumb.Connectors[renderMode][connector[0]](jsPlumb.extend(connector[1], connectorArgs));
  2061. this.canvas = this.connector.canvas;
  2062. var _mouseDown = false, _mouseWasDown = false, _mouseDownAt = null;
  2063. // add mouse events
  2064. this.connector.bind("click", function(con, e) {
  2065. _mouseWasDown = false;
  2066. self.fire("click", self, e);
  2067. });
  2068. this.connector.bind("dblclick", function(con, e) { _mouseWasDown = false;self.fire("dblclick", self, e); });
  2069. this.connector.bind("mouseenter", function(con, e) {
  2070. if (!self.isHover()) {
  2071. if (_connectionBeingDragged == null) {
  2072. self.setHover(true);
  2073. }
  2074. self.fire("mouseenter", self, e);
  2075. }
  2076. });
  2077. this.connector.bind("mouseexit", function(con, e) {
  2078. if (self.isHover()) {
  2079. if (_connectionBeingDragged == null) {
  2080. self.setHover(false);
  2081. }
  2082. self.fire("mouseexit", self, e);
  2083. }
  2084. });
  2085. this.connector.bind("mousedown", function(con, e) {
  2086. _mouseDown = true;
  2087. _mouseDownAt = jsPlumb.CurrentLibrary.getPageXY(e);
  2088. self.savePosition();
  2089. });
  2090. this.connector.bind("mouseup", function(con, e) {
  2091. _mouseDown = false;
  2092. if (self.connector == _connectionBeingDragged) _connectionBeingDragged = null;
  2093. });
  2094. if (!doNotRepaint) self.repaint();
  2095. };
  2096. /*
  2097. * Property: connector
  2098. * The underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
  2099. */
  2100. self.setConnector(this.endpoints[0].connector ||
  2101. this.endpoints[1].connector ||
  2102. params.connector ||
  2103. _currentInstance.Defaults.Connector ||
  2104. jsPlumb.Defaults.Connector, true);
  2105. this.setPaintStyle(this.endpoints[0].connectorStyle ||
  2106. this.endpoints[1].connectorStyle ||
  2107. params.paintStyle ||
  2108. _currentInstance.Defaults.PaintStyle ||
  2109. jsPlumb.Defaults.PaintStyle, true);
  2110. this.setHoverPaintStyle(this.endpoints[0].connectorHoverStyle ||
  2111. this.endpoints[1].connectorHoverStyle ||
  2112. params.hoverPaintStyle ||
  2113. _currentInstance.Defaults.HoverPaintStyle ||
  2114. jsPlumb.Defaults.HoverPaintStyle, true);
  2115. this.paintStyleInUse = this.paintStyle;
  2116. /*
  2117. * Property: overlays
  2118. * List of Overlays for this Connection.
  2119. */
  2120. this.overlays = [];
  2121. var _overlays = params.overlays || _currentInstance.Defaults.Overlays;
  2122. if (_overlays) {
  2123. for (var i = 0; i < _overlays.length; i++) {
  2124. var o = _overlays[i], _newOverlay = null, _overlayEvents = null;
  2125. if (o.constructor == Array) { // this is for the shorthand ["Arrow", { width:50 }] syntax
  2126. // there's also a three arg version:
  2127. // ["Arrow", { width:50 }, {location:0.7}]
  2128. // which merges the 3rd arg into the 2nd.
  2129. var type = o[0];
  2130. 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...
  2131. if (o.length == 3) jsPlumb.CurrentLibrary.extend(p, o[2]);
  2132. _newOverlay = new jsPlumb.Overlays[renderMode][type](p);
  2133. if (p.events) {
  2134. for (var evt in p.events) {
  2135. _newOverlay.bind(evt, p.events[evt]);
  2136. }
  2137. }
  2138. } else if (o.constructor == String) {
  2139. _newOverlay = new jsPlumb.Overlays[renderMode][o]({connection:self, _jsPlumb:_currentInstance});
  2140. } else {
  2141. _newOverlay = o;
  2142. }
  2143. this.overlays.push(_newOverlay);
  2144. }
  2145. }
  2146. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2147. /*
  2148. * Function: bind
  2149. * Bind to an event on the Connection.
  2150. *
  2151. * Parameters:
  2152. * event - the event to bind. Available events on a Connection are:
  2153. * - *click* : notification that a Connection was clicked.
  2154. * - *dblclick* : notification that a Connection was double clicked.
  2155. * - *mouseenter* : notification that the mouse is over a Connection.
  2156. * - *mouseexit* : notification that the mouse exited a Connection.
  2157. *
  2158. * callback - function to callback. This function will be passed the Connection that caused the event, and also the original event.
  2159. */
  2160. /*
  2161. * Function: setPaintStyle
  2162. * Sets the Connection's paint style and then repaints the Connection.
  2163. *
  2164. * Parameters:
  2165. * style - Style to use.
  2166. */
  2167. /*
  2168. * Function: setHoverPaintStyle
  2169. * Sets the paint style to use when the mouse is hovering over the Connection. This is null by default.
  2170. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  2171. * it. This is because people will most likely want to change just one thing when hovering, say the
  2172. * color for example, but leave the rest of the appearance the same.
  2173. *
  2174. * Parameters:
  2175. * style - Style to use when the mouse is hovering.
  2176. * doNotRepaint - if true, the Connection will not be repainted. useful when setting things up initially.
  2177. */
  2178. /*
  2179. * Function: setHover
  2180. * Sets/unsets the hover state of this Connection.
  2181. *
  2182. * Parameters:
  2183. * hover - hover state boolean
  2184. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  2185. */
  2186. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2187. /*
  2188. * Function: addOverlay
  2189. * Adds an Overlay to the Connection.
  2190. *
  2191. * Parameters:
  2192. * overlay - Overlay to add.
  2193. */
  2194. this.addOverlay = function(overlay) { self.overlays.push(overlay); };
  2195. /**
  2196. * Function: removeAllOverlays
  2197. * Removes all overlays from the Connection, and then repaints.
  2198. */
  2199. this.removeAllOverlays = function() {
  2200. self.overlays.splice(0, self.overlays.length);
  2201. self.repaint();
  2202. };
  2203. /**
  2204. * Function:removeOverlay
  2205. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  2206. * Parameters:
  2207. * overlayId - id of the overlay to remove.
  2208. */
  2209. this.removeOverlay = function(overlayId) {
  2210. var idx = -1;
  2211. for (var i = 0; i < self.overlays.length; i++) {
  2212. if (overlayId === self.overlays[i].id) {
  2213. idx = i;
  2214. break;
  2215. }
  2216. }
  2217. if (idx != -1) self.overlays.splice(idx, 1);
  2218. };
  2219. /**
  2220. * Function:removeOverlay
  2221. * Removes an overlay by ID. Note: by ID. this is a string you set in the overlay spec.
  2222. * Parameters:
  2223. * overlayIds - this function takes an arbitrary number of arguments, each of which is a single overlay id.
  2224. */
  2225. this.removeOverlays = function() {
  2226. for (var i = 0; i < arguments.length; i++)
  2227. self.removeOverlay(arguments[i]);
  2228. };
  2229. // this is a shortcut helper method to let people add a label as
  2230. // overlay.
  2231. this.labelStyle = params.labelStyle || _currentInstance.Defaults.LabelStyle || jsPlumb.Defaults.LabelStyle;
  2232. this.label = params.label;
  2233. if (this.label) {
  2234. this.overlays.push(new jsPlumb.Overlays[renderMode].Label( {
  2235. cssClass:params.cssClass,
  2236. labelStyle : this.labelStyle,
  2237. label : this.label,
  2238. connection:self,
  2239. _jsPlumb:_currentInstance
  2240. }));
  2241. }
  2242. _updateOffset( { elId : this.sourceId });
  2243. _updateOffset( { elId : this.targetId });
  2244. /*
  2245. * Function: setLabel
  2246. * Sets the Connection's label.
  2247. *
  2248. * Parameters:
  2249. * l - label to set. May be a String or a Function that returns a String.
  2250. */
  2251. this.setLabel = function(l) {
  2252. self.label = l;
  2253. _currentInstance.repaint(self.source);
  2254. };
  2255. // paint the endpoints
  2256. var myOffset = offsets[this.sourceId], myWH = sizes[this.sourceId];
  2257. var otherOffset = offsets[this.targetId];
  2258. var otherWH = sizes[this.targetId];
  2259. var anchorLoc = this.endpoints[0].anchor.compute( {
  2260. xy : [ myOffset.left, myOffset.top ], wh : myWH, element : this.endpoints[0],
  2261. txy : [ otherOffset.left, otherOffset.top ], twh : otherWH, tElement : this.endpoints[1]
  2262. });
  2263. this.endpoints[0].paint( { anchorLoc : anchorLoc });
  2264. anchorLoc = this.endpoints[1].anchor.compute( {
  2265. xy : [ otherOffset.left, otherOffset.top ], wh : otherWH, element : this.endpoints[1],
  2266. txy : [ myOffset.left, myOffset.top ], twh : myWH, tElement : this.endpoints[0]
  2267. });
  2268. this.endpoints[1].paint({ anchorLoc : anchorLoc });
  2269. /*
  2270. * Paints the Connection. Not exposed for public usage.
  2271. *
  2272. * Parameters:
  2273. * elId - Id of the element that is in motion.
  2274. * ui - current library's event system ui object (present if we came from a drag to get here).
  2275. * recalc - whether or not to recalculate all anchors etc before painting.
  2276. * timestamp - timestamp of this paint. If the Connection was last painted with the same timestamp, it does not paint again.
  2277. */
  2278. this.paint = function(params) {
  2279. params = params || {};
  2280. var elId = params.elId, ui = params.ui, recalc = params.recalc, timestamp = params.timestamp;
  2281. var fai = self.floatingAnchorIndex;
  2282. // if the moving object is not the source we must transpose the two references.
  2283. var swap = false;
  2284. var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
  2285. var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
  2286. var el = swap ? this.target : this.source;
  2287. _updateOffset( { elId : elId, offset : ui, recalc : recalc, timestamp : timestamp });
  2288. _updateOffset( { elId : tId, timestamp : timestamp }); // update the target if this is a forced repaint. otherwise, only the source has been moved.
  2289. var sAnchorP = this.endpoints[sIdx].anchor.getCurrentLocation();
  2290. var sAnchorO = this.endpoints[sIdx].anchor.getOrientation();
  2291. var tAnchorP = this.endpoints[tIdx].anchor.getCurrentLocation();
  2292. var tAnchorO = this.endpoints[tIdx].anchor.getOrientation();
  2293. /* paint overlays*/
  2294. var maxSize = 0;
  2295. for ( var i = 0; i < self.overlays.length; i++) {
  2296. var o = self.overlays[i];
  2297. var s = o.computeMaxSize(self.connector);
  2298. if (s > maxSize)
  2299. maxSize = s;
  2300. }
  2301. var dim = this.connector.compute(sAnchorP, tAnchorP, this.endpoints[sIdx].anchor, this.endpoints[tIdx].anchor, self.paintStyleInUse.lineWidth, maxSize);
  2302. self.connector.paint(dim, self.paintStyleInUse);
  2303. /* paint overlays*/
  2304. for ( var i = 0; i < self.overlays.length; i++) {
  2305. var o = self.overlays[i];
  2306. self.overlayPlacements[i] = o.draw(self.connector, self.paintStyleInUse, dim);
  2307. }
  2308. };
  2309. /*
  2310. * Function: repaint
  2311. * Repaints the Connection.
  2312. */
  2313. this.repaint = function() {
  2314. this.paint({ elId : this.sourceId, recalc : true });
  2315. };
  2316. _initDraggableIfNecessary(self.source, params.draggable, params.dragOptions);
  2317. _initDraggableIfNecessary(self.target, params.draggable, params.dragOptions);
  2318. // resizing (using the jquery.ba-resize plugin). todo: decide
  2319. // whether to include or not.
  2320. if (this.source.resize) {
  2321. this.source.resize(function(e) {
  2322. jsPlumb.repaint(self.sourceId);
  2323. });
  2324. }
  2325. // just to make sure the UI gets initialised fully on all browsers.
  2326. self.repaint();
  2327. };
  2328. /*
  2329. * Class: Endpoint
  2330. *
  2331. * Models an endpoint. Can have 1 to 'maxConnections' Connections emanating from it (set maxConnections to -1
  2332. * to allow unlimited). Typically, if you use 'jsPlumb.connect' to programmatically connect two elements, you won't
  2333. * actually deal with the underlying Endpoint objects. But if you wish to support drag and drop Connections, one of the ways you
  2334. * do so is by creating and registering Endpoints using 'jsPlumb.addEndpoint', and marking these Endpoints as 'source' and/or
  2335. * 'target' Endpoints for Connections.
  2336. *
  2337. *
  2338. */
  2339. /*
  2340. * Function: Endpoint
  2341. *
  2342. * Endpoint constructor.
  2343. *
  2344. * Parameters:
  2345. * 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.
  2346. * 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 } ].
  2347. * paintStyle - endpoint style, a js object. may be null.
  2348. * hoverPaintStyle - style to use when the mouse is hovering over the Endpoint. A js object. may be null; defaults to null.
  2349. * source - element the Endpoint is attached to, of type String (an element id) or element selector. Required.
  2350. * canvas - canvas element to use. may be, and most often is, null.
  2351. * connections - optional list of Connections to configure the Endpoint with.
  2352. * isSource - boolean. indicates the endpoint can act as a source of new connections. Optional; defaults to false.
  2353. * maxConnections - integer; defaults to 1. a value of -1 means no upper limit.
  2354. * dragOptions - if isSource is set to true, you can supply arguments for the underlying library's drag method. Optional; defaults to null.
  2355. * connectorStyle - if isSource is set to true, this is the paint style for Connections from this Endpoint. Optional; defaults to null.
  2356. * connectorHoverStyle - if isSource is set to true, this is the hover paint style for Connections from this Endpoint. Optional; defaults to null.
  2357. * 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 } ].
  2358. * connectorOverlays - optional array of Overlay definitions that will be applied to any Connection from this Endpoint.
  2359. * isTarget - boolean. indicates the endpoint can act as a target of new connections. Optional; defaults to false.
  2360. * 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.
  2361. * 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.
  2362. */
  2363. var Endpoint = function(params) {
  2364. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  2365. params = params || {};
  2366. var self = this;
  2367. // ***************************** PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2368. /*
  2369. * Function: bind
  2370. * Bind to an event on the Endpoint.
  2371. *
  2372. * Parameters:
  2373. * event - the event to bind. Available events on an Endpoint are:
  2374. * - *click* : notification that a Endpoint was clicked.
  2375. * - *dblclick* : notification that a Endpoint was double clicked.
  2376. * - *mouseenter* : notification that the mouse is over a Endpoint.
  2377. * - *mouseexit* : notification that the mouse exited a Endpoint.
  2378. *
  2379. * callback - function to callback. This function will be passed the Endpoint that caused the event, and also the original event.
  2380. */
  2381. /*
  2382. * Function: setPaintStyle
  2383. * Sets the Endpoint's paint style and then repaints the Endpoint.
  2384. *
  2385. * Parameters:
  2386. * style - Style to use.
  2387. */
  2388. /*
  2389. * Function: setHoverPaintStyle
  2390. * Sets the paint style to use when the mouse is hovering over the Endpoint. This is null by default.
  2391. * The hover paint style is applied as extensions to the paintStyle; it does not entirely replace
  2392. * it. This is because people will most likely want to change just one thing when hovering, say the
  2393. * color for example, but leave the rest of the appearance the same.
  2394. *
  2395. * Parameters:
  2396. * style - Style to use when the mouse is hovering.
  2397. * doNotRepaint - if true, the Endpoint will not be repainted. useful when setting things up initially.
  2398. */
  2399. /*
  2400. * Function: setHover
  2401. * Sets/unsets the hover state of this Endpoint.
  2402. *
  2403. * Parameters:
  2404. * hover - hover state boolean
  2405. * ignoreAttachedElements - if true, does not notify any attached elements of the change in hover state. used mostly to avoid infinite loops.
  2406. */
  2407. // ***************************** END OF PLACEHOLDERS FOR NATURAL DOCS *************************************************
  2408. var visible = true;
  2409. /*
  2410. Function: isVisible
  2411. Returns whether or not the Endpoint is currently visible.
  2412. */
  2413. this.isVisible = function() { return visible; };
  2414. /*
  2415. Function: setVisible
  2416. Sets whether or not the Endpoint is currently visible.
  2417. Parameters:
  2418. visible - whether or not the Endpoint should be visible.
  2419. doNotChangeConnections - Instructs jsPlumb to not pass the visible state on to any attached Connections. defaults to false.
  2420. doNotNotifyOtherEndpoint - Instructs jsPlumb to not pass the visible state on to Endpoints at the other end of any attached Connections. defaults to false.
  2421. */
  2422. this.setVisible = function(v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
  2423. visible = v;
  2424. if (self.canvas) self.canvas.style.display = v ? "block" : "none";
  2425. if (!doNotChangeConnections) {
  2426. for (var i = 0; i < self.connections.length; i++) {
  2427. self.connections[i].setVisible(v);
  2428. if (!doNotNotifyOtherEndpoint) {
  2429. var oIdx = self === self.connections[i].endpoints[0] ? 1 : 0;
  2430. // only change the other endpoint if this is its only connection.
  2431. if (self.connections[i].endpoints[oIdx].connections.length == 1) self.connections[i].endpoints[oIdx].setVisible(v, true, true);
  2432. }
  2433. }
  2434. }
  2435. };
  2436. var id = new String('_jsplumb_e_' + (new Date()).getTime());
  2437. this.getId = function() { return id; };
  2438. if (params.dynamicAnchors)
  2439. self.anchor = new DynamicAnchor(jsPlumb.makeAnchors(params.dynamicAnchors));
  2440. else
  2441. self.anchor = params.anchor ? jsPlumb.makeAnchor(params.anchor) : params.anchors ? jsPlumb.makeAnchor(params.anchors) : jsPlumb.makeAnchor("TopCenter");
  2442. var _endpoint = params.endpoint || _currentInstance.Defaults.Endpoint || jsPlumb.Defaults.Endpoint || "Dot",
  2443. endpointArgs = { _jsPlumb:self._jsPlumb, parent:params.parent };
  2444. if (_endpoint.constructor == String)
  2445. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint](endpointArgs);
  2446. else if (_endpoint.constructor == Array)
  2447. _endpoint = new jsPlumb.Endpoints[renderMode][_endpoint[0]](jsPlumb.extend(_endpoint[1], endpointArgs ));
  2448. else _endpoint = _endpoint.clone();
  2449. self.endpoint = _endpoint;
  2450. this.endpoint.bind("click", function(e) { self.fire("click", self, e); });
  2451. this.endpoint.bind("dblclick", function(e) { self.fire("dblclick", self, e); });
  2452. this.setPaintStyle(params.paintStyle ||
  2453. params.style ||
  2454. _currentInstance.Defaults.EndpointStyle ||
  2455. jsPlumb.Defaults.EndpointStyle, true);
  2456. this.setHoverPaintStyle(params.hoverPaintStyle ||
  2457. _currentInstance.Defaults.EndpointHoverStyle ||
  2458. jsPlumb.Defaults.EndpointHoverStyle, true);
  2459. this.paintStyleInUse = this.paintStyle;
  2460. this.connectorStyle = params.connectorStyle;
  2461. this.connectorHoverStyle = params.connectorHoverStyle;
  2462. this.connectorOverlays = params.connectorOverlays;
  2463. this.connector = params.connector;
  2464. this.parent = params.parent;
  2465. this.isSource = params.isSource || false;
  2466. this.isTarget = params.isTarget || false;
  2467. var _element = params.source,
  2468. _uuid = params.uuid,
  2469. floatingEndpoint = null,
  2470. inPlaceCopy = null;
  2471. if (_uuid) endpointsByUUID[_uuid] = self;
  2472. var _elementId = _getAttribute(_element, "id");
  2473. this.elementId = _elementId;
  2474. this.element = _element;
  2475. var _maxConnections = params.maxConnections || _currentInstance.Defaults.MaxConnections; // maximum number of connections this endpoint can be the source of.
  2476. this.getAttachedElements = function() {
  2477. return self.connections;
  2478. };
  2479. /*
  2480. * Property: canvas
  2481. * The Endpoint's Canvas.
  2482. */
  2483. this.canvas = this.endpoint.canvas;
  2484. /*
  2485. * Property: connections
  2486. * List of Connections this Endpoint is attached to.
  2487. */
  2488. this.connections = params.connections || [];
  2489. /*
  2490. * Property: scope
  2491. * Scope descriptor for this Endpoint.
  2492. */
  2493. this.scope = params.scope || DEFAULT_SCOPE;
  2494. this.timestamp = null;
  2495. var _reattach = params.reattach || false;
  2496. var dragAllowedWhenFull = params.dragAllowedWhenFull || true;
  2497. this.computeAnchor = function(params) {
  2498. return self.anchor.compute(params);
  2499. };
  2500. /*
  2501. * Function: addConnection
  2502. * Adds a Connection to this Endpoint.
  2503. *
  2504. * Parameters:
  2505. * connection - the Connection to add.
  2506. */
  2507. this.addConnection = function(connection) {
  2508. self.connections.push(connection);
  2509. };
  2510. /*
  2511. * Function: detach
  2512. * Detaches the given Connection from this Endpoint.
  2513. *
  2514. * Parameters:
  2515. * connection - the Connection to detach.
  2516. * ignoreTarget - optional; tells the Endpoint to not notify the Connection target that the Connection was detached. The default behaviour is to notify the target.
  2517. */
  2518. this.detach = function(connection, ignoreTarget) {
  2519. var idx = _findIndex(self.connections, connection);
  2520. if (idx >= 0) {
  2521. self.connections.splice(idx, 1);
  2522. // this avoids a circular loop
  2523. if (!ignoreTarget) {
  2524. var t = connection.endpoints[0] == self ? connection.endpoints[1] : connection.endpoints[0];
  2525. t.detach(connection, true);
  2526. // check connection to see if we want to delete the other endpoint.
  2527. // if the user uses makeTarget to make some element a target for connections,
  2528. // it is possible that they will have set 'endpointToDeleteOnDetach': when
  2529. // you make a connection to an element that acts as a target (note: NOT an
  2530. // Endpoint; just some div as a target), Endpoints are created for that
  2531. // connection. so if you then delete that Connection, it is feasible you
  2532. // will want these auto-generated endpoints to be removed.
  2533. if (connection.endpointToDeleteOnDetach && connection.endpointToDeleteOnDetach.connections.length == 0)
  2534. jsPlumb.deleteEndpoint(connection.endpointToDeleteOnDetach);
  2535. }
  2536. _removeElements(connection.connector.getDisplayElements(), connection.parent);
  2537. _removeFromList(connectionsByScope, connection.scope, connection);
  2538. if(!ignoreTarget) fireDetachEvent(connection);
  2539. }
  2540. };
  2541. /*
  2542. * Function: detachAll
  2543. * Detaches all Connections this Endpoint has.
  2544. */
  2545. this.detachAll = function() {
  2546. while (self.connections.length > 0) {
  2547. self.detach(self.connections[0]);
  2548. }
  2549. };
  2550. /*
  2551. * Function: detachFrom
  2552. * Removes any connections from this Endpoint that are connected to the given target endpoint.
  2553. *
  2554. * Parameters:
  2555. * targetEndpoint - Endpoint from which to detach all Connections from this Endpoint.
  2556. */
  2557. this.detachFrom = function(targetEndpoint) {
  2558. var c = [];
  2559. for ( var i = 0; i < self.connections.length; i++) {
  2560. if (self.connections[i].endpoints[1] == targetEndpoint
  2561. || self.connections[i].endpoints[0] == targetEndpoint) {
  2562. c.push(self.connections[i]);
  2563. }
  2564. }
  2565. for ( var i = 0; i < c.length; i++) {
  2566. c[i].setHover(false);
  2567. self.detach(c[i]);
  2568. }
  2569. };
  2570. /*
  2571. * Function: detachFromConnection
  2572. * Detach this Endpoint from the Connection, but leave the Connection alive. Used when dragging.
  2573. *
  2574. * Parameters:
  2575. * connection - Connection to detach from.
  2576. */
  2577. this.detachFromConnection = function(connection) {
  2578. var idx = _findIndex(self.connections, connection);
  2579. if (idx >= 0) {
  2580. self.connections.splice(idx, 1);
  2581. }
  2582. };
  2583. /*
  2584. * Function: getElement
  2585. * Returns the DOM element this Endpoint is attached to.
  2586. */
  2587. this.getElement = function() {
  2588. return _element;
  2589. };
  2590. /*
  2591. * Function: getUuid
  2592. * Returns the UUID for this Endpoint, if there is one. Otherwise returns null.
  2593. */
  2594. this.getUuid = function() {
  2595. return _uuid;
  2596. };
  2597. /**
  2598. * private but must be exposed.
  2599. */
  2600. this.makeInPlaceCopy = function() {
  2601. return _newEndpoint( { anchor : self.anchor, source : _element, paintStyle : this.paintStyle, endpoint : _endpoint });
  2602. };
  2603. /*
  2604. * Function: isConnectedTo
  2605. * Returns whether or not this endpoint is connected to the given Endpoint.
  2606. *
  2607. * Parameters:
  2608. * endpoint - Endpoint to test.
  2609. */
  2610. this.isConnectedTo = function(endpoint) {
  2611. var found = false;
  2612. if (endpoint) {
  2613. for ( var i = 0; i < self.connections.length; i++) {
  2614. if (self.connections[i].endpoints[1] == endpoint) {
  2615. found = true;
  2616. break;
  2617. }
  2618. }
  2619. }
  2620. return found;
  2621. };
  2622. /**
  2623. * private but needs to be exposed.
  2624. */
  2625. this.isFloating = function() {
  2626. return floatingEndpoint != null;
  2627. };
  2628. /**
  2629. * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
  2630. */
  2631. this.connectorSelector = function() {
  2632. return (self.connections.length < _maxConnections) ? null : self.connections[0];
  2633. };
  2634. /*
  2635. * Function: isFull
  2636. * Returns whether or not the Endpoint can accept any more Connections.
  2637. */
  2638. this.isFull = function() {
  2639. return !(self.isFloating() || _maxConnections < 1 || self.connections.length < _maxConnections);
  2640. };
  2641. /*
  2642. * Function: setDragAllowedWhenFull
  2643. * Sets whether or not connections can be dragged from this Endpoint once it is full. You would use this in a UI in
  2644. * which you're going to provide some other way of breaking connections, if you need to break them at all. This property
  2645. * is by default true; use it in conjunction with the 'reattach' option on a connect call.
  2646. *
  2647. * Parameters:
  2648. * allowed - whether drag is allowed or not when the Endpoint is full.
  2649. */
  2650. this.setDragAllowedWhenFull = function(allowed) {
  2651. dragAllowedWhenFull = allowed;
  2652. };
  2653. /*
  2654. * Function: setStyle
  2655. * 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.
  2656. * TODO move setStyle into EventGenerator, remove it from here. is Connection's method currently setPaintStyle ? wire that one up to
  2657. * setStyle and deprecate it if so.
  2658. *
  2659. * Parameters:
  2660. * style - Style object to set, for example {fillStyle:"blue"}.
  2661. *
  2662. * @deprecated use setPaintStyle instead.
  2663. */
  2664. this.setStyle = self.setPaintStyle;
  2665. /**
  2666. * a deep equals check. everything must match, including the anchor,
  2667. * styles, everything. TODO: finish Endpoint.equals
  2668. */
  2669. this.equals = function(endpoint) {
  2670. return this.anchor.equals(endpoint.anchor);
  2671. };
  2672. /*
  2673. * Function: paint
  2674. * Paints the Endpoint, recalculating offset and anchor positions if necessary.
  2675. *
  2676. * Parameters:
  2677. * 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.
  2678. * canvas - optional Canvas to paint on. Only used internally by jsPlumb in certain obscure situations.
  2679. * connectorPaintStyle - paint style of the Connector attached to this Endpoint. Used to get a fillStyle if nothing else was supplied.
  2680. */
  2681. this.paint = function(params) {
  2682. params = params || {};
  2683. var timestamp = params.timestamp;
  2684. if (!timestamp || self.timestamp !== timestamp) {
  2685. var ap = params.anchorPoint, canvas = params.canvas, connectorPaintStyle = params.connectorPaintStyle;
  2686. if (ap == null) {
  2687. var xy = params.offset || offsets[_elementId];
  2688. var wh = params.dimensions || sizes[_elementId];
  2689. if (xy == null || wh == null) {
  2690. _updateOffset( { elId : _elementId, timestamp : timestamp });
  2691. xy = offsets[_elementId];
  2692. wh = sizes[_elementId];
  2693. }
  2694. var anchorParams = { xy : [ xy.left, xy.top ], wh : wh, element : self, timestamp : timestamp };
  2695. if (self.anchor.isDynamic) {
  2696. if (self.connections.length > 0) {
  2697. var c = self.connections[0];
  2698. var oIdx = c.endpoints[0] == self ? 1 : 0;
  2699. var oId = oIdx == 0 ? c.sourceId : c.targetId;
  2700. var oOffset = offsets[oId], oWH = sizes[oId];
  2701. anchorParams.txy = [ oOffset.left, oOffset.top ];
  2702. anchorParams.twh = oWH;
  2703. anchorParams.tElement = c.endpoints[oIdx];
  2704. }
  2705. }
  2706. ap = self.anchor.compute(anchorParams);
  2707. }
  2708. var d = _endpoint.compute(ap, self.anchor.getOrientation(), self.paintStyleInUse, connectorPaintStyle || self.paintStyleInUse);
  2709. _endpoint.paint(d, self.paintStyleInUse, self.anchor);
  2710. self.timestamp = timestamp;
  2711. }
  2712. };
  2713. this.repaint = this.paint;
  2714. /**
  2715. * @deprecated
  2716. */
  2717. this.removeConnection = this.detach; // backwards compatibility
  2718. // is this a connection source? we make it draggable and have the
  2719. // drag listener maintain a connection with a floating endpoint.
  2720. if (params.isSource && jsPlumb.CurrentLibrary.isDragSupported(_element)) {
  2721. var n = null, id = null, jpc = null, existingJpc = false, existingJpcParams = null;
  2722. var start = function() {
  2723. jpc = self.connectorSelector();
  2724. if (self.isFull() && !dragAllowedWhenFull) return false;
  2725. _updateOffset( { elId : _elementId });
  2726. inPlaceCopy = self.makeInPlaceCopy();
  2727. inPlaceCopy.paint();
  2728. n = document.createElement("div");
  2729. n.style.position = "absolute";
  2730. var nE = _getElementObject(n);
  2731. _appendElement(n, self.parent);
  2732. // create and assign an id, and initialize the offset.
  2733. var id = _getId(nE);
  2734. // set the offset of this div to be where 'inPlaceCopy' is, to start with.
  2735. var ipcoel = _getElementObject(inPlaceCopy.canvas),
  2736. ipco = jsPlumb.CurrentLibrary.getOffset(ipcoel),
  2737. ipcs = jsPlumb.CurrentLibrary.getSize(ipcoel);
  2738. jsPlumb.CurrentLibrary.setOffset(n, ipco);
  2739. _updateOffset( { elId : id });
  2740. // store the id of the dragging div and the source element. the drop function will pick these up.
  2741. _setAttribute(_getElementObject(self.canvas), "dragId", id);
  2742. _setAttribute(_getElementObject(self.canvas), "elId", _elementId);
  2743. // create a floating anchor
  2744. var floatingAnchor = new FloatingAnchor( { reference : self.anchor, referenceCanvas : self.canvas });
  2745. floatingEndpoint = _newEndpoint({ paintStyle : self.paintStyle, endpoint : _endpoint, anchor : floatingAnchor, source : nE });
  2746. if (jpc == null) {
  2747. self.anchor.locked = true;
  2748. // create a connection. one end is this endpoint, the
  2749. // other is a floating endpoint.
  2750. jpc = _newConnection({
  2751. sourceEndpoint : self,
  2752. targetEndpoint : floatingEndpoint,
  2753. source : _getElementObject(_element),
  2754. target : _getElementObject(n),
  2755. anchors : [ self.anchor, floatingAnchor ],
  2756. paintStyle : params.connectorStyle, // this can be null. Connection will use the default.
  2757. hoverPaintStyle:params.connectorHoverStyle,
  2758. connector : params.connector, // this can also be null. Connection will use the default.
  2759. overlays : params.connectorOverlays
  2760. });
  2761. // TODO determine whether or not we wish to do de-select hover when dragging a connection.
  2762. // it may be the case that we actually want to set it, since it provides a good
  2763. // visual cue.
  2764. jpc.connector.setHover(false);
  2765. } else {
  2766. existingJpc = true;
  2767. // TODO determine whether or not we wish to do de-select hover when dragging a connection.
  2768. // it may be the case that we actually want to set it, since it provides a good
  2769. // visual cue.
  2770. jpc.connector.setHover(false);
  2771. // if existing connection, allow to be dropped back on the source endpoint (issue 51).
  2772. _initDropTarget(_getElementObject(inPlaceCopy.canvas));
  2773. var anchorIdx = jpc.sourceId == _elementId ? 0 : 1; // are we the source or the target?
  2774. jpc.floatingAnchorIndex = anchorIdx; // save our anchor index as the connection's floating index.
  2775. self.detachFromConnection(jpc); // detach from the connection while dragging is occurring.
  2776. // store the original scope (issue 57)
  2777. var c = _getElementObject(self.canvas);
  2778. var dragScope = jsPlumb.CurrentLibrary.getDragScope(c);
  2779. _setAttribute(c, "originalScope", dragScope);
  2780. // get a new, temporary scope, to use (issue 57)
  2781. var newScope = "scope_" + (new Date()).getTime();
  2782. // now we replace ourselves with the temporary div we created above:
  2783. if (anchorIdx == 0) {
  2784. existingJpcParams = [ jpc.source, jpc.sourceId, i, dragScope ];
  2785. jpc.source = _getElementObject(n);
  2786. jpc.sourceId = id;
  2787. } else {
  2788. existingJpcParams = [ jpc.target, jpc.targetId, i, dragScope ];
  2789. jpc.target = _getElementObject(n);
  2790. jpc.targetId = id;
  2791. }
  2792. // set the new, temporary scope (issue 57)
  2793. jsPlumb.CurrentLibrary.setDragScope(i, newScope);
  2794. // lock the other endpoint; if it is dynamic it will not move while the drag is occurring.
  2795. jpc.endpoints[anchorIdx == 0 ? 1 : 0].anchor.locked = true;
  2796. // store the original endpoint and assign the new floating endpoint for the drag.
  2797. jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
  2798. jpc.endpoints[anchorIdx] = floatingEndpoint;
  2799. }
  2800. // register it.
  2801. floatingConnections[id] = jpc;
  2802. // TODO unregister on stop? or will floating endpoint's
  2803. // destruction be assured.
  2804. floatingEndpoint.addConnection(jpc);
  2805. // only register for the target endpoint; we will not be
  2806. // dragging the source at any time
  2807. // before this connection is either discarded or made into a
  2808. // permanent connection.
  2809. _addToList(endpointsByElement, id, floatingEndpoint);
  2810. // tell jsplumb about it
  2811. _currentInstance.currentlyDragging = true;
  2812. };
  2813. var jpcl = jsPlumb.CurrentLibrary,
  2814. dragOptions = params.dragOptions || {},
  2815. defaultOpts = jsPlumb.extend( {}, jpcl.defaultDragOptions),
  2816. startEvent = jpcl.dragEvents['start'],
  2817. stopEvent = jpcl.dragEvents['stop'],
  2818. dragEvent = jpcl.dragEvents['drag'];
  2819. dragOptions = jsPlumb.extend(defaultOpts, dragOptions);
  2820. dragOptions.scope = dragOptions.scope || self.scope;
  2821. dragOptions[startEvent] = _wrap(dragOptions[startEvent], start);
  2822. dragOptions[dragEvent] = _wrap(dragOptions[dragEvent],
  2823. function() {
  2824. var _ui = jsPlumb.CurrentLibrary.getUIPosition(arguments);
  2825. jsPlumb.CurrentLibrary.setOffset(n, _ui);
  2826. _draw(_getElementObject(n), _ui);
  2827. });
  2828. dragOptions[stopEvent] = _wrap(dragOptions[stopEvent],
  2829. function() {
  2830. _removeFromList(endpointsByElement, id, floatingEndpoint);
  2831. _removeElements( [ n, floatingEndpoint.canvas ], _element); // TODO: clean up the connection canvas (if the user aborted)
  2832. _removeElement(inPlaceCopy.canvas, _element);
  2833. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2834. jpc.endpoints[idx == 0 ? 1 : 0].anchor.locked = false;
  2835. if (jpc.endpoints[idx] == floatingEndpoint) {
  2836. // if the connection was an existing one:
  2837. if (existingJpc && jpc.suspendedEndpoint) {
  2838. // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
  2839. // floating endpoint has been replaced.
  2840. if (idx == 0) {
  2841. jpc.source = existingJpcParams[0];
  2842. jpc.sourceId = existingJpcParams[1];
  2843. } else {
  2844. jpc.target = existingJpcParams[0];
  2845. jpc.targetId = existingJpcParams[1];
  2846. }
  2847. // restore the original scope (issue 57)
  2848. jsPlumb.CurrentLibrary.setDragScope(existingJpcParams[2], existingJpcParams[3]);
  2849. jpc.endpoints[idx] = jpc.suspendedEndpoint;
  2850. if (_reattach) {
  2851. jpc.floatingAnchorIndex = null;
  2852. jpc.suspendedEndpoint.addConnection(jpc);
  2853. jsPlumb.repaint(existingJpcParams[1]);
  2854. } else {
  2855. jpc.endpoints[idx == 0 ? 1 : 0].detach(jpc); // the main endpoint will inform the floating endpoint
  2856. // to disconnect, and also post the detached event.
  2857. }
  2858. } else {
  2859. // TODO this looks suspiciously kind of like an Endpoint.detach call too.
  2860. // i wonder if this one should post an event though. maybe this is good like this.
  2861. _removeElements(jpc.connector.getDisplayElements(), self.parent);
  2862. self.detachFromConnection(jpc);
  2863. }
  2864. }
  2865. self.anchor.locked = false;
  2866. self.paint();
  2867. jpc.setHover(false);
  2868. jpc.repaint();
  2869. jpc = null;
  2870. delete inPlaceCopy;
  2871. delete endpointsByElement[floatingEndpoint.elementId];
  2872. floatingEndpoint = null;
  2873. delete floatingEndpoint;
  2874. _currentInstance.currentlyDragging = false;
  2875. });
  2876. var i = _getElementObject(self.canvas);
  2877. jsPlumb.CurrentLibrary.initDraggable(i, dragOptions);
  2878. }
  2879. // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
  2880. // back onto the endpoint you detached it from.
  2881. var _initDropTarget = function(canvas) {
  2882. if (params.isTarget && jsPlumb.CurrentLibrary.isDropSupported(_element)) {
  2883. var dropOptions = params.dropOptions || _currentInstance.Defaults.DropOptions || jsPlumb.Defaults.DropOptions;
  2884. dropOptions = jsPlumb.extend( {}, dropOptions);
  2885. dropOptions.scope = dropOptions.scope || self.scope;
  2886. var originalAnchor = null;
  2887. var dropEvent = jsPlumb.CurrentLibrary.dragEvents['drop'];
  2888. var overEvent = jsPlumb.CurrentLibrary.dragEvents['over'];
  2889. var outEvent = jsPlumb.CurrentLibrary.dragEvents['out'];
  2890. var drop = function() {
  2891. var draggable = _getElementObject(jsPlumb.CurrentLibrary.getDragObject(arguments));
  2892. var id = _getAttribute(draggable, "dragId");
  2893. var elId = _getAttribute(draggable, "elId");
  2894. // restore the original scope if necessary (issue 57)
  2895. var scope = _getAttribute(draggable, "originalScope");
  2896. if (scope) jsPlumb.CurrentLibrary.setDragScope(draggable, scope);
  2897. var jpc = floatingConnections[id];
  2898. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex, oidx = idx == 0 ? 1 : 0;
  2899. if (!self.isFull() && !(idx == 0 && !self.isSource) && !(idx == 1 && !self.isTarget)) {
  2900. if (idx == 0) {
  2901. jpc.source = _element;
  2902. jpc.sourceId = _elementId;
  2903. } else {
  2904. jpc.target = _element;
  2905. jpc.targetId = _elementId;
  2906. }
  2907. // todo test that the target is not full.
  2908. // remove this jpc from the current endpoint
  2909. jpc.endpoints[idx].detachFromConnection(jpc);
  2910. if (jpc.suspendedEndpoint) jpc.suspendedEndpoint.detachFromConnection(jpc);
  2911. jpc.endpoints[idx] = self;
  2912. self.addConnection(jpc);
  2913. if (!jpc.suspendedEndpoint) {
  2914. _addToList(connectionsByScope, jpc.scope, jpc);
  2915. _initDraggableIfNecessary(_element, params.draggable, {});
  2916. }
  2917. else {
  2918. var suspendedElement = jpc.suspendedEndpoint.getElement(), suspendedElementId = jpc.suspendedEndpoint.elementId;
  2919. // fire a detach event
  2920. _currentInstance.fire("jsPlumbConnectionDetached", {
  2921. source : idx == 0 ? suspendedElement : jpc.source,
  2922. target : idx == 1 ? suspendedElement : jpc.target,
  2923. sourceId : idx == 0 ? suspendedElementId : jpc.sourceId,
  2924. targetId : idx == 1 ? suspendedElementId : jpc.targetId,
  2925. sourceEndpoint : idx == 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
  2926. targetEndpoint : idx == 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
  2927. connection : jpc
  2928. });
  2929. }
  2930. jsPlumb.repaint(elId);
  2931. _currentInstance.fire("jsPlumbConnection", {
  2932. source : jpc.source, target : jpc.target,
  2933. sourceId : jpc.sourceId, targetId : jpc.targetId,
  2934. sourceEndpoint : jpc.endpoints[0],
  2935. targetEndpoint : jpc.endpoints[1],
  2936. connection:jpc
  2937. });
  2938. }
  2939. _currentInstance.currentlyDragging = false;
  2940. delete floatingConnections[id];
  2941. };
  2942. dropOptions[dropEvent] = _wrap(dropOptions[dropEvent], drop);
  2943. dropOptions[overEvent] = _wrap(dropOptions[overEvent],
  2944. function() {
  2945. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments);
  2946. var id = _getAttribute( _getElementObject(draggable), "dragId");
  2947. var jpc = floatingConnections[id];
  2948. if (jpc != null) {
  2949. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2950. jpc.endpoints[idx].anchor.over(self.anchor);
  2951. }
  2952. });
  2953. dropOptions[outEvent] = _wrap(dropOptions[outEvent],
  2954. function() {
  2955. var draggable = jsPlumb.CurrentLibrary.getDragObject(arguments),
  2956. id = _getAttribute(_getElementObject(draggable), "dragId"),
  2957. jpc = floatingConnections[id];
  2958. if (jpc != null) {
  2959. var idx = jpc.floatingAnchorIndex == null ? 1 : jpc.floatingAnchorIndex;
  2960. jpc.endpoints[idx].anchor.out();
  2961. }
  2962. });
  2963. jsPlumb.CurrentLibrary.initDroppable(canvas, dropOptions);
  2964. }
  2965. };
  2966. // 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.
  2967. _initDropTarget(_getElementObject(self.canvas));
  2968. return self;
  2969. };
  2970. };
  2971. var jsPlumb = window.jsPlumb = new jsPlumbInstance();
  2972. jsPlumb.getInstance = function(_defaults) {
  2973. var j = new jsPlumbInstance(_defaults);
  2974. //if (_defaults) jsPlumb.extend(j.Defaults, _defaults);
  2975. return j;
  2976. };
  2977. var _curryAnchor = function(x,y,ox,oy) {
  2978. return function() {
  2979. return jsPlumb.makeAnchor(x,y,ox,oy);
  2980. };
  2981. };
  2982. jsPlumb.Anchors["TopCenter"] = _curryAnchor(0.5, 0, 0,-1);
  2983. jsPlumb.Anchors["BottomCenter"] = _curryAnchor(0.5, 1, 0, 1);
  2984. jsPlumb.Anchors["LeftMiddle"] = _curryAnchor(0, 0.5, -1, 0);
  2985. jsPlumb.Anchors["RightMiddle"] = _curryAnchor(1, 0.5, 1, 0);
  2986. jsPlumb.Anchors["Center"] = _curryAnchor(0.5, 0.5, 0, 0);
  2987. jsPlumb.Anchors["TopRight"] = _curryAnchor(1, 0, 0,-1);
  2988. jsPlumb.Anchors["BottomRight"] = _curryAnchor(1, 1, 0, 1);
  2989. jsPlumb.Anchors["TopLeft"] = _curryAnchor(0, 0, 0, -1);
  2990. jsPlumb.Anchors["BottomLeft"] = _curryAnchor(0, 1, 0, 1);
  2991. jsPlumb.Defaults.DynamicAnchors = function() {
  2992. return jsPlumb.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"]);
  2993. };
  2994. jsPlumb.Anchors["AutoDefault"] = function() { return jsPlumb.makeDynamicAnchor(jsPlumb.Defaults.DynamicAnchors()); };
  2995. })();
  2996. /*
  2997. * jsPlumb-defaults-1.3.0-RC1
  2998. *
  2999. * Copyright 2010 - 2011 Simon Porritt http://jsplumb.org
  3000. *
  3001. * Triple licensed under the MIT, GPL2 and Beer licenses.
  3002. */
  3003. (function() {
  3004. /**
  3005. *
  3006. * Helper class to consume unused mouse events by components that are DOM elements and
  3007. * are used by all of the different rendering modes.
  3008. *
  3009. */
  3010. jsPlumb.DOMElementComponent = function(params) {
  3011. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  3012. // when render mode is canvas, these functions may be called by the canvas mouse handler.
  3013. // this component is safe to pipe this stuff to /dev/null.
  3014. this.mousemove =
  3015. this.dblclick =
  3016. this.click =
  3017. this.mousedown =
  3018. this.mouseup = function(e) { };
  3019. };
  3020. /**
  3021. * Class: Connectors.Straight
  3022. * The Straight connector draws a simple straight line between the two anchor points. It does not have any constructor parameters.
  3023. */
  3024. jsPlumb.Connectors.Straight = function() {
  3025. var self = this;
  3026. var currentPoints = null;
  3027. var _m, _m2, _b, _dx, _dy, _theta, _theta2, _sx, _sy, _tx, _ty;
  3028. /**
  3029. * Computes the new size and position of the canvas.
  3030. * @param sourceAnchor Absolute position on screen of the source object's anchor.
  3031. * @param targetAnchor Absolute position on screen of the target object's anchor.
  3032. * @param positionMatrix Indicates the relative positions of the left,top of the
  3033. * two plumbed objects. so [0,0] indicates that the source is to the left of, and
  3034. * above, the target. [1,0] means the source is to the right and above. [0,1] means
  3035. * the source is to the left and below. [1,1] means the source is to the right
  3036. * and below. this is used to figure out which direction to draw the connector in.
  3037. * @returns an array of positioning information. the first two values are
  3038. * the [left, top] absolute position the canvas should be placed on screen. the
  3039. * next two values are the [width,height] the canvas should be. after that each
  3040. * Connector can put whatever it likes into the array:it will be passed back in
  3041. * to the paint call. This particular function stores the origin and destination of
  3042. * the line it is going to draw. a more involved implementation, like a Bezier curve,
  3043. * would store the control point info in this array too.
  3044. */
  3045. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  3046. var w = Math.abs(sourcePos[0] - targetPos[0]);
  3047. var h = Math.abs(sourcePos[1] - targetPos[1]);
  3048. var widthAdjusted = false, heightAdjusted = false;
  3049. // these are padding to ensure the whole connector line appears
  3050. var xo = 0.45 * w, yo = 0.45 * h;
  3051. // these are padding to ensure the whole connector line appears
  3052. w *= 1.9; h *=1.9;
  3053. var x = Math.min(sourcePos[0], targetPos[0]) - xo;
  3054. var y = Math.min(sourcePos[1], targetPos[1]) - yo;
  3055. // minimum size is 2 * line Width if minWidth was not given.
  3056. var calculatedMinWidth = Math.max(2 * lineWidth, minWidth);
  3057. if (w < calculatedMinWidth) {
  3058. w = calculatedMinWidth;
  3059. x = sourcePos[0] + ((targetPos[0] - sourcePos[0]) / 2) - (calculatedMinWidth / 2);
  3060. xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;
  3061. }
  3062. if (h < calculatedMinWidth) {
  3063. h = calculatedMinWidth;
  3064. y = sourcePos[1] + ((targetPos[1] - sourcePos[1]) / 2) - (calculatedMinWidth / 2);
  3065. yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;
  3066. }
  3067. _sx = sourcePos[0] < targetPos[0] ? xo : w-xo;
  3068. _sy = sourcePos[1] < targetPos[1] ? yo:h-yo;
  3069. _tx = sourcePos[0] < targetPos[0] ? w-xo : xo;
  3070. _ty = sourcePos[1] < targetPos[1] ? h-yo : yo;
  3071. currentPoints = [ x, y, w, h, _sx, _sy, _tx, _ty ];
  3072. _dx = _tx - _sx, _dy = (_ty - _sy);
  3073. _m = _dy / _dx, _m2 = -1 / _m;
  3074. _b = -1 * ((_m * _sx) - _sy);
  3075. _theta = Math.atan(_m); _theta2 = Math.atan(_m2);
  3076. return currentPoints;
  3077. };
  3078. /**
  3079. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  3080. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  3081. */
  3082. this.pointOnPath = function(location) {
  3083. var xp = _sx + (location * _dx);
  3084. var yp = (_m == Infinity || _m == -Infinity) ? _sy + (location * (_ty - _sy)) : (_m * xp) + _b;
  3085. return {x:xp, y:yp};
  3086. };
  3087. /**
  3088. * returns the gradient of the connector at the given point - which for us is constant.
  3089. */
  3090. this.gradientAtPoint = function(location) { return _m; };
  3091. /**
  3092. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  3093. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
  3094. */
  3095. this.pointAlongPathFrom = function(location, distance) {
  3096. var p = self.pointOnPath(location);
  3097. var orientation = distance > 0 ? 1 : -1;
  3098. var y = Math.abs(distance * Math.sin(_theta));
  3099. if (_sy > _ty) y = y * -1;
  3100. var x = Math.abs(distance * Math.cos(_theta));
  3101. if (_sx > _tx) x = x * -1;
  3102. return {x:p.x + (orientation * x), y:p.y + (orientation * y)};
  3103. };
  3104. /**
  3105. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  3106. * the line is 'length' pixels long.
  3107. */
  3108. this.perpendicularToPathAt = function(location, length, distance) {
  3109. var p = self.pointAlongPathFrom(location, distance);
  3110. var m = self.gradientAtPoint(p.location);
  3111. var _theta2 = Math.atan(-1 / m);
  3112. var y = length / 2 * Math.sin(_theta2);
  3113. var x = length / 2 * Math.cos(_theta2);
  3114. return [{x:p.x + x, y:p.y + y}, {x:p.x - x, y:p.y - y}];
  3115. };
  3116. };
  3117. /**
  3118. * Class:Connectors.Bezier
  3119. * This Connector draws a Bezier curve with two control points. You can provide a 'curviness' value which gets applied to jsPlumb's
  3120. * internal voodoo machine and ends up generating locations for the two control points. See the constructor documentation below.
  3121. */
  3122. /**
  3123. * Function:Constructor
  3124. *
  3125. * Parameters:
  3126. * curviness - How 'curvy' you want the curve to be! This is a directive for the placement of control points, not endpoints of the curve, so your curve does not
  3127. * actually touch the given point, but it has the tendency to lean towards it. The larger this value, the greater the curve is pulled from a straight line.
  3128. * Optional; defaults to 150.
  3129. *
  3130. */
  3131. jsPlumb.Connectors.Bezier = function(params) {
  3132. var self = this;
  3133. params = params || {};
  3134. this.majorAnchor = params.curviness || 150;
  3135. this.minorAnchor = 10;
  3136. var currentPoints = null;
  3137. this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
  3138. // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
  3139. // points around if so (code could be tightened up)
  3140. var soo = sourceAnchor.getOrientation(), too = targetAnchor.getOrientation();
  3141. var perpendicular = soo[0] != too[0] || soo[1] == too[1];
  3142. var p = [];
  3143. var ma = self.majorAnchor, mi = self.minorAnchor;
  3144. if (!perpendicular) {
  3145. if (soo[0] == 0) // X
  3146. p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  3147. else p.push(point[0] - (ma * soo[0]));
  3148. if (soo[1] == 0) // Y
  3149. p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  3150. else p.push(point[1] + (ma * too[1]));
  3151. }
  3152. else {
  3153. if (too[0] == 0) // X
  3154. p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
  3155. else p.push(point[0] + (ma * too[0]));
  3156. if (too[1] == 0) // Y
  3157. p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
  3158. else p.push(point[1] + (ma * soo[1]));
  3159. }
  3160. return p;
  3161. };
  3162. var _CP, _CP2, _sx, _tx, _ty, _sx, _sy, _canvasX, _canvasY, _w, _h;
  3163. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth)
  3164. {
  3165. lineWidth = lineWidth || 0;
  3166. _w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth;
  3167. _h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
  3168. _canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2);
  3169. _canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
  3170. _sx = sourcePos[0] < targetPos[0] ? _w - (lineWidth/2): (lineWidth/2);
  3171. _sy = sourcePos[1] < targetPos[1] ? _h - (lineWidth/2) : (lineWidth/2);
  3172. _tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : _w - (lineWidth/2);
  3173. _ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : _h - (lineWidth/2);
  3174. _CP = self._findControlPoint([_sx,_sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
  3175. _CP2 = self._findControlPoint([_tx,_ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
  3176. var minx1 = Math.min(_sx,_tx); var minx2 = Math.min(_CP[0], _CP2[0]); var minx = Math.min(minx1,minx2);
  3177. var maxx1 = Math.max(_sx,_tx); var maxx2 = Math.max(_CP[0], _CP2[0]); var maxx = Math.max(maxx1,maxx2);
  3178. if (maxx > _w) _w = maxx;
  3179. if (minx < 0) {
  3180. _canvasX += minx; var ox = Math.abs(minx);
  3181. _w += ox; _CP[0] += ox; _sx += ox; _tx +=ox; _CP2[0] += ox;
  3182. }
  3183. var miny1 = Math.min(_sy,_ty); var miny2 = Math.min(_CP[1], _CP2[1]); var miny = Math.min(miny1,miny2);
  3184. var maxy1 = Math.max(_sy,_ty); var maxy2 = Math.max(_CP[1], _CP2[1]); var maxy = Math.max(maxy1,maxy2);
  3185. if (maxy > _h) _h = maxy;
  3186. if (miny < 0) {
  3187. _canvasY += miny; var oy = Math.abs(miny);
  3188. _h += oy; _CP[1] += oy; _sy += oy; _ty +=oy; _CP2[1] += oy;
  3189. }
  3190. if (minWidth && _w < minWidth) {
  3191. var posAdjust = (minWidth - _w) / 2;
  3192. _w = minWidth;
  3193. _canvasX -= posAdjust; _sx = _sx + posAdjust ; _tx = _tx + posAdjust; _CP[0] = _CP[0] + posAdjust; _CP2[0] = _CP2[0] + posAdjust;
  3194. }
  3195. if (minWidth && _h < minWidth) {
  3196. var posAdjust = (minWidth - _h) / 2;
  3197. _h = minWidth;
  3198. _canvasY -= posAdjust; _sy = _sy + posAdjust ; _ty = _ty + posAdjust; _CP[1] = _CP[1] + posAdjust; _CP2[1] = _CP2[1] + posAdjust;
  3199. }
  3200. currentPoints = [_canvasX, _canvasY, _w, _h, _sx, _sy, _tx, _ty, _CP[0], _CP[1], _CP2[0], _CP2[1] ];
  3201. return currentPoints;
  3202. };
  3203. var _makeCurve = function() {
  3204. return [
  3205. { x:_sx, y:_sy },
  3206. { x:_CP[0], y:_CP[1] },
  3207. { x:_CP2[0], y:_CP2[1] },
  3208. { x:_tx, y:_ty }
  3209. ];
  3210. };
  3211. /**
  3212. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  3213. * 0 to 1 inclusive. for the straight line connector this is simple maths. for Bezier, not so much.
  3214. */
  3215. this.pointOnPath = function(location) {
  3216. return jsBezier.pointOnCurve(_makeCurve(), location);
  3217. };
  3218. /**
  3219. * returns the gradient of the connector at the given point.
  3220. */
  3221. this.gradientAtPoint = function(location) {
  3222. return jsBezier.gradientAtPoint(_makeCurve(), location);
  3223. };
  3224. /**
  3225. * for Bezier curves this method is a little tricky, cos calculating path distance algebraically is notoriously difficult.
  3226. * this method is iterative, jumping forward .05% of the path at a time and summing the distance between this point and the previous
  3227. * one, until the sum reaches 'distance'. the method may turn out to be computationally expensive; we'll see.
  3228. * another drawback of this method is that if the connector gets quite long, .05% of the length of it is not necessarily smaller
  3229. * than the desired distance, in which case the loop returns immediately and the arrow is mis-shapen. so a better strategy might be to
  3230. * calculate the step as a function of distance/distance between endpoints.
  3231. */
  3232. this.pointAlongPathFrom = function(location, distance) {
  3233. return jsBezier.pointAlongCurveFrom(_makeCurve(), location, distance);
  3234. };
  3235. /**
  3236. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  3237. * the line is 'length' pixels long.
  3238. */
  3239. this.perpendicularToPathAt = function(location, length, distance) {
  3240. return jsBezier.perpendicularToCurveAt(_makeCurve(), location, length, distance);
  3241. };
  3242. };
  3243. /**
  3244. * Class: Connectors.Flowchart
  3245. * Provides 'flowchart' connectors, consisting of vertical and horizontal line segments.
  3246. */
  3247. /**
  3248. * Function: Constructor
  3249. *
  3250. * Parameters:
  3251. * stub - minimum length for the stub at each end of the connector. defaults to 30 pixels.
  3252. */
  3253. jsPlumb.Connectors.Flowchart = function(params) {
  3254. params = params || {};
  3255. var self = this,
  3256. minStubLength = params.stub || params.minStubLength /* bwds compat. */ || 30,
  3257. segments = [],
  3258. segmentGradients = [],
  3259. segmentProportions = [],
  3260. segmentLengths = [],
  3261. segmentProportionalLengths = [],
  3262. points = [],
  3263. swapX,
  3264. swapY,
  3265. /**
  3266. * recalculates the gradients of each segment, and the points at which the segments begin, proportional to the total length travelled
  3267. * by all the segments that constitute the connector.
  3268. */
  3269. updateSegmentGradientsAndProportions = function(startX, startY, endX, endY) {
  3270. var total = 0;
  3271. for (var i = 0; i < segments.length; i++) {
  3272. var sx = i == 0 ? startX : segments[i][2],
  3273. sy = i == 0 ? startY : segments[i][3],
  3274. ex = segments[i][0],
  3275. ey = segments[i][1];
  3276. segmentGradients[i] = sx == ex ? Infinity : 0;
  3277. segmentLengths[i] = Math.abs(sx == ex ? ey - sy : ex - sx);
  3278. total += segmentLengths[i];
  3279. }
  3280. var curLoc = 0;
  3281. for (var i = 0; i < segments.length; i++) {
  3282. segmentProportionalLengths[i] = segmentLengths[i] / total;
  3283. segmentProportions[i] = [curLoc, (curLoc += (segmentLengths[i] / total)) ];
  3284. }
  3285. },
  3286. appendSegmentsToPoints = function() {
  3287. points.push(segments.length);
  3288. for (var i = 0; i < segments.length; i++) {
  3289. points.push(segments[i][0]);
  3290. points.push(segments[i][1]);
  3291. }
  3292. },
  3293. /**
  3294. * helper method to add a segment.
  3295. */
  3296. addSegment = function(x, y, sx, sy, tx, ty) {
  3297. var lx = segments.length == 0 ? sx : segments[segments.length - 1][0];
  3298. var ly = segments.length == 0 ? sy : segments[segments.length - 1][1];
  3299. segments.push([x, y, lx, ly]);
  3300. },
  3301. /**
  3302. * returns [segment, proportion of travel in segment, segment index] for the segment
  3303. * that contains the point which is 'location' distance along the entire path, where
  3304. * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
  3305. * are made up of a list of segments, each of which contributes some fraction to
  3306. * the total length.
  3307. */
  3308. findSegmentForLocation = function(location) {
  3309. var idx = segmentProportions.length - 1, inSegmentProportion = 0;
  3310. for (var i = 0; i < segmentProportions.length; i++) {
  3311. if (segmentProportions[i][1] >= location) {
  3312. idx = i;
  3313. inSegmentProportion = (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
  3314. break;
  3315. }
  3316. }
  3317. return { segment:segments[idx], proportion:inSegmentProportion, index:idx };
  3318. };
  3319. this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth, minWidth) {
  3320. segments = [];
  3321. segmentGradients = [];
  3322. segmentProportionalLengths = [];
  3323. segmentLengths = [];
  3324. segmentProportionals = [];
  3325. swapX = targetPos[0] < sourcePos[0];
  3326. swapY = targetPos[1] < sourcePos[1];
  3327. var lw = lineWidth || 1,
  3328. offx = (lw / 2) + (minStubLength * 2),
  3329. offy = (lw / 2) + (minStubLength * 2),
  3330. so = sourceAnchor.orientation || sourceAnchor.getOrientation(),
  3331. to = targetAnchor.orientation || targetAnchor.getOrientation(),
  3332. x = swapX ? targetPos[0] : sourcePos[0],
  3333. y = swapY ? targetPos[1] : sourcePos[1],
  3334. w = Math.abs(targetPos[0] - sourcePos[0]) + 2*offx,
  3335. h = Math.abs(targetPos[1] - sourcePos[1]) + 2*offy;
  3336. if (w < minWidth) {
  3337. offx += (minWidth - w) / 2;
  3338. w = minWidth;
  3339. }
  3340. if (h < minWidth) {
  3341. offy += (minWidth - h) / 2;
  3342. h = minWidth;
  3343. }
  3344. var sx = swapX ? w-offx : offx,
  3345. sy = swapY ? h-offy : offy,
  3346. tx = swapX ? offx : w-offx ,
  3347. ty = swapY ? offy : h-offy,
  3348. startStubX = sx + (so[0] * minStubLength),
  3349. startStubY = sy + (so[1] * minStubLength),
  3350. endStubX = tx + (to[0] * minStubLength),
  3351. endStubY = ty + (to[1] * minStubLength),
  3352. midx = startStubX + ((endStubX - startStubX) / 2),
  3353. midy = startStubY + ((endStubY - startStubY) / 2);
  3354. x -= offx; y -= offy;
  3355. points = [x, y, w, h, sx, sy, tx, ty], extraPoints = [];
  3356. addSegment(startStubX, startStubY, sx, sy, tx, ty);
  3357. if (so[0] == 0) {
  3358. var startStubIsBeforeEndStub = startStubY < endStubY;
  3359. // when start point's stub is less than endpoint's stub
  3360. if (startStubIsBeforeEndStub) {
  3361. addSegment(startStubX, midy, sx, sy, tx, ty);
  3362. addSegment(midx, midy, sx, sy, tx, ty);
  3363. addSegment(endStubX, midy, sx, sy, tx, ty);
  3364. } else {
  3365. // when start point's stub is greater than endpoint's stub
  3366. addSegment(midx, startStubY, sx, sy, tx, ty);
  3367. addSegment(midx, endStubY, sx, sy, tx, ty);
  3368. }
  3369. }
  3370. else {
  3371. var startStubIsBeforeEndStub = startStubX < endStubX;
  3372. // when start point's stub is less than endpoint's stub
  3373. if (startStubIsBeforeEndStub) {
  3374. addSegment(midx, startStubY, sx, sy, tx, ty);
  3375. addSegment(midx, midy, sx, sy, tx, ty);
  3376. addSegment(midx, endStubY, sx, sy, tx, ty);
  3377. } else {
  3378. // when start point's stub is greater than endpoint's stub
  3379. addSegment(startStubX, midy, sx, sy, tx, ty);
  3380. addSegment(endStubX, midy, sx, sy, tx, ty);
  3381. }
  3382. }
  3383. addSegment(endStubX, endStubY, sx, sy, tx, ty);
  3384. addSegment(tx, ty, sx, sy, tx, ty);
  3385. appendSegmentsToPoints();
  3386. updateSegmentGradientsAndProportions(sx, sy, tx, ty);
  3387. return points;
  3388. };
  3389. /**
  3390. * returns the point on the connector's path that is 'location' along the length of the path, where 'location' is a decimal from
  3391. * 0 to 1 inclusive. for this connector we must first figure out which segment the given point lies in, and then compute the x,y position
  3392. * from our knowledge of the segment's start and end points.
  3393. */
  3394. this.pointOnPath = function(location) {
  3395. return self.pointAlongPathFrom(location, 0);
  3396. };
  3397. /**
  3398. * returns the gradient of the connector at the given point; the gradient will be either 0 or Infinity, depending on the direction of the
  3399. * segment the point falls in. segment gradients are calculated in the compute method.
  3400. */
  3401. this.gradientAtPoint = function(location) {
  3402. return segmentGradients[findSegmentForLocation(location)["index"]];
  3403. };
  3404. /**
  3405. * returns the point on the connector's path that is 'distance' along the length of the path from 'location', where
  3406. * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels. when you consider this concept from the point of view
  3407. * of this connector, it starts to become clear that there's a problem with the overlay paint code: given that this connector makes several
  3408. * 90 degree turns, it's entirely possible that an arrow overlay could be forced to paint itself around a corner, which would look stupid. this is
  3409. * because jsPlumb uses this method (and pointOnPath) so determine the locations of the various points that go to make up an overlay. a better
  3410. * solution would probably be to just use pointOnPath along with gradientAtPoint, and draw the overlay so that its axis ran along
  3411. * a tangent to the connector. for straight line connectors this would obviously mean the overlay was painted directly on the connector, since a
  3412. * tangent to a straight line is the line itself, which is what we want; for this connector, and for beziers, the results would probably be better. an additional
  3413. * advantage is, of course, that there's less computation involved doing it that way.
  3414. */
  3415. this.pointAlongPathFrom = function(location, distance) {
  3416. var s = findSegmentForLocation(location), seg = s.segment, p = s.proportion, sl = segmentLengths[s.index], m = segmentGradients[s.index];
  3417. var e = {
  3418. x : m == Infinity ? seg[2] : seg[2] > seg[0] ? seg[0] + ((1 - p) * sl) - distance : seg[2] + (p * sl) + distance,
  3419. y : m == 0 ? seg[3] : seg[3] > seg[1] ? seg[1] + ((1 - p) * sl) - distance : seg[3] + (p * sl) + distance,
  3420. segmentInfo : s
  3421. };
  3422. return e;
  3423. };
  3424. /**
  3425. * calculates a line that is perpendicular to, and centered on, the path at 'distance' pixels from the given location.
  3426. * the line is 'length' pixels long.
  3427. */
  3428. this.perpendicularToPathAt = function(location, length, distance) {
  3429. var p = self.pointAlongPathFrom(location, distance);
  3430. var m = segmentGradients[p.segmentInfo.index];
  3431. var _theta2 = Math.atan(-1 / m);
  3432. var y = length / 2 * Math.sin(_theta2);
  3433. var x = length / 2 * Math.cos(_theta2);
  3434. return [{x:p.x + x, y:p.y + y}, {x:p.x - x, y:p.y - y}];
  3435. };
  3436. };
  3437. // ********************************* END OF CONNECTOR TYPES *******************************************************************
  3438. // ********************************* ENDPOINT TYPES *******************************************************************
  3439. /**
  3440. * Class: Endpoints.Dot
  3441. * A round endpoint, with default radius 10 pixels.
  3442. */
  3443. /**
  3444. * Function: Constructor
  3445. *
  3446. * Parameters:
  3447. *
  3448. * radius - radius of the endpoint. defaults to 10 pixels.
  3449. */
  3450. jsPlumb.Endpoints.Dot = function(params) {
  3451. var self = this;
  3452. params = params || {};
  3453. this.radius = params.radius || 10;
  3454. this.defaultOffset = 0.5 * this.radius;
  3455. this.defaultInnerRadius = this.radius / 3;
  3456. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3457. var r = endpointStyle.radius || self.radius;
  3458. var x = anchorPoint[0] - r;
  3459. var y = anchorPoint[1] - r;
  3460. return [ x, y, r * 2, r * 2, r ];
  3461. };
  3462. };
  3463. /**
  3464. * Class: Endpoints.Rectangle
  3465. * A Rectangular Endpoint, with default size 20x20.
  3466. */
  3467. /**
  3468. * Function: Constructor
  3469. *
  3470. * Parameters:
  3471. *
  3472. * width - width of the endpoint. defaults to 20 pixels.
  3473. * height - height of the endpoint. defaults to 20 pixels.
  3474. */
  3475. jsPlumb.Endpoints.Rectangle = function(params) {
  3476. var self = this;
  3477. params = params || {};
  3478. this.width = params.width || 20;
  3479. this.height = params.height || 20;
  3480. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3481. var width = endpointStyle.width || self.width;
  3482. var height = endpointStyle.height || self.height;
  3483. var x = anchorPoint[0] - (width/2);
  3484. var y = anchorPoint[1] - (height/2);
  3485. return [ x, y, width, height];
  3486. };
  3487. };
  3488. /**
  3489. * Class: Endpoints.Image
  3490. * Draws an image as the Endpoint.
  3491. */
  3492. /**
  3493. * Function: Constructor
  3494. *
  3495. * Parameters:
  3496. *
  3497. * src - location of the image to use.
  3498. */
  3499. jsPlumb.Endpoints.Image = function(params) {
  3500. jsPlumb.DOMElementComponent.apply(this, arguments);
  3501. var self = this, initialized = false;
  3502. this.img = new Image();
  3503. self.ready = false;
  3504. this.img.onload = function() {
  3505. self.ready = true;
  3506. };
  3507. this.img.src = params.src || params.url;
  3508. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3509. self.anchorPoint = anchorPoint;
  3510. if (self.ready) return [anchorPoint[0] - self.img.width / 2, anchorPoint[1] - self.img.height/ 2, self.img.width, self.img.height];
  3511. else return [0,0,0,0];
  3512. };
  3513. self.canvas = document.createElement("img"), initialized = false;
  3514. self.canvas.style["margin"] = 0;
  3515. self.canvas.style["padding"] = 0;
  3516. self.canvas.style["outline"] = 0;
  3517. self.canvas.style["position"] = "absolute";
  3518. self.canvas.className = jsPlumb.endpointClass;
  3519. jsPlumb.appendElement(self.canvas, params.parent);
  3520. self.attachListeners(self.canvas, self);
  3521. var actuallyPaint = function(d, style, anchor) {
  3522. if (!initialized) {
  3523. self.canvas.setAttribute("src", self.img.src);
  3524. initialized = true;
  3525. }
  3526. var width = self.img.width,
  3527. height = self.img.height,
  3528. x = self.anchorPoint[0] - (width/2),
  3529. y = self.anchorPoint[1] - (height/2);
  3530. jsPlumb.sizeCanvas(self.canvas, x, y, width, height);
  3531. };
  3532. this.paint = function(d, style, anchor) {
  3533. if (self.ready) {
  3534. actuallyPaint(d, style, anchor);
  3535. }
  3536. else {
  3537. window.setTimeout(function() {
  3538. self.paint(d, style, anchor);
  3539. }, 200);
  3540. }
  3541. };
  3542. };
  3543. /**
  3544. * Class: Endpoints.Blank
  3545. * An Endpoint that paints nothing on the screen, and cannot be interacted with using the mouse. There are no constructor parameters for this Endpoint.
  3546. */
  3547. jsPlumb.Endpoints.Blank = function() {
  3548. jsPlumb.DOMElementComponent.apply(this, arguments);
  3549. this.compute = function() {
  3550. return [0,0,0,0];
  3551. };
  3552. self.canvas = document.createElement("div");
  3553. this.paint = function() { };
  3554. };
  3555. /**
  3556. * Class: Endpoints.Triangle
  3557. * A triangular Endpoint.
  3558. */
  3559. /**
  3560. * Function: Constructor
  3561. *
  3562. * Parameters:
  3563. *
  3564. * width - width of the triangle's base. defaults to 55 pixels.
  3565. * height - height of the triangle from base to apex. defaults to 55 pixels.
  3566. */
  3567. jsPlumb.Endpoints.Triangle = function(params) {
  3568. params = params || { };
  3569. params.width = params.width || 55;
  3570. param.height = params.height || 55;
  3571. this.width = params.width;
  3572. this.height = params.height;
  3573. this.compute = function(anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
  3574. var width = endpointStyle.width || self.width;
  3575. var height = endpointStyle.height || self.height;
  3576. var x = anchorPoint[0] - (width/2);
  3577. var y = anchorPoint[1] - (height/2);
  3578. return [ x, y, width, height ];
  3579. };
  3580. };
  3581. // ********************************* END OF ENDPOINT TYPES *******************************************************************
  3582. // ********************************* OVERLAY DEFINITIONS ***********************************************************************
  3583. /**
  3584. * Class: Overlays.Arrow
  3585. *
  3586. * An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length
  3587. * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
  3588. * of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line
  3589. * across the tail.
  3590. */
  3591. /**
  3592. * Function: Constructor
  3593. *
  3594. * Parameters:
  3595. *
  3596. * length - distance in pixels from head to tail baseline. default 20.
  3597. * width - width in pixels of the tail baseline. default 20.
  3598. * fillStyle - style to use when filling the arrow. defaults to "black".
  3599. * strokeStyle - style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
  3600. * lineWidth - line width to use when stroking the arrow. defaults to 1, but only used if strokeStyle is not null.
  3601. * foldback - distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
  3602. * location - distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
  3603. * direction - indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
  3604. */
  3605. jsPlumb.Overlays.Arrow = function(params) {
  3606. params = params || {};
  3607. var self = this;
  3608. this.length = params.length || 20;
  3609. this.width = params.width || 20;
  3610. this.id = params.id;
  3611. this.connection = params.connection;
  3612. var direction = (params.direction || 1) < 0 ? -1 : 1;
  3613. var paintStyle = params.paintStyle || { lineWidth:1 };
  3614. this.loc = params.location == null ? 0.5 : params.location;
  3615. // how far along the arrow the lines folding back in come to. default is 62.3%.
  3616. var foldback = params.foldback || 0.623;
  3617. var _getFoldBackPoint = function(connector, loc) {
  3618. if (foldback == 0.5) return connector.pointOnPath(loc);
  3619. else {
  3620. var adj = 0.5 - foldback; // we calculate relative to the center
  3621. return connector.pointAlongPathFrom(loc, direction * self.length * adj);
  3622. }
  3623. };
  3624. this.computeMaxSize = function() { return self.width * 1.5; };
  3625. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  3626. // this is the arrow head position
  3627. var hxy = connector.pointAlongPathFrom(self.loc, direction * (self.length / 2));
  3628. // this is the center of the tail
  3629. var txy = connector.pointAlongPathFrom(self.loc, -1 * direction * (self.length / 2)), tx = txy.x, ty = txy.y;
  3630. // this is the tail vector
  3631. var tail = connector.perpendicularToPathAt(self.loc, self.width, -1 * direction * (self.length / 2));
  3632. // this is the point the tail goes in to
  3633. var cxy = _getFoldBackPoint(connector, self.loc);
  3634. // if loc = 1, then hxy should be flush with the element, or if direction == -1, the tail midpoint.
  3635. if (self.loc == 1) {
  3636. var lxy = connector.pointOnPath(self.loc);
  3637. // TODO determine why the 1.2.6 released version does not
  3638. // use 'direction' in the two equations below, yet both
  3639. // that and 1.3.0 still paint the arrows correctly.
  3640. var dx = (lxy.x - hxy.x) * direction, dy = (lxy.y - hxy.y) * direction;
  3641. cxy.x += dx; cxy.y += dy;
  3642. txy.x += dx; txy.y += dy;
  3643. tail[0].x += dx; tail[0].y += dy;
  3644. tail[1].x += dx; tail[1].y += dy;
  3645. hxy.x += dx; hxy.y += dy;
  3646. }
  3647. // if loc = 0, then tail midpoint should be flush with the element, or, if direction == -1, hxy should be.
  3648. if (self.loc == 0) {
  3649. var lxy = connector.pointOnPath(self.loc);
  3650. var tailMid = foldback > 1 ? cxy : {
  3651. x:tail[0].x + ((tail[1].x - tail[0].x) / 2),
  3652. y:tail[0].y + ((tail[1].y - tail[0].y) / 2)
  3653. };
  3654. var dx = (lxy.x - tailMid.x) * direction, dy = (lxy.y - tailMid.y) * direction;
  3655. cxy.x += dx; cxy.y += dy;
  3656. txy.x += dx; txy.y += dy;
  3657. tail[0].x += dx; tail[0].y += dy;
  3658. tail[1].x += dx; tail[1].y += dy;
  3659. hxy.x += dx; hxy.y += dy;
  3660. }
  3661. var minx = Math.min(hxy.x, tail[0].x, tail[1].x);
  3662. var maxx = Math.max(hxy.x, tail[0].x, tail[1].x);
  3663. var miny = Math.min(hxy.y, tail[0].y, tail[1].y);
  3664. var maxy = Math.max(hxy.y, tail[0].y, tail[1].y);
  3665. var d = { hxy:hxy, tail:tail, cxy:cxy },
  3666. strokeStyle = paintStyle.strokeStyle || currentConnectionPaintStyle.strokeStyle,
  3667. fillStyle = paintStyle.fillStyle || currentConnectionPaintStyle.strokeStyle,
  3668. lineWidth = paintStyle.lineWidth || currentConnectionPaintStyle.lineWidth;
  3669. self.paint(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions);
  3670. return [ minx, maxx, miny, maxy];
  3671. };
  3672. };
  3673. /**
  3674. * Class: Overlays.PlainArrow
  3675. *
  3676. * A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some
  3677. * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
  3678. * a 'call' to Arrow with foldback set appropriately.
  3679. */
  3680. /**
  3681. * Function: Constructor
  3682. * See <Overlays.Arrow> for allowed parameters for this overlay.
  3683. */
  3684. jsPlumb.Overlays.PlainArrow = function(params) {
  3685. params = params || {};
  3686. var p = jsPlumb.extend(params, {foldback:1});
  3687. jsPlumb.Overlays.Arrow.call(this, p);
  3688. };
  3689. /**
  3690. * Class: Overlays.Diamond
  3691. *
  3692. * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
  3693. * happens that in this case, that point is greater than the length of the the arrow.
  3694. *
  3695. * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
  3696. * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
  3697. * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
  3698. * would be -l/4 in this case - move along one quarter of the total length.
  3699. */
  3700. /**
  3701. * Function: Constructor
  3702. * See <Overlays.Arrow> for allowed parameters for this overlay.
  3703. */
  3704. jsPlumb.Overlays.Diamond = function(params) {
  3705. params = params || {};
  3706. var l = params.length || 40;
  3707. var p = jsPlumb.extend(params, {length:l/2, foldback:2});
  3708. jsPlumb.Overlays.Arrow.call(this, p);
  3709. };
  3710. /**
  3711. * Class: Overlays.Label
  3712. * A Label overlay. For all different renderer types (SVG/Canvas/VML), jsPlumb draws a Label overlay as a styled DIV. Version 1.3.0 of jsPlumb
  3713. * introduced the ability to set css classes on the label; this is now the preferred way for you to style a label. The 'labelStyle' parameter
  3714. * is still supported in 1.3.0 but its usage is deprecated. Under the hood, jsPlumb just turns that object into a bunch of CSS directive that it
  3715. * puts on the Label's 'style' attribute, so the end result is the same.
  3716. */
  3717. /**
  3718. * Function: Constructor
  3719. *
  3720. * Parameters:
  3721. * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
  3722. * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
  3723. * label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your
  3724. * label function returns null. empty strings _will_ be painted.
  3725. * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
  3726. * labelStyle - (deprecated) js object containing style instructions for the label. defaults to jsPlumb.Defaults.LabelStyle.
  3727. * borderWidth - (deprecated) width of a border to paint. defaults to zero.
  3728. * borderStyle - (deprecated) strokeStyle to use when painting the border, if necessary.
  3729. *
  3730. */
  3731. jsPlumb.Overlays.Label = function(params) {
  3732. jsPlumb.DOMElementComponent.apply(this, arguments);
  3733. this.labelStyle = params.labelStyle || jsPlumb.Defaults.LabelStyle;
  3734. this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
  3735. this.label = params.label;
  3736. this.connection = params.connection;
  3737. this.id = params.id;
  3738. var self = this;
  3739. var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
  3740. this.location = params.location || 0.5;
  3741. this.cachedDimensions = null; // setting on 'this' rather than using closures uses a lot less memory. just don't monkey with it!
  3742. var initialised = false,
  3743. labelText = null,
  3744. div = document.createElement("div");
  3745. div.style["position"] = "absolute";
  3746. div.style["textAlign"] = "center";
  3747. div.style["cursor"] = "pointer";
  3748. div.style["font"] = self.labelStyle.font;
  3749. div.style["color"] = self.labelStyle.color || "black";
  3750. if (self.labelStyle.fillStyle) div.style["background"] = self.labelStyle.fillStyle;//_convertStyle(self.labelStyle.fillStyle, true);
  3751. if (self.labelStyle.borderWidth > 0) {
  3752. var dStyle = self.labelStyle.borderStyle ? self.labelStyle.borderStyle/*_convertStyle(self.labelStyle.borderStyle, true)*/ : "black";
  3753. div.style["border"] = self.labelStyle.borderWidth + "px solid " + dStyle;
  3754. }
  3755. if (self.labelStyle.padding) div.style["padding"] = self.labelStyle.padding;
  3756. var clazz = params["_jsPlumb"].overlayClass + " " +
  3757. (self.labelStyle.cssClass ? self.labelStyle.cssClass :
  3758. params.cssClass ? params.cssClass : "");
  3759. div.className = clazz;
  3760. jsPlumb.appendElement(div, params.connection.parent);
  3761. jsPlumb.getId(div);
  3762. self.attachListeners(div, self);
  3763. this.paint = function(connector, d, connectorDimensions) {
  3764. if (!initialised) {
  3765. connector.appendDisplayElement(div);
  3766. self.attachListeners(div, connector);
  3767. initialised = true;
  3768. }
  3769. div.style.left = (connectorDimensions[0] + d.minx) + "px";
  3770. div.style.top = (connectorDimensions[1] + d.miny) + "px";
  3771. };
  3772. this.getTextDimensions = function(connector) {
  3773. labelText = typeof self.label == 'function' ? self.label(self) : self.label;
  3774. div.innerHTML = labelText.replace(/\r\n/g, "<br/>");
  3775. var de = jsPlumb.CurrentLibrary.getElementObject(div),
  3776. s = jsPlumb.CurrentLibrary.getSize(de);
  3777. return {width:s[0], height:s[1]};
  3778. };
  3779. this.computeMaxSize = function(connector) {
  3780. var td = self.getTextDimensions(connector);
  3781. return td.width ? Math.max(td.width, td.height) * 1.5 : 0;
  3782. };
  3783. this.draw = function(connector, currentConnectionPaintStyle, connectorDimensions) {
  3784. var td = self.getTextDimensions(connector);
  3785. if (td.width != null) {
  3786. var cxy = connector.pointOnPath(self.location);
  3787. var minx = cxy.x - (td.width / 2);
  3788. var miny = cxy.y - (td.height / 2);
  3789. self.paint(connector, {
  3790. minx:minx,
  3791. miny:miny,
  3792. td:td,
  3793. cxy:cxy
  3794. }, connectorDimensions);
  3795. return [minx, minx+td.width, miny, miny+td.height];
  3796. }
  3797. else return [0,0,0,0];
  3798. };
  3799. };
  3800. // ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
  3801. // ********************************* OVERLAY CANVAS RENDERERS***********************************************************************
  3802. // ********************************* END OF OVERLAY CANVAS RENDERERS ***********************************************************************
  3803. })();;(function() {
  3804. // http://ajaxian.com/archives/the-vml-changes-in-ie-8
  3805. // http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/
  3806. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  3807. var vmlAttributeMap = {
  3808. "stroke-linejoin":"joinstyle",
  3809. "joinstyle":"joinstyle",
  3810. "endcap":"endcap",
  3811. "miterlimit":"miterlimit"
  3812. };
  3813. if (document.createStyleSheet) {
  3814. // this is the style rule for IE7/6: it uses a CSS class, tidy.
  3815. document.createStyleSheet().addRule(".jsplumb_vml", "behavior:url(#default#VML);position:absolute;");
  3816. // these are for VML in IE8. you have to explicitly call out which elements
  3817. // you're going to expect to support VML!
  3818. //
  3819. // try to avoid IE8. it is recommended you set X-UA-Compatible="IE=7" if you can.
  3820. //
  3821. document.createStyleSheet().addRule("jsplumb\\:textbox", "behavior:url(#default#VML);position:absolute;");
  3822. document.createStyleSheet().addRule("jsplumb\\:oval", "behavior:url(#default#VML);position:absolute;");
  3823. document.createStyleSheet().addRule("jsplumb\\:rect", "behavior:url(#default#VML);position:absolute;");
  3824. document.createStyleSheet().addRule("jsplumb\\:stroke", "behavior:url(#default#VML);position:absolute;");
  3825. document.createStyleSheet().addRule("jsplumb\\:shape", "behavior:url(#default#VML);position:absolute;");
  3826. // in this page it is also mentioned that IE requires the extra arg to the namespace
  3827. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  3828. // but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either.
  3829. // var iev = document.documentMode;
  3830. //if (!iev || iev < 8)
  3831. document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml");
  3832. //else
  3833. // document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML");
  3834. }
  3835. var scale = 1000,
  3836. _atts = function(o, atts) {
  3837. for (var i in atts) {
  3838. // IE8 fix: setattribute does not work after an element has been added to the dom!
  3839. // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/
  3840. //o.setAttribute(i, atts[i]);
  3841. o[i] = atts[i];
  3842. }
  3843. },
  3844. _node = function(name, d, atts) {
  3845. atts = atts || {};
  3846. var o = document.createElement("jsplumb:" + name);
  3847. o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml";
  3848. _pos(o, d);
  3849. _atts(o, atts);
  3850. return o;
  3851. },
  3852. _pos = function(o,d) {
  3853. o.style.left = d[0] + "px";
  3854. o.style.top = d[1] + "px";
  3855. o.style.width= d[2] + "px";
  3856. o.style.height= d[3] + "px";
  3857. o.style.position = "absolute";
  3858. },
  3859. _conv = function(v) {
  3860. return Math.floor(v * scale);
  3861. },
  3862. _convertStyle = function(s, ignoreAlpha) {
  3863. var o = s,
  3864. pad = function(n) { return n.length == 1 ? "0" + n : n; },
  3865. hex = function(k) { return pad(Number(k).toString(16)); },
  3866. pattern = /(rgb[a]?\()(.*)(\))/;
  3867. if (s.match(pattern)) {
  3868. var parts = s.match(pattern)[2].split(",");
  3869. o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
  3870. if (!ignoreAlpha && parts.length == 4)
  3871. o = o + hex(parts[3]);
  3872. }
  3873. return o;
  3874. },
  3875. _applyStyles = function(node, style, component) {
  3876. var styleToWrite = {};
  3877. if (style.strokeStyle) {
  3878. styleToWrite["stroked"] = "true";
  3879. styleToWrite["strokecolor"] =_convertStyle(style.strokeStyle, true);
  3880. styleToWrite["strokeweight"] = style.lineWidth + "px";
  3881. }
  3882. else styleToWrite["stroked"] = "false";
  3883. if (style.fillStyle) {
  3884. styleToWrite["filled"] = "true";
  3885. styleToWrite["fillcolor"] = _convertStyle(style.fillStyle, true);
  3886. }
  3887. else styleToWrite["filled"] = "false";
  3888. if(style["dashstyle"]) {
  3889. if (component.strokeNode == null) {
  3890. component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] });
  3891. node.appendChild(component.strokeNode);
  3892. }
  3893. else
  3894. component.strokeNode.dashstyle = style["dashstyle"];
  3895. }
  3896. else if (style["stroke-dasharray"] && style["lineWidth"]) {
  3897. var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",",
  3898. parts = style["stroke-dasharray"].split(sep),
  3899. styleToUse = "";
  3900. for(var i = 0; i < parts.length; i++) {
  3901. styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep);
  3902. }
  3903. if (component.strokeNode == null) {
  3904. component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse });
  3905. node.appendChild(component.strokeNode);
  3906. }
  3907. else
  3908. component.strokeNode.dashstyle = styleToUse;
  3909. }
  3910. _atts(node, styleToWrite);
  3911. },
  3912. /*
  3913. * Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent.
  3914. */
  3915. VmlComponent = function() {
  3916. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  3917. },
  3918. /*
  3919. * Base class for Vml connectors. extends VmlComponent.
  3920. */
  3921. VmlConnector = function(params) {
  3922. var self = this;
  3923. self.strokeNode = null;
  3924. self.canvas = null;
  3925. VmlComponent.apply(this, arguments);
  3926. clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : "");
  3927. this.paint = function(d, style, anchor) {
  3928. if (style != null) {
  3929. var path = self.getPath(d), p = { "path":path };
  3930. if (style.outlineColor) {
  3931. var outlineWidth = style.outlineWidth || 1,
  3932. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  3933. outlineStyle = {
  3934. strokeStyle:_convertStyle(style.outlineColor),
  3935. lineWidth:outlineStrokeWidth
  3936. };
  3937. if (self.bgCanvas == null) {
  3938. p["class"] = clazz;
  3939. self.bgCanvas = _node("shape", d, p);
  3940. jsPlumb.appendElement(self.bgCanvas, params.parent);
  3941. displayElements.push(self.bgCanvas);
  3942. }
  3943. else {
  3944. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  3945. _pos(self.bgCanvas, d);
  3946. _atts(self.bgCanvas, p);
  3947. }
  3948. _applyStyles(self.bgCanvas, outlineStyle, self);
  3949. }
  3950. if (self.canvas == null) {
  3951. p["class"] = clazz;
  3952. self.canvas = _node("shape", d, p);
  3953. jsPlumb.appendElement(self.canvas, params.parent);
  3954. displayElements.push(self.canvas);
  3955. self.attachListeners(self.canvas, self);
  3956. }
  3957. else {
  3958. p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale);
  3959. _pos(self.canvas, d);
  3960. _atts(self.canvas, p);
  3961. }
  3962. _applyStyles(self.canvas, style, self);
  3963. }
  3964. };
  3965. var displayElements = [ self.canvas ];
  3966. this.getDisplayElements = function() {
  3967. return displayElements;
  3968. };
  3969. this.appendDisplayElement = function(el) {
  3970. self.canvas.parentNode.appendChild(el);
  3971. displayElements.push(el);
  3972. };
  3973. },
  3974. /*
  3975. *
  3976. * Base class for Vml Endpoints. extends VmlComponent.
  3977. *
  3978. */
  3979. VmlEndpoint = function(params) {
  3980. VmlComponent.apply(this, arguments);
  3981. var vml = null, self = this;
  3982. self.canvas = document.createElement("div");
  3983. self.canvas.style["position"] = "absolute";
  3984. jsPlumb.appendElement(self.canvas, params.parent);
  3985. this.paint = function(d, style, anchor) {
  3986. var p = { };
  3987. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  3988. if (vml == null) {
  3989. p["class"] = jsPlumb.endpointClass;
  3990. vml = self.getVml([0,0, d[2], d[3]], p, anchor);
  3991. self.canvas.appendChild(vml);
  3992. self.attachListeners(vml, self);
  3993. }
  3994. else {
  3995. //p["coordsize"] = "1,1";//(d[2] * scale) + "," + (d[3] * scale); again, unsure.
  3996. _pos(vml, [0,0, d[2], d[3]]);
  3997. _atts(vml, p);
  3998. }
  3999. _applyStyles(vml, style);
  4000. };
  4001. };
  4002. jsPlumb.Connectors.vml.Bezier = function() {
  4003. jsPlumb.Connectors.Bezier.apply(this, arguments);
  4004. VmlConnector.apply(this, arguments);
  4005. this.getPath = function(d) {
  4006. return "m" + _conv(d[4]) + "," + _conv(d[5]) +
  4007. " c" + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[10]) + "," + _conv(d[11]) + "," + _conv(d[6]) + "," + _conv(d[7]) + " e";
  4008. };
  4009. };
  4010. jsPlumb.Connectors.vml.Straight = function() {
  4011. jsPlumb.Connectors.Straight.apply(this, arguments);
  4012. VmlConnector.apply(this, arguments);
  4013. this.getPath = function(d) {
  4014. return "m" + _conv(d[4]) + "," + _conv(d[5]) + " l" + _conv(d[6]) + "," + _conv(d[7]) + " e";
  4015. };
  4016. };
  4017. jsPlumb.Connectors.vml.Flowchart = function() {
  4018. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  4019. VmlConnector.apply(this, arguments);
  4020. this.getPath = function(dimensions) {
  4021. var p = "m " + _conv(dimensions[4]) + "," + _conv(dimensions[5]) + " l";
  4022. // loop through extra points
  4023. for (var i = 0; i < dimensions[8]; i++) {
  4024. p = p + " " + _conv(dimensions[9 + (i*2)]) + "," + _conv(dimensions[10 + (i*2)]);
  4025. }
  4026. // finally draw a line to the end
  4027. p = p + " " + _conv(dimensions[6]) + "," + _conv(dimensions[7]) + " e";
  4028. return p;
  4029. };
  4030. };
  4031. jsPlumb.Endpoints.vml.Dot = function() {
  4032. jsPlumb.Endpoints.Dot.apply(this, arguments);
  4033. VmlEndpoint.apply(this, arguments);
  4034. this.getVml = function(d, atts, anchor) { return _node("oval", d, atts); };
  4035. };
  4036. jsPlumb.Endpoints.vml.Rectangle = function() {
  4037. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  4038. VmlEndpoint.apply(this, arguments);
  4039. this.getVml = function(d, atts, anchor) { return _node("rect", d, atts); };
  4040. };
  4041. /*
  4042. * VML Image Endpoint is the same as the default image endpoint.
  4043. */
  4044. jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image;
  4045. /**
  4046. * placeholder for Blank endpoint in vml renderer.
  4047. */
  4048. jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank;
  4049. /**
  4050. * VML Label renderer. uses the default label renderer (which adds an element to the DOM)
  4051. */
  4052. jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label;
  4053. var AbstractVmlArrowOverlay = function(superclass, originalArgs) {
  4054. superclass.apply(this, originalArgs);
  4055. VmlComponent.apply(this, arguments);
  4056. var self = this, canvas = null, path =null;
  4057. var getPath = function(d, connectorDimensions) {
  4058. return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) +
  4059. " l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) +
  4060. " " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) +
  4061. " " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) +
  4062. " x e";
  4063. };
  4064. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions) {
  4065. var p = {};
  4066. if (strokeStyle) {
  4067. p["stroked"] = "true";
  4068. p["strokecolor"] =_convertStyle(strokeStyle, true);
  4069. }
  4070. if (lineWidth) p["strokeweight"] = lineWidth + "px";
  4071. if (fillStyle) {
  4072. p["filled"] = "true";
  4073. p["fillcolor"] = fillStyle;
  4074. }
  4075. var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
  4076. ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
  4077. xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x),
  4078. ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y),
  4079. w = Math.abs(xmax - xmin),
  4080. h = Math.abs(ymax - ymin),
  4081. dim = [xmin, ymin, w, h];
  4082. // for VML, we create overlays using shapes that have the same dimensions and
  4083. // coordsize as their connector - overlays calculate themselves relative to the
  4084. // connector (it's how it's been done since the original canvas implementation, because
  4085. // for canvas that makes sense).
  4086. p["path"] = getPath(d, connectorDimensions);
  4087. p["coordsize"] = (connectorDimensions[2] * scale) + "," + (connectorDimensions[3] * scale);
  4088. dim[0] = connectorDimensions[0];
  4089. dim[1] = connectorDimensions[1];
  4090. dim[2] = connectorDimensions[2];
  4091. dim[3] = connectorDimensions[3];
  4092. if (canvas == null) {
  4093. //p["class"] = jsPlumb.overlayClass; // TODO currentInstance?
  4094. canvas = _node("shape", dim, p);
  4095. connector.appendDisplayElement(canvas);
  4096. self.attachListeners(canvas, connector);
  4097. }
  4098. else {
  4099. _pos(canvas, dim);
  4100. _atts(canvas, p);
  4101. }
  4102. };
  4103. };
  4104. jsPlumb.Overlays.vml.Arrow = function() {
  4105. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  4106. };
  4107. jsPlumb.Overlays.vml.PlainArrow = function() {
  4108. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  4109. };
  4110. jsPlumb.Overlays.vml.Diamond = function() {
  4111. AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  4112. };
  4113. })();/**
  4114. * SVG support for jsPlumb.
  4115. *
  4116. * things to investigate:
  4117. *
  4118. * gradients: https://developer.mozilla.org/en/svg_in_html_introduction
  4119. * css:http://tutorials.jenkov.com/svg/svg-and-css.html
  4120. * text on a path: http://www.w3.org/TR/SVG/text.html#TextOnAPath
  4121. * pointer events: https://developer.mozilla.org/en/css/pointer-events
  4122. *
  4123. */
  4124. ;(function() {
  4125. var svgAttributeMap = {
  4126. "stroke-linejoin":"stroke-linejoin",
  4127. "joinstyle":"stroke-linejoin",
  4128. "stroke-dashoffset":"stroke-dashoffset"
  4129. };
  4130. var ns = {
  4131. svg:"http://www.w3.org/2000/svg",
  4132. xhtml:"http://www.w3.org/1999/xhtml"
  4133. },
  4134. _attr = function(node, attributes) {
  4135. for (var i in attributes)
  4136. node.setAttribute(i, "" + attributes[i]);
  4137. },
  4138. _node = function(name, attributes) {
  4139. var n = document.createElementNS(ns.svg, name);
  4140. attributes = attributes || {};
  4141. attributes["version"] = "1.1";
  4142. attributes["xmnls"] = ns.xhtml;
  4143. _attr(n, attributes);
  4144. return n;
  4145. },
  4146. _pos = function(d) { return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; },
  4147. _convertStyle = function(s, ignoreAlpha) {
  4148. var o = s,
  4149. pad = function(n) { return n.length == 1 ? "0" + n : n; },
  4150. hex = function(k) { return pad(Number(k).toString(16)); },
  4151. pattern = /(rgb[a]?\()(.*)(\))/;
  4152. if (s.match(pattern)) {
  4153. var parts = s.match(pattern)[2].split(",");
  4154. o = "#" + hex(parts[0]) + hex(parts[1]) + hex(parts[2]);
  4155. if (!ignoreAlpha && parts.length == 4)
  4156. o = o + hex(parts[3]);
  4157. }
  4158. return o;
  4159. },
  4160. _clearGradient = function(parent) {
  4161. for (var i = 0; i < parent.childNodes.length; i++) {
  4162. if (parent.childNodes[i].tagName == "linearGradient" || parent.childNodes[i].tagName == "radialGradient")
  4163. parent.removeChild(parent.childNodes[i]);
  4164. }
  4165. },
  4166. _updateGradient = function(parent, node, style, dimensions) {
  4167. var id = "jsplumb_gradient_" + (new Date()).getTime();
  4168. // first clear out any existing gradient
  4169. _clearGradient(parent);
  4170. // this checks for an 'offset' property in the gradient, and in the absence of it, assumes
  4171. // we want a linear gradient. if it's there, we create a radial gradient.
  4172. // it is possible that a more explicit means of defining the gradient type would be
  4173. // better. relying on 'offset' means that we can never have a radial gradient that uses
  4174. // some default offset, for instance.
  4175. if (!style.gradient.offset) {
  4176. var g = _node("linearGradient", {id:id});
  4177. parent.appendChild(g);
  4178. }
  4179. else {
  4180. var g = _node("radialGradient", {
  4181. id:id
  4182. });
  4183. parent.appendChild(g);
  4184. }
  4185. // the svg radial gradient seems to treat stops in the reverse
  4186. // order to how canvas does it. so we want to keep all the maths the same, but
  4187. // iterate the actual style declarations in reverse order, if the x indexes are not in order.
  4188. for (var i = 0; i < style.gradient.stops.length; i++) {
  4189. // Straight Connectors and Bezier connectors act slightly differently; this code is a bit of a kludge. but next version of
  4190. // jsplumb will be replacing both Straight and Bezier to be generic instances of 'Connector', which has a list of segments.
  4191. // so, not too concerned about leaving this in for now.
  4192. var styleToUse = i;
  4193. if (dimensions.length == 8)
  4194. styleToUse = dimensions[4] < dimensions[6] ? i: style.gradient.stops.length - 1 - i;
  4195. else
  4196. styleToUse = dimensions[4] < dimensions[6] ? style.gradient.stops.length - 1 - i : i;
  4197. var stopColor = _convertStyle(style.gradient.stops[styleToUse][1], true);
  4198. var s = _node("stop", {"offset":Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color":stopColor});
  4199. g.appendChild(s);
  4200. }
  4201. var applyGradientTo = style.strokeStyle ? "stroke" : "fill";
  4202. node.setAttribute("style", applyGradientTo + ":url(#" + id + ")");
  4203. },
  4204. _applyStyles = function(parent, node, style, dimensions) {
  4205. if (style.gradient) {
  4206. _updateGradient(parent, node, style, dimensions);
  4207. }
  4208. else {
  4209. // make sure we clear any existing gradient
  4210. _clearGradient(parent);
  4211. node.setAttribute("style", "");
  4212. }
  4213. node.setAttribute("fill", style.fillStyle ? _convertStyle(style.fillStyle, true) : "none");
  4214. node.setAttribute("stroke", style.strokeStyle ? _convertStyle(style.strokeStyle, true) : "none");
  4215. if (style.lineWidth) {
  4216. node.setAttribute("stroke-width", style.lineWidth);
  4217. }
  4218. // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
  4219. // the syntax in VML but is actually kind of nasty: values are given in the pixel
  4220. // coordinate space, whereas in VML they are multiples of the width of the stroked
  4221. // line, which makes a lot more sense. for that reason, jsPlumb is supporting both
  4222. // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
  4223. // VML, which will be the preferred method. the code below this converts a dashstyle
  4224. // attribute given in terms of stroke width into a pixel representation, by using the
  4225. // stroke's lineWidth.
  4226. if(style["stroke-dasharray"]) {
  4227. node.setAttribute("stroke-dasharray", style["stroke-dasharray"]);
  4228. }
  4229. if (style["dashstyle"] && style["lineWidth"]) {
  4230. var sep = style["dashstyle"].indexOf(",") == -1 ? " " : ",",
  4231. parts = style["dashstyle"].split(sep),
  4232. styleToUse = "";
  4233. parts.forEach(function(p) {
  4234. styleToUse += (Math.floor(p * style.lineWidth) + sep);
  4235. });
  4236. node.setAttribute("stroke-dasharray", styleToUse);
  4237. }
  4238. // extra attributes such as join type, dash offset.
  4239. for (var i in svgAttributeMap) {
  4240. if (style[i]) {
  4241. node.setAttribute(svgAttributeMap[i], style[i]);
  4242. }
  4243. }
  4244. },
  4245. _decodeFont = function(f) {
  4246. var r = /([0-9].)(p[xt])\s(.*)/;
  4247. var bits = f.match(r);
  4248. return {size:bits[1] + bits[2], font:bits[3]};
  4249. };
  4250. /*
  4251. * Base class for SVG components.
  4252. */
  4253. var SvgComponent = function(cssClass, originalArgs, pointerEventsSpec) {
  4254. var self = this;
  4255. pointerEventsSpec = pointerEventsSpec || "all";
  4256. jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
  4257. self.canvas = null, self.path = null, self.svg = null;
  4258. this.setHover = function() { };
  4259. self.canvas = document.createElement("div");
  4260. self.canvas.style["position"] = "absolute";
  4261. jsPlumb.sizeCanvas(self.canvas,0,0,1,1);
  4262. var clazz = cssClass + " " + (originalArgs[0].cssClass || "");
  4263. self.svg = _node("svg", {
  4264. "style":"",
  4265. "width":0,
  4266. "height":0,
  4267. "pointer-events":pointerEventsSpec,
  4268. "class": clazz
  4269. });
  4270. jsPlumb.appendElement(self.canvas, originalArgs[0]["parent"]);
  4271. self.canvas.appendChild(self.svg);
  4272. // TODO this displayElement stuff is common between all components, across all
  4273. // renderers. would be best moved to jsPlumbUIComponent.
  4274. var displayElements = [ self.canvas ];
  4275. this.getDisplayElements = function() {
  4276. return displayElements;
  4277. };
  4278. this.appendDisplayElement = function(el) {
  4279. displayElements.push(el);
  4280. };
  4281. this.paint = function(d, style, anchor) {
  4282. if (style != null) {
  4283. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  4284. _attr(self.svg, {
  4285. "style":_pos([0,0,d[2], d[3]]),
  4286. "width": d[2],
  4287. "height": d[3]
  4288. });
  4289. self._paint.apply(this, arguments);
  4290. }
  4291. };
  4292. };
  4293. /*
  4294. * Base class for SVG connectors.
  4295. */
  4296. var SvgConnector = function(params) {
  4297. var self = this;
  4298. SvgComponent.apply(this, [ params["_jsPlumb"].connectorClass, arguments, "none" ]);
  4299. this._paint = function(d, style) {
  4300. var p = self.getPath(d), a = { "d":p }, outlineStyle = null;
  4301. a["pointer-events"] = "all";
  4302. // outline style. actually means drawing an svg object underneath the main one.
  4303. if (style.outlineColor) {
  4304. var outlineWidth = style.outlineWidth || 1,
  4305. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  4306. outlineStyle = {
  4307. strokeStyle:_convertStyle(style.outlineColor),
  4308. lineWidth:outlineStrokeWidth
  4309. };
  4310. if (self.bgPath == null) {
  4311. self.bgPath = _node("path", a);
  4312. self.svg.appendChild(self.bgPath);
  4313. self.attachListeners(self.bgPath, self);
  4314. }
  4315. else {
  4316. _attr(self.bgPath, a);
  4317. }
  4318. _applyStyles(self.svg, self.bgPath, outlineStyle, d);
  4319. }
  4320. if (self.path == null) {
  4321. self.path = _node("path", a);
  4322. self.svg.appendChild(self.path);
  4323. self.attachListeners(self.path, self);
  4324. }
  4325. else {
  4326. _attr(self.path, a);
  4327. }
  4328. _applyStyles(self.svg, self.path, style, d);
  4329. };
  4330. };
  4331. /*
  4332. * SVG Bezier Connector
  4333. */
  4334. jsPlumb.Connectors.svg.Bezier = function(params) {
  4335. jsPlumb.Connectors.Bezier.apply(this, arguments);
  4336. SvgConnector.apply(this, arguments);
  4337. this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " C " + d[8] + " " + d[9] + " " + d[10] + " " + d[11] + " " + d[6] + " " + d[7]; };
  4338. };
  4339. /*
  4340. * SVG straight line Connector
  4341. */
  4342. jsPlumb.Connectors.svg.Straight = function(params) {
  4343. jsPlumb.Connectors.Straight.apply(this, arguments);
  4344. SvgConnector.apply(this, arguments);
  4345. this.getPath = function(d) { return "M " + d[4] + " " + d[5] + " L " + d[6] + " " + d[7]; };
  4346. };
  4347. jsPlumb.Connectors.svg.Flowchart = function() {
  4348. var self = this;
  4349. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  4350. SvgConnector.apply(this, arguments);
  4351. this.getPath = function(dimensions) {
  4352. var p = "M " + dimensions[4] + "," + dimensions[5];
  4353. // loop through extra points
  4354. for (var i = 0; i < dimensions[8]; i++) {
  4355. p = p + " L " + dimensions[9 + (i*2)] + " " + dimensions[10 + (i*2)];
  4356. }
  4357. // finally draw a line to the end
  4358. p = p + " " + dimensions[6] + "," + dimensions[7];
  4359. return p;
  4360. };
  4361. };
  4362. /*
  4363. * Base class for SVG endpoints.
  4364. */
  4365. var SvgEndpoint = function(params) {
  4366. var self = this;
  4367. SvgComponent.apply(this, [ params["_jsPlumb"].endpointClass, arguments, "all" ]);
  4368. this._paint = function(d, style) {
  4369. var s = jsPlumb.extend({}, style);
  4370. if (s.outlineColor) {
  4371. s.strokeWidth = s.outlineWidth;
  4372. s.strokeStyle = _convertStyle(s.outlineColor, true);
  4373. }
  4374. if (self.node == null) {
  4375. self.node = self.makeNode(d, s);
  4376. self.svg.appendChild(self.node);
  4377. self.attachListeners(self.node, self);
  4378. }
  4379. _applyStyles(self.svg, self.node, s, d);
  4380. _pos(self.node, d);
  4381. };
  4382. };
  4383. /*
  4384. * SVG Dot Endpoint
  4385. */
  4386. jsPlumb.Endpoints.svg.Dot = function() {
  4387. jsPlumb.Endpoints.Dot.apply(this, arguments);
  4388. SvgEndpoint.apply(this, arguments);
  4389. this.makeNode = function(d, style) {
  4390. return _node("circle", {
  4391. "cx" : d[2] / 2,
  4392. "cy" : d[3] / 2,
  4393. "r" : d[2] / 2
  4394. });
  4395. };
  4396. };
  4397. /*
  4398. * SVG Rectangle Endpoint
  4399. */
  4400. jsPlumb.Endpoints.svg.Rectangle = function() {
  4401. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  4402. SvgEndpoint.apply(this, arguments);
  4403. this.makeNode = function(d, style) {
  4404. return _node("rect", {
  4405. "width":d[2],
  4406. "height":d[3]
  4407. });
  4408. };
  4409. };
  4410. /*
  4411. * SVG Image Endpoint is the default image endpoint.
  4412. */
  4413. jsPlumb.Endpoints.svg.Image = jsPlumb.Endpoints.Image;
  4414. /*
  4415. * Blank endpoint in svg renderer is the default Blank endpoint.
  4416. */
  4417. jsPlumb.Endpoints.svg.Blank = jsPlumb.Endpoints.Blank;
  4418. /*
  4419. * Label endpoint in svg renderer is the default Label endpoint.
  4420. */
  4421. jsPlumb.Overlays.svg.Label = jsPlumb.Overlays.Label;
  4422. var AbstractSvgArrowOverlay = function(superclass, originalArgs) {
  4423. superclass.apply(this, originalArgs);
  4424. jsPlumb.jsPlumbUIComponent.apply(this, originalArgs);
  4425. var self = this, path =null;
  4426. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  4427. if (path == null) {
  4428. path = _node("path");
  4429. connector.svg.appendChild(path);
  4430. self.attachListeners(path, connector);
  4431. self.attachListeners(path, self);
  4432. }
  4433. _attr(path, {
  4434. "d" : makePath(d),
  4435. stroke : strokeStyle ? strokeStyle : null,
  4436. fill : fillStyle ? fillStyle : null
  4437. });
  4438. };
  4439. var makePath = function(d) {
  4440. return "M" + d.hxy.x + "," + d.hxy.y +
  4441. " L" + d.tail[0].x + "," + d.tail[0].y +
  4442. " L" + d.cxy.x + "," + d.cxy.y +
  4443. " L" + d.tail[1].x + "," + d.tail[1].y +
  4444. " L" + d.hxy.x + "," + d.hxy.y;
  4445. };
  4446. };
  4447. jsPlumb.Overlays.svg.Arrow = function() {
  4448. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  4449. };
  4450. jsPlumb.Overlays.svg.PlainArrow = function() {
  4451. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  4452. };
  4453. jsPlumb.Overlays.svg.Diamond = function() {
  4454. AbstractSvgArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  4455. };
  4456. })();;(function() {
  4457. // ********************************* CANVAS RENDERERS FOR CONNECTORS AND ENDPOINTS *******************************************************************
  4458. // TODO refactor to renderer common script. put a ref to jsPlumb.sizeCanvas in there too.
  4459. var _connectionBeingDragged = null,
  4460. _getAttribute = function(el, attName) { return jsPlumb.CurrentLibrary.getAttribute(_getElementObject(el), attName); },
  4461. _setAttribute = function(el, attName, attValue) { jsPlumb.CurrentLibrary.setAttribute(_getElementObject(el), attName, attValue); },
  4462. _addClass = function(el, clazz) { jsPlumb.CurrentLibrary.addClass(_getElementObject(el), clazz); },
  4463. _hasClass = function(el, clazz) { return jsPlumb.CurrentLibrary.hasClass(_getElementObject(el), clazz); },
  4464. _removeClass = function(el, clazz) { jsPlumb.CurrentLibrary.removeClass(_getElementObject(el), clazz); },
  4465. _getElementObject = function(el) { return jsPlumb.CurrentLibrary.getElementObject(el); },
  4466. _getOffset = function(el) { return jsPlumb.CurrentLibrary.getOffset(_getElementObject(el)); },
  4467. _getSize = function(el) { return jsPlumb.CurrentLibrary.getSize(_getElementObject(el)); },
  4468. _pageXY = function(el) { return jsPlumb.CurrentLibrary.getPageXY(el); },
  4469. _clientXY = function(el) { return jsPlumb.CurrentLibrary.getClientXY(el); },
  4470. _setOffset = function(el, o) { jsPlumb.CurrentLibrary.setOffset(el, o); };
  4471. /*
  4472. * Class:CanvasMouseAdapter
  4473. * Provides support for mouse events on canvases.
  4474. */
  4475. var CanvasMouseAdapter = function() {
  4476. var self = this;
  4477. self.overlayPlacements = [];
  4478. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  4479. jsPlumb.EventGenerator.apply(this, arguments);
  4480. /**
  4481. * returns whether or not the given event is ojver a painted area of the canvas.
  4482. */
  4483. this._over = function(e) {
  4484. var o = _getOffset(_getElementObject(self.canvas)),
  4485. pageXY = _pageXY(e),
  4486. x = pageXY[0] - o.left, y = pageXY[1] - o.top;
  4487. if (x > 0 && y > 0 && x < self.canvas.width && y < self.canvas.height) {
  4488. // first check overlays
  4489. for ( var i = 0; i < self.overlayPlacements.length; i++) {
  4490. var p = self.overlayPlacements[i];
  4491. if (p && (p[0] <= x && p[1] >= x && p[2] <= y && p[3] >= y))
  4492. return true;
  4493. }
  4494. // then the canvas
  4495. var d = self.canvas.getContext("2d").getImageData(parseInt(x), parseInt(y), 1, 1);
  4496. return d.data[0] != 0 || d.data[1] != 0 || d.data[2] != 0 || d.data[3] != 0;
  4497. }
  4498. return false;
  4499. };
  4500. var _mouseover = false;
  4501. var _mouseDown = false, _posWhenMouseDown = null, _mouseWasDown = false;
  4502. var _nullSafeHasClass = function(el, clazz) {
  4503. return el != null && _hasClass(el, clazz);
  4504. };
  4505. this.mousemove = function(e) {
  4506. var pageXY = _pageXY(e), clientXY = _clientXY(e),
  4507. ee = document.elementFromPoint(clientXY[0], clientXY[1]),
  4508. eventSourceWasOverlay = _nullSafeHasClass(ee, "_jsPlumb_overlay");
  4509. var _continue = _connectionBeingDragged == null && (_nullSafeHasClass(ee, "_jsPlumb_endpoint") || _nullSafeHasClass(ee, "_jsPlumb_connector"));
  4510. if (!_mouseover && _continue && self._over(e)) {
  4511. _mouseover = true;
  4512. self.fire("mouseenter", self, e);
  4513. return true;
  4514. }
  4515. // TODO here there is a remote chance that the overlay the mouse moved onto
  4516. // is actually not an overlay for the current component. a more thorough check would
  4517. // be to ensure the overlay belonged to the current component.
  4518. else if (_mouseover && (!self._over(e) || !_continue) && !eventSourceWasOverlay) {
  4519. _mouseover = false;
  4520. self.fire("mouseexit", self, e);
  4521. }
  4522. self.fire("mousemove", self, e);
  4523. };
  4524. this.click = function(e) {
  4525. if (_mouseover && self._over(e) && !_mouseWasDown)
  4526. self.fire("click", self, e);
  4527. _mouseWasDown = false;
  4528. };
  4529. this.dblclick = function(e) {
  4530. if (_mouseover && self._over(e) && !_mouseWasDown)
  4531. self.fire("dblclick", self, e);
  4532. _mouseWasDown = false;
  4533. };
  4534. this.mousedown = function(e) {
  4535. if(self._over(e) && !_mouseDown) {
  4536. _mouseDown = true;
  4537. _posWhenMouseDown = _getOffset(_getElementObject(self.canvas));
  4538. self.fire("mousedown", self, e);
  4539. }
  4540. };
  4541. this.mouseup = function(e) {
  4542. //if (self == _connectionBeingDragged) _connectionBeingDragged = null;
  4543. _mouseDown = false;
  4544. self.fire("mouseup", self, e);
  4545. };
  4546. };
  4547. var _newCanvas = function(params) {
  4548. var canvas = document.createElement("canvas");
  4549. jsPlumb.appendElement(canvas, params.parent);
  4550. canvas.style.position = "absolute";
  4551. if (params["class"]) canvas.className = params["class"];
  4552. // set an id. if no id on the element and if uuid was supplied it
  4553. // will be used, otherwise we'll create one.
  4554. params["_jsPlumb"].getId(canvas, params.uuid);
  4555. return canvas;
  4556. };
  4557. /**
  4558. * Class:CanvasConnector
  4559. * Superclass for Canvas Connector renderers.
  4560. */
  4561. var CanvasConnector = jsPlumb.CanvasConnector = function(params) {
  4562. CanvasMouseAdapter.apply(this, arguments);
  4563. var _paintOneStyle = function(dim, aStyle) {
  4564. self.ctx.save();
  4565. jsPlumb.extend(self.ctx, aStyle);
  4566. if (aStyle.gradient) {
  4567. var g = self.createGradient(dim, self.ctx);
  4568. for ( var i = 0; i < aStyle.gradient.stops.length; i++)
  4569. g.addColorStop(aStyle.gradient.stops[i][0], aStyle.gradient.stops[i][1]);
  4570. self.ctx.strokeStyle = g;
  4571. }
  4572. self._paint(dim);
  4573. self.ctx.restore();
  4574. };
  4575. var self = this,
  4576. clazz = self._jsPlumb.connectorClass + " " + (params.cssClass || "");
  4577. self.canvas = _newCanvas({
  4578. "class":clazz,
  4579. _jsPlumb:self._jsPlumb,
  4580. parent:params.parent
  4581. });
  4582. self.ctx = self.canvas.getContext("2d");
  4583. var displayElements = [ self.canvas ];
  4584. this.getDisplayElements = function() {
  4585. return displayElements;
  4586. };
  4587. this.appendDisplayElement = function(el) {
  4588. displayElements.push(el);
  4589. };
  4590. self.paint = function(dim, style) {
  4591. if (style != null) {
  4592. jsPlumb.sizeCanvas(self.canvas, dim[0], dim[1], dim[2], dim[3]);
  4593. if (style.outlineColor != null) {
  4594. var outlineWidth = style.outlineWidth || 1,
  4595. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  4596. var outlineStyle = {
  4597. strokeStyle:style.outlineColor,
  4598. lineWidth:outlineStrokeWidth
  4599. };
  4600. _paintOneStyle(dim, outlineStyle);
  4601. }
  4602. _paintOneStyle(dim, style);
  4603. }
  4604. };
  4605. };
  4606. /**
  4607. * Class:CanvasEndpoint
  4608. * Superclass for Canvas Endpoint renderers.
  4609. */
  4610. var CanvasEndpoint = function(params) {
  4611. var self = this;
  4612. CanvasMouseAdapter.apply(this, arguments);
  4613. var clazz = self._jsPlumb.endpointClass + " " + (params.cssClass || "");
  4614. self.canvas = _newCanvas({
  4615. "class":clazz,
  4616. _jsPlumb:self._jsPlumb,
  4617. parent:params.parent
  4618. });
  4619. self.ctx = self.canvas.getContext("2d");
  4620. this.paint = function(d, style, anchor) {
  4621. jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]);
  4622. if (style.outlineColor != null) {
  4623. var outlineWidth = style.outlineWidth || 1,
  4624. outlineStrokeWidth = style.lineWidth + (2 * outlineWidth);
  4625. var outlineStyle = {
  4626. strokeStyle:style.outlineColor,
  4627. lineWidth:outlineStrokeWidth
  4628. };
  4629. // _paintOneStyle(d, outlineStyle);
  4630. }
  4631. self._paint.apply(this, arguments);
  4632. };
  4633. };
  4634. jsPlumb.Endpoints.canvas.Dot = function(params) {
  4635. var self = this;
  4636. jsPlumb.Endpoints.Dot.apply(this, arguments);
  4637. CanvasEndpoint.apply(this, arguments);
  4638. var parseValue = function(value) {
  4639. try {
  4640. return parseInt(value);
  4641. }
  4642. catch(e) {
  4643. if (value.substring(value.length - 1) == '%')
  4644. return parseInt(value.substring(0, value - 1));
  4645. }
  4646. };
  4647. var calculateAdjustments = function(gradient) {
  4648. var offsetAdjustment = self.defaultOffset, innerRadius = self.defaultInnerRadius;
  4649. gradient.offset && (offsetAdjustment = parseValue(gradient.offset));
  4650. gradient.innerRadius && (innerRadius = parseValue(gradient.innerRadius));
  4651. return [offsetAdjustment, innerRadius];
  4652. };
  4653. this._paint = function(d, style, anchor) {
  4654. if (style != null) {
  4655. var ctx = self.canvas.getContext('2d'), orientation = anchor.getOrientation();
  4656. jsPlumb.extend(ctx, style);
  4657. if (style.gradient) {
  4658. var adjustments = calculateAdjustments(style.gradient),
  4659. yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0],
  4660. xAdjust = orientation[0] == 1 ? adjustments[0] * -1: adjustments[0],
  4661. g = ctx.createRadialGradient(d[4], d[4], d[4], d[4] + xAdjust, d[4] + yAdjust, adjustments[1]);
  4662. for (var i = 0; i < style.gradient.stops.length; i++)
  4663. g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
  4664. ctx.fillStyle = g;
  4665. }
  4666. ctx.beginPath();
  4667. ctx.arc(d[4], d[4], d[4], 0, Math.PI*2, true);
  4668. ctx.closePath();
  4669. if (style.fillStyle || style.gradient) ctx.fill();
  4670. if (style.strokeStyle) ctx.stroke();
  4671. }
  4672. };
  4673. };
  4674. jsPlumb.Endpoints.canvas.Rectangle = function(params) {
  4675. var self = this;
  4676. jsPlumb.Endpoints.Rectangle.apply(this, arguments);
  4677. CanvasEndpoint.apply(this, arguments);
  4678. this._paint = function(d, style, anchor) {
  4679. var ctx = self.canvas.getContext("2d"), orientation = anchor.getOrientation();
  4680. jsPlumb.extend(ctx, style);
  4681. /* canvas gradient */
  4682. if (style.gradient) {
  4683. // first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
  4684. var y1 = orientation[1] == 1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
  4685. var y2 = orientation[1] == -1 ? d[3] : orientation[1] == 0 ? d[3] / 2 : 0;
  4686. var x1 = orientation[0] == 1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
  4687. var x2 = orientation[0] == -1 ? d[2] : orientation[0] == 0 ? d[2] / 2 : 0;
  4688. var g = ctx.createLinearGradient(x1,y1,x2,y2);
  4689. for (var i = 0; i < style.gradient.stops.length; i++)
  4690. g.addColorStop(style.gradient.stops[i][0], style.gradient.stops[i][1]);
  4691. ctx.fillStyle = g;
  4692. }
  4693. ctx.beginPath();
  4694. ctx.rect(0, 0, d[2], d[3]);
  4695. ctx.closePath();
  4696. if (style.fillStyle || style.gradient) ctx.fill();
  4697. if (style.strokeStyle) ctx.stroke();
  4698. };
  4699. };
  4700. jsPlumb.Endpoints.canvas.Triangle = function(params) {
  4701. var self = this;
  4702. jsPlumb.Endpoints.Triangle.apply(this, arguments);
  4703. CanvasEndpoint.apply(this, arguments);
  4704. this._paint = function(d, style, anchor)
  4705. {
  4706. var width = d[2], height = d[3], x = d[0], y = d[1];
  4707. var ctx = self.canvas.getContext('2d');
  4708. var offsetX = 0, offsetY = 0, angle = 0;
  4709. if( orientation[0] == 1 )
  4710. {
  4711. offsetX = width;
  4712. offsetY = height;
  4713. angle = 180;
  4714. }
  4715. if( orientation[1] == -1 )
  4716. {
  4717. offsetX = width;
  4718. angle = 90;
  4719. }
  4720. if( orientation[1] == 1 )
  4721. {
  4722. offsetY = height;
  4723. angle = -90;
  4724. }
  4725. ctx.fillStyle = style.fillStyle;
  4726. ctx.translate(offsetX, offsetY);
  4727. ctx.rotate(angle * Math.PI/180);
  4728. ctx.beginPath();
  4729. ctx.moveTo(0, 0);
  4730. ctx.lineTo(width/2, height/2);
  4731. ctx.lineTo(0, height);
  4732. ctx.closePath();
  4733. if (style.fillStyle || style.gradient) ctx.fill();
  4734. if (style.strokeStyle) ctx.stroke();
  4735. };
  4736. };
  4737. /*
  4738. * Canvas Image Endpoint: uses the default version, which creates an <img> tag.
  4739. */
  4740. jsPlumb.Endpoints.canvas.Image = jsPlumb.Endpoints.Image;
  4741. /*
  4742. * Blank endpoint in all renderers is just the default Blank endpoint.
  4743. */
  4744. jsPlumb.Endpoints.canvas.Blank = jsPlumb.Endpoints.Blank;
  4745. /*
  4746. * Canvas Bezier Connector. Draws a Bezier curve onto a Canvas element.
  4747. */
  4748. jsPlumb.Connectors.canvas.Bezier = function() {
  4749. var self = this;
  4750. jsPlumb.Connectors.Bezier.apply(this, arguments);
  4751. CanvasConnector.apply(this, arguments);
  4752. this._paint = function(dimensions) {
  4753. self.ctx.beginPath();
  4754. self.ctx.moveTo(dimensions[4], dimensions[5]);
  4755. self.ctx.bezierCurveTo(dimensions[8], dimensions[9], dimensions[10], dimensions[11], dimensions[6], dimensions[7]);
  4756. self.ctx.stroke();
  4757. };
  4758. // TODO i doubt this handles the case that source and target are swapped.
  4759. this.createGradient = function(dim, ctx, swap) {
  4760. return /*(swap) ? self.ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : */self.ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
  4761. };
  4762. };
  4763. /*
  4764. * Canvas straight line Connector. Draws a straight line onto a Canvas element.
  4765. */
  4766. jsPlumb.Connectors.canvas.Straight = function() {
  4767. var self = this;
  4768. jsPlumb.Connectors.Straight.apply(this, arguments);
  4769. CanvasConnector.apply(this, arguments);
  4770. this._paint = function(dimensions) {
  4771. self.ctx.beginPath();
  4772. self.ctx.moveTo(dimensions[4], dimensions[5]);
  4773. self.ctx.lineTo(dimensions[6], dimensions[7]);
  4774. self.ctx.stroke();
  4775. };
  4776. // TODO this does not handle the case that src and target are swapped.
  4777. this.createGradient = function(dim, ctx) {
  4778. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  4779. };
  4780. };
  4781. jsPlumb.Connectors.canvas.Flowchart = function() {
  4782. var self = this;
  4783. jsPlumb.Connectors.Flowchart.apply(this, arguments);
  4784. CanvasConnector.apply(this, arguments);
  4785. this._paint = function(dimensions) {
  4786. self.ctx.beginPath();
  4787. self.ctx.moveTo(dimensions[4], dimensions[5]);
  4788. // loop through extra points
  4789. for (var i = 0; i < dimensions[8]; i++) {
  4790. self.ctx.lineTo(dimensions[9 + (i*2)], dimensions[10 + (i*2)]);
  4791. }
  4792. // finally draw a line to the end
  4793. self.ctx.lineTo(dimensions[6], dimensions[7]);
  4794. self.ctx.stroke();
  4795. };
  4796. this.createGradient = function(dim, ctx) {
  4797. return ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]);
  4798. };
  4799. };
  4800. // ********************************* END OF CANVAS RENDERERS *******************************************************************
  4801. jsPlumb.Overlays.canvas.Label = jsPlumb.Overlays.Label;
  4802. /**
  4803. * a placeholder right now, really just exists to mirror the fact that there are SVG and VML versions of this.
  4804. */
  4805. var CanvasOverlay = function() {
  4806. jsPlumb.jsPlumbUIComponent.apply(this, arguments);
  4807. };
  4808. var AbstractCanvasArrowOverlay = function(superclass, originalArgs) {
  4809. superclass.apply(this, originalArgs);
  4810. CanvasOverlay.apply(this, arguments);
  4811. this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle) {
  4812. var ctx = connector.ctx;
  4813. ctx.lineWidth = lineWidth;
  4814. ctx.beginPath();
  4815. ctx.moveTo(d.hxy.x, d.hxy.y);
  4816. ctx.lineTo(d.tail[0].x, d.tail[0].y);
  4817. ctx.lineTo(d.cxy.x, d.cxy.y);
  4818. ctx.lineTo(d.tail[1].x, d.tail[1].y);
  4819. ctx.lineTo(d.hxy.x, d.hxy.y);
  4820. ctx.closePath();
  4821. if (strokeStyle) {
  4822. ctx.strokeStyle = strokeStyle;
  4823. ctx.stroke();
  4824. }
  4825. if (fillStyle) {
  4826. ctx.fillStyle = fillStyle;
  4827. ctx.fill();
  4828. }
  4829. };
  4830. };
  4831. jsPlumb.Overlays.canvas.Arrow = function() {
  4832. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]);
  4833. };
  4834. jsPlumb.Overlays.canvas.PlainArrow = function() {
  4835. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]);
  4836. };
  4837. jsPlumb.Overlays.canvas.Diamond = function() {
  4838. AbstractCanvasArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]);
  4839. };
  4840. })();/*
  4841. * jsPlumb
  4842. *
  4843. * jquery.jsPlumb 1.3.0-RC1
  4844. *
  4845. * jQuery specific functionality for jsPlumb.
  4846. *
  4847. * http://jsplumb.org
  4848. * http://code.google.com/p/jsplumb
  4849. *
  4850. * Triple licensed under MIT, GPL2 and Beer licenses.
  4851. *
  4852. */
  4853. /*
  4854. * the library specific functions, such as find offset, get id, get attribute, extend etc.
  4855. * the full list is:
  4856. *
  4857. * addClass adds a class to the given element
  4858. * animate calls the underlying library's animate functionality
  4859. * appendElement appends a child element to a parent element.
  4860. * bind binds some event to an element
  4861. * dragEvents a dictionary of event names
  4862. * extend extend some js object with another. probably not overly necessary; jsPlumb could just do this internally.
  4863. * getAttribute gets some attribute from an element
  4864. * getDragObject gets the object that is being dragged, by extracting it from the arguments passed to a drag callback
  4865. * getDragScope gets the drag scope for a given element.
  4866. * getElementObject turns an id or dom element into an element object of the underlying library's type.
  4867. * getOffset gets an element's offset
  4868. * getPageXY gets the page event's xy location.
  4869. * getParent gets the parent of some element.
  4870. * getScrollLeft gets an element's scroll left. TODO: is this actually used? will it be?
  4871. * getScrollTop gets an element's scroll top. TODO: is this actually used? will it be?
  4872. * getSize gets an element's size.
  4873. * getUIPosition gets the position of some element that is currently being dragged, by extracting it from the arguments passed to a drag callback.
  4874. * hasClass returns whether or not the given element has the given class.
  4875. * initDraggable initializes an element to be draggable
  4876. * initDroppable initializes an element to be droppable
  4877. * isDragSupported returns whether or not drag is supported for some element.
  4878. * isDropSupported returns whether or not drop is supported for some element.
  4879. * removeClass removes a class from a given element.
  4880. * removeElement removes some element completely from the DOM.
  4881. * setAttribute sets an attribute on some element.
  4882. * setDraggable sets whether or not some element should be draggable.
  4883. * setDragScope sets the drag scope for a given element.
  4884. * setOffset sets the offset of some element.
  4885. */
  4886. (function($) {
  4887. //var getBoundingClientRectSupported = "getBoundingClientRect" in document.documentElement;
  4888. jsPlumb.CurrentLibrary = {
  4889. /**
  4890. * adds the given class to the element object.
  4891. */
  4892. addClass : function(el, clazz) {
  4893. el.addClass(clazz);
  4894. },
  4895. /**
  4896. * animates the given element.
  4897. */
  4898. animate : function(el, properties, options) {
  4899. el.animate(properties, options);
  4900. },
  4901. /**
  4902. * appends the given child to the given parent.
  4903. */
  4904. appendElement : function(child, parent) {
  4905. jsPlumb.CurrentLibrary.getElementObject(parent).append(child);
  4906. },
  4907. /**
  4908. * event binding wrapper. it just so happens that jQuery uses 'bind' also. yui3, for example,
  4909. * uses 'on'.
  4910. */
  4911. bind : function(el, event, callback) {
  4912. el = jsPlumb.CurrentLibrary.getElementObject(el);
  4913. el.bind(event, callback);
  4914. },
  4915. /**
  4916. * mapping of drag events for jQuery
  4917. */
  4918. dragEvents : {
  4919. 'start':'start', 'stop':'stop', 'drag':'drag', 'step':'step',
  4920. 'over':'over', 'out':'out', 'drop':'drop', 'complete':'complete'
  4921. },
  4922. /**
  4923. * wrapper around the library's 'extend' functionality (which it hopefully has.
  4924. * otherwise you'll have to do it yourself). perhaps jsPlumb could do this for you
  4925. * instead. it's not like its hard.
  4926. */
  4927. extend : function(o1, o2) {
  4928. return $.extend(o1, o2);
  4929. },
  4930. /**
  4931. * gets the named attribute from the given element object.
  4932. */
  4933. getAttribute : function(el, attName) {
  4934. return el.attr(attName);
  4935. },
  4936. getClientXY : function(eventObject) {
  4937. return [eventObject.clientX, eventObject.clientY];
  4938. },
  4939. getDocumentElement : function() { return document; },
  4940. /**
  4941. * takes the args passed to an event function and returns you an object representing that which is being dragged.
  4942. */
  4943. getDragObject : function(eventArgs) {
  4944. return eventArgs[1].draggable;
  4945. },
  4946. getDragScope : function(el) {
  4947. return el.draggable("option", "scope");
  4948. },
  4949. /**
  4950. * gets an "element object" from the given input. this means an object that is used by the
  4951. * underlying library on which jsPlumb is running. 'el' may already be one of these objects,
  4952. * in which case it is returned as-is. otherwise, 'el' is a String, the library's lookup
  4953. * function is used to find the element, using the given String as the element's id.
  4954. *
  4955. */
  4956. getElementObject : function(el) {
  4957. return typeof(el)=='string' ? $("#" + el) : $(el);
  4958. },
  4959. /**
  4960. * gets the offset for the element object. this should return a js object like this:
  4961. *
  4962. * { left:xxx, top: xxx }
  4963. */
  4964. getOffset : function(el) {
  4965. return el.offset();
  4966. },
  4967. getPageXY : function(eventObject) {
  4968. return [eventObject.pageX, eventObject.pageY];
  4969. },
  4970. getParent : function(el) {
  4971. return jsPlumb.CurrentLibrary.getElementObject(el).parent();
  4972. },
  4973. getScrollLeft : function(el) {
  4974. return el.scrollLeft();
  4975. },
  4976. getScrollTop : function(el) {
  4977. return el.scrollTop();
  4978. },
  4979. /**
  4980. * gets the size for the element object, in an array : [ width, height ].
  4981. */
  4982. getSize : function(el) {
  4983. return [el.outerWidth(), el.outerHeight()];
  4984. },
  4985. /**
  4986. * takes the args passed to an event function and returns you an object that gives the
  4987. * position of the object being moved, as a js object with the same params as the result of
  4988. * getOffset, ie: { left: xxx, top: xxx }.
  4989. *
  4990. * different libraries have different signatures for their event callbacks.
  4991. * see getDragObject as well
  4992. */
  4993. getUIPosition : function(eventArgs) {
  4994. // this code is a workaround for the case that the element being dragged has a margin set on it. jquery UI passes
  4995. // in the wrong offset if the element has a margin (it doesn't take the margin into account). the getBoundingClientRect
  4996. // method, which is in pretty much all browsers now, reports the right numbers. but it introduces a noticeable lag, which
  4997. // i don't like.
  4998. /*if ( getBoundingClientRectSupported ) {
  4999. var r = eventArgs[1].helper[0].getBoundingClientRect();
  5000. return { left : r.left, top: r.top };
  5001. } else {*/
  5002. var ui = eventArgs[1], _offset = ui.offset;
  5003. return _offset || ui.absolutePosition;
  5004. //}
  5005. },
  5006. hasClass : function(el, clazz) {
  5007. return el.hasClass(clazz);
  5008. },
  5009. /**
  5010. * initialises the given element to be draggable.
  5011. */
  5012. initDraggable : function(el, options) {
  5013. // remove helper directive if present.
  5014. options.helper = null;
  5015. options['scope'] = options['scope'] || jsPlumb.Defaults.Scope;
  5016. el.draggable(options);
  5017. },
  5018. /**
  5019. * initialises the given element to be droppable.
  5020. */
  5021. initDroppable : function(el, options) {
  5022. options['scope'] = options['scope'] || jsPlumb.Defaults.Scope;
  5023. el.droppable(options);
  5024. },
  5025. isAlreadyDraggable : function(el) {
  5026. el = jsPlumb.CurrentLibrary.getElementObject(el);
  5027. return el.hasClass("ui-draggable");
  5028. },
  5029. /**
  5030. * returns whether or not drag is supported (by the library, not whether or not it is disabled) for the given element.
  5031. */
  5032. isDragSupported : function(el, options) {
  5033. return el.draggable;
  5034. },
  5035. /**
  5036. * returns whether or not drop is supported (by the library, not whether or not it is disabled) for the given element.
  5037. */
  5038. isDropSupported : function(el, options) {
  5039. return el.droppable;
  5040. },
  5041. /**
  5042. * removes the given class from the element object.
  5043. */
  5044. removeClass : function(el, clazz) {
  5045. el.removeClass(clazz);
  5046. },
  5047. removeElement : function(element, parent) {
  5048. jsPlumb.CurrentLibrary.getElementObject(element).remove();
  5049. },
  5050. /**
  5051. * sets the named attribute on the given element object.
  5052. */
  5053. setAttribute : function(el, attName, attValue) {
  5054. el.attr(attName, attValue);
  5055. },
  5056. /**
  5057. * sets the draggable state for the given element
  5058. */
  5059. setDraggable : function(el, draggable) {
  5060. el.draggable("option", "disabled", !draggable);
  5061. },
  5062. /**
  5063. * sets the drag scope. probably time for a setDragOption method (roll this and the one above together)
  5064. * @param el
  5065. * @param scope
  5066. */
  5067. setDragScope : function(el, scope) {
  5068. el.draggable("option", "scope", scope);
  5069. },
  5070. setOffset : function(el, o) {
  5071. jsPlumb.CurrentLibrary.getElementObject(el).offset(o);
  5072. }
  5073. };
  5074. $(document).ready(jsPlumb.init);
  5075. })(jQuery);
  5076. (function(){if(typeof Math.sgn=="undefined")Math.sgn=function(a){return a==0?0:a>0?1:-1};var p={subtract:function(a,b){return{x:a.x-b.x,y:a.y-b.y}},dotProduct:function(a,b){return a.x*b.x+a.y*b.y},square:function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},scale:function(a,b){return{x:a.x*b,y:a.y*b}}},y=Math.pow(2,-65),u=function(a,b){for(var g=[],d=b.length-1,h=2*d-1,f=[],c=[],l=[],k=[],i=[[1,0.6,0.3,0.1],[0.4,0.6,0.6,0.4],[0.1,0.3,0.6,1]],e=0;e<=d;e++)f[e]=p.subtract(b[e],a);for(e=0;e<=d-1;e++){c[e]=
  5077. p.subtract(b[e+1],b[e]);c[e]=p.scale(c[e],3)}for(e=0;e<=d-1;e++)for(var m=0;m<=d;m++){l[e]||(l[e]=[]);l[e][m]=p.dotProduct(c[e],f[m])}for(e=0;e<=h;e++){k[e]||(k[e]=[]);k[e].y=0;k[e].x=parseFloat(e)/h}h=d-1;for(f=0;f<=d+h;f++){c=Math.min(f,d);for(e=Math.max(0,f-h);e<=c;e++){j=f-e;k[e+j].y+=l[j][e]*i[j][e]}}d=b.length-1;k=s(k,2*d-1,g,0);h=p.subtract(a,b[0]);l=p.square(h);for(e=i=0;e<k;e++){h=p.subtract(a,t(b,d,g[e],null,null));h=p.square(h);if(h<l){l=h;i=g[e]}}h=p.subtract(a,b[d]);h=p.square(h);if(h<
  5078. l){l=h;i=1}return{location:i,distance:l}},s=function(a,b,g,d){var h=[],f=[],c=[],l=[],k=0,i,e;e=Math.sgn(a[0].y);for(var m=1;m<=b;m++){i=Math.sgn(a[m].y);i!=e&&k++;e=i}switch(k){case 0:return 0;case 1:if(d>=64){g[0]=(a[0].x+a[b].x)/2;return 1}var n,o,q;k=a[0].y-a[b].y;i=a[b].x-a[0].x;e=a[0].x*a[b].y-a[b].x*a[0].y;m=max_distance_below=0;for(o=1;o<b;o++){q=k*a[o].x+i*a[o].y+e;if(q>m)m=q;else if(q<max_distance_below)max_distance_below=q}n=k;o=i;q=e-m;n=0*o-n*1;n=1/n;m=(1*q-o*0)*n;n=k;o=i;q=e-max_distance_below;
  5079. n=0*o-n*1;n=1/n;k=(1*q-o*0)*n;if(Math.max(m,k)-Math.min(m,k)<y?1:0){c=a[b].x-a[0].x;l=a[b].y-a[0].y;g[0]=0+1*(c*(a[0].y-0)-l*(a[0].x-0))*(1/(c*0-l*1));return 1}}t(a,b,0.5,h,f);a=s(h,b,c,d+1);b=s(f,b,l,d+1);for(d=0;d<a;d++)g[d]=c[d];for(d=0;d<b;d++)g[d+a]=l[d];return a+b},t=function(a,b,g,d,h){for(var f=[[]],c=0;c<=b;c++)f[0][c]=a[c];for(a=1;a<=b;a++)for(c=0;c<=b-a;c++){f[a]||(f[a]=[]);f[a][c]||(f[a][c]={});f[a][c].x=(1-g)*f[a-1][c].x+g*f[a-1][c+1].x;f[a][c].y=(1-g)*f[a-1][c].y+g*f[a-1][c+1].y}if(d!=
  5080. null)for(c=0;c<=b;c++)d[c]=f[c][0];if(h!=null)for(c=0;c<=b;c++)h[c]=f[b-c][c];return f[b][0]},v={},z=function(a){var b=v[a];if(!b){b=[];var g=function(i){return function(){return i}},d=function(){return function(i){return i}},h=function(){return function(i){return 1-i}},f=function(i){return function(e){for(var m=1,n=0;n<i.length;n++)m*=i[n](e);return m}};b.push(new function(){return function(i){return Math.pow(i,a)}});for(var c=1;c<a;c++){for(var l=[new g(a)],k=0;k<a-c;k++)l.push(new d);for(k=0;k<
  5081. c;k++)l.push(new h);b.push(new f(l))}b.push(new function(){return function(i){return Math.pow(1-i,a)}});v[a]=b}return b},r=function(a,b){for(var g=z(a.length-1),d=0,h=0,f=0;f<a.length;f++){d+=a[f].x*g[f](b);h+=a[f].y*g[f](b)}return{x:d,y:h}},w=function(a,b,g){var d=r(a,b),h=0;b=b;for(var f=g>0?1:-1,c=null;h<Math.abs(g);){b+=0.0050*f;c=r(a,b);h+=Math.sqrt(Math.pow(c.x-d.x,2)+Math.pow(c.y-d.y,2));d=c}return{point:c,location:b}},x=function(a,b){var g=r(a,b),d=r(a.slice(0,a.length-1),b);return Math.atan((d.y-
  5082. g.y)/(d.x-g.x))};window.jsBezier={distanceFromCurve:u,gradientAtPoint:x,nearestPointOnCurve:function(a,b){var g=u(a,b);return{point:t(b,b.length-1,g.location,null,null),location:g.location}},pointOnCurve:r,pointAlongCurveFrom:function(a,b,g){return w(a,b,g).point},perpendicularToCurveAt:function(a,b,g,d){d=d==null?0:d;b=w(a,b,d);a=x(a,b.location);d=Math.atan(-1/a);a=g/2*Math.sin(d);g=g/2*Math.cos(d);return[{x:b.point.x+g,y:b.point.y+a},{x:b.point.x-g,y:b.point.y-a}]}}})();