vis.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 4.16.1
  8. * @date 2016-04-18
  9. *
  10. * @license
  11. * Copyright (C) 2011-2016 Almende B.V, http://almende.com
  12. *
  13. * Vis.js is dual licensed under both
  14. *
  15. * * The Apache 2.0 License
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * and
  19. *
  20. * * The MIT License
  21. * http://opensource.org/licenses/MIT
  22. *
  23. * Vis.js may be distributed under either license.
  24. */
  25. "use strict";
  26. (function webpackUniversalModuleDefinition(root, factory) {
  27. if(typeof exports === 'object' && typeof module === 'object')
  28. module.exports = factory();
  29. else if(typeof define === 'function' && define.amd)
  30. define([], factory);
  31. else if(typeof exports === 'object')
  32. exports["vis"] = factory();
  33. else
  34. root["vis"] = factory();
  35. })(this, function() {
  36. return /******/ (function(modules) { // webpackBootstrap
  37. /******/ // The module cache
  38. /******/ var installedModules = {};
  39. /******/ // The require function
  40. /******/ function __webpack_require__(moduleId) {
  41. /******/ // Check if module is in cache
  42. /******/ if(installedModules[moduleId])
  43. /******/ return installedModules[moduleId].exports;
  44. /******/ // Create a new module (and put it into the cache)
  45. /******/ var module = installedModules[moduleId] = {
  46. /******/ exports: {},
  47. /******/ id: moduleId,
  48. /******/ loaded: false
  49. /******/ };
  50. /******/ // Execute the module function
  51. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  52. /******/ // Flag the module as loaded
  53. /******/ module.loaded = true;
  54. /******/ // Return the exports of the module
  55. /******/ return module.exports;
  56. /******/ }
  57. /******/ // expose the modules object (__webpack_modules__)
  58. /******/ __webpack_require__.m = modules;
  59. /******/ // expose the module cache
  60. /******/ __webpack_require__.c = installedModules;
  61. /******/ // __webpack_public_path__
  62. /******/ __webpack_require__.p = "";
  63. /******/ // Load entry module and return exports
  64. /******/ return __webpack_require__(0);
  65. /******/ })
  66. /************************************************************************/
  67. /******/ ([
  68. /* 0 */
  69. /***/ function(module, exports, __webpack_require__) {
  70. 'use strict';
  71. var util = __webpack_require__(1);
  72. // Graph3d
  73. util.extend(exports, __webpack_require__(7));
  74. // Timeline & Graph2d
  75. util.extend(exports, __webpack_require__(24));
  76. // Network
  77. util.extend(exports, __webpack_require__(60));
  78. /***/ },
  79. /* 1 */
  80. /***/ function(module, exports, __webpack_require__) {
  81. 'use strict';
  82. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  83. // utility functions
  84. // first check if moment.js is already loaded in the browser window, if so,
  85. // use this instance. Else, load via commonjs.
  86. var moment = __webpack_require__(2);
  87. var uuid = __webpack_require__(6);
  88. /**
  89. * Test whether given object is a number
  90. * @param {*} object
  91. * @return {Boolean} isNumber
  92. */
  93. exports.isNumber = function (object) {
  94. return object instanceof Number || typeof object == 'number';
  95. };
  96. /**
  97. * Remove everything in the DOM object
  98. * @param DOMobject
  99. */
  100. exports.recursiveDOMDelete = function (DOMobject) {
  101. if (DOMobject) {
  102. while (DOMobject.hasChildNodes() === true) {
  103. exports.recursiveDOMDelete(DOMobject.firstChild);
  104. DOMobject.removeChild(DOMobject.firstChild);
  105. }
  106. }
  107. };
  108. /**
  109. * this function gives you a range between 0 and 1 based on the min and max values in the set, the total sum of all values and the current value.
  110. *
  111. * @param min
  112. * @param max
  113. * @param total
  114. * @param value
  115. * @returns {number}
  116. */
  117. exports.giveRange = function (min, max, total, value) {
  118. if (max == min) {
  119. return 0.5;
  120. } else {
  121. var scale = 1 / (max - min);
  122. return Math.max(0, (value - min) * scale);
  123. }
  124. };
  125. /**
  126. * Test whether given object is a string
  127. * @param {*} object
  128. * @return {Boolean} isString
  129. */
  130. exports.isString = function (object) {
  131. return object instanceof String || typeof object == 'string';
  132. };
  133. /**
  134. * Test whether given object is a Date, or a String containing a Date
  135. * @param {Date | String} object
  136. * @return {Boolean} isDate
  137. */
  138. exports.isDate = function (object) {
  139. if (object instanceof Date) {
  140. return true;
  141. } else if (exports.isString(object)) {
  142. // test whether this string contains a date
  143. var match = ASPDateRegex.exec(object);
  144. if (match) {
  145. return true;
  146. } else if (!isNaN(Date.parse(object))) {
  147. return true;
  148. }
  149. }
  150. return false;
  151. };
  152. /**
  153. * Create a semi UUID
  154. * source: http://stackoverflow.com/a/105074/1262753
  155. * @return {String} uuid
  156. */
  157. exports.randomUUID = function () {
  158. return uuid.v4();
  159. };
  160. /**
  161. * assign all keys of an object that are not nested objects to a certain value (used for color objects).
  162. * @param obj
  163. * @param value
  164. */
  165. exports.assignAllKeys = function (obj, value) {
  166. for (var prop in obj) {
  167. if (obj.hasOwnProperty(prop)) {
  168. if (_typeof(obj[prop]) !== 'object') {
  169. obj[prop] = value;
  170. }
  171. }
  172. }
  173. };
  174. /**
  175. * Fill an object with a possibly partially defined other object. Only copies values if the a object has an object requiring values.
  176. * That means an object is not created on a property if only the b object has it.
  177. * @param obj
  178. * @param value
  179. */
  180. exports.fillIfDefined = function (a, b) {
  181. var allowDeletion = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  182. for (var prop in a) {
  183. if (b[prop] !== undefined) {
  184. if (_typeof(b[prop]) !== 'object') {
  185. if ((b[prop] === undefined || b[prop] === null) && a[prop] !== undefined && allowDeletion === true) {
  186. delete a[prop];
  187. } else {
  188. a[prop] = b[prop];
  189. }
  190. } else {
  191. if (_typeof(a[prop]) === 'object') {
  192. exports.fillIfDefined(a[prop], b[prop], allowDeletion);
  193. }
  194. }
  195. }
  196. }
  197. };
  198. /**
  199. * Extend object a with the properties of object b or a series of objects
  200. * Only properties with defined values are copied
  201. * @param {Object} a
  202. * @param {... Object} b
  203. * @return {Object} a
  204. */
  205. exports.protoExtend = function (a, b) {
  206. for (var i = 1; i < arguments.length; i++) {
  207. var other = arguments[i];
  208. for (var prop in other) {
  209. a[prop] = other[prop];
  210. }
  211. }
  212. return a;
  213. };
  214. /**
  215. * Extend object a with the properties of object b or a series of objects
  216. * Only properties with defined values are copied
  217. * @param {Object} a
  218. * @param {... Object} b
  219. * @return {Object} a
  220. */
  221. exports.extend = function (a, b) {
  222. for (var i = 1; i < arguments.length; i++) {
  223. var other = arguments[i];
  224. for (var prop in other) {
  225. if (other.hasOwnProperty(prop)) {
  226. a[prop] = other[prop];
  227. }
  228. }
  229. }
  230. return a;
  231. };
  232. /**
  233. * Extend object a with selected properties of object b or a series of objects
  234. * Only properties with defined values are copied
  235. * @param {Array.<String>} props
  236. * @param {Object} a
  237. * @param {Object} b
  238. * @return {Object} a
  239. */
  240. exports.selectiveExtend = function (props, a, b) {
  241. if (!Array.isArray(props)) {
  242. throw new Error('Array with property names expected as first argument');
  243. }
  244. for (var i = 2; i < arguments.length; i++) {
  245. var other = arguments[i];
  246. for (var p = 0; p < props.length; p++) {
  247. var prop = props[p];
  248. if (other.hasOwnProperty(prop)) {
  249. a[prop] = other[prop];
  250. }
  251. }
  252. }
  253. return a;
  254. };
  255. /**
  256. * Extend object a with selected properties of object b or a series of objects
  257. * Only properties with defined values are copied
  258. * @param {Array.<String>} props
  259. * @param {Object} a
  260. * @param {Object} b
  261. * @return {Object} a
  262. */
  263. exports.selectiveDeepExtend = function (props, a, b) {
  264. var allowDeletion = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
  265. // TODO: add support for Arrays to deepExtend
  266. if (Array.isArray(b)) {
  267. throw new TypeError('Arrays are not supported by deepExtend');
  268. }
  269. for (var i = 2; i < arguments.length; i++) {
  270. var other = arguments[i];
  271. for (var p = 0; p < props.length; p++) {
  272. var prop = props[p];
  273. if (other.hasOwnProperty(prop)) {
  274. if (b[prop] && b[prop].constructor === Object) {
  275. if (a[prop] === undefined) {
  276. a[prop] = {};
  277. }
  278. if (a[prop].constructor === Object) {
  279. exports.deepExtend(a[prop], b[prop], false, allowDeletion);
  280. } else {
  281. if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) {
  282. delete a[prop];
  283. } else {
  284. a[prop] = b[prop];
  285. }
  286. }
  287. } else if (Array.isArray(b[prop])) {
  288. throw new TypeError('Arrays are not supported by deepExtend');
  289. } else {
  290. if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) {
  291. delete a[prop];
  292. } else {
  293. a[prop] = b[prop];
  294. }
  295. }
  296. }
  297. }
  298. }
  299. return a;
  300. };
  301. /**
  302. * Extend object a with selected properties of object b or a series of objects
  303. * Only properties with defined values are copied
  304. * @param {Array.<String>} props
  305. * @param {Object} a
  306. * @param {Object} b
  307. * @return {Object} a
  308. */
  309. exports.selectiveNotDeepExtend = function (props, a, b) {
  310. var allowDeletion = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
  311. // TODO: add support for Arrays to deepExtend
  312. if (Array.isArray(b)) {
  313. throw new TypeError('Arrays are not supported by deepExtend');
  314. }
  315. for (var prop in b) {
  316. if (b.hasOwnProperty(prop)) {
  317. if (props.indexOf(prop) == -1) {
  318. if (b[prop] && b[prop].constructor === Object) {
  319. if (a[prop] === undefined) {
  320. a[prop] = {};
  321. }
  322. if (a[prop].constructor === Object) {
  323. exports.deepExtend(a[prop], b[prop]);
  324. } else {
  325. if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) {
  326. delete a[prop];
  327. } else {
  328. a[prop] = b[prop];
  329. }
  330. }
  331. } else if (Array.isArray(b[prop])) {
  332. a[prop] = [];
  333. for (var i = 0; i < b[prop].length; i++) {
  334. a[prop].push(b[prop][i]);
  335. }
  336. } else {
  337. if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) {
  338. delete a[prop];
  339. } else {
  340. a[prop] = b[prop];
  341. }
  342. }
  343. }
  344. }
  345. }
  346. return a;
  347. };
  348. /**
  349. * Deep extend an object a with the properties of object b
  350. * @param {Object} a
  351. * @param {Object} b
  352. * @param [Boolean] protoExtend --> optional parameter. If true, the prototype values will also be extended.
  353. * (ie. the options objects that inherit from others will also get the inherited options)
  354. * @param [Boolean] global --> optional parameter. If true, the values of fields that are null will not deleted
  355. * @returns {Object}
  356. */
  357. exports.deepExtend = function (a, b, protoExtend, allowDeletion) {
  358. for (var prop in b) {
  359. if (b.hasOwnProperty(prop) || protoExtend === true) {
  360. if (b[prop] && b[prop].constructor === Object) {
  361. if (a[prop] === undefined) {
  362. a[prop] = {};
  363. }
  364. if (a[prop].constructor === Object) {
  365. exports.deepExtend(a[prop], b[prop], protoExtend);
  366. } else {
  367. if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) {
  368. delete a[prop];
  369. } else {
  370. a[prop] = b[prop];
  371. }
  372. }
  373. } else if (Array.isArray(b[prop])) {
  374. a[prop] = [];
  375. for (var i = 0; i < b[prop].length; i++) {
  376. a[prop].push(b[prop][i]);
  377. }
  378. } else {
  379. if (b[prop] === null && a[prop] !== undefined && allowDeletion === true) {
  380. delete a[prop];
  381. } else {
  382. a[prop] = b[prop];
  383. }
  384. }
  385. }
  386. }
  387. return a;
  388. };
  389. /**
  390. * Test whether all elements in two arrays are equal.
  391. * @param {Array} a
  392. * @param {Array} b
  393. * @return {boolean} Returns true if both arrays have the same length and same
  394. * elements.
  395. */
  396. exports.equalArray = function (a, b) {
  397. if (a.length != b.length) return false;
  398. for (var i = 0, len = a.length; i < len; i++) {
  399. if (a[i] != b[i]) return false;
  400. }
  401. return true;
  402. };
  403. /**
  404. * Convert an object to another type
  405. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  406. * @param {String | undefined} type Name of the type. Available types:
  407. * 'Boolean', 'Number', 'String',
  408. * 'Date', 'Moment', ISODate', 'ASPDate'.
  409. * @return {*} object
  410. * @throws Error
  411. */
  412. exports.convert = function (object, type) {
  413. var match;
  414. if (object === undefined) {
  415. return undefined;
  416. }
  417. if (object === null) {
  418. return null;
  419. }
  420. if (!type) {
  421. return object;
  422. }
  423. if (!(typeof type === 'string') && !(type instanceof String)) {
  424. throw new Error('Type must be a string');
  425. }
  426. //noinspection FallthroughInSwitchStatementJS
  427. switch (type) {
  428. case 'boolean':
  429. case 'Boolean':
  430. return Boolean(object);
  431. case 'number':
  432. case 'Number':
  433. return Number(object.valueOf());
  434. case 'string':
  435. case 'String':
  436. return String(object);
  437. case 'Date':
  438. if (exports.isNumber(object)) {
  439. return new Date(object);
  440. }
  441. if (object instanceof Date) {
  442. return new Date(object.valueOf());
  443. } else if (moment.isMoment(object)) {
  444. return new Date(object.valueOf());
  445. }
  446. if (exports.isString(object)) {
  447. match = ASPDateRegex.exec(object);
  448. if (match) {
  449. // object is an ASP date
  450. return new Date(Number(match[1])); // parse number
  451. } else {
  452. return moment(object).toDate(); // parse string
  453. }
  454. } else {
  455. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date');
  456. }
  457. case 'Moment':
  458. if (exports.isNumber(object)) {
  459. return moment(object);
  460. }
  461. if (object instanceof Date) {
  462. return moment(object.valueOf());
  463. } else if (moment.isMoment(object)) {
  464. return moment(object);
  465. }
  466. if (exports.isString(object)) {
  467. match = ASPDateRegex.exec(object);
  468. if (match) {
  469. // object is an ASP date
  470. return moment(Number(match[1])); // parse number
  471. } else {
  472. return moment(object); // parse string
  473. }
  474. } else {
  475. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date');
  476. }
  477. case 'ISODate':
  478. if (exports.isNumber(object)) {
  479. return new Date(object);
  480. } else if (object instanceof Date) {
  481. return object.toISOString();
  482. } else if (moment.isMoment(object)) {
  483. return object.toDate().toISOString();
  484. } else if (exports.isString(object)) {
  485. match = ASPDateRegex.exec(object);
  486. if (match) {
  487. // object is an ASP date
  488. return new Date(Number(match[1])).toISOString(); // parse number
  489. } else {
  490. return new Date(object).toISOString(); // parse string
  491. }
  492. } else {
  493. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ISODate');
  494. }
  495. case 'ASPDate':
  496. if (exports.isNumber(object)) {
  497. return '/Date(' + object + ')/';
  498. } else if (object instanceof Date) {
  499. return '/Date(' + object.valueOf() + ')/';
  500. } else if (exports.isString(object)) {
  501. match = ASPDateRegex.exec(object);
  502. var value;
  503. if (match) {
  504. // object is an ASP date
  505. value = new Date(Number(match[1])).valueOf(); // parse number
  506. } else {
  507. value = new Date(object).valueOf(); // parse string
  508. }
  509. return '/Date(' + value + ')/';
  510. } else {
  511. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate');
  512. }
  513. default:
  514. throw new Error('Unknown type "' + type + '"');
  515. }
  516. };
  517. // parse ASP.Net Date pattern,
  518. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  519. // code from http://momentjs.com/
  520. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  521. /**
  522. * Get the type of an object, for example exports.getType([]) returns 'Array'
  523. * @param {*} object
  524. * @return {String} type
  525. */
  526. exports.getType = function (object) {
  527. var type = typeof object === 'undefined' ? 'undefined' : _typeof(object);
  528. if (type == 'object') {
  529. if (object === null) {
  530. return 'null';
  531. }
  532. if (object instanceof Boolean) {
  533. return 'Boolean';
  534. }
  535. if (object instanceof Number) {
  536. return 'Number';
  537. }
  538. if (object instanceof String) {
  539. return 'String';
  540. }
  541. if (Array.isArray(object)) {
  542. return 'Array';
  543. }
  544. if (object instanceof Date) {
  545. return 'Date';
  546. }
  547. return 'Object';
  548. } else if (type == 'number') {
  549. return 'Number';
  550. } else if (type == 'boolean') {
  551. return 'Boolean';
  552. } else if (type == 'string') {
  553. return 'String';
  554. } else if (type === undefined) {
  555. return 'undefined';
  556. }
  557. return type;
  558. };
  559. /**
  560. * Used to extend an array and copy it. This is used to propagate paths recursively.
  561. *
  562. * @param arr
  563. * @param newValue
  564. * @returns {Array}
  565. */
  566. exports.copyAndExtendArray = function (arr, newValue) {
  567. var newArr = [];
  568. for (var i = 0; i < arr.length; i++) {
  569. newArr.push(arr[i]);
  570. }
  571. newArr.push(newValue);
  572. return newArr;
  573. };
  574. /**
  575. * Used to extend an array and copy it. This is used to propagate paths recursively.
  576. *
  577. * @param arr
  578. * @param newValue
  579. * @returns {Array}
  580. */
  581. exports.copyArray = function (arr) {
  582. var newArr = [];
  583. for (var i = 0; i < arr.length; i++) {
  584. newArr.push(arr[i]);
  585. }
  586. return newArr;
  587. };
  588. /**
  589. * Retrieve the absolute left value of a DOM element
  590. * @param {Element} elem A dom element, for example a div
  591. * @return {number} left The absolute left position of this element
  592. * in the browser page.
  593. */
  594. exports.getAbsoluteLeft = function (elem) {
  595. return elem.getBoundingClientRect().left;
  596. };
  597. exports.getAbsoluteRight = function (elem) {
  598. return elem.getBoundingClientRect().right;
  599. };
  600. /**
  601. * Retrieve the absolute top value of a DOM element
  602. * @param {Element} elem A dom element, for example a div
  603. * @return {number} top The absolute top position of this element
  604. * in the browser page.
  605. */
  606. exports.getAbsoluteTop = function (elem) {
  607. return elem.getBoundingClientRect().top;
  608. };
  609. /**
  610. * add a className to the given elements style
  611. * @param {Element} elem
  612. * @param {String} className
  613. */
  614. exports.addClassName = function (elem, className) {
  615. var classes = elem.className.split(' ');
  616. if (classes.indexOf(className) == -1) {
  617. classes.push(className); // add the class to the array
  618. elem.className = classes.join(' ');
  619. }
  620. };
  621. /**
  622. * add a className to the given elements style
  623. * @param {Element} elem
  624. * @param {String} className
  625. */
  626. exports.removeClassName = function (elem, className) {
  627. var classes = elem.className.split(' ');
  628. var index = classes.indexOf(className);
  629. if (index != -1) {
  630. classes.splice(index, 1); // remove the class from the array
  631. elem.className = classes.join(' ');
  632. }
  633. };
  634. /**
  635. * For each method for both arrays and objects.
  636. * In case of an array, the built-in Array.forEach() is applied.
  637. * In case of an Object, the method loops over all properties of the object.
  638. * @param {Object | Array} object An Object or Array
  639. * @param {function} callback Callback method, called for each item in
  640. * the object or array with three parameters:
  641. * callback(value, index, object)
  642. */
  643. exports.forEach = function (object, callback) {
  644. var i, len;
  645. if (Array.isArray(object)) {
  646. // array
  647. for (i = 0, len = object.length; i < len; i++) {
  648. callback(object[i], i, object);
  649. }
  650. } else {
  651. // object
  652. for (i in object) {
  653. if (object.hasOwnProperty(i)) {
  654. callback(object[i], i, object);
  655. }
  656. }
  657. }
  658. };
  659. /**
  660. * Convert an object into an array: all objects properties are put into the
  661. * array. The resulting array is unordered.
  662. * @param {Object} object
  663. * @param {Array} array
  664. */
  665. exports.toArray = function (object) {
  666. var array = [];
  667. for (var prop in object) {
  668. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  669. }
  670. return array;
  671. };
  672. /**
  673. * Update a property in an object
  674. * @param {Object} object
  675. * @param {String} key
  676. * @param {*} value
  677. * @return {Boolean} changed
  678. */
  679. exports.updateProperty = function (object, key, value) {
  680. if (object[key] !== value) {
  681. object[key] = value;
  682. return true;
  683. } else {
  684. return false;
  685. }
  686. };
  687. /**
  688. * Throttle the given function to be only executed once every `wait` milliseconds
  689. * @param {function} fn
  690. * @param {number} wait Time in milliseconds
  691. * @returns {function} Returns the throttled function
  692. */
  693. exports.throttle = function (fn, wait) {
  694. var timeout = null;
  695. var needExecution = false;
  696. return function throttled() {
  697. if (!timeout) {
  698. needExecution = false;
  699. fn();
  700. timeout = setTimeout(function () {
  701. timeout = null;
  702. if (needExecution) {
  703. throttled();
  704. }
  705. }, wait);
  706. } else {
  707. needExecution = true;
  708. }
  709. };
  710. };
  711. /**
  712. * Add and event listener. Works for all browsers
  713. * @param {Element} element An html element
  714. * @param {string} action The action, for example "click",
  715. * without the prefix "on"
  716. * @param {function} listener The callback function to be executed
  717. * @param {boolean} [useCapture]
  718. */
  719. exports.addEventListener = function (element, action, listener, useCapture) {
  720. if (element.addEventListener) {
  721. if (useCapture === undefined) useCapture = false;
  722. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  723. action = "DOMMouseScroll"; // For Firefox
  724. }
  725. element.addEventListener(action, listener, useCapture);
  726. } else {
  727. element.attachEvent("on" + action, listener); // IE browsers
  728. }
  729. };
  730. /**
  731. * Remove an event listener from an element
  732. * @param {Element} element An html dom element
  733. * @param {string} action The name of the event, for example "mousedown"
  734. * @param {function} listener The listener function
  735. * @param {boolean} [useCapture]
  736. */
  737. exports.removeEventListener = function (element, action, listener, useCapture) {
  738. if (element.removeEventListener) {
  739. // non-IE browsers
  740. if (useCapture === undefined) useCapture = false;
  741. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  742. action = "DOMMouseScroll"; // For Firefox
  743. }
  744. element.removeEventListener(action, listener, useCapture);
  745. } else {
  746. // IE browsers
  747. element.detachEvent("on" + action, listener);
  748. }
  749. };
  750. /**
  751. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  752. */
  753. exports.preventDefault = function (event) {
  754. if (!event) event = window.event;
  755. if (event.preventDefault) {
  756. event.preventDefault(); // non-IE browsers
  757. } else {
  758. event.returnValue = false; // IE browsers
  759. }
  760. };
  761. /**
  762. * Get HTML element which is the target of the event
  763. * @param {Event} event
  764. * @return {Element} target element
  765. */
  766. exports.getTarget = function (event) {
  767. // code from http://www.quirksmode.org/js/events_properties.html
  768. if (!event) {
  769. event = window.event;
  770. }
  771. var target;
  772. if (event.target) {
  773. target = event.target;
  774. } else if (event.srcElement) {
  775. target = event.srcElement;
  776. }
  777. if (target.nodeType != undefined && target.nodeType == 3) {
  778. // defeat Safari bug
  779. target = target.parentNode;
  780. }
  781. return target;
  782. };
  783. /**
  784. * Check if given element contains given parent somewhere in the DOM tree
  785. * @param {Element} element
  786. * @param {Element} parent
  787. */
  788. exports.hasParent = function (element, parent) {
  789. var e = element;
  790. while (e) {
  791. if (e === parent) {
  792. return true;
  793. }
  794. e = e.parentNode;
  795. }
  796. return false;
  797. };
  798. exports.option = {};
  799. /**
  800. * Convert a value into a boolean
  801. * @param {Boolean | function | undefined} value
  802. * @param {Boolean} [defaultValue]
  803. * @returns {Boolean} bool
  804. */
  805. exports.option.asBoolean = function (value, defaultValue) {
  806. if (typeof value == 'function') {
  807. value = value();
  808. }
  809. if (value != null) {
  810. return value != false;
  811. }
  812. return defaultValue || null;
  813. };
  814. /**
  815. * Convert a value into a number
  816. * @param {Boolean | function | undefined} value
  817. * @param {Number} [defaultValue]
  818. * @returns {Number} number
  819. */
  820. exports.option.asNumber = function (value, defaultValue) {
  821. if (typeof value == 'function') {
  822. value = value();
  823. }
  824. if (value != null) {
  825. return Number(value) || defaultValue || null;
  826. }
  827. return defaultValue || null;
  828. };
  829. /**
  830. * Convert a value into a string
  831. * @param {String | function | undefined} value
  832. * @param {String} [defaultValue]
  833. * @returns {String} str
  834. */
  835. exports.option.asString = function (value, defaultValue) {
  836. if (typeof value == 'function') {
  837. value = value();
  838. }
  839. if (value != null) {
  840. return String(value);
  841. }
  842. return defaultValue || null;
  843. };
  844. /**
  845. * Convert a size or location into a string with pixels or a percentage
  846. * @param {String | Number | function | undefined} value
  847. * @param {String} [defaultValue]
  848. * @returns {String} size
  849. */
  850. exports.option.asSize = function (value, defaultValue) {
  851. if (typeof value == 'function') {
  852. value = value();
  853. }
  854. if (exports.isString(value)) {
  855. return value;
  856. } else if (exports.isNumber(value)) {
  857. return value + 'px';
  858. } else {
  859. return defaultValue || null;
  860. }
  861. };
  862. /**
  863. * Convert a value into a DOM element
  864. * @param {HTMLElement | function | undefined} value
  865. * @param {HTMLElement} [defaultValue]
  866. * @returns {HTMLElement | null} dom
  867. */
  868. exports.option.asElement = function (value, defaultValue) {
  869. if (typeof value == 'function') {
  870. value = value();
  871. }
  872. return value || defaultValue || null;
  873. };
  874. /**
  875. * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
  876. *
  877. * @param {String} hex
  878. * @returns {{r: *, g: *, b: *}} | 255 range
  879. */
  880. exports.hexToRGB = function (hex) {
  881. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  882. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  883. hex = hex.replace(shorthandRegex, function (m, r, g, b) {
  884. return r + r + g + g + b + b;
  885. });
  886. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  887. return result ? {
  888. r: parseInt(result[1], 16),
  889. g: parseInt(result[2], 16),
  890. b: parseInt(result[3], 16)
  891. } : null;
  892. };
  893. /**
  894. * This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string.
  895. * @param color
  896. * @param opacity
  897. * @returns {*}
  898. */
  899. exports.overrideOpacity = function (color, opacity) {
  900. if (color.indexOf("rgba") != -1) {
  901. return color;
  902. } else if (color.indexOf("rgb") != -1) {
  903. var rgb = color.substr(color.indexOf("(") + 1).replace(")", "").split(",");
  904. return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
  905. } else {
  906. var rgb = exports.hexToRGB(color);
  907. if (rgb == null) {
  908. return color;
  909. } else {
  910. return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")";
  911. }
  912. }
  913. };
  914. /**
  915. *
  916. * @param red 0 -- 255
  917. * @param green 0 -- 255
  918. * @param blue 0 -- 255
  919. * @returns {string}
  920. * @constructor
  921. */
  922. exports.RGBToHex = function (red, green, blue) {
  923. return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
  924. };
  925. /**
  926. * Parse a color property into an object with border, background, and
  927. * highlight colors
  928. * @param {Object | String} color
  929. * @return {Object} colorObject
  930. */
  931. exports.parseColor = function (color) {
  932. var c;
  933. if (exports.isString(color) === true) {
  934. if (exports.isValidRGB(color) === true) {
  935. var rgb = color.substr(4).substr(0, color.length - 5).split(',').map(function (value) {
  936. return parseInt(value);
  937. });
  938. color = exports.RGBToHex(rgb[0], rgb[1], rgb[2]);
  939. }
  940. if (exports.isValidHex(color) === true) {
  941. var hsv = exports.hexToHSV(color);
  942. var lighterColorHSV = { h: hsv.h, s: hsv.s * 0.8, v: Math.min(1, hsv.v * 1.02) };
  943. var darkerColorHSV = { h: hsv.h, s: Math.min(1, hsv.s * 1.25), v: hsv.v * 0.8 };
  944. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
  945. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
  946. c = {
  947. background: color,
  948. border: darkerColorHex,
  949. highlight: {
  950. background: lighterColorHex,
  951. border: darkerColorHex
  952. },
  953. hover: {
  954. background: lighterColorHex,
  955. border: darkerColorHex
  956. }
  957. };
  958. } else {
  959. c = {
  960. background: color,
  961. border: color,
  962. highlight: {
  963. background: color,
  964. border: color
  965. },
  966. hover: {
  967. background: color,
  968. border: color
  969. }
  970. };
  971. }
  972. } else {
  973. c = {};
  974. c.background = color.background || undefined;
  975. c.border = color.border || undefined;
  976. if (exports.isString(color.highlight)) {
  977. c.highlight = {
  978. border: color.highlight,
  979. background: color.highlight
  980. };
  981. } else {
  982. c.highlight = {};
  983. c.highlight.background = color.highlight && color.highlight.background || undefined;
  984. c.highlight.border = color.highlight && color.highlight.border || undefined;
  985. }
  986. if (exports.isString(color.hover)) {
  987. c.hover = {
  988. border: color.hover,
  989. background: color.hover
  990. };
  991. } else {
  992. c.hover = {};
  993. c.hover.background = color.hover && color.hover.background || undefined;
  994. c.hover.border = color.hover && color.hover.border || undefined;
  995. }
  996. }
  997. return c;
  998. };
  999. /**
  1000. * http://www.javascripter.net/faq/rgb2hsv.htm
  1001. *
  1002. * @param red
  1003. * @param green
  1004. * @param blue
  1005. * @returns {*}
  1006. * @constructor
  1007. */
  1008. exports.RGBToHSV = function (red, green, blue) {
  1009. red = red / 255;green = green / 255;blue = blue / 255;
  1010. var minRGB = Math.min(red, Math.min(green, blue));
  1011. var maxRGB = Math.max(red, Math.max(green, blue));
  1012. // Black-gray-white
  1013. if (minRGB == maxRGB) {
  1014. return { h: 0, s: 0, v: minRGB };
  1015. }
  1016. // Colors other than black-gray-white:
  1017. var d = red == minRGB ? green - blue : blue == minRGB ? red - green : blue - red;
  1018. var h = red == minRGB ? 3 : blue == minRGB ? 1 : 5;
  1019. var hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
  1020. var saturation = (maxRGB - minRGB) / maxRGB;
  1021. var value = maxRGB;
  1022. return { h: hue, s: saturation, v: value };
  1023. };
  1024. var cssUtil = {
  1025. // split a string with css styles into an object with key/values
  1026. split: function split(cssText) {
  1027. var styles = {};
  1028. cssText.split(';').forEach(function (style) {
  1029. if (style.trim() != '') {
  1030. var parts = style.split(':');
  1031. var key = parts[0].trim();
  1032. var value = parts[1].trim();
  1033. styles[key] = value;
  1034. }
  1035. });
  1036. return styles;
  1037. },
  1038. // build a css text string from an object with key/values
  1039. join: function join(styles) {
  1040. return Object.keys(styles).map(function (key) {
  1041. return key + ': ' + styles[key];
  1042. }).join('; ');
  1043. }
  1044. };
  1045. /**
  1046. * Append a string with css styles to an element
  1047. * @param {Element} element
  1048. * @param {String} cssText
  1049. */
  1050. exports.addCssText = function (element, cssText) {
  1051. var currentStyles = cssUtil.split(element.style.cssText);
  1052. var newStyles = cssUtil.split(cssText);
  1053. var styles = exports.extend(currentStyles, newStyles);
  1054. element.style.cssText = cssUtil.join(styles);
  1055. };
  1056. /**
  1057. * Remove a string with css styles from an element
  1058. * @param {Element} element
  1059. * @param {String} cssText
  1060. */
  1061. exports.removeCssText = function (element, cssText) {
  1062. var styles = cssUtil.split(element.style.cssText);
  1063. var removeStyles = cssUtil.split(cssText);
  1064. for (var key in removeStyles) {
  1065. if (removeStyles.hasOwnProperty(key)) {
  1066. delete styles[key];
  1067. }
  1068. }
  1069. element.style.cssText = cssUtil.join(styles);
  1070. };
  1071. /**
  1072. * https://gist.github.com/mjijackson/5311256
  1073. * @param h
  1074. * @param s
  1075. * @param v
  1076. * @returns {{r: number, g: number, b: number}}
  1077. * @constructor
  1078. */
  1079. exports.HSVToRGB = function (h, s, v) {
  1080. var r, g, b;
  1081. var i = Math.floor(h * 6);
  1082. var f = h * 6 - i;
  1083. var p = v * (1 - s);
  1084. var q = v * (1 - f * s);
  1085. var t = v * (1 - (1 - f) * s);
  1086. switch (i % 6) {
  1087. case 0:
  1088. r = v, g = t, b = p;break;
  1089. case 1:
  1090. r = q, g = v, b = p;break;
  1091. case 2:
  1092. r = p, g = v, b = t;break;
  1093. case 3:
  1094. r = p, g = q, b = v;break;
  1095. case 4:
  1096. r = t, g = p, b = v;break;
  1097. case 5:
  1098. r = v, g = p, b = q;break;
  1099. }
  1100. return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) };
  1101. };
  1102. exports.HSVToHex = function (h, s, v) {
  1103. var rgb = exports.HSVToRGB(h, s, v);
  1104. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1105. };
  1106. exports.hexToHSV = function (hex) {
  1107. var rgb = exports.hexToRGB(hex);
  1108. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1109. };
  1110. exports.isValidHex = function (hex) {
  1111. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1112. return isOk;
  1113. };
  1114. exports.isValidRGB = function (rgb) {
  1115. rgb = rgb.replace(" ", "");
  1116. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1117. return isOk;
  1118. };
  1119. exports.isValidRGBA = function (rgba) {
  1120. rgba = rgba.replace(" ", "");
  1121. var isOk = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(rgba);
  1122. return isOk;
  1123. };
  1124. /**
  1125. * This recursively redirects the prototype of JSON objects to the referenceObject
  1126. * This is used for default options.
  1127. *
  1128. * @param referenceObject
  1129. * @returns {*}
  1130. */
  1131. exports.selectiveBridgeObject = function (fields, referenceObject) {
  1132. if ((typeof referenceObject === 'undefined' ? 'undefined' : _typeof(referenceObject)) == "object") {
  1133. var objectTo = Object.create(referenceObject);
  1134. for (var i = 0; i < fields.length; i++) {
  1135. if (referenceObject.hasOwnProperty(fields[i])) {
  1136. if (_typeof(referenceObject[fields[i]]) == "object") {
  1137. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1138. }
  1139. }
  1140. }
  1141. return objectTo;
  1142. } else {
  1143. return null;
  1144. }
  1145. };
  1146. /**
  1147. * This recursively redirects the prototype of JSON objects to the referenceObject
  1148. * This is used for default options.
  1149. *
  1150. * @param referenceObject
  1151. * @returns {*}
  1152. */
  1153. exports.bridgeObject = function (referenceObject) {
  1154. if ((typeof referenceObject === 'undefined' ? 'undefined' : _typeof(referenceObject)) == "object") {
  1155. var objectTo = Object.create(referenceObject);
  1156. for (var i in referenceObject) {
  1157. if (referenceObject.hasOwnProperty(i)) {
  1158. if (_typeof(referenceObject[i]) == "object") {
  1159. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1160. }
  1161. }
  1162. }
  1163. return objectTo;
  1164. } else {
  1165. return null;
  1166. }
  1167. };
  1168. /**
  1169. * This method provides a stable sort implementation, very fast for presorted data
  1170. *
  1171. * @param a the array
  1172. * @param a order comparator
  1173. * @returns {the array}
  1174. */
  1175. exports.insertSort = function (a, compare) {
  1176. for (var i = 0; i < a.length; i++) {
  1177. var k = a[i];
  1178. for (var j = i; j > 0 && compare(k, a[j - 1]) < 0; j--) {
  1179. a[j] = a[j - 1];
  1180. }
  1181. a[j] = k;
  1182. }
  1183. return a;
  1184. };
  1185. /**
  1186. * this is used to set the options of subobjects in the options object. A requirement of these subobjects
  1187. * is that they have an 'enabled' element which is optional for the user but mandatory for the program.
  1188. *
  1189. * @param [object] mergeTarget | this is either this.options or the options used for the groups.
  1190. * @param [object] options | options
  1191. * @param [String] option | this is the option key in the options argument
  1192. */
  1193. exports.mergeOptions = function (mergeTarget, options, option) {
  1194. var allowDeletion = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
  1195. var globalOptions = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4];
  1196. if (options[option] === null) {
  1197. mergeTarget[option] = Object.create(globalOptions[option]);
  1198. } else {
  1199. if (options[option] !== undefined) {
  1200. if (typeof options[option] === 'boolean') {
  1201. mergeTarget[option].enabled = options[option];
  1202. } else {
  1203. if (options[option].enabled === undefined) {
  1204. mergeTarget[option].enabled = true;
  1205. }
  1206. for (var prop in options[option]) {
  1207. if (options[option].hasOwnProperty(prop)) {
  1208. mergeTarget[option][prop] = options[option][prop];
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. };
  1215. /**
  1216. * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
  1217. * this function will then iterate in both directions over this sorted list to find all visible items.
  1218. *
  1219. * @param {Item[]} orderedItems | Items ordered by start
  1220. * @param {function} comparator | -1 is lower, 0 is equal, 1 is higher
  1221. * @param {String} field
  1222. * @param {String} field2
  1223. * @returns {number}
  1224. * @private
  1225. */
  1226. exports.binarySearchCustom = function (orderedItems, comparator, field, field2) {
  1227. var maxIterations = 10000;
  1228. var iteration = 0;
  1229. var low = 0;
  1230. var high = orderedItems.length - 1;
  1231. while (low <= high && iteration < maxIterations) {
  1232. var middle = Math.floor((low + high) / 2);
  1233. var item = orderedItems[middle];
  1234. var value = field2 === undefined ? item[field] : item[field][field2];
  1235. var searchResult = comparator(value);
  1236. if (searchResult == 0) {
  1237. // jihaa, found a visible item!
  1238. return middle;
  1239. } else if (searchResult == -1) {
  1240. // it is too small --> increase low
  1241. low = middle + 1;
  1242. } else {
  1243. // it is too big --> decrease high
  1244. high = middle - 1;
  1245. }
  1246. iteration++;
  1247. }
  1248. return -1;
  1249. };
  1250. /**
  1251. * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
  1252. * two values, we return either the one before or the one after, depending on user input
  1253. * If it is found, we return the index, else -1.
  1254. *
  1255. * @param {Array} orderedItems
  1256. * @param {{start: number, end: number}} target
  1257. * @param {String} field
  1258. * @param {String} sidePreference 'before' or 'after'
  1259. * @param {function} comparator an optional comparator, returning -1,0,1 for <,==,>.
  1260. * @returns {number}
  1261. * @private
  1262. */
  1263. exports.binarySearchValue = function (orderedItems, target, field, sidePreference, comparator) {
  1264. var maxIterations = 10000;
  1265. var iteration = 0;
  1266. var low = 0;
  1267. var high = orderedItems.length - 1;
  1268. var prevValue, value, nextValue, middle;
  1269. var comparator = comparator != undefined ? comparator : function (a, b) {
  1270. return a == b ? 0 : a < b ? -1 : 1;
  1271. };
  1272. while (low <= high && iteration < maxIterations) {
  1273. // get a new guess
  1274. middle = Math.floor(0.5 * (high + low));
  1275. prevValue = orderedItems[Math.max(0, middle - 1)][field];
  1276. value = orderedItems[middle][field];
  1277. nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
  1278. if (comparator(value, target) == 0) {
  1279. // we found the target
  1280. return middle;
  1281. } else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) {
  1282. // target is in between of the previous and the current
  1283. return sidePreference == 'before' ? Math.max(0, middle - 1) : middle;
  1284. } else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) {
  1285. // target is in between of the current and the next
  1286. return sidePreference == 'before' ? middle : Math.min(orderedItems.length - 1, middle + 1);
  1287. } else {
  1288. // didnt find the target, we need to change our boundaries.
  1289. if (comparator(value, target) < 0) {
  1290. // it is too small --> increase low
  1291. low = middle + 1;
  1292. } else {
  1293. // it is too big --> decrease high
  1294. high = middle - 1;
  1295. }
  1296. }
  1297. iteration++;
  1298. }
  1299. // didnt find anything. Return -1.
  1300. return -1;
  1301. };
  1302. /*
  1303. * Easing Functions - inspired from http://gizma.com/easing/
  1304. * only considering the t value for the range [0, 1] => [0, 1]
  1305. * https://gist.github.com/gre/1650294
  1306. */
  1307. exports.easingFunctions = {
  1308. // no easing, no acceleration
  1309. linear: function linear(t) {
  1310. return t;
  1311. },
  1312. // accelerating from zero velocity
  1313. easeInQuad: function easeInQuad(t) {
  1314. return t * t;
  1315. },
  1316. // decelerating to zero velocity
  1317. easeOutQuad: function easeOutQuad(t) {
  1318. return t * (2 - t);
  1319. },
  1320. // acceleration until halfway, then deceleration
  1321. easeInOutQuad: function easeInOutQuad(t) {
  1322. return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  1323. },
  1324. // accelerating from zero velocity
  1325. easeInCubic: function easeInCubic(t) {
  1326. return t * t * t;
  1327. },
  1328. // decelerating to zero velocity
  1329. easeOutCubic: function easeOutCubic(t) {
  1330. return --t * t * t + 1;
  1331. },
  1332. // acceleration until halfway, then deceleration
  1333. easeInOutCubic: function easeInOutCubic(t) {
  1334. return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  1335. },
  1336. // accelerating from zero velocity
  1337. easeInQuart: function easeInQuart(t) {
  1338. return t * t * t * t;
  1339. },
  1340. // decelerating to zero velocity
  1341. easeOutQuart: function easeOutQuart(t) {
  1342. return 1 - --t * t * t * t;
  1343. },
  1344. // acceleration until halfway, then deceleration
  1345. easeInOutQuart: function easeInOutQuart(t) {
  1346. return t < .5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
  1347. },
  1348. // accelerating from zero velocity
  1349. easeInQuint: function easeInQuint(t) {
  1350. return t * t * t * t * t;
  1351. },
  1352. // decelerating to zero velocity
  1353. easeOutQuint: function easeOutQuint(t) {
  1354. return 1 + --t * t * t * t * t;
  1355. },
  1356. // acceleration until halfway, then deceleration
  1357. easeInOutQuint: function easeInOutQuint(t) {
  1358. return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
  1359. }
  1360. };
  1361. /***/ },
  1362. /* 2 */
  1363. /***/ function(module, exports, __webpack_require__) {
  1364. 'use strict';
  1365. // first check if moment.js is already loaded in the browser window, if so,
  1366. // use this instance. Else, load via commonjs.
  1367. module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(3);
  1368. /***/ },
  1369. /* 3 */
  1370. /***/ function(module, exports, __webpack_require__) {
  1371. /* WEBPACK VAR INJECTION */(function(module) {//! moment.js
  1372. //! version : 2.13.0
  1373. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  1374. //! license : MIT
  1375. //! momentjs.com
  1376. ;(function (global, factory) {
  1377. true ? module.exports = factory() :
  1378. typeof define === 'function' && define.amd ? define(factory) :
  1379. global.moment = factory()
  1380. }(this, function () { 'use strict';
  1381. var hookCallback;
  1382. function utils_hooks__hooks () {
  1383. return hookCallback.apply(null, arguments);
  1384. }
  1385. // This is done to register the method called with moment()
  1386. // without creating circular dependencies.
  1387. function setHookCallback (callback) {
  1388. hookCallback = callback;
  1389. }
  1390. function isArray(input) {
  1391. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  1392. }
  1393. function isDate(input) {
  1394. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  1395. }
  1396. function map(arr, fn) {
  1397. var res = [], i;
  1398. for (i = 0; i < arr.length; ++i) {
  1399. res.push(fn(arr[i], i));
  1400. }
  1401. return res;
  1402. }
  1403. function hasOwnProp(a, b) {
  1404. return Object.prototype.hasOwnProperty.call(a, b);
  1405. }
  1406. function extend(a, b) {
  1407. for (var i in b) {
  1408. if (hasOwnProp(b, i)) {
  1409. a[i] = b[i];
  1410. }
  1411. }
  1412. if (hasOwnProp(b, 'toString')) {
  1413. a.toString = b.toString;
  1414. }
  1415. if (hasOwnProp(b, 'valueOf')) {
  1416. a.valueOf = b.valueOf;
  1417. }
  1418. return a;
  1419. }
  1420. function create_utc__createUTC (input, format, locale, strict) {
  1421. return createLocalOrUTC(input, format, locale, strict, true).utc();
  1422. }
  1423. function defaultParsingFlags() {
  1424. // We need to deep clone this object.
  1425. return {
  1426. empty : false,
  1427. unusedTokens : [],
  1428. unusedInput : [],
  1429. overflow : -2,
  1430. charsLeftOver : 0,
  1431. nullInput : false,
  1432. invalidMonth : null,
  1433. invalidFormat : false,
  1434. userInvalidated : false,
  1435. iso : false,
  1436. parsedDateParts : [],
  1437. meridiem : null
  1438. };
  1439. }
  1440. function getParsingFlags(m) {
  1441. if (m._pf == null) {
  1442. m._pf = defaultParsingFlags();
  1443. }
  1444. return m._pf;
  1445. }
  1446. var some;
  1447. if (Array.prototype.some) {
  1448. some = Array.prototype.some;
  1449. } else {
  1450. some = function (fun) {
  1451. var t = Object(this);
  1452. var len = t.length >>> 0;
  1453. for (var i = 0; i < len; i++) {
  1454. if (i in t && fun.call(this, t[i], i, t)) {
  1455. return true;
  1456. }
  1457. }
  1458. return false;
  1459. };
  1460. }
  1461. function valid__isValid(m) {
  1462. if (m._isValid == null) {
  1463. var flags = getParsingFlags(m);
  1464. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  1465. return i != null;
  1466. });
  1467. m._isValid = !isNaN(m._d.getTime()) &&
  1468. flags.overflow < 0 &&
  1469. !flags.empty &&
  1470. !flags.invalidMonth &&
  1471. !flags.invalidWeekday &&
  1472. !flags.nullInput &&
  1473. !flags.invalidFormat &&
  1474. !flags.userInvalidated &&
  1475. (!flags.meridiem || (flags.meridiem && parsedParts));
  1476. if (m._strict) {
  1477. m._isValid = m._isValid &&
  1478. flags.charsLeftOver === 0 &&
  1479. flags.unusedTokens.length === 0 &&
  1480. flags.bigHour === undefined;
  1481. }
  1482. }
  1483. return m._isValid;
  1484. }
  1485. function valid__createInvalid (flags) {
  1486. var m = create_utc__createUTC(NaN);
  1487. if (flags != null) {
  1488. extend(getParsingFlags(m), flags);
  1489. }
  1490. else {
  1491. getParsingFlags(m).userInvalidated = true;
  1492. }
  1493. return m;
  1494. }
  1495. function isUndefined(input) {
  1496. return input === void 0;
  1497. }
  1498. // Plugins that add properties should also add the key here (null value),
  1499. // so we can properly clone ourselves.
  1500. var momentProperties = utils_hooks__hooks.momentProperties = [];
  1501. function copyConfig(to, from) {
  1502. var i, prop, val;
  1503. if (!isUndefined(from._isAMomentObject)) {
  1504. to._isAMomentObject = from._isAMomentObject;
  1505. }
  1506. if (!isUndefined(from._i)) {
  1507. to._i = from._i;
  1508. }
  1509. if (!isUndefined(from._f)) {
  1510. to._f = from._f;
  1511. }
  1512. if (!isUndefined(from._l)) {
  1513. to._l = from._l;
  1514. }
  1515. if (!isUndefined(from._strict)) {
  1516. to._strict = from._strict;
  1517. }
  1518. if (!isUndefined(from._tzm)) {
  1519. to._tzm = from._tzm;
  1520. }
  1521. if (!isUndefined(from._isUTC)) {
  1522. to._isUTC = from._isUTC;
  1523. }
  1524. if (!isUndefined(from._offset)) {
  1525. to._offset = from._offset;
  1526. }
  1527. if (!isUndefined(from._pf)) {
  1528. to._pf = getParsingFlags(from);
  1529. }
  1530. if (!isUndefined(from._locale)) {
  1531. to._locale = from._locale;
  1532. }
  1533. if (momentProperties.length > 0) {
  1534. for (i in momentProperties) {
  1535. prop = momentProperties[i];
  1536. val = from[prop];
  1537. if (!isUndefined(val)) {
  1538. to[prop] = val;
  1539. }
  1540. }
  1541. }
  1542. return to;
  1543. }
  1544. var updateInProgress = false;
  1545. // Moment prototype object
  1546. function Moment(config) {
  1547. copyConfig(this, config);
  1548. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  1549. // Prevent infinite loop in case updateOffset creates new moment
  1550. // objects.
  1551. if (updateInProgress === false) {
  1552. updateInProgress = true;
  1553. utils_hooks__hooks.updateOffset(this);
  1554. updateInProgress = false;
  1555. }
  1556. }
  1557. function isMoment (obj) {
  1558. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  1559. }
  1560. function absFloor (number) {
  1561. if (number < 0) {
  1562. return Math.ceil(number);
  1563. } else {
  1564. return Math.floor(number);
  1565. }
  1566. }
  1567. function toInt(argumentForCoercion) {
  1568. var coercedNumber = +argumentForCoercion,
  1569. value = 0;
  1570. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  1571. value = absFloor(coercedNumber);
  1572. }
  1573. return value;
  1574. }
  1575. // compare two arrays, return the number of differences
  1576. function compareArrays(array1, array2, dontConvert) {
  1577. var len = Math.min(array1.length, array2.length),
  1578. lengthDiff = Math.abs(array1.length - array2.length),
  1579. diffs = 0,
  1580. i;
  1581. for (i = 0; i < len; i++) {
  1582. if ((dontConvert && array1[i] !== array2[i]) ||
  1583. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  1584. diffs++;
  1585. }
  1586. }
  1587. return diffs + lengthDiff;
  1588. }
  1589. function warn(msg) {
  1590. if (utils_hooks__hooks.suppressDeprecationWarnings === false &&
  1591. (typeof console !== 'undefined') && console.warn) {
  1592. console.warn('Deprecation warning: ' + msg);
  1593. }
  1594. }
  1595. function deprecate(msg, fn) {
  1596. var firstTime = true;
  1597. return extend(function () {
  1598. if (utils_hooks__hooks.deprecationHandler != null) {
  1599. utils_hooks__hooks.deprecationHandler(null, msg);
  1600. }
  1601. if (firstTime) {
  1602. warn(msg + '\nArguments: ' + Array.prototype.slice.call(arguments).join(', ') + '\n' + (new Error()).stack);
  1603. firstTime = false;
  1604. }
  1605. return fn.apply(this, arguments);
  1606. }, fn);
  1607. }
  1608. var deprecations = {};
  1609. function deprecateSimple(name, msg) {
  1610. if (utils_hooks__hooks.deprecationHandler != null) {
  1611. utils_hooks__hooks.deprecationHandler(name, msg);
  1612. }
  1613. if (!deprecations[name]) {
  1614. warn(msg);
  1615. deprecations[name] = true;
  1616. }
  1617. }
  1618. utils_hooks__hooks.suppressDeprecationWarnings = false;
  1619. utils_hooks__hooks.deprecationHandler = null;
  1620. function isFunction(input) {
  1621. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  1622. }
  1623. function isObject(input) {
  1624. return Object.prototype.toString.call(input) === '[object Object]';
  1625. }
  1626. function locale_set__set (config) {
  1627. var prop, i;
  1628. for (i in config) {
  1629. prop = config[i];
  1630. if (isFunction(prop)) {
  1631. this[i] = prop;
  1632. } else {
  1633. this['_' + i] = prop;
  1634. }
  1635. }
  1636. this._config = config;
  1637. // Lenient ordinal parsing accepts just a number in addition to
  1638. // number + (possibly) stuff coming from _ordinalParseLenient.
  1639. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
  1640. }
  1641. function mergeConfigs(parentConfig, childConfig) {
  1642. var res = extend({}, parentConfig), prop;
  1643. for (prop in childConfig) {
  1644. if (hasOwnProp(childConfig, prop)) {
  1645. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  1646. res[prop] = {};
  1647. extend(res[prop], parentConfig[prop]);
  1648. extend(res[prop], childConfig[prop]);
  1649. } else if (childConfig[prop] != null) {
  1650. res[prop] = childConfig[prop];
  1651. } else {
  1652. delete res[prop];
  1653. }
  1654. }
  1655. }
  1656. return res;
  1657. }
  1658. function Locale(config) {
  1659. if (config != null) {
  1660. this.set(config);
  1661. }
  1662. }
  1663. var keys;
  1664. if (Object.keys) {
  1665. keys = Object.keys;
  1666. } else {
  1667. keys = function (obj) {
  1668. var i, res = [];
  1669. for (i in obj) {
  1670. if (hasOwnProp(obj, i)) {
  1671. res.push(i);
  1672. }
  1673. }
  1674. return res;
  1675. };
  1676. }
  1677. // internal storage for locale config files
  1678. var locales = {};
  1679. var globalLocale;
  1680. function normalizeLocale(key) {
  1681. return key ? key.toLowerCase().replace('_', '-') : key;
  1682. }
  1683. // pick the locale from the array
  1684. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  1685. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  1686. function chooseLocale(names) {
  1687. var i = 0, j, next, locale, split;
  1688. while (i < names.length) {
  1689. split = normalizeLocale(names[i]).split('-');
  1690. j = split.length;
  1691. next = normalizeLocale(names[i + 1]);
  1692. next = next ? next.split('-') : null;
  1693. while (j > 0) {
  1694. locale = loadLocale(split.slice(0, j).join('-'));
  1695. if (locale) {
  1696. return locale;
  1697. }
  1698. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  1699. //the next array item is better than a shallower substring of this one
  1700. break;
  1701. }
  1702. j--;
  1703. }
  1704. i++;
  1705. }
  1706. return null;
  1707. }
  1708. function loadLocale(name) {
  1709. var oldLocale = null;
  1710. // TODO: Find a better way to register and load all the locales in Node
  1711. if (!locales[name] && (typeof module !== 'undefined') &&
  1712. module && module.exports) {
  1713. try {
  1714. oldLocale = globalLocale._abbr;
  1715. !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
  1716. // because defineLocale currently also sets the global locale, we
  1717. // want to undo that for lazy loaded locales
  1718. locale_locales__getSetGlobalLocale(oldLocale);
  1719. } catch (e) { }
  1720. }
  1721. return locales[name];
  1722. }
  1723. // This function will load locale and then set the global locale. If
  1724. // no arguments are passed in, it will simply return the current global
  1725. // locale key.
  1726. function locale_locales__getSetGlobalLocale (key, values) {
  1727. var data;
  1728. if (key) {
  1729. if (isUndefined(values)) {
  1730. data = locale_locales__getLocale(key);
  1731. }
  1732. else {
  1733. data = defineLocale(key, values);
  1734. }
  1735. if (data) {
  1736. // moment.duration._locale = moment._locale = data;
  1737. globalLocale = data;
  1738. }
  1739. }
  1740. return globalLocale._abbr;
  1741. }
  1742. function defineLocale (name, config) {
  1743. if (config !== null) {
  1744. config.abbr = name;
  1745. if (locales[name] != null) {
  1746. deprecateSimple('defineLocaleOverride',
  1747. 'use moment.updateLocale(localeName, config) to change ' +
  1748. 'an existing locale. moment.defineLocale(localeName, ' +
  1749. 'config) should only be used for creating a new locale');
  1750. config = mergeConfigs(locales[name]._config, config);
  1751. } else if (config.parentLocale != null) {
  1752. if (locales[config.parentLocale] != null) {
  1753. config = mergeConfigs(locales[config.parentLocale]._config, config);
  1754. } else {
  1755. // treat as if there is no base config
  1756. deprecateSimple('parentLocaleUndefined',
  1757. 'specified parentLocale is not defined yet');
  1758. }
  1759. }
  1760. locales[name] = new Locale(config);
  1761. // backwards compat for now: also set the locale
  1762. locale_locales__getSetGlobalLocale(name);
  1763. return locales[name];
  1764. } else {
  1765. // useful for testing
  1766. delete locales[name];
  1767. return null;
  1768. }
  1769. }
  1770. function updateLocale(name, config) {
  1771. if (config != null) {
  1772. var locale;
  1773. if (locales[name] != null) {
  1774. config = mergeConfigs(locales[name]._config, config);
  1775. }
  1776. locale = new Locale(config);
  1777. locale.parentLocale = locales[name];
  1778. locales[name] = locale;
  1779. // backwards compat for now: also set the locale
  1780. locale_locales__getSetGlobalLocale(name);
  1781. } else {
  1782. // pass null for config to unupdate, useful for tests
  1783. if (locales[name] != null) {
  1784. if (locales[name].parentLocale != null) {
  1785. locales[name] = locales[name].parentLocale;
  1786. } else if (locales[name] != null) {
  1787. delete locales[name];
  1788. }
  1789. }
  1790. }
  1791. return locales[name];
  1792. }
  1793. // returns locale data
  1794. function locale_locales__getLocale (key) {
  1795. var locale;
  1796. if (key && key._locale && key._locale._abbr) {
  1797. key = key._locale._abbr;
  1798. }
  1799. if (!key) {
  1800. return globalLocale;
  1801. }
  1802. if (!isArray(key)) {
  1803. //short-circuit everything else
  1804. locale = loadLocale(key);
  1805. if (locale) {
  1806. return locale;
  1807. }
  1808. key = [key];
  1809. }
  1810. return chooseLocale(key);
  1811. }
  1812. function locale_locales__listLocales() {
  1813. return keys(locales);
  1814. }
  1815. var aliases = {};
  1816. function addUnitAlias (unit, shorthand) {
  1817. var lowerCase = unit.toLowerCase();
  1818. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  1819. }
  1820. function normalizeUnits(units) {
  1821. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  1822. }
  1823. function normalizeObjectUnits(inputObject) {
  1824. var normalizedInput = {},
  1825. normalizedProp,
  1826. prop;
  1827. for (prop in inputObject) {
  1828. if (hasOwnProp(inputObject, prop)) {
  1829. normalizedProp = normalizeUnits(prop);
  1830. if (normalizedProp) {
  1831. normalizedInput[normalizedProp] = inputObject[prop];
  1832. }
  1833. }
  1834. }
  1835. return normalizedInput;
  1836. }
  1837. function makeGetSet (unit, keepTime) {
  1838. return function (value) {
  1839. if (value != null) {
  1840. get_set__set(this, unit, value);
  1841. utils_hooks__hooks.updateOffset(this, keepTime);
  1842. return this;
  1843. } else {
  1844. return get_set__get(this, unit);
  1845. }
  1846. };
  1847. }
  1848. function get_set__get (mom, unit) {
  1849. return mom.isValid() ?
  1850. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  1851. }
  1852. function get_set__set (mom, unit, value) {
  1853. if (mom.isValid()) {
  1854. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  1855. }
  1856. }
  1857. // MOMENTS
  1858. function getSet (units, value) {
  1859. var unit;
  1860. if (typeof units === 'object') {
  1861. for (unit in units) {
  1862. this.set(unit, units[unit]);
  1863. }
  1864. } else {
  1865. units = normalizeUnits(units);
  1866. if (isFunction(this[units])) {
  1867. return this[units](value);
  1868. }
  1869. }
  1870. return this;
  1871. }
  1872. function zeroFill(number, targetLength, forceSign) {
  1873. var absNumber = '' + Math.abs(number),
  1874. zerosToFill = targetLength - absNumber.length,
  1875. sign = number >= 0;
  1876. return (sign ? (forceSign ? '+' : '') : '-') +
  1877. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  1878. }
  1879. var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
  1880. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  1881. var formatFunctions = {};
  1882. var formatTokenFunctions = {};
  1883. // token: 'M'
  1884. // padded: ['MM', 2]
  1885. // ordinal: 'Mo'
  1886. // callback: function () { this.month() + 1 }
  1887. function addFormatToken (token, padded, ordinal, callback) {
  1888. var func = callback;
  1889. if (typeof callback === 'string') {
  1890. func = function () {
  1891. return this[callback]();
  1892. };
  1893. }
  1894. if (token) {
  1895. formatTokenFunctions[token] = func;
  1896. }
  1897. if (padded) {
  1898. formatTokenFunctions[padded[0]] = function () {
  1899. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  1900. };
  1901. }
  1902. if (ordinal) {
  1903. formatTokenFunctions[ordinal] = function () {
  1904. return this.localeData().ordinal(func.apply(this, arguments), token);
  1905. };
  1906. }
  1907. }
  1908. function removeFormattingTokens(input) {
  1909. if (input.match(/\[[\s\S]/)) {
  1910. return input.replace(/^\[|\]$/g, '');
  1911. }
  1912. return input.replace(/\\/g, '');
  1913. }
  1914. function makeFormatFunction(format) {
  1915. var array = format.match(formattingTokens), i, length;
  1916. for (i = 0, length = array.length; i < length; i++) {
  1917. if (formatTokenFunctions[array[i]]) {
  1918. array[i] = formatTokenFunctions[array[i]];
  1919. } else {
  1920. array[i] = removeFormattingTokens(array[i]);
  1921. }
  1922. }
  1923. return function (mom) {
  1924. var output = '', i;
  1925. for (i = 0; i < length; i++) {
  1926. output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
  1927. }
  1928. return output;
  1929. };
  1930. }
  1931. // format date using native date object
  1932. function formatMoment(m, format) {
  1933. if (!m.isValid()) {
  1934. return m.localeData().invalidDate();
  1935. }
  1936. format = expandFormat(format, m.localeData());
  1937. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  1938. return formatFunctions[format](m);
  1939. }
  1940. function expandFormat(format, locale) {
  1941. var i = 5;
  1942. function replaceLongDateFormatTokens(input) {
  1943. return locale.longDateFormat(input) || input;
  1944. }
  1945. localFormattingTokens.lastIndex = 0;
  1946. while (i >= 0 && localFormattingTokens.test(format)) {
  1947. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  1948. localFormattingTokens.lastIndex = 0;
  1949. i -= 1;
  1950. }
  1951. return format;
  1952. }
  1953. var match1 = /\d/; // 0 - 9
  1954. var match2 = /\d\d/; // 00 - 99
  1955. var match3 = /\d{3}/; // 000 - 999
  1956. var match4 = /\d{4}/; // 0000 - 9999
  1957. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  1958. var match1to2 = /\d\d?/; // 0 - 99
  1959. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  1960. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  1961. var match1to3 = /\d{1,3}/; // 0 - 999
  1962. var match1to4 = /\d{1,4}/; // 0 - 9999
  1963. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  1964. var matchUnsigned = /\d+/; // 0 - inf
  1965. var matchSigned = /[+-]?\d+/; // -inf - inf
  1966. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  1967. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  1968. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  1969. // any word (or two) characters or numbers including two/three word month in arabic.
  1970. // includes scottish gaelic two word and hyphenated months
  1971. var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
  1972. var regexes = {};
  1973. function addRegexToken (token, regex, strictRegex) {
  1974. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  1975. return (isStrict && strictRegex) ? strictRegex : regex;
  1976. };
  1977. }
  1978. function getParseRegexForToken (token, config) {
  1979. if (!hasOwnProp(regexes, token)) {
  1980. return new RegExp(unescapeFormat(token));
  1981. }
  1982. return regexes[token](config._strict, config._locale);
  1983. }
  1984. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  1985. function unescapeFormat(s) {
  1986. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  1987. return p1 || p2 || p3 || p4;
  1988. }));
  1989. }
  1990. function regexEscape(s) {
  1991. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  1992. }
  1993. var tokens = {};
  1994. function addParseToken (token, callback) {
  1995. var i, func = callback;
  1996. if (typeof token === 'string') {
  1997. token = [token];
  1998. }
  1999. if (typeof callback === 'number') {
  2000. func = function (input, array) {
  2001. array[callback] = toInt(input);
  2002. };
  2003. }
  2004. for (i = 0; i < token.length; i++) {
  2005. tokens[token[i]] = func;
  2006. }
  2007. }
  2008. function addWeekParseToken (token, callback) {
  2009. addParseToken(token, function (input, array, config, token) {
  2010. config._w = config._w || {};
  2011. callback(input, config._w, config, token);
  2012. });
  2013. }
  2014. function addTimeToArrayFromToken(token, input, config) {
  2015. if (input != null && hasOwnProp(tokens, token)) {
  2016. tokens[token](input, config._a, config, token);
  2017. }
  2018. }
  2019. var YEAR = 0;
  2020. var MONTH = 1;
  2021. var DATE = 2;
  2022. var HOUR = 3;
  2023. var MINUTE = 4;
  2024. var SECOND = 5;
  2025. var MILLISECOND = 6;
  2026. var WEEK = 7;
  2027. var WEEKDAY = 8;
  2028. var indexOf;
  2029. if (Array.prototype.indexOf) {
  2030. indexOf = Array.prototype.indexOf;
  2031. } else {
  2032. indexOf = function (o) {
  2033. // I know
  2034. var i;
  2035. for (i = 0; i < this.length; ++i) {
  2036. if (this[i] === o) {
  2037. return i;
  2038. }
  2039. }
  2040. return -1;
  2041. };
  2042. }
  2043. function daysInMonth(year, month) {
  2044. return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  2045. }
  2046. // FORMATTING
  2047. addFormatToken('M', ['MM', 2], 'Mo', function () {
  2048. return this.month() + 1;
  2049. });
  2050. addFormatToken('MMM', 0, 0, function (format) {
  2051. return this.localeData().monthsShort(this, format);
  2052. });
  2053. addFormatToken('MMMM', 0, 0, function (format) {
  2054. return this.localeData().months(this, format);
  2055. });
  2056. // ALIASES
  2057. addUnitAlias('month', 'M');
  2058. // PARSING
  2059. addRegexToken('M', match1to2);
  2060. addRegexToken('MM', match1to2, match2);
  2061. addRegexToken('MMM', function (isStrict, locale) {
  2062. return locale.monthsShortRegex(isStrict);
  2063. });
  2064. addRegexToken('MMMM', function (isStrict, locale) {
  2065. return locale.monthsRegex(isStrict);
  2066. });
  2067. addParseToken(['M', 'MM'], function (input, array) {
  2068. array[MONTH] = toInt(input) - 1;
  2069. });
  2070. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  2071. var month = config._locale.monthsParse(input, token, config._strict);
  2072. // if we didn't find a month name, mark the date as invalid.
  2073. if (month != null) {
  2074. array[MONTH] = month;
  2075. } else {
  2076. getParsingFlags(config).invalidMonth = input;
  2077. }
  2078. });
  2079. // LOCALES
  2080. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/;
  2081. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  2082. function localeMonths (m, format) {
  2083. return isArray(this._months) ? this._months[m.month()] :
  2084. this._months[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  2085. }
  2086. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  2087. function localeMonthsShort (m, format) {
  2088. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  2089. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  2090. }
  2091. function units_month__handleStrictParse(monthName, format, strict) {
  2092. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  2093. if (!this._monthsParse) {
  2094. // this is not used
  2095. this._monthsParse = [];
  2096. this._longMonthsParse = [];
  2097. this._shortMonthsParse = [];
  2098. for (i = 0; i < 12; ++i) {
  2099. mom = create_utc__createUTC([2000, i]);
  2100. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  2101. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  2102. }
  2103. }
  2104. if (strict) {
  2105. if (format === 'MMM') {
  2106. ii = indexOf.call(this._shortMonthsParse, llc);
  2107. return ii !== -1 ? ii : null;
  2108. } else {
  2109. ii = indexOf.call(this._longMonthsParse, llc);
  2110. return ii !== -1 ? ii : null;
  2111. }
  2112. } else {
  2113. if (format === 'MMM') {
  2114. ii = indexOf.call(this._shortMonthsParse, llc);
  2115. if (ii !== -1) {
  2116. return ii;
  2117. }
  2118. ii = indexOf.call(this._longMonthsParse, llc);
  2119. return ii !== -1 ? ii : null;
  2120. } else {
  2121. ii = indexOf.call(this._longMonthsParse, llc);
  2122. if (ii !== -1) {
  2123. return ii;
  2124. }
  2125. ii = indexOf.call(this._shortMonthsParse, llc);
  2126. return ii !== -1 ? ii : null;
  2127. }
  2128. }
  2129. }
  2130. function localeMonthsParse (monthName, format, strict) {
  2131. var i, mom, regex;
  2132. if (this._monthsParseExact) {
  2133. return units_month__handleStrictParse.call(this, monthName, format, strict);
  2134. }
  2135. if (!this._monthsParse) {
  2136. this._monthsParse = [];
  2137. this._longMonthsParse = [];
  2138. this._shortMonthsParse = [];
  2139. }
  2140. // TODO: add sorting
  2141. // Sorting makes sure if one month (or abbr) is a prefix of another
  2142. // see sorting in computeMonthsParse
  2143. for (i = 0; i < 12; i++) {
  2144. // make the regex if we don't have it already
  2145. mom = create_utc__createUTC([2000, i]);
  2146. if (strict && !this._longMonthsParse[i]) {
  2147. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  2148. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  2149. }
  2150. if (!strict && !this._monthsParse[i]) {
  2151. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  2152. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  2153. }
  2154. // test the regex
  2155. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  2156. return i;
  2157. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  2158. return i;
  2159. } else if (!strict && this._monthsParse[i].test(monthName)) {
  2160. return i;
  2161. }
  2162. }
  2163. }
  2164. // MOMENTS
  2165. function setMonth (mom, value) {
  2166. var dayOfMonth;
  2167. if (!mom.isValid()) {
  2168. // No op
  2169. return mom;
  2170. }
  2171. if (typeof value === 'string') {
  2172. if (/^\d+$/.test(value)) {
  2173. value = toInt(value);
  2174. } else {
  2175. value = mom.localeData().monthsParse(value);
  2176. // TODO: Another silent failure?
  2177. if (typeof value !== 'number') {
  2178. return mom;
  2179. }
  2180. }
  2181. }
  2182. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  2183. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  2184. return mom;
  2185. }
  2186. function getSetMonth (value) {
  2187. if (value != null) {
  2188. setMonth(this, value);
  2189. utils_hooks__hooks.updateOffset(this, true);
  2190. return this;
  2191. } else {
  2192. return get_set__get(this, 'Month');
  2193. }
  2194. }
  2195. function getDaysInMonth () {
  2196. return daysInMonth(this.year(), this.month());
  2197. }
  2198. var defaultMonthsShortRegex = matchWord;
  2199. function monthsShortRegex (isStrict) {
  2200. if (this._monthsParseExact) {
  2201. if (!hasOwnProp(this, '_monthsRegex')) {
  2202. computeMonthsParse.call(this);
  2203. }
  2204. if (isStrict) {
  2205. return this._monthsShortStrictRegex;
  2206. } else {
  2207. return this._monthsShortRegex;
  2208. }
  2209. } else {
  2210. return this._monthsShortStrictRegex && isStrict ?
  2211. this._monthsShortStrictRegex : this._monthsShortRegex;
  2212. }
  2213. }
  2214. var defaultMonthsRegex = matchWord;
  2215. function monthsRegex (isStrict) {
  2216. if (this._monthsParseExact) {
  2217. if (!hasOwnProp(this, '_monthsRegex')) {
  2218. computeMonthsParse.call(this);
  2219. }
  2220. if (isStrict) {
  2221. return this._monthsStrictRegex;
  2222. } else {
  2223. return this._monthsRegex;
  2224. }
  2225. } else {
  2226. return this._monthsStrictRegex && isStrict ?
  2227. this._monthsStrictRegex : this._monthsRegex;
  2228. }
  2229. }
  2230. function computeMonthsParse () {
  2231. function cmpLenRev(a, b) {
  2232. return b.length - a.length;
  2233. }
  2234. var shortPieces = [], longPieces = [], mixedPieces = [],
  2235. i, mom;
  2236. for (i = 0; i < 12; i++) {
  2237. // make the regex if we don't have it already
  2238. mom = create_utc__createUTC([2000, i]);
  2239. shortPieces.push(this.monthsShort(mom, ''));
  2240. longPieces.push(this.months(mom, ''));
  2241. mixedPieces.push(this.months(mom, ''));
  2242. mixedPieces.push(this.monthsShort(mom, ''));
  2243. }
  2244. // Sorting makes sure if one month (or abbr) is a prefix of another it
  2245. // will match the longer piece.
  2246. shortPieces.sort(cmpLenRev);
  2247. longPieces.sort(cmpLenRev);
  2248. mixedPieces.sort(cmpLenRev);
  2249. for (i = 0; i < 12; i++) {
  2250. shortPieces[i] = regexEscape(shortPieces[i]);
  2251. longPieces[i] = regexEscape(longPieces[i]);
  2252. mixedPieces[i] = regexEscape(mixedPieces[i]);
  2253. }
  2254. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  2255. this._monthsShortRegex = this._monthsRegex;
  2256. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  2257. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  2258. }
  2259. function checkOverflow (m) {
  2260. var overflow;
  2261. var a = m._a;
  2262. if (a && getParsingFlags(m).overflow === -2) {
  2263. overflow =
  2264. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  2265. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  2266. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  2267. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  2268. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  2269. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  2270. -1;
  2271. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  2272. overflow = DATE;
  2273. }
  2274. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  2275. overflow = WEEK;
  2276. }
  2277. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  2278. overflow = WEEKDAY;
  2279. }
  2280. getParsingFlags(m).overflow = overflow;
  2281. }
  2282. return m;
  2283. }
  2284. // iso 8601 regex
  2285. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  2286. var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;
  2287. var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;
  2288. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  2289. var isoDates = [
  2290. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  2291. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  2292. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  2293. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  2294. ['YYYY-DDD', /\d{4}-\d{3}/],
  2295. ['YYYY-MM', /\d{4}-\d\d/, false],
  2296. ['YYYYYYMMDD', /[+-]\d{10}/],
  2297. ['YYYYMMDD', /\d{8}/],
  2298. // YYYYMM is NOT allowed by the standard
  2299. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  2300. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  2301. ['YYYYDDD', /\d{7}/]
  2302. ];
  2303. // iso time formats and regexes
  2304. var isoTimes = [
  2305. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  2306. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  2307. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  2308. ['HH:mm', /\d\d:\d\d/],
  2309. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  2310. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  2311. ['HHmmss', /\d\d\d\d\d\d/],
  2312. ['HHmm', /\d\d\d\d/],
  2313. ['HH', /\d\d/]
  2314. ];
  2315. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  2316. // date from iso format
  2317. function configFromISO(config) {
  2318. var i, l,
  2319. string = config._i,
  2320. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  2321. allowTime, dateFormat, timeFormat, tzFormat;
  2322. if (match) {
  2323. getParsingFlags(config).iso = true;
  2324. for (i = 0, l = isoDates.length; i < l; i++) {
  2325. if (isoDates[i][1].exec(match[1])) {
  2326. dateFormat = isoDates[i][0];
  2327. allowTime = isoDates[i][2] !== false;
  2328. break;
  2329. }
  2330. }
  2331. if (dateFormat == null) {
  2332. config._isValid = false;
  2333. return;
  2334. }
  2335. if (match[3]) {
  2336. for (i = 0, l = isoTimes.length; i < l; i++) {
  2337. if (isoTimes[i][1].exec(match[3])) {
  2338. // match[2] should be 'T' or space
  2339. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  2340. break;
  2341. }
  2342. }
  2343. if (timeFormat == null) {
  2344. config._isValid = false;
  2345. return;
  2346. }
  2347. }
  2348. if (!allowTime && timeFormat != null) {
  2349. config._isValid = false;
  2350. return;
  2351. }
  2352. if (match[4]) {
  2353. if (tzRegex.exec(match[4])) {
  2354. tzFormat = 'Z';
  2355. } else {
  2356. config._isValid = false;
  2357. return;
  2358. }
  2359. }
  2360. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  2361. configFromStringAndFormat(config);
  2362. } else {
  2363. config._isValid = false;
  2364. }
  2365. }
  2366. // date from iso format or fallback
  2367. function configFromString(config) {
  2368. var matched = aspNetJsonRegex.exec(config._i);
  2369. if (matched !== null) {
  2370. config._d = new Date(+matched[1]);
  2371. return;
  2372. }
  2373. configFromISO(config);
  2374. if (config._isValid === false) {
  2375. delete config._isValid;
  2376. utils_hooks__hooks.createFromInputFallback(config);
  2377. }
  2378. }
  2379. utils_hooks__hooks.createFromInputFallback = deprecate(
  2380. 'moment construction falls back to js Date. This is ' +
  2381. 'discouraged and will be removed in upcoming major ' +
  2382. 'release. Please refer to ' +
  2383. 'https://github.com/moment/moment/issues/1407 for more info.',
  2384. function (config) {
  2385. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  2386. }
  2387. );
  2388. function createDate (y, m, d, h, M, s, ms) {
  2389. //can't just apply() to create a date:
  2390. //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
  2391. var date = new Date(y, m, d, h, M, s, ms);
  2392. //the date constructor remaps years 0-99 to 1900-1999
  2393. if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
  2394. date.setFullYear(y);
  2395. }
  2396. return date;
  2397. }
  2398. function createUTCDate (y) {
  2399. var date = new Date(Date.UTC.apply(null, arguments));
  2400. //the Date.UTC function remaps years 0-99 to 1900-1999
  2401. if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
  2402. date.setUTCFullYear(y);
  2403. }
  2404. return date;
  2405. }
  2406. // FORMATTING
  2407. addFormatToken('Y', 0, 0, function () {
  2408. var y = this.year();
  2409. return y <= 9999 ? '' + y : '+' + y;
  2410. });
  2411. addFormatToken(0, ['YY', 2], 0, function () {
  2412. return this.year() % 100;
  2413. });
  2414. addFormatToken(0, ['YYYY', 4], 0, 'year');
  2415. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  2416. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  2417. // ALIASES
  2418. addUnitAlias('year', 'y');
  2419. // PARSING
  2420. addRegexToken('Y', matchSigned);
  2421. addRegexToken('YY', match1to2, match2);
  2422. addRegexToken('YYYY', match1to4, match4);
  2423. addRegexToken('YYYYY', match1to6, match6);
  2424. addRegexToken('YYYYYY', match1to6, match6);
  2425. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  2426. addParseToken('YYYY', function (input, array) {
  2427. array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input);
  2428. });
  2429. addParseToken('YY', function (input, array) {
  2430. array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input);
  2431. });
  2432. addParseToken('Y', function (input, array) {
  2433. array[YEAR] = parseInt(input, 10);
  2434. });
  2435. // HELPERS
  2436. function daysInYear(year) {
  2437. return isLeapYear(year) ? 366 : 365;
  2438. }
  2439. function isLeapYear(year) {
  2440. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  2441. }
  2442. // HOOKS
  2443. utils_hooks__hooks.parseTwoDigitYear = function (input) {
  2444. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  2445. };
  2446. // MOMENTS
  2447. var getSetYear = makeGetSet('FullYear', true);
  2448. function getIsLeapYear () {
  2449. return isLeapYear(this.year());
  2450. }
  2451. // start-of-first-week - start-of-year
  2452. function firstWeekOffset(year, dow, doy) {
  2453. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  2454. fwd = 7 + dow - doy,
  2455. // first-week day local weekday -- which local weekday is fwd
  2456. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  2457. return -fwdlw + fwd - 1;
  2458. }
  2459. //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  2460. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  2461. var localWeekday = (7 + weekday - dow) % 7,
  2462. weekOffset = firstWeekOffset(year, dow, doy),
  2463. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  2464. resYear, resDayOfYear;
  2465. if (dayOfYear <= 0) {
  2466. resYear = year - 1;
  2467. resDayOfYear = daysInYear(resYear) + dayOfYear;
  2468. } else if (dayOfYear > daysInYear(year)) {
  2469. resYear = year + 1;
  2470. resDayOfYear = dayOfYear - daysInYear(year);
  2471. } else {
  2472. resYear = year;
  2473. resDayOfYear = dayOfYear;
  2474. }
  2475. return {
  2476. year: resYear,
  2477. dayOfYear: resDayOfYear
  2478. };
  2479. }
  2480. function weekOfYear(mom, dow, doy) {
  2481. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  2482. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  2483. resWeek, resYear;
  2484. if (week < 1) {
  2485. resYear = mom.year() - 1;
  2486. resWeek = week + weeksInYear(resYear, dow, doy);
  2487. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  2488. resWeek = week - weeksInYear(mom.year(), dow, doy);
  2489. resYear = mom.year() + 1;
  2490. } else {
  2491. resYear = mom.year();
  2492. resWeek = week;
  2493. }
  2494. return {
  2495. week: resWeek,
  2496. year: resYear
  2497. };
  2498. }
  2499. function weeksInYear(year, dow, doy) {
  2500. var weekOffset = firstWeekOffset(year, dow, doy),
  2501. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  2502. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  2503. }
  2504. // Pick the first defined of two or three arguments.
  2505. function defaults(a, b, c) {
  2506. if (a != null) {
  2507. return a;
  2508. }
  2509. if (b != null) {
  2510. return b;
  2511. }
  2512. return c;
  2513. }
  2514. function currentDateArray(config) {
  2515. // hooks is actually the exported moment object
  2516. var nowValue = new Date(utils_hooks__hooks.now());
  2517. if (config._useUTC) {
  2518. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  2519. }
  2520. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  2521. }
  2522. // convert an array to a date.
  2523. // the array should mirror the parameters below
  2524. // note: all values past the year are optional and will default to the lowest possible value.
  2525. // [year, month, day , hour, minute, second, millisecond]
  2526. function configFromArray (config) {
  2527. var i, date, input = [], currentDate, yearToUse;
  2528. if (config._d) {
  2529. return;
  2530. }
  2531. currentDate = currentDateArray(config);
  2532. //compute day of the year from weeks and weekdays
  2533. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  2534. dayOfYearFromWeekInfo(config);
  2535. }
  2536. //if the day of the year is set, figure out what it is
  2537. if (config._dayOfYear) {
  2538. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  2539. if (config._dayOfYear > daysInYear(yearToUse)) {
  2540. getParsingFlags(config)._overflowDayOfYear = true;
  2541. }
  2542. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  2543. config._a[MONTH] = date.getUTCMonth();
  2544. config._a[DATE] = date.getUTCDate();
  2545. }
  2546. // Default to current date.
  2547. // * if no year, month, day of month are given, default to today
  2548. // * if day of month is given, default month and year
  2549. // * if month is given, default only year
  2550. // * if year is given, don't default anything
  2551. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  2552. config._a[i] = input[i] = currentDate[i];
  2553. }
  2554. // Zero out whatever was not defaulted, including time
  2555. for (; i < 7; i++) {
  2556. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  2557. }
  2558. // Check for 24:00:00.000
  2559. if (config._a[HOUR] === 24 &&
  2560. config._a[MINUTE] === 0 &&
  2561. config._a[SECOND] === 0 &&
  2562. config._a[MILLISECOND] === 0) {
  2563. config._nextDay = true;
  2564. config._a[HOUR] = 0;
  2565. }
  2566. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  2567. // Apply timezone offset from input. The actual utcOffset can be changed
  2568. // with parseZone.
  2569. if (config._tzm != null) {
  2570. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  2571. }
  2572. if (config._nextDay) {
  2573. config._a[HOUR] = 24;
  2574. }
  2575. }
  2576. function dayOfYearFromWeekInfo(config) {
  2577. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  2578. w = config._w;
  2579. if (w.GG != null || w.W != null || w.E != null) {
  2580. dow = 1;
  2581. doy = 4;
  2582. // TODO: We need to take the current isoWeekYear, but that depends on
  2583. // how we interpret now (local, utc, fixed offset). So create
  2584. // a now version of current config (take local/utc/offset flags, and
  2585. // create now).
  2586. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
  2587. week = defaults(w.W, 1);
  2588. weekday = defaults(w.E, 1);
  2589. if (weekday < 1 || weekday > 7) {
  2590. weekdayOverflow = true;
  2591. }
  2592. } else {
  2593. dow = config._locale._week.dow;
  2594. doy = config._locale._week.doy;
  2595. weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
  2596. week = defaults(w.w, 1);
  2597. if (w.d != null) {
  2598. // weekday -- low day numbers are considered next week
  2599. weekday = w.d;
  2600. if (weekday < 0 || weekday > 6) {
  2601. weekdayOverflow = true;
  2602. }
  2603. } else if (w.e != null) {
  2604. // local weekday -- counting starts from begining of week
  2605. weekday = w.e + dow;
  2606. if (w.e < 0 || w.e > 6) {
  2607. weekdayOverflow = true;
  2608. }
  2609. } else {
  2610. // default to begining of week
  2611. weekday = dow;
  2612. }
  2613. }
  2614. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  2615. getParsingFlags(config)._overflowWeeks = true;
  2616. } else if (weekdayOverflow != null) {
  2617. getParsingFlags(config)._overflowWeekday = true;
  2618. } else {
  2619. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  2620. config._a[YEAR] = temp.year;
  2621. config._dayOfYear = temp.dayOfYear;
  2622. }
  2623. }
  2624. // constant that refers to the ISO standard
  2625. utils_hooks__hooks.ISO_8601 = function () {};
  2626. // date from string and format string
  2627. function configFromStringAndFormat(config) {
  2628. // TODO: Move this to another part of the creation flow to prevent circular deps
  2629. if (config._f === utils_hooks__hooks.ISO_8601) {
  2630. configFromISO(config);
  2631. return;
  2632. }
  2633. config._a = [];
  2634. getParsingFlags(config).empty = true;
  2635. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  2636. var string = '' + config._i,
  2637. i, parsedInput, tokens, token, skipped,
  2638. stringLength = string.length,
  2639. totalParsedInputLength = 0;
  2640. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  2641. for (i = 0; i < tokens.length; i++) {
  2642. token = tokens[i];
  2643. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  2644. // console.log('token', token, 'parsedInput', parsedInput,
  2645. // 'regex', getParseRegexForToken(token, config));
  2646. if (parsedInput) {
  2647. skipped = string.substr(0, string.indexOf(parsedInput));
  2648. if (skipped.length > 0) {
  2649. getParsingFlags(config).unusedInput.push(skipped);
  2650. }
  2651. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  2652. totalParsedInputLength += parsedInput.length;
  2653. }
  2654. // don't parse if it's not a known token
  2655. if (formatTokenFunctions[token]) {
  2656. if (parsedInput) {
  2657. getParsingFlags(config).empty = false;
  2658. }
  2659. else {
  2660. getParsingFlags(config).unusedTokens.push(token);
  2661. }
  2662. addTimeToArrayFromToken(token, parsedInput, config);
  2663. }
  2664. else if (config._strict && !parsedInput) {
  2665. getParsingFlags(config).unusedTokens.push(token);
  2666. }
  2667. }
  2668. // add remaining unparsed input length to the string
  2669. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  2670. if (string.length > 0) {
  2671. getParsingFlags(config).unusedInput.push(string);
  2672. }
  2673. // clear _12h flag if hour is <= 12
  2674. if (getParsingFlags(config).bigHour === true &&
  2675. config._a[HOUR] <= 12 &&
  2676. config._a[HOUR] > 0) {
  2677. getParsingFlags(config).bigHour = undefined;
  2678. }
  2679. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  2680. getParsingFlags(config).meridiem = config._meridiem;
  2681. // handle meridiem
  2682. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  2683. configFromArray(config);
  2684. checkOverflow(config);
  2685. }
  2686. function meridiemFixWrap (locale, hour, meridiem) {
  2687. var isPm;
  2688. if (meridiem == null) {
  2689. // nothing to do
  2690. return hour;
  2691. }
  2692. if (locale.meridiemHour != null) {
  2693. return locale.meridiemHour(hour, meridiem);
  2694. } else if (locale.isPM != null) {
  2695. // Fallback
  2696. isPm = locale.isPM(meridiem);
  2697. if (isPm && hour < 12) {
  2698. hour += 12;
  2699. }
  2700. if (!isPm && hour === 12) {
  2701. hour = 0;
  2702. }
  2703. return hour;
  2704. } else {
  2705. // this is not supposed to happen
  2706. return hour;
  2707. }
  2708. }
  2709. // date from string and array of format strings
  2710. function configFromStringAndArray(config) {
  2711. var tempConfig,
  2712. bestMoment,
  2713. scoreToBeat,
  2714. i,
  2715. currentScore;
  2716. if (config._f.length === 0) {
  2717. getParsingFlags(config).invalidFormat = true;
  2718. config._d = new Date(NaN);
  2719. return;
  2720. }
  2721. for (i = 0; i < config._f.length; i++) {
  2722. currentScore = 0;
  2723. tempConfig = copyConfig({}, config);
  2724. if (config._useUTC != null) {
  2725. tempConfig._useUTC = config._useUTC;
  2726. }
  2727. tempConfig._f = config._f[i];
  2728. configFromStringAndFormat(tempConfig);
  2729. if (!valid__isValid(tempConfig)) {
  2730. continue;
  2731. }
  2732. // if there is any input that was not parsed add a penalty for that format
  2733. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  2734. //or tokens
  2735. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  2736. getParsingFlags(tempConfig).score = currentScore;
  2737. if (scoreToBeat == null || currentScore < scoreToBeat) {
  2738. scoreToBeat = currentScore;
  2739. bestMoment = tempConfig;
  2740. }
  2741. }
  2742. extend(config, bestMoment || tempConfig);
  2743. }
  2744. function configFromObject(config) {
  2745. if (config._d) {
  2746. return;
  2747. }
  2748. var i = normalizeObjectUnits(config._i);
  2749. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  2750. return obj && parseInt(obj, 10);
  2751. });
  2752. configFromArray(config);
  2753. }
  2754. function createFromConfig (config) {
  2755. var res = new Moment(checkOverflow(prepareConfig(config)));
  2756. if (res._nextDay) {
  2757. // Adding is smart enough around DST
  2758. res.add(1, 'd');
  2759. res._nextDay = undefined;
  2760. }
  2761. return res;
  2762. }
  2763. function prepareConfig (config) {
  2764. var input = config._i,
  2765. format = config._f;
  2766. config._locale = config._locale || locale_locales__getLocale(config._l);
  2767. if (input === null || (format === undefined && input === '')) {
  2768. return valid__createInvalid({nullInput: true});
  2769. }
  2770. if (typeof input === 'string') {
  2771. config._i = input = config._locale.preparse(input);
  2772. }
  2773. if (isMoment(input)) {
  2774. return new Moment(checkOverflow(input));
  2775. } else if (isArray(format)) {
  2776. configFromStringAndArray(config);
  2777. } else if (format) {
  2778. configFromStringAndFormat(config);
  2779. } else if (isDate(input)) {
  2780. config._d = input;
  2781. } else {
  2782. configFromInput(config);
  2783. }
  2784. if (!valid__isValid(config)) {
  2785. config._d = null;
  2786. }
  2787. return config;
  2788. }
  2789. function configFromInput(config) {
  2790. var input = config._i;
  2791. if (input === undefined) {
  2792. config._d = new Date(utils_hooks__hooks.now());
  2793. } else if (isDate(input)) {
  2794. config._d = new Date(input.valueOf());
  2795. } else if (typeof input === 'string') {
  2796. configFromString(config);
  2797. } else if (isArray(input)) {
  2798. config._a = map(input.slice(0), function (obj) {
  2799. return parseInt(obj, 10);
  2800. });
  2801. configFromArray(config);
  2802. } else if (typeof(input) === 'object') {
  2803. configFromObject(config);
  2804. } else if (typeof(input) === 'number') {
  2805. // from milliseconds
  2806. config._d = new Date(input);
  2807. } else {
  2808. utils_hooks__hooks.createFromInputFallback(config);
  2809. }
  2810. }
  2811. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  2812. var c = {};
  2813. if (typeof(locale) === 'boolean') {
  2814. strict = locale;
  2815. locale = undefined;
  2816. }
  2817. // object construction must be done this way.
  2818. // https://github.com/moment/moment/issues/1423
  2819. c._isAMomentObject = true;
  2820. c._useUTC = c._isUTC = isUTC;
  2821. c._l = locale;
  2822. c._i = input;
  2823. c._f = format;
  2824. c._strict = strict;
  2825. return createFromConfig(c);
  2826. }
  2827. function local__createLocal (input, format, locale, strict) {
  2828. return createLocalOrUTC(input, format, locale, strict, false);
  2829. }
  2830. var prototypeMin = deprecate(
  2831. 'moment().min is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
  2832. function () {
  2833. var other = local__createLocal.apply(null, arguments);
  2834. if (this.isValid() && other.isValid()) {
  2835. return other < this ? this : other;
  2836. } else {
  2837. return valid__createInvalid();
  2838. }
  2839. }
  2840. );
  2841. var prototypeMax = deprecate(
  2842. 'moment().max is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
  2843. function () {
  2844. var other = local__createLocal.apply(null, arguments);
  2845. if (this.isValid() && other.isValid()) {
  2846. return other > this ? this : other;
  2847. } else {
  2848. return valid__createInvalid();
  2849. }
  2850. }
  2851. );
  2852. // Pick a moment m from moments so that m[fn](other) is true for all
  2853. // other. This relies on the function fn to be transitive.
  2854. //
  2855. // moments should either be an array of moment objects or an array, whose
  2856. // first element is an array of moment objects.
  2857. function pickBy(fn, moments) {
  2858. var res, i;
  2859. if (moments.length === 1 && isArray(moments[0])) {
  2860. moments = moments[0];
  2861. }
  2862. if (!moments.length) {
  2863. return local__createLocal();
  2864. }
  2865. res = moments[0];
  2866. for (i = 1; i < moments.length; ++i) {
  2867. if (!moments[i].isValid() || moments[i][fn](res)) {
  2868. res = moments[i];
  2869. }
  2870. }
  2871. return res;
  2872. }
  2873. // TODO: Use [].sort instead?
  2874. function min () {
  2875. var args = [].slice.call(arguments, 0);
  2876. return pickBy('isBefore', args);
  2877. }
  2878. function max () {
  2879. var args = [].slice.call(arguments, 0);
  2880. return pickBy('isAfter', args);
  2881. }
  2882. var now = function () {
  2883. return Date.now ? Date.now() : +(new Date());
  2884. };
  2885. function Duration (duration) {
  2886. var normalizedInput = normalizeObjectUnits(duration),
  2887. years = normalizedInput.year || 0,
  2888. quarters = normalizedInput.quarter || 0,
  2889. months = normalizedInput.month || 0,
  2890. weeks = normalizedInput.week || 0,
  2891. days = normalizedInput.day || 0,
  2892. hours = normalizedInput.hour || 0,
  2893. minutes = normalizedInput.minute || 0,
  2894. seconds = normalizedInput.second || 0,
  2895. milliseconds = normalizedInput.millisecond || 0;
  2896. // representation for dateAddRemove
  2897. this._milliseconds = +milliseconds +
  2898. seconds * 1e3 + // 1000
  2899. minutes * 6e4 + // 1000 * 60
  2900. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  2901. // Because of dateAddRemove treats 24 hours as different from a
  2902. // day when working around DST, we need to store them separately
  2903. this._days = +days +
  2904. weeks * 7;
  2905. // It is impossible translate months into days without knowing
  2906. // which months you are are talking about, so we have to store
  2907. // it separately.
  2908. this._months = +months +
  2909. quarters * 3 +
  2910. years * 12;
  2911. this._data = {};
  2912. this._locale = locale_locales__getLocale();
  2913. this._bubble();
  2914. }
  2915. function isDuration (obj) {
  2916. return obj instanceof Duration;
  2917. }
  2918. // FORMATTING
  2919. function offset (token, separator) {
  2920. addFormatToken(token, 0, 0, function () {
  2921. var offset = this.utcOffset();
  2922. var sign = '+';
  2923. if (offset < 0) {
  2924. offset = -offset;
  2925. sign = '-';
  2926. }
  2927. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  2928. });
  2929. }
  2930. offset('Z', ':');
  2931. offset('ZZ', '');
  2932. // PARSING
  2933. addRegexToken('Z', matchShortOffset);
  2934. addRegexToken('ZZ', matchShortOffset);
  2935. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  2936. config._useUTC = true;
  2937. config._tzm = offsetFromString(matchShortOffset, input);
  2938. });
  2939. // HELPERS
  2940. // timezone chunker
  2941. // '+10:00' > ['10', '00']
  2942. // '-1530' > ['-15', '30']
  2943. var chunkOffset = /([\+\-]|\d\d)/gi;
  2944. function offsetFromString(matcher, string) {
  2945. var matches = ((string || '').match(matcher) || []);
  2946. var chunk = matches[matches.length - 1] || [];
  2947. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  2948. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  2949. return parts[0] === '+' ? minutes : -minutes;
  2950. }
  2951. // Return a moment from input, that is local/utc/zone equivalent to model.
  2952. function cloneWithOffset(input, model) {
  2953. var res, diff;
  2954. if (model._isUTC) {
  2955. res = model.clone();
  2956. diff = (isMoment(input) || isDate(input) ? input.valueOf() : local__createLocal(input).valueOf()) - res.valueOf();
  2957. // Use low-level api, because this fn is low-level api.
  2958. res._d.setTime(res._d.valueOf() + diff);
  2959. utils_hooks__hooks.updateOffset(res, false);
  2960. return res;
  2961. } else {
  2962. return local__createLocal(input).local();
  2963. }
  2964. }
  2965. function getDateOffset (m) {
  2966. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  2967. // https://github.com/moment/moment/pull/1871
  2968. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  2969. }
  2970. // HOOKS
  2971. // This function will be called whenever a moment is mutated.
  2972. // It is intended to keep the offset in sync with the timezone.
  2973. utils_hooks__hooks.updateOffset = function () {};
  2974. // MOMENTS
  2975. // keepLocalTime = true means only change the timezone, without
  2976. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  2977. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  2978. // +0200, so we adjust the time as needed, to be valid.
  2979. //
  2980. // Keeping the time actually adds/subtracts (one hour)
  2981. // from the actual represented time. That is why we call updateOffset
  2982. // a second time. In case it wants us to change the offset again
  2983. // _changeInProgress == true case, then we have to adjust, because
  2984. // there is no such time in the given timezone.
  2985. function getSetOffset (input, keepLocalTime) {
  2986. var offset = this._offset || 0,
  2987. localAdjust;
  2988. if (!this.isValid()) {
  2989. return input != null ? this : NaN;
  2990. }
  2991. if (input != null) {
  2992. if (typeof input === 'string') {
  2993. input = offsetFromString(matchShortOffset, input);
  2994. } else if (Math.abs(input) < 16) {
  2995. input = input * 60;
  2996. }
  2997. if (!this._isUTC && keepLocalTime) {
  2998. localAdjust = getDateOffset(this);
  2999. }
  3000. this._offset = input;
  3001. this._isUTC = true;
  3002. if (localAdjust != null) {
  3003. this.add(localAdjust, 'm');
  3004. }
  3005. if (offset !== input) {
  3006. if (!keepLocalTime || this._changeInProgress) {
  3007. add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
  3008. } else if (!this._changeInProgress) {
  3009. this._changeInProgress = true;
  3010. utils_hooks__hooks.updateOffset(this, true);
  3011. this._changeInProgress = null;
  3012. }
  3013. }
  3014. return this;
  3015. } else {
  3016. return this._isUTC ? offset : getDateOffset(this);
  3017. }
  3018. }
  3019. function getSetZone (input, keepLocalTime) {
  3020. if (input != null) {
  3021. if (typeof input !== 'string') {
  3022. input = -input;
  3023. }
  3024. this.utcOffset(input, keepLocalTime);
  3025. return this;
  3026. } else {
  3027. return -this.utcOffset();
  3028. }
  3029. }
  3030. function setOffsetToUTC (keepLocalTime) {
  3031. return this.utcOffset(0, keepLocalTime);
  3032. }
  3033. function setOffsetToLocal (keepLocalTime) {
  3034. if (this._isUTC) {
  3035. this.utcOffset(0, keepLocalTime);
  3036. this._isUTC = false;
  3037. if (keepLocalTime) {
  3038. this.subtract(getDateOffset(this), 'm');
  3039. }
  3040. }
  3041. return this;
  3042. }
  3043. function setOffsetToParsedOffset () {
  3044. if (this._tzm) {
  3045. this.utcOffset(this._tzm);
  3046. } else if (typeof this._i === 'string') {
  3047. this.utcOffset(offsetFromString(matchOffset, this._i));
  3048. }
  3049. return this;
  3050. }
  3051. function hasAlignedHourOffset (input) {
  3052. if (!this.isValid()) {
  3053. return false;
  3054. }
  3055. input = input ? local__createLocal(input).utcOffset() : 0;
  3056. return (this.utcOffset() - input) % 60 === 0;
  3057. }
  3058. function isDaylightSavingTime () {
  3059. return (
  3060. this.utcOffset() > this.clone().month(0).utcOffset() ||
  3061. this.utcOffset() > this.clone().month(5).utcOffset()
  3062. );
  3063. }
  3064. function isDaylightSavingTimeShifted () {
  3065. if (!isUndefined(this._isDSTShifted)) {
  3066. return this._isDSTShifted;
  3067. }
  3068. var c = {};
  3069. copyConfig(c, this);
  3070. c = prepareConfig(c);
  3071. if (c._a) {
  3072. var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a);
  3073. this._isDSTShifted = this.isValid() &&
  3074. compareArrays(c._a, other.toArray()) > 0;
  3075. } else {
  3076. this._isDSTShifted = false;
  3077. }
  3078. return this._isDSTShifted;
  3079. }
  3080. function isLocal () {
  3081. return this.isValid() ? !this._isUTC : false;
  3082. }
  3083. function isUtcOffset () {
  3084. return this.isValid() ? this._isUTC : false;
  3085. }
  3086. function isUtc () {
  3087. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  3088. }
  3089. // ASP.NET json date format regex
  3090. var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/;
  3091. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  3092. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  3093. // and further modified to allow for strings containing both week and day
  3094. var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
  3095. function create__createDuration (input, key) {
  3096. var duration = input,
  3097. // matching against regexp is expensive, do it on demand
  3098. match = null,
  3099. sign,
  3100. ret,
  3101. diffRes;
  3102. if (isDuration(input)) {
  3103. duration = {
  3104. ms : input._milliseconds,
  3105. d : input._days,
  3106. M : input._months
  3107. };
  3108. } else if (typeof input === 'number') {
  3109. duration = {};
  3110. if (key) {
  3111. duration[key] = input;
  3112. } else {
  3113. duration.milliseconds = input;
  3114. }
  3115. } else if (!!(match = aspNetRegex.exec(input))) {
  3116. sign = (match[1] === '-') ? -1 : 1;
  3117. duration = {
  3118. y : 0,
  3119. d : toInt(match[DATE]) * sign,
  3120. h : toInt(match[HOUR]) * sign,
  3121. m : toInt(match[MINUTE]) * sign,
  3122. s : toInt(match[SECOND]) * sign,
  3123. ms : toInt(match[MILLISECOND]) * sign
  3124. };
  3125. } else if (!!(match = isoRegex.exec(input))) {
  3126. sign = (match[1] === '-') ? -1 : 1;
  3127. duration = {
  3128. y : parseIso(match[2], sign),
  3129. M : parseIso(match[3], sign),
  3130. w : parseIso(match[4], sign),
  3131. d : parseIso(match[5], sign),
  3132. h : parseIso(match[6], sign),
  3133. m : parseIso(match[7], sign),
  3134. s : parseIso(match[8], sign)
  3135. };
  3136. } else if (duration == null) {// checks for null or undefined
  3137. duration = {};
  3138. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  3139. diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));
  3140. duration = {};
  3141. duration.ms = diffRes.milliseconds;
  3142. duration.M = diffRes.months;
  3143. }
  3144. ret = new Duration(duration);
  3145. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  3146. ret._locale = input._locale;
  3147. }
  3148. return ret;
  3149. }
  3150. create__createDuration.fn = Duration.prototype;
  3151. function parseIso (inp, sign) {
  3152. // We'd normally use ~~inp for this, but unfortunately it also
  3153. // converts floats to ints.
  3154. // inp may be undefined, so careful calling replace on it.
  3155. var res = inp && parseFloat(inp.replace(',', '.'));
  3156. // apply sign while we're at it
  3157. return (isNaN(res) ? 0 : res) * sign;
  3158. }
  3159. function positiveMomentsDifference(base, other) {
  3160. var res = {milliseconds: 0, months: 0};
  3161. res.months = other.month() - base.month() +
  3162. (other.year() - base.year()) * 12;
  3163. if (base.clone().add(res.months, 'M').isAfter(other)) {
  3164. --res.months;
  3165. }
  3166. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  3167. return res;
  3168. }
  3169. function momentsDifference(base, other) {
  3170. var res;
  3171. if (!(base.isValid() && other.isValid())) {
  3172. return {milliseconds: 0, months: 0};
  3173. }
  3174. other = cloneWithOffset(other, base);
  3175. if (base.isBefore(other)) {
  3176. res = positiveMomentsDifference(base, other);
  3177. } else {
  3178. res = positiveMomentsDifference(other, base);
  3179. res.milliseconds = -res.milliseconds;
  3180. res.months = -res.months;
  3181. }
  3182. return res;
  3183. }
  3184. function absRound (number) {
  3185. if (number < 0) {
  3186. return Math.round(-1 * number) * -1;
  3187. } else {
  3188. return Math.round(number);
  3189. }
  3190. }
  3191. // TODO: remove 'name' arg after deprecation is removed
  3192. function createAdder(direction, name) {
  3193. return function (val, period) {
  3194. var dur, tmp;
  3195. //invert the arguments, but complain about it
  3196. if (period !== null && !isNaN(+period)) {
  3197. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
  3198. tmp = val; val = period; period = tmp;
  3199. }
  3200. val = typeof val === 'string' ? +val : val;
  3201. dur = create__createDuration(val, period);
  3202. add_subtract__addSubtract(this, dur, direction);
  3203. return this;
  3204. };
  3205. }
  3206. function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) {
  3207. var milliseconds = duration._milliseconds,
  3208. days = absRound(duration._days),
  3209. months = absRound(duration._months);
  3210. if (!mom.isValid()) {
  3211. // No op
  3212. return;
  3213. }
  3214. updateOffset = updateOffset == null ? true : updateOffset;
  3215. if (milliseconds) {
  3216. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  3217. }
  3218. if (days) {
  3219. get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
  3220. }
  3221. if (months) {
  3222. setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
  3223. }
  3224. if (updateOffset) {
  3225. utils_hooks__hooks.updateOffset(mom, days || months);
  3226. }
  3227. }
  3228. var add_subtract__add = createAdder(1, 'add');
  3229. var add_subtract__subtract = createAdder(-1, 'subtract');
  3230. function moment_calendar__calendar (time, formats) {
  3231. // We want to compare the start of today, vs this.
  3232. // Getting start-of-today depends on whether we're local/utc/offset or not.
  3233. var now = time || local__createLocal(),
  3234. sod = cloneWithOffset(now, this).startOf('day'),
  3235. diff = this.diff(sod, 'days', true),
  3236. format = diff < -6 ? 'sameElse' :
  3237. diff < -1 ? 'lastWeek' :
  3238. diff < 0 ? 'lastDay' :
  3239. diff < 1 ? 'sameDay' :
  3240. diff < 2 ? 'nextDay' :
  3241. diff < 7 ? 'nextWeek' : 'sameElse';
  3242. var output = formats && (isFunction(formats[format]) ? formats[format]() : formats[format]);
  3243. return this.format(output || this.localeData().calendar(format, this, local__createLocal(now)));
  3244. }
  3245. function clone () {
  3246. return new Moment(this);
  3247. }
  3248. function isAfter (input, units) {
  3249. var localInput = isMoment(input) ? input : local__createLocal(input);
  3250. if (!(this.isValid() && localInput.isValid())) {
  3251. return false;
  3252. }
  3253. units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
  3254. if (units === 'millisecond') {
  3255. return this.valueOf() > localInput.valueOf();
  3256. } else {
  3257. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  3258. }
  3259. }
  3260. function isBefore (input, units) {
  3261. var localInput = isMoment(input) ? input : local__createLocal(input);
  3262. if (!(this.isValid() && localInput.isValid())) {
  3263. return false;
  3264. }
  3265. units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
  3266. if (units === 'millisecond') {
  3267. return this.valueOf() < localInput.valueOf();
  3268. } else {
  3269. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  3270. }
  3271. }
  3272. function isBetween (from, to, units, inclusivity) {
  3273. inclusivity = inclusivity || '()';
  3274. return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
  3275. (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
  3276. }
  3277. function isSame (input, units) {
  3278. var localInput = isMoment(input) ? input : local__createLocal(input),
  3279. inputMs;
  3280. if (!(this.isValid() && localInput.isValid())) {
  3281. return false;
  3282. }
  3283. units = normalizeUnits(units || 'millisecond');
  3284. if (units === 'millisecond') {
  3285. return this.valueOf() === localInput.valueOf();
  3286. } else {
  3287. inputMs = localInput.valueOf();
  3288. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  3289. }
  3290. }
  3291. function isSameOrAfter (input, units) {
  3292. return this.isSame(input, units) || this.isAfter(input,units);
  3293. }
  3294. function isSameOrBefore (input, units) {
  3295. return this.isSame(input, units) || this.isBefore(input,units);
  3296. }
  3297. function diff (input, units, asFloat) {
  3298. var that,
  3299. zoneDelta,
  3300. delta, output;
  3301. if (!this.isValid()) {
  3302. return NaN;
  3303. }
  3304. that = cloneWithOffset(input, this);
  3305. if (!that.isValid()) {
  3306. return NaN;
  3307. }
  3308. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  3309. units = normalizeUnits(units);
  3310. if (units === 'year' || units === 'month' || units === 'quarter') {
  3311. output = monthDiff(this, that);
  3312. if (units === 'quarter') {
  3313. output = output / 3;
  3314. } else if (units === 'year') {
  3315. output = output / 12;
  3316. }
  3317. } else {
  3318. delta = this - that;
  3319. output = units === 'second' ? delta / 1e3 : // 1000
  3320. units === 'minute' ? delta / 6e4 : // 1000 * 60
  3321. units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
  3322. units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
  3323. units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
  3324. delta;
  3325. }
  3326. return asFloat ? output : absFloor(output);
  3327. }
  3328. function monthDiff (a, b) {
  3329. // difference in months
  3330. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  3331. // b is in (anchor - 1 month, anchor + 1 month)
  3332. anchor = a.clone().add(wholeMonthDiff, 'months'),
  3333. anchor2, adjust;
  3334. if (b - anchor < 0) {
  3335. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  3336. // linear across the month
  3337. adjust = (b - anchor) / (anchor - anchor2);
  3338. } else {
  3339. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  3340. // linear across the month
  3341. adjust = (b - anchor) / (anchor2 - anchor);
  3342. }
  3343. //check for negative zero, return zero if negative zero
  3344. return -(wholeMonthDiff + adjust) || 0;
  3345. }
  3346. utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  3347. utils_hooks__hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  3348. function toString () {
  3349. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  3350. }
  3351. function moment_format__toISOString () {
  3352. var m = this.clone().utc();
  3353. if (0 < m.year() && m.year() <= 9999) {
  3354. if (isFunction(Date.prototype.toISOString)) {
  3355. // native implementation is ~50x faster, use it when we can
  3356. return this.toDate().toISOString();
  3357. } else {
  3358. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  3359. }
  3360. } else {
  3361. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  3362. }
  3363. }
  3364. function format (inputString) {
  3365. if (!inputString) {
  3366. inputString = this.isUtc() ? utils_hooks__hooks.defaultFormatUtc : utils_hooks__hooks.defaultFormat;
  3367. }
  3368. var output = formatMoment(this, inputString);
  3369. return this.localeData().postformat(output);
  3370. }
  3371. function from (time, withoutSuffix) {
  3372. if (this.isValid() &&
  3373. ((isMoment(time) && time.isValid()) ||
  3374. local__createLocal(time).isValid())) {
  3375. return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  3376. } else {
  3377. return this.localeData().invalidDate();
  3378. }
  3379. }
  3380. function fromNow (withoutSuffix) {
  3381. return this.from(local__createLocal(), withoutSuffix);
  3382. }
  3383. function to (time, withoutSuffix) {
  3384. if (this.isValid() &&
  3385. ((isMoment(time) && time.isValid()) ||
  3386. local__createLocal(time).isValid())) {
  3387. return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  3388. } else {
  3389. return this.localeData().invalidDate();
  3390. }
  3391. }
  3392. function toNow (withoutSuffix) {
  3393. return this.to(local__createLocal(), withoutSuffix);
  3394. }
  3395. // If passed a locale key, it will set the locale for this
  3396. // instance. Otherwise, it will return the locale configuration
  3397. // variables for this instance.
  3398. function locale (key) {
  3399. var newLocaleData;
  3400. if (key === undefined) {
  3401. return this._locale._abbr;
  3402. } else {
  3403. newLocaleData = locale_locales__getLocale(key);
  3404. if (newLocaleData != null) {
  3405. this._locale = newLocaleData;
  3406. }
  3407. return this;
  3408. }
  3409. }
  3410. var lang = deprecate(
  3411. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  3412. function (key) {
  3413. if (key === undefined) {
  3414. return this.localeData();
  3415. } else {
  3416. return this.locale(key);
  3417. }
  3418. }
  3419. );
  3420. function localeData () {
  3421. return this._locale;
  3422. }
  3423. function startOf (units) {
  3424. units = normalizeUnits(units);
  3425. // the following switch intentionally omits break keywords
  3426. // to utilize falling through the cases.
  3427. switch (units) {
  3428. case 'year':
  3429. this.month(0);
  3430. /* falls through */
  3431. case 'quarter':
  3432. case 'month':
  3433. this.date(1);
  3434. /* falls through */
  3435. case 'week':
  3436. case 'isoWeek':
  3437. case 'day':
  3438. case 'date':
  3439. this.hours(0);
  3440. /* falls through */
  3441. case 'hour':
  3442. this.minutes(0);
  3443. /* falls through */
  3444. case 'minute':
  3445. this.seconds(0);
  3446. /* falls through */
  3447. case 'second':
  3448. this.milliseconds(0);
  3449. }
  3450. // weeks are a special case
  3451. if (units === 'week') {
  3452. this.weekday(0);
  3453. }
  3454. if (units === 'isoWeek') {
  3455. this.isoWeekday(1);
  3456. }
  3457. // quarters are also special
  3458. if (units === 'quarter') {
  3459. this.month(Math.floor(this.month() / 3) * 3);
  3460. }
  3461. return this;
  3462. }
  3463. function endOf (units) {
  3464. units = normalizeUnits(units);
  3465. if (units === undefined || units === 'millisecond') {
  3466. return this;
  3467. }
  3468. // 'date' is an alias for 'day', so it should be considered as such.
  3469. if (units === 'date') {
  3470. units = 'day';
  3471. }
  3472. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  3473. }
  3474. function to_type__valueOf () {
  3475. return this._d.valueOf() - ((this._offset || 0) * 60000);
  3476. }
  3477. function unix () {
  3478. return Math.floor(this.valueOf() / 1000);
  3479. }
  3480. function toDate () {
  3481. return this._offset ? new Date(this.valueOf()) : this._d;
  3482. }
  3483. function toArray () {
  3484. var m = this;
  3485. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  3486. }
  3487. function toObject () {
  3488. var m = this;
  3489. return {
  3490. years: m.year(),
  3491. months: m.month(),
  3492. date: m.date(),
  3493. hours: m.hours(),
  3494. minutes: m.minutes(),
  3495. seconds: m.seconds(),
  3496. milliseconds: m.milliseconds()
  3497. };
  3498. }
  3499. function toJSON () {
  3500. // new Date(NaN).toJSON() === null
  3501. return this.isValid() ? this.toISOString() : null;
  3502. }
  3503. function moment_valid__isValid () {
  3504. return valid__isValid(this);
  3505. }
  3506. function parsingFlags () {
  3507. return extend({}, getParsingFlags(this));
  3508. }
  3509. function invalidAt () {
  3510. return getParsingFlags(this).overflow;
  3511. }
  3512. function creationData() {
  3513. return {
  3514. input: this._i,
  3515. format: this._f,
  3516. locale: this._locale,
  3517. isUTC: this._isUTC,
  3518. strict: this._strict
  3519. };
  3520. }
  3521. // FORMATTING
  3522. addFormatToken(0, ['gg', 2], 0, function () {
  3523. return this.weekYear() % 100;
  3524. });
  3525. addFormatToken(0, ['GG', 2], 0, function () {
  3526. return this.isoWeekYear() % 100;
  3527. });
  3528. function addWeekYearFormatToken (token, getter) {
  3529. addFormatToken(0, [token, token.length], 0, getter);
  3530. }
  3531. addWeekYearFormatToken('gggg', 'weekYear');
  3532. addWeekYearFormatToken('ggggg', 'weekYear');
  3533. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  3534. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  3535. // ALIASES
  3536. addUnitAlias('weekYear', 'gg');
  3537. addUnitAlias('isoWeekYear', 'GG');
  3538. // PARSING
  3539. addRegexToken('G', matchSigned);
  3540. addRegexToken('g', matchSigned);
  3541. addRegexToken('GG', match1to2, match2);
  3542. addRegexToken('gg', match1to2, match2);
  3543. addRegexToken('GGGG', match1to4, match4);
  3544. addRegexToken('gggg', match1to4, match4);
  3545. addRegexToken('GGGGG', match1to6, match6);
  3546. addRegexToken('ggggg', match1to6, match6);
  3547. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  3548. week[token.substr(0, 2)] = toInt(input);
  3549. });
  3550. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  3551. week[token] = utils_hooks__hooks.parseTwoDigitYear(input);
  3552. });
  3553. // MOMENTS
  3554. function getSetWeekYear (input) {
  3555. return getSetWeekYearHelper.call(this,
  3556. input,
  3557. this.week(),
  3558. this.weekday(),
  3559. this.localeData()._week.dow,
  3560. this.localeData()._week.doy);
  3561. }
  3562. function getSetISOWeekYear (input) {
  3563. return getSetWeekYearHelper.call(this,
  3564. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  3565. }
  3566. function getISOWeeksInYear () {
  3567. return weeksInYear(this.year(), 1, 4);
  3568. }
  3569. function getWeeksInYear () {
  3570. var weekInfo = this.localeData()._week;
  3571. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  3572. }
  3573. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  3574. var weeksTarget;
  3575. if (input == null) {
  3576. return weekOfYear(this, dow, doy).year;
  3577. } else {
  3578. weeksTarget = weeksInYear(input, dow, doy);
  3579. if (week > weeksTarget) {
  3580. week = weeksTarget;
  3581. }
  3582. return setWeekAll.call(this, input, week, weekday, dow, doy);
  3583. }
  3584. }
  3585. function setWeekAll(weekYear, week, weekday, dow, doy) {
  3586. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  3587. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  3588. this.year(date.getUTCFullYear());
  3589. this.month(date.getUTCMonth());
  3590. this.date(date.getUTCDate());
  3591. return this;
  3592. }
  3593. // FORMATTING
  3594. addFormatToken('Q', 0, 'Qo', 'quarter');
  3595. // ALIASES
  3596. addUnitAlias('quarter', 'Q');
  3597. // PARSING
  3598. addRegexToken('Q', match1);
  3599. addParseToken('Q', function (input, array) {
  3600. array[MONTH] = (toInt(input) - 1) * 3;
  3601. });
  3602. // MOMENTS
  3603. function getSetQuarter (input) {
  3604. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  3605. }
  3606. // FORMATTING
  3607. addFormatToken('w', ['ww', 2], 'wo', 'week');
  3608. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  3609. // ALIASES
  3610. addUnitAlias('week', 'w');
  3611. addUnitAlias('isoWeek', 'W');
  3612. // PARSING
  3613. addRegexToken('w', match1to2);
  3614. addRegexToken('ww', match1to2, match2);
  3615. addRegexToken('W', match1to2);
  3616. addRegexToken('WW', match1to2, match2);
  3617. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  3618. week[token.substr(0, 1)] = toInt(input);
  3619. });
  3620. // HELPERS
  3621. // LOCALES
  3622. function localeWeek (mom) {
  3623. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  3624. }
  3625. var defaultLocaleWeek = {
  3626. dow : 0, // Sunday is the first day of the week.
  3627. doy : 6 // The week that contains Jan 1st is the first week of the year.
  3628. };
  3629. function localeFirstDayOfWeek () {
  3630. return this._week.dow;
  3631. }
  3632. function localeFirstDayOfYear () {
  3633. return this._week.doy;
  3634. }
  3635. // MOMENTS
  3636. function getSetWeek (input) {
  3637. var week = this.localeData().week(this);
  3638. return input == null ? week : this.add((input - week) * 7, 'd');
  3639. }
  3640. function getSetISOWeek (input) {
  3641. var week = weekOfYear(this, 1, 4).week;
  3642. return input == null ? week : this.add((input - week) * 7, 'd');
  3643. }
  3644. // FORMATTING
  3645. addFormatToken('D', ['DD', 2], 'Do', 'date');
  3646. // ALIASES
  3647. addUnitAlias('date', 'D');
  3648. // PARSING
  3649. addRegexToken('D', match1to2);
  3650. addRegexToken('DD', match1to2, match2);
  3651. addRegexToken('Do', function (isStrict, locale) {
  3652. return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
  3653. });
  3654. addParseToken(['D', 'DD'], DATE);
  3655. addParseToken('Do', function (input, array) {
  3656. array[DATE] = toInt(input.match(match1to2)[0], 10);
  3657. });
  3658. // MOMENTS
  3659. var getSetDayOfMonth = makeGetSet('Date', true);
  3660. // FORMATTING
  3661. addFormatToken('d', 0, 'do', 'day');
  3662. addFormatToken('dd', 0, 0, function (format) {
  3663. return this.localeData().weekdaysMin(this, format);
  3664. });
  3665. addFormatToken('ddd', 0, 0, function (format) {
  3666. return this.localeData().weekdaysShort(this, format);
  3667. });
  3668. addFormatToken('dddd', 0, 0, function (format) {
  3669. return this.localeData().weekdays(this, format);
  3670. });
  3671. addFormatToken('e', 0, 0, 'weekday');
  3672. addFormatToken('E', 0, 0, 'isoWeekday');
  3673. // ALIASES
  3674. addUnitAlias('day', 'd');
  3675. addUnitAlias('weekday', 'e');
  3676. addUnitAlias('isoWeekday', 'E');
  3677. // PARSING
  3678. addRegexToken('d', match1to2);
  3679. addRegexToken('e', match1to2);
  3680. addRegexToken('E', match1to2);
  3681. addRegexToken('dd', function (isStrict, locale) {
  3682. return locale.weekdaysMinRegex(isStrict);
  3683. });
  3684. addRegexToken('ddd', function (isStrict, locale) {
  3685. return locale.weekdaysShortRegex(isStrict);
  3686. });
  3687. addRegexToken('dddd', function (isStrict, locale) {
  3688. return locale.weekdaysRegex(isStrict);
  3689. });
  3690. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  3691. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  3692. // if we didn't get a weekday name, mark the date as invalid
  3693. if (weekday != null) {
  3694. week.d = weekday;
  3695. } else {
  3696. getParsingFlags(config).invalidWeekday = input;
  3697. }
  3698. });
  3699. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  3700. week[token] = toInt(input);
  3701. });
  3702. // HELPERS
  3703. function parseWeekday(input, locale) {
  3704. if (typeof input !== 'string') {
  3705. return input;
  3706. }
  3707. if (!isNaN(input)) {
  3708. return parseInt(input, 10);
  3709. }
  3710. input = locale.weekdaysParse(input);
  3711. if (typeof input === 'number') {
  3712. return input;
  3713. }
  3714. return null;
  3715. }
  3716. // LOCALES
  3717. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  3718. function localeWeekdays (m, format) {
  3719. return isArray(this._weekdays) ? this._weekdays[m.day()] :
  3720. this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
  3721. }
  3722. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  3723. function localeWeekdaysShort (m) {
  3724. return this._weekdaysShort[m.day()];
  3725. }
  3726. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  3727. function localeWeekdaysMin (m) {
  3728. return this._weekdaysMin[m.day()];
  3729. }
  3730. function day_of_week__handleStrictParse(weekdayName, format, strict) {
  3731. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  3732. if (!this._weekdaysParse) {
  3733. this._weekdaysParse = [];
  3734. this._shortWeekdaysParse = [];
  3735. this._minWeekdaysParse = [];
  3736. for (i = 0; i < 7; ++i) {
  3737. mom = create_utc__createUTC([2000, 1]).day(i);
  3738. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  3739. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  3740. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  3741. }
  3742. }
  3743. if (strict) {
  3744. if (format === 'dddd') {
  3745. ii = indexOf.call(this._weekdaysParse, llc);
  3746. return ii !== -1 ? ii : null;
  3747. } else if (format === 'ddd') {
  3748. ii = indexOf.call(this._shortWeekdaysParse, llc);
  3749. return ii !== -1 ? ii : null;
  3750. } else {
  3751. ii = indexOf.call(this._minWeekdaysParse, llc);
  3752. return ii !== -1 ? ii : null;
  3753. }
  3754. } else {
  3755. if (format === 'dddd') {
  3756. ii = indexOf.call(this._weekdaysParse, llc);
  3757. if (ii !== -1) {
  3758. return ii;
  3759. }
  3760. ii = indexOf.call(this._shortWeekdaysParse, llc);
  3761. if (ii !== -1) {
  3762. return ii;
  3763. }
  3764. ii = indexOf.call(this._minWeekdaysParse, llc);
  3765. return ii !== -1 ? ii : null;
  3766. } else if (format === 'ddd') {
  3767. ii = indexOf.call(this._shortWeekdaysParse, llc);
  3768. if (ii !== -1) {
  3769. return ii;
  3770. }
  3771. ii = indexOf.call(this._weekdaysParse, llc);
  3772. if (ii !== -1) {
  3773. return ii;
  3774. }
  3775. ii = indexOf.call(this._minWeekdaysParse, llc);
  3776. return ii !== -1 ? ii : null;
  3777. } else {
  3778. ii = indexOf.call(this._minWeekdaysParse, llc);
  3779. if (ii !== -1) {
  3780. return ii;
  3781. }
  3782. ii = indexOf.call(this._weekdaysParse, llc);
  3783. if (ii !== -1) {
  3784. return ii;
  3785. }
  3786. ii = indexOf.call(this._shortWeekdaysParse, llc);
  3787. return ii !== -1 ? ii : null;
  3788. }
  3789. }
  3790. }
  3791. function localeWeekdaysParse (weekdayName, format, strict) {
  3792. var i, mom, regex;
  3793. if (this._weekdaysParseExact) {
  3794. return day_of_week__handleStrictParse.call(this, weekdayName, format, strict);
  3795. }
  3796. if (!this._weekdaysParse) {
  3797. this._weekdaysParse = [];
  3798. this._minWeekdaysParse = [];
  3799. this._shortWeekdaysParse = [];
  3800. this._fullWeekdaysParse = [];
  3801. }
  3802. for (i = 0; i < 7; i++) {
  3803. // make the regex if we don't have it already
  3804. mom = create_utc__createUTC([2000, 1]).day(i);
  3805. if (strict && !this._fullWeekdaysParse[i]) {
  3806. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
  3807. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
  3808. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
  3809. }
  3810. if (!this._weekdaysParse[i]) {
  3811. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  3812. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  3813. }
  3814. // test the regex
  3815. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  3816. return i;
  3817. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  3818. return i;
  3819. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  3820. return i;
  3821. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  3822. return i;
  3823. }
  3824. }
  3825. }
  3826. // MOMENTS
  3827. function getSetDayOfWeek (input) {
  3828. if (!this.isValid()) {
  3829. return input != null ? this : NaN;
  3830. }
  3831. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  3832. if (input != null) {
  3833. input = parseWeekday(input, this.localeData());
  3834. return this.add(input - day, 'd');
  3835. } else {
  3836. return day;
  3837. }
  3838. }
  3839. function getSetLocaleDayOfWeek (input) {
  3840. if (!this.isValid()) {
  3841. return input != null ? this : NaN;
  3842. }
  3843. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  3844. return input == null ? weekday : this.add(input - weekday, 'd');
  3845. }
  3846. function getSetISODayOfWeek (input) {
  3847. if (!this.isValid()) {
  3848. return input != null ? this : NaN;
  3849. }
  3850. // behaves the same as moment#day except
  3851. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  3852. // as a setter, sunday should belong to the previous week.
  3853. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
  3854. }
  3855. var defaultWeekdaysRegex = matchWord;
  3856. function weekdaysRegex (isStrict) {
  3857. if (this._weekdaysParseExact) {
  3858. if (!hasOwnProp(this, '_weekdaysRegex')) {
  3859. computeWeekdaysParse.call(this);
  3860. }
  3861. if (isStrict) {
  3862. return this._weekdaysStrictRegex;
  3863. } else {
  3864. return this._weekdaysRegex;
  3865. }
  3866. } else {
  3867. return this._weekdaysStrictRegex && isStrict ?
  3868. this._weekdaysStrictRegex : this._weekdaysRegex;
  3869. }
  3870. }
  3871. var defaultWeekdaysShortRegex = matchWord;
  3872. function weekdaysShortRegex (isStrict) {
  3873. if (this._weekdaysParseExact) {
  3874. if (!hasOwnProp(this, '_weekdaysRegex')) {
  3875. computeWeekdaysParse.call(this);
  3876. }
  3877. if (isStrict) {
  3878. return this._weekdaysShortStrictRegex;
  3879. } else {
  3880. return this._weekdaysShortRegex;
  3881. }
  3882. } else {
  3883. return this._weekdaysShortStrictRegex && isStrict ?
  3884. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  3885. }
  3886. }
  3887. var defaultWeekdaysMinRegex = matchWord;
  3888. function weekdaysMinRegex (isStrict) {
  3889. if (this._weekdaysParseExact) {
  3890. if (!hasOwnProp(this, '_weekdaysRegex')) {
  3891. computeWeekdaysParse.call(this);
  3892. }
  3893. if (isStrict) {
  3894. return this._weekdaysMinStrictRegex;
  3895. } else {
  3896. return this._weekdaysMinRegex;
  3897. }
  3898. } else {
  3899. return this._weekdaysMinStrictRegex && isStrict ?
  3900. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  3901. }
  3902. }
  3903. function computeWeekdaysParse () {
  3904. function cmpLenRev(a, b) {
  3905. return b.length - a.length;
  3906. }
  3907. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  3908. i, mom, minp, shortp, longp;
  3909. for (i = 0; i < 7; i++) {
  3910. // make the regex if we don't have it already
  3911. mom = create_utc__createUTC([2000, 1]).day(i);
  3912. minp = this.weekdaysMin(mom, '');
  3913. shortp = this.weekdaysShort(mom, '');
  3914. longp = this.weekdays(mom, '');
  3915. minPieces.push(minp);
  3916. shortPieces.push(shortp);
  3917. longPieces.push(longp);
  3918. mixedPieces.push(minp);
  3919. mixedPieces.push(shortp);
  3920. mixedPieces.push(longp);
  3921. }
  3922. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  3923. // will match the longer piece.
  3924. minPieces.sort(cmpLenRev);
  3925. shortPieces.sort(cmpLenRev);
  3926. longPieces.sort(cmpLenRev);
  3927. mixedPieces.sort(cmpLenRev);
  3928. for (i = 0; i < 7; i++) {
  3929. shortPieces[i] = regexEscape(shortPieces[i]);
  3930. longPieces[i] = regexEscape(longPieces[i]);
  3931. mixedPieces[i] = regexEscape(mixedPieces[i]);
  3932. }
  3933. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  3934. this._weekdaysShortRegex = this._weekdaysRegex;
  3935. this._weekdaysMinRegex = this._weekdaysRegex;
  3936. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  3937. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  3938. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  3939. }
  3940. // FORMATTING
  3941. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  3942. // ALIASES
  3943. addUnitAlias('dayOfYear', 'DDD');
  3944. // PARSING
  3945. addRegexToken('DDD', match1to3);
  3946. addRegexToken('DDDD', match3);
  3947. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  3948. config._dayOfYear = toInt(input);
  3949. });
  3950. // HELPERS
  3951. // MOMENTS
  3952. function getSetDayOfYear (input) {
  3953. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  3954. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  3955. }
  3956. // FORMATTING
  3957. function hFormat() {
  3958. return this.hours() % 12 || 12;
  3959. }
  3960. function kFormat() {
  3961. return this.hours() || 24;
  3962. }
  3963. addFormatToken('H', ['HH', 2], 0, 'hour');
  3964. addFormatToken('h', ['hh', 2], 0, hFormat);
  3965. addFormatToken('k', ['kk', 2], 0, kFormat);
  3966. addFormatToken('hmm', 0, 0, function () {
  3967. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  3968. });
  3969. addFormatToken('hmmss', 0, 0, function () {
  3970. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  3971. zeroFill(this.seconds(), 2);
  3972. });
  3973. addFormatToken('Hmm', 0, 0, function () {
  3974. return '' + this.hours() + zeroFill(this.minutes(), 2);
  3975. });
  3976. addFormatToken('Hmmss', 0, 0, function () {
  3977. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  3978. zeroFill(this.seconds(), 2);
  3979. });
  3980. function meridiem (token, lowercase) {
  3981. addFormatToken(token, 0, 0, function () {
  3982. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  3983. });
  3984. }
  3985. meridiem('a', true);
  3986. meridiem('A', false);
  3987. // ALIASES
  3988. addUnitAlias('hour', 'h');
  3989. // PARSING
  3990. function matchMeridiem (isStrict, locale) {
  3991. return locale._meridiemParse;
  3992. }
  3993. addRegexToken('a', matchMeridiem);
  3994. addRegexToken('A', matchMeridiem);
  3995. addRegexToken('H', match1to2);
  3996. addRegexToken('h', match1to2);
  3997. addRegexToken('HH', match1to2, match2);
  3998. addRegexToken('hh', match1to2, match2);
  3999. addRegexToken('hmm', match3to4);
  4000. addRegexToken('hmmss', match5to6);
  4001. addRegexToken('Hmm', match3to4);
  4002. addRegexToken('Hmmss', match5to6);
  4003. addParseToken(['H', 'HH'], HOUR);
  4004. addParseToken(['a', 'A'], function (input, array, config) {
  4005. config._isPm = config._locale.isPM(input);
  4006. config._meridiem = input;
  4007. });
  4008. addParseToken(['h', 'hh'], function (input, array, config) {
  4009. array[HOUR] = toInt(input);
  4010. getParsingFlags(config).bigHour = true;
  4011. });
  4012. addParseToken('hmm', function (input, array, config) {
  4013. var pos = input.length - 2;
  4014. array[HOUR] = toInt(input.substr(0, pos));
  4015. array[MINUTE] = toInt(input.substr(pos));
  4016. getParsingFlags(config).bigHour = true;
  4017. });
  4018. addParseToken('hmmss', function (input, array, config) {
  4019. var pos1 = input.length - 4;
  4020. var pos2 = input.length - 2;
  4021. array[HOUR] = toInt(input.substr(0, pos1));
  4022. array[MINUTE] = toInt(input.substr(pos1, 2));
  4023. array[SECOND] = toInt(input.substr(pos2));
  4024. getParsingFlags(config).bigHour = true;
  4025. });
  4026. addParseToken('Hmm', function (input, array, config) {
  4027. var pos = input.length - 2;
  4028. array[HOUR] = toInt(input.substr(0, pos));
  4029. array[MINUTE] = toInt(input.substr(pos));
  4030. });
  4031. addParseToken('Hmmss', function (input, array, config) {
  4032. var pos1 = input.length - 4;
  4033. var pos2 = input.length - 2;
  4034. array[HOUR] = toInt(input.substr(0, pos1));
  4035. array[MINUTE] = toInt(input.substr(pos1, 2));
  4036. array[SECOND] = toInt(input.substr(pos2));
  4037. });
  4038. // LOCALES
  4039. function localeIsPM (input) {
  4040. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  4041. // Using charAt should be more compatible.
  4042. return ((input + '').toLowerCase().charAt(0) === 'p');
  4043. }
  4044. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  4045. function localeMeridiem (hours, minutes, isLower) {
  4046. if (hours > 11) {
  4047. return isLower ? 'pm' : 'PM';
  4048. } else {
  4049. return isLower ? 'am' : 'AM';
  4050. }
  4051. }
  4052. // MOMENTS
  4053. // Setting the hour should keep the time, because the user explicitly
  4054. // specified which hour he wants. So trying to maintain the same hour (in
  4055. // a new timezone) makes sense. Adding/subtracting hours does not follow
  4056. // this rule.
  4057. var getSetHour = makeGetSet('Hours', true);
  4058. // FORMATTING
  4059. addFormatToken('m', ['mm', 2], 0, 'minute');
  4060. // ALIASES
  4061. addUnitAlias('minute', 'm');
  4062. // PARSING
  4063. addRegexToken('m', match1to2);
  4064. addRegexToken('mm', match1to2, match2);
  4065. addParseToken(['m', 'mm'], MINUTE);
  4066. // MOMENTS
  4067. var getSetMinute = makeGetSet('Minutes', false);
  4068. // FORMATTING
  4069. addFormatToken('s', ['ss', 2], 0, 'second');
  4070. // ALIASES
  4071. addUnitAlias('second', 's');
  4072. // PARSING
  4073. addRegexToken('s', match1to2);
  4074. addRegexToken('ss', match1to2, match2);
  4075. addParseToken(['s', 'ss'], SECOND);
  4076. // MOMENTS
  4077. var getSetSecond = makeGetSet('Seconds', false);
  4078. // FORMATTING
  4079. addFormatToken('S', 0, 0, function () {
  4080. return ~~(this.millisecond() / 100);
  4081. });
  4082. addFormatToken(0, ['SS', 2], 0, function () {
  4083. return ~~(this.millisecond() / 10);
  4084. });
  4085. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  4086. addFormatToken(0, ['SSSS', 4], 0, function () {
  4087. return this.millisecond() * 10;
  4088. });
  4089. addFormatToken(0, ['SSSSS', 5], 0, function () {
  4090. return this.millisecond() * 100;
  4091. });
  4092. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  4093. return this.millisecond() * 1000;
  4094. });
  4095. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  4096. return this.millisecond() * 10000;
  4097. });
  4098. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  4099. return this.millisecond() * 100000;
  4100. });
  4101. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  4102. return this.millisecond() * 1000000;
  4103. });
  4104. // ALIASES
  4105. addUnitAlias('millisecond', 'ms');
  4106. // PARSING
  4107. addRegexToken('S', match1to3, match1);
  4108. addRegexToken('SS', match1to3, match2);
  4109. addRegexToken('SSS', match1to3, match3);
  4110. var token;
  4111. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  4112. addRegexToken(token, matchUnsigned);
  4113. }
  4114. function parseMs(input, array) {
  4115. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  4116. }
  4117. for (token = 'S'; token.length <= 9; token += 'S') {
  4118. addParseToken(token, parseMs);
  4119. }
  4120. // MOMENTS
  4121. var getSetMillisecond = makeGetSet('Milliseconds', false);
  4122. // FORMATTING
  4123. addFormatToken('z', 0, 0, 'zoneAbbr');
  4124. addFormatToken('zz', 0, 0, 'zoneName');
  4125. // MOMENTS
  4126. function getZoneAbbr () {
  4127. return this._isUTC ? 'UTC' : '';
  4128. }
  4129. function getZoneName () {
  4130. return this._isUTC ? 'Coordinated Universal Time' : '';
  4131. }
  4132. var momentPrototype__proto = Moment.prototype;
  4133. momentPrototype__proto.add = add_subtract__add;
  4134. momentPrototype__proto.calendar = moment_calendar__calendar;
  4135. momentPrototype__proto.clone = clone;
  4136. momentPrototype__proto.diff = diff;
  4137. momentPrototype__proto.endOf = endOf;
  4138. momentPrototype__proto.format = format;
  4139. momentPrototype__proto.from = from;
  4140. momentPrototype__proto.fromNow = fromNow;
  4141. momentPrototype__proto.to = to;
  4142. momentPrototype__proto.toNow = toNow;
  4143. momentPrototype__proto.get = getSet;
  4144. momentPrototype__proto.invalidAt = invalidAt;
  4145. momentPrototype__proto.isAfter = isAfter;
  4146. momentPrototype__proto.isBefore = isBefore;
  4147. momentPrototype__proto.isBetween = isBetween;
  4148. momentPrototype__proto.isSame = isSame;
  4149. momentPrototype__proto.isSameOrAfter = isSameOrAfter;
  4150. momentPrototype__proto.isSameOrBefore = isSameOrBefore;
  4151. momentPrototype__proto.isValid = moment_valid__isValid;
  4152. momentPrototype__proto.lang = lang;
  4153. momentPrototype__proto.locale = locale;
  4154. momentPrototype__proto.localeData = localeData;
  4155. momentPrototype__proto.max = prototypeMax;
  4156. momentPrototype__proto.min = prototypeMin;
  4157. momentPrototype__proto.parsingFlags = parsingFlags;
  4158. momentPrototype__proto.set = getSet;
  4159. momentPrototype__proto.startOf = startOf;
  4160. momentPrototype__proto.subtract = add_subtract__subtract;
  4161. momentPrototype__proto.toArray = toArray;
  4162. momentPrototype__proto.toObject = toObject;
  4163. momentPrototype__proto.toDate = toDate;
  4164. momentPrototype__proto.toISOString = moment_format__toISOString;
  4165. momentPrototype__proto.toJSON = toJSON;
  4166. momentPrototype__proto.toString = toString;
  4167. momentPrototype__proto.unix = unix;
  4168. momentPrototype__proto.valueOf = to_type__valueOf;
  4169. momentPrototype__proto.creationData = creationData;
  4170. // Year
  4171. momentPrototype__proto.year = getSetYear;
  4172. momentPrototype__proto.isLeapYear = getIsLeapYear;
  4173. // Week Year
  4174. momentPrototype__proto.weekYear = getSetWeekYear;
  4175. momentPrototype__proto.isoWeekYear = getSetISOWeekYear;
  4176. // Quarter
  4177. momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;
  4178. // Month
  4179. momentPrototype__proto.month = getSetMonth;
  4180. momentPrototype__proto.daysInMonth = getDaysInMonth;
  4181. // Week
  4182. momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek;
  4183. momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek;
  4184. momentPrototype__proto.weeksInYear = getWeeksInYear;
  4185. momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;
  4186. // Day
  4187. momentPrototype__proto.date = getSetDayOfMonth;
  4188. momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek;
  4189. momentPrototype__proto.weekday = getSetLocaleDayOfWeek;
  4190. momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
  4191. momentPrototype__proto.dayOfYear = getSetDayOfYear;
  4192. // Hour
  4193. momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;
  4194. // Minute
  4195. momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;
  4196. // Second
  4197. momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;
  4198. // Millisecond
  4199. momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;
  4200. // Offset
  4201. momentPrototype__proto.utcOffset = getSetOffset;
  4202. momentPrototype__proto.utc = setOffsetToUTC;
  4203. momentPrototype__proto.local = setOffsetToLocal;
  4204. momentPrototype__proto.parseZone = setOffsetToParsedOffset;
  4205. momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
  4206. momentPrototype__proto.isDST = isDaylightSavingTime;
  4207. momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted;
  4208. momentPrototype__proto.isLocal = isLocal;
  4209. momentPrototype__proto.isUtcOffset = isUtcOffset;
  4210. momentPrototype__proto.isUtc = isUtc;
  4211. momentPrototype__proto.isUTC = isUtc;
  4212. // Timezone
  4213. momentPrototype__proto.zoneAbbr = getZoneAbbr;
  4214. momentPrototype__proto.zoneName = getZoneName;
  4215. // Deprecations
  4216. momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  4217. momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  4218. momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  4219. momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone);
  4220. var momentPrototype = momentPrototype__proto;
  4221. function moment__createUnix (input) {
  4222. return local__createLocal(input * 1000);
  4223. }
  4224. function moment__createInZone () {
  4225. return local__createLocal.apply(null, arguments).parseZone();
  4226. }
  4227. var defaultCalendar = {
  4228. sameDay : '[Today at] LT',
  4229. nextDay : '[Tomorrow at] LT',
  4230. nextWeek : 'dddd [at] LT',
  4231. lastDay : '[Yesterday at] LT',
  4232. lastWeek : '[Last] dddd [at] LT',
  4233. sameElse : 'L'
  4234. };
  4235. function locale_calendar__calendar (key, mom, now) {
  4236. var output = this._calendar[key];
  4237. return isFunction(output) ? output.call(mom, now) : output;
  4238. }
  4239. var defaultLongDateFormat = {
  4240. LTS : 'h:mm:ss A',
  4241. LT : 'h:mm A',
  4242. L : 'MM/DD/YYYY',
  4243. LL : 'MMMM D, YYYY',
  4244. LLL : 'MMMM D, YYYY h:mm A',
  4245. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  4246. };
  4247. function longDateFormat (key) {
  4248. var format = this._longDateFormat[key],
  4249. formatUpper = this._longDateFormat[key.toUpperCase()];
  4250. if (format || !formatUpper) {
  4251. return format;
  4252. }
  4253. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  4254. return val.slice(1);
  4255. });
  4256. return this._longDateFormat[key];
  4257. }
  4258. var defaultInvalidDate = 'Invalid date';
  4259. function invalidDate () {
  4260. return this._invalidDate;
  4261. }
  4262. var defaultOrdinal = '%d';
  4263. var defaultOrdinalParse = /\d{1,2}/;
  4264. function ordinal (number) {
  4265. return this._ordinal.replace('%d', number);
  4266. }
  4267. function preParsePostFormat (string) {
  4268. return string;
  4269. }
  4270. var defaultRelativeTime = {
  4271. future : 'in %s',
  4272. past : '%s ago',
  4273. s : 'a few seconds',
  4274. m : 'a minute',
  4275. mm : '%d minutes',
  4276. h : 'an hour',
  4277. hh : '%d hours',
  4278. d : 'a day',
  4279. dd : '%d days',
  4280. M : 'a month',
  4281. MM : '%d months',
  4282. y : 'a year',
  4283. yy : '%d years'
  4284. };
  4285. function relative__relativeTime (number, withoutSuffix, string, isFuture) {
  4286. var output = this._relativeTime[string];
  4287. return (isFunction(output)) ?
  4288. output(number, withoutSuffix, string, isFuture) :
  4289. output.replace(/%d/i, number);
  4290. }
  4291. function pastFuture (diff, output) {
  4292. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  4293. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  4294. }
  4295. var prototype__proto = Locale.prototype;
  4296. prototype__proto._calendar = defaultCalendar;
  4297. prototype__proto.calendar = locale_calendar__calendar;
  4298. prototype__proto._longDateFormat = defaultLongDateFormat;
  4299. prototype__proto.longDateFormat = longDateFormat;
  4300. prototype__proto._invalidDate = defaultInvalidDate;
  4301. prototype__proto.invalidDate = invalidDate;
  4302. prototype__proto._ordinal = defaultOrdinal;
  4303. prototype__proto.ordinal = ordinal;
  4304. prototype__proto._ordinalParse = defaultOrdinalParse;
  4305. prototype__proto.preparse = preParsePostFormat;
  4306. prototype__proto.postformat = preParsePostFormat;
  4307. prototype__proto._relativeTime = defaultRelativeTime;
  4308. prototype__proto.relativeTime = relative__relativeTime;
  4309. prototype__proto.pastFuture = pastFuture;
  4310. prototype__proto.set = locale_set__set;
  4311. // Month
  4312. prototype__proto.months = localeMonths;
  4313. prototype__proto._months = defaultLocaleMonths;
  4314. prototype__proto.monthsShort = localeMonthsShort;
  4315. prototype__proto._monthsShort = defaultLocaleMonthsShort;
  4316. prototype__proto.monthsParse = localeMonthsParse;
  4317. prototype__proto._monthsRegex = defaultMonthsRegex;
  4318. prototype__proto.monthsRegex = monthsRegex;
  4319. prototype__proto._monthsShortRegex = defaultMonthsShortRegex;
  4320. prototype__proto.monthsShortRegex = monthsShortRegex;
  4321. // Week
  4322. prototype__proto.week = localeWeek;
  4323. prototype__proto._week = defaultLocaleWeek;
  4324. prototype__proto.firstDayOfYear = localeFirstDayOfYear;
  4325. prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;
  4326. // Day of Week
  4327. prototype__proto.weekdays = localeWeekdays;
  4328. prototype__proto._weekdays = defaultLocaleWeekdays;
  4329. prototype__proto.weekdaysMin = localeWeekdaysMin;
  4330. prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin;
  4331. prototype__proto.weekdaysShort = localeWeekdaysShort;
  4332. prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort;
  4333. prototype__proto.weekdaysParse = localeWeekdaysParse;
  4334. prototype__proto._weekdaysRegex = defaultWeekdaysRegex;
  4335. prototype__proto.weekdaysRegex = weekdaysRegex;
  4336. prototype__proto._weekdaysShortRegex = defaultWeekdaysShortRegex;
  4337. prototype__proto.weekdaysShortRegex = weekdaysShortRegex;
  4338. prototype__proto._weekdaysMinRegex = defaultWeekdaysMinRegex;
  4339. prototype__proto.weekdaysMinRegex = weekdaysMinRegex;
  4340. // Hours
  4341. prototype__proto.isPM = localeIsPM;
  4342. prototype__proto._meridiemParse = defaultLocaleMeridiemParse;
  4343. prototype__proto.meridiem = localeMeridiem;
  4344. function lists__get (format, index, field, setter) {
  4345. var locale = locale_locales__getLocale();
  4346. var utc = create_utc__createUTC().set(setter, index);
  4347. return locale[field](utc, format);
  4348. }
  4349. function listMonthsImpl (format, index, field) {
  4350. if (typeof format === 'number') {
  4351. index = format;
  4352. format = undefined;
  4353. }
  4354. format = format || '';
  4355. if (index != null) {
  4356. return lists__get(format, index, field, 'month');
  4357. }
  4358. var i;
  4359. var out = [];
  4360. for (i = 0; i < 12; i++) {
  4361. out[i] = lists__get(format, i, field, 'month');
  4362. }
  4363. return out;
  4364. }
  4365. // ()
  4366. // (5)
  4367. // (fmt, 5)
  4368. // (fmt)
  4369. // (true)
  4370. // (true, 5)
  4371. // (true, fmt, 5)
  4372. // (true, fmt)
  4373. function listWeekdaysImpl (localeSorted, format, index, field) {
  4374. if (typeof localeSorted === 'boolean') {
  4375. if (typeof format === 'number') {
  4376. index = format;
  4377. format = undefined;
  4378. }
  4379. format = format || '';
  4380. } else {
  4381. format = localeSorted;
  4382. index = format;
  4383. localeSorted = false;
  4384. if (typeof format === 'number') {
  4385. index = format;
  4386. format = undefined;
  4387. }
  4388. format = format || '';
  4389. }
  4390. var locale = locale_locales__getLocale(),
  4391. shift = localeSorted ? locale._week.dow : 0;
  4392. if (index != null) {
  4393. return lists__get(format, (index + shift) % 7, field, 'day');
  4394. }
  4395. var i;
  4396. var out = [];
  4397. for (i = 0; i < 7; i++) {
  4398. out[i] = lists__get(format, (i + shift) % 7, field, 'day');
  4399. }
  4400. return out;
  4401. }
  4402. function lists__listMonths (format, index) {
  4403. return listMonthsImpl(format, index, 'months');
  4404. }
  4405. function lists__listMonthsShort (format, index) {
  4406. return listMonthsImpl(format, index, 'monthsShort');
  4407. }
  4408. function lists__listWeekdays (localeSorted, format, index) {
  4409. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  4410. }
  4411. function lists__listWeekdaysShort (localeSorted, format, index) {
  4412. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  4413. }
  4414. function lists__listWeekdaysMin (localeSorted, format, index) {
  4415. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  4416. }
  4417. locale_locales__getSetGlobalLocale('en', {
  4418. ordinalParse: /\d{1,2}(th|st|nd|rd)/,
  4419. ordinal : function (number) {
  4420. var b = number % 10,
  4421. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  4422. (b === 1) ? 'st' :
  4423. (b === 2) ? 'nd' :
  4424. (b === 3) ? 'rd' : 'th';
  4425. return number + output;
  4426. }
  4427. });
  4428. // Side effect imports
  4429. utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale);
  4430. utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale);
  4431. var mathAbs = Math.abs;
  4432. function duration_abs__abs () {
  4433. var data = this._data;
  4434. this._milliseconds = mathAbs(this._milliseconds);
  4435. this._days = mathAbs(this._days);
  4436. this._months = mathAbs(this._months);
  4437. data.milliseconds = mathAbs(data.milliseconds);
  4438. data.seconds = mathAbs(data.seconds);
  4439. data.minutes = mathAbs(data.minutes);
  4440. data.hours = mathAbs(data.hours);
  4441. data.months = mathAbs(data.months);
  4442. data.years = mathAbs(data.years);
  4443. return this;
  4444. }
  4445. function duration_add_subtract__addSubtract (duration, input, value, direction) {
  4446. var other = create__createDuration(input, value);
  4447. duration._milliseconds += direction * other._milliseconds;
  4448. duration._days += direction * other._days;
  4449. duration._months += direction * other._months;
  4450. return duration._bubble();
  4451. }
  4452. // supports only 2.0-style add(1, 's') or add(duration)
  4453. function duration_add_subtract__add (input, value) {
  4454. return duration_add_subtract__addSubtract(this, input, value, 1);
  4455. }
  4456. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  4457. function duration_add_subtract__subtract (input, value) {
  4458. return duration_add_subtract__addSubtract(this, input, value, -1);
  4459. }
  4460. function absCeil (number) {
  4461. if (number < 0) {
  4462. return Math.floor(number);
  4463. } else {
  4464. return Math.ceil(number);
  4465. }
  4466. }
  4467. function bubble () {
  4468. var milliseconds = this._milliseconds;
  4469. var days = this._days;
  4470. var months = this._months;
  4471. var data = this._data;
  4472. var seconds, minutes, hours, years, monthsFromDays;
  4473. // if we have a mix of positive and negative values, bubble down first
  4474. // check: https://github.com/moment/moment/issues/2166
  4475. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  4476. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  4477. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  4478. days = 0;
  4479. months = 0;
  4480. }
  4481. // The following code bubbles up values, see the tests for
  4482. // examples of what that means.
  4483. data.milliseconds = milliseconds % 1000;
  4484. seconds = absFloor(milliseconds / 1000);
  4485. data.seconds = seconds % 60;
  4486. minutes = absFloor(seconds / 60);
  4487. data.minutes = minutes % 60;
  4488. hours = absFloor(minutes / 60);
  4489. data.hours = hours % 24;
  4490. days += absFloor(hours / 24);
  4491. // convert days to months
  4492. monthsFromDays = absFloor(daysToMonths(days));
  4493. months += monthsFromDays;
  4494. days -= absCeil(monthsToDays(monthsFromDays));
  4495. // 12 months -> 1 year
  4496. years = absFloor(months / 12);
  4497. months %= 12;
  4498. data.days = days;
  4499. data.months = months;
  4500. data.years = years;
  4501. return this;
  4502. }
  4503. function daysToMonths (days) {
  4504. // 400 years have 146097 days (taking into account leap year rules)
  4505. // 400 years have 12 months === 4800
  4506. return days * 4800 / 146097;
  4507. }
  4508. function monthsToDays (months) {
  4509. // the reverse of daysToMonths
  4510. return months * 146097 / 4800;
  4511. }
  4512. function as (units) {
  4513. var days;
  4514. var months;
  4515. var milliseconds = this._milliseconds;
  4516. units = normalizeUnits(units);
  4517. if (units === 'month' || units === 'year') {
  4518. days = this._days + milliseconds / 864e5;
  4519. months = this._months + daysToMonths(days);
  4520. return units === 'month' ? months : months / 12;
  4521. } else {
  4522. // handle milliseconds separately because of floating point math errors (issue #1867)
  4523. days = this._days + Math.round(monthsToDays(this._months));
  4524. switch (units) {
  4525. case 'week' : return days / 7 + milliseconds / 6048e5;
  4526. case 'day' : return days + milliseconds / 864e5;
  4527. case 'hour' : return days * 24 + milliseconds / 36e5;
  4528. case 'minute' : return days * 1440 + milliseconds / 6e4;
  4529. case 'second' : return days * 86400 + milliseconds / 1000;
  4530. // Math.floor prevents floating point math errors here
  4531. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  4532. default: throw new Error('Unknown unit ' + units);
  4533. }
  4534. }
  4535. }
  4536. // TODO: Use this.as('ms')?
  4537. function duration_as__valueOf () {
  4538. return (
  4539. this._milliseconds +
  4540. this._days * 864e5 +
  4541. (this._months % 12) * 2592e6 +
  4542. toInt(this._months / 12) * 31536e6
  4543. );
  4544. }
  4545. function makeAs (alias) {
  4546. return function () {
  4547. return this.as(alias);
  4548. };
  4549. }
  4550. var asMilliseconds = makeAs('ms');
  4551. var asSeconds = makeAs('s');
  4552. var asMinutes = makeAs('m');
  4553. var asHours = makeAs('h');
  4554. var asDays = makeAs('d');
  4555. var asWeeks = makeAs('w');
  4556. var asMonths = makeAs('M');
  4557. var asYears = makeAs('y');
  4558. function duration_get__get (units) {
  4559. units = normalizeUnits(units);
  4560. return this[units + 's']();
  4561. }
  4562. function makeGetter(name) {
  4563. return function () {
  4564. return this._data[name];
  4565. };
  4566. }
  4567. var milliseconds = makeGetter('milliseconds');
  4568. var seconds = makeGetter('seconds');
  4569. var minutes = makeGetter('minutes');
  4570. var hours = makeGetter('hours');
  4571. var days = makeGetter('days');
  4572. var months = makeGetter('months');
  4573. var years = makeGetter('years');
  4574. function weeks () {
  4575. return absFloor(this.days() / 7);
  4576. }
  4577. var round = Math.round;
  4578. var thresholds = {
  4579. s: 45, // seconds to minute
  4580. m: 45, // minutes to hour
  4581. h: 22, // hours to day
  4582. d: 26, // days to month
  4583. M: 11 // months to year
  4584. };
  4585. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  4586. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  4587. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  4588. }
  4589. function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) {
  4590. var duration = create__createDuration(posNegDuration).abs();
  4591. var seconds = round(duration.as('s'));
  4592. var minutes = round(duration.as('m'));
  4593. var hours = round(duration.as('h'));
  4594. var days = round(duration.as('d'));
  4595. var months = round(duration.as('M'));
  4596. var years = round(duration.as('y'));
  4597. var a = seconds < thresholds.s && ['s', seconds] ||
  4598. minutes <= 1 && ['m'] ||
  4599. minutes < thresholds.m && ['mm', minutes] ||
  4600. hours <= 1 && ['h'] ||
  4601. hours < thresholds.h && ['hh', hours] ||
  4602. days <= 1 && ['d'] ||
  4603. days < thresholds.d && ['dd', days] ||
  4604. months <= 1 && ['M'] ||
  4605. months < thresholds.M && ['MM', months] ||
  4606. years <= 1 && ['y'] || ['yy', years];
  4607. a[2] = withoutSuffix;
  4608. a[3] = +posNegDuration > 0;
  4609. a[4] = locale;
  4610. return substituteTimeAgo.apply(null, a);
  4611. }
  4612. // This function allows you to set a threshold for relative time strings
  4613. function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) {
  4614. if (thresholds[threshold] === undefined) {
  4615. return false;
  4616. }
  4617. if (limit === undefined) {
  4618. return thresholds[threshold];
  4619. }
  4620. thresholds[threshold] = limit;
  4621. return true;
  4622. }
  4623. function humanize (withSuffix) {
  4624. var locale = this.localeData();
  4625. var output = duration_humanize__relativeTime(this, !withSuffix, locale);
  4626. if (withSuffix) {
  4627. output = locale.pastFuture(+this, output);
  4628. }
  4629. return locale.postformat(output);
  4630. }
  4631. var iso_string__abs = Math.abs;
  4632. function iso_string__toISOString() {
  4633. // for ISO strings we do not use the normal bubbling rules:
  4634. // * milliseconds bubble up until they become hours
  4635. // * days do not bubble at all
  4636. // * months bubble up until they become years
  4637. // This is because there is no context-free conversion between hours and days
  4638. // (think of clock changes)
  4639. // and also not between days and months (28-31 days per month)
  4640. var seconds = iso_string__abs(this._milliseconds) / 1000;
  4641. var days = iso_string__abs(this._days);
  4642. var months = iso_string__abs(this._months);
  4643. var minutes, hours, years;
  4644. // 3600 seconds -> 60 minutes -> 1 hour
  4645. minutes = absFloor(seconds / 60);
  4646. hours = absFloor(minutes / 60);
  4647. seconds %= 60;
  4648. minutes %= 60;
  4649. // 12 months -> 1 year
  4650. years = absFloor(months / 12);
  4651. months %= 12;
  4652. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  4653. var Y = years;
  4654. var M = months;
  4655. var D = days;
  4656. var h = hours;
  4657. var m = minutes;
  4658. var s = seconds;
  4659. var total = this.asSeconds();
  4660. if (!total) {
  4661. // this is the same as C#'s (Noda) and python (isodate)...
  4662. // but not other JS (goog.date)
  4663. return 'P0D';
  4664. }
  4665. return (total < 0 ? '-' : '') +
  4666. 'P' +
  4667. (Y ? Y + 'Y' : '') +
  4668. (M ? M + 'M' : '') +
  4669. (D ? D + 'D' : '') +
  4670. ((h || m || s) ? 'T' : '') +
  4671. (h ? h + 'H' : '') +
  4672. (m ? m + 'M' : '') +
  4673. (s ? s + 'S' : '');
  4674. }
  4675. var duration_prototype__proto = Duration.prototype;
  4676. duration_prototype__proto.abs = duration_abs__abs;
  4677. duration_prototype__proto.add = duration_add_subtract__add;
  4678. duration_prototype__proto.subtract = duration_add_subtract__subtract;
  4679. duration_prototype__proto.as = as;
  4680. duration_prototype__proto.asMilliseconds = asMilliseconds;
  4681. duration_prototype__proto.asSeconds = asSeconds;
  4682. duration_prototype__proto.asMinutes = asMinutes;
  4683. duration_prototype__proto.asHours = asHours;
  4684. duration_prototype__proto.asDays = asDays;
  4685. duration_prototype__proto.asWeeks = asWeeks;
  4686. duration_prototype__proto.asMonths = asMonths;
  4687. duration_prototype__proto.asYears = asYears;
  4688. duration_prototype__proto.valueOf = duration_as__valueOf;
  4689. duration_prototype__proto._bubble = bubble;
  4690. duration_prototype__proto.get = duration_get__get;
  4691. duration_prototype__proto.milliseconds = milliseconds;
  4692. duration_prototype__proto.seconds = seconds;
  4693. duration_prototype__proto.minutes = minutes;
  4694. duration_prototype__proto.hours = hours;
  4695. duration_prototype__proto.days = days;
  4696. duration_prototype__proto.weeks = weeks;
  4697. duration_prototype__proto.months = months;
  4698. duration_prototype__proto.years = years;
  4699. duration_prototype__proto.humanize = humanize;
  4700. duration_prototype__proto.toISOString = iso_string__toISOString;
  4701. duration_prototype__proto.toString = iso_string__toISOString;
  4702. duration_prototype__proto.toJSON = iso_string__toISOString;
  4703. duration_prototype__proto.locale = locale;
  4704. duration_prototype__proto.localeData = localeData;
  4705. // Deprecations
  4706. duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
  4707. duration_prototype__proto.lang = lang;
  4708. // Side effect imports
  4709. // FORMATTING
  4710. addFormatToken('X', 0, 0, 'unix');
  4711. addFormatToken('x', 0, 0, 'valueOf');
  4712. // PARSING
  4713. addRegexToken('x', matchSigned);
  4714. addRegexToken('X', matchTimestamp);
  4715. addParseToken('X', function (input, array, config) {
  4716. config._d = new Date(parseFloat(input, 10) * 1000);
  4717. });
  4718. addParseToken('x', function (input, array, config) {
  4719. config._d = new Date(toInt(input));
  4720. });
  4721. // Side effect imports
  4722. utils_hooks__hooks.version = '2.13.0';
  4723. setHookCallback(local__createLocal);
  4724. utils_hooks__hooks.fn = momentPrototype;
  4725. utils_hooks__hooks.min = min;
  4726. utils_hooks__hooks.max = max;
  4727. utils_hooks__hooks.now = now;
  4728. utils_hooks__hooks.utc = create_utc__createUTC;
  4729. utils_hooks__hooks.unix = moment__createUnix;
  4730. utils_hooks__hooks.months = lists__listMonths;
  4731. utils_hooks__hooks.isDate = isDate;
  4732. utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale;
  4733. utils_hooks__hooks.invalid = valid__createInvalid;
  4734. utils_hooks__hooks.duration = create__createDuration;
  4735. utils_hooks__hooks.isMoment = isMoment;
  4736. utils_hooks__hooks.weekdays = lists__listWeekdays;
  4737. utils_hooks__hooks.parseZone = moment__createInZone;
  4738. utils_hooks__hooks.localeData = locale_locales__getLocale;
  4739. utils_hooks__hooks.isDuration = isDuration;
  4740. utils_hooks__hooks.monthsShort = lists__listMonthsShort;
  4741. utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin;
  4742. utils_hooks__hooks.defineLocale = defineLocale;
  4743. utils_hooks__hooks.updateLocale = updateLocale;
  4744. utils_hooks__hooks.locales = locale_locales__listLocales;
  4745. utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort;
  4746. utils_hooks__hooks.normalizeUnits = normalizeUnits;
  4747. utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold;
  4748. utils_hooks__hooks.prototype = momentPrototype;
  4749. var _moment = utils_hooks__hooks;
  4750. return _moment;
  4751. }));
  4752. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)(module)))
  4753. /***/ },
  4754. /* 4 */
  4755. /***/ function(module, exports) {
  4756. module.exports = function(module) {
  4757. if(!module.webpackPolyfill) {
  4758. module.deprecate = function() {};
  4759. module.paths = [];
  4760. // module.parent = undefined by default
  4761. module.children = [];
  4762. module.webpackPolyfill = 1;
  4763. }
  4764. return module;
  4765. }
  4766. /***/ },
  4767. /* 5 */
  4768. /***/ function(module, exports) {
  4769. function webpackContext(req) {
  4770. throw new Error("Cannot find module '" + req + "'.");
  4771. }
  4772. webpackContext.keys = function() { return []; };
  4773. webpackContext.resolve = webpackContext;
  4774. module.exports = webpackContext;
  4775. webpackContext.id = 5;
  4776. /***/ },
  4777. /* 6 */
  4778. /***/ function(module, exports) {
  4779. /* WEBPACK VAR INJECTION */(function(global) {'use strict';
  4780. var _rng;
  4781. var globalVar = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null;
  4782. if (globalVar && globalVar.crypto && crypto.getRandomValues) {
  4783. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  4784. // Moderately fast, high quality
  4785. var _rnds8 = new Uint8Array(16);
  4786. _rng = function whatwgRNG() {
  4787. crypto.getRandomValues(_rnds8);
  4788. return _rnds8;
  4789. };
  4790. }
  4791. if (!_rng) {
  4792. // Math.random()-based (RNG)
  4793. //
  4794. // If all else fails, use Math.random(). It's fast, but is of unspecified
  4795. // quality.
  4796. var _rnds = new Array(16);
  4797. _rng = function _rng() {
  4798. for (var i = 0, r; i < 16; i++) {
  4799. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  4800. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  4801. }
  4802. return _rnds;
  4803. };
  4804. }
  4805. // uuid.js
  4806. //
  4807. // Copyright (c) 2010-2012 Robert Kieffer
  4808. // MIT License - http://opensource.org/licenses/mit-license.php
  4809. // Unique ID creation requires a high quality random # generator. We feature
  4810. // detect to determine the best RNG source, normalizing to a function that
  4811. // returns 128-bits of randomness, since that's what's usually required
  4812. //var _rng = require('./rng');
  4813. // Maps for number <-> hex string conversion
  4814. var _byteToHex = [];
  4815. var _hexToByte = {};
  4816. for (var i = 0; i < 256; i++) {
  4817. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  4818. _hexToByte[_byteToHex[i]] = i;
  4819. }
  4820. // **`parse()` - Parse a UUID into it's component bytes**
  4821. function parse(s, buf, offset) {
  4822. var i = buf && offset || 0,
  4823. ii = 0;
  4824. buf = buf || [];
  4825. s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
  4826. if (ii < 16) {
  4827. // Don't overflow!
  4828. buf[i + ii++] = _hexToByte[oct];
  4829. }
  4830. });
  4831. // Zero out remaining bytes if string was short
  4832. while (ii < 16) {
  4833. buf[i + ii++] = 0;
  4834. }
  4835. return buf;
  4836. }
  4837. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  4838. function unparse(buf, offset) {
  4839. var i = offset || 0,
  4840. bth = _byteToHex;
  4841. return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]];
  4842. }
  4843. // **`v1()` - Generate time-based UUID**
  4844. //
  4845. // Inspired by https://github.com/LiosK/UUID.js
  4846. // and http://docs.python.org/library/uuid.html
  4847. // random #'s we need to init node and clockseq
  4848. var _seedBytes = _rng();
  4849. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  4850. var _nodeId = [_seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]];
  4851. // Per 4.2.2, randomize (14 bit) clockseq
  4852. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  4853. // Previous uuid creation time
  4854. var _lastMSecs = 0,
  4855. _lastNSecs = 0;
  4856. // See https://github.com/broofa/node-uuid for API details
  4857. function v1(options, buf, offset) {
  4858. var i = buf && offset || 0;
  4859. var b = buf || [];
  4860. options = options || {};
  4861. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  4862. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  4863. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  4864. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  4865. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  4866. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  4867. // Per 4.2.1.2, use count of uuid's generated during the current clock
  4868. // cycle to simulate higher resolution clock
  4869. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  4870. // Time since last uuid creation (in msecs)
  4871. var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;
  4872. // Per 4.2.1.2, Bump clockseq on clock regression
  4873. if (dt < 0 && options.clockseq === undefined) {
  4874. clockseq = clockseq + 1 & 0x3fff;
  4875. }
  4876. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  4877. // time interval
  4878. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  4879. nsecs = 0;
  4880. }
  4881. // Per 4.2.1.2 Throw error if too many uuids are requested
  4882. if (nsecs >= 10000) {
  4883. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  4884. }
  4885. _lastMSecs = msecs;
  4886. _lastNSecs = nsecs;
  4887. _clockseq = clockseq;
  4888. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  4889. msecs += 12219292800000;
  4890. // `time_low`
  4891. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  4892. b[i++] = tl >>> 24 & 0xff;
  4893. b[i++] = tl >>> 16 & 0xff;
  4894. b[i++] = tl >>> 8 & 0xff;
  4895. b[i++] = tl & 0xff;
  4896. // `time_mid`
  4897. var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  4898. b[i++] = tmh >>> 8 & 0xff;
  4899. b[i++] = tmh & 0xff;
  4900. // `time_high_and_version`
  4901. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  4902. b[i++] = tmh >>> 16 & 0xff;
  4903. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  4904. b[i++] = clockseq >>> 8 | 0x80;
  4905. // `clock_seq_low`
  4906. b[i++] = clockseq & 0xff;
  4907. // `node`
  4908. var node = options.node || _nodeId;
  4909. for (var n = 0; n < 6; n++) {
  4910. b[i + n] = node[n];
  4911. }
  4912. return buf ? buf : unparse(b);
  4913. }
  4914. // **`v4()` - Generate random UUID**
  4915. // See https://github.com/broofa/node-uuid for API details
  4916. function v4(options, buf, offset) {
  4917. // Deprecated - 'format' argument, as supported in v1.2
  4918. var i = buf && offset || 0;
  4919. if (typeof options == 'string') {
  4920. buf = options == 'binary' ? new Array(16) : null;
  4921. options = null;
  4922. }
  4923. options = options || {};
  4924. var rnds = options.random || (options.rng || _rng)();
  4925. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  4926. rnds[6] = rnds[6] & 0x0f | 0x40;
  4927. rnds[8] = rnds[8] & 0x3f | 0x80;
  4928. // Copy bytes to buffer, if provided
  4929. if (buf) {
  4930. for (var ii = 0; ii < 16; ii++) {
  4931. buf[i + ii] = rnds[ii];
  4932. }
  4933. }
  4934. return buf || unparse(rnds);
  4935. }
  4936. // Export public API
  4937. var uuid = v4;
  4938. uuid.v1 = v1;
  4939. uuid.v4 = v4;
  4940. uuid.parse = parse;
  4941. uuid.unparse = unparse;
  4942. module.exports = uuid;
  4943. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  4944. /***/ },
  4945. /* 7 */
  4946. /***/ function(module, exports, __webpack_require__) {
  4947. 'use strict';
  4948. // utils
  4949. exports.util = __webpack_require__(1);
  4950. exports.DOMutil = __webpack_require__(8);
  4951. // data
  4952. exports.DataSet = __webpack_require__(9);
  4953. exports.DataView = __webpack_require__(11);
  4954. exports.Queue = __webpack_require__(10);
  4955. // Graph3d
  4956. exports.Graph3d = __webpack_require__(12);
  4957. exports.graph3d = {
  4958. Camera: __webpack_require__(16),
  4959. Filter: __webpack_require__(17),
  4960. Point2d: __webpack_require__(15),
  4961. Point3d: __webpack_require__(14),
  4962. Slider: __webpack_require__(18),
  4963. StepNumber: __webpack_require__(19)
  4964. };
  4965. // bundled external libraries
  4966. exports.moment = __webpack_require__(2);
  4967. exports.Hammer = __webpack_require__(20);
  4968. exports.keycharm = __webpack_require__(23);
  4969. /***/ },
  4970. /* 8 */
  4971. /***/ function(module, exports) {
  4972. 'use strict';
  4973. // DOM utility methods
  4974. /**
  4975. * this prepares the JSON container for allocating SVG elements
  4976. * @param JSONcontainer
  4977. * @private
  4978. */
  4979. exports.prepareElements = function (JSONcontainer) {
  4980. // cleanup the redundant svgElements;
  4981. for (var elementType in JSONcontainer) {
  4982. if (JSONcontainer.hasOwnProperty(elementType)) {
  4983. JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
  4984. JSONcontainer[elementType].used = [];
  4985. }
  4986. }
  4987. };
  4988. /**
  4989. * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
  4990. * which to remove the redundant elements.
  4991. *
  4992. * @param JSONcontainer
  4993. * @private
  4994. */
  4995. exports.cleanupElements = function (JSONcontainer) {
  4996. // cleanup the redundant svgElements;
  4997. for (var elementType in JSONcontainer) {
  4998. if (JSONcontainer.hasOwnProperty(elementType)) {
  4999. if (JSONcontainer[elementType].redundant) {
  5000. for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
  5001. JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
  5002. }
  5003. JSONcontainer[elementType].redundant = [];
  5004. }
  5005. }
  5006. }
  5007. };
  5008. /**
  5009. * Ensures that all elements are removed first up so they can be recreated cleanly
  5010. * @param JSONcontainer
  5011. */
  5012. exports.resetElements = function (JSONcontainer) {
  5013. exports.prepareElements(JSONcontainer);
  5014. exports.cleanupElements(JSONcontainer);
  5015. exports.prepareElements(JSONcontainer);
  5016. };
  5017. /**
  5018. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  5019. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  5020. *
  5021. * @param elementType
  5022. * @param JSONcontainer
  5023. * @param svgContainer
  5024. * @returns {*}
  5025. * @private
  5026. */
  5027. exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
  5028. var element;
  5029. // allocate SVG element, if it doesnt yet exist, create one.
  5030. if (JSONcontainer.hasOwnProperty(elementType)) {
  5031. // this element has been created before
  5032. // check if there is an redundant element
  5033. if (JSONcontainer[elementType].redundant.length > 0) {
  5034. element = JSONcontainer[elementType].redundant[0];
  5035. JSONcontainer[elementType].redundant.shift();
  5036. } else {
  5037. // create a new element and add it to the SVG
  5038. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  5039. svgContainer.appendChild(element);
  5040. }
  5041. } else {
  5042. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  5043. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  5044. JSONcontainer[elementType] = { used: [], redundant: [] };
  5045. svgContainer.appendChild(element);
  5046. }
  5047. JSONcontainer[elementType].used.push(element);
  5048. return element;
  5049. };
  5050. /**
  5051. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  5052. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  5053. *
  5054. * @param elementType
  5055. * @param JSONcontainer
  5056. * @param DOMContainer
  5057. * @returns {*}
  5058. * @private
  5059. */
  5060. exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
  5061. var element;
  5062. // allocate DOM element, if it doesnt yet exist, create one.
  5063. if (JSONcontainer.hasOwnProperty(elementType)) {
  5064. // this element has been created before
  5065. // check if there is an redundant element
  5066. if (JSONcontainer[elementType].redundant.length > 0) {
  5067. element = JSONcontainer[elementType].redundant[0];
  5068. JSONcontainer[elementType].redundant.shift();
  5069. } else {
  5070. // create a new element and add it to the SVG
  5071. element = document.createElement(elementType);
  5072. if (insertBefore !== undefined) {
  5073. DOMContainer.insertBefore(element, insertBefore);
  5074. } else {
  5075. DOMContainer.appendChild(element);
  5076. }
  5077. }
  5078. } else {
  5079. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  5080. element = document.createElement(elementType);
  5081. JSONcontainer[elementType] = { used: [], redundant: [] };
  5082. if (insertBefore !== undefined) {
  5083. DOMContainer.insertBefore(element, insertBefore);
  5084. } else {
  5085. DOMContainer.appendChild(element);
  5086. }
  5087. }
  5088. JSONcontainer[elementType].used.push(element);
  5089. return element;
  5090. };
  5091. /**
  5092. * Draw a point object. This is a separate function because it can also be called by the legend.
  5093. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
  5094. * as well.
  5095. *
  5096. * @param x
  5097. * @param y
  5098. * @param groupTemplate: A template containing the necessary information to draw the datapoint e.g., {style: 'circle', size: 5, className: 'className' }
  5099. * @param JSONcontainer
  5100. * @param svgContainer
  5101. * @param labelObj
  5102. * @returns {*}
  5103. */
  5104. exports.drawPoint = function (x, y, groupTemplate, JSONcontainer, svgContainer, labelObj) {
  5105. var point;
  5106. if (groupTemplate.style == 'circle') {
  5107. point = exports.getSVGElement('circle', JSONcontainer, svgContainer);
  5108. point.setAttributeNS(null, "cx", x);
  5109. point.setAttributeNS(null, "cy", y);
  5110. point.setAttributeNS(null, "r", 0.5 * groupTemplate.size);
  5111. } else {
  5112. point = exports.getSVGElement('rect', JSONcontainer, svgContainer);
  5113. point.setAttributeNS(null, "x", x - 0.5 * groupTemplate.size);
  5114. point.setAttributeNS(null, "y", y - 0.5 * groupTemplate.size);
  5115. point.setAttributeNS(null, "width", groupTemplate.size);
  5116. point.setAttributeNS(null, "height", groupTemplate.size);
  5117. }
  5118. if (groupTemplate.styles !== undefined) {
  5119. point.setAttributeNS(null, "style", groupTemplate.styles);
  5120. }
  5121. point.setAttributeNS(null, "class", groupTemplate.className + " vis-point");
  5122. //handle label
  5123. if (labelObj) {
  5124. var label = exports.getSVGElement('text', JSONcontainer, svgContainer);
  5125. if (labelObj.xOffset) {
  5126. x = x + labelObj.xOffset;
  5127. }
  5128. if (labelObj.yOffset) {
  5129. y = y + labelObj.yOffset;
  5130. }
  5131. if (labelObj.content) {
  5132. label.textContent = labelObj.content;
  5133. }
  5134. if (labelObj.className) {
  5135. label.setAttributeNS(null, "class", labelObj.className + " vis-label");
  5136. }
  5137. label.setAttributeNS(null, "x", x);
  5138. label.setAttributeNS(null, "y", y);
  5139. }
  5140. return point;
  5141. };
  5142. /**
  5143. * draw a bar SVG element centered on the X coordinate
  5144. *
  5145. * @param x
  5146. * @param y
  5147. * @param className
  5148. */
  5149. exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer, style) {
  5150. if (height != 0) {
  5151. if (height < 0) {
  5152. height *= -1;
  5153. y -= height;
  5154. }
  5155. var rect = exports.getSVGElement('rect', JSONcontainer, svgContainer);
  5156. rect.setAttributeNS(null, "x", x - 0.5 * width);
  5157. rect.setAttributeNS(null, "y", y);
  5158. rect.setAttributeNS(null, "width", width);
  5159. rect.setAttributeNS(null, "height", height);
  5160. rect.setAttributeNS(null, "class", className);
  5161. if (style) {
  5162. rect.setAttributeNS(null, "style", style);
  5163. }
  5164. }
  5165. };
  5166. /***/ },
  5167. /* 9 */
  5168. /***/ function(module, exports, __webpack_require__) {
  5169. 'use strict';
  5170. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  5171. var util = __webpack_require__(1);
  5172. var Queue = __webpack_require__(10);
  5173. /**
  5174. * DataSet
  5175. *
  5176. * Usage:
  5177. * var dataSet = new DataSet({
  5178. * fieldId: '_id',
  5179. * type: {
  5180. * // ...
  5181. * }
  5182. * });
  5183. *
  5184. * dataSet.add(item);
  5185. * dataSet.add(data);
  5186. * dataSet.update(item);
  5187. * dataSet.update(data);
  5188. * dataSet.remove(id);
  5189. * dataSet.remove(ids);
  5190. * var data = dataSet.get();
  5191. * var data = dataSet.get(id);
  5192. * var data = dataSet.get(ids);
  5193. * var data = dataSet.get(ids, options, data);
  5194. * dataSet.clear();
  5195. *
  5196. * A data set can:
  5197. * - add/remove/update data
  5198. * - gives triggers upon changes in the data
  5199. * - can import/export data in various data formats
  5200. *
  5201. * @param {Array} [data] Optional array with initial data
  5202. * @param {Object} [options] Available options:
  5203. * {String} fieldId Field name of the id in the
  5204. * items, 'id' by default.
  5205. * {Object.<String, String} type
  5206. * A map with field names as key,
  5207. * and the field type as value.
  5208. * {Object} queue Queue changes to the DataSet,
  5209. * flush them all at once.
  5210. * Queue options:
  5211. * - {number} delay Delay in ms, null by default
  5212. * - {number} max Maximum number of entries in the queue, Infinity by default
  5213. * @constructor DataSet
  5214. */
  5215. // TODO: add a DataSet constructor DataSet(data, options)
  5216. function DataSet(data, options) {
  5217. // correctly read optional arguments
  5218. if (data && !Array.isArray(data)) {
  5219. options = data;
  5220. data = null;
  5221. }
  5222. this._options = options || {};
  5223. this._data = {}; // map with data indexed by id
  5224. this.length = 0; // number of items in the DataSet
  5225. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  5226. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  5227. // all variants of a Date are internally stored as Date, so we can convert
  5228. // from everything to everything (also from ISODate to Number for example)
  5229. if (this._options.type) {
  5230. var fields = Object.keys(this._options.type);
  5231. for (var i = 0, len = fields.length; i < len; i++) {
  5232. var field = fields[i];
  5233. var value = this._options.type[field];
  5234. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  5235. this._type[field] = 'Date';
  5236. } else {
  5237. this._type[field] = value;
  5238. }
  5239. }
  5240. }
  5241. // TODO: deprecated since version 1.1.1 (or 2.0.0?)
  5242. if (this._options.convert) {
  5243. throw new Error('Option "convert" is deprecated. Use "type" instead.');
  5244. }
  5245. this._subscribers = {}; // event subscribers
  5246. // add initial data when provided
  5247. if (data) {
  5248. this.add(data);
  5249. }
  5250. this.setOptions(options);
  5251. }
  5252. /**
  5253. * @param {Object} [options] Available options:
  5254. * {Object} queue Queue changes to the DataSet,
  5255. * flush them all at once.
  5256. * Queue options:
  5257. * - {number} delay Delay in ms, null by default
  5258. * - {number} max Maximum number of entries in the queue, Infinity by default
  5259. * @param options
  5260. */
  5261. DataSet.prototype.setOptions = function (options) {
  5262. if (options && options.queue !== undefined) {
  5263. if (options.queue === false) {
  5264. // delete queue if loaded
  5265. if (this._queue) {
  5266. this._queue.destroy();
  5267. delete this._queue;
  5268. }
  5269. } else {
  5270. // create queue and update its options
  5271. if (!this._queue) {
  5272. this._queue = Queue.extend(this, {
  5273. replace: ['add', 'update', 'remove']
  5274. });
  5275. }
  5276. if (_typeof(options.queue) === 'object') {
  5277. this._queue.setOptions(options.queue);
  5278. }
  5279. }
  5280. }
  5281. };
  5282. /**
  5283. * Subscribe to an event, add an event listener
  5284. * @param {String} event Event name. Available events: 'put', 'update',
  5285. * 'remove'
  5286. * @param {function} callback Callback method. Called with three parameters:
  5287. * {String} event
  5288. * {Object | null} params
  5289. * {String | Number} senderId
  5290. */
  5291. DataSet.prototype.on = function (event, callback) {
  5292. var subscribers = this._subscribers[event];
  5293. if (!subscribers) {
  5294. subscribers = [];
  5295. this._subscribers[event] = subscribers;
  5296. }
  5297. subscribers.push({
  5298. callback: callback
  5299. });
  5300. };
  5301. // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0)
  5302. DataSet.prototype.subscribe = function () {
  5303. throw new Error('DataSet.subscribe is deprecated. Use DataSet.on instead.');
  5304. };
  5305. /**
  5306. * Unsubscribe from an event, remove an event listener
  5307. * @param {String} event
  5308. * @param {function} callback
  5309. */
  5310. DataSet.prototype.off = function (event, callback) {
  5311. var subscribers = this._subscribers[event];
  5312. if (subscribers) {
  5313. this._subscribers[event] = subscribers.filter(function (listener) {
  5314. return listener.callback != callback;
  5315. });
  5316. }
  5317. };
  5318. // TODO: remove this deprecated function some day (replaced with `on` since version 0.5, deprecated since v4.0)
  5319. DataSet.prototype.unsubscribe = function () {
  5320. throw new Error('DataSet.unsubscribe is deprecated. Use DataSet.off instead.');
  5321. };
  5322. /**
  5323. * Trigger an event
  5324. * @param {String} event
  5325. * @param {Object | null} params
  5326. * @param {String} [senderId] Optional id of the sender.
  5327. * @private
  5328. */
  5329. DataSet.prototype._trigger = function (event, params, senderId) {
  5330. if (event == '*') {
  5331. throw new Error('Cannot trigger event *');
  5332. }
  5333. var subscribers = [];
  5334. if (event in this._subscribers) {
  5335. subscribers = subscribers.concat(this._subscribers[event]);
  5336. }
  5337. if ('*' in this._subscribers) {
  5338. subscribers = subscribers.concat(this._subscribers['*']);
  5339. }
  5340. for (var i = 0, len = subscribers.length; i < len; i++) {
  5341. var subscriber = subscribers[i];
  5342. if (subscriber.callback) {
  5343. subscriber.callback(event, params, senderId || null);
  5344. }
  5345. }
  5346. };
  5347. /**
  5348. * Add data.
  5349. * Adding an item will fail when there already is an item with the same id.
  5350. * @param {Object | Array} data
  5351. * @param {String} [senderId] Optional sender id
  5352. * @return {Array} addedIds Array with the ids of the added items
  5353. */
  5354. DataSet.prototype.add = function (data, senderId) {
  5355. var addedIds = [],
  5356. id,
  5357. me = this;
  5358. if (Array.isArray(data)) {
  5359. // Array
  5360. for (var i = 0, len = data.length; i < len; i++) {
  5361. id = me._addItem(data[i]);
  5362. addedIds.push(id);
  5363. }
  5364. } else if (data instanceof Object) {
  5365. // Single item
  5366. id = me._addItem(data);
  5367. addedIds.push(id);
  5368. } else {
  5369. throw new Error('Unknown dataType');
  5370. }
  5371. if (addedIds.length) {
  5372. this._trigger('add', { items: addedIds }, senderId);
  5373. }
  5374. return addedIds;
  5375. };
  5376. /**
  5377. * Update existing items. When an item does not exist, it will be created
  5378. * @param {Object | Array} data
  5379. * @param {String} [senderId] Optional sender id
  5380. * @return {Array} updatedIds The ids of the added or updated items
  5381. */
  5382. DataSet.prototype.update = function (data, senderId) {
  5383. var addedIds = [];
  5384. var updatedIds = [];
  5385. var oldData = [];
  5386. var updatedData = [];
  5387. var me = this;
  5388. var fieldId = me._fieldId;
  5389. var addOrUpdate = function addOrUpdate(item) {
  5390. var id = item[fieldId];
  5391. if (me._data[id]) {
  5392. var oldItem = util.extend({}, me._data[id]);
  5393. // update item
  5394. id = me._updateItem(item);
  5395. updatedIds.push(id);
  5396. updatedData.push(item);
  5397. oldData.push(oldItem);
  5398. } else {
  5399. // add new item
  5400. id = me._addItem(item);
  5401. addedIds.push(id);
  5402. }
  5403. };
  5404. if (Array.isArray(data)) {
  5405. // Array
  5406. for (var i = 0, len = data.length; i < len; i++) {
  5407. if (data[i] instanceof Object) {
  5408. addOrUpdate(data[i]);
  5409. } else {
  5410. console.warn('Ignoring input item, which is not an object at index ' + i);
  5411. }
  5412. }
  5413. } else if (data instanceof Object) {
  5414. // Single item
  5415. addOrUpdate(data);
  5416. } else {
  5417. throw new Error('Unknown dataType');
  5418. }
  5419. if (addedIds.length) {
  5420. this._trigger('add', { items: addedIds }, senderId);
  5421. }
  5422. if (updatedIds.length) {
  5423. var props = { items: updatedIds, oldData: oldData, data: updatedData };
  5424. // TODO: remove deprecated property 'data' some day
  5425. //Object.defineProperty(props, 'data', {
  5426. // 'get': (function() {
  5427. // console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
  5428. // return updatedData;
  5429. // }).bind(this)
  5430. //});
  5431. this._trigger('update', props, senderId);
  5432. }
  5433. return addedIds.concat(updatedIds);
  5434. };
  5435. /**
  5436. * Get a data item or multiple items.
  5437. *
  5438. * Usage:
  5439. *
  5440. * get()
  5441. * get(options: Object)
  5442. *
  5443. * get(id: Number | String)
  5444. * get(id: Number | String, options: Object)
  5445. *
  5446. * get(ids: Number[] | String[])
  5447. * get(ids: Number[] | String[], options: Object)
  5448. *
  5449. * Where:
  5450. *
  5451. * {Number | String} id The id of an item
  5452. * {Number[] | String{}} ids An array with ids of items
  5453. * {Object} options An Object with options. Available options:
  5454. * {String} [returnType] Type of data to be returned.
  5455. * Can be 'Array' (default) or 'Object'.
  5456. * {Object.<String, String>} [type]
  5457. * {String[]} [fields] field names to be returned
  5458. * {function} [filter] filter items
  5459. * {String | function} [order] Order the items by a field name or custom sort function.
  5460. * @throws Error
  5461. */
  5462. DataSet.prototype.get = function (args) {
  5463. var me = this;
  5464. // parse the arguments
  5465. var id, ids, options;
  5466. var firstType = util.getType(arguments[0]);
  5467. if (firstType == 'String' || firstType == 'Number') {
  5468. // get(id [, options])
  5469. id = arguments[0];
  5470. options = arguments[1];
  5471. } else if (firstType == 'Array') {
  5472. // get(ids [, options])
  5473. ids = arguments[0];
  5474. options = arguments[1];
  5475. } else {
  5476. // get([, options])
  5477. options = arguments[0];
  5478. }
  5479. // determine the return type
  5480. var returnType;
  5481. if (options && options.returnType) {
  5482. var allowedValues = ['Array', 'Object'];
  5483. returnType = allowedValues.indexOf(options.returnType) == -1 ? 'Array' : options.returnType;
  5484. } else {
  5485. returnType = 'Array';
  5486. }
  5487. // build options
  5488. var type = options && options.type || this._options.type;
  5489. var filter = options && options.filter;
  5490. var items = [],
  5491. item,
  5492. itemIds,
  5493. itemId,
  5494. i,
  5495. len;
  5496. // convert items
  5497. if (id != undefined) {
  5498. // return a single item
  5499. item = me._getItem(id, type);
  5500. if (item && filter && !filter(item)) {
  5501. item = null;
  5502. }
  5503. } else if (ids != undefined) {
  5504. // return a subset of items
  5505. for (i = 0, len = ids.length; i < len; i++) {
  5506. item = me._getItem(ids[i], type);
  5507. if (!filter || filter(item)) {
  5508. items.push(item);
  5509. }
  5510. }
  5511. } else {
  5512. // return all items
  5513. itemIds = Object.keys(this._data);
  5514. for (i = 0, len = itemIds.length; i < len; i++) {
  5515. itemId = itemIds[i];
  5516. item = me._getItem(itemId, type);
  5517. if (!filter || filter(item)) {
  5518. items.push(item);
  5519. }
  5520. }
  5521. }
  5522. // order the results
  5523. if (options && options.order && id == undefined) {
  5524. this._sort(items, options.order);
  5525. }
  5526. // filter fields of the items
  5527. if (options && options.fields) {
  5528. var fields = options.fields;
  5529. if (id != undefined) {
  5530. item = this._filterFields(item, fields);
  5531. } else {
  5532. for (i = 0, len = items.length; i < len; i++) {
  5533. items[i] = this._filterFields(items[i], fields);
  5534. }
  5535. }
  5536. }
  5537. // return the results
  5538. if (returnType == 'Object') {
  5539. var result = {},
  5540. resultant;
  5541. for (i = 0, len = items.length; i < len; i++) {
  5542. resultant = items[i];
  5543. result[resultant.id] = resultant;
  5544. }
  5545. return result;
  5546. } else {
  5547. if (id != undefined) {
  5548. // a single item
  5549. return item;
  5550. } else {
  5551. // just return our array
  5552. return items;
  5553. }
  5554. }
  5555. };
  5556. /**
  5557. * Get ids of all items or from a filtered set of items.
  5558. * @param {Object} [options] An Object with options. Available options:
  5559. * {function} [filter] filter items
  5560. * {String | function} [order] Order the items by
  5561. * a field name or custom sort function.
  5562. * @return {Array} ids
  5563. */
  5564. DataSet.prototype.getIds = function (options) {
  5565. var data = this._data,
  5566. filter = options && options.filter,
  5567. order = options && options.order,
  5568. type = options && options.type || this._options.type,
  5569. itemIds = Object.keys(data),
  5570. i,
  5571. len,
  5572. id,
  5573. item,
  5574. items,
  5575. ids = [];
  5576. if (filter) {
  5577. // get filtered items
  5578. if (order) {
  5579. // create ordered list
  5580. items = [];
  5581. for (i = 0, len = itemIds.length; i < len; i++) {
  5582. id = itemIds[i];
  5583. item = this._getItem(id, type);
  5584. if (filter(item)) {
  5585. items.push(item);
  5586. }
  5587. }
  5588. this._sort(items, order);
  5589. for (i = 0, len = items.length; i < len; i++) {
  5590. ids.push(items[i][this._fieldId]);
  5591. }
  5592. } else {
  5593. // create unordered list
  5594. for (i = 0, len = itemIds.length; i < len; i++) {
  5595. id = itemIds[i];
  5596. item = this._getItem(id, type);
  5597. if (filter(item)) {
  5598. ids.push(item[this._fieldId]);
  5599. }
  5600. }
  5601. }
  5602. } else {
  5603. // get all items
  5604. if (order) {
  5605. // create an ordered list
  5606. items = [];
  5607. for (i = 0, len = itemIds.length; i < len; i++) {
  5608. id = itemIds[i];
  5609. items.push(data[id]);
  5610. }
  5611. this._sort(items, order);
  5612. for (i = 0, len = items.length; i < len; i++) {
  5613. ids.push(items[i][this._fieldId]);
  5614. }
  5615. } else {
  5616. // create unordered list
  5617. for (i = 0, len = itemIds.length; i < len; i++) {
  5618. id = itemIds[i];
  5619. item = data[id];
  5620. ids.push(item[this._fieldId]);
  5621. }
  5622. }
  5623. }
  5624. return ids;
  5625. };
  5626. /**
  5627. * Returns the DataSet itself. Is overwritten for example by the DataView,
  5628. * which returns the DataSet it is connected to instead.
  5629. */
  5630. DataSet.prototype.getDataSet = function () {
  5631. return this;
  5632. };
  5633. /**
  5634. * Execute a callback function for every item in the dataset.
  5635. * @param {function} callback
  5636. * @param {Object} [options] Available options:
  5637. * {Object.<String, String>} [type]
  5638. * {String[]} [fields] filter fields
  5639. * {function} [filter] filter items
  5640. * {String | function} [order] Order the items by
  5641. * a field name or custom sort function.
  5642. */
  5643. DataSet.prototype.forEach = function (callback, options) {
  5644. var filter = options && options.filter,
  5645. type = options && options.type || this._options.type,
  5646. data = this._data,
  5647. itemIds = Object.keys(data),
  5648. i,
  5649. len,
  5650. item,
  5651. id;
  5652. if (options && options.order) {
  5653. // execute forEach on ordered list
  5654. var items = this.get(options);
  5655. for (i = 0, len = items.length; i < len; i++) {
  5656. item = items[i];
  5657. id = item[this._fieldId];
  5658. callback(item, id);
  5659. }
  5660. } else {
  5661. // unordered
  5662. for (i = 0, len = itemIds.length; i < len; i++) {
  5663. id = itemIds[i];
  5664. item = this._getItem(id, type);
  5665. if (!filter || filter(item)) {
  5666. callback(item, id);
  5667. }
  5668. }
  5669. }
  5670. };
  5671. /**
  5672. * Map every item in the dataset.
  5673. * @param {function} callback
  5674. * @param {Object} [options] Available options:
  5675. * {Object.<String, String>} [type]
  5676. * {String[]} [fields] filter fields
  5677. * {function} [filter] filter items
  5678. * {String | function} [order] Order the items by
  5679. * a field name or custom sort function.
  5680. * @return {Object[]} mappedItems
  5681. */
  5682. DataSet.prototype.map = function (callback, options) {
  5683. var filter = options && options.filter,
  5684. type = options && options.type || this._options.type,
  5685. mappedItems = [],
  5686. data = this._data,
  5687. itemIds = Object.keys(data),
  5688. i,
  5689. len,
  5690. id,
  5691. item;
  5692. // convert and filter items
  5693. for (i = 0, len = itemIds.length; i < len; i++) {
  5694. id = itemIds[i];
  5695. item = this._getItem(id, type);
  5696. if (!filter || filter(item)) {
  5697. mappedItems.push(callback(item, id));
  5698. }
  5699. }
  5700. // order items
  5701. if (options && options.order) {
  5702. this._sort(mappedItems, options.order);
  5703. }
  5704. return mappedItems;
  5705. };
  5706. /**
  5707. * Filter the fields of an item
  5708. * @param {Object | null} item
  5709. * @param {String[]} fields Field names
  5710. * @return {Object | null} filteredItem or null if no item is provided
  5711. * @private
  5712. */
  5713. DataSet.prototype._filterFields = function (item, fields) {
  5714. if (!item) {
  5715. // item is null
  5716. return item;
  5717. }
  5718. var filteredItem = {},
  5719. itemFields = Object.keys(item),
  5720. len = itemFields.length,
  5721. i,
  5722. field;
  5723. if (Array.isArray(fields)) {
  5724. for (i = 0; i < len; i++) {
  5725. field = itemFields[i];
  5726. if (fields.indexOf(field) != -1) {
  5727. filteredItem[field] = item[field];
  5728. }
  5729. }
  5730. } else {
  5731. for (i = 0; i < len; i++) {
  5732. field = itemFields[i];
  5733. if (fields.hasOwnProperty(field)) {
  5734. filteredItem[fields[field]] = item[field];
  5735. }
  5736. }
  5737. }
  5738. return filteredItem;
  5739. };
  5740. /**
  5741. * Sort the provided array with items
  5742. * @param {Object[]} items
  5743. * @param {String | function} order A field name or custom sort function.
  5744. * @private
  5745. */
  5746. DataSet.prototype._sort = function (items, order) {
  5747. if (util.isString(order)) {
  5748. // order by provided field name
  5749. var name = order; // field name
  5750. items.sort(function (a, b) {
  5751. var av = a[name];
  5752. var bv = b[name];
  5753. return av > bv ? 1 : av < bv ? -1 : 0;
  5754. });
  5755. } else if (typeof order === 'function') {
  5756. // order by sort function
  5757. items.sort(order);
  5758. }
  5759. // TODO: extend order by an Object {field:String, direction:String}
  5760. // where direction can be 'asc' or 'desc'
  5761. else {
  5762. throw new TypeError('Order must be a function or a string');
  5763. }
  5764. };
  5765. /**
  5766. * Remove an object by pointer or by id
  5767. * @param {String | Number | Object | Array} id Object or id, or an array with
  5768. * objects or ids to be removed
  5769. * @param {String} [senderId] Optional sender id
  5770. * @return {Array} removedIds
  5771. */
  5772. DataSet.prototype.remove = function (id, senderId) {
  5773. var removedIds = [],
  5774. i,
  5775. len,
  5776. removedId;
  5777. if (Array.isArray(id)) {
  5778. for (i = 0, len = id.length; i < len; i++) {
  5779. removedId = this._remove(id[i]);
  5780. if (removedId != null) {
  5781. removedIds.push(removedId);
  5782. }
  5783. }
  5784. } else {
  5785. removedId = this._remove(id);
  5786. if (removedId != null) {
  5787. removedIds.push(removedId);
  5788. }
  5789. }
  5790. if (removedIds.length) {
  5791. this._trigger('remove', { items: removedIds }, senderId);
  5792. }
  5793. return removedIds;
  5794. };
  5795. /**
  5796. * Remove an item by its id
  5797. * @param {Number | String | Object} id id or item
  5798. * @returns {Number | String | null} id
  5799. * @private
  5800. */
  5801. DataSet.prototype._remove = function (id) {
  5802. if (util.isNumber(id) || util.isString(id)) {
  5803. if (this._data[id]) {
  5804. delete this._data[id];
  5805. this.length--;
  5806. return id;
  5807. }
  5808. } else if (id instanceof Object) {
  5809. var itemId = id[this._fieldId];
  5810. if (itemId !== undefined && this._data[itemId]) {
  5811. delete this._data[itemId];
  5812. this.length--;
  5813. return itemId;
  5814. }
  5815. }
  5816. return null;
  5817. };
  5818. /**
  5819. * Clear the data
  5820. * @param {String} [senderId] Optional sender id
  5821. * @return {Array} removedIds The ids of all removed items
  5822. */
  5823. DataSet.prototype.clear = function (senderId) {
  5824. var ids = Object.keys(this._data);
  5825. this._data = {};
  5826. this.length = 0;
  5827. this._trigger('remove', { items: ids }, senderId);
  5828. return ids;
  5829. };
  5830. /**
  5831. * Find the item with maximum value of a specified field
  5832. * @param {String} field
  5833. * @return {Object | null} item Item containing max value, or null if no items
  5834. */
  5835. DataSet.prototype.max = function (field) {
  5836. var data = this._data,
  5837. itemIds = Object.keys(data),
  5838. max = null,
  5839. maxField = null,
  5840. i,
  5841. len;
  5842. for (i = 0, len = itemIds.length; i < len; i++) {
  5843. var id = itemIds[i];
  5844. var item = data[id];
  5845. var itemField = item[field];
  5846. if (itemField != null && (!max || itemField > maxField)) {
  5847. max = item;
  5848. maxField = itemField;
  5849. }
  5850. }
  5851. return max;
  5852. };
  5853. /**
  5854. * Find the item with minimum value of a specified field
  5855. * @param {String} field
  5856. * @return {Object | null} item Item containing max value, or null if no items
  5857. */
  5858. DataSet.prototype.min = function (field) {
  5859. var data = this._data,
  5860. itemIds = Object.keys(data),
  5861. min = null,
  5862. minField = null,
  5863. i,
  5864. len;
  5865. for (i = 0, len = itemIds.length; i < len; i++) {
  5866. var id = itemIds[i];
  5867. var item = data[id];
  5868. var itemField = item[field];
  5869. if (itemField != null && (!min || itemField < minField)) {
  5870. min = item;
  5871. minField = itemField;
  5872. }
  5873. }
  5874. return min;
  5875. };
  5876. /**
  5877. * Find all distinct values of a specified field
  5878. * @param {String} field
  5879. * @return {Array} values Array containing all distinct values. If data items
  5880. * do not contain the specified field are ignored.
  5881. * The returned array is unordered.
  5882. */
  5883. DataSet.prototype.distinct = function (field) {
  5884. var data = this._data;
  5885. var itemIds = Object.keys(data);
  5886. var values = [];
  5887. var fieldType = this._options.type && this._options.type[field] || null;
  5888. var count = 0;
  5889. var i, j, len;
  5890. for (i = 0, len = itemIds.length; i < len; i++) {
  5891. var id = itemIds[i];
  5892. var item = data[id];
  5893. var value = item[field];
  5894. var exists = false;
  5895. for (j = 0; j < count; j++) {
  5896. if (values[j] == value) {
  5897. exists = true;
  5898. break;
  5899. }
  5900. }
  5901. if (!exists && value !== undefined) {
  5902. values[count] = value;
  5903. count++;
  5904. }
  5905. }
  5906. if (fieldType) {
  5907. for (i = 0, len = values.length; i < len; i++) {
  5908. values[i] = util.convert(values[i], fieldType);
  5909. }
  5910. }
  5911. return values;
  5912. };
  5913. /**
  5914. * Add a single item. Will fail when an item with the same id already exists.
  5915. * @param {Object} item
  5916. * @return {String} id
  5917. * @private
  5918. */
  5919. DataSet.prototype._addItem = function (item) {
  5920. var id = item[this._fieldId];
  5921. if (id != undefined) {
  5922. // check whether this id is already taken
  5923. if (this._data[id]) {
  5924. // item already exists
  5925. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  5926. }
  5927. } else {
  5928. // generate an id
  5929. id = util.randomUUID();
  5930. item[this._fieldId] = id;
  5931. }
  5932. var d = {},
  5933. fields = Object.keys(item),
  5934. i,
  5935. len;
  5936. for (i = 0, len = fields.length; i < len; i++) {
  5937. var field = fields[i];
  5938. var fieldType = this._type[field]; // type may be undefined
  5939. d[field] = util.convert(item[field], fieldType);
  5940. }
  5941. this._data[id] = d;
  5942. this.length++;
  5943. return id;
  5944. };
  5945. /**
  5946. * Get an item. Fields can be converted to a specific type
  5947. * @param {String} id
  5948. * @param {Object.<String, String>} [types] field types to convert
  5949. * @return {Object | null} item
  5950. * @private
  5951. */
  5952. DataSet.prototype._getItem = function (id, types) {
  5953. var field, value, i, len;
  5954. // get the item from the dataset
  5955. var raw = this._data[id];
  5956. if (!raw) {
  5957. return null;
  5958. }
  5959. // convert the items field types
  5960. var converted = {},
  5961. fields = Object.keys(raw);
  5962. if (types) {
  5963. for (i = 0, len = fields.length; i < len; i++) {
  5964. field = fields[i];
  5965. value = raw[field];
  5966. converted[field] = util.convert(value, types[field]);
  5967. }
  5968. } else {
  5969. // no field types specified, no converting needed
  5970. for (i = 0, len = fields.length; i < len; i++) {
  5971. field = fields[i];
  5972. value = raw[field];
  5973. converted[field] = value;
  5974. }
  5975. }
  5976. return converted;
  5977. };
  5978. /**
  5979. * Update a single item: merge with existing item.
  5980. * Will fail when the item has no id, or when there does not exist an item
  5981. * with the same id.
  5982. * @param {Object} item
  5983. * @return {String} id
  5984. * @private
  5985. */
  5986. DataSet.prototype._updateItem = function (item) {
  5987. var id = item[this._fieldId];
  5988. if (id == undefined) {
  5989. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  5990. }
  5991. var d = this._data[id];
  5992. if (!d) {
  5993. // item doesn't exist
  5994. throw new Error('Cannot update item: no item with id ' + id + ' found');
  5995. }
  5996. // merge with current item
  5997. var fields = Object.keys(item);
  5998. for (var i = 0, len = fields.length; i < len; i++) {
  5999. var field = fields[i];
  6000. var fieldType = this._type[field]; // type may be undefined
  6001. d[field] = util.convert(item[field], fieldType);
  6002. }
  6003. return id;
  6004. };
  6005. module.exports = DataSet;
  6006. /***/ },
  6007. /* 10 */
  6008. /***/ function(module, exports) {
  6009. 'use strict';
  6010. /**
  6011. * A queue
  6012. * @param {Object} options
  6013. * Available options:
  6014. * - delay: number When provided, the queue will be flushed
  6015. * automatically after an inactivity of this delay
  6016. * in milliseconds.
  6017. * Default value is null.
  6018. * - max: number When the queue exceeds the given maximum number
  6019. * of entries, the queue is flushed automatically.
  6020. * Default value of max is Infinity.
  6021. * @constructor
  6022. */
  6023. function Queue(options) {
  6024. // options
  6025. this.delay = null;
  6026. this.max = Infinity;
  6027. // properties
  6028. this._queue = [];
  6029. this._timeout = null;
  6030. this._extended = null;
  6031. this.setOptions(options);
  6032. }
  6033. /**
  6034. * Update the configuration of the queue
  6035. * @param {Object} options
  6036. * Available options:
  6037. * - delay: number When provided, the queue will be flushed
  6038. * automatically after an inactivity of this delay
  6039. * in milliseconds.
  6040. * Default value is null.
  6041. * - max: number When the queue exceeds the given maximum number
  6042. * of entries, the queue is flushed automatically.
  6043. * Default value of max is Infinity.
  6044. * @param options
  6045. */
  6046. Queue.prototype.setOptions = function (options) {
  6047. if (options && typeof options.delay !== 'undefined') {
  6048. this.delay = options.delay;
  6049. }
  6050. if (options && typeof options.max !== 'undefined') {
  6051. this.max = options.max;
  6052. }
  6053. this._flushIfNeeded();
  6054. };
  6055. /**
  6056. * Extend an object with queuing functionality.
  6057. * The object will be extended with a function flush, and the methods provided
  6058. * in options.replace will be replaced with queued ones.
  6059. * @param {Object} object
  6060. * @param {Object} options
  6061. * Available options:
  6062. * - replace: Array.<string>
  6063. * A list with method names of the methods
  6064. * on the object to be replaced with queued ones.
  6065. * - delay: number When provided, the queue will be flushed
  6066. * automatically after an inactivity of this delay
  6067. * in milliseconds.
  6068. * Default value is null.
  6069. * - max: number When the queue exceeds the given maximum number
  6070. * of entries, the queue is flushed automatically.
  6071. * Default value of max is Infinity.
  6072. * @return {Queue} Returns the created queue
  6073. */
  6074. Queue.extend = function (object, options) {
  6075. var queue = new Queue(options);
  6076. if (object.flush !== undefined) {
  6077. throw new Error('Target object already has a property flush');
  6078. }
  6079. object.flush = function () {
  6080. queue.flush();
  6081. };
  6082. var methods = [{
  6083. name: 'flush',
  6084. original: undefined
  6085. }];
  6086. if (options && options.replace) {
  6087. for (var i = 0; i < options.replace.length; i++) {
  6088. var name = options.replace[i];
  6089. methods.push({
  6090. name: name,
  6091. original: object[name]
  6092. });
  6093. queue.replace(object, name);
  6094. }
  6095. }
  6096. queue._extended = {
  6097. object: object,
  6098. methods: methods
  6099. };
  6100. return queue;
  6101. };
  6102. /**
  6103. * Destroy the queue. The queue will first flush all queued actions, and in
  6104. * case it has extended an object, will restore the original object.
  6105. */
  6106. Queue.prototype.destroy = function () {
  6107. this.flush();
  6108. if (this._extended) {
  6109. var object = this._extended.object;
  6110. var methods = this._extended.methods;
  6111. for (var i = 0; i < methods.length; i++) {
  6112. var method = methods[i];
  6113. if (method.original) {
  6114. object[method.name] = method.original;
  6115. } else {
  6116. delete object[method.name];
  6117. }
  6118. }
  6119. this._extended = null;
  6120. }
  6121. };
  6122. /**
  6123. * Replace a method on an object with a queued version
  6124. * @param {Object} object Object having the method
  6125. * @param {string} method The method name
  6126. */
  6127. Queue.prototype.replace = function (object, method) {
  6128. var me = this;
  6129. var original = object[method];
  6130. if (!original) {
  6131. throw new Error('Method ' + method + ' undefined');
  6132. }
  6133. object[method] = function () {
  6134. // create an Array with the arguments
  6135. var args = [];
  6136. for (var i = 0; i < arguments.length; i++) {
  6137. args[i] = arguments[i];
  6138. }
  6139. // add this call to the queue
  6140. me.queue({
  6141. args: args,
  6142. fn: original,
  6143. context: this
  6144. });
  6145. };
  6146. };
  6147. /**
  6148. * Queue a call
  6149. * @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
  6150. */
  6151. Queue.prototype.queue = function (entry) {
  6152. if (typeof entry === 'function') {
  6153. this._queue.push({ fn: entry });
  6154. } else {
  6155. this._queue.push(entry);
  6156. }
  6157. this._flushIfNeeded();
  6158. };
  6159. /**
  6160. * Check whether the queue needs to be flushed
  6161. * @private
  6162. */
  6163. Queue.prototype._flushIfNeeded = function () {
  6164. // flush when the maximum is exceeded.
  6165. if (this._queue.length > this.max) {
  6166. this.flush();
  6167. }
  6168. // flush after a period of inactivity when a delay is configured
  6169. clearTimeout(this._timeout);
  6170. if (this.queue.length > 0 && typeof this.delay === 'number') {
  6171. var me = this;
  6172. this._timeout = setTimeout(function () {
  6173. me.flush();
  6174. }, this.delay);
  6175. }
  6176. };
  6177. /**
  6178. * Flush all queued calls
  6179. */
  6180. Queue.prototype.flush = function () {
  6181. while (this._queue.length > 0) {
  6182. var entry = this._queue.shift();
  6183. entry.fn.apply(entry.context || entry.fn, entry.args || []);
  6184. }
  6185. };
  6186. module.exports = Queue;
  6187. /***/ },
  6188. /* 11 */
  6189. /***/ function(module, exports, __webpack_require__) {
  6190. 'use strict';
  6191. var util = __webpack_require__(1);
  6192. var DataSet = __webpack_require__(9);
  6193. /**
  6194. * DataView
  6195. *
  6196. * a dataview offers a filtered view on a dataset or an other dataview.
  6197. *
  6198. * @param {DataSet | DataView} data
  6199. * @param {Object} [options] Available options: see method get
  6200. *
  6201. * @constructor DataView
  6202. */
  6203. function DataView(data, options) {
  6204. this._data = null;
  6205. this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
  6206. this.length = 0; // number of items in the DataView
  6207. this._options = options || {};
  6208. this._fieldId = 'id'; // name of the field containing id
  6209. this._subscribers = {}; // event subscribers
  6210. var me = this;
  6211. this.listener = function () {
  6212. me._onEvent.apply(me, arguments);
  6213. };
  6214. this.setData(data);
  6215. }
  6216. // TODO: implement a function .config() to dynamically update things like configured filter
  6217. // and trigger changes accordingly
  6218. /**
  6219. * Set a data source for the view
  6220. * @param {DataSet | DataView} data
  6221. */
  6222. DataView.prototype.setData = function (data) {
  6223. var ids, id, i, len;
  6224. if (this._data) {
  6225. // unsubscribe from current dataset
  6226. if (this._data.off) {
  6227. this._data.off('*', this.listener);
  6228. }
  6229. // trigger a remove of all items in memory
  6230. ids = Object.keys(this._ids);
  6231. this._ids = {};
  6232. this.length = 0;
  6233. this._trigger('remove', { items: ids });
  6234. }
  6235. this._data = data;
  6236. if (this._data) {
  6237. // update fieldId
  6238. this._fieldId = this._options.fieldId || this._data && this._data.options && this._data.options.fieldId || 'id';
  6239. // trigger an add of all added items
  6240. ids = this._data.getIds({ filter: this._options && this._options.filter });
  6241. for (i = 0, len = ids.length; i < len; i++) {
  6242. id = ids[i];
  6243. this._ids[id] = true;
  6244. }
  6245. this.length = ids.length;
  6246. this._trigger('add', { items: ids });
  6247. // subscribe to new dataset
  6248. if (this._data.on) {
  6249. this._data.on('*', this.listener);
  6250. }
  6251. }
  6252. };
  6253. /**
  6254. * Refresh the DataView. Useful when the DataView has a filter function
  6255. * containing a variable parameter.
  6256. */
  6257. DataView.prototype.refresh = function () {
  6258. var id, i, len;
  6259. var ids = this._data.getIds({ filter: this._options && this._options.filter });
  6260. var oldIds = Object.keys(this._ids);
  6261. var newIds = {};
  6262. var added = [];
  6263. var removed = [];
  6264. // check for additions
  6265. for (i = 0, len = ids.length; i < len; i++) {
  6266. id = ids[i];
  6267. newIds[id] = true;
  6268. if (!this._ids[id]) {
  6269. added.push(id);
  6270. this._ids[id] = true;
  6271. }
  6272. }
  6273. // check for removals
  6274. for (i = 0, len = oldIds.length; i < len; i++) {
  6275. id = oldIds[i];
  6276. if (!newIds[id]) {
  6277. removed.push(id);
  6278. delete this._ids[id];
  6279. }
  6280. }
  6281. this.length += added.length - removed.length;
  6282. // trigger events
  6283. if (added.length) {
  6284. this._trigger('add', { items: added });
  6285. }
  6286. if (removed.length) {
  6287. this._trigger('remove', { items: removed });
  6288. }
  6289. };
  6290. /**
  6291. * Get data from the data view
  6292. *
  6293. * Usage:
  6294. *
  6295. * get()
  6296. * get(options: Object)
  6297. * get(options: Object, data: Array | DataTable)
  6298. *
  6299. * get(id: Number)
  6300. * get(id: Number, options: Object)
  6301. * get(id: Number, options: Object, data: Array | DataTable)
  6302. *
  6303. * get(ids: Number[])
  6304. * get(ids: Number[], options: Object)
  6305. * get(ids: Number[], options: Object, data: Array | DataTable)
  6306. *
  6307. * Where:
  6308. *
  6309. * {Number | String} id The id of an item
  6310. * {Number[] | String{}} ids An array with ids of items
  6311. * {Object} options An Object with options. Available options:
  6312. * {String} [type] Type of data to be returned. Can
  6313. * be 'DataTable' or 'Array' (default)
  6314. * {Object.<String, String>} [convert]
  6315. * {String[]} [fields] field names to be returned
  6316. * {function} [filter] filter items
  6317. * {String | function} [order] Order the items by
  6318. * a field name or custom sort function.
  6319. * {Array | DataTable} [data] If provided, items will be appended to this
  6320. * array or table. Required in case of Google
  6321. * DataTable.
  6322. * @param args
  6323. */
  6324. DataView.prototype.get = function (args) {
  6325. var me = this;
  6326. // parse the arguments
  6327. var ids, options, data;
  6328. var firstType = util.getType(arguments[0]);
  6329. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  6330. // get(id(s) [, options] [, data])
  6331. ids = arguments[0]; // can be a single id or an array with ids
  6332. options = arguments[1];
  6333. data = arguments[2];
  6334. } else {
  6335. // get([, options] [, data])
  6336. options = arguments[0];
  6337. data = arguments[1];
  6338. }
  6339. // extend the options with the default options and provided options
  6340. var viewOptions = util.extend({}, this._options, options);
  6341. // create a combined filter method when needed
  6342. if (this._options.filter && options && options.filter) {
  6343. viewOptions.filter = function (item) {
  6344. return me._options.filter(item) && options.filter(item);
  6345. };
  6346. }
  6347. // build up the call to the linked data set
  6348. var getArguments = [];
  6349. if (ids != undefined) {
  6350. getArguments.push(ids);
  6351. }
  6352. getArguments.push(viewOptions);
  6353. getArguments.push(data);
  6354. return this._data && this._data.get.apply(this._data, getArguments);
  6355. };
  6356. /**
  6357. * Get ids of all items or from a filtered set of items.
  6358. * @param {Object} [options] An Object with options. Available options:
  6359. * {function} [filter] filter items
  6360. * {String | function} [order] Order the items by
  6361. * a field name or custom sort function.
  6362. * @return {Array} ids
  6363. */
  6364. DataView.prototype.getIds = function (options) {
  6365. var ids;
  6366. if (this._data) {
  6367. var defaultFilter = this._options.filter;
  6368. var filter;
  6369. if (options && options.filter) {
  6370. if (defaultFilter) {
  6371. filter = function filter(item) {
  6372. return defaultFilter(item) && options.filter(item);
  6373. };
  6374. } else {
  6375. filter = options.filter;
  6376. }
  6377. } else {
  6378. filter = defaultFilter;
  6379. }
  6380. ids = this._data.getIds({
  6381. filter: filter,
  6382. order: options && options.order
  6383. });
  6384. } else {
  6385. ids = [];
  6386. }
  6387. return ids;
  6388. };
  6389. /**
  6390. * Map every item in the dataset.
  6391. * @param {function} callback
  6392. * @param {Object} [options] Available options:
  6393. * {Object.<String, String>} [type]
  6394. * {String[]} [fields] filter fields
  6395. * {function} [filter] filter items
  6396. * {String | function} [order] Order the items by
  6397. * a field name or custom sort function.
  6398. * @return {Object[]} mappedItems
  6399. */
  6400. DataView.prototype.map = function (callback, options) {
  6401. var mappedItems = [];
  6402. if (this._data) {
  6403. var defaultFilter = this._options.filter;
  6404. var filter;
  6405. if (options && options.filter) {
  6406. if (defaultFilter) {
  6407. filter = function filter(item) {
  6408. return defaultFilter(item) && options.filter(item);
  6409. };
  6410. } else {
  6411. filter = options.filter;
  6412. }
  6413. } else {
  6414. filter = defaultFilter;
  6415. }
  6416. mappedItems = this._data.map(callback, {
  6417. filter: filter,
  6418. order: options && options.order
  6419. });
  6420. } else {
  6421. mappedItems = [];
  6422. }
  6423. return mappedItems;
  6424. };
  6425. /**
  6426. * Get the DataSet to which this DataView is connected. In case there is a chain
  6427. * of multiple DataViews, the root DataSet of this chain is returned.
  6428. * @return {DataSet} dataSet
  6429. */
  6430. DataView.prototype.getDataSet = function () {
  6431. var dataSet = this;
  6432. while (dataSet instanceof DataView) {
  6433. dataSet = dataSet._data;
  6434. }
  6435. return dataSet || null;
  6436. };
  6437. /**
  6438. * Event listener. Will propagate all events from the connected data set to
  6439. * the subscribers of the DataView, but will filter the items and only trigger
  6440. * when there are changes in the filtered data set.
  6441. * @param {String} event
  6442. * @param {Object | null} params
  6443. * @param {String} senderId
  6444. * @private
  6445. */
  6446. DataView.prototype._onEvent = function (event, params, senderId) {
  6447. var i, len, id, item;
  6448. var ids = params && params.items;
  6449. var data = this._data;
  6450. var updatedData = [];
  6451. var added = [];
  6452. var updated = [];
  6453. var removed = [];
  6454. if (ids && data) {
  6455. switch (event) {
  6456. case 'add':
  6457. // filter the ids of the added items
  6458. for (i = 0, len = ids.length; i < len; i++) {
  6459. id = ids[i];
  6460. item = this.get(id);
  6461. if (item) {
  6462. this._ids[id] = true;
  6463. added.push(id);
  6464. }
  6465. }
  6466. break;
  6467. case 'update':
  6468. // determine the event from the views viewpoint: an updated
  6469. // item can be added, updated, or removed from this view.
  6470. for (i = 0, len = ids.length; i < len; i++) {
  6471. id = ids[i];
  6472. item = this.get(id);
  6473. if (item) {
  6474. if (this._ids[id]) {
  6475. updated.push(id);
  6476. updatedData.push(params.data[i]);
  6477. } else {
  6478. this._ids[id] = true;
  6479. added.push(id);
  6480. }
  6481. } else {
  6482. if (this._ids[id]) {
  6483. delete this._ids[id];
  6484. removed.push(id);
  6485. } else {
  6486. // nothing interesting for me :-(
  6487. }
  6488. }
  6489. }
  6490. break;
  6491. case 'remove':
  6492. // filter the ids of the removed items
  6493. for (i = 0, len = ids.length; i < len; i++) {
  6494. id = ids[i];
  6495. if (this._ids[id]) {
  6496. delete this._ids[id];
  6497. removed.push(id);
  6498. }
  6499. }
  6500. break;
  6501. }
  6502. this.length += added.length - removed.length;
  6503. if (added.length) {
  6504. this._trigger('add', { items: added }, senderId);
  6505. }
  6506. if (updated.length) {
  6507. this._trigger('update', { items: updated, data: updatedData }, senderId);
  6508. }
  6509. if (removed.length) {
  6510. this._trigger('remove', { items: removed }, senderId);
  6511. }
  6512. }
  6513. };
  6514. // copy subscription functionality from DataSet
  6515. DataView.prototype.on = DataSet.prototype.on;
  6516. DataView.prototype.off = DataSet.prototype.off;
  6517. DataView.prototype._trigger = DataSet.prototype._trigger;
  6518. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  6519. DataView.prototype.subscribe = DataView.prototype.on;
  6520. DataView.prototype.unsubscribe = DataView.prototype.off;
  6521. module.exports = DataView;
  6522. /***/ },
  6523. /* 12 */
  6524. /***/ function(module, exports, __webpack_require__) {
  6525. 'use strict';
  6526. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  6527. var Emitter = __webpack_require__(13);
  6528. var DataSet = __webpack_require__(9);
  6529. var DataView = __webpack_require__(11);
  6530. var util = __webpack_require__(1);
  6531. var Point3d = __webpack_require__(14);
  6532. var Point2d = __webpack_require__(15);
  6533. var Camera = __webpack_require__(16);
  6534. var Filter = __webpack_require__(17);
  6535. var Slider = __webpack_require__(18);
  6536. var StepNumber = __webpack_require__(19);
  6537. /**
  6538. * @constructor Graph3d
  6539. * Graph3d displays data in 3d.
  6540. *
  6541. * Graph3d is developed in javascript as a Google Visualization Chart.
  6542. *
  6543. * @param {Element} container The DOM element in which the Graph3d will
  6544. * be created. Normally a div element.
  6545. * @param {DataSet | DataView | Array} [data]
  6546. * @param {Object} [options]
  6547. */
  6548. function Graph3d(container, data, options) {
  6549. if (!(this instanceof Graph3d)) {
  6550. throw new SyntaxError('Constructor must be called with the new operator');
  6551. }
  6552. // create variables and set default values
  6553. this.containerElement = container;
  6554. this.width = '400px';
  6555. this.height = '400px';
  6556. this.margin = 10; // px
  6557. this.defaultXCenter = '55%';
  6558. this.defaultYCenter = '50%';
  6559. this.xLabel = 'x';
  6560. this.yLabel = 'y';
  6561. this.zLabel = 'z';
  6562. var passValueFn = function passValueFn(v) {
  6563. return v;
  6564. };
  6565. this.xValueLabel = passValueFn;
  6566. this.yValueLabel = passValueFn;
  6567. this.zValueLabel = passValueFn;
  6568. this.filterLabel = 'time';
  6569. this.legendLabel = 'value';
  6570. this.style = Graph3d.STYLE.DOT;
  6571. this.showPerspective = true;
  6572. this.showGrid = true;
  6573. this.keepAspectRatio = true;
  6574. this.showShadow = false;
  6575. this.showGrayBottom = false; // TODO: this does not work correctly
  6576. this.showTooltip = false;
  6577. this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
  6578. this.animationInterval = 1000; // milliseconds
  6579. this.animationPreload = false;
  6580. this.camera = new Camera();
  6581. this.camera.setArmRotation(1.0, 0.5);
  6582. this.camera.setArmLength(1.7);
  6583. this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  6584. this.dataTable = null; // The original data table
  6585. this.dataPoints = null; // The table with point objects
  6586. // the column indexes
  6587. this.colX = undefined;
  6588. this.colY = undefined;
  6589. this.colZ = undefined;
  6590. this.colValue = undefined;
  6591. this.colFilter = undefined;
  6592. this.xMin = 0;
  6593. this.xStep = undefined; // auto by default
  6594. this.xMax = 1;
  6595. this.yMin = 0;
  6596. this.yStep = undefined; // auto by default
  6597. this.yMax = 1;
  6598. this.zMin = 0;
  6599. this.zStep = undefined; // auto by default
  6600. this.zMax = 1;
  6601. this.valueMin = 0;
  6602. this.valueMax = 1;
  6603. this.xBarWidth = 1;
  6604. this.yBarWidth = 1;
  6605. // TODO: customize axis range
  6606. // colors
  6607. this.axisColor = '#4D4D4D';
  6608. this.gridColor = '#D3D3D3';
  6609. this.dataColor = {
  6610. fill: '#7DC1FF',
  6611. stroke: '#3267D2',
  6612. strokeWidth: 1 // px
  6613. };
  6614. this.dotSizeRatio = 0.02; // size of the dots as a fraction of the graph width
  6615. // create a frame and canvas
  6616. this.create();
  6617. // apply options (also when undefined)
  6618. this.setOptions(options);
  6619. // apply data
  6620. if (data) {
  6621. this.setData(data);
  6622. }
  6623. }
  6624. // Extend Graph3d with an Emitter mixin
  6625. Emitter(Graph3d.prototype);
  6626. /**
  6627. * Calculate the scaling values, dependent on the range in x, y, and z direction
  6628. */
  6629. Graph3d.prototype._setScale = function () {
  6630. this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin));
  6631. // keep aspect ration between x and y scale if desired
  6632. if (this.keepAspectRatio) {
  6633. if (this.scale.x < this.scale.y) {
  6634. //noinspection JSSuspiciousNameCombination
  6635. this.scale.y = this.scale.x;
  6636. } else {
  6637. //noinspection JSSuspiciousNameCombination
  6638. this.scale.x = this.scale.y;
  6639. }
  6640. }
  6641. // scale the vertical axis
  6642. this.scale.z *= this.verticalRatio;
  6643. // TODO: can this be automated? verticalRatio?
  6644. // determine scale for (optional) value
  6645. this.scale.value = 1 / (this.valueMax - this.valueMin);
  6646. // position the camera arm
  6647. var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
  6648. var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
  6649. var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
  6650. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  6651. };
  6652. /**
  6653. * Convert a 3D location to a 2D location on screen
  6654. * http://en.wikipedia.org/wiki/3D_projection
  6655. * @param {Point3d} point3d A 3D point with parameters x, y, z
  6656. * @return {Point2d} point2d A 2D point with parameters x, y
  6657. */
  6658. Graph3d.prototype._convert3Dto2D = function (point3d) {
  6659. var translation = this._convertPointToTranslation(point3d);
  6660. return this._convertTranslationToScreen(translation);
  6661. };
  6662. /**
  6663. * Convert a 3D location its translation seen from the camera
  6664. * http://en.wikipedia.org/wiki/3D_projection
  6665. * @param {Point3d} point3d A 3D point with parameters x, y, z
  6666. * @return {Point3d} translation A 3D point with parameters x, y, z This is
  6667. * the translation of the point, seen from the
  6668. * camera
  6669. */
  6670. Graph3d.prototype._convertPointToTranslation = function (point3d) {
  6671. var ax = point3d.x * this.scale.x,
  6672. ay = point3d.y * this.scale.y,
  6673. az = point3d.z * this.scale.z,
  6674. cx = this.camera.getCameraLocation().x,
  6675. cy = this.camera.getCameraLocation().y,
  6676. cz = this.camera.getCameraLocation().z,
  6677. // calculate angles
  6678. sinTx = Math.sin(this.camera.getCameraRotation().x),
  6679. cosTx = Math.cos(this.camera.getCameraRotation().x),
  6680. sinTy = Math.sin(this.camera.getCameraRotation().y),
  6681. cosTy = Math.cos(this.camera.getCameraRotation().y),
  6682. sinTz = Math.sin(this.camera.getCameraRotation().z),
  6683. cosTz = Math.cos(this.camera.getCameraRotation().z),
  6684. // calculate translation
  6685. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  6686. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)),
  6687. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx));
  6688. return new Point3d(dx, dy, dz);
  6689. };
  6690. /**
  6691. * Convert a translation point to a point on the screen
  6692. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  6693. * the translation of the point, seen from the
  6694. * camera
  6695. * @return {Point2d} point2d A 2D point with parameters x, y
  6696. */
  6697. Graph3d.prototype._convertTranslationToScreen = function (translation) {
  6698. var ex = this.eye.x,
  6699. ey = this.eye.y,
  6700. ez = this.eye.z,
  6701. dx = translation.x,
  6702. dy = translation.y,
  6703. dz = translation.z;
  6704. // calculate position on screen from translation
  6705. var bx;
  6706. var by;
  6707. if (this.showPerspective) {
  6708. bx = (dx - ex) * (ez / dz);
  6709. by = (dy - ey) * (ez / dz);
  6710. } else {
  6711. bx = dx * -(ez / this.camera.getArmLength());
  6712. by = dy * -(ez / this.camera.getArmLength());
  6713. }
  6714. // shift and scale the point to the center of the screen
  6715. // use the width of the graph to scale both horizontally and vertically.
  6716. return new Point2d(this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth);
  6717. };
  6718. /**
  6719. * Set the background styling for the graph
  6720. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  6721. */
  6722. Graph3d.prototype._setBackgroundColor = function (backgroundColor) {
  6723. var fill = 'white';
  6724. var stroke = 'gray';
  6725. var strokeWidth = 1;
  6726. if (typeof backgroundColor === 'string') {
  6727. fill = backgroundColor;
  6728. stroke = 'none';
  6729. strokeWidth = 0;
  6730. } else if ((typeof backgroundColor === 'undefined' ? 'undefined' : _typeof(backgroundColor)) === 'object') {
  6731. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  6732. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  6733. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  6734. } else if (backgroundColor === undefined) {
  6735. // use use defaults
  6736. } else {
  6737. throw 'Unsupported type of backgroundColor';
  6738. }
  6739. this.frame.style.backgroundColor = fill;
  6740. this.frame.style.borderColor = stroke;
  6741. this.frame.style.borderWidth = strokeWidth + 'px';
  6742. this.frame.style.borderStyle = 'solid';
  6743. };
  6744. /// enumerate the available styles
  6745. Graph3d.STYLE = {
  6746. BAR: 0,
  6747. BARCOLOR: 1,
  6748. BARSIZE: 2,
  6749. DOT: 3,
  6750. DOTLINE: 4,
  6751. DOTCOLOR: 5,
  6752. DOTSIZE: 6,
  6753. GRID: 7,
  6754. LINE: 8,
  6755. SURFACE: 9
  6756. };
  6757. /**
  6758. * Retrieve the style index from given styleName
  6759. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  6760. * @return {Number} styleNumber Enumeration value representing the style, or -1
  6761. * when not found
  6762. */
  6763. Graph3d.prototype._getStyleNumber = function (styleName) {
  6764. switch (styleName) {
  6765. case 'dot':
  6766. return Graph3d.STYLE.DOT;
  6767. case 'dot-line':
  6768. return Graph3d.STYLE.DOTLINE;
  6769. case 'dot-color':
  6770. return Graph3d.STYLE.DOTCOLOR;
  6771. case 'dot-size':
  6772. return Graph3d.STYLE.DOTSIZE;
  6773. case 'line':
  6774. return Graph3d.STYLE.LINE;
  6775. case 'grid':
  6776. return Graph3d.STYLE.GRID;
  6777. case 'surface':
  6778. return Graph3d.STYLE.SURFACE;
  6779. case 'bar':
  6780. return Graph3d.STYLE.BAR;
  6781. case 'bar-color':
  6782. return Graph3d.STYLE.BARCOLOR;
  6783. case 'bar-size':
  6784. return Graph3d.STYLE.BARSIZE;
  6785. }
  6786. return -1;
  6787. };
  6788. /**
  6789. * Determine the indexes of the data columns, based on the given style and data
  6790. * @param {DataSet} data
  6791. * @param {Number} style
  6792. */
  6793. Graph3d.prototype._determineColumnIndexes = function (data, style) {
  6794. if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) {
  6795. // 3 columns expected, and optionally a 4th with filter values
  6796. this.colX = 0;
  6797. this.colY = 1;
  6798. this.colZ = 2;
  6799. this.colValue = undefined;
  6800. if (data.getNumberOfColumns() > 3) {
  6801. this.colFilter = 3;
  6802. }
  6803. } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) {
  6804. // 4 columns expected, and optionally a 5th with filter values
  6805. this.colX = 0;
  6806. this.colY = 1;
  6807. this.colZ = 2;
  6808. this.colValue = 3;
  6809. if (data.getNumberOfColumns() > 4) {
  6810. this.colFilter = 4;
  6811. }
  6812. } else {
  6813. throw 'Unknown style "' + this.style + '"';
  6814. }
  6815. };
  6816. Graph3d.prototype.getNumberOfRows = function (data) {
  6817. return data.length;
  6818. };
  6819. Graph3d.prototype.getNumberOfColumns = function (data) {
  6820. var counter = 0;
  6821. for (var column in data[0]) {
  6822. if (data[0].hasOwnProperty(column)) {
  6823. counter++;
  6824. }
  6825. }
  6826. return counter;
  6827. };
  6828. Graph3d.prototype.getDistinctValues = function (data, column) {
  6829. var distinctValues = [];
  6830. for (var i = 0; i < data.length; i++) {
  6831. if (distinctValues.indexOf(data[i][column]) == -1) {
  6832. distinctValues.push(data[i][column]);
  6833. }
  6834. }
  6835. return distinctValues;
  6836. };
  6837. Graph3d.prototype.getColumnRange = function (data, column) {
  6838. var minMax = { min: data[0][column], max: data[0][column] };
  6839. for (var i = 0; i < data.length; i++) {
  6840. if (minMax.min > data[i][column]) {
  6841. minMax.min = data[i][column];
  6842. }
  6843. if (minMax.max < data[i][column]) {
  6844. minMax.max = data[i][column];
  6845. }
  6846. }
  6847. return minMax;
  6848. };
  6849. /**
  6850. * Initialize the data from the data table. Calculate minimum and maximum values
  6851. * and column index values
  6852. * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
  6853. * @param {Number} style Style Number
  6854. */
  6855. Graph3d.prototype._dataInitialize = function (rawData, style) {
  6856. var me = this;
  6857. // unsubscribe from the dataTable
  6858. if (this.dataSet) {
  6859. this.dataSet.off('*', this._onChange);
  6860. }
  6861. if (rawData === undefined) return;
  6862. if (Array.isArray(rawData)) {
  6863. rawData = new DataSet(rawData);
  6864. }
  6865. var data;
  6866. if (rawData instanceof DataSet || rawData instanceof DataView) {
  6867. data = rawData.get();
  6868. } else {
  6869. throw new Error('Array, DataSet, or DataView expected');
  6870. }
  6871. if (data.length == 0) return;
  6872. this.dataSet = rawData;
  6873. this.dataTable = data;
  6874. // subscribe to changes in the dataset
  6875. this._onChange = function () {
  6876. me.setData(me.dataSet);
  6877. };
  6878. this.dataSet.on('*', this._onChange);
  6879. // _determineColumnIndexes
  6880. // getNumberOfRows (points)
  6881. // getNumberOfColumns (x,y,z,v,t,t1,t2...)
  6882. // getDistinctValues (unique values?)
  6883. // getColumnRange
  6884. // determine the location of x,y,z,value,filter columns
  6885. this.colX = 'x';
  6886. this.colY = 'y';
  6887. this.colZ = 'z';
  6888. this.colValue = 'style';
  6889. this.colFilter = 'filter';
  6890. // check if a filter column is provided
  6891. if (data[0].hasOwnProperty('filter')) {
  6892. if (this.dataFilter === undefined) {
  6893. this.dataFilter = new Filter(rawData, this.colFilter, this);
  6894. this.dataFilter.setOnLoadCallback(function () {
  6895. me.redraw();
  6896. });
  6897. }
  6898. }
  6899. var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE;
  6900. // determine barWidth from data
  6901. if (withBars) {
  6902. if (this.defaultXBarWidth !== undefined) {
  6903. this.xBarWidth = this.defaultXBarWidth;
  6904. } else {
  6905. var dataX = this.getDistinctValues(data, this.colX);
  6906. this.xBarWidth = dataX[1] - dataX[0] || 1;
  6907. }
  6908. if (this.defaultYBarWidth !== undefined) {
  6909. this.yBarWidth = this.defaultYBarWidth;
  6910. } else {
  6911. var dataY = this.getDistinctValues(data, this.colY);
  6912. this.yBarWidth = dataY[1] - dataY[0] || 1;
  6913. }
  6914. }
  6915. // calculate minimums and maximums
  6916. var xRange = this.getColumnRange(data, this.colX);
  6917. if (withBars) {
  6918. xRange.min -= this.xBarWidth / 2;
  6919. xRange.max += this.xBarWidth / 2;
  6920. }
  6921. this.xMin = this.defaultXMin !== undefined ? this.defaultXMin : xRange.min;
  6922. this.xMax = this.defaultXMax !== undefined ? this.defaultXMax : xRange.max;
  6923. if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
  6924. this.xStep = this.defaultXStep !== undefined ? this.defaultXStep : (this.xMax - this.xMin) / 5;
  6925. var yRange = this.getColumnRange(data, this.colY);
  6926. if (withBars) {
  6927. yRange.min -= this.yBarWidth / 2;
  6928. yRange.max += this.yBarWidth / 2;
  6929. }
  6930. this.yMin = this.defaultYMin !== undefined ? this.defaultYMin : yRange.min;
  6931. this.yMax = this.defaultYMax !== undefined ? this.defaultYMax : yRange.max;
  6932. if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
  6933. this.yStep = this.defaultYStep !== undefined ? this.defaultYStep : (this.yMax - this.yMin) / 5;
  6934. var zRange = this.getColumnRange(data, this.colZ);
  6935. this.zMin = this.defaultZMin !== undefined ? this.defaultZMin : zRange.min;
  6936. this.zMax = this.defaultZMax !== undefined ? this.defaultZMax : zRange.max;
  6937. if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
  6938. this.zStep = this.defaultZStep !== undefined ? this.defaultZStep : (this.zMax - this.zMin) / 5;
  6939. if (this.colValue !== undefined) {
  6940. var valueRange = this.getColumnRange(data, this.colValue);
  6941. this.valueMin = this.defaultValueMin !== undefined ? this.defaultValueMin : valueRange.min;
  6942. this.valueMax = this.defaultValueMax !== undefined ? this.defaultValueMax : valueRange.max;
  6943. if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
  6944. }
  6945. // set the scale dependent on the ranges.
  6946. this._setScale();
  6947. };
  6948. /**
  6949. * Filter the data based on the current filter
  6950. * @param {Array} data
  6951. * @return {Array} dataPoints Array with point objects which can be drawn on screen
  6952. */
  6953. Graph3d.prototype._getDataPoints = function (data) {
  6954. // TODO: store the created matrix dataPoints in the filters instead of reloading each time
  6955. var x, y, i, z, obj, point;
  6956. var dataPoints = [];
  6957. if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) {
  6958. // copy all values from the google data table to a matrix
  6959. // the provided values are supposed to form a grid of (x,y) positions
  6960. // create two lists with all present x and y values
  6961. var dataX = [];
  6962. var dataY = [];
  6963. for (i = 0; i < this.getNumberOfRows(data); i++) {
  6964. x = data[i][this.colX] || 0;
  6965. y = data[i][this.colY] || 0;
  6966. if (dataX.indexOf(x) === -1) {
  6967. dataX.push(x);
  6968. }
  6969. if (dataY.indexOf(y) === -1) {
  6970. dataY.push(y);
  6971. }
  6972. }
  6973. var sortNumber = function sortNumber(a, b) {
  6974. return a - b;
  6975. };
  6976. dataX.sort(sortNumber);
  6977. dataY.sort(sortNumber);
  6978. // create a grid, a 2d matrix, with all values.
  6979. var dataMatrix = []; // temporary data matrix
  6980. for (i = 0; i < data.length; i++) {
  6981. x = data[i][this.colX] || 0;
  6982. y = data[i][this.colY] || 0;
  6983. z = data[i][this.colZ] || 0;
  6984. var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
  6985. var yIndex = dataY.indexOf(y);
  6986. if (dataMatrix[xIndex] === undefined) {
  6987. dataMatrix[xIndex] = [];
  6988. }
  6989. var point3d = new Point3d();
  6990. point3d.x = x;
  6991. point3d.y = y;
  6992. point3d.z = z;
  6993. obj = {};
  6994. obj.point = point3d;
  6995. obj.trans = undefined;
  6996. obj.screen = undefined;
  6997. obj.bottom = new Point3d(x, y, this.zMin);
  6998. dataMatrix[xIndex][yIndex] = obj;
  6999. dataPoints.push(obj);
  7000. }
  7001. // fill in the pointers to the neighbors.
  7002. for (x = 0; x < dataMatrix.length; x++) {
  7003. for (y = 0; y < dataMatrix[x].length; y++) {
  7004. if (dataMatrix[x][y]) {
  7005. dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined;
  7006. dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined;
  7007. dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined;
  7008. }
  7009. }
  7010. }
  7011. } else {
  7012. // 'dot', 'dot-line', etc.
  7013. // copy all values from the google data table to a list with Point3d objects
  7014. for (i = 0; i < data.length; i++) {
  7015. point = new Point3d();
  7016. point.x = data[i][this.colX] || 0;
  7017. point.y = data[i][this.colY] || 0;
  7018. point.z = data[i][this.colZ] || 0;
  7019. if (this.colValue !== undefined) {
  7020. point.value = data[i][this.colValue] || 0;
  7021. }
  7022. obj = {};
  7023. obj.point = point;
  7024. obj.bottom = new Point3d(point.x, point.y, this.zMin);
  7025. obj.trans = undefined;
  7026. obj.screen = undefined;
  7027. dataPoints.push(obj);
  7028. }
  7029. }
  7030. return dataPoints;
  7031. };
  7032. /**
  7033. * Create the main frame for the Graph3d.
  7034. * This function is executed once when a Graph3d object is created. The frame
  7035. * contains a canvas, and this canvas contains all objects like the axis and
  7036. * nodes.
  7037. */
  7038. Graph3d.prototype.create = function () {
  7039. // remove all elements from the container element.
  7040. while (this.containerElement.hasChildNodes()) {
  7041. this.containerElement.removeChild(this.containerElement.firstChild);
  7042. }
  7043. this.frame = document.createElement('div');
  7044. this.frame.style.position = 'relative';
  7045. this.frame.style.overflow = 'hidden';
  7046. // create the graph canvas (HTML canvas element)
  7047. this.frame.canvas = document.createElement('canvas');
  7048. this.frame.canvas.style.position = 'relative';
  7049. this.frame.appendChild(this.frame.canvas);
  7050. //if (!this.frame.canvas.getContext) {
  7051. {
  7052. var noCanvas = document.createElement('DIV');
  7053. noCanvas.style.color = 'red';
  7054. noCanvas.style.fontWeight = 'bold';
  7055. noCanvas.style.padding = '10px';
  7056. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  7057. this.frame.canvas.appendChild(noCanvas);
  7058. }
  7059. this.frame.filter = document.createElement('div');
  7060. this.frame.filter.style.position = 'absolute';
  7061. this.frame.filter.style.bottom = '0px';
  7062. this.frame.filter.style.left = '0px';
  7063. this.frame.filter.style.width = '100%';
  7064. this.frame.appendChild(this.frame.filter);
  7065. // add event listeners to handle moving and zooming the contents
  7066. var me = this;
  7067. var onmousedown = function onmousedown(event) {
  7068. me._onMouseDown(event);
  7069. };
  7070. var ontouchstart = function ontouchstart(event) {
  7071. me._onTouchStart(event);
  7072. };
  7073. var onmousewheel = function onmousewheel(event) {
  7074. me._onWheel(event);
  7075. };
  7076. var ontooltip = function ontooltip(event) {
  7077. me._onTooltip(event);
  7078. };
  7079. // TODO: these events are never cleaned up... can give a 'memory leakage'
  7080. util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
  7081. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  7082. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  7083. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  7084. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  7085. // add the new graph to the container element
  7086. this.containerElement.appendChild(this.frame);
  7087. };
  7088. /**
  7089. * Set a new size for the graph
  7090. * @param {string} width Width in pixels or percentage (for example '800px'
  7091. * or '50%')
  7092. * @param {string} height Height in pixels or percentage (for example '400px'
  7093. * or '30%')
  7094. */
  7095. Graph3d.prototype.setSize = function (width, height) {
  7096. this.frame.style.width = width;
  7097. this.frame.style.height = height;
  7098. this._resizeCanvas();
  7099. };
  7100. /**
  7101. * Resize the canvas to the current size of the frame
  7102. */
  7103. Graph3d.prototype._resizeCanvas = function () {
  7104. this.frame.canvas.style.width = '100%';
  7105. this.frame.canvas.style.height = '100%';
  7106. this.frame.canvas.width = this.frame.canvas.clientWidth;
  7107. this.frame.canvas.height = this.frame.canvas.clientHeight;
  7108. // adjust with for margin
  7109. this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px';
  7110. };
  7111. /**
  7112. * Start animation
  7113. */
  7114. Graph3d.prototype.animationStart = function () {
  7115. if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available';
  7116. this.frame.filter.slider.play();
  7117. };
  7118. /**
  7119. * Stop animation
  7120. */
  7121. Graph3d.prototype.animationStop = function () {
  7122. if (!this.frame.filter || !this.frame.filter.slider) return;
  7123. this.frame.filter.slider.stop();
  7124. };
  7125. /**
  7126. * Resize the center position based on the current values in this.defaultXCenter
  7127. * and this.defaultYCenter (which are strings with a percentage or a value
  7128. * in pixels). The center positions are the variables this.xCenter
  7129. * and this.yCenter
  7130. */
  7131. Graph3d.prototype._resizeCenter = function () {
  7132. // calculate the horizontal center position
  7133. if (this.defaultXCenter.charAt(this.defaultXCenter.length - 1) === '%') {
  7134. this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth;
  7135. } else {
  7136. this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
  7137. }
  7138. // calculate the vertical center position
  7139. if (this.defaultYCenter.charAt(this.defaultYCenter.length - 1) === '%') {
  7140. this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  7141. } else {
  7142. this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
  7143. }
  7144. };
  7145. /**
  7146. * Set the rotation and distance of the camera
  7147. * @param {Object} pos An object with the camera position. The object
  7148. * contains three parameters:
  7149. * - horizontal {Number}
  7150. * The horizontal rotation, between 0 and 2*PI.
  7151. * Optional, can be left undefined.
  7152. * - vertical {Number}
  7153. * The vertical rotation, between 0 and 0.5*PI
  7154. * if vertical=0.5*PI, the graph is shown from the
  7155. * top. Optional, can be left undefined.
  7156. * - distance {Number}
  7157. * The (normalized) distance of the camera to the
  7158. * center of the graph, a value between 0.71 and 5.0.
  7159. * Optional, can be left undefined.
  7160. */
  7161. Graph3d.prototype.setCameraPosition = function (pos) {
  7162. if (pos === undefined) {
  7163. return;
  7164. }
  7165. if (pos.horizontal !== undefined && pos.vertical !== undefined) {
  7166. this.camera.setArmRotation(pos.horizontal, pos.vertical);
  7167. }
  7168. if (pos.distance !== undefined) {
  7169. this.camera.setArmLength(pos.distance);
  7170. }
  7171. this.redraw();
  7172. };
  7173. /**
  7174. * Retrieve the current camera rotation
  7175. * @return {object} An object with parameters horizontal, vertical, and
  7176. * distance
  7177. */
  7178. Graph3d.prototype.getCameraPosition = function () {
  7179. var pos = this.camera.getArmRotation();
  7180. pos.distance = this.camera.getArmLength();
  7181. return pos;
  7182. };
  7183. /**
  7184. * Load data into the 3D Graph
  7185. */
  7186. Graph3d.prototype._readData = function (data) {
  7187. // read the data
  7188. this._dataInitialize(data, this.style);
  7189. if (this.dataFilter) {
  7190. // apply filtering
  7191. this.dataPoints = this.dataFilter._getDataPoints();
  7192. } else {
  7193. // no filtering. load all data
  7194. this.dataPoints = this._getDataPoints(this.dataTable);
  7195. }
  7196. // draw the filter
  7197. this._redrawFilter();
  7198. };
  7199. /**
  7200. * Replace the dataset of the Graph3d
  7201. * @param {Array | DataSet | DataView} data
  7202. */
  7203. Graph3d.prototype.setData = function (data) {
  7204. this._readData(data);
  7205. this.redraw();
  7206. // start animation when option is true
  7207. if (this.animationAutoStart && this.dataFilter) {
  7208. this.animationStart();
  7209. }
  7210. };
  7211. /**
  7212. * Update the options. Options will be merged with current options
  7213. * @param {Object} options
  7214. */
  7215. Graph3d.prototype.setOptions = function (options) {
  7216. var cameraPosition = undefined;
  7217. this.animationStop();
  7218. if (options !== undefined) {
  7219. // retrieve parameter values
  7220. if (options.width !== undefined) this.width = options.width;
  7221. if (options.height !== undefined) this.height = options.height;
  7222. if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
  7223. if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
  7224. if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
  7225. if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
  7226. if (options.xLabel !== undefined) this.xLabel = options.xLabel;
  7227. if (options.yLabel !== undefined) this.yLabel = options.yLabel;
  7228. if (options.zLabel !== undefined) this.zLabel = options.zLabel;
  7229. if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel;
  7230. if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel;
  7231. if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel;
  7232. if (options.dotSizeRatio !== undefined) this.dotSizeRatio = options.dotSizeRatio;
  7233. if (options.style !== undefined) {
  7234. var styleNumber = this._getStyleNumber(options.style);
  7235. if (styleNumber !== -1) {
  7236. this.style = styleNumber;
  7237. }
  7238. }
  7239. if (options.showGrid !== undefined) this.showGrid = options.showGrid;
  7240. if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
  7241. if (options.showShadow !== undefined) this.showShadow = options.showShadow;
  7242. if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
  7243. if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
  7244. if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
  7245. if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
  7246. if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
  7247. if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
  7248. if (options.animationAutoStart !== undefined) this.animationAutoStart = options.animationAutoStart;
  7249. if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
  7250. if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
  7251. if (options.xMin !== undefined) this.defaultXMin = options.xMin;
  7252. if (options.xStep !== undefined) this.defaultXStep = options.xStep;
  7253. if (options.xMax !== undefined) this.defaultXMax = options.xMax;
  7254. if (options.yMin !== undefined) this.defaultYMin = options.yMin;
  7255. if (options.yStep !== undefined) this.defaultYStep = options.yStep;
  7256. if (options.yMax !== undefined) this.defaultYMax = options.yMax;
  7257. if (options.zMin !== undefined) this.defaultZMin = options.zMin;
  7258. if (options.zStep !== undefined) this.defaultZStep = options.zStep;
  7259. if (options.zMax !== undefined) this.defaultZMax = options.zMax;
  7260. if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
  7261. if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
  7262. if (options.backgroundColor !== undefined) this._setBackgroundColor(options.backgroundColor);
  7263. if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
  7264. if (cameraPosition !== undefined) {
  7265. this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
  7266. this.camera.setArmLength(cameraPosition.distance);
  7267. }
  7268. // colors
  7269. if (options.axisColor !== undefined) this.axisColor = options.axisColor;
  7270. if (options.gridColor !== undefined) this.gridColor = options.gridColor;
  7271. if (options.dataColor) {
  7272. if (typeof options.dataColor === 'string') {
  7273. this.dataColor.fill = options.dataColor;
  7274. this.dataColor.stroke = options.dataColor;
  7275. } else {
  7276. if (options.dataColor.fill) {
  7277. this.dataColor.fill = options.dataColor.fill;
  7278. }
  7279. if (options.dataColor.stroke) {
  7280. this.dataColor.stroke = options.dataColor.stroke;
  7281. }
  7282. if (options.dataColor.strokeWidth !== undefined) {
  7283. this.dataColor.strokeWidth = options.dataColor.strokeWidth;
  7284. }
  7285. }
  7286. }
  7287. }
  7288. this.setSize(this.width, this.height);
  7289. // re-load the data
  7290. if (this.dataTable) {
  7291. this.setData(this.dataTable);
  7292. }
  7293. // start animation when option is true
  7294. if (this.animationAutoStart && this.dataFilter) {
  7295. this.animationStart();
  7296. }
  7297. };
  7298. /**
  7299. * Redraw the Graph.
  7300. */
  7301. Graph3d.prototype.redraw = function () {
  7302. if (this.dataPoints === undefined) {
  7303. throw 'Error: graph data not initialized';
  7304. }
  7305. this._resizeCanvas();
  7306. this._resizeCenter();
  7307. this._redrawSlider();
  7308. this._redrawClear();
  7309. this._redrawAxis();
  7310. if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) {
  7311. this._redrawDataGrid();
  7312. } else if (this.style === Graph3d.STYLE.LINE) {
  7313. this._redrawDataLine();
  7314. } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) {
  7315. this._redrawDataBar();
  7316. } else {
  7317. // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
  7318. this._redrawDataDot();
  7319. }
  7320. this._redrawInfo();
  7321. this._redrawLegend();
  7322. };
  7323. /**
  7324. * Clear the canvas before redrawing
  7325. */
  7326. Graph3d.prototype._redrawClear = function () {
  7327. var canvas = this.frame.canvas;
  7328. var ctx = canvas.getContext('2d');
  7329. ctx.clearRect(0, 0, canvas.width, canvas.height);
  7330. };
  7331. /**
  7332. * Redraw the legend showing the colors
  7333. */
  7334. Graph3d.prototype._redrawLegend = function () {
  7335. var y;
  7336. if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) {
  7337. var dotSize = this.frame.clientWidth * this.dotSizeRatio;
  7338. var widthMin, widthMax;
  7339. if (this.style === Graph3d.STYLE.DOTSIZE) {
  7340. widthMin = dotSize / 2; // px
  7341. widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
  7342. } else {
  7343. widthMin = 20; // px
  7344. widthMax = 20; // px
  7345. }
  7346. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  7347. var top = this.margin;
  7348. var right = this.frame.clientWidth - this.margin;
  7349. var left = right - widthMax;
  7350. var bottom = top + height;
  7351. }
  7352. var canvas = this.frame.canvas;
  7353. var ctx = canvas.getContext('2d');
  7354. ctx.lineWidth = 1;
  7355. ctx.font = '14px arial'; // TODO: put in options
  7356. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  7357. // draw the color bar
  7358. var ymin = 0;
  7359. var ymax = height; // Todo: make height customizable
  7360. for (y = ymin; y < ymax; y++) {
  7361. var f = (y - ymin) / (ymax - ymin);
  7362. //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
  7363. var hue = f * 240;
  7364. var color = this._hsv2rgb(hue, 1, 1);
  7365. ctx.strokeStyle = color;
  7366. ctx.beginPath();
  7367. ctx.moveTo(left, top + y);
  7368. ctx.lineTo(right, top + y);
  7369. ctx.stroke();
  7370. }
  7371. ctx.strokeStyle = this.axisColor;
  7372. ctx.strokeRect(left, top, widthMax, height);
  7373. }
  7374. if (this.style === Graph3d.STYLE.DOTSIZE) {
  7375. // draw border around color bar
  7376. ctx.strokeStyle = this.axisColor;
  7377. ctx.fillStyle = this.dataColor.fill;
  7378. ctx.beginPath();
  7379. ctx.moveTo(left, top);
  7380. ctx.lineTo(right, top);
  7381. ctx.lineTo(right - widthMax + widthMin, bottom);
  7382. ctx.lineTo(left, bottom);
  7383. ctx.closePath();
  7384. ctx.fill();
  7385. ctx.stroke();
  7386. }
  7387. if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) {
  7388. // print values along the color bar
  7389. var gridLineLen = 5; // px
  7390. var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax - this.valueMin) / 5, true);
  7391. step.start();
  7392. if (step.getCurrent() < this.valueMin) {
  7393. step.next();
  7394. }
  7395. while (!step.end()) {
  7396. y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
  7397. ctx.beginPath();
  7398. ctx.moveTo(left - gridLineLen, y);
  7399. ctx.lineTo(left, y);
  7400. ctx.stroke();
  7401. ctx.textAlign = 'right';
  7402. ctx.textBaseline = 'middle';
  7403. ctx.fillStyle = this.axisColor;
  7404. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  7405. step.next();
  7406. }
  7407. ctx.textAlign = 'right';
  7408. ctx.textBaseline = 'top';
  7409. var label = this.legendLabel;
  7410. ctx.fillText(label, right, bottom + this.margin);
  7411. }
  7412. };
  7413. /**
  7414. * Redraw the filter
  7415. */
  7416. Graph3d.prototype._redrawFilter = function () {
  7417. this.frame.filter.innerHTML = '';
  7418. if (this.dataFilter) {
  7419. var options = {
  7420. 'visible': this.showAnimationControls
  7421. };
  7422. var slider = new Slider(this.frame.filter, options);
  7423. this.frame.filter.slider = slider;
  7424. // TODO: css here is not nice here...
  7425. this.frame.filter.style.padding = '10px';
  7426. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  7427. slider.setValues(this.dataFilter.values);
  7428. slider.setPlayInterval(this.animationInterval);
  7429. // create an event handler
  7430. var me = this;
  7431. var onchange = function onchange() {
  7432. var index = slider.getIndex();
  7433. me.dataFilter.selectValue(index);
  7434. me.dataPoints = me.dataFilter._getDataPoints();
  7435. me.redraw();
  7436. };
  7437. slider.setOnChangeCallback(onchange);
  7438. } else {
  7439. this.frame.filter.slider = undefined;
  7440. }
  7441. };
  7442. /**
  7443. * Redraw the slider
  7444. */
  7445. Graph3d.prototype._redrawSlider = function () {
  7446. if (this.frame.filter.slider !== undefined) {
  7447. this.frame.filter.slider.redraw();
  7448. }
  7449. };
  7450. /**
  7451. * Redraw common information
  7452. */
  7453. Graph3d.prototype._redrawInfo = function () {
  7454. if (this.dataFilter) {
  7455. var canvas = this.frame.canvas;
  7456. var ctx = canvas.getContext('2d');
  7457. ctx.font = '14px arial'; // TODO: put in options
  7458. ctx.lineStyle = 'gray';
  7459. ctx.fillStyle = 'gray';
  7460. ctx.textAlign = 'left';
  7461. ctx.textBaseline = 'top';
  7462. var x = this.margin;
  7463. var y = this.margin;
  7464. ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
  7465. }
  7466. };
  7467. /**
  7468. * Redraw the axis
  7469. */
  7470. Graph3d.prototype._redrawAxis = function () {
  7471. var canvas = this.frame.canvas,
  7472. ctx = canvas.getContext('2d'),
  7473. from,
  7474. to,
  7475. step,
  7476. prettyStep,
  7477. text,
  7478. xText,
  7479. yText,
  7480. zText,
  7481. offset,
  7482. xOffset,
  7483. yOffset,
  7484. xMin2d,
  7485. xMax2d;
  7486. // TODO: get the actual rendered style of the containerElement
  7487. //ctx.font = this.containerElement.style.font;
  7488. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  7489. // calculate the length for the short grid lines
  7490. var gridLenX = 0.025 / this.scale.x;
  7491. var gridLenY = 0.025 / this.scale.y;
  7492. var textMargin = 5 / this.camera.getArmLength(); // px
  7493. var armAngle = this.camera.getArmRotation().horizontal;
  7494. // draw x-grid lines
  7495. ctx.lineWidth = 1;
  7496. prettyStep = this.defaultXStep === undefined;
  7497. step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
  7498. step.start();
  7499. if (step.getCurrent() < this.xMin) {
  7500. step.next();
  7501. }
  7502. while (!step.end()) {
  7503. var x = step.getCurrent();
  7504. if (this.showGrid) {
  7505. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  7506. to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  7507. ctx.strokeStyle = this.gridColor;
  7508. ctx.beginPath();
  7509. ctx.moveTo(from.x, from.y);
  7510. ctx.lineTo(to.x, to.y);
  7511. ctx.stroke();
  7512. } else {
  7513. from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
  7514. to = this._convert3Dto2D(new Point3d(x, this.yMin + gridLenX, this.zMin));
  7515. ctx.strokeStyle = this.axisColor;
  7516. ctx.beginPath();
  7517. ctx.moveTo(from.x, from.y);
  7518. ctx.lineTo(to.x, to.y);
  7519. ctx.stroke();
  7520. from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
  7521. to = this._convert3Dto2D(new Point3d(x, this.yMax - gridLenX, this.zMin));
  7522. ctx.strokeStyle = this.axisColor;
  7523. ctx.beginPath();
  7524. ctx.moveTo(from.x, from.y);
  7525. ctx.lineTo(to.x, to.y);
  7526. ctx.stroke();
  7527. }
  7528. yText = Math.cos(armAngle) > 0 ? this.yMin : this.yMax;
  7529. text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
  7530. if (Math.cos(armAngle * 2) > 0) {
  7531. ctx.textAlign = 'center';
  7532. ctx.textBaseline = 'top';
  7533. text.y += textMargin;
  7534. } else if (Math.sin(armAngle * 2) < 0) {
  7535. ctx.textAlign = 'right';
  7536. ctx.textBaseline = 'middle';
  7537. } else {
  7538. ctx.textAlign = 'left';
  7539. ctx.textBaseline = 'middle';
  7540. }
  7541. ctx.fillStyle = this.axisColor;
  7542. ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  7543. step.next();
  7544. }
  7545. // draw y-grid lines
  7546. ctx.lineWidth = 1;
  7547. prettyStep = this.defaultYStep === undefined;
  7548. step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
  7549. step.start();
  7550. if (step.getCurrent() < this.yMin) {
  7551. step.next();
  7552. }
  7553. while (!step.end()) {
  7554. if (this.showGrid) {
  7555. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  7556. to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  7557. ctx.strokeStyle = this.gridColor;
  7558. ctx.beginPath();
  7559. ctx.moveTo(from.x, from.y);
  7560. ctx.lineTo(to.x, to.y);
  7561. ctx.stroke();
  7562. } else {
  7563. from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
  7564. to = this._convert3Dto2D(new Point3d(this.xMin + gridLenY, step.getCurrent(), this.zMin));
  7565. ctx.strokeStyle = this.axisColor;
  7566. ctx.beginPath();
  7567. ctx.moveTo(from.x, from.y);
  7568. ctx.lineTo(to.x, to.y);
  7569. ctx.stroke();
  7570. from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
  7571. to = this._convert3Dto2D(new Point3d(this.xMax - gridLenY, step.getCurrent(), this.zMin));
  7572. ctx.strokeStyle = this.axisColor;
  7573. ctx.beginPath();
  7574. ctx.moveTo(from.x, from.y);
  7575. ctx.lineTo(to.x, to.y);
  7576. ctx.stroke();
  7577. }
  7578. xText = Math.sin(armAngle) > 0 ? this.xMin : this.xMax;
  7579. text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
  7580. if (Math.cos(armAngle * 2) < 0) {
  7581. ctx.textAlign = 'center';
  7582. ctx.textBaseline = 'top';
  7583. text.y += textMargin;
  7584. } else if (Math.sin(armAngle * 2) > 0) {
  7585. ctx.textAlign = 'right';
  7586. ctx.textBaseline = 'middle';
  7587. } else {
  7588. ctx.textAlign = 'left';
  7589. ctx.textBaseline = 'middle';
  7590. }
  7591. ctx.fillStyle = this.axisColor;
  7592. ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y);
  7593. step.next();
  7594. }
  7595. // draw z-grid lines and axis
  7596. ctx.lineWidth = 1;
  7597. prettyStep = this.defaultZStep === undefined;
  7598. step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
  7599. step.start();
  7600. if (step.getCurrent() < this.zMin) {
  7601. step.next();
  7602. }
  7603. xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax;
  7604. yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax;
  7605. while (!step.end()) {
  7606. // TODO: make z-grid lines really 3d?
  7607. from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
  7608. ctx.strokeStyle = this.axisColor;
  7609. ctx.beginPath();
  7610. ctx.moveTo(from.x, from.y);
  7611. ctx.lineTo(from.x - textMargin, from.y);
  7612. ctx.stroke();
  7613. ctx.textAlign = 'right';
  7614. ctx.textBaseline = 'middle';
  7615. ctx.fillStyle = this.axisColor;
  7616. ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y);
  7617. step.next();
  7618. }
  7619. ctx.lineWidth = 1;
  7620. from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  7621. to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
  7622. ctx.strokeStyle = this.axisColor;
  7623. ctx.beginPath();
  7624. ctx.moveTo(from.x, from.y);
  7625. ctx.lineTo(to.x, to.y);
  7626. ctx.stroke();
  7627. // draw x-axis
  7628. ctx.lineWidth = 1;
  7629. // line at yMin
  7630. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  7631. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  7632. ctx.strokeStyle = this.axisColor;
  7633. ctx.beginPath();
  7634. ctx.moveTo(xMin2d.x, xMin2d.y);
  7635. ctx.lineTo(xMax2d.x, xMax2d.y);
  7636. ctx.stroke();
  7637. // line at ymax
  7638. xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  7639. xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  7640. ctx.strokeStyle = this.axisColor;
  7641. ctx.beginPath();
  7642. ctx.moveTo(xMin2d.x, xMin2d.y);
  7643. ctx.lineTo(xMax2d.x, xMax2d.y);
  7644. ctx.stroke();
  7645. // draw y-axis
  7646. ctx.lineWidth = 1;
  7647. // line at xMin
  7648. from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
  7649. to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
  7650. ctx.strokeStyle = this.axisColor;
  7651. ctx.beginPath();
  7652. ctx.moveTo(from.x, from.y);
  7653. ctx.lineTo(to.x, to.y);
  7654. ctx.stroke();
  7655. // line at xMax
  7656. from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
  7657. to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
  7658. ctx.strokeStyle = this.axisColor;
  7659. ctx.beginPath();
  7660. ctx.moveTo(from.x, from.y);
  7661. ctx.lineTo(to.x, to.y);
  7662. ctx.stroke();
  7663. // draw x-label
  7664. var xLabel = this.xLabel;
  7665. if (xLabel.length > 0) {
  7666. yOffset = 0.1 / this.scale.y;
  7667. xText = (this.xMin + this.xMax) / 2;
  7668. yText = Math.cos(armAngle) > 0 ? this.yMin - yOffset : this.yMax + yOffset;
  7669. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  7670. if (Math.cos(armAngle * 2) > 0) {
  7671. ctx.textAlign = 'center';
  7672. ctx.textBaseline = 'top';
  7673. } else if (Math.sin(armAngle * 2) < 0) {
  7674. ctx.textAlign = 'right';
  7675. ctx.textBaseline = 'middle';
  7676. } else {
  7677. ctx.textAlign = 'left';
  7678. ctx.textBaseline = 'middle';
  7679. }
  7680. ctx.fillStyle = this.axisColor;
  7681. ctx.fillText(xLabel, text.x, text.y);
  7682. }
  7683. // draw y-label
  7684. var yLabel = this.yLabel;
  7685. if (yLabel.length > 0) {
  7686. xOffset = 0.1 / this.scale.x;
  7687. xText = Math.sin(armAngle) > 0 ? this.xMin - xOffset : this.xMax + xOffset;
  7688. yText = (this.yMin + this.yMax) / 2;
  7689. text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
  7690. if (Math.cos(armAngle * 2) < 0) {
  7691. ctx.textAlign = 'center';
  7692. ctx.textBaseline = 'top';
  7693. } else if (Math.sin(armAngle * 2) > 0) {
  7694. ctx.textAlign = 'right';
  7695. ctx.textBaseline = 'middle';
  7696. } else {
  7697. ctx.textAlign = 'left';
  7698. ctx.textBaseline = 'middle';
  7699. }
  7700. ctx.fillStyle = this.axisColor;
  7701. ctx.fillText(yLabel, text.x, text.y);
  7702. }
  7703. // draw z-label
  7704. var zLabel = this.zLabel;
  7705. if (zLabel.length > 0) {
  7706. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  7707. xText = Math.cos(armAngle) > 0 ? this.xMin : this.xMax;
  7708. yText = Math.sin(armAngle) < 0 ? this.yMin : this.yMax;
  7709. zText = (this.zMin + this.zMax) / 2;
  7710. text = this._convert3Dto2D(new Point3d(xText, yText, zText));
  7711. ctx.textAlign = 'right';
  7712. ctx.textBaseline = 'middle';
  7713. ctx.fillStyle = this.axisColor;
  7714. ctx.fillText(zLabel, text.x - offset, text.y);
  7715. }
  7716. };
  7717. /**
  7718. * Calculate the color based on the given value.
  7719. * @param {Number} H Hue, a value be between 0 and 360
  7720. * @param {Number} S Saturation, a value between 0 and 1
  7721. * @param {Number} V Value, a value between 0 and 1
  7722. */
  7723. Graph3d.prototype._hsv2rgb = function (H, S, V) {
  7724. var R, G, B, C, Hi, X;
  7725. C = V * S;
  7726. Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5
  7727. X = C * (1 - Math.abs(H / 60 % 2 - 1));
  7728. switch (Hi) {
  7729. case 0:
  7730. R = C;G = X;B = 0;break;
  7731. case 1:
  7732. R = X;G = C;B = 0;break;
  7733. case 2:
  7734. R = 0;G = C;B = X;break;
  7735. case 3:
  7736. R = 0;G = X;B = C;break;
  7737. case 4:
  7738. R = X;G = 0;B = C;break;
  7739. case 5:
  7740. R = C;G = 0;B = X;break;
  7741. default:
  7742. R = 0;G = 0;B = 0;break;
  7743. }
  7744. return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')';
  7745. };
  7746. /**
  7747. * Draw all datapoints as a grid
  7748. * This function can be used when the style is 'grid'
  7749. */
  7750. Graph3d.prototype._redrawDataGrid = function () {
  7751. var canvas = this.frame.canvas,
  7752. ctx = canvas.getContext('2d'),
  7753. point,
  7754. right,
  7755. top,
  7756. cross,
  7757. i,
  7758. topSideVisible,
  7759. fillStyle,
  7760. strokeStyle,
  7761. lineWidth,
  7762. h,
  7763. s,
  7764. v,
  7765. zAvg;
  7766. ctx.lineJoin = 'round';
  7767. ctx.lineCap = 'round';
  7768. if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception?
  7769. // calculate the translations and screen position of all points
  7770. for (i = 0; i < this.dataPoints.length; i++) {
  7771. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  7772. var screen = this._convertTranslationToScreen(trans);
  7773. this.dataPoints[i].trans = trans;
  7774. this.dataPoints[i].screen = screen;
  7775. // calculate the translation of the point at the bottom (needed for sorting)
  7776. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  7777. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  7778. }
  7779. // sort the points on depth of their (x,y) position (not on z)
  7780. var sortDepth = function sortDepth(a, b) {
  7781. return b.dist - a.dist;
  7782. };
  7783. this.dataPoints.sort(sortDepth);
  7784. if (this.style === Graph3d.STYLE.SURFACE) {
  7785. for (i = 0; i < this.dataPoints.length; i++) {
  7786. point = this.dataPoints[i];
  7787. right = this.dataPoints[i].pointRight;
  7788. top = this.dataPoints[i].pointTop;
  7789. cross = this.dataPoints[i].pointCross;
  7790. if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
  7791. if (this.showGrayBottom || this.showShadow) {
  7792. // calculate the cross product of the two vectors from center
  7793. // to left and right, in order to know whether we are looking at the
  7794. // bottom or at the top side. We can also use the cross product
  7795. // for calculating light intensity
  7796. var aDiff = Point3d.subtract(cross.trans, point.trans);
  7797. var bDiff = Point3d.subtract(top.trans, right.trans);
  7798. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  7799. var len = crossproduct.length();
  7800. // FIXME: there is a bug with determining the surface side (shadow or colored)
  7801. topSideVisible = crossproduct.z > 0;
  7802. } else {
  7803. topSideVisible = true;
  7804. }
  7805. if (topSideVisible) {
  7806. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  7807. zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  7808. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  7809. s = 1; // saturation
  7810. if (this.showShadow) {
  7811. v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale
  7812. fillStyle = this._hsv2rgb(h, s, v);
  7813. strokeStyle = fillStyle;
  7814. } else {
  7815. v = 1;
  7816. fillStyle = this._hsv2rgb(h, s, v);
  7817. strokeStyle = this.axisColor; // TODO: should be customizable
  7818. }
  7819. } else {
  7820. fillStyle = 'gray';
  7821. strokeStyle = this.axisColor;
  7822. }
  7823. ctx.lineWidth = this._getStrokeWidth(point);
  7824. ctx.fillStyle = fillStyle;
  7825. ctx.strokeStyle = strokeStyle;
  7826. ctx.beginPath();
  7827. ctx.moveTo(point.screen.x, point.screen.y);
  7828. ctx.lineTo(right.screen.x, right.screen.y);
  7829. ctx.lineTo(cross.screen.x, cross.screen.y);
  7830. ctx.lineTo(top.screen.x, top.screen.y);
  7831. ctx.closePath();
  7832. ctx.fill();
  7833. ctx.stroke(); // TODO: only draw stroke when strokeWidth > 0
  7834. }
  7835. }
  7836. } else {
  7837. // grid style
  7838. for (i = 0; i < this.dataPoints.length; i++) {
  7839. point = this.dataPoints[i];
  7840. right = this.dataPoints[i].pointRight;
  7841. top = this.dataPoints[i].pointTop;
  7842. if (point !== undefined && right !== undefined) {
  7843. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  7844. zAvg = (point.point.z + right.point.z) / 2;
  7845. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  7846. ctx.lineWidth = this._getStrokeWidth(point) * 2;
  7847. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  7848. ctx.beginPath();
  7849. ctx.moveTo(point.screen.x, point.screen.y);
  7850. ctx.lineTo(right.screen.x, right.screen.y);
  7851. ctx.stroke();
  7852. }
  7853. if (point !== undefined && top !== undefined) {
  7854. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  7855. zAvg = (point.point.z + top.point.z) / 2;
  7856. h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  7857. ctx.lineWidth = this._getStrokeWidth(point) * 2;
  7858. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  7859. ctx.beginPath();
  7860. ctx.moveTo(point.screen.x, point.screen.y);
  7861. ctx.lineTo(top.screen.x, top.screen.y);
  7862. ctx.stroke();
  7863. }
  7864. }
  7865. }
  7866. };
  7867. Graph3d.prototype._getStrokeWidth = function (point) {
  7868. if (point !== undefined) {
  7869. if (this.showPerspective) {
  7870. return 1 / -point.trans.z * this.dataColor.strokeWidth;
  7871. } else {
  7872. return -(this.eye.z / this.camera.getArmLength()) * this.dataColor.strokeWidth;
  7873. }
  7874. }
  7875. return this.dataColor.strokeWidth;
  7876. };
  7877. /**
  7878. * Draw all datapoints as dots.
  7879. * This function can be used when the style is 'dot' or 'dot-line'
  7880. */
  7881. Graph3d.prototype._redrawDataDot = function () {
  7882. var canvas = this.frame.canvas;
  7883. var ctx = canvas.getContext('2d');
  7884. var i;
  7885. if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception?
  7886. // calculate the translations of all points
  7887. for (i = 0; i < this.dataPoints.length; i++) {
  7888. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  7889. var screen = this._convertTranslationToScreen(trans);
  7890. this.dataPoints[i].trans = trans;
  7891. this.dataPoints[i].screen = screen;
  7892. // calculate the distance from the point at the bottom to the camera
  7893. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  7894. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  7895. }
  7896. // order the translated points by depth
  7897. var sortDepth = function sortDepth(a, b) {
  7898. return b.dist - a.dist;
  7899. };
  7900. this.dataPoints.sort(sortDepth);
  7901. // draw the datapoints as colored circles
  7902. var dotSize = this.frame.clientWidth * this.dotSizeRatio; // px
  7903. for (i = 0; i < this.dataPoints.length; i++) {
  7904. var point = this.dataPoints[i];
  7905. if (this.style === Graph3d.STYLE.DOTLINE) {
  7906. // draw a vertical line from the bottom to the graph value
  7907. //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
  7908. var from = this._convert3Dto2D(point.bottom);
  7909. ctx.lineWidth = 1;
  7910. ctx.strokeStyle = this.gridColor;
  7911. ctx.beginPath();
  7912. ctx.moveTo(from.x, from.y);
  7913. ctx.lineTo(point.screen.x, point.screen.y);
  7914. ctx.stroke();
  7915. }
  7916. // calculate radius for the circle
  7917. var size;
  7918. if (this.style === Graph3d.STYLE.DOTSIZE) {
  7919. size = dotSize / 2 + 2 * dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
  7920. } else {
  7921. size = dotSize;
  7922. }
  7923. var radius;
  7924. if (this.showPerspective) {
  7925. radius = size / -point.trans.z;
  7926. } else {
  7927. radius = size * -(this.eye.z / this.camera.getArmLength());
  7928. }
  7929. if (radius < 0) {
  7930. radius = 0;
  7931. }
  7932. var hue, color, borderColor;
  7933. if (this.style === Graph3d.STYLE.DOTCOLOR) {
  7934. // calculate the color based on the value
  7935. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  7936. color = this._hsv2rgb(hue, 1, 1);
  7937. borderColor = this._hsv2rgb(hue, 1, 0.8);
  7938. } else if (this.style === Graph3d.STYLE.DOTSIZE) {
  7939. color = this.dataColor.fill;
  7940. borderColor = this.dataColor.stroke;
  7941. } else {
  7942. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  7943. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  7944. color = this._hsv2rgb(hue, 1, 1);
  7945. borderColor = this._hsv2rgb(hue, 1, 0.8);
  7946. }
  7947. // draw the circle
  7948. ctx.lineWidth = this._getStrokeWidth(point);
  7949. ctx.strokeStyle = borderColor;
  7950. ctx.fillStyle = color;
  7951. ctx.beginPath();
  7952. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true);
  7953. ctx.fill();
  7954. ctx.stroke();
  7955. }
  7956. };
  7957. /**
  7958. * Draw all datapoints as bars.
  7959. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
  7960. */
  7961. Graph3d.prototype._redrawDataBar = function () {
  7962. var canvas = this.frame.canvas;
  7963. var ctx = canvas.getContext('2d');
  7964. var i, j, surface, corners;
  7965. if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception?
  7966. // calculate the translations of all points
  7967. for (i = 0; i < this.dataPoints.length; i++) {
  7968. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  7969. var screen = this._convertTranslationToScreen(trans);
  7970. this.dataPoints[i].trans = trans;
  7971. this.dataPoints[i].screen = screen;
  7972. // calculate the distance from the point at the bottom to the camera
  7973. var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
  7974. this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  7975. }
  7976. // order the translated points by depth
  7977. var sortDepth = function sortDepth(a, b) {
  7978. return b.dist - a.dist;
  7979. };
  7980. this.dataPoints.sort(sortDepth);
  7981. ctx.lineJoin = 'round';
  7982. ctx.lineCap = 'round';
  7983. // draw the datapoints as bars
  7984. var xWidth = this.xBarWidth / 2;
  7985. var yWidth = this.yBarWidth / 2;
  7986. for (i = 0; i < this.dataPoints.length; i++) {
  7987. var point = this.dataPoints[i];
  7988. // determine color
  7989. var hue, color, borderColor;
  7990. if (this.style === Graph3d.STYLE.BARCOLOR) {
  7991. // calculate the color based on the value
  7992. hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
  7993. color = this._hsv2rgb(hue, 1, 1);
  7994. borderColor = this._hsv2rgb(hue, 1, 0.8);
  7995. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  7996. color = this.dataColor.fill;
  7997. borderColor = this.dataColor.stroke;
  7998. } else {
  7999. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  8000. hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
  8001. color = this._hsv2rgb(hue, 1, 1);
  8002. borderColor = this._hsv2rgb(hue, 1, 0.8);
  8003. }
  8004. // calculate size for the bar
  8005. if (this.style === Graph3d.STYLE.BARSIZE) {
  8006. xWidth = this.xBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  8007. yWidth = this.yBarWidth / 2 * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
  8008. }
  8009. // calculate all corner points
  8010. var me = this;
  8011. var point3d = point.point;
  8012. var top = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z) }];
  8013. var bottom = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin) }];
  8014. // calculate screen location of the points
  8015. top.forEach(function (obj) {
  8016. obj.screen = me._convert3Dto2D(obj.point);
  8017. });
  8018. bottom.forEach(function (obj) {
  8019. obj.screen = me._convert3Dto2D(obj.point);
  8020. });
  8021. // create five sides, calculate both corner points and center points
  8022. var surfaces = [{ corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point) }, { corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point) }, { corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point) }, { corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point) }, { corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point) }];
  8023. point.surfaces = surfaces;
  8024. // calculate the distance of each of the surface centers to the camera
  8025. for (j = 0; j < surfaces.length; j++) {
  8026. surface = surfaces[j];
  8027. var transCenter = this._convertPointToTranslation(surface.center);
  8028. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  8029. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  8030. // but the current solution is fast/simple and works in 99.9% of all cases
  8031. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  8032. }
  8033. // order the surfaces by their (translated) depth
  8034. surfaces.sort(function (a, b) {
  8035. var diff = b.dist - a.dist;
  8036. if (diff) return diff;
  8037. // if equal depth, sort the top surface last
  8038. if (a.corners === top) return 1;
  8039. if (b.corners === top) return -1;
  8040. // both are equal
  8041. return 0;
  8042. });
  8043. // draw the ordered surfaces
  8044. ctx.lineWidth = this._getStrokeWidth(point);
  8045. ctx.strokeStyle = borderColor;
  8046. ctx.fillStyle = color;
  8047. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  8048. for (j = 2; j < surfaces.length; j++) {
  8049. surface = surfaces[j];
  8050. corners = surface.corners;
  8051. ctx.beginPath();
  8052. ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
  8053. ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
  8054. ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
  8055. ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
  8056. ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
  8057. ctx.fill();
  8058. ctx.stroke();
  8059. }
  8060. }
  8061. };
  8062. /**
  8063. * Draw a line through all datapoints.
  8064. * This function can be used when the style is 'line'
  8065. */
  8066. Graph3d.prototype._redrawDataLine = function () {
  8067. var canvas = this.frame.canvas,
  8068. ctx = canvas.getContext('2d'),
  8069. point,
  8070. i;
  8071. if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception?
  8072. // calculate the translations of all points
  8073. for (i = 0; i < this.dataPoints.length; i++) {
  8074. var trans = this._convertPointToTranslation(this.dataPoints[i].point);
  8075. var screen = this._convertTranslationToScreen(trans);
  8076. this.dataPoints[i].trans = trans;
  8077. this.dataPoints[i].screen = screen;
  8078. }
  8079. // start the line
  8080. if (this.dataPoints.length > 0) {
  8081. point = this.dataPoints[0];
  8082. ctx.lineWidth = this._getStrokeWidth(point);
  8083. ctx.lineJoin = 'round';
  8084. ctx.lineCap = 'round';
  8085. ctx.strokeStyle = this.dataColor.stroke;
  8086. ctx.beginPath();
  8087. ctx.moveTo(point.screen.x, point.screen.y);
  8088. // draw the datapoints as colored circles
  8089. for (i = 1; i < this.dataPoints.length; i++) {
  8090. point = this.dataPoints[i];
  8091. ctx.lineTo(point.screen.x, point.screen.y);
  8092. }
  8093. // finish the line
  8094. ctx.stroke();
  8095. }
  8096. };
  8097. /**
  8098. * Start a moving operation inside the provided parent element
  8099. * @param {Event} event The event that occurred (required for
  8100. * retrieving the mouse position)
  8101. */
  8102. Graph3d.prototype._onMouseDown = function (event) {
  8103. event = event || window.event;
  8104. // check if mouse is still down (may be up when focus is lost for example
  8105. // in an iframe)
  8106. if (this.leftButtonDown) {
  8107. this._onMouseUp(event);
  8108. }
  8109. // only react on left mouse button down
  8110. this.leftButtonDown = event.which ? event.which === 1 : event.button === 1;
  8111. if (!this.leftButtonDown && !this.touchDown) return;
  8112. // get mouse position (different code for IE and all other browsers)
  8113. this.startMouseX = getMouseX(event);
  8114. this.startMouseY = getMouseY(event);
  8115. this.startStart = new Date(this.start);
  8116. this.startEnd = new Date(this.end);
  8117. this.startArmRotation = this.camera.getArmRotation();
  8118. this.frame.style.cursor = 'move';
  8119. // add event listeners to handle moving the contents
  8120. // we store the function onmousemove and onmouseup in the graph, so we can
  8121. // remove the eventlisteners lateron in the function mouseUp()
  8122. var me = this;
  8123. this.onmousemove = function (event) {
  8124. me._onMouseMove(event);
  8125. };
  8126. this.onmouseup = function (event) {
  8127. me._onMouseUp(event);
  8128. };
  8129. util.addEventListener(document, 'mousemove', me.onmousemove);
  8130. util.addEventListener(document, 'mouseup', me.onmouseup);
  8131. util.preventDefault(event);
  8132. };
  8133. /**
  8134. * Perform moving operating.
  8135. * This function activated from within the funcion Graph.mouseDown().
  8136. * @param {Event} event Well, eehh, the event
  8137. */
  8138. Graph3d.prototype._onMouseMove = function (event) {
  8139. event = event || window.event;
  8140. // calculate change in mouse position
  8141. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  8142. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  8143. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  8144. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  8145. var snapAngle = 4; // degrees
  8146. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  8147. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  8148. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  8149. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  8150. horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001;
  8151. }
  8152. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  8153. horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001;
  8154. }
  8155. // snap vertically to nice angles
  8156. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  8157. verticalNew = Math.round(verticalNew / Math.PI) * Math.PI;
  8158. }
  8159. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  8160. verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI;
  8161. }
  8162. this.camera.setArmRotation(horizontalNew, verticalNew);
  8163. this.redraw();
  8164. // fire a cameraPositionChange event
  8165. var parameters = this.getCameraPosition();
  8166. this.emit('cameraPositionChange', parameters);
  8167. util.preventDefault(event);
  8168. };
  8169. /**
  8170. * Stop moving operating.
  8171. * This function activated from within the funcion Graph.mouseDown().
  8172. * @param {event} event The event
  8173. */
  8174. Graph3d.prototype._onMouseUp = function (event) {
  8175. this.frame.style.cursor = 'auto';
  8176. this.leftButtonDown = false;
  8177. // remove event listeners here
  8178. util.removeEventListener(document, 'mousemove', this.onmousemove);
  8179. util.removeEventListener(document, 'mouseup', this.onmouseup);
  8180. util.preventDefault(event);
  8181. };
  8182. /**
  8183. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  8184. * @param {Event} event A mouse move event
  8185. */
  8186. Graph3d.prototype._onTooltip = function (event) {
  8187. var delay = 300; // ms
  8188. var boundingRect = this.frame.getBoundingClientRect();
  8189. var mouseX = getMouseX(event) - boundingRect.left;
  8190. var mouseY = getMouseY(event) - boundingRect.top;
  8191. if (!this.showTooltip) {
  8192. return;
  8193. }
  8194. if (this.tooltipTimeout) {
  8195. clearTimeout(this.tooltipTimeout);
  8196. }
  8197. // (delayed) display of a tooltip only if no mouse button is down
  8198. if (this.leftButtonDown) {
  8199. this._hideTooltip();
  8200. return;
  8201. }
  8202. if (this.tooltip && this.tooltip.dataPoint) {
  8203. // tooltip is currently visible
  8204. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  8205. if (dataPoint !== this.tooltip.dataPoint) {
  8206. // datapoint changed
  8207. if (dataPoint) {
  8208. this._showTooltip(dataPoint);
  8209. } else {
  8210. this._hideTooltip();
  8211. }
  8212. }
  8213. } else {
  8214. // tooltip is currently not visible
  8215. var me = this;
  8216. this.tooltipTimeout = setTimeout(function () {
  8217. me.tooltipTimeout = null;
  8218. // show a tooltip if we have a data point
  8219. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  8220. if (dataPoint) {
  8221. me._showTooltip(dataPoint);
  8222. }
  8223. }, delay);
  8224. }
  8225. };
  8226. /**
  8227. * Event handler for touchstart event on mobile devices
  8228. */
  8229. Graph3d.prototype._onTouchStart = function (event) {
  8230. this.touchDown = true;
  8231. var me = this;
  8232. this.ontouchmove = function (event) {
  8233. me._onTouchMove(event);
  8234. };
  8235. this.ontouchend = function (event) {
  8236. me._onTouchEnd(event);
  8237. };
  8238. util.addEventListener(document, 'touchmove', me.ontouchmove);
  8239. util.addEventListener(document, 'touchend', me.ontouchend);
  8240. this._onMouseDown(event);
  8241. };
  8242. /**
  8243. * Event handler for touchmove event on mobile devices
  8244. */
  8245. Graph3d.prototype._onTouchMove = function (event) {
  8246. this._onMouseMove(event);
  8247. };
  8248. /**
  8249. * Event handler for touchend event on mobile devices
  8250. */
  8251. Graph3d.prototype._onTouchEnd = function (event) {
  8252. this.touchDown = false;
  8253. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  8254. util.removeEventListener(document, 'touchend', this.ontouchend);
  8255. this._onMouseUp(event);
  8256. };
  8257. /**
  8258. * Event handler for mouse wheel event, used to zoom the graph
  8259. * Code from http://adomas.org/javascript-mouse-wheel/
  8260. * @param {event} event The event
  8261. */
  8262. Graph3d.prototype._onWheel = function (event) {
  8263. if (!event) /* For IE. */
  8264. event = window.event;
  8265. // retrieve delta
  8266. var delta = 0;
  8267. if (event.wheelDelta) {
  8268. /* IE/Opera. */
  8269. delta = event.wheelDelta / 120;
  8270. } else if (event.detail) {
  8271. /* Mozilla case. */
  8272. // In Mozilla, sign of delta is different than in IE.
  8273. // Also, delta is multiple of 3.
  8274. delta = -event.detail / 3;
  8275. }
  8276. // If delta is nonzero, handle it.
  8277. // Basically, delta is now positive if wheel was scrolled up,
  8278. // and negative, if wheel was scrolled down.
  8279. if (delta) {
  8280. var oldLength = this.camera.getArmLength();
  8281. var newLength = oldLength * (1 - delta / 10);
  8282. this.camera.setArmLength(newLength);
  8283. this.redraw();
  8284. this._hideTooltip();
  8285. }
  8286. // fire a cameraPositionChange event
  8287. var parameters = this.getCameraPosition();
  8288. this.emit('cameraPositionChange', parameters);
  8289. // Prevent default actions caused by mouse wheel.
  8290. // That might be ugly, but we handle scrolls somehow
  8291. // anyway, so don't bother here..
  8292. util.preventDefault(event);
  8293. };
  8294. /**
  8295. * Test whether a point lies inside given 2D triangle
  8296. * @param {Point2d} point
  8297. * @param {Point2d[]} triangle
  8298. * @return {boolean} Returns true if given point lies inside or on the edge of the triangle
  8299. * @private
  8300. */
  8301. Graph3d.prototype._insideTriangle = function (point, triangle) {
  8302. var a = triangle[0],
  8303. b = triangle[1],
  8304. c = triangle[2];
  8305. function sign(x) {
  8306. return x > 0 ? 1 : x < 0 ? -1 : 0;
  8307. }
  8308. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  8309. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  8310. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  8311. // each of the three signs must be either equal to each other or zero
  8312. return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs);
  8313. };
  8314. /**
  8315. * Find a data point close to given screen position (x, y)
  8316. * @param {Number} x
  8317. * @param {Number} y
  8318. * @return {Object | null} The closest data point or null if not close to any data point
  8319. * @private
  8320. */
  8321. Graph3d.prototype._dataPointFromXY = function (x, y) {
  8322. var i,
  8323. distMax = 100,
  8324. // px
  8325. dataPoint = null,
  8326. closestDataPoint = null,
  8327. closestDist = null,
  8328. center = new Point2d(x, y);
  8329. if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) {
  8330. // the data points are ordered from far away to closest
  8331. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  8332. dataPoint = this.dataPoints[i];
  8333. var surfaces = dataPoint.surfaces;
  8334. if (surfaces) {
  8335. for (var s = surfaces.length - 1; s >= 0; s--) {
  8336. // split each surface in two triangles, and see if the center point is inside one of these
  8337. var surface = surfaces[s];
  8338. var corners = surface.corners;
  8339. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  8340. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  8341. if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) {
  8342. // return immediately at the first hit
  8343. return dataPoint;
  8344. }
  8345. }
  8346. }
  8347. }
  8348. } else {
  8349. // find the closest data point, using distance to the center of the point on 2d screen
  8350. for (i = 0; i < this.dataPoints.length; i++) {
  8351. dataPoint = this.dataPoints[i];
  8352. var point = dataPoint.screen;
  8353. if (point) {
  8354. var distX = Math.abs(x - point.x);
  8355. var distY = Math.abs(y - point.y);
  8356. var dist = Math.sqrt(distX * distX + distY * distY);
  8357. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  8358. closestDist = dist;
  8359. closestDataPoint = dataPoint;
  8360. }
  8361. }
  8362. }
  8363. }
  8364. return closestDataPoint;
  8365. };
  8366. /**
  8367. * Display a tooltip for given data point
  8368. * @param {Object} dataPoint
  8369. * @private
  8370. */
  8371. Graph3d.prototype._showTooltip = function (dataPoint) {
  8372. var content, line, dot;
  8373. if (!this.tooltip) {
  8374. content = document.createElement('div');
  8375. content.style.position = 'absolute';
  8376. content.style.padding = '10px';
  8377. content.style.border = '1px solid #4d4d4d';
  8378. content.style.color = '#1a1a1a';
  8379. content.style.background = 'rgba(255,255,255,0.7)';
  8380. content.style.borderRadius = '2px';
  8381. content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
  8382. line = document.createElement('div');
  8383. line.style.position = 'absolute';
  8384. line.style.height = '40px';
  8385. line.style.width = '0';
  8386. line.style.borderLeft = '1px solid #4d4d4d';
  8387. dot = document.createElement('div');
  8388. dot.style.position = 'absolute';
  8389. dot.style.height = '0';
  8390. dot.style.width = '0';
  8391. dot.style.border = '5px solid #4d4d4d';
  8392. dot.style.borderRadius = '5px';
  8393. this.tooltip = {
  8394. dataPoint: null,
  8395. dom: {
  8396. content: content,
  8397. line: line,
  8398. dot: dot
  8399. }
  8400. };
  8401. } else {
  8402. content = this.tooltip.dom.content;
  8403. line = this.tooltip.dom.line;
  8404. dot = this.tooltip.dom.dot;
  8405. }
  8406. this._hideTooltip();
  8407. this.tooltip.dataPoint = dataPoint;
  8408. if (typeof this.showTooltip === 'function') {
  8409. content.innerHTML = this.showTooltip(dataPoint.point);
  8410. } else {
  8411. content.innerHTML = '<table>' + '<tr><td>' + this.xLabel + ':</td><td>' + dataPoint.point.x + '</td></tr>' + '<tr><td>' + this.yLabel + ':</td><td>' + dataPoint.point.y + '</td></tr>' + '<tr><td>' + this.zLabel + ':</td><td>' + dataPoint.point.z + '</td></tr>' + '</table>';
  8412. }
  8413. content.style.left = '0';
  8414. content.style.top = '0';
  8415. this.frame.appendChild(content);
  8416. this.frame.appendChild(line);
  8417. this.frame.appendChild(dot);
  8418. // calculate sizes
  8419. var contentWidth = content.offsetWidth;
  8420. var contentHeight = content.offsetHeight;
  8421. var lineHeight = line.offsetHeight;
  8422. var dotWidth = dot.offsetWidth;
  8423. var dotHeight = dot.offsetHeight;
  8424. var left = dataPoint.screen.x - contentWidth / 2;
  8425. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  8426. line.style.left = dataPoint.screen.x + 'px';
  8427. line.style.top = dataPoint.screen.y - lineHeight + 'px';
  8428. content.style.left = left + 'px';
  8429. content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px';
  8430. dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px';
  8431. dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px';
  8432. };
  8433. /**
  8434. * Hide the tooltip when displayed
  8435. * @private
  8436. */
  8437. Graph3d.prototype._hideTooltip = function () {
  8438. if (this.tooltip) {
  8439. this.tooltip.dataPoint = null;
  8440. for (var prop in this.tooltip.dom) {
  8441. if (this.tooltip.dom.hasOwnProperty(prop)) {
  8442. var elem = this.tooltip.dom[prop];
  8443. if (elem && elem.parentNode) {
  8444. elem.parentNode.removeChild(elem);
  8445. }
  8446. }
  8447. }
  8448. }
  8449. };
  8450. /**--------------------------------------------------------------------------**/
  8451. /**
  8452. * Get the horizontal mouse position from a mouse event
  8453. * @param {Event} event
  8454. * @return {Number} mouse x
  8455. */
  8456. function getMouseX(event) {
  8457. if ('clientX' in event) return event.clientX;
  8458. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  8459. }
  8460. /**
  8461. * Get the vertical mouse position from a mouse event
  8462. * @param {Event} event
  8463. * @return {Number} mouse y
  8464. */
  8465. function getMouseY(event) {
  8466. if ('clientY' in event) return event.clientY;
  8467. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  8468. }
  8469. module.exports = Graph3d;
  8470. /***/ },
  8471. /* 13 */
  8472. /***/ function(module, exports) {
  8473. /**
  8474. * Expose `Emitter`.
  8475. */
  8476. module.exports = Emitter;
  8477. /**
  8478. * Initialize a new `Emitter`.
  8479. *
  8480. * @api public
  8481. */
  8482. function Emitter(obj) {
  8483. if (obj) return mixin(obj);
  8484. };
  8485. /**
  8486. * Mixin the emitter properties.
  8487. *
  8488. * @param {Object} obj
  8489. * @return {Object}
  8490. * @api private
  8491. */
  8492. function mixin(obj) {
  8493. for (var key in Emitter.prototype) {
  8494. obj[key] = Emitter.prototype[key];
  8495. }
  8496. return obj;
  8497. }
  8498. /**
  8499. * Listen on the given `event` with `fn`.
  8500. *
  8501. * @param {String} event
  8502. * @param {Function} fn
  8503. * @return {Emitter}
  8504. * @api public
  8505. */
  8506. Emitter.prototype.on =
  8507. Emitter.prototype.addEventListener = function(event, fn){
  8508. this._callbacks = this._callbacks || {};
  8509. (this._callbacks[event] = this._callbacks[event] || [])
  8510. .push(fn);
  8511. return this;
  8512. };
  8513. /**
  8514. * Adds an `event` listener that will be invoked a single
  8515. * time then automatically removed.
  8516. *
  8517. * @param {String} event
  8518. * @param {Function} fn
  8519. * @return {Emitter}
  8520. * @api public
  8521. */
  8522. Emitter.prototype.once = function(event, fn){
  8523. var self = this;
  8524. this._callbacks = this._callbacks || {};
  8525. function on() {
  8526. self.off(event, on);
  8527. fn.apply(this, arguments);
  8528. }
  8529. on.fn = fn;
  8530. this.on(event, on);
  8531. return this;
  8532. };
  8533. /**
  8534. * Remove the given callback for `event` or all
  8535. * registered callbacks.
  8536. *
  8537. * @param {String} event
  8538. * @param {Function} fn
  8539. * @return {Emitter}
  8540. * @api public
  8541. */
  8542. Emitter.prototype.off =
  8543. Emitter.prototype.removeListener =
  8544. Emitter.prototype.removeAllListeners =
  8545. Emitter.prototype.removeEventListener = function(event, fn){
  8546. this._callbacks = this._callbacks || {};
  8547. // all
  8548. if (0 == arguments.length) {
  8549. this._callbacks = {};
  8550. return this;
  8551. }
  8552. // specific event
  8553. var callbacks = this._callbacks[event];
  8554. if (!callbacks) return this;
  8555. // remove all handlers
  8556. if (1 == arguments.length) {
  8557. delete this._callbacks[event];
  8558. return this;
  8559. }
  8560. // remove specific handler
  8561. var cb;
  8562. for (var i = 0; i < callbacks.length; i++) {
  8563. cb = callbacks[i];
  8564. if (cb === fn || cb.fn === fn) {
  8565. callbacks.splice(i, 1);
  8566. break;
  8567. }
  8568. }
  8569. return this;
  8570. };
  8571. /**
  8572. * Emit `event` with the given args.
  8573. *
  8574. * @param {String} event
  8575. * @param {Mixed} ...
  8576. * @return {Emitter}
  8577. */
  8578. Emitter.prototype.emit = function(event){
  8579. this._callbacks = this._callbacks || {};
  8580. var args = [].slice.call(arguments, 1)
  8581. , callbacks = this._callbacks[event];
  8582. if (callbacks) {
  8583. callbacks = callbacks.slice(0);
  8584. for (var i = 0, len = callbacks.length; i < len; ++i) {
  8585. callbacks[i].apply(this, args);
  8586. }
  8587. }
  8588. return this;
  8589. };
  8590. /**
  8591. * Return array of callbacks for `event`.
  8592. *
  8593. * @param {String} event
  8594. * @return {Array}
  8595. * @api public
  8596. */
  8597. Emitter.prototype.listeners = function(event){
  8598. this._callbacks = this._callbacks || {};
  8599. return this._callbacks[event] || [];
  8600. };
  8601. /**
  8602. * Check if this emitter has `event` handlers.
  8603. *
  8604. * @param {String} event
  8605. * @return {Boolean}
  8606. * @api public
  8607. */
  8608. Emitter.prototype.hasListeners = function(event){
  8609. return !! this.listeners(event).length;
  8610. };
  8611. /***/ },
  8612. /* 14 */
  8613. /***/ function(module, exports) {
  8614. "use strict";
  8615. /**
  8616. * @prototype Point3d
  8617. * @param {Number} [x]
  8618. * @param {Number} [y]
  8619. * @param {Number} [z]
  8620. */
  8621. function Point3d(x, y, z) {
  8622. this.x = x !== undefined ? x : 0;
  8623. this.y = y !== undefined ? y : 0;
  8624. this.z = z !== undefined ? z : 0;
  8625. };
  8626. /**
  8627. * Subtract the two provided points, returns a-b
  8628. * @param {Point3d} a
  8629. * @param {Point3d} b
  8630. * @return {Point3d} a-b
  8631. */
  8632. Point3d.subtract = function (a, b) {
  8633. var sub = new Point3d();
  8634. sub.x = a.x - b.x;
  8635. sub.y = a.y - b.y;
  8636. sub.z = a.z - b.z;
  8637. return sub;
  8638. };
  8639. /**
  8640. * Add the two provided points, returns a+b
  8641. * @param {Point3d} a
  8642. * @param {Point3d} b
  8643. * @return {Point3d} a+b
  8644. */
  8645. Point3d.add = function (a, b) {
  8646. var sum = new Point3d();
  8647. sum.x = a.x + b.x;
  8648. sum.y = a.y + b.y;
  8649. sum.z = a.z + b.z;
  8650. return sum;
  8651. };
  8652. /**
  8653. * Calculate the average of two 3d points
  8654. * @param {Point3d} a
  8655. * @param {Point3d} b
  8656. * @return {Point3d} The average, (a+b)/2
  8657. */
  8658. Point3d.avg = function (a, b) {
  8659. return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2);
  8660. };
  8661. /**
  8662. * Calculate the cross product of the two provided points, returns axb
  8663. * Documentation: http://en.wikipedia.org/wiki/Cross_product
  8664. * @param {Point3d} a
  8665. * @param {Point3d} b
  8666. * @return {Point3d} cross product axb
  8667. */
  8668. Point3d.crossProduct = function (a, b) {
  8669. var crossproduct = new Point3d();
  8670. crossproduct.x = a.y * b.z - a.z * b.y;
  8671. crossproduct.y = a.z * b.x - a.x * b.z;
  8672. crossproduct.z = a.x * b.y - a.y * b.x;
  8673. return crossproduct;
  8674. };
  8675. /**
  8676. * Rtrieve the length of the vector (or the distance from this point to the origin
  8677. * @return {Number} length
  8678. */
  8679. Point3d.prototype.length = function () {
  8680. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  8681. };
  8682. module.exports = Point3d;
  8683. /***/ },
  8684. /* 15 */
  8685. /***/ function(module, exports) {
  8686. "use strict";
  8687. /**
  8688. * @prototype Point2d
  8689. * @param {Number} [x]
  8690. * @param {Number} [y]
  8691. */
  8692. function Point2d(x, y) {
  8693. this.x = x !== undefined ? x : 0;
  8694. this.y = y !== undefined ? y : 0;
  8695. }
  8696. module.exports = Point2d;
  8697. /***/ },
  8698. /* 16 */
  8699. /***/ function(module, exports, __webpack_require__) {
  8700. 'use strict';
  8701. var Point3d = __webpack_require__(14);
  8702. /**
  8703. * @class Camera
  8704. * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
  8705. * The camera is always looking in the direction of the origin of the arm.
  8706. * This way, the camera always rotates around one fixed point, the location
  8707. * of the camera arm.
  8708. *
  8709. * Documentation:
  8710. * http://en.wikipedia.org/wiki/3D_projection
  8711. */
  8712. function Camera() {
  8713. this.armLocation = new Point3d();
  8714. this.armRotation = {};
  8715. this.armRotation.horizontal = 0;
  8716. this.armRotation.vertical = 0;
  8717. this.armLength = 1.7;
  8718. this.cameraLocation = new Point3d();
  8719. this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0);
  8720. this.calculateCameraOrientation();
  8721. }
  8722. /**
  8723. * Set the location (origin) of the arm
  8724. * @param {Number} x Normalized value of x
  8725. * @param {Number} y Normalized value of y
  8726. * @param {Number} z Normalized value of z
  8727. */
  8728. Camera.prototype.setArmLocation = function (x, y, z) {
  8729. this.armLocation.x = x;
  8730. this.armLocation.y = y;
  8731. this.armLocation.z = z;
  8732. this.calculateCameraOrientation();
  8733. };
  8734. /**
  8735. * Set the rotation of the camera arm
  8736. * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
  8737. * Optional, can be left undefined.
  8738. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
  8739. * if vertical=0.5*PI, the graph is shown from the
  8740. * top. Optional, can be left undefined.
  8741. */
  8742. Camera.prototype.setArmRotation = function (horizontal, vertical) {
  8743. if (horizontal !== undefined) {
  8744. this.armRotation.horizontal = horizontal;
  8745. }
  8746. if (vertical !== undefined) {
  8747. this.armRotation.vertical = vertical;
  8748. if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
  8749. if (this.armRotation.vertical > 0.5 * Math.PI) this.armRotation.vertical = 0.5 * Math.PI;
  8750. }
  8751. if (horizontal !== undefined || vertical !== undefined) {
  8752. this.calculateCameraOrientation();
  8753. }
  8754. };
  8755. /**
  8756. * Retrieve the current arm rotation
  8757. * @return {object} An object with parameters horizontal and vertical
  8758. */
  8759. Camera.prototype.getArmRotation = function () {
  8760. var rot = {};
  8761. rot.horizontal = this.armRotation.horizontal;
  8762. rot.vertical = this.armRotation.vertical;
  8763. return rot;
  8764. };
  8765. /**
  8766. * Set the (normalized) length of the camera arm.
  8767. * @param {Number} length A length between 0.71 and 5.0
  8768. */
  8769. Camera.prototype.setArmLength = function (length) {
  8770. if (length === undefined) return;
  8771. this.armLength = length;
  8772. // Radius must be larger than the corner of the graph,
  8773. // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
  8774. // graph
  8775. if (this.armLength < 0.71) this.armLength = 0.71;
  8776. if (this.armLength > 5.0) this.armLength = 5.0;
  8777. this.calculateCameraOrientation();
  8778. };
  8779. /**
  8780. * Retrieve the arm length
  8781. * @return {Number} length
  8782. */
  8783. Camera.prototype.getArmLength = function () {
  8784. return this.armLength;
  8785. };
  8786. /**
  8787. * Retrieve the camera location
  8788. * @return {Point3d} cameraLocation
  8789. */
  8790. Camera.prototype.getCameraLocation = function () {
  8791. return this.cameraLocation;
  8792. };
  8793. /**
  8794. * Retrieve the camera rotation
  8795. * @return {Point3d} cameraRotation
  8796. */
  8797. Camera.prototype.getCameraRotation = function () {
  8798. return this.cameraRotation;
  8799. };
  8800. /**
  8801. * Calculate the location and rotation of the camera based on the
  8802. * position and orientation of the camera arm
  8803. */
  8804. Camera.prototype.calculateCameraOrientation = function () {
  8805. // calculate location of the camera
  8806. this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  8807. this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  8808. this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
  8809. // calculate rotation of the camera
  8810. this.cameraRotation.x = Math.PI / 2 - this.armRotation.vertical;
  8811. this.cameraRotation.y = 0;
  8812. this.cameraRotation.z = -this.armRotation.horizontal;
  8813. };
  8814. module.exports = Camera;
  8815. /***/ },
  8816. /* 17 */
  8817. /***/ function(module, exports, __webpack_require__) {
  8818. 'use strict';
  8819. var DataView = __webpack_require__(11);
  8820. /**
  8821. * @class Filter
  8822. *
  8823. * @param {DataSet} data The google data table
  8824. * @param {Number} column The index of the column to be filtered
  8825. * @param {Graph} graph The graph
  8826. */
  8827. function Filter(data, column, graph) {
  8828. this.data = data;
  8829. this.column = column;
  8830. this.graph = graph; // the parent graph
  8831. this.index = undefined;
  8832. this.value = undefined;
  8833. // read all distinct values and select the first one
  8834. this.values = graph.getDistinctValues(data.get(), this.column);
  8835. // sort both numeric and string values correctly
  8836. this.values.sort(function (a, b) {
  8837. return a > b ? 1 : a < b ? -1 : 0;
  8838. });
  8839. if (this.values.length > 0) {
  8840. this.selectValue(0);
  8841. }
  8842. // create an array with the filtered datapoints. this will be loaded afterwards
  8843. this.dataPoints = [];
  8844. this.loaded = false;
  8845. this.onLoadCallback = undefined;
  8846. if (graph.animationPreload) {
  8847. this.loaded = false;
  8848. this.loadInBackground();
  8849. } else {
  8850. this.loaded = true;
  8851. }
  8852. };
  8853. /**
  8854. * Return the label
  8855. * @return {string} label
  8856. */
  8857. Filter.prototype.isLoaded = function () {
  8858. return this.loaded;
  8859. };
  8860. /**
  8861. * Return the loaded progress
  8862. * @return {Number} percentage between 0 and 100
  8863. */
  8864. Filter.prototype.getLoadedProgress = function () {
  8865. var len = this.values.length;
  8866. var i = 0;
  8867. while (this.dataPoints[i]) {
  8868. i++;
  8869. }
  8870. return Math.round(i / len * 100);
  8871. };
  8872. /**
  8873. * Return the label
  8874. * @return {string} label
  8875. */
  8876. Filter.prototype.getLabel = function () {
  8877. return this.graph.filterLabel;
  8878. };
  8879. /**
  8880. * Return the columnIndex of the filter
  8881. * @return {Number} columnIndex
  8882. */
  8883. Filter.prototype.getColumn = function () {
  8884. return this.column;
  8885. };
  8886. /**
  8887. * Return the currently selected value. Returns undefined if there is no selection
  8888. * @return {*} value
  8889. */
  8890. Filter.prototype.getSelectedValue = function () {
  8891. if (this.index === undefined) return undefined;
  8892. return this.values[this.index];
  8893. };
  8894. /**
  8895. * Retrieve all values of the filter
  8896. * @return {Array} values
  8897. */
  8898. Filter.prototype.getValues = function () {
  8899. return this.values;
  8900. };
  8901. /**
  8902. * Retrieve one value of the filter
  8903. * @param {Number} index
  8904. * @return {*} value
  8905. */
  8906. Filter.prototype.getValue = function (index) {
  8907. if (index >= this.values.length) throw 'Error: index out of range';
  8908. return this.values[index];
  8909. };
  8910. /**
  8911. * Retrieve the (filtered) dataPoints for the currently selected filter index
  8912. * @param {Number} [index] (optional)
  8913. * @return {Array} dataPoints
  8914. */
  8915. Filter.prototype._getDataPoints = function (index) {
  8916. if (index === undefined) index = this.index;
  8917. if (index === undefined) return [];
  8918. var dataPoints;
  8919. if (this.dataPoints[index]) {
  8920. dataPoints = this.dataPoints[index];
  8921. } else {
  8922. var f = {};
  8923. f.column = this.column;
  8924. f.value = this.values[index];
  8925. var dataView = new DataView(this.data, { filter: function filter(item) {
  8926. return item[f.column] == f.value;
  8927. } }).get();
  8928. dataPoints = this.graph._getDataPoints(dataView);
  8929. this.dataPoints[index] = dataPoints;
  8930. }
  8931. return dataPoints;
  8932. };
  8933. /**
  8934. * Set a callback function when the filter is fully loaded.
  8935. */
  8936. Filter.prototype.setOnLoadCallback = function (callback) {
  8937. this.onLoadCallback = callback;
  8938. };
  8939. /**
  8940. * Add a value to the list with available values for this filter
  8941. * No double entries will be created.
  8942. * @param {Number} index
  8943. */
  8944. Filter.prototype.selectValue = function (index) {
  8945. if (index >= this.values.length) throw 'Error: index out of range';
  8946. this.index = index;
  8947. this.value = this.values[index];
  8948. };
  8949. /**
  8950. * Load all filtered rows in the background one by one
  8951. * Start this method without providing an index!
  8952. */
  8953. Filter.prototype.loadInBackground = function (index) {
  8954. if (index === undefined) index = 0;
  8955. var frame = this.graph.frame;
  8956. if (index < this.values.length) {
  8957. var dataPointsTemp = this._getDataPoints(index);
  8958. //this.graph.redrawInfo(); // TODO: not neat
  8959. // create a progress box
  8960. if (frame.progress === undefined) {
  8961. frame.progress = document.createElement('DIV');
  8962. frame.progress.style.position = 'absolute';
  8963. frame.progress.style.color = 'gray';
  8964. frame.appendChild(frame.progress);
  8965. }
  8966. var progress = this.getLoadedProgress();
  8967. frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
  8968. // TODO: this is no nice solution...
  8969. frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
  8970. frame.progress.style.left = 10 + 'px';
  8971. var me = this;
  8972. setTimeout(function () {
  8973. me.loadInBackground(index + 1);
  8974. }, 10);
  8975. this.loaded = false;
  8976. } else {
  8977. this.loaded = true;
  8978. // remove the progress box
  8979. if (frame.progress !== undefined) {
  8980. frame.removeChild(frame.progress);
  8981. frame.progress = undefined;
  8982. }
  8983. if (this.onLoadCallback) this.onLoadCallback();
  8984. }
  8985. };
  8986. module.exports = Filter;
  8987. /***/ },
  8988. /* 18 */
  8989. /***/ function(module, exports, __webpack_require__) {
  8990. 'use strict';
  8991. var util = __webpack_require__(1);
  8992. /**
  8993. * @constructor Slider
  8994. *
  8995. * An html slider control with start/stop/prev/next buttons
  8996. * @param {Element} container The element where the slider will be created
  8997. * @param {Object} options Available options:
  8998. * {boolean} visible If true (default) the
  8999. * slider is visible.
  9000. */
  9001. function Slider(container, options) {
  9002. if (container === undefined) {
  9003. throw 'Error: No container element defined';
  9004. }
  9005. this.container = container;
  9006. this.visible = options && options.visible != undefined ? options.visible : true;
  9007. if (this.visible) {
  9008. this.frame = document.createElement('DIV');
  9009. //this.frame.style.backgroundColor = '#E5E5E5';
  9010. this.frame.style.width = '100%';
  9011. this.frame.style.position = 'relative';
  9012. this.container.appendChild(this.frame);
  9013. this.frame.prev = document.createElement('INPUT');
  9014. this.frame.prev.type = 'BUTTON';
  9015. this.frame.prev.value = 'Prev';
  9016. this.frame.appendChild(this.frame.prev);
  9017. this.frame.play = document.createElement('INPUT');
  9018. this.frame.play.type = 'BUTTON';
  9019. this.frame.play.value = 'Play';
  9020. this.frame.appendChild(this.frame.play);
  9021. this.frame.next = document.createElement('INPUT');
  9022. this.frame.next.type = 'BUTTON';
  9023. this.frame.next.value = 'Next';
  9024. this.frame.appendChild(this.frame.next);
  9025. this.frame.bar = document.createElement('INPUT');
  9026. this.frame.bar.type = 'BUTTON';
  9027. this.frame.bar.style.position = 'absolute';
  9028. this.frame.bar.style.border = '1px solid red';
  9029. this.frame.bar.style.width = '100px';
  9030. this.frame.bar.style.height = '6px';
  9031. this.frame.bar.style.borderRadius = '2px';
  9032. this.frame.bar.style.MozBorderRadius = '2px';
  9033. this.frame.bar.style.border = '1px solid #7F7F7F';
  9034. this.frame.bar.style.backgroundColor = '#E5E5E5';
  9035. this.frame.appendChild(this.frame.bar);
  9036. this.frame.slide = document.createElement('INPUT');
  9037. this.frame.slide.type = 'BUTTON';
  9038. this.frame.slide.style.margin = '0px';
  9039. this.frame.slide.value = ' ';
  9040. this.frame.slide.style.position = 'relative';
  9041. this.frame.slide.style.left = '-100px';
  9042. this.frame.appendChild(this.frame.slide);
  9043. // create events
  9044. var me = this;
  9045. this.frame.slide.onmousedown = function (event) {
  9046. me._onMouseDown(event);
  9047. };
  9048. this.frame.prev.onclick = function (event) {
  9049. me.prev(event);
  9050. };
  9051. this.frame.play.onclick = function (event) {
  9052. me.togglePlay(event);
  9053. };
  9054. this.frame.next.onclick = function (event) {
  9055. me.next(event);
  9056. };
  9057. }
  9058. this.onChangeCallback = undefined;
  9059. this.values = [];
  9060. this.index = undefined;
  9061. this.playTimeout = undefined;
  9062. this.playInterval = 1000; // milliseconds
  9063. this.playLoop = true;
  9064. }
  9065. /**
  9066. * Select the previous index
  9067. */
  9068. Slider.prototype.prev = function () {
  9069. var index = this.getIndex();
  9070. if (index > 0) {
  9071. index--;
  9072. this.setIndex(index);
  9073. }
  9074. };
  9075. /**
  9076. * Select the next index
  9077. */
  9078. Slider.prototype.next = function () {
  9079. var index = this.getIndex();
  9080. if (index < this.values.length - 1) {
  9081. index++;
  9082. this.setIndex(index);
  9083. }
  9084. };
  9085. /**
  9086. * Select the next index
  9087. */
  9088. Slider.prototype.playNext = function () {
  9089. var start = new Date();
  9090. var index = this.getIndex();
  9091. if (index < this.values.length - 1) {
  9092. index++;
  9093. this.setIndex(index);
  9094. } else if (this.playLoop) {
  9095. // jump to the start
  9096. index = 0;
  9097. this.setIndex(index);
  9098. }
  9099. var end = new Date();
  9100. var diff = end - start;
  9101. // calculate how much time it to to set the index and to execute the callback
  9102. // function.
  9103. var interval = Math.max(this.playInterval - diff, 0);
  9104. // document.title = diff // TODO: cleanup
  9105. var me = this;
  9106. this.playTimeout = setTimeout(function () {
  9107. me.playNext();
  9108. }, interval);
  9109. };
  9110. /**
  9111. * Toggle start or stop playing
  9112. */
  9113. Slider.prototype.togglePlay = function () {
  9114. if (this.playTimeout === undefined) {
  9115. this.play();
  9116. } else {
  9117. this.stop();
  9118. }
  9119. };
  9120. /**
  9121. * Start playing
  9122. */
  9123. Slider.prototype.play = function () {
  9124. // Test whether already playing
  9125. if (this.playTimeout) return;
  9126. this.playNext();
  9127. if (this.frame) {
  9128. this.frame.play.value = 'Stop';
  9129. }
  9130. };
  9131. /**
  9132. * Stop playing
  9133. */
  9134. Slider.prototype.stop = function () {
  9135. clearInterval(this.playTimeout);
  9136. this.playTimeout = undefined;
  9137. if (this.frame) {
  9138. this.frame.play.value = 'Play';
  9139. }
  9140. };
  9141. /**
  9142. * Set a callback function which will be triggered when the value of the
  9143. * slider bar has changed.
  9144. */
  9145. Slider.prototype.setOnChangeCallback = function (callback) {
  9146. this.onChangeCallback = callback;
  9147. };
  9148. /**
  9149. * Set the interval for playing the list
  9150. * @param {Number} interval The interval in milliseconds
  9151. */
  9152. Slider.prototype.setPlayInterval = function (interval) {
  9153. this.playInterval = interval;
  9154. };
  9155. /**
  9156. * Retrieve the current play interval
  9157. * @return {Number} interval The interval in milliseconds
  9158. */
  9159. Slider.prototype.getPlayInterval = function (interval) {
  9160. return this.playInterval;
  9161. };
  9162. /**
  9163. * Set looping on or off
  9164. * @pararm {boolean} doLoop If true, the slider will jump to the start when
  9165. * the end is passed, and will jump to the end
  9166. * when the start is passed.
  9167. */
  9168. Slider.prototype.setPlayLoop = function (doLoop) {
  9169. this.playLoop = doLoop;
  9170. };
  9171. /**
  9172. * Execute the onchange callback function
  9173. */
  9174. Slider.prototype.onChange = function () {
  9175. if (this.onChangeCallback !== undefined) {
  9176. this.onChangeCallback();
  9177. }
  9178. };
  9179. /**
  9180. * redraw the slider on the correct place
  9181. */
  9182. Slider.prototype.redraw = function () {
  9183. if (this.frame) {
  9184. // resize the bar
  9185. this.frame.bar.style.top = this.frame.clientHeight / 2 - this.frame.bar.offsetHeight / 2 + 'px';
  9186. this.frame.bar.style.width = this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30 + 'px';
  9187. // position the slider button
  9188. var left = this.indexToLeft(this.index);
  9189. this.frame.slide.style.left = left + 'px';
  9190. }
  9191. };
  9192. /**
  9193. * Set the list with values for the slider
  9194. * @param {Array} values A javascript array with values (any type)
  9195. */
  9196. Slider.prototype.setValues = function (values) {
  9197. this.values = values;
  9198. if (this.values.length > 0) this.setIndex(0);else this.index = undefined;
  9199. };
  9200. /**
  9201. * Select a value by its index
  9202. * @param {Number} index
  9203. */
  9204. Slider.prototype.setIndex = function (index) {
  9205. if (index < this.values.length) {
  9206. this.index = index;
  9207. this.redraw();
  9208. this.onChange();
  9209. } else {
  9210. throw 'Error: index out of range';
  9211. }
  9212. };
  9213. /**
  9214. * retrieve the index of the currently selected vaue
  9215. * @return {Number} index
  9216. */
  9217. Slider.prototype.getIndex = function () {
  9218. return this.index;
  9219. };
  9220. /**
  9221. * retrieve the currently selected value
  9222. * @return {*} value
  9223. */
  9224. Slider.prototype.get = function () {
  9225. return this.values[this.index];
  9226. };
  9227. Slider.prototype._onMouseDown = function (event) {
  9228. // only react on left mouse button down
  9229. var leftButtonDown = event.which ? event.which === 1 : event.button === 1;
  9230. if (!leftButtonDown) return;
  9231. this.startClientX = event.clientX;
  9232. this.startSlideX = parseFloat(this.frame.slide.style.left);
  9233. this.frame.style.cursor = 'move';
  9234. // add event listeners to handle moving the contents
  9235. // we store the function onmousemove and onmouseup in the graph, so we can
  9236. // remove the eventlisteners lateron in the function mouseUp()
  9237. var me = this;
  9238. this.onmousemove = function (event) {
  9239. me._onMouseMove(event);
  9240. };
  9241. this.onmouseup = function (event) {
  9242. me._onMouseUp(event);
  9243. };
  9244. util.addEventListener(document, 'mousemove', this.onmousemove);
  9245. util.addEventListener(document, 'mouseup', this.onmouseup);
  9246. util.preventDefault(event);
  9247. };
  9248. Slider.prototype.leftToIndex = function (left) {
  9249. var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
  9250. var x = left - 3;
  9251. var index = Math.round(x / width * (this.values.length - 1));
  9252. if (index < 0) index = 0;
  9253. if (index > this.values.length - 1) index = this.values.length - 1;
  9254. return index;
  9255. };
  9256. Slider.prototype.indexToLeft = function (index) {
  9257. var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
  9258. var x = index / (this.values.length - 1) * width;
  9259. var left = x + 3;
  9260. return left;
  9261. };
  9262. Slider.prototype._onMouseMove = function (event) {
  9263. var diff = event.clientX - this.startClientX;
  9264. var x = this.startSlideX + diff;
  9265. var index = this.leftToIndex(x);
  9266. this.setIndex(index);
  9267. util.preventDefault();
  9268. };
  9269. Slider.prototype._onMouseUp = function (event) {
  9270. this.frame.style.cursor = 'auto';
  9271. // remove event listeners
  9272. util.removeEventListener(document, 'mousemove', this.onmousemove);
  9273. util.removeEventListener(document, 'mouseup', this.onmouseup);
  9274. util.preventDefault();
  9275. };
  9276. module.exports = Slider;
  9277. /***/ },
  9278. /* 19 */
  9279. /***/ function(module, exports) {
  9280. "use strict";
  9281. /**
  9282. * @prototype StepNumber
  9283. * The class StepNumber is an iterator for Numbers. You provide a start and end
  9284. * value, and a best step size. StepNumber itself rounds to fixed values and
  9285. * a finds the step that best fits the provided step.
  9286. *
  9287. * If prettyStep is true, the step size is chosen as close as possible to the
  9288. * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
  9289. *
  9290. * Example usage:
  9291. * var step = new StepNumber(0, 10, 2.5, true);
  9292. * step.start();
  9293. * while (!step.end()) {
  9294. * alert(step.getCurrent());
  9295. * step.next();
  9296. * }
  9297. *
  9298. * Version: 1.0
  9299. *
  9300. * @param {Number} start The start value
  9301. * @param {Number} end The end value
  9302. * @param {Number} step Optional. Step size. Must be a positive value.
  9303. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  9304. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  9305. */
  9306. function StepNumber(start, end, step, prettyStep) {
  9307. // set default values
  9308. this._start = 0;
  9309. this._end = 0;
  9310. this._step = 1;
  9311. this.prettyStep = true;
  9312. this.precision = 5;
  9313. this._current = 0;
  9314. this.setRange(start, end, step, prettyStep);
  9315. };
  9316. /**
  9317. * Set a new range: start, end and step.
  9318. *
  9319. * @param {Number} start The start value
  9320. * @param {Number} end The end value
  9321. * @param {Number} step Optional. Step size. Must be a positive value.
  9322. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  9323. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  9324. */
  9325. StepNumber.prototype.setRange = function (start, end, step, prettyStep) {
  9326. this._start = start ? start : 0;
  9327. this._end = end ? end : 0;
  9328. this.setStep(step, prettyStep);
  9329. };
  9330. /**
  9331. * Set a new step size
  9332. * @param {Number} step New step size. Must be a positive value
  9333. * @param {boolean} prettyStep Optional. If true, the provided step is rounded
  9334. * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  9335. */
  9336. StepNumber.prototype.setStep = function (step, prettyStep) {
  9337. if (step === undefined || step <= 0) return;
  9338. if (prettyStep !== undefined) this.prettyStep = prettyStep;
  9339. if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step;
  9340. };
  9341. /**
  9342. * Calculate a nice step size, closest to the desired step size.
  9343. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
  9344. * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
  9345. * @param {Number} step Desired step size
  9346. * @return {Number} Nice step size
  9347. */
  9348. StepNumber.calculatePrettyStep = function (step) {
  9349. var log10 = function log10(x) {
  9350. return Math.log(x) / Math.LN10;
  9351. };
  9352. // try three steps (multiple of 1, 2, or 5
  9353. var step1 = Math.pow(10, Math.round(log10(step))),
  9354. step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
  9355. step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
  9356. // choose the best step (closest to minimum step)
  9357. var prettyStep = step1;
  9358. if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
  9359. if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
  9360. // for safety
  9361. if (prettyStep <= 0) {
  9362. prettyStep = 1;
  9363. }
  9364. return prettyStep;
  9365. };
  9366. /**
  9367. * returns the current value of the step
  9368. * @return {Number} current value
  9369. */
  9370. StepNumber.prototype.getCurrent = function () {
  9371. return parseFloat(this._current.toPrecision(this.precision));
  9372. };
  9373. /**
  9374. * returns the current step size
  9375. * @return {Number} current step size
  9376. */
  9377. StepNumber.prototype.getStep = function () {
  9378. return this._step;
  9379. };
  9380. /**
  9381. * Set the current value to the largest value smaller than start, which
  9382. * is a multiple of the step size
  9383. */
  9384. StepNumber.prototype.start = function () {
  9385. this._current = this._start - this._start % this._step;
  9386. };
  9387. /**
  9388. * Do a step, add the step size to the current value
  9389. */
  9390. StepNumber.prototype.next = function () {
  9391. this._current += this._step;
  9392. };
  9393. /**
  9394. * Returns true whether the end is reached
  9395. * @return {boolean} True if the current value has passed the end value.
  9396. */
  9397. StepNumber.prototype.end = function () {
  9398. return this._current > this._end;
  9399. };
  9400. module.exports = StepNumber;
  9401. /***/ },
  9402. /* 20 */
  9403. /***/ function(module, exports, __webpack_require__) {
  9404. 'use strict';
  9405. // Only load hammer.js when in a browser environment
  9406. // (loading hammer.js in a node.js environment gives errors)
  9407. if (typeof window !== 'undefined') {
  9408. var propagating = __webpack_require__(21);
  9409. var Hammer = window['Hammer'] || __webpack_require__(22);
  9410. module.exports = propagating(Hammer, {
  9411. preventDefault: 'mouse'
  9412. });
  9413. } else {
  9414. module.exports = function () {
  9415. throw Error('hammer.js is only available in a browser, not in node.js.');
  9416. };
  9417. }
  9418. /***/ },
  9419. /* 21 */
  9420. /***/ function(module, exports, __webpack_require__) {
  9421. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
  9422. (function (factory) {
  9423. if (true) {
  9424. // AMD. Register as an anonymous module.
  9425. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  9426. } else if (typeof exports === 'object') {
  9427. // Node. Does not work with strict CommonJS, but
  9428. // only CommonJS-like environments that support module.exports,
  9429. // like Node.
  9430. module.exports = factory();
  9431. } else {
  9432. // Browser globals (root is window)
  9433. window.propagating = factory();
  9434. }
  9435. }(function () {
  9436. var _firstTarget = null; // singleton, will contain the target element where the touch event started
  9437. /**
  9438. * Extend an Hammer.js instance with event propagation.
  9439. *
  9440. * Features:
  9441. * - Events emitted by hammer will propagate in order from child to parent
  9442. * elements.
  9443. * - Events are extended with a function `event.stopPropagation()` to stop
  9444. * propagation to parent elements.
  9445. * - An option `preventDefault` to stop all default browser behavior.
  9446. *
  9447. * Usage:
  9448. * var hammer = propagatingHammer(new Hammer(element));
  9449. * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true});
  9450. *
  9451. * @param {Hammer.Manager} hammer An hammer instance.
  9452. * @param {Object} [options] Available options:
  9453. * - `preventDefault: true | false | 'mouse' | 'touch' | 'pen'`.
  9454. * Enforce preventing the default browser behavior.
  9455. * Cannot be set to `false`.
  9456. * @return {Hammer.Manager} Returns the same hammer instance with extended
  9457. * functionality
  9458. */
  9459. return function propagating(hammer, options) {
  9460. var _options = options || {
  9461. preventDefault: false
  9462. };
  9463. if (hammer.Manager) {
  9464. // This looks like the Hammer constructor.
  9465. // Overload the constructors with our own.
  9466. var Hammer = hammer;
  9467. var PropagatingHammer = function(element, options) {
  9468. var o = Object.create(_options);
  9469. if (options) Hammer.assign(o, options);
  9470. return propagating(new Hammer(element, o), o);
  9471. };
  9472. Hammer.assign(PropagatingHammer, Hammer);
  9473. PropagatingHammer.Manager = function (element, options) {
  9474. var o = Object.create(_options);
  9475. if (options) Hammer.assign(o, options);
  9476. return propagating(new Hammer.Manager(element, o), o);
  9477. };
  9478. return PropagatingHammer;
  9479. }
  9480. // create a wrapper object which will override the functions
  9481. // `on`, `off`, `destroy`, and `emit` of the hammer instance
  9482. var wrapper = Object.create(hammer);
  9483. // attach to DOM element
  9484. var element = hammer.element;
  9485. if(!element.hammer) element.hammer = [];
  9486. element.hammer.push(wrapper);
  9487. // register an event to catch the start of a gesture and store the
  9488. // target in a singleton
  9489. hammer.on('hammer.input', function (event) {
  9490. if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) {
  9491. event.preventDefault();
  9492. }
  9493. if (event.isFirst) {
  9494. _firstTarget = event.target;
  9495. }
  9496. });
  9497. /** @type {Object.<String, Array.<function>>} */
  9498. wrapper._handlers = {};
  9499. /**
  9500. * Register a handler for one or multiple events
  9501. * @param {String} events A space separated string with events
  9502. * @param {function} handler A callback function, called as handler(event)
  9503. * @returns {Hammer.Manager} Returns the hammer instance
  9504. */
  9505. wrapper.on = function (events, handler) {
  9506. // register the handler
  9507. split(events).forEach(function (event) {
  9508. var _handlers = wrapper._handlers[event];
  9509. if (!_handlers) {
  9510. wrapper._handlers[event] = _handlers = [];
  9511. // register the static, propagated handler
  9512. hammer.on(event, propagatedHandler);
  9513. }
  9514. _handlers.push(handler);
  9515. });
  9516. return wrapper;
  9517. };
  9518. /**
  9519. * Unregister a handler for one or multiple events
  9520. * @param {String} events A space separated string with events
  9521. * @param {function} [handler] Optional. The registered handler. If not
  9522. * provided, all handlers for given events
  9523. * are removed.
  9524. * @returns {Hammer.Manager} Returns the hammer instance
  9525. */
  9526. wrapper.off = function (events, handler) {
  9527. // unregister the handler
  9528. split(events).forEach(function (event) {
  9529. var _handlers = wrapper._handlers[event];
  9530. if (_handlers) {
  9531. _handlers = handler ? _handlers.filter(function (h) {
  9532. return h !== handler;
  9533. }) : [];
  9534. if (_handlers.length > 0) {
  9535. wrapper._handlers[event] = _handlers;
  9536. }
  9537. else {
  9538. // remove static, propagated handler
  9539. hammer.off(event, propagatedHandler);
  9540. delete wrapper._handlers[event];
  9541. }
  9542. }
  9543. });
  9544. return wrapper;
  9545. };
  9546. /**
  9547. * Emit to the event listeners
  9548. * @param {string} eventType
  9549. * @param {Event} event
  9550. */
  9551. wrapper.emit = function(eventType, event) {
  9552. _firstTarget = event.target;
  9553. hammer.emit(eventType, event);
  9554. };
  9555. wrapper.destroy = function () {
  9556. // Detach from DOM element
  9557. var hammers = hammer.element.hammer;
  9558. var idx = hammers.indexOf(wrapper);
  9559. if(idx !== -1) hammers.splice(idx,1);
  9560. if(!hammers.length) delete hammer.element.hammer;
  9561. // clear all handlers
  9562. wrapper._handlers = {};
  9563. // call original hammer destroy
  9564. hammer.destroy();
  9565. };
  9566. // split a string with space separated words
  9567. function split(events) {
  9568. return events.match(/[^ ]+/g);
  9569. }
  9570. /**
  9571. * A static event handler, applying event propagation.
  9572. * @param {Object} event
  9573. */
  9574. function propagatedHandler(event) {
  9575. // let only a single hammer instance handle this event
  9576. if (event.type !== 'hammer.input') {
  9577. // it is possible that the same srcEvent is used with multiple hammer events,
  9578. // we keep track on which events are handled in an object _handled
  9579. if (!event.srcEvent._handled) {
  9580. event.srcEvent._handled = {};
  9581. }
  9582. if (event.srcEvent._handled[event.type]) {
  9583. return;
  9584. }
  9585. else {
  9586. event.srcEvent._handled[event.type] = true;
  9587. }
  9588. }
  9589. // attach a stopPropagation function to the event
  9590. var stopped = false;
  9591. event.stopPropagation = function () {
  9592. stopped = true;
  9593. };
  9594. //wrap the srcEvent's stopPropagation to also stop hammer propagation:
  9595. var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
  9596. if(typeof srcStop == "function") {
  9597. event.srcEvent.stopPropagation = function(){
  9598. srcStop();
  9599. event.stopPropagation();
  9600. }
  9601. }
  9602. // attach firstTarget property to the event
  9603. event.firstTarget = _firstTarget;
  9604. // propagate over all elements (until stopped)
  9605. var elem = _firstTarget;
  9606. while (elem && !stopped) {
  9607. var elemHammer = elem.hammer;
  9608. if(elemHammer){
  9609. var _handlers;
  9610. for(var k = 0; k < elemHammer.length; k++){
  9611. _handlers = elemHammer[k]._handlers[event.type];
  9612. if(_handlers) for (var i = 0; i < _handlers.length && !stopped; i++) {
  9613. _handlers[i](event);
  9614. }
  9615. }
  9616. }
  9617. elem = elem.parentNode;
  9618. }
  9619. }
  9620. return wrapper;
  9621. };
  9622. }));
  9623. /***/ },
  9624. /* 22 */
  9625. /***/ function(module, exports, __webpack_require__) {
  9626. var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.6 - 2015-12-23
  9627. * http://hammerjs.github.io/
  9628. *
  9629. * Copyright (c) 2015 Jorik Tangelder;
  9630. * Licensed under the license */
  9631. (function(window, document, exportName, undefined) {
  9632. 'use strict';
  9633. var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
  9634. var TEST_ELEMENT = document.createElement('div');
  9635. var TYPE_FUNCTION = 'function';
  9636. var round = Math.round;
  9637. var abs = Math.abs;
  9638. var now = Date.now;
  9639. /**
  9640. * set a timeout with a given scope
  9641. * @param {Function} fn
  9642. * @param {Number} timeout
  9643. * @param {Object} context
  9644. * @returns {number}
  9645. */
  9646. function setTimeoutContext(fn, timeout, context) {
  9647. return setTimeout(bindFn(fn, context), timeout);
  9648. }
  9649. /**
  9650. * if the argument is an array, we want to execute the fn on each entry
  9651. * if it aint an array we don't want to do a thing.
  9652. * this is used by all the methods that accept a single and array argument.
  9653. * @param {*|Array} arg
  9654. * @param {String} fn
  9655. * @param {Object} [context]
  9656. * @returns {Boolean}
  9657. */
  9658. function invokeArrayArg(arg, fn, context) {
  9659. if (Array.isArray(arg)) {
  9660. each(arg, context[fn], context);
  9661. return true;
  9662. }
  9663. return false;
  9664. }
  9665. /**
  9666. * walk objects and arrays
  9667. * @param {Object} obj
  9668. * @param {Function} iterator
  9669. * @param {Object} context
  9670. */
  9671. function each(obj, iterator, context) {
  9672. var i;
  9673. if (!obj) {
  9674. return;
  9675. }
  9676. if (obj.forEach) {
  9677. obj.forEach(iterator, context);
  9678. } else if (obj.length !== undefined) {
  9679. i = 0;
  9680. while (i < obj.length) {
  9681. iterator.call(context, obj[i], i, obj);
  9682. i++;
  9683. }
  9684. } else {
  9685. for (i in obj) {
  9686. obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
  9687. }
  9688. }
  9689. }
  9690. /**
  9691. * wrap a method with a deprecation warning and stack trace
  9692. * @param {Function} method
  9693. * @param {String} name
  9694. * @param {String} message
  9695. * @returns {Function} A new function wrapping the supplied method.
  9696. */
  9697. function deprecate(method, name, message) {
  9698. var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
  9699. return function() {
  9700. var e = new Error('get-stack-trace');
  9701. var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
  9702. .replace(/^\s+at\s+/gm, '')
  9703. .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
  9704. var log = window.console && (window.console.warn || window.console.log);
  9705. if (log) {
  9706. log.call(window.console, deprecationMessage, stack);
  9707. }
  9708. return method.apply(this, arguments);
  9709. };
  9710. }
  9711. /**
  9712. * extend object.
  9713. * means that properties in dest will be overwritten by the ones in src.
  9714. * @param {Object} target
  9715. * @param {...Object} objects_to_assign
  9716. * @returns {Object} target
  9717. */
  9718. var assign;
  9719. if (typeof Object.assign !== 'function') {
  9720. assign = function assign(target) {
  9721. if (target === undefined || target === null) {
  9722. throw new TypeError('Cannot convert undefined or null to object');
  9723. }
  9724. var output = Object(target);
  9725. for (var index = 1; index < arguments.length; index++) {
  9726. var source = arguments[index];
  9727. if (source !== undefined && source !== null) {
  9728. for (var nextKey in source) {
  9729. if (source.hasOwnProperty(nextKey)) {
  9730. output[nextKey] = source[nextKey];
  9731. }
  9732. }
  9733. }
  9734. }
  9735. return output;
  9736. };
  9737. } else {
  9738. assign = Object.assign;
  9739. }
  9740. /**
  9741. * extend object.
  9742. * means that properties in dest will be overwritten by the ones in src.
  9743. * @param {Object} dest
  9744. * @param {Object} src
  9745. * @param {Boolean=false} [merge]
  9746. * @returns {Object} dest
  9747. */
  9748. var extend = deprecate(function extend(dest, src, merge) {
  9749. var keys = Object.keys(src);
  9750. var i = 0;
  9751. while (i < keys.length) {
  9752. if (!merge || (merge && dest[keys[i]] === undefined)) {
  9753. dest[keys[i]] = src[keys[i]];
  9754. }
  9755. i++;
  9756. }
  9757. return dest;
  9758. }, 'extend', 'Use `assign`.');
  9759. /**
  9760. * merge the values from src in the dest.
  9761. * means that properties that exist in dest will not be overwritten by src
  9762. * @param {Object} dest
  9763. * @param {Object} src
  9764. * @returns {Object} dest
  9765. */
  9766. var merge = deprecate(function merge(dest, src) {
  9767. return extend(dest, src, true);
  9768. }, 'merge', 'Use `assign`.');
  9769. /**
  9770. * simple class inheritance
  9771. * @param {Function} child
  9772. * @param {Function} base
  9773. * @param {Object} [properties]
  9774. */
  9775. function inherit(child, base, properties) {
  9776. var baseP = base.prototype,
  9777. childP;
  9778. childP = child.prototype = Object.create(baseP);
  9779. childP.constructor = child;
  9780. childP._super = baseP;
  9781. if (properties) {
  9782. assign(childP, properties);
  9783. }
  9784. }
  9785. /**
  9786. * simple function bind
  9787. * @param {Function} fn
  9788. * @param {Object} context
  9789. * @returns {Function}
  9790. */
  9791. function bindFn(fn, context) {
  9792. return function boundFn() {
  9793. return fn.apply(context, arguments);
  9794. };
  9795. }
  9796. /**
  9797. * let a boolean value also be a function that must return a boolean
  9798. * this first item in args will be used as the context
  9799. * @param {Boolean|Function} val
  9800. * @param {Array} [args]
  9801. * @returns {Boolean}
  9802. */
  9803. function boolOrFn(val, args) {
  9804. if (typeof val == TYPE_FUNCTION) {
  9805. return val.apply(args ? args[0] || undefined : undefined, args);
  9806. }
  9807. return val;
  9808. }
  9809. /**
  9810. * use the val2 when val1 is undefined
  9811. * @param {*} val1
  9812. * @param {*} val2
  9813. * @returns {*}
  9814. */
  9815. function ifUndefined(val1, val2) {
  9816. return (val1 === undefined) ? val2 : val1;
  9817. }
  9818. /**
  9819. * addEventListener with multiple events at once
  9820. * @param {EventTarget} target
  9821. * @param {String} types
  9822. * @param {Function} handler
  9823. */
  9824. function addEventListeners(target, types, handler) {
  9825. each(splitStr(types), function(type) {
  9826. target.addEventListener(type, handler, false);
  9827. });
  9828. }
  9829. /**
  9830. * removeEventListener with multiple events at once
  9831. * @param {EventTarget} target
  9832. * @param {String} types
  9833. * @param {Function} handler
  9834. */
  9835. function removeEventListeners(target, types, handler) {
  9836. each(splitStr(types), function(type) {
  9837. target.removeEventListener(type, handler, false);
  9838. });
  9839. }
  9840. /**
  9841. * find if a node is in the given parent
  9842. * @method hasParent
  9843. * @param {HTMLElement} node
  9844. * @param {HTMLElement} parent
  9845. * @return {Boolean} found
  9846. */
  9847. function hasParent(node, parent) {
  9848. while (node) {
  9849. if (node == parent) {
  9850. return true;
  9851. }
  9852. node = node.parentNode;
  9853. }
  9854. return false;
  9855. }
  9856. /**
  9857. * small indexOf wrapper
  9858. * @param {String} str
  9859. * @param {String} find
  9860. * @returns {Boolean} found
  9861. */
  9862. function inStr(str, find) {
  9863. return str.indexOf(find) > -1;
  9864. }
  9865. /**
  9866. * split string on whitespace
  9867. * @param {String} str
  9868. * @returns {Array} words
  9869. */
  9870. function splitStr(str) {
  9871. return str.trim().split(/\s+/g);
  9872. }
  9873. /**
  9874. * find if a array contains the object using indexOf or a simple polyFill
  9875. * @param {Array} src
  9876. * @param {String} find
  9877. * @param {String} [findByKey]
  9878. * @return {Boolean|Number} false when not found, or the index
  9879. */
  9880. function inArray(src, find, findByKey) {
  9881. if (src.indexOf && !findByKey) {
  9882. return src.indexOf(find);
  9883. } else {
  9884. var i = 0;
  9885. while (i < src.length) {
  9886. if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
  9887. return i;
  9888. }
  9889. i++;
  9890. }
  9891. return -1;
  9892. }
  9893. }
  9894. /**
  9895. * convert array-like objects to real arrays
  9896. * @param {Object} obj
  9897. * @returns {Array}
  9898. */
  9899. function toArray(obj) {
  9900. return Array.prototype.slice.call(obj, 0);
  9901. }
  9902. /**
  9903. * unique array with objects based on a key (like 'id') or just by the array's value
  9904. * @param {Array} src [{id:1},{id:2},{id:1}]
  9905. * @param {String} [key]
  9906. * @param {Boolean} [sort=False]
  9907. * @returns {Array} [{id:1},{id:2}]
  9908. */
  9909. function uniqueArray(src, key, sort) {
  9910. var results = [];
  9911. var values = [];
  9912. var i = 0;
  9913. while (i < src.length) {
  9914. var val = key ? src[i][key] : src[i];
  9915. if (inArray(values, val) < 0) {
  9916. results.push(src[i]);
  9917. }
  9918. values[i] = val;
  9919. i++;
  9920. }
  9921. if (sort) {
  9922. if (!key) {
  9923. results = results.sort();
  9924. } else {
  9925. results = results.sort(function sortUniqueArray(a, b) {
  9926. return a[key] > b[key];
  9927. });
  9928. }
  9929. }
  9930. return results;
  9931. }
  9932. /**
  9933. * get the prefixed property
  9934. * @param {Object} obj
  9935. * @param {String} property
  9936. * @returns {String|Undefined} prefixed
  9937. */
  9938. function prefixed(obj, property) {
  9939. var prefix, prop;
  9940. var camelProp = property[0].toUpperCase() + property.slice(1);
  9941. var i = 0;
  9942. while (i < VENDOR_PREFIXES.length) {
  9943. prefix = VENDOR_PREFIXES[i];
  9944. prop = (prefix) ? prefix + camelProp : property;
  9945. if (prop in obj) {
  9946. return prop;
  9947. }
  9948. i++;
  9949. }
  9950. return undefined;
  9951. }
  9952. /**
  9953. * get a unique id
  9954. * @returns {number} uniqueId
  9955. */
  9956. var _uniqueId = 1;
  9957. function uniqueId() {
  9958. return _uniqueId++;
  9959. }
  9960. /**
  9961. * get the window object of an element
  9962. * @param {HTMLElement} element
  9963. * @returns {DocumentView|Window}
  9964. */
  9965. function getWindowForElement(element) {
  9966. var doc = element.ownerDocument || element;
  9967. return (doc.defaultView || doc.parentWindow || window);
  9968. }
  9969. var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  9970. var SUPPORT_TOUCH = ('ontouchstart' in window);
  9971. var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
  9972. var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
  9973. var INPUT_TYPE_TOUCH = 'touch';
  9974. var INPUT_TYPE_PEN = 'pen';
  9975. var INPUT_TYPE_MOUSE = 'mouse';
  9976. var INPUT_TYPE_KINECT = 'kinect';
  9977. var COMPUTE_INTERVAL = 25;
  9978. var INPUT_START = 1;
  9979. var INPUT_MOVE = 2;
  9980. var INPUT_END = 4;
  9981. var INPUT_CANCEL = 8;
  9982. var DIRECTION_NONE = 1;
  9983. var DIRECTION_LEFT = 2;
  9984. var DIRECTION_RIGHT = 4;
  9985. var DIRECTION_UP = 8;
  9986. var DIRECTION_DOWN = 16;
  9987. var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
  9988. var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
  9989. var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
  9990. var PROPS_XY = ['x', 'y'];
  9991. var PROPS_CLIENT_XY = ['clientX', 'clientY'];
  9992. /**
  9993. * create new input type manager
  9994. * @param {Manager} manager
  9995. * @param {Function} callback
  9996. * @returns {Input}
  9997. * @constructor
  9998. */
  9999. function Input(manager, callback) {
  10000. var self = this;
  10001. this.manager = manager;
  10002. this.callback = callback;
  10003. this.element = manager.element;
  10004. this.target = manager.options.inputTarget;
  10005. // smaller wrapper around the handler, for the scope and the enabled state of the manager,
  10006. // so when disabled the input events are completely bypassed.
  10007. this.domHandler = function(ev) {
  10008. if (boolOrFn(manager.options.enable, [manager])) {
  10009. self.handler(ev);
  10010. }
  10011. };
  10012. this.init();
  10013. }
  10014. Input.prototype = {
  10015. /**
  10016. * should handle the inputEvent data and trigger the callback
  10017. * @virtual
  10018. */
  10019. handler: function() { },
  10020. /**
  10021. * bind the events
  10022. */
  10023. init: function() {
  10024. this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
  10025. this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
  10026. this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  10027. },
  10028. /**
  10029. * unbind the events
  10030. */
  10031. destroy: function() {
  10032. this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
  10033. this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
  10034. this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  10035. }
  10036. };
  10037. /**
  10038. * create new input type manager
  10039. * called by the Manager constructor
  10040. * @param {Hammer} manager
  10041. * @returns {Input}
  10042. */
  10043. function createInputInstance(manager) {
  10044. var Type;
  10045. var inputClass = manager.options.inputClass;
  10046. if (inputClass) {
  10047. Type = inputClass;
  10048. } else if (SUPPORT_POINTER_EVENTS) {
  10049. Type = PointerEventInput;
  10050. } else if (SUPPORT_ONLY_TOUCH) {
  10051. Type = TouchInput;
  10052. } else if (!SUPPORT_TOUCH) {
  10053. Type = MouseInput;
  10054. } else {
  10055. Type = TouchMouseInput;
  10056. }
  10057. return new (Type)(manager, inputHandler);
  10058. }
  10059. /**
  10060. * handle input events
  10061. * @param {Manager} manager
  10062. * @param {String} eventType
  10063. * @param {Object} input
  10064. */
  10065. function inputHandler(manager, eventType, input) {
  10066. var pointersLen = input.pointers.length;
  10067. var changedPointersLen = input.changedPointers.length;
  10068. var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
  10069. var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
  10070. input.isFirst = !!isFirst;
  10071. input.isFinal = !!isFinal;
  10072. if (isFirst) {
  10073. manager.session = {};
  10074. }
  10075. // source event is the normalized value of the domEvents
  10076. // like 'touchstart, mouseup, pointerdown'
  10077. input.eventType = eventType;
  10078. // compute scale, rotation etc
  10079. computeInputData(manager, input);
  10080. // emit secret event
  10081. manager.emit('hammer.input', input);
  10082. manager.recognize(input);
  10083. manager.session.prevInput = input;
  10084. }
  10085. /**
  10086. * extend the data with some usable properties like scale, rotate, velocity etc
  10087. * @param {Object} manager
  10088. * @param {Object} input
  10089. */
  10090. function computeInputData(manager, input) {
  10091. var session = manager.session;
  10092. var pointers = input.pointers;
  10093. var pointersLength = pointers.length;
  10094. // store the first input to calculate the distance and direction
  10095. if (!session.firstInput) {
  10096. session.firstInput = simpleCloneInputData(input);
  10097. }
  10098. // to compute scale and rotation we need to store the multiple touches
  10099. if (pointersLength > 1 && !session.firstMultiple) {
  10100. session.firstMultiple = simpleCloneInputData(input);
  10101. } else if (pointersLength === 1) {
  10102. session.firstMultiple = false;
  10103. }
  10104. var firstInput = session.firstInput;
  10105. var firstMultiple = session.firstMultiple;
  10106. var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
  10107. var center = input.center = getCenter(pointers);
  10108. input.timeStamp = now();
  10109. input.deltaTime = input.timeStamp - firstInput.timeStamp;
  10110. input.angle = getAngle(offsetCenter, center);
  10111. input.distance = getDistance(offsetCenter, center);
  10112. computeDeltaXY(session, input);
  10113. input.offsetDirection = getDirection(input.deltaX, input.deltaY);
  10114. var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
  10115. input.overallVelocityX = overallVelocity.x;
  10116. input.overallVelocityY = overallVelocity.y;
  10117. input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;
  10118. input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
  10119. input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
  10120. input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
  10121. session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);
  10122. computeIntervalInputData(session, input);
  10123. // find the correct target
  10124. var target = manager.element;
  10125. if (hasParent(input.srcEvent.target, target)) {
  10126. target = input.srcEvent.target;
  10127. }
  10128. input.target = target;
  10129. }
  10130. function computeDeltaXY(session, input) {
  10131. var center = input.center;
  10132. var offset = session.offsetDelta || {};
  10133. var prevDelta = session.prevDelta || {};
  10134. var prevInput = session.prevInput || {};
  10135. if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
  10136. prevDelta = session.prevDelta = {
  10137. x: prevInput.deltaX || 0,
  10138. y: prevInput.deltaY || 0
  10139. };
  10140. offset = session.offsetDelta = {
  10141. x: center.x,
  10142. y: center.y
  10143. };
  10144. }
  10145. input.deltaX = prevDelta.x + (center.x - offset.x);
  10146. input.deltaY = prevDelta.y + (center.y - offset.y);
  10147. }
  10148. /**
  10149. * velocity is calculated every x ms
  10150. * @param {Object} session
  10151. * @param {Object} input
  10152. */
  10153. function computeIntervalInputData(session, input) {
  10154. var last = session.lastInterval || input,
  10155. deltaTime = input.timeStamp - last.timeStamp,
  10156. velocity, velocityX, velocityY, direction;
  10157. if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
  10158. var deltaX = input.deltaX - last.deltaX;
  10159. var deltaY = input.deltaY - last.deltaY;
  10160. var v = getVelocity(deltaTime, deltaX, deltaY);
  10161. velocityX = v.x;
  10162. velocityY = v.y;
  10163. velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
  10164. direction = getDirection(deltaX, deltaY);
  10165. session.lastInterval = input;
  10166. } else {
  10167. // use latest velocity info if it doesn't overtake a minimum period
  10168. velocity = last.velocity;
  10169. velocityX = last.velocityX;
  10170. velocityY = last.velocityY;
  10171. direction = last.direction;
  10172. }
  10173. input.velocity = velocity;
  10174. input.velocityX = velocityX;
  10175. input.velocityY = velocityY;
  10176. input.direction = direction;
  10177. }
  10178. /**
  10179. * create a simple clone from the input used for storage of firstInput and firstMultiple
  10180. * @param {Object} input
  10181. * @returns {Object} clonedInputData
  10182. */
  10183. function simpleCloneInputData(input) {
  10184. // make a simple copy of the pointers because we will get a reference if we don't
  10185. // we only need clientXY for the calculations
  10186. var pointers = [];
  10187. var i = 0;
  10188. while (i < input.pointers.length) {
  10189. pointers[i] = {
  10190. clientX: round(input.pointers[i].clientX),
  10191. clientY: round(input.pointers[i].clientY)
  10192. };
  10193. i++;
  10194. }
  10195. return {
  10196. timeStamp: now(),
  10197. pointers: pointers,
  10198. center: getCenter(pointers),
  10199. deltaX: input.deltaX,
  10200. deltaY: input.deltaY
  10201. };
  10202. }
  10203. /**
  10204. * get the center of all the pointers
  10205. * @param {Array} pointers
  10206. * @return {Object} center contains `x` and `y` properties
  10207. */
  10208. function getCenter(pointers) {
  10209. var pointersLength = pointers.length;
  10210. // no need to loop when only one touch
  10211. if (pointersLength === 1) {
  10212. return {
  10213. x: round(pointers[0].clientX),
  10214. y: round(pointers[0].clientY)
  10215. };
  10216. }
  10217. var x = 0, y = 0, i = 0;
  10218. while (i < pointersLength) {
  10219. x += pointers[i].clientX;
  10220. y += pointers[i].clientY;
  10221. i++;
  10222. }
  10223. return {
  10224. x: round(x / pointersLength),
  10225. y: round(y / pointersLength)
  10226. };
  10227. }
  10228. /**
  10229. * calculate the velocity between two points. unit is in px per ms.
  10230. * @param {Number} deltaTime
  10231. * @param {Number} x
  10232. * @param {Number} y
  10233. * @return {Object} velocity `x` and `y`
  10234. */
  10235. function getVelocity(deltaTime, x, y) {
  10236. return {
  10237. x: x / deltaTime || 0,
  10238. y: y / deltaTime || 0
  10239. };
  10240. }
  10241. /**
  10242. * get the direction between two points
  10243. * @param {Number} x
  10244. * @param {Number} y
  10245. * @return {Number} direction
  10246. */
  10247. function getDirection(x, y) {
  10248. if (x === y) {
  10249. return DIRECTION_NONE;
  10250. }
  10251. if (abs(x) >= abs(y)) {
  10252. return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  10253. }
  10254. return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
  10255. }
  10256. /**
  10257. * calculate the absolute distance between two points
  10258. * @param {Object} p1 {x, y}
  10259. * @param {Object} p2 {x, y}
  10260. * @param {Array} [props] containing x and y keys
  10261. * @return {Number} distance
  10262. */
  10263. function getDistance(p1, p2, props) {
  10264. if (!props) {
  10265. props = PROPS_XY;
  10266. }
  10267. var x = p2[props[0]] - p1[props[0]],
  10268. y = p2[props[1]] - p1[props[1]];
  10269. return Math.sqrt((x * x) + (y * y));
  10270. }
  10271. /**
  10272. * calculate the angle between two coordinates
  10273. * @param {Object} p1
  10274. * @param {Object} p2
  10275. * @param {Array} [props] containing x and y keys
  10276. * @return {Number} angle
  10277. */
  10278. function getAngle(p1, p2, props) {
  10279. if (!props) {
  10280. props = PROPS_XY;
  10281. }
  10282. var x = p2[props[0]] - p1[props[0]],
  10283. y = p2[props[1]] - p1[props[1]];
  10284. return Math.atan2(y, x) * 180 / Math.PI;
  10285. }
  10286. /**
  10287. * calculate the rotation degrees between two pointersets
  10288. * @param {Array} start array of pointers
  10289. * @param {Array} end array of pointers
  10290. * @return {Number} rotation
  10291. */
  10292. function getRotation(start, end) {
  10293. return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
  10294. }
  10295. /**
  10296. * calculate the scale factor between two pointersets
  10297. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  10298. * @param {Array} start array of pointers
  10299. * @param {Array} end array of pointers
  10300. * @return {Number} scale
  10301. */
  10302. function getScale(start, end) {
  10303. return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
  10304. }
  10305. var MOUSE_INPUT_MAP = {
  10306. mousedown: INPUT_START,
  10307. mousemove: INPUT_MOVE,
  10308. mouseup: INPUT_END
  10309. };
  10310. var MOUSE_ELEMENT_EVENTS = 'mousedown';
  10311. var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
  10312. /**
  10313. * Mouse events input
  10314. * @constructor
  10315. * @extends Input
  10316. */
  10317. function MouseInput() {
  10318. this.evEl = MOUSE_ELEMENT_EVENTS;
  10319. this.evWin = MOUSE_WINDOW_EVENTS;
  10320. this.allow = true; // used by Input.TouchMouse to disable mouse events
  10321. this.pressed = false; // mousedown state
  10322. Input.apply(this, arguments);
  10323. }
  10324. inherit(MouseInput, Input, {
  10325. /**
  10326. * handle mouse events
  10327. * @param {Object} ev
  10328. */
  10329. handler: function MEhandler(ev) {
  10330. var eventType = MOUSE_INPUT_MAP[ev.type];
  10331. // on start we want to have the left mouse button down
  10332. if (eventType & INPUT_START && ev.button === 0) {
  10333. this.pressed = true;
  10334. }
  10335. if (eventType & INPUT_MOVE && ev.which !== 1) {
  10336. eventType = INPUT_END;
  10337. }
  10338. // mouse must be down, and mouse events are allowed (see the TouchMouse input)
  10339. if (!this.pressed || !this.allow) {
  10340. return;
  10341. }
  10342. if (eventType & INPUT_END) {
  10343. this.pressed = false;
  10344. }
  10345. this.callback(this.manager, eventType, {
  10346. pointers: [ev],
  10347. changedPointers: [ev],
  10348. pointerType: INPUT_TYPE_MOUSE,
  10349. srcEvent: ev
  10350. });
  10351. }
  10352. });
  10353. var POINTER_INPUT_MAP = {
  10354. pointerdown: INPUT_START,
  10355. pointermove: INPUT_MOVE,
  10356. pointerup: INPUT_END,
  10357. pointercancel: INPUT_CANCEL,
  10358. pointerout: INPUT_CANCEL
  10359. };
  10360. // in IE10 the pointer types is defined as an enum
  10361. var IE10_POINTER_TYPE_ENUM = {
  10362. 2: INPUT_TYPE_TOUCH,
  10363. 3: INPUT_TYPE_PEN,
  10364. 4: INPUT_TYPE_MOUSE,
  10365. 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
  10366. };
  10367. var POINTER_ELEMENT_EVENTS = 'pointerdown';
  10368. var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
  10369. // IE10 has prefixed support, and case-sensitive
  10370. if (window.MSPointerEvent && !window.PointerEvent) {
  10371. POINTER_ELEMENT_EVENTS = 'MSPointerDown';
  10372. POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
  10373. }
  10374. /**
  10375. * Pointer events input
  10376. * @constructor
  10377. * @extends Input
  10378. */
  10379. function PointerEventInput() {
  10380. this.evEl = POINTER_ELEMENT_EVENTS;
  10381. this.evWin = POINTER_WINDOW_EVENTS;
  10382. Input.apply(this, arguments);
  10383. this.store = (this.manager.session.pointerEvents = []);
  10384. }
  10385. inherit(PointerEventInput, Input, {
  10386. /**
  10387. * handle mouse events
  10388. * @param {Object} ev
  10389. */
  10390. handler: function PEhandler(ev) {
  10391. var store = this.store;
  10392. var removePointer = false;
  10393. var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
  10394. var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
  10395. var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
  10396. var isTouch = (pointerType == INPUT_TYPE_TOUCH);
  10397. // get index of the event in the store
  10398. var storeIndex = inArray(store, ev.pointerId, 'pointerId');
  10399. // start and mouse must be down
  10400. if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
  10401. if (storeIndex < 0) {
  10402. store.push(ev);
  10403. storeIndex = store.length - 1;
  10404. }
  10405. } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
  10406. removePointer = true;
  10407. }
  10408. // it not found, so the pointer hasn't been down (so it's probably a hover)
  10409. if (storeIndex < 0) {
  10410. return;
  10411. }
  10412. // update the event in the store
  10413. store[storeIndex] = ev;
  10414. this.callback(this.manager, eventType, {
  10415. pointers: store,
  10416. changedPointers: [ev],
  10417. pointerType: pointerType,
  10418. srcEvent: ev
  10419. });
  10420. if (removePointer) {
  10421. // remove from the store
  10422. store.splice(storeIndex, 1);
  10423. }
  10424. }
  10425. });
  10426. var SINGLE_TOUCH_INPUT_MAP = {
  10427. touchstart: INPUT_START,
  10428. touchmove: INPUT_MOVE,
  10429. touchend: INPUT_END,
  10430. touchcancel: INPUT_CANCEL
  10431. };
  10432. var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
  10433. var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
  10434. /**
  10435. * Touch events input
  10436. * @constructor
  10437. * @extends Input
  10438. */
  10439. function SingleTouchInput() {
  10440. this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
  10441. this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
  10442. this.started = false;
  10443. Input.apply(this, arguments);
  10444. }
  10445. inherit(SingleTouchInput, Input, {
  10446. handler: function TEhandler(ev) {
  10447. var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
  10448. // should we handle the touch events?
  10449. if (type === INPUT_START) {
  10450. this.started = true;
  10451. }
  10452. if (!this.started) {
  10453. return;
  10454. }
  10455. var touches = normalizeSingleTouches.call(this, ev, type);
  10456. // when done, reset the started state
  10457. if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
  10458. this.started = false;
  10459. }
  10460. this.callback(this.manager, type, {
  10461. pointers: touches[0],
  10462. changedPointers: touches[1],
  10463. pointerType: INPUT_TYPE_TOUCH,
  10464. srcEvent: ev
  10465. });
  10466. }
  10467. });
  10468. /**
  10469. * @this {TouchInput}
  10470. * @param {Object} ev
  10471. * @param {Number} type flag
  10472. * @returns {undefined|Array} [all, changed]
  10473. */
  10474. function normalizeSingleTouches(ev, type) {
  10475. var all = toArray(ev.touches);
  10476. var changed = toArray(ev.changedTouches);
  10477. if (type & (INPUT_END | INPUT_CANCEL)) {
  10478. all = uniqueArray(all.concat(changed), 'identifier', true);
  10479. }
  10480. return [all, changed];
  10481. }
  10482. var TOUCH_INPUT_MAP = {
  10483. touchstart: INPUT_START,
  10484. touchmove: INPUT_MOVE,
  10485. touchend: INPUT_END,
  10486. touchcancel: INPUT_CANCEL
  10487. };
  10488. var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
  10489. /**
  10490. * Multi-user touch events input
  10491. * @constructor
  10492. * @extends Input
  10493. */
  10494. function TouchInput() {
  10495. this.evTarget = TOUCH_TARGET_EVENTS;
  10496. this.targetIds = {};
  10497. Input.apply(this, arguments);
  10498. }
  10499. inherit(TouchInput, Input, {
  10500. handler: function MTEhandler(ev) {
  10501. var type = TOUCH_INPUT_MAP[ev.type];
  10502. var touches = getTouches.call(this, ev, type);
  10503. if (!touches) {
  10504. return;
  10505. }
  10506. this.callback(this.manager, type, {
  10507. pointers: touches[0],
  10508. changedPointers: touches[1],
  10509. pointerType: INPUT_TYPE_TOUCH,
  10510. srcEvent: ev
  10511. });
  10512. }
  10513. });
  10514. /**
  10515. * @this {TouchInput}
  10516. * @param {Object} ev
  10517. * @param {Number} type flag
  10518. * @returns {undefined|Array} [all, changed]
  10519. */
  10520. function getTouches(ev, type) {
  10521. var allTouches = toArray(ev.touches);
  10522. var targetIds = this.targetIds;
  10523. // when there is only one touch, the process can be simplified
  10524. if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
  10525. targetIds[allTouches[0].identifier] = true;
  10526. return [allTouches, allTouches];
  10527. }
  10528. var i,
  10529. targetTouches,
  10530. changedTouches = toArray(ev.changedTouches),
  10531. changedTargetTouches = [],
  10532. target = this.target;
  10533. // get target touches from touches
  10534. targetTouches = allTouches.filter(function(touch) {
  10535. return hasParent(touch.target, target);
  10536. });
  10537. // collect touches
  10538. if (type === INPUT_START) {
  10539. i = 0;
  10540. while (i < targetTouches.length) {
  10541. targetIds[targetTouches[i].identifier] = true;
  10542. i++;
  10543. }
  10544. }
  10545. // filter changed touches to only contain touches that exist in the collected target ids
  10546. i = 0;
  10547. while (i < changedTouches.length) {
  10548. if (targetIds[changedTouches[i].identifier]) {
  10549. changedTargetTouches.push(changedTouches[i]);
  10550. }
  10551. // cleanup removed touches
  10552. if (type & (INPUT_END | INPUT_CANCEL)) {
  10553. delete targetIds[changedTouches[i].identifier];
  10554. }
  10555. i++;
  10556. }
  10557. if (!changedTargetTouches.length) {
  10558. return;
  10559. }
  10560. return [
  10561. // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
  10562. uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
  10563. changedTargetTouches
  10564. ];
  10565. }
  10566. /**
  10567. * Combined touch and mouse input
  10568. *
  10569. * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
  10570. * This because touch devices also emit mouse events while doing a touch.
  10571. *
  10572. * @constructor
  10573. * @extends Input
  10574. */
  10575. function TouchMouseInput() {
  10576. Input.apply(this, arguments);
  10577. var handler = bindFn(this.handler, this);
  10578. this.touch = new TouchInput(this.manager, handler);
  10579. this.mouse = new MouseInput(this.manager, handler);
  10580. }
  10581. inherit(TouchMouseInput, Input, {
  10582. /**
  10583. * handle mouse and touch events
  10584. * @param {Hammer} manager
  10585. * @param {String} inputEvent
  10586. * @param {Object} inputData
  10587. */
  10588. handler: function TMEhandler(manager, inputEvent, inputData) {
  10589. var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
  10590. isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
  10591. // when we're in a touch event, so block all upcoming mouse events
  10592. // most mobile browser also emit mouseevents, right after touchstart
  10593. if (isTouch) {
  10594. this.mouse.allow = false;
  10595. } else if (isMouse && !this.mouse.allow) {
  10596. return;
  10597. }
  10598. // reset the allowMouse when we're done
  10599. if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
  10600. this.mouse.allow = true;
  10601. }
  10602. this.callback(manager, inputEvent, inputData);
  10603. },
  10604. /**
  10605. * remove the event listeners
  10606. */
  10607. destroy: function destroy() {
  10608. this.touch.destroy();
  10609. this.mouse.destroy();
  10610. }
  10611. });
  10612. var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
  10613. var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
  10614. // magical touchAction value
  10615. var TOUCH_ACTION_COMPUTE = 'compute';
  10616. var TOUCH_ACTION_AUTO = 'auto';
  10617. var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
  10618. var TOUCH_ACTION_NONE = 'none';
  10619. var TOUCH_ACTION_PAN_X = 'pan-x';
  10620. var TOUCH_ACTION_PAN_Y = 'pan-y';
  10621. /**
  10622. * Touch Action
  10623. * sets the touchAction property or uses the js alternative
  10624. * @param {Manager} manager
  10625. * @param {String} value
  10626. * @constructor
  10627. */
  10628. function TouchAction(manager, value) {
  10629. this.manager = manager;
  10630. this.set(value);
  10631. }
  10632. TouchAction.prototype = {
  10633. /**
  10634. * set the touchAction value on the element or enable the polyfill
  10635. * @param {String} value
  10636. */
  10637. set: function(value) {
  10638. // find out the touch-action by the event handlers
  10639. if (value == TOUCH_ACTION_COMPUTE) {
  10640. value = this.compute();
  10641. }
  10642. if (NATIVE_TOUCH_ACTION && this.manager.element.style) {
  10643. this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
  10644. }
  10645. this.actions = value.toLowerCase().trim();
  10646. },
  10647. /**
  10648. * just re-set the touchAction value
  10649. */
  10650. update: function() {
  10651. this.set(this.manager.options.touchAction);
  10652. },
  10653. /**
  10654. * compute the value for the touchAction property based on the recognizer's settings
  10655. * @returns {String} value
  10656. */
  10657. compute: function() {
  10658. var actions = [];
  10659. each(this.manager.recognizers, function(recognizer) {
  10660. if (boolOrFn(recognizer.options.enable, [recognizer])) {
  10661. actions = actions.concat(recognizer.getTouchAction());
  10662. }
  10663. });
  10664. return cleanTouchActions(actions.join(' '));
  10665. },
  10666. /**
  10667. * this method is called on each input cycle and provides the preventing of the browser behavior
  10668. * @param {Object} input
  10669. */
  10670. preventDefaults: function(input) {
  10671. // not needed with native support for the touchAction property
  10672. if (NATIVE_TOUCH_ACTION) {
  10673. return;
  10674. }
  10675. var srcEvent = input.srcEvent;
  10676. var direction = input.offsetDirection;
  10677. // if the touch action did prevented once this session
  10678. if (this.manager.session.prevented) {
  10679. srcEvent.preventDefault();
  10680. return;
  10681. }
  10682. var actions = this.actions;
  10683. var hasNone = inStr(actions, TOUCH_ACTION_NONE);
  10684. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  10685. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  10686. if (hasNone) {
  10687. //do not prevent defaults if this is a tap gesture
  10688. var isTapPointer = input.pointers.length === 1;
  10689. var isTapMovement = input.distance < 2;
  10690. var isTapTouchTime = input.deltaTime < 250;
  10691. if (isTapPointer && isTapMovement && isTapTouchTime) {
  10692. return;
  10693. }
  10694. }
  10695. if (hasPanX && hasPanY) {
  10696. // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
  10697. return;
  10698. }
  10699. if (hasNone ||
  10700. (hasPanY && direction & DIRECTION_HORIZONTAL) ||
  10701. (hasPanX && direction & DIRECTION_VERTICAL)) {
  10702. return this.preventSrc(srcEvent);
  10703. }
  10704. },
  10705. /**
  10706. * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
  10707. * @param {Object} srcEvent
  10708. */
  10709. preventSrc: function(srcEvent) {
  10710. this.manager.session.prevented = true;
  10711. srcEvent.preventDefault();
  10712. }
  10713. };
  10714. /**
  10715. * when the touchActions are collected they are not a valid value, so we need to clean things up. *
  10716. * @param {String} actions
  10717. * @returns {*}
  10718. */
  10719. function cleanTouchActions(actions) {
  10720. // none
  10721. if (inStr(actions, TOUCH_ACTION_NONE)) {
  10722. return TOUCH_ACTION_NONE;
  10723. }
  10724. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  10725. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  10726. // if both pan-x and pan-y are set (different recognizers
  10727. // for different directions, e.g. horizontal pan but vertical swipe?)
  10728. // we need none (as otherwise with pan-x pan-y combined none of these
  10729. // recognizers will work, since the browser would handle all panning
  10730. if (hasPanX && hasPanY) {
  10731. return TOUCH_ACTION_NONE;
  10732. }
  10733. // pan-x OR pan-y
  10734. if (hasPanX || hasPanY) {
  10735. return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
  10736. }
  10737. // manipulation
  10738. if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
  10739. return TOUCH_ACTION_MANIPULATION;
  10740. }
  10741. return TOUCH_ACTION_AUTO;
  10742. }
  10743. /**
  10744. * Recognizer flow explained; *
  10745. * All recognizers have the initial state of POSSIBLE when a input session starts.
  10746. * The definition of a input session is from the first input until the last input, with all it's movement in it. *
  10747. * Example session for mouse-input: mousedown -> mousemove -> mouseup
  10748. *
  10749. * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
  10750. * which determines with state it should be.
  10751. *
  10752. * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
  10753. * POSSIBLE to give it another change on the next cycle.
  10754. *
  10755. * Possible
  10756. * |
  10757. * +-----+---------------+
  10758. * | |
  10759. * +-----+-----+ |
  10760. * | | |
  10761. * Failed Cancelled |
  10762. * +-------+------+
  10763. * | |
  10764. * Recognized Began
  10765. * |
  10766. * Changed
  10767. * |
  10768. * Ended/Recognized
  10769. */
  10770. var STATE_POSSIBLE = 1;
  10771. var STATE_BEGAN = 2;
  10772. var STATE_CHANGED = 4;
  10773. var STATE_ENDED = 8;
  10774. var STATE_RECOGNIZED = STATE_ENDED;
  10775. var STATE_CANCELLED = 16;
  10776. var STATE_FAILED = 32;
  10777. /**
  10778. * Recognizer
  10779. * Every recognizer needs to extend from this class.
  10780. * @constructor
  10781. * @param {Object} options
  10782. */
  10783. function Recognizer(options) {
  10784. this.options = assign({}, this.defaults, options || {});
  10785. this.id = uniqueId();
  10786. this.manager = null;
  10787. // default is enable true
  10788. this.options.enable = ifUndefined(this.options.enable, true);
  10789. this.state = STATE_POSSIBLE;
  10790. this.simultaneous = {};
  10791. this.requireFail = [];
  10792. }
  10793. Recognizer.prototype = {
  10794. /**
  10795. * @virtual
  10796. * @type {Object}
  10797. */
  10798. defaults: {},
  10799. /**
  10800. * set options
  10801. * @param {Object} options
  10802. * @return {Recognizer}
  10803. */
  10804. set: function(options) {
  10805. assign(this.options, options);
  10806. // also update the touchAction, in case something changed about the directions/enabled state
  10807. this.manager && this.manager.touchAction.update();
  10808. return this;
  10809. },
  10810. /**
  10811. * recognize simultaneous with an other recognizer.
  10812. * @param {Recognizer} otherRecognizer
  10813. * @returns {Recognizer} this
  10814. */
  10815. recognizeWith: function(otherRecognizer) {
  10816. if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
  10817. return this;
  10818. }
  10819. var simultaneous = this.simultaneous;
  10820. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  10821. if (!simultaneous[otherRecognizer.id]) {
  10822. simultaneous[otherRecognizer.id] = otherRecognizer;
  10823. otherRecognizer.recognizeWith(this);
  10824. }
  10825. return this;
  10826. },
  10827. /**
  10828. * drop the simultaneous link. it doesnt remove the link on the other recognizer.
  10829. * @param {Recognizer} otherRecognizer
  10830. * @returns {Recognizer} this
  10831. */
  10832. dropRecognizeWith: function(otherRecognizer) {
  10833. if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
  10834. return this;
  10835. }
  10836. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  10837. delete this.simultaneous[otherRecognizer.id];
  10838. return this;
  10839. },
  10840. /**
  10841. * recognizer can only run when an other is failing
  10842. * @param {Recognizer} otherRecognizer
  10843. * @returns {Recognizer} this
  10844. */
  10845. requireFailure: function(otherRecognizer) {
  10846. if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
  10847. return this;
  10848. }
  10849. var requireFail = this.requireFail;
  10850. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  10851. if (inArray(requireFail, otherRecognizer) === -1) {
  10852. requireFail.push(otherRecognizer);
  10853. otherRecognizer.requireFailure(this);
  10854. }
  10855. return this;
  10856. },
  10857. /**
  10858. * drop the requireFailure link. it does not remove the link on the other recognizer.
  10859. * @param {Recognizer} otherRecognizer
  10860. * @returns {Recognizer} this
  10861. */
  10862. dropRequireFailure: function(otherRecognizer) {
  10863. if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
  10864. return this;
  10865. }
  10866. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  10867. var index = inArray(this.requireFail, otherRecognizer);
  10868. if (index > -1) {
  10869. this.requireFail.splice(index, 1);
  10870. }
  10871. return this;
  10872. },
  10873. /**
  10874. * has require failures boolean
  10875. * @returns {boolean}
  10876. */
  10877. hasRequireFailures: function() {
  10878. return this.requireFail.length > 0;
  10879. },
  10880. /**
  10881. * if the recognizer can recognize simultaneous with an other recognizer
  10882. * @param {Recognizer} otherRecognizer
  10883. * @returns {Boolean}
  10884. */
  10885. canRecognizeWith: function(otherRecognizer) {
  10886. return !!this.simultaneous[otherRecognizer.id];
  10887. },
  10888. /**
  10889. * You should use `tryEmit` instead of `emit` directly to check
  10890. * that all the needed recognizers has failed before emitting.
  10891. * @param {Object} input
  10892. */
  10893. emit: function(input) {
  10894. var self = this;
  10895. var state = this.state;
  10896. function emit(event) {
  10897. self.manager.emit(event, input);
  10898. }
  10899. // 'panstart' and 'panmove'
  10900. if (state < STATE_ENDED) {
  10901. emit(self.options.event + stateStr(state));
  10902. }
  10903. emit(self.options.event); // simple 'eventName' events
  10904. if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
  10905. emit(input.additionalEvent);
  10906. }
  10907. // panend and pancancel
  10908. if (state >= STATE_ENDED) {
  10909. emit(self.options.event + stateStr(state));
  10910. }
  10911. },
  10912. /**
  10913. * Check that all the require failure recognizers has failed,
  10914. * if true, it emits a gesture event,
  10915. * otherwise, setup the state to FAILED.
  10916. * @param {Object} input
  10917. */
  10918. tryEmit: function(input) {
  10919. if (this.canEmit()) {
  10920. return this.emit(input);
  10921. }
  10922. // it's failing anyway
  10923. this.state = STATE_FAILED;
  10924. },
  10925. /**
  10926. * can we emit?
  10927. * @returns {boolean}
  10928. */
  10929. canEmit: function() {
  10930. var i = 0;
  10931. while (i < this.requireFail.length) {
  10932. if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
  10933. return false;
  10934. }
  10935. i++;
  10936. }
  10937. return true;
  10938. },
  10939. /**
  10940. * update the recognizer
  10941. * @param {Object} inputData
  10942. */
  10943. recognize: function(inputData) {
  10944. // make a new copy of the inputData
  10945. // so we can change the inputData without messing up the other recognizers
  10946. var inputDataClone = assign({}, inputData);
  10947. // is is enabled and allow recognizing?
  10948. if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
  10949. this.reset();
  10950. this.state = STATE_FAILED;
  10951. return;
  10952. }
  10953. // reset when we've reached the end
  10954. if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
  10955. this.state = STATE_POSSIBLE;
  10956. }
  10957. this.state = this.process(inputDataClone);
  10958. // the recognizer has recognized a gesture
  10959. // so trigger an event
  10960. if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
  10961. this.tryEmit(inputDataClone);
  10962. }
  10963. },
  10964. /**
  10965. * return the state of the recognizer
  10966. * the actual recognizing happens in this method
  10967. * @virtual
  10968. * @param {Object} inputData
  10969. * @returns {Const} STATE
  10970. */
  10971. process: function(inputData) { }, // jshint ignore:line
  10972. /**
  10973. * return the preferred touch-action
  10974. * @virtual
  10975. * @returns {Array}
  10976. */
  10977. getTouchAction: function() { },
  10978. /**
  10979. * called when the gesture isn't allowed to recognize
  10980. * like when another is being recognized or it is disabled
  10981. * @virtual
  10982. */
  10983. reset: function() { }
  10984. };
  10985. /**
  10986. * get a usable string, used as event postfix
  10987. * @param {Const} state
  10988. * @returns {String} state
  10989. */
  10990. function stateStr(state) {
  10991. if (state & STATE_CANCELLED) {
  10992. return 'cancel';
  10993. } else if (state & STATE_ENDED) {
  10994. return 'end';
  10995. } else if (state & STATE_CHANGED) {
  10996. return 'move';
  10997. } else if (state & STATE_BEGAN) {
  10998. return 'start';
  10999. }
  11000. return '';
  11001. }
  11002. /**
  11003. * direction cons to string
  11004. * @param {Const} direction
  11005. * @returns {String}
  11006. */
  11007. function directionStr(direction) {
  11008. if (direction == DIRECTION_DOWN) {
  11009. return 'down';
  11010. } else if (direction == DIRECTION_UP) {
  11011. return 'up';
  11012. } else if (direction == DIRECTION_LEFT) {
  11013. return 'left';
  11014. } else if (direction == DIRECTION_RIGHT) {
  11015. return 'right';
  11016. }
  11017. return '';
  11018. }
  11019. /**
  11020. * get a recognizer by name if it is bound to a manager
  11021. * @param {Recognizer|String} otherRecognizer
  11022. * @param {Recognizer} recognizer
  11023. * @returns {Recognizer}
  11024. */
  11025. function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
  11026. var manager = recognizer.manager;
  11027. if (manager) {
  11028. return manager.get(otherRecognizer);
  11029. }
  11030. return otherRecognizer;
  11031. }
  11032. /**
  11033. * This recognizer is just used as a base for the simple attribute recognizers.
  11034. * @constructor
  11035. * @extends Recognizer
  11036. */
  11037. function AttrRecognizer() {
  11038. Recognizer.apply(this, arguments);
  11039. }
  11040. inherit(AttrRecognizer, Recognizer, {
  11041. /**
  11042. * @namespace
  11043. * @memberof AttrRecognizer
  11044. */
  11045. defaults: {
  11046. /**
  11047. * @type {Number}
  11048. * @default 1
  11049. */
  11050. pointers: 1
  11051. },
  11052. /**
  11053. * Used to check if it the recognizer receives valid input, like input.distance > 10.
  11054. * @memberof AttrRecognizer
  11055. * @param {Object} input
  11056. * @returns {Boolean} recognized
  11057. */
  11058. attrTest: function(input) {
  11059. var optionPointers = this.options.pointers;
  11060. return optionPointers === 0 || input.pointers.length === optionPointers;
  11061. },
  11062. /**
  11063. * Process the input and return the state for the recognizer
  11064. * @memberof AttrRecognizer
  11065. * @param {Object} input
  11066. * @returns {*} State
  11067. */
  11068. process: function(input) {
  11069. var state = this.state;
  11070. var eventType = input.eventType;
  11071. var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
  11072. var isValid = this.attrTest(input);
  11073. // on cancel input and we've recognized before, return STATE_CANCELLED
  11074. if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
  11075. return state | STATE_CANCELLED;
  11076. } else if (isRecognized || isValid) {
  11077. if (eventType & INPUT_END) {
  11078. return state | STATE_ENDED;
  11079. } else if (!(state & STATE_BEGAN)) {
  11080. return STATE_BEGAN;
  11081. }
  11082. return state | STATE_CHANGED;
  11083. }
  11084. return STATE_FAILED;
  11085. }
  11086. });
  11087. /**
  11088. * Pan
  11089. * Recognized when the pointer is down and moved in the allowed direction.
  11090. * @constructor
  11091. * @extends AttrRecognizer
  11092. */
  11093. function PanRecognizer() {
  11094. AttrRecognizer.apply(this, arguments);
  11095. this.pX = null;
  11096. this.pY = null;
  11097. }
  11098. inherit(PanRecognizer, AttrRecognizer, {
  11099. /**
  11100. * @namespace
  11101. * @memberof PanRecognizer
  11102. */
  11103. defaults: {
  11104. event: 'pan',
  11105. threshold: 10,
  11106. pointers: 1,
  11107. direction: DIRECTION_ALL
  11108. },
  11109. getTouchAction: function() {
  11110. var direction = this.options.direction;
  11111. var actions = [];
  11112. if (direction & DIRECTION_HORIZONTAL) {
  11113. actions.push(TOUCH_ACTION_PAN_Y);
  11114. }
  11115. if (direction & DIRECTION_VERTICAL) {
  11116. actions.push(TOUCH_ACTION_PAN_X);
  11117. }
  11118. return actions;
  11119. },
  11120. directionTest: function(input) {
  11121. var options = this.options;
  11122. var hasMoved = true;
  11123. var distance = input.distance;
  11124. var direction = input.direction;
  11125. var x = input.deltaX;
  11126. var y = input.deltaY;
  11127. // lock to axis?
  11128. if (!(direction & options.direction)) {
  11129. if (options.direction & DIRECTION_HORIZONTAL) {
  11130. direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  11131. hasMoved = x != this.pX;
  11132. distance = Math.abs(input.deltaX);
  11133. } else {
  11134. direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  11135. hasMoved = y != this.pY;
  11136. distance = Math.abs(input.deltaY);
  11137. }
  11138. }
  11139. input.direction = direction;
  11140. return hasMoved && distance > options.threshold && direction & options.direction;
  11141. },
  11142. attrTest: function(input) {
  11143. return AttrRecognizer.prototype.attrTest.call(this, input) &&
  11144. (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
  11145. },
  11146. emit: function(input) {
  11147. this.pX = input.deltaX;
  11148. this.pY = input.deltaY;
  11149. var direction = directionStr(input.direction);
  11150. if (direction) {
  11151. input.additionalEvent = this.options.event + direction;
  11152. }
  11153. this._super.emit.call(this, input);
  11154. }
  11155. });
  11156. /**
  11157. * Pinch
  11158. * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
  11159. * @constructor
  11160. * @extends AttrRecognizer
  11161. */
  11162. function PinchRecognizer() {
  11163. AttrRecognizer.apply(this, arguments);
  11164. }
  11165. inherit(PinchRecognizer, AttrRecognizer, {
  11166. /**
  11167. * @namespace
  11168. * @memberof PinchRecognizer
  11169. */
  11170. defaults: {
  11171. event: 'pinch',
  11172. threshold: 0,
  11173. pointers: 2
  11174. },
  11175. getTouchAction: function() {
  11176. return [TOUCH_ACTION_NONE];
  11177. },
  11178. attrTest: function(input) {
  11179. return this._super.attrTest.call(this, input) &&
  11180. (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
  11181. },
  11182. emit: function(input) {
  11183. if (input.scale !== 1) {
  11184. var inOut = input.scale < 1 ? 'in' : 'out';
  11185. input.additionalEvent = this.options.event + inOut;
  11186. }
  11187. this._super.emit.call(this, input);
  11188. }
  11189. });
  11190. /**
  11191. * Press
  11192. * Recognized when the pointer is down for x ms without any movement.
  11193. * @constructor
  11194. * @extends Recognizer
  11195. */
  11196. function PressRecognizer() {
  11197. Recognizer.apply(this, arguments);
  11198. this._timer = null;
  11199. this._input = null;
  11200. }
  11201. inherit(PressRecognizer, Recognizer, {
  11202. /**
  11203. * @namespace
  11204. * @memberof PressRecognizer
  11205. */
  11206. defaults: {
  11207. event: 'press',
  11208. pointers: 1,
  11209. time: 251, // minimal time of the pointer to be pressed
  11210. threshold: 9 // a minimal movement is ok, but keep it low
  11211. },
  11212. getTouchAction: function() {
  11213. return [TOUCH_ACTION_AUTO];
  11214. },
  11215. process: function(input) {
  11216. var options = this.options;
  11217. var validPointers = input.pointers.length === options.pointers;
  11218. var validMovement = input.distance < options.threshold;
  11219. var validTime = input.deltaTime > options.time;
  11220. this._input = input;
  11221. // we only allow little movement
  11222. // and we've reached an end event, so a tap is possible
  11223. if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
  11224. this.reset();
  11225. } else if (input.eventType & INPUT_START) {
  11226. this.reset();
  11227. this._timer = setTimeoutContext(function() {
  11228. this.state = STATE_RECOGNIZED;
  11229. this.tryEmit();
  11230. }, options.time, this);
  11231. } else if (input.eventType & INPUT_END) {
  11232. return STATE_RECOGNIZED;
  11233. }
  11234. return STATE_FAILED;
  11235. },
  11236. reset: function() {
  11237. clearTimeout(this._timer);
  11238. },
  11239. emit: function(input) {
  11240. if (this.state !== STATE_RECOGNIZED) {
  11241. return;
  11242. }
  11243. if (input && (input.eventType & INPUT_END)) {
  11244. this.manager.emit(this.options.event + 'up', input);
  11245. } else {
  11246. this._input.timeStamp = now();
  11247. this.manager.emit(this.options.event, this._input);
  11248. }
  11249. }
  11250. });
  11251. /**
  11252. * Rotate
  11253. * Recognized when two or more pointer are moving in a circular motion.
  11254. * @constructor
  11255. * @extends AttrRecognizer
  11256. */
  11257. function RotateRecognizer() {
  11258. AttrRecognizer.apply(this, arguments);
  11259. }
  11260. inherit(RotateRecognizer, AttrRecognizer, {
  11261. /**
  11262. * @namespace
  11263. * @memberof RotateRecognizer
  11264. */
  11265. defaults: {
  11266. event: 'rotate',
  11267. threshold: 0,
  11268. pointers: 2
  11269. },
  11270. getTouchAction: function() {
  11271. return [TOUCH_ACTION_NONE];
  11272. },
  11273. attrTest: function(input) {
  11274. return this._super.attrTest.call(this, input) &&
  11275. (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
  11276. }
  11277. });
  11278. /**
  11279. * Swipe
  11280. * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
  11281. * @constructor
  11282. * @extends AttrRecognizer
  11283. */
  11284. function SwipeRecognizer() {
  11285. AttrRecognizer.apply(this, arguments);
  11286. }
  11287. inherit(SwipeRecognizer, AttrRecognizer, {
  11288. /**
  11289. * @namespace
  11290. * @memberof SwipeRecognizer
  11291. */
  11292. defaults: {
  11293. event: 'swipe',
  11294. threshold: 10,
  11295. velocity: 0.3,
  11296. direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
  11297. pointers: 1
  11298. },
  11299. getTouchAction: function() {
  11300. return PanRecognizer.prototype.getTouchAction.call(this);
  11301. },
  11302. attrTest: function(input) {
  11303. var direction = this.options.direction;
  11304. var velocity;
  11305. if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
  11306. velocity = input.overallVelocity;
  11307. } else if (direction & DIRECTION_HORIZONTAL) {
  11308. velocity = input.overallVelocityX;
  11309. } else if (direction & DIRECTION_VERTICAL) {
  11310. velocity = input.overallVelocityY;
  11311. }
  11312. return this._super.attrTest.call(this, input) &&
  11313. direction & input.offsetDirection &&
  11314. input.distance > this.options.threshold &&
  11315. input.maxPointers == this.options.pointers &&
  11316. abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
  11317. },
  11318. emit: function(input) {
  11319. var direction = directionStr(input.offsetDirection);
  11320. if (direction) {
  11321. this.manager.emit(this.options.event + direction, input);
  11322. }
  11323. this.manager.emit(this.options.event, input);
  11324. }
  11325. });
  11326. /**
  11327. * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
  11328. * between the given interval and position. The delay option can be used to recognize multi-taps without firing
  11329. * a single tap.
  11330. *
  11331. * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
  11332. * multi-taps being recognized.
  11333. * @constructor
  11334. * @extends Recognizer
  11335. */
  11336. function TapRecognizer() {
  11337. Recognizer.apply(this, arguments);
  11338. // previous time and center,
  11339. // used for tap counting
  11340. this.pTime = false;
  11341. this.pCenter = false;
  11342. this._timer = null;
  11343. this._input = null;
  11344. this.count = 0;
  11345. }
  11346. inherit(TapRecognizer, Recognizer, {
  11347. /**
  11348. * @namespace
  11349. * @memberof PinchRecognizer
  11350. */
  11351. defaults: {
  11352. event: 'tap',
  11353. pointers: 1,
  11354. taps: 1,
  11355. interval: 300, // max time between the multi-tap taps
  11356. time: 250, // max time of the pointer to be down (like finger on the screen)
  11357. threshold: 9, // a minimal movement is ok, but keep it low
  11358. posThreshold: 10 // a multi-tap can be a bit off the initial position
  11359. },
  11360. getTouchAction: function() {
  11361. return [TOUCH_ACTION_MANIPULATION];
  11362. },
  11363. process: function(input) {
  11364. var options = this.options;
  11365. var validPointers = input.pointers.length === options.pointers;
  11366. var validMovement = input.distance < options.threshold;
  11367. var validTouchTime = input.deltaTime < options.time;
  11368. this.reset();
  11369. if ((input.eventType & INPUT_START) && (this.count === 0)) {
  11370. return this.failTimeout();
  11371. }
  11372. // we only allow little movement
  11373. // and we've reached an end event, so a tap is possible
  11374. if (validMovement && validTouchTime && validPointers) {
  11375. if (input.eventType != INPUT_END) {
  11376. return this.failTimeout();
  11377. }
  11378. var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
  11379. var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
  11380. this.pTime = input.timeStamp;
  11381. this.pCenter = input.center;
  11382. if (!validMultiTap || !validInterval) {
  11383. this.count = 1;
  11384. } else {
  11385. this.count += 1;
  11386. }
  11387. this._input = input;
  11388. // if tap count matches we have recognized it,
  11389. // else it has began recognizing...
  11390. var tapCount = this.count % options.taps;
  11391. if (tapCount === 0) {
  11392. // no failing requirements, immediately trigger the tap event
  11393. // or wait as long as the multitap interval to trigger
  11394. if (!this.hasRequireFailures()) {
  11395. return STATE_RECOGNIZED;
  11396. } else {
  11397. this._timer = setTimeoutContext(function() {
  11398. this.state = STATE_RECOGNIZED;
  11399. this.tryEmit();
  11400. }, options.interval, this);
  11401. return STATE_BEGAN;
  11402. }
  11403. }
  11404. }
  11405. return STATE_FAILED;
  11406. },
  11407. failTimeout: function() {
  11408. this._timer = setTimeoutContext(function() {
  11409. this.state = STATE_FAILED;
  11410. }, this.options.interval, this);
  11411. return STATE_FAILED;
  11412. },
  11413. reset: function() {
  11414. clearTimeout(this._timer);
  11415. },
  11416. emit: function() {
  11417. if (this.state == STATE_RECOGNIZED) {
  11418. this._input.tapCount = this.count;
  11419. this.manager.emit(this.options.event, this._input);
  11420. }
  11421. }
  11422. });
  11423. /**
  11424. * Simple way to create a manager with a default set of recognizers.
  11425. * @param {HTMLElement} element
  11426. * @param {Object} [options]
  11427. * @constructor
  11428. */
  11429. function Hammer(element, options) {
  11430. options = options || {};
  11431. options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
  11432. return new Manager(element, options);
  11433. }
  11434. /**
  11435. * @const {string}
  11436. */
  11437. Hammer.VERSION = '2.0.6';
  11438. /**
  11439. * default settings
  11440. * @namespace
  11441. */
  11442. Hammer.defaults = {
  11443. /**
  11444. * set if DOM events are being triggered.
  11445. * But this is slower and unused by simple implementations, so disabled by default.
  11446. * @type {Boolean}
  11447. * @default false
  11448. */
  11449. domEvents: false,
  11450. /**
  11451. * The value for the touchAction property/fallback.
  11452. * When set to `compute` it will magically set the correct value based on the added recognizers.
  11453. * @type {String}
  11454. * @default compute
  11455. */
  11456. touchAction: TOUCH_ACTION_COMPUTE,
  11457. /**
  11458. * @type {Boolean}
  11459. * @default true
  11460. */
  11461. enable: true,
  11462. /**
  11463. * EXPERIMENTAL FEATURE -- can be removed/changed
  11464. * Change the parent input target element.
  11465. * If Null, then it is being set the to main element.
  11466. * @type {Null|EventTarget}
  11467. * @default null
  11468. */
  11469. inputTarget: null,
  11470. /**
  11471. * force an input class
  11472. * @type {Null|Function}
  11473. * @default null
  11474. */
  11475. inputClass: null,
  11476. /**
  11477. * Default recognizer setup when calling `Hammer()`
  11478. * When creating a new Manager these will be skipped.
  11479. * @type {Array}
  11480. */
  11481. preset: [
  11482. // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
  11483. [RotateRecognizer, {enable: false}],
  11484. [PinchRecognizer, {enable: false}, ['rotate']],
  11485. [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
  11486. [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
  11487. [TapRecognizer],
  11488. [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
  11489. [PressRecognizer]
  11490. ],
  11491. /**
  11492. * Some CSS properties can be used to improve the working of Hammer.
  11493. * Add them to this method and they will be set when creating a new Manager.
  11494. * @namespace
  11495. */
  11496. cssProps: {
  11497. /**
  11498. * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
  11499. * @type {String}
  11500. * @default 'none'
  11501. */
  11502. userSelect: 'none',
  11503. /**
  11504. * Disable the Windows Phone grippers when pressing an element.
  11505. * @type {String}
  11506. * @default 'none'
  11507. */
  11508. touchSelect: 'none',
  11509. /**
  11510. * Disables the default callout shown when you touch and hold a touch target.
  11511. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  11512. * a callout containing information about the link. This property allows you to disable that callout.
  11513. * @type {String}
  11514. * @default 'none'
  11515. */
  11516. touchCallout: 'none',
  11517. /**
  11518. * Specifies whether zooming is enabled. Used by IE10>
  11519. * @type {String}
  11520. * @default 'none'
  11521. */
  11522. contentZooming: 'none',
  11523. /**
  11524. * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
  11525. * @type {String}
  11526. * @default 'none'
  11527. */
  11528. userDrag: 'none',
  11529. /**
  11530. * Overrides the highlight color shown when the user taps a link or a JavaScript
  11531. * clickable element in iOS. This property obeys the alpha value, if specified.
  11532. * @type {String}
  11533. * @default 'rgba(0,0,0,0)'
  11534. */
  11535. tapHighlightColor: 'rgba(0,0,0,0)'
  11536. }
  11537. };
  11538. var STOP = 1;
  11539. var FORCED_STOP = 2;
  11540. /**
  11541. * Manager
  11542. * @param {HTMLElement} element
  11543. * @param {Object} [options]
  11544. * @constructor
  11545. */
  11546. function Manager(element, options) {
  11547. this.options = assign({}, Hammer.defaults, options || {});
  11548. this.options.inputTarget = this.options.inputTarget || element;
  11549. this.handlers = {};
  11550. this.session = {};
  11551. this.recognizers = [];
  11552. this.element = element;
  11553. this.input = createInputInstance(this);
  11554. this.touchAction = new TouchAction(this, this.options.touchAction);
  11555. toggleCssProps(this, true);
  11556. each(this.options.recognizers, function(item) {
  11557. var recognizer = this.add(new (item[0])(item[1]));
  11558. item[2] && recognizer.recognizeWith(item[2]);
  11559. item[3] && recognizer.requireFailure(item[3]);
  11560. }, this);
  11561. }
  11562. Manager.prototype = {
  11563. /**
  11564. * set options
  11565. * @param {Object} options
  11566. * @returns {Manager}
  11567. */
  11568. set: function(options) {
  11569. assign(this.options, options);
  11570. // Options that need a little more setup
  11571. if (options.touchAction) {
  11572. this.touchAction.update();
  11573. }
  11574. if (options.inputTarget) {
  11575. // Clean up existing event listeners and reinitialize
  11576. this.input.destroy();
  11577. this.input.target = options.inputTarget;
  11578. this.input.init();
  11579. }
  11580. return this;
  11581. },
  11582. /**
  11583. * stop recognizing for this session.
  11584. * This session will be discarded, when a new [input]start event is fired.
  11585. * When forced, the recognizer cycle is stopped immediately.
  11586. * @param {Boolean} [force]
  11587. */
  11588. stop: function(force) {
  11589. this.session.stopped = force ? FORCED_STOP : STOP;
  11590. },
  11591. /**
  11592. * run the recognizers!
  11593. * called by the inputHandler function on every movement of the pointers (touches)
  11594. * it walks through all the recognizers and tries to detect the gesture that is being made
  11595. * @param {Object} inputData
  11596. */
  11597. recognize: function(inputData) {
  11598. var session = this.session;
  11599. if (session.stopped) {
  11600. return;
  11601. }
  11602. // run the touch-action polyfill
  11603. this.touchAction.preventDefaults(inputData);
  11604. var recognizer;
  11605. var recognizers = this.recognizers;
  11606. // this holds the recognizer that is being recognized.
  11607. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
  11608. // if no recognizer is detecting a thing, it is set to `null`
  11609. var curRecognizer = session.curRecognizer;
  11610. // reset when the last recognizer is recognized
  11611. // or when we're in a new session
  11612. if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
  11613. curRecognizer = session.curRecognizer = null;
  11614. }
  11615. var i = 0;
  11616. while (i < recognizers.length) {
  11617. recognizer = recognizers[i];
  11618. // find out if we are allowed try to recognize the input for this one.
  11619. // 1. allow if the session is NOT forced stopped (see the .stop() method)
  11620. // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
  11621. // that is being recognized.
  11622. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
  11623. // this can be setup with the `recognizeWith()` method on the recognizer.
  11624. if (session.stopped !== FORCED_STOP && ( // 1
  11625. !curRecognizer || recognizer == curRecognizer || // 2
  11626. recognizer.canRecognizeWith(curRecognizer))) { // 3
  11627. recognizer.recognize(inputData);
  11628. } else {
  11629. recognizer.reset();
  11630. }
  11631. // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
  11632. // current active recognizer. but only if we don't already have an active recognizer
  11633. if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
  11634. curRecognizer = session.curRecognizer = recognizer;
  11635. }
  11636. i++;
  11637. }
  11638. },
  11639. /**
  11640. * get a recognizer by its event name.
  11641. * @param {Recognizer|String} recognizer
  11642. * @returns {Recognizer|Null}
  11643. */
  11644. get: function(recognizer) {
  11645. if (recognizer instanceof Recognizer) {
  11646. return recognizer;
  11647. }
  11648. var recognizers = this.recognizers;
  11649. for (var i = 0; i < recognizers.length; i++) {
  11650. if (recognizers[i].options.event == recognizer) {
  11651. return recognizers[i];
  11652. }
  11653. }
  11654. return null;
  11655. },
  11656. /**
  11657. * add a recognizer to the manager
  11658. * existing recognizers with the same event name will be removed
  11659. * @param {Recognizer} recognizer
  11660. * @returns {Recognizer|Manager}
  11661. */
  11662. add: function(recognizer) {
  11663. if (invokeArrayArg(recognizer, 'add', this)) {
  11664. return this;
  11665. }
  11666. // remove existing
  11667. var existing = this.get(recognizer.options.event);
  11668. if (existing) {
  11669. this.remove(existing);
  11670. }
  11671. this.recognizers.push(recognizer);
  11672. recognizer.manager = this;
  11673. this.touchAction.update();
  11674. return recognizer;
  11675. },
  11676. /**
  11677. * remove a recognizer by name or instance
  11678. * @param {Recognizer|String} recognizer
  11679. * @returns {Manager}
  11680. */
  11681. remove: function(recognizer) {
  11682. if (invokeArrayArg(recognizer, 'remove', this)) {
  11683. return this;
  11684. }
  11685. recognizer = this.get(recognizer);
  11686. // let's make sure this recognizer exists
  11687. if (recognizer) {
  11688. var recognizers = this.recognizers;
  11689. var index = inArray(recognizers, recognizer);
  11690. if (index !== -1) {
  11691. recognizers.splice(index, 1);
  11692. this.touchAction.update();
  11693. }
  11694. }
  11695. return this;
  11696. },
  11697. /**
  11698. * bind event
  11699. * @param {String} events
  11700. * @param {Function} handler
  11701. * @returns {EventEmitter} this
  11702. */
  11703. on: function(events, handler) {
  11704. var handlers = this.handlers;
  11705. each(splitStr(events), function(event) {
  11706. handlers[event] = handlers[event] || [];
  11707. handlers[event].push(handler);
  11708. });
  11709. return this;
  11710. },
  11711. /**
  11712. * unbind event, leave emit blank to remove all handlers
  11713. * @param {String} events
  11714. * @param {Function} [handler]
  11715. * @returns {EventEmitter} this
  11716. */
  11717. off: function(events, handler) {
  11718. var handlers = this.handlers;
  11719. each(splitStr(events), function(event) {
  11720. if (!handler) {
  11721. delete handlers[event];
  11722. } else {
  11723. handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
  11724. }
  11725. });
  11726. return this;
  11727. },
  11728. /**
  11729. * emit event to the listeners
  11730. * @param {String} event
  11731. * @param {Object} data
  11732. */
  11733. emit: function(event, data) {
  11734. // we also want to trigger dom events
  11735. if (this.options.domEvents) {
  11736. triggerDomEvent(event, data);
  11737. }
  11738. // no handlers, so skip it all
  11739. var handlers = this.handlers[event] && this.handlers[event].slice();
  11740. if (!handlers || !handlers.length) {
  11741. return;
  11742. }
  11743. data.type = event;
  11744. data.preventDefault = function() {
  11745. data.srcEvent.preventDefault();
  11746. };
  11747. var i = 0;
  11748. while (i < handlers.length) {
  11749. handlers[i](data);
  11750. i++;
  11751. }
  11752. },
  11753. /**
  11754. * destroy the manager and unbinds all events
  11755. * it doesn't unbind dom events, that is the user own responsibility
  11756. */
  11757. destroy: function() {
  11758. this.element && toggleCssProps(this, false);
  11759. this.handlers = {};
  11760. this.session = {};
  11761. this.input.destroy();
  11762. this.element = null;
  11763. }
  11764. };
  11765. /**
  11766. * add/remove the css properties as defined in manager.options.cssProps
  11767. * @param {Manager} manager
  11768. * @param {Boolean} add
  11769. */
  11770. function toggleCssProps(manager, add) {
  11771. var element = manager.element;
  11772. if (!element.style) {
  11773. return;
  11774. }
  11775. each(manager.options.cssProps, function(value, name) {
  11776. element.style[prefixed(element.style, name)] = add ? value : '';
  11777. });
  11778. }
  11779. /**
  11780. * trigger dom event
  11781. * @param {String} event
  11782. * @param {Object} data
  11783. */
  11784. function triggerDomEvent(event, data) {
  11785. var gestureEvent = document.createEvent('Event');
  11786. gestureEvent.initEvent(event, true, true);
  11787. gestureEvent.gesture = data;
  11788. data.target.dispatchEvent(gestureEvent);
  11789. }
  11790. assign(Hammer, {
  11791. INPUT_START: INPUT_START,
  11792. INPUT_MOVE: INPUT_MOVE,
  11793. INPUT_END: INPUT_END,
  11794. INPUT_CANCEL: INPUT_CANCEL,
  11795. STATE_POSSIBLE: STATE_POSSIBLE,
  11796. STATE_BEGAN: STATE_BEGAN,
  11797. STATE_CHANGED: STATE_CHANGED,
  11798. STATE_ENDED: STATE_ENDED,
  11799. STATE_RECOGNIZED: STATE_RECOGNIZED,
  11800. STATE_CANCELLED: STATE_CANCELLED,
  11801. STATE_FAILED: STATE_FAILED,
  11802. DIRECTION_NONE: DIRECTION_NONE,
  11803. DIRECTION_LEFT: DIRECTION_LEFT,
  11804. DIRECTION_RIGHT: DIRECTION_RIGHT,
  11805. DIRECTION_UP: DIRECTION_UP,
  11806. DIRECTION_DOWN: DIRECTION_DOWN,
  11807. DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
  11808. DIRECTION_VERTICAL: DIRECTION_VERTICAL,
  11809. DIRECTION_ALL: DIRECTION_ALL,
  11810. Manager: Manager,
  11811. Input: Input,
  11812. TouchAction: TouchAction,
  11813. TouchInput: TouchInput,
  11814. MouseInput: MouseInput,
  11815. PointerEventInput: PointerEventInput,
  11816. TouchMouseInput: TouchMouseInput,
  11817. SingleTouchInput: SingleTouchInput,
  11818. Recognizer: Recognizer,
  11819. AttrRecognizer: AttrRecognizer,
  11820. Tap: TapRecognizer,
  11821. Pan: PanRecognizer,
  11822. Swipe: SwipeRecognizer,
  11823. Pinch: PinchRecognizer,
  11824. Rotate: RotateRecognizer,
  11825. Press: PressRecognizer,
  11826. on: addEventListeners,
  11827. off: removeEventListeners,
  11828. each: each,
  11829. merge: merge,
  11830. extend: extend,
  11831. assign: assign,
  11832. inherit: inherit,
  11833. bindFn: bindFn,
  11834. prefixed: prefixed
  11835. });
  11836. // this prevents errors when Hammer is loaded in the presence of an AMD
  11837. // style loader but by script tag, not by the loader.
  11838. var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
  11839. freeGlobal.Hammer = Hammer;
  11840. if (true) {
  11841. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
  11842. return Hammer;
  11843. }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  11844. } else if (typeof module != 'undefined' && module.exports) {
  11845. module.exports = Hammer;
  11846. } else {
  11847. window[exportName] = Hammer;
  11848. }
  11849. })(window, document, 'Hammer');
  11850. /***/ },
  11851. /* 23 */
  11852. /***/ function(module, exports, __webpack_require__) {
  11853. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
  11854. /**
  11855. * Created by Alex on 11/6/2014.
  11856. */
  11857. // https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
  11858. // if the module has no dependencies, the above pattern can be simplified to
  11859. (function (root, factory) {
  11860. if (true) {
  11861. // AMD. Register as an anonymous module.
  11862. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  11863. } else if (typeof exports === 'object') {
  11864. // Node. Does not work with strict CommonJS, but
  11865. // only CommonJS-like environments that support module.exports,
  11866. // like Node.
  11867. module.exports = factory();
  11868. } else {
  11869. // Browser globals (root is window)
  11870. root.keycharm = factory();
  11871. }
  11872. }(this, function () {
  11873. function keycharm(options) {
  11874. var preventDefault = options && options.preventDefault || false;
  11875. var container = options && options.container || window;
  11876. var _exportFunctions = {};
  11877. var _bound = {keydown:{}, keyup:{}};
  11878. var _keys = {};
  11879. var i;
  11880. // a - z
  11881. for (i = 97; i <= 122; i++) {_keys[String.fromCharCode(i)] = {code:65 + (i - 97), shift: false};}
  11882. // A - Z
  11883. for (i = 65; i <= 90; i++) {_keys[String.fromCharCode(i)] = {code:i, shift: true};}
  11884. // 0 - 9
  11885. for (i = 0; i <= 9; i++) {_keys['' + i] = {code:48 + i, shift: false};}
  11886. // F1 - F12
  11887. for (i = 1; i <= 12; i++) {_keys['F' + i] = {code:111 + i, shift: false};}
  11888. // num0 - num9
  11889. for (i = 0; i <= 9; i++) {_keys['num' + i] = {code:96 + i, shift: false};}
  11890. // numpad misc
  11891. _keys['num*'] = {code:106, shift: false};
  11892. _keys['num+'] = {code:107, shift: false};
  11893. _keys['num-'] = {code:109, shift: false};
  11894. _keys['num/'] = {code:111, shift: false};
  11895. _keys['num.'] = {code:110, shift: false};
  11896. // arrows
  11897. _keys['left'] = {code:37, shift: false};
  11898. _keys['up'] = {code:38, shift: false};
  11899. _keys['right'] = {code:39, shift: false};
  11900. _keys['down'] = {code:40, shift: false};
  11901. // extra keys
  11902. _keys['space'] = {code:32, shift: false};
  11903. _keys['enter'] = {code:13, shift: false};
  11904. _keys['shift'] = {code:16, shift: undefined};
  11905. _keys['esc'] = {code:27, shift: false};
  11906. _keys['backspace'] = {code:8, shift: false};
  11907. _keys['tab'] = {code:9, shift: false};
  11908. _keys['ctrl'] = {code:17, shift: false};
  11909. _keys['alt'] = {code:18, shift: false};
  11910. _keys['delete'] = {code:46, shift: false};
  11911. _keys['pageup'] = {code:33, shift: false};
  11912. _keys['pagedown'] = {code:34, shift: false};
  11913. // symbols
  11914. _keys['='] = {code:187, shift: false};
  11915. _keys['-'] = {code:189, shift: false};
  11916. _keys[']'] = {code:221, shift: false};
  11917. _keys['['] = {code:219, shift: false};
  11918. var down = function(event) {handleEvent(event,'keydown');};
  11919. var up = function(event) {handleEvent(event,'keyup');};
  11920. // handle the actualy bound key with the event
  11921. var handleEvent = function(event,type) {
  11922. if (_bound[type][event.keyCode] !== undefined) {
  11923. var bound = _bound[type][event.keyCode];
  11924. for (var i = 0; i < bound.length; i++) {
  11925. if (bound[i].shift === undefined) {
  11926. bound[i].fn(event);
  11927. }
  11928. else if (bound[i].shift == true && event.shiftKey == true) {
  11929. bound[i].fn(event);
  11930. }
  11931. else if (bound[i].shift == false && event.shiftKey == false) {
  11932. bound[i].fn(event);
  11933. }
  11934. }
  11935. if (preventDefault == true) {
  11936. event.preventDefault();
  11937. }
  11938. }
  11939. };
  11940. // bind a key to a callback
  11941. _exportFunctions.bind = function(key, callback, type) {
  11942. if (type === undefined) {
  11943. type = 'keydown';
  11944. }
  11945. if (_keys[key] === undefined) {
  11946. throw new Error("unsupported key: " + key);
  11947. }
  11948. if (_bound[type][_keys[key].code] === undefined) {
  11949. _bound[type][_keys[key].code] = [];
  11950. }
  11951. _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift});
  11952. };
  11953. // bind all keys to a call back (demo purposes)
  11954. _exportFunctions.bindAll = function(callback, type) {
  11955. if (type === undefined) {
  11956. type = 'keydown';
  11957. }
  11958. for (var key in _keys) {
  11959. if (_keys.hasOwnProperty(key)) {
  11960. _exportFunctions.bind(key,callback,type);
  11961. }
  11962. }
  11963. };
  11964. // get the key label from an event
  11965. _exportFunctions.getKey = function(event) {
  11966. for (var key in _keys) {
  11967. if (_keys.hasOwnProperty(key)) {
  11968. if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
  11969. return key;
  11970. }
  11971. else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
  11972. return key;
  11973. }
  11974. else if (event.keyCode == _keys[key].code && key == 'shift') {
  11975. return key;
  11976. }
  11977. }
  11978. }
  11979. return "unknown key, currently not supported";
  11980. };
  11981. // unbind either a specific callback from a key or all of them (by leaving callback undefined)
  11982. _exportFunctions.unbind = function(key, callback, type) {
  11983. if (type === undefined) {
  11984. type = 'keydown';
  11985. }
  11986. if (_keys[key] === undefined) {
  11987. throw new Error("unsupported key: " + key);
  11988. }
  11989. if (callback !== undefined) {
  11990. var newBindings = [];
  11991. var bound = _bound[type][_keys[key].code];
  11992. if (bound !== undefined) {
  11993. for (var i = 0; i < bound.length; i++) {
  11994. if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
  11995. newBindings.push(_bound[type][_keys[key].code][i]);
  11996. }
  11997. }
  11998. }
  11999. _bound[type][_keys[key].code] = newBindings;
  12000. }
  12001. else {
  12002. _bound[type][_keys[key].code] = [];
  12003. }
  12004. };
  12005. // reset all bound variables.
  12006. _exportFunctions.reset = function() {
  12007. _bound = {keydown:{}, keyup:{}};
  12008. };
  12009. // unbind all listeners and reset all variables.
  12010. _exportFunctions.destroy = function() {
  12011. _bound = {keydown:{}, keyup:{}};
  12012. container.removeEventListener('keydown', down, true);
  12013. container.removeEventListener('keyup', up, true);
  12014. };
  12015. // create listeners.
  12016. container.addEventListener('keydown',down,true);
  12017. container.addEventListener('keyup',up,true);
  12018. // return the public functions.
  12019. return _exportFunctions;
  12020. }
  12021. return keycharm;
  12022. }));
  12023. /***/ },
  12024. /* 24 */
  12025. /***/ function(module, exports, __webpack_require__) {
  12026. 'use strict';
  12027. // utils
  12028. exports.util = __webpack_require__(1);
  12029. exports.DOMutil = __webpack_require__(8);
  12030. // data
  12031. exports.DataSet = __webpack_require__(9);
  12032. exports.DataView = __webpack_require__(11);
  12033. exports.Queue = __webpack_require__(10);
  12034. // Timeline
  12035. exports.Timeline = __webpack_require__(25);
  12036. exports.Graph2d = __webpack_require__(50);
  12037. exports.timeline = {
  12038. Core: __webpack_require__(33),
  12039. DateUtil: __webpack_require__(32),
  12040. Range: __webpack_require__(30),
  12041. stack: __webpack_require__(37),
  12042. TimeStep: __webpack_require__(35),
  12043. components: {
  12044. items: {
  12045. Item: __webpack_require__(39),
  12046. BackgroundItem: __webpack_require__(43),
  12047. BoxItem: __webpack_require__(41),
  12048. PointItem: __webpack_require__(42),
  12049. RangeItem: __webpack_require__(38)
  12050. },
  12051. BackgroundGroup: __webpack_require__(40),
  12052. Component: __webpack_require__(31),
  12053. CurrentTime: __webpack_require__(48),
  12054. CustomTime: __webpack_require__(46),
  12055. DataAxis: __webpack_require__(52),
  12056. DataScale: __webpack_require__(53),
  12057. GraphGroup: __webpack_require__(54),
  12058. Group: __webpack_require__(36),
  12059. ItemSet: __webpack_require__(34),
  12060. Legend: __webpack_require__(58),
  12061. LineGraph: __webpack_require__(51),
  12062. TimeAxis: __webpack_require__(44)
  12063. }
  12064. };
  12065. // bundled external libraries
  12066. exports.moment = __webpack_require__(2);
  12067. exports.Hammer = __webpack_require__(20);
  12068. exports.keycharm = __webpack_require__(23);
  12069. /***/ },
  12070. /* 25 */
  12071. /***/ function(module, exports, __webpack_require__) {
  12072. 'use strict';
  12073. var _Configurator = __webpack_require__(26);
  12074. var _Configurator2 = _interopRequireDefault(_Configurator);
  12075. var _Validator = __webpack_require__(29);
  12076. var _Validator2 = _interopRequireDefault(_Validator);
  12077. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12078. var Emitter = __webpack_require__(13);
  12079. var Hammer = __webpack_require__(20);
  12080. var moment = __webpack_require__(2);
  12081. var util = __webpack_require__(1);
  12082. var DataSet = __webpack_require__(9);
  12083. var DataView = __webpack_require__(11);
  12084. var Range = __webpack_require__(30);
  12085. var Core = __webpack_require__(33);
  12086. var TimeAxis = __webpack_require__(44);
  12087. var CurrentTime = __webpack_require__(48);
  12088. var CustomTime = __webpack_require__(46);
  12089. var ItemSet = __webpack_require__(34);
  12090. var printStyle = __webpack_require__(29).printStyle;
  12091. var allOptions = __webpack_require__(49).allOptions;
  12092. var configureOptions = __webpack_require__(49).configureOptions;
  12093. /**
  12094. * Create a timeline visualization
  12095. * @param {HTMLElement} container
  12096. * @param {vis.DataSet | vis.DataView | Array} [items]
  12097. * @param {vis.DataSet | vis.DataView | Array} [groups]
  12098. * @param {Object} [options] See Timeline.setOptions for the available options.
  12099. * @constructor
  12100. * @extends Core
  12101. */
  12102. function Timeline(container, items, groups, options) {
  12103. if (!(this instanceof Timeline)) {
  12104. throw new SyntaxError('Constructor must be called with the new operator');
  12105. }
  12106. // if the third element is options, the forth is groups (optionally);
  12107. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  12108. var forthArgument = options;
  12109. options = groups;
  12110. groups = forthArgument;
  12111. }
  12112. var me = this;
  12113. this.defaultOptions = {
  12114. start: null,
  12115. end: null,
  12116. autoResize: true,
  12117. throttleRedraw: 0, // ms
  12118. orientation: {
  12119. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  12120. item: 'bottom' // not relevant
  12121. },
  12122. rtl: false,
  12123. moment: moment,
  12124. width: null,
  12125. height: null,
  12126. maxHeight: null,
  12127. minHeight: null
  12128. };
  12129. this.options = util.deepExtend({}, this.defaultOptions);
  12130. // Create the DOM, props, and emitter
  12131. this._create(container);
  12132. // all components listed here will be repainted automatically
  12133. this.components = [];
  12134. this.body = {
  12135. dom: this.dom,
  12136. domProps: this.props,
  12137. emitter: {
  12138. on: this.on.bind(this),
  12139. off: this.off.bind(this),
  12140. emit: this.emit.bind(this)
  12141. },
  12142. hiddenDates: [],
  12143. util: {
  12144. getScale: function getScale() {
  12145. return me.timeAxis.step.scale;
  12146. },
  12147. getStep: function getStep() {
  12148. return me.timeAxis.step.step;
  12149. },
  12150. toScreen: me._toScreen.bind(me),
  12151. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  12152. toTime: me._toTime.bind(me),
  12153. toGlobalTime: me._toGlobalTime.bind(me)
  12154. }
  12155. };
  12156. // range
  12157. this.range = new Range(this.body);
  12158. this.components.push(this.range);
  12159. this.body.range = this.range;
  12160. // time axis
  12161. this.timeAxis = new TimeAxis(this.body);
  12162. this.timeAxis2 = null; // used in case of orientation option 'both'
  12163. this.components.push(this.timeAxis);
  12164. // current time bar
  12165. this.currentTime = new CurrentTime(this.body);
  12166. this.components.push(this.currentTime);
  12167. // item set
  12168. this.itemSet = new ItemSet(this.body, this.options);
  12169. this.components.push(this.itemSet);
  12170. this.itemsData = null; // DataSet
  12171. this.groupsData = null; // DataSet
  12172. this.on('tap', function (event) {
  12173. me.emit('click', me.getEventProperties(event));
  12174. });
  12175. this.on('doubletap', function (event) {
  12176. me.emit('doubleClick', me.getEventProperties(event));
  12177. });
  12178. this.dom.root.oncontextmenu = function (event) {
  12179. me.emit('contextmenu', me.getEventProperties(event));
  12180. };
  12181. //Single time autoscale/fit
  12182. this.fitDone = false;
  12183. this.on('changed', function () {
  12184. if (this.itemsData == null) return;
  12185. if (!me.fitDone) {
  12186. me.fitDone = true;
  12187. if (me.options.start != undefined || me.options.end != undefined) {
  12188. if (me.options.start == undefined || me.options.end == undefined) {
  12189. var range = me.getItemRange();
  12190. }
  12191. var start = me.options.start != undefined ? me.options.start : range.min;
  12192. var end = me.options.end != undefined ? me.options.end : range.max;
  12193. me.setWindow(start, end, { animation: false });
  12194. } else {
  12195. me.fit({ animation: false });
  12196. }
  12197. }
  12198. });
  12199. // apply options
  12200. if (options) {
  12201. this.setOptions(options);
  12202. }
  12203. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  12204. if (groups) {
  12205. this.setGroups(groups);
  12206. }
  12207. // create itemset
  12208. if (items) {
  12209. this.setItems(items);
  12210. }
  12211. // draw for the first time
  12212. this._redraw();
  12213. }
  12214. // Extend the functionality from Core
  12215. Timeline.prototype = new Core();
  12216. /**
  12217. * Load a configurator
  12218. * @return {Object}
  12219. * @private
  12220. */
  12221. Timeline.prototype._createConfigurator = function () {
  12222. return new _Configurator2.default(this, this.dom.container, configureOptions);
  12223. };
  12224. /**
  12225. * Force a redraw. The size of all items will be recalculated.
  12226. * Can be useful to manually redraw when option autoResize=false and the window
  12227. * has been resized, or when the items CSS has been changed.
  12228. *
  12229. * Note: this function will be overridden on construction with a trottled version
  12230. */
  12231. Timeline.prototype.redraw = function () {
  12232. this.itemSet && this.itemSet.markDirty({ refreshItems: true });
  12233. this._redraw();
  12234. };
  12235. Timeline.prototype.setOptions = function (options) {
  12236. // validate options
  12237. var errorFound = _Validator2.default.validate(options, allOptions);
  12238. if (errorFound === true) {
  12239. console.log('%cErrors have been found in the supplied options object.', printStyle);
  12240. }
  12241. Core.prototype.setOptions.call(this, options);
  12242. if ('type' in options) {
  12243. if (options.type !== this.options.type) {
  12244. this.options.type = options.type;
  12245. // force recreation of all items
  12246. var itemsData = this.itemsData;
  12247. if (itemsData) {
  12248. var selection = this.getSelection();
  12249. this.setItems(null); // remove all
  12250. this.setItems(itemsData); // add all
  12251. this.setSelection(selection); // restore selection
  12252. }
  12253. }
  12254. }
  12255. };
  12256. /**
  12257. * Set items
  12258. * @param {vis.DataSet | Array | null} items
  12259. */
  12260. Timeline.prototype.setItems = function (items) {
  12261. // convert to type DataSet when needed
  12262. var newDataSet;
  12263. if (!items) {
  12264. newDataSet = null;
  12265. } else if (items instanceof DataSet || items instanceof DataView) {
  12266. newDataSet = items;
  12267. } else {
  12268. // turn an array into a dataset
  12269. newDataSet = new DataSet(items, {
  12270. type: {
  12271. start: 'Date',
  12272. end: 'Date'
  12273. }
  12274. });
  12275. }
  12276. // set items
  12277. this.itemsData = newDataSet;
  12278. this.itemSet && this.itemSet.setItems(newDataSet);
  12279. };
  12280. /**
  12281. * Set groups
  12282. * @param {vis.DataSet | Array} groups
  12283. */
  12284. Timeline.prototype.setGroups = function (groups) {
  12285. // convert to type DataSet when needed
  12286. var newDataSet;
  12287. if (!groups) {
  12288. newDataSet = null;
  12289. } else if (groups instanceof DataSet || groups instanceof DataView) {
  12290. newDataSet = groups;
  12291. } else {
  12292. // turn an array into a dataset
  12293. newDataSet = new DataSet(groups);
  12294. }
  12295. this.groupsData = newDataSet;
  12296. this.itemSet.setGroups(newDataSet);
  12297. };
  12298. /**
  12299. * Set both items and groups in one go
  12300. * @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
  12301. */
  12302. Timeline.prototype.setData = function (data) {
  12303. if (data && data.groups) {
  12304. this.setGroups(data.groups);
  12305. }
  12306. if (data && data.items) {
  12307. this.setItems(data.items);
  12308. }
  12309. };
  12310. /**
  12311. * Set selected items by their id. Replaces the current selection
  12312. * Unknown id's are silently ignored.
  12313. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  12314. * selected. If ids is an empty array, all items will be
  12315. * unselected.
  12316. * @param {Object} [options] Available options:
  12317. * `focus: boolean`
  12318. * If true, focus will be set to the selected item(s)
  12319. * `animation: boolean | {duration: number, easingFunction: string}`
  12320. * If true (default), the range is animated
  12321. * smoothly to the new window. An object can be
  12322. * provided to specify duration and easing function.
  12323. * Default duration is 500 ms, and default easing
  12324. * function is 'easeInOutQuad'.
  12325. * Only applicable when option focus is true.
  12326. */
  12327. Timeline.prototype.setSelection = function (ids, options) {
  12328. this.itemSet && this.itemSet.setSelection(ids);
  12329. if (options && options.focus) {
  12330. this.focus(ids, options);
  12331. }
  12332. };
  12333. /**
  12334. * Get the selected items by their id
  12335. * @return {Array} ids The ids of the selected items
  12336. */
  12337. Timeline.prototype.getSelection = function () {
  12338. return this.itemSet && this.itemSet.getSelection() || [];
  12339. };
  12340. /**
  12341. * Adjust the visible window such that the selected item (or multiple items)
  12342. * are centered on screen.
  12343. * @param {String | String[]} id An item id or array with item ids
  12344. * @param {Object} [options] Available options:
  12345. * `animation: boolean | {duration: number, easingFunction: string}`
  12346. * If true (default), the range is animated
  12347. * smoothly to the new window. An object can be
  12348. * provided to specify duration and easing function.
  12349. * Default duration is 500 ms, and default easing
  12350. * function is 'easeInOutQuad'.
  12351. */
  12352. Timeline.prototype.focus = function (id, options) {
  12353. if (!this.itemsData || id == undefined) return;
  12354. var ids = Array.isArray(id) ? id : [id];
  12355. // get the specified item(s)
  12356. var itemsData = this.itemsData.getDataSet().get(ids, {
  12357. type: {
  12358. start: 'Date',
  12359. end: 'Date'
  12360. }
  12361. });
  12362. // calculate minimum start and maximum end of specified items
  12363. var start = null;
  12364. var end = null;
  12365. itemsData.forEach(function (itemData) {
  12366. var s = itemData.start.valueOf();
  12367. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  12368. if (start === null || s < start) {
  12369. start = s;
  12370. }
  12371. if (end === null || e > end) {
  12372. end = e;
  12373. }
  12374. });
  12375. if (start !== null && end !== null) {
  12376. // calculate the new middle and interval for the window
  12377. var middle = (start + end) / 2;
  12378. var interval = Math.max(this.range.end - this.range.start, (end - start) * 1.1);
  12379. var animation = options && options.animation !== undefined ? options.animation : true;
  12380. this.range.setRange(middle - interval / 2, middle + interval / 2, animation);
  12381. }
  12382. };
  12383. /**
  12384. * Set Timeline window such that it fits all items
  12385. * @param {Object} [options] Available options:
  12386. * `animation: boolean | {duration: number, easingFunction: string}`
  12387. * If true (default), the range is animated
  12388. * smoothly to the new window. An object can be
  12389. * provided to specify duration and easing function.
  12390. * Default duration is 500 ms, and default easing
  12391. * function is 'easeInOutQuad'.
  12392. */
  12393. Timeline.prototype.fit = function (options) {
  12394. var animation = options && options.animation !== undefined ? options.animation : true;
  12395. var range;
  12396. var dataset = this.itemsData && this.itemsData.getDataSet();
  12397. if (dataset.length === 1 && dataset.get()[0].end === undefined) {
  12398. // a single item -> don't fit, just show a range around the item from -4 to +3 days
  12399. range = this.getDataRange();
  12400. this.moveTo(range.min.valueOf(), { animation: animation });
  12401. } else {
  12402. // exactly fit the items (plus a small margin)
  12403. range = this.getItemRange();
  12404. this.range.setRange(range.min, range.max, animation);
  12405. }
  12406. };
  12407. /**
  12408. * Determine the range of the items, taking into account their actual width
  12409. * and a margin of 10 pixels on both sides.
  12410. * @return {{min: Date | null, max: Date | null}}
  12411. */
  12412. Timeline.prototype.getItemRange = function () {
  12413. var _this = this;
  12414. // get a rough approximation for the range based on the items start and end dates
  12415. var range = this.getDataRange();
  12416. var min = range.min !== null ? range.min.valueOf() : null;
  12417. var max = range.max !== null ? range.max.valueOf() : null;
  12418. var minItem = null;
  12419. var maxItem = null;
  12420. if (min != null && max != null) {
  12421. var interval;
  12422. var factor;
  12423. var lhs;
  12424. var rhs;
  12425. var delta;
  12426. (function () {
  12427. var getStart = function getStart(item) {
  12428. return util.convert(item.data.start, 'Date').valueOf();
  12429. };
  12430. var getEnd = function getEnd(item) {
  12431. var end = item.data.end != undefined ? item.data.end : item.data.start;
  12432. return util.convert(end, 'Date').valueOf();
  12433. };
  12434. // calculate the date of the left side and right side of the items given
  12435. interval = max - min; // ms
  12436. if (interval <= 0) {
  12437. interval = 10;
  12438. }
  12439. factor = interval / _this.props.center.width;
  12440. util.forEach(_this.itemSet.items, function (item) {
  12441. item.show();
  12442. item.repositionX();
  12443. var start = getStart(item);
  12444. var end = getEnd(item);
  12445. if (this.options.rtl) {
  12446. var startSide = start - (item.getWidthRight() + 10) * factor;
  12447. var endSide = end + (item.getWidthLeft() + 10) * factor;
  12448. } else {
  12449. var startSide = start - (item.getWidthLeft() + 10) * factor;
  12450. var endSide = end + (item.getWidthRight() + 10) * factor;
  12451. }
  12452. if (startSide < min) {
  12453. min = startSide;
  12454. minItem = item;
  12455. }
  12456. if (endSide > max) {
  12457. max = endSide;
  12458. maxItem = item;
  12459. }
  12460. }.bind(_this));
  12461. if (minItem && maxItem) {
  12462. lhs = minItem.getWidthLeft() + 10;
  12463. rhs = maxItem.getWidthRight() + 10;
  12464. delta = _this.props.center.width - lhs - rhs; // px
  12465. if (delta > 0) {
  12466. if (_this.options.rtl) {
  12467. min = getStart(minItem) - rhs * interval / delta; // ms
  12468. max = getEnd(maxItem) + lhs * interval / delta; // ms
  12469. } else {
  12470. min = getStart(minItem) - lhs * interval / delta; // ms
  12471. max = getEnd(maxItem) + rhs * interval / delta; // ms
  12472. }
  12473. }
  12474. }
  12475. })();
  12476. }
  12477. return {
  12478. min: min != null ? new Date(min) : null,
  12479. max: max != null ? new Date(max) : null
  12480. };
  12481. };
  12482. /**
  12483. * Calculate the data range of the items start and end dates
  12484. * @returns {{min: Date | null, max: Date | null}}
  12485. */
  12486. Timeline.prototype.getDataRange = function () {
  12487. var min = null;
  12488. var max = null;
  12489. var dataset = this.itemsData && this.itemsData.getDataSet();
  12490. if (dataset) {
  12491. dataset.forEach(function (item) {
  12492. var start = util.convert(item.start, 'Date').valueOf();
  12493. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  12494. if (min === null || start < min) {
  12495. min = start;
  12496. }
  12497. if (max === null || end > max) {
  12498. max = end;
  12499. }
  12500. });
  12501. }
  12502. return {
  12503. min: min != null ? new Date(min) : null,
  12504. max: max != null ? new Date(max) : null
  12505. };
  12506. };
  12507. /**
  12508. * Generate Timeline related information from an event
  12509. * @param {Event} event
  12510. * @return {Object} An object with related information, like on which area
  12511. * The event happened, whether clicked on an item, etc.
  12512. */
  12513. Timeline.prototype.getEventProperties = function (event) {
  12514. var clientX = event.center ? event.center.x : event.clientX;
  12515. var clientY = event.center ? event.center.y : event.clientY;
  12516. if (this.options.rtl) {
  12517. var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  12518. } else {
  12519. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  12520. }
  12521. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  12522. var item = this.itemSet.itemFromTarget(event);
  12523. var group = this.itemSet.groupFromTarget(event);
  12524. var customTime = CustomTime.customTimeFromTarget(event);
  12525. var snap = this.itemSet.options.snap || null;
  12526. var scale = this.body.util.getScale();
  12527. var step = this.body.util.getStep();
  12528. var time = this._toTime(x);
  12529. var snappedTime = snap ? snap(time, scale, step) : time;
  12530. var element = util.getTarget(event);
  12531. var what = null;
  12532. if (item != null) {
  12533. what = 'item';
  12534. } else if (customTime != null) {
  12535. what = 'custom-time';
  12536. } else if (util.hasParent(element, this.timeAxis.dom.foreground)) {
  12537. what = 'axis';
  12538. } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {
  12539. what = 'axis';
  12540. } else if (util.hasParent(element, this.itemSet.dom.labelSet)) {
  12541. what = 'group-label';
  12542. } else if (util.hasParent(element, this.currentTime.bar)) {
  12543. what = 'current-time';
  12544. } else if (util.hasParent(element, this.dom.center)) {
  12545. what = 'background';
  12546. }
  12547. return {
  12548. event: event,
  12549. item: item ? item.id : null,
  12550. group: group ? group.groupId : null,
  12551. what: what,
  12552. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  12553. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  12554. x: x,
  12555. y: y,
  12556. time: time,
  12557. snappedTime: snappedTime
  12558. };
  12559. };
  12560. module.exports = Timeline;
  12561. /***/ },
  12562. /* 26 */
  12563. /***/ function(module, exports, __webpack_require__) {
  12564. 'use strict';
  12565. Object.defineProperty(exports, "__esModule", {
  12566. value: true
  12567. });
  12568. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  12569. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  12570. var _ColorPicker = __webpack_require__(27);
  12571. var _ColorPicker2 = _interopRequireDefault(_ColorPicker);
  12572. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12573. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12574. var util = __webpack_require__(1);
  12575. /**
  12576. * The way this works is for all properties of this.possible options, you can supply the property name in any form to list the options.
  12577. * Boolean options are recognised as Boolean
  12578. * Number options should be written as array: [default value, min value, max value, stepsize]
  12579. * Colors should be written as array: ['color', '#ffffff']
  12580. * Strings with should be written as array: [option1, option2, option3, ..]
  12581. *
  12582. * The options are matched with their counterparts in each of the modules and the values used in the configuration are
  12583. *
  12584. * @param parentModule | the location where parentModule.setOptions() can be called
  12585. * @param defaultContainer | the default container of the module
  12586. * @param configureOptions | the fully configured and predefined options set found in allOptions.js
  12587. * @param pixelRatio | canvas pixel ratio
  12588. */
  12589. var Configurator = function () {
  12590. function Configurator(parentModule, defaultContainer, configureOptions) {
  12591. var pixelRatio = arguments.length <= 3 || arguments[3] === undefined ? 1 : arguments[3];
  12592. _classCallCheck(this, Configurator);
  12593. this.parent = parentModule;
  12594. this.changedOptions = [];
  12595. this.container = defaultContainer;
  12596. this.allowCreation = false;
  12597. this.options = {};
  12598. this.initialized = false;
  12599. this.popupCounter = 0;
  12600. this.defaultOptions = {
  12601. enabled: false,
  12602. filter: true,
  12603. container: undefined,
  12604. showButton: true
  12605. };
  12606. util.extend(this.options, this.defaultOptions);
  12607. this.configureOptions = configureOptions;
  12608. this.moduleOptions = {};
  12609. this.domElements = [];
  12610. this.popupDiv = {};
  12611. this.popupLimit = 5;
  12612. this.popupHistory = {};
  12613. this.colorPicker = new _ColorPicker2.default(pixelRatio);
  12614. this.wrapper = undefined;
  12615. }
  12616. /**
  12617. * refresh all options.
  12618. * Because all modules parse their options by themselves, we just use their options. We copy them here.
  12619. *
  12620. * @param options
  12621. */
  12622. _createClass(Configurator, [{
  12623. key: 'setOptions',
  12624. value: function setOptions(options) {
  12625. if (options !== undefined) {
  12626. // reset the popup history because the indices may have been changed.
  12627. this.popupHistory = {};
  12628. this._removePopup();
  12629. var enabled = true;
  12630. if (typeof options === 'string') {
  12631. this.options.filter = options;
  12632. } else if (options instanceof Array) {
  12633. this.options.filter = options.join();
  12634. } else if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
  12635. if (options.container !== undefined) {
  12636. this.options.container = options.container;
  12637. }
  12638. if (options.filter !== undefined) {
  12639. this.options.filter = options.filter;
  12640. }
  12641. if (options.showButton !== undefined) {
  12642. this.options.showButton = options.showButton;
  12643. }
  12644. if (options.enabled !== undefined) {
  12645. enabled = options.enabled;
  12646. }
  12647. } else if (typeof options === 'boolean') {
  12648. this.options.filter = true;
  12649. enabled = options;
  12650. } else if (typeof options === 'function') {
  12651. this.options.filter = options;
  12652. enabled = true;
  12653. }
  12654. if (this.options.filter === false) {
  12655. enabled = false;
  12656. }
  12657. this.options.enabled = enabled;
  12658. }
  12659. this._clean();
  12660. }
  12661. }, {
  12662. key: 'setModuleOptions',
  12663. value: function setModuleOptions(moduleOptions) {
  12664. this.moduleOptions = moduleOptions;
  12665. if (this.options.enabled === true) {
  12666. this._clean();
  12667. if (this.options.container !== undefined) {
  12668. this.container = this.options.container;
  12669. }
  12670. this._create();
  12671. }
  12672. }
  12673. /**
  12674. * Create all DOM elements
  12675. * @private
  12676. */
  12677. }, {
  12678. key: '_create',
  12679. value: function _create() {
  12680. var _this = this;
  12681. this._clean();
  12682. this.changedOptions = [];
  12683. var filter = this.options.filter;
  12684. var counter = 0;
  12685. var show = false;
  12686. for (var option in this.configureOptions) {
  12687. if (this.configureOptions.hasOwnProperty(option)) {
  12688. this.allowCreation = false;
  12689. show = false;
  12690. if (typeof filter === 'function') {
  12691. show = filter(option, []);
  12692. show = show || this._handleObject(this.configureOptions[option], [option], true);
  12693. } else if (filter === true || filter.indexOf(option) !== -1) {
  12694. show = true;
  12695. }
  12696. if (show !== false) {
  12697. this.allowCreation = true;
  12698. // linebreak between categories
  12699. if (counter > 0) {
  12700. this._makeItem([]);
  12701. }
  12702. // a header for the category
  12703. this._makeHeader(option);
  12704. // get the sub options
  12705. this._handleObject(this.configureOptions[option], [option]);
  12706. }
  12707. counter++;
  12708. }
  12709. }
  12710. if (this.options.showButton === true) {
  12711. (function () {
  12712. var generateButton = document.createElement('div');
  12713. generateButton.className = 'vis-configuration vis-config-button';
  12714. generateButton.innerHTML = 'generate options';
  12715. generateButton.onclick = function () {
  12716. _this._printOptions();
  12717. };
  12718. generateButton.onmouseover = function () {
  12719. generateButton.className = 'vis-configuration vis-config-button hover';
  12720. };
  12721. generateButton.onmouseout = function () {
  12722. generateButton.className = 'vis-configuration vis-config-button';
  12723. };
  12724. _this.optionsContainer = document.createElement('div');
  12725. _this.optionsContainer.className = 'vis-configuration vis-config-option-container';
  12726. _this.domElements.push(_this.optionsContainer);
  12727. _this.domElements.push(generateButton);
  12728. })();
  12729. }
  12730. this._push();
  12731. //~ this.colorPicker.insertTo(this.container);
  12732. }
  12733. /**
  12734. * draw all DOM elements on the screen
  12735. * @private
  12736. */
  12737. }, {
  12738. key: '_push',
  12739. value: function _push() {
  12740. this.wrapper = document.createElement('div');
  12741. this.wrapper.className = 'vis-configuration-wrapper';
  12742. this.container.appendChild(this.wrapper);
  12743. for (var i = 0; i < this.domElements.length; i++) {
  12744. this.wrapper.appendChild(this.domElements[i]);
  12745. }
  12746. this._showPopupIfNeeded();
  12747. }
  12748. /**
  12749. * delete all DOM elements
  12750. * @private
  12751. */
  12752. }, {
  12753. key: '_clean',
  12754. value: function _clean() {
  12755. for (var i = 0; i < this.domElements.length; i++) {
  12756. this.wrapper.removeChild(this.domElements[i]);
  12757. }
  12758. if (this.wrapper !== undefined) {
  12759. this.container.removeChild(this.wrapper);
  12760. this.wrapper = undefined;
  12761. }
  12762. this.domElements = [];
  12763. this._removePopup();
  12764. }
  12765. /**
  12766. * get the value from the actualOptions if it exists
  12767. * @param {array} path | where to look for the actual option
  12768. * @returns {*}
  12769. * @private
  12770. */
  12771. }, {
  12772. key: '_getValue',
  12773. value: function _getValue(path) {
  12774. var base = this.moduleOptions;
  12775. for (var i = 0; i < path.length; i++) {
  12776. if (base[path[i]] !== undefined) {
  12777. base = base[path[i]];
  12778. } else {
  12779. base = undefined;
  12780. break;
  12781. }
  12782. }
  12783. return base;
  12784. }
  12785. /**
  12786. * all option elements are wrapped in an item
  12787. * @param path
  12788. * @param domElements
  12789. * @private
  12790. */
  12791. }, {
  12792. key: '_makeItem',
  12793. value: function _makeItem(path) {
  12794. var _arguments = arguments,
  12795. _this2 = this;
  12796. if (this.allowCreation === true) {
  12797. var _len, domElements, _key;
  12798. var _ret2 = function () {
  12799. var item = document.createElement('div');
  12800. item.className = 'vis-configuration vis-config-item vis-config-s' + path.length;
  12801. for (_len = _arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12802. domElements[_key - 1] = _arguments[_key];
  12803. }
  12804. domElements.forEach(function (element) {
  12805. item.appendChild(element);
  12806. });
  12807. _this2.domElements.push(item);
  12808. return {
  12809. v: _this2.domElements.length
  12810. };
  12811. }();
  12812. if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
  12813. }
  12814. return 0;
  12815. }
  12816. /**
  12817. * header for major subjects
  12818. * @param name
  12819. * @private
  12820. */
  12821. }, {
  12822. key: '_makeHeader',
  12823. value: function _makeHeader(name) {
  12824. var div = document.createElement('div');
  12825. div.className = 'vis-configuration vis-config-header';
  12826. div.innerHTML = name;
  12827. this._makeItem([], div);
  12828. }
  12829. /**
  12830. * make a label, if it is an object label, it gets different styling.
  12831. * @param name
  12832. * @param path
  12833. * @param objectLabel
  12834. * @returns {HTMLElement}
  12835. * @private
  12836. */
  12837. }, {
  12838. key: '_makeLabel',
  12839. value: function _makeLabel(name, path) {
  12840. var objectLabel = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  12841. var div = document.createElement('div');
  12842. div.className = 'vis-configuration vis-config-label vis-config-s' + path.length;
  12843. if (objectLabel === true) {
  12844. div.innerHTML = '<i><b>' + name + ':</b></i>';
  12845. } else {
  12846. div.innerHTML = name + ':';
  12847. }
  12848. return div;
  12849. }
  12850. /**
  12851. * make a dropdown list for multiple possible string optoins
  12852. * @param arr
  12853. * @param value
  12854. * @param path
  12855. * @private
  12856. */
  12857. }, {
  12858. key: '_makeDropdown',
  12859. value: function _makeDropdown(arr, value, path) {
  12860. var select = document.createElement('select');
  12861. select.className = 'vis-configuration vis-config-select';
  12862. var selectedValue = 0;
  12863. if (value !== undefined) {
  12864. if (arr.indexOf(value) !== -1) {
  12865. selectedValue = arr.indexOf(value);
  12866. }
  12867. }
  12868. for (var i = 0; i < arr.length; i++) {
  12869. var option = document.createElement('option');
  12870. option.value = arr[i];
  12871. if (i === selectedValue) {
  12872. option.selected = 'selected';
  12873. }
  12874. option.innerHTML = arr[i];
  12875. select.appendChild(option);
  12876. }
  12877. var me = this;
  12878. select.onchange = function () {
  12879. me._update(this.value, path);
  12880. };
  12881. var label = this._makeLabel(path[path.length - 1], path);
  12882. this._makeItem(path, label, select);
  12883. }
  12884. /**
  12885. * make a range object for numeric options
  12886. * @param arr
  12887. * @param value
  12888. * @param path
  12889. * @private
  12890. */
  12891. }, {
  12892. key: '_makeRange',
  12893. value: function _makeRange(arr, value, path) {
  12894. var defaultValue = arr[0];
  12895. var min = arr[1];
  12896. var max = arr[2];
  12897. var step = arr[3];
  12898. var range = document.createElement('input');
  12899. range.className = 'vis-configuration vis-config-range';
  12900. try {
  12901. range.type = 'range'; // not supported on IE9
  12902. range.min = min;
  12903. range.max = max;
  12904. } catch (err) {}
  12905. range.step = step;
  12906. // set up the popup settings in case they are needed.
  12907. var popupString = '';
  12908. var popupValue = 0;
  12909. if (value !== undefined) {
  12910. var factor = 1.20;
  12911. if (value < 0 && value * factor < min) {
  12912. range.min = Math.ceil(value * factor);
  12913. popupValue = range.min;
  12914. popupString = 'range increased';
  12915. } else if (value / factor < min) {
  12916. range.min = Math.ceil(value / factor);
  12917. popupValue = range.min;
  12918. popupString = 'range increased';
  12919. }
  12920. if (value * factor > max && max !== 1) {
  12921. range.max = Math.ceil(value * factor);
  12922. popupValue = range.max;
  12923. popupString = 'range increased';
  12924. }
  12925. range.value = value;
  12926. } else {
  12927. range.value = defaultValue;
  12928. }
  12929. var input = document.createElement('input');
  12930. input.className = 'vis-configuration vis-config-rangeinput';
  12931. input.value = range.value;
  12932. var me = this;
  12933. range.onchange = function () {
  12934. input.value = this.value;me._update(Number(this.value), path);
  12935. };
  12936. range.oninput = function () {
  12937. input.value = this.value;
  12938. };
  12939. var label = this._makeLabel(path[path.length - 1], path);
  12940. var itemIndex = this._makeItem(path, label, range, input);
  12941. // if a popup is needed AND it has not been shown for this value, show it.
  12942. if (popupString !== '' && this.popupHistory[itemIndex] !== popupValue) {
  12943. this.popupHistory[itemIndex] = popupValue;
  12944. this._setupPopup(popupString, itemIndex);
  12945. }
  12946. }
  12947. /**
  12948. * prepare the popup
  12949. * @param string
  12950. * @param index
  12951. * @private
  12952. */
  12953. }, {
  12954. key: '_setupPopup',
  12955. value: function _setupPopup(string, index) {
  12956. var _this3 = this;
  12957. if (this.initialized === true && this.allowCreation === true && this.popupCounter < this.popupLimit) {
  12958. var div = document.createElement("div");
  12959. div.id = "vis-configuration-popup";
  12960. div.className = "vis-configuration-popup";
  12961. div.innerHTML = string;
  12962. div.onclick = function () {
  12963. _this3._removePopup();
  12964. };
  12965. this.popupCounter += 1;
  12966. this.popupDiv = { html: div, index: index };
  12967. }
  12968. }
  12969. /**
  12970. * remove the popup from the dom
  12971. * @private
  12972. */
  12973. }, {
  12974. key: '_removePopup',
  12975. value: function _removePopup() {
  12976. if (this.popupDiv.html !== undefined) {
  12977. this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);
  12978. clearTimeout(this.popupDiv.hideTimeout);
  12979. clearTimeout(this.popupDiv.deleteTimeout);
  12980. this.popupDiv = {};
  12981. }
  12982. }
  12983. /**
  12984. * Show the popup if it is needed.
  12985. * @private
  12986. */
  12987. }, {
  12988. key: '_showPopupIfNeeded',
  12989. value: function _showPopupIfNeeded() {
  12990. var _this4 = this;
  12991. if (this.popupDiv.html !== undefined) {
  12992. var correspondingElement = this.domElements[this.popupDiv.index];
  12993. var rect = correspondingElement.getBoundingClientRect();
  12994. this.popupDiv.html.style.left = rect.left + "px";
  12995. this.popupDiv.html.style.top = rect.top - 30 + "px"; // 30 is the height;
  12996. document.body.appendChild(this.popupDiv.html);
  12997. this.popupDiv.hideTimeout = setTimeout(function () {
  12998. _this4.popupDiv.html.style.opacity = 0;
  12999. }, 1500);
  13000. this.popupDiv.deleteTimeout = setTimeout(function () {
  13001. _this4._removePopup();
  13002. }, 1800);
  13003. }
  13004. }
  13005. /**
  13006. * make a checkbox for boolean options.
  13007. * @param defaultValue
  13008. * @param value
  13009. * @param path
  13010. * @private
  13011. */
  13012. }, {
  13013. key: '_makeCheckbox',
  13014. value: function _makeCheckbox(defaultValue, value, path) {
  13015. var checkbox = document.createElement('input');
  13016. checkbox.type = 'checkbox';
  13017. checkbox.className = 'vis-configuration vis-config-checkbox';
  13018. checkbox.checked = defaultValue;
  13019. if (value !== undefined) {
  13020. checkbox.checked = value;
  13021. if (value !== defaultValue) {
  13022. if ((typeof defaultValue === 'undefined' ? 'undefined' : _typeof(defaultValue)) === 'object') {
  13023. if (value !== defaultValue.enabled) {
  13024. this.changedOptions.push({ path: path, value: value });
  13025. }
  13026. } else {
  13027. this.changedOptions.push({ path: path, value: value });
  13028. }
  13029. }
  13030. }
  13031. var me = this;
  13032. checkbox.onchange = function () {
  13033. me._update(this.checked, path);
  13034. };
  13035. var label = this._makeLabel(path[path.length - 1], path);
  13036. this._makeItem(path, label, checkbox);
  13037. }
  13038. /**
  13039. * make a text input field for string options.
  13040. * @param defaultValue
  13041. * @param value
  13042. * @param path
  13043. * @private
  13044. */
  13045. }, {
  13046. key: '_makeTextInput',
  13047. value: function _makeTextInput(defaultValue, value, path) {
  13048. var checkbox = document.createElement('input');
  13049. checkbox.type = 'text';
  13050. checkbox.className = 'vis-configuration vis-config-text';
  13051. checkbox.value = value;
  13052. if (value !== defaultValue) {
  13053. this.changedOptions.push({ path: path, value: value });
  13054. }
  13055. var me = this;
  13056. checkbox.onchange = function () {
  13057. me._update(this.value, path);
  13058. };
  13059. var label = this._makeLabel(path[path.length - 1], path);
  13060. this._makeItem(path, label, checkbox);
  13061. }
  13062. /**
  13063. * make a color field with a color picker for color fields
  13064. * @param arr
  13065. * @param value
  13066. * @param path
  13067. * @private
  13068. */
  13069. }, {
  13070. key: '_makeColorField',
  13071. value: function _makeColorField(arr, value, path) {
  13072. var _this5 = this;
  13073. var defaultColor = arr[1];
  13074. var div = document.createElement('div');
  13075. value = value === undefined ? defaultColor : value;
  13076. if (value !== 'none') {
  13077. div.className = 'vis-configuration vis-config-colorBlock';
  13078. div.style.backgroundColor = value;
  13079. } else {
  13080. div.className = 'vis-configuration vis-config-colorBlock none';
  13081. }
  13082. value = value === undefined ? defaultColor : value;
  13083. div.onclick = function () {
  13084. _this5._showColorPicker(value, div, path);
  13085. };
  13086. var label = this._makeLabel(path[path.length - 1], path);
  13087. this._makeItem(path, label, div);
  13088. }
  13089. /**
  13090. * used by the color buttons to call the color picker.
  13091. * @param event
  13092. * @param value
  13093. * @param div
  13094. * @param path
  13095. * @private
  13096. */
  13097. }, {
  13098. key: '_showColorPicker',
  13099. value: function _showColorPicker(value, div, path) {
  13100. var _this6 = this;
  13101. // clear the callback from this div
  13102. div.onclick = function () {};
  13103. this.colorPicker.insertTo(div);
  13104. this.colorPicker.show();
  13105. this.colorPicker.setColor(value);
  13106. this.colorPicker.setUpdateCallback(function (color) {
  13107. var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')';
  13108. div.style.backgroundColor = colorString;
  13109. _this6._update(colorString, path);
  13110. });
  13111. // on close of the colorpicker, restore the callback.
  13112. this.colorPicker.setCloseCallback(function () {
  13113. div.onclick = function () {
  13114. _this6._showColorPicker(value, div, path);
  13115. };
  13116. });
  13117. }
  13118. /**
  13119. * parse an object and draw the correct items
  13120. * @param obj
  13121. * @param path
  13122. * @private
  13123. */
  13124. }, {
  13125. key: '_handleObject',
  13126. value: function _handleObject(obj) {
  13127. var path = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
  13128. var checkOnly = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  13129. var show = false;
  13130. var filter = this.options.filter;
  13131. var visibleInSet = false;
  13132. for (var subObj in obj) {
  13133. if (obj.hasOwnProperty(subObj)) {
  13134. show = true;
  13135. var item = obj[subObj];
  13136. var newPath = util.copyAndExtendArray(path, subObj);
  13137. if (typeof filter === 'function') {
  13138. show = filter(subObj, path);
  13139. // if needed we must go deeper into the object.
  13140. if (show === false) {
  13141. if (!(item instanceof Array) && typeof item !== 'string' && typeof item !== 'boolean' && item instanceof Object) {
  13142. this.allowCreation = false;
  13143. show = this._handleObject(item, newPath, true);
  13144. this.allowCreation = checkOnly === false;
  13145. }
  13146. }
  13147. }
  13148. if (show !== false) {
  13149. visibleInSet = true;
  13150. var value = this._getValue(newPath);
  13151. if (item instanceof Array) {
  13152. this._handleArray(item, value, newPath);
  13153. } else if (typeof item === 'string') {
  13154. this._makeTextInput(item, value, newPath);
  13155. } else if (typeof item === 'boolean') {
  13156. this._makeCheckbox(item, value, newPath);
  13157. } else if (item instanceof Object) {
  13158. // collapse the physics options that are not enabled
  13159. var draw = true;
  13160. if (path.indexOf('physics') !== -1) {
  13161. if (this.moduleOptions.physics.solver !== subObj) {
  13162. draw = false;
  13163. }
  13164. }
  13165. if (draw === true) {
  13166. // initially collapse options with an disabled enabled option.
  13167. if (item.enabled !== undefined) {
  13168. var enabledPath = util.copyAndExtendArray(newPath, 'enabled');
  13169. var enabledValue = this._getValue(enabledPath);
  13170. if (enabledValue === true) {
  13171. var label = this._makeLabel(subObj, newPath, true);
  13172. this._makeItem(newPath, label);
  13173. visibleInSet = this._handleObject(item, newPath) || visibleInSet;
  13174. } else {
  13175. this._makeCheckbox(item, enabledValue, newPath);
  13176. }
  13177. } else {
  13178. var _label = this._makeLabel(subObj, newPath, true);
  13179. this._makeItem(newPath, _label);
  13180. visibleInSet = this._handleObject(item, newPath) || visibleInSet;
  13181. }
  13182. }
  13183. } else {
  13184. console.error('dont know how to handle', item, subObj, newPath);
  13185. }
  13186. }
  13187. }
  13188. }
  13189. return visibleInSet;
  13190. }
  13191. /**
  13192. * handle the array type of option
  13193. * @param optionName
  13194. * @param arr
  13195. * @param value
  13196. * @param path
  13197. * @private
  13198. */
  13199. }, {
  13200. key: '_handleArray',
  13201. value: function _handleArray(arr, value, path) {
  13202. if (typeof arr[0] === 'string' && arr[0] === 'color') {
  13203. this._makeColorField(arr, value, path);
  13204. if (arr[1] !== value) {
  13205. this.changedOptions.push({ path: path, value: value });
  13206. }
  13207. } else if (typeof arr[0] === 'string') {
  13208. this._makeDropdown(arr, value, path);
  13209. if (arr[0] !== value) {
  13210. this.changedOptions.push({ path: path, value: value });
  13211. }
  13212. } else if (typeof arr[0] === 'number') {
  13213. this._makeRange(arr, value, path);
  13214. if (arr[0] !== value) {
  13215. this.changedOptions.push({ path: path, value: Number(value) });
  13216. }
  13217. }
  13218. }
  13219. /**
  13220. * called to update the network with the new settings.
  13221. * @param value
  13222. * @param path
  13223. * @private
  13224. */
  13225. }, {
  13226. key: '_update',
  13227. value: function _update(value, path) {
  13228. var options = this._constructOptions(value, path);
  13229. if (this.parent.body && this.parent.body.emitter && this.parent.body.emitter.emit) {
  13230. this.parent.body.emitter.emit("configChange", options);
  13231. }
  13232. this.initialized = true;
  13233. this.parent.setOptions(options);
  13234. }
  13235. }, {
  13236. key: '_constructOptions',
  13237. value: function _constructOptions(value, path) {
  13238. var optionsObj = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  13239. var pointer = optionsObj;
  13240. // when dropdown boxes can be string or boolean, we typecast it into correct types
  13241. value = value === 'true' ? true : value;
  13242. value = value === 'false' ? false : value;
  13243. for (var i = 0; i < path.length; i++) {
  13244. if (path[i] !== 'global') {
  13245. if (pointer[path[i]] === undefined) {
  13246. pointer[path[i]] = {};
  13247. }
  13248. if (i !== path.length - 1) {
  13249. pointer = pointer[path[i]];
  13250. } else {
  13251. pointer[path[i]] = value;
  13252. }
  13253. }
  13254. }
  13255. return optionsObj;
  13256. }
  13257. }, {
  13258. key: '_printOptions',
  13259. value: function _printOptions() {
  13260. var options = this.getOptions();
  13261. this.optionsContainer.innerHTML = '<pre>var options = ' + JSON.stringify(options, null, 2) + '</pre>';
  13262. }
  13263. }, {
  13264. key: 'getOptions',
  13265. value: function getOptions() {
  13266. var options = {};
  13267. for (var i = 0; i < this.changedOptions.length; i++) {
  13268. this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options);
  13269. }
  13270. return options;
  13271. }
  13272. }]);
  13273. return Configurator;
  13274. }();
  13275. exports.default = Configurator;
  13276. /***/ },
  13277. /* 27 */
  13278. /***/ function(module, exports, __webpack_require__) {
  13279. 'use strict';
  13280. Object.defineProperty(exports, "__esModule", {
  13281. value: true
  13282. });
  13283. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13284. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13285. var Hammer = __webpack_require__(20);
  13286. var hammerUtil = __webpack_require__(28);
  13287. var util = __webpack_require__(1);
  13288. var ColorPicker = function () {
  13289. function ColorPicker() {
  13290. var pixelRatio = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
  13291. _classCallCheck(this, ColorPicker);
  13292. this.pixelRatio = pixelRatio;
  13293. this.generated = false;
  13294. this.centerCoordinates = { x: 289 / 2, y: 289 / 2 };
  13295. this.r = 289 * 0.49;
  13296. this.color = { r: 255, g: 255, b: 255, a: 1.0 };
  13297. this.hueCircle = undefined;
  13298. this.initialColor = { r: 255, g: 255, b: 255, a: 1.0 };
  13299. this.previousColor = undefined;
  13300. this.applied = false;
  13301. // bound by
  13302. this.updateCallback = function () {};
  13303. this.closeCallback = function () {};
  13304. // create all DOM elements
  13305. this._create();
  13306. }
  13307. /**
  13308. * this inserts the colorPicker into a div from the DOM
  13309. * @param container
  13310. */
  13311. _createClass(ColorPicker, [{
  13312. key: 'insertTo',
  13313. value: function insertTo(container) {
  13314. if (this.hammer !== undefined) {
  13315. this.hammer.destroy();
  13316. this.hammer = undefined;
  13317. }
  13318. this.container = container;
  13319. this.container.appendChild(this.frame);
  13320. this._bindHammer();
  13321. this._setSize();
  13322. }
  13323. /**
  13324. * the callback is executed on apply and save. Bind it to the application
  13325. * @param callback
  13326. */
  13327. }, {
  13328. key: 'setUpdateCallback',
  13329. value: function setUpdateCallback(callback) {
  13330. if (typeof callback === 'function') {
  13331. this.updateCallback = callback;
  13332. } else {
  13333. throw new Error("Function attempted to set as colorPicker update callback is not a function.");
  13334. }
  13335. }
  13336. /**
  13337. * the callback is executed on apply and save. Bind it to the application
  13338. * @param callback
  13339. */
  13340. }, {
  13341. key: 'setCloseCallback',
  13342. value: function setCloseCallback(callback) {
  13343. if (typeof callback === 'function') {
  13344. this.closeCallback = callback;
  13345. } else {
  13346. throw new Error("Function attempted to set as colorPicker closing callback is not a function.");
  13347. }
  13348. }
  13349. }, {
  13350. key: '_isColorString',
  13351. value: function _isColorString(color) {
  13352. var htmlColors = { black: '#000000', navy: '#000080', darkblue: '#00008B', mediumblue: '#0000CD', blue: '#0000FF', darkgreen: '#006400', green: '#008000', teal: '#008080', darkcyan: '#008B8B', deepskyblue: '#00BFFF', darkturquoise: '#00CED1', mediumspringgreen: '#00FA9A', lime: '#00FF00', springgreen: '#00FF7F', aqua: '#00FFFF', cyan: '#00FFFF', midnightblue: '#191970', dodgerblue: '#1E90FF', lightseagreen: '#20B2AA', forestgreen: '#228B22', seagreen: '#2E8B57', darkslategray: '#2F4F4F', limegreen: '#32CD32', mediumseagreen: '#3CB371', turquoise: '#40E0D0', royalblue: '#4169E1', steelblue: '#4682B4', darkslateblue: '#483D8B', mediumturquoise: '#48D1CC', indigo: '#4B0082', darkolivegreen: '#556B2F', cadetblue: '#5F9EA0', cornflowerblue: '#6495ED', mediumaquamarine: '#66CDAA', dimgray: '#696969', slateblue: '#6A5ACD', olivedrab: '#6B8E23', slategray: '#708090', lightslategray: '#778899', mediumslateblue: '#7B68EE', lawngreen: '#7CFC00', chartreuse: '#7FFF00', aquamarine: '#7FFFD4', maroon: '#800000', purple: '#800080', olive: '#808000', gray: '#808080', skyblue: '#87CEEB', lightskyblue: '#87CEFA', blueviolet: '#8A2BE2', darkred: '#8B0000', darkmagenta: '#8B008B', saddlebrown: '#8B4513', darkseagreen: '#8FBC8F', lightgreen: '#90EE90', mediumpurple: '#9370D8', darkviolet: '#9400D3', palegreen: '#98FB98', darkorchid: '#9932CC', yellowgreen: '#9ACD32', sienna: '#A0522D', brown: '#A52A2A', darkgray: '#A9A9A9', lightblue: '#ADD8E6', greenyellow: '#ADFF2F', paleturquoise: '#AFEEEE', lightsteelblue: '#B0C4DE', powderblue: '#B0E0E6', firebrick: '#B22222', darkgoldenrod: '#B8860B', mediumorchid: '#BA55D3', rosybrown: '#BC8F8F', darkkhaki: '#BDB76B', silver: '#C0C0C0', mediumvioletred: '#C71585', indianred: '#CD5C5C', peru: '#CD853F', chocolate: '#D2691E', tan: '#D2B48C', lightgrey: '#D3D3D3', palevioletred: '#D87093', thistle: '#D8BFD8', orchid: '#DA70D6', goldenrod: '#DAA520', crimson: '#DC143C', gainsboro: '#DCDCDC', plum: '#DDA0DD', burlywood: '#DEB887', lightcyan: '#E0FFFF', lavender: '#E6E6FA', darksalmon: '#E9967A', violet: '#EE82EE', palegoldenrod: '#EEE8AA', lightcoral: '#F08080', khaki: '#F0E68C', aliceblue: '#F0F8FF', honeydew: '#F0FFF0', azure: '#F0FFFF', sandybrown: '#F4A460', wheat: '#F5DEB3', beige: '#F5F5DC', whitesmoke: '#F5F5F5', mintcream: '#F5FFFA', ghostwhite: '#F8F8FF', salmon: '#FA8072', antiquewhite: '#FAEBD7', linen: '#FAF0E6', lightgoldenrodyellow: '#FAFAD2', oldlace: '#FDF5E6', red: '#FF0000', fuchsia: '#FF00FF', magenta: '#FF00FF', deeppink: '#FF1493', orangered: '#FF4500', tomato: '#FF6347', hotpink: '#FF69B4', coral: '#FF7F50', darkorange: '#FF8C00', lightsalmon: '#FFA07A', orange: '#FFA500', lightpink: '#FFB6C1', pink: '#FFC0CB', gold: '#FFD700', peachpuff: '#FFDAB9', navajowhite: '#FFDEAD', moccasin: '#FFE4B5', bisque: '#FFE4C4', mistyrose: '#FFE4E1', blanchedalmond: '#FFEBCD', papayawhip: '#FFEFD5', lavenderblush: '#FFF0F5', seashell: '#FFF5EE', cornsilk: '#FFF8DC', lemonchiffon: '#FFFACD', floralwhite: '#FFFAF0', snow: '#FFFAFA', yellow: '#FFFF00', lightyellow: '#FFFFE0', ivory: '#FFFFF0', white: '#FFFFFF' };
  13353. if (typeof color === 'string') {
  13354. return htmlColors[color];
  13355. }
  13356. }
  13357. /**
  13358. * Set the color of the colorPicker
  13359. * Supported formats:
  13360. * 'red' --> HTML color string
  13361. * '#ffffff' --> hex string
  13362. * 'rbg(255,255,255)' --> rgb string
  13363. * 'rgba(255,255,255,1.0)' --> rgba string
  13364. * {r:255,g:255,b:255} --> rgb object
  13365. * {r:255,g:255,b:255,a:1.0} --> rgba object
  13366. * @param color
  13367. * @param setInitial
  13368. */
  13369. }, {
  13370. key: 'setColor',
  13371. value: function setColor(color) {
  13372. var setInitial = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  13373. if (color === 'none') {
  13374. return;
  13375. }
  13376. var rgba = void 0;
  13377. // if a html color shorthand is used, convert to hex
  13378. var htmlColor = this._isColorString(color);
  13379. if (htmlColor !== undefined) {
  13380. color = htmlColor;
  13381. }
  13382. // check format
  13383. if (util.isString(color) === true) {
  13384. if (util.isValidRGB(color) === true) {
  13385. var rgbaArray = color.substr(4).substr(0, color.length - 5).split(',');
  13386. rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1.0 };
  13387. } else if (util.isValidRGBA(color) === true) {
  13388. var _rgbaArray = color.substr(5).substr(0, color.length - 6).split(',');
  13389. rgba = { r: _rgbaArray[0], g: _rgbaArray[1], b: _rgbaArray[2], a: _rgbaArray[3] };
  13390. } else if (util.isValidHex(color) === true) {
  13391. var rgbObj = util.hexToRGB(color);
  13392. rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1.0 };
  13393. }
  13394. } else {
  13395. if (color instanceof Object) {
  13396. if (color.r !== undefined && color.g !== undefined && color.b !== undefined) {
  13397. var alpha = color.a !== undefined ? color.a : '1.0';
  13398. rgba = { r: color.r, g: color.g, b: color.b, a: alpha };
  13399. }
  13400. }
  13401. }
  13402. // set color
  13403. if (rgba === undefined) {
  13404. throw new Error("Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: " + JSON.stringify(color));
  13405. } else {
  13406. this._setColor(rgba, setInitial);
  13407. }
  13408. }
  13409. /**
  13410. * this shows the color picker.
  13411. * The hue circle is constructed once and stored.
  13412. */
  13413. }, {
  13414. key: 'show',
  13415. value: function show() {
  13416. if (this.closeCallback !== undefined) {
  13417. this.closeCallback();
  13418. this.closeCallback = undefined;
  13419. }
  13420. this.applied = false;
  13421. this.frame.style.display = 'block';
  13422. this._generateHueCircle();
  13423. }
  13424. // ------------------------------------------ PRIVATE ----------------------------- //
  13425. /**
  13426. * Hide the picker. Is called by the cancel button.
  13427. * Optional boolean to store the previous color for easy access later on.
  13428. * @param storePrevious
  13429. * @private
  13430. */
  13431. }, {
  13432. key: '_hide',
  13433. value: function _hide() {
  13434. var _this = this;
  13435. var storePrevious = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
  13436. // store the previous color for next time;
  13437. if (storePrevious === true) {
  13438. this.previousColor = util.extend({}, this.color);
  13439. }
  13440. if (this.applied === true) {
  13441. this.updateCallback(this.initialColor);
  13442. }
  13443. this.frame.style.display = 'none';
  13444. // call the closing callback, restoring the onclick method.
  13445. // this is in a setTimeout because it will trigger the show again before the click is done.
  13446. setTimeout(function () {
  13447. if (_this.closeCallback !== undefined) {
  13448. _this.closeCallback();
  13449. _this.closeCallback = undefined;
  13450. }
  13451. }, 0);
  13452. }
  13453. /**
  13454. * bound to the save button. Saves and hides.
  13455. * @private
  13456. */
  13457. }, {
  13458. key: '_save',
  13459. value: function _save() {
  13460. this.updateCallback(this.color);
  13461. this.applied = false;
  13462. this._hide();
  13463. }
  13464. /**
  13465. * Bound to apply button. Saves but does not close. Is undone by the cancel button.
  13466. * @private
  13467. */
  13468. }, {
  13469. key: '_apply',
  13470. value: function _apply() {
  13471. this.applied = true;
  13472. this.updateCallback(this.color);
  13473. this._updatePicker(this.color);
  13474. }
  13475. /**
  13476. * load the color from the previous session.
  13477. * @private
  13478. */
  13479. }, {
  13480. key: '_loadLast',
  13481. value: function _loadLast() {
  13482. if (this.previousColor !== undefined) {
  13483. this.setColor(this.previousColor, false);
  13484. } else {
  13485. alert("There is no last color to load...");
  13486. }
  13487. }
  13488. /**
  13489. * set the color, place the picker
  13490. * @param rgba
  13491. * @param setInitial
  13492. * @private
  13493. */
  13494. }, {
  13495. key: '_setColor',
  13496. value: function _setColor(rgba) {
  13497. var setInitial = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  13498. // store the initial color
  13499. if (setInitial === true) {
  13500. this.initialColor = util.extend({}, rgba);
  13501. }
  13502. this.color = rgba;
  13503. var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  13504. var angleConvert = 2 * Math.PI;
  13505. var radius = this.r * hsv.s;
  13506. var x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h);
  13507. var y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h);
  13508. this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  13509. this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  13510. this._updatePicker(rgba);
  13511. }
  13512. /**
  13513. * bound to opacity control
  13514. * @param value
  13515. * @private
  13516. */
  13517. }, {
  13518. key: '_setOpacity',
  13519. value: function _setOpacity(value) {
  13520. this.color.a = value / 100;
  13521. this._updatePicker(this.color);
  13522. }
  13523. /**
  13524. * bound to brightness control
  13525. * @param value
  13526. * @private
  13527. */
  13528. }, {
  13529. key: '_setBrightness',
  13530. value: function _setBrightness(value) {
  13531. var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  13532. hsv.v = value / 100;
  13533. var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  13534. rgba['a'] = this.color.a;
  13535. this.color = rgba;
  13536. this._updatePicker();
  13537. }
  13538. /**
  13539. * update the color picker. A black circle overlays the hue circle to mimic the brightness decreasing.
  13540. * @param rgba
  13541. * @private
  13542. */
  13543. }, {
  13544. key: '_updatePicker',
  13545. value: function _updatePicker() {
  13546. var rgba = arguments.length <= 0 || arguments[0] === undefined ? this.color : arguments[0];
  13547. var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  13548. var ctx = this.colorPickerCanvas.getContext('2d');
  13549. if (this.pixelRation === undefined) {
  13550. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  13551. }
  13552. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  13553. // clear the canvas
  13554. var w = this.colorPickerCanvas.clientWidth;
  13555. var h = this.colorPickerCanvas.clientHeight;
  13556. ctx.clearRect(0, 0, w, h);
  13557. ctx.putImageData(this.hueCircle, 0, 0);
  13558. ctx.fillStyle = 'rgba(0,0,0,' + (1 - hsv.v) + ')';
  13559. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  13560. ctx.fill();
  13561. this.brightnessRange.value = 100 * hsv.v;
  13562. this.opacityRange.value = 100 * rgba.a;
  13563. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  13564. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  13565. }
  13566. /**
  13567. * used by create to set the size of the canvas.
  13568. * @private
  13569. */
  13570. }, {
  13571. key: '_setSize',
  13572. value: function _setSize() {
  13573. this.colorPickerCanvas.style.width = '100%';
  13574. this.colorPickerCanvas.style.height = '100%';
  13575. this.colorPickerCanvas.width = 289 * this.pixelRatio;
  13576. this.colorPickerCanvas.height = 289 * this.pixelRatio;
  13577. }
  13578. /**
  13579. * create all dom elements
  13580. * TODO: cleanup, lots of similar dom elements
  13581. * @private
  13582. */
  13583. }, {
  13584. key: '_create',
  13585. value: function _create() {
  13586. this.frame = document.createElement('div');
  13587. this.frame.className = 'vis-color-picker';
  13588. this.colorPickerDiv = document.createElement('div');
  13589. this.colorPickerSelector = document.createElement('div');
  13590. this.colorPickerSelector.className = 'vis-selector';
  13591. this.colorPickerDiv.appendChild(this.colorPickerSelector);
  13592. this.colorPickerCanvas = document.createElement('canvas');
  13593. this.colorPickerDiv.appendChild(this.colorPickerCanvas);
  13594. if (!this.colorPickerCanvas.getContext) {
  13595. var noCanvas = document.createElement('DIV');
  13596. noCanvas.style.color = 'red';
  13597. noCanvas.style.fontWeight = 'bold';
  13598. noCanvas.style.padding = '10px';
  13599. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  13600. this.colorPickerCanvas.appendChild(noCanvas);
  13601. } else {
  13602. var ctx = this.colorPickerCanvas.getContext("2d");
  13603. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  13604. this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  13605. }
  13606. this.colorPickerDiv.className = 'vis-color';
  13607. this.opacityDiv = document.createElement('div');
  13608. this.opacityDiv.className = 'vis-opacity';
  13609. this.brightnessDiv = document.createElement('div');
  13610. this.brightnessDiv.className = 'vis-brightness';
  13611. this.arrowDiv = document.createElement('div');
  13612. this.arrowDiv.className = 'vis-arrow';
  13613. this.opacityRange = document.createElement('input');
  13614. try {
  13615. this.opacityRange.type = 'range'; // Not supported on IE9
  13616. this.opacityRange.min = '0';
  13617. this.opacityRange.max = '100';
  13618. } catch (err) {}
  13619. this.opacityRange.value = '100';
  13620. this.opacityRange.className = 'vis-range';
  13621. this.brightnessRange = document.createElement('input');
  13622. try {
  13623. this.brightnessRange.type = 'range'; // Not supported on IE9
  13624. this.brightnessRange.min = '0';
  13625. this.brightnessRange.max = '100';
  13626. } catch (err) {}
  13627. this.brightnessRange.value = '100';
  13628. this.brightnessRange.className = 'vis-range';
  13629. this.opacityDiv.appendChild(this.opacityRange);
  13630. this.brightnessDiv.appendChild(this.brightnessRange);
  13631. var me = this;
  13632. this.opacityRange.onchange = function () {
  13633. me._setOpacity(this.value);
  13634. };
  13635. this.opacityRange.oninput = function () {
  13636. me._setOpacity(this.value);
  13637. };
  13638. this.brightnessRange.onchange = function () {
  13639. me._setBrightness(this.value);
  13640. };
  13641. this.brightnessRange.oninput = function () {
  13642. me._setBrightness(this.value);
  13643. };
  13644. this.brightnessLabel = document.createElement("div");
  13645. this.brightnessLabel.className = "vis-label vis-brightness";
  13646. this.brightnessLabel.innerHTML = 'brightness:';
  13647. this.opacityLabel = document.createElement("div");
  13648. this.opacityLabel.className = "vis-label vis-opacity";
  13649. this.opacityLabel.innerHTML = 'opacity:';
  13650. this.newColorDiv = document.createElement("div");
  13651. this.newColorDiv.className = "vis-new-color";
  13652. this.newColorDiv.innerHTML = 'new';
  13653. this.initialColorDiv = document.createElement("div");
  13654. this.initialColorDiv.className = "vis-initial-color";
  13655. this.initialColorDiv.innerHTML = 'initial';
  13656. this.cancelButton = document.createElement("div");
  13657. this.cancelButton.className = "vis-button vis-cancel";
  13658. this.cancelButton.innerHTML = 'cancel';
  13659. this.cancelButton.onclick = this._hide.bind(this, false);
  13660. this.applyButton = document.createElement("div");
  13661. this.applyButton.className = "vis-button vis-apply";
  13662. this.applyButton.innerHTML = 'apply';
  13663. this.applyButton.onclick = this._apply.bind(this);
  13664. this.saveButton = document.createElement("div");
  13665. this.saveButton.className = "vis-button vis-save";
  13666. this.saveButton.innerHTML = 'save';
  13667. this.saveButton.onclick = this._save.bind(this);
  13668. this.loadButton = document.createElement("div");
  13669. this.loadButton.className = "vis-button vis-load";
  13670. this.loadButton.innerHTML = 'load last';
  13671. this.loadButton.onclick = this._loadLast.bind(this);
  13672. this.frame.appendChild(this.colorPickerDiv);
  13673. this.frame.appendChild(this.arrowDiv);
  13674. this.frame.appendChild(this.brightnessLabel);
  13675. this.frame.appendChild(this.brightnessDiv);
  13676. this.frame.appendChild(this.opacityLabel);
  13677. this.frame.appendChild(this.opacityDiv);
  13678. this.frame.appendChild(this.newColorDiv);
  13679. this.frame.appendChild(this.initialColorDiv);
  13680. this.frame.appendChild(this.cancelButton);
  13681. this.frame.appendChild(this.applyButton);
  13682. this.frame.appendChild(this.saveButton);
  13683. this.frame.appendChild(this.loadButton);
  13684. }
  13685. /**
  13686. * bind hammer to the color picker
  13687. * @private
  13688. */
  13689. }, {
  13690. key: '_bindHammer',
  13691. value: function _bindHammer() {
  13692. var _this2 = this;
  13693. this.drag = {};
  13694. this.pinch = {};
  13695. this.hammer = new Hammer(this.colorPickerCanvas);
  13696. this.hammer.get('pinch').set({ enable: true });
  13697. hammerUtil.onTouch(this.hammer, function (event) {
  13698. _this2._moveSelector(event);
  13699. });
  13700. this.hammer.on('tap', function (event) {
  13701. _this2._moveSelector(event);
  13702. });
  13703. this.hammer.on('panstart', function (event) {
  13704. _this2._moveSelector(event);
  13705. });
  13706. this.hammer.on('panmove', function (event) {
  13707. _this2._moveSelector(event);
  13708. });
  13709. this.hammer.on('panend', function (event) {
  13710. _this2._moveSelector(event);
  13711. });
  13712. }
  13713. /**
  13714. * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
  13715. * @private
  13716. */
  13717. }, {
  13718. key: '_generateHueCircle',
  13719. value: function _generateHueCircle() {
  13720. if (this.generated === false) {
  13721. var ctx = this.colorPickerCanvas.getContext('2d');
  13722. if (this.pixelRation === undefined) {
  13723. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  13724. }
  13725. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  13726. // clear the canvas
  13727. var w = this.colorPickerCanvas.clientWidth;
  13728. var h = this.colorPickerCanvas.clientHeight;
  13729. ctx.clearRect(0, 0, w, h);
  13730. // draw hue circle
  13731. var x = void 0,
  13732. y = void 0,
  13733. hue = void 0,
  13734. sat = void 0;
  13735. this.centerCoordinates = { x: w * 0.5, y: h * 0.5 };
  13736. this.r = 0.49 * w;
  13737. var angleConvert = 2 * Math.PI / 360;
  13738. var hfac = 1 / 360;
  13739. var sfac = 1 / this.r;
  13740. var rgb = void 0;
  13741. for (hue = 0; hue < 360; hue++) {
  13742. for (sat = 0; sat < this.r; sat++) {
  13743. x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
  13744. y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
  13745. rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1);
  13746. ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
  13747. ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
  13748. }
  13749. }
  13750. ctx.strokeStyle = 'rgba(0,0,0,1)';
  13751. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  13752. ctx.stroke();
  13753. this.hueCircle = ctx.getImageData(0, 0, w, h);
  13754. }
  13755. this.generated = true;
  13756. }
  13757. /**
  13758. * move the selector. This is called by hammer functions.
  13759. *
  13760. * @param event
  13761. * @private
  13762. */
  13763. }, {
  13764. key: '_moveSelector',
  13765. value: function _moveSelector(event) {
  13766. var rect = this.colorPickerDiv.getBoundingClientRect();
  13767. var left = event.center.x - rect.left;
  13768. var top = event.center.y - rect.top;
  13769. var centerY = 0.5 * this.colorPickerDiv.clientHeight;
  13770. var centerX = 0.5 * this.colorPickerDiv.clientWidth;
  13771. var x = left - centerX;
  13772. var y = top - centerY;
  13773. var angle = Math.atan2(x, y);
  13774. var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);
  13775. var newTop = Math.cos(angle) * radius + centerY;
  13776. var newLeft = Math.sin(angle) * radius + centerX;
  13777. this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  13778. this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  13779. // set color
  13780. var h = angle / (2 * Math.PI);
  13781. h = h < 0 ? h + 1 : h;
  13782. var s = radius / this.r;
  13783. var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  13784. hsv.h = h;
  13785. hsv.s = s;
  13786. var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  13787. rgba['a'] = this.color.a;
  13788. this.color = rgba;
  13789. // update previews
  13790. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  13791. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  13792. }
  13793. }]);
  13794. return ColorPicker;
  13795. }();
  13796. exports.default = ColorPicker;
  13797. /***/ },
  13798. /* 28 */
  13799. /***/ function(module, exports, __webpack_require__) {
  13800. 'use strict';
  13801. var Hammer = __webpack_require__(20);
  13802. /**
  13803. * Register a touch event, taking place before a gesture
  13804. * @param {Hammer} hammer A hammer instance
  13805. * @param {function} callback Callback, called as callback(event)
  13806. */
  13807. exports.onTouch = function (hammer, callback) {
  13808. callback.inputHandler = function (event) {
  13809. if (event.isFirst) {
  13810. callback(event);
  13811. }
  13812. };
  13813. hammer.on('hammer.input', callback.inputHandler);
  13814. };
  13815. /**
  13816. * Register a release event, taking place after a gesture
  13817. * @param {Hammer} hammer A hammer instance
  13818. * @param {function} callback Callback, called as callback(event)
  13819. */
  13820. exports.onRelease = function (hammer, callback) {
  13821. callback.inputHandler = function (event) {
  13822. if (event.isFinal) {
  13823. callback(event);
  13824. }
  13825. };
  13826. return hammer.on('hammer.input', callback.inputHandler);
  13827. };
  13828. /**
  13829. * Unregister a touch event, taking place before a gesture
  13830. * @param {Hammer} hammer A hammer instance
  13831. * @param {function} callback Callback, called as callback(event)
  13832. */
  13833. exports.offTouch = function (hammer, callback) {
  13834. hammer.off('hammer.input', callback.inputHandler);
  13835. };
  13836. /**
  13837. * Unregister a release event, taking place before a gesture
  13838. * @param {Hammer} hammer A hammer instance
  13839. * @param {function} callback Callback, called as callback(event)
  13840. */
  13841. exports.offRelease = exports.offTouch;
  13842. /**
  13843. * Hack the PinchRecognizer such that it doesn't prevent default behavior
  13844. * for vertical panning.
  13845. *
  13846. * Yeah ... this is quite a hack ... see https://github.com/hammerjs/hammer.js/issues/932
  13847. *
  13848. * @param {Hammer.Pinch} pinchRecognizer
  13849. * @return {Hammer.Pinch} returns the pinchRecognizer
  13850. */
  13851. exports.disablePreventDefaultVertically = function (pinchRecognizer) {
  13852. var TOUCH_ACTION_PAN_Y = 'pan-y';
  13853. pinchRecognizer.getTouchAction = function () {
  13854. // default method returns [TOUCH_ACTION_NONE]
  13855. return [TOUCH_ACTION_PAN_Y];
  13856. };
  13857. return pinchRecognizer;
  13858. };
  13859. /***/ },
  13860. /* 29 */
  13861. /***/ function(module, exports, __webpack_require__) {
  13862. 'use strict';
  13863. Object.defineProperty(exports, "__esModule", {
  13864. value: true
  13865. });
  13866. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  13867. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13868. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13869. var util = __webpack_require__(1);
  13870. var errorFound = false;
  13871. var allOptions = void 0;
  13872. var printStyle = 'background: #FFeeee; color: #dd0000';
  13873. /**
  13874. * Used to validate options.
  13875. */
  13876. var Validator = function () {
  13877. function Validator() {
  13878. _classCallCheck(this, Validator);
  13879. }
  13880. /**
  13881. * Main function to be called
  13882. * @param options
  13883. * @param subObject
  13884. * @returns {boolean}
  13885. */
  13886. _createClass(Validator, null, [{
  13887. key: 'validate',
  13888. value: function validate(options, referenceOptions, subObject) {
  13889. errorFound = false;
  13890. allOptions = referenceOptions;
  13891. var usedOptions = referenceOptions;
  13892. if (subObject !== undefined) {
  13893. usedOptions = referenceOptions[subObject];
  13894. }
  13895. Validator.parse(options, usedOptions, []);
  13896. return errorFound;
  13897. }
  13898. /**
  13899. * Will traverse an object recursively and check every value
  13900. * @param options
  13901. * @param referenceOptions
  13902. * @param path
  13903. */
  13904. }, {
  13905. key: 'parse',
  13906. value: function parse(options, referenceOptions, path) {
  13907. for (var option in options) {
  13908. if (options.hasOwnProperty(option)) {
  13909. Validator.check(option, options, referenceOptions, path);
  13910. }
  13911. }
  13912. }
  13913. /**
  13914. * Check every value. If the value is an object, call the parse function on that object.
  13915. * @param option
  13916. * @param options
  13917. * @param referenceOptions
  13918. * @param path
  13919. */
  13920. }, {
  13921. key: 'check',
  13922. value: function check(option, options, referenceOptions, path) {
  13923. if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) {
  13924. Validator.getSuggestion(option, referenceOptions, path);
  13925. } else if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
  13926. // __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
  13927. if (Validator.getType(options[option]) === 'object' && referenceOptions['__any__'].__type__ !== undefined) {
  13928. // if the any subgroup is not a predefined object int he configurator we do not look deeper into the object.
  13929. Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'].__type__, path);
  13930. } else {
  13931. Validator.checkFields(option, options, referenceOptions, '__any__', referenceOptions['__any__'], path);
  13932. }
  13933. } else {
  13934. // Since all options in the reference are objects, we can check whether they are supposed to be object to look for the __type__ field.
  13935. if (referenceOptions[option].__type__ !== undefined) {
  13936. // if this should be an object, we check if the correct type has been supplied to account for shorthand options.
  13937. Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option].__type__, path);
  13938. } else {
  13939. Validator.checkFields(option, options, referenceOptions, option, referenceOptions[option], path);
  13940. }
  13941. }
  13942. }
  13943. /**
  13944. *
  13945. * @param {String} option | the option property
  13946. * @param {Object} options | The supplied options object
  13947. * @param {Object} referenceOptions | The reference options containing all options and their allowed formats
  13948. * @param {String} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
  13949. * @param {String} refOptionType | This is the type object from the reference options
  13950. * @param {Array} path | where in the object is the option
  13951. */
  13952. }, {
  13953. key: 'checkFields',
  13954. value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
  13955. var optionType = Validator.getType(options[option]);
  13956. var refOptionType = refOptionObj[optionType];
  13957. if (refOptionType !== undefined) {
  13958. // if the type is correct, we check if it is supposed to be one of a few select values
  13959. if (Validator.getType(refOptionType) === 'array') {
  13960. if (refOptionType.indexOf(options[option]) === -1) {
  13961. console.log('%cInvalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ' + Validator.printLocation(path, option), printStyle);
  13962. errorFound = true;
  13963. } else if (optionType === 'object' && referenceOption !== "__any__") {
  13964. path = util.copyAndExtendArray(path, option);
  13965. Validator.parse(options[option], referenceOptions[referenceOption], path);
  13966. }
  13967. } else if (optionType === 'object' && referenceOption !== "__any__") {
  13968. path = util.copyAndExtendArray(path, option);
  13969. Validator.parse(options[option], referenceOptions[referenceOption], path);
  13970. }
  13971. } else if (refOptionObj['any'] === undefined) {
  13972. // type of the field is incorrect and the field cannot be any
  13973. console.log('%cInvalid type received for "' + option + '". Expected: ' + Validator.print(Object.keys(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"' + Validator.printLocation(path, option), printStyle);
  13974. errorFound = true;
  13975. }
  13976. }
  13977. }, {
  13978. key: 'getType',
  13979. value: function getType(object) {
  13980. var type = typeof object === 'undefined' ? 'undefined' : _typeof(object);
  13981. if (type === 'object') {
  13982. if (object === null) {
  13983. return 'null';
  13984. }
  13985. if (object instanceof Boolean) {
  13986. return 'boolean';
  13987. }
  13988. if (object instanceof Number) {
  13989. return 'number';
  13990. }
  13991. if (object instanceof String) {
  13992. return 'string';
  13993. }
  13994. if (Array.isArray(object)) {
  13995. return 'array';
  13996. }
  13997. if (object instanceof Date) {
  13998. return 'date';
  13999. }
  14000. if (object.nodeType !== undefined) {
  14001. return 'dom';
  14002. }
  14003. if (object._isAMomentObject === true) {
  14004. return 'moment';
  14005. }
  14006. return 'object';
  14007. } else if (type === 'number') {
  14008. return 'number';
  14009. } else if (type === 'boolean') {
  14010. return 'boolean';
  14011. } else if (type === 'string') {
  14012. return 'string';
  14013. } else if (type === undefined) {
  14014. return 'undefined';
  14015. }
  14016. return type;
  14017. }
  14018. }, {
  14019. key: 'getSuggestion',
  14020. value: function getSuggestion(option, options, path) {
  14021. var localSearch = Validator.findInOptions(option, options, path, false);
  14022. var globalSearch = Validator.findInOptions(option, allOptions, [], true);
  14023. var localSearchThreshold = 8;
  14024. var globalSearchThreshold = 4;
  14025. if (localSearch.indexMatch !== undefined) {
  14026. console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n', printStyle);
  14027. } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
  14028. console.log('%cUnknown option detected: "' + option + '" in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, ''), printStyle);
  14029. } else if (localSearch.distance <= localSearchThreshold) {
  14030. console.log('%cUnknown option detected: "' + option + '". Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option), printStyle);
  14031. } else {
  14032. console.log('%cUnknown option detected: "' + option + '". Did you mean one of these: ' + Validator.print(Object.keys(options)) + Validator.printLocation(path, option), printStyle);
  14033. }
  14034. errorFound = true;
  14035. }
  14036. /**
  14037. * traverse the options in search for a match.
  14038. * @param option
  14039. * @param options
  14040. * @param path
  14041. * @param recursive
  14042. * @returns {{closestMatch: string, path: Array, distance: number}}
  14043. */
  14044. }, {
  14045. key: 'findInOptions',
  14046. value: function findInOptions(option, options, path) {
  14047. var recursive = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
  14048. var min = 1e9;
  14049. var closestMatch = '';
  14050. var closestMatchPath = [];
  14051. var lowerCaseOption = option.toLowerCase();
  14052. var indexMatch = undefined;
  14053. for (var op in options) {
  14054. var distance = void 0;
  14055. if (options[op].__type__ !== undefined && recursive === true) {
  14056. var result = Validator.findInOptions(option, options[op], util.copyAndExtendArray(path, op));
  14057. if (min > result.distance) {
  14058. closestMatch = result.closestMatch;
  14059. closestMatchPath = result.path;
  14060. min = result.distance;
  14061. indexMatch = result.indexMatch;
  14062. }
  14063. } else {
  14064. if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
  14065. indexMatch = op;
  14066. }
  14067. distance = Validator.levenshteinDistance(option, op);
  14068. if (min > distance) {
  14069. closestMatch = op;
  14070. closestMatchPath = util.copyArray(path);
  14071. min = distance;
  14072. }
  14073. }
  14074. }
  14075. return { closestMatch: closestMatch, path: closestMatchPath, distance: min, indexMatch: indexMatch };
  14076. }
  14077. }, {
  14078. key: 'printLocation',
  14079. value: function printLocation(path, option) {
  14080. var prefix = arguments.length <= 2 || arguments[2] === undefined ? 'Problem value found at: \n' : arguments[2];
  14081. var str = '\n\n' + prefix + 'options = {\n';
  14082. for (var i = 0; i < path.length; i++) {
  14083. for (var j = 0; j < i + 1; j++) {
  14084. str += ' ';
  14085. }
  14086. str += path[i] + ': {\n';
  14087. }
  14088. for (var _j = 0; _j < path.length + 1; _j++) {
  14089. str += ' ';
  14090. }
  14091. str += option + '\n';
  14092. for (var _i = 0; _i < path.length + 1; _i++) {
  14093. for (var _j2 = 0; _j2 < path.length - _i; _j2++) {
  14094. str += ' ';
  14095. }
  14096. str += '}\n';
  14097. }
  14098. return str + '\n\n';
  14099. }
  14100. }, {
  14101. key: 'print',
  14102. value: function print(options) {
  14103. return JSON.stringify(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, "").replace(/(\,)/g, ', ');
  14104. }
  14105. // Compute the edit distance between the two given strings
  14106. // http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
  14107. /*
  14108. Copyright (c) 2011 Andrei Mackenzie
  14109. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  14110. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  14111. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  14112. */
  14113. }, {
  14114. key: 'levenshteinDistance',
  14115. value: function levenshteinDistance(a, b) {
  14116. if (a.length === 0) return b.length;
  14117. if (b.length === 0) return a.length;
  14118. var matrix = [];
  14119. // increment along the first column of each row
  14120. var i;
  14121. for (i = 0; i <= b.length; i++) {
  14122. matrix[i] = [i];
  14123. }
  14124. // increment each column in the first row
  14125. var j;
  14126. for (j = 0; j <= a.length; j++) {
  14127. matrix[0][j] = j;
  14128. }
  14129. // Fill in the rest of the matrix
  14130. for (i = 1; i <= b.length; i++) {
  14131. for (j = 1; j <= a.length; j++) {
  14132. if (b.charAt(i - 1) == a.charAt(j - 1)) {
  14133. matrix[i][j] = matrix[i - 1][j - 1];
  14134. } else {
  14135. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
  14136. Math.min(matrix[i][j - 1] + 1, // insertion
  14137. matrix[i - 1][j] + 1)); // deletion
  14138. }
  14139. }
  14140. }
  14141. return matrix[b.length][a.length];
  14142. }
  14143. }]);
  14144. return Validator;
  14145. }();
  14146. exports.default = Validator;
  14147. exports.printStyle = printStyle;
  14148. /***/ },
  14149. /* 30 */
  14150. /***/ function(module, exports, __webpack_require__) {
  14151. 'use strict';
  14152. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  14153. var util = __webpack_require__(1);
  14154. var hammerUtil = __webpack_require__(28);
  14155. var moment = __webpack_require__(2);
  14156. var Component = __webpack_require__(31);
  14157. var DateUtil = __webpack_require__(32);
  14158. /**
  14159. * @constructor Range
  14160. * A Range controls a numeric range with a start and end value.
  14161. * The Range adjusts the range based on mouse events or programmatic changes,
  14162. * and triggers events when the range is changing or has been changed.
  14163. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  14164. * @param {Object} [options] See description at Range.setOptions
  14165. */
  14166. function Range(body, options) {
  14167. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  14168. this.start = now.clone().add(-3, 'days').valueOf(); // Number
  14169. this.end = now.clone().add(4, 'days').valueOf(); // Number
  14170. this.body = body;
  14171. this.deltaDifference = 0;
  14172. this.scaleOffset = 0;
  14173. this.startToFront = false;
  14174. this.endToFront = true;
  14175. // default options
  14176. this.defaultOptions = {
  14177. rtl: false,
  14178. start: null,
  14179. end: null,
  14180. moment: moment,
  14181. direction: 'horizontal', // 'horizontal' or 'vertical'
  14182. moveable: true,
  14183. zoomable: true,
  14184. min: null,
  14185. max: null,
  14186. zoomMin: 10, // milliseconds
  14187. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
  14188. };
  14189. this.options = util.extend({}, this.defaultOptions);
  14190. this.props = {
  14191. touch: {}
  14192. };
  14193. this.animationTimer = null;
  14194. // drag listeners for dragging
  14195. this.body.emitter.on('panstart', this._onDragStart.bind(this));
  14196. this.body.emitter.on('panmove', this._onDrag.bind(this));
  14197. this.body.emitter.on('panend', this._onDragEnd.bind(this));
  14198. // mouse wheel for zooming
  14199. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  14200. // pinch to zoom
  14201. this.body.emitter.on('touch', this._onTouch.bind(this));
  14202. this.body.emitter.on('pinch', this._onPinch.bind(this));
  14203. this.setOptions(options);
  14204. }
  14205. Range.prototype = new Component();
  14206. /**
  14207. * Set options for the range controller
  14208. * @param {Object} options Available options:
  14209. * {Number | Date | String} start Start date for the range
  14210. * {Number | Date | String} end End date for the range
  14211. * {Number} min Minimum value for start
  14212. * {Number} max Maximum value for end
  14213. * {Number} zoomMin Set a minimum value for
  14214. * (end - start).
  14215. * {Number} zoomMax Set a maximum value for
  14216. * (end - start).
  14217. * {Boolean} moveable Enable moving of the range
  14218. * by dragging. True by default
  14219. * {Boolean} zoomable Enable zooming of the range
  14220. * by pinching/scrolling. True by default
  14221. */
  14222. Range.prototype.setOptions = function (options) {
  14223. if (options) {
  14224. // copy the options that we know
  14225. var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'moment', 'activate', 'hiddenDates', 'zoomKey', 'rtl'];
  14226. util.selectiveExtend(fields, this.options, options);
  14227. if ('start' in options || 'end' in options) {
  14228. // apply a new range. both start and end are optional
  14229. this.setRange(options.start, options.end);
  14230. }
  14231. }
  14232. };
  14233. /**
  14234. * Test whether direction has a valid value
  14235. * @param {String} direction 'horizontal' or 'vertical'
  14236. */
  14237. function validateDirection(direction) {
  14238. if (direction != 'horizontal' && direction != 'vertical') {
  14239. throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".');
  14240. }
  14241. }
  14242. /**
  14243. * Set a new start and end range
  14244. * @param {Date | Number | String} [start]
  14245. * @param {Date | Number | String} [end]
  14246. * @param {boolean | {duration: number, easingFunction: string}} [animation=false]
  14247. * If true (default), the range is animated
  14248. * smoothly to the new window. An object can be
  14249. * provided to specify duration and easing function.
  14250. * Default duration is 500 ms, and default easing
  14251. * function is 'easeInOutQuad'.
  14252. * @param {Boolean} [byUser=false]
  14253. *
  14254. */
  14255. Range.prototype.setRange = function (start, end, animation, byUser) {
  14256. if (byUser !== true) {
  14257. byUser = false;
  14258. }
  14259. var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  14260. var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  14261. this._cancelAnimation();
  14262. if (animation) {
  14263. // true or an Object
  14264. var me = this;
  14265. var initStart = this.start;
  14266. var initEnd = this.end;
  14267. var duration = (typeof animation === 'undefined' ? 'undefined' : _typeof(animation)) === 'object' && 'duration' in animation ? animation.duration : 500;
  14268. var easingName = (typeof animation === 'undefined' ? 'undefined' : _typeof(animation)) === 'object' && 'easingFunction' in animation ? animation.easingFunction : 'easeInOutQuad';
  14269. var easingFunction = util.easingFunctions[easingName];
  14270. if (!easingFunction) {
  14271. throw new Error('Unknown easing function ' + JSON.stringify(easingName) + '. ' + 'Choose from: ' + Object.keys(util.easingFunctions).join(', '));
  14272. }
  14273. var initTime = new Date().valueOf();
  14274. var anyChanged = false;
  14275. var next = function next() {
  14276. if (!me.props.touch.dragging) {
  14277. var now = new Date().valueOf();
  14278. var time = now - initTime;
  14279. var ease = easingFunction(time / duration);
  14280. var done = time > duration;
  14281. var s = done || finalStart === null ? finalStart : initStart + (finalStart - initStart) * ease;
  14282. var e = done || finalEnd === null ? finalEnd : initEnd + (finalEnd - initEnd) * ease;
  14283. changed = me._applyRange(s, e);
  14284. DateUtil.updateHiddenDates(me.options.moment, me.body, me.options.hiddenDates);
  14285. anyChanged = anyChanged || changed;
  14286. if (changed) {
  14287. me.body.emitter.emit('rangechange', { start: new Date(me.start), end: new Date(me.end), byUser: byUser });
  14288. }
  14289. if (done) {
  14290. if (anyChanged) {
  14291. me.body.emitter.emit('rangechanged', { start: new Date(me.start), end: new Date(me.end), byUser: byUser });
  14292. }
  14293. } else {
  14294. // animate with as high as possible frame rate, leave 20 ms in between
  14295. // each to prevent the browser from blocking
  14296. me.animationTimer = setTimeout(next, 20);
  14297. }
  14298. }
  14299. };
  14300. return next();
  14301. } else {
  14302. var changed = this._applyRange(finalStart, finalEnd);
  14303. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  14304. if (changed) {
  14305. var params = { start: new Date(this.start), end: new Date(this.end), byUser: byUser };
  14306. this.body.emitter.emit('rangechange', params);
  14307. this.body.emitter.emit('rangechanged', params);
  14308. }
  14309. }
  14310. };
  14311. /**
  14312. * Stop an animation
  14313. * @private
  14314. */
  14315. Range.prototype._cancelAnimation = function () {
  14316. if (this.animationTimer) {
  14317. clearTimeout(this.animationTimer);
  14318. this.animationTimer = null;
  14319. }
  14320. };
  14321. /**
  14322. * Set a new start and end range. This method is the same as setRange, but
  14323. * does not trigger a range change and range changed event, and it returns
  14324. * true when the range is changed
  14325. * @param {Number} [start]
  14326. * @param {Number} [end]
  14327. * @return {Boolean} changed
  14328. * @private
  14329. */
  14330. Range.prototype._applyRange = function (start, end) {
  14331. var newStart = start != null ? util.convert(start, 'Date').valueOf() : this.start,
  14332. newEnd = end != null ? util.convert(end, 'Date').valueOf() : this.end,
  14333. max = this.options.max != null ? util.convert(this.options.max, 'Date').valueOf() : null,
  14334. min = this.options.min != null ? util.convert(this.options.min, 'Date').valueOf() : null,
  14335. diff;
  14336. // check for valid number
  14337. if (isNaN(newStart) || newStart === null) {
  14338. throw new Error('Invalid start "' + start + '"');
  14339. }
  14340. if (isNaN(newEnd) || newEnd === null) {
  14341. throw new Error('Invalid end "' + end + '"');
  14342. }
  14343. // prevent start < end
  14344. if (newEnd < newStart) {
  14345. newEnd = newStart;
  14346. }
  14347. // prevent start < min
  14348. if (min !== null) {
  14349. if (newStart < min) {
  14350. diff = min - newStart;
  14351. newStart += diff;
  14352. newEnd += diff;
  14353. // prevent end > max
  14354. if (max != null) {
  14355. if (newEnd > max) {
  14356. newEnd = max;
  14357. }
  14358. }
  14359. }
  14360. }
  14361. // prevent end > max
  14362. if (max !== null) {
  14363. if (newEnd > max) {
  14364. diff = newEnd - max;
  14365. newStart -= diff;
  14366. newEnd -= diff;
  14367. // prevent start < min
  14368. if (min != null) {
  14369. if (newStart < min) {
  14370. newStart = min;
  14371. }
  14372. }
  14373. }
  14374. }
  14375. // prevent (end-start) < zoomMin
  14376. if (this.options.zoomMin !== null) {
  14377. var zoomMin = parseFloat(this.options.zoomMin);
  14378. if (zoomMin < 0) {
  14379. zoomMin = 0;
  14380. }
  14381. if (newEnd - newStart < zoomMin) {
  14382. if (this.end - this.start === zoomMin && newStart > this.start && newEnd < this.end) {
  14383. // ignore this action, we are already zoomed to the minimum
  14384. newStart = this.start;
  14385. newEnd = this.end;
  14386. } else {
  14387. // zoom to the minimum
  14388. diff = zoomMin - (newEnd - newStart);
  14389. newStart -= diff / 2;
  14390. newEnd += diff / 2;
  14391. }
  14392. }
  14393. }
  14394. // prevent (end-start) > zoomMax
  14395. if (this.options.zoomMax !== null) {
  14396. var zoomMax = parseFloat(this.options.zoomMax);
  14397. if (zoomMax < 0) {
  14398. zoomMax = 0;
  14399. }
  14400. if (newEnd - newStart > zoomMax) {
  14401. if (this.end - this.start === zoomMax && newStart < this.start && newEnd > this.end) {
  14402. // ignore this action, we are already zoomed to the maximum
  14403. newStart = this.start;
  14404. newEnd = this.end;
  14405. } else {
  14406. // zoom to the maximum
  14407. diff = newEnd - newStart - zoomMax;
  14408. newStart += diff / 2;
  14409. newEnd -= diff / 2;
  14410. }
  14411. }
  14412. }
  14413. var changed = this.start != newStart || this.end != newEnd;
  14414. // if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
  14415. if (!(newStart >= this.start && newStart <= this.end || newEnd >= this.start && newEnd <= this.end) && !(this.start >= newStart && this.start <= newEnd || this.end >= newStart && this.end <= newEnd)) {
  14416. this.body.emitter.emit('checkRangedItems');
  14417. }
  14418. this.start = newStart;
  14419. this.end = newEnd;
  14420. return changed;
  14421. };
  14422. /**
  14423. * Retrieve the current range.
  14424. * @return {Object} An object with start and end properties
  14425. */
  14426. Range.prototype.getRange = function () {
  14427. return {
  14428. start: this.start,
  14429. end: this.end
  14430. };
  14431. };
  14432. /**
  14433. * Calculate the conversion offset and scale for current range, based on
  14434. * the provided width
  14435. * @param {Number} width
  14436. * @returns {{offset: number, scale: number}} conversion
  14437. */
  14438. Range.prototype.conversion = function (width, totalHidden) {
  14439. return Range.conversion(this.start, this.end, width, totalHidden);
  14440. };
  14441. /**
  14442. * Static method to calculate the conversion offset and scale for a range,
  14443. * based on the provided start, end, and width
  14444. * @param {Number} start
  14445. * @param {Number} end
  14446. * @param {Number} width
  14447. * @returns {{offset: number, scale: number}} conversion
  14448. */
  14449. Range.conversion = function (start, end, width, totalHidden) {
  14450. if (totalHidden === undefined) {
  14451. totalHidden = 0;
  14452. }
  14453. if (width != 0 && end - start != 0) {
  14454. return {
  14455. offset: start,
  14456. scale: width / (end - start - totalHidden)
  14457. };
  14458. } else {
  14459. return {
  14460. offset: 0,
  14461. scale: 1
  14462. };
  14463. }
  14464. };
  14465. /**
  14466. * Start dragging horizontally or vertically
  14467. * @param {Event} event
  14468. * @private
  14469. */
  14470. Range.prototype._onDragStart = function (event) {
  14471. this.deltaDifference = 0;
  14472. this.previousDelta = 0;
  14473. // only allow dragging when configured as movable
  14474. if (!this.options.moveable) return;
  14475. // only start dragging when the mouse is inside the current range
  14476. if (!this._isInsideRange(event)) return;
  14477. // refuse to drag when we where pinching to prevent the timeline make a jump
  14478. // when releasing the fingers in opposite order from the touch screen
  14479. if (!this.props.touch.allowDragging) return;
  14480. this.props.touch.start = this.start;
  14481. this.props.touch.end = this.end;
  14482. this.props.touch.dragging = true;
  14483. if (this.body.dom.root) {
  14484. this.body.dom.root.style.cursor = 'move';
  14485. }
  14486. };
  14487. /**
  14488. * Perform dragging operation
  14489. * @param {Event} event
  14490. * @private
  14491. */
  14492. Range.prototype._onDrag = function (event) {
  14493. if (!this.props.touch.dragging) return;
  14494. // only allow dragging when configured as movable
  14495. if (!this.options.moveable) return;
  14496. // TODO: this may be redundant in hammerjs2
  14497. // refuse to drag when we where pinching to prevent the timeline make a jump
  14498. // when releasing the fingers in opposite order from the touch screen
  14499. if (!this.props.touch.allowDragging) return;
  14500. var direction = this.options.direction;
  14501. validateDirection(direction);
  14502. var delta = direction == 'horizontal' ? event.deltaX : event.deltaY;
  14503. delta -= this.deltaDifference;
  14504. var interval = this.props.touch.end - this.props.touch.start;
  14505. // normalize dragging speed if cutout is in between.
  14506. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  14507. interval -= duration;
  14508. var width = direction == 'horizontal' ? this.body.domProps.center.width : this.body.domProps.center.height;
  14509. if (this.options.rtl) {
  14510. var diffRange = delta / width * interval;
  14511. } else {
  14512. var diffRange = -delta / width * interval;
  14513. }
  14514. var newStart = this.props.touch.start + diffRange;
  14515. var newEnd = this.props.touch.end + diffRange;
  14516. // snapping times away from hidden zones
  14517. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta - delta, true);
  14518. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta - delta, true);
  14519. if (safeStart != newStart || safeEnd != newEnd) {
  14520. this.deltaDifference += delta;
  14521. this.props.touch.start = safeStart;
  14522. this.props.touch.end = safeEnd;
  14523. this._onDrag(event);
  14524. return;
  14525. }
  14526. this.previousDelta = delta;
  14527. this._applyRange(newStart, newEnd);
  14528. var startDate = new Date(this.start);
  14529. var endDate = new Date(this.end);
  14530. // fire a rangechange event
  14531. this.body.emitter.emit('rangechange', {
  14532. start: startDate,
  14533. end: endDate,
  14534. byUser: true
  14535. });
  14536. };
  14537. /**
  14538. * Stop dragging operation
  14539. * @param {event} event
  14540. * @private
  14541. */
  14542. Range.prototype._onDragEnd = function (event) {
  14543. if (!this.props.touch.dragging) return;
  14544. // only allow dragging when configured as movable
  14545. if (!this.options.moveable) return;
  14546. // TODO: this may be redundant in hammerjs2
  14547. // refuse to drag when we where pinching to prevent the timeline make a jump
  14548. // when releasing the fingers in opposite order from the touch screen
  14549. if (!this.props.touch.allowDragging) return;
  14550. this.props.touch.dragging = false;
  14551. if (this.body.dom.root) {
  14552. this.body.dom.root.style.cursor = 'auto';
  14553. }
  14554. // fire a rangechanged event
  14555. this.body.emitter.emit('rangechanged', {
  14556. start: new Date(this.start),
  14557. end: new Date(this.end),
  14558. byUser: true
  14559. });
  14560. };
  14561. /**
  14562. * Event handler for mouse wheel event, used to zoom
  14563. * Code from http://adomas.org/javascript-mouse-wheel/
  14564. * @param {Event} event
  14565. * @private
  14566. */
  14567. Range.prototype._onMouseWheel = function (event) {
  14568. // only allow zooming when configured as zoomable and moveable
  14569. if (!(this.options.zoomable && this.options.moveable)) return;
  14570. // only zoom when the mouse is inside the current range
  14571. if (!this._isInsideRange(event)) return;
  14572. // only zoom when the according key is pressed and the zoomKey option is set
  14573. if (this.options.zoomKey && !event[this.options.zoomKey]) return;
  14574. // retrieve delta
  14575. var delta = 0;
  14576. if (event.wheelDelta) {
  14577. /* IE/Opera. */
  14578. delta = event.wheelDelta / 120;
  14579. } else if (event.detail) {
  14580. /* Mozilla case. */
  14581. // In Mozilla, sign of delta is different than in IE.
  14582. // Also, delta is multiple of 3.
  14583. delta = -event.detail / 3;
  14584. }
  14585. // If delta is nonzero, handle it.
  14586. // Basically, delta is now positive if wheel was scrolled up,
  14587. // and negative, if wheel was scrolled down.
  14588. if (delta) {
  14589. // perform the zoom action. Delta is normally 1 or -1
  14590. // adjust a negative delta such that zooming in with delta 0.1
  14591. // equals zooming out with a delta -0.1
  14592. var scale;
  14593. if (delta < 0) {
  14594. scale = 1 - delta / 5;
  14595. } else {
  14596. scale = 1 / (1 + delta / 5);
  14597. }
  14598. // calculate center, the date to zoom around
  14599. var pointer = this.getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center);
  14600. var pointerDate = this._pointerToDate(pointer);
  14601. this.zoom(scale, pointerDate, delta);
  14602. }
  14603. // Prevent default actions caused by mouse wheel
  14604. // (else the page and timeline both zoom and scroll)
  14605. event.preventDefault();
  14606. };
  14607. /**
  14608. * Start of a touch gesture
  14609. * @private
  14610. */
  14611. Range.prototype._onTouch = function (event) {
  14612. this.props.touch.start = this.start;
  14613. this.props.touch.end = this.end;
  14614. this.props.touch.allowDragging = true;
  14615. this.props.touch.center = null;
  14616. this.scaleOffset = 0;
  14617. this.deltaDifference = 0;
  14618. };
  14619. /**
  14620. * Handle pinch event
  14621. * @param {Event} event
  14622. * @private
  14623. */
  14624. Range.prototype._onPinch = function (event) {
  14625. // only allow zooming when configured as zoomable and moveable
  14626. if (!(this.options.zoomable && this.options.moveable)) return;
  14627. this.props.touch.allowDragging = false;
  14628. if (!this.props.touch.center) {
  14629. this.props.touch.center = this.getPointer(event.center, this.body.dom.center);
  14630. }
  14631. var scale = 1 / (event.scale + this.scaleOffset);
  14632. var centerDate = this._pointerToDate(this.props.touch.center);
  14633. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  14634. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, centerDate);
  14635. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  14636. // calculate new start and end
  14637. var newStart = centerDate - hiddenDurationBefore + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  14638. var newEnd = centerDate + hiddenDurationAfter + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  14639. // snapping times away from hidden zones
  14640. this.startToFront = 1 - scale <= 0; // used to do the right auto correction with periodic hidden times
  14641. this.endToFront = scale - 1 <= 0; // used to do the right auto correction with periodic hidden times
  14642. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  14643. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  14644. if (safeStart != newStart || safeEnd != newEnd) {
  14645. this.props.touch.start = safeStart;
  14646. this.props.touch.end = safeEnd;
  14647. this.scaleOffset = 1 - event.scale;
  14648. newStart = safeStart;
  14649. newEnd = safeEnd;
  14650. }
  14651. this.setRange(newStart, newEnd, false, true);
  14652. this.startToFront = false; // revert to default
  14653. this.endToFront = true; // revert to default
  14654. };
  14655. /**
  14656. * Test whether the mouse from a mouse event is inside the visible window,
  14657. * between the current start and end date
  14658. * @param {Object} event
  14659. * @return {boolean} Returns true when inside the visible window
  14660. * @private
  14661. */
  14662. Range.prototype._isInsideRange = function (event) {
  14663. // calculate the time where the mouse is, check whether inside
  14664. // and no scroll action should happen.
  14665. var clientX = event.center ? event.center.x : event.clientX;
  14666. if (this.options.rtl) {
  14667. var x = clientX - util.getAbsoluteLeft(this.body.dom.centerContainer);
  14668. } else {
  14669. var x = util.getAbsoluteRight(this.body.dom.centerContainer) - clientX;
  14670. }
  14671. var time = this.body.util.toTime(x);
  14672. return time >= this.start && time <= this.end;
  14673. };
  14674. /**
  14675. * Helper function to calculate the center date for zooming
  14676. * @param {{x: Number, y: Number}} pointer
  14677. * @return {number} date
  14678. * @private
  14679. */
  14680. Range.prototype._pointerToDate = function (pointer) {
  14681. var conversion;
  14682. var direction = this.options.direction;
  14683. validateDirection(direction);
  14684. if (direction == 'horizontal') {
  14685. return this.body.util.toTime(pointer.x).valueOf();
  14686. } else {
  14687. var height = this.body.domProps.center.height;
  14688. conversion = this.conversion(height);
  14689. return pointer.y / conversion.scale + conversion.offset;
  14690. }
  14691. };
  14692. /**
  14693. * Get the pointer location relative to the location of the dom element
  14694. * @param {{x: Number, y: Number}} touch
  14695. * @param {Element} element HTML DOM element
  14696. * @return {{x: Number, y: Number}} pointer
  14697. * @private
  14698. */
  14699. Range.prototype.getPointer = function (touch, element) {
  14700. if (this.options.rtl) {
  14701. return {
  14702. x: util.getAbsoluteRight(element) - touch.x,
  14703. y: touch.y - util.getAbsoluteTop(element)
  14704. };
  14705. } else {
  14706. return {
  14707. x: touch.x - util.getAbsoluteLeft(element),
  14708. y: touch.y - util.getAbsoluteTop(element)
  14709. };
  14710. }
  14711. };
  14712. /**
  14713. * Zoom the range the given scale in or out. Start and end date will
  14714. * be adjusted, and the timeline will be redrawn. You can optionally give a
  14715. * date around which to zoom.
  14716. * For example, try scale = 0.9 or 1.1
  14717. * @param {Number} scale Scaling factor. Values above 1 will zoom out,
  14718. * values below 1 will zoom in.
  14719. * @param {Number} [center] Value representing a date around which will
  14720. * be zoomed.
  14721. */
  14722. Range.prototype.zoom = function (scale, center, delta) {
  14723. // if centerDate is not provided, take it half between start Date and end Date
  14724. if (center == null) {
  14725. center = (this.start + this.end) / 2;
  14726. }
  14727. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  14728. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, center);
  14729. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  14730. // calculate new start and end
  14731. var newStart = center - hiddenDurationBefore + (this.start - (center - hiddenDurationBefore)) * scale;
  14732. var newEnd = center + hiddenDurationAfter + (this.end - (center + hiddenDurationAfter)) * scale;
  14733. // snapping times away from hidden zones
  14734. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  14735. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  14736. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  14737. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  14738. if (safeStart != newStart || safeEnd != newEnd) {
  14739. newStart = safeStart;
  14740. newEnd = safeEnd;
  14741. }
  14742. this.setRange(newStart, newEnd, false, true);
  14743. this.startToFront = false; // revert to default
  14744. this.endToFront = true; // revert to default
  14745. };
  14746. /**
  14747. * Move the range with a given delta to the left or right. Start and end
  14748. * value will be adjusted. For example, try delta = 0.1 or -0.1
  14749. * @param {Number} delta Moving amount. Positive value will move right,
  14750. * negative value will move left
  14751. */
  14752. Range.prototype.move = function (delta) {
  14753. // zoom start Date and end Date relative to the centerDate
  14754. var diff = this.end - this.start;
  14755. // apply new values
  14756. var newStart = this.start + diff * delta;
  14757. var newEnd = this.end + diff * delta;
  14758. // TODO: reckon with min and max range
  14759. this.start = newStart;
  14760. this.end = newEnd;
  14761. };
  14762. /**
  14763. * Move the range to a new center point
  14764. * @param {Number} moveTo New center point of the range
  14765. */
  14766. Range.prototype.moveTo = function (moveTo) {
  14767. var center = (this.start + this.end) / 2;
  14768. var diff = center - moveTo;
  14769. // calculate new start and end
  14770. var newStart = this.start - diff;
  14771. var newEnd = this.end - diff;
  14772. this.setRange(newStart, newEnd);
  14773. };
  14774. module.exports = Range;
  14775. /***/ },
  14776. /* 31 */
  14777. /***/ function(module, exports) {
  14778. "use strict";
  14779. /**
  14780. * Prototype for visual components
  14781. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
  14782. * @param {Object} [options]
  14783. */
  14784. function Component(body, options) {
  14785. this.options = null;
  14786. this.props = null;
  14787. }
  14788. /**
  14789. * Set options for the component. The new options will be merged into the
  14790. * current options.
  14791. * @param {Object} options
  14792. */
  14793. Component.prototype.setOptions = function (options) {
  14794. if (options) {
  14795. util.extend(this.options, options);
  14796. }
  14797. };
  14798. /**
  14799. * Repaint the component
  14800. * @return {boolean} Returns true if the component is resized
  14801. */
  14802. Component.prototype.redraw = function () {
  14803. // should be implemented by the component
  14804. return false;
  14805. };
  14806. /**
  14807. * Destroy the component. Cleanup DOM and event listeners
  14808. */
  14809. Component.prototype.destroy = function () {
  14810. // should be implemented by the component
  14811. };
  14812. /**
  14813. * Test whether the component is resized since the last time _isResized() was
  14814. * called.
  14815. * @return {Boolean} Returns true if the component is resized
  14816. * @protected
  14817. */
  14818. Component.prototype._isResized = function () {
  14819. var resized = this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height;
  14820. this.props._previousWidth = this.props.width;
  14821. this.props._previousHeight = this.props.height;
  14822. return resized;
  14823. };
  14824. module.exports = Component;
  14825. /***/ },
  14826. /* 32 */
  14827. /***/ function(module, exports) {
  14828. "use strict";
  14829. /**
  14830. * used in Core to convert the options into a volatile variable
  14831. *
  14832. * @param {function} moment
  14833. * @param {Object} body
  14834. * @param {Array | Object} hiddenDates
  14835. */
  14836. exports.convertHiddenOptions = function (moment, body, hiddenDates) {
  14837. if (hiddenDates && !Array.isArray(hiddenDates)) {
  14838. return exports.convertHiddenOptions(moment, body, [hiddenDates]);
  14839. }
  14840. body.hiddenDates = [];
  14841. if (hiddenDates) {
  14842. if (Array.isArray(hiddenDates) == true) {
  14843. for (var i = 0; i < hiddenDates.length; i++) {
  14844. if (hiddenDates[i].repeat === undefined) {
  14845. var dateItem = {};
  14846. dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
  14847. dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
  14848. body.hiddenDates.push(dateItem);
  14849. }
  14850. }
  14851. body.hiddenDates.sort(function (a, b) {
  14852. return a.start - b.start;
  14853. }); // sort by start time
  14854. }
  14855. }
  14856. };
  14857. /**
  14858. * create new entrees for the repeating hidden dates
  14859. * @param {function} moment
  14860. * @param {Object} body
  14861. * @param {Array | Object} hiddenDates
  14862. */
  14863. exports.updateHiddenDates = function (moment, body, hiddenDates) {
  14864. if (hiddenDates && !Array.isArray(hiddenDates)) {
  14865. return exports.updateHiddenDates(moment, body, [hiddenDates]);
  14866. }
  14867. if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
  14868. exports.convertHiddenOptions(moment, body, hiddenDates);
  14869. var start = moment(body.range.start);
  14870. var end = moment(body.range.end);
  14871. var totalRange = body.range.end - body.range.start;
  14872. var pixelTime = totalRange / body.domProps.centerContainer.width;
  14873. for (var i = 0; i < hiddenDates.length; i++) {
  14874. if (hiddenDates[i].repeat !== undefined) {
  14875. var startDate = moment(hiddenDates[i].start);
  14876. var endDate = moment(hiddenDates[i].end);
  14877. if (startDate._d == "Invalid Date") {
  14878. throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
  14879. }
  14880. if (endDate._d == "Invalid Date") {
  14881. throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
  14882. }
  14883. var duration = endDate - startDate;
  14884. if (duration >= 4 * pixelTime) {
  14885. var offset = 0;
  14886. var runUntil = end.clone();
  14887. switch (hiddenDates[i].repeat) {
  14888. case "daily":
  14889. // case of time
  14890. if (startDate.day() != endDate.day()) {
  14891. offset = 1;
  14892. }
  14893. startDate.dayOfYear(start.dayOfYear());
  14894. startDate.year(start.year());
  14895. startDate.subtract(7, 'days');
  14896. endDate.dayOfYear(start.dayOfYear());
  14897. endDate.year(start.year());
  14898. endDate.subtract(7 - offset, 'days');
  14899. runUntil.add(1, 'weeks');
  14900. break;
  14901. case "weekly":
  14902. var dayOffset = endDate.diff(startDate, 'days');
  14903. var day = startDate.day();
  14904. // set the start date to the range.start
  14905. startDate.date(start.date());
  14906. startDate.month(start.month());
  14907. startDate.year(start.year());
  14908. endDate = startDate.clone();
  14909. // force
  14910. startDate.day(day);
  14911. endDate.day(day);
  14912. endDate.add(dayOffset, 'days');
  14913. startDate.subtract(1, 'weeks');
  14914. endDate.subtract(1, 'weeks');
  14915. runUntil.add(1, 'weeks');
  14916. break;
  14917. case "monthly":
  14918. if (startDate.month() != endDate.month()) {
  14919. offset = 1;
  14920. }
  14921. startDate.month(start.month());
  14922. startDate.year(start.year());
  14923. startDate.subtract(1, 'months');
  14924. endDate.month(start.month());
  14925. endDate.year(start.year());
  14926. endDate.subtract(1, 'months');
  14927. endDate.add(offset, 'months');
  14928. runUntil.add(1, 'months');
  14929. break;
  14930. case "yearly":
  14931. if (startDate.year() != endDate.year()) {
  14932. offset = 1;
  14933. }
  14934. startDate.year(start.year());
  14935. startDate.subtract(1, 'years');
  14936. endDate.year(start.year());
  14937. endDate.subtract(1, 'years');
  14938. endDate.add(offset, 'years');
  14939. runUntil.add(1, 'years');
  14940. break;
  14941. default:
  14942. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  14943. return;
  14944. }
  14945. while (startDate < runUntil) {
  14946. body.hiddenDates.push({ start: startDate.valueOf(), end: endDate.valueOf() });
  14947. switch (hiddenDates[i].repeat) {
  14948. case "daily":
  14949. startDate.add(1, 'days');
  14950. endDate.add(1, 'days');
  14951. break;
  14952. case "weekly":
  14953. startDate.add(1, 'weeks');
  14954. endDate.add(1, 'weeks');
  14955. break;
  14956. case "monthly":
  14957. startDate.add(1, 'months');
  14958. endDate.add(1, 'months');
  14959. break;
  14960. case "yearly":
  14961. startDate.add(1, 'y');
  14962. endDate.add(1, 'y');
  14963. break;
  14964. default:
  14965. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  14966. return;
  14967. }
  14968. }
  14969. body.hiddenDates.push({ start: startDate.valueOf(), end: endDate.valueOf() });
  14970. }
  14971. }
  14972. }
  14973. // remove duplicates, merge where possible
  14974. exports.removeDuplicates(body);
  14975. // ensure the new positions are not on hidden dates
  14976. var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
  14977. var endHidden = exports.isHidden(body.range.end, body.hiddenDates);
  14978. var rangeStart = body.range.start;
  14979. var rangeEnd = body.range.end;
  14980. if (startHidden.hidden == true) {
  14981. rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;
  14982. }
  14983. if (endHidden.hidden == true) {
  14984. rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;
  14985. }
  14986. if (startHidden.hidden == true || endHidden.hidden == true) {
  14987. body.range._applyRange(rangeStart, rangeEnd);
  14988. }
  14989. }
  14990. };
  14991. /**
  14992. * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
  14993. * Scales with N^2
  14994. * @param body
  14995. */
  14996. exports.removeDuplicates = function (body) {
  14997. var hiddenDates = body.hiddenDates;
  14998. var safeDates = [];
  14999. for (var i = 0; i < hiddenDates.length; i++) {
  15000. for (var j = 0; j < hiddenDates.length; j++) {
  15001. if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
  15002. // j inside i
  15003. if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  15004. hiddenDates[j].remove = true;
  15005. }
  15006. // j start inside i
  15007. else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
  15008. hiddenDates[i].end = hiddenDates[j].end;
  15009. hiddenDates[j].remove = true;
  15010. }
  15011. // j end inside i
  15012. else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  15013. hiddenDates[i].start = hiddenDates[j].start;
  15014. hiddenDates[j].remove = true;
  15015. }
  15016. }
  15017. }
  15018. }
  15019. for (var i = 0; i < hiddenDates.length; i++) {
  15020. if (hiddenDates[i].remove !== true) {
  15021. safeDates.push(hiddenDates[i]);
  15022. }
  15023. }
  15024. body.hiddenDates = safeDates;
  15025. body.hiddenDates.sort(function (a, b) {
  15026. return a.start - b.start;
  15027. }); // sort by start time
  15028. };
  15029. exports.printDates = function (dates) {
  15030. for (var i = 0; i < dates.length; i++) {
  15031. console.log(i, new Date(dates[i].start), new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
  15032. }
  15033. };
  15034. /**
  15035. * Used in TimeStep to avoid the hidden times.
  15036. * @param {function} moment
  15037. * @param {TimeStep} timeStep
  15038. * @param previousTime
  15039. */
  15040. exports.stepOverHiddenDates = function (moment, timeStep, previousTime) {
  15041. var stepInHidden = false;
  15042. var currentValue = timeStep.current.valueOf();
  15043. for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  15044. var startDate = timeStep.hiddenDates[i].start;
  15045. var endDate = timeStep.hiddenDates[i].end;
  15046. if (currentValue >= startDate && currentValue < endDate) {
  15047. stepInHidden = true;
  15048. break;
  15049. }
  15050. }
  15051. if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
  15052. var prevValue = moment(previousTime);
  15053. var newValue = moment(endDate);
  15054. //check if the next step should be major
  15055. if (prevValue.year() != newValue.year()) {
  15056. timeStep.switchedYear = true;
  15057. } else if (prevValue.month() != newValue.month()) {
  15058. timeStep.switchedMonth = true;
  15059. } else if (prevValue.dayOfYear() != newValue.dayOfYear()) {
  15060. timeStep.switchedDay = true;
  15061. }
  15062. timeStep.current = newValue;
  15063. }
  15064. };
  15065. ///**
  15066. // * Used in TimeStep to avoid the hidden times.
  15067. // * @param timeStep
  15068. // * @param previousTime
  15069. // */
  15070. //exports.checkFirstStep = function(timeStep) {
  15071. // var stepInHidden = false;
  15072. // var currentValue = timeStep.current.valueOf();
  15073. // for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  15074. // var startDate = timeStep.hiddenDates[i].start;
  15075. // var endDate = timeStep.hiddenDates[i].end;
  15076. // if (currentValue >= startDate && currentValue < endDate) {
  15077. // stepInHidden = true;
  15078. // break;
  15079. // }
  15080. // }
  15081. //
  15082. // if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
  15083. // var newValue = moment(endDate);
  15084. // timeStep.current = newValue.toDate();
  15085. // }
  15086. //};
  15087. /**
  15088. * replaces the Core toScreen methods
  15089. * @param Core
  15090. * @param time
  15091. * @param width
  15092. * @returns {number}
  15093. */
  15094. exports.toScreen = function (Core, time, width) {
  15095. if (Core.body.hiddenDates.length == 0) {
  15096. var conversion = Core.range.conversion(width);
  15097. return (time.valueOf() - conversion.offset) * conversion.scale;
  15098. } else {
  15099. var hidden = exports.isHidden(time, Core.body.hiddenDates);
  15100. if (hidden.hidden == true) {
  15101. time = hidden.startDate;
  15102. }
  15103. var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  15104. time = exports.correctTimeForHidden(Core.options.moment, Core.body.hiddenDates, Core.range, time);
  15105. var conversion = Core.range.conversion(width, duration);
  15106. return (time.valueOf() - conversion.offset) * conversion.scale;
  15107. }
  15108. };
  15109. /**
  15110. * Replaces the core toTime methods
  15111. * @param body
  15112. * @param range
  15113. * @param x
  15114. * @param width
  15115. * @returns {Date}
  15116. */
  15117. exports.toTime = function (Core, x, width) {
  15118. if (Core.body.hiddenDates.length == 0) {
  15119. var conversion = Core.range.conversion(width);
  15120. return new Date(x / conversion.scale + conversion.offset);
  15121. } else {
  15122. var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  15123. var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
  15124. var partialDuration = totalDuration * x / width;
  15125. var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
  15126. var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
  15127. return newTime;
  15128. }
  15129. };
  15130. /**
  15131. * Support function
  15132. *
  15133. * @param hiddenDates
  15134. * @param range
  15135. * @returns {number}
  15136. */
  15137. exports.getHiddenDurationBetween = function (hiddenDates, start, end) {
  15138. var duration = 0;
  15139. for (var i = 0; i < hiddenDates.length; i++) {
  15140. var startDate = hiddenDates[i].start;
  15141. var endDate = hiddenDates[i].end;
  15142. // if time after the cutout, and the
  15143. if (startDate >= start && endDate < end) {
  15144. duration += endDate - startDate;
  15145. }
  15146. }
  15147. return duration;
  15148. };
  15149. /**
  15150. * Support function
  15151. * @param moment
  15152. * @param hiddenDates
  15153. * @param range
  15154. * @param time
  15155. * @returns {{duration: number, time: *, offset: number}}
  15156. */
  15157. exports.correctTimeForHidden = function (moment, hiddenDates, range, time) {
  15158. time = moment(time).toDate().valueOf();
  15159. time -= exports.getHiddenDurationBefore(moment, hiddenDates, range, time);
  15160. return time;
  15161. };
  15162. exports.getHiddenDurationBefore = function (moment, hiddenDates, range, time) {
  15163. var timeOffset = 0;
  15164. time = moment(time).toDate().valueOf();
  15165. for (var i = 0; i < hiddenDates.length; i++) {
  15166. var startDate = hiddenDates[i].start;
  15167. var endDate = hiddenDates[i].end;
  15168. // if time after the cutout, and the
  15169. if (startDate >= range.start && endDate < range.end) {
  15170. if (time >= endDate) {
  15171. timeOffset += endDate - startDate;
  15172. }
  15173. }
  15174. }
  15175. return timeOffset;
  15176. };
  15177. /**
  15178. * sum the duration from start to finish, including the hidden duration,
  15179. * until the required amount has been reached, return the accumulated hidden duration
  15180. * @param hiddenDates
  15181. * @param range
  15182. * @param time
  15183. * @returns {{duration: number, time: *, offset: number}}
  15184. */
  15185. exports.getAccumulatedHiddenDuration = function (hiddenDates, range, requiredDuration) {
  15186. var hiddenDuration = 0;
  15187. var duration = 0;
  15188. var previousPoint = range.start;
  15189. //exports.printDates(hiddenDates)
  15190. for (var i = 0; i < hiddenDates.length; i++) {
  15191. var startDate = hiddenDates[i].start;
  15192. var endDate = hiddenDates[i].end;
  15193. // if time after the cutout, and the
  15194. if (startDate >= range.start && endDate < range.end) {
  15195. duration += startDate - previousPoint;
  15196. previousPoint = endDate;
  15197. if (duration >= requiredDuration) {
  15198. break;
  15199. } else {
  15200. hiddenDuration += endDate - startDate;
  15201. }
  15202. }
  15203. }
  15204. return hiddenDuration;
  15205. };
  15206. /**
  15207. * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
  15208. * @param hiddenDates
  15209. * @param time
  15210. * @param direction
  15211. * @param correctionEnabled
  15212. * @returns {*}
  15213. */
  15214. exports.snapAwayFromHidden = function (hiddenDates, time, direction, correctionEnabled) {
  15215. var isHidden = exports.isHidden(time, hiddenDates);
  15216. if (isHidden.hidden == true) {
  15217. if (direction < 0) {
  15218. if (correctionEnabled == true) {
  15219. return isHidden.startDate - (isHidden.endDate - time) - 1;
  15220. } else {
  15221. return isHidden.startDate - 1;
  15222. }
  15223. } else {
  15224. if (correctionEnabled == true) {
  15225. return isHidden.endDate + (time - isHidden.startDate) + 1;
  15226. } else {
  15227. return isHidden.endDate + 1;
  15228. }
  15229. }
  15230. } else {
  15231. return time;
  15232. }
  15233. };
  15234. /**
  15235. * Check if a time is hidden
  15236. *
  15237. * @param time
  15238. * @param hiddenDates
  15239. * @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
  15240. */
  15241. exports.isHidden = function (time, hiddenDates) {
  15242. for (var i = 0; i < hiddenDates.length; i++) {
  15243. var startDate = hiddenDates[i].start;
  15244. var endDate = hiddenDates[i].end;
  15245. if (time >= startDate && time < endDate) {
  15246. // if the start is entering a hidden zone
  15247. return { hidden: true, startDate: startDate, endDate: endDate };
  15248. break;
  15249. }
  15250. }
  15251. return { hidden: false, startDate: startDate, endDate: endDate };
  15252. };
  15253. /***/ },
  15254. /* 33 */
  15255. /***/ function(module, exports, __webpack_require__) {
  15256. 'use strict';
  15257. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  15258. var Emitter = __webpack_require__(13);
  15259. var Hammer = __webpack_require__(20);
  15260. var hammerUtil = __webpack_require__(28);
  15261. var util = __webpack_require__(1);
  15262. var DataSet = __webpack_require__(9);
  15263. var DataView = __webpack_require__(11);
  15264. var Range = __webpack_require__(30);
  15265. var ItemSet = __webpack_require__(34);
  15266. var TimeAxis = __webpack_require__(44);
  15267. var Activator = __webpack_require__(45);
  15268. var DateUtil = __webpack_require__(32);
  15269. var CustomTime = __webpack_require__(46);
  15270. /**
  15271. * Create a timeline visualization
  15272. * @constructor
  15273. */
  15274. function Core() {}
  15275. // turn Core into an event emitter
  15276. Emitter(Core.prototype);
  15277. /**
  15278. * Create the main DOM for the Core: a root panel containing left, right,
  15279. * top, bottom, content, and background panel.
  15280. * @param {Element} container The container element where the Core will
  15281. * be attached.
  15282. * @protected
  15283. */
  15284. Core.prototype._create = function (container) {
  15285. this.dom = {};
  15286. this.dom.container = container;
  15287. this.dom.root = document.createElement('div');
  15288. this.dom.background = document.createElement('div');
  15289. this.dom.backgroundVertical = document.createElement('div');
  15290. this.dom.backgroundHorizontal = document.createElement('div');
  15291. this.dom.centerContainer = document.createElement('div');
  15292. this.dom.leftContainer = document.createElement('div');
  15293. this.dom.rightContainer = document.createElement('div');
  15294. this.dom.center = document.createElement('div');
  15295. this.dom.left = document.createElement('div');
  15296. this.dom.right = document.createElement('div');
  15297. this.dom.top = document.createElement('div');
  15298. this.dom.bottom = document.createElement('div');
  15299. this.dom.shadowTop = document.createElement('div');
  15300. this.dom.shadowBottom = document.createElement('div');
  15301. this.dom.shadowTopLeft = document.createElement('div');
  15302. this.dom.shadowBottomLeft = document.createElement('div');
  15303. this.dom.shadowTopRight = document.createElement('div');
  15304. this.dom.shadowBottomRight = document.createElement('div');
  15305. this.dom.root.className = 'vis-timeline';
  15306. this.dom.background.className = 'vis-panel vis-background';
  15307. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
  15308. this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
  15309. this.dom.centerContainer.className = 'vis-panel vis-center';
  15310. this.dom.leftContainer.className = 'vis-panel vis-left';
  15311. this.dom.rightContainer.className = 'vis-panel vis-right';
  15312. this.dom.top.className = 'vis-panel vis-top';
  15313. this.dom.bottom.className = 'vis-panel vis-bottom';
  15314. this.dom.left.className = 'vis-content';
  15315. this.dom.center.className = 'vis-content';
  15316. this.dom.right.className = 'vis-content';
  15317. this.dom.shadowTop.className = 'vis-shadow vis-top';
  15318. this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
  15319. this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
  15320. this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
  15321. this.dom.shadowTopRight.className = 'vis-shadow vis-top';
  15322. this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
  15323. this.dom.root.appendChild(this.dom.background);
  15324. this.dom.root.appendChild(this.dom.backgroundVertical);
  15325. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  15326. this.dom.root.appendChild(this.dom.centerContainer);
  15327. this.dom.root.appendChild(this.dom.leftContainer);
  15328. this.dom.root.appendChild(this.dom.rightContainer);
  15329. this.dom.root.appendChild(this.dom.top);
  15330. this.dom.root.appendChild(this.dom.bottom);
  15331. this.dom.centerContainer.appendChild(this.dom.center);
  15332. this.dom.leftContainer.appendChild(this.dom.left);
  15333. this.dom.rightContainer.appendChild(this.dom.right);
  15334. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  15335. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  15336. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  15337. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  15338. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  15339. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  15340. this.on('rangechange', function () {
  15341. if (this.initialDrawDone === true) {
  15342. this._redraw(); // this allows overriding the _redraw method
  15343. }
  15344. }.bind(this));
  15345. this.on('touch', this._onTouch.bind(this));
  15346. this.on('pan', this._onDrag.bind(this));
  15347. var me = this;
  15348. this.on('_change', function (properties) {
  15349. if (properties && properties.queue == true) {
  15350. // redraw once on next tick
  15351. if (!me._redrawTimer) {
  15352. me._redrawTimer = setTimeout(function () {
  15353. me._redrawTimer = null;
  15354. me._redraw();
  15355. }, 0);
  15356. }
  15357. } else {
  15358. // redraw immediately
  15359. me._redraw();
  15360. }
  15361. });
  15362. // create event listeners for all interesting events, these events will be
  15363. // emitted via emitter
  15364. this.hammer = new Hammer(this.dom.root);
  15365. var pinchRecognizer = this.hammer.get('pinch').set({ enable: true });
  15366. hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
  15367. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  15368. this.listeners = {};
  15369. var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend'
  15370. // TODO: cleanup
  15371. //'touch', 'pinch',
  15372. //'tap', 'doubletap', 'hold',
  15373. //'dragstart', 'drag', 'dragend',
  15374. //'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  15375. ];
  15376. events.forEach(function (type) {
  15377. var listener = function listener(event) {
  15378. if (me.isActive()) {
  15379. me.emit(type, event);
  15380. }
  15381. };
  15382. me.hammer.on(type, listener);
  15383. me.listeners[type] = listener;
  15384. });
  15385. // emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
  15386. hammerUtil.onTouch(this.hammer, function (event) {
  15387. me.emit('touch', event);
  15388. }.bind(this));
  15389. // emulate a release event (emitted after a pan, pinch, tap, or press)
  15390. hammerUtil.onRelease(this.hammer, function (event) {
  15391. me.emit('release', event);
  15392. }.bind(this));
  15393. function onMouseWheel(event) {
  15394. if (me.isActive()) {
  15395. me.emit('mousewheel', event);
  15396. }
  15397. }
  15398. this.dom.root.addEventListener('mousewheel', onMouseWheel);
  15399. this.dom.root.addEventListener('DOMMouseScroll', onMouseWheel);
  15400. // size properties of each of the panels
  15401. this.props = {
  15402. root: {},
  15403. background: {},
  15404. centerContainer: {},
  15405. leftContainer: {},
  15406. rightContainer: {},
  15407. center: {},
  15408. left: {},
  15409. right: {},
  15410. top: {},
  15411. bottom: {},
  15412. border: {},
  15413. scrollTop: 0,
  15414. scrollTopMin: 0
  15415. };
  15416. this.customTimes = [];
  15417. // store state information needed for touch events
  15418. this.touch = {};
  15419. this.redrawCount = 0;
  15420. this.initialDrawDone = false;
  15421. // attach the root panel to the provided container
  15422. if (!container) throw new Error('No container provided');
  15423. container.appendChild(this.dom.root);
  15424. };
  15425. /**
  15426. * Set options. Options will be passed to all components loaded in the Timeline.
  15427. * @param {Object} [options]
  15428. * {String} orientation
  15429. * Vertical orientation for the Timeline,
  15430. * can be 'bottom' (default) or 'top'.
  15431. * {String | Number} width
  15432. * Width for the timeline, a number in pixels or
  15433. * a css string like '1000px' or '75%'. '100%' by default.
  15434. * {String | Number} height
  15435. * Fixed height for the Timeline, a number in pixels or
  15436. * a css string like '400px' or '75%'. If undefined,
  15437. * The Timeline will automatically size such that
  15438. * its contents fit.
  15439. * {String | Number} minHeight
  15440. * Minimum height for the Timeline, a number in pixels or
  15441. * a css string like '400px' or '75%'.
  15442. * {String | Number} maxHeight
  15443. * Maximum height for the Timeline, a number in pixels or
  15444. * a css string like '400px' or '75%'.
  15445. * {Number | Date | String} start
  15446. * Start date for the visible window
  15447. * {Number | Date | String} end
  15448. * End date for the visible window
  15449. */
  15450. Core.prototype.setOptions = function (options) {
  15451. if (options) {
  15452. // copy the known options
  15453. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates', 'locale', 'locales', 'moment', 'rtl', 'throttleRedraw'];
  15454. util.selectiveExtend(fields, this.options, options);
  15455. if (this.options.rtl) {
  15456. var contentContainer = this.dom.leftContainer;
  15457. this.dom.leftContainer = this.dom.rightContainer;
  15458. this.dom.rightContainer = contentContainer;
  15459. this.dom.container.style.direction = "rtl";
  15460. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical-rtl';
  15461. }
  15462. this.options.orientation = { item: undefined, axis: undefined };
  15463. if ('orientation' in options) {
  15464. if (typeof options.orientation === 'string') {
  15465. this.options.orientation = {
  15466. item: options.orientation,
  15467. axis: options.orientation
  15468. };
  15469. } else if (_typeof(options.orientation) === 'object') {
  15470. if ('item' in options.orientation) {
  15471. this.options.orientation.item = options.orientation.item;
  15472. }
  15473. if ('axis' in options.orientation) {
  15474. this.options.orientation.axis = options.orientation.axis;
  15475. }
  15476. }
  15477. }
  15478. if (this.options.orientation.axis === 'both') {
  15479. if (!this.timeAxis2) {
  15480. var timeAxis2 = this.timeAxis2 = new TimeAxis(this.body);
  15481. timeAxis2.setOptions = function (options) {
  15482. var _options = options ? util.extend({}, options) : {};
  15483. _options.orientation = 'top'; // override the orientation option, always top
  15484. TimeAxis.prototype.setOptions.call(timeAxis2, _options);
  15485. };
  15486. this.components.push(timeAxis2);
  15487. }
  15488. } else {
  15489. if (this.timeAxis2) {
  15490. var index = this.components.indexOf(this.timeAxis2);
  15491. if (index !== -1) {
  15492. this.components.splice(index, 1);
  15493. }
  15494. this.timeAxis2.destroy();
  15495. this.timeAxis2 = null;
  15496. }
  15497. }
  15498. // if the graph2d's drawPoints is a function delegate the callback to the onRender property
  15499. if (typeof options.drawPoints == 'function') {
  15500. options.drawPoints = {
  15501. onRender: options.drawPoints
  15502. };
  15503. }
  15504. if ('hiddenDates' in this.options) {
  15505. DateUtil.convertHiddenOptions(this.options.moment, this.body, this.options.hiddenDates);
  15506. }
  15507. if ('clickToUse' in options) {
  15508. if (options.clickToUse) {
  15509. if (!this.activator) {
  15510. this.activator = new Activator(this.dom.root);
  15511. }
  15512. } else {
  15513. if (this.activator) {
  15514. this.activator.destroy();
  15515. delete this.activator;
  15516. }
  15517. }
  15518. }
  15519. if ('showCustomTime' in options) {
  15520. throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])');
  15521. }
  15522. // enable/disable autoResize
  15523. this._initAutoResize();
  15524. }
  15525. // propagate options to all components
  15526. this.components.forEach(function (component) {
  15527. return component.setOptions(options);
  15528. });
  15529. // enable/disable configure
  15530. if ('configure' in options) {
  15531. if (!this.configurator) {
  15532. this.configurator = this._createConfigurator();
  15533. }
  15534. this.configurator.setOptions(options.configure);
  15535. // collect the settings of all components, and pass them to the configuration system
  15536. var appliedOptions = util.deepExtend({}, this.options);
  15537. this.components.forEach(function (component) {
  15538. util.deepExtend(appliedOptions, component.options);
  15539. });
  15540. this.configurator.setModuleOptions({ global: appliedOptions });
  15541. }
  15542. // override redraw with a throttled version
  15543. if (!this._origRedraw) {
  15544. this._origRedraw = this._redraw.bind(this);
  15545. this._redraw = util.throttle(this._origRedraw, this.options.throttleRedraw);
  15546. } else {
  15547. // Not the initial run: redraw everything
  15548. this._redraw();
  15549. }
  15550. };
  15551. /**
  15552. * Returns true when the Timeline is active.
  15553. * @returns {boolean}
  15554. */
  15555. Core.prototype.isActive = function () {
  15556. return !this.activator || this.activator.active;
  15557. };
  15558. /**
  15559. * Destroy the Core, clean up all DOM elements and event listeners.
  15560. */
  15561. Core.prototype.destroy = function () {
  15562. // unbind datasets
  15563. this.setItems(null);
  15564. this.setGroups(null);
  15565. // remove all event listeners
  15566. this.off();
  15567. // stop checking for changed size
  15568. this._stopAutoResize();
  15569. // remove from DOM
  15570. if (this.dom.root.parentNode) {
  15571. this.dom.root.parentNode.removeChild(this.dom.root);
  15572. }
  15573. this.dom = null;
  15574. // remove Activator
  15575. if (this.activator) {
  15576. this.activator.destroy();
  15577. delete this.activator;
  15578. }
  15579. // cleanup hammer touch events
  15580. for (var event in this.listeners) {
  15581. if (this.listeners.hasOwnProperty(event)) {
  15582. delete this.listeners[event];
  15583. }
  15584. }
  15585. this.listeners = null;
  15586. this.hammer = null;
  15587. // give all components the opportunity to cleanup
  15588. this.components.forEach(function (component) {
  15589. return component.destroy();
  15590. });
  15591. this.body = null;
  15592. };
  15593. /**
  15594. * Set a custom time bar
  15595. * @param {Date} time
  15596. * @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
  15597. */
  15598. Core.prototype.setCustomTime = function (time, id) {
  15599. var customTimes = this.customTimes.filter(function (component) {
  15600. return id === component.options.id;
  15601. });
  15602. if (customTimes.length === 0) {
  15603. throw new Error('No custom time bar found with id ' + JSON.stringify(id));
  15604. }
  15605. if (customTimes.length > 0) {
  15606. customTimes[0].setCustomTime(time);
  15607. }
  15608. };
  15609. /**
  15610. * Retrieve the current custom time.
  15611. * @param {number} [id=undefined] Id of the custom time bar.
  15612. * @return {Date | undefined} customTime
  15613. */
  15614. Core.prototype.getCustomTime = function (id) {
  15615. var customTimes = this.customTimes.filter(function (component) {
  15616. return component.options.id === id;
  15617. });
  15618. if (customTimes.length === 0) {
  15619. throw new Error('No custom time bar found with id ' + JSON.stringify(id));
  15620. }
  15621. return customTimes[0].getCustomTime();
  15622. };
  15623. /**
  15624. * Set a custom title for the custom time bar.
  15625. * @param {String} [title] Custom title
  15626. * @param {number} [id=undefined] Id of the custom time bar.
  15627. */
  15628. Core.prototype.setCustomTimeTitle = function (title, id) {
  15629. var customTimes = this.customTimes.filter(function (component) {
  15630. return component.options.id === id;
  15631. });
  15632. if (customTimes.length === 0) {
  15633. throw new Error('No custom time bar found with id ' + JSON.stringify(id));
  15634. }
  15635. if (customTimes.length > 0) {
  15636. return customTimes[0].setCustomTitle(title);
  15637. }
  15638. };
  15639. /**
  15640. * Retrieve meta information from an event.
  15641. * Should be overridden by classes extending Core
  15642. * @param {Event} event
  15643. * @return {Object} An object with related information.
  15644. */
  15645. Core.prototype.getEventProperties = function (event) {
  15646. return { event: event };
  15647. };
  15648. /**
  15649. * Add custom vertical bar
  15650. * @param {Date | String | Number} [time] A Date, unix timestamp, or
  15651. * ISO date string. Time point where
  15652. * the new bar should be placed.
  15653. * If not provided, `new Date()` will
  15654. * be used.
  15655. * @param {Number | String} [id=undefined] Id of the new bar. Optional
  15656. * @return {Number | String} Returns the id of the new bar
  15657. */
  15658. Core.prototype.addCustomTime = function (time, id) {
  15659. var timestamp = time !== undefined ? util.convert(time, 'Date').valueOf() : new Date();
  15660. var exists = this.customTimes.some(function (customTime) {
  15661. return customTime.options.id === id;
  15662. });
  15663. if (exists) {
  15664. throw new Error('A custom time with id ' + JSON.stringify(id) + ' already exists');
  15665. }
  15666. var customTime = new CustomTime(this.body, util.extend({}, this.options, {
  15667. time: timestamp,
  15668. id: id
  15669. }));
  15670. this.customTimes.push(customTime);
  15671. this.components.push(customTime);
  15672. this._redraw();
  15673. return id;
  15674. };
  15675. /**
  15676. * Remove previously added custom bar
  15677. * @param {int} id ID of the custom bar to be removed
  15678. * @return {boolean} True if the bar exists and is removed, false otherwise
  15679. */
  15680. Core.prototype.removeCustomTime = function (id) {
  15681. var customTimes = this.customTimes.filter(function (bar) {
  15682. return bar.options.id === id;
  15683. });
  15684. if (customTimes.length === 0) {
  15685. throw new Error('No custom time bar found with id ' + JSON.stringify(id));
  15686. }
  15687. customTimes.forEach(function (customTime) {
  15688. this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
  15689. this.components.splice(this.components.indexOf(customTime), 1);
  15690. customTime.destroy();
  15691. }.bind(this));
  15692. };
  15693. /**
  15694. * Get the id's of the currently visible items.
  15695. * @returns {Array} The ids of the visible items
  15696. */
  15697. Core.prototype.getVisibleItems = function () {
  15698. return this.itemSet && this.itemSet.getVisibleItems() || [];
  15699. };
  15700. /**
  15701. * Set Core window such that it fits all items
  15702. * @param {Object} [options] Available options:
  15703. * `animation: boolean | {duration: number, easingFunction: string}`
  15704. * If true (default), the range is animated
  15705. * smoothly to the new window. An object can be
  15706. * provided to specify duration and easing function.
  15707. * Default duration is 500 ms, and default easing
  15708. * function is 'easeInOutQuad'.
  15709. */
  15710. Core.prototype.fit = function (options) {
  15711. var range = this.getDataRange();
  15712. // skip range set if there is no min and max date
  15713. if (range.min === null && range.max === null) {
  15714. return;
  15715. }
  15716. // apply a margin of 1% left and right of the data
  15717. var interval = range.max - range.min;
  15718. var min = new Date(range.min.valueOf() - interval * 0.01);
  15719. var max = new Date(range.max.valueOf() + interval * 0.01);
  15720. var animation = options && options.animation !== undefined ? options.animation : true;
  15721. this.range.setRange(min, max, animation);
  15722. };
  15723. /**
  15724. * Calculate the data range of the items start and end dates
  15725. * @returns {{min: Date | null, max: Date | null}}
  15726. * @protected
  15727. */
  15728. Core.prototype.getDataRange = function () {
  15729. // must be implemented by Timeline and Graph2d
  15730. throw new Error('Cannot invoke abstract method getDataRange');
  15731. };
  15732. /**
  15733. * Set the visible window. Both parameters are optional, you can change only
  15734. * start or only end. Syntax:
  15735. *
  15736. * TimeLine.setWindow(start, end)
  15737. * TimeLine.setWindow(start, end, options)
  15738. * TimeLine.setWindow(range)
  15739. *
  15740. * Where start and end can be a Date, number, or string, and range is an
  15741. * object with properties start and end.
  15742. *
  15743. * @param {Date | Number | String | Object} [start] Start date of visible window
  15744. * @param {Date | Number | String} [end] End date of visible window
  15745. * @param {Object} [options] Available options:
  15746. * `animation: boolean | {duration: number, easingFunction: string}`
  15747. * If true (default), the range is animated
  15748. * smoothly to the new window. An object can be
  15749. * provided to specify duration and easing function.
  15750. * Default duration is 500 ms, and default easing
  15751. * function is 'easeInOutQuad'.
  15752. */
  15753. Core.prototype.setWindow = function (start, end, options) {
  15754. var animation;
  15755. if (arguments.length == 1) {
  15756. var range = arguments[0];
  15757. animation = range.animation !== undefined ? range.animation : true;
  15758. this.range.setRange(range.start, range.end, animation);
  15759. } else {
  15760. animation = options && options.animation !== undefined ? options.animation : true;
  15761. this.range.setRange(start, end, animation);
  15762. }
  15763. };
  15764. /**
  15765. * Move the window such that given time is centered on screen.
  15766. * @param {Date | Number | String} time
  15767. * @param {Object} [options] Available options:
  15768. * `animation: boolean | {duration: number, easingFunction: string}`
  15769. * If true (default), the range is animated
  15770. * smoothly to the new window. An object can be
  15771. * provided to specify duration and easing function.
  15772. * Default duration is 500 ms, and default easing
  15773. * function is 'easeInOutQuad'.
  15774. */
  15775. Core.prototype.moveTo = function (time, options) {
  15776. var interval = this.range.end - this.range.start;
  15777. var t = util.convert(time, 'Date').valueOf();
  15778. var start = t - interval / 2;
  15779. var end = t + interval / 2;
  15780. var animation = options && options.animation !== undefined ? options.animation : true;
  15781. this.range.setRange(start, end, animation);
  15782. };
  15783. /**
  15784. * Get the visible window
  15785. * @return {{start: Date, end: Date}} Visible range
  15786. */
  15787. Core.prototype.getWindow = function () {
  15788. var range = this.range.getRange();
  15789. return {
  15790. start: new Date(range.start),
  15791. end: new Date(range.end)
  15792. };
  15793. };
  15794. /**
  15795. * Force a redraw. Can be overridden by implementations of Core
  15796. *
  15797. * Note: this function will be overridden on construction with a trottled version
  15798. */
  15799. Core.prototype.redraw = function () {
  15800. this._redraw();
  15801. };
  15802. /**
  15803. * Redraw for internal use. Redraws all components. See also the public
  15804. * method redraw.
  15805. * @protected
  15806. */
  15807. Core.prototype._redraw = function () {
  15808. this.redrawCount++;
  15809. var resized = false;
  15810. var options = this.options;
  15811. var props = this.props;
  15812. var dom = this.dom;
  15813. if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
  15814. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  15815. // update class names
  15816. if (options.orientation == 'top') {
  15817. util.addClassName(dom.root, 'vis-top');
  15818. util.removeClassName(dom.root, 'vis-bottom');
  15819. } else {
  15820. util.removeClassName(dom.root, 'vis-top');
  15821. util.addClassName(dom.root, 'vis-bottom');
  15822. }
  15823. // update root width and height options
  15824. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  15825. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  15826. dom.root.style.width = util.option.asSize(options.width, '');
  15827. // calculate border widths
  15828. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  15829. props.border.right = props.border.left;
  15830. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  15831. props.border.bottom = props.border.top;
  15832. var borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight;
  15833. var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  15834. // workaround for a bug in IE: the clientWidth of an element with
  15835. // a height:0px and overflow:hidden is not calculated and always has value 0
  15836. if (dom.centerContainer.clientHeight === 0) {
  15837. props.border.left = props.border.top;
  15838. props.border.right = props.border.left;
  15839. }
  15840. if (dom.root.clientHeight === 0) {
  15841. borderRootWidth = borderRootHeight;
  15842. }
  15843. // calculate the heights. If any of the side panels is empty, we set the height to
  15844. // minus the border width, such that the border will be invisible
  15845. props.center.height = dom.center.offsetHeight;
  15846. props.left.height = dom.left.offsetHeight;
  15847. props.right.height = dom.right.offsetHeight;
  15848. props.top.height = dom.top.clientHeight || -props.border.top;
  15849. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  15850. // TODO: compensate borders when any of the panels is empty.
  15851. // apply auto height
  15852. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  15853. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  15854. var autoHeight = props.top.height + contentHeight + props.bottom.height + borderRootHeight + props.border.top + props.border.bottom;
  15855. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  15856. // calculate heights of the content panels
  15857. props.root.height = dom.root.offsetHeight;
  15858. props.background.height = props.root.height - borderRootHeight;
  15859. var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight;
  15860. props.centerContainer.height = containerHeight;
  15861. props.leftContainer.height = containerHeight;
  15862. props.rightContainer.height = props.leftContainer.height;
  15863. // calculate the widths of the panels
  15864. props.root.width = dom.root.offsetWidth;
  15865. props.background.width = props.root.width - borderRootWidth;
  15866. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  15867. props.leftContainer.width = props.left.width;
  15868. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  15869. props.rightContainer.width = props.right.width;
  15870. var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth;
  15871. props.center.width = centerWidth;
  15872. props.centerContainer.width = centerWidth;
  15873. props.top.width = centerWidth;
  15874. props.bottom.width = centerWidth;
  15875. // resize the panels
  15876. dom.background.style.height = props.background.height + 'px';
  15877. dom.backgroundVertical.style.height = props.background.height + 'px';
  15878. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  15879. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  15880. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  15881. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  15882. dom.background.style.width = props.background.width + 'px';
  15883. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  15884. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  15885. dom.centerContainer.style.width = props.center.width + 'px';
  15886. dom.top.style.width = props.top.width + 'px';
  15887. dom.bottom.style.width = props.bottom.width + 'px';
  15888. // reposition the panels
  15889. dom.background.style.left = '0';
  15890. dom.background.style.top = '0';
  15891. dom.backgroundVertical.style.left = props.left.width + props.border.left + 'px';
  15892. dom.backgroundVertical.style.top = '0';
  15893. dom.backgroundHorizontal.style.left = '0';
  15894. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  15895. dom.centerContainer.style.left = props.left.width + 'px';
  15896. dom.centerContainer.style.top = props.top.height + 'px';
  15897. dom.leftContainer.style.left = '0';
  15898. dom.leftContainer.style.top = props.top.height + 'px';
  15899. dom.rightContainer.style.left = props.left.width + props.center.width + 'px';
  15900. dom.rightContainer.style.top = props.top.height + 'px';
  15901. dom.top.style.left = props.left.width + 'px';
  15902. dom.top.style.top = '0';
  15903. dom.bottom.style.left = props.left.width + 'px';
  15904. dom.bottom.style.top = props.top.height + props.centerContainer.height + 'px';
  15905. // update the scrollTop, feasible range for the offset can be changed
  15906. // when the height of the Core or of the contents of the center changed
  15907. this._updateScrollTop();
  15908. // reposition the scrollable contents
  15909. var offset = this.props.scrollTop;
  15910. if (options.orientation.item != 'top') {
  15911. offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0);
  15912. }
  15913. dom.center.style.left = '0';
  15914. dom.center.style.top = offset + 'px';
  15915. dom.left.style.left = '0';
  15916. dom.left.style.top = offset + 'px';
  15917. dom.right.style.left = '0';
  15918. dom.right.style.top = offset + 'px';
  15919. // show shadows when vertical scrolling is available
  15920. var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : '';
  15921. var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : '';
  15922. dom.shadowTop.style.visibility = visibilityTop;
  15923. dom.shadowBottom.style.visibility = visibilityBottom;
  15924. dom.shadowTopLeft.style.visibility = visibilityTop;
  15925. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  15926. dom.shadowTopRight.style.visibility = visibilityTop;
  15927. dom.shadowBottomRight.style.visibility = visibilityBottom;
  15928. // enable/disable vertical panning
  15929. var contentsOverflow = this.props.center.height > this.props.centerContainer.height;
  15930. this.hammer.get('pan').set({
  15931. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  15932. });
  15933. // redraw all components
  15934. this.components.forEach(function (component) {
  15935. resized = component.redraw() || resized;
  15936. });
  15937. var MAX_REDRAW = 5;
  15938. if (resized) {
  15939. if (this.redrawCount < MAX_REDRAW) {
  15940. this.body.emitter.emit('_change');
  15941. return;
  15942. } else {
  15943. console.log('WARNING: infinite loop in redraw?');
  15944. }
  15945. } else {
  15946. this.redrawCount = 0;
  15947. }
  15948. this.initialDrawDone = true;
  15949. //Emit public 'changed' event for UI updates, see issue #1592
  15950. this.body.emitter.emit("changed");
  15951. };
  15952. // TODO: deprecated since version 1.1.0, remove some day
  15953. Core.prototype.repaint = function () {
  15954. throw new Error('Function repaint is deprecated. Use redraw instead.');
  15955. };
  15956. /**
  15957. * Set a current time. This can be used for example to ensure that a client's
  15958. * time is synchronized with a shared server time.
  15959. * Only applicable when option `showCurrentTime` is true.
  15960. * @param {Date | String | Number} time A Date, unix timestamp, or
  15961. * ISO date string.
  15962. */
  15963. Core.prototype.setCurrentTime = function (time) {
  15964. if (!this.currentTime) {
  15965. throw new Error('Option showCurrentTime must be true');
  15966. }
  15967. this.currentTime.setCurrentTime(time);
  15968. };
  15969. /**
  15970. * Get the current time.
  15971. * Only applicable when option `showCurrentTime` is true.
  15972. * @return {Date} Returns the current time.
  15973. */
  15974. Core.prototype.getCurrentTime = function () {
  15975. if (!this.currentTime) {
  15976. throw new Error('Option showCurrentTime must be true');
  15977. }
  15978. return this.currentTime.getCurrentTime();
  15979. };
  15980. /**
  15981. * Convert a position on screen (pixels) to a datetime
  15982. * @param {int} x Position on the screen in pixels
  15983. * @return {Date} time The datetime the corresponds with given position x
  15984. * @protected
  15985. */
  15986. // TODO: move this function to Range
  15987. Core.prototype._toTime = function (x) {
  15988. return DateUtil.toTime(this, x, this.props.center.width);
  15989. };
  15990. /**
  15991. * Convert a position on the global screen (pixels) to a datetime
  15992. * @param {int} x Position on the screen in pixels
  15993. * @return {Date} time The datetime the corresponds with given position x
  15994. * @protected
  15995. */
  15996. // TODO: move this function to Range
  15997. Core.prototype._toGlobalTime = function (x) {
  15998. return DateUtil.toTime(this, x, this.props.root.width);
  15999. //var conversion = this.range.conversion(this.props.root.width);
  16000. //return new Date(x / conversion.scale + conversion.offset);
  16001. };
  16002. /**
  16003. * Convert a datetime (Date object) into a position on the screen
  16004. * @param {Date} time A date
  16005. * @return {int} x The position on the screen in pixels which corresponds
  16006. * with the given date.
  16007. * @protected
  16008. */
  16009. // TODO: move this function to Range
  16010. Core.prototype._toScreen = function (time) {
  16011. return DateUtil.toScreen(this, time, this.props.center.width);
  16012. };
  16013. /**
  16014. * Convert a datetime (Date object) into a position on the root
  16015. * This is used to get the pixel density estimate for the screen, not the center panel
  16016. * @param {Date} time A date
  16017. * @return {int} x The position on root in pixels which corresponds
  16018. * with the given date.
  16019. * @protected
  16020. */
  16021. // TODO: move this function to Range
  16022. Core.prototype._toGlobalScreen = function (time) {
  16023. return DateUtil.toScreen(this, time, this.props.root.width);
  16024. //var conversion = this.range.conversion(this.props.root.width);
  16025. //return (time.valueOf() - conversion.offset) * conversion.scale;
  16026. };
  16027. /**
  16028. * Initialize watching when option autoResize is true
  16029. * @private
  16030. */
  16031. Core.prototype._initAutoResize = function () {
  16032. if (this.options.autoResize == true) {
  16033. this._startAutoResize();
  16034. } else {
  16035. this._stopAutoResize();
  16036. }
  16037. };
  16038. /**
  16039. * Watch for changes in the size of the container. On resize, the Panel will
  16040. * automatically redraw itself.
  16041. * @private
  16042. */
  16043. Core.prototype._startAutoResize = function () {
  16044. var me = this;
  16045. this._stopAutoResize();
  16046. this._onResize = function () {
  16047. if (me.options.autoResize != true) {
  16048. // stop watching when the option autoResize is changed to false
  16049. me._stopAutoResize();
  16050. return;
  16051. }
  16052. if (me.dom.root) {
  16053. // check whether the frame is resized
  16054. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  16055. // IE does not restore the clientWidth from 0 to the actual width after
  16056. // changing the timeline's container display style from none to visible
  16057. if (me.dom.root.offsetWidth != me.props.lastWidth || me.dom.root.offsetHeight != me.props.lastHeight) {
  16058. me.props.lastWidth = me.dom.root.offsetWidth;
  16059. me.props.lastHeight = me.dom.root.offsetHeight;
  16060. me.body.emitter.emit('_change');
  16061. }
  16062. }
  16063. };
  16064. // add event listener to window resize
  16065. util.addEventListener(window, 'resize', this._onResize);
  16066. //Prevent initial unnecessary redraw
  16067. if (me.dom.root) {
  16068. me.props.lastWidth = me.dom.root.offsetWidth;
  16069. me.props.lastHeight = me.dom.root.offsetHeight;
  16070. }
  16071. this.watchTimer = setInterval(this._onResize, 1000);
  16072. };
  16073. /**
  16074. * Stop watching for a resize of the frame.
  16075. * @private
  16076. */
  16077. Core.prototype._stopAutoResize = function () {
  16078. if (this.watchTimer) {
  16079. clearInterval(this.watchTimer);
  16080. this.watchTimer = undefined;
  16081. }
  16082. // remove event listener on window.resize
  16083. if (this._onResize) {
  16084. util.removeEventListener(window, 'resize', this._onResize);
  16085. this._onResize = null;
  16086. }
  16087. };
  16088. /**
  16089. * Start moving the timeline vertically
  16090. * @param {Event} event
  16091. * @private
  16092. */
  16093. Core.prototype._onTouch = function (event) {
  16094. this.touch.allowDragging = true;
  16095. this.touch.initialScrollTop = this.props.scrollTop;
  16096. };
  16097. /**
  16098. * Start moving the timeline vertically
  16099. * @param {Event} event
  16100. * @private
  16101. */
  16102. Core.prototype._onPinch = function (event) {
  16103. this.touch.allowDragging = false;
  16104. };
  16105. /**
  16106. * Move the timeline vertically
  16107. * @param {Event} event
  16108. * @private
  16109. */
  16110. Core.prototype._onDrag = function (event) {
  16111. // refuse to drag when we where pinching to prevent the timeline make a jump
  16112. // when releasing the fingers in opposite order from the touch screen
  16113. if (!this.touch.allowDragging) return;
  16114. var delta = event.deltaY;
  16115. var oldScrollTop = this._getScrollTop();
  16116. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  16117. if (newScrollTop != oldScrollTop) {
  16118. this.emit("verticalDrag");
  16119. }
  16120. };
  16121. /**
  16122. * Apply a scrollTop
  16123. * @param {Number} scrollTop
  16124. * @returns {Number} scrollTop Returns the applied scrollTop
  16125. * @private
  16126. */
  16127. Core.prototype._setScrollTop = function (scrollTop) {
  16128. this.props.scrollTop = scrollTop;
  16129. this._updateScrollTop();
  16130. return this.props.scrollTop;
  16131. };
  16132. /**
  16133. * Update the current scrollTop when the height of the containers has been changed
  16134. * @returns {Number} scrollTop Returns the applied scrollTop
  16135. * @private
  16136. */
  16137. Core.prototype._updateScrollTop = function () {
  16138. // recalculate the scrollTopMin
  16139. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  16140. if (scrollTopMin != this.props.scrollTopMin) {
  16141. // in case of bottom orientation, change the scrollTop such that the contents
  16142. // do not move relative to the time axis at the bottom
  16143. if (this.options.orientation.item != 'top') {
  16144. this.props.scrollTop += scrollTopMin - this.props.scrollTopMin;
  16145. }
  16146. this.props.scrollTopMin = scrollTopMin;
  16147. }
  16148. // limit the scrollTop to the feasible scroll range
  16149. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  16150. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  16151. return this.props.scrollTop;
  16152. };
  16153. /**
  16154. * Get the current scrollTop
  16155. * @returns {number} scrollTop
  16156. * @private
  16157. */
  16158. Core.prototype._getScrollTop = function () {
  16159. return this.props.scrollTop;
  16160. };
  16161. /**
  16162. * Load a configurator
  16163. * @return {Object}
  16164. * @private
  16165. */
  16166. Core.prototype._createConfigurator = function () {
  16167. throw new Error('Cannot invoke abstract method _createConfigurator');
  16168. };
  16169. module.exports = Core;
  16170. /***/ },
  16171. /* 34 */
  16172. /***/ function(module, exports, __webpack_require__) {
  16173. 'use strict';
  16174. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  16175. var Hammer = __webpack_require__(20);
  16176. var util = __webpack_require__(1);
  16177. var DataSet = __webpack_require__(9);
  16178. var DataView = __webpack_require__(11);
  16179. var TimeStep = __webpack_require__(35);
  16180. var Component = __webpack_require__(31);
  16181. var Group = __webpack_require__(36);
  16182. var BackgroundGroup = __webpack_require__(40);
  16183. var BoxItem = __webpack_require__(41);
  16184. var PointItem = __webpack_require__(42);
  16185. var RangeItem = __webpack_require__(38);
  16186. var BackgroundItem = __webpack_require__(43);
  16187. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  16188. var BACKGROUND = '__background__'; // reserved group id for background items without group
  16189. /**
  16190. * An ItemSet holds a set of items and ranges which can be displayed in a
  16191. * range. The width is determined by the parent of the ItemSet, and the height
  16192. * is determined by the size of the items.
  16193. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  16194. * @param {Object} [options] See ItemSet.setOptions for the available options.
  16195. * @constructor ItemSet
  16196. * @extends Component
  16197. */
  16198. function ItemSet(body, options) {
  16199. this.body = body;
  16200. this.defaultOptions = {
  16201. rtl: false,
  16202. type: null, // 'box', 'point', 'range', 'background'
  16203. orientation: {
  16204. item: 'bottom' // item orientation: 'top' or 'bottom'
  16205. },
  16206. align: 'auto', // alignment of box items
  16207. stack: true,
  16208. groupOrderSwap: function groupOrderSwap(fromGroup, toGroup, groups) {
  16209. var targetOrder = toGroup.order;
  16210. toGroup.order = fromGroup.order;
  16211. fromGroup.order = targetOrder;
  16212. },
  16213. groupOrder: 'order',
  16214. selectable: true,
  16215. multiselect: false,
  16216. itemsAlwaysDraggable: false,
  16217. editable: {
  16218. updateTime: false,
  16219. updateGroup: false,
  16220. add: false,
  16221. remove: false
  16222. },
  16223. groupEditable: {
  16224. order: false,
  16225. add: false,
  16226. remove: false
  16227. },
  16228. snap: TimeStep.snap,
  16229. onAdd: function onAdd(item, callback) {
  16230. callback(item);
  16231. },
  16232. onUpdate: function onUpdate(item, callback) {
  16233. callback(item);
  16234. },
  16235. onMove: function onMove(item, callback) {
  16236. callback(item);
  16237. },
  16238. onRemove: function onRemove(item, callback) {
  16239. callback(item);
  16240. },
  16241. onMoving: function onMoving(item, callback) {
  16242. callback(item);
  16243. },
  16244. onAddGroup: function onAddGroup(item, callback) {
  16245. callback(item);
  16246. },
  16247. onMoveGroup: function onMoveGroup(item, callback) {
  16248. callback(item);
  16249. },
  16250. onRemoveGroup: function onRemoveGroup(item, callback) {
  16251. callback(item);
  16252. },
  16253. margin: {
  16254. item: {
  16255. horizontal: 10,
  16256. vertical: 10
  16257. },
  16258. axis: 20
  16259. }
  16260. };
  16261. // options is shared by this ItemSet and all its items
  16262. this.options = util.extend({}, this.defaultOptions);
  16263. // options for getting items from the DataSet with the correct type
  16264. this.itemOptions = {
  16265. type: { start: 'Date', end: 'Date' }
  16266. };
  16267. this.conversion = {
  16268. toScreen: body.util.toScreen,
  16269. toTime: body.util.toTime
  16270. };
  16271. this.dom = {};
  16272. this.props = {};
  16273. this.hammer = null;
  16274. var me = this;
  16275. this.itemsData = null; // DataSet
  16276. this.groupsData = null; // DataSet
  16277. // listeners for the DataSet of the items
  16278. this.itemListeners = {
  16279. 'add': function add(event, params, senderId) {
  16280. me._onAdd(params.items);
  16281. },
  16282. 'update': function update(event, params, senderId) {
  16283. me._onUpdate(params.items);
  16284. },
  16285. 'remove': function remove(event, params, senderId) {
  16286. me._onRemove(params.items);
  16287. }
  16288. };
  16289. // listeners for the DataSet of the groups
  16290. this.groupListeners = {
  16291. 'add': function add(event, params, senderId) {
  16292. me._onAddGroups(params.items);
  16293. },
  16294. 'update': function update(event, params, senderId) {
  16295. me._onUpdateGroups(params.items);
  16296. },
  16297. 'remove': function remove(event, params, senderId) {
  16298. me._onRemoveGroups(params.items);
  16299. }
  16300. };
  16301. this.items = {}; // object with an Item for every data item
  16302. this.groups = {}; // Group object for every group
  16303. this.groupIds = [];
  16304. this.selection = []; // list with the ids of all selected nodes
  16305. this.stackDirty = true; // if true, all items will be restacked on next redraw
  16306. this.touchParams = {}; // stores properties while dragging
  16307. this.groupTouchParams = {};
  16308. // create the HTML DOM
  16309. this._create();
  16310. this.setOptions(options);
  16311. }
  16312. ItemSet.prototype = new Component();
  16313. // available item types will be registered here
  16314. ItemSet.types = {
  16315. background: BackgroundItem,
  16316. box: BoxItem,
  16317. range: RangeItem,
  16318. point: PointItem
  16319. };
  16320. /**
  16321. * Create the HTML DOM for the ItemSet
  16322. */
  16323. ItemSet.prototype._create = function () {
  16324. var frame = document.createElement('div');
  16325. frame.className = 'vis-itemset';
  16326. frame['timeline-itemset'] = this;
  16327. this.dom.frame = frame;
  16328. // create background panel
  16329. var background = document.createElement('div');
  16330. background.className = 'vis-background';
  16331. frame.appendChild(background);
  16332. this.dom.background = background;
  16333. // create foreground panel
  16334. var foreground = document.createElement('div');
  16335. foreground.className = 'vis-foreground';
  16336. frame.appendChild(foreground);
  16337. this.dom.foreground = foreground;
  16338. // create axis panel
  16339. var axis = document.createElement('div');
  16340. axis.className = 'vis-axis';
  16341. this.dom.axis = axis;
  16342. // create labelset
  16343. var labelSet = document.createElement('div');
  16344. labelSet.className = 'vis-labelset';
  16345. this.dom.labelSet = labelSet;
  16346. // create ungrouped Group
  16347. this._updateUngrouped();
  16348. // create background Group
  16349. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  16350. backgroundGroup.show();
  16351. this.groups[BACKGROUND] = backgroundGroup;
  16352. // attach event listeners
  16353. // Note: we bind to the centerContainer for the case where the height
  16354. // of the center container is larger than of the ItemSet, so we
  16355. // can click in the empty area to create a new item or deselect an item.
  16356. this.hammer = new Hammer(this.body.dom.centerContainer);
  16357. // drag items when selected
  16358. this.hammer.on('hammer.input', function (event) {
  16359. if (event.isFirst) {
  16360. this._onTouch(event);
  16361. }
  16362. }.bind(this));
  16363. this.hammer.on('panstart', this._onDragStart.bind(this));
  16364. this.hammer.on('panmove', this._onDrag.bind(this));
  16365. this.hammer.on('panend', this._onDragEnd.bind(this));
  16366. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  16367. // single select (or unselect) when tapping an item
  16368. this.hammer.on('tap', this._onSelectItem.bind(this));
  16369. // multi select when holding mouse/touch, or on ctrl+click
  16370. this.hammer.on('press', this._onMultiSelectItem.bind(this));
  16371. // add item on doubletap
  16372. this.hammer.on('doubletap', this._onAddItem.bind(this));
  16373. this.groupHammer = new Hammer(this.body.dom.leftContainer);
  16374. this.groupHammer.on('panstart', this._onGroupDragStart.bind(this));
  16375. this.groupHammer.on('panmove', this._onGroupDrag.bind(this));
  16376. this.groupHammer.on('panend', this._onGroupDragEnd.bind(this));
  16377. this.groupHammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  16378. // attach to the DOM
  16379. this.show();
  16380. };
  16381. /**
  16382. * Set options for the ItemSet. Existing options will be extended/overwritten.
  16383. * @param {Object} [options] The following options are available:
  16384. * {String} type
  16385. * Default type for the items. Choose from 'box'
  16386. * (default), 'point', 'range', or 'background'.
  16387. * The default style can be overwritten by
  16388. * individual items.
  16389. * {String} align
  16390. * Alignment for the items, only applicable for
  16391. * BoxItem. Choose 'center' (default), 'left', or
  16392. * 'right'.
  16393. * {String} orientation.item
  16394. * Orientation of the item set. Choose 'top' or
  16395. * 'bottom' (default).
  16396. * {Function} groupOrder
  16397. * A sorting function for ordering groups
  16398. * {Boolean} stack
  16399. * If true (default), items will be stacked on
  16400. * top of each other.
  16401. * {Number} margin.axis
  16402. * Margin between the axis and the items in pixels.
  16403. * Default is 20.
  16404. * {Number} margin.item.horizontal
  16405. * Horizontal margin between items in pixels.
  16406. * Default is 10.
  16407. * {Number} margin.item.vertical
  16408. * Vertical Margin between items in pixels.
  16409. * Default is 10.
  16410. * {Number} margin.item
  16411. * Margin between items in pixels in both horizontal
  16412. * and vertical direction. Default is 10.
  16413. * {Number} margin
  16414. * Set margin for both axis and items in pixels.
  16415. * {Boolean} selectable
  16416. * If true (default), items can be selected.
  16417. * {Boolean} multiselect
  16418. * If true, multiple items can be selected.
  16419. * False by default.
  16420. * {Boolean} editable
  16421. * Set all editable options to true or false
  16422. * {Boolean} editable.updateTime
  16423. * Allow dragging an item to an other moment in time
  16424. * {Boolean} editable.updateGroup
  16425. * Allow dragging an item to an other group
  16426. * {Boolean} editable.add
  16427. * Allow creating new items on double tap
  16428. * {Boolean} editable.remove
  16429. * Allow removing items by clicking the delete button
  16430. * top right of a selected item.
  16431. * {Function(item: Item, callback: Function)} onAdd
  16432. * Callback function triggered when an item is about to be added:
  16433. * when the user double taps an empty space in the Timeline.
  16434. * {Function(item: Item, callback: Function)} onUpdate
  16435. * Callback function fired when an item is about to be updated.
  16436. * This function typically has to show a dialog where the user
  16437. * change the item. If not implemented, nothing happens.
  16438. * {Function(item: Item, callback: Function)} onMove
  16439. * Fired when an item has been moved. If not implemented,
  16440. * the move action will be accepted.
  16441. * {Function(item: Item, callback: Function)} onRemove
  16442. * Fired when an item is about to be deleted.
  16443. * If not implemented, the item will be always removed.
  16444. */
  16445. ItemSet.prototype.setOptions = function (options) {
  16446. if (options) {
  16447. // copy all options that we know
  16448. var fields = ['type', 'rtl', 'align', 'order', 'stack', 'selectable', 'multiselect', 'itemsAlwaysDraggable', 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'hide', 'snap', 'groupOrderSwap'];
  16449. util.selectiveExtend(fields, this.options, options);
  16450. if ('orientation' in options) {
  16451. if (typeof options.orientation === 'string') {
  16452. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  16453. } else if (_typeof(options.orientation) === 'object' && 'item' in options.orientation) {
  16454. this.options.orientation.item = options.orientation.item;
  16455. }
  16456. }
  16457. if ('margin' in options) {
  16458. if (typeof options.margin === 'number') {
  16459. this.options.margin.axis = options.margin;
  16460. this.options.margin.item.horizontal = options.margin;
  16461. this.options.margin.item.vertical = options.margin;
  16462. } else if (_typeof(options.margin) === 'object') {
  16463. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  16464. if ('item' in options.margin) {
  16465. if (typeof options.margin.item === 'number') {
  16466. this.options.margin.item.horizontal = options.margin.item;
  16467. this.options.margin.item.vertical = options.margin.item;
  16468. } else if (_typeof(options.margin.item) === 'object') {
  16469. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  16470. }
  16471. }
  16472. }
  16473. }
  16474. if ('editable' in options) {
  16475. if (typeof options.editable === 'boolean') {
  16476. this.options.editable.updateTime = options.editable;
  16477. this.options.editable.updateGroup = options.editable;
  16478. this.options.editable.add = options.editable;
  16479. this.options.editable.remove = options.editable;
  16480. } else if (_typeof(options.editable) === 'object') {
  16481. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
  16482. }
  16483. }
  16484. if ('groupEditable' in options) {
  16485. if (typeof options.groupEditable === 'boolean') {
  16486. this.options.groupEditable.order = options.groupEditable;
  16487. this.options.groupEditable.add = options.groupEditable;
  16488. this.options.groupEditable.remove = options.groupEditable;
  16489. } else if (_typeof(options.groupEditable) === 'object') {
  16490. util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
  16491. }
  16492. }
  16493. // callback functions
  16494. var addCallback = function (name) {
  16495. var fn = options[name];
  16496. if (fn) {
  16497. if (!(fn instanceof Function)) {
  16498. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  16499. }
  16500. this.options[name] = fn;
  16501. }
  16502. }.bind(this);
  16503. ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
  16504. // force the itemSet to refresh: options like orientation and margins may be changed
  16505. this.markDirty();
  16506. }
  16507. };
  16508. /**
  16509. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  16510. * Optionally, all items can be marked as dirty and be refreshed.
  16511. * @param {{refreshItems: boolean}} [options]
  16512. */
  16513. ItemSet.prototype.markDirty = function (options) {
  16514. this.groupIds = [];
  16515. this.stackDirty = true;
  16516. if (options && options.refreshItems) {
  16517. util.forEach(this.items, function (item) {
  16518. item.dirty = true;
  16519. if (item.displayed) item.redraw();
  16520. });
  16521. }
  16522. };
  16523. /**
  16524. * Destroy the ItemSet
  16525. */
  16526. ItemSet.prototype.destroy = function () {
  16527. this.hide();
  16528. this.setItems(null);
  16529. this.setGroups(null);
  16530. this.hammer = null;
  16531. this.body = null;
  16532. this.conversion = null;
  16533. };
  16534. /**
  16535. * Hide the component from the DOM
  16536. */
  16537. ItemSet.prototype.hide = function () {
  16538. // remove the frame containing the items
  16539. if (this.dom.frame.parentNode) {
  16540. this.dom.frame.parentNode.removeChild(this.dom.frame);
  16541. }
  16542. // remove the axis with dots
  16543. if (this.dom.axis.parentNode) {
  16544. this.dom.axis.parentNode.removeChild(this.dom.axis);
  16545. }
  16546. // remove the labelset containing all group labels
  16547. if (this.dom.labelSet.parentNode) {
  16548. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  16549. }
  16550. };
  16551. /**
  16552. * Show the component in the DOM (when not already visible).
  16553. * @return {Boolean} changed
  16554. */
  16555. ItemSet.prototype.show = function () {
  16556. // show frame containing the items
  16557. if (!this.dom.frame.parentNode) {
  16558. this.body.dom.center.appendChild(this.dom.frame);
  16559. }
  16560. // show axis with dots
  16561. if (!this.dom.axis.parentNode) {
  16562. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  16563. }
  16564. // show labelset containing labels
  16565. if (!this.dom.labelSet.parentNode) {
  16566. this.body.dom.left.appendChild(this.dom.labelSet);
  16567. }
  16568. };
  16569. /**
  16570. * Set selected items by their id. Replaces the current selection
  16571. * Unknown id's are silently ignored.
  16572. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  16573. * selected, or a single item id. If ids is undefined
  16574. * or an empty array, all items will be unselected.
  16575. */
  16576. ItemSet.prototype.setSelection = function (ids) {
  16577. var i, ii, id, item;
  16578. if (ids == undefined) ids = [];
  16579. if (!Array.isArray(ids)) ids = [ids];
  16580. // unselect currently selected items
  16581. for (i = 0, ii = this.selection.length; i < ii; i++) {
  16582. id = this.selection[i];
  16583. item = this.items[id];
  16584. if (item) item.unselect();
  16585. }
  16586. // select items
  16587. this.selection = [];
  16588. for (i = 0, ii = ids.length; i < ii; i++) {
  16589. id = ids[i];
  16590. item = this.items[id];
  16591. if (item) {
  16592. this.selection.push(id);
  16593. item.select();
  16594. }
  16595. }
  16596. };
  16597. /**
  16598. * Get the selected items by their id
  16599. * @return {Array} ids The ids of the selected items
  16600. */
  16601. ItemSet.prototype.getSelection = function () {
  16602. return this.selection.concat([]);
  16603. };
  16604. /**
  16605. * Get the id's of the currently visible items.
  16606. * @returns {Array} The ids of the visible items
  16607. */
  16608. ItemSet.prototype.getVisibleItems = function () {
  16609. var range = this.body.range.getRange();
  16610. if (this.options.rtl) {
  16611. var right = this.body.util.toScreen(range.start);
  16612. var left = this.body.util.toScreen(range.end);
  16613. } else {
  16614. var left = this.body.util.toScreen(range.start);
  16615. var right = this.body.util.toScreen(range.end);
  16616. }
  16617. var ids = [];
  16618. for (var groupId in this.groups) {
  16619. if (this.groups.hasOwnProperty(groupId)) {
  16620. var group = this.groups[groupId];
  16621. var rawVisibleItems = group.visibleItems;
  16622. // filter the "raw" set with visibleItems into a set which is really
  16623. // visible by pixels
  16624. for (var i = 0; i < rawVisibleItems.length; i++) {
  16625. var item = rawVisibleItems[i];
  16626. // TODO: also check whether visible vertically
  16627. if (this.options.rtl) {
  16628. if (item.right < left && item.right + item.width > right) {
  16629. ids.push(item.id);
  16630. }
  16631. } else {
  16632. if (item.left < right && item.left + item.width > left) {
  16633. ids.push(item.id);
  16634. }
  16635. }
  16636. }
  16637. }
  16638. }
  16639. return ids;
  16640. };
  16641. /**
  16642. * Deselect a selected item
  16643. * @param {String | Number} id
  16644. * @private
  16645. */
  16646. ItemSet.prototype._deselect = function (id) {
  16647. var selection = this.selection;
  16648. for (var i = 0, ii = selection.length; i < ii; i++) {
  16649. if (selection[i] == id) {
  16650. // non-strict comparison!
  16651. selection.splice(i, 1);
  16652. break;
  16653. }
  16654. }
  16655. };
  16656. /**
  16657. * Repaint the component
  16658. * @return {boolean} Returns true if the component is resized
  16659. */
  16660. ItemSet.prototype.redraw = function () {
  16661. var margin = this.options.margin,
  16662. range = this.body.range,
  16663. asSize = util.option.asSize,
  16664. options = this.options,
  16665. orientation = options.orientation.item,
  16666. resized = false,
  16667. frame = this.dom.frame;
  16668. // recalculate absolute position (before redrawing groups)
  16669. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  16670. if (this.options.rtl) {
  16671. this.props.right = this.body.domProps.right.width + this.body.domProps.border.right;
  16672. } else {
  16673. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  16674. }
  16675. // update class name
  16676. frame.className = 'vis-itemset';
  16677. // reorder the groups (if needed)
  16678. resized = this._orderGroups() || resized;
  16679. // check whether zoomed (in that case we need to re-stack everything)
  16680. // TODO: would be nicer to get this as a trigger from Range
  16681. var visibleInterval = range.end - range.start;
  16682. var zoomed = visibleInterval != this.lastVisibleInterval || this.props.width != this.props.lastWidth;
  16683. if (zoomed) this.stackDirty = true;
  16684. this.lastVisibleInterval = visibleInterval;
  16685. this.props.lastWidth = this.props.width;
  16686. var restack = this.stackDirty;
  16687. var firstGroup = this._firstGroup();
  16688. var firstMargin = {
  16689. item: margin.item,
  16690. axis: margin.axis
  16691. };
  16692. var nonFirstMargin = {
  16693. item: margin.item,
  16694. axis: margin.item.vertical / 2
  16695. };
  16696. var height = 0;
  16697. var minHeight = margin.axis + margin.item.vertical;
  16698. // redraw the background group
  16699. this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
  16700. // redraw all regular groups
  16701. util.forEach(this.groups, function (group) {
  16702. var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin;
  16703. var groupResized = group.redraw(range, groupMargin, restack);
  16704. resized = groupResized || resized;
  16705. height += group.height;
  16706. });
  16707. height = Math.max(height, minHeight);
  16708. this.stackDirty = false;
  16709. // update frame height
  16710. frame.style.height = asSize(height);
  16711. // calculate actual size
  16712. this.props.width = frame.offsetWidth;
  16713. this.props.height = height;
  16714. // reposition axis
  16715. this.dom.axis.style.top = asSize(orientation == 'top' ? this.body.domProps.top.height + this.body.domProps.border.top : this.body.domProps.top.height + this.body.domProps.centerContainer.height);
  16716. if (this.options.rtl) {
  16717. this.dom.axis.style.right = '0';
  16718. } else {
  16719. this.dom.axis.style.left = '0';
  16720. }
  16721. // check if this component is resized
  16722. resized = this._isResized() || resized;
  16723. return resized;
  16724. };
  16725. /**
  16726. * Get the first group, aligned with the axis
  16727. * @return {Group | null} firstGroup
  16728. * @private
  16729. */
  16730. ItemSet.prototype._firstGroup = function () {
  16731. var firstGroupIndex = this.options.orientation.item == 'top' ? 0 : this.groupIds.length - 1;
  16732. var firstGroupId = this.groupIds[firstGroupIndex];
  16733. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  16734. return firstGroup || null;
  16735. };
  16736. /**
  16737. * Create or delete the group holding all ungrouped items. This group is used when
  16738. * there are no groups specified.
  16739. * @protected
  16740. */
  16741. ItemSet.prototype._updateUngrouped = function () {
  16742. var ungrouped = this.groups[UNGROUPED];
  16743. var background = this.groups[BACKGROUND];
  16744. var item, itemId;
  16745. if (this.groupsData) {
  16746. // remove the group holding all ungrouped items
  16747. if (ungrouped) {
  16748. ungrouped.hide();
  16749. delete this.groups[UNGROUPED];
  16750. for (itemId in this.items) {
  16751. if (this.items.hasOwnProperty(itemId)) {
  16752. item = this.items[itemId];
  16753. item.parent && item.parent.remove(item);
  16754. var groupId = this._getGroupId(item.data);
  16755. var group = this.groups[groupId];
  16756. group && group.add(item) || item.hide();
  16757. }
  16758. }
  16759. }
  16760. } else {
  16761. // create a group holding all (unfiltered) items
  16762. if (!ungrouped) {
  16763. var id = null;
  16764. var data = null;
  16765. ungrouped = new Group(id, data, this);
  16766. this.groups[UNGROUPED] = ungrouped;
  16767. for (itemId in this.items) {
  16768. if (this.items.hasOwnProperty(itemId)) {
  16769. item = this.items[itemId];
  16770. ungrouped.add(item);
  16771. }
  16772. }
  16773. ungrouped.show();
  16774. }
  16775. }
  16776. };
  16777. /**
  16778. * Get the element for the labelset
  16779. * @return {HTMLElement} labelSet
  16780. */
  16781. ItemSet.prototype.getLabelSet = function () {
  16782. return this.dom.labelSet;
  16783. };
  16784. /**
  16785. * Set items
  16786. * @param {vis.DataSet | null} items
  16787. */
  16788. ItemSet.prototype.setItems = function (items) {
  16789. var me = this,
  16790. ids,
  16791. oldItemsData = this.itemsData;
  16792. // replace the dataset
  16793. if (!items) {
  16794. this.itemsData = null;
  16795. } else if (items instanceof DataSet || items instanceof DataView) {
  16796. this.itemsData = items;
  16797. } else {
  16798. throw new TypeError('Data must be an instance of DataSet or DataView');
  16799. }
  16800. if (oldItemsData) {
  16801. // unsubscribe from old dataset
  16802. util.forEach(this.itemListeners, function (callback, event) {
  16803. oldItemsData.off(event, callback);
  16804. });
  16805. // remove all drawn items
  16806. ids = oldItemsData.getIds();
  16807. this._onRemove(ids);
  16808. }
  16809. if (this.itemsData) {
  16810. // subscribe to new dataset
  16811. var id = this.id;
  16812. util.forEach(this.itemListeners, function (callback, event) {
  16813. me.itemsData.on(event, callback, id);
  16814. });
  16815. // add all new items
  16816. ids = this.itemsData.getIds();
  16817. this._onAdd(ids);
  16818. // update the group holding all ungrouped items
  16819. this._updateUngrouped();
  16820. }
  16821. this.body.emitter.emit('_change', { queue: true });
  16822. };
  16823. /**
  16824. * Get the current items
  16825. * @returns {vis.DataSet | null}
  16826. */
  16827. ItemSet.prototype.getItems = function () {
  16828. return this.itemsData;
  16829. };
  16830. /**
  16831. * Set groups
  16832. * @param {vis.DataSet} groups
  16833. */
  16834. ItemSet.prototype.setGroups = function (groups) {
  16835. var me = this,
  16836. ids;
  16837. // unsubscribe from current dataset
  16838. if (this.groupsData) {
  16839. util.forEach(this.groupListeners, function (callback, event) {
  16840. me.groupsData.off(event, callback);
  16841. });
  16842. // remove all drawn groups
  16843. ids = this.groupsData.getIds();
  16844. this.groupsData = null;
  16845. this._onRemoveGroups(ids); // note: this will cause a redraw
  16846. }
  16847. // replace the dataset
  16848. if (!groups) {
  16849. this.groupsData = null;
  16850. } else if (groups instanceof DataSet || groups instanceof DataView) {
  16851. this.groupsData = groups;
  16852. } else {
  16853. throw new TypeError('Data must be an instance of DataSet or DataView');
  16854. }
  16855. if (this.groupsData) {
  16856. // subscribe to new dataset
  16857. var id = this.id;
  16858. util.forEach(this.groupListeners, function (callback, event) {
  16859. me.groupsData.on(event, callback, id);
  16860. });
  16861. // draw all ms
  16862. ids = this.groupsData.getIds();
  16863. this._onAddGroups(ids);
  16864. }
  16865. // update the group holding all ungrouped items
  16866. this._updateUngrouped();
  16867. // update the order of all items in each group
  16868. this._order();
  16869. this.body.emitter.emit('_change', { queue: true });
  16870. };
  16871. /**
  16872. * Get the current groups
  16873. * @returns {vis.DataSet | null} groups
  16874. */
  16875. ItemSet.prototype.getGroups = function () {
  16876. return this.groupsData;
  16877. };
  16878. /**
  16879. * Remove an item by its id
  16880. * @param {String | Number} id
  16881. */
  16882. ItemSet.prototype.removeItem = function (id) {
  16883. var item = this.itemsData.get(id),
  16884. dataset = this.itemsData.getDataSet();
  16885. if (item) {
  16886. // confirm deletion
  16887. this.options.onRemove(item, function (item) {
  16888. if (item) {
  16889. // remove by id here, it is possible that an item has no id defined
  16890. // itself, so better not delete by the item itself
  16891. dataset.remove(id);
  16892. }
  16893. });
  16894. }
  16895. };
  16896. /**
  16897. * Get the time of an item based on it's data and options.type
  16898. * @param {Object} itemData
  16899. * @returns {string} Returns the type
  16900. * @private
  16901. */
  16902. ItemSet.prototype._getType = function (itemData) {
  16903. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  16904. };
  16905. /**
  16906. * Get the group id for an item
  16907. * @param {Object} itemData
  16908. * @returns {string} Returns the groupId
  16909. * @private
  16910. */
  16911. ItemSet.prototype._getGroupId = function (itemData) {
  16912. var type = this._getType(itemData);
  16913. if (type == 'background' && itemData.group == undefined) {
  16914. return BACKGROUND;
  16915. } else {
  16916. return this.groupsData ? itemData.group : UNGROUPED;
  16917. }
  16918. };
  16919. /**
  16920. * Handle updated items
  16921. * @param {Number[]} ids
  16922. * @protected
  16923. */
  16924. ItemSet.prototype._onUpdate = function (ids) {
  16925. var me = this;
  16926. ids.forEach(function (id) {
  16927. var itemData = me.itemsData.get(id, me.itemOptions);
  16928. var item = me.items[id];
  16929. var type = me._getType(itemData);
  16930. var constructor = ItemSet.types[type];
  16931. var selected;
  16932. if (item) {
  16933. // update item
  16934. if (!constructor || !(item instanceof constructor)) {
  16935. // item type has changed, delete the item and recreate it
  16936. selected = item.selected; // preserve selection of this item
  16937. me._removeItem(item);
  16938. item = null;
  16939. } else {
  16940. me._updateItem(item, itemData);
  16941. }
  16942. }
  16943. if (!item) {
  16944. // create item
  16945. if (constructor) {
  16946. item = new constructor(itemData, me.conversion, me.options);
  16947. item.id = id; // TODO: not so nice setting id afterwards
  16948. me._addItem(item);
  16949. if (selected) {
  16950. this.selection.push(id);
  16951. item.select();
  16952. }
  16953. } else if (type == 'rangeoverflow') {
  16954. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  16955. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' + '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  16956. } else {
  16957. throw new TypeError('Unknown item type "' + type + '"');
  16958. }
  16959. }
  16960. }.bind(this));
  16961. this._order();
  16962. this.stackDirty = true; // force re-stacking of all items next redraw
  16963. this.body.emitter.emit('_change', { queue: true });
  16964. };
  16965. /**
  16966. * Handle added items
  16967. * @param {Number[]} ids
  16968. * @protected
  16969. */
  16970. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  16971. /**
  16972. * Handle removed items
  16973. * @param {Number[]} ids
  16974. * @protected
  16975. */
  16976. ItemSet.prototype._onRemove = function (ids) {
  16977. var count = 0;
  16978. var me = this;
  16979. ids.forEach(function (id) {
  16980. var item = me.items[id];
  16981. if (item) {
  16982. count++;
  16983. me._removeItem(item);
  16984. }
  16985. });
  16986. if (count) {
  16987. // update order
  16988. this._order();
  16989. this.stackDirty = true; // force re-stacking of all items next redraw
  16990. this.body.emitter.emit('_change', { queue: true });
  16991. }
  16992. };
  16993. /**
  16994. * Update the order of item in all groups
  16995. * @private
  16996. */
  16997. ItemSet.prototype._order = function () {
  16998. // reorder the items in all groups
  16999. // TODO: optimization: only reorder groups affected by the changed items
  17000. util.forEach(this.groups, function (group) {
  17001. group.order();
  17002. });
  17003. };
  17004. /**
  17005. * Handle updated groups
  17006. * @param {Number[]} ids
  17007. * @private
  17008. */
  17009. ItemSet.prototype._onUpdateGroups = function (ids) {
  17010. this._onAddGroups(ids);
  17011. };
  17012. /**
  17013. * Handle changed groups (added or updated)
  17014. * @param {Number[]} ids
  17015. * @private
  17016. */
  17017. ItemSet.prototype._onAddGroups = function (ids) {
  17018. var me = this;
  17019. ids.forEach(function (id) {
  17020. var groupData = me.groupsData.get(id);
  17021. var group = me.groups[id];
  17022. if (!group) {
  17023. // check for reserved ids
  17024. if (id == UNGROUPED || id == BACKGROUND) {
  17025. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  17026. }
  17027. var groupOptions = Object.create(me.options);
  17028. util.extend(groupOptions, {
  17029. height: null
  17030. });
  17031. group = new Group(id, groupData, me);
  17032. me.groups[id] = group;
  17033. // add items with this groupId to the new group
  17034. for (var itemId in me.items) {
  17035. if (me.items.hasOwnProperty(itemId)) {
  17036. var item = me.items[itemId];
  17037. if (item.data.group == id) {
  17038. group.add(item);
  17039. }
  17040. }
  17041. }
  17042. group.order();
  17043. group.show();
  17044. } else {
  17045. // update group
  17046. group.setData(groupData);
  17047. }
  17048. });
  17049. this.body.emitter.emit('_change', { queue: true });
  17050. };
  17051. /**
  17052. * Handle removed groups
  17053. * @param {Number[]} ids
  17054. * @private
  17055. */
  17056. ItemSet.prototype._onRemoveGroups = function (ids) {
  17057. var groups = this.groups;
  17058. ids.forEach(function (id) {
  17059. var group = groups[id];
  17060. if (group) {
  17061. group.hide();
  17062. delete groups[id];
  17063. }
  17064. });
  17065. this.markDirty();
  17066. this.body.emitter.emit('_change', { queue: true });
  17067. };
  17068. /**
  17069. * Reorder the groups if needed
  17070. * @return {boolean} changed
  17071. * @private
  17072. */
  17073. ItemSet.prototype._orderGroups = function () {
  17074. if (this.groupsData) {
  17075. // reorder the groups
  17076. var groupIds = this.groupsData.getIds({
  17077. order: this.options.groupOrder
  17078. });
  17079. var changed = !util.equalArray(groupIds, this.groupIds);
  17080. if (changed) {
  17081. // hide all groups, removes them from the DOM
  17082. var groups = this.groups;
  17083. groupIds.forEach(function (groupId) {
  17084. groups[groupId].hide();
  17085. });
  17086. // show the groups again, attach them to the DOM in correct order
  17087. groupIds.forEach(function (groupId) {
  17088. groups[groupId].show();
  17089. });
  17090. this.groupIds = groupIds;
  17091. }
  17092. return changed;
  17093. } else {
  17094. return false;
  17095. }
  17096. };
  17097. /**
  17098. * Add a new item
  17099. * @param {Item} item
  17100. * @private
  17101. */
  17102. ItemSet.prototype._addItem = function (item) {
  17103. this.items[item.id] = item;
  17104. // add to group
  17105. var groupId = this._getGroupId(item.data);
  17106. var group = this.groups[groupId];
  17107. if (group) group.add(item);
  17108. };
  17109. /**
  17110. * Update an existing item
  17111. * @param {Item} item
  17112. * @param {Object} itemData
  17113. * @private
  17114. */
  17115. ItemSet.prototype._updateItem = function (item, itemData) {
  17116. var oldGroupId = item.data.group;
  17117. var oldSubGroupId = item.data.subgroup;
  17118. // update the items data (will redraw the item when displayed)
  17119. item.setData(itemData);
  17120. // update group
  17121. if (oldGroupId != item.data.group || oldSubGroupId != item.data.subgroup) {
  17122. var oldGroup = this.groups[oldGroupId];
  17123. if (oldGroup) oldGroup.remove(item);
  17124. var groupId = this._getGroupId(item.data);
  17125. var group = this.groups[groupId];
  17126. if (group) group.add(item);
  17127. }
  17128. };
  17129. /**
  17130. * Delete an item from the ItemSet: remove it from the DOM, from the map
  17131. * with items, and from the map with visible items, and from the selection
  17132. * @param {Item} item
  17133. * @private
  17134. */
  17135. ItemSet.prototype._removeItem = function (item) {
  17136. // remove from DOM
  17137. item.hide();
  17138. // remove from items
  17139. delete this.items[item.id];
  17140. // remove from selection
  17141. var index = this.selection.indexOf(item.id);
  17142. if (index != -1) this.selection.splice(index, 1);
  17143. // remove from group
  17144. item.parent && item.parent.remove(item);
  17145. };
  17146. /**
  17147. * Create an array containing all items being a range (having an end date)
  17148. * @param array
  17149. * @returns {Array}
  17150. * @private
  17151. */
  17152. ItemSet.prototype._constructByEndArray = function (array) {
  17153. var endArray = [];
  17154. for (var i = 0; i < array.length; i++) {
  17155. if (array[i] instanceof RangeItem) {
  17156. endArray.push(array[i]);
  17157. }
  17158. }
  17159. return endArray;
  17160. };
  17161. /**
  17162. * Register the clicked item on touch, before dragStart is initiated.
  17163. *
  17164. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  17165. * already moving. Therefore, the mouse/touch can sometimes be above an other
  17166. * DOM element than the item itself.
  17167. *
  17168. * @param {Event} event
  17169. * @private
  17170. */
  17171. ItemSet.prototype._onTouch = function (event) {
  17172. // store the touched item, used in _onDragStart
  17173. this.touchParams.item = this.itemFromTarget(event);
  17174. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  17175. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  17176. this.touchParams.itemProps = null;
  17177. };
  17178. /**
  17179. * Given an group id, returns the index it has.
  17180. *
  17181. * @param {Number} groupID
  17182. * @private
  17183. */
  17184. ItemSet.prototype._getGroupIndex = function (groupId) {
  17185. for (var i = 0; i < this.groupIds.length; i++) {
  17186. if (groupId == this.groupIds[i]) return i;
  17187. }
  17188. };
  17189. /**
  17190. * Start dragging the selected events
  17191. * @param {Event} event
  17192. * @private
  17193. */
  17194. ItemSet.prototype._onDragStart = function (event) {
  17195. var item = this.touchParams.item || null;
  17196. var me = this;
  17197. var props;
  17198. if (item && (item.selected || this.options.itemsAlwaysDraggable)) {
  17199. if (!this.options.editable.updateTime && !this.options.editable.updateGroup && !item.editable) {
  17200. return;
  17201. }
  17202. // override options.editable
  17203. if (item.editable === false) {
  17204. return;
  17205. }
  17206. var dragLeftItem = this.touchParams.dragLeftItem;
  17207. var dragRightItem = this.touchParams.dragRightItem;
  17208. if (dragLeftItem) {
  17209. props = {
  17210. item: dragLeftItem,
  17211. initialX: event.center.x,
  17212. dragLeft: true,
  17213. data: this._cloneItemData(item.data)
  17214. };
  17215. this.touchParams.itemProps = [props];
  17216. } else if (dragRightItem) {
  17217. props = {
  17218. item: dragRightItem,
  17219. initialX: event.center.x,
  17220. dragRight: true,
  17221. data: this._cloneItemData(item.data)
  17222. };
  17223. this.touchParams.itemProps = [props];
  17224. } else {
  17225. this.touchParams.selectedItem = item;
  17226. var baseGroupIndex = this._getGroupIndex(item.data.group);
  17227. var itemsToDrag = this.options.itemsAlwaysDraggable && !item.selected ? [item.id] : this.getSelection();
  17228. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  17229. var item = me.items[id];
  17230. var groupIndex = me._getGroupIndex(item.data.group);
  17231. return {
  17232. item: item,
  17233. initialX: event.center.x,
  17234. groupOffset: baseGroupIndex - groupIndex,
  17235. data: this._cloneItemData(item.data)
  17236. };
  17237. }.bind(this));
  17238. }
  17239. event.stopPropagation();
  17240. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  17241. // create a new range item when dragging with ctrl key down
  17242. this._onDragStartAddItem(event);
  17243. }
  17244. };
  17245. /**
  17246. * Start creating a new range item by dragging.
  17247. * @param {Event} event
  17248. * @private
  17249. */
  17250. ItemSet.prototype._onDragStartAddItem = function (event) {
  17251. var snap = this.options.snap || null;
  17252. if (this.options.rtl) {
  17253. var xAbs = util.getAbsoluteRight(this.dom.frame);
  17254. var x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  17255. } else {
  17256. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  17257. var x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  17258. }
  17259. var time = this.body.util.toTime(x);
  17260. var scale = this.body.util.getScale();
  17261. var step = this.body.util.getStep();
  17262. var start = snap ? snap(time, scale, step) : time;
  17263. var end = start;
  17264. var itemData = {
  17265. type: 'range',
  17266. start: start,
  17267. end: end,
  17268. content: 'new item'
  17269. };
  17270. var id = util.randomUUID();
  17271. itemData[this.itemsData._fieldId] = id;
  17272. var group = this.groupFromTarget(event);
  17273. if (group) {
  17274. itemData.group = group.groupId;
  17275. }
  17276. var newItem = new RangeItem(itemData, this.conversion, this.options);
  17277. newItem.id = id; // TODO: not so nice setting id afterwards
  17278. newItem.data = this._cloneItemData(itemData);
  17279. this._addItem(newItem);
  17280. var props = {
  17281. item: newItem,
  17282. initialX: event.center.x,
  17283. data: newItem.data
  17284. };
  17285. if (this.options.rtl) {
  17286. props.dragLeft = true;
  17287. } else {
  17288. props.dragRight = true;
  17289. }
  17290. this.touchParams.itemProps = [props];
  17291. event.stopPropagation();
  17292. };
  17293. /**
  17294. * Drag selected items
  17295. * @param {Event} event
  17296. * @private
  17297. */
  17298. ItemSet.prototype._onDrag = function (event) {
  17299. if (this.touchParams.itemProps) {
  17300. event.stopPropagation();
  17301. var me = this;
  17302. var snap = this.options.snap || null;
  17303. if (this.options.rtl) {
  17304. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  17305. } else {
  17306. var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  17307. }
  17308. var scale = this.body.util.getScale();
  17309. var step = this.body.util.getStep();
  17310. //only calculate the new group for the item that's actually dragged
  17311. var selectedItem = this.touchParams.selectedItem;
  17312. var updateGroupAllowed = me.options.editable.updateGroup;
  17313. var newGroupBase = null;
  17314. if (updateGroupAllowed && selectedItem) {
  17315. if (selectedItem.data.group != undefined) {
  17316. // drag from one group to another
  17317. var group = me.groupFromTarget(event);
  17318. if (group) {
  17319. //we know the offset for all items, so the new group for all items
  17320. //will be relative to this one.
  17321. newGroupBase = this._getGroupIndex(group.groupId);
  17322. }
  17323. }
  17324. }
  17325. // move
  17326. this.touchParams.itemProps.forEach(function (props) {
  17327. var current = me.body.util.toTime(event.center.x - xOffset);
  17328. var initial = me.body.util.toTime(props.initialX - xOffset);
  17329. if (this.options.rtl) {
  17330. var offset = -(current - initial); // ms
  17331. } else {
  17332. var offset = current - initial; // ms
  17333. }
  17334. var itemData = this._cloneItemData(props.item.data); // clone the data
  17335. if (props.item.editable === false) {
  17336. return;
  17337. }
  17338. var updateTimeAllowed = me.options.editable.updateTime || props.item.editable === true;
  17339. if (updateTimeAllowed) {
  17340. if (props.dragLeft) {
  17341. // drag left side of a range item
  17342. if (this.options.rtl) {
  17343. if (itemData.end != undefined) {
  17344. var initialEnd = util.convert(props.data.end, 'Date');
  17345. var end = new Date(initialEnd.valueOf() + offset);
  17346. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  17347. itemData.end = snap ? snap(end, scale, step) : end;
  17348. }
  17349. } else {
  17350. if (itemData.start != undefined) {
  17351. var initialStart = util.convert(props.data.start, 'Date');
  17352. var start = new Date(initialStart.valueOf() + offset);
  17353. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  17354. itemData.start = snap ? snap(start, scale, step) : start;
  17355. }
  17356. }
  17357. } else if (props.dragRight) {
  17358. // drag right side of a range item
  17359. if (this.options.rtl) {
  17360. if (itemData.start != undefined) {
  17361. var initialStart = util.convert(props.data.start, 'Date');
  17362. var start = new Date(initialStart.valueOf() + offset);
  17363. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  17364. itemData.start = snap ? snap(start, scale, step) : start;
  17365. }
  17366. } else {
  17367. if (itemData.end != undefined) {
  17368. var initialEnd = util.convert(props.data.end, 'Date');
  17369. var end = new Date(initialEnd.valueOf() + offset);
  17370. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  17371. itemData.end = snap ? snap(end, scale, step) : end;
  17372. }
  17373. }
  17374. } else {
  17375. // drag both start and end
  17376. if (itemData.start != undefined) {
  17377. var initialStart = util.convert(props.data.start, 'Date').valueOf();
  17378. var start = new Date(initialStart + offset);
  17379. if (itemData.end != undefined) {
  17380. var initialEnd = util.convert(props.data.end, 'Date');
  17381. var duration = initialEnd.valueOf() - initialStart.valueOf();
  17382. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  17383. itemData.start = snap ? snap(start, scale, step) : start;
  17384. itemData.end = new Date(itemData.start.valueOf() + duration);
  17385. } else {
  17386. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  17387. itemData.start = snap ? snap(start, scale, step) : start;
  17388. }
  17389. }
  17390. }
  17391. }
  17392. var updateGroupAllowed = me.options.editable.updateGroup || props.item.editable === true;
  17393. if (updateGroupAllowed && !props.dragLeft && !props.dragRight && newGroupBase != null) {
  17394. if (itemData.group != undefined) {
  17395. var newOffset = newGroupBase - props.groupOffset;
  17396. //make sure we stay in bounds
  17397. newOffset = Math.max(0, newOffset);
  17398. newOffset = Math.min(me.groupIds.length - 1, newOffset);
  17399. itemData.group = me.groupIds[newOffset];
  17400. }
  17401. }
  17402. // confirm moving the item
  17403. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  17404. me.options.onMoving(itemData, function (itemData) {
  17405. if (itemData) {
  17406. props.item.setData(this._cloneItemData(itemData, 'Date'));
  17407. }
  17408. }.bind(this));
  17409. }.bind(this));
  17410. this.stackDirty = true; // force re-stacking of all items next redraw
  17411. this.body.emitter.emit('_change');
  17412. }
  17413. };
  17414. /**
  17415. * Move an item to another group
  17416. * @param {Item} item
  17417. * @param {String | Number} groupId
  17418. * @private
  17419. */
  17420. ItemSet.prototype._moveToGroup = function (item, groupId) {
  17421. var group = this.groups[groupId];
  17422. if (group && group.groupId != item.data.group) {
  17423. var oldGroup = item.parent;
  17424. oldGroup.remove(item);
  17425. oldGroup.order();
  17426. group.add(item);
  17427. group.order();
  17428. item.data.group = group.groupId;
  17429. }
  17430. };
  17431. /**
  17432. * End of dragging selected items
  17433. * @param {Event} event
  17434. * @private
  17435. */
  17436. ItemSet.prototype._onDragEnd = function (event) {
  17437. if (this.touchParams.itemProps) {
  17438. event.stopPropagation();
  17439. var me = this;
  17440. var dataset = this.itemsData.getDataSet();
  17441. var itemProps = this.touchParams.itemProps;
  17442. this.touchParams.itemProps = null;
  17443. itemProps.forEach(function (props) {
  17444. var id = props.item.id;
  17445. var exists = me.itemsData.get(id, me.itemOptions) != null;
  17446. if (!exists) {
  17447. // add a new item
  17448. me.options.onAdd(props.item.data, function (itemData) {
  17449. me._removeItem(props.item); // remove temporary item
  17450. if (itemData) {
  17451. me.itemsData.getDataSet().add(itemData);
  17452. }
  17453. // force re-stacking of all items next redraw
  17454. me.stackDirty = true;
  17455. me.body.emitter.emit('_change');
  17456. });
  17457. } else {
  17458. // update existing item
  17459. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  17460. me.options.onMove(itemData, function (itemData) {
  17461. if (itemData) {
  17462. // apply changes
  17463. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  17464. dataset.update(itemData);
  17465. } else {
  17466. // restore original values
  17467. props.item.setData(props.data);
  17468. me.stackDirty = true; // force re-stacking of all items next redraw
  17469. me.body.emitter.emit('_change');
  17470. }
  17471. });
  17472. }
  17473. }.bind(this));
  17474. }
  17475. };
  17476. ItemSet.prototype._onGroupDragStart = function (event) {
  17477. if (this.options.groupEditable.order) {
  17478. this.groupTouchParams.group = this.groupFromTarget(event);
  17479. if (this.groupTouchParams.group) {
  17480. event.stopPropagation();
  17481. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  17482. order: this.options.groupOrder
  17483. });
  17484. }
  17485. }
  17486. };
  17487. ItemSet.prototype._onGroupDrag = function (event) {
  17488. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  17489. event.stopPropagation();
  17490. // drag from one group to another
  17491. var group = this.groupFromTarget(event);
  17492. // try to avoid toggling when groups differ in height
  17493. if (group && group.height != this.groupTouchParams.group.height) {
  17494. var movingUp = group.top < this.groupTouchParams.group.top;
  17495. var clientY = event.center ? event.center.y : event.clientY;
  17496. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  17497. var draggedGroupHeight = this.groupTouchParams.group.height;
  17498. if (movingUp) {
  17499. // skip swapping the groups when the dragged group is not below clientY afterwards
  17500. if (targetGroupTop + draggedGroupHeight < clientY) {
  17501. return;
  17502. }
  17503. } else {
  17504. var targetGroupHeight = group.height;
  17505. // skip swapping the groups when the dragged group is not below clientY afterwards
  17506. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  17507. return;
  17508. }
  17509. }
  17510. }
  17511. if (group && group != this.groupTouchParams.group) {
  17512. var groupsData = this.groupsData;
  17513. var targetGroup = groupsData.get(group.groupId);
  17514. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  17515. // switch groups
  17516. if (draggedGroup && targetGroup) {
  17517. this.options.groupOrderSwap(draggedGroup, targetGroup, this.groupsData);
  17518. this.groupsData.update(draggedGroup);
  17519. this.groupsData.update(targetGroup);
  17520. }
  17521. // fetch current order of groups
  17522. var newOrder = this.groupsData.getIds({
  17523. order: this.options.groupOrder
  17524. });
  17525. // in case of changes since _onGroupDragStart
  17526. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  17527. var groupsData = this.groupsData;
  17528. var origOrder = this.groupTouchParams.originalOrder;
  17529. var draggedId = this.groupTouchParams.group.groupId;
  17530. var numGroups = Math.min(origOrder.length, newOrder.length);
  17531. var curPos = 0;
  17532. var newOffset = 0;
  17533. var orgOffset = 0;
  17534. while (curPos < numGroups) {
  17535. // as long as the groups are where they should be step down along the groups order
  17536. while (curPos + newOffset < numGroups && curPos + orgOffset < numGroups && newOrder[curPos + newOffset] == origOrder[curPos + orgOffset]) {
  17537. curPos++;
  17538. }
  17539. // all ok
  17540. if (curPos + newOffset >= numGroups) {
  17541. break;
  17542. }
  17543. // not all ok
  17544. // if dragged group was move upwards everything below should have an offset
  17545. if (newOrder[curPos + newOffset] == draggedId) {
  17546. newOffset = 1;
  17547. continue;
  17548. }
  17549. // if dragged group was move downwards everything above should have an offset
  17550. else if (origOrder[curPos + orgOffset] == draggedId) {
  17551. orgOffset = 1;
  17552. continue;
  17553. }
  17554. // found a group (apart from dragged group) that has the wrong position -> switch with the
  17555. // group at the position where other one should be, fix index arrays and continue
  17556. else {
  17557. var slippedPosition = newOrder.indexOf(origOrder[curPos + orgOffset]);
  17558. var switchGroup = groupsData.get(newOrder[curPos + newOffset]);
  17559. var shouldBeGroup = groupsData.get(origOrder[curPos + orgOffset]);
  17560. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  17561. groupsData.update(switchGroup);
  17562. groupsData.update(shouldBeGroup);
  17563. var switchGroupId = newOrder[curPos + newOffset];
  17564. newOrder[curPos + newOffset] = origOrder[curPos + orgOffset];
  17565. newOrder[slippedPosition] = switchGroupId;
  17566. curPos++;
  17567. }
  17568. }
  17569. }
  17570. }
  17571. }
  17572. };
  17573. ItemSet.prototype._onGroupDragEnd = function (event) {
  17574. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  17575. event.stopPropagation();
  17576. // update existing group
  17577. var me = this;
  17578. var id = me.groupTouchParams.group.groupId;
  17579. var dataset = me.groupsData.getDataSet();
  17580. var groupData = util.extend({}, dataset.get(id)); // clone the data
  17581. me.options.onMoveGroup(groupData, function (groupData) {
  17582. if (groupData) {
  17583. // apply changes
  17584. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  17585. dataset.update(groupData);
  17586. } else {
  17587. // fetch current order of groups
  17588. var newOrder = dataset.getIds({
  17589. order: me.options.groupOrder
  17590. });
  17591. // restore original order
  17592. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  17593. var origOrder = me.groupTouchParams.originalOrder;
  17594. var numGroups = Math.min(origOrder.length, newOrder.length);
  17595. var curPos = 0;
  17596. while (curPos < numGroups) {
  17597. // as long as the groups are where they should be step down along the groups order
  17598. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  17599. curPos++;
  17600. }
  17601. // all ok
  17602. if (curPos >= numGroups) {
  17603. break;
  17604. }
  17605. // found a group that has the wrong position -> switch with the
  17606. // group at the position where other one should be, fix index arrays and continue
  17607. var slippedPosition = newOrder.indexOf(origOrder[curPos]);
  17608. var switchGroup = dataset.get(newOrder[curPos]);
  17609. var shouldBeGroup = dataset.get(origOrder[curPos]);
  17610. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  17611. groupsData.update(switchGroup);
  17612. groupsData.update(shouldBeGroup);
  17613. var switchGroupId = newOrder[curPos];
  17614. newOrder[curPos] = origOrder[curPos];
  17615. newOrder[slippedPosition] = switchGroupId;
  17616. curPos++;
  17617. }
  17618. }
  17619. }
  17620. });
  17621. me.body.emitter.emit('groupDragged', { groupId: id });
  17622. }
  17623. };
  17624. /**
  17625. * Handle selecting/deselecting an item when tapping it
  17626. * @param {Event} event
  17627. * @private
  17628. */
  17629. ItemSet.prototype._onSelectItem = function (event) {
  17630. if (!this.options.selectable) return;
  17631. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  17632. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  17633. if (ctrlKey || shiftKey) {
  17634. this._onMultiSelectItem(event);
  17635. return;
  17636. }
  17637. var oldSelection = this.getSelection();
  17638. var item = this.itemFromTarget(event);
  17639. var selection = item ? [item.id] : [];
  17640. this.setSelection(selection);
  17641. var newSelection = this.getSelection();
  17642. // emit a select event,
  17643. // except when old selection is empty and new selection is still empty
  17644. if (newSelection.length > 0 || oldSelection.length > 0) {
  17645. this.body.emitter.emit('select', {
  17646. items: newSelection,
  17647. event: event
  17648. });
  17649. }
  17650. };
  17651. /**
  17652. * Handle creation and updates of an item on double tap
  17653. * @param event
  17654. * @private
  17655. */
  17656. ItemSet.prototype._onAddItem = function (event) {
  17657. if (!this.options.selectable) return;
  17658. if (!this.options.editable.add) return;
  17659. var me = this;
  17660. var snap = this.options.snap || null;
  17661. var item = this.itemFromTarget(event);
  17662. if (item) {
  17663. // update item
  17664. // execute async handler to update the item (or cancel it)
  17665. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  17666. this.options.onUpdate(itemData, function (itemData) {
  17667. if (itemData) {
  17668. me.itemsData.getDataSet().update(itemData);
  17669. }
  17670. });
  17671. } else {
  17672. // add item
  17673. if (this.options.rtl) {
  17674. var xAbs = util.getAbsoluteRight(this.dom.frame);
  17675. var x = xAbs - event.center.x;
  17676. } else {
  17677. var xAbs = util.getAbsoluteLeft(this.dom.frame);
  17678. var x = event.center.x - xAbs;
  17679. }
  17680. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  17681. // var x = event.center.x - xAbs;
  17682. var start = this.body.util.toTime(x);
  17683. var scale = this.body.util.getScale();
  17684. var step = this.body.util.getStep();
  17685. var newItemData = {
  17686. start: snap ? snap(start, scale, step) : start,
  17687. content: 'new item'
  17688. };
  17689. // when default type is a range, add a default end date to the new item
  17690. if (this.options.type === 'range') {
  17691. var end = this.body.util.toTime(x + this.props.width / 5);
  17692. newItemData.end = snap ? snap(end, scale, step) : end;
  17693. }
  17694. newItemData[this.itemsData._fieldId] = util.randomUUID();
  17695. var group = this.groupFromTarget(event);
  17696. if (group) {
  17697. newItemData.group = group.groupId;
  17698. }
  17699. // execute async handler to customize (or cancel) adding an item
  17700. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  17701. this.options.onAdd(newItemData, function (item) {
  17702. if (item) {
  17703. me.itemsData.getDataSet().add(item);
  17704. // TODO: need to trigger a redraw?
  17705. }
  17706. });
  17707. }
  17708. };
  17709. /**
  17710. * Handle selecting/deselecting multiple items when holding an item
  17711. * @param {Event} event
  17712. * @private
  17713. */
  17714. ItemSet.prototype._onMultiSelectItem = function (event) {
  17715. if (!this.options.selectable) return;
  17716. var item = this.itemFromTarget(event);
  17717. if (item) {
  17718. // multi select items (if allowed)
  17719. var selection = this.options.multiselect ? this.getSelection() // take current selection
  17720. : []; // deselect current selection
  17721. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  17722. if (shiftKey && this.options.multiselect) {
  17723. // select all items between the old selection and the tapped item
  17724. var itemGroup = this.itemsData.get(item.id).group;
  17725. // when filtering get the group of the last selected item
  17726. var lastSelectedGroup = undefined;
  17727. if (this.options.multiselectPerGroup) {
  17728. if (selection.length > 0) {
  17729. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  17730. }
  17731. }
  17732. // determine the selection range
  17733. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  17734. selection.push(item.id);
  17735. }
  17736. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  17737. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  17738. // select all items within the selection range
  17739. selection = [];
  17740. for (var id in this.items) {
  17741. if (this.items.hasOwnProperty(id)) {
  17742. var _item = this.items[id];
  17743. var start = _item.data.start;
  17744. var end = _item.data.end !== undefined ? _item.data.end : start;
  17745. if (start >= range.min && end <= range.max && (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) && !(_item instanceof BackgroundItem)) {
  17746. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  17747. }
  17748. }
  17749. }
  17750. }
  17751. } else {
  17752. // add/remove this item from the current selection
  17753. var index = selection.indexOf(item.id);
  17754. if (index == -1) {
  17755. // item is not yet selected -> select it
  17756. selection.push(item.id);
  17757. } else {
  17758. // item is already selected -> deselect it
  17759. selection.splice(index, 1);
  17760. }
  17761. }
  17762. this.setSelection(selection);
  17763. this.body.emitter.emit('select', {
  17764. items: this.getSelection(),
  17765. event: event
  17766. });
  17767. }
  17768. };
  17769. /**
  17770. * Calculate the time range of a list of items
  17771. * @param {Array.<Object>} itemsData
  17772. * @return {{min: Date, max: Date}} Returns the range of the provided items
  17773. * @private
  17774. */
  17775. ItemSet._getItemRange = function (itemsData) {
  17776. var max = null;
  17777. var min = null;
  17778. itemsData.forEach(function (data) {
  17779. if (min == null || data.start < min) {
  17780. min = data.start;
  17781. }
  17782. if (data.end != undefined) {
  17783. if (max == null || data.end > max) {
  17784. max = data.end;
  17785. }
  17786. } else {
  17787. if (max == null || data.start > max) {
  17788. max = data.start;
  17789. }
  17790. }
  17791. });
  17792. return {
  17793. min: min,
  17794. max: max
  17795. };
  17796. };
  17797. /**
  17798. * Find an item from an event target:
  17799. * searches for the attribute 'timeline-item' in the event target's element tree
  17800. * @param {Event} event
  17801. * @return {Item | null} item
  17802. */
  17803. ItemSet.prototype.itemFromTarget = function (event) {
  17804. var target = event.target;
  17805. while (target) {
  17806. if (target.hasOwnProperty('timeline-item')) {
  17807. return target['timeline-item'];
  17808. }
  17809. target = target.parentNode;
  17810. }
  17811. return null;
  17812. };
  17813. /**
  17814. * Find the Group from an event target:
  17815. * searches for the attribute 'timeline-group' in the event target's element tree
  17816. * @param {Event} event
  17817. * @return {Group | null} group
  17818. */
  17819. ItemSet.prototype.groupFromTarget = function (event) {
  17820. var clientY = event.center ? event.center.y : event.clientY;
  17821. for (var i = 0; i < this.groupIds.length; i++) {
  17822. var groupId = this.groupIds[i];
  17823. var group = this.groups[groupId];
  17824. var foreground = group.dom.foreground;
  17825. var top = util.getAbsoluteTop(foreground);
  17826. if (clientY > top && clientY < top + foreground.offsetHeight) {
  17827. return group;
  17828. }
  17829. if (this.options.orientation.item === 'top') {
  17830. if (i === this.groupIds.length - 1 && clientY > top) {
  17831. return group;
  17832. }
  17833. } else {
  17834. if (i === 0 && clientY < top + foreground.offset) {
  17835. return group;
  17836. }
  17837. }
  17838. }
  17839. return null;
  17840. };
  17841. /**
  17842. * Find the ItemSet from an event target:
  17843. * searches for the attribute 'timeline-itemset' in the event target's element tree
  17844. * @param {Event} event
  17845. * @return {ItemSet | null} item
  17846. */
  17847. ItemSet.itemSetFromTarget = function (event) {
  17848. var target = event.target;
  17849. while (target) {
  17850. if (target.hasOwnProperty('timeline-itemset')) {
  17851. return target['timeline-itemset'];
  17852. }
  17853. target = target.parentNode;
  17854. }
  17855. return null;
  17856. };
  17857. /**
  17858. * Clone the data of an item, and "normalize" it: convert the start and end date
  17859. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  17860. * start and end are converted to Date.
  17861. * @param {Object} itemData, typically `item.data`
  17862. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  17863. * @return {Object} The cloned object
  17864. * @private
  17865. */
  17866. ItemSet.prototype._cloneItemData = function (itemData, type) {
  17867. var clone = util.extend({}, itemData);
  17868. if (!type) {
  17869. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  17870. type = this.itemsData.getDataSet()._options.type;
  17871. }
  17872. if (clone.start != undefined) {
  17873. clone.start = util.convert(clone.start, type && type.start || 'Date');
  17874. }
  17875. if (clone.end != undefined) {
  17876. clone.end = util.convert(clone.end, type && type.end || 'Date');
  17877. }
  17878. return clone;
  17879. };
  17880. module.exports = ItemSet;
  17881. /***/ },
  17882. /* 35 */
  17883. /***/ function(module, exports, __webpack_require__) {
  17884. 'use strict';
  17885. var moment = __webpack_require__(2);
  17886. var DateUtil = __webpack_require__(32);
  17887. var util = __webpack_require__(1);
  17888. /**
  17889. * @constructor TimeStep
  17890. * The class TimeStep is an iterator for dates. You provide a start date and an
  17891. * end date. The class itself determines the best scale (step size) based on the
  17892. * provided start Date, end Date, and minimumStep.
  17893. *
  17894. * If minimumStep is provided, the step size is chosen as close as possible
  17895. * to the minimumStep but larger than minimumStep. If minimumStep is not
  17896. * provided, the scale is set to 1 DAY.
  17897. * The minimumStep should correspond with the onscreen size of about 6 characters
  17898. *
  17899. * Alternatively, you can set a scale by hand.
  17900. * After creation, you can initialize the class by executing first(). Then you
  17901. * can iterate from the start date to the end date via next(). You can check if
  17902. * the end date is reached with the function hasNext(). After each step, you can
  17903. * retrieve the current date via getCurrent().
  17904. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  17905. * days, to years.
  17906. *
  17907. * Version: 1.2
  17908. *
  17909. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  17910. * or new Date(2010, 9, 21, 23, 45, 00)
  17911. * @param {Date} [end] The end date
  17912. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  17913. */
  17914. function TimeStep(start, end, minimumStep, hiddenDates) {
  17915. this.moment = moment;
  17916. // variables
  17917. this.current = this.moment();
  17918. this._start = this.moment();
  17919. this._end = this.moment();
  17920. this.autoScale = true;
  17921. this.scale = 'day';
  17922. this.step = 1;
  17923. // initialize the range
  17924. this.setRange(start, end, minimumStep);
  17925. // hidden Dates options
  17926. this.switchedDay = false;
  17927. this.switchedMonth = false;
  17928. this.switchedYear = false;
  17929. if (Array.isArray(hiddenDates)) {
  17930. this.hiddenDates = hiddenDates;
  17931. } else if (hiddenDates != undefined) {
  17932. this.hiddenDates = [hiddenDates];
  17933. } else {
  17934. this.hiddenDates = [];
  17935. }
  17936. this.format = TimeStep.FORMAT; // default formatting
  17937. }
  17938. // Time formatting
  17939. TimeStep.FORMAT = {
  17940. minorLabels: {
  17941. millisecond: 'SSS',
  17942. second: 's',
  17943. minute: 'HH:mm',
  17944. hour: 'HH:mm',
  17945. weekday: 'ddd D',
  17946. day: 'D',
  17947. month: 'MMM',
  17948. year: 'YYYY'
  17949. },
  17950. majorLabels: {
  17951. millisecond: 'HH:mm:ss',
  17952. second: 'D MMMM HH:mm',
  17953. minute: 'ddd D MMMM',
  17954. hour: 'ddd D MMMM',
  17955. weekday: 'MMMM YYYY',
  17956. day: 'MMMM YYYY',
  17957. month: 'YYYY',
  17958. year: ''
  17959. }
  17960. };
  17961. /**
  17962. * Set custom constructor function for moment. Can be used to set dates
  17963. * to UTC or to set a utcOffset.
  17964. * @param {function} moment
  17965. */
  17966. TimeStep.prototype.setMoment = function (moment) {
  17967. this.moment = moment;
  17968. // update the date properties, can have a new utcOffset
  17969. this.current = this.moment(this.current);
  17970. this._start = this.moment(this._start);
  17971. this._end = this.moment(this._end);
  17972. };
  17973. /**
  17974. * Set custom formatting for the minor an major labels of the TimeStep.
  17975. * Both `minorLabels` and `majorLabels` are an Object with properties:
  17976. * 'millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'.
  17977. * @param {{minorLabels: Object, majorLabels: Object}} format
  17978. */
  17979. TimeStep.prototype.setFormat = function (format) {
  17980. var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
  17981. this.format = util.deepExtend(defaultFormat, format);
  17982. };
  17983. /**
  17984. * Set a new range
  17985. * If minimumStep is provided, the step size is chosen as close as possible
  17986. * to the minimumStep but larger than minimumStep. If minimumStep is not
  17987. * provided, the scale is set to 1 DAY.
  17988. * The minimumStep should correspond with the onscreen size of about 6 characters
  17989. * @param {Date} [start] The start date and time.
  17990. * @param {Date} [end] The end date and time.
  17991. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  17992. */
  17993. TimeStep.prototype.setRange = function (start, end, minimumStep) {
  17994. if (!(start instanceof Date) || !(end instanceof Date)) {
  17995. throw "No legal start or end date in method setRange";
  17996. }
  17997. this._start = start != undefined ? this.moment(start.valueOf()) : new Date();
  17998. this._end = end != undefined ? this.moment(end.valueOf()) : new Date();
  17999. if (this.autoScale) {
  18000. this.setMinimumStep(minimumStep);
  18001. }
  18002. };
  18003. /**
  18004. * Set the range iterator to the start date.
  18005. */
  18006. TimeStep.prototype.start = function () {
  18007. this.current = this._start.clone();
  18008. this.roundToMinor();
  18009. };
  18010. /**
  18011. * Round the current date to the first minor date value
  18012. * This must be executed once when the current date is set to start Date
  18013. */
  18014. TimeStep.prototype.roundToMinor = function () {
  18015. // round to floor
  18016. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  18017. // noinspection FallThroughInSwitchStatementJS
  18018. switch (this.scale) {
  18019. case 'year':
  18020. this.current.year(this.step * Math.floor(this.current.year() / this.step));
  18021. this.current.month(0);
  18022. case 'month':
  18023. this.current.date(1);
  18024. case 'day': // intentional fall through
  18025. case 'weekday':
  18026. this.current.hours(0);
  18027. case 'hour':
  18028. this.current.minutes(0);
  18029. case 'minute':
  18030. this.current.seconds(0);
  18031. case 'second':
  18032. this.current.milliseconds(0);
  18033. //case 'millisecond': // nothing to do for milliseconds
  18034. }
  18035. if (this.step != 1) {
  18036. // round down to the first minor value that is a multiple of the current step size
  18037. switch (this.scale) {
  18038. case 'millisecond':
  18039. this.current.subtract(this.current.milliseconds() % this.step, 'milliseconds');break;
  18040. case 'second':
  18041. this.current.subtract(this.current.seconds() % this.step, 'seconds');break;
  18042. case 'minute':
  18043. this.current.subtract(this.current.minutes() % this.step, 'minutes');break;
  18044. case 'hour':
  18045. this.current.subtract(this.current.hours() % this.step, 'hours');break;
  18046. case 'weekday': // intentional fall through
  18047. case 'day':
  18048. this.current.subtract((this.current.date() - 1) % this.step, 'day');break;
  18049. case 'month':
  18050. this.current.subtract(this.current.month() % this.step, 'month');break;
  18051. case 'year':
  18052. this.current.subtract(this.current.year() % this.step, 'year');break;
  18053. default:
  18054. break;
  18055. }
  18056. }
  18057. };
  18058. /**
  18059. * Check if the there is a next step
  18060. * @return {boolean} true if the current date has not passed the end date
  18061. */
  18062. TimeStep.prototype.hasNext = function () {
  18063. return this.current.valueOf() <= this._end.valueOf();
  18064. };
  18065. /**
  18066. * Do the next step
  18067. */
  18068. TimeStep.prototype.next = function () {
  18069. var prev = this.current.valueOf();
  18070. // Two cases, needed to prevent issues with switching daylight savings
  18071. // (end of March and end of October)
  18072. if (this.current.month() < 6) {
  18073. switch (this.scale) {
  18074. case 'millisecond':
  18075. this.current.add(this.step, 'millisecond');break;
  18076. case 'second':
  18077. this.current.add(this.step, 'second');break;
  18078. case 'minute':
  18079. this.current.add(this.step, 'minute');break;
  18080. case 'hour':
  18081. this.current.add(this.step, 'hour');
  18082. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  18083. // TODO: is this still needed now we use the function of moment.js?
  18084. this.current.subtract(this.current.hours() % this.step, 'hour');
  18085. break;
  18086. case 'weekday': // intentional fall through
  18087. case 'day':
  18088. this.current.add(this.step, 'day');break;
  18089. case 'month':
  18090. this.current.add(this.step, 'month');break;
  18091. case 'year':
  18092. this.current.add(this.step, 'year');break;
  18093. default:
  18094. break;
  18095. }
  18096. } else {
  18097. switch (this.scale) {
  18098. case 'millisecond':
  18099. this.current.add(this.step, 'millisecond');break;
  18100. case 'second':
  18101. this.current.add(this.step, 'second');break;
  18102. case 'minute':
  18103. this.current.add(this.step, 'minute');break;
  18104. case 'hour':
  18105. this.current.add(this.step, 'hour');break;
  18106. case 'weekday': // intentional fall through
  18107. case 'day':
  18108. this.current.add(this.step, 'day');break;
  18109. case 'month':
  18110. this.current.add(this.step, 'month');break;
  18111. case 'year':
  18112. this.current.add(this.step, 'year');break;
  18113. default:
  18114. break;
  18115. }
  18116. }
  18117. if (this.step != 1) {
  18118. // round down to the correct major value
  18119. switch (this.scale) {
  18120. case 'millisecond':
  18121. if (this.current.milliseconds() < this.step) this.current.milliseconds(0);break;
  18122. case 'second':
  18123. if (this.current.seconds() < this.step) this.current.seconds(0);break;
  18124. case 'minute':
  18125. if (this.current.minutes() < this.step) this.current.minutes(0);break;
  18126. case 'hour':
  18127. if (this.current.hours() < this.step) this.current.hours(0);break;
  18128. case 'weekday': // intentional fall through
  18129. case 'day':
  18130. if (this.current.date() < this.step + 1) this.current.date(1);break;
  18131. case 'month':
  18132. if (this.current.month() < this.step) this.current.month(0);break;
  18133. case 'year':
  18134. break; // nothing to do for year
  18135. default:
  18136. break;
  18137. }
  18138. }
  18139. // safety mechanism: if current time is still unchanged, move to the end
  18140. if (this.current.valueOf() == prev) {
  18141. this.current = this._end.clone();
  18142. }
  18143. DateUtil.stepOverHiddenDates(this.moment, this, prev);
  18144. };
  18145. /**
  18146. * Get the current datetime
  18147. * @return {Moment} current The current date
  18148. */
  18149. TimeStep.prototype.getCurrent = function () {
  18150. return this.current;
  18151. };
  18152. /**
  18153. * Set a custom scale. Autoscaling will be disabled.
  18154. * For example setScale('minute', 5) will result
  18155. * in minor steps of 5 minutes, and major steps of an hour.
  18156. *
  18157. * @param {{scale: string, step: number}} params
  18158. * An object containing two properties:
  18159. * - A string 'scale'. Choose from 'millisecond', 'second',
  18160. * 'minute', 'hour', 'weekday', 'day', 'month', 'year'.
  18161. * - A number 'step'. A step size, by default 1.
  18162. * Choose for example 1, 2, 5, or 10.
  18163. */
  18164. TimeStep.prototype.setScale = function (params) {
  18165. if (params && typeof params.scale == 'string') {
  18166. this.scale = params.scale;
  18167. this.step = params.step > 0 ? params.step : 1;
  18168. this.autoScale = false;
  18169. }
  18170. };
  18171. /**
  18172. * Enable or disable autoscaling
  18173. * @param {boolean} enable If true, autoascaling is set true
  18174. */
  18175. TimeStep.prototype.setAutoScale = function (enable) {
  18176. this.autoScale = enable;
  18177. };
  18178. /**
  18179. * Automatically determine the scale that bests fits the provided minimum step
  18180. * @param {Number} [minimumStep] The minimum step size in milliseconds
  18181. */
  18182. TimeStep.prototype.setMinimumStep = function (minimumStep) {
  18183. if (minimumStep == undefined) {
  18184. return;
  18185. }
  18186. //var b = asc + ds;
  18187. var stepYear = 1000 * 60 * 60 * 24 * 30 * 12;
  18188. var stepMonth = 1000 * 60 * 60 * 24 * 30;
  18189. var stepDay = 1000 * 60 * 60 * 24;
  18190. var stepHour = 1000 * 60 * 60;
  18191. var stepMinute = 1000 * 60;
  18192. var stepSecond = 1000;
  18193. var stepMillisecond = 1;
  18194. // find the smallest step that is larger than the provided minimumStep
  18195. if (stepYear * 1000 > minimumStep) {
  18196. this.scale = 'year';this.step = 1000;
  18197. }
  18198. if (stepYear * 500 > minimumStep) {
  18199. this.scale = 'year';this.step = 500;
  18200. }
  18201. if (stepYear * 100 > minimumStep) {
  18202. this.scale = 'year';this.step = 100;
  18203. }
  18204. if (stepYear * 50 > minimumStep) {
  18205. this.scale = 'year';this.step = 50;
  18206. }
  18207. if (stepYear * 10 > minimumStep) {
  18208. this.scale = 'year';this.step = 10;
  18209. }
  18210. if (stepYear * 5 > minimumStep) {
  18211. this.scale = 'year';this.step = 5;
  18212. }
  18213. if (stepYear > minimumStep) {
  18214. this.scale = 'year';this.step = 1;
  18215. }
  18216. if (stepMonth * 3 > minimumStep) {
  18217. this.scale = 'month';this.step = 3;
  18218. }
  18219. if (stepMonth > minimumStep) {
  18220. this.scale = 'month';this.step = 1;
  18221. }
  18222. if (stepDay * 5 > minimumStep) {
  18223. this.scale = 'day';this.step = 5;
  18224. }
  18225. if (stepDay * 2 > minimumStep) {
  18226. this.scale = 'day';this.step = 2;
  18227. }
  18228. if (stepDay > minimumStep) {
  18229. this.scale = 'day';this.step = 1;
  18230. }
  18231. if (stepDay / 2 > minimumStep) {
  18232. this.scale = 'weekday';this.step = 1;
  18233. }
  18234. if (stepHour * 4 > minimumStep) {
  18235. this.scale = 'hour';this.step = 4;
  18236. }
  18237. if (stepHour > minimumStep) {
  18238. this.scale = 'hour';this.step = 1;
  18239. }
  18240. if (stepMinute * 15 > minimumStep) {
  18241. this.scale = 'minute';this.step = 15;
  18242. }
  18243. if (stepMinute * 10 > minimumStep) {
  18244. this.scale = 'minute';this.step = 10;
  18245. }
  18246. if (stepMinute * 5 > minimumStep) {
  18247. this.scale = 'minute';this.step = 5;
  18248. }
  18249. if (stepMinute > minimumStep) {
  18250. this.scale = 'minute';this.step = 1;
  18251. }
  18252. if (stepSecond * 15 > minimumStep) {
  18253. this.scale = 'second';this.step = 15;
  18254. }
  18255. if (stepSecond * 10 > minimumStep) {
  18256. this.scale = 'second';this.step = 10;
  18257. }
  18258. if (stepSecond * 5 > minimumStep) {
  18259. this.scale = 'second';this.step = 5;
  18260. }
  18261. if (stepSecond > minimumStep) {
  18262. this.scale = 'second';this.step = 1;
  18263. }
  18264. if (stepMillisecond * 200 > minimumStep) {
  18265. this.scale = 'millisecond';this.step = 200;
  18266. }
  18267. if (stepMillisecond * 100 > minimumStep) {
  18268. this.scale = 'millisecond';this.step = 100;
  18269. }
  18270. if (stepMillisecond * 50 > minimumStep) {
  18271. this.scale = 'millisecond';this.step = 50;
  18272. }
  18273. if (stepMillisecond * 10 > minimumStep) {
  18274. this.scale = 'millisecond';this.step = 10;
  18275. }
  18276. if (stepMillisecond * 5 > minimumStep) {
  18277. this.scale = 'millisecond';this.step = 5;
  18278. }
  18279. if (stepMillisecond > minimumStep) {
  18280. this.scale = 'millisecond';this.step = 1;
  18281. }
  18282. };
  18283. /**
  18284. * Snap a date to a rounded value.
  18285. * The snap intervals are dependent on the current scale and step.
  18286. * Static function
  18287. * @param {Date} date the date to be snapped.
  18288. * @param {string} scale Current scale, can be 'millisecond', 'second',
  18289. * 'minute', 'hour', 'weekday, 'day', 'month', 'year'.
  18290. * @param {number} step Current step (1, 2, 4, 5, ...
  18291. * @return {Date} snappedDate
  18292. */
  18293. TimeStep.snap = function (date, scale, step) {
  18294. var clone = moment(date);
  18295. if (scale == 'year') {
  18296. var year = clone.year() + Math.round(clone.month() / 12);
  18297. clone.year(Math.round(year / step) * step);
  18298. clone.month(0);
  18299. clone.date(0);
  18300. clone.hours(0);
  18301. clone.minutes(0);
  18302. clone.seconds(0);
  18303. clone.milliseconds(0);
  18304. } else if (scale == 'month') {
  18305. if (clone.date() > 15) {
  18306. clone.date(1);
  18307. clone.add(1, 'month');
  18308. // important: first set Date to 1, after that change the month.
  18309. } else {
  18310. clone.date(1);
  18311. }
  18312. clone.hours(0);
  18313. clone.minutes(0);
  18314. clone.seconds(0);
  18315. clone.milliseconds(0);
  18316. } else if (scale == 'day') {
  18317. //noinspection FallthroughInSwitchStatementJS
  18318. switch (step) {
  18319. case 5:
  18320. case 2:
  18321. clone.hours(Math.round(clone.hours() / 24) * 24);break;
  18322. default:
  18323. clone.hours(Math.round(clone.hours() / 12) * 12);break;
  18324. }
  18325. clone.minutes(0);
  18326. clone.seconds(0);
  18327. clone.milliseconds(0);
  18328. } else if (scale == 'weekday') {
  18329. //noinspection FallthroughInSwitchStatementJS
  18330. switch (step) {
  18331. case 5:
  18332. case 2:
  18333. clone.hours(Math.round(clone.hours() / 12) * 12);break;
  18334. default:
  18335. clone.hours(Math.round(clone.hours() / 6) * 6);break;
  18336. }
  18337. clone.minutes(0);
  18338. clone.seconds(0);
  18339. clone.milliseconds(0);
  18340. } else if (scale == 'hour') {
  18341. switch (step) {
  18342. case 4:
  18343. clone.minutes(Math.round(clone.minutes() / 60) * 60);break;
  18344. default:
  18345. clone.minutes(Math.round(clone.minutes() / 30) * 30);break;
  18346. }
  18347. clone.seconds(0);
  18348. clone.milliseconds(0);
  18349. } else if (scale == 'minute') {
  18350. //noinspection FallthroughInSwitchStatementJS
  18351. switch (step) {
  18352. case 15:
  18353. case 10:
  18354. clone.minutes(Math.round(clone.minutes() / 5) * 5);
  18355. clone.seconds(0);
  18356. break;
  18357. case 5:
  18358. clone.seconds(Math.round(clone.seconds() / 60) * 60);break;
  18359. default:
  18360. clone.seconds(Math.round(clone.seconds() / 30) * 30);break;
  18361. }
  18362. clone.milliseconds(0);
  18363. } else if (scale == 'second') {
  18364. //noinspection FallthroughInSwitchStatementJS
  18365. switch (step) {
  18366. case 15:
  18367. case 10:
  18368. clone.seconds(Math.round(clone.seconds() / 5) * 5);
  18369. clone.milliseconds(0);
  18370. break;
  18371. case 5:
  18372. clone.milliseconds(Math.round(clone.milliseconds() / 1000) * 1000);break;
  18373. default:
  18374. clone.milliseconds(Math.round(clone.milliseconds() / 500) * 500);break;
  18375. }
  18376. } else if (scale == 'millisecond') {
  18377. var _step = step > 5 ? step / 2 : 1;
  18378. clone.milliseconds(Math.round(clone.milliseconds() / _step) * _step);
  18379. }
  18380. return clone;
  18381. };
  18382. /**
  18383. * Check if the current value is a major value (for example when the step
  18384. * is DAY, a major value is each first day of the MONTH)
  18385. * @return {boolean} true if current date is major, else false.
  18386. */
  18387. TimeStep.prototype.isMajor = function () {
  18388. if (this.switchedYear == true) {
  18389. this.switchedYear = false;
  18390. switch (this.scale) {
  18391. case 'year':
  18392. case 'month':
  18393. case 'weekday':
  18394. case 'day':
  18395. case 'hour':
  18396. case 'minute':
  18397. case 'second':
  18398. case 'millisecond':
  18399. return true;
  18400. default:
  18401. return false;
  18402. }
  18403. } else if (this.switchedMonth == true) {
  18404. this.switchedMonth = false;
  18405. switch (this.scale) {
  18406. case 'weekday':
  18407. case 'day':
  18408. case 'hour':
  18409. case 'minute':
  18410. case 'second':
  18411. case 'millisecond':
  18412. return true;
  18413. default:
  18414. return false;
  18415. }
  18416. } else if (this.switchedDay == true) {
  18417. this.switchedDay = false;
  18418. switch (this.scale) {
  18419. case 'millisecond':
  18420. case 'second':
  18421. case 'minute':
  18422. case 'hour':
  18423. return true;
  18424. default:
  18425. return false;
  18426. }
  18427. }
  18428. var date = this.moment(this.current);
  18429. switch (this.scale) {
  18430. case 'millisecond':
  18431. return date.milliseconds() == 0;
  18432. case 'second':
  18433. return date.seconds() == 0;
  18434. case 'minute':
  18435. return date.hours() == 0 && date.minutes() == 0;
  18436. case 'hour':
  18437. return date.hours() == 0;
  18438. case 'weekday': // intentional fall through
  18439. case 'day':
  18440. return date.date() == 1;
  18441. case 'month':
  18442. return date.month() == 0;
  18443. case 'year':
  18444. return false;
  18445. default:
  18446. return false;
  18447. }
  18448. };
  18449. /**
  18450. * Returns formatted text for the minor axislabel, depending on the current
  18451. * date and the scale. For example when scale is MINUTE, the current time is
  18452. * formatted as "hh:mm".
  18453. * @param {Date} [date] custom date. if not provided, current date is taken
  18454. */
  18455. TimeStep.prototype.getLabelMinor = function (date) {
  18456. if (date == undefined) {
  18457. date = this.current;
  18458. }
  18459. var format = this.format.minorLabels[this.scale];
  18460. return format && format.length > 0 ? this.moment(date).format(format) : '';
  18461. };
  18462. /**
  18463. * Returns formatted text for the major axis label, depending on the current
  18464. * date and the scale. For example when scale is MINUTE, the major scale is
  18465. * hours, and the hour will be formatted as "hh".
  18466. * @param {Date} [date] custom date. if not provided, current date is taken
  18467. */
  18468. TimeStep.prototype.getLabelMajor = function (date) {
  18469. if (date == undefined) {
  18470. date = this.current;
  18471. }
  18472. var format = this.format.majorLabels[this.scale];
  18473. return format && format.length > 0 ? this.moment(date).format(format) : '';
  18474. };
  18475. TimeStep.prototype.getClassName = function () {
  18476. var _moment = this.moment;
  18477. var m = this.moment(this.current);
  18478. var current = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function
  18479. var step = this.step;
  18480. function even(value) {
  18481. return value / step % 2 == 0 ? ' vis-even' : ' vis-odd';
  18482. }
  18483. function today(date) {
  18484. if (date.isSame(new Date(), 'day')) {
  18485. return ' vis-today';
  18486. }
  18487. if (date.isSame(_moment().add(1, 'day'), 'day')) {
  18488. return ' vis-tomorrow';
  18489. }
  18490. if (date.isSame(_moment().add(-1, 'day'), 'day')) {
  18491. return ' vis-yesterday';
  18492. }
  18493. return '';
  18494. }
  18495. function currentWeek(date) {
  18496. return date.isSame(new Date(), 'week') ? ' vis-current-week' : '';
  18497. }
  18498. function currentMonth(date) {
  18499. return date.isSame(new Date(), 'month') ? ' vis-current-month' : '';
  18500. }
  18501. function currentYear(date) {
  18502. return date.isSame(new Date(), 'year') ? ' vis-current-year' : '';
  18503. }
  18504. switch (this.scale) {
  18505. case 'millisecond':
  18506. return even(current.milliseconds()).trim();
  18507. case 'second':
  18508. return even(current.seconds()).trim();
  18509. case 'minute':
  18510. return even(current.minutes()).trim();
  18511. case 'hour':
  18512. var hours = current.hours();
  18513. if (this.step == 4) {
  18514. hours = hours + '-h' + (hours + 4);
  18515. }
  18516. return 'vis-h' + hours + today(current) + even(current.hours());
  18517. case 'weekday':
  18518. return 'vis-' + current.format('dddd').toLowerCase() + today(current) + currentWeek(current) + even(current.date());
  18519. case 'day':
  18520. var day = current.date();
  18521. var month = current.format('MMMM').toLowerCase();
  18522. return 'vis-day' + day + ' vis-' + month + currentMonth(current) + even(day - 1);
  18523. case 'month':
  18524. return 'vis-' + current.format('MMMM').toLowerCase() + currentMonth(current) + even(current.month());
  18525. case 'year':
  18526. var year = current.year();
  18527. return 'vis-year' + year + currentYear(current) + even(year);
  18528. default:
  18529. return '';
  18530. }
  18531. };
  18532. module.exports = TimeStep;
  18533. /***/ },
  18534. /* 36 */
  18535. /***/ function(module, exports, __webpack_require__) {
  18536. 'use strict';
  18537. var util = __webpack_require__(1);
  18538. var stack = __webpack_require__(37);
  18539. var RangeItem = __webpack_require__(38);
  18540. /**
  18541. * @constructor Group
  18542. * @param {Number | String} groupId
  18543. * @param {Object} data
  18544. * @param {ItemSet} itemSet
  18545. */
  18546. function Group(groupId, data, itemSet) {
  18547. this.groupId = groupId;
  18548. this.subgroups = {};
  18549. this.subgroupIndex = 0;
  18550. this.subgroupOrderer = data && data.subgroupOrder;
  18551. this.itemSet = itemSet;
  18552. this.dom = {};
  18553. this.props = {
  18554. label: {
  18555. width: 0,
  18556. height: 0
  18557. }
  18558. };
  18559. this.className = null;
  18560. this.items = {}; // items filtered by groupId of this group
  18561. this.visibleItems = []; // items currently visible in window
  18562. this.orderedItems = {
  18563. byStart: [],
  18564. byEnd: []
  18565. };
  18566. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  18567. var me = this;
  18568. this.itemSet.body.emitter.on("checkRangedItems", function () {
  18569. me.checkRangedItems = true;
  18570. });
  18571. this._create();
  18572. this.setData(data);
  18573. }
  18574. /**
  18575. * Create DOM elements for the group
  18576. * @private
  18577. */
  18578. Group.prototype._create = function () {
  18579. var label = document.createElement('div');
  18580. if (this.itemSet.options.groupEditable.order) {
  18581. label.className = 'vis-label draggable';
  18582. } else {
  18583. label.className = 'vis-label';
  18584. }
  18585. this.dom.label = label;
  18586. var inner = document.createElement('div');
  18587. inner.className = 'vis-inner';
  18588. label.appendChild(inner);
  18589. this.dom.inner = inner;
  18590. var foreground = document.createElement('div');
  18591. foreground.className = 'vis-group';
  18592. foreground['timeline-group'] = this;
  18593. this.dom.foreground = foreground;
  18594. this.dom.background = document.createElement('div');
  18595. this.dom.background.className = 'vis-group';
  18596. this.dom.axis = document.createElement('div');
  18597. this.dom.axis.className = 'vis-group';
  18598. // create a hidden marker to detect when the Timelines container is attached
  18599. // to the DOM, or the style of a parent of the Timeline is changed from
  18600. // display:none is changed to visible.
  18601. this.dom.marker = document.createElement('div');
  18602. this.dom.marker.style.visibility = 'hidden';
  18603. this.dom.marker.innerHTML = '?';
  18604. this.dom.background.appendChild(this.dom.marker);
  18605. };
  18606. /**
  18607. * Set the group data for this group
  18608. * @param {Object} data Group data, can contain properties content and className
  18609. */
  18610. Group.prototype.setData = function (data) {
  18611. // update contents
  18612. var content;
  18613. if (this.itemSet.options && this.itemSet.options.groupTemplate) {
  18614. content = this.itemSet.options.groupTemplate(data);
  18615. } else {
  18616. content = data && data.content;
  18617. }
  18618. if (content instanceof Element) {
  18619. this.dom.inner.appendChild(content);
  18620. while (this.dom.inner.firstChild) {
  18621. this.dom.inner.removeChild(this.dom.inner.firstChild);
  18622. }
  18623. this.dom.inner.appendChild(content);
  18624. } else if (content !== undefined && content !== null) {
  18625. this.dom.inner.innerHTML = content;
  18626. } else {
  18627. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  18628. }
  18629. // update title
  18630. this.dom.label.title = data && data.title || '';
  18631. if (!this.dom.inner.firstChild) {
  18632. util.addClassName(this.dom.inner, 'vis-hidden');
  18633. } else {
  18634. util.removeClassName(this.dom.inner, 'vis-hidden');
  18635. }
  18636. // update className
  18637. var className = data && data.className || null;
  18638. if (className != this.className) {
  18639. if (this.className) {
  18640. util.removeClassName(this.dom.label, this.className);
  18641. util.removeClassName(this.dom.foreground, this.className);
  18642. util.removeClassName(this.dom.background, this.className);
  18643. util.removeClassName(this.dom.axis, this.className);
  18644. }
  18645. util.addClassName(this.dom.label, className);
  18646. util.addClassName(this.dom.foreground, className);
  18647. util.addClassName(this.dom.background, className);
  18648. util.addClassName(this.dom.axis, className);
  18649. this.className = className;
  18650. }
  18651. // update style
  18652. if (this.style) {
  18653. util.removeCssText(this.dom.label, this.style);
  18654. this.style = null;
  18655. }
  18656. if (data && data.style) {
  18657. util.addCssText(this.dom.label, data.style);
  18658. this.style = data.style;
  18659. }
  18660. };
  18661. /**
  18662. * Get the width of the group label
  18663. * @return {number} width
  18664. */
  18665. Group.prototype.getLabelWidth = function () {
  18666. return this.props.label.width;
  18667. };
  18668. /**
  18669. * Repaint this group
  18670. * @param {{start: number, end: number}} range
  18671. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  18672. * @param {boolean} [restack=false] Force restacking of all items
  18673. * @return {boolean} Returns true if the group is resized
  18674. */
  18675. Group.prototype.redraw = function (range, margin, restack) {
  18676. var resized = false;
  18677. // force recalculation of the height of the items when the marker height changed
  18678. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  18679. var markerHeight = this.dom.marker.clientHeight;
  18680. if (markerHeight != this.lastMarkerHeight) {
  18681. this.lastMarkerHeight = markerHeight;
  18682. util.forEach(this.items, function (item) {
  18683. item.dirty = true;
  18684. if (item.displayed) item.redraw();
  18685. });
  18686. restack = true;
  18687. }
  18688. // recalculate the height of the subgroups
  18689. this._calculateSubGroupHeights();
  18690. // reposition visible items vertically
  18691. if (typeof this.itemSet.options.order === 'function') {
  18692. // a custom order function
  18693. if (restack) {
  18694. // brute force restack of all items
  18695. // show all items
  18696. var me = this;
  18697. var limitSize = false;
  18698. util.forEach(this.items, function (item) {
  18699. if (!item.displayed) {
  18700. item.redraw();
  18701. me.visibleItems.push(item);
  18702. }
  18703. item.repositionX(limitSize);
  18704. });
  18705. // order all items and force a restacking
  18706. var customOrderedItems = this.orderedItems.byStart.slice().sort(function (a, b) {
  18707. return me.itemSet.options.order(a.data, b.data);
  18708. });
  18709. stack.stack(customOrderedItems, margin, true /* restack=true */);
  18710. }
  18711. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  18712. } else {
  18713. // no custom order function, lazy stacking
  18714. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  18715. if (this.itemSet.options.stack) {
  18716. // TODO: ugly way to access options...
  18717. stack.stack(this.visibleItems, margin, restack);
  18718. } else {
  18719. // no stacking
  18720. stack.nostack(this.visibleItems, margin, this.subgroups);
  18721. }
  18722. }
  18723. // recalculate the height of the group
  18724. var height = this._calculateHeight(margin);
  18725. // calculate actual size and position
  18726. var foreground = this.dom.foreground;
  18727. this.top = foreground.offsetTop;
  18728. this.right = foreground.offsetLeft;
  18729. this.width = foreground.offsetWidth;
  18730. resized = util.updateProperty(this, 'height', height) || resized;
  18731. // recalculate size of label
  18732. resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
  18733. resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
  18734. // apply new height
  18735. this.dom.background.style.height = height + 'px';
  18736. this.dom.foreground.style.height = height + 'px';
  18737. this.dom.label.style.height = height + 'px';
  18738. // update vertical position of items after they are re-stacked and the height of the group is calculated
  18739. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  18740. var item = this.visibleItems[i];
  18741. item.repositionY(margin);
  18742. }
  18743. return resized;
  18744. };
  18745. /**
  18746. * recalculate the height of the subgroups
  18747. * @private
  18748. */
  18749. Group.prototype._calculateSubGroupHeights = function () {
  18750. if (Object.keys(this.subgroups).length > 0) {
  18751. var me = this;
  18752. this.resetSubgroups();
  18753. util.forEach(this.visibleItems, function (item) {
  18754. if (item.data.subgroup !== undefined) {
  18755. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height);
  18756. me.subgroups[item.data.subgroup].visible = true;
  18757. }
  18758. });
  18759. }
  18760. };
  18761. /**
  18762. * recalculate the height of the group
  18763. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  18764. * @returns {number} Returns the height
  18765. * @private
  18766. */
  18767. Group.prototype._calculateHeight = function (margin) {
  18768. // recalculate the height of the group
  18769. var height;
  18770. var visibleItems = this.visibleItems;
  18771. if (visibleItems.length > 0) {
  18772. var min = visibleItems[0].top;
  18773. var max = visibleItems[0].top + visibleItems[0].height;
  18774. util.forEach(visibleItems, function (item) {
  18775. min = Math.min(min, item.top);
  18776. max = Math.max(max, item.top + item.height);
  18777. });
  18778. if (min > margin.axis) {
  18779. // there is an empty gap between the lowest item and the axis
  18780. var offset = min - margin.axis;
  18781. max -= offset;
  18782. util.forEach(visibleItems, function (item) {
  18783. item.top -= offset;
  18784. });
  18785. }
  18786. height = max + margin.item.vertical / 2;
  18787. } else {
  18788. height = 0;
  18789. }
  18790. height = Math.max(height, this.props.label.height);
  18791. return height;
  18792. };
  18793. /**
  18794. * Show this group: attach to the DOM
  18795. */
  18796. Group.prototype.show = function () {
  18797. if (!this.dom.label.parentNode) {
  18798. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  18799. }
  18800. if (!this.dom.foreground.parentNode) {
  18801. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  18802. }
  18803. if (!this.dom.background.parentNode) {
  18804. this.itemSet.dom.background.appendChild(this.dom.background);
  18805. }
  18806. if (!this.dom.axis.parentNode) {
  18807. this.itemSet.dom.axis.appendChild(this.dom.axis);
  18808. }
  18809. };
  18810. /**
  18811. * Hide this group: remove from the DOM
  18812. */
  18813. Group.prototype.hide = function () {
  18814. var label = this.dom.label;
  18815. if (label.parentNode) {
  18816. label.parentNode.removeChild(label);
  18817. }
  18818. var foreground = this.dom.foreground;
  18819. if (foreground.parentNode) {
  18820. foreground.parentNode.removeChild(foreground);
  18821. }
  18822. var background = this.dom.background;
  18823. if (background.parentNode) {
  18824. background.parentNode.removeChild(background);
  18825. }
  18826. var axis = this.dom.axis;
  18827. if (axis.parentNode) {
  18828. axis.parentNode.removeChild(axis);
  18829. }
  18830. };
  18831. /**
  18832. * Add an item to the group
  18833. * @param {Item} item
  18834. */
  18835. Group.prototype.add = function (item) {
  18836. this.items[item.id] = item;
  18837. item.setParent(this);
  18838. // add to
  18839. if (item.data.subgroup !== undefined) {
  18840. if (this.subgroups[item.data.subgroup] === undefined) {
  18841. this.subgroups[item.data.subgroup] = { height: 0, visible: false, index: this.subgroupIndex, items: [] };
  18842. this.subgroupIndex++;
  18843. }
  18844. this.subgroups[item.data.subgroup].items.push(item);
  18845. }
  18846. this.orderSubgroups();
  18847. if (this.visibleItems.indexOf(item) == -1) {
  18848. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  18849. this._checkIfVisible(item, this.visibleItems, range);
  18850. }
  18851. };
  18852. Group.prototype.orderSubgroups = function () {
  18853. if (this.subgroupOrderer !== undefined) {
  18854. var sortArray = [];
  18855. if (typeof this.subgroupOrderer == 'string') {
  18856. for (var subgroup in this.subgroups) {
  18857. sortArray.push({ subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer] });
  18858. }
  18859. sortArray.sort(function (a, b) {
  18860. return a.sortField - b.sortField;
  18861. });
  18862. } else if (typeof this.subgroupOrderer == 'function') {
  18863. for (var subgroup in this.subgroups) {
  18864. sortArray.push(this.subgroups[subgroup].items[0].data);
  18865. }
  18866. sortArray.sort(this.subgroupOrderer);
  18867. }
  18868. if (sortArray.length > 0) {
  18869. for (var i = 0; i < sortArray.length; i++) {
  18870. this.subgroups[sortArray[i].subgroup].index = i;
  18871. }
  18872. }
  18873. }
  18874. };
  18875. Group.prototype.resetSubgroups = function () {
  18876. for (var subgroup in this.subgroups) {
  18877. if (this.subgroups.hasOwnProperty(subgroup)) {
  18878. this.subgroups[subgroup].visible = false;
  18879. }
  18880. }
  18881. };
  18882. /**
  18883. * Remove an item from the group
  18884. * @param {Item} item
  18885. */
  18886. Group.prototype.remove = function (item) {
  18887. delete this.items[item.id];
  18888. item.setParent(null);
  18889. // remove from visible items
  18890. var index = this.visibleItems.indexOf(item);
  18891. if (index != -1) this.visibleItems.splice(index, 1);
  18892. if (item.data.subgroup !== undefined) {
  18893. var subgroup = this.subgroups[item.data.subgroup];
  18894. if (subgroup) {
  18895. var itemIndex = subgroup.items.indexOf(item);
  18896. subgroup.items.splice(itemIndex, 1);
  18897. if (!subgroup.items.length) {
  18898. delete this.subgroups[item.data.subgroup];
  18899. this.subgroupIndex--;
  18900. }
  18901. this.orderSubgroups();
  18902. }
  18903. }
  18904. };
  18905. /**
  18906. * Remove an item from the corresponding DataSet
  18907. * @param {Item} item
  18908. */
  18909. Group.prototype.removeFromDataSet = function (item) {
  18910. this.itemSet.removeItem(item.id);
  18911. };
  18912. /**
  18913. * Reorder the items
  18914. */
  18915. Group.prototype.order = function () {
  18916. var array = util.toArray(this.items);
  18917. var startArray = [];
  18918. var endArray = [];
  18919. for (var i = 0; i < array.length; i++) {
  18920. if (array[i].data.end !== undefined) {
  18921. endArray.push(array[i]);
  18922. }
  18923. startArray.push(array[i]);
  18924. }
  18925. this.orderedItems = {
  18926. byStart: startArray,
  18927. byEnd: endArray
  18928. };
  18929. stack.orderByStart(this.orderedItems.byStart);
  18930. stack.orderByEnd(this.orderedItems.byEnd);
  18931. };
  18932. /**
  18933. * Update the visible items
  18934. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  18935. * @param {Item[]} visibleItems The previously visible items.
  18936. * @param {{start: number, end: number}} range Visible range
  18937. * @return {Item[]} visibleItems The new visible items.
  18938. * @private
  18939. */
  18940. Group.prototype._updateVisibleItems = function (orderedItems, oldVisibleItems, range) {
  18941. var visibleItems = [];
  18942. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  18943. var interval = (range.end - range.start) / 4;
  18944. var lowerBound = range.start - interval;
  18945. var upperBound = range.end + interval;
  18946. var item, i;
  18947. // this function is used to do the binary search.
  18948. var searchFunction = function searchFunction(value) {
  18949. if (value < lowerBound) {
  18950. return -1;
  18951. } else if (value <= upperBound) {
  18952. return 0;
  18953. } else {
  18954. return 1;
  18955. }
  18956. };
  18957. // first check if the items that were in view previously are still in view.
  18958. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  18959. // also cleans up invisible items.
  18960. if (oldVisibleItems.length > 0) {
  18961. for (i = 0; i < oldVisibleItems.length; i++) {
  18962. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  18963. }
  18964. }
  18965. // we do a binary search for the items that have only start values.
  18966. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start');
  18967. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  18968. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  18969. return item.data.start < lowerBound || item.data.start > upperBound;
  18970. });
  18971. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  18972. // We therefore have to brute force check all items in the byEnd list
  18973. if (this.checkRangedItems == true) {
  18974. this.checkRangedItems = false;
  18975. for (i = 0; i < orderedItems.byEnd.length; i++) {
  18976. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  18977. }
  18978. } else {
  18979. // we do a binary search for the items that have defined end times.
  18980. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data', 'end');
  18981. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  18982. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  18983. return item.data.end < lowerBound || item.data.end > upperBound;
  18984. });
  18985. }
  18986. // finally, we reposition all the visible items.
  18987. for (i = 0; i < visibleItems.length; i++) {
  18988. item = visibleItems[i];
  18989. if (!item.displayed) item.show();
  18990. // reposition item horizontally
  18991. item.repositionX();
  18992. }
  18993. // debug
  18994. //console.log("new line")
  18995. //if (this.groupId == null) {
  18996. // for (i = 0; i < orderedItems.byStart.length; i++) {
  18997. // item = orderedItems.byStart[i].data;
  18998. // console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
  18999. // }
  19000. // for (i = 0; i < orderedItems.byEnd.length; i++) {
  19001. // item = orderedItems.byEnd[i].data;
  19002. // console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
  19003. // }
  19004. //}
  19005. return visibleItems;
  19006. };
  19007. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  19008. var item;
  19009. var i;
  19010. if (initialPos != -1) {
  19011. for (i = initialPos; i >= 0; i--) {
  19012. item = items[i];
  19013. if (breakCondition(item)) {
  19014. break;
  19015. } else {
  19016. if (visibleItemsLookup[item.id] === undefined) {
  19017. visibleItemsLookup[item.id] = true;
  19018. visibleItems.push(item);
  19019. }
  19020. }
  19021. }
  19022. for (i = initialPos + 1; i < items.length; i++) {
  19023. item = items[i];
  19024. if (breakCondition(item)) {
  19025. break;
  19026. } else {
  19027. if (visibleItemsLookup[item.id] === undefined) {
  19028. visibleItemsLookup[item.id] = true;
  19029. visibleItems.push(item);
  19030. }
  19031. }
  19032. }
  19033. }
  19034. };
  19035. /**
  19036. * this function is very similar to the _checkIfInvisible() but it does not
  19037. * return booleans, hides the item if it should not be seen and always adds to
  19038. * the visibleItems.
  19039. * this one is for brute forcing and hiding.
  19040. *
  19041. * @param {Item} item
  19042. * @param {Array} visibleItems
  19043. * @param {{start:number, end:number}} range
  19044. * @private
  19045. */
  19046. Group.prototype._checkIfVisible = function (item, visibleItems, range) {
  19047. if (item.isVisible(range)) {
  19048. if (!item.displayed) item.show();
  19049. // reposition item horizontally
  19050. item.repositionX();
  19051. visibleItems.push(item);
  19052. } else {
  19053. if (item.displayed) item.hide();
  19054. }
  19055. };
  19056. /**
  19057. * this function is very similar to the _checkIfInvisible() but it does not
  19058. * return booleans, hides the item if it should not be seen and always adds to
  19059. * the visibleItems.
  19060. * this one is for brute forcing and hiding.
  19061. *
  19062. * @param {Item} item
  19063. * @param {Array} visibleItems
  19064. * @param {{start:number, end:number}} range
  19065. * @private
  19066. */
  19067. Group.prototype._checkIfVisibleWithReference = function (item, visibleItems, visibleItemsLookup, range) {
  19068. if (item.isVisible(range)) {
  19069. if (visibleItemsLookup[item.id] === undefined) {
  19070. visibleItemsLookup[item.id] = true;
  19071. visibleItems.push(item);
  19072. }
  19073. } else {
  19074. if (item.displayed) item.hide();
  19075. }
  19076. };
  19077. module.exports = Group;
  19078. /***/ },
  19079. /* 37 */
  19080. /***/ function(module, exports) {
  19081. 'use strict';
  19082. // Utility functions for ordering and stacking of items
  19083. var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
  19084. /**
  19085. * Order items by their start data
  19086. * @param {Item[]} items
  19087. */
  19088. exports.orderByStart = function (items) {
  19089. items.sort(function (a, b) {
  19090. return a.data.start - b.data.start;
  19091. });
  19092. };
  19093. /**
  19094. * Order items by their end date. If they have no end date, their start date
  19095. * is used.
  19096. * @param {Item[]} items
  19097. */
  19098. exports.orderByEnd = function (items) {
  19099. items.sort(function (a, b) {
  19100. var aTime = 'end' in a.data ? a.data.end : a.data.start,
  19101. bTime = 'end' in b.data ? b.data.end : b.data.start;
  19102. return aTime - bTime;
  19103. });
  19104. };
  19105. /**
  19106. * Adjust vertical positions of the items such that they don't overlap each
  19107. * other.
  19108. * @param {Item[]} items
  19109. * All visible items
  19110. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  19111. * Margins between items and between items and the axis.
  19112. * @param {boolean} [force=false]
  19113. * If true, all items will be repositioned. If false (default), only
  19114. * items having a top===null will be re-stacked
  19115. */
  19116. exports.stack = function (items, margin, force) {
  19117. var i, iMax;
  19118. if (force) {
  19119. // reset top position of all items
  19120. for (i = 0, iMax = items.length; i < iMax; i++) {
  19121. items[i].top = null;
  19122. }
  19123. }
  19124. // calculate new, non-overlapping positions
  19125. for (i = 0, iMax = items.length; i < iMax; i++) {
  19126. var item = items[i];
  19127. if (item.stack && item.top === null) {
  19128. // initialize top position
  19129. item.top = margin.axis;
  19130. do {
  19131. // TODO: optimize checking for overlap. when there is a gap without items,
  19132. // you only need to check for items from the next item on, not from zero
  19133. var collidingItem = null;
  19134. for (var j = 0, jj = items.length; j < jj; j++) {
  19135. var other = items[j];
  19136. if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item, other.options.rtl)) {
  19137. collidingItem = other;
  19138. break;
  19139. }
  19140. }
  19141. if (collidingItem != null) {
  19142. // There is a collision. Reposition the items above the colliding element
  19143. item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
  19144. }
  19145. } while (collidingItem);
  19146. }
  19147. }
  19148. };
  19149. /**
  19150. * Adjust vertical positions of the items without stacking them
  19151. * @param {Item[]} items
  19152. * All visible items
  19153. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  19154. * Margins between items and between items and the axis.
  19155. */
  19156. exports.nostack = function (items, margin, subgroups) {
  19157. var i, iMax, newTop;
  19158. // reset top position of all items
  19159. for (i = 0, iMax = items.length; i < iMax; i++) {
  19160. if (items[i].data.subgroup !== undefined) {
  19161. newTop = margin.axis;
  19162. for (var subgroup in subgroups) {
  19163. if (subgroups.hasOwnProperty(subgroup)) {
  19164. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) {
  19165. newTop += subgroups[subgroup].height + margin.item.vertical;
  19166. }
  19167. }
  19168. }
  19169. items[i].top = newTop;
  19170. } else {
  19171. items[i].top = margin.axis;
  19172. }
  19173. }
  19174. };
  19175. /**
  19176. * Test if the two provided items collide
  19177. * The items must have parameters left, width, top, and height.
  19178. * @param {Item} a The first item
  19179. * @param {Item} b The second item
  19180. * @param {{horizontal: number, vertical: number}} margin
  19181. * An object containing a horizontal and vertical
  19182. * minimum required margin.
  19183. * @param {boolean} rtl
  19184. * @return {boolean} true if a and b collide, else false
  19185. */
  19186. exports.collision = function (a, b, margin, rtl) {
  19187. if (rtl) {
  19188. return a.right - margin.horizontal + EPSILON < b.right + b.width && a.right + a.width + margin.horizontal - EPSILON > b.right && a.top - margin.vertical + EPSILON < b.top + b.height && a.top + a.height + margin.vertical - EPSILON > b.top;
  19189. } else {
  19190. return a.left - margin.horizontal + EPSILON < b.left + b.width && a.left + a.width + margin.horizontal - EPSILON > b.left && a.top - margin.vertical + EPSILON < b.top + b.height && a.top + a.height + margin.vertical - EPSILON > b.top;
  19191. }
  19192. };
  19193. /***/ },
  19194. /* 38 */
  19195. /***/ function(module, exports, __webpack_require__) {
  19196. 'use strict';
  19197. var Hammer = __webpack_require__(20);
  19198. var Item = __webpack_require__(39);
  19199. /**
  19200. * @constructor RangeItem
  19201. * @extends Item
  19202. * @param {Object} data Object containing parameters start, end
  19203. * content, className.
  19204. * @param {{toScreen: function, toTime: function}} conversion
  19205. * Conversion functions from time to screen and vice versa
  19206. * @param {Object} [options] Configuration options
  19207. * // TODO: describe options
  19208. */
  19209. function RangeItem(data, conversion, options) {
  19210. this.props = {
  19211. content: {
  19212. width: 0
  19213. }
  19214. };
  19215. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  19216. this.options = options;
  19217. // validate data
  19218. if (data) {
  19219. if (data.start == undefined) {
  19220. throw new Error('Property "start" missing in item ' + data.id);
  19221. }
  19222. if (data.end == undefined) {
  19223. throw new Error('Property "end" missing in item ' + data.id);
  19224. }
  19225. }
  19226. Item.call(this, data, conversion, options);
  19227. }
  19228. RangeItem.prototype = new Item(null, null, null);
  19229. RangeItem.prototype.baseClassName = 'vis-item vis-range';
  19230. /**
  19231. * Check whether this item is visible inside given range
  19232. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  19233. * @returns {boolean} True if visible
  19234. */
  19235. RangeItem.prototype.isVisible = function (range) {
  19236. // determine visibility
  19237. return this.data.start < range.end && this.data.end > range.start;
  19238. };
  19239. /**
  19240. * Repaint the item
  19241. */
  19242. RangeItem.prototype.redraw = function () {
  19243. var dom = this.dom;
  19244. if (!dom) {
  19245. // create DOM
  19246. this.dom = {};
  19247. dom = this.dom;
  19248. // background box
  19249. dom.box = document.createElement('div');
  19250. // className is updated in redraw()
  19251. // frame box (to prevent the item contents from overflowing
  19252. dom.frame = document.createElement('div');
  19253. dom.frame.className = 'vis-item-overflow';
  19254. dom.box.appendChild(dom.frame);
  19255. // contents box
  19256. dom.content = document.createElement('div');
  19257. dom.content.className = 'vis-item-content';
  19258. dom.frame.appendChild(dom.content);
  19259. // attach this item as attribute
  19260. dom.box['timeline-item'] = this;
  19261. this.dirty = true;
  19262. }
  19263. // append DOM to parent DOM
  19264. if (!this.parent) {
  19265. throw new Error('Cannot redraw item: no parent attached');
  19266. }
  19267. if (!dom.box.parentNode) {
  19268. var foreground = this.parent.dom.foreground;
  19269. if (!foreground) {
  19270. throw new Error('Cannot redraw item: parent has no foreground container element');
  19271. }
  19272. foreground.appendChild(dom.box);
  19273. }
  19274. this.displayed = true;
  19275. // Update DOM when item is marked dirty. An item is marked dirty when:
  19276. // - the item is not yet rendered
  19277. // - the item's data is changed
  19278. // - the item is selected/deselected
  19279. if (this.dirty) {
  19280. this._updateContents(this.dom.content);
  19281. this._updateTitle(this.dom.box);
  19282. this._updateDataAttributes(this.dom.box);
  19283. this._updateStyle(this.dom.box);
  19284. var editable = (this.options.editable.updateTime || this.options.editable.updateGroup || this.editable === true) && this.editable !== false;
  19285. // update class
  19286. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
  19287. dom.box.className = this.baseClassName + className;
  19288. // determine from css whether this box has overflow
  19289. this.overflow = window.getComputedStyle(dom.frame).overflow !== 'hidden';
  19290. // recalculate size
  19291. // turn off max-width to be able to calculate the real width
  19292. // this causes an extra browser repaint/reflow, but so be it
  19293. this.dom.content.style.maxWidth = 'none';
  19294. this.props.content.width = this.dom.content.offsetWidth;
  19295. this.height = this.dom.box.offsetHeight;
  19296. this.dom.content.style.maxWidth = '';
  19297. this.dirty = false;
  19298. }
  19299. this._repaintDeleteButton(dom.box);
  19300. this._repaintDragLeft();
  19301. this._repaintDragRight();
  19302. };
  19303. /**
  19304. * Show the item in the DOM (when not already visible). The items DOM will
  19305. * be created when needed.
  19306. */
  19307. RangeItem.prototype.show = function () {
  19308. if (!this.displayed) {
  19309. this.redraw();
  19310. }
  19311. };
  19312. /**
  19313. * Hide the item from the DOM (when visible)
  19314. * @return {Boolean} changed
  19315. */
  19316. RangeItem.prototype.hide = function () {
  19317. if (this.displayed) {
  19318. var box = this.dom.box;
  19319. if (box.parentNode) {
  19320. box.parentNode.removeChild(box);
  19321. }
  19322. this.displayed = false;
  19323. }
  19324. };
  19325. /**
  19326. * Reposition the item horizontally
  19327. * @param {boolean} [limitSize=true] If true (default), the width of the range
  19328. * item will be limited, as the browser cannot
  19329. * display very wide divs. This means though
  19330. * that the applied left and width may
  19331. * not correspond to the ranges start and end
  19332. * @Override
  19333. */
  19334. RangeItem.prototype.repositionX = function (limitSize) {
  19335. var parentWidth = this.parent.width;
  19336. var start = this.conversion.toScreen(this.data.start);
  19337. var end = this.conversion.toScreen(this.data.end);
  19338. var contentStartPosition;
  19339. var contentWidth;
  19340. // limit the width of the range, as browsers cannot draw very wide divs
  19341. if (limitSize === undefined || limitSize === true) {
  19342. if (start < -parentWidth) {
  19343. start = -parentWidth;
  19344. }
  19345. if (end > 2 * parentWidth) {
  19346. end = 2 * parentWidth;
  19347. }
  19348. }
  19349. var boxWidth = Math.max(end - start, 1);
  19350. if (this.overflow) {
  19351. if (this.options.rtl) {
  19352. this.right = start;
  19353. } else {
  19354. this.left = start;
  19355. }
  19356. this.width = boxWidth + this.props.content.width;
  19357. contentWidth = this.props.content.width;
  19358. // Note: The calculation of width is an optimistic calculation, giving
  19359. // a width which will not change when moving the Timeline
  19360. // So no re-stacking needed, which is nicer for the eye;
  19361. } else {
  19362. if (this.options.rtl) {
  19363. this.right = start;
  19364. } else {
  19365. this.left = start;
  19366. }
  19367. this.width = boxWidth;
  19368. contentWidth = Math.min(end - start, this.props.content.width);
  19369. }
  19370. if (this.options.rtl) {
  19371. this.dom.box.style.right = this.right + 'px';
  19372. } else {
  19373. this.dom.box.style.left = this.left + 'px';
  19374. }
  19375. this.dom.box.style.width = boxWidth + 'px';
  19376. switch (this.options.align) {
  19377. case 'left':
  19378. if (this.options.rtl) {
  19379. this.dom.content.style.right = '0';
  19380. } else {
  19381. this.dom.content.style.left = '0';
  19382. }
  19383. break;
  19384. case 'right':
  19385. if (this.options.rtl) {
  19386. this.dom.content.style.right = Math.max(boxWidth - contentWidth, 0) + 'px';
  19387. } else {
  19388. this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px';
  19389. }
  19390. break;
  19391. case 'center':
  19392. if (this.options.rtl) {
  19393. this.dom.content.style.right = Math.max((boxWidth - contentWidth) / 2, 0) + 'px';
  19394. } else {
  19395. this.dom.content.style.left = Math.max((boxWidth - contentWidth) / 2, 0) + 'px';
  19396. }
  19397. break;
  19398. default:
  19399. // 'auto'
  19400. // when range exceeds left of the window, position the contents at the left of the visible area
  19401. if (this.overflow) {
  19402. if (end > 0) {
  19403. contentStartPosition = Math.max(-start, 0);
  19404. } else {
  19405. contentStartPosition = -contentWidth; // ensure it's not visible anymore
  19406. }
  19407. } else {
  19408. if (start < 0) {
  19409. contentStartPosition = -start;
  19410. } else {
  19411. contentStartPosition = 0;
  19412. }
  19413. }
  19414. if (this.options.rtl) {
  19415. this.dom.content.style.right = contentStartPosition + 'px';
  19416. } else {
  19417. this.dom.content.style.left = contentStartPosition + 'px';
  19418. }
  19419. }
  19420. };
  19421. /**
  19422. * Reposition the item vertically
  19423. * @Override
  19424. */
  19425. RangeItem.prototype.repositionY = function () {
  19426. var orientation = this.options.orientation.item;
  19427. var box = this.dom.box;
  19428. if (orientation == 'top') {
  19429. box.style.top = this.top + 'px';
  19430. } else {
  19431. box.style.top = this.parent.height - this.top - this.height + 'px';
  19432. }
  19433. };
  19434. /**
  19435. * Repaint a drag area on the left side of the range when the range is selected
  19436. * @protected
  19437. */
  19438. RangeItem.prototype._repaintDragLeft = function () {
  19439. if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
  19440. // create and show drag area
  19441. var dragLeft = document.createElement('div');
  19442. dragLeft.className = 'vis-drag-left';
  19443. dragLeft.dragLeftItem = this;
  19444. this.dom.box.appendChild(dragLeft);
  19445. this.dom.dragLeft = dragLeft;
  19446. } else if (!this.selected && this.dom.dragLeft) {
  19447. // delete drag area
  19448. if (this.dom.dragLeft.parentNode) {
  19449. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  19450. }
  19451. this.dom.dragLeft = null;
  19452. }
  19453. };
  19454. /**
  19455. * Repaint a drag area on the right side of the range when the range is selected
  19456. * @protected
  19457. */
  19458. RangeItem.prototype._repaintDragRight = function () {
  19459. if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
  19460. // create and show drag area
  19461. var dragRight = document.createElement('div');
  19462. dragRight.className = 'vis-drag-right';
  19463. dragRight.dragRightItem = this;
  19464. this.dom.box.appendChild(dragRight);
  19465. this.dom.dragRight = dragRight;
  19466. } else if (!this.selected && this.dom.dragRight) {
  19467. // delete drag area
  19468. if (this.dom.dragRight.parentNode) {
  19469. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  19470. }
  19471. this.dom.dragRight = null;
  19472. }
  19473. };
  19474. module.exports = RangeItem;
  19475. /***/ },
  19476. /* 39 */
  19477. /***/ function(module, exports, __webpack_require__) {
  19478. 'use strict';
  19479. var Hammer = __webpack_require__(20);
  19480. var util = __webpack_require__(1);
  19481. /**
  19482. * @constructor Item
  19483. * @param {Object} data Object containing (optional) parameters type,
  19484. * start, end, content, group, className.
  19485. * @param {{toScreen: function, toTime: function}} conversion
  19486. * Conversion functions from time to screen and vice versa
  19487. * @param {Object} options Configuration options
  19488. * // TODO: describe available options
  19489. */
  19490. function Item(data, conversion, options) {
  19491. this.id = null;
  19492. this.parent = null;
  19493. this.data = data;
  19494. this.dom = null;
  19495. this.conversion = conversion || {};
  19496. this.options = options || {};
  19497. this.selected = false;
  19498. this.displayed = false;
  19499. this.dirty = true;
  19500. this.top = null;
  19501. this.right = null;
  19502. this.left = null;
  19503. this.width = null;
  19504. this.height = null;
  19505. this.editable = null;
  19506. if (this.data && this.data.hasOwnProperty('editable') && typeof this.data.editable === 'boolean') {
  19507. this.editable = data.editable;
  19508. }
  19509. }
  19510. Item.prototype.stack = true;
  19511. /**
  19512. * Select current item
  19513. */
  19514. Item.prototype.select = function () {
  19515. this.selected = true;
  19516. this.dirty = true;
  19517. if (this.displayed) this.redraw();
  19518. };
  19519. /**
  19520. * Unselect current item
  19521. */
  19522. Item.prototype.unselect = function () {
  19523. this.selected = false;
  19524. this.dirty = true;
  19525. if (this.displayed) this.redraw();
  19526. };
  19527. /**
  19528. * Set data for the item. Existing data will be updated. The id should not
  19529. * be changed. When the item is displayed, it will be redrawn immediately.
  19530. * @param {Object} data
  19531. */
  19532. Item.prototype.setData = function (data) {
  19533. var groupChanged = data.group != undefined && this.data.group != data.group;
  19534. if (groupChanged) {
  19535. this.parent.itemSet._moveToGroup(this, data.group);
  19536. }
  19537. if (data.hasOwnProperty('editable') && typeof data.editable === 'boolean') {
  19538. this.editable = data.editable;
  19539. }
  19540. this.data = data;
  19541. this.dirty = true;
  19542. if (this.displayed) this.redraw();
  19543. };
  19544. /**
  19545. * Set a parent for the item
  19546. * @param {ItemSet | Group} parent
  19547. */
  19548. Item.prototype.setParent = function (parent) {
  19549. if (this.displayed) {
  19550. this.hide();
  19551. this.parent = parent;
  19552. if (this.parent) {
  19553. this.show();
  19554. }
  19555. } else {
  19556. this.parent = parent;
  19557. }
  19558. };
  19559. /**
  19560. * Check whether this item is visible inside given range
  19561. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  19562. * @returns {boolean} True if visible
  19563. */
  19564. Item.prototype.isVisible = function (range) {
  19565. // Should be implemented by Item implementations
  19566. return false;
  19567. };
  19568. /**
  19569. * Show the Item in the DOM (when not already visible)
  19570. * @return {Boolean} changed
  19571. */
  19572. Item.prototype.show = function () {
  19573. return false;
  19574. };
  19575. /**
  19576. * Hide the Item from the DOM (when visible)
  19577. * @return {Boolean} changed
  19578. */
  19579. Item.prototype.hide = function () {
  19580. return false;
  19581. };
  19582. /**
  19583. * Repaint the item
  19584. */
  19585. Item.prototype.redraw = function () {
  19586. // should be implemented by the item
  19587. };
  19588. /**
  19589. * Reposition the Item horizontally
  19590. */
  19591. Item.prototype.repositionX = function () {
  19592. // should be implemented by the item
  19593. };
  19594. /**
  19595. * Reposition the Item vertically
  19596. */
  19597. Item.prototype.repositionY = function () {
  19598. // should be implemented by the item
  19599. };
  19600. /**
  19601. * Repaint a delete button on the top right of the item when the item is selected
  19602. * @param {HTMLElement} anchor
  19603. * @protected
  19604. */
  19605. Item.prototype._repaintDeleteButton = function (anchor) {
  19606. var editable = (this.options.editable.remove || this.data.editable === true) && this.data.editable !== false;
  19607. if (this.selected && editable && !this.dom.deleteButton) {
  19608. // create and show button
  19609. var me = this;
  19610. var deleteButton = document.createElement('div');
  19611. if (this.options.rtl) {
  19612. deleteButton.className = 'vis-delete-rtl';
  19613. } else {
  19614. deleteButton.className = 'vis-delete';
  19615. }
  19616. deleteButton.title = 'Delete this item';
  19617. // TODO: be able to destroy the delete button
  19618. new Hammer(deleteButton).on('tap', function (event) {
  19619. event.stopPropagation();
  19620. me.parent.removeFromDataSet(me);
  19621. });
  19622. anchor.appendChild(deleteButton);
  19623. this.dom.deleteButton = deleteButton;
  19624. } else if (!this.selected && this.dom.deleteButton) {
  19625. // remove button
  19626. if (this.dom.deleteButton.parentNode) {
  19627. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  19628. }
  19629. this.dom.deleteButton = null;
  19630. }
  19631. };
  19632. /**
  19633. * Set HTML contents for the item
  19634. * @param {Element} element HTML element to fill with the contents
  19635. * @private
  19636. */
  19637. Item.prototype._updateContents = function (element) {
  19638. var content;
  19639. if (this.options.template) {
  19640. var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
  19641. content = this.options.template(itemData);
  19642. } else {
  19643. content = this.data.content;
  19644. }
  19645. var changed = this._contentToString(this.content) !== this._contentToString(content);
  19646. if (changed) {
  19647. // only replace the content when changed
  19648. if (content instanceof Element) {
  19649. element.innerHTML = '';
  19650. element.appendChild(content);
  19651. } else if (content != undefined) {
  19652. element.innerHTML = content;
  19653. } else {
  19654. if (!(this.data.type == 'background' && this.data.content === undefined)) {
  19655. throw new Error('Property "content" missing in item ' + this.id);
  19656. }
  19657. }
  19658. this.content = content;
  19659. }
  19660. };
  19661. /**
  19662. * Set HTML contents for the item
  19663. * @param {Element} element HTML element to fill with the contents
  19664. * @private
  19665. */
  19666. Item.prototype._updateTitle = function (element) {
  19667. if (this.data.title != null) {
  19668. element.title = this.data.title || '';
  19669. } else {
  19670. element.removeAttribute('vis-title');
  19671. }
  19672. };
  19673. /**
  19674. * Process dataAttributes timeline option and set as data- attributes on dom.content
  19675. * @param {Element} element HTML element to which the attributes will be attached
  19676. * @private
  19677. */
  19678. Item.prototype._updateDataAttributes = function (element) {
  19679. if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
  19680. var attributes = [];
  19681. if (Array.isArray(this.options.dataAttributes)) {
  19682. attributes = this.options.dataAttributes;
  19683. } else if (this.options.dataAttributes == 'all') {
  19684. attributes = Object.keys(this.data);
  19685. } else {
  19686. return;
  19687. }
  19688. for (var i = 0; i < attributes.length; i++) {
  19689. var name = attributes[i];
  19690. var value = this.data[name];
  19691. if (value != null) {
  19692. element.setAttribute('data-' + name, value);
  19693. } else {
  19694. element.removeAttribute('data-' + name);
  19695. }
  19696. }
  19697. }
  19698. };
  19699. /**
  19700. * Update custom styles of the element
  19701. * @param element
  19702. * @private
  19703. */
  19704. Item.prototype._updateStyle = function (element) {
  19705. // remove old styles
  19706. if (this.style) {
  19707. util.removeCssText(element, this.style);
  19708. this.style = null;
  19709. }
  19710. // append new styles
  19711. if (this.data.style) {
  19712. util.addCssText(element, this.data.style);
  19713. this.style = this.data.style;
  19714. }
  19715. };
  19716. /**
  19717. * Stringify the items contents
  19718. * @param {string | Element | undefined} content
  19719. * @returns {string | undefined}
  19720. * @private
  19721. */
  19722. Item.prototype._contentToString = function (content) {
  19723. if (typeof content === 'string') return content;
  19724. if (content && 'outerHTML' in content) return content.outerHTML;
  19725. return content;
  19726. };
  19727. /**
  19728. * Return the width of the item left from its start date
  19729. * @return {number}
  19730. */
  19731. Item.prototype.getWidthLeft = function () {
  19732. return 0;
  19733. };
  19734. /**
  19735. * Return the width of the item right from the max of its start and end date
  19736. * @return {number}
  19737. */
  19738. Item.prototype.getWidthRight = function () {
  19739. return 0;
  19740. };
  19741. module.exports = Item;
  19742. /***/ },
  19743. /* 40 */
  19744. /***/ function(module, exports, __webpack_require__) {
  19745. 'use strict';
  19746. var util = __webpack_require__(1);
  19747. var Group = __webpack_require__(36);
  19748. /**
  19749. * @constructor BackgroundGroup
  19750. * @param {Number | String} groupId
  19751. * @param {Object} data
  19752. * @param {ItemSet} itemSet
  19753. */
  19754. function BackgroundGroup(groupId, data, itemSet) {
  19755. Group.call(this, groupId, data, itemSet);
  19756. this.width = 0;
  19757. this.height = 0;
  19758. this.top = 0;
  19759. this.left = 0;
  19760. }
  19761. BackgroundGroup.prototype = Object.create(Group.prototype);
  19762. /**
  19763. * Repaint this group
  19764. * @param {{start: number, end: number}} range
  19765. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  19766. * @param {boolean} [restack=false] Force restacking of all items
  19767. * @return {boolean} Returns true if the group is resized
  19768. */
  19769. BackgroundGroup.prototype.redraw = function (range, margin, restack) {
  19770. var resized = false;
  19771. this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
  19772. // calculate actual size
  19773. this.width = this.dom.background.offsetWidth;
  19774. // apply new height (just always zero for BackgroundGroup
  19775. this.dom.background.style.height = '0';
  19776. // update vertical position of items after they are re-stacked and the height of the group is calculated
  19777. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  19778. var item = this.visibleItems[i];
  19779. item.repositionY(margin);
  19780. }
  19781. return resized;
  19782. };
  19783. /**
  19784. * Show this group: attach to the DOM
  19785. */
  19786. BackgroundGroup.prototype.show = function () {
  19787. if (!this.dom.background.parentNode) {
  19788. this.itemSet.dom.background.appendChild(this.dom.background);
  19789. }
  19790. };
  19791. module.exports = BackgroundGroup;
  19792. /***/ },
  19793. /* 41 */
  19794. /***/ function(module, exports, __webpack_require__) {
  19795. 'use strict';
  19796. var Item = __webpack_require__(39);
  19797. var util = __webpack_require__(1);
  19798. /**
  19799. * @constructor BoxItem
  19800. * @extends Item
  19801. * @param {Object} data Object containing parameters start
  19802. * content, className.
  19803. * @param {{toScreen: function, toTime: function}} conversion
  19804. * Conversion functions from time to screen and vice versa
  19805. * @param {Object} [options] Configuration options
  19806. * // TODO: describe available options
  19807. */
  19808. function BoxItem(data, conversion, options) {
  19809. this.props = {
  19810. dot: {
  19811. width: 0,
  19812. height: 0
  19813. },
  19814. line: {
  19815. width: 0,
  19816. height: 0
  19817. }
  19818. };
  19819. this.options = options;
  19820. // validate data
  19821. if (data) {
  19822. if (data.start == undefined) {
  19823. throw new Error('Property "start" missing in item ' + data);
  19824. }
  19825. }
  19826. Item.call(this, data, conversion, options);
  19827. }
  19828. BoxItem.prototype = new Item(null, null, null);
  19829. /**
  19830. * Check whether this item is visible inside given range
  19831. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  19832. * @returns {boolean} True if visible
  19833. */
  19834. BoxItem.prototype.isVisible = function (range) {
  19835. // determine visibility
  19836. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  19837. var interval = (range.end - range.start) / 4;
  19838. return this.data.start > range.start - interval && this.data.start < range.end + interval;
  19839. };
  19840. /**
  19841. * Repaint the item
  19842. */
  19843. BoxItem.prototype.redraw = function () {
  19844. var dom = this.dom;
  19845. if (!dom) {
  19846. // create DOM
  19847. this.dom = {};
  19848. dom = this.dom;
  19849. // create main box
  19850. dom.box = document.createElement('DIV');
  19851. // contents box (inside the background box). used for making margins
  19852. dom.content = document.createElement('DIV');
  19853. dom.content.className = 'vis-item-content';
  19854. dom.box.appendChild(dom.content);
  19855. // line to axis
  19856. dom.line = document.createElement('DIV');
  19857. dom.line.className = 'vis-line';
  19858. // dot on axis
  19859. dom.dot = document.createElement('DIV');
  19860. dom.dot.className = 'vis-dot';
  19861. // attach this item as attribute
  19862. dom.box['timeline-item'] = this;
  19863. this.dirty = true;
  19864. }
  19865. // append DOM to parent DOM
  19866. if (!this.parent) {
  19867. throw new Error('Cannot redraw item: no parent attached');
  19868. }
  19869. if (!dom.box.parentNode) {
  19870. var foreground = this.parent.dom.foreground;
  19871. if (!foreground) throw new Error('Cannot redraw item: parent has no foreground container element');
  19872. foreground.appendChild(dom.box);
  19873. }
  19874. if (!dom.line.parentNode) {
  19875. var background = this.parent.dom.background;
  19876. if (!background) throw new Error('Cannot redraw item: parent has no background container element');
  19877. background.appendChild(dom.line);
  19878. }
  19879. if (!dom.dot.parentNode) {
  19880. var axis = this.parent.dom.axis;
  19881. if (!background) throw new Error('Cannot redraw item: parent has no axis container element');
  19882. axis.appendChild(dom.dot);
  19883. }
  19884. this.displayed = true;
  19885. // Update DOM when item is marked dirty. An item is marked dirty when:
  19886. // - the item is not yet rendered
  19887. // - the item's data is changed
  19888. // - the item is selected/deselected
  19889. if (this.dirty) {
  19890. this._updateContents(this.dom.content);
  19891. this._updateTitle(this.dom.box);
  19892. this._updateDataAttributes(this.dom.box);
  19893. this._updateStyle(this.dom.box);
  19894. var editable = (this.options.editable.updateTime || this.options.editable.updateGroup || this.editable === true) && this.editable !== false;
  19895. // update class
  19896. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
  19897. dom.box.className = 'vis-item vis-box' + className;
  19898. dom.line.className = 'vis-item vis-line' + className;
  19899. dom.dot.className = 'vis-item vis-dot' + className;
  19900. // recalculate size
  19901. this.props.dot.height = dom.dot.offsetHeight;
  19902. this.props.dot.width = dom.dot.offsetWidth;
  19903. this.props.line.width = dom.line.offsetWidth;
  19904. this.width = dom.box.offsetWidth;
  19905. this.height = dom.box.offsetHeight;
  19906. this.dirty = false;
  19907. }
  19908. this._repaintDeleteButton(dom.box);
  19909. };
  19910. /**
  19911. * Show the item in the DOM (when not already displayed). The items DOM will
  19912. * be created when needed.
  19913. */
  19914. BoxItem.prototype.show = function () {
  19915. if (!this.displayed) {
  19916. this.redraw();
  19917. }
  19918. };
  19919. /**
  19920. * Hide the item from the DOM (when visible)
  19921. */
  19922. BoxItem.prototype.hide = function () {
  19923. if (this.displayed) {
  19924. var dom = this.dom;
  19925. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  19926. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  19927. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  19928. this.displayed = false;
  19929. }
  19930. };
  19931. /**
  19932. * Reposition the item horizontally
  19933. * @Override
  19934. */
  19935. BoxItem.prototype.repositionX = function () {
  19936. var start = this.conversion.toScreen(this.data.start);
  19937. var align = this.options.align;
  19938. // calculate left position of the box
  19939. if (align == 'right') {
  19940. if (this.options.rtl) {
  19941. this.right = start - this.width;
  19942. // reposition box, line, and dot
  19943. this.dom.box.style.right = this.right + 'px';
  19944. this.dom.line.style.right = start - this.props.line.width + 'px';
  19945. this.dom.dot.style.right = start - this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  19946. } else {
  19947. this.left = start - this.width;
  19948. // reposition box, line, and dot
  19949. this.dom.box.style.left = this.left + 'px';
  19950. this.dom.line.style.left = start - this.props.line.width + 'px';
  19951. this.dom.dot.style.left = start - this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  19952. }
  19953. } else if (align == 'left') {
  19954. if (this.options.rtl) {
  19955. this.right = start;
  19956. // reposition box, line, and dot
  19957. this.dom.box.style.right = this.right + 'px';
  19958. this.dom.line.style.right = start + 'px';
  19959. this.dom.dot.style.right = start + this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  19960. } else {
  19961. this.left = start;
  19962. // reposition box, line, and dot
  19963. this.dom.box.style.left = this.left + 'px';
  19964. this.dom.line.style.left = start + 'px';
  19965. this.dom.dot.style.left = start + this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  19966. }
  19967. } else {
  19968. // default or 'center'
  19969. if (this.options.rtl) {
  19970. this.right = start - this.width / 2;
  19971. // reposition box, line, and dot
  19972. this.dom.box.style.right = this.right + 'px';
  19973. this.dom.line.style.right = start - this.props.line.width + 'px';
  19974. this.dom.dot.style.right = start - this.props.dot.width / 2 + 'px';
  19975. } else {
  19976. this.left = start - this.width / 2;
  19977. // reposition box, line, and dot
  19978. this.dom.box.style.left = this.left + 'px';
  19979. this.dom.line.style.left = start - this.props.line.width / 2 + 'px';
  19980. this.dom.dot.style.left = start - this.props.dot.width / 2 + 'px';
  19981. }
  19982. }
  19983. };
  19984. /**
  19985. * Reposition the item vertically
  19986. * @Override
  19987. */
  19988. BoxItem.prototype.repositionY = function () {
  19989. var orientation = this.options.orientation.item;
  19990. var box = this.dom.box;
  19991. var line = this.dom.line;
  19992. var dot = this.dom.dot;
  19993. if (orientation == 'top') {
  19994. box.style.top = (this.top || 0) + 'px';
  19995. line.style.top = '0';
  19996. line.style.height = this.parent.top + this.top + 1 + 'px';
  19997. line.style.bottom = '';
  19998. } else {
  19999. // orientation 'bottom'
  20000. var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
  20001. var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
  20002. box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
  20003. line.style.top = itemSetHeight - lineHeight + 'px';
  20004. line.style.bottom = '0';
  20005. }
  20006. dot.style.top = -this.props.dot.height / 2 + 'px';
  20007. };
  20008. /**
  20009. * Return the width of the item left from its start date
  20010. * @return {number}
  20011. */
  20012. BoxItem.prototype.getWidthLeft = function () {
  20013. return this.width / 2;
  20014. };
  20015. /**
  20016. * Return the width of the item right from its start date
  20017. * @return {number}
  20018. */
  20019. BoxItem.prototype.getWidthRight = function () {
  20020. return this.width / 2;
  20021. };
  20022. module.exports = BoxItem;
  20023. /***/ },
  20024. /* 42 */
  20025. /***/ function(module, exports, __webpack_require__) {
  20026. 'use strict';
  20027. var Item = __webpack_require__(39);
  20028. /**
  20029. * @constructor PointItem
  20030. * @extends Item
  20031. * @param {Object} data Object containing parameters start
  20032. * content, className.
  20033. * @param {{toScreen: function, toTime: function}} conversion
  20034. * Conversion functions from time to screen and vice versa
  20035. * @param {Object} [options] Configuration options
  20036. * // TODO: describe available options
  20037. */
  20038. function PointItem(data, conversion, options) {
  20039. this.props = {
  20040. dot: {
  20041. top: 0,
  20042. width: 0,
  20043. height: 0
  20044. },
  20045. content: {
  20046. height: 0,
  20047. marginLeft: 0,
  20048. marginRight: 0
  20049. }
  20050. };
  20051. this.options = options;
  20052. // validate data
  20053. if (data) {
  20054. if (data.start == undefined) {
  20055. throw new Error('Property "start" missing in item ' + data);
  20056. }
  20057. }
  20058. Item.call(this, data, conversion, options);
  20059. }
  20060. PointItem.prototype = new Item(null, null, null);
  20061. /**
  20062. * Check whether this item is visible inside given range
  20063. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  20064. * @returns {boolean} True if visible
  20065. */
  20066. PointItem.prototype.isVisible = function (range) {
  20067. // determine visibility
  20068. // TODO: account for the real width of the item. Right now we just add 1/4 to the window
  20069. var interval = (range.end - range.start) / 4;
  20070. return this.data.start > range.start - interval && this.data.start < range.end + interval;
  20071. };
  20072. /**
  20073. * Repaint the item
  20074. */
  20075. PointItem.prototype.redraw = function () {
  20076. var dom = this.dom;
  20077. if (!dom) {
  20078. // create DOM
  20079. this.dom = {};
  20080. dom = this.dom;
  20081. // background box
  20082. dom.point = document.createElement('div');
  20083. // className is updated in redraw()
  20084. // contents box, right from the dot
  20085. dom.content = document.createElement('div');
  20086. dom.content.className = 'vis-item-content';
  20087. dom.point.appendChild(dom.content);
  20088. // dot at start
  20089. dom.dot = document.createElement('div');
  20090. dom.point.appendChild(dom.dot);
  20091. // attach this item as attribute
  20092. dom.point['timeline-item'] = this;
  20093. this.dirty = true;
  20094. }
  20095. // append DOM to parent DOM
  20096. if (!this.parent) {
  20097. throw new Error('Cannot redraw item: no parent attached');
  20098. }
  20099. if (!dom.point.parentNode) {
  20100. var foreground = this.parent.dom.foreground;
  20101. if (!foreground) {
  20102. throw new Error('Cannot redraw item: parent has no foreground container element');
  20103. }
  20104. foreground.appendChild(dom.point);
  20105. }
  20106. this.displayed = true;
  20107. // Update DOM when item is marked dirty. An item is marked dirty when:
  20108. // - the item is not yet rendered
  20109. // - the item's data is changed
  20110. // - the item is selected/deselected
  20111. if (this.dirty) {
  20112. this._updateContents(this.dom.content);
  20113. this._updateTitle(this.dom.point);
  20114. this._updateDataAttributes(this.dom.point);
  20115. this._updateStyle(this.dom.point);
  20116. var editable = (this.options.editable.updateTime || this.options.editable.updateGroup || this.editable === true) && this.editable !== false;
  20117. // update class
  20118. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
  20119. dom.point.className = 'vis-item vis-point' + className;
  20120. dom.dot.className = 'vis-item vis-dot' + className;
  20121. // recalculate size of dot and contents
  20122. this.props.dot.width = dom.dot.offsetWidth;
  20123. this.props.dot.height = dom.dot.offsetHeight;
  20124. this.props.content.height = dom.content.offsetHeight;
  20125. // resize contents
  20126. if (this.options.rtl) {
  20127. dom.content.style.marginRight = 2 * this.props.dot.width + 'px';
  20128. } else {
  20129. dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  20130. }
  20131. //dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  20132. // recalculate size
  20133. this.width = dom.point.offsetWidth;
  20134. this.height = dom.point.offsetHeight;
  20135. // reposition the dot
  20136. dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px';
  20137. if (this.options.rtl) {
  20138. dom.dot.style.right = this.props.dot.width / 2 + 'px';
  20139. } else {
  20140. dom.dot.style.left = this.props.dot.width / 2 + 'px';
  20141. }
  20142. this.dirty = false;
  20143. }
  20144. this._repaintDeleteButton(dom.point);
  20145. };
  20146. /**
  20147. * Show the item in the DOM (when not already visible). The items DOM will
  20148. * be created when needed.
  20149. */
  20150. PointItem.prototype.show = function () {
  20151. if (!this.displayed) {
  20152. this.redraw();
  20153. }
  20154. };
  20155. /**
  20156. * Hide the item from the DOM (when visible)
  20157. */
  20158. PointItem.prototype.hide = function () {
  20159. if (this.displayed) {
  20160. if (this.dom.point.parentNode) {
  20161. this.dom.point.parentNode.removeChild(this.dom.point);
  20162. }
  20163. this.displayed = false;
  20164. }
  20165. };
  20166. /**
  20167. * Reposition the item horizontally
  20168. * @Override
  20169. */
  20170. PointItem.prototype.repositionX = function () {
  20171. var start = this.conversion.toScreen(this.data.start);
  20172. if (this.options.rtl) {
  20173. this.right = start - this.props.dot.width;
  20174. // reposition point
  20175. this.dom.point.style.right = this.right + 'px';
  20176. } else {
  20177. this.left = start - this.props.dot.width;
  20178. // reposition point
  20179. this.dom.point.style.left = this.left + 'px';
  20180. }
  20181. };
  20182. /**
  20183. * Reposition the item vertically
  20184. * @Override
  20185. */
  20186. PointItem.prototype.repositionY = function () {
  20187. var orientation = this.options.orientation.item;
  20188. var point = this.dom.point;
  20189. if (orientation == 'top') {
  20190. point.style.top = this.top + 'px';
  20191. } else {
  20192. point.style.top = this.parent.height - this.top - this.height + 'px';
  20193. }
  20194. };
  20195. /**
  20196. * Return the width of the item left from its start date
  20197. * @return {number}
  20198. */
  20199. PointItem.prototype.getWidthLeft = function () {
  20200. return this.props.dot.width;
  20201. };
  20202. /**
  20203. * Return the width of the item right from its start date
  20204. * @return {number}
  20205. */
  20206. PointItem.prototype.getWidthRight = function () {
  20207. return this.props.dot.width;
  20208. };
  20209. module.exports = PointItem;
  20210. /***/ },
  20211. /* 43 */
  20212. /***/ function(module, exports, __webpack_require__) {
  20213. 'use strict';
  20214. var Hammer = __webpack_require__(20);
  20215. var Item = __webpack_require__(39);
  20216. var BackgroundGroup = __webpack_require__(40);
  20217. var RangeItem = __webpack_require__(38);
  20218. /**
  20219. * @constructor BackgroundItem
  20220. * @extends Item
  20221. * @param {Object} data Object containing parameters start, end
  20222. * content, className.
  20223. * @param {{toScreen: function, toTime: function}} conversion
  20224. * Conversion functions from time to screen and vice versa
  20225. * @param {Object} [options] Configuration options
  20226. * // TODO: describe options
  20227. */
  20228. // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
  20229. function BackgroundItem(data, conversion, options) {
  20230. this.props = {
  20231. content: {
  20232. width: 0
  20233. }
  20234. };
  20235. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  20236. // validate data
  20237. if (data) {
  20238. if (data.start == undefined) {
  20239. throw new Error('Property "start" missing in item ' + data.id);
  20240. }
  20241. if (data.end == undefined) {
  20242. throw new Error('Property "end" missing in item ' + data.id);
  20243. }
  20244. }
  20245. Item.call(this, data, conversion, options);
  20246. }
  20247. BackgroundItem.prototype = new Item(null, null, null);
  20248. BackgroundItem.prototype.baseClassName = 'vis-item vis-background';
  20249. BackgroundItem.prototype.stack = false;
  20250. /**
  20251. * Check whether this item is visible inside given range
  20252. * @returns {{start: Number, end: Number}} range with a timestamp for start and end
  20253. * @returns {boolean} True if visible
  20254. */
  20255. BackgroundItem.prototype.isVisible = function (range) {
  20256. // determine visibility
  20257. return this.data.start < range.end && this.data.end > range.start;
  20258. };
  20259. /**
  20260. * Repaint the item
  20261. */
  20262. BackgroundItem.prototype.redraw = function () {
  20263. var dom = this.dom;
  20264. if (!dom) {
  20265. // create DOM
  20266. this.dom = {};
  20267. dom = this.dom;
  20268. // background box
  20269. dom.box = document.createElement('div');
  20270. // className is updated in redraw()
  20271. // frame box (to prevent the item contents from overflowing
  20272. dom.frame = document.createElement('div');
  20273. dom.frame.className = 'vis-item-overflow';
  20274. dom.box.appendChild(dom.frame);
  20275. // contents box
  20276. dom.content = document.createElement('div');
  20277. dom.content.className = 'vis-item-content';
  20278. dom.frame.appendChild(dom.content);
  20279. // Note: we do NOT attach this item as attribute to the DOM,
  20280. // such that background items cannot be selected
  20281. //dom.box['timeline-item'] = this;
  20282. this.dirty = true;
  20283. }
  20284. // append DOM to parent DOM
  20285. if (!this.parent) {
  20286. throw new Error('Cannot redraw item: no parent attached');
  20287. }
  20288. if (!dom.box.parentNode) {
  20289. var background = this.parent.dom.background;
  20290. if (!background) {
  20291. throw new Error('Cannot redraw item: parent has no background container element');
  20292. }
  20293. background.appendChild(dom.box);
  20294. }
  20295. this.displayed = true;
  20296. // Update DOM when item is marked dirty. An item is marked dirty when:
  20297. // - the item is not yet rendered
  20298. // - the item's data is changed
  20299. // - the item is selected/deselected
  20300. if (this.dirty) {
  20301. this._updateContents(this.dom.content);
  20302. this._updateTitle(this.dom.content);
  20303. this._updateDataAttributes(this.dom.content);
  20304. this._updateStyle(this.dom.box);
  20305. // update class
  20306. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '');
  20307. dom.box.className = this.baseClassName + className;
  20308. // determine from css whether this box has overflow
  20309. this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
  20310. // recalculate size
  20311. this.props.content.width = this.dom.content.offsetWidth;
  20312. this.height = 0; // set height zero, so this item will be ignored when stacking items
  20313. this.dirty = false;
  20314. }
  20315. };
  20316. /**
  20317. * Show the item in the DOM (when not already visible). The items DOM will
  20318. * be created when needed.
  20319. */
  20320. BackgroundItem.prototype.show = RangeItem.prototype.show;
  20321. /**
  20322. * Hide the item from the DOM (when visible)
  20323. * @return {Boolean} changed
  20324. */
  20325. BackgroundItem.prototype.hide = RangeItem.prototype.hide;
  20326. /**
  20327. * Reposition the item horizontally
  20328. * @Override
  20329. */
  20330. BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX;
  20331. /**
  20332. * Reposition the item vertically
  20333. * @Override
  20334. */
  20335. BackgroundItem.prototype.repositionY = function (margin) {
  20336. var onTop = this.options.orientation.item === 'top';
  20337. this.dom.content.style.top = onTop ? '' : '0';
  20338. this.dom.content.style.bottom = onTop ? '0' : '';
  20339. var height;
  20340. // special positioning for subgroups
  20341. if (this.data.subgroup !== undefined) {
  20342. // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset
  20343. var itemSubgroup = this.data.subgroup;
  20344. var subgroups = this.parent.subgroups;
  20345. var subgroupIndex = subgroups[itemSubgroup].index;
  20346. // if the orientation is top, we need to take the difference in height into account.
  20347. if (onTop == true) {
  20348. // the first subgroup will have to account for the distance from the top to the first item.
  20349. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  20350. height += subgroupIndex == 0 ? margin.axis - 0.5 * margin.item.vertical : 0;
  20351. var newTop = this.parent.top;
  20352. for (var subgroup in subgroups) {
  20353. if (subgroups.hasOwnProperty(subgroup)) {
  20354. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) {
  20355. newTop += subgroups[subgroup].height + margin.item.vertical;
  20356. }
  20357. }
  20358. }
  20359. // the others will have to be offset downwards with this same distance.
  20360. newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0;
  20361. this.dom.box.style.top = newTop + 'px';
  20362. this.dom.box.style.bottom = '';
  20363. }
  20364. // and when the orientation is bottom:
  20365. else {
  20366. var newTop = this.parent.top;
  20367. var totalHeight = 0;
  20368. for (var subgroup in subgroups) {
  20369. if (subgroups.hasOwnProperty(subgroup)) {
  20370. if (subgroups[subgroup].visible == true) {
  20371. var newHeight = subgroups[subgroup].height + margin.item.vertical;
  20372. totalHeight += newHeight;
  20373. if (subgroups[subgroup].index > subgroupIndex) {
  20374. newTop += newHeight;
  20375. }
  20376. }
  20377. }
  20378. }
  20379. height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
  20380. this.dom.box.style.top = this.parent.height - totalHeight + newTop + 'px';
  20381. this.dom.box.style.bottom = '';
  20382. }
  20383. }
  20384. // and in the case of no subgroups:
  20385. else {
  20386. // we want backgrounds with groups to only show in groups.
  20387. if (this.parent instanceof BackgroundGroup) {
  20388. // if the item is not in a group:
  20389. height = Math.max(this.parent.height, this.parent.itemSet.body.domProps.center.height, this.parent.itemSet.body.domProps.centerContainer.height);
  20390. this.dom.box.style.top = onTop ? '0' : '';
  20391. this.dom.box.style.bottom = onTop ? '' : '0';
  20392. } else {
  20393. height = this.parent.height;
  20394. // same alignment for items when orientation is top or bottom
  20395. this.dom.box.style.top = this.parent.top + 'px';
  20396. this.dom.box.style.bottom = '';
  20397. }
  20398. }
  20399. this.dom.box.style.height = height + 'px';
  20400. };
  20401. module.exports = BackgroundItem;
  20402. /***/ },
  20403. /* 44 */
  20404. /***/ function(module, exports, __webpack_require__) {
  20405. 'use strict';
  20406. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  20407. var util = __webpack_require__(1);
  20408. var Component = __webpack_require__(31);
  20409. var TimeStep = __webpack_require__(35);
  20410. var DateUtil = __webpack_require__(32);
  20411. var moment = __webpack_require__(2);
  20412. /**
  20413. * A horizontal time axis
  20414. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  20415. * @param {Object} [options] See TimeAxis.setOptions for the available
  20416. * options.
  20417. * @constructor TimeAxis
  20418. * @extends Component
  20419. */
  20420. function TimeAxis(body, options) {
  20421. this.dom = {
  20422. foreground: null,
  20423. lines: [],
  20424. majorTexts: [],
  20425. minorTexts: [],
  20426. redundant: {
  20427. lines: [],
  20428. majorTexts: [],
  20429. minorTexts: []
  20430. }
  20431. };
  20432. this.props = {
  20433. range: {
  20434. start: 0,
  20435. end: 0,
  20436. minimumStep: 0
  20437. },
  20438. lineTop: 0
  20439. };
  20440. this.defaultOptions = {
  20441. orientation: {
  20442. axis: 'bottom'
  20443. }, // axis orientation: 'top' or 'bottom'
  20444. showMinorLabels: true,
  20445. showMajorLabels: true,
  20446. maxMinorChars: 7,
  20447. format: TimeStep.FORMAT,
  20448. moment: moment,
  20449. timeAxis: null
  20450. };
  20451. this.options = util.extend({}, this.defaultOptions);
  20452. this.body = body;
  20453. // create the HTML DOM
  20454. this._create();
  20455. this.setOptions(options);
  20456. }
  20457. TimeAxis.prototype = new Component();
  20458. /**
  20459. * Set options for the TimeAxis.
  20460. * Parameters will be merged in current options.
  20461. * @param {Object} options Available options:
  20462. * {string} [orientation.axis]
  20463. * {boolean} [showMinorLabels]
  20464. * {boolean} [showMajorLabels]
  20465. */
  20466. TimeAxis.prototype.setOptions = function (options) {
  20467. if (options) {
  20468. // copy all options that we know
  20469. util.selectiveExtend(['showMinorLabels', 'showMajorLabels', 'maxMinorChars', 'hiddenDates', 'timeAxis', 'moment', 'rtl'], this.options, options);
  20470. // deep copy the format options
  20471. util.selectiveDeepExtend(['format'], this.options, options);
  20472. if ('orientation' in options) {
  20473. if (typeof options.orientation === 'string') {
  20474. this.options.orientation.axis = options.orientation;
  20475. } else if (_typeof(options.orientation) === 'object' && 'axis' in options.orientation) {
  20476. this.options.orientation.axis = options.orientation.axis;
  20477. }
  20478. }
  20479. // apply locale to moment.js
  20480. // TODO: not so nice, this is applied globally to moment.js
  20481. if ('locale' in options) {
  20482. if (typeof moment.locale === 'function') {
  20483. // moment.js 2.8.1+
  20484. moment.locale(options.locale);
  20485. } else {
  20486. moment.lang(options.locale);
  20487. }
  20488. }
  20489. }
  20490. };
  20491. /**
  20492. * Create the HTML DOM for the TimeAxis
  20493. */
  20494. TimeAxis.prototype._create = function () {
  20495. this.dom.foreground = document.createElement('div');
  20496. this.dom.background = document.createElement('div');
  20497. this.dom.foreground.className = 'vis-time-axis vis-foreground';
  20498. this.dom.background.className = 'vis-time-axis vis-background';
  20499. };
  20500. /**
  20501. * Destroy the TimeAxis
  20502. */
  20503. TimeAxis.prototype.destroy = function () {
  20504. // remove from DOM
  20505. if (this.dom.foreground.parentNode) {
  20506. this.dom.foreground.parentNode.removeChild(this.dom.foreground);
  20507. }
  20508. if (this.dom.background.parentNode) {
  20509. this.dom.background.parentNode.removeChild(this.dom.background);
  20510. }
  20511. this.body = null;
  20512. };
  20513. /**
  20514. * Repaint the component
  20515. * @return {boolean} Returns true if the component is resized
  20516. */
  20517. TimeAxis.prototype.redraw = function () {
  20518. var props = this.props;
  20519. var foreground = this.dom.foreground;
  20520. var background = this.dom.background;
  20521. // determine the correct parent DOM element (depending on option orientation)
  20522. var parent = this.options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom;
  20523. var parentChanged = foreground.parentNode !== parent;
  20524. // calculate character width and height
  20525. this._calculateCharSize();
  20526. // TODO: recalculate sizes only needed when parent is resized or options is changed
  20527. var showMinorLabels = this.options.showMinorLabels && this.options.orientation.axis !== 'none';
  20528. var showMajorLabels = this.options.showMajorLabels && this.options.orientation.axis !== 'none';
  20529. // determine the width and height of the elemens for the axis
  20530. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  20531. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  20532. props.height = props.minorLabelHeight + props.majorLabelHeight;
  20533. props.width = foreground.offsetWidth;
  20534. props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (this.options.orientation.axis == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
  20535. props.minorLineWidth = 1; // TODO: really calculate width
  20536. props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
  20537. props.majorLineWidth = 1; // TODO: really calculate width
  20538. // take foreground and background offline while updating (is almost twice as fast)
  20539. var foregroundNextSibling = foreground.nextSibling;
  20540. var backgroundNextSibling = background.nextSibling;
  20541. foreground.parentNode && foreground.parentNode.removeChild(foreground);
  20542. background.parentNode && background.parentNode.removeChild(background);
  20543. foreground.style.height = this.props.height + 'px';
  20544. this._repaintLabels();
  20545. // put DOM online again (at the same place)
  20546. if (foregroundNextSibling) {
  20547. parent.insertBefore(foreground, foregroundNextSibling);
  20548. } else {
  20549. parent.appendChild(foreground);
  20550. }
  20551. if (backgroundNextSibling) {
  20552. this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
  20553. } else {
  20554. this.body.dom.backgroundVertical.appendChild(background);
  20555. }
  20556. return this._isResized() || parentChanged;
  20557. };
  20558. /**
  20559. * Repaint major and minor text labels and vertical grid lines
  20560. * @private
  20561. */
  20562. TimeAxis.prototype._repaintLabels = function () {
  20563. var orientation = this.options.orientation.axis;
  20564. // calculate range and step (step such that we have space for 7 characters per label)
  20565. var start = util.convert(this.body.range.start, 'Number');
  20566. var end = util.convert(this.body.range.end, 'Number');
  20567. var timeLabelsize = this.body.util.toTime((this.props.minorCharWidth || 10) * this.options.maxMinorChars).valueOf();
  20568. var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this.body.range, timeLabelsize);
  20569. minimumStep -= this.body.util.toTime(0).valueOf();
  20570. var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates);
  20571. step.setMoment(this.options.moment);
  20572. if (this.options.format) {
  20573. step.setFormat(this.options.format);
  20574. }
  20575. if (this.options.timeAxis) {
  20576. step.setScale(this.options.timeAxis);
  20577. }
  20578. this.step = step;
  20579. // Move all DOM elements to a "redundant" list, where they
  20580. // can be picked for re-use, and clear the lists with lines and texts.
  20581. // At the end of the function _repaintLabels, left over elements will be cleaned up
  20582. var dom = this.dom;
  20583. dom.redundant.lines = dom.lines;
  20584. dom.redundant.majorTexts = dom.majorTexts;
  20585. dom.redundant.minorTexts = dom.minorTexts;
  20586. dom.lines = [];
  20587. dom.majorTexts = [];
  20588. dom.minorTexts = [];
  20589. var current;
  20590. var next;
  20591. var x;
  20592. var xNext;
  20593. var isMajor, nextIsMajor;
  20594. var width = 0,
  20595. prevWidth;
  20596. var line;
  20597. var labelMinor;
  20598. var xFirstMajorLabel = undefined;
  20599. var count = 0;
  20600. var MAX = 1000;
  20601. var className;
  20602. step.start();
  20603. next = step.getCurrent();
  20604. xNext = this.body.util.toScreen(next);
  20605. while (step.hasNext() && count < MAX) {
  20606. count++;
  20607. isMajor = step.isMajor();
  20608. className = step.getClassName();
  20609. labelMinor = step.getLabelMinor();
  20610. current = next;
  20611. x = xNext;
  20612. step.next();
  20613. next = step.getCurrent();
  20614. nextIsMajor = step.isMajor();
  20615. xNext = this.body.util.toScreen(next);
  20616. prevWidth = width;
  20617. width = xNext - x;
  20618. var showMinorGrid = width >= prevWidth * 0.4; // prevent displaying of the 31th of the month on a scale of 5 days
  20619. if (this.options.showMinorLabels && showMinorGrid) {
  20620. var label = this._repaintMinorText(x, labelMinor, orientation, className);
  20621. label.style.width = width + 'px'; // set width to prevent overflow
  20622. }
  20623. if (isMajor && this.options.showMajorLabels) {
  20624. if (x > 0) {
  20625. if (xFirstMajorLabel == undefined) {
  20626. xFirstMajorLabel = x;
  20627. }
  20628. label = this._repaintMajorText(x, step.getLabelMajor(), orientation, className);
  20629. }
  20630. line = this._repaintMajorLine(x, width, orientation, className);
  20631. } else {
  20632. // minor line
  20633. if (showMinorGrid) {
  20634. line = this._repaintMinorLine(x, width, orientation, className);
  20635. } else {
  20636. if (line) {
  20637. // adjust the width of the previous grid
  20638. line.style.width = parseInt(line.style.width) + width + 'px';
  20639. }
  20640. }
  20641. }
  20642. }
  20643. if (count === MAX && !warnedForOverflow) {
  20644. console.warn('Something is wrong with the Timeline scale. Limited drawing of grid lines to ' + MAX + ' lines.');
  20645. warnedForOverflow = true;
  20646. }
  20647. // create a major label on the left when needed
  20648. if (this.options.showMajorLabels) {
  20649. var leftTime = this.body.util.toTime(0),
  20650. leftText = step.getLabelMajor(leftTime),
  20651. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  20652. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  20653. this._repaintMajorText(0, leftText, orientation, className);
  20654. }
  20655. }
  20656. // Cleanup leftover DOM elements from the redundant list
  20657. util.forEach(this.dom.redundant, function (arr) {
  20658. while (arr.length) {
  20659. var elem = arr.pop();
  20660. if (elem && elem.parentNode) {
  20661. elem.parentNode.removeChild(elem);
  20662. }
  20663. }
  20664. });
  20665. };
  20666. /**
  20667. * Create a minor label for the axis at position x
  20668. * @param {Number} x
  20669. * @param {String} text
  20670. * @param {String} orientation "top" or "bottom" (default)
  20671. * @param {String} className
  20672. * @return {Element} Returns the HTML element of the created label
  20673. * @private
  20674. */
  20675. TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) {
  20676. // reuse redundant label
  20677. var label = this.dom.redundant.minorTexts.shift();
  20678. if (!label) {
  20679. // create new label
  20680. var content = document.createTextNode('');
  20681. label = document.createElement('div');
  20682. label.appendChild(content);
  20683. this.dom.foreground.appendChild(label);
  20684. }
  20685. this.dom.minorTexts.push(label);
  20686. label.childNodes[0].nodeValue = text;
  20687. label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0';
  20688. if (this.options.rtl) {
  20689. label.style.left = "";
  20690. label.style.right = x + 'px';
  20691. } else {
  20692. label.style.left = x + 'px';
  20693. };
  20694. label.className = 'vis-text vis-minor ' + className;
  20695. //label.title = title; // TODO: this is a heavy operation
  20696. return label;
  20697. };
  20698. /**
  20699. * Create a Major label for the axis at position x
  20700. * @param {Number} x
  20701. * @param {String} text
  20702. * @param {String} orientation "top" or "bottom" (default)
  20703. * @param {String} className
  20704. * @return {Element} Returns the HTML element of the created label
  20705. * @private
  20706. */
  20707. TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) {
  20708. // reuse redundant label
  20709. var label = this.dom.redundant.majorTexts.shift();
  20710. if (!label) {
  20711. // create label
  20712. var content = document.createTextNode(text);
  20713. label = document.createElement('div');
  20714. label.appendChild(content);
  20715. this.dom.foreground.appendChild(label);
  20716. }
  20717. this.dom.majorTexts.push(label);
  20718. label.childNodes[0].nodeValue = text;
  20719. label.className = 'vis-text vis-major ' + className;
  20720. //label.title = title; // TODO: this is a heavy operation
  20721. label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px';
  20722. if (this.options.rtl) {
  20723. label.style.left = "";
  20724. label.style.right = x + 'px';
  20725. } else {
  20726. label.style.left = x + 'px';
  20727. };
  20728. return label;
  20729. };
  20730. /**
  20731. * Create a minor line for the axis at position x
  20732. * @param {Number} x
  20733. * @param {Number} width
  20734. * @param {String} orientation "top" or "bottom" (default)
  20735. * @param {String} className
  20736. * @return {Element} Returns the created line
  20737. * @private
  20738. */
  20739. TimeAxis.prototype._repaintMinorLine = function (x, width, orientation, className) {
  20740. // reuse redundant line
  20741. var line = this.dom.redundant.lines.shift();
  20742. if (!line) {
  20743. // create vertical line
  20744. line = document.createElement('div');
  20745. this.dom.background.appendChild(line);
  20746. }
  20747. this.dom.lines.push(line);
  20748. var props = this.props;
  20749. if (orientation == 'top') {
  20750. line.style.top = props.majorLabelHeight + 'px';
  20751. } else {
  20752. line.style.top = this.body.domProps.top.height + 'px';
  20753. }
  20754. line.style.height = props.minorLineHeight + 'px';
  20755. if (this.options.rtl) {
  20756. line.style.left = "";
  20757. line.style.right = x - props.minorLineWidth / 2 + 'px';
  20758. line.className = 'vis-grid vis-vertical-rtl vis-minor ' + className;
  20759. } else {
  20760. line.style.left = x - props.minorLineWidth / 2 + 'px';
  20761. line.className = 'vis-grid vis-vertical vis-minor ' + className;
  20762. };
  20763. line.style.width = width + 'px';
  20764. return line;
  20765. };
  20766. /**
  20767. * Create a Major line for the axis at position x
  20768. * @param {Number} x
  20769. * @param {Number} width
  20770. * @param {String} orientation "top" or "bottom" (default)
  20771. * @param {String} className
  20772. * @return {Element} Returns the created line
  20773. * @private
  20774. */
  20775. TimeAxis.prototype._repaintMajorLine = function (x, width, orientation, className) {
  20776. // reuse redundant line
  20777. var line = this.dom.redundant.lines.shift();
  20778. if (!line) {
  20779. // create vertical line
  20780. line = document.createElement('div');
  20781. this.dom.background.appendChild(line);
  20782. }
  20783. this.dom.lines.push(line);
  20784. var props = this.props;
  20785. if (orientation == 'top') {
  20786. line.style.top = '0';
  20787. } else {
  20788. line.style.top = this.body.domProps.top.height + 'px';
  20789. }
  20790. if (this.options.rtl) {
  20791. line.style.left = "";
  20792. line.style.right = x - props.majorLineWidth / 2 + 'px';
  20793. line.className = 'vis-grid vis-vertical-rtl vis-major ' + className;
  20794. } else {
  20795. line.style.left = x - props.majorLineWidth / 2 + 'px';
  20796. line.className = 'vis-grid vis-vertical vis-major ' + className;
  20797. }
  20798. line.style.height = props.majorLineHeight + 'px';
  20799. line.style.width = width + 'px';
  20800. return line;
  20801. };
  20802. /**
  20803. * Determine the size of text on the axis (both major and minor axis).
  20804. * The size is calculated only once and then cached in this.props.
  20805. * @private
  20806. */
  20807. TimeAxis.prototype._calculateCharSize = function () {
  20808. // Note: We calculate char size with every redraw. Size may change, for
  20809. // example when any of the timelines parents had display:none for example.
  20810. // determine the char width and height on the minor axis
  20811. if (!this.dom.measureCharMinor) {
  20812. this.dom.measureCharMinor = document.createElement('DIV');
  20813. this.dom.measureCharMinor.className = 'vis-text vis-minor vis-measure';
  20814. this.dom.measureCharMinor.style.position = 'absolute';
  20815. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  20816. this.dom.foreground.appendChild(this.dom.measureCharMinor);
  20817. }
  20818. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  20819. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  20820. // determine the char width and height on the major axis
  20821. if (!this.dom.measureCharMajor) {
  20822. this.dom.measureCharMajor = document.createElement('DIV');
  20823. this.dom.measureCharMajor.className = 'vis-text vis-major vis-measure';
  20824. this.dom.measureCharMajor.style.position = 'absolute';
  20825. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  20826. this.dom.foreground.appendChild(this.dom.measureCharMajor);
  20827. }
  20828. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  20829. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  20830. };
  20831. var warnedForOverflow = false;
  20832. module.exports = TimeAxis;
  20833. /***/ },
  20834. /* 45 */
  20835. /***/ function(module, exports, __webpack_require__) {
  20836. 'use strict';
  20837. var keycharm = __webpack_require__(23);
  20838. var Emitter = __webpack_require__(13);
  20839. var Hammer = __webpack_require__(20);
  20840. var util = __webpack_require__(1);
  20841. /**
  20842. * Turn an element into an clickToUse element.
  20843. * When not active, the element has a transparent overlay. When the overlay is
  20844. * clicked, the mode is changed to active.
  20845. * When active, the element is displayed with a blue border around it, and
  20846. * the interactive contents of the element can be used. When clicked outside
  20847. * the element, the elements mode is changed to inactive.
  20848. * @param {Element} container
  20849. * @constructor
  20850. */
  20851. function Activator(container) {
  20852. this.active = false;
  20853. this.dom = {
  20854. container: container
  20855. };
  20856. this.dom.overlay = document.createElement('div');
  20857. this.dom.overlay.className = 'vis-overlay';
  20858. this.dom.container.appendChild(this.dom.overlay);
  20859. this.hammer = Hammer(this.dom.overlay);
  20860. this.hammer.on('tap', this._onTapOverlay.bind(this));
  20861. // block all touch events (except tap)
  20862. var me = this;
  20863. var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend'];
  20864. events.forEach(function (event) {
  20865. me.hammer.on(event, function (event) {
  20866. event.stopPropagation();
  20867. });
  20868. });
  20869. // attach a click event to the window, in order to deactivate when clicking outside the timeline
  20870. if (document && document.body) {
  20871. this.onClick = function (event) {
  20872. if (!_hasParent(event.target, container)) {
  20873. me.deactivate();
  20874. }
  20875. };
  20876. document.body.addEventListener('click', this.onClick);
  20877. }
  20878. if (this.keycharm !== undefined) {
  20879. this.keycharm.destroy();
  20880. }
  20881. this.keycharm = keycharm();
  20882. // keycharm listener only bounded when active)
  20883. this.escListener = this.deactivate.bind(this);
  20884. }
  20885. // turn into an event emitter
  20886. Emitter(Activator.prototype);
  20887. // The currently active activator
  20888. Activator.current = null;
  20889. /**
  20890. * Destroy the activator. Cleans up all created DOM and event listeners
  20891. */
  20892. Activator.prototype.destroy = function () {
  20893. this.deactivate();
  20894. // remove dom
  20895. this.dom.overlay.parentNode.removeChild(this.dom.overlay);
  20896. // remove global event listener
  20897. if (this.onClick) {
  20898. document.body.removeEventListener('click', this.onClick);
  20899. }
  20900. // cleanup hammer instances
  20901. this.hammer.destroy();
  20902. this.hammer = null;
  20903. // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
  20904. };
  20905. /**
  20906. * Activate the element
  20907. * Overlay is hidden, element is decorated with a blue shadow border
  20908. */
  20909. Activator.prototype.activate = function () {
  20910. // we allow only one active activator at a time
  20911. if (Activator.current) {
  20912. Activator.current.deactivate();
  20913. }
  20914. Activator.current = this;
  20915. this.active = true;
  20916. this.dom.overlay.style.display = 'none';
  20917. util.addClassName(this.dom.container, 'vis-active');
  20918. this.emit('change');
  20919. this.emit('activate');
  20920. // ugly hack: bind ESC after emitting the events, as the Network rebinds all
  20921. // keyboard events on a 'change' event
  20922. this.keycharm.bind('esc', this.escListener);
  20923. };
  20924. /**
  20925. * Deactivate the element
  20926. * Overlay is displayed on top of the element
  20927. */
  20928. Activator.prototype.deactivate = function () {
  20929. this.active = false;
  20930. this.dom.overlay.style.display = '';
  20931. util.removeClassName(this.dom.container, 'vis-active');
  20932. this.keycharm.unbind('esc', this.escListener);
  20933. this.emit('change');
  20934. this.emit('deactivate');
  20935. };
  20936. /**
  20937. * Handle a tap event: activate the container
  20938. * @param event
  20939. * @private
  20940. */
  20941. Activator.prototype._onTapOverlay = function (event) {
  20942. // activate the container
  20943. this.activate();
  20944. event.stopPropagation();
  20945. };
  20946. /**
  20947. * Test whether the element has the requested parent element somewhere in
  20948. * its chain of parent nodes.
  20949. * @param {HTMLElement} element
  20950. * @param {HTMLElement} parent
  20951. * @returns {boolean} Returns true when the parent is found somewhere in the
  20952. * chain of parent nodes.
  20953. * @private
  20954. */
  20955. function _hasParent(element, parent) {
  20956. while (element) {
  20957. if (element === parent) {
  20958. return true;
  20959. }
  20960. element = element.parentNode;
  20961. }
  20962. return false;
  20963. }
  20964. module.exports = Activator;
  20965. /***/ },
  20966. /* 46 */
  20967. /***/ function(module, exports, __webpack_require__) {
  20968. 'use strict';
  20969. var Hammer = __webpack_require__(20);
  20970. var util = __webpack_require__(1);
  20971. var Component = __webpack_require__(31);
  20972. var moment = __webpack_require__(2);
  20973. var locales = __webpack_require__(47);
  20974. /**
  20975. * A custom time bar
  20976. * @param {{range: Range, dom: Object}} body
  20977. * @param {Object} [options] Available parameters:
  20978. * {number | string} id
  20979. * {string} locales
  20980. * {string} locale
  20981. * @constructor CustomTime
  20982. * @extends Component
  20983. */
  20984. function CustomTime(body, options) {
  20985. this.body = body;
  20986. // default options
  20987. this.defaultOptions = {
  20988. moment: moment,
  20989. locales: locales,
  20990. locale: 'en',
  20991. id: undefined,
  20992. title: undefined
  20993. };
  20994. this.options = util.extend({}, this.defaultOptions);
  20995. if (options && options.time) {
  20996. this.customTime = options.time;
  20997. } else {
  20998. this.customTime = new Date();
  20999. }
  21000. this.eventParams = {}; // stores state parameters while dragging the bar
  21001. this.setOptions(options);
  21002. // create the DOM
  21003. this._create();
  21004. }
  21005. CustomTime.prototype = new Component();
  21006. /**
  21007. * Set options for the component. Options will be merged in current options.
  21008. * @param {Object} options Available parameters:
  21009. * {number | string} id
  21010. * {string} locales
  21011. * {string} locale
  21012. */
  21013. CustomTime.prototype.setOptions = function (options) {
  21014. if (options) {
  21015. // copy all options that we know
  21016. util.selectiveExtend(['moment', 'locale', 'locales', 'id'], this.options, options);
  21017. }
  21018. };
  21019. /**
  21020. * Create the DOM for the custom time
  21021. * @private
  21022. */
  21023. CustomTime.prototype._create = function () {
  21024. var bar = document.createElement('div');
  21025. bar['custom-time'] = this;
  21026. bar.className = 'vis-custom-time ' + (this.options.id || '');
  21027. bar.style.position = 'absolute';
  21028. bar.style.top = '0px';
  21029. bar.style.height = '100%';
  21030. this.bar = bar;
  21031. var drag = document.createElement('div');
  21032. drag.style.position = 'relative';
  21033. drag.style.top = '0px';
  21034. drag.style.left = '-10px';
  21035. drag.style.height = '100%';
  21036. drag.style.width = '20px';
  21037. bar.appendChild(drag);
  21038. // attach event listeners
  21039. this.hammer = new Hammer(drag);
  21040. this.hammer.on('panstart', this._onDragStart.bind(this));
  21041. this.hammer.on('panmove', this._onDrag.bind(this));
  21042. this.hammer.on('panend', this._onDragEnd.bind(this));
  21043. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  21044. };
  21045. /**
  21046. * Destroy the CustomTime bar
  21047. */
  21048. CustomTime.prototype.destroy = function () {
  21049. this.hide();
  21050. this.hammer.destroy();
  21051. this.hammer = null;
  21052. this.body = null;
  21053. };
  21054. /**
  21055. * Repaint the component
  21056. * @return {boolean} Returns true if the component is resized
  21057. */
  21058. CustomTime.prototype.redraw = function () {
  21059. var parent = this.body.dom.backgroundVertical;
  21060. if (this.bar.parentNode != parent) {
  21061. // attach to the dom
  21062. if (this.bar.parentNode) {
  21063. this.bar.parentNode.removeChild(this.bar);
  21064. }
  21065. parent.appendChild(this.bar);
  21066. }
  21067. var x = this.body.util.toScreen(this.customTime);
  21068. var locale = this.options.locales[this.options.locale];
  21069. if (!locale) {
  21070. if (!this.warned) {
  21071. console.log('WARNING: options.locales[\'' + this.options.locale + '\'] not found. See http://visjs.org/docs/timeline.html#Localization');
  21072. this.warned = true;
  21073. }
  21074. locale = this.options.locales['en']; // fall back on english when not available
  21075. }
  21076. var title = this.options.title;
  21077. // To hide the title completely use empty string ''.
  21078. if (title === undefined) {
  21079. title = locale.time + ': ' + this.options.moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
  21080. title = title.charAt(0).toUpperCase() + title.substring(1);
  21081. }
  21082. this.bar.style.left = x + 'px';
  21083. this.bar.title = title;
  21084. return false;
  21085. };
  21086. /**
  21087. * Remove the CustomTime from the DOM
  21088. */
  21089. CustomTime.prototype.hide = function () {
  21090. // remove the line from the DOM
  21091. if (this.bar.parentNode) {
  21092. this.bar.parentNode.removeChild(this.bar);
  21093. }
  21094. };
  21095. /**
  21096. * Set custom time.
  21097. * @param {Date | number | string} time
  21098. */
  21099. CustomTime.prototype.setCustomTime = function (time) {
  21100. this.customTime = util.convert(time, 'Date');
  21101. this.redraw();
  21102. };
  21103. /**
  21104. * Retrieve the current custom time.
  21105. * @return {Date} customTime
  21106. */
  21107. CustomTime.prototype.getCustomTime = function () {
  21108. return new Date(this.customTime.valueOf());
  21109. };
  21110. /**
  21111. * Set custom title.
  21112. * @param {Date | number | string} title
  21113. */
  21114. CustomTime.prototype.setCustomTitle = function (title) {
  21115. this.options.title = title;
  21116. };
  21117. /**
  21118. * Start moving horizontally
  21119. * @param {Event} event
  21120. * @private
  21121. */
  21122. CustomTime.prototype._onDragStart = function (event) {
  21123. this.eventParams.dragging = true;
  21124. this.eventParams.customTime = this.customTime;
  21125. event.stopPropagation();
  21126. };
  21127. /**
  21128. * Perform moving operating.
  21129. * @param {Event} event
  21130. * @private
  21131. */
  21132. CustomTime.prototype._onDrag = function (event) {
  21133. if (!this.eventParams.dragging) return;
  21134. var x = this.body.util.toScreen(this.eventParams.customTime) + event.deltaX;
  21135. var time = this.body.util.toTime(x);
  21136. this.setCustomTime(time);
  21137. // fire a timechange event
  21138. this.body.emitter.emit('timechange', {
  21139. id: this.options.id,
  21140. time: new Date(this.customTime.valueOf())
  21141. });
  21142. event.stopPropagation();
  21143. };
  21144. /**
  21145. * Stop moving operating.
  21146. * @param {Event} event
  21147. * @private
  21148. */
  21149. CustomTime.prototype._onDragEnd = function (event) {
  21150. if (!this.eventParams.dragging) return;
  21151. // fire a timechanged event
  21152. this.body.emitter.emit('timechanged', {
  21153. id: this.options.id,
  21154. time: new Date(this.customTime.valueOf())
  21155. });
  21156. event.stopPropagation();
  21157. };
  21158. /**
  21159. * Find a custom time from an event target:
  21160. * searches for the attribute 'custom-time' in the event target's element tree
  21161. * @param {Event} event
  21162. * @return {CustomTime | null} customTime
  21163. */
  21164. CustomTime.customTimeFromTarget = function (event) {
  21165. var target = event.target;
  21166. while (target) {
  21167. if (target.hasOwnProperty('custom-time')) {
  21168. return target['custom-time'];
  21169. }
  21170. target = target.parentNode;
  21171. }
  21172. return null;
  21173. };
  21174. module.exports = CustomTime;
  21175. /***/ },
  21176. /* 47 */
  21177. /***/ function(module, exports) {
  21178. 'use strict';
  21179. // English
  21180. exports['en'] = {
  21181. current: 'current',
  21182. time: 'time'
  21183. };
  21184. exports['en_EN'] = exports['en'];
  21185. exports['en_US'] = exports['en'];
  21186. // Dutch
  21187. exports['nl'] = {
  21188. current: 'huidige',
  21189. time: 'tijd'
  21190. };
  21191. exports['nl_NL'] = exports['nl'];
  21192. exports['nl_BE'] = exports['nl'];
  21193. /***/ },
  21194. /* 48 */
  21195. /***/ function(module, exports, __webpack_require__) {
  21196. 'use strict';
  21197. var util = __webpack_require__(1);
  21198. var Component = __webpack_require__(31);
  21199. var moment = __webpack_require__(2);
  21200. var locales = __webpack_require__(47);
  21201. /**
  21202. * A current time bar
  21203. * @param {{range: Range, dom: Object, domProps: Object}} body
  21204. * @param {Object} [options] Available parameters:
  21205. * {Boolean} [showCurrentTime]
  21206. * @constructor CurrentTime
  21207. * @extends Component
  21208. */
  21209. function CurrentTime(body, options) {
  21210. this.body = body;
  21211. // default options
  21212. this.defaultOptions = {
  21213. rtl: false,
  21214. showCurrentTime: true,
  21215. moment: moment,
  21216. locales: locales,
  21217. locale: 'en'
  21218. };
  21219. this.options = util.extend({}, this.defaultOptions);
  21220. this.offset = 0;
  21221. this._create();
  21222. this.setOptions(options);
  21223. }
  21224. CurrentTime.prototype = new Component();
  21225. /**
  21226. * Create the HTML DOM for the current time bar
  21227. * @private
  21228. */
  21229. CurrentTime.prototype._create = function () {
  21230. var bar = document.createElement('div');
  21231. bar.className = 'vis-current-time';
  21232. bar.style.position = 'absolute';
  21233. bar.style.top = '0px';
  21234. bar.style.height = '100%';
  21235. this.bar = bar;
  21236. };
  21237. /**
  21238. * Destroy the CurrentTime bar
  21239. */
  21240. CurrentTime.prototype.destroy = function () {
  21241. this.options.showCurrentTime = false;
  21242. this.redraw(); // will remove the bar from the DOM and stop refreshing
  21243. this.body = null;
  21244. };
  21245. /**
  21246. * Set options for the component. Options will be merged in current options.
  21247. * @param {Object} options Available parameters:
  21248. * {boolean} [showCurrentTime]
  21249. */
  21250. CurrentTime.prototype.setOptions = function (options) {
  21251. if (options) {
  21252. // copy all options that we know
  21253. util.selectiveExtend(['rtl', 'showCurrentTime', 'moment', 'locale', 'locales'], this.options, options);
  21254. }
  21255. };
  21256. /**
  21257. * Repaint the component
  21258. * @return {boolean} Returns true if the component is resized
  21259. */
  21260. CurrentTime.prototype.redraw = function () {
  21261. if (this.options.showCurrentTime) {
  21262. var parent = this.body.dom.backgroundVertical;
  21263. if (this.bar.parentNode != parent) {
  21264. // attach to the dom
  21265. if (this.bar.parentNode) {
  21266. this.bar.parentNode.removeChild(this.bar);
  21267. }
  21268. parent.appendChild(this.bar);
  21269. this.start();
  21270. }
  21271. var now = this.options.moment(new Date().valueOf() + this.offset);
  21272. var x = this.body.util.toScreen(now);
  21273. var locale = this.options.locales[this.options.locale];
  21274. if (!locale) {
  21275. if (!this.warned) {
  21276. console.log('WARNING: options.locales[\'' + this.options.locale + '\'] not found. See http://visjs.org/docs/timeline/#Localization');
  21277. this.warned = true;
  21278. }
  21279. locale = this.options.locales['en']; // fall back on english when not available
  21280. }
  21281. var title = locale.current + ' ' + locale.time + ': ' + now.format('dddd, MMMM Do YYYY, H:mm:ss');
  21282. title = title.charAt(0).toUpperCase() + title.substring(1);
  21283. if (this.options.rtl) {
  21284. this.bar.style.right = x + 'px';
  21285. } else {
  21286. this.bar.style.left = x + 'px';
  21287. }
  21288. this.bar.title = title;
  21289. } else {
  21290. // remove the line from the DOM
  21291. if (this.bar.parentNode) {
  21292. this.bar.parentNode.removeChild(this.bar);
  21293. }
  21294. this.stop();
  21295. }
  21296. return false;
  21297. };
  21298. /**
  21299. * Start auto refreshing the current time bar
  21300. */
  21301. CurrentTime.prototype.start = function () {
  21302. var me = this;
  21303. function update() {
  21304. me.stop();
  21305. // determine interval to refresh
  21306. var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
  21307. var interval = 1 / scale / 10;
  21308. if (interval < 30) interval = 30;
  21309. if (interval > 1000) interval = 1000;
  21310. me.redraw();
  21311. me.body.emitter.emit('currentTimeTick');
  21312. // start a renderTimer to adjust for the new time
  21313. me.currentTimeTimer = setTimeout(update, interval);
  21314. }
  21315. update();
  21316. };
  21317. /**
  21318. * Stop auto refreshing the current time bar
  21319. */
  21320. CurrentTime.prototype.stop = function () {
  21321. if (this.currentTimeTimer !== undefined) {
  21322. clearTimeout(this.currentTimeTimer);
  21323. delete this.currentTimeTimer;
  21324. }
  21325. };
  21326. /**
  21327. * Set a current time. This can be used for example to ensure that a client's
  21328. * time is synchronized with a shared server time.
  21329. * @param {Date | String | Number} time A Date, unix timestamp, or
  21330. * ISO date string.
  21331. */
  21332. CurrentTime.prototype.setCurrentTime = function (time) {
  21333. var t = util.convert(time, 'Date').valueOf();
  21334. var now = new Date().valueOf();
  21335. this.offset = t - now;
  21336. this.redraw();
  21337. };
  21338. /**
  21339. * Get the current time.
  21340. * @return {Date} Returns the current time.
  21341. */
  21342. CurrentTime.prototype.getCurrentTime = function () {
  21343. return new Date(new Date().valueOf() + this.offset);
  21344. };
  21345. module.exports = CurrentTime;
  21346. /***/ },
  21347. /* 49 */
  21348. /***/ function(module, exports) {
  21349. 'use strict';
  21350. Object.defineProperty(exports, "__esModule", {
  21351. value: true
  21352. });
  21353. /**
  21354. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  21355. * of the allowed values.
  21356. *
  21357. * __any__ means that the name of the property does not matter.
  21358. * __type__ is a required field for all objects and contains the allowed types of all objects
  21359. */
  21360. var string = 'string';
  21361. var boolean = 'boolean';
  21362. var number = 'number';
  21363. var array = 'array';
  21364. var date = 'date';
  21365. var object = 'object'; // should only be in a __type__ property
  21366. var dom = 'dom';
  21367. var moment = 'moment';
  21368. var any = 'any';
  21369. var allOptions = {
  21370. configure: {
  21371. enabled: { boolean: boolean },
  21372. filter: { boolean: boolean, 'function': 'function' },
  21373. container: { dom: dom },
  21374. __type__: { object: object, boolean: boolean, 'function': 'function' }
  21375. },
  21376. //globals :
  21377. align: { string: string },
  21378. rtl: { boolean: boolean, 'undefined': 'undefined' },
  21379. autoResize: { boolean: boolean },
  21380. throttleRedraw: { number: number },
  21381. clickToUse: { boolean: boolean },
  21382. dataAttributes: { string: string, array: array },
  21383. editable: {
  21384. add: { boolean: boolean, 'undefined': 'undefined' },
  21385. remove: { boolean: boolean, 'undefined': 'undefined' },
  21386. updateGroup: { boolean: boolean, 'undefined': 'undefined' },
  21387. updateTime: { boolean: boolean, 'undefined': 'undefined' },
  21388. __type__: { boolean: boolean, object: object }
  21389. },
  21390. end: { number: number, date: date, string: string, moment: moment },
  21391. format: {
  21392. minorLabels: {
  21393. millisecond: { string: string, 'undefined': 'undefined' },
  21394. second: { string: string, 'undefined': 'undefined' },
  21395. minute: { string: string, 'undefined': 'undefined' },
  21396. hour: { string: string, 'undefined': 'undefined' },
  21397. weekday: { string: string, 'undefined': 'undefined' },
  21398. day: { string: string, 'undefined': 'undefined' },
  21399. month: { string: string, 'undefined': 'undefined' },
  21400. year: { string: string, 'undefined': 'undefined' },
  21401. __type__: { object: object }
  21402. },
  21403. majorLabels: {
  21404. millisecond: { string: string, 'undefined': 'undefined' },
  21405. second: { string: string, 'undefined': 'undefined' },
  21406. minute: { string: string, 'undefined': 'undefined' },
  21407. hour: { string: string, 'undefined': 'undefined' },
  21408. weekday: { string: string, 'undefined': 'undefined' },
  21409. day: { string: string, 'undefined': 'undefined' },
  21410. month: { string: string, 'undefined': 'undefined' },
  21411. year: { string: string, 'undefined': 'undefined' },
  21412. __type__: { object: object }
  21413. },
  21414. __type__: { object: object }
  21415. },
  21416. moment: { 'function': 'function' },
  21417. groupOrder: { string: string, 'function': 'function' },
  21418. groupEditable: {
  21419. add: { boolean: boolean, 'undefined': 'undefined' },
  21420. remove: { boolean: boolean, 'undefined': 'undefined' },
  21421. order: { boolean: boolean, 'undefined': 'undefined' },
  21422. __type__: { boolean: boolean, object: object }
  21423. },
  21424. groupOrderSwap: { 'function': 'function' },
  21425. height: { string: string, number: number },
  21426. hiddenDates: {
  21427. start: { date: date, number: number, string: string, moment: moment },
  21428. end: { date: date, number: number, string: string, moment: moment },
  21429. repeat: { string: string },
  21430. __type__: { object: object, array: array }
  21431. },
  21432. itemsAlwaysDraggable: { boolean: boolean },
  21433. locale: { string: string },
  21434. locales: {
  21435. __any__: { any: any },
  21436. __type__: { object: object }
  21437. },
  21438. margin: {
  21439. axis: { number: number },
  21440. item: {
  21441. horizontal: { number: number, 'undefined': 'undefined' },
  21442. vertical: { number: number, 'undefined': 'undefined' },
  21443. __type__: { object: object, number: number }
  21444. },
  21445. __type__: { object: object, number: number }
  21446. },
  21447. max: { date: date, number: number, string: string, moment: moment },
  21448. maxHeight: { number: number, string: string },
  21449. maxMinorChars: { number: number },
  21450. min: { date: date, number: number, string: string, moment: moment },
  21451. minHeight: { number: number, string: string },
  21452. moveable: { boolean: boolean },
  21453. multiselect: { boolean: boolean },
  21454. multiselectPerGroup: { boolean: boolean },
  21455. onAdd: { 'function': 'function' },
  21456. onUpdate: { 'function': 'function' },
  21457. onMove: { 'function': 'function' },
  21458. onMoving: { 'function': 'function' },
  21459. onRemove: { 'function': 'function' },
  21460. onAddGroup: { 'function': 'function' },
  21461. onMoveGroup: { 'function': 'function' },
  21462. onRemoveGroup: { 'function': 'function' },
  21463. order: { 'function': 'function' },
  21464. orientation: {
  21465. axis: { string: string, 'undefined': 'undefined' },
  21466. item: { string: string, 'undefined': 'undefined' },
  21467. __type__: { string: string, object: object }
  21468. },
  21469. selectable: { boolean: boolean },
  21470. showCurrentTime: { boolean: boolean },
  21471. showMajorLabels: { boolean: boolean },
  21472. showMinorLabels: { boolean: boolean },
  21473. stack: { boolean: boolean },
  21474. snap: { 'function': 'function', 'null': 'null' },
  21475. start: { date: date, number: number, string: string, moment: moment },
  21476. template: { 'function': 'function' },
  21477. groupTemplate: { 'function': 'function' },
  21478. timeAxis: {
  21479. scale: { string: string, 'undefined': 'undefined' },
  21480. step: { number: number, 'undefined': 'undefined' },
  21481. __type__: { object: object }
  21482. },
  21483. type: { string: string },
  21484. width: { string: string, number: number },
  21485. zoomable: { boolean: boolean },
  21486. zoomKey: { string: ['ctrlKey', 'altKey', 'metaKey', ''] },
  21487. zoomMax: { number: number },
  21488. zoomMin: { number: number },
  21489. __type__: { object: object }
  21490. };
  21491. var configureOptions = {
  21492. global: {
  21493. align: ['center', 'left', 'right'],
  21494. direction: false,
  21495. autoResize: true,
  21496. throttleRedraw: [10, 0, 1000, 10],
  21497. clickToUse: false,
  21498. // dataAttributes: ['all'], // FIXME: can be 'all' or string[]
  21499. editable: {
  21500. add: false,
  21501. remove: false,
  21502. updateGroup: false,
  21503. updateTime: false
  21504. },
  21505. end: '',
  21506. format: {
  21507. minorLabels: {
  21508. millisecond: 'SSS',
  21509. second: 's',
  21510. minute: 'HH:mm',
  21511. hour: 'HH:mm',
  21512. weekday: 'ddd D',
  21513. day: 'D',
  21514. month: 'MMM',
  21515. year: 'YYYY'
  21516. },
  21517. majorLabels: {
  21518. millisecond: 'HH:mm:ss',
  21519. second: 'D MMMM HH:mm',
  21520. minute: 'ddd D MMMM',
  21521. hour: 'ddd D MMMM',
  21522. weekday: 'MMMM YYYY',
  21523. day: 'MMMM YYYY',
  21524. month: 'YYYY',
  21525. year: ''
  21526. }
  21527. },
  21528. //groupOrder: {string, 'function': 'function'},
  21529. groupsDraggable: false,
  21530. height: '',
  21531. //hiddenDates: {object, array},
  21532. locale: '',
  21533. margin: {
  21534. axis: [20, 0, 100, 1],
  21535. item: {
  21536. horizontal: [10, 0, 100, 1],
  21537. vertical: [10, 0, 100, 1]
  21538. }
  21539. },
  21540. max: '',
  21541. maxHeight: '',
  21542. maxMinorChars: [7, 0, 20, 1],
  21543. min: '',
  21544. minHeight: '',
  21545. moveable: false,
  21546. multiselect: false,
  21547. multiselectPerGroup: false,
  21548. //onAdd: {'function': 'function'},
  21549. //onUpdate: {'function': 'function'},
  21550. //onMove: {'function': 'function'},
  21551. //onMoving: {'function': 'function'},
  21552. //onRename: {'function': 'function'},
  21553. //order: {'function': 'function'},
  21554. orientation: {
  21555. axis: ['both', 'bottom', 'top'],
  21556. item: ['bottom', 'top']
  21557. },
  21558. selectable: true,
  21559. showCurrentTime: false,
  21560. showMajorLabels: true,
  21561. showMinorLabels: true,
  21562. stack: true,
  21563. //snap: {'function': 'function', nada},
  21564. start: '',
  21565. //template: {'function': 'function'},
  21566. //timeAxis: {
  21567. // scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'month', 'year'],
  21568. // step: [1, 1, 10, 1]
  21569. //},
  21570. type: ['box', 'point', 'range', 'background'],
  21571. width: '100%',
  21572. zoomable: true,
  21573. zoomKey: ['ctrlKey', 'altKey', 'metaKey', ''],
  21574. zoomMax: [315360000000000, 10, 315360000000000, 1],
  21575. zoomMin: [10, 10, 315360000000000, 1]
  21576. }
  21577. };
  21578. exports.allOptions = allOptions;
  21579. exports.configureOptions = configureOptions;
  21580. /***/ },
  21581. /* 50 */
  21582. /***/ function(module, exports, __webpack_require__) {
  21583. 'use strict';
  21584. var _Configurator = __webpack_require__(26);
  21585. var _Configurator2 = _interopRequireDefault(_Configurator);
  21586. var _Validator = __webpack_require__(29);
  21587. var _Validator2 = _interopRequireDefault(_Validator);
  21588. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21589. var Emitter = __webpack_require__(13);
  21590. var Hammer = __webpack_require__(20);
  21591. var moment = __webpack_require__(2);
  21592. var util = __webpack_require__(1);
  21593. var DataSet = __webpack_require__(9);
  21594. var DataView = __webpack_require__(11);
  21595. var Range = __webpack_require__(30);
  21596. var Core = __webpack_require__(33);
  21597. var TimeAxis = __webpack_require__(44);
  21598. var CurrentTime = __webpack_require__(48);
  21599. var CustomTime = __webpack_require__(46);
  21600. var LineGraph = __webpack_require__(51);
  21601. var printStyle = __webpack_require__(29).printStyle;
  21602. var allOptions = __webpack_require__(59).allOptions;
  21603. var configureOptions = __webpack_require__(59).configureOptions;
  21604. /**
  21605. * Create a timeline visualization
  21606. * @param {HTMLElement} container
  21607. * @param {vis.DataSet | Array} [items]
  21608. * @param {Object} [options] See Graph2d.setOptions for the available options.
  21609. * @constructor
  21610. * @extends Core
  21611. */
  21612. function Graph2d(container, items, groups, options) {
  21613. // if the third element is options, the forth is groups (optionally);
  21614. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  21615. var forthArgument = options;
  21616. options = groups;
  21617. groups = forthArgument;
  21618. }
  21619. var me = this;
  21620. this.defaultOptions = {
  21621. start: null,
  21622. end: null,
  21623. autoResize: true,
  21624. orientation: {
  21625. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  21626. item: 'bottom' // not relevant for Graph2d
  21627. },
  21628. moment: moment,
  21629. width: null,
  21630. height: null,
  21631. maxHeight: null,
  21632. minHeight: null
  21633. };
  21634. this.options = util.deepExtend({}, this.defaultOptions);
  21635. // Create the DOM, props, and emitter
  21636. this._create(container);
  21637. // all components listed here will be repainted automatically
  21638. this.components = [];
  21639. this.body = {
  21640. dom: this.dom,
  21641. domProps: this.props,
  21642. emitter: {
  21643. on: this.on.bind(this),
  21644. off: this.off.bind(this),
  21645. emit: this.emit.bind(this)
  21646. },
  21647. hiddenDates: [],
  21648. util: {
  21649. toScreen: me._toScreen.bind(me),
  21650. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  21651. toTime: me._toTime.bind(me),
  21652. toGlobalTime: me._toGlobalTime.bind(me)
  21653. }
  21654. };
  21655. // range
  21656. this.range = new Range(this.body);
  21657. this.components.push(this.range);
  21658. this.body.range = this.range;
  21659. // time axis
  21660. this.timeAxis = new TimeAxis(this.body);
  21661. this.components.push(this.timeAxis);
  21662. //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  21663. // current time bar
  21664. this.currentTime = new CurrentTime(this.body);
  21665. this.components.push(this.currentTime);
  21666. // item set
  21667. this.linegraph = new LineGraph(this.body);
  21668. this.components.push(this.linegraph);
  21669. this.itemsData = null; // DataSet
  21670. this.groupsData = null; // DataSet
  21671. this.on('tap', function (event) {
  21672. me.emit('click', me.getEventProperties(event));
  21673. });
  21674. this.on('doubletap', function (event) {
  21675. me.emit('doubleClick', me.getEventProperties(event));
  21676. });
  21677. this.dom.root.oncontextmenu = function (event) {
  21678. me.emit('contextmenu', me.getEventProperties(event));
  21679. };
  21680. // apply options
  21681. if (options) {
  21682. this.setOptions(options);
  21683. }
  21684. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  21685. if (groups) {
  21686. this.setGroups(groups);
  21687. }
  21688. // create itemset
  21689. if (items) {
  21690. this.setItems(items);
  21691. }
  21692. // draw for the first time
  21693. this._redraw();
  21694. }
  21695. // Extend the functionality from Core
  21696. Graph2d.prototype = new Core();
  21697. Graph2d.prototype.setOptions = function (options) {
  21698. // validate options
  21699. var errorFound = _Validator2.default.validate(options, allOptions);
  21700. if (errorFound === true) {
  21701. console.log('%cErrors have been found in the supplied options object.', printStyle);
  21702. }
  21703. Core.prototype.setOptions.call(this, options);
  21704. };
  21705. /**
  21706. * Set items
  21707. * @param {vis.DataSet | Array | null} items
  21708. */
  21709. Graph2d.prototype.setItems = function (items) {
  21710. var initialLoad = this.itemsData == null;
  21711. // convert to type DataSet when needed
  21712. var newDataSet;
  21713. if (!items) {
  21714. newDataSet = null;
  21715. } else if (items instanceof DataSet || items instanceof DataView) {
  21716. newDataSet = items;
  21717. } else {
  21718. // turn an array into a dataset
  21719. newDataSet = new DataSet(items, {
  21720. type: {
  21721. start: 'Date',
  21722. end: 'Date'
  21723. }
  21724. });
  21725. }
  21726. // set items
  21727. this.itemsData = newDataSet;
  21728. this.linegraph && this.linegraph.setItems(newDataSet);
  21729. if (initialLoad) {
  21730. if (this.options.start != undefined || this.options.end != undefined) {
  21731. var start = this.options.start != undefined ? this.options.start : null;
  21732. var end = this.options.end != undefined ? this.options.end : null;
  21733. this.setWindow(start, end, { animation: false });
  21734. } else {
  21735. this.fit({ animation: false });
  21736. }
  21737. }
  21738. };
  21739. /**
  21740. * Set groups
  21741. * @param {vis.DataSet | Array} groups
  21742. */
  21743. Graph2d.prototype.setGroups = function (groups) {
  21744. // convert to type DataSet when needed
  21745. var newDataSet;
  21746. if (!groups) {
  21747. newDataSet = null;
  21748. } else if (groups instanceof DataSet || groups instanceof DataView) {
  21749. newDataSet = groups;
  21750. } else {
  21751. // turn an array into a dataset
  21752. newDataSet = new DataSet(groups);
  21753. }
  21754. this.groupsData = newDataSet;
  21755. this.linegraph.setGroups(newDataSet);
  21756. };
  21757. /**
  21758. * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right).
  21759. * @param groupId
  21760. * @param width
  21761. * @param height
  21762. */
  21763. Graph2d.prototype.getLegend = function (groupId, width, height) {
  21764. if (width === undefined) {
  21765. width = 15;
  21766. }
  21767. if (height === undefined) {
  21768. height = 15;
  21769. }
  21770. if (this.linegraph.groups[groupId] !== undefined) {
  21771. return this.linegraph.groups[groupId].getLegend(width, height);
  21772. } else {
  21773. return "cannot find group:'" + groupId + "'";
  21774. }
  21775. };
  21776. /**
  21777. * This checks if the visible option of the supplied group (by ID) is true or false.
  21778. * @param groupId
  21779. * @returns {*}
  21780. */
  21781. Graph2d.prototype.isGroupVisible = function (groupId) {
  21782. if (this.linegraph.groups[groupId] !== undefined) {
  21783. return this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true);
  21784. } else {
  21785. return false;
  21786. }
  21787. };
  21788. /**
  21789. * Get the data range of the item set.
  21790. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  21791. * When no minimum is found, min==null
  21792. * When no maximum is found, max==null
  21793. */
  21794. Graph2d.prototype.getDataRange = function () {
  21795. var min = null;
  21796. var max = null;
  21797. // calculate min from start filed
  21798. for (var groupId in this.linegraph.groups) {
  21799. if (this.linegraph.groups.hasOwnProperty(groupId)) {
  21800. if (this.linegraph.groups[groupId].visible == true) {
  21801. for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
  21802. var item = this.linegraph.groups[groupId].itemsData[i];
  21803. var value = util.convert(item.x, 'Date').valueOf();
  21804. min = min == null ? value : min > value ? value : min;
  21805. max = max == null ? value : max < value ? value : max;
  21806. }
  21807. }
  21808. }
  21809. }
  21810. return {
  21811. min: min != null ? new Date(min) : null,
  21812. max: max != null ? new Date(max) : null
  21813. };
  21814. };
  21815. /**
  21816. * Generate Timeline related information from an event
  21817. * @param {Event} event
  21818. * @return {Object} An object with related information, like on which area
  21819. * The event happened, whether clicked on an item, etc.
  21820. */
  21821. Graph2d.prototype.getEventProperties = function (event) {
  21822. var clientX = event.center ? event.center.x : event.clientX;
  21823. var clientY = event.center ? event.center.y : event.clientY;
  21824. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  21825. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  21826. var time = this._toTime(x);
  21827. var customTime = CustomTime.customTimeFromTarget(event);
  21828. var element = util.getTarget(event);
  21829. var what = null;
  21830. if (util.hasParent(element, this.timeAxis.dom.foreground)) {
  21831. what = 'axis';
  21832. } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {
  21833. what = 'axis';
  21834. } else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) {
  21835. what = 'data-axis';
  21836. } else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) {
  21837. what = 'data-axis';
  21838. } else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) {
  21839. what = 'legend';
  21840. } else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) {
  21841. what = 'legend';
  21842. } else if (customTime != null) {
  21843. what = 'custom-time';
  21844. } else if (util.hasParent(element, this.currentTime.bar)) {
  21845. what = 'current-time';
  21846. } else if (util.hasParent(element, this.dom.center)) {
  21847. what = 'background';
  21848. }
  21849. var value = [];
  21850. var yAxisLeft = this.linegraph.yAxisLeft;
  21851. var yAxisRight = this.linegraph.yAxisRight;
  21852. if (!yAxisLeft.hidden) {
  21853. value.push(yAxisLeft.screenToValue(y));
  21854. }
  21855. if (!yAxisRight.hidden) {
  21856. value.push(yAxisRight.screenToValue(y));
  21857. }
  21858. return {
  21859. event: event,
  21860. what: what,
  21861. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  21862. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  21863. x: x,
  21864. y: y,
  21865. time: time,
  21866. value: value
  21867. };
  21868. };
  21869. /**
  21870. * Load a configurator
  21871. * @return {Object}
  21872. * @private
  21873. */
  21874. Graph2d.prototype._createConfigurator = function () {
  21875. return new _Configurator2.default(this, this.dom.container, configureOptions);
  21876. };
  21877. module.exports = Graph2d;
  21878. /***/ },
  21879. /* 51 */
  21880. /***/ function(module, exports, __webpack_require__) {
  21881. 'use strict';
  21882. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  21883. var util = __webpack_require__(1);
  21884. var DOMutil = __webpack_require__(8);
  21885. var DataSet = __webpack_require__(9);
  21886. var DataView = __webpack_require__(11);
  21887. var Component = __webpack_require__(31);
  21888. var DataAxis = __webpack_require__(52);
  21889. var GraphGroup = __webpack_require__(54);
  21890. var Legend = __webpack_require__(58);
  21891. var Bars = __webpack_require__(55);
  21892. var Lines = __webpack_require__(57);
  21893. var Points = __webpack_require__(56);
  21894. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  21895. /**
  21896. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  21897. *
  21898. * @param body
  21899. * @param options
  21900. * @constructor
  21901. */
  21902. function LineGraph(body, options) {
  21903. this.id = util.randomUUID();
  21904. this.body = body;
  21905. this.defaultOptions = {
  21906. yAxisOrientation: 'left',
  21907. defaultGroup: 'default',
  21908. sort: true,
  21909. sampling: true,
  21910. stack: false,
  21911. graphHeight: '400px',
  21912. shaded: {
  21913. enabled: false,
  21914. orientation: 'bottom' // top, bottom, zero
  21915. },
  21916. style: 'line', // line, bar
  21917. barChart: {
  21918. width: 50,
  21919. sideBySide: false,
  21920. align: 'center' // left, center, right
  21921. },
  21922. interpolation: {
  21923. enabled: true,
  21924. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  21925. alpha: 0.5
  21926. },
  21927. drawPoints: {
  21928. enabled: true,
  21929. size: 6,
  21930. style: 'square' // square, circle
  21931. },
  21932. dataAxis: {}, //Defaults are done on DataAxis level
  21933. legend: {}, //Defaults are done on Legend level
  21934. groups: {
  21935. visibility: {}
  21936. }
  21937. };
  21938. // options is shared by this lineGraph and all its items
  21939. this.options = util.extend({}, this.defaultOptions);
  21940. this.dom = {};
  21941. this.props = {};
  21942. this.hammer = null;
  21943. this.groups = {};
  21944. this.abortedGraphUpdate = false;
  21945. this.updateSVGheight = false;
  21946. this.updateSVGheightOnResize = false;
  21947. this.forceGraphUpdate = true;
  21948. var me = this;
  21949. this.itemsData = null; // DataSet
  21950. this.groupsData = null; // DataSet
  21951. // listeners for the DataSet of the items
  21952. this.itemListeners = {
  21953. 'add': function add(event, params, senderId) {
  21954. me._onAdd(params.items);
  21955. },
  21956. 'update': function update(event, params, senderId) {
  21957. me._onUpdate(params.items);
  21958. },
  21959. 'remove': function remove(event, params, senderId) {
  21960. me._onRemove(params.items);
  21961. }
  21962. };
  21963. // listeners for the DataSet of the groups
  21964. this.groupListeners = {
  21965. 'add': function add(event, params, senderId) {
  21966. me._onAddGroups(params.items);
  21967. },
  21968. 'update': function update(event, params, senderId) {
  21969. me._onUpdateGroups(params.items);
  21970. },
  21971. 'remove': function remove(event, params, senderId) {
  21972. me._onRemoveGroups(params.items);
  21973. }
  21974. };
  21975. this.items = {}; // object with an Item for every data item
  21976. this.selection = []; // list with the ids of all selected nodes
  21977. this.lastStart = this.body.range.start;
  21978. this.touchParams = {}; // stores properties while dragging
  21979. this.svgElements = {};
  21980. this.setOptions(options);
  21981. this.groupsUsingDefaultStyles = [0];
  21982. this.body.emitter.on('rangechanged', function () {
  21983. me.lastStart = me.body.range.start;
  21984. me.svg.style.left = util.option.asSize(-me.props.width);
  21985. me.forceGraphUpdate = true;
  21986. //Is this local redraw necessary? (Core also does a change event!)
  21987. me.redraw.call(me);
  21988. });
  21989. // create the HTML DOM
  21990. this._create();
  21991. this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups };
  21992. }
  21993. LineGraph.prototype = new Component();
  21994. /**
  21995. * Create the HTML DOM for the ItemSet
  21996. */
  21997. LineGraph.prototype._create = function () {
  21998. var frame = document.createElement('div');
  21999. frame.className = 'vis-line-graph';
  22000. this.dom.frame = frame;
  22001. // create svg element for graph drawing.
  22002. this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  22003. this.svg.style.position = 'relative';
  22004. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  22005. this.svg.style.display = 'block';
  22006. frame.appendChild(this.svg);
  22007. // data axis
  22008. this.options.dataAxis.orientation = 'left';
  22009. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  22010. this.options.dataAxis.orientation = 'right';
  22011. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  22012. delete this.options.dataAxis.orientation;
  22013. // legends
  22014. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  22015. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  22016. this.show();
  22017. };
  22018. /**
  22019. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  22020. * @param {object} options
  22021. */
  22022. LineGraph.prototype.setOptions = function (options) {
  22023. if (options) {
  22024. var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups'];
  22025. if (options.graphHeight === undefined && options.height !== undefined) {
  22026. this.updateSVGheight = true;
  22027. this.updateSVGheightOnResize = true;
  22028. } else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  22029. if (parseInt((options.graphHeight + '').replace("px", '')) < this.body.domProps.centerContainer.height) {
  22030. this.updateSVGheight = true;
  22031. }
  22032. }
  22033. util.selectiveDeepExtend(fields, this.options, options);
  22034. util.mergeOptions(this.options, options, 'interpolation');
  22035. util.mergeOptions(this.options, options, 'drawPoints');
  22036. util.mergeOptions(this.options, options, 'shaded');
  22037. util.mergeOptions(this.options, options, 'legend');
  22038. if (options.interpolation) {
  22039. if (_typeof(options.interpolation) == 'object') {
  22040. if (options.interpolation.parametrization) {
  22041. if (options.interpolation.parametrization == 'uniform') {
  22042. this.options.interpolation.alpha = 0;
  22043. } else if (options.interpolation.parametrization == 'chordal') {
  22044. this.options.interpolation.alpha = 1.0;
  22045. } else {
  22046. this.options.interpolation.parametrization = 'centripetal';
  22047. this.options.interpolation.alpha = 0.5;
  22048. }
  22049. }
  22050. }
  22051. }
  22052. if (this.yAxisLeft) {
  22053. if (options.dataAxis !== undefined) {
  22054. this.yAxisLeft.setOptions(this.options.dataAxis);
  22055. this.yAxisRight.setOptions(this.options.dataAxis);
  22056. }
  22057. }
  22058. if (this.legendLeft) {
  22059. if (options.legend !== undefined) {
  22060. this.legendLeft.setOptions(this.options.legend);
  22061. this.legendRight.setOptions(this.options.legend);
  22062. }
  22063. }
  22064. if (this.groups.hasOwnProperty(UNGROUPED)) {
  22065. this.groups[UNGROUPED].setOptions(options);
  22066. }
  22067. }
  22068. // this is used to redraw the graph if the visibility of the groups is changed.
  22069. if (this.dom.frame) {
  22070. //not on initial run?
  22071. this.forceGraphUpdate = true;
  22072. this.body.emitter.emit("_change", { queue: true });
  22073. }
  22074. };
  22075. /**
  22076. * Hide the component from the DOM
  22077. */
  22078. LineGraph.prototype.hide = function () {
  22079. // remove the frame containing the items
  22080. if (this.dom.frame.parentNode) {
  22081. this.dom.frame.parentNode.removeChild(this.dom.frame);
  22082. }
  22083. };
  22084. /**
  22085. * Show the component in the DOM (when not already visible).
  22086. * @return {Boolean} changed
  22087. */
  22088. LineGraph.prototype.show = function () {
  22089. // show frame containing the items
  22090. if (!this.dom.frame.parentNode) {
  22091. this.body.dom.center.appendChild(this.dom.frame);
  22092. }
  22093. };
  22094. /**
  22095. * Set items
  22096. * @param {vis.DataSet | null} items
  22097. */
  22098. LineGraph.prototype.setItems = function (items) {
  22099. var me = this,
  22100. ids,
  22101. oldItemsData = this.itemsData;
  22102. // replace the dataset
  22103. if (!items) {
  22104. this.itemsData = null;
  22105. } else if (items instanceof DataSet || items instanceof DataView) {
  22106. this.itemsData = items;
  22107. } else {
  22108. throw new TypeError('Data must be an instance of DataSet or DataView');
  22109. }
  22110. if (oldItemsData) {
  22111. // unsubscribe from old dataset
  22112. util.forEach(this.itemListeners, function (callback, event) {
  22113. oldItemsData.off(event, callback);
  22114. });
  22115. // remove all drawn items
  22116. ids = oldItemsData.getIds();
  22117. this._onRemove(ids);
  22118. }
  22119. if (this.itemsData) {
  22120. // subscribe to new dataset
  22121. var id = this.id;
  22122. util.forEach(this.itemListeners, function (callback, event) {
  22123. me.itemsData.on(event, callback, id);
  22124. });
  22125. // add all new items
  22126. ids = this.itemsData.getIds();
  22127. this._onAdd(ids);
  22128. }
  22129. };
  22130. /**
  22131. * Set groups
  22132. * @param {vis.DataSet} groups
  22133. */
  22134. LineGraph.prototype.setGroups = function (groups) {
  22135. var me = this;
  22136. var ids;
  22137. // unsubscribe from current dataset
  22138. if (this.groupsData) {
  22139. util.forEach(this.groupListeners, function (callback, event) {
  22140. me.groupsData.off(event, callback);
  22141. });
  22142. // remove all drawn groups
  22143. ids = this.groupsData.getIds();
  22144. this.groupsData = null;
  22145. for (var i = 0; i < ids.length; i++) {
  22146. this._removeGroup(ids[i]);
  22147. }
  22148. }
  22149. // replace the dataset
  22150. if (!groups) {
  22151. this.groupsData = null;
  22152. } else if (groups instanceof DataSet || groups instanceof DataView) {
  22153. this.groupsData = groups;
  22154. } else {
  22155. throw new TypeError('Data must be an instance of DataSet or DataView');
  22156. }
  22157. if (this.groupsData) {
  22158. // subscribe to new dataset
  22159. var id = this.id;
  22160. util.forEach(this.groupListeners, function (callback, event) {
  22161. me.groupsData.on(event, callback, id);
  22162. });
  22163. // draw all ms
  22164. ids = this.groupsData.getIds();
  22165. this._onAddGroups(ids);
  22166. }
  22167. };
  22168. LineGraph.prototype._onUpdate = function (ids) {
  22169. this._updateAllGroupData();
  22170. };
  22171. LineGraph.prototype._onAdd = function (ids) {
  22172. this._onUpdate(ids);
  22173. };
  22174. LineGraph.prototype._onRemove = function (ids) {
  22175. this._onUpdate(ids);
  22176. };
  22177. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  22178. this._updateAllGroupData();
  22179. };
  22180. LineGraph.prototype._onAddGroups = function (groupIds) {
  22181. this._onUpdateGroups(groupIds);
  22182. };
  22183. /**
  22184. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  22185. * @param {Array} groupIds
  22186. * @private
  22187. */
  22188. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  22189. for (var i = 0; i < groupIds.length; i++) {
  22190. this._removeGroup(groupIds[i]);
  22191. }
  22192. this.forceGraphUpdate = true;
  22193. this.body.emitter.emit("_change", { queue: true });
  22194. };
  22195. /**
  22196. * this cleans the group out off the legends and the dataaxis
  22197. * @param groupId
  22198. * @private
  22199. */
  22200. LineGraph.prototype._removeGroup = function (groupId) {
  22201. if (this.groups.hasOwnProperty(groupId)) {
  22202. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  22203. this.yAxisRight.removeGroup(groupId);
  22204. this.legendRight.removeGroup(groupId);
  22205. this.legendRight.redraw();
  22206. } else {
  22207. this.yAxisLeft.removeGroup(groupId);
  22208. this.legendLeft.removeGroup(groupId);
  22209. this.legendLeft.redraw();
  22210. }
  22211. delete this.groups[groupId];
  22212. }
  22213. };
  22214. /**
  22215. * update a group object with the group dataset entree
  22216. *
  22217. * @param group
  22218. * @param groupId
  22219. * @private
  22220. */
  22221. LineGraph.prototype._updateGroup = function (group, groupId) {
  22222. if (!this.groups.hasOwnProperty(groupId)) {
  22223. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  22224. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  22225. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  22226. this.legendRight.addGroup(groupId, this.groups[groupId]);
  22227. } else {
  22228. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  22229. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  22230. }
  22231. } else {
  22232. this.groups[groupId].update(group);
  22233. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  22234. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  22235. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  22236. //If yAxisOrientation changed, clean out the group from the other axis.
  22237. this.yAxisLeft.removeGroup(groupId);
  22238. this.legendLeft.removeGroup(groupId);
  22239. } else {
  22240. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  22241. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  22242. //If yAxisOrientation changed, clean out the group from the other axis.
  22243. this.yAxisRight.removeGroup(groupId);
  22244. this.legendRight.removeGroup(groupId);
  22245. }
  22246. }
  22247. this.legendLeft.redraw();
  22248. this.legendRight.redraw();
  22249. };
  22250. /**
  22251. * this updates all groups, it is used when there is an update the the itemset.
  22252. *
  22253. * @private
  22254. */
  22255. LineGraph.prototype._updateAllGroupData = function () {
  22256. if (this.itemsData != null) {
  22257. var groupsContent = {};
  22258. var items = this.itemsData.get();
  22259. //pre-Determine array sizes, for more efficient memory claim
  22260. var groupCounts = {};
  22261. for (var i = 0; i < items.length; i++) {
  22262. var item = items[i];
  22263. var groupId = item.group;
  22264. if (groupId === null || groupId === undefined) {
  22265. groupId = UNGROUPED;
  22266. }
  22267. groupCounts.hasOwnProperty(groupId) ? groupCounts[groupId]++ : groupCounts[groupId] = 1;
  22268. }
  22269. //Now insert data into the arrays.
  22270. for (var i = 0; i < items.length; i++) {
  22271. var item = items[i];
  22272. var groupId = item.group;
  22273. if (groupId === null || groupId === undefined) {
  22274. groupId = UNGROUPED;
  22275. }
  22276. if (!groupsContent.hasOwnProperty(groupId)) {
  22277. groupsContent[groupId] = new Array(groupCounts[groupId]);
  22278. }
  22279. //Copy data (because of unmodifiable DataView input.
  22280. var extended = util.bridgeObject(item);
  22281. extended.x = util.convert(item.x, 'Date');
  22282. extended.orginalY = item.y; //real Y
  22283. extended.y = Number(item.y);
  22284. var index = groupsContent[groupId].length - groupCounts[groupId]--;
  22285. groupsContent[groupId][index] = extended;
  22286. }
  22287. //Make sure all groups are present, to allow removal of old groups
  22288. for (var groupId in this.groups) {
  22289. if (this.groups.hasOwnProperty(groupId)) {
  22290. if (!groupsContent.hasOwnProperty(groupId)) {
  22291. groupsContent[groupId] = new Array(0);
  22292. }
  22293. }
  22294. }
  22295. //Update legendas, style and axis
  22296. for (var groupId in groupsContent) {
  22297. if (groupsContent.hasOwnProperty(groupId)) {
  22298. if (groupsContent[groupId].length == 0) {
  22299. if (this.groups.hasOwnProperty(groupId)) {
  22300. this._removeGroup(groupId);
  22301. }
  22302. } else {
  22303. var group = undefined;
  22304. if (this.groupsData != undefined) {
  22305. group = this.groupsData.get(groupId);
  22306. }
  22307. if (group == undefined) {
  22308. group = { id: groupId, content: this.options.defaultGroup + groupId };
  22309. }
  22310. this._updateGroup(group, groupId);
  22311. this.groups[groupId].setItems(groupsContent[groupId]);
  22312. }
  22313. }
  22314. }
  22315. this.forceGraphUpdate = true;
  22316. this.body.emitter.emit("_change", { queue: true });
  22317. }
  22318. };
  22319. /**
  22320. * Redraw the component, mandatory function
  22321. * @return {boolean} Returns true if the component is resized
  22322. */
  22323. LineGraph.prototype.redraw = function () {
  22324. var resized = false;
  22325. // calculate actual size and position
  22326. this.props.width = this.dom.frame.offsetWidth;
  22327. this.props.height = this.body.domProps.centerContainer.height - this.body.domProps.border.top - this.body.domProps.border.bottom;
  22328. // check if this component is resized
  22329. resized = this._isResized() || resized;
  22330. // check whether zoomed (in that case we need to re-stack everything)
  22331. var visibleInterval = this.body.range.end - this.body.range.start;
  22332. var zoomed = visibleInterval != this.lastVisibleInterval;
  22333. this.lastVisibleInterval = visibleInterval;
  22334. // the svg element is three times as big as the width, this allows for fully dragging left and right
  22335. // without reloading the graph. the controls for this are bound to events in the constructor
  22336. if (resized == true) {
  22337. this.svg.style.width = util.option.asSize(3 * this.props.width);
  22338. this.svg.style.left = util.option.asSize(-this.props.width);
  22339. // if the height of the graph is set as proportional, change the height of the svg
  22340. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  22341. this.updateSVGheight = true;
  22342. }
  22343. }
  22344. // update the height of the graph on each redraw of the graph.
  22345. if (this.updateSVGheight == true) {
  22346. if (this.options.graphHeight != this.props.height + 'px') {
  22347. this.options.graphHeight = this.props.height + 'px';
  22348. this.svg.style.height = this.props.height + 'px';
  22349. }
  22350. this.updateSVGheight = false;
  22351. } else {
  22352. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  22353. }
  22354. // zoomed is here to ensure that animations are shown correctly.
  22355. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || this.forceGraphUpdate == true) {
  22356. resized = this._updateGraph() || resized;
  22357. this.forceGraphUpdate = false;
  22358. } else {
  22359. // move the whole svg while dragging
  22360. if (this.lastStart != 0) {
  22361. var offset = this.body.range.start - this.lastStart;
  22362. var range = this.body.range.end - this.body.range.start;
  22363. if (this.props.width != 0) {
  22364. var rangePerPixelInv = this.props.width / range;
  22365. var xOffset = offset * rangePerPixelInv;
  22366. this.svg.style.left = -this.props.width - xOffset + 'px';
  22367. }
  22368. }
  22369. }
  22370. this.legendLeft.redraw();
  22371. this.legendRight.redraw();
  22372. return resized;
  22373. };
  22374. LineGraph.prototype._getSortedGroupIds = function () {
  22375. // getting group Ids
  22376. var grouplist = [];
  22377. for (var groupId in this.groups) {
  22378. if (this.groups.hasOwnProperty(groupId)) {
  22379. var group = this.groups[groupId];
  22380. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  22381. grouplist.push({ id: groupId, zIndex: group.options.zIndex });
  22382. }
  22383. }
  22384. }
  22385. util.insertSort(grouplist, function (a, b) {
  22386. var az = a.zIndex;
  22387. var bz = b.zIndex;
  22388. if (az === undefined) az = 0;
  22389. if (bz === undefined) bz = 0;
  22390. return az == bz ? 0 : az < bz ? -1 : 1;
  22391. });
  22392. var groupIds = new Array(grouplist.length);
  22393. for (var i = 0; i < grouplist.length; i++) {
  22394. groupIds[i] = grouplist[i].id;
  22395. }
  22396. return groupIds;
  22397. };
  22398. /**
  22399. * Update and redraw the graph.
  22400. *
  22401. */
  22402. LineGraph.prototype._updateGraph = function () {
  22403. // reset the svg elements
  22404. DOMutil.prepareElements(this.svgElements);
  22405. if (this.props.width != 0 && this.itemsData != null) {
  22406. var group, i;
  22407. var groupRanges = {};
  22408. var changeCalled = false;
  22409. // this is the range of the SVG canvas
  22410. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  22411. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  22412. // getting group Ids
  22413. var groupIds = this._getSortedGroupIds();
  22414. if (groupIds.length > 0) {
  22415. var groupsData = {};
  22416. // fill groups data, this only loads the data we require based on the timewindow
  22417. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  22418. // apply sampling, if disabled, it will pass through this function.
  22419. this._applySampling(groupIds, groupsData);
  22420. // we transform the X coordinates to detect collisions
  22421. for (i = 0; i < groupIds.length; i++) {
  22422. this._convertXcoordinates(groupsData[groupIds[i]]);
  22423. }
  22424. // now all needed data has been collected we start the processing.
  22425. this._getYRanges(groupIds, groupsData, groupRanges);
  22426. // update the Y axis first, we use this data to draw at the correct Y points
  22427. changeCalled = this._updateYAxis(groupIds, groupRanges);
  22428. // at changeCalled, abort this update cycle as the graph needs another update with new Width input from the Redraw container.
  22429. // Cleanup SVG elements on abort.
  22430. if (changeCalled == true) {
  22431. DOMutil.cleanupElements(this.svgElements);
  22432. this.abortedGraphUpdate = true;
  22433. return true;
  22434. }
  22435. this.abortedGraphUpdate = false;
  22436. // With the yAxis scaled correctly, use this to get the Y values of the points.
  22437. var below = undefined;
  22438. for (i = 0; i < groupIds.length; i++) {
  22439. group = this.groups[groupIds[i]];
  22440. if (this.options.stack === true && this.options.style === 'line') {
  22441. if (group.options.excludeFromStacking == undefined || !group.options.excludeFromStacking) {
  22442. if (below != undefined) {
  22443. this._stack(groupsData[group.id], groupsData[below.id]);
  22444. if (group.options.shaded.enabled == true && group.options.shaded.orientation !== "group") {
  22445. if (group.options.shaded.orientation == "top" && below.options.shaded.orientation !== "group") {
  22446. below.options.shaded.orientation = "group";
  22447. below.options.shaded.groupId = group.id;
  22448. } else {
  22449. group.options.shaded.orientation = "group";
  22450. group.options.shaded.groupId = below.id;
  22451. }
  22452. }
  22453. }
  22454. below = group;
  22455. }
  22456. }
  22457. this._convertYcoordinates(groupsData[groupIds[i]], group);
  22458. }
  22459. //Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
  22460. var paths = {};
  22461. for (i = 0; i < groupIds.length; i++) {
  22462. group = this.groups[groupIds[i]];
  22463. if (group.options.style === 'line' && group.options.shaded.enabled == true) {
  22464. var dataset = groupsData[groupIds[i]];
  22465. if (dataset == null || dataset.length == 0) {
  22466. continue;
  22467. }
  22468. if (!paths.hasOwnProperty(groupIds[i])) {
  22469. paths[groupIds[i]] = Lines.calcPath(dataset, group);
  22470. }
  22471. if (group.options.shaded.orientation === "group") {
  22472. var subGroupId = group.options.shaded.groupId;
  22473. if (groupIds.indexOf(subGroupId) === -1) {
  22474. console.log(group.id + ": Unknown shading group target given:" + subGroupId);
  22475. continue;
  22476. }
  22477. if (!paths.hasOwnProperty(subGroupId)) {
  22478. paths[subGroupId] = Lines.calcPath(groupsData[subGroupId], this.groups[subGroupId]);
  22479. }
  22480. Lines.drawShading(paths[groupIds[i]], group, paths[subGroupId], this.framework);
  22481. } else {
  22482. Lines.drawShading(paths[groupIds[i]], group, undefined, this.framework);
  22483. }
  22484. }
  22485. }
  22486. // draw the groups, calculating paths if still necessary.
  22487. Bars.draw(groupIds, groupsData, this.framework);
  22488. for (i = 0; i < groupIds.length; i++) {
  22489. group = this.groups[groupIds[i]];
  22490. if (groupsData[groupIds[i]].length > 0) {
  22491. switch (group.options.style) {
  22492. case "line":
  22493. if (!paths.hasOwnProperty(groupIds[i])) {
  22494. paths[groupIds[i]] = Lines.calcPath(groupsData[groupIds[i]], group);
  22495. }
  22496. Lines.draw(paths[groupIds[i]], group, this.framework);
  22497. //explicit no break;
  22498. case "point":
  22499. //explicit no break;
  22500. case "points":
  22501. if (group.options.style == "point" || group.options.style == "points" || group.options.drawPoints.enabled == true) {
  22502. Points.draw(groupsData[groupIds[i]], group, this.framework);
  22503. }
  22504. break;
  22505. case "bar":
  22506. // bar needs to be drawn enmasse
  22507. //explicit no break
  22508. default:
  22509. //do nothing...
  22510. }
  22511. }
  22512. }
  22513. }
  22514. }
  22515. // cleanup unused svg elements
  22516. DOMutil.cleanupElements(this.svgElements);
  22517. return false;
  22518. };
  22519. LineGraph.prototype._stack = function (data, subData) {
  22520. var index, dx, dy, subPrevPoint, subNextPoint;
  22521. index = 0;
  22522. // for each data point we look for a matching on in the set below
  22523. for (var j = 0; j < data.length; j++) {
  22524. subPrevPoint = undefined;
  22525. subNextPoint = undefined;
  22526. // we look for time matches or a before-after point
  22527. for (var k = index; k < subData.length; k++) {
  22528. // if times match exactly
  22529. if (subData[k].x === data[j].x) {
  22530. subPrevPoint = subData[k];
  22531. subNextPoint = subData[k];
  22532. index = k;
  22533. break;
  22534. } else if (subData[k].x > data[j].x) {
  22535. // overshoot
  22536. subNextPoint = subData[k];
  22537. if (k == 0) {
  22538. subPrevPoint = subNextPoint;
  22539. } else {
  22540. subPrevPoint = subData[k - 1];
  22541. }
  22542. index = k;
  22543. break;
  22544. }
  22545. }
  22546. // in case the last data point has been used, we assume it stays like this.
  22547. if (subNextPoint === undefined) {
  22548. subPrevPoint = subData[subData.length - 1];
  22549. subNextPoint = subData[subData.length - 1];
  22550. }
  22551. // linear interpolation
  22552. dx = subNextPoint.x - subPrevPoint.x;
  22553. dy = subNextPoint.y - subPrevPoint.y;
  22554. if (dx == 0) {
  22555. data[j].y = data[j].orginalY + subNextPoint.y;
  22556. } else {
  22557. data[j].y = data[j].orginalY + dy / dx * (data[j].x - subPrevPoint.x) + subPrevPoint.y; // ax + b where b is data[j].y
  22558. }
  22559. }
  22560. };
  22561. /**
  22562. * first select and preprocess the data from the datasets.
  22563. * the groups have their preselection of data, we now loop over this data to see
  22564. * what data we need to draw. Sorted data is much faster.
  22565. * more optimization is possible by doing the sampling before and using the binary search
  22566. * to find the end date to determine the increment.
  22567. *
  22568. * @param {array} groupIds
  22569. * @param {object} groupsData
  22570. * @param {date} minDate
  22571. * @param {date} maxDate
  22572. * @private
  22573. */
  22574. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  22575. var group, i, j, item;
  22576. if (groupIds.length > 0) {
  22577. for (i = 0; i < groupIds.length; i++) {
  22578. group = this.groups[groupIds[i]];
  22579. var itemsData = group.getItems();
  22580. // optimization for sorted data
  22581. if (group.options.sort == true) {
  22582. var dateComparator = function dateComparator(a, b) {
  22583. return a.getTime() == b.getTime() ? 0 : a < b ? -1 : 1;
  22584. };
  22585. var first = Math.max(0, util.binarySearchValue(itemsData, minDate, 'x', 'before', dateComparator));
  22586. var last = Math.min(itemsData.length, util.binarySearchValue(itemsData, maxDate, 'x', 'after', dateComparator) + 1);
  22587. if (last <= 0) {
  22588. last = itemsData.length;
  22589. }
  22590. var dataContainer = new Array(last - first);
  22591. for (j = first; j < last; j++) {
  22592. item = group.itemsData[j];
  22593. dataContainer[j - first] = item;
  22594. }
  22595. groupsData[groupIds[i]] = dataContainer;
  22596. } else {
  22597. // If unsorted data, all data is relevant, just returning entire structure
  22598. groupsData[groupIds[i]] = group.itemsData;
  22599. }
  22600. }
  22601. }
  22602. };
  22603. /**
  22604. *
  22605. * @param groupIds
  22606. * @param groupsData
  22607. * @private
  22608. */
  22609. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  22610. var group;
  22611. if (groupIds.length > 0) {
  22612. for (var i = 0; i < groupIds.length; i++) {
  22613. group = this.groups[groupIds[i]];
  22614. if (group.options.sampling == true) {
  22615. var dataContainer = groupsData[groupIds[i]];
  22616. if (dataContainer.length > 0) {
  22617. var increment = 1;
  22618. var amountOfPoints = dataContainer.length;
  22619. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  22620. // of width changing of the yAxis.
  22621. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  22622. var pointsPerPixel = amountOfPoints / xDistance;
  22623. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  22624. var sampledData = new Array(amountOfPoints);
  22625. for (var j = 0; j < amountOfPoints; j += increment) {
  22626. var idx = Math.round(j / increment);
  22627. sampledData[idx] = dataContainer[j];
  22628. }
  22629. groupsData[groupIds[i]] = sampledData.splice(0, Math.round(amountOfPoints / increment));
  22630. }
  22631. }
  22632. }
  22633. }
  22634. };
  22635. /**
  22636. *
  22637. *
  22638. * @param {array} groupIds
  22639. * @param {object} groupsData
  22640. * @param {object} groupRanges | this is being filled here
  22641. * @private
  22642. */
  22643. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  22644. var groupData, group, i;
  22645. var combinedDataLeft = [];
  22646. var combinedDataRight = [];
  22647. var options;
  22648. if (groupIds.length > 0) {
  22649. for (i = 0; i < groupIds.length; i++) {
  22650. groupData = groupsData[groupIds[i]];
  22651. options = this.groups[groupIds[i]].options;
  22652. if (groupData.length > 0) {
  22653. group = this.groups[groupIds[i]];
  22654. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  22655. if (options.stack === true && options.style === 'bar') {
  22656. if (options.yAxisOrientation === 'left') {
  22657. combinedDataLeft = combinedDataLeft.concat(group.getItems());
  22658. } else {
  22659. combinedDataRight = combinedDataRight.concat(group.getItems());
  22660. }
  22661. } else {
  22662. groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]);
  22663. }
  22664. }
  22665. }
  22666. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  22667. Bars.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left');
  22668. Bars.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  22669. }
  22670. };
  22671. /**
  22672. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  22673. * @param {Array} groupIds
  22674. * @param {Object} groupRanges
  22675. * @private
  22676. */
  22677. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  22678. var resized = false;
  22679. var yAxisLeftUsed = false;
  22680. var yAxisRightUsed = false;
  22681. var minLeft = 1e9,
  22682. minRight = 1e9,
  22683. maxLeft = -1e9,
  22684. maxRight = -1e9,
  22685. minVal,
  22686. maxVal;
  22687. // if groups are present
  22688. if (groupIds.length > 0) {
  22689. // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop.
  22690. for (var i = 0; i < groupIds.length; i++) {
  22691. var group = this.groups[groupIds[i]];
  22692. if (group && group.options.yAxisOrientation != 'right') {
  22693. yAxisLeftUsed = true;
  22694. minLeft = 1e9;
  22695. maxLeft = -1e9;
  22696. } else if (group && group.options.yAxisOrientation) {
  22697. yAxisRightUsed = true;
  22698. minRight = 1e9;
  22699. maxRight = -1e9;
  22700. }
  22701. }
  22702. // if there are items:
  22703. for (var i = 0; i < groupIds.length; i++) {
  22704. if (groupRanges.hasOwnProperty(groupIds[i])) {
  22705. if (groupRanges[groupIds[i]].ignore !== true) {
  22706. minVal = groupRanges[groupIds[i]].min;
  22707. maxVal = groupRanges[groupIds[i]].max;
  22708. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  22709. yAxisLeftUsed = true;
  22710. minLeft = minLeft > minVal ? minVal : minLeft;
  22711. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  22712. } else {
  22713. yAxisRightUsed = true;
  22714. minRight = minRight > minVal ? minVal : minRight;
  22715. maxRight = maxRight < maxVal ? maxVal : maxRight;
  22716. }
  22717. }
  22718. }
  22719. }
  22720. if (yAxisLeftUsed == true) {
  22721. this.yAxisLeft.setRange(minLeft, maxLeft);
  22722. }
  22723. if (yAxisRightUsed == true) {
  22724. this.yAxisRight.setRange(minRight, maxRight);
  22725. }
  22726. }
  22727. resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized;
  22728. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  22729. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  22730. this.yAxisLeft.drawIcons = true;
  22731. this.yAxisRight.drawIcons = true;
  22732. } else {
  22733. this.yAxisLeft.drawIcons = false;
  22734. this.yAxisRight.drawIcons = false;
  22735. }
  22736. this.yAxisRight.master = !yAxisLeftUsed;
  22737. this.yAxisRight.masterAxis = this.yAxisLeft;
  22738. if (this.yAxisRight.master == false) {
  22739. if (yAxisRightUsed == true) {
  22740. this.yAxisLeft.lineOffset = this.yAxisRight.width;
  22741. } else {
  22742. this.yAxisLeft.lineOffset = 0;
  22743. }
  22744. resized = this.yAxisLeft.redraw() || resized;
  22745. resized = this.yAxisRight.redraw() || resized;
  22746. } else {
  22747. resized = this.yAxisRight.redraw() || resized;
  22748. }
  22749. // clean the accumulated lists
  22750. var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight'];
  22751. for (var i = 0; i < tempGroups.length; i++) {
  22752. if (groupIds.indexOf(tempGroups[i]) != -1) {
  22753. groupIds.splice(groupIds.indexOf(tempGroups[i]), 1);
  22754. }
  22755. }
  22756. return resized;
  22757. };
  22758. /**
  22759. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  22760. *
  22761. * @param {boolean} axisUsed
  22762. * @returns {boolean}
  22763. * @private
  22764. * @param axis
  22765. */
  22766. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  22767. var changed = false;
  22768. if (axisUsed == false) {
  22769. if (axis.dom.frame.parentNode && axis.hidden == false) {
  22770. axis.hide();
  22771. changed = true;
  22772. }
  22773. } else {
  22774. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  22775. axis.show();
  22776. changed = true;
  22777. }
  22778. }
  22779. return changed;
  22780. };
  22781. /**
  22782. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  22783. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  22784. * the yAxis.
  22785. *
  22786. * @param datapoints
  22787. * @returns {Array}
  22788. * @private
  22789. */
  22790. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  22791. var toScreen = this.body.util.toScreen;
  22792. for (var i = 0; i < datapoints.length; i++) {
  22793. datapoints[i].screen_x = toScreen(datapoints[i].x) + this.props.width;
  22794. datapoints[i].screen_y = datapoints[i].y; //starting point for range calculations
  22795. }
  22796. };
  22797. /**
  22798. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  22799. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  22800. * the yAxis.
  22801. *
  22802. * @param datapoints
  22803. * @param group
  22804. * @returns {Array}
  22805. * @private
  22806. */
  22807. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  22808. var axis = this.yAxisLeft;
  22809. var svgHeight = Number(this.svg.style.height.replace('px', ''));
  22810. if (group.options.yAxisOrientation == 'right') {
  22811. axis = this.yAxisRight;
  22812. }
  22813. for (var i = 0; i < datapoints.length; i++) {
  22814. datapoints[i].screen_y = Math.round(axis.convertValue(datapoints[i].y));
  22815. }
  22816. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  22817. };
  22818. module.exports = LineGraph;
  22819. /***/ },
  22820. /* 52 */
  22821. /***/ function(module, exports, __webpack_require__) {
  22822. 'use strict';
  22823. var util = __webpack_require__(1);
  22824. var DOMutil = __webpack_require__(8);
  22825. var Component = __webpack_require__(31);
  22826. var DataScale = __webpack_require__(53);
  22827. /**
  22828. * A horizontal time axis
  22829. * @param {Object} [options] See DataAxis.setOptions for the available
  22830. * options.
  22831. * @constructor DataAxis
  22832. * @extends Component
  22833. * @param body
  22834. */
  22835. function DataAxis(body, options, svg, linegraphOptions) {
  22836. this.id = util.randomUUID();
  22837. this.body = body;
  22838. this.defaultOptions = {
  22839. orientation: 'left', // supported: 'left', 'right'
  22840. showMinorLabels: true,
  22841. showMajorLabels: true,
  22842. icons: false,
  22843. majorLinesOffset: 7,
  22844. minorLinesOffset: 4,
  22845. labelOffsetX: 10,
  22846. labelOffsetY: 2,
  22847. iconWidth: 20,
  22848. width: '40px',
  22849. visible: true,
  22850. alignZeros: true,
  22851. left: {
  22852. range: { min: undefined, max: undefined },
  22853. format: function format(value) {
  22854. return '' + parseFloat(value.toPrecision(3));
  22855. },
  22856. title: { text: undefined, style: undefined }
  22857. },
  22858. right: {
  22859. range: { min: undefined, max: undefined },
  22860. format: function format(value) {
  22861. return '' + parseFloat(value.toPrecision(3));
  22862. },
  22863. title: { text: undefined, style: undefined }
  22864. }
  22865. };
  22866. this.linegraphOptions = linegraphOptions;
  22867. this.linegraphSVG = svg;
  22868. this.props = {};
  22869. this.DOMelements = { // dynamic elements
  22870. lines: {},
  22871. labels: {},
  22872. title: {}
  22873. };
  22874. this.dom = {};
  22875. this.scale = undefined;
  22876. this.range = { start: 0, end: 0 };
  22877. this.options = util.extend({}, this.defaultOptions);
  22878. this.conversionFactor = 1;
  22879. this.setOptions(options);
  22880. this.width = Number(('' + this.options.width).replace("px", ""));
  22881. this.minWidth = this.width;
  22882. this.height = this.linegraphSVG.getBoundingClientRect().height;
  22883. this.hidden = false;
  22884. this.stepPixels = 25;
  22885. this.zeroCrossing = -1;
  22886. this.amountOfSteps = -1;
  22887. this.lineOffset = 0;
  22888. this.master = true;
  22889. this.masterAxis = null;
  22890. this.svgElements = {};
  22891. this.iconsRemoved = false;
  22892. this.groups = {};
  22893. this.amountOfGroups = 0;
  22894. // create the HTML DOM
  22895. this._create();
  22896. this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups };
  22897. var me = this;
  22898. this.body.emitter.on("verticalDrag", function () {
  22899. me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px';
  22900. });
  22901. }
  22902. DataAxis.prototype = new Component();
  22903. DataAxis.prototype.addGroup = function (label, graphOptions) {
  22904. if (!this.groups.hasOwnProperty(label)) {
  22905. this.groups[label] = graphOptions;
  22906. }
  22907. this.amountOfGroups += 1;
  22908. };
  22909. DataAxis.prototype.updateGroup = function (label, graphOptions) {
  22910. if (!this.groups.hasOwnProperty(label)) {
  22911. this.amountOfGroups += 1;
  22912. }
  22913. this.groups[label] = graphOptions;
  22914. };
  22915. DataAxis.prototype.removeGroup = function (label) {
  22916. if (this.groups.hasOwnProperty(label)) {
  22917. delete this.groups[label];
  22918. this.amountOfGroups -= 1;
  22919. }
  22920. };
  22921. DataAxis.prototype.setOptions = function (options) {
  22922. if (options) {
  22923. var redraw = false;
  22924. if (this.options.orientation != options.orientation && options.orientation !== undefined) {
  22925. redraw = true;
  22926. }
  22927. var fields = ['orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'left', 'right', 'alignZeros'];
  22928. util.selectiveDeepExtend(fields, this.options, options);
  22929. this.minWidth = Number(('' + this.options.width).replace("px", ""));
  22930. if (redraw === true && this.dom.frame) {
  22931. this.hide();
  22932. this.show();
  22933. }
  22934. }
  22935. };
  22936. /**
  22937. * Create the HTML DOM for the DataAxis
  22938. */
  22939. DataAxis.prototype._create = function () {
  22940. this.dom.frame = document.createElement('div');
  22941. this.dom.frame.style.width = this.options.width;
  22942. this.dom.frame.style.height = this.height;
  22943. this.dom.lineContainer = document.createElement('div');
  22944. this.dom.lineContainer.style.width = '100%';
  22945. this.dom.lineContainer.style.height = this.height;
  22946. this.dom.lineContainer.style.position = 'relative';
  22947. // create svg element for graph drawing.
  22948. this.svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
  22949. this.svg.style.position = "absolute";
  22950. this.svg.style.top = '0px';
  22951. this.svg.style.height = '100%';
  22952. this.svg.style.width = '100%';
  22953. this.svg.style.display = "block";
  22954. this.dom.frame.appendChild(this.svg);
  22955. };
  22956. DataAxis.prototype._redrawGroupIcons = function () {
  22957. DOMutil.prepareElements(this.svgElements);
  22958. var x;
  22959. var iconWidth = this.options.iconWidth;
  22960. var iconHeight = 15;
  22961. var iconOffset = 4;
  22962. var y = iconOffset + 0.5 * iconHeight;
  22963. if (this.options.orientation === 'left') {
  22964. x = iconOffset;
  22965. } else {
  22966. x = this.width - iconWidth - iconOffset;
  22967. }
  22968. var groupArray = Object.keys(this.groups);
  22969. groupArray.sort(function (a, b) {
  22970. return a < b ? -1 : 1;
  22971. });
  22972. for (var i = 0; i < groupArray.length; i++) {
  22973. var groupId = groupArray[i];
  22974. if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) {
  22975. this.groups[groupId].getLegend(iconWidth, iconHeight, this.framework, x, y);
  22976. y += iconHeight + iconOffset;
  22977. }
  22978. }
  22979. DOMutil.cleanupElements(this.svgElements);
  22980. this.iconsRemoved = false;
  22981. };
  22982. DataAxis.prototype._cleanupIcons = function () {
  22983. if (this.iconsRemoved === false) {
  22984. DOMutil.prepareElements(this.svgElements);
  22985. DOMutil.cleanupElements(this.svgElements);
  22986. this.iconsRemoved = true;
  22987. }
  22988. };
  22989. /**
  22990. * Create the HTML DOM for the DataAxis
  22991. */
  22992. DataAxis.prototype.show = function () {
  22993. this.hidden = false;
  22994. if (!this.dom.frame.parentNode) {
  22995. if (this.options.rtl) {
  22996. this.body.dom.left.appendChild(this.dom.frame);
  22997. } else {
  22998. this.body.dom.left.appendChild(this.dom.frame);
  22999. }
  23000. }
  23001. if (!this.dom.lineContainer.parentNode) {
  23002. this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
  23003. }
  23004. };
  23005. /**
  23006. * Create the HTML DOM for the DataAxis
  23007. */
  23008. DataAxis.prototype.hide = function () {
  23009. this.hidden = true;
  23010. if (this.dom.frame.parentNode) {
  23011. this.dom.frame.parentNode.removeChild(this.dom.frame);
  23012. }
  23013. if (this.dom.lineContainer.parentNode) {
  23014. this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
  23015. }
  23016. };
  23017. /**
  23018. * Set a range (start and end)
  23019. * @param end
  23020. * @param start
  23021. * @param end
  23022. */
  23023. DataAxis.prototype.setRange = function (start, end) {
  23024. this.range.start = start;
  23025. this.range.end = end;
  23026. };
  23027. /**
  23028. * Repaint the component
  23029. * @return {boolean} Returns true if the component is resized
  23030. */
  23031. DataAxis.prototype.redraw = function () {
  23032. var resized = false;
  23033. var activeGroups = 0;
  23034. // Make sure the line container adheres to the vertical scrolling.
  23035. this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px';
  23036. for (var groupId in this.groups) {
  23037. if (this.groups.hasOwnProperty(groupId)) {
  23038. if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) {
  23039. activeGroups++;
  23040. }
  23041. }
  23042. }
  23043. if (this.amountOfGroups === 0 || activeGroups === 0) {
  23044. this.hide();
  23045. } else {
  23046. this.show();
  23047. this.height = Number(this.linegraphSVG.style.height.replace("px", ""));
  23048. // svg offsetheight did not work in firefox and explorer...
  23049. this.dom.lineContainer.style.height = this.height + 'px';
  23050. this.width = this.options.visible === true ? Number(('' + this.options.width).replace("px", "")) : 0;
  23051. var props = this.props;
  23052. var frame = this.dom.frame;
  23053. // update classname
  23054. frame.className = 'vis-data-axis';
  23055. // calculate character width and height
  23056. this._calculateCharSize();
  23057. var orientation = this.options.orientation;
  23058. var showMinorLabels = this.options.showMinorLabels;
  23059. var showMajorLabels = this.options.showMajorLabels;
  23060. // determine the width and height of the elements for the axis
  23061. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  23062. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  23063. props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
  23064. props.minorLineHeight = 1;
  23065. props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
  23066. props.majorLineHeight = 1;
  23067. // take frame offline while updating (is almost twice as fast)
  23068. if (orientation === 'left') {
  23069. frame.style.top = '0';
  23070. frame.style.left = '0';
  23071. frame.style.bottom = '';
  23072. frame.style.width = this.width + 'px';
  23073. frame.style.height = this.height + "px";
  23074. this.props.width = this.body.domProps.left.width;
  23075. this.props.height = this.body.domProps.left.height;
  23076. } else {
  23077. // right
  23078. frame.style.top = '';
  23079. frame.style.bottom = '0';
  23080. frame.style.left = '0';
  23081. frame.style.width = this.width + 'px';
  23082. frame.style.height = this.height + "px";
  23083. this.props.width = this.body.domProps.right.width;
  23084. this.props.height = this.body.domProps.right.height;
  23085. }
  23086. resized = this._redrawLabels();
  23087. resized = this._isResized() || resized;
  23088. if (this.options.icons === true) {
  23089. this._redrawGroupIcons();
  23090. } else {
  23091. this._cleanupIcons();
  23092. }
  23093. this._redrawTitle(orientation);
  23094. }
  23095. return resized;
  23096. };
  23097. /**
  23098. * Repaint major and minor text labels and vertical grid lines
  23099. * @private
  23100. */
  23101. DataAxis.prototype._redrawLabels = function () {
  23102. var _this = this;
  23103. var resized = false;
  23104. DOMutil.prepareElements(this.DOMelements.lines);
  23105. DOMutil.prepareElements(this.DOMelements.labels);
  23106. var orientation = this.options['orientation'];
  23107. var customRange = this.options[orientation].range != undefined ? this.options[orientation].range : {};
  23108. //Override range with manual options:
  23109. var autoScaleEnd = true;
  23110. if (customRange.max != undefined) {
  23111. this.range.end = customRange.max;
  23112. autoScaleEnd = false;
  23113. }
  23114. var autoScaleStart = true;
  23115. if (customRange.min != undefined) {
  23116. this.range.start = customRange.min;
  23117. autoScaleStart = false;
  23118. }
  23119. this.scale = new DataScale(this.range.start, this.range.end, autoScaleStart, autoScaleEnd, this.dom.frame.offsetHeight, this.props.majorCharHeight, this.options.alignZeros, this.options[orientation].format);
  23120. if (this.master === false && this.masterAxis != undefined) {
  23121. this.scale.followScale(this.masterAxis.scale);
  23122. }
  23123. //Is updated in side-effect of _redrawLabel():
  23124. this.maxLabelSize = 0;
  23125. var lines = this.scale.getLines();
  23126. lines.forEach(function (line) {
  23127. var y = line.y;
  23128. var isMajor = line.major;
  23129. if (_this.options['showMinorLabels'] && isMajor === false) {
  23130. _this._redrawLabel(y - 2, line.val, orientation, 'vis-y-axis vis-minor', _this.props.minorCharHeight);
  23131. }
  23132. if (isMajor) {
  23133. if (y >= 0) {
  23134. _this._redrawLabel(y - 2, line.val, orientation, 'vis-y-axis vis-major', _this.props.majorCharHeight);
  23135. }
  23136. }
  23137. if (_this.master === true) {
  23138. if (isMajor) {
  23139. _this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-major', _this.options.majorLinesOffset, _this.props.majorLineWidth);
  23140. } else {
  23141. _this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-minor', _this.options.minorLinesOffset, _this.props.minorLineWidth);
  23142. }
  23143. }
  23144. });
  23145. // Note that title is rotated, so we're using the height, not width!
  23146. var titleWidth = 0;
  23147. if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) {
  23148. titleWidth = this.props.titleCharHeight;
  23149. }
  23150. var offset = this.options.icons === true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15;
  23151. // this will resize the yAxis to accommodate the labels.
  23152. if (this.maxLabelSize > this.width - offset && this.options.visible === true) {
  23153. this.width = this.maxLabelSize + offset;
  23154. this.options.width = this.width + "px";
  23155. DOMutil.cleanupElements(this.DOMelements.lines);
  23156. DOMutil.cleanupElements(this.DOMelements.labels);
  23157. this.redraw();
  23158. resized = true;
  23159. }
  23160. // this will resize the yAxis if it is too big for the labels.
  23161. else if (this.maxLabelSize < this.width - offset && this.options.visible === true && this.width > this.minWidth) {
  23162. this.width = Math.max(this.minWidth, this.maxLabelSize + offset);
  23163. this.options.width = this.width + "px";
  23164. DOMutil.cleanupElements(this.DOMelements.lines);
  23165. DOMutil.cleanupElements(this.DOMelements.labels);
  23166. this.redraw();
  23167. resized = true;
  23168. } else {
  23169. DOMutil.cleanupElements(this.DOMelements.lines);
  23170. DOMutil.cleanupElements(this.DOMelements.labels);
  23171. resized = false;
  23172. }
  23173. return resized;
  23174. };
  23175. DataAxis.prototype.convertValue = function (value) {
  23176. return this.scale.convertValue(value);
  23177. };
  23178. DataAxis.prototype.screenToValue = function (x) {
  23179. return this.scale.screenToValue(x);
  23180. };
  23181. /**
  23182. * Create a label for the axis at position x
  23183. * @private
  23184. * @param y
  23185. * @param text
  23186. * @param orientation
  23187. * @param className
  23188. * @param characterHeight
  23189. */
  23190. DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
  23191. // reuse redundant label
  23192. var label = DOMutil.getDOMElement('div', this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
  23193. label.className = className;
  23194. label.innerHTML = text;
  23195. if (orientation === 'left') {
  23196. label.style.left = '-' + this.options.labelOffsetX + 'px';
  23197. label.style.textAlign = "right";
  23198. } else {
  23199. label.style.right = '-' + this.options.labelOffsetX + 'px';
  23200. label.style.textAlign = "left";
  23201. }
  23202. label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
  23203. text += '';
  23204. var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth);
  23205. if (this.maxLabelSize < text.length * largestWidth) {
  23206. this.maxLabelSize = text.length * largestWidth;
  23207. }
  23208. };
  23209. /**
  23210. * Create a minor line for the axis at position y
  23211. * @param y
  23212. * @param orientation
  23213. * @param className
  23214. * @param offset
  23215. * @param width
  23216. */
  23217. DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
  23218. if (this.master === true) {
  23219. var line = DOMutil.getDOMElement('div', this.DOMelements.lines, this.dom.lineContainer); //this.dom.redundant.lines.shift();
  23220. line.className = className;
  23221. line.innerHTML = '';
  23222. if (orientation === 'left') {
  23223. line.style.left = this.width - offset + 'px';
  23224. } else {
  23225. line.style.right = this.width - offset + 'px';
  23226. }
  23227. line.style.width = width + 'px';
  23228. line.style.top = y + 'px';
  23229. }
  23230. };
  23231. /**
  23232. * Create a title for the axis
  23233. * @private
  23234. * @param orientation
  23235. */
  23236. DataAxis.prototype._redrawTitle = function (orientation) {
  23237. DOMutil.prepareElements(this.DOMelements.title);
  23238. // Check if the title is defined for this axes
  23239. if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) {
  23240. var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame);
  23241. title.className = 'vis-y-axis vis-title vis-' + orientation;
  23242. title.innerHTML = this.options[orientation].title.text;
  23243. // Add style - if provided
  23244. if (this.options[orientation].title.style !== undefined) {
  23245. util.addCssText(title, this.options[orientation].title.style);
  23246. }
  23247. if (orientation === 'left') {
  23248. title.style.left = this.props.titleCharHeight + 'px';
  23249. } else {
  23250. title.style.right = this.props.titleCharHeight + 'px';
  23251. }
  23252. title.style.width = this.height + 'px';
  23253. }
  23254. // we need to clean up in case we did not use all elements.
  23255. DOMutil.cleanupElements(this.DOMelements.title);
  23256. };
  23257. /**
  23258. * Determine the size of text on the axis (both major and minor axis).
  23259. * The size is calculated only once and then cached in this.props.
  23260. * @private
  23261. */
  23262. DataAxis.prototype._calculateCharSize = function () {
  23263. // determine the char width and height on the minor axis
  23264. if (!('minorCharHeight' in this.props)) {
  23265. var textMinor = document.createTextNode('0');
  23266. var measureCharMinor = document.createElement('div');
  23267. measureCharMinor.className = 'vis-y-axis vis-minor vis-measure';
  23268. measureCharMinor.appendChild(textMinor);
  23269. this.dom.frame.appendChild(measureCharMinor);
  23270. this.props.minorCharHeight = measureCharMinor.clientHeight;
  23271. this.props.minorCharWidth = measureCharMinor.clientWidth;
  23272. this.dom.frame.removeChild(measureCharMinor);
  23273. }
  23274. if (!('majorCharHeight' in this.props)) {
  23275. var textMajor = document.createTextNode('0');
  23276. var measureCharMajor = document.createElement('div');
  23277. measureCharMajor.className = 'vis-y-axis vis-major vis-measure';
  23278. measureCharMajor.appendChild(textMajor);
  23279. this.dom.frame.appendChild(measureCharMajor);
  23280. this.props.majorCharHeight = measureCharMajor.clientHeight;
  23281. this.props.majorCharWidth = measureCharMajor.clientWidth;
  23282. this.dom.frame.removeChild(measureCharMajor);
  23283. }
  23284. if (!('titleCharHeight' in this.props)) {
  23285. var textTitle = document.createTextNode('0');
  23286. var measureCharTitle = document.createElement('div');
  23287. measureCharTitle.className = 'vis-y-axis vis-title vis-measure';
  23288. measureCharTitle.appendChild(textTitle);
  23289. this.dom.frame.appendChild(measureCharTitle);
  23290. this.props.titleCharHeight = measureCharTitle.clientHeight;
  23291. this.props.titleCharWidth = measureCharTitle.clientWidth;
  23292. this.dom.frame.removeChild(measureCharTitle);
  23293. }
  23294. };
  23295. module.exports = DataAxis;
  23296. /***/ },
  23297. /* 53 */
  23298. /***/ function(module, exports) {
  23299. 'use strict';
  23300. /**
  23301. * Created by ludo on 25-1-16.
  23302. */
  23303. function DataScale(start, end, autoScaleStart, autoScaleEnd, containerHeight, majorCharHeight) {
  23304. var zeroAlign = arguments.length <= 6 || arguments[6] === undefined ? false : arguments[6];
  23305. var formattingFunction = arguments.length <= 7 || arguments[7] === undefined ? false : arguments[7];
  23306. this.majorSteps = [1, 2, 5, 10];
  23307. this.minorSteps = [0.25, 0.5, 1, 2];
  23308. this.customLines = null;
  23309. this.containerHeight = containerHeight;
  23310. this.majorCharHeight = majorCharHeight;
  23311. this._start = start;
  23312. this._end = end;
  23313. this.scale = 1;
  23314. this.minorStepIdx = -1;
  23315. this.magnitudefactor = 1;
  23316. this.determineScale();
  23317. this.zeroAlign = zeroAlign;
  23318. this.autoScaleStart = autoScaleStart;
  23319. this.autoScaleEnd = autoScaleEnd;
  23320. this.formattingFunction = formattingFunction;
  23321. if (autoScaleStart || autoScaleEnd) {
  23322. var me = this;
  23323. var roundToMinor = function roundToMinor(value) {
  23324. var rounded = value - value % (me.magnitudefactor * me.minorSteps[me.minorStepIdx]);
  23325. if (value % (me.magnitudefactor * me.minorSteps[me.minorStepIdx]) > 0.5 * (me.magnitudefactor * me.minorSteps[me.minorStepIdx])) {
  23326. return rounded + me.magnitudefactor * me.minorSteps[me.minorStepIdx];
  23327. } else {
  23328. return rounded;
  23329. }
  23330. };
  23331. if (autoScaleStart) {
  23332. this._start -= this.magnitudefactor * 2 * this.minorSteps[this.minorStepIdx];
  23333. this._start = roundToMinor(this._start);
  23334. }
  23335. if (autoScaleEnd) {
  23336. this._end += this.magnitudefactor * this.minorSteps[this.minorStepIdx];
  23337. this._end = roundToMinor(this._end);
  23338. }
  23339. this.determineScale();
  23340. }
  23341. }
  23342. DataScale.prototype.setCharHeight = function (majorCharHeight) {
  23343. this.majorCharHeight = majorCharHeight;
  23344. };
  23345. DataScale.prototype.setHeight = function (containerHeight) {
  23346. this.containerHeight = containerHeight;
  23347. };
  23348. DataScale.prototype.determineScale = function () {
  23349. var range = this._end - this._start;
  23350. this.scale = this.containerHeight / range;
  23351. var minimumStepValue = this.majorCharHeight / this.scale;
  23352. var orderOfMagnitude = range > 0 ? Math.round(Math.log(range) / Math.LN10) : 0;
  23353. this.minorStepIdx = -1;
  23354. this.magnitudefactor = Math.pow(10, orderOfMagnitude);
  23355. var start = 0;
  23356. if (orderOfMagnitude < 0) {
  23357. start = orderOfMagnitude;
  23358. }
  23359. var solutionFound = false;
  23360. for (var l = start; Math.abs(l) <= Math.abs(orderOfMagnitude); l++) {
  23361. this.magnitudefactor = Math.pow(10, l);
  23362. for (var j = 0; j < this.minorSteps.length; j++) {
  23363. var stepSize = this.magnitudefactor * this.minorSteps[j];
  23364. if (stepSize >= minimumStepValue) {
  23365. solutionFound = true;
  23366. this.minorStepIdx = j;
  23367. break;
  23368. }
  23369. }
  23370. if (solutionFound === true) {
  23371. break;
  23372. }
  23373. }
  23374. };
  23375. DataScale.prototype.is_major = function (value) {
  23376. return value % (this.magnitudefactor * this.majorSteps[this.minorStepIdx]) === 0;
  23377. };
  23378. DataScale.prototype.getStep = function () {
  23379. return this.magnitudefactor * this.minorSteps[this.minorStepIdx];
  23380. };
  23381. DataScale.prototype.getFirstMajor = function () {
  23382. var majorStep = this.magnitudefactor * this.majorSteps[this.minorStepIdx];
  23383. return this.convertValue(this._start + (majorStep - this._start % majorStep) % majorStep);
  23384. };
  23385. DataScale.prototype.formatValue = function (current) {
  23386. var returnValue = current.toPrecision(5);
  23387. if (typeof this.formattingFunction === 'function') {
  23388. returnValue = this.formattingFunction(current);
  23389. }
  23390. if (typeof returnValue === 'number') {
  23391. return '' + returnValue;
  23392. } else if (typeof returnValue === 'string') {
  23393. return returnValue;
  23394. } else {
  23395. return current.toPrecision(5);
  23396. }
  23397. };
  23398. DataScale.prototype.getLines = function () {
  23399. var lines = [];
  23400. var step = this.getStep();
  23401. var bottomOffset = (step - this._start % step) % step;
  23402. for (var i = this._start + bottomOffset; this._end - i > 0.00001; i += step) {
  23403. if (i != this._start) {
  23404. //Skip the bottom line
  23405. lines.push({ major: this.is_major(i), y: this.convertValue(i), val: this.formatValue(i) });
  23406. }
  23407. }
  23408. return lines;
  23409. };
  23410. DataScale.prototype.followScale = function (other) {
  23411. var oldStepIdx = this.minorStepIdx;
  23412. var oldStart = this._start;
  23413. var oldEnd = this._end;
  23414. var me = this;
  23415. var increaseMagnitude = function increaseMagnitude() {
  23416. me.magnitudefactor *= 2;
  23417. };
  23418. var decreaseMagnitude = function decreaseMagnitude() {
  23419. me.magnitudefactor /= 2;
  23420. };
  23421. if (other.minorStepIdx <= 1 && this.minorStepIdx <= 1 || other.minorStepIdx > 1 && this.minorStepIdx > 1) {
  23422. //easy, no need to change stepIdx nor multiplication factor
  23423. } else if (other.minorStepIdx < this.minorStepIdx) {
  23424. //I'm 5, they are 4 per major.
  23425. this.minorStepIdx = 1;
  23426. if (oldStepIdx == 2) {
  23427. increaseMagnitude();
  23428. } else {
  23429. increaseMagnitude();
  23430. increaseMagnitude();
  23431. }
  23432. } else {
  23433. //I'm 4, they are 5 per major
  23434. this.minorStepIdx = 2;
  23435. if (oldStepIdx == 1) {
  23436. decreaseMagnitude();
  23437. } else {
  23438. decreaseMagnitude();
  23439. decreaseMagnitude();
  23440. }
  23441. }
  23442. //Get masters stats:
  23443. var lines = other.getLines();
  23444. var otherZero = other.convertValue(0);
  23445. var otherStep = other.getStep() * other.scale;
  23446. var done = false;
  23447. var count = 0;
  23448. //Loop until magnitude is correct for given constrains.
  23449. while (!done && count++ < 5) {
  23450. //Get my stats:
  23451. this.scale = otherStep / (this.minorSteps[this.minorStepIdx] * this.magnitudefactor);
  23452. var newRange = this.containerHeight / this.scale;
  23453. //For the case the magnitudefactor has changed:
  23454. this._start = oldStart;
  23455. this._end = this._start + newRange;
  23456. var myOriginalZero = this._end * this.scale;
  23457. var majorStep = this.magnitudefactor * this.majorSteps[this.minorStepIdx];
  23458. var majorOffset = this.getFirstMajor() - other.getFirstMajor();
  23459. if (this.zeroAlign) {
  23460. var zeroOffset = otherZero - myOriginalZero;
  23461. this._end += zeroOffset / this.scale;
  23462. this._start = this._end - newRange;
  23463. } else {
  23464. if (!this.autoScaleStart) {
  23465. this._start += majorStep - majorOffset / this.scale;
  23466. this._end = this._start + newRange;
  23467. } else {
  23468. this._start -= majorOffset / this.scale;
  23469. this._end = this._start + newRange;
  23470. }
  23471. }
  23472. if (!this.autoScaleEnd && this._end > oldEnd + 0.00001) {
  23473. //Need to decrease magnitude to prevent scale overshoot! (end)
  23474. decreaseMagnitude();
  23475. done = false;
  23476. continue;
  23477. }
  23478. if (!this.autoScaleStart && this._start < oldStart - 0.00001) {
  23479. if (this.zeroAlign && oldStart >= 0) {
  23480. console.warn("Can't adhere to given 'min' range, due to zeroalign");
  23481. } else {
  23482. //Need to decrease magnitude to prevent scale overshoot! (start)
  23483. decreaseMagnitude();
  23484. done = false;
  23485. continue;
  23486. }
  23487. }
  23488. if (this.autoScaleStart && this.autoScaleEnd && newRange < oldEnd - oldStart) {
  23489. increaseMagnitude();
  23490. done = false;
  23491. continue;
  23492. }
  23493. done = true;
  23494. }
  23495. };
  23496. DataScale.prototype.convertValue = function (value) {
  23497. return this.containerHeight - (value - this._start) * this.scale;
  23498. };
  23499. DataScale.prototype.screenToValue = function (pixels) {
  23500. return (this.containerHeight - pixels) / this.scale + this._start;
  23501. };
  23502. module.exports = DataScale;
  23503. /***/ },
  23504. /* 54 */
  23505. /***/ function(module, exports, __webpack_require__) {
  23506. 'use strict';
  23507. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  23508. var util = __webpack_require__(1);
  23509. var DOMutil = __webpack_require__(8);
  23510. var Bars = __webpack_require__(55);
  23511. var Lines = __webpack_require__(57);
  23512. var Points = __webpack_require__(56);
  23513. /**
  23514. * /**
  23515. * @param {object} group | the object of the group from the dataset
  23516. * @param {string} groupId | ID of the group
  23517. * @param {object} options | the default options
  23518. * @param {array} groupsUsingDefaultStyles | this array has one entree.
  23519. * It is passed as an array so it is passed by reference.
  23520. * It enumerates through the default styles
  23521. * @constructor
  23522. */
  23523. function GraphGroup(group, groupId, options, groupsUsingDefaultStyles) {
  23524. this.id = groupId;
  23525. var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'drawPoints', 'shaded', 'interpolation', 'zIndex', 'excludeFromStacking', 'excludeFromLegend'];
  23526. this.options = util.selectiveBridgeObject(fields, options);
  23527. this.usingDefaultStyle = group.className === undefined;
  23528. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  23529. this.zeroPosition = 0;
  23530. this.update(group);
  23531. if (this.usingDefaultStyle == true) {
  23532. this.groupsUsingDefaultStyles[0] += 1;
  23533. }
  23534. this.itemsData = [];
  23535. this.visible = group.visible === undefined ? true : group.visible;
  23536. }
  23537. /**
  23538. * this loads a reference to all items in this group into this group.
  23539. * @param {array} items
  23540. */
  23541. GraphGroup.prototype.setItems = function (items) {
  23542. if (items != null) {
  23543. this.itemsData = items;
  23544. if (this.options.sort == true) {
  23545. util.insertSort(this.itemsData, function (a, b) {
  23546. return a.x > b.x ? 1 : -1;
  23547. });
  23548. }
  23549. } else {
  23550. this.itemsData = [];
  23551. }
  23552. };
  23553. GraphGroup.prototype.getItems = function () {
  23554. return this.itemsData;
  23555. };
  23556. /**
  23557. * this is used for barcharts and shading, this way, we only have to calculate it once.
  23558. * @param pos
  23559. */
  23560. GraphGroup.prototype.setZeroPosition = function (pos) {
  23561. this.zeroPosition = pos;
  23562. };
  23563. /**
  23564. * set the options of the graph group over the default options.
  23565. * @param options
  23566. */
  23567. GraphGroup.prototype.setOptions = function (options) {
  23568. if (options !== undefined) {
  23569. var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'zIndex', 'excludeFromStacking', 'excludeFromLegend'];
  23570. util.selectiveDeepExtend(fields, this.options, options);
  23571. // if the group's drawPoints is a function delegate the callback to the onRender property
  23572. if (typeof options.drawPoints == 'function') {
  23573. options.drawPoints = {
  23574. onRender: options.drawPoints
  23575. };
  23576. }
  23577. util.mergeOptions(this.options, options, 'interpolation');
  23578. util.mergeOptions(this.options, options, 'drawPoints');
  23579. util.mergeOptions(this.options, options, 'shaded');
  23580. if (options.interpolation) {
  23581. if (_typeof(options.interpolation) == 'object') {
  23582. if (options.interpolation.parametrization) {
  23583. if (options.interpolation.parametrization == 'uniform') {
  23584. this.options.interpolation.alpha = 0;
  23585. } else if (options.interpolation.parametrization == 'chordal') {
  23586. this.options.interpolation.alpha = 1.0;
  23587. } else {
  23588. this.options.interpolation.parametrization = 'centripetal';
  23589. this.options.interpolation.alpha = 0.5;
  23590. }
  23591. }
  23592. }
  23593. }
  23594. }
  23595. };
  23596. /**
  23597. * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
  23598. * @param group
  23599. */
  23600. GraphGroup.prototype.update = function (group) {
  23601. this.group = group;
  23602. this.content = group.content || 'graph';
  23603. this.className = group.className || this.className || 'vis-graph-group' + this.groupsUsingDefaultStyles[0] % 10;
  23604. this.visible = group.visible === undefined ? true : group.visible;
  23605. this.style = group.style;
  23606. this.setOptions(group.options);
  23607. };
  23608. /**
  23609. * return the legend entree for this group.
  23610. *
  23611. * @param iconWidth
  23612. * @param iconHeight
  23613. * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
  23614. */
  23615. GraphGroup.prototype.getLegend = function (iconWidth, iconHeight, framework, x, y) {
  23616. if (framework == undefined || framework == null) {
  23617. var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
  23618. framework = { svg: svg, svgElements: {}, options: this.options, groups: [this] };
  23619. }
  23620. if (x == undefined || x == null) {
  23621. x = 0;
  23622. }
  23623. if (y == undefined || y == null) {
  23624. y = 0.5 * iconHeight;
  23625. }
  23626. switch (this.options.style) {
  23627. case "line":
  23628. Lines.drawIcon(this, x, y, iconWidth, iconHeight, framework);
  23629. break;
  23630. case "points": //explicit no break
  23631. case "point":
  23632. Points.drawIcon(this, x, y, iconWidth, iconHeight, framework);
  23633. break;
  23634. case "bar":
  23635. Bars.drawIcon(this, x, y, iconWidth, iconHeight, framework);
  23636. break;
  23637. }
  23638. return { icon: framework.svg, label: this.content, orientation: this.options.yAxisOrientation };
  23639. };
  23640. GraphGroup.prototype.getYRange = function (groupData) {
  23641. var yMin = groupData[0].y;
  23642. var yMax = groupData[0].y;
  23643. for (var j = 0; j < groupData.length; j++) {
  23644. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  23645. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  23646. }
  23647. return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation };
  23648. };
  23649. module.exports = GraphGroup;
  23650. /***/ },
  23651. /* 55 */
  23652. /***/ function(module, exports, __webpack_require__) {
  23653. 'use strict';
  23654. var DOMutil = __webpack_require__(8);
  23655. var Points = __webpack_require__(56);
  23656. function Bargraph(groupId, options) {}
  23657. Bargraph.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
  23658. var fillHeight = iconHeight * 0.5;
  23659. var path, fillPath;
  23660. var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
  23661. outline.setAttributeNS(null, "x", x);
  23662. outline.setAttributeNS(null, "y", y - fillHeight);
  23663. outline.setAttributeNS(null, "width", iconWidth);
  23664. outline.setAttributeNS(null, "height", 2 * fillHeight);
  23665. outline.setAttributeNS(null, "class", "vis-outline");
  23666. var barWidth = Math.round(0.3 * iconWidth);
  23667. var originalWidth = group.options.barChart.width;
  23668. var scale = originalWidth / barWidth;
  23669. var bar1Height = Math.round(0.4 * iconHeight);
  23670. var bar2Height = Math.round(0.75 * iconHeight);
  23671. var offset = Math.round((iconWidth - 2 * barWidth) / 3);
  23672. DOMutil.drawBar(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, barWidth, bar1Height, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style);
  23673. DOMutil.drawBar(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style);
  23674. if (group.options.drawPoints.enabled == true) {
  23675. var groupTemplate = {
  23676. style: group.options.drawPoints.style,
  23677. styles: group.options.drawPoints.styles,
  23678. size: group.options.drawPoints.size / scale,
  23679. className: group.className
  23680. };
  23681. DOMutil.drawPoint(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, groupTemplate, framework.svgElements, framework.svg);
  23682. DOMutil.drawPoint(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, groupTemplate, framework.svgElements, framework.svg);
  23683. }
  23684. };
  23685. /**
  23686. * draw a bar graph
  23687. *
  23688. * @param groupIds
  23689. * @param processedGroupData
  23690. */
  23691. Bargraph.draw = function (groupIds, processedGroupData, framework) {
  23692. var combinedData = [];
  23693. var intersections = {};
  23694. var coreDistance;
  23695. var key, drawData;
  23696. var group;
  23697. var i, j;
  23698. var barPoints = 0;
  23699. // combine all barchart data
  23700. for (i = 0; i < groupIds.length; i++) {
  23701. group = framework.groups[groupIds[i]];
  23702. if (group.options.style === 'bar') {
  23703. if (group.visible === true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] === true)) {
  23704. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  23705. combinedData.push({
  23706. screen_x: processedGroupData[groupIds[i]][j].screen_x,
  23707. screen_y: processedGroupData[groupIds[i]][j].screen_y,
  23708. x: processedGroupData[groupIds[i]][j].x,
  23709. y: processedGroupData[groupIds[i]][j].y,
  23710. groupId: groupIds[i],
  23711. label: processedGroupData[groupIds[i]][j].label
  23712. });
  23713. barPoints += 1;
  23714. }
  23715. }
  23716. }
  23717. }
  23718. if (barPoints === 0) {
  23719. return;
  23720. }
  23721. // sort by time and by group
  23722. combinedData.sort(function (a, b) {
  23723. if (a.screen_x === b.screen_x) {
  23724. return a.groupId < b.groupId ? -1 : 1;
  23725. } else {
  23726. return a.screen_x - b.screen_x;
  23727. }
  23728. });
  23729. // get intersections
  23730. Bargraph._getDataIntersections(intersections, combinedData);
  23731. // plot barchart
  23732. for (i = 0; i < combinedData.length; i++) {
  23733. group = framework.groups[combinedData[i].groupId];
  23734. var minWidth = group.options.barChart.minWidth != undefined ? group.options.barChart.minWidth : 0.1 * group.options.barChart.width;
  23735. key = combinedData[i].screen_x;
  23736. var heightOffset = 0;
  23737. if (intersections[key] === undefined) {
  23738. if (i + 1 < combinedData.length) {
  23739. coreDistance = Math.abs(combinedData[i + 1].screen_x - key);
  23740. }
  23741. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  23742. } else {
  23743. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  23744. var prevKey = i - (intersections[key].resolved + 1);
  23745. if (nextKey < combinedData.length) {
  23746. coreDistance = Math.abs(combinedData[nextKey].screen_x - key);
  23747. }
  23748. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  23749. intersections[key].resolved += 1;
  23750. if (group.options.stack === true && group.options.excludeFromStacking !== true) {
  23751. if (combinedData[i].screen_y < group.zeroPosition) {
  23752. heightOffset = intersections[key].accumulatedNegative;
  23753. intersections[key].accumulatedNegative += group.zeroPosition - combinedData[i].screen_y;
  23754. } else {
  23755. heightOffset = intersections[key].accumulatedPositive;
  23756. intersections[key].accumulatedPositive += group.zeroPosition - combinedData[i].screen_y;
  23757. }
  23758. } else if (group.options.barChart.sideBySide === true) {
  23759. drawData.width = drawData.width / intersections[key].amount;
  23760. drawData.offset += intersections[key].resolved * drawData.width - 0.5 * drawData.width * (intersections[key].amount + 1);
  23761. }
  23762. }
  23763. DOMutil.drawBar(combinedData[i].screen_x + drawData.offset, combinedData[i].screen_y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].screen_y, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style);
  23764. // draw points
  23765. if (group.options.drawPoints.enabled === true) {
  23766. var pointData = {
  23767. screen_x: combinedData[i].screen_x,
  23768. screen_y: combinedData[i].screen_y - heightOffset,
  23769. x: combinedData[i].x,
  23770. y: combinedData[i].y,
  23771. groupId: combinedData[i].groupId,
  23772. label: combinedData[i].label
  23773. };
  23774. Points.draw([pointData], group, framework, drawData.offset);
  23775. //DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg);
  23776. }
  23777. }
  23778. };
  23779. /**
  23780. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  23781. * @param intersections
  23782. * @param combinedData
  23783. * @private
  23784. */
  23785. Bargraph._getDataIntersections = function (intersections, combinedData) {
  23786. // get intersections
  23787. var coreDistance;
  23788. for (var i = 0; i < combinedData.length; i++) {
  23789. if (i + 1 < combinedData.length) {
  23790. coreDistance = Math.abs(combinedData[i + 1].screen_x - combinedData[i].screen_x);
  23791. }
  23792. if (i > 0) {
  23793. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].screen_x - combinedData[i].screen_x));
  23794. }
  23795. if (coreDistance === 0) {
  23796. if (intersections[combinedData[i].screen_x] === undefined) {
  23797. intersections[combinedData[i].screen_x] = {
  23798. amount: 0,
  23799. resolved: 0,
  23800. accumulatedPositive: 0,
  23801. accumulatedNegative: 0
  23802. };
  23803. }
  23804. intersections[combinedData[i].screen_x].amount += 1;
  23805. }
  23806. }
  23807. };
  23808. /**
  23809. * Get the width and offset for bargraphs based on the coredistance between datapoints
  23810. *
  23811. * @param coreDistance
  23812. * @param group
  23813. * @param minWidth
  23814. * @returns {{width: Number, offset: Number}}
  23815. * @private
  23816. */
  23817. Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) {
  23818. var width, offset;
  23819. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  23820. width = coreDistance < minWidth ? minWidth : coreDistance;
  23821. offset = 0; // recalculate offset with the new width;
  23822. if (group.options.barChart.align === 'left') {
  23823. offset -= 0.5 * coreDistance;
  23824. } else if (group.options.barChart.align === 'right') {
  23825. offset += 0.5 * coreDistance;
  23826. }
  23827. } else {
  23828. // default settings
  23829. width = group.options.barChart.width;
  23830. offset = 0;
  23831. if (group.options.barChart.align === 'left') {
  23832. offset -= 0.5 * group.options.barChart.width;
  23833. } else if (group.options.barChart.align === 'right') {
  23834. offset += 0.5 * group.options.barChart.width;
  23835. }
  23836. }
  23837. return { width: width, offset: offset };
  23838. };
  23839. Bargraph.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) {
  23840. if (combinedData.length > 0) {
  23841. // sort by time and by group
  23842. combinedData.sort(function (a, b) {
  23843. if (a.screen_x === b.screen_x) {
  23844. return a.groupId < b.groupId ? -1 : 1;
  23845. } else {
  23846. return a.screen_x - b.screen_x;
  23847. }
  23848. });
  23849. var intersections = {};
  23850. Bargraph._getDataIntersections(intersections, combinedData);
  23851. groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData);
  23852. groupRanges[groupLabel].yAxisOrientation = orientation;
  23853. groupIds.push(groupLabel);
  23854. }
  23855. };
  23856. Bargraph._getStackedYRange = function (intersections, combinedData) {
  23857. var key;
  23858. var yMin = combinedData[0].screen_y;
  23859. var yMax = combinedData[0].screen_y;
  23860. for (var i = 0; i < combinedData.length; i++) {
  23861. key = combinedData[i].screen_x;
  23862. if (intersections[key] === undefined) {
  23863. yMin = yMin > combinedData[i].screen_y ? combinedData[i].screen_y : yMin;
  23864. yMax = yMax < combinedData[i].screen_y ? combinedData[i].screen_y : yMax;
  23865. } else {
  23866. if (combinedData[i].screen_y < 0) {
  23867. intersections[key].accumulatedNegative += combinedData[i].screen_y;
  23868. } else {
  23869. intersections[key].accumulatedPositive += combinedData[i].screen_y;
  23870. }
  23871. }
  23872. }
  23873. for (var xpos in intersections) {
  23874. if (intersections.hasOwnProperty(xpos)) {
  23875. yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin;
  23876. yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin;
  23877. yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax;
  23878. yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax;
  23879. }
  23880. }
  23881. return { min: yMin, max: yMax };
  23882. };
  23883. module.exports = Bargraph;
  23884. /***/ },
  23885. /* 56 */
  23886. /***/ function(module, exports, __webpack_require__) {
  23887. 'use strict';
  23888. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  23889. var DOMutil = __webpack_require__(8);
  23890. function Points(groupId, options) {}
  23891. /**
  23892. * draw the data points
  23893. *
  23894. * @param {Array} dataset
  23895. * @param {Object} JSONcontainer
  23896. * @param {Object} svg | SVG DOM element
  23897. * @param {GraphGroup} group
  23898. * @param {Number} [offset]
  23899. */
  23900. Points.draw = function (dataset, group, framework, offset) {
  23901. offset = offset || 0;
  23902. var callback = getCallback(framework, group);
  23903. for (var i = 0; i < dataset.length; i++) {
  23904. if (!callback) {
  23905. // draw the point the simple way.
  23906. DOMutil.drawPoint(dataset[i].screen_x + offset, dataset[i].screen_y, getGroupTemplate(group), framework.svgElements, framework.svg, dataset[i].label);
  23907. } else {
  23908. var callbackResult = callback(dataset[i], group); // result might be true, false or an object
  23909. if (callbackResult === true || (typeof callbackResult === 'undefined' ? 'undefined' : _typeof(callbackResult)) === 'object') {
  23910. DOMutil.drawPoint(dataset[i].screen_x + offset, dataset[i].screen_y, getGroupTemplate(group, callbackResult), framework.svgElements, framework.svg, dataset[i].label);
  23911. }
  23912. }
  23913. }
  23914. };
  23915. Points.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
  23916. var fillHeight = iconHeight * 0.5;
  23917. var path, fillPath;
  23918. var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
  23919. outline.setAttributeNS(null, "x", x);
  23920. outline.setAttributeNS(null, "y", y - fillHeight);
  23921. outline.setAttributeNS(null, "width", iconWidth);
  23922. outline.setAttributeNS(null, "height", 2 * fillHeight);
  23923. outline.setAttributeNS(null, "class", "vis-outline");
  23924. //Don't call callback on icon
  23925. DOMutil.drawPoint(x + 0.5 * iconWidth, y, getGroupTemplate(group), framework.svgElements, framework.svg);
  23926. };
  23927. function getGroupTemplate(group, callbackResult) {
  23928. callbackResult = typeof callbackResult === 'undefined' ? {} : callbackResult;
  23929. return {
  23930. style: callbackResult.style || group.options.drawPoints.style,
  23931. styles: callbackResult.styles || group.options.drawPoints.styles,
  23932. size: callbackResult.size || group.options.drawPoints.size,
  23933. className: callbackResult.className || group.className
  23934. };
  23935. }
  23936. function getCallback(framework, group) {
  23937. var callback = undefined;
  23938. // check for the graph2d onRender
  23939. if (framework.options && framework.options.drawPoints && framework.options.drawPoints.onRender && typeof framework.options.drawPoints.onRender == 'function') {
  23940. callback = framework.options.drawPoints.onRender;
  23941. }
  23942. // override it with the group onRender if defined
  23943. if (group.group.options && group.group.options.drawPoints && group.group.options.drawPoints.onRender && typeof group.group.options.drawPoints.onRender == 'function') {
  23944. callback = group.group.options.drawPoints.onRender;
  23945. }
  23946. return callback;
  23947. }
  23948. module.exports = Points;
  23949. /***/ },
  23950. /* 57 */
  23951. /***/ function(module, exports, __webpack_require__) {
  23952. "use strict";
  23953. var DOMutil = __webpack_require__(8);
  23954. function Line(groupId, options) {}
  23955. Line.calcPath = function (dataset, group) {
  23956. if (dataset != null) {
  23957. if (dataset.length > 0) {
  23958. var d = [];
  23959. // construct path from dataset
  23960. if (group.options.interpolation.enabled == true) {
  23961. d = Line._catmullRom(dataset, group);
  23962. } else {
  23963. d = Line._linear(dataset);
  23964. }
  23965. return d;
  23966. }
  23967. }
  23968. };
  23969. Line.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
  23970. var fillHeight = iconHeight * 0.5;
  23971. var path, fillPath;
  23972. var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
  23973. outline.setAttributeNS(null, "x", x);
  23974. outline.setAttributeNS(null, "y", y - fillHeight);
  23975. outline.setAttributeNS(null, "width", iconWidth);
  23976. outline.setAttributeNS(null, "height", 2 * fillHeight);
  23977. outline.setAttributeNS(null, "class", "vis-outline");
  23978. path = DOMutil.getSVGElement("path", framework.svgElements, framework.svg);
  23979. path.setAttributeNS(null, "class", group.className);
  23980. if (group.style !== undefined) {
  23981. path.setAttributeNS(null, "style", group.style);
  23982. }
  23983. path.setAttributeNS(null, "d", "M" + x + "," + y + " L" + (x + iconWidth) + "," + y + "");
  23984. if (group.options.shaded.enabled == true) {
  23985. fillPath = DOMutil.getSVGElement("path", framework.svgElements, framework.svg);
  23986. if (group.options.shaded.orientation == 'top') {
  23987. fillPath.setAttributeNS(null, "d", "M" + x + ", " + (y - fillHeight) + "L" + x + "," + y + " L" + (x + iconWidth) + "," + y + " L" + (x + iconWidth) + "," + (y - fillHeight));
  23988. } else {
  23989. fillPath.setAttributeNS(null, "d", "M" + x + "," + y + " " + "L" + x + "," + (y + fillHeight) + " " + "L" + (x + iconWidth) + "," + (y + fillHeight) + "L" + (x + iconWidth) + "," + y);
  23990. }
  23991. fillPath.setAttributeNS(null, "class", group.className + " vis-icon-fill");
  23992. if (group.options.shaded.style !== undefined && group.options.shaded.style !== "") {
  23993. fillPath.setAttributeNS(null, "style", group.options.shaded.style);
  23994. }
  23995. }
  23996. if (group.options.drawPoints.enabled == true) {
  23997. var groupTemplate = {
  23998. style: group.options.drawPoints.style,
  23999. styles: group.options.drawPoints.styles,
  24000. size: group.options.drawPoints.size,
  24001. className: group.className
  24002. };
  24003. DOMutil.drawPoint(x + 0.5 * iconWidth, y, groupTemplate, framework.svgElements, framework.svg);
  24004. }
  24005. };
  24006. Line.drawShading = function (pathArray, group, subPathArray, framework) {
  24007. // append shading to the path
  24008. if (group.options.shaded.enabled == true) {
  24009. var svgHeight = Number(framework.svg.style.height.replace('px', ''));
  24010. var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  24011. var type = "L";
  24012. if (group.options.interpolation.enabled == true) {
  24013. type = "C";
  24014. }
  24015. var dFill;
  24016. var zero = 0;
  24017. if (group.options.shaded.orientation == 'top') {
  24018. zero = 0;
  24019. } else if (group.options.shaded.orientation == 'bottom') {
  24020. zero = svgHeight;
  24021. } else {
  24022. zero = Math.min(Math.max(0, group.zeroPosition), svgHeight);
  24023. }
  24024. if (group.options.shaded.orientation == 'group' && subPathArray != null && subPathArray != undefined) {
  24025. dFill = 'M' + pathArray[0][0] + "," + pathArray[0][1] + " " + this.serializePath(pathArray, type, false) + ' L' + subPathArray[subPathArray.length - 1][0] + "," + subPathArray[subPathArray.length - 1][1] + " " + this.serializePath(subPathArray, type, true) + subPathArray[0][0] + "," + subPathArray[0][1] + " Z";
  24026. } else {
  24027. dFill = 'M' + pathArray[0][0] + "," + pathArray[0][1] + " " + this.serializePath(pathArray, type, false) + ' V' + zero + ' H' + pathArray[0][0] + " Z";
  24028. }
  24029. fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill');
  24030. if (group.options.shaded.style !== undefined) {
  24031. fillPath.setAttributeNS(null, 'style', group.options.shaded.style);
  24032. }
  24033. fillPath.setAttributeNS(null, 'd', dFill);
  24034. }
  24035. };
  24036. /**
  24037. * draw a line graph
  24038. *
  24039. * @param dataset
  24040. * @param group
  24041. */
  24042. Line.draw = function (pathArray, group, framework) {
  24043. if (pathArray != null && pathArray != undefined) {
  24044. var path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  24045. path.setAttributeNS(null, "class", group.className);
  24046. if (group.style !== undefined) {
  24047. path.setAttributeNS(null, "style", group.style);
  24048. }
  24049. var type = "L";
  24050. if (group.options.interpolation.enabled == true) {
  24051. type = "C";
  24052. }
  24053. // copy properties to path for drawing.
  24054. path.setAttributeNS(null, 'd', 'M' + pathArray[0][0] + "," + pathArray[0][1] + " " + this.serializePath(pathArray, type, false));
  24055. }
  24056. };
  24057. Line.serializePath = function (pathArray, type, inverse) {
  24058. if (pathArray.length < 2) {
  24059. //Too little data to create a path.
  24060. return "";
  24061. }
  24062. var d = type;
  24063. if (inverse) {
  24064. for (var i = pathArray.length - 2; i > 0; i--) {
  24065. d += pathArray[i][0] + "," + pathArray[i][1] + " ";
  24066. }
  24067. } else {
  24068. for (var i = 1; i < pathArray.length; i++) {
  24069. d += pathArray[i][0] + "," + pathArray[i][1] + " ";
  24070. }
  24071. }
  24072. return d;
  24073. };
  24074. /**
  24075. * This uses an uniform parametrization of the interpolation algorithm:
  24076. * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
  24077. * @param data
  24078. * @returns {string}
  24079. * @private
  24080. */
  24081. Line._catmullRomUniform = function (data) {
  24082. // catmull rom
  24083. var p0, p1, p2, p3, bp1, bp2;
  24084. var d = [];
  24085. d.push([Math.round(data[0].screen_x), Math.round(data[0].screen_y)]);
  24086. var normalization = 1 / 6;
  24087. var length = data.length;
  24088. for (var i = 0; i < length - 1; i++) {
  24089. p0 = i == 0 ? data[0] : data[i - 1];
  24090. p1 = data[i];
  24091. p2 = data[i + 1];
  24092. p3 = i + 2 < length ? data[i + 2] : p2;
  24093. // Catmull-Rom to Cubic Bezier conversion matrix
  24094. // 0 1 0 0
  24095. // -1/6 1 1/6 0
  24096. // 0 1/6 1 -1/6
  24097. // 0 0 1 0
  24098. // bp0 = { x: p1.x, y: p1.y };
  24099. bp1 = {
  24100. screen_x: (-p0.screen_x + 6 * p1.screen_x + p2.screen_x) * normalization,
  24101. screen_y: (-p0.screen_y + 6 * p1.screen_y + p2.screen_y) * normalization
  24102. };
  24103. bp2 = {
  24104. screen_x: (p1.screen_x + 6 * p2.screen_x - p3.screen_x) * normalization,
  24105. screen_y: (p1.screen_y + 6 * p2.screen_y - p3.screen_y) * normalization
  24106. };
  24107. // bp0 = { x: p2.x, y: p2.y };
  24108. d.push([bp1.screen_x, bp1.screen_y]);
  24109. d.push([bp2.screen_x, bp2.screen_y]);
  24110. d.push([p2.screen_x, p2.screen_y]);
  24111. }
  24112. return d;
  24113. };
  24114. /**
  24115. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  24116. * By default, the centripetal parameterization is used because this gives the nicest results.
  24117. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  24118. *
  24119. * One optimization can be used to reuse distances since this is a sliding window approach.
  24120. * @param data
  24121. * @param group
  24122. * @returns {string}
  24123. * @private
  24124. */
  24125. Line._catmullRom = function (data, group) {
  24126. var alpha = group.options.interpolation.alpha;
  24127. if (alpha == 0 || alpha === undefined) {
  24128. return this._catmullRomUniform(data);
  24129. } else {
  24130. var p0, p1, p2, p3, bp1, bp2, d1, d2, d3, A, B, N, M;
  24131. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  24132. var d = [];
  24133. d.push([Math.round(data[0].screen_x), Math.round(data[0].screen_y)]);
  24134. var length = data.length;
  24135. for (var i = 0; i < length - 1; i++) {
  24136. p0 = i == 0 ? data[0] : data[i - 1];
  24137. p1 = data[i];
  24138. p2 = data[i + 1];
  24139. p3 = i + 2 < length ? data[i + 2] : p2;
  24140. d1 = Math.sqrt(Math.pow(p0.screen_x - p1.screen_x, 2) + Math.pow(p0.screen_y - p1.screen_y, 2));
  24141. d2 = Math.sqrt(Math.pow(p1.screen_x - p2.screen_x, 2) + Math.pow(p1.screen_y - p2.screen_y, 2));
  24142. d3 = Math.sqrt(Math.pow(p2.screen_x - p3.screen_x, 2) + Math.pow(p2.screen_y - p3.screen_y, 2));
  24143. // Catmull-Rom to Cubic Bezier conversion matrix
  24144. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  24145. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  24146. // [ 0 1 0 0 ]
  24147. // [ -d2^2a /N A/N d1^2a /N 0 ]
  24148. // [ 0 d3^2a /M B/M -d2^2a /M ]
  24149. // [ 0 0 1 0 ]
  24150. d3powA = Math.pow(d3, alpha);
  24151. d3pow2A = Math.pow(d3, 2 * alpha);
  24152. d2powA = Math.pow(d2, alpha);
  24153. d2pow2A = Math.pow(d2, 2 * alpha);
  24154. d1powA = Math.pow(d1, alpha);
  24155. d1pow2A = Math.pow(d1, 2 * alpha);
  24156. A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A;
  24157. B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A;
  24158. N = 3 * d1powA * (d1powA + d2powA);
  24159. if (N > 0) {
  24160. N = 1 / N;
  24161. }
  24162. M = 3 * d3powA * (d3powA + d2powA);
  24163. if (M > 0) {
  24164. M = 1 / M;
  24165. }
  24166. bp1 = {
  24167. screen_x: (-d2pow2A * p0.screen_x + A * p1.screen_x + d1pow2A * p2.screen_x) * N,
  24168. screen_y: (-d2pow2A * p0.screen_y + A * p1.screen_y + d1pow2A * p2.screen_y) * N
  24169. };
  24170. bp2 = {
  24171. screen_x: (d3pow2A * p1.screen_x + B * p2.screen_x - d2pow2A * p3.screen_x) * M,
  24172. screen_y: (d3pow2A * p1.screen_y + B * p2.screen_y - d2pow2A * p3.screen_y) * M
  24173. };
  24174. if (bp1.screen_x == 0 && bp1.screen_y == 0) {
  24175. bp1 = p1;
  24176. }
  24177. if (bp2.screen_x == 0 && bp2.screen_y == 0) {
  24178. bp2 = p2;
  24179. }
  24180. d.push([bp1.screen_x, bp1.screen_y]);
  24181. d.push([bp2.screen_x, bp2.screen_y]);
  24182. d.push([p2.screen_x, p2.screen_y]);
  24183. }
  24184. return d;
  24185. }
  24186. };
  24187. /**
  24188. * this generates the SVG path for a linear drawing between datapoints.
  24189. * @param data
  24190. * @returns {string}
  24191. * @private
  24192. */
  24193. Line._linear = function (data) {
  24194. // linear
  24195. var d = [];
  24196. for (var i = 0; i < data.length; i++) {
  24197. d.push([data[i].screen_x, data[i].screen_y]);
  24198. }
  24199. return d;
  24200. };
  24201. module.exports = Line;
  24202. /***/ },
  24203. /* 58 */
  24204. /***/ function(module, exports, __webpack_require__) {
  24205. 'use strict';
  24206. var util = __webpack_require__(1);
  24207. var DOMutil = __webpack_require__(8);
  24208. var Component = __webpack_require__(31);
  24209. /**
  24210. * Legend for Graph2d
  24211. */
  24212. function Legend(body, options, side, linegraphOptions) {
  24213. this.body = body;
  24214. this.defaultOptions = {
  24215. enabled: false,
  24216. icons: true,
  24217. iconSize: 20,
  24218. iconSpacing: 6,
  24219. left: {
  24220. visible: true,
  24221. position: 'top-left' // top/bottom - left,center,right
  24222. },
  24223. right: {
  24224. visible: true,
  24225. position: 'top-right' // top/bottom - left,center,right
  24226. }
  24227. };
  24228. this.side = side;
  24229. this.options = util.extend({}, this.defaultOptions);
  24230. this.linegraphOptions = linegraphOptions;
  24231. this.svgElements = {};
  24232. this.dom = {};
  24233. this.groups = {};
  24234. this.amountOfGroups = 0;
  24235. this._create();
  24236. this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups };
  24237. this.setOptions(options);
  24238. }
  24239. Legend.prototype = new Component();
  24240. Legend.prototype.clear = function () {
  24241. this.groups = {};
  24242. this.amountOfGroups = 0;
  24243. };
  24244. Legend.prototype.addGroup = function (label, graphOptions) {
  24245. // Include a group only if the group option 'excludeFromLegend: false' is not set.
  24246. if (graphOptions.options.excludeFromLegend != true) {
  24247. if (!this.groups.hasOwnProperty(label)) {
  24248. this.groups[label] = graphOptions;
  24249. }
  24250. this.amountOfGroups += 1;
  24251. }
  24252. };
  24253. Legend.prototype.updateGroup = function (label, graphOptions) {
  24254. this.groups[label] = graphOptions;
  24255. };
  24256. Legend.prototype.removeGroup = function (label) {
  24257. if (this.groups.hasOwnProperty(label)) {
  24258. delete this.groups[label];
  24259. this.amountOfGroups -= 1;
  24260. }
  24261. };
  24262. Legend.prototype._create = function () {
  24263. this.dom.frame = document.createElement('div');
  24264. this.dom.frame.className = 'vis-legend';
  24265. this.dom.frame.style.position = "absolute";
  24266. this.dom.frame.style.top = "10px";
  24267. this.dom.frame.style.display = "block";
  24268. this.dom.textArea = document.createElement('div');
  24269. this.dom.textArea.className = 'vis-legend-text';
  24270. this.dom.textArea.style.position = "relative";
  24271. this.dom.textArea.style.top = "0px";
  24272. this.svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
  24273. this.svg.style.position = 'absolute';
  24274. this.svg.style.top = 0 + 'px';
  24275. this.svg.style.width = this.options.iconSize + 5 + 'px';
  24276. this.svg.style.height = '100%';
  24277. this.dom.frame.appendChild(this.svg);
  24278. this.dom.frame.appendChild(this.dom.textArea);
  24279. };
  24280. /**
  24281. * Hide the component from the DOM
  24282. */
  24283. Legend.prototype.hide = function () {
  24284. // remove the frame containing the items
  24285. if (this.dom.frame.parentNode) {
  24286. this.dom.frame.parentNode.removeChild(this.dom.frame);
  24287. }
  24288. };
  24289. /**
  24290. * Show the component in the DOM (when not already visible).
  24291. * @return {Boolean} changed
  24292. */
  24293. Legend.prototype.show = function () {
  24294. // show frame containing the items
  24295. if (!this.dom.frame.parentNode) {
  24296. this.body.dom.center.appendChild(this.dom.frame);
  24297. }
  24298. };
  24299. Legend.prototype.setOptions = function (options) {
  24300. var fields = ['enabled', 'orientation', 'icons', 'left', 'right'];
  24301. util.selectiveDeepExtend(fields, this.options, options);
  24302. };
  24303. Legend.prototype.redraw = function () {
  24304. var activeGroups = 0;
  24305. var groupArray = Object.keys(this.groups);
  24306. groupArray.sort(function (a, b) {
  24307. return a < b ? -1 : 1;
  24308. });
  24309. for (var i = 0; i < groupArray.length; i++) {
  24310. var groupId = groupArray[i];
  24311. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  24312. activeGroups++;
  24313. }
  24314. }
  24315. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  24316. this.hide();
  24317. } else {
  24318. this.show();
  24319. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  24320. this.dom.frame.style.left = '4px';
  24321. this.dom.frame.style.textAlign = "left";
  24322. this.dom.textArea.style.textAlign = "left";
  24323. this.dom.textArea.style.left = this.options.iconSize + 15 + 'px';
  24324. this.dom.textArea.style.right = '';
  24325. this.svg.style.left = 0 + 'px';
  24326. this.svg.style.right = '';
  24327. } else {
  24328. this.dom.frame.style.right = '4px';
  24329. this.dom.frame.style.textAlign = "right";
  24330. this.dom.textArea.style.textAlign = "right";
  24331. this.dom.textArea.style.right = this.options.iconSize + 15 + 'px';
  24332. this.dom.textArea.style.left = '';
  24333. this.svg.style.right = 0 + 'px';
  24334. this.svg.style.left = '';
  24335. }
  24336. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  24337. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px", "")) + 'px';
  24338. this.dom.frame.style.bottom = '';
  24339. } else {
  24340. var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height;
  24341. this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace("px", "")) + 'px';
  24342. this.dom.frame.style.top = '';
  24343. }
  24344. if (this.options.icons == false) {
  24345. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  24346. this.dom.textArea.style.right = '';
  24347. this.dom.textArea.style.left = '';
  24348. this.svg.style.width = '0px';
  24349. } else {
  24350. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px';
  24351. this.drawLegendIcons();
  24352. }
  24353. var content = '';
  24354. for (var i = 0; i < groupArray.length; i++) {
  24355. var groupId = groupArray[i];
  24356. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  24357. content += this.groups[groupId].content + '<br />';
  24358. }
  24359. }
  24360. this.dom.textArea.innerHTML = content;
  24361. this.dom.textArea.style.lineHeight = 0.75 * this.options.iconSize + this.options.iconSpacing + 'px';
  24362. }
  24363. };
  24364. Legend.prototype.drawLegendIcons = function () {
  24365. if (this.dom.frame.parentNode) {
  24366. var groupArray = Object.keys(this.groups);
  24367. groupArray.sort(function (a, b) {
  24368. return a < b ? -1 : 1;
  24369. });
  24370. // this resets the elements so the order is maintained
  24371. DOMutil.resetElements(this.svgElements);
  24372. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  24373. var iconOffset = Number(padding.replace('px', ''));
  24374. var x = iconOffset;
  24375. var iconWidth = this.options.iconSize;
  24376. var iconHeight = 0.75 * this.options.iconSize;
  24377. var y = iconOffset + 0.5 * iconHeight + 3;
  24378. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  24379. for (var i = 0; i < groupArray.length; i++) {
  24380. var groupId = groupArray[i];
  24381. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  24382. this.groups[groupId].getLegend(iconWidth, iconHeight, this.framework, x, y);
  24383. y += iconHeight + this.options.iconSpacing;
  24384. }
  24385. }
  24386. }
  24387. };
  24388. module.exports = Legend;
  24389. /***/ },
  24390. /* 59 */
  24391. /***/ function(module, exports) {
  24392. 'use strict';
  24393. Object.defineProperty(exports, "__esModule", {
  24394. value: true
  24395. });
  24396. /**
  24397. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  24398. * of the allowed values.
  24399. *
  24400. * __any__ means that the name of the property does not matter.
  24401. * __type__ is a required field for all objects and contains the allowed types of all objects
  24402. */
  24403. var string = 'string';
  24404. var boolean = 'boolean';
  24405. var number = 'number';
  24406. var array = 'array';
  24407. var date = 'date';
  24408. var object = 'object'; // should only be in a __type__ property
  24409. var dom = 'dom';
  24410. var moment = 'moment';
  24411. var any = 'any';
  24412. var allOptions = {
  24413. configure: {
  24414. enabled: { boolean: boolean },
  24415. filter: { boolean: boolean, 'function': 'function' },
  24416. container: { dom: dom },
  24417. __type__: { object: object, boolean: boolean, 'function': 'function' }
  24418. },
  24419. //globals :
  24420. yAxisOrientation: { string: ['left', 'right'] },
  24421. defaultGroup: { string: string },
  24422. sort: { boolean: boolean },
  24423. sampling: { boolean: boolean },
  24424. stack: { boolean: boolean },
  24425. graphHeight: { string: string, number: number },
  24426. shaded: {
  24427. enabled: { boolean: boolean },
  24428. orientation: { string: ['bottom', 'top', 'zero', 'group'] }, // top, bottom, zero, group
  24429. groupId: { object: object },
  24430. __type__: { boolean: boolean, object: object }
  24431. },
  24432. style: { string: ['line', 'bar', 'points'] }, // line, bar
  24433. barChart: {
  24434. width: { number: number },
  24435. minWidth: { number: number },
  24436. sideBySide: { boolean: boolean },
  24437. align: { string: ['left', 'center', 'right'] },
  24438. __type__: { object: object }
  24439. },
  24440. interpolation: {
  24441. enabled: { boolean: boolean },
  24442. parametrization: { string: ['centripetal', 'chordal', 'uniform'] }, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  24443. alpha: { number: number },
  24444. __type__: { object: object, boolean: boolean }
  24445. },
  24446. drawPoints: {
  24447. enabled: { boolean: boolean },
  24448. onRender: { 'function': 'function' },
  24449. size: { number: number },
  24450. style: { string: ['square', 'circle'] }, // square, circle
  24451. __type__: { object: object, boolean: boolean, 'function': 'function' }
  24452. },
  24453. dataAxis: {
  24454. showMinorLabels: { boolean: boolean },
  24455. showMajorLabels: { boolean: boolean },
  24456. icons: { boolean: boolean },
  24457. width: { string: string, number: number },
  24458. visible: { boolean: boolean },
  24459. alignZeros: { boolean: boolean },
  24460. left: {
  24461. range: { min: { number: number }, max: { number: number }, __type__: { object: object } },
  24462. format: { 'function': 'function' },
  24463. title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } },
  24464. __type__: { object: object }
  24465. },
  24466. right: {
  24467. range: { min: { number: number }, max: { number: number }, __type__: { object: object } },
  24468. format: { 'function': 'function' },
  24469. title: { text: { string: string, number: number }, style: { string: string }, __type__: { object: object } },
  24470. __type__: { object: object }
  24471. },
  24472. __type__: { object: object }
  24473. },
  24474. legend: {
  24475. enabled: { boolean: boolean },
  24476. icons: { boolean: boolean },
  24477. left: {
  24478. visible: { boolean: boolean },
  24479. position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] },
  24480. __type__: { object: object }
  24481. },
  24482. right: {
  24483. visible: { boolean: boolean },
  24484. position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] },
  24485. __type__: { object: object }
  24486. },
  24487. __type__: { object: object, boolean: boolean }
  24488. },
  24489. groups: {
  24490. visibility: { any: any },
  24491. __type__: { object: object }
  24492. },
  24493. autoResize: { boolean: boolean },
  24494. throttleRedraw: { number: number },
  24495. clickToUse: { boolean: boolean },
  24496. end: { number: number, date: date, string: string, moment: moment },
  24497. format: {
  24498. minorLabels: {
  24499. millisecond: { string: string, 'undefined': 'undefined' },
  24500. second: { string: string, 'undefined': 'undefined' },
  24501. minute: { string: string, 'undefined': 'undefined' },
  24502. hour: { string: string, 'undefined': 'undefined' },
  24503. weekday: { string: string, 'undefined': 'undefined' },
  24504. day: { string: string, 'undefined': 'undefined' },
  24505. month: { string: string, 'undefined': 'undefined' },
  24506. year: { string: string, 'undefined': 'undefined' },
  24507. __type__: { object: object }
  24508. },
  24509. majorLabels: {
  24510. millisecond: { string: string, 'undefined': 'undefined' },
  24511. second: { string: string, 'undefined': 'undefined' },
  24512. minute: { string: string, 'undefined': 'undefined' },
  24513. hour: { string: string, 'undefined': 'undefined' },
  24514. weekday: { string: string, 'undefined': 'undefined' },
  24515. day: { string: string, 'undefined': 'undefined' },
  24516. month: { string: string, 'undefined': 'undefined' },
  24517. year: { string: string, 'undefined': 'undefined' },
  24518. __type__: { object: object }
  24519. },
  24520. __type__: { object: object }
  24521. },
  24522. moment: { 'function': 'function' },
  24523. height: { string: string, number: number },
  24524. hiddenDates: {
  24525. start: { date: date, number: number, string: string, moment: moment },
  24526. end: { date: date, number: number, string: string, moment: moment },
  24527. repeat: { string: string },
  24528. __type__: { object: object, array: array }
  24529. },
  24530. locale: { string: string },
  24531. locales: {
  24532. __any__: { any: any },
  24533. __type__: { object: object }
  24534. },
  24535. max: { date: date, number: number, string: string, moment: moment },
  24536. maxHeight: { number: number, string: string },
  24537. maxMinorChars: { number: number },
  24538. min: { date: date, number: number, string: string, moment: moment },
  24539. minHeight: { number: number, string: string },
  24540. moveable: { boolean: boolean },
  24541. multiselect: { boolean: boolean },
  24542. orientation: { string: string },
  24543. showCurrentTime: { boolean: boolean },
  24544. showMajorLabels: { boolean: boolean },
  24545. showMinorLabels: { boolean: boolean },
  24546. start: { date: date, number: number, string: string, moment: moment },
  24547. timeAxis: {
  24548. scale: { string: string, 'undefined': 'undefined' },
  24549. step: { number: number, 'undefined': 'undefined' },
  24550. __type__: { object: object }
  24551. },
  24552. width: { string: string, number: number },
  24553. zoomable: { boolean: boolean },
  24554. zoomKey: { string: ['ctrlKey', 'altKey', 'metaKey', ''] },
  24555. zoomMax: { number: number },
  24556. zoomMin: { number: number },
  24557. zIndex: { number: number },
  24558. __type__: { object: object }
  24559. };
  24560. var configureOptions = {
  24561. global: {
  24562. //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly
  24563. sort: true,
  24564. sampling: true,
  24565. stack: false,
  24566. shaded: {
  24567. enabled: false,
  24568. orientation: ['zero', 'top', 'bottom', 'group'] // zero, top, bottom
  24569. },
  24570. style: ['line', 'bar', 'points'], // line, bar
  24571. barChart: {
  24572. width: [50, 5, 100, 5],
  24573. minWidth: [50, 5, 100, 5],
  24574. sideBySide: false,
  24575. align: ['left', 'center', 'right'] // left, center, right
  24576. },
  24577. interpolation: {
  24578. enabled: true,
  24579. parametrization: ['centripetal', 'chordal', 'uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  24580. },
  24581. drawPoints: {
  24582. enabled: true,
  24583. size: [6, 2, 30, 1],
  24584. style: ['square', 'circle'] // square, circle
  24585. },
  24586. dataAxis: {
  24587. showMinorLabels: true,
  24588. showMajorLabels: true,
  24589. icons: false,
  24590. width: [40, 0, 200, 1],
  24591. visible: true,
  24592. alignZeros: true,
  24593. left: {
  24594. //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined},
  24595. //format: function (value) {return value;},
  24596. title: { text: '', style: '' }
  24597. },
  24598. right: {
  24599. //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined},
  24600. //format: function (value) {return value;},
  24601. title: { text: '', style: '' }
  24602. }
  24603. },
  24604. legend: {
  24605. enabled: false,
  24606. icons: true,
  24607. left: {
  24608. visible: true,
  24609. position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right
  24610. },
  24611. right: {
  24612. visible: true,
  24613. position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right
  24614. }
  24615. },
  24616. autoResize: true,
  24617. throttleRedraw: [10, 0, 1000, 10],
  24618. clickToUse: false,
  24619. end: '',
  24620. format: {
  24621. minorLabels: {
  24622. millisecond: 'SSS',
  24623. second: 's',
  24624. minute: 'HH:mm',
  24625. hour: 'HH:mm',
  24626. weekday: 'ddd D',
  24627. day: 'D',
  24628. month: 'MMM',
  24629. year: 'YYYY'
  24630. },
  24631. majorLabels: {
  24632. millisecond: 'HH:mm:ss',
  24633. second: 'D MMMM HH:mm',
  24634. minute: 'ddd D MMMM',
  24635. hour: 'ddd D MMMM',
  24636. weekday: 'MMMM YYYY',
  24637. day: 'MMMM YYYY',
  24638. month: 'YYYY',
  24639. year: ''
  24640. }
  24641. },
  24642. height: '',
  24643. locale: '',
  24644. max: '',
  24645. maxHeight: '',
  24646. maxMinorChars: [7, 0, 20, 1],
  24647. min: '',
  24648. minHeight: '',
  24649. moveable: true,
  24650. orientation: ['both', 'bottom', 'top'],
  24651. showCurrentTime: false,
  24652. showMajorLabels: true,
  24653. showMinorLabels: true,
  24654. start: '',
  24655. width: '100%',
  24656. zoomable: true,
  24657. zoomKey: ['ctrlKey', 'altKey', 'metaKey', ''],
  24658. zoomMax: [315360000000000, 10, 315360000000000, 1],
  24659. zoomMin: [10, 10, 315360000000000, 1],
  24660. zIndex: 0
  24661. }
  24662. };
  24663. exports.allOptions = allOptions;
  24664. exports.configureOptions = configureOptions;
  24665. /***/ },
  24666. /* 60 */
  24667. /***/ function(module, exports, __webpack_require__) {
  24668. 'use strict';
  24669. // utils
  24670. exports.util = __webpack_require__(1);
  24671. exports.DOMutil = __webpack_require__(8);
  24672. // data
  24673. exports.DataSet = __webpack_require__(9);
  24674. exports.DataView = __webpack_require__(11);
  24675. exports.Queue = __webpack_require__(10);
  24676. // Network
  24677. exports.Network = __webpack_require__(61);
  24678. exports.network = {
  24679. Images: __webpack_require__(62),
  24680. dotparser: __webpack_require__(118),
  24681. gephiParser: __webpack_require__(119),
  24682. allOptions: __webpack_require__(114)
  24683. };
  24684. exports.network.convertDot = function (input) {
  24685. return exports.network.dotparser.DOTToGraph(input);
  24686. };
  24687. exports.network.convertGephi = function (input, options) {
  24688. return exports.network.gephiParser.parseGephi(input, options);
  24689. };
  24690. // bundled external libraries
  24691. exports.moment = __webpack_require__(2);
  24692. exports.Hammer = __webpack_require__(20);
  24693. exports.keycharm = __webpack_require__(23);
  24694. /***/ },
  24695. /* 61 */
  24696. /***/ function(module, exports, __webpack_require__) {
  24697. 'use strict';
  24698. var _Images = __webpack_require__(62);
  24699. var _Images2 = _interopRequireDefault(_Images);
  24700. var _Groups = __webpack_require__(63);
  24701. var _Groups2 = _interopRequireDefault(_Groups);
  24702. var _NodesHandler = __webpack_require__(64);
  24703. var _NodesHandler2 = _interopRequireDefault(_NodesHandler);
  24704. var _EdgesHandler = __webpack_require__(84);
  24705. var _EdgesHandler2 = _interopRequireDefault(_EdgesHandler);
  24706. var _PhysicsEngine = __webpack_require__(93);
  24707. var _PhysicsEngine2 = _interopRequireDefault(_PhysicsEngine);
  24708. var _Clustering = __webpack_require__(102);
  24709. var _Clustering2 = _interopRequireDefault(_Clustering);
  24710. var _CanvasRenderer = __webpack_require__(105);
  24711. var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer);
  24712. var _Canvas = __webpack_require__(106);
  24713. var _Canvas2 = _interopRequireDefault(_Canvas);
  24714. var _View = __webpack_require__(107);
  24715. var _View2 = _interopRequireDefault(_View);
  24716. var _InteractionHandler = __webpack_require__(108);
  24717. var _InteractionHandler2 = _interopRequireDefault(_InteractionHandler);
  24718. var _SelectionHandler = __webpack_require__(111);
  24719. var _SelectionHandler2 = _interopRequireDefault(_SelectionHandler);
  24720. var _LayoutEngine = __webpack_require__(112);
  24721. var _LayoutEngine2 = _interopRequireDefault(_LayoutEngine);
  24722. var _ManipulationSystem = __webpack_require__(113);
  24723. var _ManipulationSystem2 = _interopRequireDefault(_ManipulationSystem);
  24724. var _Configurator = __webpack_require__(26);
  24725. var _Configurator2 = _interopRequireDefault(_Configurator);
  24726. var _Validator = __webpack_require__(29);
  24727. var _Validator2 = _interopRequireDefault(_Validator);
  24728. var _options = __webpack_require__(114);
  24729. var _KamadaKawai = __webpack_require__(115);
  24730. var _KamadaKawai2 = _interopRequireDefault(_KamadaKawai);
  24731. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24732. // Load custom shapes into CanvasRenderingContext2D
  24733. __webpack_require__(117);
  24734. var Emitter = __webpack_require__(13);
  24735. var util = __webpack_require__(1);
  24736. var DataSet = __webpack_require__(9);
  24737. var DataView = __webpack_require__(11);
  24738. var dotparser = __webpack_require__(118);
  24739. var gephiParser = __webpack_require__(119);
  24740. var Activator = __webpack_require__(45);
  24741. var locales = __webpack_require__(120);
  24742. /**
  24743. * @constructor Network
  24744. * Create a network visualization, displaying nodes and edges.
  24745. *
  24746. * @param {Element} container The DOM element in which the Network will
  24747. * be created. Normally a div element.
  24748. * @param {Object} data An object containing parameters
  24749. * {Array} nodes
  24750. * {Array} edges
  24751. * @param {Object} options Options
  24752. */
  24753. function Network(container, data, options) {
  24754. var _this = this;
  24755. if (!(this instanceof Network)) {
  24756. throw new SyntaxError('Constructor must be called with the new operator');
  24757. }
  24758. // set constant values
  24759. this.options = {};
  24760. this.defaultOptions = {
  24761. locale: 'en',
  24762. locales: locales,
  24763. clickToUse: false
  24764. };
  24765. util.extend(this.options, this.defaultOptions);
  24766. // containers for nodes and edges
  24767. this.body = {
  24768. container: container,
  24769. nodes: {},
  24770. nodeIndices: [],
  24771. edges: {},
  24772. edgeIndices: [],
  24773. emitter: {
  24774. on: this.on.bind(this),
  24775. off: this.off.bind(this),
  24776. emit: this.emit.bind(this),
  24777. once: this.once.bind(this)
  24778. },
  24779. eventListeners: {
  24780. onTap: function onTap() {},
  24781. onTouch: function onTouch() {},
  24782. onDoubleTap: function onDoubleTap() {},
  24783. onHold: function onHold() {},
  24784. onDragStart: function onDragStart() {},
  24785. onDrag: function onDrag() {},
  24786. onDragEnd: function onDragEnd() {},
  24787. onMouseWheel: function onMouseWheel() {},
  24788. onPinch: function onPinch() {},
  24789. onMouseMove: function onMouseMove() {},
  24790. onRelease: function onRelease() {},
  24791. onContext: function onContext() {}
  24792. },
  24793. data: {
  24794. nodes: null, // A DataSet or DataView
  24795. edges: null // A DataSet or DataView
  24796. },
  24797. functions: {
  24798. createNode: function createNode() {},
  24799. createEdge: function createEdge() {},
  24800. getPointer: function getPointer() {}
  24801. },
  24802. modules: {},
  24803. view: {
  24804. scale: 1,
  24805. translation: { x: 0, y: 0 }
  24806. }
  24807. };
  24808. // bind the event listeners
  24809. this.bindEventListeners();
  24810. // setting up all modules
  24811. this.images = new _Images2.default(function () {
  24812. return _this.body.emitter.emit("_requestRedraw");
  24813. }); // object with images
  24814. this.groups = new _Groups2.default(); // object with groups
  24815. this.canvas = new _Canvas2.default(this.body); // DOM handler
  24816. this.selectionHandler = new _SelectionHandler2.default(this.body, this.canvas); // Selection handler
  24817. this.interactionHandler = new _InteractionHandler2.default(this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key
  24818. this.view = new _View2.default(this.body, this.canvas); // camera handler, does animations and zooms
  24819. this.renderer = new _CanvasRenderer2.default(this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into
  24820. this.physics = new _PhysicsEngine2.default(this.body); // physics engine, does all the simulations
  24821. this.layoutEngine = new _LayoutEngine2.default(this.body); // layout engine for inital layout and hierarchical layout
  24822. this.clustering = new _Clustering2.default(this.body); // clustering api
  24823. this.manipulation = new _ManipulationSystem2.default(this.body, this.canvas, this.selectionHandler); // data manipulation system
  24824. this.nodesHandler = new _NodesHandler2.default(this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options
  24825. this.edgesHandler = new _EdgesHandler2.default(this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options
  24826. this.body.modules["kamadaKawai"] = new _KamadaKawai2.default(this.body, 150, 0.05); // Layouting algorithm.
  24827. this.body.modules["clustering"] = this.clustering;
  24828. // create the DOM elements
  24829. this.canvas._create();
  24830. // apply options
  24831. this.setOptions(options);
  24832. // load data (the disable start variable will be the same as the enabled clustering)
  24833. this.setData(data);
  24834. }
  24835. // Extend Network with an Emitter mixin
  24836. Emitter(Network.prototype);
  24837. /**
  24838. * Set options
  24839. * @param {Object} options
  24840. */
  24841. Network.prototype.setOptions = function (options) {
  24842. var _this2 = this;
  24843. if (options !== undefined) {
  24844. var errorFound = _Validator2.default.validate(options, _options.allOptions);
  24845. if (errorFound === true) {
  24846. console.log('%cErrors have been found in the supplied options object.', _Validator.printStyle);
  24847. }
  24848. // copy the global fields over
  24849. var fields = ['locale', 'locales', 'clickToUse'];
  24850. util.selectiveDeepExtend(fields, this.options, options);
  24851. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  24852. options = this.layoutEngine.setOptions(options.layout, options);
  24853. this.canvas.setOptions(options); // options for canvas are in globals
  24854. // pass the options to the modules
  24855. this.groups.setOptions(options.groups);
  24856. this.nodesHandler.setOptions(options.nodes);
  24857. this.edgesHandler.setOptions(options.edges);
  24858. this.physics.setOptions(options.physics);
  24859. this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals
  24860. this.interactionHandler.setOptions(options.interaction);
  24861. this.renderer.setOptions(options.interaction); // options for rendering are in interaction
  24862. this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction
  24863. // reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
  24864. if (options.groups !== undefined) {
  24865. this.body.emitter.emit("refreshNodes");
  24866. }
  24867. // these two do not have options at the moment, here for completeness
  24868. //this.view.setOptions(options.view);
  24869. //this.clustering.setOptions(options.clustering);
  24870. if ('configure' in options) {
  24871. if (!this.configurator) {
  24872. this.configurator = new _Configurator2.default(this, this.body.container, _options.configureOptions, this.canvas.pixelRatio);
  24873. }
  24874. this.configurator.setOptions(options.configure);
  24875. }
  24876. // if the configuration system is enabled, copy all options and put them into the config system
  24877. if (this.configurator && this.configurator.options.enabled === true) {
  24878. var networkOptions = { nodes: {}, edges: {}, layout: {}, interaction: {}, manipulation: {}, physics: {}, global: {} };
  24879. util.deepExtend(networkOptions.nodes, this.nodesHandler.options);
  24880. util.deepExtend(networkOptions.edges, this.edgesHandler.options);
  24881. util.deepExtend(networkOptions.layout, this.layoutEngine.options);
  24882. // load the selectionHandler and render default options in to the interaction group
  24883. util.deepExtend(networkOptions.interaction, this.selectionHandler.options);
  24884. util.deepExtend(networkOptions.interaction, this.renderer.options);
  24885. util.deepExtend(networkOptions.interaction, this.interactionHandler.options);
  24886. util.deepExtend(networkOptions.manipulation, this.manipulation.options);
  24887. util.deepExtend(networkOptions.physics, this.physics.options);
  24888. // load globals into the global object
  24889. util.deepExtend(networkOptions.global, this.canvas.options);
  24890. util.deepExtend(networkOptions.global, this.options);
  24891. this.configurator.setModuleOptions(networkOptions);
  24892. }
  24893. // handle network global options
  24894. if (options.clickToUse !== undefined) {
  24895. if (options.clickToUse === true) {
  24896. if (this.activator === undefined) {
  24897. this.activator = new Activator(this.canvas.frame);
  24898. this.activator.on('change', function () {
  24899. _this2.body.emitter.emit("activate");
  24900. });
  24901. }
  24902. } else {
  24903. if (this.activator !== undefined) {
  24904. this.activator.destroy();
  24905. delete this.activator;
  24906. }
  24907. this.body.emitter.emit("activate");
  24908. }
  24909. } else {
  24910. this.body.emitter.emit("activate");
  24911. }
  24912. this.canvas.setSize();
  24913. // start the physics simulation. Can be safely called multiple times.
  24914. this.body.emitter.emit("startSimulation");
  24915. }
  24916. };
  24917. /**
  24918. * Update the this.body.nodeIndices with the most recent node index list
  24919. * @private
  24920. */
  24921. Network.prototype._updateVisibleIndices = function () {
  24922. var nodes = this.body.nodes;
  24923. var edges = this.body.edges;
  24924. this.body.nodeIndices = [];
  24925. this.body.edgeIndices = [];
  24926. for (var nodeId in nodes) {
  24927. if (nodes.hasOwnProperty(nodeId)) {
  24928. if (nodes[nodeId].options.hidden === false) {
  24929. this.body.nodeIndices.push(nodes[nodeId].id);
  24930. }
  24931. }
  24932. }
  24933. for (var edgeId in edges) {
  24934. if (edges.hasOwnProperty(edgeId)) {
  24935. if (edges[edgeId].options.hidden === false) {
  24936. this.body.edgeIndices.push(edges[edgeId].id);
  24937. }
  24938. }
  24939. }
  24940. };
  24941. /**
  24942. * Bind all events
  24943. */
  24944. Network.prototype.bindEventListeners = function () {
  24945. var _this3 = this;
  24946. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  24947. this.body.emitter.on("_dataChanged", function () {
  24948. // update shortcut lists
  24949. _this3._updateVisibleIndices();
  24950. _this3.body.emitter.emit("_requestRedraw");
  24951. // call the dataUpdated event because the only difference between the two is the updating of the indices
  24952. _this3.body.emitter.emit("_dataUpdated");
  24953. });
  24954. // this is called when options of EXISTING nodes or edges have changed.
  24955. this.body.emitter.on("_dataUpdated", function () {
  24956. // update values
  24957. _this3._updateValueRange(_this3.body.nodes);
  24958. _this3._updateValueRange(_this3.body.edges);
  24959. // start simulation (can be called safely, even if already running)
  24960. _this3.body.emitter.emit("startSimulation");
  24961. _this3.body.emitter.emit("_requestRedraw");
  24962. });
  24963. };
  24964. /**
  24965. * Set nodes and edges, and optionally options as well.
  24966. *
  24967. * @param {Object} data Object containing parameters:
  24968. * {Array | DataSet | DataView} [nodes] Array with nodes
  24969. * {Array | DataSet | DataView} [edges] Array with edges
  24970. * {String} [dot] String containing data in DOT format
  24971. * {String} [gephi] String containing data in gephi JSON format
  24972. * {Options} [options] Object with options
  24973. */
  24974. Network.prototype.setData = function (data) {
  24975. // reset the physics engine.
  24976. this.body.emitter.emit("resetPhysics");
  24977. this.body.emitter.emit("_resetData");
  24978. // unselect all to ensure no selections from old data are carried over.
  24979. this.selectionHandler.unselectAll();
  24980. if (data && data.dot && (data.nodes || data.edges)) {
  24981. throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.');
  24982. }
  24983. // set options
  24984. this.setOptions(data && data.options);
  24985. // set all data
  24986. if (data && data.dot) {
  24987. console.log('The dot property has been depricated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);');
  24988. // parse DOT file
  24989. var dotData = dotparser.DOTToGraph(data.dot);
  24990. this.setData(dotData);
  24991. return;
  24992. } else if (data && data.gephi) {
  24993. // parse DOT file
  24994. console.log('The gephi property has been depricated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);');
  24995. var gephiData = gephiParser.parseGephi(data.gephi);
  24996. this.setData(gephiData);
  24997. return;
  24998. } else {
  24999. this.nodesHandler.setData(data && data.nodes, true);
  25000. this.edgesHandler.setData(data && data.edges, true);
  25001. }
  25002. // emit change in data
  25003. this.body.emitter.emit("_dataChanged");
  25004. // emit data loaded
  25005. this.body.emitter.emit("_dataLoaded");
  25006. // find a stable position or start animating to a stable position
  25007. this.body.emitter.emit("initPhysics");
  25008. };
  25009. /**
  25010. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  25011. * var network = new vis.Network(..);
  25012. * network.destroy();
  25013. * network = null;
  25014. */
  25015. Network.prototype.destroy = function () {
  25016. this.body.emitter.emit("destroy");
  25017. // clear events
  25018. this.body.emitter.off();
  25019. this.off();
  25020. // delete modules
  25021. delete this.groups;
  25022. delete this.canvas;
  25023. delete this.selectionHandler;
  25024. delete this.interactionHandler;
  25025. delete this.view;
  25026. delete this.renderer;
  25027. delete this.physics;
  25028. delete this.layoutEngine;
  25029. delete this.clustering;
  25030. delete this.manipulation;
  25031. delete this.nodesHandler;
  25032. delete this.edgesHandler;
  25033. delete this.configurator;
  25034. delete this.images;
  25035. for (var nodeId in this.body.nodes) {
  25036. delete this.body.nodes[nodeId];
  25037. }
  25038. for (var edgeId in this.body.edges) {
  25039. delete this.body.edges[edgeId];
  25040. }
  25041. // remove the container and everything inside it recursively
  25042. util.recursiveDOMDelete(this.body.container);
  25043. };
  25044. /**
  25045. * Update the values of all object in the given array according to the current
  25046. * value range of the objects in the array.
  25047. * @param {Object} obj An object containing a set of Edges or Nodes
  25048. * The objects must have a method getValue() and
  25049. * setValueRange(min, max).
  25050. * @private
  25051. */
  25052. Network.prototype._updateValueRange = function (obj) {
  25053. var id;
  25054. // determine the range of the objects
  25055. var valueMin = undefined;
  25056. var valueMax = undefined;
  25057. var valueTotal = 0;
  25058. for (id in obj) {
  25059. if (obj.hasOwnProperty(id)) {
  25060. var value = obj[id].getValue();
  25061. if (value !== undefined) {
  25062. valueMin = valueMin === undefined ? value : Math.min(value, valueMin);
  25063. valueMax = valueMax === undefined ? value : Math.max(value, valueMax);
  25064. valueTotal += value;
  25065. }
  25066. }
  25067. }
  25068. // adjust the range of all objects
  25069. if (valueMin !== undefined && valueMax !== undefined) {
  25070. for (id in obj) {
  25071. if (obj.hasOwnProperty(id)) {
  25072. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  25073. }
  25074. }
  25075. }
  25076. };
  25077. /**
  25078. * Returns true when the Network is active.
  25079. * @returns {boolean}
  25080. */
  25081. Network.prototype.isActive = function () {
  25082. return !this.activator || this.activator.active;
  25083. };
  25084. Network.prototype.setSize = function () {
  25085. return this.canvas.setSize.apply(this.canvas, arguments);
  25086. };
  25087. Network.prototype.canvasToDOM = function () {
  25088. return this.canvas.canvasToDOM.apply(this.canvas, arguments);
  25089. };
  25090. Network.prototype.DOMtoCanvas = function () {
  25091. return this.canvas.DOMtoCanvas.apply(this.canvas, arguments);
  25092. };
  25093. Network.prototype.findNode = function () {
  25094. return this.clustering.findNode.apply(this.clustering, arguments);
  25095. };
  25096. Network.prototype.isCluster = function () {
  25097. return this.clustering.isCluster.apply(this.clustering, arguments);
  25098. };
  25099. Network.prototype.openCluster = function () {
  25100. return this.clustering.openCluster.apply(this.clustering, arguments);
  25101. };
  25102. Network.prototype.cluster = function () {
  25103. return this.clustering.cluster.apply(this.clustering, arguments);
  25104. };
  25105. Network.prototype.getNodesInCluster = function () {
  25106. return this.clustering.getNodesInCluster.apply(this.clustering, arguments);
  25107. };
  25108. Network.prototype.clusterByConnection = function () {
  25109. return this.clustering.clusterByConnection.apply(this.clustering, arguments);
  25110. };
  25111. Network.prototype.clusterByHubsize = function () {
  25112. return this.clustering.clusterByHubsize.apply(this.clustering, arguments);
  25113. };
  25114. Network.prototype.clusterOutliers = function () {
  25115. return this.clustering.clusterOutliers.apply(this.clustering, arguments);
  25116. };
  25117. Network.prototype.getSeed = function () {
  25118. return this.layoutEngine.getSeed.apply(this.layoutEngine, arguments);
  25119. };
  25120. Network.prototype.enableEditMode = function () {
  25121. return this.manipulation.enableEditMode.apply(this.manipulation, arguments);
  25122. };
  25123. Network.prototype.disableEditMode = function () {
  25124. return this.manipulation.disableEditMode.apply(this.manipulation, arguments);
  25125. };
  25126. Network.prototype.addNodeMode = function () {
  25127. return this.manipulation.addNodeMode.apply(this.manipulation, arguments);
  25128. };
  25129. Network.prototype.editNode = function () {
  25130. return this.manipulation.editNode.apply(this.manipulation, arguments);
  25131. };
  25132. Network.prototype.editNodeMode = function () {
  25133. console.log("Deprecated: Please use editNode instead of editNodeMode.");return this.manipulation.editNode.apply(this.manipulation, arguments);
  25134. };
  25135. Network.prototype.addEdgeMode = function () {
  25136. return this.manipulation.addEdgeMode.apply(this.manipulation, arguments);
  25137. };
  25138. Network.prototype.editEdgeMode = function () {
  25139. return this.manipulation.editEdgeMode.apply(this.manipulation, arguments);
  25140. };
  25141. Network.prototype.deleteSelected = function () {
  25142. return this.manipulation.deleteSelected.apply(this.manipulation, arguments);
  25143. };
  25144. Network.prototype.getPositions = function () {
  25145. return this.nodesHandler.getPositions.apply(this.nodesHandler, arguments);
  25146. };
  25147. Network.prototype.storePositions = function () {
  25148. return this.nodesHandler.storePositions.apply(this.nodesHandler, arguments);
  25149. };
  25150. Network.prototype.moveNode = function () {
  25151. return this.nodesHandler.moveNode.apply(this.nodesHandler, arguments);
  25152. };
  25153. Network.prototype.getBoundingBox = function () {
  25154. return this.nodesHandler.getBoundingBox.apply(this.nodesHandler, arguments);
  25155. };
  25156. Network.prototype.getConnectedNodes = function (objectId) {
  25157. if (this.body.nodes[objectId] !== undefined) {
  25158. return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler, arguments);
  25159. } else {
  25160. return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler, arguments);
  25161. }
  25162. };
  25163. Network.prototype.getConnectedEdges = function () {
  25164. return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler, arguments);
  25165. };
  25166. Network.prototype.startSimulation = function () {
  25167. return this.physics.startSimulation.apply(this.physics, arguments);
  25168. };
  25169. Network.prototype.stopSimulation = function () {
  25170. return this.physics.stopSimulation.apply(this.physics, arguments);
  25171. };
  25172. Network.prototype.stabilize = function () {
  25173. return this.physics.stabilize.apply(this.physics, arguments);
  25174. };
  25175. Network.prototype.getSelection = function () {
  25176. return this.selectionHandler.getSelection.apply(this.selectionHandler, arguments);
  25177. };
  25178. Network.prototype.setSelection = function () {
  25179. return this.selectionHandler.setSelection.apply(this.selectionHandler, arguments);
  25180. };
  25181. Network.prototype.getSelectedNodes = function () {
  25182. return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler, arguments);
  25183. };
  25184. Network.prototype.getSelectedEdges = function () {
  25185. return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler, arguments);
  25186. };
  25187. Network.prototype.getNodeAt = function () {
  25188. var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler, arguments);
  25189. if (node !== undefined && node.id !== undefined) {
  25190. return node.id;
  25191. }
  25192. return node;
  25193. };
  25194. Network.prototype.getEdgeAt = function () {
  25195. var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler, arguments);
  25196. if (edge !== undefined && edge.id !== undefined) {
  25197. return edge.id;
  25198. }
  25199. return edge;
  25200. };
  25201. Network.prototype.selectNodes = function () {
  25202. return this.selectionHandler.selectNodes.apply(this.selectionHandler, arguments);
  25203. };
  25204. Network.prototype.selectEdges = function () {
  25205. return this.selectionHandler.selectEdges.apply(this.selectionHandler, arguments);
  25206. };
  25207. Network.prototype.unselectAll = function () {
  25208. this.selectionHandler.unselectAll.apply(this.selectionHandler, arguments);
  25209. this.redraw();
  25210. };
  25211. Network.prototype.redraw = function () {
  25212. return this.renderer.redraw.apply(this.renderer, arguments);
  25213. };
  25214. Network.prototype.getScale = function () {
  25215. return this.view.getScale.apply(this.view, arguments);
  25216. };
  25217. Network.prototype.getViewPosition = function () {
  25218. return this.view.getViewPosition.apply(this.view, arguments);
  25219. };
  25220. Network.prototype.fit = function () {
  25221. return this.view.fit.apply(this.view, arguments);
  25222. };
  25223. Network.prototype.moveTo = function () {
  25224. return this.view.moveTo.apply(this.view, arguments);
  25225. };
  25226. Network.prototype.focus = function () {
  25227. return this.view.focus.apply(this.view, arguments);
  25228. };
  25229. Network.prototype.releaseNode = function () {
  25230. return this.view.releaseNode.apply(this.view, arguments);
  25231. };
  25232. Network.prototype.getOptionsFromConfigurator = function () {
  25233. var options = {};
  25234. if (this.configurator) {
  25235. options = this.configurator.getOptions.apply(this.configurator);
  25236. }
  25237. return options;
  25238. };
  25239. module.exports = Network;
  25240. /***/ },
  25241. /* 62 */
  25242. /***/ function(module, exports) {
  25243. "use strict";
  25244. Object.defineProperty(exports, "__esModule", {
  25245. value: true
  25246. });
  25247. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  25248. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25249. /**
  25250. * @class Images
  25251. * This class loads images and keeps them stored.
  25252. */
  25253. var Images = function () {
  25254. function Images(callback) {
  25255. _classCallCheck(this, Images);
  25256. this.images = {};
  25257. this.imageBroken = {};
  25258. this.callback = callback;
  25259. }
  25260. /**
  25261. * @param {string} url The Url to cache the image as
  25262. * @return {Image} imageToLoadBrokenUrlOn The image object
  25263. */
  25264. _createClass(Images, [{
  25265. key: "_addImageToCache",
  25266. value: function _addImageToCache(url, imageToCache) {
  25267. // IE11 fix -- thanks dponch!
  25268. if (imageToCache.width === 0) {
  25269. document.body.appendChild(imageToCache);
  25270. imageToCache.width = imageToCache.offsetWidth;
  25271. imageToCache.height = imageToCache.offsetHeight;
  25272. document.body.removeChild(imageToCache);
  25273. }
  25274. this.images[url] = imageToCache;
  25275. }
  25276. /**
  25277. * @param {string} url The original Url that failed to load, if the broken image is successfully loaded it will be added to the cache using this Url as the key so that subsequent requests for this Url will return the broken image
  25278. * @param {string} brokenUrl Url the broken image to try and load
  25279. * @return {Image} imageToLoadBrokenUrlOn The image object
  25280. */
  25281. }, {
  25282. key: "_tryloadBrokenUrl",
  25283. value: function _tryloadBrokenUrl(url, brokenUrl, imageToLoadBrokenUrlOn) {
  25284. var _this = this;
  25285. //If any of the parameters aren't specified then exit the function because nothing constructive can be done
  25286. if (url === undefined || brokenUrl === undefined || imageToLoadBrokenUrlOn === undefined) return;
  25287. //Clear the old subscription to the error event and put a new in place that only handle errors in loading the brokenImageUrl
  25288. imageToLoadBrokenUrlOn.onerror = function () {
  25289. console.error("Could not load brokenImage:", brokenUrl);
  25290. //Add an empty image to the cache so that when subsequent load calls are made for the url we don't try load the image and broken image again
  25291. _this._addImageToCache(url, new Image());
  25292. };
  25293. //Set the source of the image to the brokenUrl, this is actually what kicks off the loading of the broken image
  25294. imageToLoadBrokenUrlOn.src = brokenUrl;
  25295. }
  25296. /**
  25297. * @return {Image} imageToRedrawWith The images that will be passed to the callback when it is invoked
  25298. */
  25299. }, {
  25300. key: "_redrawWithImage",
  25301. value: function _redrawWithImage(imageToRedrawWith) {
  25302. if (this.callback) {
  25303. this.callback(imageToRedrawWith);
  25304. }
  25305. }
  25306. /**
  25307. * @param {string} url Url of the image
  25308. * @param {string} brokenUrl Url of an image to use if the url image is not found
  25309. * @return {Image} img The image object
  25310. */
  25311. }, {
  25312. key: "load",
  25313. value: function load(url, brokenUrl, id) {
  25314. var _this2 = this;
  25315. //Try and get the image from the cache, if successful then return the cached image
  25316. var cachedImage = this.images[url];
  25317. if (cachedImage) return cachedImage;
  25318. //Create a new image
  25319. var img = new Image();
  25320. //Subscribe to the event that is raised if the image loads successfully
  25321. img.onload = function () {
  25322. //Add the image to the cache and then request a redraw
  25323. _this2._addImageToCache(url, img);
  25324. _this2._redrawWithImage(img);
  25325. };
  25326. //Subscribe to the event that is raised if the image fails to load
  25327. img.onerror = function () {
  25328. console.error("Could not load image:", url);
  25329. //Try and load the image specified by the brokenUrl using
  25330. _this2._tryloadBrokenUrl(url, brokenUrl, img);
  25331. };
  25332. //Set the source of the image to the url, this is actuall what kicks off the loading of the image
  25333. img.src = url;
  25334. //Return the new image
  25335. return img;
  25336. }
  25337. }]);
  25338. return Images;
  25339. }();
  25340. exports.default = Images;
  25341. /***/ },
  25342. /* 63 */
  25343. /***/ function(module, exports, __webpack_require__) {
  25344. "use strict";
  25345. Object.defineProperty(exports, "__esModule", {
  25346. value: true
  25347. });
  25348. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  25349. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25350. var util = __webpack_require__(1);
  25351. /**
  25352. * @class Groups
  25353. * This class can store groups and options specific for groups.
  25354. */
  25355. var Groups = function () {
  25356. function Groups() {
  25357. _classCallCheck(this, Groups);
  25358. this.clear();
  25359. this.defaultIndex = 0;
  25360. this.groupsArray = [];
  25361. this.groupIndex = 0;
  25362. this.defaultGroups = [{ border: "#2B7CE9", background: "#97C2FC", highlight: { border: "#2B7CE9", background: "#D2E5FF" }, hover: { border: "#2B7CE9", background: "#D2E5FF" } }, // 0: blue
  25363. { border: "#FFA500", background: "#FFFF00", highlight: { border: "#FFA500", background: "#FFFFA3" }, hover: { border: "#FFA500", background: "#FFFFA3" } }, // 1: yellow
  25364. { border: "#FA0A10", background: "#FB7E81", highlight: { border: "#FA0A10", background: "#FFAFB1" }, hover: { border: "#FA0A10", background: "#FFAFB1" } }, // 2: red
  25365. { border: "#41A906", background: "#7BE141", highlight: { border: "#41A906", background: "#A1EC76" }, hover: { border: "#41A906", background: "#A1EC76" } }, // 3: green
  25366. { border: "#E129F0", background: "#EB7DF4", highlight: { border: "#E129F0", background: "#F0B3F5" }, hover: { border: "#E129F0", background: "#F0B3F5" } }, // 4: magenta
  25367. { border: "#7C29F0", background: "#AD85E4", highlight: { border: "#7C29F0", background: "#D3BDF0" }, hover: { border: "#7C29F0", background: "#D3BDF0" } }, // 5: purple
  25368. { border: "#C37F00", background: "#FFA807", highlight: { border: "#C37F00", background: "#FFCA66" }, hover: { border: "#C37F00", background: "#FFCA66" } }, // 6: orange
  25369. { border: "#4220FB", background: "#6E6EFD", highlight: { border: "#4220FB", background: "#9B9BFD" }, hover: { border: "#4220FB", background: "#9B9BFD" } }, // 7: darkblue
  25370. { border: "#FD5A77", background: "#FFC0CB", highlight: { border: "#FD5A77", background: "#FFD1D9" }, hover: { border: "#FD5A77", background: "#FFD1D9" } }, // 8: pink
  25371. { border: "#4AD63A", background: "#C2FABC", highlight: { border: "#4AD63A", background: "#E6FFE3" }, hover: { border: "#4AD63A", background: "#E6FFE3" } }, // 9: mint
  25372. { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red
  25373. { border: "#FF6000", background: "#FF6000", highlight: { border: "#FF6000", background: "#FF6000" }, hover: { border: "#FF6000", background: "#FF6000" } }, // 12: real orange
  25374. { border: "#97C2FC", background: "#2B7CE9", highlight: { border: "#D2E5FF", background: "#2B7CE9" }, hover: { border: "#D2E5FF", background: "#2B7CE9" } }, // 13: blue
  25375. { border: "#399605", background: "#255C03", highlight: { border: "#399605", background: "#255C03" }, hover: { border: "#399605", background: "#255C03" } }, // 14: green
  25376. { border: "#B70054", background: "#FF007E", highlight: { border: "#B70054", background: "#FF007E" }, hover: { border: "#B70054", background: "#FF007E" } }, // 15: magenta
  25377. { border: "#AD85E4", background: "#7C29F0", highlight: { border: "#D3BDF0", background: "#7C29F0" }, hover: { border: "#D3BDF0", background: "#7C29F0" } }, // 16: purple
  25378. { border: "#4557FA", background: "#000EA1", highlight: { border: "#6E6EFD", background: "#000EA1" }, hover: { border: "#6E6EFD", background: "#000EA1" } }, // 17: darkblue
  25379. { border: "#FFC0CB", background: "#FD5A77", highlight: { border: "#FFD1D9", background: "#FD5A77" }, hover: { border: "#FFD1D9", background: "#FD5A77" } }, // 18: pink
  25380. { border: "#C2FABC", background: "#74D66A", highlight: { border: "#E6FFE3", background: "#74D66A" }, hover: { border: "#E6FFE3", background: "#74D66A" } }, // 19: mint
  25381. { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } } // 20:bright red
  25382. ];
  25383. this.options = {};
  25384. this.defaultOptions = {
  25385. useDefaultGroups: true
  25386. };
  25387. util.extend(this.options, this.defaultOptions);
  25388. }
  25389. _createClass(Groups, [{
  25390. key: "setOptions",
  25391. value: function setOptions(options) {
  25392. var optionFields = ['useDefaultGroups'];
  25393. if (options !== undefined) {
  25394. for (var groupName in options) {
  25395. if (options.hasOwnProperty(groupName)) {
  25396. if (optionFields.indexOf(groupName) === -1) {
  25397. var group = options[groupName];
  25398. this.add(groupName, group);
  25399. }
  25400. }
  25401. }
  25402. }
  25403. }
  25404. /**
  25405. * Clear all groups
  25406. */
  25407. }, {
  25408. key: "clear",
  25409. value: function clear() {
  25410. this.groups = {};
  25411. this.groupsArray = [];
  25412. }
  25413. /**
  25414. * get group options of a groupname. If groupname is not found, a new group
  25415. * is added.
  25416. * @param {*} groupname Can be a number, string, Date, etc.
  25417. * @return {Object} group The created group, containing all group options
  25418. */
  25419. }, {
  25420. key: "get",
  25421. value: function get(groupname) {
  25422. var group = this.groups[groupname];
  25423. if (group === undefined) {
  25424. if (this.options.useDefaultGroups === false && this.groupsArray.length > 0) {
  25425. // create new group
  25426. var index = this.groupIndex % this.groupsArray.length;
  25427. this.groupIndex++;
  25428. group = {};
  25429. group.color = this.groups[this.groupsArray[index]];
  25430. this.groups[groupname] = group;
  25431. } else {
  25432. // create new group
  25433. var _index = this.defaultIndex % this.defaultGroups.length;
  25434. this.defaultIndex++;
  25435. group = {};
  25436. group.color = this.defaultGroups[_index];
  25437. this.groups[groupname] = group;
  25438. }
  25439. }
  25440. return group;
  25441. }
  25442. /**
  25443. * Add a custom group style
  25444. * @param {String} groupName
  25445. * @param {Object} style An object containing borderColor,
  25446. * backgroundColor, etc.
  25447. * @return {Object} group The created group object
  25448. */
  25449. }, {
  25450. key: "add",
  25451. value: function add(groupName, style) {
  25452. this.groups[groupName] = style;
  25453. this.groupsArray.push(groupName);
  25454. return style;
  25455. }
  25456. }]);
  25457. return Groups;
  25458. }();
  25459. exports.default = Groups;
  25460. /***/ },
  25461. /* 64 */
  25462. /***/ function(module, exports, __webpack_require__) {
  25463. 'use strict';
  25464. Object.defineProperty(exports, "__esModule", {
  25465. value: true
  25466. });
  25467. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  25468. var _Node = __webpack_require__(65);
  25469. var _Node2 = _interopRequireDefault(_Node);
  25470. var _Label = __webpack_require__(66);
  25471. var _Label2 = _interopRequireDefault(_Label);
  25472. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25473. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25474. var util = __webpack_require__(1);
  25475. var DataSet = __webpack_require__(9);
  25476. var DataView = __webpack_require__(11);
  25477. var NodesHandler = function () {
  25478. function NodesHandler(body, images, groups, layoutEngine) {
  25479. var _this = this;
  25480. _classCallCheck(this, NodesHandler);
  25481. this.body = body;
  25482. this.images = images;
  25483. this.groups = groups;
  25484. this.layoutEngine = layoutEngine;
  25485. // create the node API in the body container
  25486. this.body.functions.createNode = this.create.bind(this);
  25487. this.nodesListeners = {
  25488. add: function add(event, params) {
  25489. _this.add(params.items);
  25490. },
  25491. update: function update(event, params) {
  25492. _this.update(params.items, params.data);
  25493. },
  25494. remove: function remove(event, params) {
  25495. _this.remove(params.items);
  25496. }
  25497. };
  25498. this.options = {};
  25499. this.defaultOptions = {
  25500. borderWidth: 1,
  25501. borderWidthSelected: 2,
  25502. brokenImage: undefined,
  25503. color: {
  25504. border: '#2B7CE9',
  25505. background: '#97C2FC',
  25506. highlight: {
  25507. border: '#2B7CE9',
  25508. background: '#D2E5FF'
  25509. },
  25510. hover: {
  25511. border: '#2B7CE9',
  25512. background: '#D2E5FF'
  25513. }
  25514. },
  25515. fixed: {
  25516. x: false,
  25517. y: false
  25518. },
  25519. font: {
  25520. color: '#343434',
  25521. size: 14, // px
  25522. face: 'arial',
  25523. background: 'none',
  25524. strokeWidth: 0, // px
  25525. strokeColor: '#ffffff',
  25526. align: 'center'
  25527. },
  25528. group: undefined,
  25529. hidden: false,
  25530. icon: {
  25531. face: 'FontAwesome', //'FontAwesome',
  25532. code: undefined, //'\uf007',
  25533. size: 50, //50,
  25534. color: '#2B7CE9' //'#aa00ff'
  25535. },
  25536. image: undefined, // --> URL
  25537. label: undefined,
  25538. labelHighlightBold: true,
  25539. level: undefined,
  25540. mass: 1,
  25541. physics: true,
  25542. scaling: {
  25543. min: 10,
  25544. max: 30,
  25545. label: {
  25546. enabled: false,
  25547. min: 14,
  25548. max: 30,
  25549. maxVisible: 30,
  25550. drawThreshold: 5
  25551. },
  25552. customScalingFunction: function customScalingFunction(min, max, total, value) {
  25553. if (max === min) {
  25554. return 0.5;
  25555. } else {
  25556. var scale = 1 / (max - min);
  25557. return Math.max(0, (value - min) * scale);
  25558. }
  25559. }
  25560. },
  25561. shadow: {
  25562. enabled: false,
  25563. color: 'rgba(0,0,0,0.5)',
  25564. size: 10,
  25565. x: 5,
  25566. y: 5
  25567. },
  25568. shape: 'ellipse',
  25569. shapeProperties: {
  25570. borderDashes: false, // only for borders
  25571. borderRadius: 6, // only for box shape
  25572. interpolation: true, // only for image and circularImage shapes
  25573. useImageSize: false, // only for image and circularImage shapes
  25574. useBorderWithImage: false // only for image shape
  25575. },
  25576. size: 25,
  25577. title: undefined,
  25578. value: undefined,
  25579. x: undefined,
  25580. y: undefined
  25581. };
  25582. util.extend(this.options, this.defaultOptions);
  25583. this.bindEventListeners();
  25584. }
  25585. _createClass(NodesHandler, [{
  25586. key: 'bindEventListeners',
  25587. value: function bindEventListeners() {
  25588. var _this2 = this;
  25589. // refresh the nodes. Used when reverting from hierarchical layout
  25590. this.body.emitter.on('refreshNodes', this.refresh.bind(this));
  25591. this.body.emitter.on('refresh', this.refresh.bind(this));
  25592. this.body.emitter.on('destroy', function () {
  25593. util.forEach(_this2.nodesListeners, function (callback, event) {
  25594. if (_this2.body.data.nodes) _this2.body.data.nodes.off(event, callback);
  25595. });
  25596. delete _this2.body.functions.createNode;
  25597. delete _this2.nodesListeners.add;
  25598. delete _this2.nodesListeners.update;
  25599. delete _this2.nodesListeners.remove;
  25600. delete _this2.nodesListeners;
  25601. });
  25602. }
  25603. }, {
  25604. key: 'setOptions',
  25605. value: function setOptions(options) {
  25606. if (options !== undefined) {
  25607. _Node2.default.parseOptions(this.options, options);
  25608. // update the shape in all nodes
  25609. if (options.shape !== undefined) {
  25610. for (var nodeId in this.body.nodes) {
  25611. if (this.body.nodes.hasOwnProperty(nodeId)) {
  25612. this.body.nodes[nodeId].updateShape();
  25613. }
  25614. }
  25615. }
  25616. // update the font in all nodes
  25617. if (options.font !== undefined) {
  25618. _Label2.default.parseOptions(this.options.font, options);
  25619. for (var _nodeId in this.body.nodes) {
  25620. if (this.body.nodes.hasOwnProperty(_nodeId)) {
  25621. this.body.nodes[_nodeId].updateLabelModule();
  25622. this.body.nodes[_nodeId]._reset();
  25623. }
  25624. }
  25625. }
  25626. // update the shape size in all nodes
  25627. if (options.size !== undefined) {
  25628. for (var _nodeId2 in this.body.nodes) {
  25629. if (this.body.nodes.hasOwnProperty(_nodeId2)) {
  25630. this.body.nodes[_nodeId2]._reset();
  25631. }
  25632. }
  25633. }
  25634. // update the state of the letiables if needed
  25635. if (options.hidden !== undefined || options.physics !== undefined) {
  25636. this.body.emitter.emit('_dataChanged');
  25637. }
  25638. }
  25639. }
  25640. /**
  25641. * Set a data set with nodes for the network
  25642. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  25643. * @private
  25644. */
  25645. }, {
  25646. key: 'setData',
  25647. value: function setData(nodes) {
  25648. var _this3 = this;
  25649. var doNotEmit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  25650. var oldNodesData = this.body.data.nodes;
  25651. if (nodes instanceof DataSet || nodes instanceof DataView) {
  25652. this.body.data.nodes = nodes;
  25653. } else if (Array.isArray(nodes)) {
  25654. this.body.data.nodes = new DataSet();
  25655. this.body.data.nodes.add(nodes);
  25656. } else if (!nodes) {
  25657. this.body.data.nodes = new DataSet();
  25658. } else {
  25659. throw new TypeError('Array or DataSet expected');
  25660. }
  25661. if (oldNodesData) {
  25662. // unsubscribe from old dataset
  25663. util.forEach(this.nodesListeners, function (callback, event) {
  25664. oldNodesData.off(event, callback);
  25665. });
  25666. }
  25667. // remove drawn nodes
  25668. this.body.nodes = {};
  25669. if (this.body.data.nodes) {
  25670. (function () {
  25671. // subscribe to new dataset
  25672. var me = _this3;
  25673. util.forEach(_this3.nodesListeners, function (callback, event) {
  25674. me.body.data.nodes.on(event, callback);
  25675. });
  25676. // draw all new nodes
  25677. var ids = _this3.body.data.nodes.getIds();
  25678. _this3.add(ids, true);
  25679. })();
  25680. }
  25681. if (doNotEmit === false) {
  25682. this.body.emitter.emit("_dataChanged");
  25683. }
  25684. }
  25685. /**
  25686. * Add nodes
  25687. * @param {Number[] | String[]} ids
  25688. * @private
  25689. */
  25690. }, {
  25691. key: 'add',
  25692. value: function add(ids) {
  25693. var doNotEmit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  25694. var id = void 0;
  25695. var newNodes = [];
  25696. for (var i = 0; i < ids.length; i++) {
  25697. id = ids[i];
  25698. var properties = this.body.data.nodes.get(id);
  25699. var node = this.create(properties);
  25700. newNodes.push(node);
  25701. this.body.nodes[id] = node; // note: this may replace an existing node
  25702. }
  25703. this.layoutEngine.positionInitially(newNodes);
  25704. if (doNotEmit === false) {
  25705. this.body.emitter.emit("_dataChanged");
  25706. }
  25707. }
  25708. /**
  25709. * Update existing nodes, or create them when not yet existing
  25710. * @param {Number[] | String[]} ids
  25711. * @private
  25712. */
  25713. }, {
  25714. key: 'update',
  25715. value: function update(ids, changedData) {
  25716. var nodes = this.body.nodes;
  25717. var dataChanged = false;
  25718. for (var i = 0; i < ids.length; i++) {
  25719. var id = ids[i];
  25720. var node = nodes[id];
  25721. var data = changedData[i];
  25722. if (node !== undefined) {
  25723. // update node
  25724. dataChanged = node.setOptions(data);
  25725. } else {
  25726. dataChanged = true;
  25727. // create node
  25728. node = this.create(data);
  25729. nodes[id] = node;
  25730. }
  25731. }
  25732. if (dataChanged === true) {
  25733. this.body.emitter.emit("_dataChanged");
  25734. } else {
  25735. this.body.emitter.emit("_dataUpdated");
  25736. }
  25737. }
  25738. /**
  25739. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  25740. * @param {Number[] | String[]} ids
  25741. * @private
  25742. */
  25743. }, {
  25744. key: 'remove',
  25745. value: function remove(ids) {
  25746. var nodes = this.body.nodes;
  25747. for (var i = 0; i < ids.length; i++) {
  25748. var id = ids[i];
  25749. delete nodes[id];
  25750. }
  25751. this.body.emitter.emit("_dataChanged");
  25752. }
  25753. /**
  25754. * create a node
  25755. * @param properties
  25756. * @param constructorClass
  25757. */
  25758. }, {
  25759. key: 'create',
  25760. value: function create(properties) {
  25761. var constructorClass = arguments.length <= 1 || arguments[1] === undefined ? _Node2.default : arguments[1];
  25762. return new constructorClass(properties, this.body, this.images, this.groups, this.options);
  25763. }
  25764. }, {
  25765. key: 'refresh',
  25766. value: function refresh() {
  25767. var clearPositions = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];
  25768. var nodes = this.body.nodes;
  25769. for (var nodeId in nodes) {
  25770. var node = undefined;
  25771. if (nodes.hasOwnProperty(nodeId)) {
  25772. node = nodes[nodeId];
  25773. }
  25774. var data = this.body.data.nodes._data[nodeId];
  25775. if (node !== undefined && data !== undefined) {
  25776. if (clearPositions === true) {
  25777. node.setOptions({ x: null, y: null });
  25778. }
  25779. node.setOptions({ fixed: false });
  25780. node.setOptions(data);
  25781. }
  25782. }
  25783. }
  25784. /**
  25785. * Returns the positions of the nodes.
  25786. * @param ids --> optional, can be array of nodeIds, can be string
  25787. * @returns {{}}
  25788. */
  25789. }, {
  25790. key: 'getPositions',
  25791. value: function getPositions(ids) {
  25792. var dataArray = {};
  25793. if (ids !== undefined) {
  25794. if (Array.isArray(ids) === true) {
  25795. for (var i = 0; i < ids.length; i++) {
  25796. if (this.body.nodes[ids[i]] !== undefined) {
  25797. var node = this.body.nodes[ids[i]];
  25798. dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  25799. }
  25800. }
  25801. } else {
  25802. if (this.body.nodes[ids] !== undefined) {
  25803. var _node = this.body.nodes[ids];
  25804. dataArray[ids] = { x: Math.round(_node.x), y: Math.round(_node.y) };
  25805. }
  25806. }
  25807. } else {
  25808. for (var _i = 0; _i < this.body.nodeIndices.length; _i++) {
  25809. var _node2 = this.body.nodes[this.body.nodeIndices[_i]];
  25810. dataArray[this.body.nodeIndices[_i]] = { x: Math.round(_node2.x), y: Math.round(_node2.y) };
  25811. }
  25812. }
  25813. return dataArray;
  25814. }
  25815. /**
  25816. * Load the XY positions of the nodes into the dataset.
  25817. */
  25818. }, {
  25819. key: 'storePositions',
  25820. value: function storePositions() {
  25821. // todo: add support for clusters and hierarchical.
  25822. var dataArray = [];
  25823. var dataset = this.body.data.nodes.getDataSet();
  25824. for (var nodeId in dataset._data) {
  25825. if (dataset._data.hasOwnProperty(nodeId)) {
  25826. var node = this.body.nodes[nodeId];
  25827. if (dataset._data[nodeId].x != Math.round(node.x) || dataset._data[nodeId].y != Math.round(node.y)) {
  25828. dataArray.push({ id: node.id, x: Math.round(node.x), y: Math.round(node.y) });
  25829. }
  25830. }
  25831. }
  25832. dataset.update(dataArray);
  25833. }
  25834. /**
  25835. * get the bounding box of a node.
  25836. * @param nodeId
  25837. * @returns {j|*}
  25838. */
  25839. }, {
  25840. key: 'getBoundingBox',
  25841. value: function getBoundingBox(nodeId) {
  25842. if (this.body.nodes[nodeId] !== undefined) {
  25843. return this.body.nodes[nodeId].shape.boundingBox;
  25844. }
  25845. }
  25846. /**
  25847. * Get the Ids of nodes connected to this node.
  25848. * @param nodeId
  25849. * @returns {Array}
  25850. */
  25851. }, {
  25852. key: 'getConnectedNodes',
  25853. value: function getConnectedNodes(nodeId) {
  25854. var nodeList = [];
  25855. if (this.body.nodes[nodeId] !== undefined) {
  25856. var node = this.body.nodes[nodeId];
  25857. var nodeObj = {}; // used to quickly check if node already exists
  25858. for (var i = 0; i < node.edges.length; i++) {
  25859. var edge = node.edges[i];
  25860. if (edge.toId == node.id) {
  25861. // these are double equals since ids can be numeric or string
  25862. if (nodeObj[edge.fromId] === undefined) {
  25863. nodeList.push(edge.fromId);
  25864. nodeObj[edge.fromId] = true;
  25865. }
  25866. } else if (edge.fromId == node.id) {
  25867. // these are double equals since ids can be numeric or string
  25868. if (nodeObj[edge.toId] === undefined) {
  25869. nodeList.push(edge.toId);
  25870. nodeObj[edge.toId] = true;
  25871. }
  25872. }
  25873. }
  25874. }
  25875. return nodeList;
  25876. }
  25877. /**
  25878. * Get the ids of the edges connected to this node.
  25879. * @param nodeId
  25880. * @returns {*}
  25881. */
  25882. }, {
  25883. key: 'getConnectedEdges',
  25884. value: function getConnectedEdges(nodeId) {
  25885. var edgeList = [];
  25886. if (this.body.nodes[nodeId] !== undefined) {
  25887. var node = this.body.nodes[nodeId];
  25888. for (var i = 0; i < node.edges.length; i++) {
  25889. edgeList.push(node.edges[i].id);
  25890. }
  25891. } else {
  25892. console.log("NodeId provided for getConnectedEdges does not exist. Provided: ", nodeId);
  25893. }
  25894. return edgeList;
  25895. }
  25896. /**
  25897. * Move a node.
  25898. * @param String nodeId
  25899. * @param Number x
  25900. * @param Number y
  25901. */
  25902. }, {
  25903. key: 'moveNode',
  25904. value: function moveNode(nodeId, x, y) {
  25905. var _this4 = this;
  25906. if (this.body.nodes[nodeId] !== undefined) {
  25907. this.body.nodes[nodeId].x = Number(x);
  25908. this.body.nodes[nodeId].y = Number(y);
  25909. setTimeout(function () {
  25910. _this4.body.emitter.emit("startSimulation");
  25911. }, 0);
  25912. } else {
  25913. console.log("Node id supplied to moveNode does not exist. Provided: ", nodeId);
  25914. }
  25915. }
  25916. }]);
  25917. return NodesHandler;
  25918. }();
  25919. exports.default = NodesHandler;
  25920. /***/ },
  25921. /* 65 */
  25922. /***/ function(module, exports, __webpack_require__) {
  25923. 'use strict';
  25924. Object.defineProperty(exports, "__esModule", {
  25925. value: true
  25926. });
  25927. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  25928. var _Label = __webpack_require__(66);
  25929. var _Label2 = _interopRequireDefault(_Label);
  25930. var _Box = __webpack_require__(67);
  25931. var _Box2 = _interopRequireDefault(_Box);
  25932. var _Circle = __webpack_require__(69);
  25933. var _Circle2 = _interopRequireDefault(_Circle);
  25934. var _CircularImage = __webpack_require__(71);
  25935. var _CircularImage2 = _interopRequireDefault(_CircularImage);
  25936. var _Database = __webpack_require__(72);
  25937. var _Database2 = _interopRequireDefault(_Database);
  25938. var _Diamond = __webpack_require__(73);
  25939. var _Diamond2 = _interopRequireDefault(_Diamond);
  25940. var _Dot = __webpack_require__(75);
  25941. var _Dot2 = _interopRequireDefault(_Dot);
  25942. var _Ellipse = __webpack_require__(76);
  25943. var _Ellipse2 = _interopRequireDefault(_Ellipse);
  25944. var _Icon = __webpack_require__(77);
  25945. var _Icon2 = _interopRequireDefault(_Icon);
  25946. var _Image = __webpack_require__(78);
  25947. var _Image2 = _interopRequireDefault(_Image);
  25948. var _Square = __webpack_require__(79);
  25949. var _Square2 = _interopRequireDefault(_Square);
  25950. var _Star = __webpack_require__(80);
  25951. var _Star2 = _interopRequireDefault(_Star);
  25952. var _Text = __webpack_require__(81);
  25953. var _Text2 = _interopRequireDefault(_Text);
  25954. var _Triangle = __webpack_require__(82);
  25955. var _Triangle2 = _interopRequireDefault(_Triangle);
  25956. var _TriangleDown = __webpack_require__(83);
  25957. var _TriangleDown2 = _interopRequireDefault(_TriangleDown);
  25958. var _Validator = __webpack_require__(29);
  25959. var _Validator2 = _interopRequireDefault(_Validator);
  25960. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25961. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  25962. var util = __webpack_require__(1);
  25963. /**
  25964. * @class Node
  25965. * A node. A node can be connected to other nodes via one or multiple edges.
  25966. * @param {object} options An object containing options for the node. All
  25967. * options are optional, except for the id.
  25968. * {number} id Id of the node. Required
  25969. * {string} label Text label for the node
  25970. * {number} x Horizontal position of the node
  25971. * {number} y Vertical position of the node
  25972. * {string} shape Node shape, available:
  25973. * "database", "circle", "ellipse",
  25974. * "box", "image", "text", "dot",
  25975. * "star", "triangle", "triangleDown",
  25976. * "square", "icon"
  25977. * {string} image An image url
  25978. * {string} title An title text, can be HTML
  25979. * {anytype} group A group name or number
  25980. * @param {Network.Images} imagelist A list with images. Only needed
  25981. * when the node has an image
  25982. * @param {Network.Groups} grouplist A list with groups. Needed for
  25983. * retrieving group options
  25984. * @param {Object} constants An object with default values for
  25985. * example for the color
  25986. *
  25987. */
  25988. var Node = function () {
  25989. function Node(options, body, imagelist, grouplist, globalOptions) {
  25990. _classCallCheck(this, Node);
  25991. this.options = util.bridgeObject(globalOptions);
  25992. this.globalOptions = globalOptions;
  25993. this.body = body;
  25994. this.edges = []; // all edges connected to this node
  25995. // set defaults for the options
  25996. this.id = undefined;
  25997. this.imagelist = imagelist;
  25998. this.grouplist = grouplist;
  25999. // state options
  26000. this.x = undefined;
  26001. this.y = undefined;
  26002. this.baseSize = this.options.size;
  26003. this.baseFontSize = this.options.font.size;
  26004. this.predefinedPosition = false; // used to check if initial fit should just take the range or approximate
  26005. this.selected = false;
  26006. this.hover = false;
  26007. this.labelModule = new _Label2.default(this.body, this.options, false /* Not edge label */);
  26008. this.setOptions(options);
  26009. }
  26010. /**
  26011. * Attach a edge to the node
  26012. * @param {Edge} edge
  26013. */
  26014. _createClass(Node, [{
  26015. key: 'attachEdge',
  26016. value: function attachEdge(edge) {
  26017. if (this.edges.indexOf(edge) === -1) {
  26018. this.edges.push(edge);
  26019. }
  26020. }
  26021. /**
  26022. * Detach a edge from the node
  26023. * @param {Edge} edge
  26024. */
  26025. }, {
  26026. key: 'detachEdge',
  26027. value: function detachEdge(edge) {
  26028. var index = this.edges.indexOf(edge);
  26029. if (index != -1) {
  26030. this.edges.splice(index, 1);
  26031. }
  26032. }
  26033. /**
  26034. * Set or overwrite options for the node
  26035. * @param {Object} options an object with options
  26036. * @param {Object} constants and object with default, global options
  26037. */
  26038. }, {
  26039. key: 'setOptions',
  26040. value: function setOptions(options) {
  26041. var currentShape = this.options.shape;
  26042. if (!options) {
  26043. return;
  26044. }
  26045. // basic options
  26046. if (options.id !== undefined) {
  26047. this.id = options.id;
  26048. }
  26049. if (this.id === undefined) {
  26050. throw "Node must have an id";
  26051. }
  26052. // set these options locally
  26053. // clear x and y positions
  26054. if (options.x !== undefined) {
  26055. if (options.x === null) {
  26056. this.x = undefined;this.predefinedPosition = false;
  26057. } else {
  26058. this.x = parseInt(options.x);this.predefinedPosition = true;
  26059. }
  26060. }
  26061. if (options.y !== undefined) {
  26062. if (options.y === null) {
  26063. this.y = undefined;this.predefinedPosition = false;
  26064. } else {
  26065. this.y = parseInt(options.y);this.predefinedPosition = true;
  26066. }
  26067. }
  26068. if (options.size !== undefined) {
  26069. this.baseSize = options.size;
  26070. }
  26071. if (options.value !== undefined) {
  26072. options.value = parseFloat(options.value);
  26073. }
  26074. // copy group options
  26075. if (typeof options.group === 'number' || typeof options.group === 'string' && options.group != '') {
  26076. var groupObj = this.grouplist.get(options.group);
  26077. util.deepExtend(this.options, groupObj);
  26078. // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case.
  26079. this.options.color = util.parseColor(this.options.color);
  26080. }
  26081. // this transforms all shorthands into fully defined options
  26082. Node.parseOptions(this.options, options, true, this.globalOptions);
  26083. // load the images
  26084. if (this.options.image !== undefined) {
  26085. if (this.imagelist) {
  26086. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id);
  26087. } else {
  26088. throw "No imagelist provided";
  26089. }
  26090. }
  26091. this.updateLabelModule();
  26092. this.updateShape(currentShape);
  26093. if (options.hidden !== undefined || options.physics !== undefined) {
  26094. return true;
  26095. }
  26096. return false;
  26097. }
  26098. /**
  26099. * This process all possible shorthands in the new options and makes sure that the parentOptions are fully defined.
  26100. * Static so it can also be used by the handler.
  26101. * @param parentOptions
  26102. * @param newOptions
  26103. * @param allowDeletion
  26104. * @param globalOptions
  26105. */
  26106. }, {
  26107. key: 'updateLabelModule',
  26108. value: function updateLabelModule() {
  26109. if (this.options.label === undefined || this.options.label === null) {
  26110. this.options.label = '';
  26111. }
  26112. this.labelModule.setOptions(this.options, true);
  26113. if (this.labelModule.baseSize !== undefined) {
  26114. this.baseFontSize = this.labelModule.baseSize;
  26115. }
  26116. }
  26117. }, {
  26118. key: 'updateShape',
  26119. value: function updateShape(currentShape) {
  26120. if (currentShape === this.options.shape && this.shape) {
  26121. this.shape.setOptions(this.options, this.imageObj);
  26122. } else {
  26123. // choose draw method depending on the shape
  26124. switch (this.options.shape) {
  26125. case 'box':
  26126. this.shape = new _Box2.default(this.options, this.body, this.labelModule);
  26127. break;
  26128. case 'circle':
  26129. this.shape = new _Circle2.default(this.options, this.body, this.labelModule);
  26130. break;
  26131. case 'circularImage':
  26132. this.shape = new _CircularImage2.default(this.options, this.body, this.labelModule, this.imageObj);
  26133. break;
  26134. case 'database':
  26135. this.shape = new _Database2.default(this.options, this.body, this.labelModule);
  26136. break;
  26137. case 'diamond':
  26138. this.shape = new _Diamond2.default(this.options, this.body, this.labelModule);
  26139. break;
  26140. case 'dot':
  26141. this.shape = new _Dot2.default(this.options, this.body, this.labelModule);
  26142. break;
  26143. case 'ellipse':
  26144. this.shape = new _Ellipse2.default(this.options, this.body, this.labelModule);
  26145. break;
  26146. case 'icon':
  26147. this.shape = new _Icon2.default(this.options, this.body, this.labelModule);
  26148. break;
  26149. case 'image':
  26150. this.shape = new _Image2.default(this.options, this.body, this.labelModule, this.imageObj);
  26151. break;
  26152. case 'square':
  26153. this.shape = new _Square2.default(this.options, this.body, this.labelModule);
  26154. break;
  26155. case 'star':
  26156. this.shape = new _Star2.default(this.options, this.body, this.labelModule);
  26157. break;
  26158. case 'text':
  26159. this.shape = new _Text2.default(this.options, this.body, this.labelModule);
  26160. break;
  26161. case 'triangle':
  26162. this.shape = new _Triangle2.default(this.options, this.body, this.labelModule);
  26163. break;
  26164. case 'triangleDown':
  26165. this.shape = new _TriangleDown2.default(this.options, this.body, this.labelModule);
  26166. break;
  26167. default:
  26168. this.shape = new _Ellipse2.default(this.options, this.body, this.labelModule);
  26169. break;
  26170. }
  26171. }
  26172. this._reset();
  26173. }
  26174. /**
  26175. * select this node
  26176. */
  26177. }, {
  26178. key: 'select',
  26179. value: function select() {
  26180. this.selected = true;
  26181. this._reset();
  26182. }
  26183. /**
  26184. * unselect this node
  26185. */
  26186. }, {
  26187. key: 'unselect',
  26188. value: function unselect() {
  26189. this.selected = false;
  26190. this._reset();
  26191. }
  26192. /**
  26193. * Reset the calculated size of the node, forces it to recalculate its size
  26194. * @private
  26195. */
  26196. }, {
  26197. key: '_reset',
  26198. value: function _reset() {
  26199. this.shape.width = undefined;
  26200. this.shape.height = undefined;
  26201. }
  26202. /**
  26203. * get the title of this node.
  26204. * @return {string} title The title of the node, or undefined when no title
  26205. * has been set.
  26206. */
  26207. }, {
  26208. key: 'getTitle',
  26209. value: function getTitle() {
  26210. return this.options.title;
  26211. }
  26212. /**
  26213. * Calculate the distance to the border of the Node
  26214. * @param {CanvasRenderingContext2D} ctx
  26215. * @param {Number} angle Angle in radians
  26216. * @returns {number} distance Distance to the border in pixels
  26217. */
  26218. }, {
  26219. key: 'distanceToBorder',
  26220. value: function distanceToBorder(ctx, angle) {
  26221. return this.shape.distanceToBorder(ctx, angle);
  26222. }
  26223. /**
  26224. * Check if this node has a fixed x and y position
  26225. * @return {boolean} true if fixed, false if not
  26226. */
  26227. }, {
  26228. key: 'isFixed',
  26229. value: function isFixed() {
  26230. return this.options.fixed.x && this.options.fixed.y;
  26231. }
  26232. /**
  26233. * check if this node is selecte
  26234. * @return {boolean} selected True if node is selected, else false
  26235. */
  26236. }, {
  26237. key: 'isSelected',
  26238. value: function isSelected() {
  26239. return this.selected;
  26240. }
  26241. /**
  26242. * Retrieve the value of the node. Can be undefined
  26243. * @return {Number} value
  26244. */
  26245. }, {
  26246. key: 'getValue',
  26247. value: function getValue() {
  26248. return this.options.value;
  26249. }
  26250. /**
  26251. * Adjust the value range of the node. The node will adjust it's size
  26252. * based on its value.
  26253. * @param {Number} min
  26254. * @param {Number} max
  26255. */
  26256. }, {
  26257. key: 'setValueRange',
  26258. value: function setValueRange(min, max, total) {
  26259. if (this.options.value !== undefined) {
  26260. var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
  26261. var sizeDiff = this.options.scaling.max - this.options.scaling.min;
  26262. if (this.options.scaling.label.enabled === true) {
  26263. var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
  26264. this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
  26265. }
  26266. this.options.size = this.options.scaling.min + scale * sizeDiff;
  26267. } else {
  26268. this.options.size = this.baseSize;
  26269. this.options.font.size = this.baseFontSize;
  26270. }
  26271. this.updateLabelModule();
  26272. }
  26273. /**
  26274. * Draw this node in the given canvas
  26275. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  26276. * @param {CanvasRenderingContext2D} ctx
  26277. */
  26278. }, {
  26279. key: 'draw',
  26280. value: function draw(ctx) {
  26281. this.shape.draw(ctx, this.x, this.y, this.selected, this.hover);
  26282. }
  26283. /**
  26284. * Update the bounding box of the shape
  26285. */
  26286. }, {
  26287. key: 'updateBoundingBox',
  26288. value: function updateBoundingBox(ctx) {
  26289. this.shape.updateBoundingBox(this.x, this.y, ctx);
  26290. }
  26291. /**
  26292. * Recalculate the size of this node in the given canvas
  26293. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  26294. * @param {CanvasRenderingContext2D} ctx
  26295. */
  26296. }, {
  26297. key: 'resize',
  26298. value: function resize(ctx) {
  26299. this.shape.resize(ctx, this.selected);
  26300. }
  26301. /**
  26302. * Check if this object is overlapping with the provided object
  26303. * @param {Object} obj an object with parameters left, top, right, bottom
  26304. * @return {boolean} True if location is located on node
  26305. */
  26306. }, {
  26307. key: 'isOverlappingWith',
  26308. value: function isOverlappingWith(obj) {
  26309. return this.shape.left < obj.right && this.shape.left + this.shape.width > obj.left && this.shape.top < obj.bottom && this.shape.top + this.shape.height > obj.top;
  26310. }
  26311. /**
  26312. * Check if this object is overlapping with the provided object
  26313. * @param {Object} obj an object with parameters left, top, right, bottom
  26314. * @return {boolean} True if location is located on node
  26315. */
  26316. }, {
  26317. key: 'isBoundingBoxOverlappingWith',
  26318. value: function isBoundingBoxOverlappingWith(obj) {
  26319. return this.shape.boundingBox.left < obj.right && this.shape.boundingBox.right > obj.left && this.shape.boundingBox.top < obj.bottom && this.shape.boundingBox.bottom > obj.top;
  26320. }
  26321. }], [{
  26322. key: 'parseOptions',
  26323. value: function parseOptions(parentOptions, newOptions) {
  26324. var allowDeletion = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  26325. var globalOptions = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
  26326. var fields = ['color', 'font', 'fixed', 'shadow'];
  26327. util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion);
  26328. // merge the shadow options into the parent.
  26329. util.mergeOptions(parentOptions, newOptions, 'shadow', allowDeletion, globalOptions);
  26330. // individual shape newOptions
  26331. if (newOptions.color !== undefined && newOptions.color !== null) {
  26332. var parsedColor = util.parseColor(newOptions.color);
  26333. util.fillIfDefined(parentOptions.color, parsedColor);
  26334. } else if (allowDeletion === true && newOptions.color === null) {
  26335. parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
  26336. }
  26337. // handle the fixed options
  26338. if (newOptions.fixed !== undefined && newOptions.fixed !== null) {
  26339. if (typeof newOptions.fixed === 'boolean') {
  26340. parentOptions.fixed.x = newOptions.fixed;
  26341. parentOptions.fixed.y = newOptions.fixed;
  26342. } else {
  26343. if (newOptions.fixed.x !== undefined && typeof newOptions.fixed.x === 'boolean') {
  26344. parentOptions.fixed.x = newOptions.fixed.x;
  26345. }
  26346. if (newOptions.fixed.y !== undefined && typeof newOptions.fixed.y === 'boolean') {
  26347. parentOptions.fixed.y = newOptions.fixed.y;
  26348. }
  26349. }
  26350. }
  26351. // handle the font options
  26352. if (newOptions.font !== undefined && newOptions.font !== null) {
  26353. _Label2.default.parseOptions(parentOptions.font, newOptions);
  26354. } else if (allowDeletion === true && newOptions.font === null) {
  26355. parentOptions.font = util.bridgeObject(globalOptions.font); // set the object back to the global options
  26356. }
  26357. // handle the scaling options, specifically the label part
  26358. if (newOptions.scaling !== undefined) {
  26359. util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', allowDeletion, globalOptions.scaling);
  26360. }
  26361. }
  26362. }]);
  26363. return Node;
  26364. }();
  26365. exports.default = Node;
  26366. /***/ },
  26367. /* 66 */
  26368. /***/ function(module, exports, __webpack_require__) {
  26369. 'use strict';
  26370. Object.defineProperty(exports, "__esModule", {
  26371. value: true
  26372. });
  26373. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  26374. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  26375. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  26376. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26377. var util = __webpack_require__(1);
  26378. var Label = function () {
  26379. function Label(body, options) {
  26380. var edgelabel = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  26381. _classCallCheck(this, Label);
  26382. this.body = body;
  26383. this.pointToSelf = false;
  26384. this.baseSize = undefined;
  26385. this.fontOptions = {};
  26386. this.setOptions(options);
  26387. this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 }; // could be cached
  26388. this.isEdgeLabel = edgelabel;
  26389. }
  26390. _createClass(Label, [{
  26391. key: 'setOptions',
  26392. value: function setOptions(options) {
  26393. var allowDeletion = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  26394. this.nodeOptions = options;
  26395. // We want to keep the font options seperated from the node options.
  26396. // The node options have to mirror the globals when they are not overruled.
  26397. this.fontOptions = util.deepExtend({}, options.font, true);
  26398. if (options.label !== undefined) {
  26399. this.labelDirty = true;
  26400. }
  26401. if (options.font !== undefined) {
  26402. Label.parseOptions(this.fontOptions, options, allowDeletion);
  26403. if (typeof options.font === 'string') {
  26404. this.baseSize = this.fontOptions.size;
  26405. } else if (_typeof(options.font) === 'object') {
  26406. if (options.font.size !== undefined) {
  26407. this.baseSize = options.font.size;
  26408. }
  26409. }
  26410. }
  26411. }
  26412. }, {
  26413. key: 'draw',
  26414. /**
  26415. * Main function. This is called from anything that wants to draw a label.
  26416. * @param ctx
  26417. * @param x
  26418. * @param y
  26419. * @param selected
  26420. * @param baseline
  26421. */
  26422. value: function draw(ctx, x, y, selected) {
  26423. var baseline = arguments.length <= 4 || arguments[4] === undefined ? 'middle' : arguments[4];
  26424. // if no label, return
  26425. if (this.nodeOptions.label === undefined) return;
  26426. // check if we have to render the label
  26427. var viewFontSize = this.fontOptions.size * this.body.view.scale;
  26428. if (this.nodeOptions.label && viewFontSize < this.nodeOptions.scaling.label.drawThreshold - 1) return;
  26429. // update the size cache if required
  26430. this.calculateLabelSize(ctx, selected, x, y, baseline);
  26431. // create the fontfill background
  26432. this._drawBackground(ctx);
  26433. // draw text
  26434. this._drawText(ctx, selected, x, y, baseline);
  26435. }
  26436. /**
  26437. * Draws the label background
  26438. * @param {CanvasRenderingContext2D} ctx
  26439. * @private
  26440. */
  26441. }, {
  26442. key: '_drawBackground',
  26443. value: function _drawBackground(ctx) {
  26444. if (this.fontOptions.background !== undefined && this.fontOptions.background !== "none") {
  26445. ctx.fillStyle = this.fontOptions.background;
  26446. var lineMargin = 2;
  26447. if (this.isEdgeLabel) {
  26448. switch (this.fontOptions.align) {
  26449. case 'middle':
  26450. ctx.fillRect(-this.size.width * 0.5, -this.size.height * 0.5, this.size.width, this.size.height);
  26451. break;
  26452. case 'top':
  26453. ctx.fillRect(-this.size.width * 0.5, -(this.size.height + lineMargin), this.size.width, this.size.height);
  26454. break;
  26455. case 'bottom':
  26456. ctx.fillRect(-this.size.width * 0.5, lineMargin, this.size.width, this.size.height);
  26457. break;
  26458. default:
  26459. ctx.fillRect(this.size.left, this.size.top - 0.5 * lineMargin, this.size.width, this.size.height);
  26460. break;
  26461. }
  26462. } else {
  26463. ctx.fillRect(this.size.left, this.size.top - 0.5 * lineMargin, this.size.width, this.size.height);
  26464. }
  26465. }
  26466. }
  26467. /**
  26468. *
  26469. * @param ctx
  26470. * @param x
  26471. * @param baseline
  26472. * @private
  26473. */
  26474. }, {
  26475. key: '_drawText',
  26476. value: function _drawText(ctx, selected, x, y) {
  26477. var baseline = arguments.length <= 4 || arguments[4] === undefined ? 'middle' : arguments[4];
  26478. var fontSize = this.fontOptions.size;
  26479. var viewFontSize = fontSize * this.body.view.scale;
  26480. // this ensures that there will not be HUGE letters on screen by setting an upper limit on the visible text size (regardless of zoomLevel)
  26481. if (viewFontSize >= this.nodeOptions.scaling.label.maxVisible) {
  26482. fontSize = Number(this.nodeOptions.scaling.label.maxVisible) / this.body.view.scale;
  26483. }
  26484. var yLine = this.size.yLine;
  26485. var _getColor2 = this._getColor(viewFontSize);
  26486. var _getColor3 = _slicedToArray(_getColor2, 2);
  26487. var fontColor = _getColor3[0];
  26488. var strokeColor = _getColor3[1];
  26489. // configure context for drawing the text
  26490. var _setAlignment2 = this._setAlignment(ctx, x, yLine, baseline);
  26491. var _setAlignment3 = _slicedToArray(_setAlignment2, 2);
  26492. x = _setAlignment3[0];
  26493. yLine = _setAlignment3[1];
  26494. ctx.font = (selected && this.nodeOptions.labelHighlightBold ? 'bold ' : '') + fontSize + "px " + this.fontOptions.face;
  26495. ctx.fillStyle = fontColor;
  26496. // When the textAlign property is 'left', make label left-justified
  26497. if (!this.isEdgeLabel && this.fontOptions.align === 'left') {
  26498. ctx.textAlign = this.fontOptions.align;
  26499. x = x - 0.5 * this.size.width; // Shift label 1/2-distance to the left
  26500. } else {
  26501. ctx.textAlign = 'center';
  26502. }
  26503. // set the strokeWidth
  26504. if (this.fontOptions.strokeWidth > 0) {
  26505. ctx.lineWidth = this.fontOptions.strokeWidth;
  26506. ctx.strokeStyle = strokeColor;
  26507. ctx.lineJoin = 'round';
  26508. }
  26509. // draw the text
  26510. for (var i = 0; i < this.lineCount; i++) {
  26511. if (this.fontOptions.strokeWidth > 0) {
  26512. ctx.strokeText(this.lines[i], x, yLine);
  26513. }
  26514. ctx.fillText(this.lines[i], x, yLine);
  26515. yLine += fontSize;
  26516. }
  26517. }
  26518. }, {
  26519. key: '_setAlignment',
  26520. value: function _setAlignment(ctx, x, yLine, baseline) {
  26521. // check for label alignment (for edges)
  26522. // TODO: make alignment for nodes
  26523. if (this.isEdgeLabel && this.fontOptions.align !== 'horizontal' && this.pointToSelf === false) {
  26524. x = 0;
  26525. yLine = 0;
  26526. var lineMargin = 2;
  26527. if (this.fontOptions.align === 'top') {
  26528. ctx.textBaseline = 'alphabetic';
  26529. yLine -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers
  26530. } else if (this.fontOptions.align === 'bottom') {
  26531. ctx.textBaseline = 'hanging';
  26532. yLine += 2 * lineMargin; // distance from edge, required because we use hanging. Hanging has less difference between browsers
  26533. } else {
  26534. ctx.textBaseline = 'middle';
  26535. }
  26536. } else {
  26537. ctx.textBaseline = baseline;
  26538. }
  26539. return [x, yLine];
  26540. }
  26541. /**
  26542. * fade in when relative scale is between threshold and threshold - 1.
  26543. * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here.
  26544. *
  26545. * @param viewFontSize
  26546. * @returns {*[]}
  26547. * @private
  26548. */
  26549. }, {
  26550. key: '_getColor',
  26551. value: function _getColor(viewFontSize) {
  26552. var fontColor = this.fontOptions.color || '#000000';
  26553. var strokeColor = this.fontOptions.strokeColor || '#ffffff';
  26554. if (viewFontSize <= this.nodeOptions.scaling.label.drawThreshold) {
  26555. var opacity = Math.max(0, Math.min(1, 1 - (this.nodeOptions.scaling.label.drawThreshold - viewFontSize)));
  26556. fontColor = util.overrideOpacity(fontColor, opacity);
  26557. strokeColor = util.overrideOpacity(strokeColor, opacity);
  26558. }
  26559. return [fontColor, strokeColor];
  26560. }
  26561. /**
  26562. *
  26563. * @param ctx
  26564. * @param selected
  26565. * @returns {{width: number, height: number}}
  26566. */
  26567. }, {
  26568. key: 'getTextSize',
  26569. value: function getTextSize(ctx) {
  26570. var selected = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  26571. var size = {
  26572. width: this._processLabel(ctx, selected),
  26573. height: this.fontOptions.size * this.lineCount,
  26574. lineCount: this.lineCount
  26575. };
  26576. return size;
  26577. }
  26578. /**
  26579. *
  26580. * @param ctx
  26581. * @param selected
  26582. * @param x
  26583. * @param y
  26584. * @param baseline
  26585. */
  26586. }, {
  26587. key: 'calculateLabelSize',
  26588. value: function calculateLabelSize(ctx, selected) {
  26589. var x = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2];
  26590. var y = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3];
  26591. var baseline = arguments.length <= 4 || arguments[4] === undefined ? 'middle' : arguments[4];
  26592. if (this.labelDirty === true) {
  26593. this.size.width = this._processLabel(ctx, selected);
  26594. }
  26595. this.size.height = this.fontOptions.size * this.lineCount;
  26596. this.size.left = x - this.size.width * 0.5;
  26597. this.size.top = y - this.size.height * 0.5;
  26598. this.size.yLine = y + (1 - this.lineCount) * 0.5 * this.fontOptions.size;
  26599. if (baseline === "hanging") {
  26600. this.size.top += 0.5 * this.fontOptions.size;
  26601. this.size.top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers
  26602. this.size.yLine += 4; // distance from node
  26603. }
  26604. this.labelDirty = false;
  26605. }
  26606. /**
  26607. * This calculates the width as well as explodes the label string and calculates the amount of lines.
  26608. * @param ctx
  26609. * @param selected
  26610. * @returns {number}
  26611. * @private
  26612. */
  26613. }, {
  26614. key: '_processLabel',
  26615. value: function _processLabel(ctx, selected) {
  26616. var width = 0;
  26617. var lines = [''];
  26618. var lineCount = 0;
  26619. if (this.nodeOptions.label !== undefined) {
  26620. lines = String(this.nodeOptions.label).split('\n');
  26621. lineCount = lines.length;
  26622. ctx.font = (selected && this.nodeOptions.labelHighlightBold ? 'bold ' : '') + this.fontOptions.size + "px " + this.fontOptions.face;
  26623. width = ctx.measureText(lines[0]).width;
  26624. for (var i = 1; i < lineCount; i++) {
  26625. var lineWidth = ctx.measureText(lines[i]).width;
  26626. width = lineWidth > width ? lineWidth : width;
  26627. }
  26628. }
  26629. this.lines = lines;
  26630. this.lineCount = lineCount;
  26631. return width;
  26632. }
  26633. }], [{
  26634. key: 'parseOptions',
  26635. value: function parseOptions(parentOptions, newOptions) {
  26636. var allowDeletion = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  26637. if (typeof newOptions.font === 'string') {
  26638. var newOptionsArray = newOptions.font.split(" ");
  26639. parentOptions.size = newOptionsArray[0].replace("px", '');
  26640. parentOptions.face = newOptionsArray[1];
  26641. parentOptions.color = newOptionsArray[2];
  26642. } else if (_typeof(newOptions.font) === 'object') {
  26643. util.fillIfDefined(parentOptions, newOptions.font, allowDeletion);
  26644. }
  26645. parentOptions.size = Number(parentOptions.size);
  26646. }
  26647. }]);
  26648. return Label;
  26649. }();
  26650. exports.default = Label;
  26651. /***/ },
  26652. /* 67 */
  26653. /***/ function(module, exports, __webpack_require__) {
  26654. 'use strict';
  26655. Object.defineProperty(exports, "__esModule", {
  26656. value: true
  26657. });
  26658. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  26659. var _NodeBase2 = __webpack_require__(68);
  26660. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  26661. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26662. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26663. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  26664. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  26665. var Box = function (_NodeBase) {
  26666. _inherits(Box, _NodeBase);
  26667. function Box(options, body, labelModule) {
  26668. _classCallCheck(this, Box);
  26669. return _possibleConstructorReturn(this, Object.getPrototypeOf(Box).call(this, options, body, labelModule));
  26670. }
  26671. _createClass(Box, [{
  26672. key: 'resize',
  26673. value: function resize(ctx, selected) {
  26674. if (this.width === undefined) {
  26675. var margin = 5;
  26676. var textSize = this.labelModule.getTextSize(ctx, selected);
  26677. this.width = textSize.width + 2 * margin;
  26678. this.height = textSize.height + 2 * margin;
  26679. this.radius = 0.5 * this.width;
  26680. }
  26681. }
  26682. }, {
  26683. key: 'draw',
  26684. value: function draw(ctx, x, y, selected, hover) {
  26685. this.resize(ctx, selected);
  26686. this.left = x - this.width / 2;
  26687. this.top = y - this.height / 2;
  26688. var borderWidth = this.options.borderWidth;
  26689. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  26690. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  26691. ctx.lineWidth = selected ? selectionLineWidth : borderWidth;
  26692. ctx.lineWidth /= this.body.view.scale;
  26693. ctx.lineWidth = Math.min(this.width, ctx.lineWidth);
  26694. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  26695. var borderRadius = this.options.shapeProperties.borderRadius; // only effective for box
  26696. ctx.roundRect(this.left, this.top, this.width, this.height, borderRadius);
  26697. // draw shadow if enabled
  26698. this.enableShadow(ctx);
  26699. // draw the background
  26700. ctx.fill();
  26701. // disable shadows for other elements.
  26702. this.disableShadow(ctx);
  26703. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  26704. ctx.save();
  26705. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  26706. if (borderWidth > 0) {
  26707. this.enableBorderDashes(ctx);
  26708. //draw the border
  26709. ctx.stroke();
  26710. //disable dashed border for other elements
  26711. this.disableBorderDashes(ctx);
  26712. }
  26713. ctx.restore();
  26714. this.updateBoundingBox(x, y, ctx, selected);
  26715. this.labelModule.draw(ctx, x, y, selected);
  26716. }
  26717. }, {
  26718. key: 'updateBoundingBox',
  26719. value: function updateBoundingBox(x, y, ctx, selected) {
  26720. this.resize(ctx, selected);
  26721. this.left = x - this.width * 0.5;
  26722. this.top = y - this.height * 0.5;
  26723. var borderRadius = this.options.shapeProperties.borderRadius; // only effective for box
  26724. this.boundingBox.left = this.left - borderRadius;
  26725. this.boundingBox.top = this.top - borderRadius;
  26726. this.boundingBox.bottom = this.top + this.height + borderRadius;
  26727. this.boundingBox.right = this.left + this.width + borderRadius;
  26728. }
  26729. }, {
  26730. key: 'distanceToBorder',
  26731. value: function distanceToBorder(ctx, angle) {
  26732. this.resize(ctx);
  26733. var borderWidth = this.options.borderWidth;
  26734. return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  26735. }
  26736. }]);
  26737. return Box;
  26738. }(_NodeBase3.default);
  26739. exports.default = Box;
  26740. /***/ },
  26741. /* 68 */
  26742. /***/ function(module, exports) {
  26743. "use strict";
  26744. Object.defineProperty(exports, "__esModule", {
  26745. value: true
  26746. });
  26747. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  26748. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26749. var NodeBase = function () {
  26750. function NodeBase(options, body, labelModule) {
  26751. _classCallCheck(this, NodeBase);
  26752. this.body = body;
  26753. this.labelModule = labelModule;
  26754. this.setOptions(options);
  26755. this.top = undefined;
  26756. this.left = undefined;
  26757. this.height = undefined;
  26758. this.width = undefined;
  26759. this.radius = undefined;
  26760. this.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 };
  26761. }
  26762. _createClass(NodeBase, [{
  26763. key: "setOptions",
  26764. value: function setOptions(options) {
  26765. this.options = options;
  26766. }
  26767. }, {
  26768. key: "_distanceToBorder",
  26769. value: function _distanceToBorder(ctx, angle) {
  26770. var borderWidth = this.options.borderWidth;
  26771. this.resize(ctx);
  26772. return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  26773. }
  26774. }, {
  26775. key: "enableShadow",
  26776. value: function enableShadow(ctx) {
  26777. if (this.options.shadow.enabled === true) {
  26778. ctx.shadowColor = this.options.shadow.color;
  26779. ctx.shadowBlur = this.options.shadow.size;
  26780. ctx.shadowOffsetX = this.options.shadow.x;
  26781. ctx.shadowOffsetY = this.options.shadow.y;
  26782. }
  26783. }
  26784. }, {
  26785. key: "disableShadow",
  26786. value: function disableShadow(ctx) {
  26787. if (this.options.shadow.enabled === true) {
  26788. ctx.shadowColor = 'rgba(0,0,0,0)';
  26789. ctx.shadowBlur = 0;
  26790. ctx.shadowOffsetX = 0;
  26791. ctx.shadowOffsetY = 0;
  26792. }
  26793. }
  26794. }, {
  26795. key: "enableBorderDashes",
  26796. value: function enableBorderDashes(ctx) {
  26797. if (this.options.shapeProperties.borderDashes !== false) {
  26798. if (ctx.setLineDash !== undefined) {
  26799. var dashes = this.options.shapeProperties.borderDashes;
  26800. if (dashes === true) {
  26801. dashes = [5, 15];
  26802. }
  26803. ctx.setLineDash(dashes);
  26804. } else {
  26805. console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");
  26806. this.options.shapeProperties.borderDashes = false;
  26807. }
  26808. }
  26809. }
  26810. }, {
  26811. key: "disableBorderDashes",
  26812. value: function disableBorderDashes(ctx) {
  26813. if (this.options.shapeProperties.borderDashes !== false) {
  26814. if (ctx.setLineDash !== undefined) {
  26815. ctx.setLineDash([0]);
  26816. } else {
  26817. console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");
  26818. this.options.shapeProperties.borderDashes = false;
  26819. }
  26820. }
  26821. }
  26822. }]);
  26823. return NodeBase;
  26824. }();
  26825. exports.default = NodeBase;
  26826. /***/ },
  26827. /* 69 */
  26828. /***/ function(module, exports, __webpack_require__) {
  26829. 'use strict';
  26830. Object.defineProperty(exports, "__esModule", {
  26831. value: true
  26832. });
  26833. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  26834. var _CircleImageBase2 = __webpack_require__(70);
  26835. var _CircleImageBase3 = _interopRequireDefault(_CircleImageBase2);
  26836. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26837. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26838. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  26839. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  26840. var Circle = function (_CircleImageBase) {
  26841. _inherits(Circle, _CircleImageBase);
  26842. function Circle(options, body, labelModule) {
  26843. _classCallCheck(this, Circle);
  26844. return _possibleConstructorReturn(this, Object.getPrototypeOf(Circle).call(this, options, body, labelModule));
  26845. }
  26846. _createClass(Circle, [{
  26847. key: 'resize',
  26848. value: function resize(ctx, selected) {
  26849. if (this.width === undefined) {
  26850. var margin = 5;
  26851. var textSize = this.labelModule.getTextSize(ctx, selected);
  26852. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  26853. this.options.size = diameter / 2;
  26854. this.width = diameter;
  26855. this.height = diameter;
  26856. this.radius = 0.5 * this.width;
  26857. }
  26858. }
  26859. }, {
  26860. key: 'draw',
  26861. value: function draw(ctx, x, y, selected, hover) {
  26862. this.resize(ctx, selected);
  26863. this.left = x - this.width / 2;
  26864. this.top = y - this.height / 2;
  26865. this._drawRawCircle(ctx, x, y, selected, hover, this.options.size);
  26866. this.boundingBox.top = y - this.options.size;
  26867. this.boundingBox.left = x - this.options.size;
  26868. this.boundingBox.right = x + this.options.size;
  26869. this.boundingBox.bottom = y + this.options.size;
  26870. this.updateBoundingBox(x, y);
  26871. this.labelModule.draw(ctx, x, y, selected);
  26872. }
  26873. }, {
  26874. key: 'updateBoundingBox',
  26875. value: function updateBoundingBox(x, y) {
  26876. this.boundingBox.top = y - this.options.size;
  26877. this.boundingBox.left = x - this.options.size;
  26878. this.boundingBox.right = x + this.options.size;
  26879. this.boundingBox.bottom = y + this.options.size;
  26880. }
  26881. }, {
  26882. key: 'distanceToBorder',
  26883. value: function distanceToBorder(ctx, angle) {
  26884. this.resize(ctx);
  26885. return this.width * 0.5;
  26886. }
  26887. }]);
  26888. return Circle;
  26889. }(_CircleImageBase3.default);
  26890. exports.default = Circle;
  26891. /***/ },
  26892. /* 70 */
  26893. /***/ function(module, exports, __webpack_require__) {
  26894. 'use strict';
  26895. Object.defineProperty(exports, "__esModule", {
  26896. value: true
  26897. });
  26898. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  26899. var _NodeBase2 = __webpack_require__(68);
  26900. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  26901. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26902. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26903. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  26904. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  26905. var CircleImageBase = function (_NodeBase) {
  26906. _inherits(CircleImageBase, _NodeBase);
  26907. function CircleImageBase(options, body, labelModule) {
  26908. _classCallCheck(this, CircleImageBase);
  26909. var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CircleImageBase).call(this, options, body, labelModule));
  26910. _this.labelOffset = 0;
  26911. _this.imageLoaded = false;
  26912. return _this;
  26913. }
  26914. _createClass(CircleImageBase, [{
  26915. key: 'setOptions',
  26916. value: function setOptions(options, imageObj) {
  26917. this.options = options;
  26918. if (imageObj) {
  26919. this.imageObj = imageObj;
  26920. }
  26921. }
  26922. /**
  26923. * This function resizes the image by the options size when the image has not yet loaded. If the image has loaded, we
  26924. * force the update of the size again.
  26925. *
  26926. * @private
  26927. */
  26928. }, {
  26929. key: '_resizeImage',
  26930. value: function _resizeImage() {
  26931. var force = false;
  26932. if (!this.imageObj.width || !this.imageObj.height) {
  26933. // undefined or 0
  26934. this.imageLoaded = false;
  26935. } else if (this.imageLoaded === false) {
  26936. this.imageLoaded = true;
  26937. force = true;
  26938. }
  26939. if (!this.width || !this.height || force === true) {
  26940. // undefined or 0
  26941. var width, height, ratio;
  26942. if (this.imageObj.width && this.imageObj.height) {
  26943. // not undefined or 0
  26944. width = 0;
  26945. height = 0;
  26946. }
  26947. if (this.options.shapeProperties.useImageSize === false) {
  26948. if (this.imageObj.width > this.imageObj.height) {
  26949. ratio = this.imageObj.width / this.imageObj.height;
  26950. width = this.options.size * 2 * ratio || this.imageObj.width;
  26951. height = this.options.size * 2 || this.imageObj.height;
  26952. } else {
  26953. if (this.imageObj.width && this.imageObj.height) {
  26954. // not undefined or 0
  26955. ratio = this.imageObj.height / this.imageObj.width;
  26956. } else {
  26957. ratio = 1;
  26958. }
  26959. width = this.options.size * 2;
  26960. height = this.options.size * 2 * ratio;
  26961. }
  26962. } else {
  26963. // when not using the size property, we use the image size
  26964. width = this.imageObj.width;
  26965. height = this.imageObj.height;
  26966. }
  26967. this.width = width;
  26968. this.height = height;
  26969. this.radius = 0.5 * this.width;
  26970. }
  26971. }
  26972. }, {
  26973. key: '_drawRawCircle',
  26974. value: function _drawRawCircle(ctx, x, y, selected, hover, size) {
  26975. var neutralborderWidth = this.options.borderWidth;
  26976. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  26977. var borderWidth = (selected ? selectionLineWidth : neutralborderWidth) / this.body.view.scale;
  26978. ctx.lineWidth = Math.min(this.width, borderWidth);
  26979. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  26980. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  26981. ctx.circle(x, y, size);
  26982. // draw shadow if enabled
  26983. this.enableShadow(ctx);
  26984. // draw the background
  26985. ctx.fill();
  26986. // disable shadows for other elements.
  26987. this.disableShadow(ctx);
  26988. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  26989. ctx.save();
  26990. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  26991. if (borderWidth > 0) {
  26992. this.enableBorderDashes(ctx);
  26993. //draw the border
  26994. ctx.stroke();
  26995. //disable dashed border for other elements
  26996. this.disableBorderDashes(ctx);
  26997. }
  26998. ctx.restore();
  26999. }
  27000. }, {
  27001. key: '_drawImageAtPosition',
  27002. value: function _drawImageAtPosition(ctx) {
  27003. if (this.imageObj.width != 0) {
  27004. // draw the image
  27005. ctx.globalAlpha = 1.0;
  27006. // draw shadow if enabled
  27007. this.enableShadow(ctx);
  27008. var factor = this.imageObj.width / this.width / this.body.view.scale;
  27009. if (factor > 2 && this.options.shapeProperties.interpolation === true) {
  27010. var w = this.imageObj.width;
  27011. var h = this.imageObj.height;
  27012. var can2 = document.createElement('canvas');
  27013. can2.width = w;
  27014. can2.height = w;
  27015. var ctx2 = can2.getContext('2d');
  27016. factor *= 0.5;
  27017. w *= 0.5;
  27018. h *= 0.5;
  27019. ctx2.drawImage(this.imageObj, 0, 0, w, h);
  27020. var distance = 0;
  27021. var iterations = 1;
  27022. while (factor > 2 && iterations < 4) {
  27023. ctx2.drawImage(can2, distance, 0, w, h, distance + w, 0, w / 2, h / 2);
  27024. distance += w;
  27025. factor *= 0.5;
  27026. w *= 0.5;
  27027. h *= 0.5;
  27028. iterations += 1;
  27029. }
  27030. ctx.drawImage(can2, distance, 0, w, h, this.left, this.top, this.width, this.height);
  27031. } else {
  27032. // draw image
  27033. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  27034. }
  27035. // disable shadows for other elements.
  27036. this.disableShadow(ctx);
  27037. }
  27038. }
  27039. }, {
  27040. key: '_drawImageLabel',
  27041. value: function _drawImageLabel(ctx, x, y, selected) {
  27042. var yLabel;
  27043. var offset = 0;
  27044. if (this.height !== undefined) {
  27045. offset = this.height * 0.5;
  27046. var labelDimensions = this.labelModule.getTextSize(ctx);
  27047. if (labelDimensions.lineCount >= 1) {
  27048. offset += labelDimensions.height / 2;
  27049. }
  27050. }
  27051. yLabel = y + offset;
  27052. if (this.options.label) {
  27053. this.labelOffset = offset;
  27054. }
  27055. this.labelModule.draw(ctx, x, yLabel, selected, 'hanging');
  27056. }
  27057. }]);
  27058. return CircleImageBase;
  27059. }(_NodeBase3.default);
  27060. exports.default = CircleImageBase;
  27061. /***/ },
  27062. /* 71 */
  27063. /***/ function(module, exports, __webpack_require__) {
  27064. 'use strict';
  27065. Object.defineProperty(exports, "__esModule", {
  27066. value: true
  27067. });
  27068. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27069. var _CircleImageBase2 = __webpack_require__(70);
  27070. var _CircleImageBase3 = _interopRequireDefault(_CircleImageBase2);
  27071. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27072. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27073. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27074. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27075. var CircularImage = function (_CircleImageBase) {
  27076. _inherits(CircularImage, _CircleImageBase);
  27077. function CircularImage(options, body, labelModule, imageObj) {
  27078. _classCallCheck(this, CircularImage);
  27079. var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CircularImage).call(this, options, body, labelModule));
  27080. _this.imageObj = imageObj;
  27081. _this._swapToImageResizeWhenImageLoaded = true;
  27082. return _this;
  27083. }
  27084. _createClass(CircularImage, [{
  27085. key: 'resize',
  27086. value: function resize() {
  27087. if (this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined) {
  27088. if (!this.width) {
  27089. var diameter = this.options.size * 2;
  27090. this.width = diameter;
  27091. this.height = diameter;
  27092. this._swapToImageResizeWhenImageLoaded = true;
  27093. this.radius = 0.5 * this.width;
  27094. }
  27095. } else {
  27096. if (this._swapToImageResizeWhenImageLoaded) {
  27097. this.width = undefined;
  27098. this.height = undefined;
  27099. this._swapToImageResizeWhenImageLoaded = false;
  27100. }
  27101. this._resizeImage();
  27102. }
  27103. }
  27104. }, {
  27105. key: 'draw',
  27106. value: function draw(ctx, x, y, selected, hover) {
  27107. this.resize();
  27108. this.left = x - this.width / 2;
  27109. this.top = y - this.height / 2;
  27110. var size = Math.min(0.5 * this.height, 0.5 * this.width);
  27111. // draw the background circle. IMPORTANT: the stroke in this method is used by the clip method below.
  27112. this._drawRawCircle(ctx, x, y, selected, hover, size);
  27113. // now we draw in the circle, we save so we can revert the clip operation after drawing.
  27114. ctx.save();
  27115. // clip is used to use the stroke in drawRawCircle as an area that we can draw in.
  27116. ctx.clip();
  27117. // draw the image
  27118. this._drawImageAtPosition(ctx);
  27119. // restore so we can again draw on the full canvas
  27120. ctx.restore();
  27121. this._drawImageLabel(ctx, x, y, selected);
  27122. this.updateBoundingBox(x, y);
  27123. }
  27124. }, {
  27125. key: 'updateBoundingBox',
  27126. value: function updateBoundingBox(x, y) {
  27127. this.boundingBox.top = y - this.options.size;
  27128. this.boundingBox.left = x - this.options.size;
  27129. this.boundingBox.right = x + this.options.size;
  27130. this.boundingBox.bottom = y + this.options.size;
  27131. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  27132. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  27133. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelOffset);
  27134. }
  27135. }, {
  27136. key: 'distanceToBorder',
  27137. value: function distanceToBorder(ctx, angle) {
  27138. this.resize(ctx);
  27139. return this.width * 0.5;
  27140. }
  27141. }]);
  27142. return CircularImage;
  27143. }(_CircleImageBase3.default);
  27144. exports.default = CircularImage;
  27145. /***/ },
  27146. /* 72 */
  27147. /***/ function(module, exports, __webpack_require__) {
  27148. 'use strict';
  27149. Object.defineProperty(exports, "__esModule", {
  27150. value: true
  27151. });
  27152. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27153. var _NodeBase2 = __webpack_require__(68);
  27154. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  27155. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27156. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27157. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27158. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27159. var Database = function (_NodeBase) {
  27160. _inherits(Database, _NodeBase);
  27161. function Database(options, body, labelModule) {
  27162. _classCallCheck(this, Database);
  27163. return _possibleConstructorReturn(this, Object.getPrototypeOf(Database).call(this, options, body, labelModule));
  27164. }
  27165. _createClass(Database, [{
  27166. key: 'resize',
  27167. value: function resize(ctx, selected) {
  27168. if (this.width === undefined) {
  27169. var margin = 5;
  27170. var textSize = this.labelModule.getTextSize(ctx, selected);
  27171. var size = textSize.width + 2 * margin;
  27172. this.width = size;
  27173. this.height = size;
  27174. this.radius = 0.5 * this.width;
  27175. }
  27176. }
  27177. }, {
  27178. key: 'draw',
  27179. value: function draw(ctx, x, y, selected, hover) {
  27180. this.resize(ctx, selected);
  27181. this.left = x - this.width / 2;
  27182. this.top = y - this.height / 2;
  27183. var neutralborderWidth = this.options.borderWidth;
  27184. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  27185. var borderWidth = (selected ? selectionLineWidth : neutralborderWidth) / this.body.view.scale;
  27186. ctx.lineWidth = Math.min(this.width, borderWidth);
  27187. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  27188. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  27189. ctx.database(x - this.width / 2, y - this.height * 0.5, this.width, this.height);
  27190. // draw shadow if enabled
  27191. this.enableShadow(ctx);
  27192. // draw the background
  27193. ctx.fill();
  27194. // disable shadows for other elements.
  27195. this.disableShadow(ctx);
  27196. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  27197. ctx.save();
  27198. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  27199. if (borderWidth > 0) {
  27200. this.enableBorderDashes(ctx);
  27201. //draw the border
  27202. ctx.stroke();
  27203. //disable dashed border for other elements
  27204. this.disableBorderDashes(ctx);
  27205. }
  27206. ctx.restore();
  27207. this.updateBoundingBox(x, y, ctx, selected);
  27208. this.labelModule.draw(ctx, x, y, selected);
  27209. }
  27210. }, {
  27211. key: 'updateBoundingBox',
  27212. value: function updateBoundingBox(x, y, ctx, selected) {
  27213. this.resize(ctx, selected);
  27214. this.left = x - this.width * 0.5;
  27215. this.top = y - this.height * 0.5;
  27216. this.boundingBox.left = this.left;
  27217. this.boundingBox.top = this.top;
  27218. this.boundingBox.bottom = this.top + this.height;
  27219. this.boundingBox.right = this.left + this.width;
  27220. }
  27221. }, {
  27222. key: 'distanceToBorder',
  27223. value: function distanceToBorder(ctx, angle) {
  27224. return this._distanceToBorder(ctx, angle);
  27225. }
  27226. }]);
  27227. return Database;
  27228. }(_NodeBase3.default);
  27229. exports.default = Database;
  27230. /***/ },
  27231. /* 73 */
  27232. /***/ function(module, exports, __webpack_require__) {
  27233. 'use strict';
  27234. Object.defineProperty(exports, "__esModule", {
  27235. value: true
  27236. });
  27237. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27238. var _ShapeBase2 = __webpack_require__(74);
  27239. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  27240. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27241. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27242. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27243. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27244. var Diamond = function (_ShapeBase) {
  27245. _inherits(Diamond, _ShapeBase);
  27246. function Diamond(options, body, labelModule) {
  27247. _classCallCheck(this, Diamond);
  27248. return _possibleConstructorReturn(this, Object.getPrototypeOf(Diamond).call(this, options, body, labelModule));
  27249. }
  27250. _createClass(Diamond, [{
  27251. key: 'resize',
  27252. value: function resize(ctx) {
  27253. this._resizeShape();
  27254. }
  27255. }, {
  27256. key: 'draw',
  27257. value: function draw(ctx, x, y, selected, hover) {
  27258. this._drawShape(ctx, 'diamond', 4, x, y, selected, hover);
  27259. }
  27260. }, {
  27261. key: 'distanceToBorder',
  27262. value: function distanceToBorder(ctx, angle) {
  27263. return this._distanceToBorder(ctx, angle);
  27264. }
  27265. }]);
  27266. return Diamond;
  27267. }(_ShapeBase3.default);
  27268. exports.default = Diamond;
  27269. /***/ },
  27270. /* 74 */
  27271. /***/ function(module, exports, __webpack_require__) {
  27272. 'use strict';
  27273. Object.defineProperty(exports, "__esModule", {
  27274. value: true
  27275. });
  27276. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27277. var _NodeBase2 = __webpack_require__(68);
  27278. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  27279. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27280. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27281. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27282. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27283. var ShapeBase = function (_NodeBase) {
  27284. _inherits(ShapeBase, _NodeBase);
  27285. function ShapeBase(options, body, labelModule) {
  27286. _classCallCheck(this, ShapeBase);
  27287. return _possibleConstructorReturn(this, Object.getPrototypeOf(ShapeBase).call(this, options, body, labelModule));
  27288. }
  27289. _createClass(ShapeBase, [{
  27290. key: '_resizeShape',
  27291. value: function _resizeShape() {
  27292. if (this.width === undefined) {
  27293. var size = 2 * this.options.size;
  27294. this.width = size;
  27295. this.height = size;
  27296. this.radius = 0.5 * this.width;
  27297. }
  27298. }
  27299. }, {
  27300. key: '_drawShape',
  27301. value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover) {
  27302. this._resizeShape();
  27303. this.left = x - this.width / 2;
  27304. this.top = y - this.height / 2;
  27305. var neutralborderWidth = this.options.borderWidth;
  27306. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  27307. var borderWidth = (selected ? selectionLineWidth : neutralborderWidth) / this.body.view.scale;
  27308. ctx.lineWidth = Math.min(this.width, borderWidth);
  27309. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  27310. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  27311. ctx[shape](x, y, this.options.size);
  27312. // draw shadow if enabled
  27313. this.enableShadow(ctx);
  27314. // draw the background
  27315. ctx.fill();
  27316. // disable shadows for other elements.
  27317. this.disableShadow(ctx);
  27318. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  27319. ctx.save();
  27320. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  27321. if (borderWidth > 0) {
  27322. this.enableBorderDashes(ctx);
  27323. //draw the border
  27324. ctx.stroke();
  27325. //disable dashed border for other elements
  27326. this.disableBorderDashes(ctx);
  27327. }
  27328. ctx.restore();
  27329. if (this.options.label !== undefined) {
  27330. var yLabel = y + 0.5 * this.height + 3; // the + 3 is to offset it a bit below the node.
  27331. this.labelModule.draw(ctx, x, yLabel, selected, 'hanging');
  27332. }
  27333. this.updateBoundingBox(x, y);
  27334. }
  27335. }, {
  27336. key: 'updateBoundingBox',
  27337. value: function updateBoundingBox(x, y) {
  27338. this.boundingBox.top = y - this.options.size;
  27339. this.boundingBox.left = x - this.options.size;
  27340. this.boundingBox.right = x + this.options.size;
  27341. this.boundingBox.bottom = y + this.options.size;
  27342. if (this.options.label !== undefined && this.labelModule.size.width > 0) {
  27343. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  27344. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  27345. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height + 3);
  27346. }
  27347. }
  27348. }]);
  27349. return ShapeBase;
  27350. }(_NodeBase3.default);
  27351. exports.default = ShapeBase;
  27352. /***/ },
  27353. /* 75 */
  27354. /***/ function(module, exports, __webpack_require__) {
  27355. 'use strict';
  27356. Object.defineProperty(exports, "__esModule", {
  27357. value: true
  27358. });
  27359. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27360. var _ShapeBase2 = __webpack_require__(74);
  27361. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  27362. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27363. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27364. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27365. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27366. var Dot = function (_ShapeBase) {
  27367. _inherits(Dot, _ShapeBase);
  27368. function Dot(options, body, labelModule) {
  27369. _classCallCheck(this, Dot);
  27370. return _possibleConstructorReturn(this, Object.getPrototypeOf(Dot).call(this, options, body, labelModule));
  27371. }
  27372. _createClass(Dot, [{
  27373. key: 'resize',
  27374. value: function resize(ctx) {
  27375. this._resizeShape();
  27376. }
  27377. }, {
  27378. key: 'draw',
  27379. value: function draw(ctx, x, y, selected, hover) {
  27380. this._drawShape(ctx, 'circle', 2, x, y, selected, hover);
  27381. }
  27382. }, {
  27383. key: 'distanceToBorder',
  27384. value: function distanceToBorder(ctx, angle) {
  27385. this.resize(ctx);
  27386. return this.options.size;
  27387. }
  27388. }]);
  27389. return Dot;
  27390. }(_ShapeBase3.default);
  27391. exports.default = Dot;
  27392. /***/ },
  27393. /* 76 */
  27394. /***/ function(module, exports, __webpack_require__) {
  27395. 'use strict';
  27396. Object.defineProperty(exports, "__esModule", {
  27397. value: true
  27398. });
  27399. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27400. var _NodeBase2 = __webpack_require__(68);
  27401. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  27402. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27403. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27404. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27405. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27406. var Ellipse = function (_NodeBase) {
  27407. _inherits(Ellipse, _NodeBase);
  27408. function Ellipse(options, body, labelModule) {
  27409. _classCallCheck(this, Ellipse);
  27410. return _possibleConstructorReturn(this, Object.getPrototypeOf(Ellipse).call(this, options, body, labelModule));
  27411. }
  27412. _createClass(Ellipse, [{
  27413. key: 'resize',
  27414. value: function resize(ctx, selected) {
  27415. if (this.width === undefined) {
  27416. var textSize = this.labelModule.getTextSize(ctx, selected);
  27417. this.width = textSize.width * 1.5;
  27418. this.height = textSize.height * 2;
  27419. if (this.width < this.height) {
  27420. this.width = this.height;
  27421. }
  27422. this.radius = 0.5 * this.width;
  27423. }
  27424. }
  27425. }, {
  27426. key: 'draw',
  27427. value: function draw(ctx, x, y, selected, hover) {
  27428. this.resize(ctx, selected);
  27429. this.left = x - this.width * 0.5;
  27430. this.top = y - this.height * 0.5;
  27431. var neutralborderWidth = this.options.borderWidth;
  27432. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  27433. var borderWidth = (selected ? selectionLineWidth : neutralborderWidth) / this.body.view.scale;
  27434. ctx.lineWidth = Math.min(this.width, borderWidth);
  27435. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  27436. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  27437. ctx.ellipse(this.left, this.top, this.width, this.height);
  27438. // draw shadow if enabled
  27439. this.enableShadow(ctx);
  27440. // draw the background
  27441. ctx.fill();
  27442. // disable shadows for other elements.
  27443. this.disableShadow(ctx);
  27444. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  27445. ctx.save();
  27446. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  27447. if (borderWidth > 0) {
  27448. this.enableBorderDashes(ctx);
  27449. //draw the border
  27450. ctx.stroke();
  27451. //disable dashed border for other elements
  27452. this.disableBorderDashes(ctx);
  27453. }
  27454. ctx.restore();
  27455. this.updateBoundingBox(x, y, ctx, selected);
  27456. this.labelModule.draw(ctx, x, y, selected);
  27457. }
  27458. }, {
  27459. key: 'updateBoundingBox',
  27460. value: function updateBoundingBox(x, y, ctx, selected) {
  27461. this.resize(ctx, selected); // just in case
  27462. this.left = x - this.width * 0.5;
  27463. this.top = y - this.height * 0.5;
  27464. this.boundingBox.left = this.left;
  27465. this.boundingBox.top = this.top;
  27466. this.boundingBox.bottom = this.top + this.height;
  27467. this.boundingBox.right = this.left + this.width;
  27468. }
  27469. }, {
  27470. key: 'distanceToBorder',
  27471. value: function distanceToBorder(ctx, angle) {
  27472. this.resize(ctx);
  27473. var a = this.width * 0.5;
  27474. var b = this.height * 0.5;
  27475. var w = Math.sin(angle) * a;
  27476. var h = Math.cos(angle) * b;
  27477. return a * b / Math.sqrt(w * w + h * h);
  27478. }
  27479. }]);
  27480. return Ellipse;
  27481. }(_NodeBase3.default);
  27482. exports.default = Ellipse;
  27483. /***/ },
  27484. /* 77 */
  27485. /***/ function(module, exports, __webpack_require__) {
  27486. 'use strict';
  27487. Object.defineProperty(exports, "__esModule", {
  27488. value: true
  27489. });
  27490. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27491. var _NodeBase2 = __webpack_require__(68);
  27492. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  27493. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27494. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27495. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27496. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27497. var Icon = function (_NodeBase) {
  27498. _inherits(Icon, _NodeBase);
  27499. function Icon(options, body, labelModule) {
  27500. _classCallCheck(this, Icon);
  27501. return _possibleConstructorReturn(this, Object.getPrototypeOf(Icon).call(this, options, body, labelModule));
  27502. }
  27503. _createClass(Icon, [{
  27504. key: 'resize',
  27505. value: function resize(ctx) {
  27506. if (this.width === undefined) {
  27507. var margin = 5;
  27508. var iconSize = {
  27509. width: Number(this.options.icon.size),
  27510. height: Number(this.options.icon.size)
  27511. };
  27512. this.width = iconSize.width + 2 * margin;
  27513. this.height = iconSize.height + 2 * margin;
  27514. this.radius = 0.5 * this.width;
  27515. }
  27516. }
  27517. }, {
  27518. key: 'draw',
  27519. value: function draw(ctx, x, y, selected, hover) {
  27520. this.resize(ctx);
  27521. this.options.icon.size = this.options.icon.size || 50;
  27522. this.left = x - this.width * 0.5;
  27523. this.top = y - this.height * 0.5;
  27524. this._icon(ctx, x, y, selected);
  27525. if (this.options.label !== undefined) {
  27526. var iconTextSpacing = 5;
  27527. this.labelModule.draw(ctx, x, y + this.height * 0.5 + iconTextSpacing, selected);
  27528. }
  27529. this.updateBoundingBox(x, y);
  27530. }
  27531. }, {
  27532. key: 'updateBoundingBox',
  27533. value: function updateBoundingBox(x, y) {
  27534. this.boundingBox.top = y - this.options.icon.size * 0.5;
  27535. this.boundingBox.left = x - this.options.icon.size * 0.5;
  27536. this.boundingBox.right = x + this.options.icon.size * 0.5;
  27537. this.boundingBox.bottom = y + this.options.icon.size * 0.5;
  27538. if (this.options.label !== undefined && this.labelModule.size.width > 0) {
  27539. var iconTextSpacing = 5;
  27540. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  27541. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  27542. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height + iconTextSpacing);
  27543. }
  27544. }
  27545. }, {
  27546. key: '_icon',
  27547. value: function _icon(ctx, x, y, selected) {
  27548. var iconSize = Number(this.options.icon.size);
  27549. if (this.options.icon.code !== undefined) {
  27550. ctx.font = (selected ? "bold " : "") + iconSize + "px " + this.options.icon.face;
  27551. // draw icon
  27552. ctx.fillStyle = this.options.icon.color || "black";
  27553. ctx.textAlign = "center";
  27554. ctx.textBaseline = "middle";
  27555. // draw shadow if enabled
  27556. this.enableShadow(ctx);
  27557. ctx.fillText(this.options.icon.code, x, y);
  27558. // disable shadows for other elements.
  27559. this.disableShadow(ctx);
  27560. } else {
  27561. console.error('When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.');
  27562. }
  27563. }
  27564. }, {
  27565. key: 'distanceToBorder',
  27566. value: function distanceToBorder(ctx, angle) {
  27567. return this._distanceToBorder(ctx, angle);
  27568. }
  27569. }]);
  27570. return Icon;
  27571. }(_NodeBase3.default);
  27572. exports.default = Icon;
  27573. /***/ },
  27574. /* 78 */
  27575. /***/ function(module, exports, __webpack_require__) {
  27576. 'use strict';
  27577. Object.defineProperty(exports, "__esModule", {
  27578. value: true
  27579. });
  27580. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27581. var _CircleImageBase2 = __webpack_require__(70);
  27582. var _CircleImageBase3 = _interopRequireDefault(_CircleImageBase2);
  27583. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27584. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27585. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27586. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27587. var Image = function (_CircleImageBase) {
  27588. _inherits(Image, _CircleImageBase);
  27589. function Image(options, body, labelModule, imageObj) {
  27590. _classCallCheck(this, Image);
  27591. var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Image).call(this, options, body, labelModule));
  27592. _this.imageObj = imageObj;
  27593. return _this;
  27594. }
  27595. _createClass(Image, [{
  27596. key: 'resize',
  27597. value: function resize() {
  27598. this._resizeImage();
  27599. }
  27600. }, {
  27601. key: 'draw',
  27602. value: function draw(ctx, x, y, selected, hover) {
  27603. this.resize();
  27604. this.left = x - this.width / 2;
  27605. this.top = y - this.height / 2;
  27606. if (this.options.shapeProperties.useBorderWithImage === true) {
  27607. var neutralborderWidth = this.options.borderWidth;
  27608. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  27609. var borderWidth = (selected ? selectionLineWidth : neutralborderWidth) / this.body.view.scale;
  27610. ctx.lineWidth = Math.min(this.width, borderWidth);
  27611. ctx.beginPath();
  27612. // setup the line properties.
  27613. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  27614. // set a fillstyle
  27615. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  27616. // draw a rectangle to form the border around. This rectangle is filled so the opacity of a picture (in future vis releases?) can be used to tint the image
  27617. ctx.rect(this.left - 0.5 * ctx.lineWidth, this.top - 0.5 * ctx.lineWidth, this.width + ctx.lineWidth, this.height + ctx.lineWidth);
  27618. ctx.fill();
  27619. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  27620. ctx.save();
  27621. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  27622. if (borderWidth > 0) {
  27623. this.enableBorderDashes(ctx);
  27624. //draw the border
  27625. ctx.stroke();
  27626. //disable dashed border for other elements
  27627. this.disableBorderDashes(ctx);
  27628. }
  27629. ctx.restore();
  27630. ctx.closePath();
  27631. }
  27632. this._drawImageAtPosition(ctx);
  27633. this._drawImageLabel(ctx, x, y, selected || hover);
  27634. this.updateBoundingBox(x, y);
  27635. }
  27636. }, {
  27637. key: 'updateBoundingBox',
  27638. value: function updateBoundingBox(x, y) {
  27639. this.resize();
  27640. this.left = x - this.width / 2;
  27641. this.top = y - this.height / 2;
  27642. this.boundingBox.top = this.top;
  27643. this.boundingBox.left = this.left;
  27644. this.boundingBox.right = this.left + this.width;
  27645. this.boundingBox.bottom = this.top + this.height;
  27646. if (this.options.label !== undefined && this.labelModule.size.width > 0) {
  27647. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  27648. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  27649. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelOffset);
  27650. }
  27651. }
  27652. }, {
  27653. key: 'distanceToBorder',
  27654. value: function distanceToBorder(ctx, angle) {
  27655. return this._distanceToBorder(ctx, angle);
  27656. }
  27657. }]);
  27658. return Image;
  27659. }(_CircleImageBase3.default);
  27660. exports.default = Image;
  27661. /***/ },
  27662. /* 79 */
  27663. /***/ function(module, exports, __webpack_require__) {
  27664. 'use strict';
  27665. Object.defineProperty(exports, "__esModule", {
  27666. value: true
  27667. });
  27668. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27669. var _ShapeBase2 = __webpack_require__(74);
  27670. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  27671. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27672. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27673. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27674. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27675. var Square = function (_ShapeBase) {
  27676. _inherits(Square, _ShapeBase);
  27677. function Square(options, body, labelModule) {
  27678. _classCallCheck(this, Square);
  27679. return _possibleConstructorReturn(this, Object.getPrototypeOf(Square).call(this, options, body, labelModule));
  27680. }
  27681. _createClass(Square, [{
  27682. key: 'resize',
  27683. value: function resize() {
  27684. this._resizeShape();
  27685. }
  27686. }, {
  27687. key: 'draw',
  27688. value: function draw(ctx, x, y, selected, hover) {
  27689. this._drawShape(ctx, 'square', 2, x, y, selected, hover);
  27690. }
  27691. }, {
  27692. key: 'distanceToBorder',
  27693. value: function distanceToBorder(ctx, angle) {
  27694. return this._distanceToBorder(ctx, angle);
  27695. }
  27696. }]);
  27697. return Square;
  27698. }(_ShapeBase3.default);
  27699. exports.default = Square;
  27700. /***/ },
  27701. /* 80 */
  27702. /***/ function(module, exports, __webpack_require__) {
  27703. 'use strict';
  27704. Object.defineProperty(exports, "__esModule", {
  27705. value: true
  27706. });
  27707. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27708. var _ShapeBase2 = __webpack_require__(74);
  27709. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  27710. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27711. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27712. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27713. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27714. var Star = function (_ShapeBase) {
  27715. _inherits(Star, _ShapeBase);
  27716. function Star(options, body, labelModule) {
  27717. _classCallCheck(this, Star);
  27718. return _possibleConstructorReturn(this, Object.getPrototypeOf(Star).call(this, options, body, labelModule));
  27719. }
  27720. _createClass(Star, [{
  27721. key: 'resize',
  27722. value: function resize(ctx) {
  27723. this._resizeShape();
  27724. }
  27725. }, {
  27726. key: 'draw',
  27727. value: function draw(ctx, x, y, selected, hover) {
  27728. this._drawShape(ctx, 'star', 4, x, y, selected, hover);
  27729. }
  27730. }, {
  27731. key: 'distanceToBorder',
  27732. value: function distanceToBorder(ctx, angle) {
  27733. return this._distanceToBorder(ctx, angle);
  27734. }
  27735. }]);
  27736. return Star;
  27737. }(_ShapeBase3.default);
  27738. exports.default = Star;
  27739. /***/ },
  27740. /* 81 */
  27741. /***/ function(module, exports, __webpack_require__) {
  27742. 'use strict';
  27743. Object.defineProperty(exports, "__esModule", {
  27744. value: true
  27745. });
  27746. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27747. var _NodeBase2 = __webpack_require__(68);
  27748. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  27749. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27750. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27751. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27752. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27753. var Text = function (_NodeBase) {
  27754. _inherits(Text, _NodeBase);
  27755. function Text(options, body, labelModule) {
  27756. _classCallCheck(this, Text);
  27757. return _possibleConstructorReturn(this, Object.getPrototypeOf(Text).call(this, options, body, labelModule));
  27758. }
  27759. _createClass(Text, [{
  27760. key: 'resize',
  27761. value: function resize(ctx, selected) {
  27762. if (this.width === undefined) {
  27763. var margin = 5;
  27764. var textSize = this.labelModule.getTextSize(ctx, selected);
  27765. this.width = textSize.width + 2 * margin;
  27766. this.height = textSize.height + 2 * margin;
  27767. this.radius = 0.5 * this.width;
  27768. }
  27769. }
  27770. }, {
  27771. key: 'draw',
  27772. value: function draw(ctx, x, y, selected, hover) {
  27773. this.resize(ctx, selected || hover);
  27774. this.left = x - this.width / 2;
  27775. this.top = y - this.height / 2;
  27776. // draw shadow if enabled
  27777. this.enableShadow(ctx);
  27778. this.labelModule.draw(ctx, x, y, selected || hover);
  27779. // disable shadows for other elements.
  27780. this.disableShadow(ctx);
  27781. this.updateBoundingBox(x, y, ctx, selected);
  27782. }
  27783. }, {
  27784. key: 'updateBoundingBox',
  27785. value: function updateBoundingBox(x, y, ctx, selected) {
  27786. this.resize(ctx, selected);
  27787. this.left = x - this.width / 2;
  27788. this.top = y - this.height / 2;
  27789. this.boundingBox.top = this.top;
  27790. this.boundingBox.left = this.left;
  27791. this.boundingBox.right = this.left + this.width;
  27792. this.boundingBox.bottom = this.top + this.height;
  27793. }
  27794. }, {
  27795. key: 'distanceToBorder',
  27796. value: function distanceToBorder(ctx, angle) {
  27797. return this._distanceToBorder(ctx, angle);
  27798. }
  27799. }]);
  27800. return Text;
  27801. }(_NodeBase3.default);
  27802. exports.default = Text;
  27803. /***/ },
  27804. /* 82 */
  27805. /***/ function(module, exports, __webpack_require__) {
  27806. 'use strict';
  27807. Object.defineProperty(exports, "__esModule", {
  27808. value: true
  27809. });
  27810. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27811. var _ShapeBase2 = __webpack_require__(74);
  27812. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  27813. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27814. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27815. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27816. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27817. var Triangle = function (_ShapeBase) {
  27818. _inherits(Triangle, _ShapeBase);
  27819. function Triangle(options, body, labelModule) {
  27820. _classCallCheck(this, Triangle);
  27821. return _possibleConstructorReturn(this, Object.getPrototypeOf(Triangle).call(this, options, body, labelModule));
  27822. }
  27823. _createClass(Triangle, [{
  27824. key: 'resize',
  27825. value: function resize(ctx) {
  27826. this._resizeShape();
  27827. }
  27828. }, {
  27829. key: 'draw',
  27830. value: function draw(ctx, x, y, selected, hover) {
  27831. this._drawShape(ctx, 'triangle', 3, x, y, selected, hover);
  27832. }
  27833. }, {
  27834. key: 'distanceToBorder',
  27835. value: function distanceToBorder(ctx, angle) {
  27836. return this._distanceToBorder(ctx, angle);
  27837. }
  27838. }]);
  27839. return Triangle;
  27840. }(_ShapeBase3.default);
  27841. exports.default = Triangle;
  27842. /***/ },
  27843. /* 83 */
  27844. /***/ function(module, exports, __webpack_require__) {
  27845. 'use strict';
  27846. Object.defineProperty(exports, "__esModule", {
  27847. value: true
  27848. });
  27849. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27850. var _ShapeBase2 = __webpack_require__(74);
  27851. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  27852. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27853. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27854. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  27855. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  27856. var TriangleDown = function (_ShapeBase) {
  27857. _inherits(TriangleDown, _ShapeBase);
  27858. function TriangleDown(options, body, labelModule) {
  27859. _classCallCheck(this, TriangleDown);
  27860. return _possibleConstructorReturn(this, Object.getPrototypeOf(TriangleDown).call(this, options, body, labelModule));
  27861. }
  27862. _createClass(TriangleDown, [{
  27863. key: 'resize',
  27864. value: function resize(ctx) {
  27865. this._resizeShape();
  27866. }
  27867. }, {
  27868. key: 'draw',
  27869. value: function draw(ctx, x, y, selected, hover) {
  27870. this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover);
  27871. }
  27872. }, {
  27873. key: 'distanceToBorder',
  27874. value: function distanceToBorder(ctx, angle) {
  27875. return this._distanceToBorder(ctx, angle);
  27876. }
  27877. }]);
  27878. return TriangleDown;
  27879. }(_ShapeBase3.default);
  27880. exports.default = TriangleDown;
  27881. /***/ },
  27882. /* 84 */
  27883. /***/ function(module, exports, __webpack_require__) {
  27884. 'use strict';
  27885. Object.defineProperty(exports, "__esModule", {
  27886. value: true
  27887. });
  27888. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  27889. var _Edge = __webpack_require__(85);
  27890. var _Edge2 = _interopRequireDefault(_Edge);
  27891. var _Label = __webpack_require__(66);
  27892. var _Label2 = _interopRequireDefault(_Label);
  27893. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27894. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27895. var util = __webpack_require__(1);
  27896. var DataSet = __webpack_require__(9);
  27897. var DataView = __webpack_require__(11);
  27898. var EdgesHandler = function () {
  27899. function EdgesHandler(body, images, groups) {
  27900. var _this = this;
  27901. _classCallCheck(this, EdgesHandler);
  27902. this.body = body;
  27903. this.images = images;
  27904. this.groups = groups;
  27905. // create the edge API in the body container
  27906. this.body.functions.createEdge = this.create.bind(this);
  27907. this.edgesListeners = {
  27908. add: function add(event, params) {
  27909. _this.add(params.items);
  27910. },
  27911. update: function update(event, params) {
  27912. _this.update(params.items);
  27913. },
  27914. remove: function remove(event, params) {
  27915. _this.remove(params.items);
  27916. }
  27917. };
  27918. this.options = {};
  27919. this.defaultOptions = {
  27920. arrows: {
  27921. to: { enabled: false, scaleFactor: 1 }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1}
  27922. middle: { enabled: false, scaleFactor: 1 },
  27923. from: { enabled: false, scaleFactor: 1 }
  27924. },
  27925. arrowStrikethrough: true,
  27926. color: {
  27927. color: '#848484',
  27928. highlight: '#848484',
  27929. hover: '#848484',
  27930. inherit: 'from',
  27931. opacity: 1.0
  27932. },
  27933. dashes: false,
  27934. font: {
  27935. color: '#343434',
  27936. size: 14, // px
  27937. face: 'arial',
  27938. background: 'none',
  27939. strokeWidth: 2, // px
  27940. strokeColor: '#ffffff',
  27941. align: 'horizontal'
  27942. },
  27943. hidden: false,
  27944. hoverWidth: 1.5,
  27945. label: undefined,
  27946. labelHighlightBold: true,
  27947. length: undefined,
  27948. physics: true,
  27949. scaling: {
  27950. min: 1,
  27951. max: 15,
  27952. label: {
  27953. enabled: true,
  27954. min: 14,
  27955. max: 30,
  27956. maxVisible: 30,
  27957. drawThreshold: 5
  27958. },
  27959. customScalingFunction: function customScalingFunction(min, max, total, value) {
  27960. if (max === min) {
  27961. return 0.5;
  27962. } else {
  27963. var scale = 1 / (max - min);
  27964. return Math.max(0, (value - min) * scale);
  27965. }
  27966. }
  27967. },
  27968. selectionWidth: 1.5,
  27969. selfReferenceSize: 20,
  27970. shadow: {
  27971. enabled: false,
  27972. color: 'rgba(0,0,0,0.5)',
  27973. size: 10,
  27974. x: 5,
  27975. y: 5
  27976. },
  27977. smooth: {
  27978. enabled: true,
  27979. type: "dynamic",
  27980. forceDirection: 'none',
  27981. roundness: 0.5
  27982. },
  27983. title: undefined,
  27984. width: 1,
  27985. value: undefined
  27986. };
  27987. util.extend(this.options, this.defaultOptions);
  27988. this.bindEventListeners();
  27989. }
  27990. _createClass(EdgesHandler, [{
  27991. key: 'bindEventListeners',
  27992. value: function bindEventListeners() {
  27993. var _this2 = this;
  27994. // this allows external modules to force all dynamic curves to turn static.
  27995. this.body.emitter.on("_forceDisableDynamicCurves", function (type) {
  27996. if (type === 'dynamic') {
  27997. type = 'continuous';
  27998. }
  27999. var emitChange = false;
  28000. for (var edgeId in _this2.body.edges) {
  28001. if (_this2.body.edges.hasOwnProperty(edgeId)) {
  28002. var edge = _this2.body.edges[edgeId];
  28003. var edgeData = _this2.body.data.edges._data[edgeId];
  28004. // only forcibly remove the smooth curve if the data has been set of the edge has the smooth curves defined.
  28005. // this is because a change in the global would not affect these curves.
  28006. if (edgeData !== undefined) {
  28007. var edgeOptions = edgeData.smooth;
  28008. if (edgeOptions !== undefined) {
  28009. if (edgeOptions.enabled === true && edgeOptions.type === 'dynamic') {
  28010. if (type === undefined) {
  28011. edge.setOptions({ smooth: false });
  28012. } else {
  28013. edge.setOptions({ smooth: { type: type } });
  28014. }
  28015. emitChange = true;
  28016. }
  28017. }
  28018. }
  28019. }
  28020. }
  28021. if (emitChange === true) {
  28022. _this2.body.emitter.emit("_dataChanged");
  28023. }
  28024. });
  28025. // this is called when options of EXISTING nodes or edges have changed.
  28026. this.body.emitter.on("_dataUpdated", function () {
  28027. _this2.reconnectEdges();
  28028. _this2.markAllEdgesAsDirty();
  28029. });
  28030. // refresh the edges. Used when reverting from hierarchical layout
  28031. this.body.emitter.on("refreshEdges", this.refresh.bind(this));
  28032. this.body.emitter.on("refresh", this.refresh.bind(this));
  28033. this.body.emitter.on("destroy", function () {
  28034. util.forEach(_this2.edgesListeners, function (callback, event) {
  28035. if (_this2.body.data.edges) _this2.body.data.edges.off(event, callback);
  28036. });
  28037. delete _this2.body.functions.createEdge;
  28038. delete _this2.edgesListeners.add;
  28039. delete _this2.edgesListeners.update;
  28040. delete _this2.edgesListeners.remove;
  28041. delete _this2.edgesListeners;
  28042. });
  28043. }
  28044. }, {
  28045. key: 'setOptions',
  28046. value: function setOptions(options) {
  28047. if (options !== undefined) {
  28048. // use the parser from the Edge class to fill in all shorthand notations
  28049. _Edge2.default.parseOptions(this.options, options);
  28050. // handle multiple input cases for color
  28051. if (options.color !== undefined) {
  28052. this.markAllEdgesAsDirty();
  28053. }
  28054. // update smooth settings in all edges
  28055. var dataChanged = false;
  28056. if (options.smooth !== undefined) {
  28057. for (var edgeId in this.body.edges) {
  28058. if (this.body.edges.hasOwnProperty(edgeId)) {
  28059. dataChanged = this.body.edges[edgeId].updateEdgeType() || dataChanged;
  28060. }
  28061. }
  28062. }
  28063. // update fonts in all edges
  28064. if (options.font !== undefined) {
  28065. // use the parser from the Label class to fill in all shorthand notations
  28066. _Label2.default.parseOptions(this.options.font, options);
  28067. for (var _edgeId in this.body.edges) {
  28068. if (this.body.edges.hasOwnProperty(_edgeId)) {
  28069. this.body.edges[_edgeId].updateLabelModule();
  28070. }
  28071. }
  28072. }
  28073. // update the state of the variables if needed
  28074. if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) {
  28075. this.body.emitter.emit('_dataChanged');
  28076. }
  28077. }
  28078. }
  28079. /**
  28080. * Load edges by reading the data table
  28081. * @param {Array | DataSet | DataView} edges The data containing the edges.
  28082. * @private
  28083. * @private
  28084. */
  28085. }, {
  28086. key: 'setData',
  28087. value: function setData(edges) {
  28088. var _this3 = this;
  28089. var doNotEmit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  28090. var oldEdgesData = this.body.data.edges;
  28091. if (edges instanceof DataSet || edges instanceof DataView) {
  28092. this.body.data.edges = edges;
  28093. } else if (Array.isArray(edges)) {
  28094. this.body.data.edges = new DataSet();
  28095. this.body.data.edges.add(edges);
  28096. } else if (!edges) {
  28097. this.body.data.edges = new DataSet();
  28098. } else {
  28099. throw new TypeError('Array or DataSet expected');
  28100. }
  28101. // TODO: is this null or undefined or false?
  28102. if (oldEdgesData) {
  28103. // unsubscribe from old dataset
  28104. util.forEach(this.edgesListeners, function (callback, event) {
  28105. oldEdgesData.off(event, callback);
  28106. });
  28107. }
  28108. // remove drawn edges
  28109. this.body.edges = {};
  28110. // TODO: is this null or undefined or false?
  28111. if (this.body.data.edges) {
  28112. // subscribe to new dataset
  28113. util.forEach(this.edgesListeners, function (callback, event) {
  28114. _this3.body.data.edges.on(event, callback);
  28115. });
  28116. // draw all new nodes
  28117. var ids = this.body.data.edges.getIds();
  28118. this.add(ids, true);
  28119. }
  28120. if (doNotEmit === false) {
  28121. this.body.emitter.emit("_dataChanged");
  28122. }
  28123. }
  28124. /**
  28125. * Add edges
  28126. * @param {Number[] | String[]} ids
  28127. * @private
  28128. */
  28129. }, {
  28130. key: 'add',
  28131. value: function add(ids) {
  28132. var doNotEmit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  28133. var edges = this.body.edges;
  28134. var edgesData = this.body.data.edges;
  28135. for (var i = 0; i < ids.length; i++) {
  28136. var id = ids[i];
  28137. var oldEdge = edges[id];
  28138. if (oldEdge) {
  28139. oldEdge.disconnect();
  28140. }
  28141. var data = edgesData.get(id, { "showInternalIds": true });
  28142. edges[id] = this.create(data);
  28143. }
  28144. if (doNotEmit === false) {
  28145. this.body.emitter.emit("_dataChanged");
  28146. }
  28147. }
  28148. /**
  28149. * Update existing edges, or create them when not yet existing
  28150. * @param {Number[] | String[]} ids
  28151. * @private
  28152. */
  28153. }, {
  28154. key: 'update',
  28155. value: function update(ids) {
  28156. var edges = this.body.edges;
  28157. var edgesData = this.body.data.edges;
  28158. var dataChanged = false;
  28159. for (var i = 0; i < ids.length; i++) {
  28160. var id = ids[i];
  28161. var data = edgesData.get(id);
  28162. var edge = edges[id];
  28163. if (edge !== undefined) {
  28164. // update edge
  28165. edge.disconnect();
  28166. dataChanged = edge.setOptions(data) || dataChanged; // if a support node is added, data can be changed.
  28167. edge.connect();
  28168. } else {
  28169. // create edge
  28170. this.body.edges[id] = this.create(data);
  28171. dataChanged = true;
  28172. }
  28173. }
  28174. if (dataChanged === true) {
  28175. this.body.emitter.emit("_dataChanged");
  28176. } else {
  28177. this.body.emitter.emit("_dataUpdated");
  28178. }
  28179. }
  28180. /**
  28181. * Remove existing edges. Non existing ids will be ignored
  28182. * @param {Number[] | String[]} ids
  28183. * @private
  28184. */
  28185. }, {
  28186. key: 'remove',
  28187. value: function remove(ids) {
  28188. var edges = this.body.edges;
  28189. for (var i = 0; i < ids.length; i++) {
  28190. var id = ids[i];
  28191. var edge = edges[id];
  28192. if (edge !== undefined) {
  28193. edge.cleanup();
  28194. edge.disconnect();
  28195. delete edges[id];
  28196. }
  28197. }
  28198. this.body.emitter.emit("_dataChanged");
  28199. }
  28200. }, {
  28201. key: 'refresh',
  28202. value: function refresh() {
  28203. var edges = this.body.edges;
  28204. for (var edgeId in edges) {
  28205. var edge = undefined;
  28206. if (edges.hasOwnProperty(edgeId)) {
  28207. edge = edges[edgeId];
  28208. }
  28209. var data = this.body.data.edges._data[edgeId];
  28210. if (edge !== undefined && data !== undefined) {
  28211. edge.setOptions(data);
  28212. }
  28213. }
  28214. }
  28215. }, {
  28216. key: 'create',
  28217. value: function create(properties) {
  28218. return new _Edge2.default(properties, this.body, this.options);
  28219. }
  28220. }, {
  28221. key: 'markAllEdgesAsDirty',
  28222. value: function markAllEdgesAsDirty() {
  28223. for (var edgeId in this.body.edges) {
  28224. this.body.edges[edgeId].edgeType.colorDirty = true;
  28225. }
  28226. }
  28227. /**
  28228. * Reconnect all edges
  28229. * @private
  28230. */
  28231. }, {
  28232. key: 'reconnectEdges',
  28233. value: function reconnectEdges() {
  28234. var id;
  28235. var nodes = this.body.nodes;
  28236. var edges = this.body.edges;
  28237. for (id in nodes) {
  28238. if (nodes.hasOwnProperty(id)) {
  28239. nodes[id].edges = [];
  28240. }
  28241. }
  28242. for (id in edges) {
  28243. if (edges.hasOwnProperty(id)) {
  28244. var edge = edges[id];
  28245. edge.from = null;
  28246. edge.to = null;
  28247. edge.connect();
  28248. }
  28249. }
  28250. }
  28251. }, {
  28252. key: 'getConnectedNodes',
  28253. value: function getConnectedNodes(edgeId) {
  28254. var nodeList = [];
  28255. if (this.body.edges[edgeId] !== undefined) {
  28256. var edge = this.body.edges[edgeId];
  28257. if (edge.fromId) {
  28258. nodeList.push(edge.fromId);
  28259. }
  28260. if (edge.toId) {
  28261. nodeList.push(edge.toId);
  28262. }
  28263. }
  28264. return nodeList;
  28265. }
  28266. }]);
  28267. return EdgesHandler;
  28268. }();
  28269. exports.default = EdgesHandler;
  28270. /***/ },
  28271. /* 85 */
  28272. /***/ function(module, exports, __webpack_require__) {
  28273. 'use strict';
  28274. Object.defineProperty(exports, "__esModule", {
  28275. value: true
  28276. });
  28277. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  28278. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28279. var _Label = __webpack_require__(66);
  28280. var _Label2 = _interopRequireDefault(_Label);
  28281. var _CubicBezierEdge = __webpack_require__(86);
  28282. var _CubicBezierEdge2 = _interopRequireDefault(_CubicBezierEdge);
  28283. var _BezierEdgeDynamic = __webpack_require__(90);
  28284. var _BezierEdgeDynamic2 = _interopRequireDefault(_BezierEdgeDynamic);
  28285. var _BezierEdgeStatic = __webpack_require__(91);
  28286. var _BezierEdgeStatic2 = _interopRequireDefault(_BezierEdgeStatic);
  28287. var _StraightEdge = __webpack_require__(92);
  28288. var _StraightEdge2 = _interopRequireDefault(_StraightEdge);
  28289. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28290. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28291. var util = __webpack_require__(1);
  28292. /**
  28293. * @class Edge
  28294. *
  28295. * A edge connects two nodes
  28296. * @param {Object} properties Object with options. Must contain
  28297. * At least options from and to.
  28298. * Available options: from (number),
  28299. * to (number), label (string, color (string),
  28300. * width (number), style (string),
  28301. * length (number), title (string)
  28302. * @param {Network} network A Network object, used to find and edge to
  28303. * nodes.
  28304. * @param {Object} constants An object with default values for
  28305. * example for the color
  28306. */
  28307. var Edge = function () {
  28308. function Edge(options, body, globalOptions) {
  28309. _classCallCheck(this, Edge);
  28310. if (body === undefined) {
  28311. throw "No body provided";
  28312. }
  28313. this.options = util.bridgeObject(globalOptions);
  28314. this.globalOptions = globalOptions;
  28315. this.body = body;
  28316. // initialize variables
  28317. this.id = undefined;
  28318. this.fromId = undefined;
  28319. this.toId = undefined;
  28320. this.selected = false;
  28321. this.hover = false;
  28322. this.labelDirty = true;
  28323. this.colorDirty = true;
  28324. this.baseWidth = this.options.width;
  28325. this.baseFontSize = this.options.font.size;
  28326. this.from = undefined; // a node
  28327. this.to = undefined; // a node
  28328. this.edgeType = undefined;
  28329. this.connected = false;
  28330. this.labelModule = new _Label2.default(this.body, this.options, true /* It's an edge label */);
  28331. this.setOptions(options);
  28332. }
  28333. /**
  28334. * Set or overwrite options for the edge
  28335. * @param {Object} options an object with options
  28336. * @param doNotEmit
  28337. */
  28338. _createClass(Edge, [{
  28339. key: 'setOptions',
  28340. value: function setOptions(options) {
  28341. if (!options) {
  28342. return;
  28343. }
  28344. this.colorDirty = true;
  28345. Edge.parseOptions(this.options, options, true, this.globalOptions);
  28346. if (options.id !== undefined) {
  28347. this.id = options.id;
  28348. }
  28349. if (options.from !== undefined) {
  28350. this.fromId = options.from;
  28351. }
  28352. if (options.to !== undefined) {
  28353. this.toId = options.to;
  28354. }
  28355. if (options.title !== undefined) {
  28356. this.title = options.title;
  28357. }
  28358. if (options.value !== undefined) {
  28359. options.value = parseFloat(options.value);
  28360. }
  28361. // update label Module
  28362. this.updateLabelModule();
  28363. var dataChanged = this.updateEdgeType();
  28364. // if anything has been updates, reset the selection width and the hover width
  28365. this._setInteractionWidths();
  28366. // A node is connected when it has a from and to node that both exist in the network.body.nodes.
  28367. this.connect();
  28368. if (options.hidden !== undefined || options.physics !== undefined) {
  28369. dataChanged = true;
  28370. }
  28371. return dataChanged;
  28372. }
  28373. }, {
  28374. key: 'updateLabelModule',
  28375. // set the object back to the global options
  28376. /**
  28377. * update the options in the label module
  28378. */
  28379. value: function updateLabelModule() {
  28380. this.labelModule.setOptions(this.options, true);
  28381. if (this.labelModule.baseSize !== undefined) {
  28382. this.baseFontSize = this.labelModule.baseSize;
  28383. }
  28384. }
  28385. /**
  28386. * update the edge type, set the options
  28387. * @returns {boolean}
  28388. */
  28389. }, {
  28390. key: 'updateEdgeType',
  28391. value: function updateEdgeType() {
  28392. var dataChanged = false;
  28393. var changeInType = true;
  28394. var smooth = this.options.smooth;
  28395. if (this.edgeType !== undefined) {
  28396. if (this.edgeType instanceof _BezierEdgeDynamic2.default && smooth.enabled === true && smooth.type === 'dynamic') {
  28397. changeInType = false;
  28398. }
  28399. if (this.edgeType instanceof _CubicBezierEdge2.default && smooth.enabled === true && smooth.type === 'cubicBezier') {
  28400. changeInType = false;
  28401. }
  28402. if (this.edgeType instanceof _BezierEdgeStatic2.default && smooth.enabled === true && smooth.type !== 'dynamic' && smooth.type !== 'cubicBezier') {
  28403. changeInType = false;
  28404. }
  28405. if (this.edgeType instanceof _StraightEdge2.default && smooth.enabled === false) {
  28406. changeInType = false;
  28407. }
  28408. if (changeInType === true) {
  28409. dataChanged = this.cleanup();
  28410. }
  28411. }
  28412. if (changeInType === true) {
  28413. if (this.options.smooth.enabled === true) {
  28414. if (this.options.smooth.type === 'dynamic') {
  28415. dataChanged = true;
  28416. this.edgeType = new _BezierEdgeDynamic2.default(this.options, this.body, this.labelModule);
  28417. } else if (this.options.smooth.type === 'cubicBezier') {
  28418. this.edgeType = new _CubicBezierEdge2.default(this.options, this.body, this.labelModule);
  28419. } else {
  28420. this.edgeType = new _BezierEdgeStatic2.default(this.options, this.body, this.labelModule);
  28421. }
  28422. } else {
  28423. this.edgeType = new _StraightEdge2.default(this.options, this.body, this.labelModule);
  28424. }
  28425. } else {
  28426. // if nothing changes, we just set the options.
  28427. this.edgeType.setOptions(this.options);
  28428. }
  28429. return dataChanged;
  28430. }
  28431. /**
  28432. * Connect an edge to its nodes
  28433. */
  28434. }, {
  28435. key: 'connect',
  28436. value: function connect() {
  28437. this.disconnect();
  28438. this.from = this.body.nodes[this.fromId] || undefined;
  28439. this.to = this.body.nodes[this.toId] || undefined;
  28440. this.connected = this.from !== undefined && this.to !== undefined;
  28441. if (this.connected === true) {
  28442. this.from.attachEdge(this);
  28443. this.to.attachEdge(this);
  28444. } else {
  28445. if (this.from) {
  28446. this.from.detachEdge(this);
  28447. }
  28448. if (this.to) {
  28449. this.to.detachEdge(this);
  28450. }
  28451. }
  28452. this.edgeType.connect();
  28453. }
  28454. /**
  28455. * Disconnect an edge from its nodes
  28456. */
  28457. }, {
  28458. key: 'disconnect',
  28459. value: function disconnect() {
  28460. if (this.from) {
  28461. this.from.detachEdge(this);
  28462. this.from = undefined;
  28463. }
  28464. if (this.to) {
  28465. this.to.detachEdge(this);
  28466. this.to = undefined;
  28467. }
  28468. this.connected = false;
  28469. }
  28470. /**
  28471. * get the title of this edge.
  28472. * @return {string} title The title of the edge, or undefined when no title
  28473. * has been set.
  28474. */
  28475. }, {
  28476. key: 'getTitle',
  28477. value: function getTitle() {
  28478. return this.title;
  28479. }
  28480. /**
  28481. * check if this node is selecte
  28482. * @return {boolean} selected True if node is selected, else false
  28483. */
  28484. }, {
  28485. key: 'isSelected',
  28486. value: function isSelected() {
  28487. return this.selected;
  28488. }
  28489. /**
  28490. * Retrieve the value of the edge. Can be undefined
  28491. * @return {Number} value
  28492. */
  28493. }, {
  28494. key: 'getValue',
  28495. value: function getValue() {
  28496. return this.options.value;
  28497. }
  28498. /**
  28499. * Adjust the value range of the edge. The edge will adjust it's width
  28500. * based on its value.
  28501. * @param {Number} min
  28502. * @param {Number} max
  28503. * @param total
  28504. */
  28505. }, {
  28506. key: 'setValueRange',
  28507. value: function setValueRange(min, max, total) {
  28508. if (this.options.value !== undefined) {
  28509. var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
  28510. var widthDiff = this.options.scaling.max - this.options.scaling.min;
  28511. if (this.options.scaling.label.enabled === true) {
  28512. var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
  28513. this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
  28514. }
  28515. this.options.width = this.options.scaling.min + scale * widthDiff;
  28516. } else {
  28517. this.options.width = this.baseWidth;
  28518. this.options.font.size = this.baseFontSize;
  28519. }
  28520. this._setInteractionWidths();
  28521. this.updateLabelModule();
  28522. }
  28523. }, {
  28524. key: '_setInteractionWidths',
  28525. value: function _setInteractionWidths() {
  28526. if (typeof this.options.hoverWidth === 'function') {
  28527. this.edgeType.hoverWidth = this.options.hoverWidth(this.options.width);
  28528. } else {
  28529. this.edgeType.hoverWidth = this.options.hoverWidth + this.options.width;
  28530. }
  28531. if (typeof this.options.selectionWidth === 'function') {
  28532. this.edgeType.selectionWidth = this.options.selectionWidth(this.options.width);
  28533. } else {
  28534. this.edgeType.selectionWidth = this.options.selectionWidth + this.options.width;
  28535. }
  28536. }
  28537. /**
  28538. * Redraw a edge
  28539. * Draw this edge in the given canvas
  28540. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  28541. * @param {CanvasRenderingContext2D} ctx
  28542. */
  28543. }, {
  28544. key: 'draw',
  28545. value: function draw(ctx) {
  28546. // get the via node from the edge type
  28547. var viaNode = this.edgeType.getViaNode();
  28548. var arrowData = {};
  28549. // restore edge targets to defaults
  28550. this.edgeType.fromPoint = this.edgeType.from;
  28551. this.edgeType.toPoint = this.edgeType.to;
  28552. // from and to arrows give a different end point for edges. we set them here
  28553. if (this.options.arrows.from.enabled === true) {
  28554. arrowData.from = this.edgeType.getArrowData(ctx, 'from', viaNode, this.selected, this.hover);
  28555. if (this.options.arrowStrikethrough === false) this.edgeType.fromPoint = arrowData.from.core;
  28556. }
  28557. if (this.options.arrows.to.enabled === true) {
  28558. arrowData.to = this.edgeType.getArrowData(ctx, 'to', viaNode, this.selected, this.hover);
  28559. if (this.options.arrowStrikethrough === false) this.edgeType.toPoint = arrowData.to.core;
  28560. }
  28561. // the middle arrow depends on the line, which can depend on the to and from arrows so we do this one lastly.
  28562. if (this.options.arrows.middle.enabled === true) {
  28563. arrowData.middle = this.edgeType.getArrowData(ctx, 'middle', viaNode, this.selected, this.hover);
  28564. }
  28565. // draw everything
  28566. this.edgeType.drawLine(ctx, this.selected, this.hover, viaNode);
  28567. this.drawArrows(ctx, arrowData);
  28568. this.drawLabel(ctx, viaNode);
  28569. }
  28570. }, {
  28571. key: 'drawArrows',
  28572. value: function drawArrows(ctx, arrowData) {
  28573. if (this.options.arrows.from.enabled === true) {
  28574. this.edgeType.drawArrowHead(ctx, this.selected, this.hover, arrowData.from);
  28575. }
  28576. if (this.options.arrows.middle.enabled === true) {
  28577. this.edgeType.drawArrowHead(ctx, this.selected, this.hover, arrowData.middle);
  28578. }
  28579. if (this.options.arrows.to.enabled === true) {
  28580. this.edgeType.drawArrowHead(ctx, this.selected, this.hover, arrowData.to);
  28581. }
  28582. }
  28583. }, {
  28584. key: 'drawLabel',
  28585. value: function drawLabel(ctx, viaNode) {
  28586. if (this.options.label !== undefined) {
  28587. // set style
  28588. var node1 = this.from;
  28589. var node2 = this.to;
  28590. var selected = this.from.selected || this.to.selected || this.selected;
  28591. if (node1.id != node2.id) {
  28592. this.labelModule.pointToSelf = false;
  28593. var point = this.edgeType.getPoint(0.5, viaNode);
  28594. ctx.save();
  28595. // if the label has to be rotated:
  28596. if (this.options.font.align !== "horizontal") {
  28597. this.labelModule.calculateLabelSize(ctx, selected, point.x, point.y);
  28598. ctx.translate(point.x, this.labelModule.size.yLine);
  28599. this._rotateForLabelAlignment(ctx);
  28600. }
  28601. // draw the label
  28602. this.labelModule.draw(ctx, point.x, point.y, selected);
  28603. ctx.restore();
  28604. } else {
  28605. // Ignore the orientations.
  28606. this.labelModule.pointToSelf = true;
  28607. var x, y;
  28608. var radius = this.options.selfReferenceSize;
  28609. if (node1.shape.width > node1.shape.height) {
  28610. x = node1.x + node1.shape.width * 0.5;
  28611. y = node1.y - radius;
  28612. } else {
  28613. x = node1.x + radius;
  28614. y = node1.y - node1.shape.height * 0.5;
  28615. }
  28616. point = this._pointOnCircle(x, y, radius, 0.125);
  28617. this.labelModule.draw(ctx, point.x, point.y, selected);
  28618. }
  28619. }
  28620. }
  28621. /**
  28622. * Check if this object is overlapping with the provided object
  28623. * @param {Object} obj an object with parameters left, top
  28624. * @return {boolean} True if location is located on the edge
  28625. */
  28626. }, {
  28627. key: 'isOverlappingWith',
  28628. value: function isOverlappingWith(obj) {
  28629. if (this.connected) {
  28630. var distMax = 10;
  28631. var xFrom = this.from.x;
  28632. var yFrom = this.from.y;
  28633. var xTo = this.to.x;
  28634. var yTo = this.to.y;
  28635. var xObj = obj.left;
  28636. var yObj = obj.top;
  28637. var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  28638. return dist < distMax;
  28639. } else {
  28640. return false;
  28641. }
  28642. }
  28643. /**
  28644. * Rotates the canvas so the text is most readable
  28645. * @param {CanvasRenderingContext2D} ctx
  28646. * @private
  28647. */
  28648. }, {
  28649. key: '_rotateForLabelAlignment',
  28650. value: function _rotateForLabelAlignment(ctx) {
  28651. var dy = this.from.y - this.to.y;
  28652. var dx = this.from.x - this.to.x;
  28653. var angleInDegrees = Math.atan2(dy, dx);
  28654. // rotate so label it is readable
  28655. if (angleInDegrees < -1 && dx < 0 || angleInDegrees > 0 && dx < 0) {
  28656. angleInDegrees = angleInDegrees + Math.PI;
  28657. }
  28658. ctx.rotate(angleInDegrees);
  28659. }
  28660. /**
  28661. * Get a point on a circle
  28662. * @param {Number} x
  28663. * @param {Number} y
  28664. * @param {Number} radius
  28665. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  28666. * @return {Object} point
  28667. * @private
  28668. */
  28669. }, {
  28670. key: '_pointOnCircle',
  28671. value: function _pointOnCircle(x, y, radius, percentage) {
  28672. var angle = percentage * 2 * Math.PI;
  28673. return {
  28674. x: x + radius * Math.cos(angle),
  28675. y: y - radius * Math.sin(angle)
  28676. };
  28677. }
  28678. }, {
  28679. key: 'select',
  28680. value: function select() {
  28681. this.selected = true;
  28682. }
  28683. }, {
  28684. key: 'unselect',
  28685. value: function unselect() {
  28686. this.selected = false;
  28687. }
  28688. /**
  28689. * cleans all required things on delete
  28690. * @returns {*}
  28691. */
  28692. }, {
  28693. key: 'cleanup',
  28694. value: function cleanup() {
  28695. return this.edgeType.cleanup();
  28696. }
  28697. }], [{
  28698. key: 'parseOptions',
  28699. value: function parseOptions(parentOptions, newOptions) {
  28700. var allowDeletion = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  28701. var globalOptions = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
  28702. var fields = ['arrowStrikethrough', 'id', 'from', 'hidden', 'hoverWidth', 'label', 'labelHighlightBold', 'length', 'line', 'opacity', 'physics', 'scaling', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width'];
  28703. // only deep extend the items in the field array. These do not have shorthand.
  28704. util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion);
  28705. util.mergeOptions(parentOptions, newOptions, 'smooth', allowDeletion, globalOptions);
  28706. util.mergeOptions(parentOptions, newOptions, 'shadow', allowDeletion, globalOptions);
  28707. if (newOptions.dashes !== undefined && newOptions.dashes !== null) {
  28708. parentOptions.dashes = newOptions.dashes;
  28709. } else if (allowDeletion === true && newOptions.dashes === null) {
  28710. parentOptions.dashes = Object.create(globalOptions.dashes); // this sets the pointer of the option back to the global option.
  28711. }
  28712. // set the scaling newOptions
  28713. if (newOptions.scaling !== undefined && newOptions.scaling !== null) {
  28714. if (newOptions.scaling.min !== undefined) {
  28715. parentOptions.scaling.min = newOptions.scaling.min;
  28716. }
  28717. if (newOptions.scaling.max !== undefined) {
  28718. parentOptions.scaling.max = newOptions.scaling.max;
  28719. }
  28720. util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', allowDeletion, globalOptions.scaling);
  28721. } else if (allowDeletion === true && newOptions.scaling === null) {
  28722. parentOptions.scaling = Object.create(globalOptions.scaling); // this sets the pointer of the option back to the global option.
  28723. }
  28724. // handle multiple input cases for arrows
  28725. if (newOptions.arrows !== undefined && newOptions.arrows !== null) {
  28726. if (typeof newOptions.arrows === 'string') {
  28727. var arrows = newOptions.arrows.toLowerCase();
  28728. parentOptions.arrows.to.enabled = arrows.indexOf("to") != -1;
  28729. parentOptions.arrows.middle.enabled = arrows.indexOf("middle") != -1;
  28730. parentOptions.arrows.from.enabled = arrows.indexOf("from") != -1;
  28731. } else if (_typeof(newOptions.arrows) === 'object') {
  28732. util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to', allowDeletion, globalOptions.arrows);
  28733. util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle', allowDeletion, globalOptions.arrows);
  28734. util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from', allowDeletion, globalOptions.arrows);
  28735. } else {
  28736. throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:" + JSON.stringify(newOptions.arrows));
  28737. }
  28738. } else if (allowDeletion === true && newOptions.arrows === null) {
  28739. parentOptions.arrows = Object.create(globalOptions.arrows); // this sets the pointer of the option back to the global option.
  28740. }
  28741. // handle multiple input cases for color
  28742. if (newOptions.color !== undefined && newOptions.color !== null) {
  28743. // make a copy of the parent object in case this is referring to the global one (due to object create once, then update)
  28744. parentOptions.color = util.deepExtend({}, parentOptions.color, true);
  28745. if (util.isString(newOptions.color)) {
  28746. parentOptions.color.color = newOptions.color;
  28747. parentOptions.color.highlight = newOptions.color;
  28748. parentOptions.color.hover = newOptions.color;
  28749. parentOptions.color.inherit = false;
  28750. } else {
  28751. var colorsDefined = false;
  28752. if (newOptions.color.color !== undefined) {
  28753. parentOptions.color.color = newOptions.color.color;colorsDefined = true;
  28754. }
  28755. if (newOptions.color.highlight !== undefined) {
  28756. parentOptions.color.highlight = newOptions.color.highlight;colorsDefined = true;
  28757. }
  28758. if (newOptions.color.hover !== undefined) {
  28759. parentOptions.color.hover = newOptions.color.hover;colorsDefined = true;
  28760. }
  28761. if (newOptions.color.inherit !== undefined) {
  28762. parentOptions.color.inherit = newOptions.color.inherit;
  28763. }
  28764. if (newOptions.color.opacity !== undefined) {
  28765. parentOptions.color.opacity = Math.min(1, Math.max(0, newOptions.color.opacity));
  28766. }
  28767. if (newOptions.color.inherit === undefined && colorsDefined === true) {
  28768. parentOptions.color.inherit = false;
  28769. }
  28770. }
  28771. } else if (allowDeletion === true && newOptions.color === null) {
  28772. parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
  28773. }
  28774. // handle the font settings
  28775. if (newOptions.font !== undefined && newOptions.font !== null) {
  28776. _Label2.default.parseOptions(parentOptions.font, newOptions);
  28777. } else if (allowDeletion === true && newOptions.font === null) {
  28778. parentOptions.font = util.bridgeObject(globalOptions.font);
  28779. }
  28780. }
  28781. }]);
  28782. return Edge;
  28783. }();
  28784. exports.default = Edge;
  28785. /***/ },
  28786. /* 86 */
  28787. /***/ function(module, exports, __webpack_require__) {
  28788. 'use strict';
  28789. Object.defineProperty(exports, "__esModule", {
  28790. value: true
  28791. });
  28792. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  28793. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28794. var _CubicBezierEdgeBase2 = __webpack_require__(87);
  28795. var _CubicBezierEdgeBase3 = _interopRequireDefault(_CubicBezierEdgeBase2);
  28796. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28797. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28798. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  28799. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  28800. var CubicBezierEdge = function (_CubicBezierEdgeBase) {
  28801. _inherits(CubicBezierEdge, _CubicBezierEdgeBase);
  28802. function CubicBezierEdge(options, body, labelModule) {
  28803. _classCallCheck(this, CubicBezierEdge);
  28804. return _possibleConstructorReturn(this, Object.getPrototypeOf(CubicBezierEdge).call(this, options, body, labelModule));
  28805. }
  28806. /**
  28807. * Draw a line between two nodes
  28808. * @param {CanvasRenderingContext2D} ctx
  28809. * @private
  28810. */
  28811. _createClass(CubicBezierEdge, [{
  28812. key: '_line',
  28813. value: function _line(ctx, viaNodes) {
  28814. // get the coordinates of the support points.
  28815. var via1 = viaNodes[0];
  28816. var via2 = viaNodes[1];
  28817. // start drawing the line.
  28818. ctx.beginPath();
  28819. ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
  28820. // fallback to normal straight edges
  28821. if (viaNodes === undefined || via1.x === undefined) {
  28822. ctx.lineTo(this.toPoint.x, this.toPoint.y);
  28823. } else {
  28824. ctx.bezierCurveTo(via1.x, via1.y, via2.x, via2.y, this.toPoint.x, this.toPoint.y);
  28825. }
  28826. // draw shadow if enabled
  28827. this.enableShadow(ctx);
  28828. ctx.stroke();
  28829. this.disableShadow(ctx);
  28830. }
  28831. }, {
  28832. key: '_getViaCoordinates',
  28833. value: function _getViaCoordinates() {
  28834. var dx = this.from.x - this.to.x;
  28835. var dy = this.from.y - this.to.y;
  28836. var x1 = void 0,
  28837. y1 = void 0,
  28838. x2 = void 0,
  28839. y2 = void 0;
  28840. var roundness = this.options.smooth.roundness;
  28841. // horizontal if x > y or if direction is forced or if direction is horizontal
  28842. if ((Math.abs(dx) > Math.abs(dy) || this.options.smooth.forceDirection === true || this.options.smooth.forceDirection === 'horizontal') && this.options.smooth.forceDirection !== 'vertical') {
  28843. y1 = this.from.y;
  28844. y2 = this.to.y;
  28845. x1 = this.from.x - roundness * dx;
  28846. x2 = this.to.x + roundness * dx;
  28847. } else {
  28848. y1 = this.from.y - roundness * dy;
  28849. y2 = this.to.y + roundness * dy;
  28850. x1 = this.from.x;
  28851. x2 = this.to.x;
  28852. }
  28853. return [{ x: x1, y: y1 }, { x: x2, y: y2 }];
  28854. }
  28855. }, {
  28856. key: 'getViaNode',
  28857. value: function getViaNode() {
  28858. return this._getViaCoordinates();
  28859. }
  28860. }, {
  28861. key: '_findBorderPosition',
  28862. value: function _findBorderPosition(nearNode, ctx) {
  28863. return this._findBorderPositionBezier(nearNode, ctx);
  28864. }
  28865. }, {
  28866. key: '_getDistanceToEdge',
  28867. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  28868. var _ref = arguments.length <= 6 || arguments[6] === undefined ? this._getViaCoordinates() : arguments[6];
  28869. var _ref2 = _slicedToArray(_ref, 2);
  28870. var via1 = _ref2[0];
  28871. var via2 = _ref2[1];
  28872. // x3,y3 is the point
  28873. return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via1, via2);
  28874. }
  28875. /**
  28876. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  28877. * @param percentage
  28878. * @param via
  28879. * @returns {{x: number, y: number}}
  28880. * @private
  28881. */
  28882. }, {
  28883. key: 'getPoint',
  28884. value: function getPoint(percentage) {
  28885. var _ref3 = arguments.length <= 1 || arguments[1] === undefined ? this._getViaCoordinates() : arguments[1];
  28886. var _ref4 = _slicedToArray(_ref3, 2);
  28887. var via1 = _ref4[0];
  28888. var via2 = _ref4[1];
  28889. var t = percentage;
  28890. var vec = [];
  28891. vec[0] = Math.pow(1 - t, 3);
  28892. vec[1] = 3 * t * Math.pow(1 - t, 2);
  28893. vec[2] = 3 * Math.pow(t, 2) * (1 - t);
  28894. vec[3] = Math.pow(t, 3);
  28895. var x = vec[0] * this.fromPoint.x + vec[1] * via1.x + vec[2] * via2.x + vec[3] * this.toPoint.x;
  28896. var y = vec[0] * this.fromPoint.y + vec[1] * via1.y + vec[2] * via2.y + vec[3] * this.toPoint.y;
  28897. return { x: x, y: y };
  28898. }
  28899. }]);
  28900. return CubicBezierEdge;
  28901. }(_CubicBezierEdgeBase3.default);
  28902. exports.default = CubicBezierEdge;
  28903. /***/ },
  28904. /* 87 */
  28905. /***/ function(module, exports, __webpack_require__) {
  28906. 'use strict';
  28907. Object.defineProperty(exports, "__esModule", {
  28908. value: true
  28909. });
  28910. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28911. var _BezierEdgeBase2 = __webpack_require__(88);
  28912. var _BezierEdgeBase3 = _interopRequireDefault(_BezierEdgeBase2);
  28913. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28914. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28915. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  28916. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  28917. var CubicBezierEdgeBase = function (_BezierEdgeBase) {
  28918. _inherits(CubicBezierEdgeBase, _BezierEdgeBase);
  28919. function CubicBezierEdgeBase(options, body, labelModule) {
  28920. _classCallCheck(this, CubicBezierEdgeBase);
  28921. return _possibleConstructorReturn(this, Object.getPrototypeOf(CubicBezierEdgeBase).call(this, options, body, labelModule));
  28922. }
  28923. /**
  28924. * Calculate the distance between a point (x3,y3) and a line segment from
  28925. * (x1,y1) to (x2,y2).
  28926. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  28927. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  28928. * @param {number} x1 from x
  28929. * @param {number} y1 from y
  28930. * @param {number} x2 to x
  28931. * @param {number} y2 to y
  28932. * @param {number} x3 point to check x
  28933. * @param {number} y3 point to check y
  28934. * @private
  28935. */
  28936. _createClass(CubicBezierEdgeBase, [{
  28937. key: '_getDistanceToBezierEdge',
  28938. value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via1, via2) {
  28939. // x3,y3 is the point
  28940. var minDistance = 1e9;
  28941. var distance = void 0;
  28942. var i = void 0,
  28943. t = void 0,
  28944. x = void 0,
  28945. y = void 0;
  28946. var lastX = x1;
  28947. var lastY = y1;
  28948. var vec = [0, 0, 0, 0];
  28949. for (i = 1; i < 10; i++) {
  28950. t = 0.1 * i;
  28951. vec[0] = Math.pow(1 - t, 3);
  28952. vec[1] = 3 * t * Math.pow(1 - t, 2);
  28953. vec[2] = 3 * Math.pow(t, 2) * (1 - t);
  28954. vec[3] = Math.pow(t, 3);
  28955. x = vec[0] * x1 + vec[1] * via1.x + vec[2] * via2.x + vec[3] * x2;
  28956. y = vec[0] * y1 + vec[1] * via1.y + vec[2] * via2.y + vec[3] * y2;
  28957. if (i > 0) {
  28958. distance = this._getDistanceToLine(lastX, lastY, x, y, x3, y3);
  28959. minDistance = distance < minDistance ? distance : minDistance;
  28960. }
  28961. lastX = x;
  28962. lastY = y;
  28963. }
  28964. return minDistance;
  28965. }
  28966. }]);
  28967. return CubicBezierEdgeBase;
  28968. }(_BezierEdgeBase3.default);
  28969. exports.default = CubicBezierEdgeBase;
  28970. /***/ },
  28971. /* 88 */
  28972. /***/ function(module, exports, __webpack_require__) {
  28973. 'use strict';
  28974. Object.defineProperty(exports, "__esModule", {
  28975. value: true
  28976. });
  28977. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28978. var _EdgeBase2 = __webpack_require__(89);
  28979. var _EdgeBase3 = _interopRequireDefault(_EdgeBase2);
  28980. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28981. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28982. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  28983. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  28984. var BezierEdgeBase = function (_EdgeBase) {
  28985. _inherits(BezierEdgeBase, _EdgeBase);
  28986. function BezierEdgeBase(options, body, labelModule) {
  28987. _classCallCheck(this, BezierEdgeBase);
  28988. return _possibleConstructorReturn(this, Object.getPrototypeOf(BezierEdgeBase).call(this, options, body, labelModule));
  28989. }
  28990. /**
  28991. * This function uses binary search to look for the point where the bezier curve crosses the border of the node.
  28992. *
  28993. * @param nearNode
  28994. * @param ctx
  28995. * @param viaNode
  28996. * @param nearNode
  28997. * @param ctx
  28998. * @param viaNode
  28999. * @param nearNode
  29000. * @param ctx
  29001. * @param viaNode
  29002. */
  29003. _createClass(BezierEdgeBase, [{
  29004. key: '_findBorderPositionBezier',
  29005. value: function _findBorderPositionBezier(nearNode, ctx) {
  29006. var viaNode = arguments.length <= 2 || arguments[2] === undefined ? this._getViaCoordinates() : arguments[2];
  29007. var maxIterations = 10;
  29008. var iteration = 0;
  29009. var low = 0;
  29010. var high = 1;
  29011. var pos, angle, distanceToBorder, distanceToPoint, difference;
  29012. var threshold = 0.2;
  29013. var node = this.to;
  29014. var from = false;
  29015. if (nearNode.id === this.from.id) {
  29016. node = this.from;
  29017. from = true;
  29018. }
  29019. while (low <= high && iteration < maxIterations) {
  29020. var middle = (low + high) * 0.5;
  29021. pos = this.getPoint(middle, viaNode);
  29022. angle = Math.atan2(node.y - pos.y, node.x - pos.x);
  29023. distanceToBorder = node.distanceToBorder(ctx, angle);
  29024. distanceToPoint = Math.sqrt(Math.pow(pos.x - node.x, 2) + Math.pow(pos.y - node.y, 2));
  29025. difference = distanceToBorder - distanceToPoint;
  29026. if (Math.abs(difference) < threshold) {
  29027. break; // found
  29028. } else if (difference < 0) {
  29029. // distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
  29030. if (from === false) {
  29031. low = middle;
  29032. } else {
  29033. high = middle;
  29034. }
  29035. } else {
  29036. if (from === false) {
  29037. high = middle;
  29038. } else {
  29039. low = middle;
  29040. }
  29041. }
  29042. iteration++;
  29043. }
  29044. pos.t = middle;
  29045. return pos;
  29046. }
  29047. /**
  29048. * Calculate the distance between a point (x3,y3) and a line segment from
  29049. * (x1,y1) to (x2,y2).
  29050. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  29051. * @param {number} x1 from x
  29052. * @param {number} y1 from y
  29053. * @param {number} x2 to x
  29054. * @param {number} y2 to y
  29055. * @param {number} x3 point to check x
  29056. * @param {number} y3 point to check y
  29057. * @private
  29058. */
  29059. }, {
  29060. key: '_getDistanceToBezierEdge',
  29061. value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) {
  29062. // x3,y3 is the point
  29063. var minDistance = 1e9;
  29064. var distance = void 0;
  29065. var i = void 0,
  29066. t = void 0,
  29067. x = void 0,
  29068. y = void 0;
  29069. var lastX = x1;
  29070. var lastY = y1;
  29071. for (i = 1; i < 10; i++) {
  29072. t = 0.1 * i;
  29073. x = Math.pow(1 - t, 2) * x1 + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * x2;
  29074. y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * y2;
  29075. if (i > 0) {
  29076. distance = this._getDistanceToLine(lastX, lastY, x, y, x3, y3);
  29077. minDistance = distance < minDistance ? distance : minDistance;
  29078. }
  29079. lastX = x;
  29080. lastY = y;
  29081. }
  29082. return minDistance;
  29083. }
  29084. }]);
  29085. return BezierEdgeBase;
  29086. }(_EdgeBase3.default);
  29087. exports.default = BezierEdgeBase;
  29088. /***/ },
  29089. /* 89 */
  29090. /***/ function(module, exports, __webpack_require__) {
  29091. 'use strict';
  29092. Object.defineProperty(exports, "__esModule", {
  29093. value: true
  29094. });
  29095. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  29096. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  29097. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29098. var util = __webpack_require__(1);
  29099. var EdgeBase = function () {
  29100. function EdgeBase(options, body, labelModule) {
  29101. _classCallCheck(this, EdgeBase);
  29102. this.body = body;
  29103. this.labelModule = labelModule;
  29104. this.options = {};
  29105. this.setOptions(options);
  29106. this.colorDirty = true;
  29107. this.color = {};
  29108. this.selectionWidth = 2;
  29109. this.hoverWidth = 1.5;
  29110. this.fromPoint = this.from;
  29111. this.toPoint = this.to;
  29112. }
  29113. _createClass(EdgeBase, [{
  29114. key: 'connect',
  29115. value: function connect() {
  29116. this.from = this.body.nodes[this.options.from];
  29117. this.to = this.body.nodes[this.options.to];
  29118. }
  29119. }, {
  29120. key: 'cleanup',
  29121. value: function cleanup() {
  29122. return false;
  29123. }
  29124. }, {
  29125. key: 'setOptions',
  29126. value: function setOptions(options) {
  29127. this.options = options;
  29128. this.from = this.body.nodes[this.options.from];
  29129. this.to = this.body.nodes[this.options.to];
  29130. this.id = this.options.id;
  29131. }
  29132. /**
  29133. * Redraw a edge as a line
  29134. * Draw this edge in the given canvas
  29135. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  29136. * @param {CanvasRenderingContext2D} ctx
  29137. * @private
  29138. */
  29139. }, {
  29140. key: 'drawLine',
  29141. value: function drawLine(ctx, selected, hover, viaNode) {
  29142. // set style
  29143. ctx.strokeStyle = this.getColor(ctx, selected, hover);
  29144. ctx.lineWidth = this.getLineWidth(selected, hover);
  29145. if (this.options.dashes !== false) {
  29146. this._drawDashedLine(ctx, viaNode);
  29147. } else {
  29148. this._drawLine(ctx, viaNode);
  29149. }
  29150. }
  29151. }, {
  29152. key: '_drawLine',
  29153. value: function _drawLine(ctx, viaNode, fromPoint, toPoint) {
  29154. if (this.from != this.to) {
  29155. // draw line
  29156. this._line(ctx, viaNode, fromPoint, toPoint);
  29157. } else {
  29158. var _getCircleData2 = this._getCircleData(ctx);
  29159. var _getCircleData3 = _slicedToArray(_getCircleData2, 3);
  29160. var x = _getCircleData3[0];
  29161. var y = _getCircleData3[1];
  29162. var radius = _getCircleData3[2];
  29163. this._circle(ctx, x, y, radius);
  29164. }
  29165. }
  29166. }, {
  29167. key: '_drawDashedLine',
  29168. value: function _drawDashedLine(ctx, viaNode, fromPoint, toPoint) {
  29169. ctx.lineCap = 'round';
  29170. var pattern = [5, 5];
  29171. if (Array.isArray(this.options.dashes) === true) {
  29172. pattern = this.options.dashes;
  29173. }
  29174. // only firefox and chrome support this method, else we use the legacy one.
  29175. if (ctx.setLineDash !== undefined) {
  29176. ctx.save();
  29177. // set dash settings for chrome or firefox
  29178. ctx.setLineDash(pattern);
  29179. ctx.lineDashOffset = 0;
  29180. // draw the line
  29181. if (this.from != this.to) {
  29182. // draw line
  29183. this._line(ctx, viaNode);
  29184. } else {
  29185. var _getCircleData4 = this._getCircleData(ctx);
  29186. var _getCircleData5 = _slicedToArray(_getCircleData4, 3);
  29187. var x = _getCircleData5[0];
  29188. var y = _getCircleData5[1];
  29189. var radius = _getCircleData5[2];
  29190. this._circle(ctx, x, y, radius);
  29191. }
  29192. // restore the dash settings.
  29193. ctx.setLineDash([0]);
  29194. ctx.lineDashOffset = 0;
  29195. ctx.restore();
  29196. } else {
  29197. // unsupporting smooth lines
  29198. if (this.from != this.to) {
  29199. // draw line
  29200. ctx.dashedLine(this.from.x, this.from.y, this.to.x, this.to.y, pattern);
  29201. } else {
  29202. var _getCircleData6 = this._getCircleData(ctx);
  29203. var _getCircleData7 = _slicedToArray(_getCircleData6, 3);
  29204. var _x = _getCircleData7[0];
  29205. var _y = _getCircleData7[1];
  29206. var _radius = _getCircleData7[2];
  29207. this._circle(ctx, _x, _y, _radius);
  29208. }
  29209. // draw shadow if enabled
  29210. this.enableShadow(ctx);
  29211. ctx.stroke();
  29212. // disable shadows for other elements.
  29213. this.disableShadow(ctx);
  29214. }
  29215. }
  29216. }, {
  29217. key: 'findBorderPosition',
  29218. value: function findBorderPosition(nearNode, ctx, options) {
  29219. if (this.from != this.to) {
  29220. return this._findBorderPosition(nearNode, ctx, options);
  29221. } else {
  29222. return this._findBorderPositionCircle(nearNode, ctx, options);
  29223. }
  29224. }
  29225. }, {
  29226. key: 'findBorderPositions',
  29227. value: function findBorderPositions(ctx) {
  29228. var from = {};
  29229. var to = {};
  29230. if (this.from != this.to) {
  29231. from = this._findBorderPosition(this.from, ctx);
  29232. to = this._findBorderPosition(this.to, ctx);
  29233. } else {
  29234. var _getCircleData8 = this._getCircleData(ctx);
  29235. var _getCircleData9 = _slicedToArray(_getCircleData8, 3);
  29236. var x = _getCircleData9[0];
  29237. var y = _getCircleData9[1];
  29238. var radius = _getCircleData9[2];
  29239. from = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 });
  29240. to = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.6, high: 0.8, direction: 1 });
  29241. }
  29242. return { from: from, to: to };
  29243. }
  29244. }, {
  29245. key: '_getCircleData',
  29246. value: function _getCircleData(ctx) {
  29247. var x = void 0,
  29248. y = void 0;
  29249. var node = this.from;
  29250. var radius = this.options.selfReferenceSize;
  29251. if (ctx !== undefined) {
  29252. if (node.shape.width === undefined) {
  29253. node.shape.resize(ctx);
  29254. }
  29255. }
  29256. // get circle coordinates
  29257. if (node.shape.width > node.shape.height) {
  29258. x = node.x + node.shape.width * 0.5;
  29259. y = node.y - radius;
  29260. } else {
  29261. x = node.x + radius;
  29262. y = node.y - node.shape.height * 0.5;
  29263. }
  29264. return [x, y, radius];
  29265. }
  29266. /**
  29267. * Get a point on a circle
  29268. * @param {Number} x
  29269. * @param {Number} y
  29270. * @param {Number} radius
  29271. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  29272. * @return {Object} point
  29273. * @private
  29274. */
  29275. }, {
  29276. key: '_pointOnCircle',
  29277. value: function _pointOnCircle(x, y, radius, percentage) {
  29278. var angle = percentage * 2 * Math.PI;
  29279. return {
  29280. x: x + radius * Math.cos(angle),
  29281. y: y - radius * Math.sin(angle)
  29282. };
  29283. }
  29284. /**
  29285. * This function uses binary search to look for the point where the circle crosses the border of the node.
  29286. * @param node
  29287. * @param ctx
  29288. * @param options
  29289. * @returns {*}
  29290. * @private
  29291. */
  29292. }, {
  29293. key: '_findBorderPositionCircle',
  29294. value: function _findBorderPositionCircle(node, ctx, options) {
  29295. var x = options.x;
  29296. var y = options.y;
  29297. var low = options.low;
  29298. var high = options.high;
  29299. var direction = options.direction;
  29300. var maxIterations = 10;
  29301. var iteration = 0;
  29302. var radius = this.options.selfReferenceSize;
  29303. var pos = void 0,
  29304. angle = void 0,
  29305. distanceToBorder = void 0,
  29306. distanceToPoint = void 0,
  29307. difference = void 0;
  29308. var threshold = 0.05;
  29309. var middle = (low + high) * 0.5;
  29310. while (low <= high && iteration < maxIterations) {
  29311. middle = (low + high) * 0.5;
  29312. pos = this._pointOnCircle(x, y, radius, middle);
  29313. angle = Math.atan2(node.y - pos.y, node.x - pos.x);
  29314. distanceToBorder = node.distanceToBorder(ctx, angle);
  29315. distanceToPoint = Math.sqrt(Math.pow(pos.x - node.x, 2) + Math.pow(pos.y - node.y, 2));
  29316. difference = distanceToBorder - distanceToPoint;
  29317. if (Math.abs(difference) < threshold) {
  29318. break; // found
  29319. } else if (difference > 0) {
  29320. // distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
  29321. if (direction > 0) {
  29322. low = middle;
  29323. } else {
  29324. high = middle;
  29325. }
  29326. } else {
  29327. if (direction > 0) {
  29328. high = middle;
  29329. } else {
  29330. low = middle;
  29331. }
  29332. }
  29333. iteration++;
  29334. }
  29335. pos.t = middle;
  29336. return pos;
  29337. }
  29338. /**
  29339. * Get the line width of the edge. Depends on width and whether one of the
  29340. * connected nodes is selected.
  29341. * @return {Number} width
  29342. * @private
  29343. */
  29344. }, {
  29345. key: 'getLineWidth',
  29346. value: function getLineWidth(selected, hover) {
  29347. if (selected === true) {
  29348. return Math.max(this.selectionWidth, 0.3 / this.body.view.scale);
  29349. } else {
  29350. if (hover === true) {
  29351. return Math.max(this.hoverWidth, 0.3 / this.body.view.scale);
  29352. } else {
  29353. return Math.max(this.options.width, 0.3 / this.body.view.scale);
  29354. }
  29355. }
  29356. }
  29357. }, {
  29358. key: 'getColor',
  29359. value: function getColor(ctx, selected, hover) {
  29360. var colorOptions = this.options.color;
  29361. if (colorOptions.inherit !== false) {
  29362. // when this is a loop edge, just use the 'from' method
  29363. if (colorOptions.inherit === 'both' && this.from.id !== this.to.id) {
  29364. var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y);
  29365. var fromColor = void 0,
  29366. toColor = void 0;
  29367. fromColor = this.from.options.color.highlight.border;
  29368. toColor = this.to.options.color.highlight.border;
  29369. if (this.from.selected === false && this.to.selected === false) {
  29370. fromColor = util.overrideOpacity(this.from.options.color.border, this.options.color.opacity);
  29371. toColor = util.overrideOpacity(this.to.options.color.border, this.options.color.opacity);
  29372. } else if (this.from.selected === true && this.to.selected === false) {
  29373. toColor = this.to.options.color.border;
  29374. } else if (this.from.selected === false && this.to.selected === true) {
  29375. fromColor = this.from.options.color.border;
  29376. }
  29377. grd.addColorStop(0, fromColor);
  29378. grd.addColorStop(1, toColor);
  29379. // -------------------- this returns -------------------- //
  29380. return grd;
  29381. }
  29382. if (this.colorDirty === true) {
  29383. if (colorOptions.inherit === "to") {
  29384. this.color.highlight = this.to.options.color.highlight.border;
  29385. this.color.hover = this.to.options.color.hover.border;
  29386. this.color.color = util.overrideOpacity(this.to.options.color.border, colorOptions.opacity);
  29387. } else {
  29388. // (this.options.color.inherit.source === "from") {
  29389. this.color.highlight = this.from.options.color.highlight.border;
  29390. this.color.hover = this.from.options.color.hover.border;
  29391. this.color.color = util.overrideOpacity(this.from.options.color.border, colorOptions.opacity);
  29392. }
  29393. }
  29394. } else if (this.colorDirty === true) {
  29395. this.color.highlight = colorOptions.highlight;
  29396. this.color.hover = colorOptions.hover;
  29397. this.color.color = util.overrideOpacity(colorOptions.color, colorOptions.opacity);
  29398. }
  29399. // if color inherit is on and gradients are used, the function has already returned by now.
  29400. this.colorDirty = false;
  29401. if (selected === true) {
  29402. return this.color.highlight;
  29403. } else if (hover === true) {
  29404. return this.color.hover;
  29405. } else {
  29406. return this.color.color;
  29407. }
  29408. }
  29409. /**
  29410. * Draw a line from a node to itself, a circle
  29411. * @param {CanvasRenderingContext2D} ctx
  29412. * @param {Number} x
  29413. * @param {Number} y
  29414. * @param {Number} radius
  29415. * @private
  29416. */
  29417. }, {
  29418. key: '_circle',
  29419. value: function _circle(ctx, x, y, radius) {
  29420. // draw shadow if enabled
  29421. this.enableShadow(ctx);
  29422. // draw a circle
  29423. ctx.beginPath();
  29424. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  29425. ctx.stroke();
  29426. // disable shadows for other elements.
  29427. this.disableShadow(ctx);
  29428. }
  29429. /**
  29430. * Calculate the distance between a point (x3,y3) and a line segment from
  29431. * (x1,y1) to (x2,y2).
  29432. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  29433. * @param {number} x1
  29434. * @param {number} y1
  29435. * @param {number} x2
  29436. * @param {number} y2
  29437. * @param {number} x3
  29438. * @param {number} y3
  29439. * @private
  29440. */
  29441. }, {
  29442. key: 'getDistanceToEdge',
  29443. value: function getDistanceToEdge(x1, y1, x2, y2, x3, y3, via) {
  29444. // x3,y3 is the point
  29445. var returnValue = 0;
  29446. if (this.from != this.to) {
  29447. returnValue = this._getDistanceToEdge(x1, y1, x2, y2, x3, y3, via);
  29448. } else {
  29449. var _getCircleData10 = this._getCircleData();
  29450. var _getCircleData11 = _slicedToArray(_getCircleData10, 3);
  29451. var x = _getCircleData11[0];
  29452. var y = _getCircleData11[1];
  29453. var radius = _getCircleData11[2];
  29454. var dx = x - x3;
  29455. var dy = y - y3;
  29456. returnValue = Math.abs(Math.sqrt(dx * dx + dy * dy) - radius);
  29457. }
  29458. if (this.labelModule.size.left < x3 && this.labelModule.size.left + this.labelModule.size.width > x3 && this.labelModule.size.top < y3 && this.labelModule.size.top + this.labelModule.size.height > y3) {
  29459. return 0;
  29460. } else {
  29461. return returnValue;
  29462. }
  29463. }
  29464. }, {
  29465. key: '_getDistanceToLine',
  29466. value: function _getDistanceToLine(x1, y1, x2, y2, x3, y3) {
  29467. var px = x2 - x1;
  29468. var py = y2 - y1;
  29469. var something = px * px + py * py;
  29470. var u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  29471. if (u > 1) {
  29472. u = 1;
  29473. } else if (u < 0) {
  29474. u = 0;
  29475. }
  29476. var x = x1 + u * px;
  29477. var y = y1 + u * py;
  29478. var dx = x - x3;
  29479. var dy = y - y3;
  29480. //# Note: If the actual distance does not matter,
  29481. //# if you only want to compare what this function
  29482. //# returns to other results of this function, you
  29483. //# can just return the squared distance instead
  29484. //# (i.e. remove the sqrt) to gain a little performance
  29485. return Math.sqrt(dx * dx + dy * dy);
  29486. }
  29487. /**
  29488. *
  29489. * @param ctx
  29490. * @param position
  29491. * @param viaNode
  29492. */
  29493. }, {
  29494. key: 'getArrowData',
  29495. value: function getArrowData(ctx, position, viaNode, selected, hover) {
  29496. // set lets
  29497. var angle = void 0;
  29498. var arrowPoint = void 0;
  29499. var node1 = void 0;
  29500. var node2 = void 0;
  29501. var guideOffset = void 0;
  29502. var scaleFactor = void 0;
  29503. var lineWidth = this.getLineWidth(selected, hover);
  29504. if (position === 'from') {
  29505. node1 = this.from;
  29506. node2 = this.to;
  29507. guideOffset = 0.1;
  29508. scaleFactor = this.options.arrows.from.scaleFactor;
  29509. } else if (position === 'to') {
  29510. node1 = this.to;
  29511. node2 = this.from;
  29512. guideOffset = -0.1;
  29513. scaleFactor = this.options.arrows.to.scaleFactor;
  29514. } else {
  29515. node1 = this.to;
  29516. node2 = this.from;
  29517. scaleFactor = this.options.arrows.middle.scaleFactor;
  29518. }
  29519. // if not connected to itself
  29520. if (node1 != node2) {
  29521. if (position !== 'middle') {
  29522. // draw arrow head
  29523. if (this.options.smooth.enabled === true) {
  29524. arrowPoint = this.findBorderPosition(node1, ctx, { via: viaNode });
  29525. var guidePos = this.getPoint(Math.max(0.0, Math.min(1.0, arrowPoint.t + guideOffset)), viaNode);
  29526. angle = Math.atan2(arrowPoint.y - guidePos.y, arrowPoint.x - guidePos.x);
  29527. } else {
  29528. angle = Math.atan2(node1.y - node2.y, node1.x - node2.x);
  29529. arrowPoint = this.findBorderPosition(node1, ctx);
  29530. }
  29531. } else {
  29532. angle = Math.atan2(node1.y - node2.y, node1.x - node2.x);
  29533. arrowPoint = this.getPoint(0.5, viaNode); // this is 0.6 to account for the size of the arrow.
  29534. }
  29535. } else {
  29536. // draw circle
  29537. var _getCircleData12 = this._getCircleData(ctx);
  29538. var _getCircleData13 = _slicedToArray(_getCircleData12, 3);
  29539. var x = _getCircleData13[0];
  29540. var y = _getCircleData13[1];
  29541. var radius = _getCircleData13[2];
  29542. if (position === 'from') {
  29543. arrowPoint = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 });
  29544. angle = arrowPoint.t * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI;
  29545. } else if (position === 'to') {
  29546. arrowPoint = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.6, high: 1.0, direction: 1 });
  29547. angle = arrowPoint.t * -2 * Math.PI + 1.5 * Math.PI - 1.1 * Math.PI;
  29548. } else {
  29549. arrowPoint = this._pointOnCircle(x, y, radius, 0.175);
  29550. angle = 3.9269908169872414; // === 0.175 * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI;
  29551. }
  29552. }
  29553. var length = 15 * scaleFactor + 3 * lineWidth; // 3* lineWidth is the width of the edge.
  29554. var xi = arrowPoint.x - length * 0.9 * Math.cos(angle);
  29555. var yi = arrowPoint.y - length * 0.9 * Math.sin(angle);
  29556. var arrowCore = { x: xi, y: yi };
  29557. return { point: arrowPoint, core: arrowCore, angle: angle, length: length };
  29558. }
  29559. /**
  29560. *
  29561. * @param ctx
  29562. * @param selected
  29563. * @param hover
  29564. * @param arrowData
  29565. */
  29566. }, {
  29567. key: 'drawArrowHead',
  29568. value: function drawArrowHead(ctx, selected, hover, arrowData) {
  29569. // set style
  29570. ctx.strokeStyle = this.getColor(ctx, selected, hover);
  29571. ctx.fillStyle = ctx.strokeStyle;
  29572. ctx.lineWidth = this.getLineWidth(selected, hover);
  29573. // draw arrow at the end of the line
  29574. ctx.arrow(arrowData.point.x, arrowData.point.y, arrowData.angle, arrowData.length);
  29575. // draw shadow if enabled
  29576. this.enableShadow(ctx);
  29577. ctx.fill();
  29578. // disable shadows for other elements.
  29579. this.disableShadow(ctx);
  29580. }
  29581. }, {
  29582. key: 'enableShadow',
  29583. value: function enableShadow(ctx) {
  29584. if (this.options.shadow.enabled === true) {
  29585. ctx.shadowColor = this.options.shadow.color;
  29586. ctx.shadowBlur = this.options.shadow.size;
  29587. ctx.shadowOffsetX = this.options.shadow.x;
  29588. ctx.shadowOffsetY = this.options.shadow.y;
  29589. }
  29590. }
  29591. }, {
  29592. key: 'disableShadow',
  29593. value: function disableShadow(ctx) {
  29594. if (this.options.shadow.enabled === true) {
  29595. ctx.shadowColor = 'rgba(0,0,0,0)';
  29596. ctx.shadowBlur = 0;
  29597. ctx.shadowOffsetX = 0;
  29598. ctx.shadowOffsetY = 0;
  29599. }
  29600. }
  29601. }]);
  29602. return EdgeBase;
  29603. }();
  29604. exports.default = EdgeBase;
  29605. /***/ },
  29606. /* 90 */
  29607. /***/ function(module, exports, __webpack_require__) {
  29608. "use strict";
  29609. Object.defineProperty(exports, "__esModule", {
  29610. value: true
  29611. });
  29612. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  29613. var _BezierEdgeBase2 = __webpack_require__(88);
  29614. var _BezierEdgeBase3 = _interopRequireDefault(_BezierEdgeBase2);
  29615. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29616. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29617. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  29618. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  29619. var BezierEdgeDynamic = function (_BezierEdgeBase) {
  29620. _inherits(BezierEdgeDynamic, _BezierEdgeBase);
  29621. function BezierEdgeDynamic(options, body, labelModule) {
  29622. _classCallCheck(this, BezierEdgeDynamic);
  29623. // --> this calls the setOptions below
  29624. var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(BezierEdgeDynamic).call(this, options, body, labelModule));
  29625. //this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked.
  29626. _this._boundFunction = function () {
  29627. _this.positionBezierNode();
  29628. };
  29629. _this.body.emitter.on("_repositionBezierNodes", _this._boundFunction);
  29630. return _this;
  29631. }
  29632. _createClass(BezierEdgeDynamic, [{
  29633. key: "setOptions",
  29634. value: function setOptions(options) {
  29635. // check if the physics has changed.
  29636. var physicsChange = false;
  29637. if (this.options.physics !== options.physics) {
  29638. physicsChange = true;
  29639. }
  29640. // set the options and the to and from nodes
  29641. this.options = options;
  29642. this.id = this.options.id;
  29643. this.from = this.body.nodes[this.options.from];
  29644. this.to = this.body.nodes[this.options.to];
  29645. // setup the support node and connect
  29646. this.setupSupportNode();
  29647. this.connect();
  29648. // when we change the physics state of the edge, we reposition the support node.
  29649. if (physicsChange === true) {
  29650. this.via.setOptions({ physics: this.options.physics });
  29651. this.positionBezierNode();
  29652. }
  29653. }
  29654. }, {
  29655. key: "connect",
  29656. value: function connect() {
  29657. this.from = this.body.nodes[this.options.from];
  29658. this.to = this.body.nodes[this.options.to];
  29659. if (this.from === undefined || this.to === undefined || this.options.physics === false) {
  29660. this.via.setOptions({ physics: false });
  29661. } else {
  29662. // fix weird behaviour where a self referencing node has physics enabled
  29663. if (this.from.id === this.to.id) {
  29664. this.via.setOptions({ physics: false });
  29665. } else {
  29666. this.via.setOptions({ physics: true });
  29667. }
  29668. }
  29669. }
  29670. /**
  29671. * remove the support nodes
  29672. * @returns {boolean}
  29673. */
  29674. }, {
  29675. key: "cleanup",
  29676. value: function cleanup() {
  29677. this.body.emitter.off("_repositionBezierNodes", this._boundFunction);
  29678. if (this.via !== undefined) {
  29679. delete this.body.nodes[this.via.id];
  29680. this.via = undefined;
  29681. return true;
  29682. }
  29683. return false;
  29684. }
  29685. /**
  29686. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  29687. * are used for the force calculation.
  29688. *
  29689. * The changed data is not called, if needed, it is returned by the main edge constructor.
  29690. * @private
  29691. */
  29692. }, {
  29693. key: "setupSupportNode",
  29694. value: function setupSupportNode() {
  29695. if (this.via === undefined) {
  29696. var nodeId = "edgeId:" + this.id;
  29697. var node = this.body.functions.createNode({
  29698. id: nodeId,
  29699. shape: 'circle',
  29700. physics: true,
  29701. hidden: true
  29702. });
  29703. this.body.nodes[nodeId] = node;
  29704. this.via = node;
  29705. this.via.parentEdgeId = this.id;
  29706. this.positionBezierNode();
  29707. }
  29708. }
  29709. }, {
  29710. key: "positionBezierNode",
  29711. value: function positionBezierNode() {
  29712. if (this.via !== undefined && this.from !== undefined && this.to !== undefined) {
  29713. this.via.x = 0.5 * (this.from.x + this.to.x);
  29714. this.via.y = 0.5 * (this.from.y + this.to.y);
  29715. } else if (this.via !== undefined) {
  29716. this.via.x = 0;
  29717. this.via.y = 0;
  29718. }
  29719. }
  29720. /**
  29721. * Draw a line between two nodes
  29722. * @param {CanvasRenderingContext2D} ctx
  29723. * @private
  29724. */
  29725. }, {
  29726. key: "_line",
  29727. value: function _line(ctx, viaNode) {
  29728. // draw a straight line
  29729. ctx.beginPath();
  29730. ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
  29731. // fallback to normal straight edges
  29732. if (viaNode.x === undefined) {
  29733. ctx.lineTo(this.toPoint.x, this.toPoint.y);
  29734. } else {
  29735. ctx.quadraticCurveTo(viaNode.x, viaNode.y, this.toPoint.x, this.toPoint.y);
  29736. }
  29737. // draw shadow if enabled
  29738. this.enableShadow(ctx);
  29739. ctx.stroke();
  29740. this.disableShadow(ctx);
  29741. }
  29742. }, {
  29743. key: "getViaNode",
  29744. value: function getViaNode() {
  29745. return this.via;
  29746. }
  29747. /**
  29748. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  29749. * @param percentage
  29750. * @param viaNode
  29751. * @returns {{x: number, y: number}}
  29752. * @private
  29753. */
  29754. }, {
  29755. key: "getPoint",
  29756. value: function getPoint(percentage) {
  29757. var viaNode = arguments.length <= 1 || arguments[1] === undefined ? this.via : arguments[1];
  29758. var t = percentage;
  29759. var x = Math.pow(1 - t, 2) * this.fromPoint.x + 2 * t * (1 - t) * viaNode.x + Math.pow(t, 2) * this.toPoint.x;
  29760. var y = Math.pow(1 - t, 2) * this.fromPoint.y + 2 * t * (1 - t) * viaNode.y + Math.pow(t, 2) * this.toPoint.y;
  29761. return { x: x, y: y };
  29762. }
  29763. }, {
  29764. key: "_findBorderPosition",
  29765. value: function _findBorderPosition(nearNode, ctx) {
  29766. return this._findBorderPositionBezier(nearNode, ctx, this.via);
  29767. }
  29768. }, {
  29769. key: "_getDistanceToEdge",
  29770. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  29771. // x3,y3 is the point
  29772. return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, this.via);
  29773. }
  29774. }]);
  29775. return BezierEdgeDynamic;
  29776. }(_BezierEdgeBase3.default);
  29777. exports.default = BezierEdgeDynamic;
  29778. /***/ },
  29779. /* 91 */
  29780. /***/ function(module, exports, __webpack_require__) {
  29781. 'use strict';
  29782. Object.defineProperty(exports, "__esModule", {
  29783. value: true
  29784. });
  29785. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  29786. var _BezierEdgeBase2 = __webpack_require__(88);
  29787. var _BezierEdgeBase3 = _interopRequireDefault(_BezierEdgeBase2);
  29788. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29789. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29790. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  29791. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  29792. var BezierEdgeStatic = function (_BezierEdgeBase) {
  29793. _inherits(BezierEdgeStatic, _BezierEdgeBase);
  29794. function BezierEdgeStatic(options, body, labelModule) {
  29795. _classCallCheck(this, BezierEdgeStatic);
  29796. return _possibleConstructorReturn(this, Object.getPrototypeOf(BezierEdgeStatic).call(this, options, body, labelModule));
  29797. }
  29798. /**
  29799. * Draw a line between two nodes
  29800. * @param {CanvasRenderingContext2D} ctx
  29801. * @private
  29802. */
  29803. _createClass(BezierEdgeStatic, [{
  29804. key: '_line',
  29805. value: function _line(ctx, viaNode) {
  29806. // draw a straight line
  29807. ctx.beginPath();
  29808. ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
  29809. // fallback to normal straight edges
  29810. if (viaNode.x === undefined) {
  29811. ctx.lineTo(this.toPoint.x, this.toPoint.y);
  29812. } else {
  29813. ctx.quadraticCurveTo(viaNode.x, viaNode.y, this.toPoint.x, this.toPoint.y);
  29814. }
  29815. // draw shadow if enabled
  29816. this.enableShadow(ctx);
  29817. ctx.stroke();
  29818. this.disableShadow(ctx);
  29819. }
  29820. }, {
  29821. key: 'getViaNode',
  29822. value: function getViaNode() {
  29823. return this._getViaCoordinates();
  29824. }
  29825. /**
  29826. * We do not use the to and fromPoints here to make the via nodes the same as edges without arrows.
  29827. * @returns {{x: undefined, y: undefined}}
  29828. * @private
  29829. */
  29830. }, {
  29831. key: '_getViaCoordinates',
  29832. value: function _getViaCoordinates() {
  29833. var xVia = undefined;
  29834. var yVia = undefined;
  29835. var factor = this.options.smooth.roundness;
  29836. var type = this.options.smooth.type;
  29837. var dx = Math.abs(this.from.x - this.to.x);
  29838. var dy = Math.abs(this.from.y - this.to.y);
  29839. if (type === 'discrete' || type === 'diagonalCross') {
  29840. if (Math.abs(this.from.x - this.to.x) <= Math.abs(this.from.y - this.to.y)) {
  29841. if (this.from.y >= this.to.y) {
  29842. if (this.from.x <= this.to.x) {
  29843. xVia = this.from.x + factor * dy;
  29844. yVia = this.from.y - factor * dy;
  29845. } else if (this.from.x > this.to.x) {
  29846. xVia = this.from.x - factor * dy;
  29847. yVia = this.from.y - factor * dy;
  29848. }
  29849. } else if (this.from.y < this.to.y) {
  29850. if (this.from.x <= this.to.x) {
  29851. xVia = this.from.x + factor * dy;
  29852. yVia = this.from.y + factor * dy;
  29853. } else if (this.from.x > this.to.x) {
  29854. xVia = this.from.x - factor * dy;
  29855. yVia = this.from.y + factor * dy;
  29856. }
  29857. }
  29858. if (type === "discrete") {
  29859. xVia = dx < factor * dy ? this.from.x : xVia;
  29860. }
  29861. } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  29862. if (this.from.y >= this.to.y) {
  29863. if (this.from.x <= this.to.x) {
  29864. xVia = this.from.x + factor * dx;
  29865. yVia = this.from.y - factor * dx;
  29866. } else if (this.from.x > this.to.x) {
  29867. xVia = this.from.x - factor * dx;
  29868. yVia = this.from.y - factor * dx;
  29869. }
  29870. } else if (this.from.y < this.to.y) {
  29871. if (this.from.x <= this.to.x) {
  29872. xVia = this.from.x + factor * dx;
  29873. yVia = this.from.y + factor * dx;
  29874. } else if (this.from.x > this.to.x) {
  29875. xVia = this.from.x - factor * dx;
  29876. yVia = this.from.y + factor * dx;
  29877. }
  29878. }
  29879. if (type === "discrete") {
  29880. yVia = dy < factor * dx ? this.from.y : yVia;
  29881. }
  29882. }
  29883. } else if (type === "straightCross") {
  29884. if (Math.abs(this.from.x - this.to.x) <= Math.abs(this.from.y - this.to.y)) {
  29885. // up - down
  29886. xVia = this.from.x;
  29887. if (this.from.y < this.to.y) {
  29888. yVia = this.to.y - (1 - factor) * dy;
  29889. } else {
  29890. yVia = this.to.y + (1 - factor) * dy;
  29891. }
  29892. } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  29893. // left - right
  29894. if (this.from.x < this.to.x) {
  29895. xVia = this.to.x - (1 - factor) * dx;
  29896. } else {
  29897. xVia = this.to.x + (1 - factor) * dx;
  29898. }
  29899. yVia = this.from.y;
  29900. }
  29901. } else if (type === 'horizontal') {
  29902. if (this.from.x < this.to.x) {
  29903. xVia = this.to.x - (1 - factor) * dx;
  29904. } else {
  29905. xVia = this.to.x + (1 - factor) * dx;
  29906. }
  29907. yVia = this.from.y;
  29908. } else if (type === 'vertical') {
  29909. xVia = this.from.x;
  29910. if (this.from.y < this.to.y) {
  29911. yVia = this.to.y - (1 - factor) * dy;
  29912. } else {
  29913. yVia = this.to.y + (1 - factor) * dy;
  29914. }
  29915. } else if (type === 'curvedCW') {
  29916. dx = this.to.x - this.from.x;
  29917. dy = this.from.y - this.to.y;
  29918. var radius = Math.sqrt(dx * dx + dy * dy);
  29919. var pi = Math.PI;
  29920. var originalAngle = Math.atan2(dy, dx);
  29921. var myAngle = (originalAngle + (factor * 0.5 + 0.5) * pi) % (2 * pi);
  29922. xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle);
  29923. yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle);
  29924. } else if (type === 'curvedCCW') {
  29925. dx = this.to.x - this.from.x;
  29926. dy = this.from.y - this.to.y;
  29927. var _radius = Math.sqrt(dx * dx + dy * dy);
  29928. var _pi = Math.PI;
  29929. var _originalAngle = Math.atan2(dy, dx);
  29930. var _myAngle = (_originalAngle + (-factor * 0.5 + 0.5) * _pi) % (2 * _pi);
  29931. xVia = this.from.x + (factor * 0.5 + 0.5) * _radius * Math.sin(_myAngle);
  29932. yVia = this.from.y + (factor * 0.5 + 0.5) * _radius * Math.cos(_myAngle);
  29933. } else {
  29934. // continuous
  29935. if (Math.abs(this.from.x - this.to.x) <= Math.abs(this.from.y - this.to.y)) {
  29936. if (this.from.y >= this.to.y) {
  29937. if (this.from.x <= this.to.x) {
  29938. xVia = this.from.x + factor * dy;
  29939. yVia = this.from.y - factor * dy;
  29940. xVia = this.to.x < xVia ? this.to.x : xVia;
  29941. } else if (this.from.x > this.to.x) {
  29942. xVia = this.from.x - factor * dy;
  29943. yVia = this.from.y - factor * dy;
  29944. xVia = this.to.x > xVia ? this.to.x : xVia;
  29945. }
  29946. } else if (this.from.y < this.to.y) {
  29947. if (this.from.x <= this.to.x) {
  29948. xVia = this.from.x + factor * dy;
  29949. yVia = this.from.y + factor * dy;
  29950. xVia = this.to.x < xVia ? this.to.x : xVia;
  29951. } else if (this.from.x > this.to.x) {
  29952. xVia = this.from.x - factor * dy;
  29953. yVia = this.from.y + factor * dy;
  29954. xVia = this.to.x > xVia ? this.to.x : xVia;
  29955. }
  29956. }
  29957. } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
  29958. if (this.from.y >= this.to.y) {
  29959. if (this.from.x <= this.to.x) {
  29960. xVia = this.from.x + factor * dx;
  29961. yVia = this.from.y - factor * dx;
  29962. yVia = this.to.y > yVia ? this.to.y : yVia;
  29963. } else if (this.from.x > this.to.x) {
  29964. xVia = this.from.x - factor * dx;
  29965. yVia = this.from.y - factor * dx;
  29966. yVia = this.to.y > yVia ? this.to.y : yVia;
  29967. }
  29968. } else if (this.from.y < this.to.y) {
  29969. if (this.from.x <= this.to.x) {
  29970. xVia = this.from.x + factor * dx;
  29971. yVia = this.from.y + factor * dx;
  29972. yVia = this.to.y < yVia ? this.to.y : yVia;
  29973. } else if (this.from.x > this.to.x) {
  29974. xVia = this.from.x - factor * dx;
  29975. yVia = this.from.y + factor * dx;
  29976. yVia = this.to.y < yVia ? this.to.y : yVia;
  29977. }
  29978. }
  29979. }
  29980. }
  29981. return { x: xVia, y: yVia };
  29982. }
  29983. }, {
  29984. key: '_findBorderPosition',
  29985. value: function _findBorderPosition(nearNode, ctx) {
  29986. var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  29987. return this._findBorderPositionBezier(nearNode, ctx, options.via);
  29988. }
  29989. }, {
  29990. key: '_getDistanceToEdge',
  29991. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  29992. var viaNode = arguments.length <= 6 || arguments[6] === undefined ? this._getViaCoordinates() : arguments[6];
  29993. // x3,y3 is the point
  29994. return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, viaNode);
  29995. }
  29996. /**
  29997. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  29998. * @param percentage
  29999. * @param viaNode
  30000. * @returns {{x: number, y: number}}
  30001. * @private
  30002. */
  30003. }, {
  30004. key: 'getPoint',
  30005. value: function getPoint(percentage) {
  30006. var viaNode = arguments.length <= 1 || arguments[1] === undefined ? this._getViaCoordinates() : arguments[1];
  30007. var t = percentage;
  30008. var x = Math.pow(1 - t, 2) * this.fromPoint.x + 2 * t * (1 - t) * viaNode.x + Math.pow(t, 2) * this.toPoint.x;
  30009. var y = Math.pow(1 - t, 2) * this.fromPoint.y + 2 * t * (1 - t) * viaNode.y + Math.pow(t, 2) * this.toPoint.y;
  30010. return { x: x, y: y };
  30011. }
  30012. }]);
  30013. return BezierEdgeStatic;
  30014. }(_BezierEdgeBase3.default);
  30015. exports.default = BezierEdgeStatic;
  30016. /***/ },
  30017. /* 92 */
  30018. /***/ function(module, exports, __webpack_require__) {
  30019. 'use strict';
  30020. Object.defineProperty(exports, "__esModule", {
  30021. value: true
  30022. });
  30023. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  30024. var _EdgeBase2 = __webpack_require__(89);
  30025. var _EdgeBase3 = _interopRequireDefault(_EdgeBase2);
  30026. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30027. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30028. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  30029. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  30030. var StraightEdge = function (_EdgeBase) {
  30031. _inherits(StraightEdge, _EdgeBase);
  30032. function StraightEdge(options, body, labelModule) {
  30033. _classCallCheck(this, StraightEdge);
  30034. return _possibleConstructorReturn(this, Object.getPrototypeOf(StraightEdge).call(this, options, body, labelModule));
  30035. }
  30036. /**
  30037. * Draw a line between two nodes
  30038. * @param {CanvasRenderingContext2D} ctx
  30039. * @private
  30040. */
  30041. _createClass(StraightEdge, [{
  30042. key: '_line',
  30043. value: function _line(ctx) {
  30044. // draw a straight line
  30045. ctx.beginPath();
  30046. ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
  30047. ctx.lineTo(this.toPoint.x, this.toPoint.y);
  30048. // draw shadow if enabled
  30049. this.enableShadow(ctx);
  30050. ctx.stroke();
  30051. this.disableShadow(ctx);
  30052. }
  30053. }, {
  30054. key: 'getViaNode',
  30055. value: function getViaNode() {
  30056. return undefined;
  30057. }
  30058. /**
  30059. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  30060. * @param percentage
  30061. * @param via
  30062. * @returns {{x: number, y: number}}
  30063. * @private
  30064. */
  30065. }, {
  30066. key: 'getPoint',
  30067. value: function getPoint(percentage) {
  30068. return {
  30069. x: (1 - percentage) * this.fromPoint.x + percentage * this.toPoint.x,
  30070. y: (1 - percentage) * this.fromPoint.y + percentage * this.toPoint.y
  30071. };
  30072. }
  30073. }, {
  30074. key: '_findBorderPosition',
  30075. value: function _findBorderPosition(nearNode, ctx) {
  30076. var node1 = this.to;
  30077. var node2 = this.from;
  30078. if (nearNode.id === this.from.id) {
  30079. node1 = this.from;
  30080. node2 = this.to;
  30081. }
  30082. var angle = Math.atan2(node1.y - node2.y, node1.x - node2.x);
  30083. var dx = node1.x - node2.x;
  30084. var dy = node1.y - node2.y;
  30085. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  30086. var toBorderDist = nearNode.distanceToBorder(ctx, angle);
  30087. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  30088. var borderPos = {};
  30089. borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x;
  30090. borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y;
  30091. return borderPos;
  30092. }
  30093. }, {
  30094. key: '_getDistanceToEdge',
  30095. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  30096. // x3,y3 is the point
  30097. return this._getDistanceToLine(x1, y1, x2, y2, x3, y3);
  30098. }
  30099. }]);
  30100. return StraightEdge;
  30101. }(_EdgeBase3.default);
  30102. exports.default = StraightEdge;
  30103. /***/ },
  30104. /* 93 */
  30105. /***/ function(module, exports, __webpack_require__) {
  30106. 'use strict';
  30107. Object.defineProperty(exports, "__esModule", {
  30108. value: true
  30109. });
  30110. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  30111. var _BarnesHutSolver = __webpack_require__(94);
  30112. var _BarnesHutSolver2 = _interopRequireDefault(_BarnesHutSolver);
  30113. var _RepulsionSolver = __webpack_require__(95);
  30114. var _RepulsionSolver2 = _interopRequireDefault(_RepulsionSolver);
  30115. var _HierarchicalRepulsionSolver = __webpack_require__(96);
  30116. var _HierarchicalRepulsionSolver2 = _interopRequireDefault(_HierarchicalRepulsionSolver);
  30117. var _SpringSolver = __webpack_require__(97);
  30118. var _SpringSolver2 = _interopRequireDefault(_SpringSolver);
  30119. var _HierarchicalSpringSolver = __webpack_require__(98);
  30120. var _HierarchicalSpringSolver2 = _interopRequireDefault(_HierarchicalSpringSolver);
  30121. var _CentralGravitySolver = __webpack_require__(99);
  30122. var _CentralGravitySolver2 = _interopRequireDefault(_CentralGravitySolver);
  30123. var _FA2BasedRepulsionSolver = __webpack_require__(100);
  30124. var _FA2BasedRepulsionSolver2 = _interopRequireDefault(_FA2BasedRepulsionSolver);
  30125. var _FA2BasedCentralGravitySolver = __webpack_require__(101);
  30126. var _FA2BasedCentralGravitySolver2 = _interopRequireDefault(_FA2BasedCentralGravitySolver);
  30127. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30128. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30129. var util = __webpack_require__(1);
  30130. var PhysicsEngine = function () {
  30131. function PhysicsEngine(body) {
  30132. _classCallCheck(this, PhysicsEngine);
  30133. this.body = body;
  30134. this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} };
  30135. this.physicsEnabled = true;
  30136. this.simulationInterval = 1000 / 60;
  30137. this.requiresTimeout = true;
  30138. this.previousStates = {};
  30139. this.referenceState = {};
  30140. this.freezeCache = {};
  30141. this.renderTimer = undefined;
  30142. // parameters for the adaptive timestep
  30143. this.adaptiveTimestep = false;
  30144. this.adaptiveTimestepEnabled = false;
  30145. this.adaptiveCounter = 0;
  30146. this.adaptiveInterval = 3;
  30147. this.stabilized = false;
  30148. this.startedStabilization = false;
  30149. this.stabilizationIterations = 0;
  30150. this.ready = false; // will be set to true if the stabilize
  30151. // default options
  30152. this.options = {};
  30153. this.defaultOptions = {
  30154. enabled: true,
  30155. barnesHut: {
  30156. theta: 0.5,
  30157. gravitationalConstant: -2000,
  30158. centralGravity: 0.3,
  30159. springLength: 95,
  30160. springConstant: 0.04,
  30161. damping: 0.09,
  30162. avoidOverlap: 0
  30163. },
  30164. forceAtlas2Based: {
  30165. theta: 0.5,
  30166. gravitationalConstant: -50,
  30167. centralGravity: 0.01,
  30168. springConstant: 0.08,
  30169. springLength: 100,
  30170. damping: 0.4,
  30171. avoidOverlap: 0
  30172. },
  30173. repulsion: {
  30174. centralGravity: 0.2,
  30175. springLength: 200,
  30176. springConstant: 0.05,
  30177. nodeDistance: 100,
  30178. damping: 0.09,
  30179. avoidOverlap: 0
  30180. },
  30181. hierarchicalRepulsion: {
  30182. centralGravity: 0.0,
  30183. springLength: 100,
  30184. springConstant: 0.01,
  30185. nodeDistance: 120,
  30186. damping: 0.09
  30187. },
  30188. maxVelocity: 50,
  30189. minVelocity: 0.75, // px/s
  30190. solver: 'barnesHut',
  30191. stabilization: {
  30192. enabled: true,
  30193. iterations: 1000, // maximum number of iteration to stabilize
  30194. updateInterval: 50,
  30195. onlyDynamicEdges: false,
  30196. fit: true
  30197. },
  30198. timestep: 0.5,
  30199. adaptiveTimestep: true
  30200. };
  30201. util.extend(this.options, this.defaultOptions);
  30202. this.timestep = 0.5;
  30203. this.layoutFailed = false;
  30204. this.bindEventListeners();
  30205. }
  30206. _createClass(PhysicsEngine, [{
  30207. key: 'bindEventListeners',
  30208. value: function bindEventListeners() {
  30209. var _this = this;
  30210. this.body.emitter.on('initPhysics', function () {
  30211. _this.initPhysics();
  30212. });
  30213. this.body.emitter.on('_layoutFailed', function () {
  30214. _this.layoutFailed = true;
  30215. });
  30216. this.body.emitter.on('resetPhysics', function () {
  30217. _this.stopSimulation();_this.ready = false;
  30218. });
  30219. this.body.emitter.on('disablePhysics', function () {
  30220. _this.physicsEnabled = false;_this.stopSimulation();
  30221. });
  30222. this.body.emitter.on('restorePhysics', function () {
  30223. _this.setOptions(_this.options);
  30224. if (_this.ready === true) {
  30225. _this.startSimulation();
  30226. }
  30227. });
  30228. this.body.emitter.on('startSimulation', function () {
  30229. if (_this.ready === true) {
  30230. _this.startSimulation();
  30231. }
  30232. });
  30233. this.body.emitter.on('stopSimulation', function () {
  30234. _this.stopSimulation();
  30235. });
  30236. this.body.emitter.on('destroy', function () {
  30237. _this.stopSimulation(false);
  30238. _this.body.emitter.off();
  30239. });
  30240. // this event will trigger a rebuilding of the cache everything. Used when nodes or edges have been added or removed.
  30241. this.body.emitter.on("_dataChanged", function () {
  30242. // update shortcut lists
  30243. _this.updatePhysicsData();
  30244. });
  30245. // debug: show forces
  30246. // this.body.emitter.on("afterDrawing", (ctx) => {this._drawForces(ctx);});
  30247. }
  30248. /**
  30249. * set the physics options
  30250. * @param options
  30251. */
  30252. }, {
  30253. key: 'setOptions',
  30254. value: function setOptions(options) {
  30255. if (options !== undefined) {
  30256. if (options === false) {
  30257. this.options.enabled = false;
  30258. this.physicsEnabled = false;
  30259. this.stopSimulation();
  30260. } else {
  30261. this.physicsEnabled = true;
  30262. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  30263. util.mergeOptions(this.options, options, 'stabilization');
  30264. if (options.enabled === undefined) {
  30265. this.options.enabled = true;
  30266. }
  30267. if (this.options.enabled === false) {
  30268. this.physicsEnabled = false;
  30269. this.stopSimulation();
  30270. }
  30271. // set the timestep
  30272. this.timestep = this.options.timestep;
  30273. }
  30274. }
  30275. this.init();
  30276. }
  30277. /**
  30278. * configure the engine.
  30279. */
  30280. }, {
  30281. key: 'init',
  30282. value: function init() {
  30283. var options;
  30284. if (this.options.solver === 'forceAtlas2Based') {
  30285. options = this.options.forceAtlas2Based;
  30286. this.nodesSolver = new _FA2BasedRepulsionSolver2.default(this.body, this.physicsBody, options);
  30287. this.edgesSolver = new _SpringSolver2.default(this.body, this.physicsBody, options);
  30288. this.gravitySolver = new _FA2BasedCentralGravitySolver2.default(this.body, this.physicsBody, options);
  30289. } else if (this.options.solver === 'repulsion') {
  30290. options = this.options.repulsion;
  30291. this.nodesSolver = new _RepulsionSolver2.default(this.body, this.physicsBody, options);
  30292. this.edgesSolver = new _SpringSolver2.default(this.body, this.physicsBody, options);
  30293. this.gravitySolver = new _CentralGravitySolver2.default(this.body, this.physicsBody, options);
  30294. } else if (this.options.solver === 'hierarchicalRepulsion') {
  30295. options = this.options.hierarchicalRepulsion;
  30296. this.nodesSolver = new _HierarchicalRepulsionSolver2.default(this.body, this.physicsBody, options);
  30297. this.edgesSolver = new _HierarchicalSpringSolver2.default(this.body, this.physicsBody, options);
  30298. this.gravitySolver = new _CentralGravitySolver2.default(this.body, this.physicsBody, options);
  30299. } else {
  30300. // barnesHut
  30301. options = this.options.barnesHut;
  30302. this.nodesSolver = new _BarnesHutSolver2.default(this.body, this.physicsBody, options);
  30303. this.edgesSolver = new _SpringSolver2.default(this.body, this.physicsBody, options);
  30304. this.gravitySolver = new _CentralGravitySolver2.default(this.body, this.physicsBody, options);
  30305. }
  30306. this.modelOptions = options;
  30307. }
  30308. /**
  30309. * initialize the engine
  30310. */
  30311. }, {
  30312. key: 'initPhysics',
  30313. value: function initPhysics() {
  30314. if (this.physicsEnabled === true && this.options.enabled === true) {
  30315. if (this.options.stabilization.enabled === true) {
  30316. this.stabilize();
  30317. } else {
  30318. this.stabilized = false;
  30319. this.ready = true;
  30320. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  30321. this.startSimulation();
  30322. }
  30323. } else {
  30324. this.ready = true;
  30325. this.body.emitter.emit('fit');
  30326. }
  30327. }
  30328. /**
  30329. * Start the simulation
  30330. */
  30331. }, {
  30332. key: 'startSimulation',
  30333. value: function startSimulation() {
  30334. if (this.physicsEnabled === true && this.options.enabled === true) {
  30335. this.stabilized = false;
  30336. // when visible, adaptivity is disabled.
  30337. this.adaptiveTimestep = false;
  30338. // this sets the width of all nodes initially which could be required for the avoidOverlap
  30339. this.body.emitter.emit("_resizeNodes");
  30340. if (this.viewFunction === undefined) {
  30341. this.viewFunction = this.simulationStep.bind(this);
  30342. this.body.emitter.on('initRedraw', this.viewFunction);
  30343. this.body.emitter.emit('_startRendering');
  30344. }
  30345. } else {
  30346. this.body.emitter.emit('_redraw');
  30347. }
  30348. }
  30349. /**
  30350. * Stop the simulation, force stabilization.
  30351. */
  30352. }, {
  30353. key: 'stopSimulation',
  30354. value: function stopSimulation() {
  30355. var emit = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
  30356. this.stabilized = true;
  30357. if (emit === true) {
  30358. this._emitStabilized();
  30359. }
  30360. if (this.viewFunction !== undefined) {
  30361. this.body.emitter.off('initRedraw', this.viewFunction);
  30362. this.viewFunction = undefined;
  30363. if (emit === true) {
  30364. this.body.emitter.emit('_stopRendering');
  30365. }
  30366. }
  30367. }
  30368. /**
  30369. * The viewFunction inserts this step into each render loop. It calls the physics tick and handles the cleanup at stabilized.
  30370. *
  30371. */
  30372. }, {
  30373. key: 'simulationStep',
  30374. value: function simulationStep() {
  30375. // check if the physics have settled
  30376. var startTime = Date.now();
  30377. this.physicsTick();
  30378. var physicsTime = Date.now() - startTime;
  30379. // run double speed if it is a little graph
  30380. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  30381. this.physicsTick();
  30382. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  30383. this.runDoubleSpeed = true;
  30384. }
  30385. if (this.stabilized === true) {
  30386. this.stopSimulation();
  30387. }
  30388. }
  30389. /**
  30390. * trigger the stabilized event.
  30391. * @private
  30392. */
  30393. }, {
  30394. key: '_emitStabilized',
  30395. value: function _emitStabilized() {
  30396. var _this2 = this;
  30397. var amountOfIterations = arguments.length <= 0 || arguments[0] === undefined ? this.stabilizationIterations : arguments[0];
  30398. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  30399. setTimeout(function () {
  30400. _this2.body.emitter.emit('stabilized', { iterations: amountOfIterations });
  30401. _this2.startedStabilization = false;
  30402. _this2.stabilizationIterations = 0;
  30403. }, 0);
  30404. }
  30405. }
  30406. /**
  30407. * A single simulation step (or 'tick') in the physics simulation
  30408. *
  30409. * @private
  30410. */
  30411. }, {
  30412. key: 'physicsTick',
  30413. value: function physicsTick() {
  30414. // this is here to ensure that there is no start event when the network is already stable.
  30415. if (this.startedStabilization === false) {
  30416. this.body.emitter.emit('startStabilizing');
  30417. this.startedStabilization = true;
  30418. }
  30419. if (this.stabilized === false) {
  30420. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  30421. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  30422. // this is the factor for increasing the timestep on success.
  30423. var factor = 1.2;
  30424. // we assume the adaptive interval is
  30425. if (this.adaptiveCounter % this.adaptiveInterval === 0) {
  30426. // we leave the timestep stable for "interval" iterations.
  30427. // first the big step and revert. Revert saves the reference state.
  30428. this.timestep = 2 * this.timestep;
  30429. this.calculateForces();
  30430. this.moveNodes();
  30431. this.revert();
  30432. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  30433. this.timestep = 0.5 * this.timestep;
  30434. // since it's half the step, we do it twice.
  30435. this.calculateForces();
  30436. this.moveNodes();
  30437. this.calculateForces();
  30438. this.moveNodes();
  30439. // we compare the two steps. if it is acceptable we double the step.
  30440. if (this._evaluateStepQuality() === true) {
  30441. this.timestep = factor * this.timestep;
  30442. } else {
  30443. // if not, we decrease the step to a minimum of the options timestep.
  30444. // if the decreased timestep is smaller than the options step, we do not reset the counter
  30445. // we assume that the options timestep is stable enough.
  30446. if (this.timestep / factor < this.options.timestep) {
  30447. this.timestep = this.options.timestep;
  30448. } else {
  30449. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  30450. // that large instabilities do not form.
  30451. this.adaptiveCounter = -1; // check again next iteration
  30452. this.timestep = Math.max(this.options.timestep, this.timestep / factor);
  30453. }
  30454. }
  30455. } else {
  30456. // normal step, keeping timestep constant
  30457. this.calculateForces();
  30458. this.moveNodes();
  30459. }
  30460. // increment the counter
  30461. this.adaptiveCounter += 1;
  30462. } else {
  30463. // case for the static timestep, we reset it to the one in options and take a normal step.
  30464. this.timestep = this.options.timestep;
  30465. this.calculateForces();
  30466. this.moveNodes();
  30467. }
  30468. // determine if the network has stabilzied
  30469. if (this.stabilized === true) {
  30470. this.revert();
  30471. }
  30472. this.stabilizationIterations++;
  30473. }
  30474. }
  30475. /**
  30476. * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time.
  30477. *
  30478. * @private
  30479. */
  30480. }, {
  30481. key: 'updatePhysicsData',
  30482. value: function updatePhysicsData() {
  30483. this.physicsBody.forces = {};
  30484. this.physicsBody.physicsNodeIndices = [];
  30485. this.physicsBody.physicsEdgeIndices = [];
  30486. var nodes = this.body.nodes;
  30487. var edges = this.body.edges;
  30488. // get node indices for physics
  30489. for (var nodeId in nodes) {
  30490. if (nodes.hasOwnProperty(nodeId)) {
  30491. if (nodes[nodeId].options.physics === true) {
  30492. this.physicsBody.physicsNodeIndices.push(nodes[nodeId].id);
  30493. }
  30494. }
  30495. }
  30496. // get edge indices for physics
  30497. for (var edgeId in edges) {
  30498. if (edges.hasOwnProperty(edgeId)) {
  30499. if (edges[edgeId].options.physics === true) {
  30500. this.physicsBody.physicsEdgeIndices.push(edges[edgeId].id);
  30501. }
  30502. }
  30503. }
  30504. // get the velocity and the forces vector
  30505. for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  30506. var _nodeId = this.physicsBody.physicsNodeIndices[i];
  30507. this.physicsBody.forces[_nodeId] = { x: 0, y: 0 };
  30508. // forces can be reset because they are recalculated. Velocities have to persist.
  30509. if (this.physicsBody.velocities[_nodeId] === undefined) {
  30510. this.physicsBody.velocities[_nodeId] = { x: 0, y: 0 };
  30511. }
  30512. }
  30513. // clean deleted nodes from the velocity vector
  30514. for (var _nodeId2 in this.physicsBody.velocities) {
  30515. if (nodes[_nodeId2] === undefined) {
  30516. delete this.physicsBody.velocities[_nodeId2];
  30517. }
  30518. }
  30519. }
  30520. /**
  30521. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  30522. */
  30523. }, {
  30524. key: 'revert',
  30525. value: function revert() {
  30526. var nodeIds = Object.keys(this.previousStates);
  30527. var nodes = this.body.nodes;
  30528. var velocities = this.physicsBody.velocities;
  30529. this.referenceState = {};
  30530. for (var i = 0; i < nodeIds.length; i++) {
  30531. var nodeId = nodeIds[i];
  30532. if (nodes[nodeId] !== undefined) {
  30533. if (nodes[nodeId].options.physics === true) {
  30534. this.referenceState[nodeId] = {
  30535. positions: { x: nodes[nodeId].x, y: nodes[nodeId].y }
  30536. };
  30537. velocities[nodeId].x = this.previousStates[nodeId].vx;
  30538. velocities[nodeId].y = this.previousStates[nodeId].vy;
  30539. nodes[nodeId].x = this.previousStates[nodeId].x;
  30540. nodes[nodeId].y = this.previousStates[nodeId].y;
  30541. }
  30542. } else {
  30543. delete this.previousStates[nodeId];
  30544. }
  30545. }
  30546. }
  30547. /**
  30548. * This compares the reference state to the current state
  30549. */
  30550. }, {
  30551. key: '_evaluateStepQuality',
  30552. value: function _evaluateStepQuality() {
  30553. var dx = void 0,
  30554. dy = void 0,
  30555. dpos = void 0;
  30556. var nodes = this.body.nodes;
  30557. var reference = this.referenceState;
  30558. var posThreshold = 0.3;
  30559. for (var nodeId in this.referenceState) {
  30560. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  30561. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  30562. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  30563. dpos = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  30564. if (dpos > posThreshold) {
  30565. return false;
  30566. }
  30567. }
  30568. }
  30569. return true;
  30570. }
  30571. /**
  30572. * move the nodes one timestep and check if they are stabilized
  30573. * @returns {boolean}
  30574. */
  30575. }, {
  30576. key: 'moveNodes',
  30577. value: function moveNodes() {
  30578. var nodeIndices = this.physicsBody.physicsNodeIndices;
  30579. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  30580. var maxNodeVelocity = 0;
  30581. var averageNodeVelocity = 0;
  30582. // the velocity threshold (energy in the system) for the adaptivity toggle
  30583. var velocityAdaptiveThreshold = 5;
  30584. for (var i = 0; i < nodeIndices.length; i++) {
  30585. var nodeId = nodeIndices[i];
  30586. var nodeVelocity = this._performStep(nodeId, maxVelocity);
  30587. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  30588. maxNodeVelocity = Math.max(maxNodeVelocity, nodeVelocity);
  30589. averageNodeVelocity += nodeVelocity;
  30590. }
  30591. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  30592. this.adaptiveTimestepEnabled = averageNodeVelocity / nodeIndices.length < velocityAdaptiveThreshold;
  30593. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  30594. }
  30595. /**
  30596. * Perform the actual step
  30597. *
  30598. * @param nodeId
  30599. * @param maxVelocity
  30600. * @returns {number}
  30601. * @private
  30602. */
  30603. }, {
  30604. key: '_performStep',
  30605. value: function _performStep(nodeId, maxVelocity) {
  30606. var node = this.body.nodes[nodeId];
  30607. var timestep = this.timestep;
  30608. var forces = this.physicsBody.forces;
  30609. var velocities = this.physicsBody.velocities;
  30610. // store the state so we can revert
  30611. this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocities[nodeId].x, vy: velocities[nodeId].y };
  30612. if (node.options.fixed.x === false) {
  30613. var dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  30614. var ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  30615. velocities[nodeId].x += ax * timestep; // velocity
  30616. velocities[nodeId].x = Math.abs(velocities[nodeId].x) > maxVelocity ? velocities[nodeId].x > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].x;
  30617. node.x += velocities[nodeId].x * timestep; // position
  30618. } else {
  30619. forces[nodeId].x = 0;
  30620. velocities[nodeId].x = 0;
  30621. }
  30622. if (node.options.fixed.y === false) {
  30623. var dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  30624. var ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  30625. velocities[nodeId].y += ay * timestep; // velocity
  30626. velocities[nodeId].y = Math.abs(velocities[nodeId].y) > maxVelocity ? velocities[nodeId].y > 0 ? maxVelocity : -maxVelocity : velocities[nodeId].y;
  30627. node.y += velocities[nodeId].y * timestep; // position
  30628. } else {
  30629. forces[nodeId].y = 0;
  30630. velocities[nodeId].y = 0;
  30631. }
  30632. var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x, 2) + Math.pow(velocities[nodeId].y, 2));
  30633. return totalVelocity;
  30634. }
  30635. /**
  30636. * calculate the forces for one physics iteration.
  30637. */
  30638. }, {
  30639. key: 'calculateForces',
  30640. value: function calculateForces() {
  30641. this.gravitySolver.solve();
  30642. this.nodesSolver.solve();
  30643. this.edgesSolver.solve();
  30644. }
  30645. /**
  30646. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  30647. * because only the supportnodes for the smoothCurves have to settle.
  30648. *
  30649. * @private
  30650. */
  30651. }, {
  30652. key: '_freezeNodes',
  30653. value: function _freezeNodes() {
  30654. var nodes = this.body.nodes;
  30655. for (var id in nodes) {
  30656. if (nodes.hasOwnProperty(id)) {
  30657. if (nodes[id].x && nodes[id].y) {
  30658. this.freezeCache[id] = { x: nodes[id].options.fixed.x, y: nodes[id].options.fixed.y };
  30659. nodes[id].options.fixed.x = true;
  30660. nodes[id].options.fixed.y = true;
  30661. }
  30662. }
  30663. }
  30664. }
  30665. /**
  30666. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  30667. *
  30668. * @private
  30669. */
  30670. }, {
  30671. key: '_restoreFrozenNodes',
  30672. value: function _restoreFrozenNodes() {
  30673. var nodes = this.body.nodes;
  30674. for (var id in nodes) {
  30675. if (nodes.hasOwnProperty(id)) {
  30676. if (this.freezeCache[id] !== undefined) {
  30677. nodes[id].options.fixed.x = this.freezeCache[id].x;
  30678. nodes[id].options.fixed.y = this.freezeCache[id].y;
  30679. }
  30680. }
  30681. }
  30682. this.freezeCache = {};
  30683. }
  30684. /**
  30685. * Find a stable position for all nodes
  30686. */
  30687. }, {
  30688. key: 'stabilize',
  30689. value: function stabilize() {
  30690. var _this3 = this;
  30691. var iterations = arguments.length <= 0 || arguments[0] === undefined ? this.options.stabilization.iterations : arguments[0];
  30692. if (typeof iterations !== 'number') {
  30693. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  30694. iterations = this.options.stabilization.iterations;
  30695. }
  30696. if (this.physicsBody.physicsNodeIndices.length === 0) {
  30697. this.ready = true;
  30698. return;
  30699. }
  30700. // enable adaptive timesteps
  30701. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  30702. // this sets the width of all nodes initially which could be required for the avoidOverlap
  30703. this.body.emitter.emit("_resizeNodes");
  30704. // stop the render loop
  30705. this.stopSimulation();
  30706. // set stabilze to false
  30707. this.stabilized = false;
  30708. // block redraw requests
  30709. this.body.emitter.emit('_blockRedraw');
  30710. this.targetIterations = iterations;
  30711. // start the stabilization
  30712. if (this.options.stabilization.onlyDynamicEdges === true) {
  30713. this._freezeNodes();
  30714. }
  30715. this.stabilizationIterations = 0;
  30716. setTimeout(function () {
  30717. return _this3._stabilizationBatch();
  30718. }, 0);
  30719. }
  30720. /**
  30721. * One batch of stabilization
  30722. * @private
  30723. */
  30724. }, {
  30725. key: '_stabilizationBatch',
  30726. value: function _stabilizationBatch() {
  30727. // this is here to ensure that there is at least one start event.
  30728. if (this.startedStabilization === false) {
  30729. this.body.emitter.emit('startStabilizing');
  30730. this.startedStabilization = true;
  30731. }
  30732. var count = 0;
  30733. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) {
  30734. this.physicsTick();
  30735. count++;
  30736. }
  30737. if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) {
  30738. this.body.emitter.emit('stabilizationProgress', { iterations: this.stabilizationIterations, total: this.targetIterations });
  30739. setTimeout(this._stabilizationBatch.bind(this), 0);
  30740. } else {
  30741. this._finalizeStabilization();
  30742. }
  30743. }
  30744. /**
  30745. * Wrap up the stabilization, fit and emit the events.
  30746. * @private
  30747. */
  30748. }, {
  30749. key: '_finalizeStabilization',
  30750. value: function _finalizeStabilization() {
  30751. this.body.emitter.emit('_allowRedraw');
  30752. if (this.options.stabilization.fit === true) {
  30753. this.body.emitter.emit('fit');
  30754. }
  30755. if (this.options.stabilization.onlyDynamicEdges === true) {
  30756. this._restoreFrozenNodes();
  30757. }
  30758. this.body.emitter.emit('stabilizationIterationsDone');
  30759. this.body.emitter.emit('_requestRedraw');
  30760. if (this.stabilized === true) {
  30761. this._emitStabilized();
  30762. } else {
  30763. this.startSimulation();
  30764. }
  30765. this.ready = true;
  30766. }
  30767. }, {
  30768. key: '_drawForces',
  30769. value: function _drawForces(ctx) {
  30770. for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  30771. var node = this.body.nodes[this.physicsBody.physicsNodeIndices[i]];
  30772. var force = this.physicsBody.forces[this.physicsBody.physicsNodeIndices[i]];
  30773. var factor = 20;
  30774. var colorFactor = 0.03;
  30775. var forceSize = Math.sqrt(Math.pow(force.x, 2) + Math.pow(force.x, 2));
  30776. var size = Math.min(Math.max(5, forceSize), 15);
  30777. var arrowSize = 3 * size;
  30778. var color = util.HSVToHex((180 - Math.min(1, Math.max(0, colorFactor * forceSize)) * 180) / 360, 1, 1);
  30779. ctx.lineWidth = size;
  30780. ctx.strokeStyle = color;
  30781. ctx.beginPath();
  30782. ctx.moveTo(node.x, node.y);
  30783. ctx.lineTo(node.x + factor * force.x, node.y + factor * force.y);
  30784. ctx.stroke();
  30785. var angle = Math.atan2(force.y, force.x);
  30786. ctx.fillStyle = color;
  30787. ctx.arrow(node.x + factor * force.x + Math.cos(angle) * arrowSize, node.y + factor * force.y + Math.sin(angle) * arrowSize, angle, arrowSize);
  30788. ctx.fill();
  30789. }
  30790. }
  30791. }]);
  30792. return PhysicsEngine;
  30793. }();
  30794. exports.default = PhysicsEngine;
  30795. /***/ },
  30796. /* 94 */
  30797. /***/ function(module, exports) {
  30798. "use strict";
  30799. Object.defineProperty(exports, "__esModule", {
  30800. value: true
  30801. });
  30802. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  30803. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30804. var BarnesHutSolver = function () {
  30805. function BarnesHutSolver(body, physicsBody, options) {
  30806. _classCallCheck(this, BarnesHutSolver);
  30807. this.body = body;
  30808. this.physicsBody = physicsBody;
  30809. this.barnesHutTree;
  30810. this.setOptions(options);
  30811. this.randomSeed = 5;
  30812. // debug: show grid
  30813. //this.body.emitter.on("afterDrawing", (ctx) => {this._debug(ctx,'#ff0000')})
  30814. }
  30815. _createClass(BarnesHutSolver, [{
  30816. key: "setOptions",
  30817. value: function setOptions(options) {
  30818. this.options = options;
  30819. this.thetaInversed = 1 / this.options.theta;
  30820. this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1, this.options.avoidOverlap)); // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius
  30821. }
  30822. }, {
  30823. key: "seededRandom",
  30824. value: function seededRandom() {
  30825. var x = Math.sin(this.randomSeed++) * 10000;
  30826. return x - Math.floor(x);
  30827. }
  30828. /**
  30829. * This function calculates the forces the nodes apply on each other based on a gravitational model.
  30830. * The Barnes Hut method is used to speed up this N-body simulation.
  30831. *
  30832. * @private
  30833. */
  30834. }, {
  30835. key: "solve",
  30836. value: function solve() {
  30837. if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) {
  30838. var node = void 0;
  30839. var nodes = this.body.nodes;
  30840. var nodeIndices = this.physicsBody.physicsNodeIndices;
  30841. var nodeCount = nodeIndices.length;
  30842. // create the tree
  30843. var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices);
  30844. // for debugging
  30845. this.barnesHutTree = barnesHutTree;
  30846. // place the nodes one by one recursively
  30847. for (var i = 0; i < nodeCount; i++) {
  30848. node = nodes[nodeIndices[i]];
  30849. if (node.options.mass > 0) {
  30850. // starting with root is irrelevant, it never passes the BarnesHutSolver condition
  30851. this._getForceContribution(barnesHutTree.root.children.NW, node);
  30852. this._getForceContribution(barnesHutTree.root.children.NE, node);
  30853. this._getForceContribution(barnesHutTree.root.children.SW, node);
  30854. this._getForceContribution(barnesHutTree.root.children.SE, node);
  30855. }
  30856. }
  30857. }
  30858. }
  30859. /**
  30860. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  30861. * If a region contains a single node, we check if it is not itself, then we apply the force.
  30862. *
  30863. * @param parentBranch
  30864. * @param node
  30865. * @private
  30866. */
  30867. }, {
  30868. key: "_getForceContribution",
  30869. value: function _getForceContribution(parentBranch, node) {
  30870. // we get no force contribution from an empty region
  30871. if (parentBranch.childrenCount > 0) {
  30872. var dx = void 0,
  30873. dy = void 0,
  30874. distance = void 0;
  30875. // get the distance from the center of mass to the node.
  30876. dx = parentBranch.centerOfMass.x - node.x;
  30877. dy = parentBranch.centerOfMass.y - node.y;
  30878. distance = Math.sqrt(dx * dx + dy * dy);
  30879. // BarnesHutSolver condition
  30880. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  30881. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  30882. if (distance * parentBranch.calcSize > this.thetaInversed) {
  30883. this._calculateForces(distance, dx, dy, node, parentBranch);
  30884. } else {
  30885. // Did not pass the condition, go into children if available
  30886. if (parentBranch.childrenCount === 4) {
  30887. this._getForceContribution(parentBranch.children.NW, node);
  30888. this._getForceContribution(parentBranch.children.NE, node);
  30889. this._getForceContribution(parentBranch.children.SW, node);
  30890. this._getForceContribution(parentBranch.children.SE, node);
  30891. } else {
  30892. // parentBranch must have only one node, if it was empty we wouldnt be here
  30893. if (parentBranch.children.data.id != node.id) {
  30894. // if it is not self
  30895. this._calculateForces(distance, dx, dy, node, parentBranch);
  30896. }
  30897. }
  30898. }
  30899. }
  30900. }
  30901. /**
  30902. * Calculate the forces based on the distance.
  30903. *
  30904. * @param distance
  30905. * @param dx
  30906. * @param dy
  30907. * @param node
  30908. * @param parentBranch
  30909. * @private
  30910. */
  30911. }, {
  30912. key: "_calculateForces",
  30913. value: function _calculateForces(distance, dx, dy, node, parentBranch) {
  30914. if (distance === 0) {
  30915. distance = 0.1;
  30916. dx = distance;
  30917. }
  30918. if (this.overlapAvoidanceFactor < 1) {
  30919. distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius);
  30920. }
  30921. // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
  30922. // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
  30923. var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance, 3);
  30924. var fx = dx * gravityForce;
  30925. var fy = dy * gravityForce;
  30926. this.physicsBody.forces[node.id].x += fx;
  30927. this.physicsBody.forces[node.id].y += fy;
  30928. }
  30929. /**
  30930. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  30931. *
  30932. * @param nodes
  30933. * @param nodeIndices
  30934. * @private
  30935. */
  30936. }, {
  30937. key: "_formBarnesHutTree",
  30938. value: function _formBarnesHutTree(nodes, nodeIndices) {
  30939. var node = void 0;
  30940. var nodeCount = nodeIndices.length;
  30941. var minX = nodes[nodeIndices[0]].x;
  30942. var minY = nodes[nodeIndices[0]].y;
  30943. var maxX = nodes[nodeIndices[0]].x;
  30944. var maxY = nodes[nodeIndices[0]].y;
  30945. // get the range of the nodes
  30946. for (var i = 1; i < nodeCount; i++) {
  30947. var x = nodes[nodeIndices[i]].x;
  30948. var y = nodes[nodeIndices[i]].y;
  30949. if (nodes[nodeIndices[i]].options.mass > 0) {
  30950. if (x < minX) {
  30951. minX = x;
  30952. }
  30953. if (x > maxX) {
  30954. maxX = x;
  30955. }
  30956. if (y < minY) {
  30957. minY = y;
  30958. }
  30959. if (y > maxY) {
  30960. maxY = y;
  30961. }
  30962. }
  30963. }
  30964. // make the range a square
  30965. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  30966. if (sizeDiff > 0) {
  30967. minY -= 0.5 * sizeDiff;
  30968. maxY += 0.5 * sizeDiff;
  30969. } // xSize > ySize
  30970. else {
  30971. minX += 0.5 * sizeDiff;
  30972. maxX -= 0.5 * sizeDiff;
  30973. } // xSize < ySize
  30974. var minimumTreeSize = 1e-5;
  30975. var rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX));
  30976. var halfRootSize = 0.5 * rootSize;
  30977. var centerX = 0.5 * (minX + maxX),
  30978. centerY = 0.5 * (minY + maxY);
  30979. // construct the barnesHutTree
  30980. var barnesHutTree = {
  30981. root: {
  30982. centerOfMass: { x: 0, y: 0 },
  30983. mass: 0,
  30984. range: {
  30985. minX: centerX - halfRootSize, maxX: centerX + halfRootSize,
  30986. minY: centerY - halfRootSize, maxY: centerY + halfRootSize
  30987. },
  30988. size: rootSize,
  30989. calcSize: 1 / rootSize,
  30990. children: { data: null },
  30991. maxWidth: 0,
  30992. level: 0,
  30993. childrenCount: 4
  30994. }
  30995. };
  30996. this._splitBranch(barnesHutTree.root);
  30997. // place the nodes one by one recursively
  30998. for (var _i = 0; _i < nodeCount; _i++) {
  30999. node = nodes[nodeIndices[_i]];
  31000. if (node.options.mass > 0) {
  31001. this._placeInTree(barnesHutTree.root, node);
  31002. }
  31003. }
  31004. // make global
  31005. return barnesHutTree;
  31006. }
  31007. /**
  31008. * this updates the mass of a branch. this is increased by adding a node.
  31009. *
  31010. * @param parentBranch
  31011. * @param node
  31012. * @private
  31013. */
  31014. }, {
  31015. key: "_updateBranchMass",
  31016. value: function _updateBranchMass(parentBranch, node) {
  31017. var totalMass = parentBranch.mass + node.options.mass;
  31018. var totalMassInv = 1 / totalMass;
  31019. parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  31020. parentBranch.centerOfMass.x *= totalMassInv;
  31021. parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  31022. parentBranch.centerOfMass.y *= totalMassInv;
  31023. parentBranch.mass = totalMass;
  31024. var biggestSize = Math.max(Math.max(node.height, node.radius), node.width);
  31025. parentBranch.maxWidth = parentBranch.maxWidth < biggestSize ? biggestSize : parentBranch.maxWidth;
  31026. }
  31027. /**
  31028. * determine in which branch the node will be placed.
  31029. *
  31030. * @param parentBranch
  31031. * @param node
  31032. * @param skipMassUpdate
  31033. * @private
  31034. */
  31035. }, {
  31036. key: "_placeInTree",
  31037. value: function _placeInTree(parentBranch, node, skipMassUpdate) {
  31038. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  31039. // update the mass of the branch.
  31040. this._updateBranchMass(parentBranch, node);
  31041. }
  31042. if (parentBranch.children.NW.range.maxX > node.x) {
  31043. // in NW or SW
  31044. if (parentBranch.children.NW.range.maxY > node.y) {
  31045. // in NW
  31046. this._placeInRegion(parentBranch, node, "NW");
  31047. } else {
  31048. // in SW
  31049. this._placeInRegion(parentBranch, node, "SW");
  31050. }
  31051. } else {
  31052. // in NE or SE
  31053. if (parentBranch.children.NW.range.maxY > node.y) {
  31054. // in NE
  31055. this._placeInRegion(parentBranch, node, "NE");
  31056. } else {
  31057. // in SE
  31058. this._placeInRegion(parentBranch, node, "SE");
  31059. }
  31060. }
  31061. }
  31062. /**
  31063. * actually place the node in a region (or branch)
  31064. *
  31065. * @param parentBranch
  31066. * @param node
  31067. * @param region
  31068. * @private
  31069. */
  31070. }, {
  31071. key: "_placeInRegion",
  31072. value: function _placeInRegion(parentBranch, node, region) {
  31073. switch (parentBranch.children[region].childrenCount) {
  31074. case 0:
  31075. // place node here
  31076. parentBranch.children[region].children.data = node;
  31077. parentBranch.children[region].childrenCount = 1;
  31078. this._updateBranchMass(parentBranch.children[region], node);
  31079. break;
  31080. case 1:
  31081. // convert into children
  31082. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  31083. // we move one node a little bit and we do not put it in the tree.
  31084. if (parentBranch.children[region].children.data.x === node.x && parentBranch.children[region].children.data.y === node.y) {
  31085. node.x += this.seededRandom();
  31086. node.y += this.seededRandom();
  31087. } else {
  31088. this._splitBranch(parentBranch.children[region]);
  31089. this._placeInTree(parentBranch.children[region], node);
  31090. }
  31091. break;
  31092. case 4:
  31093. // place in branch
  31094. this._placeInTree(parentBranch.children[region], node);
  31095. break;
  31096. }
  31097. }
  31098. /**
  31099. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  31100. * after the split is complete.
  31101. *
  31102. * @param parentBranch
  31103. * @private
  31104. */
  31105. }, {
  31106. key: "_splitBranch",
  31107. value: function _splitBranch(parentBranch) {
  31108. // if the branch is shaded with a node, replace the node in the new subset.
  31109. var containedNode = null;
  31110. if (parentBranch.childrenCount === 1) {
  31111. containedNode = parentBranch.children.data;
  31112. parentBranch.mass = 0;
  31113. parentBranch.centerOfMass.x = 0;
  31114. parentBranch.centerOfMass.y = 0;
  31115. }
  31116. parentBranch.childrenCount = 4;
  31117. parentBranch.children.data = null;
  31118. this._insertRegion(parentBranch, "NW");
  31119. this._insertRegion(parentBranch, "NE");
  31120. this._insertRegion(parentBranch, "SW");
  31121. this._insertRegion(parentBranch, "SE");
  31122. if (containedNode != null) {
  31123. this._placeInTree(parentBranch, containedNode);
  31124. }
  31125. }
  31126. /**
  31127. * This function subdivides the region into four new segments.
  31128. * Specifically, this inserts a single new segment.
  31129. * It fills the children section of the parentBranch
  31130. *
  31131. * @param parentBranch
  31132. * @param region
  31133. * @param parentRange
  31134. * @private
  31135. */
  31136. }, {
  31137. key: "_insertRegion",
  31138. value: function _insertRegion(parentBranch, region) {
  31139. var minX = void 0,
  31140. maxX = void 0,
  31141. minY = void 0,
  31142. maxY = void 0;
  31143. var childSize = 0.5 * parentBranch.size;
  31144. switch (region) {
  31145. case "NW":
  31146. minX = parentBranch.range.minX;
  31147. maxX = parentBranch.range.minX + childSize;
  31148. minY = parentBranch.range.minY;
  31149. maxY = parentBranch.range.minY + childSize;
  31150. break;
  31151. case "NE":
  31152. minX = parentBranch.range.minX + childSize;
  31153. maxX = parentBranch.range.maxX;
  31154. minY = parentBranch.range.minY;
  31155. maxY = parentBranch.range.minY + childSize;
  31156. break;
  31157. case "SW":
  31158. minX = parentBranch.range.minX;
  31159. maxX = parentBranch.range.minX + childSize;
  31160. minY = parentBranch.range.minY + childSize;
  31161. maxY = parentBranch.range.maxY;
  31162. break;
  31163. case "SE":
  31164. minX = parentBranch.range.minX + childSize;
  31165. maxX = parentBranch.range.maxX;
  31166. minY = parentBranch.range.minY + childSize;
  31167. maxY = parentBranch.range.maxY;
  31168. break;
  31169. }
  31170. parentBranch.children[region] = {
  31171. centerOfMass: { x: 0, y: 0 },
  31172. mass: 0,
  31173. range: { minX: minX, maxX: maxX, minY: minY, maxY: maxY },
  31174. size: 0.5 * parentBranch.size,
  31175. calcSize: 2 * parentBranch.calcSize,
  31176. children: { data: null },
  31177. maxWidth: 0,
  31178. level: parentBranch.level + 1,
  31179. childrenCount: 0
  31180. };
  31181. }
  31182. //--------------------------- DEBUGGING BELOW ---------------------------//
  31183. /**
  31184. * This function is for debugging purposed, it draws the tree.
  31185. *
  31186. * @param ctx
  31187. * @param color
  31188. * @private
  31189. */
  31190. }, {
  31191. key: "_debug",
  31192. value: function _debug(ctx, color) {
  31193. if (this.barnesHutTree !== undefined) {
  31194. ctx.lineWidth = 1;
  31195. this._drawBranch(this.barnesHutTree.root, ctx, color);
  31196. }
  31197. }
  31198. /**
  31199. * This function is for debugging purposes. It draws the branches recursively.
  31200. *
  31201. * @param branch
  31202. * @param ctx
  31203. * @param color
  31204. * @private
  31205. */
  31206. }, {
  31207. key: "_drawBranch",
  31208. value: function _drawBranch(branch, ctx, color) {
  31209. if (color === undefined) {
  31210. color = "#FF0000";
  31211. }
  31212. if (branch.childrenCount === 4) {
  31213. this._drawBranch(branch.children.NW, ctx);
  31214. this._drawBranch(branch.children.NE, ctx);
  31215. this._drawBranch(branch.children.SE, ctx);
  31216. this._drawBranch(branch.children.SW, ctx);
  31217. }
  31218. ctx.strokeStyle = color;
  31219. ctx.beginPath();
  31220. ctx.moveTo(branch.range.minX, branch.range.minY);
  31221. ctx.lineTo(branch.range.maxX, branch.range.minY);
  31222. ctx.stroke();
  31223. ctx.beginPath();
  31224. ctx.moveTo(branch.range.maxX, branch.range.minY);
  31225. ctx.lineTo(branch.range.maxX, branch.range.maxY);
  31226. ctx.stroke();
  31227. ctx.beginPath();
  31228. ctx.moveTo(branch.range.maxX, branch.range.maxY);
  31229. ctx.lineTo(branch.range.minX, branch.range.maxY);
  31230. ctx.stroke();
  31231. ctx.beginPath();
  31232. ctx.moveTo(branch.range.minX, branch.range.maxY);
  31233. ctx.lineTo(branch.range.minX, branch.range.minY);
  31234. ctx.stroke();
  31235. /*
  31236. if (branch.mass > 0) {
  31237. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  31238. ctx.stroke();
  31239. }
  31240. */
  31241. }
  31242. }]);
  31243. return BarnesHutSolver;
  31244. }();
  31245. exports.default = BarnesHutSolver;
  31246. /***/ },
  31247. /* 95 */
  31248. /***/ function(module, exports) {
  31249. "use strict";
  31250. Object.defineProperty(exports, "__esModule", {
  31251. value: true
  31252. });
  31253. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31254. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31255. var RepulsionSolver = function () {
  31256. function RepulsionSolver(body, physicsBody, options) {
  31257. _classCallCheck(this, RepulsionSolver);
  31258. this.body = body;
  31259. this.physicsBody = physicsBody;
  31260. this.setOptions(options);
  31261. }
  31262. _createClass(RepulsionSolver, [{
  31263. key: "setOptions",
  31264. value: function setOptions(options) {
  31265. this.options = options;
  31266. }
  31267. /**
  31268. * Calculate the forces the nodes apply on each other based on a repulsion field.
  31269. * This field is linearly approximated.
  31270. *
  31271. * @private
  31272. */
  31273. }, {
  31274. key: "solve",
  31275. value: function solve() {
  31276. var dx, dy, distance, fx, fy, repulsingForce, node1, node2;
  31277. var nodes = this.body.nodes;
  31278. var nodeIndices = this.physicsBody.physicsNodeIndices;
  31279. var forces = this.physicsBody.forces;
  31280. // repulsing forces between nodes
  31281. var nodeDistance = this.options.nodeDistance;
  31282. // approximation constants
  31283. var a = -2 / 3 / nodeDistance;
  31284. var b = 4 / 3;
  31285. // we loop from i over all but the last entree in the array
  31286. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  31287. for (var i = 0; i < nodeIndices.length - 1; i++) {
  31288. node1 = nodes[nodeIndices[i]];
  31289. for (var j = i + 1; j < nodeIndices.length; j++) {
  31290. node2 = nodes[nodeIndices[j]];
  31291. dx = node2.x - node1.x;
  31292. dy = node2.y - node1.y;
  31293. distance = Math.sqrt(dx * dx + dy * dy);
  31294. // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping.
  31295. if (distance === 0) {
  31296. distance = 0.1 * Math.random();
  31297. dx = distance;
  31298. }
  31299. if (distance < 2 * nodeDistance) {
  31300. if (distance < 0.5 * nodeDistance) {
  31301. repulsingForce = 1.0;
  31302. } else {
  31303. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness))
  31304. }
  31305. repulsingForce = repulsingForce / distance;
  31306. fx = dx * repulsingForce;
  31307. fy = dy * repulsingForce;
  31308. forces[node1.id].x -= fx;
  31309. forces[node1.id].y -= fy;
  31310. forces[node2.id].x += fx;
  31311. forces[node2.id].y += fy;
  31312. }
  31313. }
  31314. }
  31315. }
  31316. }]);
  31317. return RepulsionSolver;
  31318. }();
  31319. exports.default = RepulsionSolver;
  31320. /***/ },
  31321. /* 96 */
  31322. /***/ function(module, exports) {
  31323. "use strict";
  31324. Object.defineProperty(exports, "__esModule", {
  31325. value: true
  31326. });
  31327. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31328. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31329. var HierarchicalRepulsionSolver = function () {
  31330. function HierarchicalRepulsionSolver(body, physicsBody, options) {
  31331. _classCallCheck(this, HierarchicalRepulsionSolver);
  31332. this.body = body;
  31333. this.physicsBody = physicsBody;
  31334. this.setOptions(options);
  31335. }
  31336. _createClass(HierarchicalRepulsionSolver, [{
  31337. key: "setOptions",
  31338. value: function setOptions(options) {
  31339. this.options = options;
  31340. }
  31341. /**
  31342. * Calculate the forces the nodes apply on each other based on a repulsion field.
  31343. * This field is linearly approximated.
  31344. *
  31345. * @private
  31346. */
  31347. }, {
  31348. key: "solve",
  31349. value: function solve() {
  31350. var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j;
  31351. var nodes = this.body.nodes;
  31352. var nodeIndices = this.physicsBody.physicsNodeIndices;
  31353. var forces = this.physicsBody.forces;
  31354. // repulsing forces between nodes
  31355. var nodeDistance = this.options.nodeDistance;
  31356. // we loop from i over all but the last entree in the array
  31357. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  31358. for (i = 0; i < nodeIndices.length - 1; i++) {
  31359. node1 = nodes[nodeIndices[i]];
  31360. for (j = i + 1; j < nodeIndices.length; j++) {
  31361. node2 = nodes[nodeIndices[j]];
  31362. // nodes only affect nodes on their level
  31363. if (node1.level === node2.level) {
  31364. dx = node2.x - node1.x;
  31365. dy = node2.y - node1.y;
  31366. distance = Math.sqrt(dx * dx + dy * dy);
  31367. var steepness = 0.05;
  31368. if (distance < nodeDistance) {
  31369. repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2);
  31370. } else {
  31371. repulsingForce = 0;
  31372. }
  31373. // normalize force with
  31374. if (distance === 0) {
  31375. distance = 0.01;
  31376. } else {
  31377. repulsingForce = repulsingForce / distance;
  31378. }
  31379. fx = dx * repulsingForce;
  31380. fy = dy * repulsingForce;
  31381. forces[node1.id].x -= fx;
  31382. forces[node1.id].y -= fy;
  31383. forces[node2.id].x += fx;
  31384. forces[node2.id].y += fy;
  31385. }
  31386. }
  31387. }
  31388. }
  31389. }]);
  31390. return HierarchicalRepulsionSolver;
  31391. }();
  31392. exports.default = HierarchicalRepulsionSolver;
  31393. /***/ },
  31394. /* 97 */
  31395. /***/ function(module, exports) {
  31396. "use strict";
  31397. Object.defineProperty(exports, "__esModule", {
  31398. value: true
  31399. });
  31400. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31401. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31402. var SpringSolver = function () {
  31403. function SpringSolver(body, physicsBody, options) {
  31404. _classCallCheck(this, SpringSolver);
  31405. this.body = body;
  31406. this.physicsBody = physicsBody;
  31407. this.setOptions(options);
  31408. }
  31409. _createClass(SpringSolver, [{
  31410. key: "setOptions",
  31411. value: function setOptions(options) {
  31412. this.options = options;
  31413. }
  31414. /**
  31415. * This function calculates the springforces on the nodes, accounting for the support nodes.
  31416. *
  31417. * @private
  31418. */
  31419. }, {
  31420. key: "solve",
  31421. value: function solve() {
  31422. var edgeLength = void 0,
  31423. edge = void 0;
  31424. var edgeIndices = this.physicsBody.physicsEdgeIndices;
  31425. var edges = this.body.edges;
  31426. var node1 = void 0,
  31427. node2 = void 0,
  31428. node3 = void 0;
  31429. // forces caused by the edges, modelled as springs
  31430. for (var i = 0; i < edgeIndices.length; i++) {
  31431. edge = edges[edgeIndices[i]];
  31432. if (edge.connected === true && edge.toId !== edge.fromId) {
  31433. // only calculate forces if nodes are in the same sector
  31434. if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) {
  31435. if (edge.edgeType.via !== undefined) {
  31436. edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length;
  31437. node1 = edge.to;
  31438. node2 = edge.edgeType.via;
  31439. node3 = edge.from;
  31440. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  31441. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  31442. } else {
  31443. // the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use
  31444. // the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger.
  31445. edgeLength = edge.options.length === undefined ? this.options.springLength * 1.5 : edge.options.length;
  31446. this._calculateSpringForce(edge.from, edge.to, edgeLength);
  31447. }
  31448. }
  31449. }
  31450. }
  31451. }
  31452. /**
  31453. * This is the code actually performing the calculation for the function above.
  31454. *
  31455. * @param node1
  31456. * @param node2
  31457. * @param edgeLength
  31458. * @private
  31459. */
  31460. }, {
  31461. key: "_calculateSpringForce",
  31462. value: function _calculateSpringForce(node1, node2, edgeLength) {
  31463. var dx = node1.x - node2.x;
  31464. var dy = node1.y - node2.y;
  31465. var distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.01);
  31466. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  31467. var springForce = this.options.springConstant * (edgeLength - distance) / distance;
  31468. var fx = dx * springForce;
  31469. var fy = dy * springForce;
  31470. // handle the case where one node is not part of the physcis
  31471. if (this.physicsBody.forces[node1.id] !== undefined) {
  31472. this.physicsBody.forces[node1.id].x += fx;
  31473. this.physicsBody.forces[node1.id].y += fy;
  31474. }
  31475. if (this.physicsBody.forces[node2.id] !== undefined) {
  31476. this.physicsBody.forces[node2.id].x -= fx;
  31477. this.physicsBody.forces[node2.id].y -= fy;
  31478. }
  31479. }
  31480. }]);
  31481. return SpringSolver;
  31482. }();
  31483. exports.default = SpringSolver;
  31484. /***/ },
  31485. /* 98 */
  31486. /***/ function(module, exports) {
  31487. "use strict";
  31488. Object.defineProperty(exports, "__esModule", {
  31489. value: true
  31490. });
  31491. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31492. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31493. var HierarchicalSpringSolver = function () {
  31494. function HierarchicalSpringSolver(body, physicsBody, options) {
  31495. _classCallCheck(this, HierarchicalSpringSolver);
  31496. this.body = body;
  31497. this.physicsBody = physicsBody;
  31498. this.setOptions(options);
  31499. }
  31500. _createClass(HierarchicalSpringSolver, [{
  31501. key: "setOptions",
  31502. value: function setOptions(options) {
  31503. this.options = options;
  31504. }
  31505. /**
  31506. * This function calculates the springforces on the nodes, accounting for the support nodes.
  31507. *
  31508. * @private
  31509. */
  31510. }, {
  31511. key: "solve",
  31512. value: function solve() {
  31513. var edgeLength, edge;
  31514. var dx, dy, fx, fy, springForce, distance;
  31515. var edges = this.body.edges;
  31516. var factor = 0.5;
  31517. var edgeIndices = this.physicsBody.physicsEdgeIndices;
  31518. var nodeIndices = this.physicsBody.physicsNodeIndices;
  31519. var forces = this.physicsBody.forces;
  31520. // initialize the spring force counters
  31521. for (var i = 0; i < nodeIndices.length; i++) {
  31522. var nodeId = nodeIndices[i];
  31523. forces[nodeId].springFx = 0;
  31524. forces[nodeId].springFy = 0;
  31525. }
  31526. // forces caused by the edges, modelled as springs
  31527. for (var _i = 0; _i < edgeIndices.length; _i++) {
  31528. edge = edges[edgeIndices[_i]];
  31529. if (edge.connected === true) {
  31530. edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length;
  31531. dx = edge.from.x - edge.to.x;
  31532. dy = edge.from.y - edge.to.y;
  31533. distance = Math.sqrt(dx * dx + dy * dy);
  31534. distance = distance === 0 ? 0.01 : distance;
  31535. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  31536. springForce = this.options.springConstant * (edgeLength - distance) / distance;
  31537. fx = dx * springForce;
  31538. fy = dy * springForce;
  31539. if (edge.to.level != edge.from.level) {
  31540. if (forces[edge.toId] !== undefined) {
  31541. forces[edge.toId].springFx -= fx;
  31542. forces[edge.toId].springFy -= fy;
  31543. }
  31544. if (forces[edge.fromId] !== undefined) {
  31545. forces[edge.fromId].springFx += fx;
  31546. forces[edge.fromId].springFy += fy;
  31547. }
  31548. } else {
  31549. if (forces[edge.toId] !== undefined) {
  31550. forces[edge.toId].x -= factor * fx;
  31551. forces[edge.toId].y -= factor * fy;
  31552. }
  31553. if (forces[edge.fromId] !== undefined) {
  31554. forces[edge.fromId].x += factor * fx;
  31555. forces[edge.fromId].y += factor * fy;
  31556. }
  31557. }
  31558. }
  31559. }
  31560. // normalize spring forces
  31561. var springForce = 1;
  31562. var springFx, springFy;
  31563. for (var _i2 = 0; _i2 < nodeIndices.length; _i2++) {
  31564. var _nodeId = nodeIndices[_i2];
  31565. springFx = Math.min(springForce, Math.max(-springForce, forces[_nodeId].springFx));
  31566. springFy = Math.min(springForce, Math.max(-springForce, forces[_nodeId].springFy));
  31567. forces[_nodeId].x += springFx;
  31568. forces[_nodeId].y += springFy;
  31569. }
  31570. // retain energy balance
  31571. var totalFx = 0;
  31572. var totalFy = 0;
  31573. for (var _i3 = 0; _i3 < nodeIndices.length; _i3++) {
  31574. var _nodeId2 = nodeIndices[_i3];
  31575. totalFx += forces[_nodeId2].x;
  31576. totalFy += forces[_nodeId2].y;
  31577. }
  31578. var correctionFx = totalFx / nodeIndices.length;
  31579. var correctionFy = totalFy / nodeIndices.length;
  31580. for (var _i4 = 0; _i4 < nodeIndices.length; _i4++) {
  31581. var _nodeId3 = nodeIndices[_i4];
  31582. forces[_nodeId3].x -= correctionFx;
  31583. forces[_nodeId3].y -= correctionFy;
  31584. }
  31585. }
  31586. }]);
  31587. return HierarchicalSpringSolver;
  31588. }();
  31589. exports.default = HierarchicalSpringSolver;
  31590. /***/ },
  31591. /* 99 */
  31592. /***/ function(module, exports) {
  31593. "use strict";
  31594. Object.defineProperty(exports, "__esModule", {
  31595. value: true
  31596. });
  31597. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31598. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31599. var CentralGravitySolver = function () {
  31600. function CentralGravitySolver(body, physicsBody, options) {
  31601. _classCallCheck(this, CentralGravitySolver);
  31602. this.body = body;
  31603. this.physicsBody = physicsBody;
  31604. this.setOptions(options);
  31605. }
  31606. _createClass(CentralGravitySolver, [{
  31607. key: "setOptions",
  31608. value: function setOptions(options) {
  31609. this.options = options;
  31610. }
  31611. }, {
  31612. key: "solve",
  31613. value: function solve() {
  31614. var dx = void 0,
  31615. dy = void 0,
  31616. distance = void 0,
  31617. node = void 0;
  31618. var nodes = this.body.nodes;
  31619. var nodeIndices = this.physicsBody.physicsNodeIndices;
  31620. var forces = this.physicsBody.forces;
  31621. for (var i = 0; i < nodeIndices.length; i++) {
  31622. var nodeId = nodeIndices[i];
  31623. node = nodes[nodeId];
  31624. dx = -node.x;
  31625. dy = -node.y;
  31626. distance = Math.sqrt(dx * dx + dy * dy);
  31627. this._calculateForces(distance, dx, dy, forces, node);
  31628. }
  31629. }
  31630. /**
  31631. * Calculate the forces based on the distance.
  31632. * @private
  31633. */
  31634. }, {
  31635. key: "_calculateForces",
  31636. value: function _calculateForces(distance, dx, dy, forces, node) {
  31637. var gravityForce = distance === 0 ? 0 : this.options.centralGravity / distance;
  31638. forces[node.id].x = dx * gravityForce;
  31639. forces[node.id].y = dy * gravityForce;
  31640. }
  31641. }]);
  31642. return CentralGravitySolver;
  31643. }();
  31644. exports.default = CentralGravitySolver;
  31645. /***/ },
  31646. /* 100 */
  31647. /***/ function(module, exports, __webpack_require__) {
  31648. "use strict";
  31649. Object.defineProperty(exports, "__esModule", {
  31650. value: true
  31651. });
  31652. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31653. var _BarnesHutSolver2 = __webpack_require__(94);
  31654. var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2);
  31655. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31656. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31657. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  31658. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  31659. var ForceAtlas2BasedRepulsionSolver = function (_BarnesHutSolver) {
  31660. _inherits(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver);
  31661. function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) {
  31662. _classCallCheck(this, ForceAtlas2BasedRepulsionSolver);
  31663. return _possibleConstructorReturn(this, Object.getPrototypeOf(ForceAtlas2BasedRepulsionSolver).call(this, body, physicsBody, options));
  31664. }
  31665. /**
  31666. * Calculate the forces based on the distance.
  31667. *
  31668. * @param distance
  31669. * @param dx
  31670. * @param dy
  31671. * @param node
  31672. * @param parentBranch
  31673. * @private
  31674. */
  31675. _createClass(ForceAtlas2BasedRepulsionSolver, [{
  31676. key: "_calculateForces",
  31677. value: function _calculateForces(distance, dx, dy, node, parentBranch) {
  31678. if (distance === 0) {
  31679. distance = 0.1 * Math.random();
  31680. dx = distance;
  31681. }
  31682. if (this.overlapAvoidanceFactor < 1) {
  31683. distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius);
  31684. }
  31685. var degree = node.edges.length + 1;
  31686. // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
  31687. // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
  31688. var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance, 2);
  31689. var fx = dx * gravityForce;
  31690. var fy = dy * gravityForce;
  31691. this.physicsBody.forces[node.id].x += fx;
  31692. this.physicsBody.forces[node.id].y += fy;
  31693. }
  31694. }]);
  31695. return ForceAtlas2BasedRepulsionSolver;
  31696. }(_BarnesHutSolver3.default);
  31697. exports.default = ForceAtlas2BasedRepulsionSolver;
  31698. /***/ },
  31699. /* 101 */
  31700. /***/ function(module, exports, __webpack_require__) {
  31701. "use strict";
  31702. Object.defineProperty(exports, "__esModule", {
  31703. value: true
  31704. });
  31705. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31706. var _CentralGravitySolver2 = __webpack_require__(99);
  31707. var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2);
  31708. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31709. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31710. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  31711. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  31712. var ForceAtlas2BasedCentralGravitySolver = function (_CentralGravitySolver) {
  31713. _inherits(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver);
  31714. function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) {
  31715. _classCallCheck(this, ForceAtlas2BasedCentralGravitySolver);
  31716. return _possibleConstructorReturn(this, Object.getPrototypeOf(ForceAtlas2BasedCentralGravitySolver).call(this, body, physicsBody, options));
  31717. }
  31718. /**
  31719. * Calculate the forces based on the distance.
  31720. * @private
  31721. */
  31722. _createClass(ForceAtlas2BasedCentralGravitySolver, [{
  31723. key: "_calculateForces",
  31724. value: function _calculateForces(distance, dx, dy, forces, node) {
  31725. if (distance > 0) {
  31726. var degree = node.edges.length + 1;
  31727. var gravityForce = this.options.centralGravity * degree * node.options.mass;
  31728. forces[node.id].x = dx * gravityForce;
  31729. forces[node.id].y = dy * gravityForce;
  31730. }
  31731. }
  31732. }]);
  31733. return ForceAtlas2BasedCentralGravitySolver;
  31734. }(_CentralGravitySolver3.default);
  31735. exports.default = ForceAtlas2BasedCentralGravitySolver;
  31736. /***/ },
  31737. /* 102 */
  31738. /***/ function(module, exports, __webpack_require__) {
  31739. 'use strict';
  31740. Object.defineProperty(exports, "__esModule", {
  31741. value: true
  31742. });
  31743. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  31744. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31745. var _NetworkUtil = __webpack_require__(103);
  31746. var _NetworkUtil2 = _interopRequireDefault(_NetworkUtil);
  31747. var _Cluster = __webpack_require__(104);
  31748. var _Cluster2 = _interopRequireDefault(_Cluster);
  31749. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31750. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31751. var util = __webpack_require__(1);
  31752. var ClusterEngine = function () {
  31753. function ClusterEngine(body) {
  31754. var _this = this;
  31755. _classCallCheck(this, ClusterEngine);
  31756. this.body = body;
  31757. this.clusteredNodes = {};
  31758. this.clusteredEdges = {};
  31759. this.options = {};
  31760. this.defaultOptions = {};
  31761. util.extend(this.options, this.defaultOptions);
  31762. this.body.emitter.on('_resetData', function () {
  31763. _this.clusteredNodes = {};_this.clusteredEdges = {};
  31764. });
  31765. }
  31766. _createClass(ClusterEngine, [{
  31767. key: 'setOptions',
  31768. value: function setOptions(options) {
  31769. if (options !== undefined) {}
  31770. }
  31771. /**
  31772. *
  31773. * @param hubsize
  31774. * @param options
  31775. */
  31776. }, {
  31777. key: 'clusterByHubsize',
  31778. value: function clusterByHubsize(hubsize, options) {
  31779. if (hubsize === undefined) {
  31780. hubsize = this._getHubSize();
  31781. } else if ((typeof hubsize === 'undefined' ? 'undefined' : _typeof(hubsize)) === "object") {
  31782. options = this._checkOptions(hubsize);
  31783. hubsize = this._getHubSize();
  31784. }
  31785. var nodesToCluster = [];
  31786. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  31787. var node = this.body.nodes[this.body.nodeIndices[i]];
  31788. if (node.edges.length >= hubsize) {
  31789. nodesToCluster.push(node.id);
  31790. }
  31791. }
  31792. for (var _i = 0; _i < nodesToCluster.length; _i++) {
  31793. this.clusterByConnection(nodesToCluster[_i], options, true);
  31794. }
  31795. this.body.emitter.emit('_dataChanged');
  31796. }
  31797. /**
  31798. * loop over all nodes, check if they adhere to the condition and cluster if needed.
  31799. * @param options
  31800. * @param refreshData
  31801. */
  31802. }, {
  31803. key: 'cluster',
  31804. value: function cluster() {
  31805. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  31806. var refreshData = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  31807. if (options.joinCondition === undefined) {
  31808. throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");
  31809. }
  31810. // check if the options object is fine, append if needed
  31811. options = this._checkOptions(options);
  31812. var childNodesObj = {};
  31813. var childEdgesObj = {};
  31814. // collect the nodes that will be in the cluster
  31815. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  31816. var nodeId = this.body.nodeIndices[i];
  31817. var node = this.body.nodes[nodeId];
  31818. var clonedOptions = _NetworkUtil2.default.cloneOptions(node);
  31819. if (options.joinCondition(clonedOptions) === true) {
  31820. childNodesObj[nodeId] = this.body.nodes[nodeId];
  31821. // collect the nodes that will be in the cluster
  31822. for (var _i2 = 0; _i2 < node.edges.length; _i2++) {
  31823. var edge = node.edges[_i2];
  31824. if (this.clusteredEdges[edge.id] === undefined) {
  31825. childEdgesObj[edge.id] = edge;
  31826. }
  31827. }
  31828. }
  31829. }
  31830. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  31831. }
  31832. /**
  31833. * Cluster all nodes in the network that have only X edges
  31834. * @param edgeCount
  31835. * @param options
  31836. * @param refreshData
  31837. */
  31838. }, {
  31839. key: 'clusterByEdgeCount',
  31840. value: function clusterByEdgeCount(edgeCount, options) {
  31841. var refreshData = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
  31842. options = this._checkOptions(options);
  31843. var clusters = [];
  31844. var usedNodes = {};
  31845. var edge = void 0,
  31846. edges = void 0,
  31847. node = void 0,
  31848. nodeId = void 0,
  31849. relevantEdgeCount = void 0;
  31850. // collect the nodes that will be in the cluster
  31851. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  31852. var childNodesObj = {};
  31853. var childEdgesObj = {};
  31854. nodeId = this.body.nodeIndices[i];
  31855. // if this node is already used in another cluster this session, we do not have to re-evaluate it.
  31856. if (usedNodes[nodeId] === undefined) {
  31857. relevantEdgeCount = 0;
  31858. node = this.body.nodes[nodeId];
  31859. edges = [];
  31860. for (var j = 0; j < node.edges.length; j++) {
  31861. edge = node.edges[j];
  31862. if (this.clusteredEdges[edge.id] === undefined) {
  31863. if (edge.toId !== edge.fromId) {
  31864. relevantEdgeCount++;
  31865. }
  31866. edges.push(edge);
  31867. }
  31868. }
  31869. // this node qualifies, we collect its neighbours to start the clustering process.
  31870. if (relevantEdgeCount === edgeCount) {
  31871. var gatheringSuccessful = true;
  31872. for (var _j = 0; _j < edges.length; _j++) {
  31873. edge = edges[_j];
  31874. var childNodeId = this._getConnectedId(edge, nodeId);
  31875. // add the nodes to the list by the join condition.
  31876. if (options.joinCondition === undefined) {
  31877. childEdgesObj[edge.id] = edge;
  31878. childNodesObj[nodeId] = this.body.nodes[nodeId];
  31879. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  31880. usedNodes[nodeId] = true;
  31881. } else {
  31882. var clonedOptions = _NetworkUtil2.default.cloneOptions(this.body.nodes[nodeId]);
  31883. if (options.joinCondition(clonedOptions) === true) {
  31884. childEdgesObj[edge.id] = edge;
  31885. childNodesObj[nodeId] = this.body.nodes[nodeId];
  31886. usedNodes[nodeId] = true;
  31887. } else {
  31888. // this node does not qualify after all.
  31889. gatheringSuccessful = false;
  31890. break;
  31891. }
  31892. }
  31893. }
  31894. // add to the cluster queue
  31895. if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0 && gatheringSuccessful === true) {
  31896. clusters.push({ nodes: childNodesObj, edges: childEdgesObj });
  31897. }
  31898. }
  31899. }
  31900. }
  31901. for (var _i3 = 0; _i3 < clusters.length; _i3++) {
  31902. this._cluster(clusters[_i3].nodes, clusters[_i3].edges, options, false);
  31903. }
  31904. if (refreshData === true) {
  31905. this.body.emitter.emit('_dataChanged');
  31906. }
  31907. }
  31908. /**
  31909. * Cluster all nodes in the network that have only 1 edge
  31910. * @param options
  31911. * @param refreshData
  31912. */
  31913. }, {
  31914. key: 'clusterOutliers',
  31915. value: function clusterOutliers(options) {
  31916. var refreshData = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  31917. this.clusterByEdgeCount(1, options, refreshData);
  31918. }
  31919. /**
  31920. * Cluster all nodes in the network that have only 2 edge
  31921. * @param options
  31922. * @param refreshData
  31923. */
  31924. }, {
  31925. key: 'clusterBridges',
  31926. value: function clusterBridges(options) {
  31927. var refreshData = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  31928. this.clusterByEdgeCount(2, options, refreshData);
  31929. }
  31930. /**
  31931. * suck all connected nodes of a node into the node.
  31932. * @param nodeId
  31933. * @param options
  31934. * @param refreshData
  31935. */
  31936. }, {
  31937. key: 'clusterByConnection',
  31938. value: function clusterByConnection(nodeId, options) {
  31939. var refreshData = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
  31940. // kill conditions
  31941. if (nodeId === undefined) {
  31942. throw new Error("No nodeId supplied to clusterByConnection!");
  31943. }
  31944. if (this.body.nodes[nodeId] === undefined) {
  31945. throw new Error("The nodeId given to clusterByConnection does not exist!");
  31946. }
  31947. var node = this.body.nodes[nodeId];
  31948. options = this._checkOptions(options, node);
  31949. if (options.clusterNodeProperties.x === undefined) {
  31950. options.clusterNodeProperties.x = node.x;
  31951. }
  31952. if (options.clusterNodeProperties.y === undefined) {
  31953. options.clusterNodeProperties.y = node.y;
  31954. }
  31955. if (options.clusterNodeProperties.fixed === undefined) {
  31956. options.clusterNodeProperties.fixed = {};
  31957. options.clusterNodeProperties.fixed.x = node.options.fixed.x;
  31958. options.clusterNodeProperties.fixed.y = node.options.fixed.y;
  31959. }
  31960. var childNodesObj = {};
  31961. var childEdgesObj = {};
  31962. var parentNodeId = node.id;
  31963. var parentClonedOptions = _NetworkUtil2.default.cloneOptions(node);
  31964. childNodesObj[parentNodeId] = node;
  31965. // collect the nodes that will be in the cluster
  31966. for (var i = 0; i < node.edges.length; i++) {
  31967. var edge = node.edges[i];
  31968. if (this.clusteredEdges[edge.id] === undefined) {
  31969. var childNodeId = this._getConnectedId(edge, parentNodeId);
  31970. // if the child node is not in a cluster
  31971. if (this.clusteredNodes[childNodeId] === undefined) {
  31972. if (childNodeId !== parentNodeId) {
  31973. if (options.joinCondition === undefined) {
  31974. childEdgesObj[edge.id] = edge;
  31975. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  31976. } else {
  31977. // clone the options and insert some additional parameters that could be interesting.
  31978. var childClonedOptions = _NetworkUtil2.default.cloneOptions(this.body.nodes[childNodeId]);
  31979. if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) {
  31980. childEdgesObj[edge.id] = edge;
  31981. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  31982. }
  31983. }
  31984. } else {
  31985. // swallow the edge if it is self-referencing.
  31986. childEdgesObj[edge.id] = edge;
  31987. }
  31988. }
  31989. }
  31990. }
  31991. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  31992. }
  31993. /**
  31994. * This function creates the edges that will be attached to the cluster
  31995. * It looks for edges that are connected to the nodes from the "outside' of the cluster.
  31996. *
  31997. * @param childNodesObj
  31998. * @param childEdgesObj
  31999. * @param clusterNodeProperties
  32000. * @param clusterEdgeProperties
  32001. * @private
  32002. */
  32003. }, {
  32004. key: '_createClusterEdges',
  32005. value: function _createClusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, clusterEdgeProperties) {
  32006. var edge = void 0,
  32007. childNodeId = void 0,
  32008. childNode = void 0,
  32009. toId = void 0,
  32010. fromId = void 0,
  32011. otherNodeId = void 0;
  32012. // loop over all child nodes and their edges to find edges going out of the cluster
  32013. // these edges will be replaced by clusterEdges.
  32014. var childKeys = Object.keys(childNodesObj);
  32015. var createEdges = [];
  32016. for (var i = 0; i < childKeys.length; i++) {
  32017. childNodeId = childKeys[i];
  32018. childNode = childNodesObj[childNodeId];
  32019. // construct new edges from the cluster to others
  32020. for (var j = 0; j < childNode.edges.length; j++) {
  32021. edge = childNode.edges[j];
  32022. // we only handle edges that are visible to the system, not the disabled ones from the clustering process.
  32023. if (this.clusteredEdges[edge.id] === undefined) {
  32024. // self-referencing edges will be added to the "hidden" list
  32025. if (edge.toId == edge.fromId) {
  32026. childEdgesObj[edge.id] = edge;
  32027. } else {
  32028. // set up the from and to.
  32029. if (edge.toId == childNodeId) {
  32030. // this is a double equals because ints and strings can be interchanged here.
  32031. toId = clusterNodeProperties.id;
  32032. fromId = edge.fromId;
  32033. otherNodeId = fromId;
  32034. } else {
  32035. toId = edge.toId;
  32036. fromId = clusterNodeProperties.id;
  32037. otherNodeId = toId;
  32038. }
  32039. }
  32040. // Only edges from the cluster outwards are being replaced.
  32041. if (childNodesObj[otherNodeId] === undefined) {
  32042. createEdges.push({ edge: edge, fromId: fromId, toId: toId });
  32043. }
  32044. }
  32045. }
  32046. }
  32047. // here we actually create the replacement edges. We could not do this in the loop above as the creation process
  32048. // would add an edge to the edges array we are iterating over.
  32049. for (var _j2 = 0; _j2 < createEdges.length; _j2++) {
  32050. var _edge = createEdges[_j2].edge;
  32051. // copy the options of the edge we will replace
  32052. var clonedOptions = _NetworkUtil2.default.cloneOptions(_edge, 'edge');
  32053. // make sure the properties of clusterEdges are superimposed on it
  32054. util.deepExtend(clonedOptions, clusterEdgeProperties);
  32055. // set up the edge
  32056. clonedOptions.from = createEdges[_j2].fromId;
  32057. clonedOptions.to = createEdges[_j2].toId;
  32058. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  32059. //clonedOptions.id = '(cf: ' + createEdges[j].fromId + " to: " + createEdges[j].toId + ")" + Math.random();
  32060. // create the edge and give a reference to the one it replaced.
  32061. var newEdge = this.body.functions.createEdge(clonedOptions);
  32062. newEdge.clusteringEdgeReplacingId = _edge.id;
  32063. // connect the edge.
  32064. this.body.edges[newEdge.id] = newEdge;
  32065. newEdge.connect();
  32066. // hide the replaced edge
  32067. this._backupEdgeOptions(_edge);
  32068. _edge.setOptions({ physics: false, hidden: true });
  32069. }
  32070. }
  32071. /**
  32072. * This function checks the options that can be supplied to the different cluster functions
  32073. * for certain fields and inserts defaults if needed
  32074. * @param options
  32075. * @returns {*}
  32076. * @private
  32077. */
  32078. }, {
  32079. key: '_checkOptions',
  32080. value: function _checkOptions() {
  32081. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  32082. if (options.clusterEdgeProperties === undefined) {
  32083. options.clusterEdgeProperties = {};
  32084. }
  32085. if (options.clusterNodeProperties === undefined) {
  32086. options.clusterNodeProperties = {};
  32087. }
  32088. return options;
  32089. }
  32090. /**
  32091. *
  32092. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  32093. * @param {Object} childEdgesObj | object with edge objects, id as keys
  32094. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  32095. * @param {Boolean} refreshData | when true, do not wrap up
  32096. * @private
  32097. */
  32098. }, {
  32099. key: '_cluster',
  32100. value: function _cluster(childNodesObj, childEdgesObj, options) {
  32101. var refreshData = arguments.length <= 3 || arguments[3] === undefined ? true : arguments[3];
  32102. // kill condition: no children so can't cluster or only one node in the cluster, don't bother
  32103. if (Object.keys(childNodesObj).length < 2) {
  32104. return;
  32105. }
  32106. // check if this cluster call is not trying to cluster anything that is in another cluster.
  32107. for (var nodeId in childNodesObj) {
  32108. if (childNodesObj.hasOwnProperty(nodeId)) {
  32109. if (this.clusteredNodes[nodeId] !== undefined) {
  32110. return;
  32111. }
  32112. }
  32113. }
  32114. var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties);
  32115. // construct the clusterNodeProperties
  32116. if (options.processProperties !== undefined) {
  32117. // get the childNode options
  32118. var childNodesOptions = [];
  32119. for (var _nodeId in childNodesObj) {
  32120. if (childNodesObj.hasOwnProperty(_nodeId)) {
  32121. var clonedOptions = _NetworkUtil2.default.cloneOptions(childNodesObj[_nodeId]);
  32122. childNodesOptions.push(clonedOptions);
  32123. }
  32124. }
  32125. // get cluster properties based on childNodes
  32126. var childEdgesOptions = [];
  32127. for (var edgeId in childEdgesObj) {
  32128. if (childEdgesObj.hasOwnProperty(edgeId)) {
  32129. // these cluster edges will be removed on creation of the cluster.
  32130. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  32131. var _clonedOptions = _NetworkUtil2.default.cloneOptions(childEdgesObj[edgeId], 'edge');
  32132. childEdgesOptions.push(_clonedOptions);
  32133. }
  32134. }
  32135. }
  32136. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  32137. if (!clusterNodeProperties) {
  32138. throw new Error("The processProperties function does not return properties!");
  32139. }
  32140. }
  32141. // check if we have an unique id;
  32142. if (clusterNodeProperties.id === undefined) {
  32143. clusterNodeProperties.id = 'cluster:' + util.randomUUID();
  32144. }
  32145. var clusterId = clusterNodeProperties.id;
  32146. if (clusterNodeProperties.label === undefined) {
  32147. clusterNodeProperties.label = 'cluster';
  32148. }
  32149. // give the clusterNode a position if it does not have one.
  32150. var pos = undefined;
  32151. if (clusterNodeProperties.x === undefined) {
  32152. pos = this._getClusterPosition(childNodesObj);
  32153. clusterNodeProperties.x = pos.x;
  32154. }
  32155. if (clusterNodeProperties.y === undefined) {
  32156. if (pos === undefined) {
  32157. pos = this._getClusterPosition(childNodesObj);
  32158. }
  32159. clusterNodeProperties.y = pos.y;
  32160. }
  32161. // force the ID to remain the same
  32162. clusterNodeProperties.id = clusterId;
  32163. // create the clusterNode
  32164. var clusterNode = this.body.functions.createNode(clusterNodeProperties, _Cluster2.default);
  32165. clusterNode.isCluster = true;
  32166. clusterNode.containedNodes = childNodesObj;
  32167. clusterNode.containedEdges = childEdgesObj;
  32168. // cache a copy from the cluster edge properties if we have to reconnect others later on
  32169. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  32170. // finally put the cluster node into global
  32171. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  32172. // create the new edges that will connect to the cluster, all self-referencing edges will be added to childEdgesObject here.
  32173. this._createClusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  32174. // disable the childEdges
  32175. for (var _edgeId in childEdgesObj) {
  32176. if (childEdgesObj.hasOwnProperty(_edgeId)) {
  32177. if (this.body.edges[_edgeId] !== undefined) {
  32178. var edge = this.body.edges[_edgeId];
  32179. // cache the options before changing
  32180. this._backupEdgeOptions(edge);
  32181. // disable physics and hide the edge
  32182. edge.setOptions({ physics: false, hidden: true });
  32183. }
  32184. }
  32185. }
  32186. // disable the childNodes
  32187. for (var _nodeId2 in childNodesObj) {
  32188. if (childNodesObj.hasOwnProperty(_nodeId2)) {
  32189. this.clusteredNodes[_nodeId2] = { clusterId: clusterNodeProperties.id, node: this.body.nodes[_nodeId2] };
  32190. this.body.nodes[_nodeId2].setOptions({ hidden: true, physics: false });
  32191. }
  32192. }
  32193. // set ID to undefined so no duplicates arise
  32194. clusterNodeProperties.id = undefined;
  32195. // wrap up
  32196. if (refreshData === true) {
  32197. this.body.emitter.emit('_dataChanged');
  32198. }
  32199. }
  32200. }, {
  32201. key: '_backupEdgeOptions',
  32202. value: function _backupEdgeOptions(edge) {
  32203. if (this.clusteredEdges[edge.id] === undefined) {
  32204. this.clusteredEdges[edge.id] = { physics: edge.options.physics, hidden: edge.options.hidden };
  32205. }
  32206. }
  32207. }, {
  32208. key: '_restoreEdge',
  32209. value: function _restoreEdge(edge) {
  32210. var originalOptions = this.clusteredEdges[edge.id];
  32211. if (originalOptions !== undefined) {
  32212. edge.setOptions({ physics: originalOptions.physics, hidden: originalOptions.hidden });
  32213. delete this.clusteredEdges[edge.id];
  32214. }
  32215. }
  32216. /**
  32217. * Check if a node is a cluster.
  32218. * @param nodeId
  32219. * @returns {*}
  32220. */
  32221. }, {
  32222. key: 'isCluster',
  32223. value: function isCluster(nodeId) {
  32224. if (this.body.nodes[nodeId] !== undefined) {
  32225. return this.body.nodes[nodeId].isCluster === true;
  32226. } else {
  32227. console.log("Node does not exist.");
  32228. return false;
  32229. }
  32230. }
  32231. /**
  32232. * get the position of the cluster node based on what's inside
  32233. * @param {object} childNodesObj | object with node objects, id as keys
  32234. * @returns {{x: number, y: number}}
  32235. * @private
  32236. */
  32237. }, {
  32238. key: '_getClusterPosition',
  32239. value: function _getClusterPosition(childNodesObj) {
  32240. var childKeys = Object.keys(childNodesObj);
  32241. var minX = childNodesObj[childKeys[0]].x;
  32242. var maxX = childNodesObj[childKeys[0]].x;
  32243. var minY = childNodesObj[childKeys[0]].y;
  32244. var maxY = childNodesObj[childKeys[0]].y;
  32245. var node = void 0;
  32246. for (var i = 1; i < childKeys.length; i++) {
  32247. node = childNodesObj[childKeys[i]];
  32248. minX = node.x < minX ? node.x : minX;
  32249. maxX = node.x > maxX ? node.x : maxX;
  32250. minY = node.y < minY ? node.y : minY;
  32251. maxY = node.y > maxY ? node.y : maxY;
  32252. }
  32253. return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) };
  32254. }
  32255. /**
  32256. * Open a cluster by calling this function.
  32257. * @param {String} clusterNodeId | the ID of the cluster node
  32258. * @param {Boolean} refreshData | wrap up afterwards if not true
  32259. */
  32260. }, {
  32261. key: 'openCluster',
  32262. value: function openCluster(clusterNodeId, options) {
  32263. var refreshData = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
  32264. // kill conditions
  32265. if (clusterNodeId === undefined) {
  32266. throw new Error("No clusterNodeId supplied to openCluster.");
  32267. }
  32268. if (this.body.nodes[clusterNodeId] === undefined) {
  32269. throw new Error("The clusterNodeId supplied to openCluster does not exist.");
  32270. }
  32271. if (this.body.nodes[clusterNodeId].containedNodes === undefined) {
  32272. console.log("The node:" + clusterNodeId + " is not a cluster.");
  32273. return;
  32274. }
  32275. var clusterNode = this.body.nodes[clusterNodeId];
  32276. var containedNodes = clusterNode.containedNodes;
  32277. var containedEdges = clusterNode.containedEdges;
  32278. // allow the user to position the nodes after release.
  32279. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  32280. var positions = {};
  32281. var clusterPosition = { x: clusterNode.x, y: clusterNode.y };
  32282. for (var nodeId in containedNodes) {
  32283. if (containedNodes.hasOwnProperty(nodeId)) {
  32284. var containedNode = this.body.nodes[nodeId];
  32285. positions[nodeId] = { x: containedNode.x, y: containedNode.y };
  32286. }
  32287. }
  32288. var newPositions = options.releaseFunction(clusterPosition, positions);
  32289. for (var _nodeId3 in containedNodes) {
  32290. if (containedNodes.hasOwnProperty(_nodeId3)) {
  32291. var _containedNode = this.body.nodes[_nodeId3];
  32292. if (newPositions[_nodeId3] !== undefined) {
  32293. _containedNode.x = newPositions[_nodeId3].x === undefined ? clusterNode.x : newPositions[_nodeId3].x;
  32294. _containedNode.y = newPositions[_nodeId3].y === undefined ? clusterNode.y : newPositions[_nodeId3].y;
  32295. }
  32296. }
  32297. }
  32298. } else {
  32299. // copy the position from the cluster
  32300. for (var _nodeId4 in containedNodes) {
  32301. if (containedNodes.hasOwnProperty(_nodeId4)) {
  32302. var _containedNode2 = this.body.nodes[_nodeId4];
  32303. _containedNode2 = containedNodes[_nodeId4];
  32304. // inherit position
  32305. if (_containedNode2.options.fixed.x === false) {
  32306. _containedNode2.x = clusterNode.x;
  32307. }
  32308. if (_containedNode2.options.fixed.y === false) {
  32309. _containedNode2.y = clusterNode.y;
  32310. }
  32311. }
  32312. }
  32313. }
  32314. // release nodes
  32315. for (var _nodeId5 in containedNodes) {
  32316. if (containedNodes.hasOwnProperty(_nodeId5)) {
  32317. var _containedNode3 = this.body.nodes[_nodeId5];
  32318. // inherit speed
  32319. _containedNode3.vx = clusterNode.vx;
  32320. _containedNode3.vy = clusterNode.vy;
  32321. // we use these methods to avoid re-instantiating the shape, which happens with setOptions.
  32322. _containedNode3.setOptions({ hidden: false, physics: true });
  32323. delete this.clusteredNodes[_nodeId5];
  32324. }
  32325. }
  32326. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  32327. var edgesToBeDeleted = [];
  32328. for (var i = 0; i < clusterNode.edges.length; i++) {
  32329. edgesToBeDeleted.push(clusterNode.edges[i]);
  32330. }
  32331. // actually handling the deleting.
  32332. for (var _i4 = 0; _i4 < edgesToBeDeleted.length; _i4++) {
  32333. var edge = edgesToBeDeleted[_i4];
  32334. var otherNodeId = this._getConnectedId(edge, clusterNodeId);
  32335. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  32336. if (this.clusteredNodes[otherNodeId] !== undefined) {
  32337. // transfer ownership:
  32338. var otherCluster = this.body.nodes[this.clusteredNodes[otherNodeId].clusterId];
  32339. var transferEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  32340. if (transferEdge !== undefined) {
  32341. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  32342. // delete local reference
  32343. delete containedEdges[transferEdge.id];
  32344. // create new cluster edge from the otherCluster:
  32345. // get to and from
  32346. var fromId = transferEdge.fromId;
  32347. var toId = transferEdge.toId;
  32348. if (transferEdge.toId == otherNodeId) {
  32349. toId = this.clusteredNodes[otherNodeId].clusterId;
  32350. } else {
  32351. fromId = this.clusteredNodes[otherNodeId].clusterId;
  32352. }
  32353. // clone the options and apply the cluster options to them
  32354. var clonedOptions = _NetworkUtil2.default.cloneOptions(transferEdge, 'edge');
  32355. util.deepExtend(clonedOptions, otherCluster.clusterEdgeProperties);
  32356. // apply the edge specific options to it.
  32357. var id = 'clusterEdge:' + util.randomUUID();
  32358. util.deepExtend(clonedOptions, { from: fromId, to: toId, hidden: false, physics: true, id: id });
  32359. // create it
  32360. var newEdge = this.body.functions.createEdge(clonedOptions);
  32361. newEdge.clusteringEdgeReplacingId = transferEdge.id;
  32362. this.body.edges[id] = newEdge;
  32363. this.body.edges[id].connect();
  32364. }
  32365. } else {
  32366. var replacedEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  32367. if (replacedEdge !== undefined) {
  32368. this._restoreEdge(replacedEdge);
  32369. }
  32370. }
  32371. edge.cleanup();
  32372. // this removes the edge from node.edges, which is why edgeIds is formed
  32373. edge.disconnect();
  32374. delete this.body.edges[edge.id];
  32375. }
  32376. // handle the releasing of the edges
  32377. for (var edgeId in containedEdges) {
  32378. if (containedEdges.hasOwnProperty(edgeId)) {
  32379. this._restoreEdge(containedEdges[edgeId]);
  32380. }
  32381. }
  32382. // remove clusterNode
  32383. delete this.body.nodes[clusterNodeId];
  32384. if (refreshData === true) {
  32385. this.body.emitter.emit('_dataChanged');
  32386. }
  32387. }
  32388. }, {
  32389. key: 'getNodesInCluster',
  32390. value: function getNodesInCluster(clusterId) {
  32391. var nodesArray = [];
  32392. if (this.isCluster(clusterId) === true) {
  32393. var containedNodes = this.body.nodes[clusterId].containedNodes;
  32394. for (var nodeId in containedNodes) {
  32395. if (containedNodes.hasOwnProperty(nodeId)) {
  32396. nodesArray.push(this.body.nodes[nodeId].id);
  32397. }
  32398. }
  32399. }
  32400. return nodesArray;
  32401. }
  32402. /**
  32403. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  32404. * @param nodeId
  32405. * @returns {Array}
  32406. */
  32407. }, {
  32408. key: 'findNode',
  32409. value: function findNode(nodeId) {
  32410. var stack = [];
  32411. var max = 100;
  32412. var counter = 0;
  32413. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  32414. stack.push(this.body.nodes[nodeId].id);
  32415. nodeId = this.clusteredNodes[nodeId].clusterId;
  32416. counter++;
  32417. }
  32418. stack.push(this.body.nodes[nodeId].id);
  32419. stack.reverse();
  32420. return stack;
  32421. }
  32422. /**
  32423. * Get the Id the node is connected to
  32424. * @param edge
  32425. * @param nodeId
  32426. * @returns {*}
  32427. * @private
  32428. */
  32429. }, {
  32430. key: '_getConnectedId',
  32431. value: function _getConnectedId(edge, nodeId) {
  32432. if (edge.toId != nodeId) {
  32433. return edge.toId;
  32434. } else if (edge.fromId != nodeId) {
  32435. return edge.fromId;
  32436. } else {
  32437. return edge.fromId;
  32438. }
  32439. }
  32440. /**
  32441. * We determine how many connections denote an important hub.
  32442. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  32443. *
  32444. * @private
  32445. */
  32446. }, {
  32447. key: '_getHubSize',
  32448. value: function _getHubSize() {
  32449. var average = 0;
  32450. var averageSquared = 0;
  32451. var hubCounter = 0;
  32452. var largestHub = 0;
  32453. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  32454. var node = this.body.nodes[this.body.nodeIndices[i]];
  32455. if (node.edges.length > largestHub) {
  32456. largestHub = node.edges.length;
  32457. }
  32458. average += node.edges.length;
  32459. averageSquared += Math.pow(node.edges.length, 2);
  32460. hubCounter += 1;
  32461. }
  32462. average = average / hubCounter;
  32463. averageSquared = averageSquared / hubCounter;
  32464. var variance = averageSquared - Math.pow(average, 2);
  32465. var standardDeviation = Math.sqrt(variance);
  32466. var hubThreshold = Math.floor(average + 2 * standardDeviation);
  32467. // always have at least one to cluster
  32468. if (hubThreshold > largestHub) {
  32469. hubThreshold = largestHub;
  32470. }
  32471. return hubThreshold;
  32472. }
  32473. }]);
  32474. return ClusterEngine;
  32475. }();
  32476. exports.default = ClusterEngine;
  32477. /***/ },
  32478. /* 103 */
  32479. /***/ function(module, exports, __webpack_require__) {
  32480. "use strict";
  32481. Object.defineProperty(exports, "__esModule", {
  32482. value: true
  32483. });
  32484. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  32485. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32486. var util = __webpack_require__(1);
  32487. var NetworkUtil = function () {
  32488. function NetworkUtil() {
  32489. _classCallCheck(this, NetworkUtil);
  32490. }
  32491. /**
  32492. * Find the center position of the network considering the bounding boxes
  32493. */
  32494. _createClass(NetworkUtil, null, [{
  32495. key: "getRange",
  32496. value: function getRange(allNodes) {
  32497. var specificNodes = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
  32498. var minY = 1e9,
  32499. maxY = -1e9,
  32500. minX = 1e9,
  32501. maxX = -1e9,
  32502. node;
  32503. if (specificNodes.length > 0) {
  32504. for (var i = 0; i < specificNodes.length; i++) {
  32505. node = allNodes[specificNodes[i]];
  32506. if (minX > node.shape.boundingBox.left) {
  32507. minX = node.shape.boundingBox.left;
  32508. }
  32509. if (maxX < node.shape.boundingBox.right) {
  32510. maxX = node.shape.boundingBox.right;
  32511. }
  32512. if (minY > node.shape.boundingBox.top) {
  32513. minY = node.shape.boundingBox.top;
  32514. } // top is negative, bottom is positive
  32515. if (maxY < node.shape.boundingBox.bottom) {
  32516. maxY = node.shape.boundingBox.bottom;
  32517. } // top is negative, bottom is positive
  32518. }
  32519. }
  32520. if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
  32521. minY = 0, maxY = 0, minX = 0, maxX = 0;
  32522. }
  32523. return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
  32524. }
  32525. /**
  32526. * Find the center position of the network
  32527. */
  32528. }, {
  32529. key: "getRangeCore",
  32530. value: function getRangeCore(allNodes) {
  32531. var specificNodes = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
  32532. var minY = 1e9,
  32533. maxY = -1e9,
  32534. minX = 1e9,
  32535. maxX = -1e9,
  32536. node;
  32537. if (specificNodes.length > 0) {
  32538. for (var i = 0; i < specificNodes.length; i++) {
  32539. node = allNodes[specificNodes[i]];
  32540. if (minX > node.x) {
  32541. minX = node.x;
  32542. }
  32543. if (maxX < node.x) {
  32544. maxX = node.x;
  32545. }
  32546. if (minY > node.y) {
  32547. minY = node.y;
  32548. } // top is negative, bottom is positive
  32549. if (maxY < node.y) {
  32550. maxY = node.y;
  32551. } // top is negative, bottom is positive
  32552. }
  32553. }
  32554. if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
  32555. minY = 0, maxY = 0, minX = 0, maxX = 0;
  32556. }
  32557. return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
  32558. }
  32559. /**
  32560. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  32561. * @returns {{x: number, y: number}}
  32562. */
  32563. }, {
  32564. key: "findCenter",
  32565. value: function findCenter(range) {
  32566. return { x: 0.5 * (range.maxX + range.minX),
  32567. y: 0.5 * (range.maxY + range.minY) };
  32568. }
  32569. /**
  32570. * This returns a clone of the options or options of the edge or node to be used for construction of new edges or check functions for new nodes.
  32571. * @param item
  32572. * @param type
  32573. * @returns {{}}
  32574. */
  32575. }, {
  32576. key: "cloneOptions",
  32577. value: function cloneOptions(item, type) {
  32578. var clonedOptions = {};
  32579. if (type === undefined || type === 'node') {
  32580. util.deepExtend(clonedOptions, item.options, true);
  32581. clonedOptions.x = item.x;
  32582. clonedOptions.y = item.y;
  32583. clonedOptions.amountOfConnections = item.edges.length;
  32584. } else {
  32585. util.deepExtend(clonedOptions, item.options, true);
  32586. }
  32587. return clonedOptions;
  32588. }
  32589. }]);
  32590. return NetworkUtil;
  32591. }();
  32592. exports.default = NetworkUtil;
  32593. /***/ },
  32594. /* 104 */
  32595. /***/ function(module, exports, __webpack_require__) {
  32596. 'use strict';
  32597. Object.defineProperty(exports, "__esModule", {
  32598. value: true
  32599. });
  32600. var _Node2 = __webpack_require__(65);
  32601. var _Node3 = _interopRequireDefault(_Node2);
  32602. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  32603. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32604. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  32605. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  32606. /**
  32607. *
  32608. */
  32609. var Cluster = function (_Node) {
  32610. _inherits(Cluster, _Node);
  32611. function Cluster(options, body, imagelist, grouplist, globalOptions) {
  32612. _classCallCheck(this, Cluster);
  32613. var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Cluster).call(this, options, body, imagelist, grouplist, globalOptions));
  32614. _this.isCluster = true;
  32615. _this.containedNodes = {};
  32616. _this.containedEdges = {};
  32617. return _this;
  32618. }
  32619. return Cluster;
  32620. }(_Node3.default);
  32621. exports.default = Cluster;
  32622. /***/ },
  32623. /* 105 */
  32624. /***/ function(module, exports, __webpack_require__) {
  32625. 'use strict';
  32626. Object.defineProperty(exports, "__esModule", {
  32627. value: true
  32628. });
  32629. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  32630. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32631. if (typeof window !== 'undefined') {
  32632. window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  32633. }
  32634. var util = __webpack_require__(1);
  32635. var CanvasRenderer = function () {
  32636. function CanvasRenderer(body, canvas) {
  32637. _classCallCheck(this, CanvasRenderer);
  32638. this.body = body;
  32639. this.canvas = canvas;
  32640. this.redrawRequested = false;
  32641. this.renderTimer = undefined;
  32642. this.requiresTimeout = true;
  32643. this.renderingActive = false;
  32644. this.renderRequests = 0;
  32645. this.pixelRatio = undefined;
  32646. this.allowRedraw = true;
  32647. this.dragging = false;
  32648. this.options = {};
  32649. this.defaultOptions = {
  32650. hideEdgesOnDrag: false,
  32651. hideNodesOnDrag: false
  32652. };
  32653. util.extend(this.options, this.defaultOptions);
  32654. this._determineBrowserMethod();
  32655. this.bindEventListeners();
  32656. }
  32657. _createClass(CanvasRenderer, [{
  32658. key: 'bindEventListeners',
  32659. value: function bindEventListeners() {
  32660. var _this = this;
  32661. this.body.emitter.on("dragStart", function () {
  32662. _this.dragging = true;
  32663. });
  32664. this.body.emitter.on("dragEnd", function () {
  32665. return _this.dragging = false;
  32666. });
  32667. this.body.emitter.on("_resizeNodes", function () {
  32668. return _this._resizeNodes();
  32669. });
  32670. this.body.emitter.on("_redraw", function () {
  32671. if (_this.renderingActive === false) {
  32672. _this._redraw();
  32673. }
  32674. });
  32675. this.body.emitter.on("_blockRedraw", function () {
  32676. _this.allowRedraw = false;
  32677. });
  32678. this.body.emitter.on("_allowRedraw", function () {
  32679. _this.allowRedraw = true;_this.redrawRequested = false;
  32680. });
  32681. this.body.emitter.on("_requestRedraw", this._requestRedraw.bind(this));
  32682. this.body.emitter.on("_startRendering", function () {
  32683. _this.renderRequests += 1;
  32684. _this.renderingActive = true;
  32685. _this._startRendering();
  32686. });
  32687. this.body.emitter.on("_stopRendering", function () {
  32688. _this.renderRequests -= 1;
  32689. _this.renderingActive = _this.renderRequests > 0;
  32690. _this.renderTimer = undefined;
  32691. });
  32692. this.body.emitter.on('destroy', function () {
  32693. _this.renderRequests = 0;
  32694. _this.allowRedraw = false;
  32695. _this.renderingActive = false;
  32696. if (_this.requiresTimeout === true) {
  32697. clearTimeout(_this.renderTimer);
  32698. } else {
  32699. cancelAnimationFrame(_this.renderTimer);
  32700. }
  32701. _this.body.emitter.off();
  32702. });
  32703. }
  32704. }, {
  32705. key: 'setOptions',
  32706. value: function setOptions(options) {
  32707. if (options !== undefined) {
  32708. var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag'];
  32709. util.selectiveDeepExtend(fields, this.options, options);
  32710. }
  32711. }
  32712. }, {
  32713. key: '_startRendering',
  32714. value: function _startRendering() {
  32715. if (this.renderingActive === true) {
  32716. if (this.renderTimer === undefined) {
  32717. if (this.requiresTimeout === true) {
  32718. this.renderTimer = window.setTimeout(this._renderStep.bind(this), this.simulationInterval); // wait this.renderTimeStep milliseconds and perform the animation step function
  32719. } else {
  32720. this.renderTimer = window.requestAnimationFrame(this._renderStep.bind(this)); // wait this.renderTimeStep milliseconds and perform the animation step function
  32721. }
  32722. }
  32723. }
  32724. }
  32725. }, {
  32726. key: '_renderStep',
  32727. value: function _renderStep() {
  32728. if (this.renderingActive === true) {
  32729. // reset the renderTimer so a new scheduled animation step can be set
  32730. this.renderTimer = undefined;
  32731. if (this.requiresTimeout === true) {
  32732. // this schedules a new simulation step
  32733. this._startRendering();
  32734. }
  32735. this._redraw();
  32736. if (this.requiresTimeout === false) {
  32737. // this schedules a new simulation step
  32738. this._startRendering();
  32739. }
  32740. }
  32741. }
  32742. /**
  32743. * Redraw the network with the current data
  32744. * chart will be resized too.
  32745. */
  32746. }, {
  32747. key: 'redraw',
  32748. value: function redraw() {
  32749. this.body.emitter.emit('setSize');
  32750. this._redraw();
  32751. }
  32752. /**
  32753. * Redraw the network with the current data
  32754. * @param hidden | used to get the first estimate of the node sizes. only the nodes are drawn after which they are quickly drawn over.
  32755. * @private
  32756. */
  32757. }, {
  32758. key: '_requestRedraw',
  32759. value: function _requestRedraw() {
  32760. var _this2 = this;
  32761. if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedraw === true) {
  32762. this.redrawRequested = true;
  32763. if (this.requiresTimeout === true) {
  32764. window.setTimeout(function () {
  32765. _this2._redraw(false);
  32766. }, 0);
  32767. } else {
  32768. window.requestAnimationFrame(function () {
  32769. _this2._redraw(false);
  32770. });
  32771. }
  32772. }
  32773. }
  32774. }, {
  32775. key: '_redraw',
  32776. value: function _redraw() {
  32777. var hidden = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];
  32778. if (this.allowRedraw === true) {
  32779. this.body.emitter.emit("initRedraw");
  32780. this.redrawRequested = false;
  32781. var ctx = this.canvas.frame.canvas.getContext('2d');
  32782. // when the container div was hidden, this fixes it back up!
  32783. if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) {
  32784. this.canvas.setSize();
  32785. }
  32786. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  32787. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  32788. // clear the canvas
  32789. var w = this.canvas.frame.canvas.clientWidth;
  32790. var h = this.canvas.frame.canvas.clientHeight;
  32791. ctx.clearRect(0, 0, w, h);
  32792. // if the div is hidden, we stop the redraw here for performance.
  32793. if (this.canvas.frame.clientWidth === 0) {
  32794. return;
  32795. }
  32796. // set scaling and translation
  32797. ctx.save();
  32798. ctx.translate(this.body.view.translation.x, this.body.view.translation.y);
  32799. ctx.scale(this.body.view.scale, this.body.view.scale);
  32800. ctx.beginPath();
  32801. this.body.emitter.emit("beforeDrawing", ctx);
  32802. ctx.closePath();
  32803. if (hidden === false) {
  32804. if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) {
  32805. this._drawEdges(ctx);
  32806. }
  32807. }
  32808. if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) {
  32809. this._drawNodes(ctx, hidden);
  32810. }
  32811. ctx.beginPath();
  32812. this.body.emitter.emit("afterDrawing", ctx);
  32813. ctx.closePath();
  32814. // restore original scaling and translation
  32815. ctx.restore();
  32816. if (hidden === true) {
  32817. ctx.clearRect(0, 0, w, h);
  32818. }
  32819. }
  32820. }
  32821. /**
  32822. * Redraw all nodes
  32823. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  32824. * @param {CanvasRenderingContext2D} ctx
  32825. * @param {Boolean} [alwaysShow]
  32826. * @private
  32827. */
  32828. }, {
  32829. key: '_resizeNodes',
  32830. value: function _resizeNodes() {
  32831. var ctx = this.canvas.frame.canvas.getContext('2d');
  32832. if (this.pixelRatio === undefined) {
  32833. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  32834. }
  32835. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  32836. ctx.save();
  32837. ctx.translate(this.body.view.translation.x, this.body.view.translation.y);
  32838. ctx.scale(this.body.view.scale, this.body.view.scale);
  32839. var nodes = this.body.nodes;
  32840. var node = void 0;
  32841. // resize all nodes
  32842. for (var nodeId in nodes) {
  32843. if (nodes.hasOwnProperty(nodeId)) {
  32844. node = nodes[nodeId];
  32845. node.resize(ctx);
  32846. node.updateBoundingBox(ctx, node.selected);
  32847. }
  32848. }
  32849. // restore original scaling and translation
  32850. ctx.restore();
  32851. }
  32852. /**
  32853. * Redraw all nodes
  32854. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  32855. * @param {CanvasRenderingContext2D} ctx
  32856. * @param {Boolean} [alwaysShow]
  32857. * @private
  32858. */
  32859. }, {
  32860. key: '_drawNodes',
  32861. value: function _drawNodes(ctx) {
  32862. var alwaysShow = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  32863. var nodes = this.body.nodes;
  32864. var nodeIndices = this.body.nodeIndices;
  32865. var node = void 0;
  32866. var selected = [];
  32867. var margin = 20;
  32868. var topLeft = this.canvas.DOMtoCanvas({ x: -margin, y: -margin });
  32869. var bottomRight = this.canvas.DOMtoCanvas({
  32870. x: this.canvas.frame.canvas.clientWidth + margin,
  32871. y: this.canvas.frame.canvas.clientHeight + margin
  32872. });
  32873. var viewableArea = { top: topLeft.y, left: topLeft.x, bottom: bottomRight.y, right: bottomRight.x };
  32874. // draw unselected nodes;
  32875. for (var i = 0; i < nodeIndices.length; i++) {
  32876. node = nodes[nodeIndices[i]];
  32877. // set selected nodes aside
  32878. if (node.isSelected()) {
  32879. selected.push(nodeIndices[i]);
  32880. } else {
  32881. if (alwaysShow === true) {
  32882. node.draw(ctx);
  32883. } else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) {
  32884. node.draw(ctx);
  32885. } else {
  32886. node.updateBoundingBox(ctx, node.selected);
  32887. }
  32888. }
  32889. }
  32890. // draw the selected nodes on top
  32891. for (var _i = 0; _i < selected.length; _i++) {
  32892. node = nodes[selected[_i]];
  32893. node.draw(ctx);
  32894. }
  32895. }
  32896. /**
  32897. * Redraw all edges
  32898. * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d');
  32899. * @param {CanvasRenderingContext2D} ctx
  32900. * @private
  32901. */
  32902. }, {
  32903. key: '_drawEdges',
  32904. value: function _drawEdges(ctx) {
  32905. var edges = this.body.edges;
  32906. var edgeIndices = this.body.edgeIndices;
  32907. var edge = void 0;
  32908. for (var i = 0; i < edgeIndices.length; i++) {
  32909. edge = edges[edgeIndices[i]];
  32910. if (edge.connected === true) {
  32911. edge.draw(ctx);
  32912. }
  32913. }
  32914. }
  32915. /**
  32916. * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
  32917. * some implementations (safari and IE9) did not support requestAnimationFrame
  32918. * @private
  32919. */
  32920. }, {
  32921. key: '_determineBrowserMethod',
  32922. value: function _determineBrowserMethod() {
  32923. if (typeof window !== 'undefined') {
  32924. var browserType = navigator.userAgent.toLowerCase();
  32925. this.requiresTimeout = false;
  32926. if (browserType.indexOf('msie 9.0') != -1) {
  32927. // IE 9
  32928. this.requiresTimeout = true;
  32929. } else if (browserType.indexOf('safari') != -1) {
  32930. // safari
  32931. if (browserType.indexOf('chrome') <= -1) {
  32932. this.requiresTimeout = true;
  32933. }
  32934. }
  32935. } else {
  32936. this.requiresTimeout = true;
  32937. }
  32938. }
  32939. }]);
  32940. return CanvasRenderer;
  32941. }();
  32942. exports.default = CanvasRenderer;
  32943. /***/ },
  32944. /* 106 */
  32945. /***/ function(module, exports, __webpack_require__) {
  32946. 'use strict';
  32947. Object.defineProperty(exports, "__esModule", {
  32948. value: true
  32949. });
  32950. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  32951. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32952. var Hammer = __webpack_require__(20);
  32953. var hammerUtil = __webpack_require__(28);
  32954. var util = __webpack_require__(1);
  32955. /**
  32956. * Create the main frame for the Network.
  32957. * This function is executed once when a Network object is created. The frame
  32958. * contains a canvas, and this canvas contains all objects like the axis and
  32959. * nodes.
  32960. * @private
  32961. */
  32962. var Canvas = function () {
  32963. function Canvas(body) {
  32964. _classCallCheck(this, Canvas);
  32965. this.body = body;
  32966. this.pixelRatio = 1;
  32967. this.resizeTimer = undefined;
  32968. this.resizeFunction = this._onResize.bind(this);
  32969. this.cameraState = {};
  32970. this.initialized = false;
  32971. this.options = {};
  32972. this.defaultOptions = {
  32973. autoResize: true,
  32974. height: '100%',
  32975. width: '100%'
  32976. };
  32977. util.extend(this.options, this.defaultOptions);
  32978. this.bindEventListeners();
  32979. }
  32980. _createClass(Canvas, [{
  32981. key: 'bindEventListeners',
  32982. value: function bindEventListeners() {
  32983. var _this = this;
  32984. // bind the events
  32985. this.body.emitter.once("resize", function (obj) {
  32986. if (obj.width !== 0) {
  32987. _this.body.view.translation.x = obj.width * 0.5;
  32988. }
  32989. if (obj.height !== 0) {
  32990. _this.body.view.translation.y = obj.height * 0.5;
  32991. }
  32992. });
  32993. this.body.emitter.on("setSize", this.setSize.bind(this));
  32994. this.body.emitter.on("destroy", function () {
  32995. _this.hammerFrame.destroy();
  32996. _this.hammer.destroy();
  32997. _this._cleanUp();
  32998. });
  32999. }
  33000. }, {
  33001. key: 'setOptions',
  33002. value: function setOptions(options) {
  33003. var _this2 = this;
  33004. if (options !== undefined) {
  33005. var fields = ['width', 'height', 'autoResize'];
  33006. util.selectiveDeepExtend(fields, this.options, options);
  33007. }
  33008. if (this.options.autoResize === true) {
  33009. // automatically adapt to a changing size of the browser.
  33010. this._cleanUp();
  33011. this.resizeTimer = setInterval(function () {
  33012. var changed = _this2.setSize();
  33013. if (changed === true) {
  33014. _this2.body.emitter.emit("_requestRedraw");
  33015. }
  33016. }, 1000);
  33017. this.resizeFunction = this._onResize.bind(this);
  33018. util.addEventListener(window, 'resize', this.resizeFunction);
  33019. }
  33020. }
  33021. }, {
  33022. key: '_cleanUp',
  33023. value: function _cleanUp() {
  33024. // automatically adapt to a changing size of the browser.
  33025. if (this.resizeTimer !== undefined) {
  33026. clearInterval(this.resizeTimer);
  33027. }
  33028. util.removeEventListener(window, 'resize', this.resizeFunction);
  33029. this.resizeFunction = undefined;
  33030. }
  33031. }, {
  33032. key: '_onResize',
  33033. value: function _onResize() {
  33034. this.setSize();
  33035. this.body.emitter.emit("_redraw");
  33036. }
  33037. /**
  33038. * Get and store the cameraState
  33039. * @private
  33040. */
  33041. }, {
  33042. key: '_getCameraState',
  33043. value: function _getCameraState() {
  33044. var pixelRatio = arguments.length <= 0 || arguments[0] === undefined ? this.pixelRatio : arguments[0];
  33045. if (this.initialized === true) {
  33046. this.cameraState.previousWidth = this.frame.canvas.width / pixelRatio;
  33047. this.cameraState.previousHeight = this.frame.canvas.height / pixelRatio;
  33048. this.cameraState.scale = this.body.view.scale;
  33049. this.cameraState.position = this.DOMtoCanvas({
  33050. x: 0.5 * this.frame.canvas.width / pixelRatio,
  33051. y: 0.5 * this.frame.canvas.height / pixelRatio
  33052. });
  33053. }
  33054. }
  33055. /**
  33056. * Set the cameraState
  33057. * @private
  33058. */
  33059. }, {
  33060. key: '_setCameraState',
  33061. value: function _setCameraState() {
  33062. if (this.cameraState.scale !== undefined && this.frame.canvas.clientWidth !== 0 && this.frame.canvas.clientHeight !== 0 && this.pixelRatio !== 0 && this.cameraState.previousWidth > 0) {
  33063. var widthRatio = this.frame.canvas.width / this.pixelRatio / this.cameraState.previousWidth;
  33064. var heightRatio = this.frame.canvas.height / this.pixelRatio / this.cameraState.previousHeight;
  33065. var newScale = this.cameraState.scale;
  33066. if (widthRatio != 1 && heightRatio != 1) {
  33067. newScale = this.cameraState.scale * 0.5 * (widthRatio + heightRatio);
  33068. } else if (widthRatio != 1) {
  33069. newScale = this.cameraState.scale * widthRatio;
  33070. } else if (heightRatio != 1) {
  33071. newScale = this.cameraState.scale * heightRatio;
  33072. }
  33073. this.body.view.scale = newScale;
  33074. // this comes from the view module.
  33075. var currentViewCenter = this.DOMtoCanvas({
  33076. x: 0.5 * this.frame.canvas.clientWidth,
  33077. y: 0.5 * this.frame.canvas.clientHeight
  33078. });
  33079. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  33080. x: currentViewCenter.x - this.cameraState.position.x,
  33081. y: currentViewCenter.y - this.cameraState.position.y
  33082. };
  33083. this.body.view.translation.x += distanceFromCenter.x * this.body.view.scale;
  33084. this.body.view.translation.y += distanceFromCenter.y * this.body.view.scale;
  33085. }
  33086. }
  33087. }, {
  33088. key: '_prepareValue',
  33089. value: function _prepareValue(value) {
  33090. if (typeof value === 'number') {
  33091. return value + 'px';
  33092. } else if (typeof value === 'string') {
  33093. if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) {
  33094. return value;
  33095. } else if (value.indexOf('%') === -1) {
  33096. return value + 'px';
  33097. }
  33098. }
  33099. throw new Error('Could not use the value supplied for width or height:' + value);
  33100. }
  33101. /**
  33102. * Create the HTML
  33103. */
  33104. }, {
  33105. key: '_create',
  33106. value: function _create() {
  33107. // remove all elements from the container element.
  33108. while (this.body.container.hasChildNodes()) {
  33109. this.body.container.removeChild(this.body.container.firstChild);
  33110. }
  33111. this.frame = document.createElement('div');
  33112. this.frame.className = 'vis-network';
  33113. this.frame.style.position = 'relative';
  33114. this.frame.style.overflow = 'hidden';
  33115. this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window
  33116. //////////////////////////////////////////////////////////////////
  33117. this.frame.canvas = document.createElement("canvas");
  33118. this.frame.canvas.style.position = 'relative';
  33119. this.frame.appendChild(this.frame.canvas);
  33120. if (!this.frame.canvas.getContext) {
  33121. var noCanvas = document.createElement('DIV');
  33122. noCanvas.style.color = 'red';
  33123. noCanvas.style.fontWeight = 'bold';
  33124. noCanvas.style.padding = '10px';
  33125. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  33126. this.frame.canvas.appendChild(noCanvas);
  33127. } else {
  33128. var ctx = this.frame.canvas.getContext("2d");
  33129. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  33130. this.frame.canvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  33131. }
  33132. // add the frame to the container element
  33133. this.body.container.appendChild(this.frame);
  33134. this.body.view.scale = 1;
  33135. this.body.view.translation = { x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight };
  33136. this._bindHammer();
  33137. }
  33138. /**
  33139. * This function binds hammer, it can be repeated over and over due to the uniqueness check.
  33140. * @private
  33141. */
  33142. }, {
  33143. key: '_bindHammer',
  33144. value: function _bindHammer() {
  33145. var _this3 = this;
  33146. if (this.hammer !== undefined) {
  33147. this.hammer.destroy();
  33148. }
  33149. this.drag = {};
  33150. this.pinch = {};
  33151. // init hammer
  33152. this.hammer = new Hammer(this.frame.canvas);
  33153. this.hammer.get('pinch').set({ enable: true });
  33154. // enable to get better response, todo: test on mobile.
  33155. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_ALL });
  33156. hammerUtil.onTouch(this.hammer, function (event) {
  33157. _this3.body.eventListeners.onTouch(event);
  33158. });
  33159. this.hammer.on('tap', function (event) {
  33160. _this3.body.eventListeners.onTap(event);
  33161. });
  33162. this.hammer.on('doubletap', function (event) {
  33163. _this3.body.eventListeners.onDoubleTap(event);
  33164. });
  33165. this.hammer.on('press', function (event) {
  33166. _this3.body.eventListeners.onHold(event);
  33167. });
  33168. this.hammer.on('panstart', function (event) {
  33169. _this3.body.eventListeners.onDragStart(event);
  33170. });
  33171. this.hammer.on('panmove', function (event) {
  33172. _this3.body.eventListeners.onDrag(event);
  33173. });
  33174. this.hammer.on('panend', function (event) {
  33175. _this3.body.eventListeners.onDragEnd(event);
  33176. });
  33177. this.hammer.on('pinch', function (event) {
  33178. _this3.body.eventListeners.onPinch(event);
  33179. });
  33180. // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work?
  33181. this.frame.canvas.addEventListener('mousewheel', function (event) {
  33182. _this3.body.eventListeners.onMouseWheel(event);
  33183. });
  33184. this.frame.canvas.addEventListener('DOMMouseScroll', function (event) {
  33185. _this3.body.eventListeners.onMouseWheel(event);
  33186. });
  33187. this.frame.canvas.addEventListener('mousemove', function (event) {
  33188. _this3.body.eventListeners.onMouseMove(event);
  33189. });
  33190. this.frame.canvas.addEventListener('contextmenu', function (event) {
  33191. _this3.body.eventListeners.onContext(event);
  33192. });
  33193. this.hammerFrame = new Hammer(this.frame);
  33194. hammerUtil.onRelease(this.hammerFrame, function (event) {
  33195. _this3.body.eventListeners.onRelease(event);
  33196. });
  33197. }
  33198. /**
  33199. * Set a new size for the network
  33200. * @param {string} width Width in pixels or percentage (for example '800px'
  33201. * or '50%')
  33202. * @param {string} height Height in pixels or percentage (for example '400px'
  33203. * or '30%')
  33204. */
  33205. }, {
  33206. key: 'setSize',
  33207. value: function setSize() {
  33208. var width = arguments.length <= 0 || arguments[0] === undefined ? this.options.width : arguments[0];
  33209. var height = arguments.length <= 1 || arguments[1] === undefined ? this.options.height : arguments[1];
  33210. width = this._prepareValue(width);
  33211. height = this._prepareValue(height);
  33212. var emitEvent = false;
  33213. var oldWidth = this.frame.canvas.width;
  33214. var oldHeight = this.frame.canvas.height;
  33215. // update the pixel ratio
  33216. var ctx = this.frame.canvas.getContext("2d");
  33217. var previousRatio = this.pixelRatio; // we cache this because the camera state storage needs the old value
  33218. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  33219. if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) {
  33220. this._getCameraState(previousRatio);
  33221. this.frame.style.width = width;
  33222. this.frame.style.height = height;
  33223. this.frame.canvas.style.width = '100%';
  33224. this.frame.canvas.style.height = '100%';
  33225. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  33226. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  33227. this.options.width = width;
  33228. this.options.height = height;
  33229. emitEvent = true;
  33230. } else {
  33231. // this would adapt the width of the canvas to the width from 100% if and only if
  33232. // there is a change.
  33233. // store the camera if there is a change in size.
  33234. if (this.frame.canvas.width != Math.round(this.frame.canvas.clientWidth * this.pixelRatio) || this.frame.canvas.height != Math.round(this.frame.canvas.clientHeight * this.pixelRatio)) {
  33235. this._getCameraState(previousRatio);
  33236. }
  33237. if (this.frame.canvas.width != Math.round(this.frame.canvas.clientWidth * this.pixelRatio)) {
  33238. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  33239. emitEvent = true;
  33240. }
  33241. if (this.frame.canvas.height != Math.round(this.frame.canvas.clientHeight * this.pixelRatio)) {
  33242. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  33243. emitEvent = true;
  33244. }
  33245. }
  33246. if (emitEvent === true) {
  33247. this.body.emitter.emit('resize', {
  33248. width: Math.round(this.frame.canvas.width / this.pixelRatio),
  33249. height: Math.round(this.frame.canvas.height / this.pixelRatio),
  33250. oldWidth: Math.round(oldWidth / this.pixelRatio),
  33251. oldHeight: Math.round(oldHeight / this.pixelRatio)
  33252. });
  33253. // restore the camera on change.
  33254. this._setCameraState();
  33255. }
  33256. // set initialized so the get and set camera will work from now on.
  33257. this.initialized = true;
  33258. return emitEvent;
  33259. }
  33260. }, {
  33261. key: '_XconvertDOMtoCanvas',
  33262. /**
  33263. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  33264. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  33265. * @param {number} x
  33266. * @returns {number}
  33267. * @private
  33268. */
  33269. value: function _XconvertDOMtoCanvas(x) {
  33270. return (x - this.body.view.translation.x) / this.body.view.scale;
  33271. }
  33272. /**
  33273. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  33274. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  33275. * @param {number} x
  33276. * @returns {number}
  33277. * @private
  33278. */
  33279. }, {
  33280. key: '_XconvertCanvasToDOM',
  33281. value: function _XconvertCanvasToDOM(x) {
  33282. return x * this.body.view.scale + this.body.view.translation.x;
  33283. }
  33284. /**
  33285. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  33286. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  33287. * @param {number} y
  33288. * @returns {number}
  33289. * @private
  33290. */
  33291. }, {
  33292. key: '_YconvertDOMtoCanvas',
  33293. value: function _YconvertDOMtoCanvas(y) {
  33294. return (y - this.body.view.translation.y) / this.body.view.scale;
  33295. }
  33296. /**
  33297. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  33298. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  33299. * @param {number} y
  33300. * @returns {number}
  33301. * @private
  33302. */
  33303. }, {
  33304. key: '_YconvertCanvasToDOM',
  33305. value: function _YconvertCanvasToDOM(y) {
  33306. return y * this.body.view.scale + this.body.view.translation.y;
  33307. }
  33308. /**
  33309. *
  33310. * @param {object} pos = {x: number, y: number}
  33311. * @returns {{x: number, y: number}}
  33312. * @constructor
  33313. */
  33314. }, {
  33315. key: 'canvasToDOM',
  33316. value: function canvasToDOM(pos) {
  33317. return { x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y) };
  33318. }
  33319. /**
  33320. *
  33321. * @param {object} pos = {x: number, y: number}
  33322. * @returns {{x: number, y: number}}
  33323. * @constructor
  33324. */
  33325. }, {
  33326. key: 'DOMtoCanvas',
  33327. value: function DOMtoCanvas(pos) {
  33328. return { x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y) };
  33329. }
  33330. }]);
  33331. return Canvas;
  33332. }();
  33333. exports.default = Canvas;
  33334. /***/ },
  33335. /* 107 */
  33336. /***/ function(module, exports, __webpack_require__) {
  33337. 'use strict';
  33338. Object.defineProperty(exports, "__esModule", {
  33339. value: true
  33340. });
  33341. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  33342. var _NetworkUtil = __webpack_require__(103);
  33343. var _NetworkUtil2 = _interopRequireDefault(_NetworkUtil);
  33344. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33345. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33346. var util = __webpack_require__(1);
  33347. var View = function () {
  33348. function View(body, canvas) {
  33349. var _this = this;
  33350. _classCallCheck(this, View);
  33351. this.body = body;
  33352. this.canvas = canvas;
  33353. this.animationSpeed = 1 / this.renderRefreshRate;
  33354. this.animationEasingFunction = "easeInOutQuint";
  33355. this.easingTime = 0;
  33356. this.sourceScale = 0;
  33357. this.targetScale = 0;
  33358. this.sourceTranslation = 0;
  33359. this.targetTranslation = 0;
  33360. this.lockedOnNodeId = undefined;
  33361. this.lockedOnNodeOffset = undefined;
  33362. this.touchTime = 0;
  33363. this.viewFunction = undefined;
  33364. this.body.emitter.on("fit", this.fit.bind(this));
  33365. this.body.emitter.on("animationFinished", function () {
  33366. _this.body.emitter.emit("_stopRendering");
  33367. });
  33368. this.body.emitter.on("unlockNode", this.releaseNode.bind(this));
  33369. }
  33370. _createClass(View, [{
  33371. key: 'setOptions',
  33372. value: function setOptions() {
  33373. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  33374. this.options = options;
  33375. }
  33376. /**
  33377. * This function zooms out to fit all data on screen based on amount of nodes
  33378. * @param {Object} Options
  33379. * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false;
  33380. */
  33381. }, {
  33382. key: 'fit',
  33383. value: function fit() {
  33384. var options = arguments.length <= 0 || arguments[0] === undefined ? { nodes: [] } : arguments[0];
  33385. var initialZoom = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  33386. var range = void 0;
  33387. var zoomLevel = void 0;
  33388. if (options.nodes === undefined || options.nodes.length === 0) {
  33389. options.nodes = this.body.nodeIndices;
  33390. }
  33391. if (initialZoom === true) {
  33392. // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation.
  33393. var positionDefined = 0;
  33394. for (var nodeId in this.body.nodes) {
  33395. if (this.body.nodes.hasOwnProperty(nodeId)) {
  33396. var node = this.body.nodes[nodeId];
  33397. if (node.predefinedPosition === true) {
  33398. positionDefined += 1;
  33399. }
  33400. }
  33401. }
  33402. if (positionDefined > 0.5 * this.body.nodeIndices.length) {
  33403. this.fit(options, false);
  33404. return;
  33405. }
  33406. range = _NetworkUtil2.default.getRange(this.body.nodes, options.nodes);
  33407. var numberOfNodes = this.body.nodeIndices.length;
  33408. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  33409. // correct for larger canvasses.
  33410. var factor = Math.min(this.canvas.frame.canvas.clientWidth / 600, this.canvas.frame.canvas.clientHeight / 600);
  33411. zoomLevel *= factor;
  33412. } else {
  33413. this.body.emitter.emit("_resizeNodes");
  33414. range = _NetworkUtil2.default.getRange(this.body.nodes, options.nodes);
  33415. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  33416. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  33417. var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance;
  33418. var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance;
  33419. zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel;
  33420. }
  33421. if (zoomLevel > 1.0) {
  33422. zoomLevel = 1.0;
  33423. } else if (zoomLevel === 0) {
  33424. zoomLevel = 1.0;
  33425. }
  33426. var center = _NetworkUtil2.default.findCenter(range);
  33427. var animationOptions = { position: center, scale: zoomLevel, animation: options.animation };
  33428. this.moveTo(animationOptions);
  33429. }
  33430. // animation
  33431. /**
  33432. * Center a node in view.
  33433. *
  33434. * @param {Number} nodeId
  33435. * @param {Number} [options]
  33436. */
  33437. }, {
  33438. key: 'focus',
  33439. value: function focus(nodeId) {
  33440. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  33441. if (this.body.nodes[nodeId] !== undefined) {
  33442. var nodePosition = { x: this.body.nodes[nodeId].x, y: this.body.nodes[nodeId].y };
  33443. options.position = nodePosition;
  33444. options.lockedOnNode = nodeId;
  33445. this.moveTo(options);
  33446. } else {
  33447. console.log("Node: " + nodeId + " cannot be found.");
  33448. }
  33449. }
  33450. /**
  33451. *
  33452. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  33453. * | options.scale = Number // scale to move to
  33454. * | options.position = {x:Number, y:Number} // position to move to
  33455. * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to
  33456. */
  33457. }, {
  33458. key: 'moveTo',
  33459. value: function moveTo(options) {
  33460. if (options === undefined) {
  33461. options = {};
  33462. return;
  33463. }
  33464. if (options.offset === undefined) {
  33465. options.offset = { x: 0, y: 0 };
  33466. }
  33467. if (options.offset.x === undefined) {
  33468. options.offset.x = 0;
  33469. }
  33470. if (options.offset.y === undefined) {
  33471. options.offset.y = 0;
  33472. }
  33473. if (options.scale === undefined) {
  33474. options.scale = this.body.view.scale;
  33475. }
  33476. if (options.position === undefined) {
  33477. options.position = this.getViewPosition();
  33478. }
  33479. if (options.animation === undefined) {
  33480. options.animation = { duration: 0 };
  33481. }
  33482. if (options.animation === false) {
  33483. options.animation = { duration: 0 };
  33484. }
  33485. if (options.animation === true) {
  33486. options.animation = {};
  33487. }
  33488. if (options.animation.duration === undefined) {
  33489. options.animation.duration = 1000;
  33490. } // default duration
  33491. if (options.animation.easingFunction === undefined) {
  33492. options.animation.easingFunction = "easeInOutQuad";
  33493. } // default easing function
  33494. this.animateView(options);
  33495. }
  33496. /**
  33497. *
  33498. * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels
  33499. * | options.time = Number // animation time in milliseconds
  33500. * | options.scale = Number // scale to animate to
  33501. * | options.position = {x:Number, y:Number} // position to animate to
  33502. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  33503. * // easeInCubic, easeOutCubic, easeInOutCubic,
  33504. * // easeInQuart, easeOutQuart, easeInOutQuart,
  33505. * // easeInQuint, easeOutQuint, easeInOutQuint
  33506. */
  33507. }, {
  33508. key: 'animateView',
  33509. value: function animateView(options) {
  33510. if (options === undefined) {
  33511. return;
  33512. }
  33513. this.animationEasingFunction = options.animation.easingFunction;
  33514. // release if something focussed on the node
  33515. this.releaseNode();
  33516. if (options.locked === true) {
  33517. this.lockedOnNodeId = options.lockedOnNode;
  33518. this.lockedOnNodeOffset = options.offset;
  33519. }
  33520. // forcefully complete the old animation if it was still running
  33521. if (this.easingTime != 0) {
  33522. this._transitionRedraw(true); // by setting easingtime to 1, we finish the animation.
  33523. }
  33524. this.sourceScale = this.body.view.scale;
  33525. this.sourceTranslation = this.body.view.translation;
  33526. this.targetScale = options.scale;
  33527. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  33528. // but at least then we'll have the target transition
  33529. this.body.view.scale = this.targetScale;
  33530. var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight });
  33531. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  33532. x: viewCenter.x - options.position.x,
  33533. y: viewCenter.y - options.position.y
  33534. };
  33535. this.targetTranslation = {
  33536. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  33537. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  33538. };
  33539. // if the time is set to 0, don't do an animation
  33540. if (options.animation.duration === 0) {
  33541. if (this.lockedOnNodeId != undefined) {
  33542. this.viewFunction = this._lockedRedraw.bind(this);
  33543. this.body.emitter.on("initRedraw", this.viewFunction);
  33544. } else {
  33545. this.body.view.scale = this.targetScale;
  33546. this.body.view.translation = this.targetTranslation;
  33547. this.body.emitter.emit("_requestRedraw");
  33548. }
  33549. } else {
  33550. this.animationSpeed = 1 / (60 * options.animation.duration * 0.001) || 1 / 60; // 60 for 60 seconds, 0.001 for milli's
  33551. this.animationEasingFunction = options.animation.easingFunction;
  33552. this.viewFunction = this._transitionRedraw.bind(this);
  33553. this.body.emitter.on("initRedraw", this.viewFunction);
  33554. this.body.emitter.emit("_startRendering");
  33555. }
  33556. }
  33557. /**
  33558. * used to animate smoothly by hijacking the redraw function.
  33559. * @private
  33560. */
  33561. }, {
  33562. key: '_lockedRedraw',
  33563. value: function _lockedRedraw() {
  33564. var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y };
  33565. var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight });
  33566. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  33567. x: viewCenter.x - nodePosition.x,
  33568. y: viewCenter.y - nodePosition.y
  33569. };
  33570. var sourceTranslation = this.body.view.translation;
  33571. var targetTranslation = {
  33572. x: sourceTranslation.x + distanceFromCenter.x * this.body.view.scale + this.lockedOnNodeOffset.x,
  33573. y: sourceTranslation.y + distanceFromCenter.y * this.body.view.scale + this.lockedOnNodeOffset.y
  33574. };
  33575. this.body.view.translation = targetTranslation;
  33576. }
  33577. }, {
  33578. key: 'releaseNode',
  33579. value: function releaseNode() {
  33580. if (this.lockedOnNodeId !== undefined && this.viewFunction !== undefined) {
  33581. this.body.emitter.off("initRedraw", this.viewFunction);
  33582. this.lockedOnNodeId = undefined;
  33583. this.lockedOnNodeOffset = undefined;
  33584. }
  33585. }
  33586. /**
  33587. *
  33588. * @param easingTime
  33589. * @private
  33590. */
  33591. }, {
  33592. key: '_transitionRedraw',
  33593. value: function _transitionRedraw() {
  33594. var finished = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];
  33595. this.easingTime += this.animationSpeed;
  33596. this.easingTime = finished === true ? 1.0 : this.easingTime;
  33597. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  33598. this.body.view.scale = this.sourceScale + (this.targetScale - this.sourceScale) * progress;
  33599. this.body.view.translation = {
  33600. x: this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  33601. y: this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  33602. };
  33603. // cleanup
  33604. if (this.easingTime >= 1.0) {
  33605. this.body.emitter.off("initRedraw", this.viewFunction);
  33606. this.easingTime = 0;
  33607. if (this.lockedOnNodeId != undefined) {
  33608. this.viewFunction = this._lockedRedraw.bind(this);
  33609. this.body.emitter.on("initRedraw", this.viewFunction);
  33610. }
  33611. this.body.emitter.emit("animationFinished");
  33612. }
  33613. }
  33614. }, {
  33615. key: 'getScale',
  33616. value: function getScale() {
  33617. return this.body.view.scale;
  33618. }
  33619. }, {
  33620. key: 'getViewPosition',
  33621. value: function getViewPosition() {
  33622. return this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight });
  33623. }
  33624. }]);
  33625. return View;
  33626. }();
  33627. exports.default = View;
  33628. /***/ },
  33629. /* 108 */
  33630. /***/ function(module, exports, __webpack_require__) {
  33631. 'use strict';
  33632. Object.defineProperty(exports, "__esModule", {
  33633. value: true
  33634. });
  33635. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  33636. var _NavigationHandler = __webpack_require__(109);
  33637. var _NavigationHandler2 = _interopRequireDefault(_NavigationHandler);
  33638. var _Popup = __webpack_require__(110);
  33639. var _Popup2 = _interopRequireDefault(_Popup);
  33640. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33641. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33642. var util = __webpack_require__(1);
  33643. var InteractionHandler = function () {
  33644. function InteractionHandler(body, canvas, selectionHandler) {
  33645. _classCallCheck(this, InteractionHandler);
  33646. this.body = body;
  33647. this.canvas = canvas;
  33648. this.selectionHandler = selectionHandler;
  33649. this.navigationHandler = new _NavigationHandler2.default(body, canvas);
  33650. // bind the events from hammer to functions in this object
  33651. this.body.eventListeners.onTap = this.onTap.bind(this);
  33652. this.body.eventListeners.onTouch = this.onTouch.bind(this);
  33653. this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this);
  33654. this.body.eventListeners.onHold = this.onHold.bind(this);
  33655. this.body.eventListeners.onDragStart = this.onDragStart.bind(this);
  33656. this.body.eventListeners.onDrag = this.onDrag.bind(this);
  33657. this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this);
  33658. this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this);
  33659. this.body.eventListeners.onPinch = this.onPinch.bind(this);
  33660. this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this);
  33661. this.body.eventListeners.onRelease = this.onRelease.bind(this);
  33662. this.body.eventListeners.onContext = this.onContext.bind(this);
  33663. this.touchTime = 0;
  33664. this.drag = {};
  33665. this.pinch = {};
  33666. this.popup = undefined;
  33667. this.popupObj = undefined;
  33668. this.popupTimer = undefined;
  33669. this.body.functions.getPointer = this.getPointer.bind(this);
  33670. this.options = {};
  33671. this.defaultOptions = {
  33672. dragNodes: true,
  33673. dragView: true,
  33674. hover: false,
  33675. keyboard: {
  33676. enabled: false,
  33677. speed: { x: 10, y: 10, zoom: 0.02 },
  33678. bindToWindow: true
  33679. },
  33680. navigationButtons: false,
  33681. tooltipDelay: 300,
  33682. zoomView: true
  33683. };
  33684. util.extend(this.options, this.defaultOptions);
  33685. this.bindEventListeners();
  33686. }
  33687. _createClass(InteractionHandler, [{
  33688. key: 'bindEventListeners',
  33689. value: function bindEventListeners() {
  33690. var _this = this;
  33691. this.body.emitter.on('destroy', function () {
  33692. clearTimeout(_this.popupTimer);
  33693. delete _this.body.functions.getPointer;
  33694. });
  33695. }
  33696. }, {
  33697. key: 'setOptions',
  33698. value: function setOptions(options) {
  33699. if (options !== undefined) {
  33700. // extend all but the values in fields
  33701. var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges'];
  33702. util.selectiveNotDeepExtend(fields, this.options, options);
  33703. // merge the keyboard options in.
  33704. util.mergeOptions(this.options, options, 'keyboard');
  33705. if (options.tooltip) {
  33706. util.extend(this.options.tooltip, options.tooltip);
  33707. if (options.tooltip.color) {
  33708. this.options.tooltip.color = util.parseColor(options.tooltip.color);
  33709. }
  33710. }
  33711. }
  33712. this.navigationHandler.setOptions(this.options);
  33713. }
  33714. /**
  33715. * Get the pointer location from a touch location
  33716. * @param {{x: Number, y: Number}} touch
  33717. * @return {{x: Number, y: Number}} pointer
  33718. * @private
  33719. */
  33720. }, {
  33721. key: 'getPointer',
  33722. value: function getPointer(touch) {
  33723. return {
  33724. x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas),
  33725. y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas)
  33726. };
  33727. }
  33728. /**
  33729. * On start of a touch gesture, store the pointer
  33730. * @param event
  33731. * @private
  33732. */
  33733. }, {
  33734. key: 'onTouch',
  33735. value: function onTouch(event) {
  33736. if (new Date().valueOf() - this.touchTime > 50) {
  33737. this.drag.pointer = this.getPointer(event.center);
  33738. this.drag.pinched = false;
  33739. this.pinch.scale = this.body.view.scale;
  33740. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  33741. this.touchTime = new Date().valueOf();
  33742. }
  33743. }
  33744. /**
  33745. * handle tap/click event: select/unselect a node
  33746. * @private
  33747. */
  33748. }, {
  33749. key: 'onTap',
  33750. value: function onTap(event) {
  33751. var pointer = this.getPointer(event.center);
  33752. var multiselect = this.selectionHandler.options.multiselect && (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey);
  33753. this.checkSelectionChanges(pointer, event, multiselect);
  33754. this.selectionHandler._generateClickEvent('click', event, pointer);
  33755. }
  33756. /**
  33757. * handle doubletap event
  33758. * @private
  33759. */
  33760. }, {
  33761. key: 'onDoubleTap',
  33762. value: function onDoubleTap(event) {
  33763. var pointer = this.getPointer(event.center);
  33764. this.selectionHandler._generateClickEvent('doubleClick', event, pointer);
  33765. }
  33766. /**
  33767. * handle long tap event: multi select nodes
  33768. * @private
  33769. */
  33770. }, {
  33771. key: 'onHold',
  33772. value: function onHold(event) {
  33773. var pointer = this.getPointer(event.center);
  33774. var multiselect = this.selectionHandler.options.multiselect;
  33775. this.checkSelectionChanges(pointer, event, multiselect);
  33776. this.selectionHandler._generateClickEvent('click', event, pointer);
  33777. this.selectionHandler._generateClickEvent('hold', event, pointer);
  33778. }
  33779. /**
  33780. * handle the release of the screen
  33781. *
  33782. * @private
  33783. */
  33784. }, {
  33785. key: 'onRelease',
  33786. value: function onRelease(event) {
  33787. if (new Date().valueOf() - this.touchTime > 10) {
  33788. var pointer = this.getPointer(event.center);
  33789. this.selectionHandler._generateClickEvent('release', event, pointer);
  33790. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  33791. this.touchTime = new Date().valueOf();
  33792. }
  33793. }
  33794. }, {
  33795. key: 'onContext',
  33796. value: function onContext(event) {
  33797. var pointer = this.getPointer({ x: event.clientX, y: event.clientY });
  33798. this.selectionHandler._generateClickEvent('oncontext', event, pointer);
  33799. }
  33800. /**
  33801. *
  33802. * @param pointer
  33803. * @param add
  33804. */
  33805. }, {
  33806. key: 'checkSelectionChanges',
  33807. value: function checkSelectionChanges(pointer, event) {
  33808. var add = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  33809. var previouslySelectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
  33810. var previouslySelectedNodeCount = this.selectionHandler._getSelectedNodeCount();
  33811. var previousSelection = this.selectionHandler.getSelection();
  33812. var selected = void 0;
  33813. if (add === true) {
  33814. selected = this.selectionHandler.selectAdditionalOnPoint(pointer);
  33815. } else {
  33816. selected = this.selectionHandler.selectOnPoint(pointer);
  33817. }
  33818. var selectedEdgesCount = this.selectionHandler._getSelectedEdgeCount();
  33819. var selectedNodesCount = this.selectionHandler._getSelectedNodeCount();
  33820. var currentSelection = this.selectionHandler.getSelection();
  33821. var _determineIfDifferent2 = this._determineIfDifferent(previousSelection, currentSelection);
  33822. var nodesChanged = _determineIfDifferent2.nodesChanged;
  33823. var edgesChanged = _determineIfDifferent2.edgesChanged;
  33824. var nodeSelected = false;
  33825. if (selectedNodesCount - previouslySelectedNodeCount > 0) {
  33826. // node was selected
  33827. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  33828. selected = true;
  33829. nodeSelected = true;
  33830. } else if (nodesChanged === true && selectedNodesCount > 0) {
  33831. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  33832. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  33833. nodeSelected = true;
  33834. selected = true;
  33835. } else if (selectedNodesCount - previouslySelectedNodeCount < 0) {
  33836. // node was deselected
  33837. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  33838. selected = true;
  33839. }
  33840. // handle the selected edges
  33841. if (selectedEdgesCount - previouslySelectedEdgeCount > 0 && nodeSelected === false) {
  33842. // edge was selected
  33843. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  33844. selected = true;
  33845. } else if (selectedEdgesCount > 0 && edgesChanged === true) {
  33846. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  33847. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  33848. selected = true;
  33849. } else if (selectedEdgesCount - previouslySelectedEdgeCount < 0) {
  33850. // edge was deselected
  33851. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  33852. selected = true;
  33853. }
  33854. // fire the select event if anything has been selected or deselected
  33855. if (selected === true) {
  33856. // select or unselect
  33857. this.selectionHandler._generateClickEvent('select', event, pointer);
  33858. }
  33859. }
  33860. /**
  33861. * This function checks if the nodes and edges previously selected have changed.
  33862. * @param previousSelection
  33863. * @param currentSelection
  33864. * @returns {{nodesChanged: boolean, edgesChanged: boolean}}
  33865. * @private
  33866. */
  33867. }, {
  33868. key: '_determineIfDifferent',
  33869. value: function _determineIfDifferent(previousSelection, currentSelection) {
  33870. var nodesChanged = false;
  33871. var edgesChanged = false;
  33872. for (var i = 0; i < previousSelection.nodes.length; i++) {
  33873. if (currentSelection.nodes.indexOf(previousSelection.nodes[i]) === -1) {
  33874. nodesChanged = true;
  33875. }
  33876. }
  33877. for (var _i = 0; _i < currentSelection.nodes.length; _i++) {
  33878. if (previousSelection.nodes.indexOf(previousSelection.nodes[_i]) === -1) {
  33879. nodesChanged = true;
  33880. }
  33881. }
  33882. for (var _i2 = 0; _i2 < previousSelection.edges.length; _i2++) {
  33883. if (currentSelection.edges.indexOf(previousSelection.edges[_i2]) === -1) {
  33884. edgesChanged = true;
  33885. }
  33886. }
  33887. for (var _i3 = 0; _i3 < currentSelection.edges.length; _i3++) {
  33888. if (previousSelection.edges.indexOf(previousSelection.edges[_i3]) === -1) {
  33889. edgesChanged = true;
  33890. }
  33891. }
  33892. return { nodesChanged: nodesChanged, edgesChanged: edgesChanged };
  33893. }
  33894. /**
  33895. * This function is called by onDragStart.
  33896. * It is separated out because we can then overload it for the datamanipulation system.
  33897. *
  33898. * @private
  33899. */
  33900. }, {
  33901. key: 'onDragStart',
  33902. value: function onDragStart(event) {
  33903. //in case the touch event was triggered on an external div, do the initial touch now.
  33904. if (this.drag.pointer === undefined) {
  33905. this.onTouch(event);
  33906. }
  33907. // note: drag.pointer is set in onTouch to get the initial touch location
  33908. var node = this.selectionHandler.getNodeAt(this.drag.pointer);
  33909. this.drag.dragging = true;
  33910. this.drag.selection = [];
  33911. this.drag.translation = util.extend({}, this.body.view.translation); // copy the object
  33912. this.drag.nodeId = undefined;
  33913. if (node !== undefined && this.options.dragNodes === true) {
  33914. this.drag.nodeId = node.id;
  33915. // select the clicked node if not yet selected
  33916. if (node.isSelected() === false) {
  33917. this.selectionHandler.unselectAll();
  33918. this.selectionHandler.selectObject(node);
  33919. }
  33920. // after select to contain the node
  33921. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer);
  33922. var selection = this.selectionHandler.selectionObj.nodes;
  33923. // create an array with the selected nodes and their original location and status
  33924. for (var nodeId in selection) {
  33925. if (selection.hasOwnProperty(nodeId)) {
  33926. var object = selection[nodeId];
  33927. var s = {
  33928. id: object.id,
  33929. node: object,
  33930. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  33931. x: object.x,
  33932. y: object.y,
  33933. xFixed: object.options.fixed.x,
  33934. yFixed: object.options.fixed.y
  33935. };
  33936. object.options.fixed.x = true;
  33937. object.options.fixed.y = true;
  33938. this.drag.selection.push(s);
  33939. }
  33940. }
  33941. } else {
  33942. // fallback if no node is selected and thus the view is dragged.
  33943. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer, undefined, true);
  33944. }
  33945. }
  33946. /**
  33947. * handle drag event
  33948. * @private
  33949. */
  33950. }, {
  33951. key: 'onDrag',
  33952. value: function onDrag(event) {
  33953. var _this2 = this;
  33954. if (this.drag.pinched === true) {
  33955. return;
  33956. }
  33957. // remove the focus on node if it is focussed on by the focusOnNode
  33958. this.body.emitter.emit('unlockNode');
  33959. var pointer = this.getPointer(event.center);
  33960. var selection = this.drag.selection;
  33961. if (selection && selection.length && this.options.dragNodes === true) {
  33962. (function () {
  33963. _this2.selectionHandler._generateClickEvent('dragging', event, pointer);
  33964. // calculate delta's and new location
  33965. var deltaX = pointer.x - _this2.drag.pointer.x;
  33966. var deltaY = pointer.y - _this2.drag.pointer.y;
  33967. // update position of all selected nodes
  33968. selection.forEach(function (selection) {
  33969. var node = selection.node;
  33970. // only move the node if it was not fixed initially
  33971. if (selection.xFixed === false) {
  33972. node.x = _this2.canvas._XconvertDOMtoCanvas(_this2.canvas._XconvertCanvasToDOM(selection.x) + deltaX);
  33973. }
  33974. // only move the node if it was not fixed initially
  33975. if (selection.yFixed === false) {
  33976. node.y = _this2.canvas._YconvertDOMtoCanvas(_this2.canvas._YconvertCanvasToDOM(selection.y) + deltaY);
  33977. }
  33978. });
  33979. // start the simulation of the physics
  33980. _this2.body.emitter.emit('startSimulation');
  33981. })();
  33982. } else {
  33983. // move the network
  33984. if (this.options.dragView === true) {
  33985. this.selectionHandler._generateClickEvent('dragging', event, pointer, undefined, true);
  33986. // if the drag was not started properly because the click started outside the network div, start it now.
  33987. if (this.drag.pointer === undefined) {
  33988. this.onDragStart(event);
  33989. return;
  33990. }
  33991. var diffX = pointer.x - this.drag.pointer.x;
  33992. var diffY = pointer.y - this.drag.pointer.y;
  33993. this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY };
  33994. this.body.emitter.emit('_redraw');
  33995. }
  33996. }
  33997. }
  33998. /**
  33999. * handle drag start event
  34000. * @private
  34001. */
  34002. }, {
  34003. key: 'onDragEnd',
  34004. value: function onDragEnd(event) {
  34005. this.drag.dragging = false;
  34006. var selection = this.drag.selection;
  34007. if (selection && selection.length) {
  34008. selection.forEach(function (s) {
  34009. // restore original xFixed and yFixed
  34010. s.node.options.fixed.x = s.xFixed;
  34011. s.node.options.fixed.y = s.yFixed;
  34012. });
  34013. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center));
  34014. this.body.emitter.emit('startSimulation');
  34015. } else {
  34016. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center), undefined, true);
  34017. this.body.emitter.emit('_requestRedraw');
  34018. }
  34019. }
  34020. /**
  34021. * Handle pinch event
  34022. * @param event
  34023. * @private
  34024. */
  34025. }, {
  34026. key: 'onPinch',
  34027. value: function onPinch(event) {
  34028. var pointer = this.getPointer(event.center);
  34029. this.drag.pinched = true;
  34030. if (this.pinch['scale'] === undefined) {
  34031. this.pinch.scale = 1;
  34032. }
  34033. // TODO: enabled moving while pinching?
  34034. var scale = this.pinch.scale * event.scale;
  34035. this.zoom(scale, pointer);
  34036. }
  34037. /**
  34038. * Zoom the network in or out
  34039. * @param {Number} scale a number around 1, and between 0.01 and 10
  34040. * @param {{x: Number, y: Number}} pointer Position on screen
  34041. * @return {Number} appliedScale scale is limited within the boundaries
  34042. * @private
  34043. */
  34044. }, {
  34045. key: 'zoom',
  34046. value: function zoom(scale, pointer) {
  34047. if (this.options.zoomView === true) {
  34048. var scaleOld = this.body.view.scale;
  34049. if (scale < 0.00001) {
  34050. scale = 0.00001;
  34051. }
  34052. if (scale > 10) {
  34053. scale = 10;
  34054. }
  34055. var preScaleDragPointer = undefined;
  34056. if (this.drag !== undefined) {
  34057. if (this.drag.dragging === true) {
  34058. preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer);
  34059. }
  34060. }
  34061. // + this.canvas.frame.canvas.clientHeight / 2
  34062. var translation = this.body.view.translation;
  34063. var scaleFrac = scale / scaleOld;
  34064. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  34065. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  34066. this.body.view.scale = scale;
  34067. this.body.view.translation = { x: tx, y: ty };
  34068. if (preScaleDragPointer != undefined) {
  34069. var postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer);
  34070. this.drag.pointer.x = postScaleDragPointer.x;
  34071. this.drag.pointer.y = postScaleDragPointer.y;
  34072. }
  34073. this.body.emitter.emit('_requestRedraw');
  34074. if (scaleOld < scale) {
  34075. this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale });
  34076. } else {
  34077. this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale });
  34078. }
  34079. }
  34080. }
  34081. /**
  34082. * Event handler for mouse wheel event, used to zoom the timeline
  34083. * See http://adomas.org/javascript-mouse-wheel/
  34084. * https://github.com/EightMedia/hammer.js/issues/256
  34085. * @param {MouseEvent} event
  34086. * @private
  34087. */
  34088. }, {
  34089. key: 'onMouseWheel',
  34090. value: function onMouseWheel(event) {
  34091. if (this.options.zoomView === true) {
  34092. // retrieve delta
  34093. var delta = 0;
  34094. if (event.wheelDelta) {
  34095. /* IE/Opera. */
  34096. delta = event.wheelDelta / 120;
  34097. } else if (event.detail) {
  34098. /* Mozilla case. */
  34099. // In Mozilla, sign of delta is different than in IE.
  34100. // Also, delta is multiple of 3.
  34101. delta = -event.detail / 3;
  34102. }
  34103. // If delta is nonzero, handle it.
  34104. // Basically, delta is now positive if wheel was scrolled up,
  34105. // and negative, if wheel was scrolled down.
  34106. if (delta !== 0) {
  34107. // calculate the new scale
  34108. var scale = this.body.view.scale;
  34109. var zoom = delta / 10;
  34110. if (delta < 0) {
  34111. zoom = zoom / (1 - zoom);
  34112. }
  34113. scale *= 1 + zoom;
  34114. // calculate the pointer location
  34115. var pointer = this.getPointer({ x: event.clientX, y: event.clientY });
  34116. // apply the new scale
  34117. this.zoom(scale, pointer);
  34118. }
  34119. // Prevent default actions caused by mouse wheel.
  34120. event.preventDefault();
  34121. }
  34122. }
  34123. /**
  34124. * Mouse move handler for checking whether the title moves over a node with a title.
  34125. * @param {Event} event
  34126. * @private
  34127. */
  34128. }, {
  34129. key: 'onMouseMove',
  34130. value: function onMouseMove(event) {
  34131. var _this3 = this;
  34132. var pointer = this.getPointer({ x: event.clientX, y: event.clientY });
  34133. var popupVisible = false;
  34134. // check if the previously selected node is still selected
  34135. if (this.popup !== undefined) {
  34136. if (this.popup.hidden === false) {
  34137. this._checkHidePopup(pointer);
  34138. }
  34139. // if the popup was not hidden above
  34140. if (this.popup.hidden === false) {
  34141. popupVisible = true;
  34142. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  34143. this.popup.show();
  34144. }
  34145. }
  34146. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
  34147. if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) {
  34148. this.canvas.frame.focus();
  34149. }
  34150. // start a timeout that will check if the mouse is positioned above an element
  34151. if (popupVisible === false) {
  34152. if (this.popupTimer !== undefined) {
  34153. clearInterval(this.popupTimer); // stop any running calculationTimer
  34154. this.popupTimer = undefined;
  34155. }
  34156. if (!this.drag.dragging) {
  34157. this.popupTimer = setTimeout(function () {
  34158. return _this3._checkShowPopup(pointer);
  34159. }, this.options.tooltipDelay);
  34160. }
  34161. }
  34162. /**
  34163. * Adding hover highlights
  34164. */
  34165. if (this.options.hover === true) {
  34166. // adding hover highlights
  34167. var obj = this.selectionHandler.getNodeAt(pointer);
  34168. if (obj === undefined) {
  34169. obj = this.selectionHandler.getEdgeAt(pointer);
  34170. }
  34171. this.selectionHandler.hoverObject(obj);
  34172. }
  34173. }
  34174. /**
  34175. * Check if there is an element on the given position in the network
  34176. * (a node or edge). If so, and if this element has a title,
  34177. * show a popup window with its title.
  34178. *
  34179. * @param {{x:Number, y:Number}} pointer
  34180. * @private
  34181. */
  34182. }, {
  34183. key: '_checkShowPopup',
  34184. value: function _checkShowPopup(pointer) {
  34185. var x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  34186. var y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  34187. var pointerObj = {
  34188. left: x,
  34189. top: y,
  34190. right: x,
  34191. bottom: y
  34192. };
  34193. var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id;
  34194. var nodeUnderCursor = false;
  34195. var popupType = 'node';
  34196. // check if a node is under the cursor.
  34197. if (this.popupObj === undefined) {
  34198. // search the nodes for overlap, select the top one in case of multiple nodes
  34199. var nodeIndices = this.body.nodeIndices;
  34200. var nodes = this.body.nodes;
  34201. var node = void 0;
  34202. var overlappingNodes = [];
  34203. for (var i = 0; i < nodeIndices.length; i++) {
  34204. node = nodes[nodeIndices[i]];
  34205. if (node.isOverlappingWith(pointerObj) === true) {
  34206. if (node.getTitle() !== undefined) {
  34207. overlappingNodes.push(nodeIndices[i]);
  34208. }
  34209. }
  34210. }
  34211. if (overlappingNodes.length > 0) {
  34212. // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
  34213. this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]];
  34214. // if you hover over a node, the title of the edge is not supposed to be shown.
  34215. nodeUnderCursor = true;
  34216. }
  34217. }
  34218. if (this.popupObj === undefined && nodeUnderCursor === false) {
  34219. // search the edges for overlap
  34220. var edgeIndices = this.body.edgeIndices;
  34221. var edges = this.body.edges;
  34222. var edge = void 0;
  34223. var overlappingEdges = [];
  34224. for (var _i4 = 0; _i4 < edgeIndices.length; _i4++) {
  34225. edge = edges[edgeIndices[_i4]];
  34226. if (edge.isOverlappingWith(pointerObj) === true) {
  34227. if (edge.connected === true && edge.getTitle() !== undefined) {
  34228. overlappingEdges.push(edgeIndices[_i4]);
  34229. }
  34230. }
  34231. }
  34232. if (overlappingEdges.length > 0) {
  34233. this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]];
  34234. popupType = 'edge';
  34235. }
  34236. }
  34237. if (this.popupObj !== undefined) {
  34238. // show popup message window
  34239. if (this.popupObj.id !== previousPopupObjId) {
  34240. if (this.popup === undefined) {
  34241. this.popup = new _Popup2.default(this.canvas.frame);
  34242. }
  34243. this.popup.popupTargetType = popupType;
  34244. this.popup.popupTargetId = this.popupObj.id;
  34245. // adjust a small offset such that the mouse cursor is located in the
  34246. // bottom left location of the popup, and you can easily move over the
  34247. // popup area
  34248. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  34249. this.popup.setText(this.popupObj.getTitle());
  34250. this.popup.show();
  34251. this.body.emitter.emit('showPopup', this.popupObj.id);
  34252. }
  34253. } else {
  34254. if (this.popup !== undefined) {
  34255. this.popup.hide();
  34256. this.body.emitter.emit('hidePopup');
  34257. }
  34258. }
  34259. }
  34260. /**
  34261. * Check if the popup must be hidden, which is the case when the mouse is no
  34262. * longer hovering on the object
  34263. * @param {{x:Number, y:Number}} pointer
  34264. * @private
  34265. */
  34266. }, {
  34267. key: '_checkHidePopup',
  34268. value: function _checkHidePopup(pointer) {
  34269. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  34270. var stillOnObj = false;
  34271. if (this.popup.popupTargetType === 'node') {
  34272. if (this.body.nodes[this.popup.popupTargetId] !== undefined) {
  34273. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  34274. // if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it.
  34275. // we initially only check stillOnObj because this is much faster.
  34276. if (stillOnObj === true) {
  34277. var overNode = this.selectionHandler.getNodeAt(pointer);
  34278. stillOnObj = overNode.id === this.popup.popupTargetId;
  34279. }
  34280. }
  34281. } else {
  34282. if (this.selectionHandler.getNodeAt(pointer) === undefined) {
  34283. if (this.body.edges[this.popup.popupTargetId] !== undefined) {
  34284. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  34285. }
  34286. }
  34287. }
  34288. if (stillOnObj === false) {
  34289. this.popupObj = undefined;
  34290. this.popup.hide();
  34291. this.body.emitter.emit('hidePopup');
  34292. }
  34293. }
  34294. }]);
  34295. return InteractionHandler;
  34296. }();
  34297. exports.default = InteractionHandler;
  34298. /***/ },
  34299. /* 109 */
  34300. /***/ function(module, exports, __webpack_require__) {
  34301. 'use strict';
  34302. Object.defineProperty(exports, "__esModule", {
  34303. value: true
  34304. });
  34305. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  34306. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34307. var util = __webpack_require__(1);
  34308. var Hammer = __webpack_require__(20);
  34309. var hammerUtil = __webpack_require__(28);
  34310. var keycharm = __webpack_require__(23);
  34311. var NavigationHandler = function () {
  34312. function NavigationHandler(body, canvas) {
  34313. var _this = this;
  34314. _classCallCheck(this, NavigationHandler);
  34315. this.body = body;
  34316. this.canvas = canvas;
  34317. this.iconsCreated = false;
  34318. this.navigationHammers = [];
  34319. this.boundFunctions = {};
  34320. this.touchTime = 0;
  34321. this.activated = false;
  34322. this.body.emitter.on("activate", function () {
  34323. _this.activated = true;_this.configureKeyboardBindings();
  34324. });
  34325. this.body.emitter.on("deactivate", function () {
  34326. _this.activated = false;_this.configureKeyboardBindings();
  34327. });
  34328. this.body.emitter.on("destroy", function () {
  34329. if (_this.keycharm !== undefined) {
  34330. _this.keycharm.destroy();
  34331. }
  34332. });
  34333. this.options = {};
  34334. }
  34335. _createClass(NavigationHandler, [{
  34336. key: 'setOptions',
  34337. value: function setOptions(options) {
  34338. if (options !== undefined) {
  34339. this.options = options;
  34340. this.create();
  34341. }
  34342. }
  34343. }, {
  34344. key: 'create',
  34345. value: function create() {
  34346. if (this.options.navigationButtons === true) {
  34347. if (this.iconsCreated === false) {
  34348. this.loadNavigationElements();
  34349. }
  34350. } else if (this.iconsCreated === true) {
  34351. this.cleanNavigation();
  34352. }
  34353. this.configureKeyboardBindings();
  34354. }
  34355. }, {
  34356. key: 'cleanNavigation',
  34357. value: function cleanNavigation() {
  34358. // clean hammer bindings
  34359. if (this.navigationHammers.length != 0) {
  34360. for (var i = 0; i < this.navigationHammers.length; i++) {
  34361. this.navigationHammers[i].destroy();
  34362. }
  34363. this.navigationHammers = [];
  34364. }
  34365. // clean up previous navigation items
  34366. if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) {
  34367. this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']);
  34368. }
  34369. this.iconsCreated = false;
  34370. }
  34371. /**
  34372. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  34373. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  34374. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  34375. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  34376. *
  34377. * @private
  34378. */
  34379. }, {
  34380. key: 'loadNavigationElements',
  34381. value: function loadNavigationElements() {
  34382. var _this2 = this;
  34383. this.cleanNavigation();
  34384. this.navigationDOM = {};
  34385. var navigationDivs = ['up', 'down', 'left', 'right', 'zoomIn', 'zoomOut', 'zoomExtends'];
  34386. var navigationDivActions = ['_moveUp', '_moveDown', '_moveLeft', '_moveRight', '_zoomIn', '_zoomOut', '_fit'];
  34387. this.navigationDOM['wrapper'] = document.createElement('div');
  34388. this.navigationDOM['wrapper'].className = 'vis-navigation';
  34389. this.canvas.frame.appendChild(this.navigationDOM['wrapper']);
  34390. for (var i = 0; i < navigationDivs.length; i++) {
  34391. this.navigationDOM[navigationDivs[i]] = document.createElement('div');
  34392. this.navigationDOM[navigationDivs[i]].className = 'vis-button vis-' + navigationDivs[i];
  34393. this.navigationDOM['wrapper'].appendChild(this.navigationDOM[navigationDivs[i]]);
  34394. var hammer = new Hammer(this.navigationDOM[navigationDivs[i]]);
  34395. if (navigationDivActions[i] === "_fit") {
  34396. hammerUtil.onTouch(hammer, this._fit.bind(this));
  34397. } else {
  34398. hammerUtil.onTouch(hammer, this.bindToRedraw.bind(this, navigationDivActions[i]));
  34399. }
  34400. this.navigationHammers.push(hammer);
  34401. }
  34402. // use a hammer for the release so we do not require the one used in the rest of the network
  34403. // the one the rest uses can be overloaded by the manipulation system.
  34404. var hammerFrame = new Hammer(this.canvas.frame);
  34405. hammerUtil.onRelease(hammerFrame, function () {
  34406. _this2._stopMovement();
  34407. });
  34408. this.navigationHammers.push(hammerFrame);
  34409. this.iconsCreated = true;
  34410. }
  34411. }, {
  34412. key: 'bindToRedraw',
  34413. value: function bindToRedraw(action) {
  34414. if (this.boundFunctions[action] === undefined) {
  34415. this.boundFunctions[action] = this[action].bind(this);
  34416. this.body.emitter.on("initRedraw", this.boundFunctions[action]);
  34417. this.body.emitter.emit("_startRendering");
  34418. }
  34419. }
  34420. }, {
  34421. key: 'unbindFromRedraw',
  34422. value: function unbindFromRedraw(action) {
  34423. if (this.boundFunctions[action] !== undefined) {
  34424. this.body.emitter.off("initRedraw", this.boundFunctions[action]);
  34425. this.body.emitter.emit("_stopRendering");
  34426. delete this.boundFunctions[action];
  34427. }
  34428. }
  34429. /**
  34430. * this stops all movement induced by the navigation buttons
  34431. *
  34432. * @private
  34433. */
  34434. }, {
  34435. key: '_fit',
  34436. value: function _fit() {
  34437. if (new Date().valueOf() - this.touchTime > 700) {
  34438. // TODO: fix ugly hack to avoid hammer's double fireing of event (because we use release?)
  34439. this.body.emitter.emit("fit", { duration: 700 });
  34440. this.touchTime = new Date().valueOf();
  34441. }
  34442. }
  34443. /**
  34444. * this stops all movement induced by the navigation buttons
  34445. *
  34446. * @private
  34447. */
  34448. }, {
  34449. key: '_stopMovement',
  34450. value: function _stopMovement() {
  34451. for (var boundAction in this.boundFunctions) {
  34452. if (this.boundFunctions.hasOwnProperty(boundAction)) {
  34453. this.body.emitter.off("initRedraw", this.boundFunctions[boundAction]);
  34454. this.body.emitter.emit("_stopRendering");
  34455. }
  34456. }
  34457. this.boundFunctions = {};
  34458. }
  34459. }, {
  34460. key: '_moveUp',
  34461. value: function _moveUp() {
  34462. this.body.view.translation.y += this.options.keyboard.speed.y;
  34463. }
  34464. }, {
  34465. key: '_moveDown',
  34466. value: function _moveDown() {
  34467. this.body.view.translation.y -= this.options.keyboard.speed.y;
  34468. }
  34469. }, {
  34470. key: '_moveLeft',
  34471. value: function _moveLeft() {
  34472. this.body.view.translation.x += this.options.keyboard.speed.x;
  34473. }
  34474. }, {
  34475. key: '_moveRight',
  34476. value: function _moveRight() {
  34477. this.body.view.translation.x -= this.options.keyboard.speed.x;
  34478. }
  34479. }, {
  34480. key: '_zoomIn',
  34481. value: function _zoomIn() {
  34482. this.body.view.scale *= 1 + this.options.keyboard.speed.zoom;
  34483. this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale });
  34484. }
  34485. }, {
  34486. key: '_zoomOut',
  34487. value: function _zoomOut() {
  34488. this.body.view.scale /= 1 + this.options.keyboard.speed.zoom;
  34489. this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale });
  34490. }
  34491. /**
  34492. * bind all keys using keycharm.
  34493. */
  34494. }, {
  34495. key: 'configureKeyboardBindings',
  34496. value: function configureKeyboardBindings() {
  34497. var _this3 = this;
  34498. if (this.keycharm !== undefined) {
  34499. this.keycharm.destroy();
  34500. }
  34501. if (this.options.keyboard.enabled === true) {
  34502. if (this.options.keyboard.bindToWindow === true) {
  34503. this.keycharm = keycharm({ container: window, preventDefault: true });
  34504. } else {
  34505. this.keycharm = keycharm({ container: this.canvas.frame, preventDefault: true });
  34506. }
  34507. this.keycharm.reset();
  34508. if (this.activated === true) {
  34509. this.keycharm.bind("up", function () {
  34510. _this3.bindToRedraw("_moveUp");
  34511. }, "keydown");
  34512. this.keycharm.bind("down", function () {
  34513. _this3.bindToRedraw("_moveDown");
  34514. }, "keydown");
  34515. this.keycharm.bind("left", function () {
  34516. _this3.bindToRedraw("_moveLeft");
  34517. }, "keydown");
  34518. this.keycharm.bind("right", function () {
  34519. _this3.bindToRedraw("_moveRight");
  34520. }, "keydown");
  34521. this.keycharm.bind("=", function () {
  34522. _this3.bindToRedraw("_zoomIn");
  34523. }, "keydown");
  34524. this.keycharm.bind("num+", function () {
  34525. _this3.bindToRedraw("_zoomIn");
  34526. }, "keydown");
  34527. this.keycharm.bind("num-", function () {
  34528. _this3.bindToRedraw("_zoomOut");
  34529. }, "keydown");
  34530. this.keycharm.bind("-", function () {
  34531. _this3.bindToRedraw("_zoomOut");
  34532. }, "keydown");
  34533. this.keycharm.bind("[", function () {
  34534. _this3.bindToRedraw("_zoomOut");
  34535. }, "keydown");
  34536. this.keycharm.bind("]", function () {
  34537. _this3.bindToRedraw("_zoomIn");
  34538. }, "keydown");
  34539. this.keycharm.bind("pageup", function () {
  34540. _this3.bindToRedraw("_zoomIn");
  34541. }, "keydown");
  34542. this.keycharm.bind("pagedown", function () {
  34543. _this3.bindToRedraw("_zoomOut");
  34544. }, "keydown");
  34545. this.keycharm.bind("up", function () {
  34546. _this3.unbindFromRedraw("_moveUp");
  34547. }, "keyup");
  34548. this.keycharm.bind("down", function () {
  34549. _this3.unbindFromRedraw("_moveDown");
  34550. }, "keyup");
  34551. this.keycharm.bind("left", function () {
  34552. _this3.unbindFromRedraw("_moveLeft");
  34553. }, "keyup");
  34554. this.keycharm.bind("right", function () {
  34555. _this3.unbindFromRedraw("_moveRight");
  34556. }, "keyup");
  34557. this.keycharm.bind("=", function () {
  34558. _this3.unbindFromRedraw("_zoomIn");
  34559. }, "keyup");
  34560. this.keycharm.bind("num+", function () {
  34561. _this3.unbindFromRedraw("_zoomIn");
  34562. }, "keyup");
  34563. this.keycharm.bind("num-", function () {
  34564. _this3.unbindFromRedraw("_zoomOut");
  34565. }, "keyup");
  34566. this.keycharm.bind("-", function () {
  34567. _this3.unbindFromRedraw("_zoomOut");
  34568. }, "keyup");
  34569. this.keycharm.bind("[", function () {
  34570. _this3.unbindFromRedraw("_zoomOut");
  34571. }, "keyup");
  34572. this.keycharm.bind("]", function () {
  34573. _this3.unbindFromRedraw("_zoomIn");
  34574. }, "keyup");
  34575. this.keycharm.bind("pageup", function () {
  34576. _this3.unbindFromRedraw("_zoomIn");
  34577. }, "keyup");
  34578. this.keycharm.bind("pagedown", function () {
  34579. _this3.unbindFromRedraw("_zoomOut");
  34580. }, "keyup");
  34581. }
  34582. }
  34583. }
  34584. }]);
  34585. return NavigationHandler;
  34586. }();
  34587. exports.default = NavigationHandler;
  34588. /***/ },
  34589. /* 110 */
  34590. /***/ function(module, exports) {
  34591. 'use strict';
  34592. Object.defineProperty(exports, "__esModule", {
  34593. value: true
  34594. });
  34595. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  34596. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34597. /**
  34598. * Popup is a class to create a popup window with some text
  34599. * @param {Element} container The container object.
  34600. * @param {Number} [x]
  34601. * @param {Number} [y]
  34602. * @param {String} [text]
  34603. * @param {Object} [style] An object containing borderColor,
  34604. * backgroundColor, etc.
  34605. */
  34606. var Popup = function () {
  34607. function Popup(container) {
  34608. _classCallCheck(this, Popup);
  34609. this.container = container;
  34610. this.x = 0;
  34611. this.y = 0;
  34612. this.padding = 5;
  34613. this.hidden = false;
  34614. // create the frame
  34615. this.frame = document.createElement('div');
  34616. this.frame.className = 'vis-network-tooltip';
  34617. this.container.appendChild(this.frame);
  34618. }
  34619. /**
  34620. * @param {number} x Horizontal position of the popup window
  34621. * @param {number} y Vertical position of the popup window
  34622. */
  34623. _createClass(Popup, [{
  34624. key: 'setPosition',
  34625. value: function setPosition(x, y) {
  34626. this.x = parseInt(x);
  34627. this.y = parseInt(y);
  34628. }
  34629. /**
  34630. * Set the content for the popup window. This can be HTML code or text.
  34631. * @param {string | Element} content
  34632. */
  34633. }, {
  34634. key: 'setText',
  34635. value: function setText(content) {
  34636. if (content instanceof Element) {
  34637. this.frame.innerHTML = '';
  34638. this.frame.appendChild(content);
  34639. } else {
  34640. this.frame.innerHTML = content; // string containing text or HTML
  34641. }
  34642. }
  34643. /**
  34644. * Show the popup window
  34645. * @param {boolean} [doShow] Show or hide the window
  34646. */
  34647. }, {
  34648. key: 'show',
  34649. value: function show(doShow) {
  34650. if (doShow === undefined) {
  34651. doShow = true;
  34652. }
  34653. if (doShow === true) {
  34654. var height = this.frame.clientHeight;
  34655. var width = this.frame.clientWidth;
  34656. var maxHeight = this.frame.parentNode.clientHeight;
  34657. var maxWidth = this.frame.parentNode.clientWidth;
  34658. var top = this.y - height;
  34659. if (top + height + this.padding > maxHeight) {
  34660. top = maxHeight - height - this.padding;
  34661. }
  34662. if (top < this.padding) {
  34663. top = this.padding;
  34664. }
  34665. var left = this.x;
  34666. if (left + width + this.padding > maxWidth) {
  34667. left = maxWidth - width - this.padding;
  34668. }
  34669. if (left < this.padding) {
  34670. left = this.padding;
  34671. }
  34672. this.frame.style.left = left + "px";
  34673. this.frame.style.top = top + "px";
  34674. this.frame.style.visibility = "visible";
  34675. this.hidden = false;
  34676. } else {
  34677. this.hide();
  34678. }
  34679. }
  34680. /**
  34681. * Hide the popup window
  34682. */
  34683. }, {
  34684. key: 'hide',
  34685. value: function hide() {
  34686. this.hidden = true;
  34687. this.frame.style.visibility = "hidden";
  34688. }
  34689. }]);
  34690. return Popup;
  34691. }();
  34692. exports.default = Popup;
  34693. /***/ },
  34694. /* 111 */
  34695. /***/ function(module, exports, __webpack_require__) {
  34696. 'use strict';
  34697. Object.defineProperty(exports, "__esModule", {
  34698. value: true
  34699. });
  34700. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  34701. var _Node = __webpack_require__(65);
  34702. var _Node2 = _interopRequireDefault(_Node);
  34703. var _Edge = __webpack_require__(85);
  34704. var _Edge2 = _interopRequireDefault(_Edge);
  34705. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  34706. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34707. var util = __webpack_require__(1);
  34708. var SelectionHandler = function () {
  34709. function SelectionHandler(body, canvas) {
  34710. var _this = this;
  34711. _classCallCheck(this, SelectionHandler);
  34712. this.body = body;
  34713. this.canvas = canvas;
  34714. this.selectionObj = { nodes: [], edges: [] };
  34715. this.hoverObj = { nodes: {}, edges: {} };
  34716. this.options = {};
  34717. this.defaultOptions = {
  34718. multiselect: false,
  34719. selectable: true,
  34720. selectConnectedEdges: true,
  34721. hoverConnectedEdges: true
  34722. };
  34723. util.extend(this.options, this.defaultOptions);
  34724. this.body.emitter.on("_dataChanged", function () {
  34725. _this.updateSelection();
  34726. });
  34727. }
  34728. _createClass(SelectionHandler, [{
  34729. key: 'setOptions',
  34730. value: function setOptions(options) {
  34731. if (options !== undefined) {
  34732. var fields = ['multiselect', 'hoverConnectedEdges', 'selectable', 'selectConnectedEdges'];
  34733. util.selectiveDeepExtend(fields, this.options, options);
  34734. }
  34735. }
  34736. /**
  34737. * handles the selection part of the tap;
  34738. *
  34739. * @param {Object} pointer
  34740. * @private
  34741. */
  34742. }, {
  34743. key: 'selectOnPoint',
  34744. value: function selectOnPoint(pointer) {
  34745. var selected = false;
  34746. if (this.options.selectable === true) {
  34747. var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer);
  34748. // unselect after getting the objects in order to restore width and height.
  34749. this.unselectAll();
  34750. if (obj !== undefined) {
  34751. selected = this.selectObject(obj);
  34752. }
  34753. this.body.emitter.emit("_requestRedraw");
  34754. }
  34755. return selected;
  34756. }
  34757. }, {
  34758. key: 'selectAdditionalOnPoint',
  34759. value: function selectAdditionalOnPoint(pointer) {
  34760. var selectionChanged = false;
  34761. if (this.options.selectable === true) {
  34762. var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer);
  34763. if (obj !== undefined) {
  34764. selectionChanged = true;
  34765. if (obj.isSelected() === true) {
  34766. this.deselectObject(obj);
  34767. } else {
  34768. this.selectObject(obj);
  34769. }
  34770. this.body.emitter.emit("_requestRedraw");
  34771. }
  34772. }
  34773. return selectionChanged;
  34774. }
  34775. }, {
  34776. key: '_generateClickEvent',
  34777. value: function _generateClickEvent(eventType, event, pointer, oldSelection) {
  34778. var emptySelection = arguments.length <= 4 || arguments[4] === undefined ? false : arguments[4];
  34779. var properties = void 0;
  34780. if (emptySelection === true) {
  34781. properties = { nodes: [], edges: [] };
  34782. } else {
  34783. properties = this.getSelection();
  34784. }
  34785. properties['pointer'] = {
  34786. DOM: { x: pointer.x, y: pointer.y },
  34787. canvas: this.canvas.DOMtoCanvas(pointer)
  34788. };
  34789. properties['event'] = event;
  34790. if (oldSelection !== undefined) {
  34791. properties['previousSelection'] = oldSelection;
  34792. }
  34793. this.body.emitter.emit(eventType, properties);
  34794. }
  34795. }, {
  34796. key: 'selectObject',
  34797. value: function selectObject(obj) {
  34798. var highlightEdges = arguments.length <= 1 || arguments[1] === undefined ? this.options.selectConnectedEdges : arguments[1];
  34799. if (obj !== undefined) {
  34800. if (obj instanceof _Node2.default) {
  34801. if (highlightEdges === true) {
  34802. this._selectConnectedEdges(obj);
  34803. }
  34804. }
  34805. obj.select();
  34806. this._addToSelection(obj);
  34807. return true;
  34808. }
  34809. return false;
  34810. }
  34811. }, {
  34812. key: 'deselectObject',
  34813. value: function deselectObject(obj) {
  34814. if (obj.isSelected() === true) {
  34815. obj.selected = false;
  34816. this._removeFromSelection(obj);
  34817. }
  34818. }
  34819. /**
  34820. * retrieve all nodes overlapping with given object
  34821. * @param {Object} object An object with parameters left, top, right, bottom
  34822. * @return {Number[]} An array with id's of the overlapping nodes
  34823. * @private
  34824. */
  34825. }, {
  34826. key: '_getAllNodesOverlappingWith',
  34827. value: function _getAllNodesOverlappingWith(object) {
  34828. var overlappingNodes = [];
  34829. var nodes = this.body.nodes;
  34830. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  34831. var nodeId = this.body.nodeIndices[i];
  34832. if (nodes[nodeId].isOverlappingWith(object)) {
  34833. overlappingNodes.push(nodeId);
  34834. }
  34835. }
  34836. return overlappingNodes;
  34837. }
  34838. /**
  34839. * Return a position object in canvasspace from a single point in screenspace
  34840. *
  34841. * @param pointer
  34842. * @returns {{left: number, top: number, right: number, bottom: number}}
  34843. * @private
  34844. */
  34845. }, {
  34846. key: '_pointerToPositionObject',
  34847. value: function _pointerToPositionObject(pointer) {
  34848. var canvasPos = this.canvas.DOMtoCanvas(pointer);
  34849. return {
  34850. left: canvasPos.x - 1,
  34851. top: canvasPos.y + 1,
  34852. right: canvasPos.x + 1,
  34853. bottom: canvasPos.y - 1
  34854. };
  34855. }
  34856. /**
  34857. * Get the top node at the a specific point (like a click)
  34858. *
  34859. * @param {{x: Number, y: Number}} pointer
  34860. * @return {Node | undefined} node
  34861. */
  34862. }, {
  34863. key: 'getNodeAt',
  34864. value: function getNodeAt(pointer) {
  34865. var returnNode = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  34866. // we first check if this is an navigation controls element
  34867. var positionObject = this._pointerToPositionObject(pointer);
  34868. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  34869. // if there are overlapping nodes, select the last one, this is the
  34870. // one which is drawn on top of the others
  34871. if (overlappingNodes.length > 0) {
  34872. if (returnNode === true) {
  34873. return this.body.nodes[overlappingNodes[overlappingNodes.length - 1]];
  34874. } else {
  34875. return overlappingNodes[overlappingNodes.length - 1];
  34876. }
  34877. } else {
  34878. return undefined;
  34879. }
  34880. }
  34881. /**
  34882. * retrieve all edges overlapping with given object, selector is around center
  34883. * @param {Object} object An object with parameters left, top, right, bottom
  34884. * @return {Number[]} An array with id's of the overlapping nodes
  34885. * @private
  34886. */
  34887. }, {
  34888. key: '_getEdgesOverlappingWith',
  34889. value: function _getEdgesOverlappingWith(object, overlappingEdges) {
  34890. var edges = this.body.edges;
  34891. for (var i = 0; i < this.body.edgeIndices.length; i++) {
  34892. var edgeId = this.body.edgeIndices[i];
  34893. if (edges[edgeId].isOverlappingWith(object)) {
  34894. overlappingEdges.push(edgeId);
  34895. }
  34896. }
  34897. }
  34898. /**
  34899. * retrieve all nodes overlapping with given object
  34900. * @param {Object} object An object with parameters left, top, right, bottom
  34901. * @return {Number[]} An array with id's of the overlapping nodes
  34902. * @private
  34903. */
  34904. }, {
  34905. key: '_getAllEdgesOverlappingWith',
  34906. value: function _getAllEdgesOverlappingWith(object) {
  34907. var overlappingEdges = [];
  34908. this._getEdgesOverlappingWith(object, overlappingEdges);
  34909. return overlappingEdges;
  34910. }
  34911. /**
  34912. * Place holder. To implement change the getNodeAt to a _getObjectAt. Have the _getObjectAt call
  34913. * getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
  34914. *
  34915. * @param pointer
  34916. * @returns {undefined}
  34917. */
  34918. }, {
  34919. key: 'getEdgeAt',
  34920. value: function getEdgeAt(pointer) {
  34921. var returnEdge = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  34922. var positionObject = this._pointerToPositionObject(pointer);
  34923. var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
  34924. if (overlappingEdges.length > 0) {
  34925. if (returnEdge === true) {
  34926. return this.body.edges[overlappingEdges[overlappingEdges.length - 1]];
  34927. } else {
  34928. return overlappingEdges[overlappingEdges.length - 1];
  34929. }
  34930. } else {
  34931. return undefined;
  34932. }
  34933. }
  34934. /**
  34935. * Add object to the selection array.
  34936. *
  34937. * @param obj
  34938. * @private
  34939. */
  34940. }, {
  34941. key: '_addToSelection',
  34942. value: function _addToSelection(obj) {
  34943. if (obj instanceof _Node2.default) {
  34944. this.selectionObj.nodes[obj.id] = obj;
  34945. } else {
  34946. this.selectionObj.edges[obj.id] = obj;
  34947. }
  34948. }
  34949. /**
  34950. * Add object to the selection array.
  34951. *
  34952. * @param obj
  34953. * @private
  34954. */
  34955. }, {
  34956. key: '_addToHover',
  34957. value: function _addToHover(obj) {
  34958. if (obj instanceof _Node2.default) {
  34959. this.hoverObj.nodes[obj.id] = obj;
  34960. } else {
  34961. this.hoverObj.edges[obj.id] = obj;
  34962. }
  34963. }
  34964. /**
  34965. * Remove a single option from selection.
  34966. *
  34967. * @param {Object} obj
  34968. * @private
  34969. */
  34970. }, {
  34971. key: '_removeFromSelection',
  34972. value: function _removeFromSelection(obj) {
  34973. if (obj instanceof _Node2.default) {
  34974. delete this.selectionObj.nodes[obj.id];
  34975. this._unselectConnectedEdges(obj);
  34976. } else {
  34977. delete this.selectionObj.edges[obj.id];
  34978. }
  34979. }
  34980. /**
  34981. * Unselect all. The selectionObj is useful for this.
  34982. */
  34983. }, {
  34984. key: 'unselectAll',
  34985. value: function unselectAll() {
  34986. for (var nodeId in this.selectionObj.nodes) {
  34987. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  34988. this.selectionObj.nodes[nodeId].unselect();
  34989. }
  34990. }
  34991. for (var edgeId in this.selectionObj.edges) {
  34992. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  34993. this.selectionObj.edges[edgeId].unselect();
  34994. }
  34995. }
  34996. this.selectionObj = { nodes: {}, edges: {} };
  34997. }
  34998. /**
  34999. * return the number of selected nodes
  35000. *
  35001. * @returns {number}
  35002. * @private
  35003. */
  35004. }, {
  35005. key: '_getSelectedNodeCount',
  35006. value: function _getSelectedNodeCount() {
  35007. var count = 0;
  35008. for (var nodeId in this.selectionObj.nodes) {
  35009. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35010. count += 1;
  35011. }
  35012. }
  35013. return count;
  35014. }
  35015. /**
  35016. * return the selected node
  35017. *
  35018. * @returns {number}
  35019. * @private
  35020. */
  35021. }, {
  35022. key: '_getSelectedNode',
  35023. value: function _getSelectedNode() {
  35024. for (var nodeId in this.selectionObj.nodes) {
  35025. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35026. return this.selectionObj.nodes[nodeId];
  35027. }
  35028. }
  35029. return undefined;
  35030. }
  35031. /**
  35032. * return the selected edge
  35033. *
  35034. * @returns {number}
  35035. * @private
  35036. */
  35037. }, {
  35038. key: '_getSelectedEdge',
  35039. value: function _getSelectedEdge() {
  35040. for (var edgeId in this.selectionObj.edges) {
  35041. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  35042. return this.selectionObj.edges[edgeId];
  35043. }
  35044. }
  35045. return undefined;
  35046. }
  35047. /**
  35048. * return the number of selected edges
  35049. *
  35050. * @returns {number}
  35051. * @private
  35052. */
  35053. }, {
  35054. key: '_getSelectedEdgeCount',
  35055. value: function _getSelectedEdgeCount() {
  35056. var count = 0;
  35057. for (var edgeId in this.selectionObj.edges) {
  35058. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  35059. count += 1;
  35060. }
  35061. }
  35062. return count;
  35063. }
  35064. /**
  35065. * return the number of selected objects.
  35066. *
  35067. * @returns {number}
  35068. * @private
  35069. */
  35070. }, {
  35071. key: '_getSelectedObjectCount',
  35072. value: function _getSelectedObjectCount() {
  35073. var count = 0;
  35074. for (var nodeId in this.selectionObj.nodes) {
  35075. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35076. count += 1;
  35077. }
  35078. }
  35079. for (var edgeId in this.selectionObj.edges) {
  35080. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  35081. count += 1;
  35082. }
  35083. }
  35084. return count;
  35085. }
  35086. /**
  35087. * Check if anything is selected
  35088. *
  35089. * @returns {boolean}
  35090. * @private
  35091. */
  35092. }, {
  35093. key: '_selectionIsEmpty',
  35094. value: function _selectionIsEmpty() {
  35095. for (var nodeId in this.selectionObj.nodes) {
  35096. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35097. return false;
  35098. }
  35099. }
  35100. for (var edgeId in this.selectionObj.edges) {
  35101. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  35102. return false;
  35103. }
  35104. }
  35105. return true;
  35106. }
  35107. /**
  35108. * check if one of the selected nodes is a cluster.
  35109. *
  35110. * @returns {boolean}
  35111. * @private
  35112. */
  35113. }, {
  35114. key: '_clusterInSelection',
  35115. value: function _clusterInSelection() {
  35116. for (var nodeId in this.selectionObj.nodes) {
  35117. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35118. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  35119. return true;
  35120. }
  35121. }
  35122. }
  35123. return false;
  35124. }
  35125. /**
  35126. * select the edges connected to the node that is being selected
  35127. *
  35128. * @param {Node} node
  35129. * @private
  35130. */
  35131. }, {
  35132. key: '_selectConnectedEdges',
  35133. value: function _selectConnectedEdges(node) {
  35134. for (var i = 0; i < node.edges.length; i++) {
  35135. var edge = node.edges[i];
  35136. edge.select();
  35137. this._addToSelection(edge);
  35138. }
  35139. }
  35140. /**
  35141. * select the edges connected to the node that is being selected
  35142. *
  35143. * @param {Node} node
  35144. * @private
  35145. */
  35146. }, {
  35147. key: '_hoverConnectedEdges',
  35148. value: function _hoverConnectedEdges(node) {
  35149. for (var i = 0; i < node.edges.length; i++) {
  35150. var edge = node.edges[i];
  35151. edge.hover = true;
  35152. this._addToHover(edge);
  35153. }
  35154. }
  35155. /**
  35156. * unselect the edges connected to the node that is being selected
  35157. *
  35158. * @param {Node} node
  35159. * @private
  35160. */
  35161. }, {
  35162. key: '_unselectConnectedEdges',
  35163. value: function _unselectConnectedEdges(node) {
  35164. for (var i = 0; i < node.edges.length; i++) {
  35165. var edge = node.edges[i];
  35166. edge.unselect();
  35167. this._removeFromSelection(edge);
  35168. }
  35169. }
  35170. /**
  35171. * This is called when someone clicks on a node. either select or deselect it.
  35172. * If there is an existing selection and we don't want to append to it, clear the existing selection
  35173. *
  35174. * @param {Node || Edge} object
  35175. * @private
  35176. */
  35177. }, {
  35178. key: 'blurObject',
  35179. value: function blurObject(object) {
  35180. if (object.hover === true) {
  35181. object.hover = false;
  35182. if (object instanceof _Node2.default) {
  35183. this.body.emitter.emit("blurNode", { node: object.id });
  35184. } else {
  35185. this.body.emitter.emit("blurEdge", { edge: object.id });
  35186. }
  35187. }
  35188. }
  35189. /**
  35190. * This is called when someone clicks on a node. either select or deselect it.
  35191. * If there is an existing selection and we don't want to append to it, clear the existing selection
  35192. *
  35193. * @param {Node || Edge} object
  35194. * @private
  35195. */
  35196. }, {
  35197. key: 'hoverObject',
  35198. value: function hoverObject(object) {
  35199. var hoverChanged = false;
  35200. // remove all node hover highlights
  35201. for (var nodeId in this.hoverObj.nodes) {
  35202. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  35203. if (object === undefined || object instanceof _Node2.default && object.id != nodeId || object instanceof _Edge2.default) {
  35204. this.blurObject(this.hoverObj.nodes[nodeId]);
  35205. delete this.hoverObj.nodes[nodeId];
  35206. hoverChanged = true;
  35207. }
  35208. }
  35209. }
  35210. // removing all edge hover highlights
  35211. for (var edgeId in this.hoverObj.edges) {
  35212. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  35213. // if the hover has been changed here it means that the node has been hovered over or off
  35214. // we then do not use the blurObject method here.
  35215. if (hoverChanged === true) {
  35216. this.hoverObj.edges[edgeId].hover = false;
  35217. delete this.hoverObj.edges[edgeId];
  35218. }
  35219. // if the blur remains the same and the object is undefined (mouse off), we blur the edge
  35220. else if (object === undefined) {
  35221. this.blurObject(this.hoverObj.edges[edgeId]);
  35222. delete this.hoverObj.edges[edgeId];
  35223. hoverChanged = true;
  35224. }
  35225. }
  35226. }
  35227. if (object !== undefined) {
  35228. if (object.hover === false) {
  35229. object.hover = true;
  35230. this._addToHover(object);
  35231. hoverChanged = true;
  35232. if (object instanceof _Node2.default) {
  35233. this.body.emitter.emit("hoverNode", { node: object.id });
  35234. } else {
  35235. this.body.emitter.emit("hoverEdge", { edge: object.id });
  35236. }
  35237. }
  35238. if (object instanceof _Node2.default && this.options.hoverConnectedEdges === true) {
  35239. this._hoverConnectedEdges(object);
  35240. }
  35241. }
  35242. if (hoverChanged === true) {
  35243. this.body.emitter.emit('_requestRedraw');
  35244. }
  35245. }
  35246. /**
  35247. *
  35248. * retrieve the currently selected objects
  35249. * @return {{nodes: Array.<String>, edges: Array.<String>}} selection
  35250. */
  35251. }, {
  35252. key: 'getSelection',
  35253. value: function getSelection() {
  35254. var nodeIds = this.getSelectedNodes();
  35255. var edgeIds = this.getSelectedEdges();
  35256. return { nodes: nodeIds, edges: edgeIds };
  35257. }
  35258. /**
  35259. *
  35260. * retrieve the currently selected nodes
  35261. * @return {String[]} selection An array with the ids of the
  35262. * selected nodes.
  35263. */
  35264. }, {
  35265. key: 'getSelectedNodes',
  35266. value: function getSelectedNodes() {
  35267. var idArray = [];
  35268. if (this.options.selectable === true) {
  35269. for (var nodeId in this.selectionObj.nodes) {
  35270. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35271. idArray.push(this.selectionObj.nodes[nodeId].id);
  35272. }
  35273. }
  35274. }
  35275. return idArray;
  35276. }
  35277. /**
  35278. *
  35279. * retrieve the currently selected edges
  35280. * @return {Array} selection An array with the ids of the
  35281. * selected nodes.
  35282. */
  35283. }, {
  35284. key: 'getSelectedEdges',
  35285. value: function getSelectedEdges() {
  35286. var idArray = [];
  35287. if (this.options.selectable === true) {
  35288. for (var edgeId in this.selectionObj.edges) {
  35289. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  35290. idArray.push(this.selectionObj.edges[edgeId].id);
  35291. }
  35292. }
  35293. }
  35294. return idArray;
  35295. }
  35296. /**
  35297. * Updates the current selection
  35298. * @param {{nodes: Array.<String>, edges: Array.<String>}} Selection
  35299. * @param {Object} options Options
  35300. */
  35301. }, {
  35302. key: 'setSelection',
  35303. value: function setSelection(selection) {
  35304. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  35305. var i = void 0,
  35306. id = void 0;
  35307. if (!selection || !selection.nodes && !selection.edges) throw 'Selection must be an object with nodes and/or edges properties';
  35308. // first unselect any selected node, if option is true or undefined
  35309. if (options.unselectAll || options.unselectAll === undefined) {
  35310. this.unselectAll();
  35311. }
  35312. if (selection.nodes) {
  35313. for (i = 0; i < selection.nodes.length; i++) {
  35314. id = selection.nodes[i];
  35315. var node = this.body.nodes[id];
  35316. if (!node) {
  35317. throw new RangeError('Node with id "' + id + '" not found');
  35318. }
  35319. // don't select edges with it
  35320. this.selectObject(node, options.highlightEdges);
  35321. }
  35322. }
  35323. if (selection.edges) {
  35324. for (i = 0; i < selection.edges.length; i++) {
  35325. id = selection.edges[i];
  35326. var edge = this.body.edges[id];
  35327. if (!edge) {
  35328. throw new RangeError('Edge with id "' + id + '" not found');
  35329. }
  35330. this.selectObject(edge);
  35331. }
  35332. }
  35333. this.body.emitter.emit('_requestRedraw');
  35334. }
  35335. /**
  35336. * select zero or more nodes with the option to highlight edges
  35337. * @param {Number[] | String[]} selection An array with the ids of the
  35338. * selected nodes.
  35339. * @param {boolean} [highlightEdges]
  35340. */
  35341. }, {
  35342. key: 'selectNodes',
  35343. value: function selectNodes(selection) {
  35344. var highlightEdges = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  35345. if (!selection || selection.length === undefined) throw 'Selection must be an array with ids';
  35346. this.setSelection({ nodes: selection }, { highlightEdges: highlightEdges });
  35347. }
  35348. /**
  35349. * select zero or more edges
  35350. * @param {Number[] | String[]} selection An array with the ids of the
  35351. * selected nodes.
  35352. */
  35353. }, {
  35354. key: 'selectEdges',
  35355. value: function selectEdges(selection) {
  35356. if (!selection || selection.length === undefined) throw 'Selection must be an array with ids';
  35357. this.setSelection({ edges: selection });
  35358. }
  35359. /**
  35360. * Validate the selection: remove ids of nodes which no longer exist
  35361. * @private
  35362. */
  35363. }, {
  35364. key: 'updateSelection',
  35365. value: function updateSelection() {
  35366. for (var nodeId in this.selectionObj.nodes) {
  35367. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  35368. if (!this.body.nodes.hasOwnProperty(nodeId)) {
  35369. delete this.selectionObj.nodes[nodeId];
  35370. }
  35371. }
  35372. }
  35373. for (var edgeId in this.selectionObj.edges) {
  35374. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  35375. if (!this.body.edges.hasOwnProperty(edgeId)) {
  35376. delete this.selectionObj.edges[edgeId];
  35377. }
  35378. }
  35379. }
  35380. }
  35381. }]);
  35382. return SelectionHandler;
  35383. }();
  35384. exports.default = SelectionHandler;
  35385. /***/ },
  35386. /* 112 */
  35387. /***/ function(module, exports, __webpack_require__) {
  35388. 'use strict';
  35389. Object.defineProperty(exports, "__esModule", {
  35390. value: true
  35391. });
  35392. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  35393. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  35394. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  35395. var _NetworkUtil = __webpack_require__(103);
  35396. var _NetworkUtil2 = _interopRequireDefault(_NetworkUtil);
  35397. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35398. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35399. var util = __webpack_require__(1);
  35400. var LayoutEngine = function () {
  35401. function LayoutEngine(body) {
  35402. _classCallCheck(this, LayoutEngine);
  35403. this.body = body;
  35404. this.initialRandomSeed = Math.round(Math.random() * 1000000);
  35405. this.randomSeed = this.initialRandomSeed;
  35406. this.setPhysics = false;
  35407. this.options = {};
  35408. this.optionsBackup = { physics: {} };
  35409. this.defaultOptions = {
  35410. randomSeed: undefined,
  35411. improvedLayout: true,
  35412. hierarchical: {
  35413. enabled: false,
  35414. levelSeparation: 150,
  35415. nodeSpacing: 100,
  35416. treeSpacing: 200,
  35417. blockShifting: true,
  35418. edgeMinimization: true,
  35419. parentCentralization: true,
  35420. direction: 'UD', // UD, DU, LR, RL
  35421. sortMethod: 'hubsize' // hubsize, directed
  35422. }
  35423. };
  35424. util.extend(this.options, this.defaultOptions);
  35425. this.bindEventListeners();
  35426. }
  35427. _createClass(LayoutEngine, [{
  35428. key: 'bindEventListeners',
  35429. value: function bindEventListeners() {
  35430. var _this = this;
  35431. this.body.emitter.on('_dataChanged', function () {
  35432. _this.setupHierarchicalLayout();
  35433. });
  35434. this.body.emitter.on('_dataLoaded', function () {
  35435. _this.layoutNetwork();
  35436. });
  35437. this.body.emitter.on('_resetHierarchicalLayout', function () {
  35438. _this.setupHierarchicalLayout();
  35439. });
  35440. }
  35441. }, {
  35442. key: 'setOptions',
  35443. value: function setOptions(options, allOptions) {
  35444. if (options !== undefined) {
  35445. var prevHierarchicalState = this.options.hierarchical.enabled;
  35446. util.selectiveDeepExtend(["randomSeed", "improvedLayout"], this.options, options);
  35447. util.mergeOptions(this.options, options, 'hierarchical');
  35448. if (options.randomSeed !== undefined) {
  35449. this.initialRandomSeed = options.randomSeed;
  35450. }
  35451. if (this.options.hierarchical.enabled === true) {
  35452. if (prevHierarchicalState === true) {
  35453. // refresh the overridden options for nodes and edges.
  35454. this.body.emitter.emit('refresh', true);
  35455. }
  35456. // make sure the level separation is the right way up
  35457. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') {
  35458. if (this.options.hierarchical.levelSeparation > 0) {
  35459. this.options.hierarchical.levelSeparation *= -1;
  35460. }
  35461. } else {
  35462. if (this.options.hierarchical.levelSeparation < 0) {
  35463. this.options.hierarchical.levelSeparation *= -1;
  35464. }
  35465. }
  35466. this.body.emitter.emit('_resetHierarchicalLayout');
  35467. // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed.
  35468. return this.adaptAllOptionsForHierarchicalLayout(allOptions);
  35469. } else {
  35470. if (prevHierarchicalState === true) {
  35471. // refresh the overridden options for nodes and edges.
  35472. this.body.emitter.emit('refresh');
  35473. return util.deepExtend(allOptions, this.optionsBackup);
  35474. }
  35475. }
  35476. }
  35477. return allOptions;
  35478. }
  35479. }, {
  35480. key: 'adaptAllOptionsForHierarchicalLayout',
  35481. value: function adaptAllOptionsForHierarchicalLayout(allOptions) {
  35482. if (this.options.hierarchical.enabled === true) {
  35483. // set the physics
  35484. if (allOptions.physics === undefined || allOptions.physics === true) {
  35485. allOptions.physics = {
  35486. enabled: this.optionsBackup.physics.enabled === undefined ? true : this.optionsBackup.physics.enabled,
  35487. solver: 'hierarchicalRepulsion'
  35488. };
  35489. this.optionsBackup.physics.enabled = this.optionsBackup.physics.enabled === undefined ? true : this.optionsBackup.physics.enabled;
  35490. this.optionsBackup.physics.solver = this.optionsBackup.physics.solver || 'barnesHut';
  35491. } else if (_typeof(allOptions.physics) === 'object') {
  35492. this.optionsBackup.physics.enabled = allOptions.physics.enabled === undefined ? true : allOptions.physics.enabled;
  35493. this.optionsBackup.physics.solver = allOptions.physics.solver || 'barnesHut';
  35494. allOptions.physics.solver = 'hierarchicalRepulsion';
  35495. } else if (allOptions.physics !== false) {
  35496. this.optionsBackup.physics.solver = 'barnesHut';
  35497. allOptions.physics = { solver: 'hierarchicalRepulsion' };
  35498. }
  35499. // get the type of static smooth curve in case it is required
  35500. var type = 'horizontal';
  35501. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') {
  35502. type = 'vertical';
  35503. }
  35504. // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves.
  35505. if (allOptions.edges === undefined) {
  35506. this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } };
  35507. allOptions.edges = { smooth: false };
  35508. } else if (allOptions.edges.smooth === undefined) {
  35509. this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } };
  35510. allOptions.edges.smooth = false;
  35511. } else {
  35512. if (typeof allOptions.edges.smooth === 'boolean') {
  35513. this.optionsBackup.edges = { smooth: allOptions.edges.smooth };
  35514. allOptions.edges.smooth = { enabled: allOptions.edges.smooth, type: type };
  35515. } else {
  35516. // allow custom types except for dynamic
  35517. if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') {
  35518. type = allOptions.edges.smooth.type;
  35519. }
  35520. this.optionsBackup.edges = {
  35521. smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  35522. type: allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type,
  35523. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  35524. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  35525. };
  35526. allOptions.edges.smooth = {
  35527. enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  35528. type: type,
  35529. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  35530. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  35531. };
  35532. }
  35533. }
  35534. // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth.
  35535. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  35536. }
  35537. return allOptions;
  35538. }
  35539. }, {
  35540. key: 'seededRandom',
  35541. value: function seededRandom() {
  35542. var x = Math.sin(this.randomSeed++) * 10000;
  35543. return x - Math.floor(x);
  35544. }
  35545. }, {
  35546. key: 'positionInitially',
  35547. value: function positionInitially(nodesArray) {
  35548. if (this.options.hierarchical.enabled !== true) {
  35549. this.randomSeed = this.initialRandomSeed;
  35550. for (var i = 0; i < nodesArray.length; i++) {
  35551. var node = nodesArray[i];
  35552. var radius = 10 * 0.1 * nodesArray.length + 10;
  35553. var angle = 2 * Math.PI * this.seededRandom();
  35554. if (node.x === undefined) {
  35555. node.x = radius * Math.cos(angle);
  35556. }
  35557. if (node.y === undefined) {
  35558. node.y = radius * Math.sin(angle);
  35559. }
  35560. }
  35561. }
  35562. }
  35563. /**
  35564. * Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
  35565. * cluster them first to reduce the amount.
  35566. */
  35567. }, {
  35568. key: 'layoutNetwork',
  35569. value: function layoutNetwork() {
  35570. if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
  35571. // first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
  35572. // nodes have predefined positions we use this.
  35573. var positionDefined = 0;
  35574. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  35575. var node = this.body.nodes[this.body.nodeIndices[i]];
  35576. if (node.predefinedPosition === true) {
  35577. positionDefined += 1;
  35578. }
  35579. }
  35580. // if less than half of the nodes have a predefined position we continue
  35581. if (positionDefined < 0.5 * this.body.nodeIndices.length) {
  35582. var MAX_LEVELS = 10;
  35583. var level = 0;
  35584. var clusterThreshold = 100;
  35585. // if there are a lot of nodes, we cluster before we run the algorithm.
  35586. if (this.body.nodeIndices.length > clusterThreshold) {
  35587. var startLength = this.body.nodeIndices.length;
  35588. while (this.body.nodeIndices.length > clusterThreshold) {
  35589. //console.time("clustering")
  35590. level += 1;
  35591. var before = this.body.nodeIndices.length;
  35592. // if there are many nodes we do a hubsize cluster
  35593. if (level % 3 === 0) {
  35594. this.body.modules.clustering.clusterBridges();
  35595. } else {
  35596. this.body.modules.clustering.clusterOutliers();
  35597. }
  35598. var after = this.body.nodeIndices.length;
  35599. if (before == after && level % 3 !== 0 || level > MAX_LEVELS) {
  35600. this._declusterAll();
  35601. this.body.emitter.emit("_layoutFailed");
  35602. console.info("This network could not be positioned by this version of the improved layout algorithm. Please disable improvedLayout for better performance.");
  35603. return;
  35604. }
  35605. //console.timeEnd("clustering")
  35606. //console.log(level,after)
  35607. }
  35608. // increase the size of the edges
  35609. this.body.modules.kamadaKawai.setOptions({ springLength: Math.max(150, 2 * startLength) });
  35610. }
  35611. // position the system for these nodes and edges
  35612. this.body.modules.kamadaKawai.solve(this.body.nodeIndices, this.body.edgeIndices, true);
  35613. // shift to center point
  35614. this._shiftToCenter();
  35615. // perturb the nodes a little bit to force the physics to kick in
  35616. var offset = 70;
  35617. for (var _i = 0; _i < this.body.nodeIndices.length; _i++) {
  35618. this.body.nodes[this.body.nodeIndices[_i]].x += (0.5 - this.seededRandom()) * offset;
  35619. this.body.nodes[this.body.nodeIndices[_i]].y += (0.5 - this.seededRandom()) * offset;
  35620. }
  35621. // uncluster all clusters
  35622. this._declusterAll();
  35623. // reposition all bezier nodes.
  35624. this.body.emitter.emit("_repositionBezierNodes");
  35625. }
  35626. }
  35627. }
  35628. /**
  35629. * Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
  35630. * @private
  35631. */
  35632. }, {
  35633. key: '_shiftToCenter',
  35634. value: function _shiftToCenter() {
  35635. var range = _NetworkUtil2.default.getRangeCore(this.body.nodes, this.body.nodeIndices);
  35636. var center = _NetworkUtil2.default.findCenter(range);
  35637. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  35638. this.body.nodes[this.body.nodeIndices[i]].x -= center.x;
  35639. this.body.nodes[this.body.nodeIndices[i]].y -= center.y;
  35640. }
  35641. }
  35642. }, {
  35643. key: '_declusterAll',
  35644. value: function _declusterAll() {
  35645. var clustersPresent = true;
  35646. while (clustersPresent === true) {
  35647. clustersPresent = false;
  35648. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  35649. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  35650. clustersPresent = true;
  35651. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  35652. }
  35653. }
  35654. if (clustersPresent === true) {
  35655. this.body.emitter.emit('_dataChanged');
  35656. }
  35657. }
  35658. }
  35659. }, {
  35660. key: 'getSeed',
  35661. value: function getSeed() {
  35662. return this.initialRandomSeed;
  35663. }
  35664. /**
  35665. * This is the main function to layout the nodes in a hierarchical way.
  35666. * It checks if the node details are supplied correctly
  35667. *
  35668. * @private
  35669. */
  35670. }, {
  35671. key: 'setupHierarchicalLayout',
  35672. value: function setupHierarchicalLayout() {
  35673. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  35674. // get the size of the largest hubs and check if the user has defined a level for a node.
  35675. var node = void 0,
  35676. nodeId = void 0;
  35677. var definedLevel = false;
  35678. var definedPositions = true;
  35679. var undefinedLevel = false;
  35680. this.hierarchicalLevels = {};
  35681. this.lastNodeOnLevel = {};
  35682. this.hierarchicalChildrenReference = {};
  35683. this.hierarchicalParentReference = {};
  35684. this.hierarchicalTrees = {};
  35685. this.treeIndex = -1;
  35686. this.distributionOrdering = {};
  35687. this.distributionIndex = {};
  35688. this.distributionOrderingPresence = {};
  35689. for (nodeId in this.body.nodes) {
  35690. if (this.body.nodes.hasOwnProperty(nodeId)) {
  35691. node = this.body.nodes[nodeId];
  35692. if (node.options.x === undefined && node.options.y === undefined) {
  35693. definedPositions = false;
  35694. }
  35695. if (node.options.level !== undefined) {
  35696. definedLevel = true;
  35697. this.hierarchicalLevels[nodeId] = node.options.level;
  35698. } else {
  35699. undefinedLevel = true;
  35700. }
  35701. }
  35702. }
  35703. // if the user defined some levels but not all, alert and run without hierarchical layout
  35704. if (undefinedLevel === true && definedLevel === true) {
  35705. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  35706. return;
  35707. } else {
  35708. // define levels if undefined by the users. Based on hubsize.
  35709. if (undefinedLevel === true) {
  35710. if (this.options.hierarchical.sortMethod === 'hubsize') {
  35711. this._determineLevelsByHubsize();
  35712. } else if (this.options.hierarchical.sortMethod === 'directed') {
  35713. this._determineLevelsDirected();
  35714. } else if (this.options.hierarchical.sortMethod === 'custom') {
  35715. this._determineLevelsCustomCallback();
  35716. }
  35717. }
  35718. // fallback for cases where there are nodes but no edges
  35719. for (var _nodeId in this.body.nodes) {
  35720. if (this.body.nodes.hasOwnProperty(_nodeId)) {
  35721. if (this.hierarchicalLevels[_nodeId] === undefined) {
  35722. this.hierarchicalLevels[_nodeId] = 0;
  35723. }
  35724. }
  35725. }
  35726. // check the distribution of the nodes per level.
  35727. var distribution = this._getDistribution();
  35728. // get the parent children relations.
  35729. this._generateMap();
  35730. // place the nodes on the canvas.
  35731. this._placeNodesByHierarchy(distribution);
  35732. // condense the whitespace.
  35733. this._condenseHierarchy();
  35734. // shift to center so gravity does not have to do much
  35735. this._shiftToCenter();
  35736. }
  35737. }
  35738. }
  35739. /**
  35740. * @private
  35741. */
  35742. }, {
  35743. key: '_condenseHierarchy',
  35744. value: function _condenseHierarchy() {
  35745. var _this2 = this;
  35746. // Global var in this scope to define when the movement has stopped.
  35747. var stillShifting = false;
  35748. var branches = {};
  35749. // first we have some methods to help shifting trees around.
  35750. // the main method to shift the trees
  35751. var shiftTrees = function shiftTrees() {
  35752. var treeSizes = getTreeSizes();
  35753. for (var i = 0; i < treeSizes.length - 1; i++) {
  35754. var diff = treeSizes[i].max - treeSizes[i + 1].min;
  35755. shiftTree(i + 1, diff + _this2.options.hierarchical.treeSpacing);
  35756. }
  35757. };
  35758. // shift a single tree by an offset
  35759. var shiftTree = function shiftTree(index, offset) {
  35760. for (var nodeId in _this2.hierarchicalTrees) {
  35761. if (_this2.hierarchicalTrees.hasOwnProperty(nodeId)) {
  35762. if (_this2.hierarchicalTrees[nodeId] === index) {
  35763. var node = _this2.body.nodes[nodeId];
  35764. var pos = _this2._getPositionForHierarchy(node);
  35765. _this2._setPositionForHierarchy(node, pos + offset, undefined, true);
  35766. }
  35767. }
  35768. }
  35769. };
  35770. // get the width of a tree
  35771. var getTreeSize = function getTreeSize(index) {
  35772. var min = 1e9;
  35773. var max = -1e9;
  35774. for (var nodeId in _this2.hierarchicalTrees) {
  35775. if (_this2.hierarchicalTrees.hasOwnProperty(nodeId)) {
  35776. if (_this2.hierarchicalTrees[nodeId] === index) {
  35777. var pos = _this2._getPositionForHierarchy(_this2.body.nodes[nodeId]);
  35778. min = Math.min(pos, min);
  35779. max = Math.max(pos, max);
  35780. }
  35781. }
  35782. }
  35783. return { min: min, max: max };
  35784. };
  35785. // get the width of all trees
  35786. var getTreeSizes = function getTreeSizes() {
  35787. var treeWidths = [];
  35788. for (var i = 0; i <= _this2.treeIndex; i++) {
  35789. treeWidths.push(getTreeSize(i));
  35790. }
  35791. return treeWidths;
  35792. };
  35793. // get a map of all nodes in this branch
  35794. var getBranchNodes = function getBranchNodes(source, map) {
  35795. map[source.id] = true;
  35796. if (_this2.hierarchicalChildrenReference[source.id]) {
  35797. var children = _this2.hierarchicalChildrenReference[source.id];
  35798. if (children.length > 0) {
  35799. for (var i = 0; i < children.length; i++) {
  35800. getBranchNodes(_this2.body.nodes[children[i]], map);
  35801. }
  35802. }
  35803. }
  35804. };
  35805. // get a min max width as well as the maximum movement space it has on either sides
  35806. // we use min max terminology because width and height can interchange depending on the direction of the layout
  35807. var getBranchBoundary = function getBranchBoundary(branchMap) {
  35808. var maxLevel = arguments.length <= 1 || arguments[1] === undefined ? 1e9 : arguments[1];
  35809. var minSpace = 1e9;
  35810. var maxSpace = 1e9;
  35811. var min = 1e9;
  35812. var max = -1e9;
  35813. for (var branchNode in branchMap) {
  35814. if (branchMap.hasOwnProperty(branchNode)) {
  35815. var node = _this2.body.nodes[branchNode];
  35816. var level = _this2.hierarchicalLevels[node.id];
  35817. var position = _this2._getPositionForHierarchy(node);
  35818. // get the space around the node.
  35819. var _getSpaceAroundNode2 = _this2._getSpaceAroundNode(node, branchMap);
  35820. var _getSpaceAroundNode3 = _slicedToArray(_getSpaceAroundNode2, 2);
  35821. var minSpaceNode = _getSpaceAroundNode3[0];
  35822. var maxSpaceNode = _getSpaceAroundNode3[1];
  35823. minSpace = Math.min(minSpaceNode, minSpace);
  35824. maxSpace = Math.min(maxSpaceNode, maxSpace);
  35825. // the width is only relevant for the levels two nodes have in common. This is why we filter on this.
  35826. if (level <= maxLevel) {
  35827. min = Math.min(position, min);
  35828. max = Math.max(position, max);
  35829. }
  35830. }
  35831. }
  35832. return [min, max, minSpace, maxSpace];
  35833. };
  35834. // get the maximum level of a branch.
  35835. var getMaxLevel = function getMaxLevel(nodeId) {
  35836. var level = _this2.hierarchicalLevels[nodeId];
  35837. if (_this2.hierarchicalChildrenReference[nodeId]) {
  35838. var children = _this2.hierarchicalChildrenReference[nodeId];
  35839. if (children.length > 0) {
  35840. for (var i = 0; i < children.length; i++) {
  35841. level = Math.max(level, getMaxLevel(children[i]));
  35842. }
  35843. }
  35844. }
  35845. return level;
  35846. };
  35847. // check what the maximum level is these nodes have in common.
  35848. var getCollisionLevel = function getCollisionLevel(node1, node2) {
  35849. var maxLevel1 = getMaxLevel(node1.id);
  35850. var maxLevel2 = getMaxLevel(node2.id);
  35851. return Math.min(maxLevel1, maxLevel2);
  35852. };
  35853. // check if two nodes have the same parent(s)
  35854. var hasSameParent = function hasSameParent(node1, node2) {
  35855. var parents1 = _this2.hierarchicalParentReference[node1.id];
  35856. var parents2 = _this2.hierarchicalParentReference[node2.id];
  35857. if (parents1 === undefined || parents2 === undefined) {
  35858. return false;
  35859. }
  35860. for (var i = 0; i < parents1.length; i++) {
  35861. for (var j = 0; j < parents2.length; j++) {
  35862. if (parents1[i] == parents2[j]) {
  35863. return true;
  35864. }
  35865. }
  35866. }
  35867. return false;
  35868. };
  35869. // condense elements. These can be nodes or branches depending on the callback.
  35870. var shiftElementsCloser = function shiftElementsCloser(callback, levels, centerParents) {
  35871. for (var i = 0; i < levels.length; i++) {
  35872. var level = levels[i];
  35873. var levelNodes = _this2.distributionOrdering[level];
  35874. if (levelNodes.length > 1) {
  35875. for (var j = 0; j < levelNodes.length - 1; j++) {
  35876. if (hasSameParent(levelNodes[j], levelNodes[j + 1]) === true) {
  35877. if (_this2.hierarchicalTrees[levelNodes[j].id] === _this2.hierarchicalTrees[levelNodes[j + 1].id]) {
  35878. callback(levelNodes[j], levelNodes[j + 1], centerParents);
  35879. }
  35880. }
  35881. }
  35882. }
  35883. }
  35884. };
  35885. // callback for shifting branches
  35886. var branchShiftCallback = function branchShiftCallback(node1, node2) {
  35887. var centerParent = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  35888. //window.CALLBACKS.push(() => {
  35889. var pos1 = _this2._getPositionForHierarchy(node1);
  35890. var pos2 = _this2._getPositionForHierarchy(node2);
  35891. var diffAbs = Math.abs(pos2 - pos1);
  35892. //console.log("NOW CHEcKING:", node1.id, node2.id, diffAbs);
  35893. if (diffAbs > _this2.options.hierarchical.nodeSpacing) {
  35894. var branchNodes1 = {};branchNodes1[node1.id] = true;
  35895. var branchNodes2 = {};branchNodes2[node2.id] = true;
  35896. getBranchNodes(node1, branchNodes1);
  35897. getBranchNodes(node2, branchNodes2);
  35898. // check the largest distance between the branches
  35899. var maxLevel = getCollisionLevel(node1, node2);
  35900. var _getBranchBoundary = getBranchBoundary(branchNodes1, maxLevel);
  35901. var _getBranchBoundary2 = _slicedToArray(_getBranchBoundary, 4);
  35902. var min1 = _getBranchBoundary2[0];
  35903. var max1 = _getBranchBoundary2[1];
  35904. var minSpace1 = _getBranchBoundary2[2];
  35905. var maxSpace1 = _getBranchBoundary2[3];
  35906. var _getBranchBoundary3 = getBranchBoundary(branchNodes2, maxLevel);
  35907. var _getBranchBoundary4 = _slicedToArray(_getBranchBoundary3, 4);
  35908. var min2 = _getBranchBoundary4[0];
  35909. var max2 = _getBranchBoundary4[1];
  35910. var minSpace2 = _getBranchBoundary4[2];
  35911. var maxSpace2 = _getBranchBoundary4[3];
  35912. //console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id, getBranchBoundary(branchNodes2, maxLevel), maxLevel);
  35913. var diffBranch = Math.abs(max1 - min2);
  35914. if (diffBranch > _this2.options.hierarchical.nodeSpacing) {
  35915. var offset = max1 - min2 + _this2.options.hierarchical.nodeSpacing;
  35916. if (offset < -minSpace2 + _this2.options.hierarchical.nodeSpacing) {
  35917. offset = -minSpace2 + _this2.options.hierarchical.nodeSpacing;
  35918. //console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
  35919. }
  35920. if (offset < 0) {
  35921. //console.log("SHIFTING", node2.id, offset);
  35922. _this2._shiftBlock(node2.id, offset);
  35923. stillShifting = true;
  35924. if (centerParent === true) _this2._centerParent(node2);
  35925. }
  35926. }
  35927. }
  35928. //this.body.emitter.emit("_redraw");})
  35929. };
  35930. var minimizeEdgeLength = function minimizeEdgeLength(iterations, node) {
  35931. //window.CALLBACKS.push(() => {
  35932. // console.log("ts",node.id);
  35933. var nodeId = node.id;
  35934. var allEdges = node.edges;
  35935. var nodeLevel = _this2.hierarchicalLevels[node.id];
  35936. // gather constants
  35937. var C2 = _this2.options.hierarchical.levelSeparation * _this2.options.hierarchical.levelSeparation;
  35938. var referenceNodes = {};
  35939. var aboveEdges = [];
  35940. for (var i = 0; i < allEdges.length; i++) {
  35941. var edge = allEdges[i];
  35942. if (edge.toId != edge.fromId) {
  35943. var otherNode = edge.toId == nodeId ? edge.from : edge.to;
  35944. referenceNodes[allEdges[i].id] = otherNode;
  35945. if (_this2.hierarchicalLevels[otherNode.id] < nodeLevel) {
  35946. aboveEdges.push(edge);
  35947. }
  35948. }
  35949. }
  35950. // differentiated sum of lengths based on only moving one node over one axis
  35951. var getFx = function getFx(point, edges) {
  35952. var sum = 0;
  35953. for (var _i2 = 0; _i2 < edges.length; _i2++) {
  35954. if (referenceNodes[edges[_i2].id] !== undefined) {
  35955. var a = _this2._getPositionForHierarchy(referenceNodes[edges[_i2].id]) - point;
  35956. sum += a / Math.sqrt(a * a + C2);
  35957. }
  35958. }
  35959. return sum;
  35960. };
  35961. // doubly differentiated sum of lengths based on only moving one node over one axis
  35962. var getDFx = function getDFx(point, edges) {
  35963. var sum = 0;
  35964. for (var _i3 = 0; _i3 < edges.length; _i3++) {
  35965. if (referenceNodes[edges[_i3].id] !== undefined) {
  35966. var a = _this2._getPositionForHierarchy(referenceNodes[edges[_i3].id]) - point;
  35967. sum -= C2 * Math.pow(a * a + C2, -1.5);
  35968. }
  35969. }
  35970. return sum;
  35971. };
  35972. var getGuess = function getGuess(iterations, edges) {
  35973. var guess = _this2._getPositionForHierarchy(node);
  35974. // Newton's method for optimization
  35975. var guessMap = {};
  35976. for (var _i4 = 0; _i4 < iterations; _i4++) {
  35977. var fx = getFx(guess, edges);
  35978. var dfx = getDFx(guess, edges);
  35979. // we limit the movement to avoid instability.
  35980. var limit = 40;
  35981. var ratio = Math.max(-limit, Math.min(limit, Math.round(fx / dfx)));
  35982. guess = guess - ratio;
  35983. // reduce duplicates
  35984. if (guessMap[guess] !== undefined) {
  35985. break;
  35986. }
  35987. guessMap[guess] = _i4;
  35988. }
  35989. return guess;
  35990. };
  35991. var moveBranch = function moveBranch(guess) {
  35992. // position node if there is space
  35993. var nodePosition = _this2._getPositionForHierarchy(node);
  35994. // check movable area of the branch
  35995. if (branches[node.id] === undefined) {
  35996. var branchNodes = {};
  35997. branchNodes[node.id] = true;
  35998. getBranchNodes(node, branchNodes);
  35999. branches[node.id] = branchNodes;
  36000. }
  36001. var _getBranchBoundary5 = getBranchBoundary(branches[node.id]);
  36002. var _getBranchBoundary6 = _slicedToArray(_getBranchBoundary5, 4);
  36003. var minBranch = _getBranchBoundary6[0];
  36004. var maxBranch = _getBranchBoundary6[1];
  36005. var minSpaceBranch = _getBranchBoundary6[2];
  36006. var maxSpaceBranch = _getBranchBoundary6[3];
  36007. var diff = guess - nodePosition;
  36008. // check if we are allowed to move the node:
  36009. var branchOffset = 0;
  36010. if (diff > 0) {
  36011. branchOffset = Math.min(diff, maxSpaceBranch - _this2.options.hierarchical.nodeSpacing);
  36012. } else if (diff < 0) {
  36013. branchOffset = -Math.min(-diff, minSpaceBranch - _this2.options.hierarchical.nodeSpacing);
  36014. }
  36015. if (branchOffset != 0) {
  36016. //console.log("moving branch:",branchOffset, maxSpaceBranch, minSpaceBranch)
  36017. _this2._shiftBlock(node.id, branchOffset);
  36018. //this.body.emitter.emit("_redraw");
  36019. stillShifting = true;
  36020. }
  36021. };
  36022. var moveNode = function moveNode(guess) {
  36023. var nodePosition = _this2._getPositionForHierarchy(node);
  36024. // position node if there is space
  36025. var _getSpaceAroundNode4 = _this2._getSpaceAroundNode(node);
  36026. var _getSpaceAroundNode5 = _slicedToArray(_getSpaceAroundNode4, 2);
  36027. var minSpace = _getSpaceAroundNode5[0];
  36028. var maxSpace = _getSpaceAroundNode5[1];
  36029. var diff = guess - nodePosition;
  36030. // check if we are allowed to move the node:
  36031. var newPosition = nodePosition;
  36032. if (diff > 0) {
  36033. newPosition = Math.min(nodePosition + (maxSpace - _this2.options.hierarchical.nodeSpacing), guess);
  36034. } else if (diff < 0) {
  36035. newPosition = Math.max(nodePosition - (minSpace - _this2.options.hierarchical.nodeSpacing), guess);
  36036. }
  36037. if (newPosition !== nodePosition) {
  36038. //console.log("moving Node:",diff, minSpace, maxSpace);
  36039. _this2._setPositionForHierarchy(node, newPosition, undefined, true);
  36040. //this.body.emitter.emit("_redraw");
  36041. stillShifting = true;
  36042. }
  36043. };
  36044. var guess = getGuess(iterations, aboveEdges);
  36045. moveBranch(guess);
  36046. guess = getGuess(iterations, allEdges);
  36047. moveNode(guess);
  36048. //})
  36049. };
  36050. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  36051. var minimizeEdgeLengthBottomUp = function minimizeEdgeLengthBottomUp(iterations) {
  36052. var levels = Object.keys(_this2.distributionOrdering);
  36053. levels = levels.reverse();
  36054. for (var i = 0; i < iterations; i++) {
  36055. stillShifting = false;
  36056. for (var j = 0; j < levels.length; j++) {
  36057. var level = levels[j];
  36058. var levelNodes = _this2.distributionOrdering[level];
  36059. for (var k = 0; k < levelNodes.length; k++) {
  36060. minimizeEdgeLength(1000, levelNodes[k]);
  36061. }
  36062. }
  36063. if (stillShifting !== true) {
  36064. //console.log("FINISHED minimizeEdgeLengthBottomUp IN " + i);
  36065. break;
  36066. }
  36067. }
  36068. };
  36069. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  36070. var shiftBranchesCloserBottomUp = function shiftBranchesCloserBottomUp(iterations) {
  36071. var levels = Object.keys(_this2.distributionOrdering);
  36072. levels = levels.reverse();
  36073. for (var i = 0; i < iterations; i++) {
  36074. stillShifting = false;
  36075. shiftElementsCloser(branchShiftCallback, levels, true);
  36076. if (stillShifting !== true) {
  36077. //console.log("FINISHED shiftBranchesCloserBottomUp IN " + (i+1));
  36078. break;
  36079. }
  36080. }
  36081. };
  36082. // center all parents
  36083. var centerAllParents = function centerAllParents() {
  36084. for (var nodeId in _this2.body.nodes) {
  36085. if (_this2.body.nodes.hasOwnProperty(nodeId)) _this2._centerParent(_this2.body.nodes[nodeId]);
  36086. }
  36087. };
  36088. // center all parents
  36089. var centerAllParentsBottomUp = function centerAllParentsBottomUp() {
  36090. var levels = Object.keys(_this2.distributionOrdering);
  36091. levels = levels.reverse();
  36092. for (var i = 0; i < levels.length; i++) {
  36093. var level = levels[i];
  36094. var levelNodes = _this2.distributionOrdering[level];
  36095. for (var j = 0; j < levelNodes.length; j++) {
  36096. _this2._centerParent(levelNodes[j]);
  36097. }
  36098. }
  36099. };
  36100. // the actual work is done here.
  36101. if (this.options.hierarchical.blockShifting === true) {
  36102. shiftBranchesCloserBottomUp(5);
  36103. centerAllParents();
  36104. }
  36105. // minimize edge length
  36106. if (this.options.hierarchical.edgeMinimization === true) {
  36107. minimizeEdgeLengthBottomUp(20);
  36108. }
  36109. if (this.options.hierarchical.parentCentralization === true) {
  36110. centerAllParentsBottomUp();
  36111. }
  36112. shiftTrees();
  36113. }
  36114. /**
  36115. * This gives the space around the node. IF a map is supplied, it will only check against nodes NOT in the map.
  36116. * This is used to only get the distances to nodes outside of a branch.
  36117. * @param node
  36118. * @param map
  36119. * @returns {*[]}
  36120. * @private
  36121. */
  36122. }, {
  36123. key: '_getSpaceAroundNode',
  36124. value: function _getSpaceAroundNode(node, map) {
  36125. var useMap = true;
  36126. if (map === undefined) {
  36127. useMap = false;
  36128. }
  36129. var level = this.hierarchicalLevels[node.id];
  36130. if (level !== undefined) {
  36131. var index = this.distributionIndex[node.id];
  36132. var position = this._getPositionForHierarchy(node);
  36133. var minSpace = 1e9;
  36134. var maxSpace = 1e9;
  36135. if (index !== 0) {
  36136. var prevNode = this.distributionOrdering[level][index - 1];
  36137. if (useMap === true && map[prevNode.id] === undefined || useMap === false) {
  36138. var prevPos = this._getPositionForHierarchy(prevNode);
  36139. minSpace = position - prevPos;
  36140. }
  36141. }
  36142. if (index != this.distributionOrdering[level].length - 1) {
  36143. var nextNode = this.distributionOrdering[level][index + 1];
  36144. if (useMap === true && map[nextNode.id] === undefined || useMap === false) {
  36145. var nextPos = this._getPositionForHierarchy(nextNode);
  36146. maxSpace = Math.min(maxSpace, nextPos - position);
  36147. }
  36148. }
  36149. return [minSpace, maxSpace];
  36150. } else {
  36151. return [0, 0];
  36152. }
  36153. }
  36154. /**
  36155. * We use this method to center a parent node and check if it does not cross other nodes when it does.
  36156. * @param node
  36157. * @private
  36158. */
  36159. }, {
  36160. key: '_centerParent',
  36161. value: function _centerParent(node) {
  36162. if (this.hierarchicalParentReference[node.id]) {
  36163. var parents = this.hierarchicalParentReference[node.id];
  36164. for (var i = 0; i < parents.length; i++) {
  36165. var parentId = parents[i];
  36166. var parentNode = this.body.nodes[parentId];
  36167. if (this.hierarchicalChildrenReference[parentId]) {
  36168. // get the range of the children
  36169. var minPos = 1e9;
  36170. var maxPos = -1e9;
  36171. var children = this.hierarchicalChildrenReference[parentId];
  36172. if (children.length > 0) {
  36173. for (var _i5 = 0; _i5 < children.length; _i5++) {
  36174. var childNode = this.body.nodes[children[_i5]];
  36175. minPos = Math.min(minPos, this._getPositionForHierarchy(childNode));
  36176. maxPos = Math.max(maxPos, this._getPositionForHierarchy(childNode));
  36177. }
  36178. }
  36179. var position = this._getPositionForHierarchy(parentNode);
  36180. var _getSpaceAroundNode6 = this._getSpaceAroundNode(parentNode);
  36181. var _getSpaceAroundNode7 = _slicedToArray(_getSpaceAroundNode6, 2);
  36182. var minSpace = _getSpaceAroundNode7[0];
  36183. var maxSpace = _getSpaceAroundNode7[1];
  36184. var newPosition = 0.5 * (minPos + maxPos);
  36185. var diff = position - newPosition;
  36186. if (diff < 0 && Math.abs(diff) < maxSpace - this.options.hierarchical.nodeSpacing || diff > 0 && Math.abs(diff) < minSpace - this.options.hierarchical.nodeSpacing) {
  36187. this._setPositionForHierarchy(parentNode, newPosition, undefined, true);
  36188. }
  36189. }
  36190. }
  36191. }
  36192. }
  36193. /**
  36194. * This function places the nodes on the canvas based on the hierarchial distribution.
  36195. *
  36196. * @param {Object} distribution | obtained by the function this._getDistribution()
  36197. * @private
  36198. */
  36199. }, {
  36200. key: '_placeNodesByHierarchy',
  36201. value: function _placeNodesByHierarchy(distribution) {
  36202. this.positionedNodes = {};
  36203. // start placing all the level 0 nodes first. Then recursively position their branches.
  36204. for (var level in distribution) {
  36205. if (distribution.hasOwnProperty(level)) {
  36206. // sort nodes in level by position:
  36207. var nodeArray = Object.keys(distribution[level]);
  36208. nodeArray = this._indexArrayToNodes(nodeArray);
  36209. this._sortNodeArray(nodeArray);
  36210. var handledNodeCount = 0;
  36211. for (var i = 0; i < nodeArray.length; i++) {
  36212. var node = nodeArray[i];
  36213. if (this.positionedNodes[node.id] === undefined) {
  36214. var pos = this.options.hierarchical.nodeSpacing * handledNodeCount;
  36215. // we get the X or Y values we need and store them in pos and previousPos. The get and set make sure we get X or Y
  36216. if (handledNodeCount > 0) {
  36217. pos = this._getPositionForHierarchy(nodeArray[i - 1]) + this.options.hierarchical.nodeSpacing;
  36218. }
  36219. this._setPositionForHierarchy(node, pos, level);
  36220. this._validataPositionAndContinue(node, level, pos);
  36221. handledNodeCount++;
  36222. }
  36223. }
  36224. }
  36225. }
  36226. }
  36227. /**
  36228. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  36229. * on a X position that ensures there will be no overlap.
  36230. *
  36231. * @param parentId
  36232. * @param parentLevel
  36233. * @private
  36234. */
  36235. }, {
  36236. key: '_placeBranchNodes',
  36237. value: function _placeBranchNodes(parentId, parentLevel) {
  36238. // if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
  36239. if (this.hierarchicalChildrenReference[parentId] === undefined) {
  36240. return;
  36241. }
  36242. // get a list of childNodes
  36243. var childNodes = [];
  36244. for (var i = 0; i < this.hierarchicalChildrenReference[parentId].length; i++) {
  36245. childNodes.push(this.body.nodes[this.hierarchicalChildrenReference[parentId][i]]);
  36246. }
  36247. // use the positions to order the nodes.
  36248. this._sortNodeArray(childNodes);
  36249. // position the childNodes
  36250. for (var _i6 = 0; _i6 < childNodes.length; _i6++) {
  36251. var childNode = childNodes[_i6];
  36252. var childNodeLevel = this.hierarchicalLevels[childNode.id];
  36253. // check if the child node is below the parent node and if it has already been positioned.
  36254. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  36255. // get the amount of space required for this node. If parent the width is based on the amount of children.
  36256. var pos = void 0;
  36257. // we get the X or Y values we need and store them in pos and previousPos. The get and set make sure we get X or Y
  36258. if (_i6 === 0) {
  36259. pos = this._getPositionForHierarchy(this.body.nodes[parentId]);
  36260. } else {
  36261. pos = this._getPositionForHierarchy(childNodes[_i6 - 1]) + this.options.hierarchical.nodeSpacing;
  36262. }
  36263. this._setPositionForHierarchy(childNode, pos, childNodeLevel);
  36264. this._validataPositionAndContinue(childNode, childNodeLevel, pos);
  36265. } else {
  36266. return;
  36267. }
  36268. }
  36269. // center the parent nodes.
  36270. var minPos = 1e9;
  36271. var maxPos = -1e9;
  36272. for (var _i7 = 0; _i7 < childNodes.length; _i7++) {
  36273. var childNodeId = childNodes[_i7].id;
  36274. minPos = Math.min(minPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  36275. maxPos = Math.max(maxPos, this._getPositionForHierarchy(this.body.nodes[childNodeId]));
  36276. }
  36277. this._setPositionForHierarchy(this.body.nodes[parentId], 0.5 * (minPos + maxPos), parentLevel);
  36278. }
  36279. /**
  36280. * This method checks for overlap and if required shifts the branch. It also keeps records of positioned nodes.
  36281. * Finally it will call _placeBranchNodes to place the branch nodes.
  36282. * @param node
  36283. * @param level
  36284. * @param pos
  36285. * @private
  36286. */
  36287. }, {
  36288. key: '_validataPositionAndContinue',
  36289. value: function _validataPositionAndContinue(node, level, pos) {
  36290. // if overlap has been detected, we shift the branch
  36291. if (this.lastNodeOnLevel[level] !== undefined) {
  36292. var previousPos = this._getPositionForHierarchy(this.body.nodes[this.lastNodeOnLevel[level]]);
  36293. if (pos - previousPos < this.options.hierarchical.nodeSpacing) {
  36294. var diff = previousPos + this.options.hierarchical.nodeSpacing - pos;
  36295. var sharedParent = this._findCommonParent(this.lastNodeOnLevel[level], node.id);
  36296. this._shiftBlock(sharedParent.withChild, diff);
  36297. }
  36298. }
  36299. // store change in position.
  36300. this.lastNodeOnLevel[level] = node.id;
  36301. this.positionedNodes[node.id] = true;
  36302. this._placeBranchNodes(node.id, level);
  36303. }
  36304. /**
  36305. * Receives an array with node indices and returns an array with the actual node references. Used for sorting based on
  36306. * node properties.
  36307. * @param idArray
  36308. */
  36309. }, {
  36310. key: '_indexArrayToNodes',
  36311. value: function _indexArrayToNodes(idArray) {
  36312. var array = [];
  36313. for (var i = 0; i < idArray.length; i++) {
  36314. array.push(this.body.nodes[idArray[i]]);
  36315. }
  36316. return array;
  36317. }
  36318. /**
  36319. * This function get the distribution of levels based on hubsize
  36320. *
  36321. * @returns {Object}
  36322. * @private
  36323. */
  36324. }, {
  36325. key: '_getDistribution',
  36326. value: function _getDistribution() {
  36327. var distribution = {};
  36328. var nodeId = void 0,
  36329. node = void 0;
  36330. // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
  36331. // the fix of X is removed after the x value has been set.
  36332. for (nodeId in this.body.nodes) {
  36333. if (this.body.nodes.hasOwnProperty(nodeId)) {
  36334. node = this.body.nodes[nodeId];
  36335. var level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  36336. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  36337. node.y = this.options.hierarchical.levelSeparation * level;
  36338. node.options.fixed.y = true;
  36339. } else {
  36340. node.x = this.options.hierarchical.levelSeparation * level;
  36341. node.options.fixed.x = true;
  36342. }
  36343. if (distribution[level] === undefined) {
  36344. distribution[level] = {};
  36345. }
  36346. distribution[level][nodeId] = node;
  36347. }
  36348. }
  36349. return distribution;
  36350. }
  36351. /**
  36352. * Get the hubsize from all remaining unlevelled nodes.
  36353. *
  36354. * @returns {number}
  36355. * @private
  36356. */
  36357. }, {
  36358. key: '_getHubSize',
  36359. value: function _getHubSize() {
  36360. var hubSize = 0;
  36361. for (var nodeId in this.body.nodes) {
  36362. if (this.body.nodes.hasOwnProperty(nodeId)) {
  36363. var node = this.body.nodes[nodeId];
  36364. if (this.hierarchicalLevels[nodeId] === undefined) {
  36365. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  36366. }
  36367. }
  36368. }
  36369. return hubSize;
  36370. }
  36371. /**
  36372. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  36373. *
  36374. * @param hubsize
  36375. * @private
  36376. */
  36377. }, {
  36378. key: '_determineLevelsByHubsize',
  36379. value: function _determineLevelsByHubsize() {
  36380. var _this3 = this;
  36381. var hubSize = 1;
  36382. var levelDownstream = function levelDownstream(nodeA, nodeB) {
  36383. if (_this3.hierarchicalLevels[nodeB.id] === undefined) {
  36384. // set initial level
  36385. if (_this3.hierarchicalLevels[nodeA.id] === undefined) {
  36386. _this3.hierarchicalLevels[nodeA.id] = 0;
  36387. }
  36388. // set level
  36389. _this3.hierarchicalLevels[nodeB.id] = _this3.hierarchicalLevels[nodeA.id] + 1;
  36390. }
  36391. };
  36392. while (hubSize > 0) {
  36393. // determine hubs
  36394. hubSize = this._getHubSize();
  36395. if (hubSize === 0) break;
  36396. for (var nodeId in this.body.nodes) {
  36397. if (this.body.nodes.hasOwnProperty(nodeId)) {
  36398. var node = this.body.nodes[nodeId];
  36399. if (node.edges.length === hubSize) {
  36400. this._crawlNetwork(levelDownstream, nodeId);
  36401. }
  36402. }
  36403. }
  36404. }
  36405. }
  36406. /**
  36407. * TODO: release feature
  36408. * @private
  36409. */
  36410. }, {
  36411. key: '_determineLevelsCustomCallback',
  36412. value: function _determineLevelsCustomCallback() {
  36413. var _this4 = this;
  36414. var minLevel = 100000;
  36415. // TODO: this should come from options.
  36416. var customCallback = function customCallback(nodeA, nodeB, edge) {};
  36417. var levelByDirection = function levelByDirection(nodeA, nodeB, edge) {
  36418. var levelA = _this4.hierarchicalLevels[nodeA.id];
  36419. // set initial level
  36420. if (levelA === undefined) {
  36421. _this4.hierarchicalLevels[nodeA.id] = minLevel;
  36422. }
  36423. var diff = customCallback(_NetworkUtil2.default.cloneOptions(nodeA, 'node'), _NetworkUtil2.default.cloneOptions(nodeB, 'node'), _NetworkUtil2.default.cloneOptions(edge, 'edge'));
  36424. _this4.hierarchicalLevels[nodeB.id] = _this4.hierarchicalLevels[nodeA.id] + diff;
  36425. };
  36426. this._crawlNetwork(levelByDirection);
  36427. this._setMinLevelToZero();
  36428. }
  36429. /**
  36430. * this function allocates nodes in levels based on the direction of the edges
  36431. *
  36432. * @param hubsize
  36433. * @private
  36434. */
  36435. }, {
  36436. key: '_determineLevelsDirected',
  36437. value: function _determineLevelsDirected() {
  36438. var _this5 = this;
  36439. var minLevel = 10000;
  36440. var levelByDirection = function levelByDirection(nodeA, nodeB, edge) {
  36441. var levelA = _this5.hierarchicalLevels[nodeA.id];
  36442. // set initial level
  36443. if (levelA === undefined) {
  36444. _this5.hierarchicalLevels[nodeA.id] = minLevel;
  36445. }
  36446. if (edge.toId == nodeB.id) {
  36447. _this5.hierarchicalLevels[nodeB.id] = _this5.hierarchicalLevels[nodeA.id] + 1;
  36448. } else {
  36449. _this5.hierarchicalLevels[nodeB.id] = _this5.hierarchicalLevels[nodeA.id] - 1;
  36450. }
  36451. };
  36452. this._crawlNetwork(levelByDirection);
  36453. this._setMinLevelToZero();
  36454. }
  36455. /**
  36456. * Small util method to set the minimum levels of the nodes to zero.
  36457. * @private
  36458. */
  36459. }, {
  36460. key: '_setMinLevelToZero',
  36461. value: function _setMinLevelToZero() {
  36462. var minLevel = 1e9;
  36463. // get the minimum level
  36464. for (var nodeId in this.body.nodes) {
  36465. if (this.body.nodes.hasOwnProperty(nodeId)) {
  36466. if (this.hierarchicalLevels[nodeId] !== undefined) {
  36467. minLevel = Math.min(this.hierarchicalLevels[nodeId], minLevel);
  36468. }
  36469. }
  36470. }
  36471. // subtract the minimum from the set so we have a range starting from 0
  36472. for (var _nodeId2 in this.body.nodes) {
  36473. if (this.body.nodes.hasOwnProperty(_nodeId2)) {
  36474. if (this.hierarchicalLevels[_nodeId2] !== undefined) {
  36475. this.hierarchicalLevels[_nodeId2] -= minLevel;
  36476. }
  36477. }
  36478. }
  36479. }
  36480. /**
  36481. * Update the bookkeeping of parent and child.
  36482. * @private
  36483. */
  36484. }, {
  36485. key: '_generateMap',
  36486. value: function _generateMap() {
  36487. var _this6 = this;
  36488. var fillInRelations = function fillInRelations(parentNode, childNode) {
  36489. if (_this6.hierarchicalLevels[childNode.id] > _this6.hierarchicalLevels[parentNode.id]) {
  36490. var parentNodeId = parentNode.id;
  36491. var childNodeId = childNode.id;
  36492. if (_this6.hierarchicalChildrenReference[parentNodeId] === undefined) {
  36493. _this6.hierarchicalChildrenReference[parentNodeId] = [];
  36494. }
  36495. _this6.hierarchicalChildrenReference[parentNodeId].push(childNodeId);
  36496. if (_this6.hierarchicalParentReference[childNodeId] === undefined) {
  36497. _this6.hierarchicalParentReference[childNodeId] = [];
  36498. }
  36499. _this6.hierarchicalParentReference[childNodeId].push(parentNodeId);
  36500. }
  36501. };
  36502. this._crawlNetwork(fillInRelations);
  36503. }
  36504. /**
  36505. * Crawl over the entire network and use a callback on each node couple that is connected to each other.
  36506. * @param callback | will receive nodeA nodeB and the connecting edge. A and B are unique.
  36507. * @param startingNodeId
  36508. * @private
  36509. */
  36510. }, {
  36511. key: '_crawlNetwork',
  36512. value: function _crawlNetwork() {
  36513. var _this7 = this;
  36514. var callback = arguments.length <= 0 || arguments[0] === undefined ? function () {} : arguments[0];
  36515. var startingNodeId = arguments[1];
  36516. var progress = {};
  36517. var treeIndex = 0;
  36518. var crawler = function crawler(node, tree) {
  36519. if (progress[node.id] === undefined) {
  36520. if (_this7.hierarchicalTrees[node.id] === undefined) {
  36521. _this7.hierarchicalTrees[node.id] = tree;
  36522. _this7.treeIndex = Math.max(tree, _this7.treeIndex);
  36523. }
  36524. progress[node.id] = true;
  36525. var childNode = void 0;
  36526. for (var i = 0; i < node.edges.length; i++) {
  36527. if (node.edges[i].connected === true) {
  36528. if (node.edges[i].toId === node.id) {
  36529. childNode = node.edges[i].from;
  36530. } else {
  36531. childNode = node.edges[i].to;
  36532. }
  36533. if (node.id !== childNode.id) {
  36534. callback(node, childNode, node.edges[i]);
  36535. crawler(childNode, tree);
  36536. }
  36537. }
  36538. }
  36539. }
  36540. };
  36541. // we can crawl from a specific node or over all nodes.
  36542. if (startingNodeId === undefined) {
  36543. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  36544. var node = this.body.nodes[this.body.nodeIndices[i]];
  36545. if (progress[node.id] === undefined) {
  36546. crawler(node, treeIndex);
  36547. treeIndex += 1;
  36548. }
  36549. }
  36550. } else {
  36551. var _node = this.body.nodes[startingNodeId];
  36552. if (_node === undefined) {
  36553. console.error("Node not found:", startingNodeId);
  36554. return;
  36555. }
  36556. crawler(_node);
  36557. }
  36558. }
  36559. /**
  36560. * Shift a branch a certain distance
  36561. * @param parentId
  36562. * @param diff
  36563. * @private
  36564. */
  36565. }, {
  36566. key: '_shiftBlock',
  36567. value: function _shiftBlock(parentId, diff) {
  36568. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  36569. this.body.nodes[parentId].x += diff;
  36570. } else {
  36571. this.body.nodes[parentId].y += diff;
  36572. }
  36573. if (this.hierarchicalChildrenReference[parentId] !== undefined) {
  36574. for (var i = 0; i < this.hierarchicalChildrenReference[parentId].length; i++) {
  36575. this._shiftBlock(this.hierarchicalChildrenReference[parentId][i], diff);
  36576. }
  36577. }
  36578. }
  36579. /**
  36580. * Find a common parent between branches.
  36581. * @param childA
  36582. * @param childB
  36583. * @returns {{foundParent, withChild}}
  36584. * @private
  36585. */
  36586. }, {
  36587. key: '_findCommonParent',
  36588. value: function _findCommonParent(childA, childB) {
  36589. var _this8 = this;
  36590. var parents = {};
  36591. var iterateParents = function iterateParents(parents, child) {
  36592. if (_this8.hierarchicalParentReference[child] !== undefined) {
  36593. for (var i = 0; i < _this8.hierarchicalParentReference[child].length; i++) {
  36594. var parent = _this8.hierarchicalParentReference[child][i];
  36595. parents[parent] = true;
  36596. iterateParents(parents, parent);
  36597. }
  36598. }
  36599. };
  36600. var findParent = function findParent(parents, child) {
  36601. if (_this8.hierarchicalParentReference[child] !== undefined) {
  36602. for (var i = 0; i < _this8.hierarchicalParentReference[child].length; i++) {
  36603. var parent = _this8.hierarchicalParentReference[child][i];
  36604. if (parents[parent] !== undefined) {
  36605. return { foundParent: parent, withChild: child };
  36606. }
  36607. var branch = findParent(parents, parent);
  36608. if (branch.foundParent !== null) {
  36609. return branch;
  36610. }
  36611. }
  36612. }
  36613. return { foundParent: null, withChild: child };
  36614. };
  36615. iterateParents(parents, childA);
  36616. return findParent(parents, childB);
  36617. }
  36618. /**
  36619. * Abstract the getting of the position so we won't have to repeat the check for direction all the time
  36620. * @param node
  36621. * @param position
  36622. * @param level
  36623. * @private
  36624. */
  36625. }, {
  36626. key: '_setPositionForHierarchy',
  36627. value: function _setPositionForHierarchy(node, position, level) {
  36628. var doNotUpdate = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
  36629. //console.log('_setPositionForHierarchy',node.id, position)
  36630. if (doNotUpdate !== true) {
  36631. if (this.distributionOrdering[level] === undefined) {
  36632. this.distributionOrdering[level] = [];
  36633. this.distributionOrderingPresence[level] = {};
  36634. }
  36635. if (this.distributionOrderingPresence[level][node.id] === undefined) {
  36636. this.distributionOrdering[level].push(node);
  36637. this.distributionIndex[node.id] = this.distributionOrdering[level].length - 1;
  36638. }
  36639. this.distributionOrderingPresence[level][node.id] = true;
  36640. }
  36641. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  36642. node.x = position;
  36643. } else {
  36644. node.y = position;
  36645. }
  36646. }
  36647. /**
  36648. * Abstract the getting of the position of a node so we do not have to repeat the direction check all the time.
  36649. * @param node
  36650. * @returns {number|*}
  36651. * @private
  36652. */
  36653. }, {
  36654. key: '_getPositionForHierarchy',
  36655. value: function _getPositionForHierarchy(node) {
  36656. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  36657. return node.x;
  36658. } else {
  36659. return node.y;
  36660. }
  36661. }
  36662. /**
  36663. * Use the x or y value to sort the array, allowing users to specify order.
  36664. * @param nodeArray
  36665. * @private
  36666. */
  36667. }, {
  36668. key: '_sortNodeArray',
  36669. value: function _sortNodeArray(nodeArray) {
  36670. if (nodeArray.length > 1) {
  36671. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  36672. nodeArray.sort(function (a, b) {
  36673. return a.x - b.x;
  36674. });
  36675. } else {
  36676. nodeArray.sort(function (a, b) {
  36677. return a.y - b.y;
  36678. });
  36679. }
  36680. }
  36681. }
  36682. }]);
  36683. return LayoutEngine;
  36684. }();
  36685. exports.default = LayoutEngine;
  36686. /***/ },
  36687. /* 113 */
  36688. /***/ function(module, exports, __webpack_require__) {
  36689. 'use strict';
  36690. Object.defineProperty(exports, "__esModule", {
  36691. value: true
  36692. });
  36693. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  36694. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36695. var util = __webpack_require__(1);
  36696. var Hammer = __webpack_require__(20);
  36697. var hammerUtil = __webpack_require__(28);
  36698. /**
  36699. * clears the toolbar div element of children
  36700. *
  36701. * @private
  36702. */
  36703. var ManipulationSystem = function () {
  36704. function ManipulationSystem(body, canvas, selectionHandler) {
  36705. var _this = this;
  36706. _classCallCheck(this, ManipulationSystem);
  36707. this.body = body;
  36708. this.canvas = canvas;
  36709. this.selectionHandler = selectionHandler;
  36710. this.editMode = false;
  36711. this.manipulationDiv = undefined;
  36712. this.editModeDiv = undefined;
  36713. this.closeDiv = undefined;
  36714. this.manipulationHammers = [];
  36715. this.temporaryUIFunctions = {};
  36716. this.temporaryEventFunctions = [];
  36717. this.touchTime = 0;
  36718. this.temporaryIds = { nodes: [], edges: [] };
  36719. this.guiEnabled = false;
  36720. this.inMode = false;
  36721. this.selectedControlNode = undefined;
  36722. this.options = {};
  36723. this.defaultOptions = {
  36724. enabled: false,
  36725. initiallyActive: false,
  36726. addNode: true,
  36727. addEdge: true,
  36728. editNode: undefined,
  36729. editEdge: true,
  36730. deleteNode: true,
  36731. deleteEdge: true,
  36732. controlNodeStyle: {
  36733. shape: 'dot',
  36734. size: 6,
  36735. color: { background: '#ff0000', border: '#3c3c3c', highlight: { background: '#07f968', border: '#3c3c3c' } },
  36736. borderWidth: 2,
  36737. borderWidthSelected: 2
  36738. }
  36739. };
  36740. util.extend(this.options, this.defaultOptions);
  36741. this.body.emitter.on('destroy', function () {
  36742. _this._clean();
  36743. });
  36744. this.body.emitter.on('_dataChanged', this._restore.bind(this));
  36745. this.body.emitter.on('_resetData', this._restore.bind(this));
  36746. }
  36747. /**
  36748. * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes.
  36749. * @private
  36750. */
  36751. _createClass(ManipulationSystem, [{
  36752. key: '_restore',
  36753. value: function _restore() {
  36754. if (this.inMode !== false) {
  36755. if (this.options.initiallyActive === true) {
  36756. this.enableEditMode();
  36757. } else {
  36758. this.disableEditMode();
  36759. }
  36760. }
  36761. }
  36762. /**
  36763. * Set the Options
  36764. * @param options
  36765. */
  36766. }, {
  36767. key: 'setOptions',
  36768. value: function setOptions(options, allOptions, globalOptions) {
  36769. if (allOptions !== undefined) {
  36770. if (allOptions.locale !== undefined) {
  36771. this.options.locale = allOptions.locale;
  36772. } else {
  36773. this.options.locale = globalOptions.locale;
  36774. }
  36775. if (allOptions.locales !== undefined) {
  36776. this.options.locales = allOptions.locales;
  36777. } else {
  36778. this.options.locales = globalOptions.locales;
  36779. }
  36780. }
  36781. if (options !== undefined) {
  36782. if (typeof options === 'boolean') {
  36783. this.options.enabled = options;
  36784. } else {
  36785. this.options.enabled = true;
  36786. util.deepExtend(this.options, options);
  36787. }
  36788. if (this.options.initiallyActive === true) {
  36789. this.editMode = true;
  36790. }
  36791. this._setup();
  36792. }
  36793. }
  36794. /**
  36795. * Enable or disable edit-mode. Draws the DOM required and cleans up after itself.
  36796. *
  36797. * @private
  36798. */
  36799. }, {
  36800. key: 'toggleEditMode',
  36801. value: function toggleEditMode() {
  36802. if (this.editMode === true) {
  36803. this.disableEditMode();
  36804. } else {
  36805. this.enableEditMode();
  36806. }
  36807. }
  36808. }, {
  36809. key: 'enableEditMode',
  36810. value: function enableEditMode() {
  36811. this.editMode = true;
  36812. this._clean();
  36813. if (this.guiEnabled === true) {
  36814. this.manipulationDiv.style.display = 'block';
  36815. this.closeDiv.style.display = 'block';
  36816. this.editModeDiv.style.display = 'none';
  36817. this.showManipulatorToolbar();
  36818. }
  36819. }
  36820. }, {
  36821. key: 'disableEditMode',
  36822. value: function disableEditMode() {
  36823. this.editMode = false;
  36824. this._clean();
  36825. if (this.guiEnabled === true) {
  36826. this.manipulationDiv.style.display = 'none';
  36827. this.closeDiv.style.display = 'none';
  36828. this.editModeDiv.style.display = 'block';
  36829. this._createEditButton();
  36830. }
  36831. }
  36832. /**
  36833. * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  36834. *
  36835. * @private
  36836. */
  36837. }, {
  36838. key: 'showManipulatorToolbar',
  36839. value: function showManipulatorToolbar() {
  36840. // restore the state of any bound functions or events, remove control nodes, restore physics
  36841. this._clean();
  36842. // reset global variables
  36843. this.manipulationDOM = {};
  36844. // if the gui is enabled, draw all elements.
  36845. if (this.guiEnabled === true) {
  36846. // a _restore will hide these menus
  36847. this.editMode = true;
  36848. this.manipulationDiv.style.display = 'block';
  36849. this.closeDiv.style.display = 'block';
  36850. var selectedNodeCount = this.selectionHandler._getSelectedNodeCount();
  36851. var selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
  36852. var selectedTotalCount = selectedNodeCount + selectedEdgeCount;
  36853. var locale = this.options.locales[this.options.locale];
  36854. var needSeperator = false;
  36855. if (this.options.addNode !== false) {
  36856. this._createAddNodeButton(locale);
  36857. needSeperator = true;
  36858. }
  36859. if (this.options.addEdge !== false) {
  36860. if (needSeperator === true) {
  36861. this._createSeperator(1);
  36862. } else {
  36863. needSeperator = true;
  36864. }
  36865. this._createAddEdgeButton(locale);
  36866. }
  36867. if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') {
  36868. if (needSeperator === true) {
  36869. this._createSeperator(2);
  36870. } else {
  36871. needSeperator = true;
  36872. }
  36873. this._createEditNodeButton(locale);
  36874. } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) {
  36875. if (needSeperator === true) {
  36876. this._createSeperator(3);
  36877. } else {
  36878. needSeperator = true;
  36879. }
  36880. this._createEditEdgeButton(locale);
  36881. }
  36882. // remove buttons
  36883. if (selectedTotalCount !== 0) {
  36884. if (selectedNodeCount > 0 && this.options.deleteNode !== false) {
  36885. if (needSeperator === true) {
  36886. this._createSeperator(4);
  36887. }
  36888. this._createDeleteButton(locale);
  36889. } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) {
  36890. if (needSeperator === true) {
  36891. this._createSeperator(4);
  36892. }
  36893. this._createDeleteButton(locale);
  36894. }
  36895. }
  36896. // bind the close button
  36897. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  36898. // refresh this bar based on what has been selected
  36899. this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this));
  36900. }
  36901. // redraw to show any possible changes
  36902. this.body.emitter.emit('_redraw');
  36903. }
  36904. /**
  36905. * Create the toolbar for adding Nodes
  36906. */
  36907. }, {
  36908. key: 'addNodeMode',
  36909. value: function addNodeMode() {
  36910. // when using the gui, enable edit mode if it wasnt already.
  36911. if (this.editMode !== true) {
  36912. this.enableEditMode();
  36913. }
  36914. // restore the state of any bound functions or events, remove control nodes, restore physics
  36915. this._clean();
  36916. this.inMode = 'addNode';
  36917. if (this.guiEnabled === true) {
  36918. var locale = this.options.locales[this.options.locale];
  36919. this.manipulationDOM = {};
  36920. this._createBackButton(locale);
  36921. this._createSeperator();
  36922. this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']);
  36923. // bind the close button
  36924. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  36925. }
  36926. this._temporaryBindEvent('click', this._performAddNode.bind(this));
  36927. }
  36928. /**
  36929. * call the bound function to handle the editing of the node. The node has to be selected.
  36930. */
  36931. }, {
  36932. key: 'editNode',
  36933. value: function editNode() {
  36934. var _this2 = this;
  36935. // when using the gui, enable edit mode if it wasnt already.
  36936. if (this.editMode !== true) {
  36937. this.enableEditMode();
  36938. }
  36939. // restore the state of any bound functions or events, remove control nodes, restore physics
  36940. this._clean();
  36941. var node = this.selectionHandler._getSelectedNode();
  36942. if (node !== undefined) {
  36943. this.inMode = 'editNode';
  36944. if (typeof this.options.editNode === 'function') {
  36945. if (node.isCluster !== true) {
  36946. var data = util.deepExtend({}, node.options, false);
  36947. data.x = node.x;
  36948. data.y = node.y;
  36949. if (this.options.editNode.length === 2) {
  36950. this.options.editNode(data, function (finalizedData) {
  36951. if (finalizedData !== null && finalizedData !== undefined && _this2.inMode === 'editNode') {
  36952. // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
  36953. _this2.body.data.nodes.getDataSet().update(finalizedData);
  36954. }
  36955. _this2.showManipulatorToolbar();
  36956. });
  36957. } else {
  36958. throw new Error('The function for edit does not support two arguments (data, callback)');
  36959. }
  36960. } else {
  36961. alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']);
  36962. }
  36963. } else {
  36964. throw new Error('No function has been configured to handle the editing of nodes.');
  36965. }
  36966. } else {
  36967. this.showManipulatorToolbar();
  36968. }
  36969. }
  36970. /**
  36971. * create the toolbar to connect nodes
  36972. */
  36973. }, {
  36974. key: 'addEdgeMode',
  36975. value: function addEdgeMode() {
  36976. // when using the gui, enable edit mode if it wasnt already.
  36977. if (this.editMode !== true) {
  36978. this.enableEditMode();
  36979. }
  36980. // restore the state of any bound functions or events, remove control nodes, restore physics
  36981. this._clean();
  36982. this.inMode = 'addEdge';
  36983. if (this.guiEnabled === true) {
  36984. var locale = this.options.locales[this.options.locale];
  36985. this.manipulationDOM = {};
  36986. this._createBackButton(locale);
  36987. this._createSeperator();
  36988. this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']);
  36989. // bind the close button
  36990. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  36991. }
  36992. // temporarily overload functions
  36993. this._temporaryBindUI('onTouch', this._handleConnect.bind(this));
  36994. this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this));
  36995. this._temporaryBindUI('onDrag', this._dragControlNode.bind(this));
  36996. this._temporaryBindUI('onRelease', this._finishConnect.bind(this));
  36997. this._temporaryBindUI('onDragStart', function () {});
  36998. this._temporaryBindUI('onHold', function () {});
  36999. }
  37000. /**
  37001. * create the toolbar to edit edges
  37002. */
  37003. }, {
  37004. key: 'editEdgeMode',
  37005. value: function editEdgeMode() {
  37006. var _this3 = this;
  37007. // when using the gui, enable edit mode if it wasn't already.
  37008. if (this.editMode !== true) {
  37009. this.enableEditMode();
  37010. }
  37011. // restore the state of any bound functions or events, remove control nodes, restore physics
  37012. this._clean();
  37013. this.inMode = 'editEdge';
  37014. if (this.guiEnabled === true) {
  37015. var locale = this.options.locales[this.options.locale];
  37016. this.manipulationDOM = {};
  37017. this._createBackButton(locale);
  37018. this._createSeperator();
  37019. this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']);
  37020. // bind the close button
  37021. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  37022. }
  37023. this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0];
  37024. if (this.edgeBeingEditedId !== undefined) {
  37025. (function () {
  37026. var edge = _this3.body.edges[_this3.edgeBeingEditedId];
  37027. // create control nodes
  37028. var controlNodeFrom = _this3._getNewTargetNode(edge.from.x, edge.from.y);
  37029. var controlNodeTo = _this3._getNewTargetNode(edge.to.x, edge.to.y);
  37030. _this3.temporaryIds.nodes.push(controlNodeFrom.id);
  37031. _this3.temporaryIds.nodes.push(controlNodeTo.id);
  37032. _this3.body.nodes[controlNodeFrom.id] = controlNodeFrom;
  37033. _this3.body.nodeIndices.push(controlNodeFrom.id);
  37034. _this3.body.nodes[controlNodeTo.id] = controlNodeTo;
  37035. _this3.body.nodeIndices.push(controlNodeTo.id);
  37036. // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI
  37037. _this3._temporaryBindUI('onTouch', _this3._controlNodeTouch.bind(_this3)); // used to get the position
  37038. _this3._temporaryBindUI('onTap', function () {}); // disabled
  37039. _this3._temporaryBindUI('onHold', function () {}); // disabled
  37040. _this3._temporaryBindUI('onDragStart', _this3._controlNodeDragStart.bind(_this3)); // used to select control node
  37041. _this3._temporaryBindUI('onDrag', _this3._controlNodeDrag.bind(_this3)); // used to drag control node
  37042. _this3._temporaryBindUI('onDragEnd', _this3._controlNodeDragEnd.bind(_this3)); // used to connect or revert control nodes
  37043. _this3._temporaryBindUI('onMouseMove', function () {}); // disabled
  37044. // create function to position control nodes correctly on movement
  37045. // automatically cleaned up because we use the temporary bind
  37046. _this3._temporaryBindEvent('beforeDrawing', function (ctx) {
  37047. var positions = edge.edgeType.findBorderPositions(ctx);
  37048. if (controlNodeFrom.selected === false) {
  37049. controlNodeFrom.x = positions.from.x;
  37050. controlNodeFrom.y = positions.from.y;
  37051. }
  37052. if (controlNodeTo.selected === false) {
  37053. controlNodeTo.x = positions.to.x;
  37054. controlNodeTo.y = positions.to.y;
  37055. }
  37056. });
  37057. _this3.body.emitter.emit('_redraw');
  37058. })();
  37059. } else {
  37060. this.showManipulatorToolbar();
  37061. }
  37062. }
  37063. /**
  37064. * delete everything in the selection
  37065. */
  37066. }, {
  37067. key: 'deleteSelected',
  37068. value: function deleteSelected() {
  37069. var _this4 = this;
  37070. // when using the gui, enable edit mode if it wasnt already.
  37071. if (this.editMode !== true) {
  37072. this.enableEditMode();
  37073. }
  37074. // restore the state of any bound functions or events, remove control nodes, restore physics
  37075. this._clean();
  37076. this.inMode = 'delete';
  37077. var selectedNodes = this.selectionHandler.getSelectedNodes();
  37078. var selectedEdges = this.selectionHandler.getSelectedEdges();
  37079. var deleteFunction = undefined;
  37080. if (selectedNodes.length > 0) {
  37081. for (var i = 0; i < selectedNodes.length; i++) {
  37082. if (this.body.nodes[selectedNodes[i]].isCluster === true) {
  37083. alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']);
  37084. return;
  37085. }
  37086. }
  37087. if (typeof this.options.deleteNode === 'function') {
  37088. deleteFunction = this.options.deleteNode;
  37089. }
  37090. } else if (selectedEdges.length > 0) {
  37091. if (typeof this.options.deleteEdge === 'function') {
  37092. deleteFunction = this.options.deleteEdge;
  37093. }
  37094. }
  37095. if (typeof deleteFunction === 'function') {
  37096. var data = { nodes: selectedNodes, edges: selectedEdges };
  37097. if (deleteFunction.length === 2) {
  37098. deleteFunction(data, function (finalizedData) {
  37099. if (finalizedData !== null && finalizedData !== undefined && _this4.inMode === 'delete') {
  37100. // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
  37101. _this4.body.data.edges.getDataSet().remove(finalizedData.edges);
  37102. _this4.body.data.nodes.getDataSet().remove(finalizedData.nodes);
  37103. _this4.body.emitter.emit('startSimulation');
  37104. _this4.showManipulatorToolbar();
  37105. } else {
  37106. _this4.body.emitter.emit('startSimulation');
  37107. _this4.showManipulatorToolbar();
  37108. }
  37109. });
  37110. } else {
  37111. throw new Error('The function for delete does not support two arguments (data, callback)');
  37112. }
  37113. } else {
  37114. this.body.data.edges.getDataSet().remove(selectedEdges);
  37115. this.body.data.nodes.getDataSet().remove(selectedNodes);
  37116. this.body.emitter.emit('startSimulation');
  37117. this.showManipulatorToolbar();
  37118. }
  37119. }
  37120. //********************************************** PRIVATE ***************************************//
  37121. /**
  37122. * draw or remove the DOM
  37123. * @private
  37124. */
  37125. }, {
  37126. key: '_setup',
  37127. value: function _setup() {
  37128. if (this.options.enabled === true) {
  37129. // Enable the GUI
  37130. this.guiEnabled = true;
  37131. this._createWrappers();
  37132. if (this.editMode === false) {
  37133. this._createEditButton();
  37134. } else {
  37135. this.showManipulatorToolbar();
  37136. }
  37137. } else {
  37138. this._removeManipulationDOM();
  37139. // disable the gui
  37140. this.guiEnabled = false;
  37141. }
  37142. }
  37143. /**
  37144. * create the div overlays that contain the DOM
  37145. * @private
  37146. */
  37147. }, {
  37148. key: '_createWrappers',
  37149. value: function _createWrappers() {
  37150. // load the manipulator HTML elements. All styling done in css.
  37151. if (this.manipulationDiv === undefined) {
  37152. this.manipulationDiv = document.createElement('div');
  37153. this.manipulationDiv.className = 'vis-manipulation';
  37154. if (this.editMode === true) {
  37155. this.manipulationDiv.style.display = 'block';
  37156. } else {
  37157. this.manipulationDiv.style.display = 'none';
  37158. }
  37159. this.canvas.frame.appendChild(this.manipulationDiv);
  37160. }
  37161. // container for the edit button.
  37162. if (this.editModeDiv === undefined) {
  37163. this.editModeDiv = document.createElement('div');
  37164. this.editModeDiv.className = 'vis-edit-mode';
  37165. if (this.editMode === true) {
  37166. this.editModeDiv.style.display = 'none';
  37167. } else {
  37168. this.editModeDiv.style.display = 'block';
  37169. }
  37170. this.canvas.frame.appendChild(this.editModeDiv);
  37171. }
  37172. // container for the close div button
  37173. if (this.closeDiv === undefined) {
  37174. this.closeDiv = document.createElement('div');
  37175. this.closeDiv.className = 'vis-close';
  37176. this.closeDiv.style.display = this.manipulationDiv.style.display;
  37177. this.canvas.frame.appendChild(this.closeDiv);
  37178. }
  37179. }
  37180. /**
  37181. * generate a new target node. Used for creating new edges and editing edges
  37182. * @param x
  37183. * @param y
  37184. * @returns {*}
  37185. * @private
  37186. */
  37187. }, {
  37188. key: '_getNewTargetNode',
  37189. value: function _getNewTargetNode(x, y) {
  37190. var controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle);
  37191. controlNodeStyle.id = 'targetNode' + util.randomUUID();
  37192. controlNodeStyle.hidden = false;
  37193. controlNodeStyle.physics = false;
  37194. controlNodeStyle.x = x;
  37195. controlNodeStyle.y = y;
  37196. // we have to define the bounding box in order for the nodes to be drawn immediately
  37197. var node = this.body.functions.createNode(controlNodeStyle);
  37198. node.shape.boundingBox = { left: x, right: x, top: y, bottom: y };
  37199. return node;
  37200. }
  37201. /**
  37202. * Create the edit button
  37203. */
  37204. }, {
  37205. key: '_createEditButton',
  37206. value: function _createEditButton() {
  37207. // restore everything to it's original state (if applicable)
  37208. this._clean();
  37209. // reset the manipulationDOM
  37210. this.manipulationDOM = {};
  37211. // empty the editModeDiv
  37212. util.recursiveDOMDelete(this.editModeDiv);
  37213. // create the contents for the editMode button
  37214. var locale = this.options.locales[this.options.locale];
  37215. var button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']);
  37216. this.editModeDiv.appendChild(button);
  37217. // bind a hammer listener to the button, calling the function toggleEditMode.
  37218. this._bindHammerToDiv(button, this.toggleEditMode.bind(this));
  37219. }
  37220. /**
  37221. * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
  37222. * @private
  37223. */
  37224. }, {
  37225. key: '_clean',
  37226. value: function _clean() {
  37227. // not in mode
  37228. this.inMode = false;
  37229. // _clean the divs
  37230. if (this.guiEnabled === true) {
  37231. util.recursiveDOMDelete(this.editModeDiv);
  37232. util.recursiveDOMDelete(this.manipulationDiv);
  37233. // removes all the bindings and overloads
  37234. this._cleanManipulatorHammers();
  37235. }
  37236. // remove temporary nodes and edges
  37237. this._cleanupTemporaryNodesAndEdges();
  37238. // restore overloaded UI functions
  37239. this._unbindTemporaryUIs();
  37240. // remove the temporaryEventFunctions
  37241. this._unbindTemporaryEvents();
  37242. // restore the physics if required
  37243. this.body.emitter.emit('restorePhysics');
  37244. }
  37245. /**
  37246. * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
  37247. * @private
  37248. */
  37249. }, {
  37250. key: '_cleanManipulatorHammers',
  37251. value: function _cleanManipulatorHammers() {
  37252. // _clean hammer bindings
  37253. if (this.manipulationHammers.length != 0) {
  37254. for (var i = 0; i < this.manipulationHammers.length; i++) {
  37255. this.manipulationHammers[i].destroy();
  37256. }
  37257. this.manipulationHammers = [];
  37258. }
  37259. }
  37260. /**
  37261. * Remove all DOM elements created by this module.
  37262. * @private
  37263. */
  37264. }, {
  37265. key: '_removeManipulationDOM',
  37266. value: function _removeManipulationDOM() {
  37267. // removes all the bindings and overloads
  37268. this._clean();
  37269. // empty the manipulation divs
  37270. util.recursiveDOMDelete(this.manipulationDiv);
  37271. util.recursiveDOMDelete(this.editModeDiv);
  37272. util.recursiveDOMDelete(this.closeDiv);
  37273. // remove the manipulation divs
  37274. if (this.manipulationDiv) {
  37275. this.canvas.frame.removeChild(this.manipulationDiv);
  37276. }
  37277. if (this.editModeDiv) {
  37278. this.canvas.frame.removeChild(this.editModeDiv);
  37279. }
  37280. if (this.closeDiv) {
  37281. this.canvas.frame.removeChild(this.closeDiv);
  37282. }
  37283. // set the references to undefined
  37284. this.manipulationDiv = undefined;
  37285. this.editModeDiv = undefined;
  37286. this.closeDiv = undefined;
  37287. }
  37288. /**
  37289. * create a seperator line. the index is to differentiate in the manipulation dom
  37290. * @param index
  37291. * @private
  37292. */
  37293. }, {
  37294. key: '_createSeperator',
  37295. value: function _createSeperator() {
  37296. var index = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
  37297. this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div');
  37298. this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line';
  37299. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]);
  37300. }
  37301. // ---------------------- DOM functions for buttons --------------------------//
  37302. }, {
  37303. key: '_createAddNodeButton',
  37304. value: function _createAddNodeButton(locale) {
  37305. var button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']);
  37306. this.manipulationDiv.appendChild(button);
  37307. this._bindHammerToDiv(button, this.addNodeMode.bind(this));
  37308. }
  37309. }, {
  37310. key: '_createAddEdgeButton',
  37311. value: function _createAddEdgeButton(locale) {
  37312. var button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']);
  37313. this.manipulationDiv.appendChild(button);
  37314. this._bindHammerToDiv(button, this.addEdgeMode.bind(this));
  37315. }
  37316. }, {
  37317. key: '_createEditNodeButton',
  37318. value: function _createEditNodeButton(locale) {
  37319. var button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']);
  37320. this.manipulationDiv.appendChild(button);
  37321. this._bindHammerToDiv(button, this.editNode.bind(this));
  37322. }
  37323. }, {
  37324. key: '_createEditEdgeButton',
  37325. value: function _createEditEdgeButton(locale) {
  37326. var button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']);
  37327. this.manipulationDiv.appendChild(button);
  37328. this._bindHammerToDiv(button, this.editEdgeMode.bind(this));
  37329. }
  37330. }, {
  37331. key: '_createDeleteButton',
  37332. value: function _createDeleteButton(locale) {
  37333. if (this.options.rtl) {
  37334. var deleteBtnClass = 'vis-button vis-delete-rtl';
  37335. } else {
  37336. var deleteBtnClass = 'vis-button vis-delete';
  37337. }
  37338. var button = this._createButton('delete', deleteBtnClass, locale['del'] || this.options.locales['en']['del']);
  37339. this.manipulationDiv.appendChild(button);
  37340. this._bindHammerToDiv(button, this.deleteSelected.bind(this));
  37341. }
  37342. }, {
  37343. key: '_createBackButton',
  37344. value: function _createBackButton(locale) {
  37345. var button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']);
  37346. this.manipulationDiv.appendChild(button);
  37347. this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this));
  37348. }
  37349. }, {
  37350. key: '_createButton',
  37351. value: function _createButton(id, className, label) {
  37352. var labelClassName = arguments.length <= 3 || arguments[3] === undefined ? 'vis-label' : arguments[3];
  37353. this.manipulationDOM[id + 'Div'] = document.createElement('div');
  37354. this.manipulationDOM[id + 'Div'].className = className;
  37355. this.manipulationDOM[id + 'Label'] = document.createElement('div');
  37356. this.manipulationDOM[id + 'Label'].className = labelClassName;
  37357. this.manipulationDOM[id + 'Label'].innerHTML = label;
  37358. this.manipulationDOM[id + 'Div'].appendChild(this.manipulationDOM[id + 'Label']);
  37359. return this.manipulationDOM[id + 'Div'];
  37360. }
  37361. }, {
  37362. key: '_createDescription',
  37363. value: function _createDescription(label) {
  37364. this.manipulationDiv.appendChild(this._createButton('description', 'vis-button vis-none', label));
  37365. }
  37366. // -------------------------- End of DOM functions for buttons ------------------------------//
  37367. /**
  37368. * this binds an event until cleanup by the clean functions.
  37369. * @param event
  37370. * @param newFunction
  37371. * @private
  37372. */
  37373. }, {
  37374. key: '_temporaryBindEvent',
  37375. value: function _temporaryBindEvent(event, newFunction) {
  37376. this.temporaryEventFunctions.push({ event: event, boundFunction: newFunction });
  37377. this.body.emitter.on(event, newFunction);
  37378. }
  37379. /**
  37380. * this overrides an UI function until cleanup by the clean function
  37381. * @param UIfunctionName
  37382. * @param newFunction
  37383. * @private
  37384. */
  37385. }, {
  37386. key: '_temporaryBindUI',
  37387. value: function _temporaryBindUI(UIfunctionName, newFunction) {
  37388. if (this.body.eventListeners[UIfunctionName] !== undefined) {
  37389. this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName];
  37390. this.body.eventListeners[UIfunctionName] = newFunction;
  37391. } else {
  37392. throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners)));
  37393. }
  37394. }
  37395. /**
  37396. * Restore the overridden UI functions to their original state.
  37397. *
  37398. * @private
  37399. */
  37400. }, {
  37401. key: '_unbindTemporaryUIs',
  37402. value: function _unbindTemporaryUIs() {
  37403. for (var functionName in this.temporaryUIFunctions) {
  37404. if (this.temporaryUIFunctions.hasOwnProperty(functionName)) {
  37405. this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName];
  37406. delete this.temporaryUIFunctions[functionName];
  37407. }
  37408. }
  37409. this.temporaryUIFunctions = {};
  37410. }
  37411. /**
  37412. * Unbind the events created by _temporaryBindEvent
  37413. * @private
  37414. */
  37415. }, {
  37416. key: '_unbindTemporaryEvents',
  37417. value: function _unbindTemporaryEvents() {
  37418. for (var i = 0; i < this.temporaryEventFunctions.length; i++) {
  37419. var eventName = this.temporaryEventFunctions[i].event;
  37420. var boundFunction = this.temporaryEventFunctions[i].boundFunction;
  37421. this.body.emitter.off(eventName, boundFunction);
  37422. }
  37423. this.temporaryEventFunctions = [];
  37424. }
  37425. /**
  37426. * Bind an hammer instance to a DOM element.
  37427. * @param domElement
  37428. * @param funct
  37429. */
  37430. }, {
  37431. key: '_bindHammerToDiv',
  37432. value: function _bindHammerToDiv(domElement, boundFunction) {
  37433. var hammer = new Hammer(domElement, {});
  37434. hammerUtil.onTouch(hammer, boundFunction);
  37435. this.manipulationHammers.push(hammer);
  37436. }
  37437. /**
  37438. * Neatly clean up temporary edges and nodes
  37439. * @private
  37440. */
  37441. }, {
  37442. key: '_cleanupTemporaryNodesAndEdges',
  37443. value: function _cleanupTemporaryNodesAndEdges() {
  37444. // _clean temporary edges
  37445. for (var i = 0; i < this.temporaryIds.edges.length; i++) {
  37446. this.body.edges[this.temporaryIds.edges[i]].disconnect();
  37447. delete this.body.edges[this.temporaryIds.edges[i]];
  37448. var indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]);
  37449. if (indexTempEdge !== -1) {
  37450. this.body.edgeIndices.splice(indexTempEdge, 1);
  37451. }
  37452. }
  37453. // _clean temporary nodes
  37454. for (var _i = 0; _i < this.temporaryIds.nodes.length; _i++) {
  37455. delete this.body.nodes[this.temporaryIds.nodes[_i]];
  37456. var indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[_i]);
  37457. if (indexTempNode !== -1) {
  37458. this.body.nodeIndices.splice(indexTempNode, 1);
  37459. }
  37460. }
  37461. this.temporaryIds = { nodes: [], edges: [] };
  37462. }
  37463. // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
  37464. /**
  37465. * the touch is used to get the position of the initial click
  37466. * @param event
  37467. * @private
  37468. */
  37469. }, {
  37470. key: '_controlNodeTouch',
  37471. value: function _controlNodeTouch(event) {
  37472. this.selectionHandler.unselectAll();
  37473. this.lastTouch = this.body.functions.getPointer(event.center);
  37474. this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object
  37475. }
  37476. /**
  37477. * the drag start is used to mark one of the control nodes as selected.
  37478. * @param event
  37479. * @private
  37480. */
  37481. }, {
  37482. key: '_controlNodeDragStart',
  37483. value: function _controlNodeDragStart(event) {
  37484. var pointer = this.lastTouch;
  37485. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  37486. var from = this.body.nodes[this.temporaryIds.nodes[0]];
  37487. var to = this.body.nodes[this.temporaryIds.nodes[1]];
  37488. var edge = this.body.edges[this.edgeBeingEditedId];
  37489. this.selectedControlNode = undefined;
  37490. var fromSelect = from.isOverlappingWith(pointerObj);
  37491. var toSelect = to.isOverlappingWith(pointerObj);
  37492. if (fromSelect === true) {
  37493. this.selectedControlNode = from;
  37494. edge.edgeType.from = from;
  37495. } else if (toSelect === true) {
  37496. this.selectedControlNode = to;
  37497. edge.edgeType.to = to;
  37498. }
  37499. // we use the selection to find the node that is being dragged. We explicitly select it here.
  37500. if (this.selectedControlNode !== undefined) {
  37501. this.selectionHandler.selectObject(this.selectedControlNode);
  37502. }
  37503. this.body.emitter.emit('_redraw');
  37504. }
  37505. /**
  37506. * dragging the control nodes or the canvas
  37507. * @param event
  37508. * @private
  37509. */
  37510. }, {
  37511. key: '_controlNodeDrag',
  37512. value: function _controlNodeDrag(event) {
  37513. this.body.emitter.emit('disablePhysics');
  37514. var pointer = this.body.functions.getPointer(event.center);
  37515. var pos = this.canvas.DOMtoCanvas(pointer);
  37516. if (this.selectedControlNode !== undefined) {
  37517. this.selectedControlNode.x = pos.x;
  37518. this.selectedControlNode.y = pos.y;
  37519. } else {
  37520. // if the drag was not started properly because the click started outside the network div, start it now.
  37521. var diffX = pointer.x - this.lastTouch.x;
  37522. var diffY = pointer.y - this.lastTouch.y;
  37523. this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY };
  37524. }
  37525. this.body.emitter.emit('_redraw');
  37526. }
  37527. /**
  37528. * connecting or restoring the control nodes.
  37529. * @param event
  37530. * @private
  37531. */
  37532. }, {
  37533. key: '_controlNodeDragEnd',
  37534. value: function _controlNodeDragEnd(event) {
  37535. var pointer = this.body.functions.getPointer(event.center);
  37536. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  37537. var edge = this.body.edges[this.edgeBeingEditedId];
  37538. // if the node that was dragged is not a control node, return
  37539. if (this.selectedControlNode === undefined) {
  37540. return;
  37541. }
  37542. // we use the selection to find the node that is being dragged. We explicitly DEselect the control node here.
  37543. this.selectionHandler.unselectAll();
  37544. var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  37545. var node = undefined;
  37546. for (var i = overlappingNodeIds.length - 1; i >= 0; i--) {
  37547. if (overlappingNodeIds[i] !== this.selectedControlNode.id) {
  37548. node = this.body.nodes[overlappingNodeIds[i]];
  37549. break;
  37550. }
  37551. }
  37552. // perform the connection
  37553. if (node !== undefined && this.selectedControlNode !== undefined) {
  37554. if (node.isCluster === true) {
  37555. alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
  37556. } else {
  37557. var from = this.body.nodes[this.temporaryIds.nodes[0]];
  37558. if (this.selectedControlNode.id === from.id) {
  37559. this._performEditEdge(node.id, edge.to.id);
  37560. } else {
  37561. this._performEditEdge(edge.from.id, node.id);
  37562. }
  37563. }
  37564. } else {
  37565. edge.updateEdgeType();
  37566. this.body.emitter.emit('restorePhysics');
  37567. }
  37568. this.body.emitter.emit('_redraw');
  37569. }
  37570. // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
  37571. // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
  37572. /**
  37573. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  37574. * to walk the user through the process.
  37575. *
  37576. * @private
  37577. */
  37578. }, {
  37579. key: '_handleConnect',
  37580. value: function _handleConnect(event) {
  37581. // check to avoid double fireing of this function.
  37582. if (new Date().valueOf() - this.touchTime > 100) {
  37583. this.lastTouch = this.body.functions.getPointer(event.center);
  37584. this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object
  37585. var pointer = this.lastTouch;
  37586. var node = this.selectionHandler.getNodeAt(pointer);
  37587. if (node !== undefined) {
  37588. if (node.isCluster === true) {
  37589. alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
  37590. } else {
  37591. // create a node the temporary line can look at
  37592. var targetNode = this._getNewTargetNode(node.x, node.y);
  37593. this.body.nodes[targetNode.id] = targetNode;
  37594. this.body.nodeIndices.push(targetNode.id);
  37595. // create a temporary edge
  37596. var connectionEdge = this.body.functions.createEdge({
  37597. id: 'connectionEdge' + util.randomUUID(),
  37598. from: node.id,
  37599. to: targetNode.id,
  37600. physics: false,
  37601. smooth: {
  37602. enabled: true,
  37603. type: 'continuous',
  37604. roundness: 0.5
  37605. }
  37606. });
  37607. this.body.edges[connectionEdge.id] = connectionEdge;
  37608. this.body.edgeIndices.push(connectionEdge.id);
  37609. this.temporaryIds.nodes.push(targetNode.id);
  37610. this.temporaryIds.edges.push(connectionEdge.id);
  37611. }
  37612. }
  37613. this.touchTime = new Date().valueOf();
  37614. }
  37615. }
  37616. }, {
  37617. key: '_dragControlNode',
  37618. value: function _dragControlNode(event) {
  37619. var pointer = this.body.functions.getPointer(event.center);
  37620. if (this.temporaryIds.nodes[0] !== undefined) {
  37621. var targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode.
  37622. targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  37623. targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  37624. this.body.emitter.emit('_redraw');
  37625. } else {
  37626. var diffX = pointer.x - this.lastTouch.x;
  37627. var diffY = pointer.y - this.lastTouch.y;
  37628. this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY };
  37629. }
  37630. }
  37631. /**
  37632. * Connect the new edge to the target if one exists, otherwise remove temp line
  37633. * @param event
  37634. * @private
  37635. */
  37636. }, {
  37637. key: '_finishConnect',
  37638. value: function _finishConnect(event) {
  37639. var pointer = this.body.functions.getPointer(event.center);
  37640. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  37641. // remember the edge id
  37642. var connectFromId = undefined;
  37643. if (this.temporaryIds.edges[0] !== undefined) {
  37644. connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId;
  37645. }
  37646. // get the overlapping node but NOT the temporary node;
  37647. var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  37648. var node = undefined;
  37649. for (var i = overlappingNodeIds.length - 1; i >= 0; i--) {
  37650. // if the node id is NOT a temporary node, accept the node.
  37651. if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) {
  37652. node = this.body.nodes[overlappingNodeIds[i]];
  37653. break;
  37654. }
  37655. }
  37656. // clean temporary nodes and edges.
  37657. this._cleanupTemporaryNodesAndEdges();
  37658. // perform the connection
  37659. if (node !== undefined) {
  37660. if (node.isCluster === true) {
  37661. alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
  37662. } else {
  37663. if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) {
  37664. this._performAddEdge(connectFromId, node.id);
  37665. }
  37666. }
  37667. }
  37668. this.body.emitter.emit('_redraw');
  37669. }
  37670. // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
  37671. // ------------------------------ Performing all the actual data manipulation ------------------------//
  37672. /**
  37673. * Adds a node on the specified location
  37674. */
  37675. }, {
  37676. key: '_performAddNode',
  37677. value: function _performAddNode(clickData) {
  37678. var _this5 = this;
  37679. var defaultData = {
  37680. id: util.randomUUID(),
  37681. x: clickData.pointer.canvas.x,
  37682. y: clickData.pointer.canvas.y,
  37683. label: 'new'
  37684. };
  37685. if (typeof this.options.addNode === 'function') {
  37686. if (this.options.addNode.length === 2) {
  37687. this.options.addNode(defaultData, function (finalizedData) {
  37688. if (finalizedData !== null && finalizedData !== undefined && _this5.inMode === 'addNode') {
  37689. // if for whatever reason the mode has changes (due to dataset change) disregard the callback
  37690. _this5.body.data.nodes.getDataSet().add(finalizedData);
  37691. _this5.showManipulatorToolbar();
  37692. }
  37693. });
  37694. } else {
  37695. throw new Error('The function for add does not support two arguments (data,callback)');
  37696. this.showManipulatorToolbar();
  37697. }
  37698. } else {
  37699. this.body.data.nodes.getDataSet().add(defaultData);
  37700. this.showManipulatorToolbar();
  37701. }
  37702. }
  37703. /**
  37704. * connect two nodes with a new edge.
  37705. *
  37706. * @private
  37707. */
  37708. }, {
  37709. key: '_performAddEdge',
  37710. value: function _performAddEdge(sourceNodeId, targetNodeId) {
  37711. var _this6 = this;
  37712. var defaultData = { from: sourceNodeId, to: targetNodeId };
  37713. if (typeof this.options.addEdge === 'function') {
  37714. if (this.options.addEdge.length === 2) {
  37715. this.options.addEdge(defaultData, function (finalizedData) {
  37716. if (finalizedData !== null && finalizedData !== undefined && _this6.inMode === 'addEdge') {
  37717. // if for whatever reason the mode has changes (due to dataset change) disregard the callback
  37718. _this6.body.data.edges.getDataSet().add(finalizedData);
  37719. _this6.selectionHandler.unselectAll();
  37720. _this6.showManipulatorToolbar();
  37721. }
  37722. });
  37723. } else {
  37724. throw new Error('The function for connect does not support two arguments (data,callback)');
  37725. }
  37726. } else {
  37727. this.body.data.edges.getDataSet().add(defaultData);
  37728. this.selectionHandler.unselectAll();
  37729. this.showManipulatorToolbar();
  37730. }
  37731. }
  37732. /**
  37733. * connect two nodes with a new edge.
  37734. *
  37735. * @private
  37736. */
  37737. }, {
  37738. key: '_performEditEdge',
  37739. value: function _performEditEdge(sourceNodeId, targetNodeId) {
  37740. var _this7 = this;
  37741. var defaultData = { id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId };
  37742. if (typeof this.options.editEdge === 'function') {
  37743. if (this.options.editEdge.length === 2) {
  37744. this.options.editEdge(defaultData, function (finalizedData) {
  37745. if (finalizedData === null || finalizedData === undefined || _this7.inMode !== 'editEdge') {
  37746. // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
  37747. _this7.body.edges[defaultData.id].updateEdgeType();
  37748. _this7.body.emitter.emit('_redraw');
  37749. } else {
  37750. _this7.body.data.edges.getDataSet().update(finalizedData);
  37751. _this7.selectionHandler.unselectAll();
  37752. _this7.showManipulatorToolbar();
  37753. }
  37754. });
  37755. } else {
  37756. throw new Error('The function for edit does not support two arguments (data, callback)');
  37757. }
  37758. } else {
  37759. this.body.data.edges.getDataSet().update(defaultData);
  37760. this.selectionHandler.unselectAll();
  37761. this.showManipulatorToolbar();
  37762. }
  37763. }
  37764. }]);
  37765. return ManipulationSystem;
  37766. }();
  37767. exports.default = ManipulationSystem;
  37768. /***/ },
  37769. /* 114 */
  37770. /***/ function(module, exports) {
  37771. 'use strict';
  37772. Object.defineProperty(exports, "__esModule", {
  37773. value: true
  37774. });
  37775. /**
  37776. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  37777. * of the allowed values.
  37778. *
  37779. * __any__ means that the name of the property does not matter.
  37780. * __type__ is a required field for all objects and contains the allowed types of all objects
  37781. */
  37782. var string = 'string';
  37783. var boolean = 'boolean';
  37784. var number = 'number';
  37785. var array = 'array';
  37786. var object = 'object'; // should only be in a __type__ property
  37787. var dom = 'dom';
  37788. var any = 'any';
  37789. var allOptions = {
  37790. configure: {
  37791. enabled: { boolean: boolean },
  37792. filter: { boolean: boolean, string: string, array: array, 'function': 'function' },
  37793. container: { dom: dom },
  37794. showButton: { boolean: boolean },
  37795. __type__: { object: object, boolean: boolean, string: string, array: array, 'function': 'function' }
  37796. },
  37797. edges: {
  37798. arrows: {
  37799. to: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } },
  37800. middle: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } },
  37801. from: { enabled: { boolean: boolean }, scaleFactor: { number: number }, __type__: { object: object, boolean: boolean } },
  37802. __type__: { string: ['from', 'to', 'middle'], object: object }
  37803. },
  37804. arrowStrikethrough: { boolean: boolean },
  37805. color: {
  37806. color: { string: string },
  37807. highlight: { string: string },
  37808. hover: { string: string },
  37809. inherit: { string: ['from', 'to', 'both'], boolean: boolean },
  37810. opacity: { number: number },
  37811. __type__: { object: object, string: string }
  37812. },
  37813. dashes: { boolean: boolean, array: array },
  37814. font: {
  37815. color: { string: string },
  37816. size: { number: number }, // px
  37817. face: { string: string },
  37818. background: { string: string },
  37819. strokeWidth: { number: number }, // px
  37820. strokeColor: { string: string },
  37821. align: { string: ['horizontal', 'top', 'middle', 'bottom'] },
  37822. __type__: { object: object, string: string }
  37823. },
  37824. hidden: { boolean: boolean },
  37825. hoverWidth: { 'function': 'function', number: number },
  37826. label: { string: string, 'undefined': 'undefined' },
  37827. labelHighlightBold: { boolean: boolean },
  37828. length: { number: number, 'undefined': 'undefined' },
  37829. physics: { boolean: boolean },
  37830. scaling: {
  37831. min: { number: number },
  37832. max: { number: number },
  37833. label: {
  37834. enabled: { boolean: boolean },
  37835. min: { number: number },
  37836. max: { number: number },
  37837. maxVisible: { number: number },
  37838. drawThreshold: { number: number },
  37839. __type__: { object: object, boolean: boolean }
  37840. },
  37841. customScalingFunction: { 'function': 'function' },
  37842. __type__: { object: object }
  37843. },
  37844. selectionWidth: { 'function': 'function', number: number },
  37845. selfReferenceSize: { number: number },
  37846. shadow: {
  37847. enabled: { boolean: boolean },
  37848. color: { string: string },
  37849. size: { number: number },
  37850. x: { number: number },
  37851. y: { number: number },
  37852. __type__: { object: object, boolean: boolean }
  37853. },
  37854. smooth: {
  37855. enabled: { boolean: boolean },
  37856. type: { string: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW', 'cubicBezier'] },
  37857. roundness: { number: number },
  37858. forceDirection: { string: ['horizontal', 'vertical', 'none'], boolean: boolean },
  37859. __type__: { object: object, boolean: boolean }
  37860. },
  37861. title: { string: string, 'undefined': 'undefined' },
  37862. width: { number: number },
  37863. value: { number: number, 'undefined': 'undefined' },
  37864. __type__: { object: object }
  37865. },
  37866. groups: {
  37867. useDefaultGroups: { boolean: boolean },
  37868. __any__: 'get from nodes, will be overwritten below',
  37869. __type__: { object: object }
  37870. },
  37871. interaction: {
  37872. dragNodes: { boolean: boolean },
  37873. dragView: { boolean: boolean },
  37874. hideEdgesOnDrag: { boolean: boolean },
  37875. hideNodesOnDrag: { boolean: boolean },
  37876. hover: { boolean: boolean },
  37877. keyboard: {
  37878. enabled: { boolean: boolean },
  37879. speed: { x: { number: number }, y: { number: number }, zoom: { number: number }, __type__: { object: object } },
  37880. bindToWindow: { boolean: boolean },
  37881. __type__: { object: object, boolean: boolean }
  37882. },
  37883. multiselect: { boolean: boolean },
  37884. navigationButtons: { boolean: boolean },
  37885. selectable: { boolean: boolean },
  37886. selectConnectedEdges: { boolean: boolean },
  37887. hoverConnectedEdges: { boolean: boolean },
  37888. tooltipDelay: { number: number },
  37889. zoomView: { boolean: boolean },
  37890. __type__: { object: object }
  37891. },
  37892. layout: {
  37893. randomSeed: { 'undefined': 'undefined', number: number },
  37894. improvedLayout: { boolean: boolean },
  37895. hierarchical: {
  37896. enabled: { boolean: boolean },
  37897. levelSeparation: { number: number },
  37898. nodeSpacing: { number: number },
  37899. treeSpacing: { number: number },
  37900. blockShifting: { boolean: boolean },
  37901. edgeMinimization: { boolean: boolean },
  37902. parentCentralization: { boolean: boolean },
  37903. direction: { string: ['UD', 'DU', 'LR', 'RL'] }, // UD, DU, LR, RL
  37904. sortMethod: { string: ['hubsize', 'directed'] }, // hubsize, directed
  37905. __type__: { object: object, boolean: boolean }
  37906. },
  37907. __type__: { object: object }
  37908. },
  37909. manipulation: {
  37910. enabled: { boolean: boolean },
  37911. initiallyActive: { boolean: boolean },
  37912. addNode: { boolean: boolean, 'function': 'function' },
  37913. addEdge: { boolean: boolean, 'function': 'function' },
  37914. editNode: { 'function': 'function' },
  37915. editEdge: { boolean: boolean, 'function': 'function' },
  37916. deleteNode: { boolean: boolean, 'function': 'function' },
  37917. deleteEdge: { boolean: boolean, 'function': 'function' },
  37918. controlNodeStyle: 'get from nodes, will be overwritten below',
  37919. __type__: { object: object, boolean: boolean }
  37920. },
  37921. nodes: {
  37922. borderWidth: { number: number },
  37923. borderWidthSelected: { number: number, 'undefined': 'undefined' },
  37924. brokenImage: { string: string, 'undefined': 'undefined' },
  37925. color: {
  37926. border: { string: string },
  37927. background: { string: string },
  37928. highlight: {
  37929. border: { string: string },
  37930. background: { string: string },
  37931. __type__: { object: object, string: string }
  37932. },
  37933. hover: {
  37934. border: { string: string },
  37935. background: { string: string },
  37936. __type__: { object: object, string: string }
  37937. },
  37938. __type__: { object: object, string: string }
  37939. },
  37940. fixed: {
  37941. x: { boolean: boolean },
  37942. y: { boolean: boolean },
  37943. __type__: { object: object, boolean: boolean }
  37944. },
  37945. font: {
  37946. align: { string: string },
  37947. color: { string: string },
  37948. size: { number: number }, // px
  37949. face: { string: string },
  37950. background: { string: string },
  37951. strokeWidth: { number: number }, // px
  37952. strokeColor: { string: string },
  37953. __type__: { object: object, string: string }
  37954. },
  37955. group: { string: string, number: number, 'undefined': 'undefined' },
  37956. hidden: { boolean: boolean },
  37957. icon: {
  37958. face: { string: string },
  37959. code: { string: string }, //'\uf007',
  37960. size: { number: number }, //50,
  37961. color: { string: string },
  37962. __type__: { object: object }
  37963. },
  37964. id: { string: string, number: number },
  37965. image: { string: string, 'undefined': 'undefined' }, // --> URL
  37966. label: { string: string, 'undefined': 'undefined' },
  37967. labelHighlightBold: { boolean: boolean },
  37968. level: { number: number, 'undefined': 'undefined' },
  37969. mass: { number: number },
  37970. physics: { boolean: boolean },
  37971. scaling: {
  37972. min: { number: number },
  37973. max: { number: number },
  37974. label: {
  37975. enabled: { boolean: boolean },
  37976. min: { number: number },
  37977. max: { number: number },
  37978. maxVisible: { number: number },
  37979. drawThreshold: { number: number },
  37980. __type__: { object: object, boolean: boolean }
  37981. },
  37982. customScalingFunction: { 'function': 'function' },
  37983. __type__: { object: object }
  37984. },
  37985. shadow: {
  37986. enabled: { boolean: boolean },
  37987. color: { string: string },
  37988. size: { number: number },
  37989. x: { number: number },
  37990. y: { number: number },
  37991. __type__: { object: object, boolean: boolean }
  37992. },
  37993. shape: { string: ['ellipse', 'circle', 'database', 'box', 'text', 'image', 'circularImage', 'diamond', 'dot', 'star', 'triangle', 'triangleDown', 'square', 'icon'] },
  37994. shapeProperties: {
  37995. borderDashes: { boolean: boolean, array: array },
  37996. borderRadius: { number: number },
  37997. interpolation: { boolean: boolean },
  37998. useImageSize: { boolean: boolean },
  37999. useBorderWithImage: { boolean: boolean },
  38000. __type__: { object: object }
  38001. },
  38002. size: { number: number },
  38003. title: { string: string, 'undefined': 'undefined' },
  38004. value: { number: number, 'undefined': 'undefined' },
  38005. x: { number: number },
  38006. y: { number: number },
  38007. __type__: { object: object }
  38008. },
  38009. physics: {
  38010. enabled: { boolean: boolean },
  38011. barnesHut: {
  38012. gravitationalConstant: { number: number },
  38013. centralGravity: { number: number },
  38014. springLength: { number: number },
  38015. springConstant: { number: number },
  38016. damping: { number: number },
  38017. avoidOverlap: { number: number },
  38018. __type__: { object: object }
  38019. },
  38020. forceAtlas2Based: {
  38021. gravitationalConstant: { number: number },
  38022. centralGravity: { number: number },
  38023. springLength: { number: number },
  38024. springConstant: { number: number },
  38025. damping: { number: number },
  38026. avoidOverlap: { number: number },
  38027. __type__: { object: object }
  38028. },
  38029. repulsion: {
  38030. centralGravity: { number: number },
  38031. springLength: { number: number },
  38032. springConstant: { number: number },
  38033. nodeDistance: { number: number },
  38034. damping: { number: number },
  38035. __type__: { object: object }
  38036. },
  38037. hierarchicalRepulsion: {
  38038. centralGravity: { number: number },
  38039. springLength: { number: number },
  38040. springConstant: { number: number },
  38041. nodeDistance: { number: number },
  38042. damping: { number: number },
  38043. __type__: { object: object }
  38044. },
  38045. maxVelocity: { number: number },
  38046. minVelocity: { number: number }, // px/s
  38047. solver: { string: ['barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'] },
  38048. stabilization: {
  38049. enabled: { boolean: boolean },
  38050. iterations: { number: number }, // maximum number of iteration to stabilize
  38051. updateInterval: { number: number },
  38052. onlyDynamicEdges: { boolean: boolean },
  38053. fit: { boolean: boolean },
  38054. __type__: { object: object, boolean: boolean }
  38055. },
  38056. timestep: { number: number },
  38057. adaptiveTimestep: { boolean: boolean },
  38058. __type__: { object: object, boolean: boolean }
  38059. },
  38060. //globals :
  38061. autoResize: { boolean: boolean },
  38062. clickToUse: { boolean: boolean },
  38063. locale: { string: string },
  38064. locales: {
  38065. __any__: { any: any },
  38066. __type__: { object: object }
  38067. },
  38068. height: { string: string },
  38069. width: { string: string },
  38070. __type__: { object: object }
  38071. };
  38072. allOptions.groups.__any__ = allOptions.nodes;
  38073. allOptions.manipulation.controlNodeStyle = allOptions.nodes;
  38074. var configureOptions = {
  38075. nodes: {
  38076. borderWidth: [1, 0, 10, 1],
  38077. borderWidthSelected: [2, 0, 10, 1],
  38078. color: {
  38079. border: ['color', '#2B7CE9'],
  38080. background: ['color', '#97C2FC'],
  38081. highlight: {
  38082. border: ['color', '#2B7CE9'],
  38083. background: ['color', '#D2E5FF']
  38084. },
  38085. hover: {
  38086. border: ['color', '#2B7CE9'],
  38087. background: ['color', '#D2E5FF']
  38088. }
  38089. },
  38090. fixed: {
  38091. x: false,
  38092. y: false
  38093. },
  38094. font: {
  38095. color: ['color', '#343434'],
  38096. size: [14, 0, 100, 1], // px
  38097. face: ['arial', 'verdana', 'tahoma'],
  38098. background: ['color', 'none'],
  38099. strokeWidth: [0, 0, 50, 1], // px
  38100. strokeColor: ['color', '#ffffff']
  38101. },
  38102. //group: 'string',
  38103. hidden: false,
  38104. labelHighlightBold: true,
  38105. //icon: {
  38106. // face: 'string', //'FontAwesome',
  38107. // code: 'string', //'\uf007',
  38108. // size: [50, 0, 200, 1], //50,
  38109. // color: ['color','#2B7CE9'] //'#aa00ff'
  38110. //},
  38111. //image: 'string', // --> URL
  38112. physics: true,
  38113. scaling: {
  38114. min: [10, 0, 200, 1],
  38115. max: [30, 0, 200, 1],
  38116. label: {
  38117. enabled: false,
  38118. min: [14, 0, 200, 1],
  38119. max: [30, 0, 200, 1],
  38120. maxVisible: [30, 0, 200, 1],
  38121. drawThreshold: [5, 0, 20, 1]
  38122. }
  38123. },
  38124. shadow: {
  38125. enabled: false,
  38126. color: 'rgba(0,0,0,0.5)',
  38127. size: [10, 0, 20, 1],
  38128. x: [5, -30, 30, 1],
  38129. y: [5, -30, 30, 1]
  38130. },
  38131. shape: ['ellipse', 'box', 'circle', 'database', 'diamond', 'dot', 'square', 'star', 'text', 'triangle', 'triangleDown'],
  38132. shapeProperties: {
  38133. borderDashes: false,
  38134. borderRadius: [6, 0, 20, 1],
  38135. interpolation: true,
  38136. useImageSize: false
  38137. },
  38138. size: [25, 0, 200, 1]
  38139. },
  38140. edges: {
  38141. arrows: {
  38142. to: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1}
  38143. middle: { enabled: false, scaleFactor: [1, 0, 3, 0.05] },
  38144. from: { enabled: false, scaleFactor: [1, 0, 3, 0.05] }
  38145. },
  38146. arrowStrikethrough: true,
  38147. color: {
  38148. color: ['color', '#848484'],
  38149. highlight: ['color', '#848484'],
  38150. hover: ['color', '#848484'],
  38151. inherit: ['from', 'to', 'both', true, false],
  38152. opacity: [1, 0, 1, 0.05]
  38153. },
  38154. dashes: false,
  38155. font: {
  38156. color: ['color', '#343434'],
  38157. size: [14, 0, 100, 1], // px
  38158. face: ['arial', 'verdana', 'tahoma'],
  38159. background: ['color', 'none'],
  38160. strokeWidth: [2, 0, 50, 1], // px
  38161. strokeColor: ['color', '#ffffff'],
  38162. align: ['horizontal', 'top', 'middle', 'bottom']
  38163. },
  38164. hidden: false,
  38165. hoverWidth: [1.5, 0, 5, 0.1],
  38166. labelHighlightBold: true,
  38167. physics: true,
  38168. scaling: {
  38169. min: [1, 0, 100, 1],
  38170. max: [15, 0, 100, 1],
  38171. label: {
  38172. enabled: true,
  38173. min: [14, 0, 200, 1],
  38174. max: [30, 0, 200, 1],
  38175. maxVisible: [30, 0, 200, 1],
  38176. drawThreshold: [5, 0, 20, 1]
  38177. }
  38178. },
  38179. selectionWidth: [1.5, 0, 5, 0.1],
  38180. selfReferenceSize: [20, 0, 200, 1],
  38181. shadow: {
  38182. enabled: false,
  38183. color: 'rgba(0,0,0,0.5)',
  38184. size: [10, 0, 20, 1],
  38185. x: [5, -30, 30, 1],
  38186. y: [5, -30, 30, 1]
  38187. },
  38188. smooth: {
  38189. enabled: true,
  38190. type: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW', 'cubicBezier'],
  38191. forceDirection: ['horizontal', 'vertical', 'none'],
  38192. roundness: [0.5, 0, 1, 0.05]
  38193. },
  38194. width: [1, 0, 30, 1]
  38195. },
  38196. layout: {
  38197. //randomSeed: [0, 0, 500, 1],
  38198. //improvedLayout: true,
  38199. hierarchical: {
  38200. enabled: false,
  38201. levelSeparation: [150, 20, 500, 5],
  38202. nodeSpacing: [100, 20, 500, 5],
  38203. treeSpacing: [200, 20, 500, 5],
  38204. blockShifting: true,
  38205. edgeMinimization: true,
  38206. parentCentralization: true,
  38207. direction: ['UD', 'DU', 'LR', 'RL'], // UD, DU, LR, RL
  38208. sortMethod: ['hubsize', 'directed'] // hubsize, directed
  38209. }
  38210. },
  38211. interaction: {
  38212. dragNodes: true,
  38213. dragView: true,
  38214. hideEdgesOnDrag: false,
  38215. hideNodesOnDrag: false,
  38216. hover: false,
  38217. keyboard: {
  38218. enabled: false,
  38219. speed: { x: [10, 0, 40, 1], y: [10, 0, 40, 1], zoom: [0.02, 0, 0.1, 0.005] },
  38220. bindToWindow: true
  38221. },
  38222. multiselect: false,
  38223. navigationButtons: false,
  38224. selectable: true,
  38225. selectConnectedEdges: true,
  38226. hoverConnectedEdges: true,
  38227. tooltipDelay: [300, 0, 1000, 25],
  38228. zoomView: true
  38229. },
  38230. manipulation: {
  38231. enabled: false,
  38232. initiallyActive: false
  38233. },
  38234. physics: {
  38235. enabled: true,
  38236. barnesHut: {
  38237. //theta: [0.5, 0.1, 1, 0.05],
  38238. gravitationalConstant: [-2000, -30000, 0, 50],
  38239. centralGravity: [0.3, 0, 10, 0.05],
  38240. springLength: [95, 0, 500, 5],
  38241. springConstant: [0.04, 0, 1.2, 0.005],
  38242. damping: [0.09, 0, 1, 0.01],
  38243. avoidOverlap: [0, 0, 1, 0.01]
  38244. },
  38245. forceAtlas2Based: {
  38246. //theta: [0.5, 0.1, 1, 0.05],
  38247. gravitationalConstant: [-50, -500, 0, 1],
  38248. centralGravity: [0.01, 0, 1, 0.005],
  38249. springLength: [95, 0, 500, 5],
  38250. springConstant: [0.08, 0, 1.2, 0.005],
  38251. damping: [0.4, 0, 1, 0.01],
  38252. avoidOverlap: [0, 0, 1, 0.01]
  38253. },
  38254. repulsion: {
  38255. centralGravity: [0.2, 0, 10, 0.05],
  38256. springLength: [200, 0, 500, 5],
  38257. springConstant: [0.05, 0, 1.2, 0.005],
  38258. nodeDistance: [100, 0, 500, 5],
  38259. damping: [0.09, 0, 1, 0.01]
  38260. },
  38261. hierarchicalRepulsion: {
  38262. centralGravity: [0.2, 0, 10, 0.05],
  38263. springLength: [100, 0, 500, 5],
  38264. springConstant: [0.01, 0, 1.2, 0.005],
  38265. nodeDistance: [120, 0, 500, 5],
  38266. damping: [0.09, 0, 1, 0.01]
  38267. },
  38268. maxVelocity: [50, 0, 150, 1],
  38269. minVelocity: [0.1, 0.01, 0.5, 0.01],
  38270. solver: ['barnesHut', 'forceAtlas2Based', 'repulsion', 'hierarchicalRepulsion'],
  38271. timestep: [0.5, 0.01, 1, 0.01]
  38272. },
  38273. //adaptiveTimestep: true
  38274. global: {
  38275. locale: ['en', 'nl']
  38276. }
  38277. };
  38278. exports.allOptions = allOptions;
  38279. exports.configureOptions = configureOptions;
  38280. /***/ },
  38281. /* 115 */
  38282. /***/ function(module, exports, __webpack_require__) {
  38283. "use strict";
  38284. Object.defineProperty(exports, "__esModule", {
  38285. value: true
  38286. });
  38287. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  38288. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // distance finding algorithm
  38289. var _FloydWarshall = __webpack_require__(116);
  38290. var _FloydWarshall2 = _interopRequireDefault(_FloydWarshall);
  38291. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  38292. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  38293. /**
  38294. * KamadaKawai positions the nodes initially based on
  38295. *
  38296. * "AN ALGORITHM FOR DRAWING GENERAL UNDIRECTED GRAPHS"
  38297. * -- Tomihisa KAMADA and Satoru KAWAI in 1989
  38298. *
  38299. * Possible optimizations in the distance calculation can be implemented.
  38300. */
  38301. var KamadaKawai = function () {
  38302. function KamadaKawai(body, edgeLength, edgeStrength) {
  38303. _classCallCheck(this, KamadaKawai);
  38304. this.body = body;
  38305. this.springLength = edgeLength;
  38306. this.springConstant = edgeStrength;
  38307. this.distanceSolver = new _FloydWarshall2.default();
  38308. }
  38309. /**
  38310. * Not sure if needed but can be used to update the spring length and spring constant
  38311. * @param options
  38312. */
  38313. _createClass(KamadaKawai, [{
  38314. key: "setOptions",
  38315. value: function setOptions(options) {
  38316. if (options) {
  38317. if (options.springLength) {
  38318. this.springLength = options.springLength;
  38319. }
  38320. if (options.springConstant) {
  38321. this.springConstant = options.springConstant;
  38322. }
  38323. }
  38324. }
  38325. /**
  38326. * Position the system
  38327. * @param nodesArray
  38328. * @param edgesArray
  38329. */
  38330. }, {
  38331. key: "solve",
  38332. value: function solve(nodesArray, edgesArray) {
  38333. var ignoreClusters = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  38334. // get distance matrix
  38335. var D_matrix = this.distanceSolver.getDistances(this.body, nodesArray, edgesArray); // distance matrix
  38336. // get the L Matrix
  38337. this._createL_matrix(D_matrix);
  38338. // get the K Matrix
  38339. this._createK_matrix(D_matrix);
  38340. // calculate positions
  38341. var threshold = 0.01;
  38342. var innerThreshold = 1;
  38343. var iterations = 0;
  38344. var maxIterations = Math.max(1000, Math.min(10 * this.body.nodeIndices.length, 6000));
  38345. var maxInnerIterations = 5;
  38346. var maxEnergy = 1e9;
  38347. var highE_nodeId = 0,
  38348. dE_dx = 0,
  38349. dE_dy = 0,
  38350. delta_m = 0,
  38351. subIterations = 0;
  38352. while (maxEnergy > threshold && iterations < maxIterations) {
  38353. iterations += 1;
  38354. var _getHighestEnergyNode2 = this._getHighestEnergyNode(ignoreClusters);
  38355. var _getHighestEnergyNode3 = _slicedToArray(_getHighestEnergyNode2, 4);
  38356. highE_nodeId = _getHighestEnergyNode3[0];
  38357. maxEnergy = _getHighestEnergyNode3[1];
  38358. dE_dx = _getHighestEnergyNode3[2];
  38359. dE_dy = _getHighestEnergyNode3[3];
  38360. delta_m = maxEnergy;
  38361. subIterations = 0;
  38362. while (delta_m > innerThreshold && subIterations < maxInnerIterations) {
  38363. subIterations += 1;
  38364. this._moveNode(highE_nodeId, dE_dx, dE_dy);
  38365. var _getEnergy2 = this._getEnergy(highE_nodeId);
  38366. var _getEnergy3 = _slicedToArray(_getEnergy2, 3);
  38367. delta_m = _getEnergy3[0];
  38368. dE_dx = _getEnergy3[1];
  38369. dE_dy = _getEnergy3[2];
  38370. }
  38371. }
  38372. }
  38373. /**
  38374. * get the node with the highest energy
  38375. * @returns {*[]}
  38376. * @private
  38377. */
  38378. }, {
  38379. key: "_getHighestEnergyNode",
  38380. value: function _getHighestEnergyNode(ignoreClusters) {
  38381. var nodesArray = this.body.nodeIndices;
  38382. var nodes = this.body.nodes;
  38383. var maxEnergy = 0;
  38384. var maxEnergyNodeId = nodesArray[0];
  38385. var dE_dx_max = 0,
  38386. dE_dy_max = 0;
  38387. for (var nodeIdx = 0; nodeIdx < nodesArray.length; nodeIdx++) {
  38388. var m = nodesArray[nodeIdx];
  38389. // by not evaluating nodes with predefined positions we should only move nodes that have no positions.
  38390. if (nodes[m].predefinedPosition === false || nodes[m].isCluster === true && ignoreClusters === true || nodes[m].options.fixed.x === true || nodes[m].options.fixed.y === true) {
  38391. var _getEnergy4 = this._getEnergy(m);
  38392. var _getEnergy5 = _slicedToArray(_getEnergy4, 3);
  38393. var delta_m = _getEnergy5[0];
  38394. var dE_dx = _getEnergy5[1];
  38395. var dE_dy = _getEnergy5[2];
  38396. if (maxEnergy < delta_m) {
  38397. maxEnergy = delta_m;
  38398. maxEnergyNodeId = m;
  38399. dE_dx_max = dE_dx;
  38400. dE_dy_max = dE_dy;
  38401. }
  38402. }
  38403. }
  38404. return [maxEnergyNodeId, maxEnergy, dE_dx_max, dE_dy_max];
  38405. }
  38406. /**
  38407. * calculate the energy of a single node
  38408. * @param m
  38409. * @returns {*[]}
  38410. * @private
  38411. */
  38412. }, {
  38413. key: "_getEnergy",
  38414. value: function _getEnergy(m) {
  38415. var nodesArray = this.body.nodeIndices;
  38416. var nodes = this.body.nodes;
  38417. var x_m = nodes[m].x;
  38418. var y_m = nodes[m].y;
  38419. var dE_dx = 0;
  38420. var dE_dy = 0;
  38421. for (var iIdx = 0; iIdx < nodesArray.length; iIdx++) {
  38422. var i = nodesArray[iIdx];
  38423. if (i !== m) {
  38424. var x_i = nodes[i].x;
  38425. var y_i = nodes[i].y;
  38426. var denominator = 1.0 / Math.sqrt(Math.pow(x_m - x_i, 2) + Math.pow(y_m - y_i, 2));
  38427. dE_dx += this.K_matrix[m][i] * (x_m - x_i - this.L_matrix[m][i] * (x_m - x_i) * denominator);
  38428. dE_dy += this.K_matrix[m][i] * (y_m - y_i - this.L_matrix[m][i] * (y_m - y_i) * denominator);
  38429. }
  38430. }
  38431. var delta_m = Math.sqrt(Math.pow(dE_dx, 2) + Math.pow(dE_dy, 2));
  38432. return [delta_m, dE_dx, dE_dy];
  38433. }
  38434. /**
  38435. * move the node based on it's energy
  38436. * the dx and dy are calculated from the linear system proposed by Kamada and Kawai
  38437. * @param m
  38438. * @param dE_dx
  38439. * @param dE_dy
  38440. * @private
  38441. */
  38442. }, {
  38443. key: "_moveNode",
  38444. value: function _moveNode(m, dE_dx, dE_dy) {
  38445. var nodesArray = this.body.nodeIndices;
  38446. var nodes = this.body.nodes;
  38447. var d2E_dx2 = 0;
  38448. var d2E_dxdy = 0;
  38449. var d2E_dy2 = 0;
  38450. var x_m = nodes[m].x;
  38451. var y_m = nodes[m].y;
  38452. for (var iIdx = 0; iIdx < nodesArray.length; iIdx++) {
  38453. var i = nodesArray[iIdx];
  38454. if (i !== m) {
  38455. var x_i = nodes[i].x;
  38456. var y_i = nodes[i].y;
  38457. var denominator = 1.0 / Math.pow(Math.pow(x_m - x_i, 2) + Math.pow(y_m - y_i, 2), 1.5);
  38458. d2E_dx2 += this.K_matrix[m][i] * (1 - this.L_matrix[m][i] * Math.pow(y_m - y_i, 2) * denominator);
  38459. d2E_dxdy += this.K_matrix[m][i] * (this.L_matrix[m][i] * (x_m - x_i) * (y_m - y_i) * denominator);
  38460. d2E_dy2 += this.K_matrix[m][i] * (1 - this.L_matrix[m][i] * Math.pow(x_m - x_i, 2) * denominator);
  38461. }
  38462. }
  38463. // make the variable names easier to make the solving of the linear system easier to read
  38464. var A = d2E_dx2,
  38465. B = d2E_dxdy,
  38466. C = dE_dx,
  38467. D = d2E_dy2,
  38468. E = dE_dy;
  38469. // solve the linear system for dx and dy
  38470. var dy = (C / A + E / B) / (B / A - D / B);
  38471. var dx = -(B * dy + C) / A;
  38472. // move the node
  38473. nodes[m].x += dx;
  38474. nodes[m].y += dy;
  38475. }
  38476. /**
  38477. * Create the L matrix: edge length times shortest path
  38478. * @param D_matrix
  38479. * @private
  38480. */
  38481. }, {
  38482. key: "_createL_matrix",
  38483. value: function _createL_matrix(D_matrix) {
  38484. var nodesArray = this.body.nodeIndices;
  38485. var edgeLength = this.springLength;
  38486. this.L_matrix = [];
  38487. for (var i = 0; i < nodesArray.length; i++) {
  38488. this.L_matrix[nodesArray[i]] = {};
  38489. for (var j = 0; j < nodesArray.length; j++) {
  38490. this.L_matrix[nodesArray[i]][nodesArray[j]] = edgeLength * D_matrix[nodesArray[i]][nodesArray[j]];
  38491. }
  38492. }
  38493. }
  38494. /**
  38495. * Create the K matrix: spring constants times shortest path
  38496. * @param D_matrix
  38497. * @private
  38498. */
  38499. }, {
  38500. key: "_createK_matrix",
  38501. value: function _createK_matrix(D_matrix) {
  38502. var nodesArray = this.body.nodeIndices;
  38503. var edgeStrength = this.springConstant;
  38504. this.K_matrix = [];
  38505. for (var i = 0; i < nodesArray.length; i++) {
  38506. this.K_matrix[nodesArray[i]] = {};
  38507. for (var j = 0; j < nodesArray.length; j++) {
  38508. this.K_matrix[nodesArray[i]][nodesArray[j]] = edgeStrength * Math.pow(D_matrix[nodesArray[i]][nodesArray[j]], -2);
  38509. }
  38510. }
  38511. }
  38512. }]);
  38513. return KamadaKawai;
  38514. }();
  38515. exports.default = KamadaKawai;
  38516. /***/ },
  38517. /* 116 */
  38518. /***/ function(module, exports) {
  38519. "use strict";
  38520. Object.defineProperty(exports, "__esModule", {
  38521. value: true
  38522. });
  38523. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  38524. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  38525. /**
  38526. * Created by Alex on 10-Aug-15.
  38527. */
  38528. var FloydWarshall = function () {
  38529. function FloydWarshall() {
  38530. _classCallCheck(this, FloydWarshall);
  38531. }
  38532. _createClass(FloydWarshall, [{
  38533. key: "getDistances",
  38534. value: function getDistances(body, nodesArray, edgesArray) {
  38535. var D_matrix = {};
  38536. var edges = body.edges;
  38537. // prepare matrix with large numbers
  38538. for (var i = 0; i < nodesArray.length; i++) {
  38539. D_matrix[nodesArray[i]] = {};
  38540. D_matrix[nodesArray[i]] = {};
  38541. for (var j = 0; j < nodesArray.length; j++) {
  38542. D_matrix[nodesArray[i]][nodesArray[j]] = i == j ? 0 : 1e9;
  38543. D_matrix[nodesArray[i]][nodesArray[j]] = i == j ? 0 : 1e9;
  38544. }
  38545. }
  38546. // put the weights for the edges in. This assumes unidirectionality.
  38547. for (var _i = 0; _i < edgesArray.length; _i++) {
  38548. var edge = edges[edgesArray[_i]];
  38549. // edge has to be connected if it counts to the distances. If it is connected to inner clusters it will crash so we also check if it is in the D_matrix
  38550. if (edge.connected === true && D_matrix[edge.fromId] !== undefined && D_matrix[edge.toId] !== undefined) {
  38551. D_matrix[edge.fromId][edge.toId] = 1;
  38552. D_matrix[edge.toId][edge.fromId] = 1;
  38553. }
  38554. }
  38555. var nodeCount = nodesArray.length;
  38556. // Adapted FloydWarshall based on unidirectionality to greatly reduce complexity.
  38557. for (var k = 0; k < nodeCount; k++) {
  38558. for (var _i2 = 0; _i2 < nodeCount - 1; _i2++) {
  38559. for (var _j = _i2 + 1; _j < nodeCount; _j++) {
  38560. D_matrix[nodesArray[_i2]][nodesArray[_j]] = Math.min(D_matrix[nodesArray[_i2]][nodesArray[_j]], D_matrix[nodesArray[_i2]][nodesArray[k]] + D_matrix[nodesArray[k]][nodesArray[_j]]);
  38561. D_matrix[nodesArray[_j]][nodesArray[_i2]] = D_matrix[nodesArray[_i2]][nodesArray[_j]];
  38562. }
  38563. }
  38564. }
  38565. return D_matrix;
  38566. }
  38567. }]);
  38568. return FloydWarshall;
  38569. }();
  38570. exports.default = FloydWarshall;
  38571. /***/ },
  38572. /* 117 */
  38573. /***/ function(module, exports) {
  38574. 'use strict';
  38575. /**
  38576. * Canvas shapes used by Network
  38577. */
  38578. if (typeof CanvasRenderingContext2D !== 'undefined') {
  38579. /**
  38580. * Draw a circle shape
  38581. */
  38582. CanvasRenderingContext2D.prototype.circle = function (x, y, r) {
  38583. this.beginPath();
  38584. this.arc(x, y, r, 0, 2 * Math.PI, false);
  38585. this.closePath();
  38586. };
  38587. /**
  38588. * Draw a square shape
  38589. * @param {Number} x horizontal center
  38590. * @param {Number} y vertical center
  38591. * @param {Number} r size, width and height of the square
  38592. */
  38593. CanvasRenderingContext2D.prototype.square = function (x, y, r) {
  38594. this.beginPath();
  38595. this.rect(x - r, y - r, r * 2, r * 2);
  38596. this.closePath();
  38597. };
  38598. /**
  38599. * Draw a triangle shape
  38600. * @param {Number} x horizontal center
  38601. * @param {Number} y vertical center
  38602. * @param {Number} r radius, half the length of the sides of the triangle
  38603. */
  38604. CanvasRenderingContext2D.prototype.triangle = function (x, y, r) {
  38605. // http://en.wikipedia.org/wiki/Equilateral_triangle
  38606. this.beginPath();
  38607. // the change in radius and the offset is here to center the shape
  38608. r *= 1.15;
  38609. y += 0.275 * r;
  38610. var s = r * 2;
  38611. var s2 = s / 2;
  38612. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  38613. var h = Math.sqrt(s * s - s2 * s2); // height
  38614. this.moveTo(x, y - (h - ir));
  38615. this.lineTo(x + s2, y + ir);
  38616. this.lineTo(x - s2, y + ir);
  38617. this.lineTo(x, y - (h - ir));
  38618. this.closePath();
  38619. };
  38620. /**
  38621. * Draw a triangle shape in downward orientation
  38622. * @param {Number} x horizontal center
  38623. * @param {Number} y vertical center
  38624. * @param {Number} r radius
  38625. */
  38626. CanvasRenderingContext2D.prototype.triangleDown = function (x, y, r) {
  38627. // http://en.wikipedia.org/wiki/Equilateral_triangle
  38628. this.beginPath();
  38629. // the change in radius and the offset is here to center the shape
  38630. r *= 1.15;
  38631. y -= 0.275 * r;
  38632. var s = r * 2;
  38633. var s2 = s / 2;
  38634. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  38635. var h = Math.sqrt(s * s - s2 * s2); // height
  38636. this.moveTo(x, y + (h - ir));
  38637. this.lineTo(x + s2, y - ir);
  38638. this.lineTo(x - s2, y - ir);
  38639. this.lineTo(x, y + (h - ir));
  38640. this.closePath();
  38641. };
  38642. /**
  38643. * Draw a star shape, a star with 5 points
  38644. * @param {Number} x horizontal center
  38645. * @param {Number} y vertical center
  38646. * @param {Number} r radius, half the length of the sides of the triangle
  38647. */
  38648. CanvasRenderingContext2D.prototype.star = function (x, y, r) {
  38649. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  38650. this.beginPath();
  38651. // the change in radius and the offset is here to center the shape
  38652. r *= 0.82;
  38653. y += 0.1 * r;
  38654. for (var n = 0; n < 10; n++) {
  38655. var radius = n % 2 === 0 ? r * 1.3 : r * 0.5;
  38656. this.lineTo(x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10));
  38657. }
  38658. this.closePath();
  38659. };
  38660. /**
  38661. * Draw a Diamond shape
  38662. * @param {Number} x horizontal center
  38663. * @param {Number} y vertical center
  38664. * @param {Number} r radius, half the length of the sides of the triangle
  38665. */
  38666. CanvasRenderingContext2D.prototype.diamond = function (x, y, r) {
  38667. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  38668. this.beginPath();
  38669. this.lineTo(x, y + r);
  38670. this.lineTo(x + r, y);
  38671. this.lineTo(x, y - r);
  38672. this.lineTo(x - r, y);
  38673. this.closePath();
  38674. };
  38675. /**
  38676. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  38677. */
  38678. CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
  38679. var r2d = Math.PI / 180;
  38680. if (w - 2 * r < 0) {
  38681. r = w / 2;
  38682. } //ensure that the radius isn't too large for x
  38683. if (h - 2 * r < 0) {
  38684. r = h / 2;
  38685. } //ensure that the radius isn't too large for y
  38686. this.beginPath();
  38687. this.moveTo(x + r, y);
  38688. this.lineTo(x + w - r, y);
  38689. this.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false);
  38690. this.lineTo(x + w, y + h - r);
  38691. this.arc(x + w - r, y + h - r, r, 0, r2d * 90, false);
  38692. this.lineTo(x + r, y + h);
  38693. this.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false);
  38694. this.lineTo(x, y + r);
  38695. this.arc(x + r, y + r, r, r2d * 180, r2d * 270, false);
  38696. this.closePath();
  38697. };
  38698. /**
  38699. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  38700. */
  38701. CanvasRenderingContext2D.prototype.ellipse = function (x, y, w, h) {
  38702. var kappa = .5522848,
  38703. ox = w / 2 * kappa,
  38704. // control point offset horizontal
  38705. oy = h / 2 * kappa,
  38706. // control point offset vertical
  38707. xe = x + w,
  38708. // x-end
  38709. ye = y + h,
  38710. // y-end
  38711. xm = x + w / 2,
  38712. // x-middle
  38713. ym = y + h / 2; // y-middle
  38714. this.beginPath();
  38715. this.moveTo(x, ym);
  38716. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  38717. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  38718. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  38719. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  38720. this.closePath();
  38721. };
  38722. /**
  38723. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  38724. */
  38725. CanvasRenderingContext2D.prototype.database = function (x, y, w, h) {
  38726. var f = 1 / 3;
  38727. var wEllipse = w;
  38728. var hEllipse = h * f;
  38729. var kappa = .5522848,
  38730. ox = wEllipse / 2 * kappa,
  38731. // control point offset horizontal
  38732. oy = hEllipse / 2 * kappa,
  38733. // control point offset vertical
  38734. xe = x + wEllipse,
  38735. // x-end
  38736. ye = y + hEllipse,
  38737. // y-end
  38738. xm = x + wEllipse / 2,
  38739. // x-middle
  38740. ym = y + hEllipse / 2,
  38741. // y-middle
  38742. ymb = y + (h - hEllipse / 2),
  38743. // y-midlle, bottom ellipse
  38744. yeb = y + h; // y-end, bottom ellipse
  38745. this.beginPath();
  38746. this.moveTo(xe, ym);
  38747. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  38748. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  38749. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  38750. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  38751. this.lineTo(xe, ymb);
  38752. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  38753. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  38754. this.lineTo(x, ym);
  38755. };
  38756. /**
  38757. * Draw an arrow point (no line)
  38758. */
  38759. CanvasRenderingContext2D.prototype.arrow = function (x, y, angle, length) {
  38760. // tail
  38761. var xt = x - length * Math.cos(angle);
  38762. var yt = y - length * Math.sin(angle);
  38763. // inner tail
  38764. var xi = x - length * 0.9 * Math.cos(angle);
  38765. var yi = y - length * 0.9 * Math.sin(angle);
  38766. // left
  38767. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  38768. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  38769. // right
  38770. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  38771. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  38772. this.beginPath();
  38773. this.moveTo(x, y);
  38774. this.lineTo(xl, yl);
  38775. this.lineTo(xi, yi);
  38776. this.lineTo(xr, yr);
  38777. this.closePath();
  38778. };
  38779. /**
  38780. * Sets up the dashedLine functionality for drawing
  38781. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  38782. * @author David Jordan
  38783. * @date 2012-08-08
  38784. */
  38785. CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, pattern) {
  38786. this.beginPath();
  38787. this.moveTo(x, y);
  38788. var patternLength = pattern.length;
  38789. var dx = x2 - x;
  38790. var dy = y2 - y;
  38791. var slope = dy / dx;
  38792. var distRemaining = Math.sqrt(dx * dx + dy * dy);
  38793. var patternIndex = 0;
  38794. var draw = true;
  38795. var xStep = 0;
  38796. var dashLength = pattern[0];
  38797. while (distRemaining >= 0.1) {
  38798. dashLength = pattern[patternIndex++ % patternLength];
  38799. if (dashLength > distRemaining) {
  38800. dashLength = distRemaining;
  38801. }
  38802. xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
  38803. xStep = dx < 0 ? -xStep : xStep;
  38804. x += xStep;
  38805. y += slope * xStep;
  38806. if (draw === true) {
  38807. this.lineTo(x, y);
  38808. } else {
  38809. this.moveTo(x, y);
  38810. }
  38811. distRemaining -= dashLength;
  38812. draw = !draw;
  38813. }
  38814. };
  38815. }
  38816. /***/ },
  38817. /* 118 */
  38818. /***/ function(module, exports) {
  38819. 'use strict';
  38820. /**
  38821. * Parse a text source containing data in DOT language into a JSON object.
  38822. * The object contains two lists: one with nodes and one with edges.
  38823. *
  38824. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  38825. *
  38826. * DOT language attributes: http://graphviz.org/content/attrs
  38827. *
  38828. * @param {String} data Text containing a graph in DOT-notation
  38829. * @return {Object} graph An object containing two parameters:
  38830. * {Object[]} nodes
  38831. * {Object[]} edges
  38832. */
  38833. function parseDOT(data) {
  38834. dot = data;
  38835. return parseGraph();
  38836. }
  38837. // mapping of attributes from DOT (the keys) to vis.js (the values)
  38838. var NODE_ATTR_MAPPING = {
  38839. 'fontsize': 'font.size',
  38840. 'fontcolor': 'font.color',
  38841. 'labelfontcolor': 'font.color',
  38842. 'fontname': 'font.face',
  38843. 'color': ['color.border', 'color.background'],
  38844. 'fillcolor': 'color.background',
  38845. 'tooltip': 'title',
  38846. 'labeltooltip': 'title'
  38847. };
  38848. var EDGE_ATTR_MAPPING = Object.create(NODE_ATTR_MAPPING);
  38849. EDGE_ATTR_MAPPING.color = 'color.color';
  38850. // token types enumeration
  38851. var TOKENTYPE = {
  38852. NULL: 0,
  38853. DELIMITER: 1,
  38854. IDENTIFIER: 2,
  38855. UNKNOWN: 3
  38856. };
  38857. // map with all delimiters
  38858. var DELIMITERS = {
  38859. '{': true,
  38860. '}': true,
  38861. '[': true,
  38862. ']': true,
  38863. ';': true,
  38864. '=': true,
  38865. ',': true,
  38866. '->': true,
  38867. '--': true
  38868. };
  38869. var dot = ''; // current dot file
  38870. var index = 0; // current index in dot file
  38871. var c = ''; // current token character in expr
  38872. var token = ''; // current token
  38873. var tokenType = TOKENTYPE.NULL; // type of the token
  38874. /**
  38875. * Get the first character from the dot file.
  38876. * The character is stored into the char c. If the end of the dot file is
  38877. * reached, the function puts an empty string in c.
  38878. */
  38879. function first() {
  38880. index = 0;
  38881. c = dot.charAt(0);
  38882. }
  38883. /**
  38884. * Get the next character from the dot file.
  38885. * The character is stored into the char c. If the end of the dot file is
  38886. * reached, the function puts an empty string in c.
  38887. */
  38888. function next() {
  38889. index++;
  38890. c = dot.charAt(index);
  38891. }
  38892. /**
  38893. * Preview the next character from the dot file.
  38894. * @return {String} cNext
  38895. */
  38896. function nextPreview() {
  38897. return dot.charAt(index + 1);
  38898. }
  38899. /**
  38900. * Test whether given character is alphabetic or numeric
  38901. * @param {String} c
  38902. * @return {Boolean} isAlphaNumeric
  38903. */
  38904. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  38905. function isAlphaNumeric(c) {
  38906. return regexAlphaNumeric.test(c);
  38907. }
  38908. /**
  38909. * Merge all options of object b into object b
  38910. * @param {Object} a
  38911. * @param {Object} b
  38912. * @return {Object} a
  38913. */
  38914. function merge(a, b) {
  38915. if (!a) {
  38916. a = {};
  38917. }
  38918. if (b) {
  38919. for (var name in b) {
  38920. if (b.hasOwnProperty(name)) {
  38921. a[name] = b[name];
  38922. }
  38923. }
  38924. }
  38925. return a;
  38926. }
  38927. /**
  38928. * Set a value in an object, where the provided parameter name can be a
  38929. * path with nested parameters. For example:
  38930. *
  38931. * var obj = {a: 2};
  38932. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  38933. *
  38934. * @param {Object} obj
  38935. * @param {String} path A parameter name or dot-separated parameter path,
  38936. * like "color.highlight.border".
  38937. * @param {*} value
  38938. */
  38939. function setValue(obj, path, value) {
  38940. var keys = path.split('.');
  38941. var o = obj;
  38942. while (keys.length) {
  38943. var key = keys.shift();
  38944. if (keys.length) {
  38945. // this isn't the end point
  38946. if (!o[key]) {
  38947. o[key] = {};
  38948. }
  38949. o = o[key];
  38950. } else {
  38951. // this is the end point
  38952. o[key] = value;
  38953. }
  38954. }
  38955. }
  38956. /**
  38957. * Add a node to a graph object. If there is already a node with
  38958. * the same id, their attributes will be merged.
  38959. * @param {Object} graph
  38960. * @param {Object} node
  38961. */
  38962. function addNode(graph, node) {
  38963. var i, len;
  38964. var current = null;
  38965. // find root graph (in case of subgraph)
  38966. var graphs = [graph]; // list with all graphs from current graph to root graph
  38967. var root = graph;
  38968. while (root.parent) {
  38969. graphs.push(root.parent);
  38970. root = root.parent;
  38971. }
  38972. // find existing node (at root level) by its id
  38973. if (root.nodes) {
  38974. for (i = 0, len = root.nodes.length; i < len; i++) {
  38975. if (node.id === root.nodes[i].id) {
  38976. current = root.nodes[i];
  38977. break;
  38978. }
  38979. }
  38980. }
  38981. if (!current) {
  38982. // this is a new node
  38983. current = {
  38984. id: node.id
  38985. };
  38986. if (graph.node) {
  38987. // clone default attributes
  38988. current.attr = merge(current.attr, graph.node);
  38989. }
  38990. }
  38991. // add node to this (sub)graph and all its parent graphs
  38992. for (i = graphs.length - 1; i >= 0; i--) {
  38993. var g = graphs[i];
  38994. if (!g.nodes) {
  38995. g.nodes = [];
  38996. }
  38997. if (g.nodes.indexOf(current) === -1) {
  38998. g.nodes.push(current);
  38999. }
  39000. }
  39001. // merge attributes
  39002. if (node.attr) {
  39003. current.attr = merge(current.attr, node.attr);
  39004. }
  39005. }
  39006. /**
  39007. * Add an edge to a graph object
  39008. * @param {Object} graph
  39009. * @param {Object} edge
  39010. */
  39011. function addEdge(graph, edge) {
  39012. if (!graph.edges) {
  39013. graph.edges = [];
  39014. }
  39015. graph.edges.push(edge);
  39016. if (graph.edge) {
  39017. var attr = merge({}, graph.edge); // clone default attributes
  39018. edge.attr = merge(attr, edge.attr); // merge attributes
  39019. }
  39020. }
  39021. /**
  39022. * Create an edge to a graph object
  39023. * @param {Object} graph
  39024. * @param {String | Number | Object} from
  39025. * @param {String | Number | Object} to
  39026. * @param {String} type
  39027. * @param {Object | null} attr
  39028. * @return {Object} edge
  39029. */
  39030. function createEdge(graph, from, to, type, attr) {
  39031. var edge = {
  39032. from: from,
  39033. to: to,
  39034. type: type
  39035. };
  39036. if (graph.edge) {
  39037. edge.attr = merge({}, graph.edge); // clone default attributes
  39038. }
  39039. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  39040. return edge;
  39041. }
  39042. /**
  39043. * Get next token in the current dot file.
  39044. * The token and token type are available as token and tokenType
  39045. */
  39046. function getToken() {
  39047. tokenType = TOKENTYPE.NULL;
  39048. token = '';
  39049. // skip over whitespaces
  39050. while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
  39051. // space, tab, enter
  39052. next();
  39053. }
  39054. do {
  39055. var isComment = false;
  39056. // skip comment
  39057. if (c === '#') {
  39058. // find the previous non-space character
  39059. var i = index - 1;
  39060. while (dot.charAt(i) === ' ' || dot.charAt(i) === '\t') {
  39061. i--;
  39062. }
  39063. if (dot.charAt(i) === '\n' || dot.charAt(i) === '') {
  39064. // the # is at the start of a line, this is indeed a line comment
  39065. while (c != '' && c != '\n') {
  39066. next();
  39067. }
  39068. isComment = true;
  39069. }
  39070. }
  39071. if (c === '/' && nextPreview() === '/') {
  39072. // skip line comment
  39073. while (c != '' && c != '\n') {
  39074. next();
  39075. }
  39076. isComment = true;
  39077. }
  39078. if (c === '/' && nextPreview() === '*') {
  39079. // skip block comment
  39080. while (c != '') {
  39081. if (c === '*' && nextPreview() === '/') {
  39082. // end of block comment found. skip these last two characters
  39083. next();
  39084. next();
  39085. break;
  39086. } else {
  39087. next();
  39088. }
  39089. }
  39090. isComment = true;
  39091. }
  39092. // skip over whitespaces
  39093. while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
  39094. // space, tab, enter
  39095. next();
  39096. }
  39097. } while (isComment);
  39098. // check for end of dot file
  39099. if (c === '') {
  39100. // token is still empty
  39101. tokenType = TOKENTYPE.DELIMITER;
  39102. return;
  39103. }
  39104. // check for delimiters consisting of 2 characters
  39105. var c2 = c + nextPreview();
  39106. if (DELIMITERS[c2]) {
  39107. tokenType = TOKENTYPE.DELIMITER;
  39108. token = c2;
  39109. next();
  39110. next();
  39111. return;
  39112. }
  39113. // check for delimiters consisting of 1 character
  39114. if (DELIMITERS[c]) {
  39115. tokenType = TOKENTYPE.DELIMITER;
  39116. token = c;
  39117. next();
  39118. return;
  39119. }
  39120. // check for an identifier (number or string)
  39121. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  39122. if (isAlphaNumeric(c) || c === '-') {
  39123. token += c;
  39124. next();
  39125. while (isAlphaNumeric(c)) {
  39126. token += c;
  39127. next();
  39128. }
  39129. if (token === 'false') {
  39130. token = false; // convert to boolean
  39131. } else if (token === 'true') {
  39132. token = true; // convert to boolean
  39133. } else if (!isNaN(Number(token))) {
  39134. token = Number(token); // convert to number
  39135. }
  39136. tokenType = TOKENTYPE.IDENTIFIER;
  39137. return;
  39138. }
  39139. // check for a string enclosed by double quotes
  39140. if (c === '"') {
  39141. next();
  39142. while (c != '' && (c != '"' || c === '"' && nextPreview() === '"')) {
  39143. token += c;
  39144. if (c === '"') {
  39145. // skip the escape character
  39146. next();
  39147. }
  39148. next();
  39149. }
  39150. if (c != '"') {
  39151. throw newSyntaxError('End of string " expected');
  39152. }
  39153. next();
  39154. tokenType = TOKENTYPE.IDENTIFIER;
  39155. return;
  39156. }
  39157. // something unknown is found, wrong characters, a syntax error
  39158. tokenType = TOKENTYPE.UNKNOWN;
  39159. while (c != '') {
  39160. token += c;
  39161. next();
  39162. }
  39163. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  39164. }
  39165. /**
  39166. * Parse a graph.
  39167. * @returns {Object} graph
  39168. */
  39169. function parseGraph() {
  39170. var graph = {};
  39171. first();
  39172. getToken();
  39173. // optional strict keyword
  39174. if (token === 'strict') {
  39175. graph.strict = true;
  39176. getToken();
  39177. }
  39178. // graph or digraph keyword
  39179. if (token === 'graph' || token === 'digraph') {
  39180. graph.type = token;
  39181. getToken();
  39182. }
  39183. // optional graph id
  39184. if (tokenType === TOKENTYPE.IDENTIFIER) {
  39185. graph.id = token;
  39186. getToken();
  39187. }
  39188. // open angle bracket
  39189. if (token != '{') {
  39190. throw newSyntaxError('Angle bracket { expected');
  39191. }
  39192. getToken();
  39193. // statements
  39194. parseStatements(graph);
  39195. // close angle bracket
  39196. if (token != '}') {
  39197. throw newSyntaxError('Angle bracket } expected');
  39198. }
  39199. getToken();
  39200. // end of file
  39201. if (token !== '') {
  39202. throw newSyntaxError('End of file expected');
  39203. }
  39204. getToken();
  39205. // remove temporary default options
  39206. delete graph.node;
  39207. delete graph.edge;
  39208. delete graph.graph;
  39209. return graph;
  39210. }
  39211. /**
  39212. * Parse a list with statements.
  39213. * @param {Object} graph
  39214. */
  39215. function parseStatements(graph) {
  39216. while (token !== '' && token != '}') {
  39217. parseStatement(graph);
  39218. if (token === ';') {
  39219. getToken();
  39220. }
  39221. }
  39222. }
  39223. /**
  39224. * Parse a single statement. Can be a an attribute statement, node
  39225. * statement, a series of node statements and edge statements, or a
  39226. * parameter.
  39227. * @param {Object} graph
  39228. */
  39229. function parseStatement(graph) {
  39230. // parse subgraph
  39231. var subgraph = parseSubgraph(graph);
  39232. if (subgraph) {
  39233. // edge statements
  39234. parseEdge(graph, subgraph);
  39235. return;
  39236. }
  39237. // parse an attribute statement
  39238. var attr = parseAttributeStatement(graph);
  39239. if (attr) {
  39240. return;
  39241. }
  39242. // parse node
  39243. if (tokenType != TOKENTYPE.IDENTIFIER) {
  39244. throw newSyntaxError('Identifier expected');
  39245. }
  39246. var id = token; // id can be a string or a number
  39247. getToken();
  39248. if (token === '=') {
  39249. // id statement
  39250. getToken();
  39251. if (tokenType != TOKENTYPE.IDENTIFIER) {
  39252. throw newSyntaxError('Identifier expected');
  39253. }
  39254. graph[id] = token;
  39255. getToken();
  39256. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  39257. } else {
  39258. parseNodeStatement(graph, id);
  39259. }
  39260. }
  39261. /**
  39262. * Parse a subgraph
  39263. * @param {Object} graph parent graph object
  39264. * @return {Object | null} subgraph
  39265. */
  39266. function parseSubgraph(graph) {
  39267. var subgraph = null;
  39268. // optional subgraph keyword
  39269. if (token === 'subgraph') {
  39270. subgraph = {};
  39271. subgraph.type = 'subgraph';
  39272. getToken();
  39273. // optional graph id
  39274. if (tokenType === TOKENTYPE.IDENTIFIER) {
  39275. subgraph.id = token;
  39276. getToken();
  39277. }
  39278. }
  39279. // open angle bracket
  39280. if (token === '{') {
  39281. getToken();
  39282. if (!subgraph) {
  39283. subgraph = {};
  39284. }
  39285. subgraph.parent = graph;
  39286. subgraph.node = graph.node;
  39287. subgraph.edge = graph.edge;
  39288. subgraph.graph = graph.graph;
  39289. // statements
  39290. parseStatements(subgraph);
  39291. // close angle bracket
  39292. if (token != '}') {
  39293. throw newSyntaxError('Angle bracket } expected');
  39294. }
  39295. getToken();
  39296. // remove temporary default options
  39297. delete subgraph.node;
  39298. delete subgraph.edge;
  39299. delete subgraph.graph;
  39300. delete subgraph.parent;
  39301. // register at the parent graph
  39302. if (!graph.subgraphs) {
  39303. graph.subgraphs = [];
  39304. }
  39305. graph.subgraphs.push(subgraph);
  39306. }
  39307. return subgraph;
  39308. }
  39309. /**
  39310. * parse an attribute statement like "node [shape=circle fontSize=16]".
  39311. * Available keywords are 'node', 'edge', 'graph'.
  39312. * The previous list with default attributes will be replaced
  39313. * @param {Object} graph
  39314. * @returns {String | null} keyword Returns the name of the parsed attribute
  39315. * (node, edge, graph), or null if nothing
  39316. * is parsed.
  39317. */
  39318. function parseAttributeStatement(graph) {
  39319. // attribute statements
  39320. if (token === 'node') {
  39321. getToken();
  39322. // node attributes
  39323. graph.node = parseAttributeList();
  39324. return 'node';
  39325. } else if (token === 'edge') {
  39326. getToken();
  39327. // edge attributes
  39328. graph.edge = parseAttributeList();
  39329. return 'edge';
  39330. } else if (token === 'graph') {
  39331. getToken();
  39332. // graph attributes
  39333. graph.graph = parseAttributeList();
  39334. return 'graph';
  39335. }
  39336. return null;
  39337. }
  39338. /**
  39339. * parse a node statement
  39340. * @param {Object} graph
  39341. * @param {String | Number} id
  39342. */
  39343. function parseNodeStatement(graph, id) {
  39344. // node statement
  39345. var node = {
  39346. id: id
  39347. };
  39348. var attr = parseAttributeList();
  39349. if (attr) {
  39350. node.attr = attr;
  39351. }
  39352. addNode(graph, node);
  39353. // edge statements
  39354. parseEdge(graph, id);
  39355. }
  39356. /**
  39357. * Parse an edge or a series of edges
  39358. * @param {Object} graph
  39359. * @param {String | Number} from Id of the from node
  39360. */
  39361. function parseEdge(graph, from) {
  39362. while (token === '->' || token === '--') {
  39363. var to;
  39364. var type = token;
  39365. getToken();
  39366. var subgraph = parseSubgraph(graph);
  39367. if (subgraph) {
  39368. to = subgraph;
  39369. } else {
  39370. if (tokenType != TOKENTYPE.IDENTIFIER) {
  39371. throw newSyntaxError('Identifier or subgraph expected');
  39372. }
  39373. to = token;
  39374. addNode(graph, {
  39375. id: to
  39376. });
  39377. getToken();
  39378. }
  39379. // parse edge attributes
  39380. var attr = parseAttributeList();
  39381. // create edge
  39382. var edge = createEdge(graph, from, to, type, attr);
  39383. addEdge(graph, edge);
  39384. from = to;
  39385. }
  39386. }
  39387. /**
  39388. * Parse a set with attributes,
  39389. * for example [label="1.000", shape=solid]
  39390. * @return {Object | null} attr
  39391. */
  39392. function parseAttributeList() {
  39393. var attr = null;
  39394. while (token === '[') {
  39395. getToken();
  39396. attr = {};
  39397. while (token !== '' && token != ']') {
  39398. if (tokenType != TOKENTYPE.IDENTIFIER) {
  39399. throw newSyntaxError('Attribute name expected');
  39400. }
  39401. var name = token;
  39402. getToken();
  39403. if (token != '=') {
  39404. throw newSyntaxError('Equal sign = expected');
  39405. }
  39406. getToken();
  39407. if (tokenType != TOKENTYPE.IDENTIFIER) {
  39408. throw newSyntaxError('Attribute value expected');
  39409. }
  39410. var value = token;
  39411. setValue(attr, name, value); // name can be a path
  39412. getToken();
  39413. if (token == ',') {
  39414. getToken();
  39415. }
  39416. }
  39417. if (token != ']') {
  39418. throw newSyntaxError('Bracket ] expected');
  39419. }
  39420. getToken();
  39421. }
  39422. return attr;
  39423. }
  39424. /**
  39425. * Create a syntax error with extra information on current token and index.
  39426. * @param {String} message
  39427. * @returns {SyntaxError} err
  39428. */
  39429. function newSyntaxError(message) {
  39430. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  39431. }
  39432. /**
  39433. * Chop off text after a maximum length
  39434. * @param {String} text
  39435. * @param {Number} maxLength
  39436. * @returns {String}
  39437. */
  39438. function chop(text, maxLength) {
  39439. return text.length <= maxLength ? text : text.substr(0, 27) + '...';
  39440. }
  39441. /**
  39442. * Execute a function fn for each pair of elements in two arrays
  39443. * @param {Array | *} array1
  39444. * @param {Array | *} array2
  39445. * @param {function} fn
  39446. */
  39447. function forEach2(array1, array2, fn) {
  39448. if (Array.isArray(array1)) {
  39449. array1.forEach(function (elem1) {
  39450. if (Array.isArray(array2)) {
  39451. array2.forEach(function (elem2) {
  39452. fn(elem1, elem2);
  39453. });
  39454. } else {
  39455. fn(elem1, array2);
  39456. }
  39457. });
  39458. } else {
  39459. if (Array.isArray(array2)) {
  39460. array2.forEach(function (elem2) {
  39461. fn(array1, elem2);
  39462. });
  39463. } else {
  39464. fn(array1, array2);
  39465. }
  39466. }
  39467. }
  39468. /**
  39469. * Set a nested property on an object
  39470. * When nested objects are missing, they will be created.
  39471. * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}}
  39472. * @param {Object} object
  39473. * @param {string} path A dot separated string like 'font.color'
  39474. * @param {*} value Value for the property
  39475. * @return {Object} Returns the original object, allows for chaining.
  39476. */
  39477. function setProp(object, path, value) {
  39478. var names = path.split('.');
  39479. var prop = names.pop();
  39480. // traverse over the nested objects
  39481. var obj = object;
  39482. for (var i = 0; i < names.length; i++) {
  39483. var name = names[i];
  39484. if (!(name in obj)) {
  39485. obj[name] = {};
  39486. }
  39487. obj = obj[name];
  39488. }
  39489. // set the property value
  39490. obj[prop] = value;
  39491. return object;
  39492. }
  39493. /**
  39494. * Convert an object with DOT attributes to their vis.js equivalents.
  39495. * @param {Object} attr Object with DOT attributes
  39496. * @param {Object} mapping
  39497. * @return {Object} Returns an object with vis.js attributes
  39498. */
  39499. function convertAttr(attr, mapping) {
  39500. var converted = {};
  39501. for (var prop in attr) {
  39502. if (attr.hasOwnProperty(prop)) {
  39503. var visProp = mapping[prop];
  39504. if (Array.isArray(visProp)) {
  39505. visProp.forEach(function (visPropI) {
  39506. setProp(converted, visPropI, attr[prop]);
  39507. });
  39508. } else if (typeof visProp === 'string') {
  39509. setProp(converted, visProp, attr[prop]);
  39510. } else {
  39511. setProp(converted, prop, attr[prop]);
  39512. }
  39513. }
  39514. }
  39515. return converted;
  39516. }
  39517. /**
  39518. * Convert a string containing a graph in DOT language into a map containing
  39519. * with nodes and edges in the format of graph.
  39520. * @param {String} data Text containing a graph in DOT-notation
  39521. * @return {Object} graphData
  39522. */
  39523. function DOTToGraph(data) {
  39524. // parse the DOT file
  39525. var dotData = parseDOT(data);
  39526. var graphData = {
  39527. nodes: [],
  39528. edges: [],
  39529. options: {}
  39530. };
  39531. // copy the nodes
  39532. if (dotData.nodes) {
  39533. dotData.nodes.forEach(function (dotNode) {
  39534. var graphNode = {
  39535. id: dotNode.id,
  39536. label: String(dotNode.label || dotNode.id)
  39537. };
  39538. merge(graphNode, convertAttr(dotNode.attr, NODE_ATTR_MAPPING));
  39539. if (graphNode.image) {
  39540. graphNode.shape = 'image';
  39541. }
  39542. graphData.nodes.push(graphNode);
  39543. });
  39544. }
  39545. // copy the edges
  39546. if (dotData.edges) {
  39547. /**
  39548. * Convert an edge in DOT format to an edge with VisGraph format
  39549. * @param {Object} dotEdge
  39550. * @returns {Object} graphEdge
  39551. */
  39552. var convertEdge = function convertEdge(dotEdge) {
  39553. var graphEdge = {
  39554. from: dotEdge.from,
  39555. to: dotEdge.to
  39556. };
  39557. merge(graphEdge, convertAttr(dotEdge.attr, EDGE_ATTR_MAPPING));
  39558. graphEdge.arrows = dotEdge.type === '->' ? 'to' : undefined;
  39559. return graphEdge;
  39560. };
  39561. dotData.edges.forEach(function (dotEdge) {
  39562. var from, to;
  39563. if (dotEdge.from instanceof Object) {
  39564. from = dotEdge.from.nodes;
  39565. } else {
  39566. from = {
  39567. id: dotEdge.from
  39568. };
  39569. }
  39570. // TODO: support of solid/dotted/dashed edges (attr = 'style')
  39571. // TODO: support for attributes 'dir' and 'arrowhead' (edge arrows)
  39572. if (dotEdge.to instanceof Object) {
  39573. to = dotEdge.to.nodes;
  39574. } else {
  39575. to = {
  39576. id: dotEdge.to
  39577. };
  39578. }
  39579. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  39580. dotEdge.from.edges.forEach(function (subEdge) {
  39581. var graphEdge = convertEdge(subEdge);
  39582. graphData.edges.push(graphEdge);
  39583. });
  39584. }
  39585. forEach2(from, to, function (from, to) {
  39586. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  39587. var graphEdge = convertEdge(subEdge);
  39588. graphData.edges.push(graphEdge);
  39589. });
  39590. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  39591. dotEdge.to.edges.forEach(function (subEdge) {
  39592. var graphEdge = convertEdge(subEdge);
  39593. graphData.edges.push(graphEdge);
  39594. });
  39595. }
  39596. });
  39597. }
  39598. // copy the options
  39599. if (dotData.attr) {
  39600. graphData.options = dotData.attr;
  39601. }
  39602. return graphData;
  39603. }
  39604. // exports
  39605. exports.parseDOT = parseDOT;
  39606. exports.DOTToGraph = DOTToGraph;
  39607. /***/ },
  39608. /* 119 */
  39609. /***/ function(module, exports) {
  39610. 'use strict';
  39611. function parseGephi(gephiJSON, optionsObj) {
  39612. var edges = [];
  39613. var nodes = [];
  39614. var options = {
  39615. edges: {
  39616. inheritColor: false
  39617. },
  39618. nodes: {
  39619. fixed: false,
  39620. parseColor: false
  39621. }
  39622. };
  39623. if (optionsObj !== undefined) {
  39624. if (optionsObj.fixed !== undefined) {
  39625. options.nodes.fixed = optionsObj.fixed;
  39626. }
  39627. if (optionsObj.parseColor !== undefined) {
  39628. options.nodes.parseColor = optionsObj.parseColor;
  39629. }
  39630. if (optionsObj.inheritColor !== undefined) {
  39631. options.edges.inheritColor = optionsObj.inheritColor;
  39632. }
  39633. }
  39634. var gEdges = gephiJSON.edges;
  39635. var gNodes = gephiJSON.nodes;
  39636. for (var i = 0; i < gEdges.length; i++) {
  39637. var edge = {};
  39638. var gEdge = gEdges[i];
  39639. edge['id'] = gEdge.id;
  39640. edge['from'] = gEdge.source;
  39641. edge['to'] = gEdge.target;
  39642. edge['attributes'] = gEdge.attributes;
  39643. edge['label'] = gEdge.label;
  39644. edge['title'] = gEdge.attributes !== undefined ? gEdge.attributes.title : undefined;
  39645. if (gEdge['type'] === 'Directed') {
  39646. edge['arrows'] = 'to';
  39647. }
  39648. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  39649. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  39650. if (gEdge.color && options.inheritColor === false) {
  39651. edge['color'] = gEdge.color;
  39652. }
  39653. edges.push(edge);
  39654. }
  39655. for (var i = 0; i < gNodes.length; i++) {
  39656. var node = {};
  39657. var gNode = gNodes[i];
  39658. node['id'] = gNode.id;
  39659. node['attributes'] = gNode.attributes;
  39660. node['title'] = gNode.title;
  39661. node['x'] = gNode.x;
  39662. node['y'] = gNode.y;
  39663. node['label'] = gNode.label;
  39664. node['title'] = gNode.attributes !== undefined ? gNode.attributes.title : undefined;
  39665. if (options.nodes.parseColor === true) {
  39666. node['color'] = gNode.color;
  39667. } else {
  39668. node['color'] = gNode.color !== undefined ? { background: gNode.color, border: gNode.color, highlight: { background: gNode.color, border: gNode.color }, hover: { background: gNode.color, border: gNode.color } } : undefined;
  39669. }
  39670. node['size'] = gNode.size;
  39671. node['fixed'] = options.nodes.fixed && gNode.x !== undefined && gNode.y !== undefined;
  39672. nodes.push(node);
  39673. }
  39674. return { nodes: nodes, edges: edges };
  39675. }
  39676. exports.parseGephi = parseGephi;
  39677. /***/ },
  39678. /* 120 */
  39679. /***/ function(module, exports) {
  39680. 'use strict';
  39681. // English
  39682. exports['en'] = {
  39683. edit: 'Edit',
  39684. del: 'Delete selected',
  39685. back: 'Back',
  39686. addNode: 'Add Node',
  39687. addEdge: 'Add Edge',
  39688. editNode: 'Edit Node',
  39689. editEdge: 'Edit Edge',
  39690. addDescription: 'Click in an empty space to place a new node.',
  39691. edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
  39692. editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
  39693. createEdgeError: 'Cannot link edges to a cluster.',
  39694. deleteClusterError: 'Clusters cannot be deleted.',
  39695. editClusterError: 'Clusters cannot be edited.'
  39696. };
  39697. exports['en_EN'] = exports['en'];
  39698. exports['en_US'] = exports['en'];
  39699. // German
  39700. exports['de'] = {
  39701. edit: 'Editieren',
  39702. del: 'Lösche Auswahl',
  39703. back: 'Zurück',
  39704. addNode: 'Knoten hinzufügen',
  39705. addEdge: 'Kante hinzufügen',
  39706. editNode: 'Knoten editieren',
  39707. editEdge: 'Kante editieren',
  39708. addDescription: 'Klicke auf eine freie Stelle, um einen neuen Knoten zu plazieren.',
  39709. edgeDescription: 'Klicke auf einen Knoten und ziehe die Kante zu einem anderen Knoten, um diese zu verbinden.',
  39710. editEdgeDescription: 'Klicke auf die Verbindungspunkte und ziehe diese auf einen Knoten, um sie zu verbinden.',
  39711. createEdgeError: 'Es ist nicht möglich, Kanten mit Clustern zu verbinden.',
  39712. deleteClusterError: 'Cluster können nicht gelöscht werden.',
  39713. editClusterError: 'Cluster können nicht editiert werden.'
  39714. };
  39715. exports['de_DE'] = exports['de'];
  39716. // Spanish
  39717. exports['es'] = {
  39718. edit: 'Editar',
  39719. del: 'Eliminar selección',
  39720. back: 'Átras',
  39721. addNode: 'Añadir nodo',
  39722. addEdge: 'Añadir arista',
  39723. editNode: 'Editar nodo',
  39724. editEdge: 'Editar arista',
  39725. addDescription: 'Haga clic en un lugar vacío para colocar un nuevo nodo.',
  39726. edgeDescription: 'Haga clic en un nodo y arrastre la arista hacia otro nodo para conectarlos.',
  39727. editEdgeDescription: 'Haga clic en un punto de control y arrastrelo a un nodo para conectarlo.',
  39728. createEdgeError: 'No se puede conectar una arista a un grupo.',
  39729. deleteClusterError: 'No es posible eliminar grupos.',
  39730. editClusterError: 'No es posible editar grupos.'
  39731. };
  39732. exports['es_ES'] = exports['es'];
  39733. // Dutch
  39734. exports['nl'] = {
  39735. edit: 'Wijzigen',
  39736. del: 'Selectie verwijderen',
  39737. back: 'Terug',
  39738. addNode: 'Node toevoegen',
  39739. addEdge: 'Link toevoegen',
  39740. editNode: 'Node wijzigen',
  39741. editEdge: 'Link wijzigen',
  39742. addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.',
  39743. edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.',
  39744. editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.',
  39745. createEdgeError: 'Kan geen link maken naar een cluster.',
  39746. deleteClusterError: 'Clusters kunnen niet worden verwijderd.',
  39747. editClusterError: 'Clusters kunnen niet worden aangepast.'
  39748. };
  39749. exports['nl_NL'] = exports['nl'];
  39750. exports['nl_BE'] = exports['nl'];
  39751. /***/ }
  39752. /******/ ])
  39753. });
  39754. ;