mootools.jsPlumb-1.3.2-all.js 224 KB

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